diff --git a/Documentation/DesignDoc/DetailedDesign.pdf b/Documentation/DesignDoc/DetailedDesign.pdf index c2969692..0fcd7c9e 100644 Binary files a/Documentation/DesignDoc/DetailedDesign.pdf and b/Documentation/DesignDoc/DetailedDesign.pdf differ diff --git a/Documentation/DesignDoc/DetailedDesign.tex b/Documentation/DesignDoc/DetailedDesign.tex index ba1ea919..dece4df3 100644 --- a/Documentation/DesignDoc/DetailedDesign.tex +++ b/Documentation/DesignDoc/DetailedDesign.tex @@ -79,8 +79,9 @@ \subsection{Revision History} \toprule \bf Description of Changes & \bf Author & \bf Date\\\midrule \arrayrulecolor{lightgray} -Set up sections and filled out Introduction section & Matthew & 2015-12-15\\\hline -Added sections for Errors and Key Algorithms & Stuart & 2016-01-08\\ +Set up sections and filled out Introduction section & Matt & 2015-12-15\\\hline +Added sections for Errors and Key Algorithms & Stuart & 2016-01-08\\\hline +Created implementation 2 Section & Matt & 2016-04-21\\ \arrayrulecolor{black} \bottomrule \end{tabular} @@ -118,7 +119,9 @@ \subsection{Technologies and Languages} \subsection{Notes} Geant4 uses its own basic types for standard C++ types (G4int, G4bool, G4double, etc). These types are currently just \texttt{typedefs} to the respective type as defined in the system libraries.\\ -The modules G4NeutronHPDataPoint and G4ParticleVector described below are existing modules of Geant4. All methods and state variables are pre-existing, and will be replicated on the GPU. The interface of the modules will not change. +The modules G4NeutronHPDataPoint and G4ParticleVector described below are existing modules of Geant4. All methods and state variables are pre-existing, and will be replicated on the GPU. The interface of the modules will not change.\\ + +This document contains two different implementations for G4ParticleVector. Both implementations use the same implementation for G4NeutronHPDataPoint. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ----- NeutronHPDataPoint \section{G4NeutronHPDataPoint} @@ -208,7 +211,7 @@ \subsection{Key Algorithms} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ----- NeutronHPVector -\section{G4ParticleVector} +\section{G4ParticleVector -- Implementation 1} \subsection{Description} This module stores a large vector of data points (G4NeutronHPDataPoint). It includes functions for setting the data points, retrieving them, and calculating information over them (such as the integral). @@ -388,6 +391,82 @@ \subsection{Key Algorithms} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ---- NeutronHPVector + + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ----- NeutronHPVector +\section{G4ParticleVector -- Implementation 2} + +\subsection{Description} +Instead of storing and maintaining everything on the GPU, only functions which are well suited to run on the GPU are implemented. The data vector will +be stored and maintained on the CPU in this implementation and will be sent to the GPU for processing results. + +\subsection{MIS (Module Interface Specification)} +Note that hyphens in routine names, inputs, outputs, and exceptions are just for linebreaks due to the table size. The actual routine names, inputs, outputs, and exceptions do not have hyphens. + +\subsubsection{Access Program Syntax}% ================ Victor +\begin{longtable}{p{0.28\textwidth}p{0.28\textwidth}p{0.28\textwidth}p{0.14\textwidth}} +\caption{G4ParticleVector -- access program syntax}\label{Table_NeutronHPVectorInterface}\\ +\toprule +\bf Routine Name & \bf Input & \bf Output & \bf Exceptions \\\midrule +\arrayrulecolor{lightgray} +SetInterpolationManager & const G4InterpolationManager \& & & \\\hline +SetInterpolationManager & G4InterpolationManager \& & & \\\hline +GetXsecList & G4double, G4int, G4ParticleHPDataPoint*, G4int & &\\\hline +GetMinIndices\_CUDA & G4ParticleHPDataPoint* , int, double* , int, int* & &\\ +\arrayrulecolor{black} +\bottomrule +\end{longtable} + +\subsubsection{Access Program Semantics}% ============ Rob +Note that hyphens in routine names and inputs are just for linebreaks due to the table size. The actual routine names and inputs do not have hyphens. + +\begin{longtable}{p{0.25\textwidth}p{0.3\textwidth}p{0.45\textwidth}} +\caption{G4ParticleVector -- access program semantics}\label{Table_NeutronHPVectorSemantics}\\ +\toprule +\bf Routine Name & \bf Input & \bf Description \\\midrule +\arrayrulecolor{lightgray} +SetInterpolation-Manager & G4Interpolation-Manager\& & sets \texttt{theManager} to the input \\\hline +GetXsecList & G4double, G4int, G4ParticleHPDataPoint*, G4int & Takes a list of energies and finds their corresponding xSecs\\\hline +GetMinIndices\_CUDA & G4ParticleHPDataPoint* , int, double* , int, int* & device function used to find the indexes for the query values given\\\hline +\arrayrulecolor{black} +\bottomrule +\end{longtable} + +\subsubsection{State Variables}% ================== Matt +The following variables maintain state for the class, and are all private to the class. + +Note that hyphens in variable names and types are just for line breaks due to the table size. The actual variable names and types do not have hyphens. + +\begin{table}[h] +\caption{G4ParticleVector -- state variables}\label{Table_NeutronHPDataPointStateVariables} +\begin{tabularx}{\textwidth}{p{0.2\textwidth}p{0.2\textwidth}p{0.5\textwidth}} +\toprule +\bf Variable & \bf Type & \bf Description\\\midrule +\arrayrulecolor{lightgray} +\texttt{theManager} & G4Interpolation-Manager & manages the interpolation schemes, knows how to interpolate data\\\hline +\texttt{theInt} & G4Neutron-Interpolator & the interpolator for sampling data (may not be linear)\\ +\arrayrulecolor{black} +\bottomrule +\end{tabularx} +\end{table} +\subsubsection{Environment Variables}% ============== Matt +There are no environment variables for this module. + +\subsubsection{Assumptions}% ==================== Stuart +It can be assumed that the module will be initialized before other functions are called. + +\subsection{Error Handling} +The \texttt{Check} method throws a G4HadronicException on error, however it is the only function to do so in the module. In the other functions, erroneous input is not handled explicitly beyond control statement checks that will assume default values for any invalid parameters. + +\subsection{Key Algorithms} +There are a variety of algorithms used in the module. When porting to the GPU, the same algorithms will be modified to run in parallel. In general, this consists of taking array traversals and running the procedures executed sequentially at the same time on different cores of the GPU. + +\subsubsection{GetXsecList} +GetXsecList takes in an array of energy queries, it then sends that array to the GPU to work on. The GPU divides up the work by having each individual thread on the GPU be responsible for a single energy query. Every thread will look through the data vector independently until it finds the xSec corresponding to its energy value. This will all be happening in parallel. The results found replace the corresponding query energies + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ---- NeutronHPVector + + %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ----- Cmake Files \section{CMake Files} \subsection{Description}\label{Sec_CMakeDesc} @@ -403,10 +482,10 @@ \subsubsection{Access Program Semantics}% ============ Rob \subsubsection{State Variables}% ================== Matt \begin{table}[h] \caption{CMake Files -- state variables}\label{Table_CMakeStateVariables} -\begin{tabularx}{\textwidth}{p{0.1\textwidth}p{0.1\textwidth}p{0.7\textwidth}} +\begin{tabularx}{\textwidth}{p{0.25\textwidth}p{0.1\textwidth}p{0.55\textwidth}} \toprule \bf Variable & \bf Type & \bf Description\\\midrule -\texttt{useCuda} & Boolean & if set to true, the makefiles generated by CMake will include directives to compile and link the CUDA code and will execute ported procedures on the GPU. Default is false.\\ +\texttt{GEANT4\_Enable\_CUDA} & Boolean & if set to true, the makefiles generated by CMake will include directives to compile and link the CUDA code and will execute ported procedures on the GPU. Default is false.\\ \bottomrule \end{tabularx} \end{table} @@ -421,10 +500,10 @@ \subsubsection{Assumptions}% ==================== Stuart It is assumed the user has CMake installed, as it is required for Geant4. \subsection{Error Handling} -If the tries to enable CUDA without compatible hardware, CMake will detect this and output a fatal error message. The user will not be able to enable CUDA unless they have compatible hardware. If the user is using an older version of CMake (before 2.8) that does not support CUDA compilation, a fatal error message will be outputted. +If user the tries to enable CUDA without compatible hardware, CMake will detect this and output a fatal error message. The user will not be able to enable CUDA unless they have compatible hardware. If the user is using an older version of CMake (before 2.8) that does not support CUDA compilation, a fatal error message will be outputted. \subsection{Key Algorithms} -CMake is the existing build system for generating make files for the project. As such, there are no key algorithms to document. +When GEANT4\_Enable\_CUDA is set to true CMake will configure a header file which will indicate if Geant4 needs to include the CUDA files or not. This file then gets moved to the include directory where G4ParticleHPVector.hh can see it and include it. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ---- Cmake Files diff --git a/Documentation/DesignDoc/SystemArchitecture.pdf b/Documentation/DesignDoc/SystemArchitecture.pdf index 88f5476e..3f0beeb0 100644 Binary files a/Documentation/DesignDoc/SystemArchitecture.pdf and b/Documentation/DesignDoc/SystemArchitecture.pdf differ diff --git a/Documentation/DesignDoc/SystemArchitecture.tex b/Documentation/DesignDoc/SystemArchitecture.tex index 0b76b4f5..6a6be7bc 100644 --- a/Documentation/DesignDoc/SystemArchitecture.tex +++ b/Documentation/DesignDoc/SystemArchitecture.tex @@ -218,7 +218,9 @@ \subsection{GPU Integration Approach}\label{Sec_IntegrationApproach} In all options except 1 and 2, a function call to one of the functions of a ported class will be received by the existing C++ class, which will then either execute the existing code if that function has not been ported or if GPU computation is disabled, or will call the corresponding function from the CUDA file. -Option 5 was chosen due to its ability to divide work easily, its compatibility with the current codebase, and the memory advantages over option 4. +Option 5 was chosen due to its ability to divide work easily, its compatibility with the current codebase, and the memory advantages over option 4. + +Option 3 was also implemented after performance testing showed that option 5 did not provide any significant speed ups. \subsection{G4ParticleVector}\label{subsec_G4ParticleVector} % rob As was explained in the preceding subsection, the problem has been decomposed to that of only integrating specific functions from given modules with the CUDA technology. With that said, a decision needed to be made as for which class and which functions within that class to integrate. diff --git a/G4STORK/.gitignore b/G4STORK/.gitignore deleted file mode 100755 index fa7082fe..00000000 --- a/G4STORK/.gitignore +++ /dev/null @@ -1,14 +0,0 @@ -.bzr/ -.bzrignore -.dropbox -.gitignore~ -AnnotatedFiles/ -Build/ -G4STORK/ -G4STORK2.0/ -G4STORKBZR/ -procgroup~ -G4STORK.cbp -G4STORK.layout -G4STORK.layout.cbTemp - diff --git a/G4STORK/CMakeLists.txt b/G4STORK/CMakeLists.txt deleted file mode 100755 index f887adcf..00000000 --- a/G4STORK/CMakeLists.txt +++ /dev/null @@ -1,120 +0,0 @@ -#---------------------------------------------------------------------------- -# Setup the project -cmake_minimum_required(VERSION 2.6 FATAL_ERROR) -project(G4_STORK) - - -#---------------------------------------------------------------------------- -# Find Geant4 package, activating all available UI and Vis drivers by default -# You can set WITH_GEANT4_UIVIS to OFF via the command line or ccmake/cmake-gui -# to build a batch mode only executable -# -option(WITH_GEANT4_UIVIS "Build example with Geant4 UI and Vis drivers" ON) -if(WITH_GEANT4_UIVIS) - find_package(Geant4 REQUIRED ui_all vis_all) -else() - find_package(Geant4 REQUIRED) -endif() - - -#---------------------------------------------------------------------------- -# Setup Geant4 include directories and compile definitions -# -include(${Geant4_USE_FILE}) -add_definitions(-fpermissive) - - -#---------------------------------------------------------------------------- -# Custom commands for generating marshalled classes -# - - -#---------------------------------------------------------------------------- -# Add options -# - -# Timing of individual components -option(G4TIME_USE "Output object execution times" OFF) -if(G4TIME_USE) - add_definitions(-DG4TIME -DG4TIMESD -DG4TIMERA -DG4TIMEEA) -endif() - -# Explicit totals for each neutron loss type (fission, capture, etc) -option(STORK_EXPLICIT_LOSS "Show explicit loss type counters" OFF) -if(STORK_EXPLICIT_LOSS) - add_definitions(-DSTORK_EXPLICIT_LOSS) -endif() - -# Visualization of geometry, hits, etc -option(G4VISUALIZE_USE "Provide visualization of simulation" OFF) -if(G4VISUALIZE_USE) - add_definitions(-DG4VISUALIZE_USE) -endif() - -# Step-by-step tracking -option(G4VERBOSE_TRACKING_USE "Show step-by-step tracking output" OFF) -if(G4VERBOSE_TRACKING_USE) - add_definitions(-G4VERBOSE_TRACKING_USE) -endif() - -# Parallel processing using TOP-C -option(TOPC_USE "Use TOP-C parallel architecture" OFF) -option(TOPC_USE_SEQ "Use TOP-C in sequential mode" OFF) -if(TOPC_USE) - if(TOPC_USE_SEQ) - set(PARMODE "--seq") - else() - set(PARMODE "--mpi") - endif() - - # Get TOP-C libraries - execute_process(COMMAND "topc-config" ${PARMODE} "--libs" - OUTPUT_VARIABLE TOPC_LIBS) - - # Remove trailing whitespace - string(STRIP ${TOPC_LIBS} TOPC_LIBS) - - # Get TOP-C compiler flags - execute_process(COMMAND "topc-config" ${PARMODE} "--cflags" - OUTPUT_VARIABLE TOPC_CFLAGS) - - add_definitions(${TOPC_CFLAGS} -DG4USE_TOPC) -endif() - - -#---------------------------------------------------------------------------- -# Locate sources and headers for this project -# -include_directories(${PROJECT_SOURCE_DIR}/include - ${Geant4_INCLUDE_DIR}) -file(GLOB sources ${PROJECT_SOURCE_DIR}/src/*.cc - ${PROJECT_SOURCE_DIR}/src/*.icc) -file(GLOB headers ${PROJECT_SOURCE_DIR}/include/*.hh - ${PROJECT_SOURCE_DIR}/include/*.h) - - -#---------------------------------------------------------------------------- -# Add the executable, and link it to the Geant4 libraries -# -add_executable(g4stork g4stork.cc ${sources} ${headers}) -target_link_libraries(g4stork ${Geant4_LIBRARIES} ${TOPC_LIBS}) - - -#---------------------------------------------------------------------------- -# Copy all scripts to the build directory, i.e. the directory in which we -# build air_shower. This is so that we can run the executable directly because it -# relies on these scripts being in the current working directory. -# - - -#---------------------------------------------------------------------------- -# Add program to the project targets -# (this avoids the need of typing the program name after make) -# -add_custom_target(G4_STORK DEPENDS g4stork) - - -#---------------------------------------------------------------------------- -# Install the executable to 'bin' directory under CMAKE_INSTALL_PREFIX -# -install(TARGETS g4stork DESTINATION bin) diff --git a/G4STORK/G4STORK_Manual.pdf b/G4STORK/G4STORK_Manual.pdf deleted file mode 100644 index 4908372d..00000000 Binary files a/G4STORK/G4STORK_Manual.pdf and /dev/null differ diff --git a/G4STORK/InputFiles/C6LatticeInput.txt b/G4STORK/InputFiles/C6LatticeInput.txt deleted file mode 100755 index 6484b4aa..00000000 --- a/G4STORK/InputFiles/C6LatticeInput.txt +++ /dev/null @@ -1,49 +0,0 @@ -# Input for a CANDU-6 lattice cell - -# Build a CANDU-6 lattice cell -WORLD C6Lattice - -# Number of runs, events per run and primaries per event -NUM_RUNS 5 -NUM_EVENTS 12 -NUM_PRIMARY_PER_EVENT 20 - -#Cross-section Data Directory -CS_DATA_DIR DEFAULT - -#Final State Data Directory -#FS_DATA_DIR /home/SuperKamiGuru/NuclearSim/Data/ZippedG4NDL/0K/ -FS_DATA_DIR DEFAULT - -# Uniform source ditribution around the fuel -#UNIFORM_DIST_WITH_DIM 1 G4Tubs 1 4.7 7.2 0.5 25. 0. 0. - -# Initial random seed -SEED 2013092304 - -# Produce delayed neutrons instantaneously -DELAYED_OPTION 1 - -# Periodic Boundary condition -PERIODIC_BC 0 - -# Periodic Boundary condition -REFLECT_BC 6 -nx nx -ny ny nz -nz - -# Duration of each run (ns) -RUN_DURATION 5e5 - -# Initial neutron energy (MeV) -NEUTRON_ENERGY 2.0 - -# Initial Neutron Dist -#INITIAL_SOURCE_FILE Src_SCWRJason-100.txt - -# Output files -OUTPUT_LOG /Users/stuart/Documents/4th_Year/CS_4ZP6/GEANT4-GPU/G4STORK/OutputFiles/Log_C6Lattice.txt -#OUTPUT_SOURCE Src_C6Lattice.txt -#OUTPUT_FISSION Fis_C6Lattice.txt - -# Frequency of source output -OUTPUT_SRC_FREQ 30 - diff --git a/G4STORK/InputFiles/SCWRDopplerInput.txt b/G4STORK/InputFiles/SCWRDopplerInput.txt deleted file mode 100644 index 1953b389..00000000 --- a/G4STORK/InputFiles/SCWRDopplerInput.txt +++ /dev/null @@ -1,54 +0,0 @@ -# Input for quater lattice cell SCWR - -# Build a quarter lattice cell SCWR -WORLD SCWRDoppler - -# Use the Generational Method -K_CALC K_Generational - -# Number of runs, events per run and primaries per event -NUM_RUNS 50 -NUM_EVENTS 12 -NUM_PRIMARY_PER_EVENT 60 - -#Cross-section Data Directory -#CS_DATA_DIR /home/SuperKamiGuru/NuclearSim/Data/InterpolatedMCNPData/SCWRDopplerNew/ - -#Final State Data Directory -#FS_DATA_DIR /home/SuperKamiGuru/NuclearSim/Data/ConvertedMCNPData/293.606K/ - -# Uniform source ditribution around the fuel -UNIFORM_DIST_WITH_DIM 1 G4Tubs 1 4.7 7.2 0.5 25. 0. 0. - -# origin for the initial source distribution -INITIAL_SOURCE_POS -6.25 -6.25 0. - -# Initial random seed -SEED 2013092304 - -# Produce delayed neutrons instantaneously -DELAYED_OPTION 1 - -# Periodic Boundary condition -PERIODIC_BC 0 - -# Periodic Boundary condition -REFLECT_BC 6 -nx nx -ny ny nz -nz - -# Duration of each run (ns) -RUN_DURATION 1e5 - -# Initial neutron energy (MeV) -NEUTRON_ENERGY 2.0 - -# Initial Neutron Dist -#INITIAL_SOURCE_FILE Src_SCWRDoppler-100.txt - -# Output files -OUTPUT_LOG /Users/stuart/Documents/4th_Year/CS_4ZP6/GEANT4-GPU/G4STORK/OutputFiles/Log_SCWROutCVRDoppler-1.75-KGen.txt -#OUTPUT_SOURCE SourceFiles/Src_SCWROutCVRDoppler-1.75-KGen.txt -#OUTPUT_FISSION FissionFiles/Fis_SCWROutCVRDoppler-1.75-KGen.txt - -# Frequency of source output -OUTPUT_SRC_FREQ 50 - diff --git a/G4STORK/InputFiles/SCWRInput.txt b/G4STORK/InputFiles/SCWRInput.txt deleted file mode 100755 index ffd6db0e..00000000 --- a/G4STORK/InputFiles/SCWRInput.txt +++ /dev/null @@ -1,45 +0,0 @@ -# Input for quater lattice cell SCWR - -# Build a quarter lattice cell SCWR -WORLD SCWR - -# Number of runs, events per run and primaries per event -NUM_RUNS 100 -NUM_EVENTS 40 -NUM_PRIMARY_PER_EVENT 40 - -#CS Datat Directory -CS_DATA_DIR DEFAULT - -# Uniform source ditribution around the fuel -#UNIFORM_DIST_WITH_DIM 1 G4Tubs 1 4.7 7.2 0.5 25. 0. 0. - -# Initial random seed -SEED 2013092304 - -# Produce delayed neutrons instantaneously -INSTANT_DELAYED 1 - -# Periodic Boundary condition -PERIODIC_BC 6 -nx nx -ny ny nz -nz - -# Periodic Boundary condition -REFLECT_BC 0 - -# Duration of each run (ns) -RUN_DURATION 1e5 - -# Initial neutron energy (MeV) -NEUTRON_ENERGY 2.0 - -# Initial Neutron Dist -#INITIAL_SOURCE_FILE Src_SCWR-100.txt - -# Output files -OUTPUT_LOG Log_SCWR.txt -OUTPUT_SOURCE Src_SCWR.txt -OUTPUT_FISSION Fis_SCWR.txt - -# Frequency of source output -OUTPUT_SRC_FREQ 50 - diff --git a/G4STORK/InputFiles/SCWRJasonInput.txt b/G4STORK/InputFiles/SCWRJasonInput.txt deleted file mode 100755 index 7f922888..00000000 --- a/G4STORK/InputFiles/SCWRJasonInput.txt +++ /dev/null @@ -1,45 +0,0 @@ -# Input for quater lattice cell SCWR - -# Build a quarter lattice cell SCWR -WORLD SCWRJason - -# Number of runs, events per run and primaries per event -NUM_RUNS 100 -NUM_EVENTS 40 -NUM_PRIMARY_PER_EVENT 300 - -#Final State Data Directory -FS_DATA_DIR /home/SuperKamiGuru/NuclearSim/Data/ZippedG4NDL/0K/ - -# Uniform source ditribution around the fuel -UNIFORM_DIST_WITH_DIM 1 G4Tubs 1 4.7 7.2 0.5 25. 0. 0. - -# Initial random seed -SEED 2013092304 - -# Produce delayed neutrons instantaneously -INSTANT_DELAYED 1 - -# Periodic Boundary condition -PERIODIC_BC 0 - -# Periodic Boundary condition -REFLECT_BC 6 -nx nx -ny ny nz -nz - -# Duration of each run (ns) -RUN_DURATION 1e5 - -# Initial neutron energy (MeV) -NEUTRON_ENERGY 2.0 - -# Initial Neutron Dist -#INITIAL_SOURCE_FILE Src_CVRSCWRJason-100.txt - -# Output files -OUTPUT_LOG Log_CVRSCWRJason.txt -#OUTPUT_SOURCE Src_CVRSCWRJason.txt -#OUTPUT_FISSION Fis_CVRSCWRJason.txt - -# Frequency of source output -OUTPUT_SRC_FREQ 100 - diff --git a/G4STORK/MarshalMakefile b/G4STORK/MarshalMakefile deleted file mode 100755 index 5277631c..00000000 --- a/G4STORK/MarshalMakefile +++ /dev/null @@ -1,31 +0,0 @@ -MARSHALGEN_PATH = /usr/local/marshalgen-1.0 -MARSHAL=$(MARSHALGEN_PATH)/marshalgen - -default: all - -all: StorkNeutronData StorkTripleFloat StorkMatPropChange StorkPrimaryData StorkEventData - (cp -p include/Marshaled* AnnotatedFiles/; \ - cp -p include/*.msh AnnotatedFiles/; \ - cp -p $(MARSHALGEN_PATH)/MarshaledObj.h include/.) - - -StorkNeutronData: include/StorkNeutronData.hh - $(MARSHAL) $? - -StorkTripleFloat: include/StorkTripleFloat.hh - $(MARSHAL) $? - -StorkMatPropChange: include/StorkMatPropChange.hh - $(MARSHAL) $? - -StorkPrimaryData: include/StorkPrimaryData.hh - $(MARSHAL) $? - -StorkEventData: include/StorkEventData.hh - $(MARSHAL) $? - -clean: - rm include/*.msh include/Marshaled* AnnotatedFiles/*.msh AnnotatedFiles/Marshaled* - -cleanMSH: - rm include/*.msh diff --git a/G4STORK/README b/G4STORK/README deleted file mode 100755 index e69de29b..00000000 diff --git a/G4STORK/g4stork.cc b/G4STORK/g4stork.cc deleted file mode 100755 index 91668a25..00000000 --- a/G4STORK/g4stork.cc +++ /dev/null @@ -1 +0,0 @@ -/* g4stork.cc Created by: Liam Russell Date: 22-06-2011 Modified: 11-03-2013 Main driver file for G4-STORK code. Instantiates run manager, required classes and optional classes. Also instantiates the parse input class (input variables). */ // G4-STORK header files #include "StorkRunManager.hh" #include "StorkWorld.hh" #include "StorkNeutronPhysicsList.hh" #include "StorkPrimaryGeneratorAction.hh" #include "StorkRunAction.hh" #include "StorkEventAction.hh" #include "StorkParseInput.hh" // Geant4 header files #include "G4Timer.hh" #include "G4VisExecutive.hh" #include "G4UIExecutive.hh" #include "G4UImanager.hh" #include "G4UIsession.hh" #include "G4UIterminal.hh" #include "G4ThreeVector.hh" #include "G4UnitsTable.hh" #include "G4EventManager.hh" #include "G4TrackingManager.hh" #include "Randomize.hh" #include "G4RunManager.hh" #include "G4VUserActionInitialization.hh" // Other header files #include // Include parallel processing file #include "g4stork.icc" #ifdef G4USE_TOPC #include "topc.h" #endif int main(int argc, char **argv) { // SIMULATION VARIABLES -------------------------------------------------------- // Set up and start the timer G4Timer mainTimer; mainTimer.Start(); std::ostream *output = NULL; G4bool master = true; G4bool readInput = false; #ifdef G4USE_TOPC master = G4bool(TOPC_is_master()); #endif // USER GEOMETRY --------------------------------------------------------------- // ***** INSTANTIATE USER DEFINED GEOMETRIES HERE ***** // ***** // USER INPUT FILE ------------------------------------------------------------- // Check that an input file was given if(argc == 1) { G4cerr << "No input file given. Exiting." << G4endl; return 1; } // Create parse input object StorkParseInput *infile = new StorkParseInput; // ***** ADD USER GEOMETRY TO PARSE INPUT HERE ***** // ***** // Parse input file readInput = infile->ReadInputFile(G4String(argv[1])); if(!readInput) { G4cerr << "*** ERROR: Invalid input in " << G4String(argv[1]) << ". Exiting." << G4endl; return 1; } // Create a constant pointer to the parse input object const StorkParseInput* USER_INPUT = infile; // Set output stream in main function output = USER_INPUT->GetLogOutputStream(); // RANDOM NUMBER GENERATOR ----------------------------------------------------- // Set up random engine CLHEP::HepRandom::setTheEngine(new CLHEP::RanecuEngine); if(master) { CLHEP::HepRandom::setTheSeed(USER_INPUT->GetRandomSeed()); CLHEP::HepRandom::showEngineStatus(); CLHEP::HepRandom::saveEngineStatus(); } // SIMULATION STRUCTURES ------------------------------------------------------- StorkRunManager* runManager = new StorkRunManager(USER_INPUT); runManager->SetVerboseLevel(0); // Set version string in the StorkParseInput object infile->SetG4VersionString(runManager->GetVersionString()); // Construct the world StorkWorld *theWorld = new StorkWorld(USER_INPUT); // ***** ADD USER GEOMETRY TO STORKWORLD HERE ***** // ***** runManager->SetUserInitialization(theWorld); // Construct the physics list runManager->SetUserInitialization(new StorkNeutronPhysicsList(USER_INPUT)); // Construct the primary generator StorkPrimaryGeneratorAction * genAction; genAction = new StorkPrimaryGeneratorAction(USER_INPUT, master); runManager->SetUserAction(genAction); // Set optional user action class // Construct the run action only if this is the master StorkRunAction *runAction = NULL; if(master) { runAction = new StorkRunAction(genAction, USER_INPUT); } runManager->SetUserAction(runAction); // Construct the event action StorkEventAction* eventAction = new StorkEventAction(); runManager->SetUserAction(eventAction); // START SIMULATION ------------------------------------------------------------ // Initialize the run runManager->Initialize(); // Record the initialization time and restart the timer for the computation mainTimer.Stop(); if(master) { // theWorld->DumpGeometricalTree(); // Set world size in run action now that the world is built runAction->SetWorldDimensions(theWorld->GetWorldBoxDimensions()); USER_INPUT->PrintInput(output); *output << "# Initialization time: " << mainTimer << G4endl << "#" << G4endl << "# ---------------------------------------------------------" << G4endl << "# " << G4endl << "# Starting Simulation" << G4endl << "#" << G4endl; } mainTimer.Start(); #ifdef G4VISUALIZE_USE //Visualization manager G4VisManager* visManager = new G4VisExecutive("warnings"); visManager->Initialize(); // Define (G)UI G4UImanager* UImanager = G4UImanager::GetUIpointer(); G4UIExecutive* ui = new G4UIExecutive(argc, argv); UImanager->ApplyCommand("/control/execute VisCommands.mac"); //G4UIsession *ui = new G4UIterminal; ui->SessionStart(); delete ui; #endif #ifdef G4VERBOSE_TRACKING_USE G4EventManager *eventMan = G4EventManager::GetEventManager(); G4TrackingManager *trackMan = eventMan->GetTrackingManager(); trackMan->SetVerboseLevel(1); #endif #ifndef G4VISUALIZE_USE // set to zero so function will go to terminal if(USER_INPUT->GetNumberOfEvents()) { runManager->BeamOn(USER_INPUT->GetNumberOfEvents()); } else { G4UIsession *ui = new G4UIterminal; ui->SessionStart(); delete ui; } #endif // WRAP-UP SIMULATION ---------------------------------------------------------- // Output the source convergence results if(master) runManager->OutputResults(); #ifdef G4VISUALIZE_USE delete visManager; #endif // Stop the timer for the total computation time mainTimer.Stop(); if(master) { *output << "#" << G4endl << "# Total computation time: " << mainTimer << G4endl; } delete infile; delete runManager; return 0; } \ No newline at end of file diff --git a/G4STORK/g4stork.icc b/G4STORK/g4stork.icc deleted file mode 100755 index 1dcbc5ee..00000000 --- a/G4STORK/g4stork.icc +++ /dev/null @@ -1,47 +0,0 @@ -/* -g4stork.icc - -Created by: Liam Russell -Date: 15-08-2011 -Modified: 11-03-2013 - -This file is used to switch to parallel processing if the environment variable -G4USE_TOPC is set. Switches the run manager class from StorkRunManager to -StorkParallelRunManager (parallelrun manager) and overrides the main function. -*/ - - -#ifdef G4USE_TOPC - -// Include header files -#include "topc.h" -#include "StorkParallelRunManager.hh" - - -// Set declaration for main function in g4stork.cc (renamed G4_main below) -static int G4_main(int argc, char **argv); - - -// TOP-C main function -// Initializes and cleans up after G4_main finishes -int main(int argc, char **argv) -{ - // Set mode to no tracer messages - TOPC_OPT_trace = 0; - //TOPC_OPT_safety=19; - // added this for SCWR Sim should remove later - TOPC_OPT_slave_timeout=104000; - - TOPC_init(&argc, &argv); - int ret_val = G4_main(argc, argv); - TOPC_finalize(); - - return ret_val; -} - - -// Redefine main() and StorkRunManager in g4stork.cc -#define StorkRunManager StorkParallelRunManager -#define main G4_main - -#endif diff --git a/G4STORK/include/BZR_Version_Info.hh b/G4STORK/include/BZR_Version_Info.hh deleted file mode 100755 index b289e7e1..00000000 --- a/G4STORK/include/BZR_Version_Info.hh +++ /dev/null @@ -1,2 +0,0 @@ -#define BZR_REVNO "0.9.3" -#define BZR_BUILD_DATE "2013-03-13 08:01:38 -0400" diff --git a/G4STORK/include/BareSphereConstructor.hh b/G4STORK/include/BareSphereConstructor.hh deleted file mode 100755 index 442d4e6a..00000000 --- a/G4STORK/include/BareSphereConstructor.hh +++ /dev/null @@ -1,64 +0,0 @@ -/* -BareSphereConstructor.hh - -Created by: Liam Russell -Date: 23-05-2012 -Modified: 10-03-2013 - -Header for BareSphereConstructor class. - -This class creates the simulation geometry and materials based on the input -file. The geometry is a bare sphere of various diameters and the materials are -either solid U235, a homogeneous mixture of natural uranium and heavy water, or -the Godiva sphere (critical sphere of HEU). - -*/ - -#ifndef BARESPHERE_H -#define BARESPHERE_H - -// Include header files -#include "StorkNeutronSD.hh" -#include "StorkVWorldConstructor.hh" -#include "G4Orb.hh" - - -class BareSphereConstructor : public StorkVWorldConstructor -{ - public: - // Public memeber functions - - // Constructor and destructor - BareSphereConstructor(); - virtual ~BareSphereConstructor(); - virtual G4VPhysicalVolume* ConstructNewWorld(const StorkParseInput* infile); - - - protected: - // Protected member functions - - // Material name enumerator - enum WorldMats - { e_U235=0, e_Godiva, e_UHW, NUM_MATERIALS }; - - // Private member functions - virtual G4VPhysicalVolume* ConstructWorld(); - virtual void ConstructMaterials(); - - protected: - // Protected member variables - - // Logical Volumes - G4LogicalVolume *reactorLogical; - - // Visualization attributes - G4VisAttributes *reactorVisAtt; - - // Stored variables from infile - G4String materialID; - G4double matTemp; - G4double matDensity[NUM_MATERIALS]; - G4double reactorRadius; -}; - -#endif // BARESPHERE_H diff --git a/G4STORK/include/C6LatticeConstructor.hh b/G4STORK/include/C6LatticeConstructor.hh deleted file mode 100755 index a9721a9b..00000000 --- a/G4STORK/include/C6LatticeConstructor.hh +++ /dev/null @@ -1,78 +0,0 @@ -/* -C6latticeConstructor.hh - -Created by: Liam Russell -Date: 23-05-2012 -Modified: 11-03-2013 - -Header for C6LatticeConstructor class. - -This class creates the simulation geometry for a CANDU 6 lattice cell. The -material and geometric composition of the lattice cell were taken from the -DRAGON manual[1]. - -Based on the "C6World" class created by Wesley Ford 10-05-2012. - -[1] G. Marleau, A. Hebert, and R. Roy, "A User Guide for DRAGON 3.06". Ecole -Polytechnique de Montreal, 2012, pp. 148-152. IGE-174 Rev. 10. - -*/ - -#ifndef C6LATTICECONSTRUCTOR_H -#define C6LATTICECONSTRUCTOR_H - -// Include header files -#include "StorkVWorldConstructor.hh" -#include "StorkNeutronSD.hh" -#include "G4Box.hh" -#include "G4Tubs.hh" -#include - - -class C6LatticeConstructor: public StorkVWorldConstructor -{ - public: - // Public member functions - - C6LatticeConstructor(); - virtual ~C6LatticeConstructor(); - - - protected: - // Protected member functions - - virtual G4VPhysicalVolume* ConstructWorld(); - virtual void ConstructMaterials(); - - protected: - // Protected member variables - - // Logical Volumes - G4LogicalVolume *cellLogical; - G4LogicalVolume *cTubeLogical; - G4LogicalVolume *gasAnnLogical; - G4LogicalVolume *pressTubeLogical; - G4LogicalVolume *coolantLogical; - G4LogicalVolume *sheatheLogical; - G4LogicalVolume *fuelLogical; - - // Visualization attributes - G4VisAttributes *modVisAtt; - G4VisAttributes *cTubeVisAtt; - G4VisAttributes *gasAnnVisAtt; - G4VisAttributes *pressTubeVisAtt; - G4VisAttributes *coolantVisAtt; - G4VisAttributes *sheatheVisAtt; - G4VisAttributes *fuelVisAtt; - - // Stored variables from infile - G4double latticePitch; - G4double fuelTemp; - G4double fuelDensity; - G4double coolantTemp; - G4double coolantDensity; - G4double moderatorTemp; - G4double moderatorDensity; -}; - -#endif // C6LATTICECONSTRUCTOR_H diff --git a/G4STORK/include/DebugConstructor.hh b/G4STORK/include/DebugConstructor.hh deleted file mode 100755 index 1874bdd6..00000000 --- a/G4STORK/include/DebugConstructor.hh +++ /dev/null @@ -1,98 +0,0 @@ -#ifndef DEBUGCONSTRUCTOR_H -#define DEBUGCONSTRUCTOR_H - -// Include header files -#include "StorkVWorldConstructor.hh" -#include "StorkNeutronSD.hh" -#include "UnionBinaryTree.hh" -#include "G4SubtractionSolid.hh" -#include "G4IntersectionSolid.hh" -#include "G4ReflectionFactory.hh" -#include "G4ReflectedSolid.hh" -#include "G4Transform3D.hh" -#include "G4DisplacedSolid.hh" -#include "G4RotationMatrix.hh" -#include "G4AffineTransform.hh" -#include "G4PVReplica.hh" -#include "G4Para.hh" -#include "G4Box.hh" -#include "G4Tubs.hh" -#include -#include "G4NistManager.hh" - -class DebugConstructor: public StorkVWorldConstructor -{ - public: - DebugConstructor(); - virtual ~DebugConstructor(); - - protected: - // Protected member functions - - virtual G4VPhysicalVolume* ConstructWorld(); - virtual void ConstructMaterials(); - - protected: - // Protected member variables - G4ThreeVector originTubeSec[6]; - // Logical Volumes - G4LogicalVolume *cellLogical; - G4LogicalVolume *alumShellLogical; - G4LogicalVolume *alumContLogical; - G4LogicalVolume *D2OContLogical; - G4LogicalVolume *reflectorLogical; - G4LogicalVolume *insAlumLogical; - G4LogicalVolume *insBeamLogical; - G4LogicalVolume *outSmallAlumLogical; - G4LogicalVolume *outLargeAlumLogical; - G4LogicalVolume *cadLinLogical; - G4LogicalVolume *outSmallBeamLogical; - G4LogicalVolume *outLargeBeamLogical; - G4LogicalVolume *coreWaterLogical; - G4LogicalVolume *coreWaterSliceLogical; - G4LogicalVolume *zircGridLogical; - G4LogicalVolume *airGapsLatLogical; -// G4LogicalVolume *airGapsLatHLogical; - G4LogicalVolume *airGapsLatHRLogical; - G4LogicalVolume *airGapsLatHR2Logical; - G4LogicalVolume *fuelLatLogical; -// G4LogicalVolume *fuelLatHLogical; - G4LogicalVolume *fuelLatHRLogical; - G4LogicalVolume *fuelLatHR2Logical; - G4LogicalVolume *contRodZirLogical; - G4LogicalVolume *contRodAlumLogical; - G4LogicalVolume *contRodCadLogical; - G4LogicalVolume *contRodCentLogical; - - -// // Visualization attributes - G4VisAttributes *cellVisAtt; - G4VisAttributes *alumShellVisAtt; - G4VisAttributes *alumContVisAtt; - G4VisAttributes *D2OContVisAtt; - G4VisAttributes *reflectorVisAtt; - G4VisAttributes *insAlumVisAtt; - G4VisAttributes *insBeamVisAtt; - G4VisAttributes *outSmallAlumVisAtt; - G4VisAttributes *outLargeAlumVisAtt; - G4VisAttributes *cadLinTubeVisAtt; - G4VisAttributes *outSmallBeamVisAtt; - G4VisAttributes *outLargeBeamVisAtt; - G4VisAttributes *coreWaterVisAtt; - G4VisAttributes *coreWaterSliceVisAtt; - G4VisAttributes *zircGridVisAtt; - G4VisAttributes *airGapsLatVisAtt; - G4VisAttributes *airGapsLatHVisAtt; - G4VisAttributes *fuelLatVisAtt; - G4VisAttributes *fuelLatHVisAtt; - G4VisAttributes *contRodZirVisAtt; - G4VisAttributes *contRodAlumVisAtt; - G4VisAttributes *contRodCadVisAtt; - G4VisAttributes *contRodCentVisAtt; - - - // Stored variables from infile - G4double contRodH; -}; - -#endif // SLOWPOKECONSTRUCTOR_H diff --git a/G4STORK/include/ElementNames.hh b/G4STORK/include/ElementNames.hh deleted file mode 100755 index f708eb6c..00000000 --- a/G4STORK/include/ElementNames.hh +++ /dev/null @@ -1,27 +0,0 @@ -#ifndef ElementNames_HH -#define ElementNames_HH - -#include -#include -using namespace std; - -class ElementNames -{ - public: - ElementNames(); - virtual ~ElementNames(); - static void ClearStore(); - static void SetElementNames(); - static string GetName(int Z) - { - return elementName[Z]; - } - static bool CheckName(string name); - static bool CheckName(string name, int Z); - static string *elementName; - protected: - private: - -}; - -#endif // ElementNames_HH diff --git a/G4STORK/include/GuillaumeConstructor.hh b/G4STORK/include/GuillaumeConstructor.hh deleted file mode 100755 index a81f6508..00000000 --- a/G4STORK/include/GuillaumeConstructor.hh +++ /dev/null @@ -1,95 +0,0 @@ -#ifndef GUILLAUMECONSTRUCTOR_H -#define GUILLAUMECONSTRUCTOR_H - - -// Include header files -#include "StorkVWorldConstructor.hh" -#include "StorkNeutronSD.hh" -#include "G4VSolid.hh" -#include "G4UnionSolid.hh" -#include "G4SubtractionSolid.hh" -#include "G4IntersectionSolid.hh" -#include "G4Para.hh" -#include "G4Box.hh" -#include "G4Tubs.hh" -#include "G4Orb.hh" -#include -#include - -class GuillaumeConstructor: public StorkVWorldConstructor -{ - public: - GuillaumeConstructor(); - virtual ~GuillaumeConstructor(); - - protected: - // Protected member functions - - virtual G4VPhysicalVolume* ConstructWorld(); - virtual void ConstructMaterials(); - - protected: - // Protected member variables - - // Logical Volumes - G4LogicalVolume *ZirconiumLogical; - G4LogicalVolume *WaterHolesLowerLogical; - G4LogicalVolume *WaterHolesUpperLogical; - G4LogicalVolume *AirGapLogical; - G4LogicalVolume *FuelRodLogical; - G4LogicalVolume *LowerPinLogical; - G4LogicalVolume *ReflectorLogical; - G4LogicalVolume *D2OContainerLogical; - G4LogicalVolume *D2OLogical; - G4LogicalVolume *contRodZirLogical; - G4LogicalVolume *contRodAlumLogical; - G4LogicalVolume *contRodCadLogical; - G4LogicalVolume *contRodCentLogical; - G4LogicalVolume *insAlumLogical; - G4LogicalVolume *insBeamLogical; - G4LogicalVolume *outSmallAlumLogical; - G4LogicalVolume *outLargeAlumLogical; - G4LogicalVolume *cadLinLogical; - G4LogicalVolume *outSmallBeamLogical; - G4LogicalVolume *outLargeBeamLogical; - G4LogicalVolume *alumShellLogical; - G4LogicalVolume *cellLogical; - - // Visualization attributes - G4VisAttributes *ZirconiumAtt; - G4VisAttributes *WaterHolesLowerAtt; - G4VisAttributes *WaterHolesUpperAtt; - G4VisAttributes *AirGapAtt; - G4VisAttributes *FuelRodAtt; - G4VisAttributes *LowerPinAtt; - G4VisAttributes *ReflectorAtt; - G4VisAttributes *D2OContainerAtt; - G4VisAttributes *D2OAtt; - G4VisAttributes *contRodZirVisAtt; - G4VisAttributes *contRodAlumVisAtt; - G4VisAttributes *contRodCadVisAtt; - G4VisAttributes *contRodCentVisAtt; - G4VisAttributes *insAlumVisAtt; - G4VisAttributes *insBeamVisAtt; - G4VisAttributes *outSmallAlumVisAtt; - G4VisAttributes *outLargeAlumVisAtt; - G4VisAttributes *cadLinTubeVisAtt; - G4VisAttributes *outSmallBeamVisAtt; - G4VisAttributes *outLargeBeamVisAtt; - G4VisAttributes *alumShellVisAtt; - G4VisAttributes *cellVisAtt; - - // Union Solid - G4UnionSolid *Zirconium; - - // Stored variables from infile - G4double latticePitch; - G4double fuelTemp; - G4double fuelDensity; - G4double coolantTemp; - G4double coolantDensity; - G4double moderatorTemp; - G4double moderatorDensity; -}; - -#endif // GUILLAUMECONSTRUCTOR_H diff --git a/G4STORK/include/InfiniteUniformLatticeConstructor.hh b/G4STORK/include/InfiniteUniformLatticeConstructor.hh deleted file mode 100755 index 3cc6b5a3..00000000 --- a/G4STORK/include/InfiniteUniformLatticeConstructor.hh +++ /dev/null @@ -1,62 +0,0 @@ -/* -InfiniteUniformLatticeConstructor.hh - -Created by: Liam Russell -Date: 23-05-2012 -Modified: 11-03-2013 - -Header for InfiniteUniformLatticeConstructor class. - -Builds a world composed of an infinite lattice of homogeneous cubic cells. -The available materials are a mixture of natural uranium and heavy water or -a cell of solid uranium with different (U235) enrichment levels. - -*/ - -#ifndef CUBECONSTRUCTOR_H -#define CUBECONSTRUCTOR_H - -// Include header files -#include "StorkVWorldConstructor.hh" -#include "StorkNeutronSD.hh" -#include "G4Box.hh" - - -class InfiniteUniformLatticeConstructor : public StorkVWorldConstructor -{ - public: - // Public member functions - - // Constructor and destructor - InfiniteUniformLatticeConstructor(); - virtual ~InfiniteUniformLatticeConstructor(); - - virtual G4VPhysicalVolume* ConstructNewWorld(const - StorkParseInput* infile); - - - protected: - // Protected member functions - - virtual G4VPhysicalVolume* ConstructWorld(); - virtual void ConstructMaterials(); - - protected: - // Protected member functions - - // Logical Volumes - G4LogicalVolume *reactorLogical; - - // Visualization attributes - G4VisAttributes *reactorVisAtt; - - // Stored variables from infile - G4String materialID; - G4double matTemp; - G4double matDensity; - G4double u235Conc; - G4double hwConc; - G4double latticePitch; -}; - -#endif // CUBECONSTRUCTOR_H diff --git a/G4STORK/include/Q_ZED2Constructor.hh b/G4STORK/include/Q_ZED2Constructor.hh deleted file mode 100755 index f2d02293..00000000 --- a/G4STORK/include/Q_ZED2Constructor.hh +++ /dev/null @@ -1,178 +0,0 @@ - -/* -Q_ZED2Constructor.hh - -Created by: Salma Mahzooni -Date: 26-07-2013 -Modified: 11-03-2013 - -Header for C6LatticeConstructor class. - -This class creates the simulation geometry for a CANDU 6 lattice cell. The -material and geometric composition of the lattice cell were taken from the -DRAGON manual[1]. - -Based on the "C6World" class created by Wesley Ford 10-05-2012. - -[1] G. Marleau, A. Hebert, and R. Roy, "A User Guide for DRAGON 3.06". Ecole -Polytechnique de Montreal, 2012, pp. 148-152. IGE-174 Rev. 10. - -*/ - -#ifndef Q_ZED2Constructor_H -#define Q_ZED2Constructor_H - -// Include header files -#include "StorkNeutronSD.hh" -#include "StorkVWorldConstructor.hh" -#include "G4UnionSolid.hh" -#include "G4Box.hh" -#include "G4Tubs.hh" -#include "G4Orb.hh" -#include "G4SubtractionSolid.hh" - - - -class Q_ZED2Constructor : public StorkVWorldConstructor -{ - public: - // Public memeber functions - - // Constructor and destructor - Q_ZED2Constructor(); - virtual ~Q_ZED2Constructor(); - virtual G4VPhysicalVolume* ConstructNewWorld(const StorkParseInput* infile); - - - protected: - // Protected member functions - - // Material name enumerator - enum WorldMats - { e_U235=0, e_Godiva, e_UHW, NUM_MATERIALS }; - - // Private member functions - virtual G4VPhysicalVolume* ConstructWorld(); - virtual void ConstructMaterials(); - - protected: - // Protected member variables - - // Logical Volumes - G4LogicalVolume *worldLogical; - G4LogicalVolume *reactDimTubeLogical; - G4LogicalVolume *airTubeLogical; - G4LogicalVolume *vesselLogical; - G4LogicalVolume *tankLogical1; - G4LogicalVolume *ModLogical; - G4LogicalVolume *logicCalandria1; - G4LogicalVolume *logicGasAnn1; - G4LogicalVolume *logicPressure1; - G4LogicalVolume *logicCoolant1; - G4LogicalVolume *logicAir1; - G4LogicalVolume *logicRodA1; - G4LogicalVolume *logicRodB1; - G4LogicalVolume *logicSheathA1; - G4LogicalVolume *logicSheathB1; - G4LogicalVolume *logicEndPlate2; - G4LogicalVolume *logicEndPlate1; - G4LogicalVolume *logicCalandria1Mod; - G4LogicalVolume *logicGasAnn1Mod; - G4LogicalVolume *logicPressure1Mod; - G4LogicalVolume *logicCoolant1Mod; - G4LogicalVolume *logicRodA1Cut2; - G4LogicalVolume *logicRodB1Cut2; - G4LogicalVolume *logicSheathA1Cut2; - G4LogicalVolume *logicSheathB1Cut2; - G4LogicalVolume *logicEndPlate2Cut2; - G4LogicalVolume *logicRodA1Mod; - G4LogicalVolume *logicRodB1Mod; - G4LogicalVolume *logicSheathA1Mod; - G4LogicalVolume *logicSheathB1Mod; - G4LogicalVolume *logicEndPlate2Mod; - G4LogicalVolume *logicEndPlate1Mod; - G4LogicalVolume *logicRodA1Cut1; - G4LogicalVolume *logicRodB1Cut1; - G4LogicalVolume *logicSheathA1Cut1; - G4LogicalVolume *logicSheathB1Cut1; - G4LogicalVolume *logicEndPlate2Cut1; - G4LogicalVolume *logicCalandria1RU; - G4LogicalVolume *logicGasAnn1RU; - G4LogicalVolume *logicPressure1RU; - G4LogicalVolume *logicCoolant1RU; - G4LogicalVolume *logicAir1RU; - G4LogicalVolume *logicRodA1RU; - G4LogicalVolume *logicRodB1RU; - G4LogicalVolume *logicSheathA1RU; - G4LogicalVolume *logicSheathB1RU; - G4LogicalVolume *logicEndPlate2RU; - G4LogicalVolume *logicEndPlate1RU; - G4LogicalVolume *logicCalandria1ModRU; - G4LogicalVolume *logicGasAnn1ModRU; - G4LogicalVolume *logicPressure1ModRU; - G4LogicalVolume *logicCoolant1ModRU; - G4LogicalVolume *logicRodA1Cut2RU; - G4LogicalVolume *logicRodB1Cut2RU; - G4LogicalVolume *logicSheathA1Cut2RU; - G4LogicalVolume *logicSheathB1Cut2RU; - G4LogicalVolume *logicEndPlate2Cut2RU; - G4LogicalVolume *logicRodA1ModRU; - G4LogicalVolume *logicRodB1ModRU; - G4LogicalVolume *logicSheathA1ModRU; - G4LogicalVolume *logicSheathB1ModRU; - G4LogicalVolume *logicEndPlate2ModRU; - G4LogicalVolume *logicEndPlate1ModRU; - G4LogicalVolume *logicRodA1Cut1RU; - G4LogicalVolume *logicRodB1Cut1RU; - G4LogicalVolume *logicSheathA1Cut1RU; - G4LogicalVolume *logicSheathB1Cut1RU; - G4LogicalVolume *logicEndPlate2Cut1RU; - G4LogicalVolume *logicDumplineAl; - G4LogicalVolume *logicDumplineHW; - G4LogicalVolume *logicDumplineAlC; - G4LogicalVolume *logicDumplineHWC; - - - - // Visualization attributes - - G4VisAttributes * vesselVisAtt; - G4VisAttributes * tank1VisATT; - G4VisAttributes * ModVisAtt; - G4VisAttributes * fuelA1VisATT; - G4VisAttributes * fuelB1VisATT; - G4VisAttributes * sheathA1VisATT; - G4VisAttributes * sheathB1VisATT; - G4VisAttributes * Air1VisAtt; - G4VisAttributes * Coolant1VisAtt; - G4VisAttributes * Pressure1VisAtt; - G4VisAttributes * GasAnn1VisAtt; - G4VisAttributes * Calandria1VisAtt; - G4VisAttributes * EndPlate2VisATT; - G4VisAttributes * airTubeVisAtt; - G4VisAttributes * DumplineAlVisAtt; - G4VisAttributes * DumplineHWVisAtt; - G4VisAttributes * reactDimTubeVisAtt; - - - - - // Multifunctional Detector - //G4MultiFunctionalDetector *FluxScorer; - // Stored variables from infile - G4String materialID; - G4double matTemp; - G4double matDensity[NUM_MATERIALS]; - G4double reactorRadius; - G4double fuelTemp; - G4double fuelDensity; - G4double AirDensity; - G4double moderatorTemp; - G4double moderatorDensity; - G4double coolantDensity; - G4double coolantTemp; -}; - - -#endif // Q_ZED2Constructor_H - diff --git a/G4STORK/include/SCWRConstructor.hh b/G4STORK/include/SCWRConstructor.hh deleted file mode 100755 index 9923d152..00000000 --- a/G4STORK/include/SCWRConstructor.hh +++ /dev/null @@ -1,132 +0,0 @@ -/* -SCWRConstructor.hh - -Created by: Wesley Ford -Date: 14-05-2014 -Modified: NA - -Header for SCWRConstructor class. - -This class creates the simulation geometry for a SCWR. - -Based on the "C6World" class created by Wesley Ford 10-05-2012. - -*/ - -#ifndef SCWRCONSTRUCTOR_H -#define SCWRCONSTRUCTOR_H - -// Include header files -#include "StorkVWorldConstructor.hh" -#include "StorkNeutronSD.hh" -#include "G4Box.hh" -#include "G4Tubs.hh" -#include - - -class SCWRConstructor: public StorkVWorldConstructor -{ - public: - // Public member functions - - SCWRConstructor(); - virtual ~SCWRConstructor(); - - - protected: - // Protected member functions - - virtual G4VPhysicalVolume* ConstructWorld(); - virtual void ConstructMaterials(); - - protected: - // Protected member variables - - // Logical Volumes - G4LogicalVolume *cellLogical; - G4LogicalVolume *pressTubeLogical1; - G4LogicalVolume *pressTubeLogical2; - G4LogicalVolume *pressTubeLogical3; - G4LogicalVolume *pressTubeLogical4; - G4LogicalVolume *outLinerLogical; - G4LogicalVolume *insulatorLogical1; - G4LogicalVolume *insulatorLogical2; - G4LogicalVolume *insulatorLogical3; - G4LogicalVolume *insulatorLogical4; - G4LogicalVolume *linerLogical; - G4LogicalVolume *coolantLogical; - G4LogicalVolume *outSheatheLogical; - G4LogicalVolume *inSheatheLogical; - G4LogicalVolume *outFuelLogical1; - G4LogicalVolume *outFuelLogical2; - G4LogicalVolume *outFuelLogical3; - G4LogicalVolume *outFuelLogical4; - G4LogicalVolume *inFuelLogical1; - G4LogicalVolume *inFuelLogical2; - G4LogicalVolume *inFuelLogical3; - G4LogicalVolume *inFuelLogical4; -// G4LogicalVolume *outFlowTubeLogical; -// G4LogicalVolume *flowTubeLogical1; -// G4LogicalVolume *flowTubeLogical2; -// G4LogicalVolume *inFlowTubeLogical; - G4LogicalVolume *flowTubeLogical; - G4LogicalVolume *centralCoolantLogical; - - - // Visualization attributes - G4VisAttributes *cellVisAtt; - G4VisAttributes *pressTubeVisAtt; - G4VisAttributes *outLinerVisAtt; - G4VisAttributes *insulatorVisAtt; - G4VisAttributes *linerVisAtt; - G4VisAttributes *coolantVisAtt; - G4VisAttributes *outSheatheVisAtt; - G4VisAttributes *inSheatheVisAtt; - G4VisAttributes *outFuelVisAtt; - G4VisAttributes *inFuelVisAtt; -// G4VisAttributes *outFlowTubeVisAtt; - G4VisAttributes *flowTubeVisAtt; -// G4VisAttributes *inFlowTubeVisAtt; - G4VisAttributes *centralCoolantVisAtt; - - // Stored variables from infile - G4double latticePitch; - - G4double moderatorTemp; - G4double moderatorDensity; - - G4double pressTubeTemp[4]; - G4double pressTubeDensity; - - G4double outLinerTemp; - G4double outLinerDensity; - - G4double insulatorTemp[4]; - G4double insulatorDensity; - - G4double linerTemp; - G4double linerDensity; - - G4double coolantTemp; - G4double coolantDensity; - - G4double inSheatheTemp; - G4double inSheatheDensity; - - G4double outSheatheTemp; - G4double outSheatheDensity; - - G4double innerFuelTemp[4]; - G4double innerFuelDensity; - - G4double outerFuelTemp[4]; - G4double outerFuelDensity; - - G4double flowTubeTemp; - G4double flowTubeDensity; - - G4double centralCoolantTemp; - G4double centralCoolantDensity; -}; - -#endif // SCWRCONSTRUCTOR_H diff --git a/G4STORK/include/SCWRDopplerConstructor.hh b/G4STORK/include/SCWRDopplerConstructor.hh deleted file mode 100755 index 7fec081c..00000000 --- a/G4STORK/include/SCWRDopplerConstructor.hh +++ /dev/null @@ -1,129 +0,0 @@ -/* -SCWRDopplerConstructor.hh - -Created by: Wesley Ford -Date: 14-05-2014 -Modified: NA - -Header for SCWRDopplerConstructor class. - -This class creates the simulation geometry for a SCWR. The -material and geometric composition of the lattice cell were taken from the -DRAGON manual[1]. - -Based on the "C6World" class created by Wesley Ford 10-05-2012. - -[1] G. Marleau, A. Hebert, and R. Roy, "A User Guide for DRAGON 3.06". Ecole -Polytechnique de Montreal, 2012, pp. 148-152. IGE-174 Rev. 10. - -*/ - -#ifndef SCWRDopplerConstructor_H -#define SCWRDopplerConstructor_H - -// Include header files -#include "StorkVWorldConstructor.hh" -#include "StorkNeutronSD.hh" -#include "G4Box.hh" -#include "G4Tubs.hh" -#include - - -class SCWRDopplerConstructor: public StorkVWorldConstructor -{ - public: - // Public member functions - - SCWRDopplerConstructor(); - virtual ~SCWRDopplerConstructor(); - - - protected: - // Protected member functions - - virtual G4VPhysicalVolume* ConstructWorld(); - virtual void ConstructMaterials(); - - protected: - // Protected member variables - - // Logical Volumes - G4LogicalVolume *cellLogical; - G4LogicalVolume *pressTubeLogical; - G4LogicalVolume *outLinerLogical; - G4LogicalVolume *insulatorLogical; - G4LogicalVolume *linerLogical; - G4LogicalVolume *coolantLogical; - G4LogicalVolume *outSheatheLogical; - G4LogicalVolume *outSheatheLogicalH1; - G4LogicalVolume *outSheatheLogicalH2; - G4LogicalVolume *inSheatheLogical; - G4LogicalVolume *inSheatheLogicalH1; - G4LogicalVolume *inSheatheLogicalH2; - G4LogicalVolume *outFuelLogical; - G4LogicalVolume *outFuelLogicalH1; - G4LogicalVolume *outFuelLogicalH2; - G4LogicalVolume *inFuelLogical; - G4LogicalVolume *inFuelLogicalH1; - G4LogicalVolume *inFuelLogicalH2; - G4LogicalVolume *flowTubeLogical; - G4LogicalVolume *centralCoolantLogical; - - - // Visualization attributes - G4VisAttributes *cellVisAtt; - G4VisAttributes *pressTubeVisAtt; - G4VisAttributes *outLinerVisAtt; - G4VisAttributes *insulatorVisAtt; - G4VisAttributes *linerVisAtt; - G4VisAttributes *coolantVisAtt; - G4VisAttributes *outSheatheVisAtt; - G4VisAttributes *inSheatheVisAtt; - G4VisAttributes *outFuelVisAtt; - G4VisAttributes *inFuelVisAtt; -// G4VisAttributes *outFlowTubeVisAtt; - G4VisAttributes *flowTubeVisAtt; -// G4VisAttributes *inFlowTubeVisAtt; - G4VisAttributes *centralCoolantVisAtt; - - // Stored variables from infile - G4double latticePitch; - - G4double moderatorTemp; - G4double moderatorDensity; - - G4double pressTubeTemp; - G4double pressTubeDensity; - - G4double outLinerTemp; - G4double outLinerDensity; - - G4double insulatorTemp; - G4double insulatorDensity; - - G4double linerTemp; - G4double linerDensity; - - G4double coolantTemp; - G4double coolantDensity; - - G4double inSheatheTemp; - G4double inSheatheDensity; - - G4double outSheatheTemp; - G4double outSheatheDensity; - - G4double innerFuelTemp; - G4double innerFuelDensity; - - G4double outerFuelTemp; - G4double outerFuelDensity; - - G4double flowTubeTemp; - G4double flowTubeDensity; - - G4double centralCoolantTemp; - G4double centralCoolantDensity; -}; - -#endif // SCWRDopplerConstructor_H diff --git a/G4STORK/include/SCWRJasonConstructor.hh b/G4STORK/include/SCWRJasonConstructor.hh deleted file mode 100755 index b2c77023..00000000 --- a/G4STORK/include/SCWRJasonConstructor.hh +++ /dev/null @@ -1,129 +0,0 @@ -/* -SCWRJasonConstructor.hh - -Created by: Wesley Ford -Date: 14-05-2014 -Modified: NA - -Header for SCWRJasonConstructor class. - -This class creates the simulation geometry for a SCWR. The -material and geometric composition of the lattice cell were taken from the -DRAGON manual[1]. - -Based on the "C6World" class created by Wesley Ford 10-05-2012. - -[1] G. Marleau, A. Hebert, and R. Roy, "A User Guide for DRAGON 3.06". Ecole -Polytechnique de Montreal, 2012, pp. 148-152. IGE-174 Rev. 10. - -*/ - -#ifndef SCWRJasonConstructor_H -#define SCWRJasonConstructor_H - -// Include header files -#include "StorkVWorldConstructor.hh" -#include "StorkNeutronSD.hh" -#include "G4Box.hh" -#include "G4Tubs.hh" -#include - - -class SCWRJasonConstructor: public StorkVWorldConstructor -{ - public: - // Public member functions - - SCWRJasonConstructor(); - virtual ~SCWRJasonConstructor(); - - - protected: - // Protected member functions - - virtual G4VPhysicalVolume* ConstructWorld(); - virtual void ConstructMaterials(); - - protected: - // Protected member variables - - // Logical Volumes - G4LogicalVolume *cellLogical; - G4LogicalVolume *pressTubeLogical; - G4LogicalVolume *outLinerLogical; - G4LogicalVolume *insulatorLogical; - G4LogicalVolume *linerLogical; - G4LogicalVolume *coolantLogical; - G4LogicalVolume *outSheatheLogical; - G4LogicalVolume *outSheatheLogicalH1; - G4LogicalVolume *outSheatheLogicalH2; - G4LogicalVolume *inSheatheLogical; - G4LogicalVolume *inSheatheLogicalH1; - G4LogicalVolume *inSheatheLogicalH2; - G4LogicalVolume *outFuelLogical; - G4LogicalVolume *outFuelLogicalH1; - G4LogicalVolume *outFuelLogicalH2; - G4LogicalVolume *inFuelLogical; - G4LogicalVolume *inFuelLogicalH1; - G4LogicalVolume *inFuelLogicalH2; - G4LogicalVolume *flowTubeLogical; - G4LogicalVolume *centralCoolantLogical; - - - // Visualization attributes - G4VisAttributes *cellVisAtt; - G4VisAttributes *pressTubeVisAtt; - G4VisAttributes *outLinerVisAtt; - G4VisAttributes *insulatorVisAtt; - G4VisAttributes *linerVisAtt; - G4VisAttributes *coolantVisAtt; - G4VisAttributes *outSheatheVisAtt; - G4VisAttributes *inSheatheVisAtt; - G4VisAttributes *outFuelVisAtt; - G4VisAttributes *inFuelVisAtt; -// G4VisAttributes *outFlowTubeVisAtt; - G4VisAttributes *flowTubeVisAtt; -// G4VisAttributes *inFlowTubeVisAtt; - G4VisAttributes *centralCoolantVisAtt; - - // Stored variables from infile - G4double latticePitch; - - G4double moderatorTemp; - G4double moderatorDensity; - - G4double pressTubeTemp; - G4double pressTubeDensity; - - G4double outLinerTemp; - G4double outLinerDensity; - - G4double insulatorTemp; - G4double insulatorDensity; - - G4double linerTemp; - G4double linerDensity; - - G4double coolantTemp; - G4double coolantDensity; - - G4double inSheatheTemp; - G4double inSheatheDensity; - - G4double outSheatheTemp; - G4double outSheatheDensity; - - G4double innerFuelTemp; - G4double innerFuelDensity; - - G4double outerFuelTemp; - G4double outerFuelDensity; - - G4double flowTubeTemp; - G4double flowTubeDensity; - - G4double centralCoolantTemp; - G4double centralCoolantDensity; -}; - -#endif // SCWRJasonConstructor_H diff --git a/G4STORK/include/SLOWPOKEConstructor.hh b/G4STORK/include/SLOWPOKEConstructor.hh deleted file mode 100755 index c7ce83aa..00000000 --- a/G4STORK/include/SLOWPOKEConstructor.hh +++ /dev/null @@ -1,97 +0,0 @@ - -#ifndef SLOWPOKECONSTRUCTOR_H -#define SLOWPOKECONSTRUCTOR_H - - -// Include header files -#include "StorkVWorldConstructor.hh" -#include "StorkNeutronSD.hh" -#include "G4VSolid.hh" -#include "G4UnionSolid.hh" -#include "G4SubtractionSolid.hh" -#include "G4IntersectionSolid.hh" - -#include "G4Para.hh" -#include "G4Box.hh" -#include "G4Tubs.hh" -#include "G4Orb.hh" -#include "StorkMaterialHT.hh" -#include -#include -#include "StorkUnion.hh" - -class SLOWPOKEConstructor: public StorkVWorldConstructor -{ - public: - SLOWPOKEConstructor(); - virtual ~SLOWPOKEConstructor(); - - protected: - // Protected member functions - - virtual G4VPhysicalVolume* ConstructWorld(); - - virtual void ConstructMaterials(); - - protected: - // Protected member variables - - // Logical Volumes - G4LogicalVolume *ZirconiumLogical1; - G4LogicalVolume *ZirconiumLogical2; - G4LogicalVolume *ZirconiumLogical3; - G4LogicalVolume *AirGapLogical; - G4LogicalVolume *AirGapLogical2; - G4LogicalVolume *FuelRodLogical; - G4LogicalVolume *FuelRodLogical2; - G4LogicalVolume *ReflectorLogical; - G4LogicalVolume *D2OContainerLogical; - G4LogicalVolume *D2OLogical; - G4LogicalVolume *contRodZirLogical; - G4LogicalVolume *contRodAlumLogical; - G4LogicalVolume *contRodCadLogical; - G4LogicalVolume *contRodCentLogical; - G4LogicalVolume *insAlumLogical; - G4LogicalVolume *insBeamLogical; - G4LogicalVolume *outSmallAlumLogical; - G4LogicalVolume *outLargeAlumLogical; - G4LogicalVolume *cadLinLogical; - G4LogicalVolume *outSmallBeamLogical; - G4LogicalVolume *outLargeBeamLogical; - G4LogicalVolume *alumShellLogical; - G4LogicalVolume *cellLogical; - - // Visualization attributes - G4VisAttributes *ZirconiumAtt1; - G4VisAttributes *ZirconiumAtt2; - G4VisAttributes *ZirconiumAtt3; - G4VisAttributes *AirGapAtt; - G4VisAttributes *FuelRodAtt; - G4VisAttributes *ReflectorAtt; - G4VisAttributes *D2OContainerAtt; - G4VisAttributes *D2OAtt; - G4VisAttributes *contRodZirVisAtt; - G4VisAttributes *contRodAlumVisAtt; - G4VisAttributes *contRodCadVisAtt; - G4VisAttributes *contRodCentVisAtt; - G4VisAttributes *insAlumVisAtt; - G4VisAttributes *insBeamVisAtt; - G4VisAttributes *outSmallAlumVisAtt; - G4VisAttributes *outLargeAlumVisAtt; - G4VisAttributes *cadLinTubeVisAtt; - G4VisAttributes *outSmallBeamVisAtt; - G4VisAttributes *outLargeBeamVisAtt; - G4VisAttributes *alumShellVisAtt; - G4VisAttributes *cellVisAtt; - - // Stored variables from infile - G4double ControlRodPosition; - G4double FuelTemp; - G4double moderatorTemp; - G4double FuelDensity; - G4double FuelRadius; - - -}; - -#endif // SLOWPOKECONSTRUCTOR_H diff --git a/G4STORK/include/STORKBooleanSolid.hh b/G4STORK/include/STORKBooleanSolid.hh deleted file mode 100755 index 5bdb4bb0..00000000 --- a/G4STORK/include/STORKBooleanSolid.hh +++ /dev/null @@ -1,103 +0,0 @@ -#ifndef STORKBOOLEANSOLID_H -#define STORKBOOLEANSOLID_H - -#include "G4DisplacedSolid.hh" - -#include "G4ThreeVector.hh" -#include "G4RotationMatrix.hh" -#include "G4Transform3D.hh" - -class HepPolyhedronProcessor; - - -class STORKBooleanSolid: public G4VSolid -{ - public: // with description - - STORKBooleanSolid( const G4String& pName, - G4VSolid* pSolidA , - G4VSolid* pSolidB ); - - STORKBooleanSolid( const G4String& pName, - G4VSolid* pSolidA , - G4VSolid* pSolidB, - G4RotationMatrix* rotMatrix, - const G4ThreeVector& transVector ); - - STORKBooleanSolid( const G4String& pName, - G4VSolid* pSolidA , - G4VSolid* pSolidB , - const G4Transform3D& transform ); - - virtual ~STORKBooleanSolid(); - - virtual const G4VSolid* GetConstituentSolid(G4int no) const; - virtual G4VSolid* GetConstituentSolid(G4int no); - // If Solid is made up from a Boolean operation of two solids, - // return the corresponding solid (for no=0 and 1). - // If the solid is not a "Boolean", return 0. - - inline G4double GetCubicVolume(); - inline G4double GetSurfaceArea(); - - virtual G4GeometryType GetEntityType() const; - virtual G4Polyhedron* GetPolyhedron () const; - - std::ostream& StreamInfo(std::ostream& os) const; - - inline G4int GetCubVolStatistics() const; - inline G4double GetCubVolEpsilon() const; - inline void SetCubVolStatistics(G4int st); - inline void SetCubVolEpsilon(G4double ep); - - inline G4int GetAreaStatistics() const; - inline G4double GetAreaAccuracy() const; - inline void SetAreaStatistics(G4int st); - inline void SetAreaAccuracy(G4double ep); - - G4ThreeVector GetPointOnSurface() const; - - public: // without description - - STORKBooleanSolid(__void__&); - // Fake default constructor for usage restricted to direct object - // persistency for clients requiring preallocation of memory for - // persistifiable objects. - - STORKBooleanSolid(const STORKBooleanSolid& rhs); - STORKBooleanSolid& operator=(const STORKBooleanSolid& rhs); - // Copy constructor and assignment operator. - - protected: - - G4Polyhedron* StackPolyhedron(HepPolyhedronProcessor&, - const G4VSolid*) const; - // Stack polyhedra for processing. Return top polyhedron. - - inline G4double GetAreaRatio() const; - // Ratio of surface areas of SolidA to total A+B - - protected: - - G4VSolid* fPtrSolidA; - G4VSolid* fPtrSolidB; - - mutable G4double fAreaRatio; // Calculation deferred to GetPointOnSurface() - - private: - - G4int fStatistics; - G4double fCubVolEpsilon; - G4double fAreaAccuracy; - G4double fCubicVolume; - G4double fSurfaceArea; - - mutable G4Polyhedron* fpPolyhedron; - - G4bool createdDisplacedSolid; - // If & only if this object created it, it must delete it -}; - -#include "STORKBooleanSolid.icc" - -#endif diff --git a/G4STORK/include/STORKBooleanSolid.icc b/G4STORK/include/STORKBooleanSolid.icc deleted file mode 100755 index b3da6e04..00000000 --- a/G4STORK/include/STORKBooleanSolid.icc +++ /dev/null @@ -1,114 +0,0 @@ -// -// ******************************************************************** -// * License and Disclaimer * -// * * -// * The Geant4 software is copyright of the Copyright Holders of * -// * the Geant4 Collaboration. It is provided under the terms and * -// * conditions of the Geant4 Software License, included in the file * -// * LICENSE and available at http://cern.ch/geant4/license . These * -// * include a list of copyright holders. * -// * * -// * Neither the authors of this software system, nor their employing * -// * institutes,nor the agencies providing financial support for this * -// * work make any representation or warranty, express or implied, * -// * regarding this software system or assume any liability for its * -// * use. Please see the license in the file LICENSE and URL above * -// * for the full disclaimer and the limitation of liability. * -// * * -// * This code implementation is the result of the scientific and * -// * technical work of the GEANT4 collaboration. * -// * By using, copying, modifying or distributing the software (or * -// * any work based on the software) you agree to acknowledge its * -// * use in resulting scientific publications, and indicate your * -// * acceptance of all terms of the Geant4 Software license. * -// ******************************************************************** -// -// -// $Id$ -// -// -------------------------------------------------------------------- -// GEANT 4 inline definitions file -// -// STORKBooleanSolid.icc -// -// Implementation of inline methods of STORKBooleanSolid -// -------------------------------------------------------------------- - -inline -G4int STORKBooleanSolid::GetCubVolStatistics() const -{ - return fStatistics; -} - -inline -G4double STORKBooleanSolid::GetCubVolEpsilon() const -{ - return fCubVolEpsilon; -} - -inline -void STORKBooleanSolid::SetCubVolStatistics(G4int st) -{ - fCubicVolume=0.; - fStatistics=st; -} - -inline -void STORKBooleanSolid::SetCubVolEpsilon(G4double ep) -{ - fCubicVolume=0.; - fCubVolEpsilon=ep; -} - -inline -G4int STORKBooleanSolid::GetAreaStatistics() const -{ - return fStatistics; -} - -inline -G4double STORKBooleanSolid::GetAreaAccuracy() const -{ - return fAreaAccuracy; -} - -inline -void STORKBooleanSolid::SetAreaStatistics(G4int st) -{ - fSurfaceArea=0.; - fStatistics=st; -} - -inline -void STORKBooleanSolid::SetAreaAccuracy(G4double ep) -{ - fSurfaceArea=0.; - fAreaAccuracy=ep; -} - -inline -G4double STORKBooleanSolid::GetCubicVolume() -{ - if(fCubicVolume != 0.) {;} - else { fCubicVolume = EstimateCubicVolume(fStatistics,fCubVolEpsilon); } - return fCubicVolume; -} - -inline -G4double STORKBooleanSolid::GetSurfaceArea() -{ - if(fSurfaceArea != 0.) {;} - else { fSurfaceArea = EstimateSurfaceArea(fStatistics,fAreaAccuracy); } - return fSurfaceArea; -} - -inline -G4double STORKBooleanSolid::GetAreaRatio() const -{ - if (fAreaRatio <= 0.) - { - fAreaRatio = fPtrSolidA->GetSurfaceArea() / - (fPtrSolidA->GetSurfaceArea()+fPtrSolidB->GetSurfaceArea()); - } - return fAreaRatio; -} diff --git a/G4STORK/include/StorkBCTransform.hh b/G4STORK/include/StorkBCTransform.hh deleted file mode 100755 index 39f4a822..00000000 --- a/G4STORK/include/StorkBCTransform.hh +++ /dev/null @@ -1,19 +0,0 @@ -#ifndef STORKBCTRANSFORM_HH -#define STORKBCTRANSFORM_HH -#include "G4ThreeVector.hh" -#include - - -class StorkBCTransform -{ - public: - StorkBCTransform(); - virtual ~StorkBCTransform(); - virtual void Transform(G4ThreeVector &pos, G4ThreeVector &mom); - protected: - G4int TransPos[3][3]; - G4int TransMom[3][3]; - private: -}; - -#endif // STORKBCTRANSFORM_HH diff --git a/G4STORK/include/StorkContainers.hh b/G4STORK/include/StorkContainers.hh deleted file mode 100755 index b8629bd5..00000000 --- a/G4STORK/include/StorkContainers.hh +++ /dev/null @@ -1,72 +0,0 @@ -/* -StorkContainers.hh - -Created by: Liam Russell -Date: 22-06-2011 -Modified: 10-03-2013 - -Header file with defintions (typedefs) for various containers classes. All -typedef container classes used in multiple files are defined here. - -*/ - - - -#ifndef CONTAINERS_HH_INCLUDED -#define CONTAINERS_HH_INCLUDED - -// Include G4-STORK headers -#include "StorkTriple.hh" -#include "StorkQuad.hh" -#include "StorkNeutronData.hh" -#include "StorkTripleFloat.hh" -#include "StorkInterpVector.hh" - -// Include Geant4 headers -#include "G4String.hh" -#include "G4LogicalVolume.hh" -#include "G4Material.hh" -#include "G4ThreeVector.hh" -#include "globals.hh" - -// Include other headers -#include -#include -#include - - -// Containers for neutron data (survivors and delayed) -typedef std::vector NeutronSources; -typedef std::list NeutronList; - - -// List of site indices for the fission source distribution -// This is used in the Shannon entropy calculation -typedef StorkTriple Index3D; -typedef std::vector SiteList; -typedef std::vector DblVector; -typedef std::vector SiteVector; -typedef std::vector MSHSiteVector; - -// Three dimensional integer array -// This is used for tallying the fission sites and calculating the -// Shannon entropy -typedef std::vector > > IntArray3D; - - -// Material-Property containers -typedef std::pair MatPropPair; - -#include "StorkMatPropChange.hh" -typedef std::vector StorkMatPropChangeVector; -typedef StorkQuad MatPropInterpolator; - - -// Property and material maps -typedef std::map InitialPropertyMap; -typedef std::map WorldPropertyMap; -typedef std::map StorkMaterialMap; -typedef std::map::iterator StorkMaterialMapItr; - -#endif // CONTAINERS_HH_INCLUDED diff --git a/G4STORK/include/StorkDelayedNeutron.hh b/G4STORK/include/StorkDelayedNeutron.hh deleted file mode 100755 index bb0d354d..00000000 --- a/G4STORK/include/StorkDelayedNeutron.hh +++ /dev/null @@ -1,64 +0,0 @@ -#ifndef STORKDELAYEDNEUTRON_H -#define STORKDELAYEDNEUTRON_H - -#include "StorkContainers.hh" -#include "StorkDelayedNeutronData.hh" -#include "G4ParticleDefinition.hh" -#include "G4ParticleTable.hh" - -class StorkDelayedNeutron -{ - //Public methods - public: - //Constructor - StorkDelayedNeutron(G4String dnFilename,G4double runDuration,G4int numPrimaries); - - //Destructor - virtual ~StorkDelayedNeutron(); - - //Method to add precursors between runs. - void AddPrecursors(); - - //Get and set functions - void SetPrecursors(std::vector p) {Precursors = p;} - std::vector GetPrecursors() {return Precursors;} - - //Generate delayed neutrons through roulette of precursors. - NeutronSources GetDelayedNeutrons(G4double runEnd); - - //Set the fission sites and energies. - void SetFissionSource(MSHSiteVector fissionSites, DblVector fissionEnergies); - - //Private methods - private: - - // Produce initial precursor groups - G4bool GetInitialPrecursors(G4int numPrimaries); - - - - - //Samples an isotope using incident fission energy and site, returns an index. - // G4int fissionIndex(G4double fEnergy, G4ThreeVector fSite); - - - //Private variables - private: - //Initial fission file name. - G4String delayedSourceFile; - - //Fission source data. - MSHSiteVector fSites; - DblVector fEnergy; - std::vector Precursors; - - G4ParticleDefinition *neutron; - - //Run duration - G4double runDuration; - - - -}; - -#endif \ No newline at end of file diff --git a/G4STORK/include/StorkDelayedNeutronData.hh b/G4STORK/include/StorkDelayedNeutronData.hh deleted file mode 100755 index 61109c9c..00000000 --- a/G4STORK/include/StorkDelayedNeutronData.hh +++ /dev/null @@ -1,57 +0,0 @@ -#ifndef STORKDELAYEDNEUTRONDATA_H -#define STORKDELAYEDNEUTRONDATA_H - -/* - Decay constant U235 data taken from ENDF/B-VII.1 and fission yields for U235 and U238 for ENDF/B-V. - Energy yields in MeV taken from ENDF/B-V for U235 and U238. - 0 = U235 thermal - 1 = U238 fast - 2 = Pu239 thermal - 3 = U233 thermal - 4 = U235 fast - 5 = Pu239 fast - 6 = U233 fast - 7 = Pu240 fast - 8 = Th232 fast - */ -// Delayed neutron data. - -//Decay Constants (1/s) -const G4double DecayConstants[9][6] = { {0.013336, 0.032379, 0.12078, 0.30278, 0.84949, 2.8530}, - {0.0132, 0.0321, 0.139, 0.358, 1.41, 4.02}, - {0.0128, 0.0301, 0.124, 0.325, 1.12, 2.69}, - {0.0126, 0.0337, 0.139, 0.325, 1.13, 2.50}, - {0.0127, 0.0317, 0.115, 0.311, 1.40, 3.87}, - {0.0129, 0.0211, 0.134, 0.331, 1.26, 3.21}, - {0.0126, 0.0334, 0.131, 0.302, 1.27, 3.13}, - {0.0129, 0.0313, 0.135, 0.333, 1.36, 4.04}, - {0.0124, 0.0334, 0.121, 0.321, 1.21, 3.29},}; - -//Fission Yields (1/fission) -const G4double FissionYields[9][6] = { {0.0006346, 0.003557, 0.00314, 0.006797, 0.002138, 0.0004342}, - {0.000572, 0.006028, 0.007128, 0.01707, 0.0099, 0.0033}, - {0.00057, 0.00197, 0.00166, 0.00184, 0.00034, 0.00022}, - {0.00063, 0.00351, 0.0031, 0.00672, 0.00211, 0.00043}, - {0.00024, 0.00176, 0.00136, 0.00207, 0.00065, 0.00022}, - {0.0006, 0.00192, 0.00159, 0.00222, 0.00051, 0.0016}, - {0.00054, 0.00564, 0.00667, 0.01599, 0.00927, 0.00309}, - {0.0028, 0.00238, 0.00162, 0.00315, 0.00119, 0.00024}, - {0.00169, 0.00744, 0.00769, 0.02212, 0.00853, 0.00213},}; - -//Summed Fission Yields -const G4double TotalYields[9] = {0.0167008, 0.043998, 0.0066, 0.0165, 0.0063, 0.00844, 0.0412, 0.01138, 0.0496}; - -//Summed Decay Constants -const G4double TotalDecayConstants[9] = {4.171765, 5.9723, 4.3019, 4.1403, 5.7404, 4.969, 4.879, 5.9122, 4.9878}; - -//Precursor constants FY/DecayConstant (only u235, add in more later) -const G4double PrecursorConstants[6] ={0.04758548290341932, 0.10985515303128571, 0.025997681735386653, 0.022448642578770064, - 0.0025168042001671594, 0.00015219067648089728}; - -const G4double TotPrecursorConstants = 0.20855595512550984; - -//Energy Yields (MeV) -const G4double EnergyYields[2][6] = {{0.2680, 0.4394, 0.4094, 0.4017, 0.4017, 0.4017}, - {0.2837, 0.4381, 0.4341, 0.4172, 0.3593, 0.3593}}; - -#endif \ No newline at end of file diff --git a/G4STORK/include/StorkElement.hh b/G4STORK/include/StorkElement.hh deleted file mode 100755 index 784c854e..00000000 --- a/G4STORK/include/StorkElement.hh +++ /dev/null @@ -1,169 +0,0 @@ -// -// ******************************************************************** -// * License and Disclaimer * -// * * -// * The Geant4 software is copyright of the Copyright Holders of * -// * the Geant4 Collaboration. It is provided under the terms and * -// * conditions of the Geant4 Software License, included in the file * -// * LICENSE and available at http://cern.ch/geant4/license . These * -// * include a list of copyright holders. * -// * * -// * Neither the authors of this software system, nor their employing * -// * institutes,nor the agencies providing financial support for this * -// * work make any representation or warranty, express or implied, * -// * regarding this software system or assume any liability for its * -// * use. Please see the license in the file LICENSE and URL above * -// * for the full disclaimer and the limitation of liability. * -// * * -// * This code implementation is the result of the scientific and * -// * technical work of the GEANT4 collaboration. * -// * By using, copying, modifying or distributing the software (or * -// * any work based on the software) you agree to acknowledge its * -// * use in resulting scientific publications, and indicate your * -// * acceptance of all terms of the Geant4 Software license. * -// ******************************************************************** -// -// -// $Id: StorkElement.hh 69704 2013-05-13 09:06:12Z gcosmo $ -// - -//--------------------------------------------------------------------------- -// -// ClassName: StorkElement -// -// Description: Contains element properties -// -// Class description: -// -// An element is a chemical element either directly defined in terms of -// its characteristics: its name, symbol, -// Z (effective atomic number) -// N (effective number of nucleons) -// A (effective mass of a mole) -// or in terms of a collection of constituent isotopes with specified -// relative abundance (i.e. fraction of nb of atoms per volume). -// -// Quantities, with physical meaning or not, which are constant in a given -// element are computed and stored here as Derived data members. -// -// The class contains as a private static member the table of defined -// elements (an ordered vector of elements). -// -// Elements can be assembled singly or in mixtures into materials used -// in volume definitions via the G4Material class. -// -// It is strongly recommended do not delete StorkElement instance in the -// user code. All StorkElements will be automatically deleted at the end -// of Geant4 session - -//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... - -// 09-07-96, new data members added by L.Urban -// 17-01-97, aesthetic rearrangement, M.Maire -// 20-01-97, Tsai formula for the rad length, M.Maire -// 21-01-97, remove mixture flag, M.Maire -// 24-01-97, new data member: fTaul -// new method: ComputeIonisationPara, M.Maire -// 20-03-97, corrected initialization of pointers, M.Maire -// 27-06-97, new function GetIsotope(int), M.Maire -// 24-02-98, fWeightVector becomes fRelativeAbundanceVector -// 27-04-98, atomic shell stuff, V. Grichine -// 09-07-98, Ionisation parameters removed from the class, M.Maire -// 04-08-98, new method GetElement(elementName), M.Maire -// 16-11-98, Subshell -> Shell, mma -// 30-03-01, suppression of the warning message in GetElement -// 17-07-01, migration to STL, M. Verderi -// 13-09-01, stl migration. Suppression of the data member fIndexInTable -// 14-09-01, fCountUse: nb of materials which use this element -// 26-02-02, fIndexInTable renewed -// 01-04-05, new data member fIndexZ to count the number of elements with same Z -// 17-10-06: Add Get/Set fNaturalAbundance (V.Ivanchenko) -// 17.09.09, add fNbOfShellElectrons and methods (V. Grichine) -//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... - -#ifndef StorkElement_HH -#define StorkElement_HH 1 - -#include "globals.hh" -#include -#include "G4ios.hh" -#include "G4Isotope.hh" -#include "G4IonisParamElm.hh" -#include "G4IsotopeVector.hh" -#include "G4Element.hh" - -//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... - -class StorkElement : public G4Element -{ -public: // with description - - // - // Constructor to Build an element directly; no reference to isotopes - // - StorkElement(const G4String& name, //its name - const G4String& symbol, //its symbol - G4double Zeff, //atomic number - G4double Aeff); //mass of mole - - // - // Constructor to Build an element from isotopes via AddIsotope - // - StorkElement(const G4String& name, //its name - const G4String& symbol, //its symbol - G4int nbIsotopes); //nb of isotopes - - ~StorkElement(); - - inline G4double GetTemperature() const {return temperature;} - inline void SetTemperature(G4double temp) {temperature=temp;} - - inline G4double GetCSDataTemp() const {return csDataTemp;} - inline void SetCSDataTemp(G4double CSDataTemp) {csDataTemp=CSDataTemp;} -/* - inline const G4String& GetName() const {return (dynamic_cast(this))->GetName();} - inline void SetName(const G4String& name) {dynamic_cast(this)->SetName(name);} - - - G4ElementTable* GetElementTable() - { - dynamic_cast(this)->GetElementTable(); - } - -*/ - - bool Exists(G4double temp, G4int &index); - - // printing methods - // - /* - friend std::ostream& operator<<(std::ostream&, StorkElement*); - friend std::ostream& operator<<(std::ostream&, StorkElement&); - friend std::ostream& operator<<(std::ostream&, G4ElementTable); - */ - -public: // without description - - G4int operator==(const StorkElement&) const; - G4int operator!=(const StorkElement&) const; - - StorkElement(StorkElement&); - StorkElement(G4Element&); - StorkElement(__void__&); - // Fake default constructor for usage restricted to direct object - // persistency for clients requiring preallocation of memory for - // persistifiable objects. - -private: - - const StorkElement & operator=(StorkElement&); - -private: - - G4double temperature; - G4double csDataTemp; -}; - -//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... - -#endif diff --git a/G4STORK/include/StorkEventAction.hh b/G4STORK/include/StorkEventAction.hh deleted file mode 100755 index e08d8674..00000000 --- a/G4STORK/include/StorkEventAction.hh +++ /dev/null @@ -1,64 +0,0 @@ -/* -StorkEventAction.hh - -Created by: Liam Russell -Date: 22-06-2011 -Modified: 11-03-2013 - -Header for StorkEventAction class. - -This class takes the tally hits created by the sensitive detectors, and converts -them into an StorkEventData container that can be marshalled. - -*/ - -#ifndef NSEVENTACTION_H -#define NSEVENTACTION_H - -// Include G4-STORK header files -#include "StorkTallyHit.hh" -#include "StorkEventData.hh" -#include "StorkTrackInfo.hh" - -// Include Geant4 header files -#include "G4Timer.hh" -#include "G4UserEventAction.hh" -#include "G4RunManager.hh" -#include "G4Event.hh" -#include "G4SDManager.hh" -#include "G4HCofThisEvent.hh" -#include "G4PrimaryParticle.hh" -#include "G4UnitsTable.hh" -#include "G4ios.hh" -#include "globals.hh" - - -class StorkEventAction: public G4UserEventAction -{ - public: - // Public member functions - - // Constructor and destructor - StorkEventAction(G4String name = "Reactor"); - ~StorkEventAction(); - - void BeginOfEventAction(const G4Event *anEvent); - void EndOfEventAction(const G4Event *anEvent); - - StorkEventData* GetEventData() const { return eventData; }; - - - private: - // Private member data - - G4int tfHCID, tmHCID; - G4String SDname; - StorkEventData *eventData; - - -#ifdef G4TIMEEA - G4Timer eventTimer; -#endif -}; - -#endif // NSEVENTACTION_H diff --git a/G4STORK/include/StorkEventData.hh b/G4STORK/include/StorkEventData.hh deleted file mode 100755 index 360ca43b..00000000 --- a/G4STORK/include/StorkEventData.hh +++ /dev/null @@ -1,141 +0,0 @@ -/* -StorkEventData.hh - -Created by: Liam Russell -Date: 07-08-2011 -Modified: 17-02-2012 - -Definition of StorkEventData class. - -This is a container class designed to be passed from slaves to the master -when they have finished simulating an event. All the data is public and may -be accessed directly. It also includes comments so that Marshalgen (automated -marshalling software) may create a marshaled class definition. - -*/ - - -#ifndef STORKEVENTDATA_HH_INCLUDED -#define STORKEVENTDATA_HH_INCLUDED - -// Include header files and libraries -#include "StorkContainers.hh" - - -//MSH_include_begin -#include "MarshaledStorkNeutronData.h" -#include "MarshaledStorkTripleFloat.h" -//MSH_include_end -//MSH_BEGIN -class StorkEventData -{ - public: - // Public member functions - - // Constructor and destructor - StorkEventData() - { - survivors = new NeutronSources(); - delayed = new NeutronSources(); - fSites = new MSHSiteVector(); - fnEnergy = new DblVector(); - totalLifetime = 0.0; - numNLost = numNProd = numDProd = 0; - eventNum = -1; - } - virtual ~StorkEventData() - { - if(survivors) delete survivors; - if(delayed) delete delayed; - if(fSites) delete fSites; - if(fnEnergy) delete fnEnergy; - - survivors = NULL; - delayed = NULL; - fSites = NULL; - fnEnergy = NULL; - } - - // Combine two StorkEventData objects from the same event - void AddEventData(const StorkEventData &right) - { - // Check if this data is not from the same event - if(eventNum != right.eventNum) - { - G4cerr << "*** WARNING: Tried to combine two different events." - << G4endl; - return; - } - - // Add input event data to - totalLifetime += right.totalLifetime; - numNLost += right.numNLost; - numNProd += right.numNProd; - survivors->insert(survivors->end(),right.survivors->begin(), - right.survivors->end()); - delayed->insert(delayed->end(),right.delayed->begin(), - right.delayed->end()); - fSites->insert(fSites->end(),right.fSites->begin(), - right.fSites->end()); - - } - - // Combine StorkEventData objects using '+' operator - StorkEventData operator + (const StorkEventData &right) - { - StorkEventData temp; - temp.AddEventData(*this); - temp.AddEventData(right); - - return temp; - } - - // Combine StorkEventData using the '+=' operator - StorkEventData& operator += (const StorkEventData &right) - { - this->AddEventData(right); - - return *this; - } - - - public: - // Public member data with marshalling instructions - - NeutronSources *survivors; /*MSH: ptr_as_array - [elementType: StorkNeutronData] - [elementCount: { $ELE_COUNT = $THIS->survivors->size(); }] - [elementGet: { $ELEMENT = $THIS->survivors->at($ELE_INDEX); }] - [elementSet: { $THIS->survivors->push_back(*$ELEMENT); }] - */ - - NeutronSources *delayed; /*MSH: ptr_as_array - [elementType: StorkNeutronData] - [elementCount: { $ELE_COUNT = $THIS->delayed->size(); }] - [elementGet: { $ELEMENT = $THIS->delayed->at($ELE_INDEX); }] - [elementSet: { $THIS->delayed->push_back(*$ELEMENT); }] - */ - - MSHSiteVector *fSites; /*MSH: ptr_as_array - [elementType: StorkTripleFloat] - [elementCount: { $ELE_COUNT = $THIS->fSites->size(); }] - [elementGet: { $ELEMENT = $THIS->fSites->at($ELE_INDEX); }] - [elementSet: { $THIS->fSites->push_back(*$ELEMENT); }] - */ - - DblVector *fnEnergy; /*MSH: ptr_as_array - [elementType: double] - [elementCount: { $ELE_COUNT = $THIS->fnEnergy->size(); }] - [elementGet: { $ELEMENT = $THIS->fnEnergy->at($ELE_INDEX); }] - [elementSet: { $THIS->fnEnergy->push_back($ELEMENT); }] - */ - - G4double totalLifetime; //MSH: primitive - G4int numNProd; //MSH: primitive - G4int numNLost; //MSH: primitive - G4int numDProd; //MSH: primitive - G4int eventNum; //MSH: primitive -}; -//MSH_END - -#endif // STORKEVENTDATA_HH_INCLUDED diff --git a/G4STORK/include/StorkHPNeutronBuilder.hh b/G4STORK/include/StorkHPNeutronBuilder.hh deleted file mode 100755 index bc2e8938..00000000 --- a/G4STORK/include/StorkHPNeutronBuilder.hh +++ /dev/null @@ -1,104 +0,0 @@ -/* -StorkHPNeutronBuilder.hh - -Created by: Liam Russell -Date: 23-02-2012 -Modified: 11-03-2013 - -Header file for StorkHPNeutronBuilderclass. - -This class creates all of the physics processes, models, particles and data. -It takes a temperature and a bool flag. The temperature denotes the temperature -the cross sections were evaluated at, which determines whether doppler -broadening is used. - -*/ - -#ifndef STORKHPNEUTRONBUILDER_H -#define STORKHPNEUTRONBUILDER_H - -// Include header files -#include "G4VNeutronBuilder.hh" -#include "globals.hh" -#include "G4ProcessManager.hh" -#include "G4ParticleTypes.hh" -#include "G4ParticleTable.hh" -#include "G4ParticleDefinition.hh" -#include "G4ParticleWithCuts.hh" - -// Processes -#include "G4HadronElasticProcess.hh" -#include "G4NeutronInelasticProcess.hh" -#include "G4HadronCaptureProcess.hh" -#include "G4HadronFissionProcess.hh" - -// Models -#include "StorkNeutronHPElastic.hh" -#include "StorkNeutronHPInelastic.hh" -#include "StorkNeutronHPCapture.hh" -#include "StorkNeutronHPFission.hh" - -// Data Sets -#include "StorkNeutronHPCSData.hh" - -// -#include "G4NeutronHPCaptureData.hh" -#include "G4NeutronHPFissionData.hh" -#include "G4NeutronHPElasticData.hh" -#include "G4NeutronHPInelasticData.hh" -// - -#ifdef G4USE_TOPC -#include "topc.h" -#include "G4HadronicProcessStore.hh" -#endif - - -class StorkHPNeutronBuilder : public G4VNeutronBuilder -{ - public: - StorkHPNeutronBuilder(G4String dir); - ~StorkHPNeutronBuilder(); - - void Build(G4HadronElasticProcess *aP); - void Build(G4HadronFissionProcess *aP); - void Build(G4HadronCaptureProcess *aP); - void Build(G4NeutronInelasticProcess *aP); - - void SetMinEnergy(G4double aM) { theIMin = theMin = aM; } - void SetMaxEnergy(G4double aM) { theIMax = theMax = aM; } - void SetMinInelasticEnergy(G4double aM) { theIMin = aM; } - void SetMaxInelasticEnergy(G4double aM) { theIMax = aM; } - - void SetFSTemperature(G4double FSTemp) { fsTemp = FSTemp; } - - private: - - // Applicability limits - G4double theMin; - G4double theMax; - G4double theIMin; - G4double theIMax; - - // User input and limits - G4String dirName; - G4double fsTemp; - - // Models - StorkNeutronHPElastic *nElasticModel; - StorkNeutronHPInelastic *nInelasticModel; - StorkNeutronHPFission *nFissionModel; - StorkNeutronHPCapture *nCaptureModel; - - // Data - StorkNeutronHPCSData *HPElasticData; - G4NeutronHPElasticData *theHPElasticData; - StorkNeutronHPCSData *HPInelasticData; - G4NeutronHPInelasticData *theHPInelasticData; - StorkNeutronHPCSData *HPFissionData; - G4NeutronHPFissionData *theHPFissionData; - StorkNeutronHPCSData *HPCaptureData; - G4NeutronHPCaptureData *theHPCaptureData; -}; - -#endif // STORKHPNEUTRONBUILDER_H diff --git a/G4STORK/include/StorkHadProjectile.hh b/G4STORK/include/StorkHadProjectile.hh deleted file mode 100755 index 03f2cc36..00000000 --- a/G4STORK/include/StorkHadProjectile.hh +++ /dev/null @@ -1,120 +0,0 @@ -// -// StorkHadProjectile.h -// G4-STORK_AT -// -// Created by Andrew Tan on 2014-07-30. -// Copyright (c) 2014 andrewtan. All rights reserved. -// - -#ifndef __G4_STORK_AT__StorkHadProjectile__ -#define __G4_STORK_AT__StorkHadProjectile__ - -#include -#include "globals.hh" -#include "G4Material.hh" -#include "G4ParticleDefinition.hh" -#include "G4LorentzVector.hh" -#include "G4LorentzVector.hh" -#include "G4LorentzRotation.hh" -#include "G4HadProjectile.hh" -#include "G4Track.hh" -#include "G4DynamicParticle.hh" - -class G4Track; -class G4DynamicParticle; - -class StorkHadProjectile -{ -public: - StorkHadProjectile(); - StorkHadProjectile(const G4Track &aT); - StorkHadProjectile(const G4DynamicParticle &aT, const G4Material *theMat); - ~StorkHadProjectile(); - - void Initialise(const G4Track &aT); - - inline const G4Material * GetMaterial() const; - inline const G4ParticleDefinition * GetDefinition() const; - inline const G4LorentzVector & Get4Momentum() const; - inline G4LorentzRotation & GetTrafoToLab(); - inline G4double GetKineticEnergy() const; - inline G4double GetTotalEnergy() const; - inline G4double GetTotalMomentum() const; - inline G4double GetGlobalTime() const; - inline G4double GetBoundEnergy() const; - inline void SetGlobalTime(G4double t); - inline void SetBoundEnergy(G4double e); - -private: - - // hide assignment operator as private - StorkHadProjectile& operator=(const StorkHadProjectile &right); - StorkHadProjectile(const StorkHadProjectile& ); - - const G4Material * theMat; - G4LorentzVector theOrgMom; - G4LorentzVector theMom; - const G4ParticleDefinition * theDef; - G4LorentzRotation toLabFrame; - G4double theTime; - G4double theBoundEnergy; -}; - -const G4Material * StorkHadProjectile::GetMaterial() const -{ - return theMat; -} - -const G4ParticleDefinition * StorkHadProjectile::GetDefinition() const -{ - return theDef; -} - -inline const G4LorentzVector& StorkHadProjectile::Get4Momentum() const -{ - return theMom; -} - -inline G4LorentzRotation& StorkHadProjectile::GetTrafoToLab() -{ - return toLabFrame; -} - -G4double StorkHadProjectile::GetTotalEnergy() const -{ - return Get4Momentum().e(); -} - -G4double StorkHadProjectile::GetTotalMomentum() const -{ - return Get4Momentum().vect().mag(); -} - -G4double StorkHadProjectile::GetKineticEnergy() const -{ - G4double ekin = GetTotalEnergy() - GetDefinition()->GetPDGMass(); - if(ekin < 0.0) { ekin = 0.0; } - return ekin; -} - -inline G4double StorkHadProjectile::GetGlobalTime() const -{ - return theTime; -} - -inline G4double StorkHadProjectile::GetBoundEnergy() const -{ - return theBoundEnergy; -} - -inline void StorkHadProjectile::SetGlobalTime(G4double t) -{ - theTime = t; -} - -inline void StorkHadProjectile::SetBoundEnergy(G4double e) -{ - theBoundEnergy = e; -} - -#endif diff --git a/G4STORK/include/StorkHadronCaptureProcess.hh b/G4STORK/include/StorkHadronCaptureProcess.hh deleted file mode 100755 index fc10d707..00000000 --- a/G4STORK/include/StorkHadronCaptureProcess.hh +++ /dev/null @@ -1,72 +0,0 @@ -/* -StorkHadronCaptureProcess.hh - -Created by: Liam Russell -Date: 29-02-2012 -Modified: 11-03-2013 - -Definition of StorkHadronCaptureProcess class. - -This class is derived from G4HadronCaptureProcess to modify the StartTracking() -function and to add a get function for theNumberOfInteractionLenghtLeft -member variable. - -*/ - - -#ifndef STORKHADRONCAPTUREPROCESS_H -#define STORKHADRONCAPTUREPROCESS_H - -// Include header files -#include "G4HadronCaptureProcess.hh" -#include "StorkHadronicProcess.hh" - -class StorkProcessManager; - -class StorkHadronCaptureProcess : public G4HadronCaptureProcess -{ - public: - // Public member functions - - // Constructor and destructor - StorkHadronCaptureProcess(const G4String& processName = - "StorkHadronCapture") - :G4HadronCaptureProcess(processName) - { -// SetVerboseLevel(2); - } - virtual ~StorkHadronCaptureProcess() {;} - - // Set the number of interaction lengths left from previous run - virtual void StartTracking(G4Track *aTrack) - { - G4VProcess::StartTracking(aTrack); - StartTrackingHadronicProcess(aTrack, - theNumberOfInteractionLengthLeft, - procIndex); - } - - // Get the current number of interaction lengths left for the process - virtual G4double GetNumberOfInteractionLengthLeft(G4double - previousStepSize) - { - SubtractNumberOfInteractionLengthLeft(previousStepSize); - return theNumberOfInteractionLengthLeft; - } - - void SetProcessIndex(G4int ind) { procIndex = ind; } - - // Declare friend function - friend void StartTrackingHadronicProcess(G4Track *aTrack, - G4double &n_lambda, - G4int procIndex); - - - private: - // Private member variables - - G4int procIndex; // Index of physics process (StorkProcessManager) -}; - - -#endif // STORKHADRONCAPTUREPROCESS_H diff --git a/G4STORK/include/StorkHadronElasticProcess.hh b/G4STORK/include/StorkHadronElasticProcess.hh deleted file mode 100755 index c1e0ea07..00000000 --- a/G4STORK/include/StorkHadronElasticProcess.hh +++ /dev/null @@ -1,70 +0,0 @@ -/* -StorkHadronElasticProcess.hh - -Created by: Liam Russell -Date: 29-02-2012 -Modified: - -Header file for StorkHadronElasticProcess class. - -This class is derived from G4HadronElasticProcess to modify the StartTracking() -function and to add a get function for theNumberOfInteractionLenghtLeft -member variable. - -*/ - - -#ifndef STORKHADRONELASTICPROCESS_H -#define STORKHADRONELASTICPROCESS_H - -// Include header files -#include "G4HadronElasticProcess.hh" -#include "StorkHadronicProcess.hh" - -class StorkProcessManager; - -class StorkHadronElasticProcess : public G4HadronElasticProcess -{ - public: - // Public member functions - - // Constructor and destructor - StorkHadronElasticProcess(const G4String& processName = "StorkHadronElastic") - :G4HadronElasticProcess(processName) - { -// SetVerboseLevel(2); - } - virtual ~StorkHadronElasticProcess() {;} - - // Set the number of interaction lengths left from previous run - virtual void StartTracking(G4Track *aTrack) - { - G4VProcess::StartTracking(aTrack); - StartTrackingHadronicProcess(aTrack, - theNumberOfInteractionLengthLeft, - procIndex); - } - - // Get the current number of interaction lengths left for the process - virtual G4double GetNumberOfInteractionLengthLeft(G4double - previousStepSize) - { - SubtractNumberOfInteractionLengthLeft(previousStepSize); - return theNumberOfInteractionLengthLeft; - } - - void SetProcessIndex(G4int ind) { procIndex = ind; } - - // Declare friend function - friend void StartTrackingHadronicProcess(G4Track *aTrack, - G4double &n_lambda, - G4int procIndex); - - private: - // Private member variables - - G4int procIndex; // Index of physics process (StorkProcessManager) -}; - - -#endif // STORKHADRONELASTICPROCESS_H diff --git a/G4STORK/include/StorkHadronFissionProcess.hh b/G4STORK/include/StorkHadronFissionProcess.hh deleted file mode 100755 index 9ebb305f..00000000 --- a/G4STORK/include/StorkHadronFissionProcess.hh +++ /dev/null @@ -1,315 +0,0 @@ -/* -StorkHadronFissionProcess.hh - -Created by: Liam Russell -Date: 29-02-2012 -Modified: 11-03-2012 - -Header file for StorkHadronFissionProcess class. - -This class is derived from G4HadronFissionProcess to modify the StartTracking() -function and to add a get function for theNumberOfInteractionLenghtLeft -member variable. - -*/ - - -#ifndef STORKHADRONFISSIONPROCESS_H -#define STORKHADRONFISSIONPROCESS_H - -#include "G4HadronFissionProcess.hh" -#include "StorkHadronicProcess.hh" -#include "StorkHadProjectile.hh" -#include "StorkNeutronData.hh" -#include "StorkHadProjectile.hh" -#include "G4TransportationManager.hh" -#include "StorkNeutronHPFission.hh" - -#include "G4DynamicParticle.hh" -#include "G4Material.hh" -#include "G4Nucleus.hh" - - -class StorkHadronFissionProcess : public G4HadronFissionProcess -{ - public: - // Public member functions - - // Constructor and destructor - StorkHadronFissionProcess(const G4String& processName = "StorkHadronFission") - :G4HadronFissionProcess(processName) - { - theFissModel = NULL; - theNavi = NULL; - theDataStore = NULL; - -// SetVerboseLevel(2); - } - virtual ~StorkHadronFissionProcess() { - if(theFissModel) delete theFissModel; - }; - - // Set the number of interaction lengths left from previous run - virtual void StartTracking(G4Track *aTrack) - { - G4VProcess::StartTracking(aTrack); - StartTrackingHadronicProcess(aTrack, - theNumberOfInteractionLengthLeft, - procIndex); - } - - // Get the current number of interaction lengths left for the process - virtual G4double GetNumberOfInteractionLengthLeft(G4double - previousStepSize) - { - SubtractNumberOfInteractionLengthLeft(previousStepSize); - return theNumberOfInteractionLengthLeft; - } - - void SetProcessIndex(G4int ind) { procIndex = ind; } - - // Declare friend function - friend void StartTrackingHadronicProcess(G4Track *aTrack, - G4double &n_lambda, - G4int procIndex); - - // Produce the characteristics of a delayed neutron - inline StorkNeutronData GetADelayedNeutron(G4DynamicParticle *aNeutron, - G4Material *theMat); - inline StorkNeutronData GetADelayedNeutron(G4DynamicParticle *aNeutron, - G4Material *theMat, G4Nucleus theTarget); - - inline G4Nucleus GetFissionNucleus(G4StepPoint* aStep); - inline G4Nucleus GetFissionNucleus(G4double fnEnergy, G4ThreeVector fnSite); - - - private: - - G4int procIndex; - StorkNeutronHPFission *theFissModel; - G4Navigator* theNavi; - G4CrossSectionDataStore *theDataStore; - -}; - -StorkNeutronData StorkHadronFissionProcess::GetADelayedNeutron( - G4DynamicParticle *aNeutron, - G4Material *theMat, G4Nucleus theTarget) -{ - // Local Variables - G4HadFinalState* theResult = NULL; - StorkHadProjectile projectile(*aNeutron,theMat); - G4HadSecondary *aSec = NULL; - G4DynamicParticle *aDelayedN = NULL; - G4bool dnFlag = false; - - - // Keep getting a result until a delayed neutron is produced - do - { - // Simulate a fission - try - { - G4HadProjectile* Temp = reinterpret_cast(&projectile); - //theResult = theFissionModel->ApplyYourself(*Temp, theTarget); - theResult = theFissModel->ApplyYourself(*Temp,theTarget); - - } - catch(G4HadronicException aR) - { - G4Exception("G4HadronicProcess", "007", FatalException, - "The fission model failed to produce a result."); - - } - - // Check to see if the result contains a delayed neutron - for(G4int i=0; iGetNumberOfSecondaries(); i++) - { - aSec = theResult->GetSecondary(i); - - // Check if a delayed neutron was created - if(aSec->GetParticle()->GetParticleDefinition() == - G4Neutron::Neutron() && - aSec->GetTime() > aNeutron->GetProperTime()) - { - dnFlag = true; - aDelayedN = aSec->GetParticle(); - - break; - } - } - } - while(!dnFlag); - - - // Create the neutron data container - StorkNeutronData dnData(aSec->GetTime(), - aSec->GetTime()-aNeutron->GetProperTime(), - G4ThreeVector(0.,0.,0.), aDelayedN->GetMomentum()); - - return dnData; -} - - -// GetADelayedNeutron() -// Produce the characteristics (momentum, time of birth, etc) of a delayed -// neutron by simulating a fission with a given incoming neutron. -// NOTE: the fission is virtual and DOES NOT OCCUR -StorkNeutronData StorkHadronFissionProcess::GetADelayedNeutron( - G4DynamicParticle *aNeutron, - G4Material *theMat) -{ - // Local Variables - G4Nucleus theTarget; - G4HadFinalState* theResult = NULL; - StorkHadProjectile theProjectile(*aNeutron, theMat); - G4HadronicInteraction *theFissionModel = NULL; - G4HadSecondary *aSec = NULL; - G4DynamicParticle *aDelayedN = NULL; - G4bool dnFlag = false; - theDataStore = GetCrossSectionDataStore(); - - - // Find the target element - G4Element *anElement = NULL; - try - { - anElement = theDataStore->SampleZandA(aNeutron, theMat, theTarget); - } - catch(G4HadronicException & aR) - { -// DumpState(aTrack,"SampleZandA"); - G4Exception("G4HadronicProcess", "007", FatalException, - "GetADelayedNeutron failed on element selection."); - } - - - // Find the appropriate interaction - try - { - theFissionModel = ChooseHadronicInteraction( - aNeutron->GetKineticEnergy(), - theMat, anElement); - } - catch(G4HadronicException & aE) - { - G4cout << "Target element "<< anElement->GetName() << G4endl; -// DumpState(aTrack,"ChooseHadronicInteraction"); - G4Exception("G4HadronicProcess", "007", FatalException, - "ChooseHadronicInteraction failed."); - } - - // Keep getting a result until a delayed neutron is produced - do - { - // Simulate a fission - try - { - G4HadProjectile* Temp = reinterpret_cast(&theProjectile); - theResult = theFissionModel->ApplyYourself((*Temp), theTarget); - } - catch(G4HadronicException aR) - { - G4Exception("G4HadronicProcess", "007", FatalException, - "The fission model failed to produce a result."); - - } - - - // Check to see if the result contains a delayed neutron - for(G4int i=0; iGetNumberOfSecondaries(); i++) - { - aSec = theResult->GetSecondary(i); - - // Check if a delayed neutron was created - if(aSec->GetParticle()->GetParticleDefinition() == - G4Neutron::Neutron() && - aSec->GetTime() > aNeutron->GetProperTime()) - { - dnFlag = true; - aDelayedN = aSec->GetParticle(); - - break; - } - } - } - while(!dnFlag); - - - // Create the neutron data container - StorkNeutronData dnData(aSec->GetTime(), - aSec->GetTime()-aNeutron->GetProperTime(), - G4ThreeVector(0.,0.,0.), aDelayedN->GetMomentum()); - - return dnData; -} - -G4Nucleus StorkHadronFissionProcess::GetFissionNucleus(G4StepPoint* aStep){ - - G4DynamicParticle *aNeutron; - if(!theNavi) theNavi = G4TransportationManager::GetTransportationManager()->GetNavigatorForTracking(); - - aNeutron = new G4DynamicParticle(G4Neutron::NeutronDefinition(), - aStep->GetMomentumDirection(), aStep->GetKineticEnergy()); - - G4ThreeVector Location = aStep->GetPosition(); - - - G4Material* Material = theNavi->LocateGlobalPointAndSetup(Location)->GetLogicalVolume()->GetMaterial(); - G4Nucleus aNuc; - - if(!theDataStore) theDataStore = GetCrossSectionDataStore(); - - try - { - theDataStore->SampleZandA(aNeutron, Material, aNuc); - } - catch(G4HadronicException & aR) - { - G4Exception("G4HadronicProcess", "007", FatalException, - "GetNeutronFissionIso failed on element selection."); - } - - if(aNeutron) delete aNeutron; - return aNuc; - - -} - -G4Nucleus StorkHadronFissionProcess::GetFissionNucleus(G4double fnEnergy, G4ThreeVector fnSite){ - - G4DynamicParticle *aNeutron; - G4ThreeVector MomentumDir; - if(!theNavi) theNavi = G4TransportationManager::GetTransportationManager()->GetNavigatorForTracking(); - - MomentumDir.setRThetaPhi(1.0, G4UniformRand()*CLHEP::pi, - G4UniformRand()*2.0*CLHEP::pi); - - aNeutron = new G4DynamicParticle(G4Neutron::NeutronDefinition(), - MomentumDir, fnEnergy); - - theNavi->ResetStackAndState(); - G4Material* Material = theNavi->LocateGlobalPointAndSetup(fnSite)->GetLogicalVolume()->GetMaterial(); - - G4Nucleus aNuc; - - if(!theDataStore) theDataStore = GetCrossSectionDataStore(); - - try - { - theDataStore->SampleZandA(aNeutron, Material, aNuc); - } - catch(G4HadronicException & aR) - { - G4Exception("G4HadronicProcess", "007", FatalException, - "GetFissionNucleus failed on element selection."); - } - - if(aNeutron) delete aNeutron; - return aNuc; - - -} - -#endif // NSHADRONFISSIONPROCESS_H - diff --git a/G4STORK/include/StorkHadronicInteraction.hh b/G4STORK/include/StorkHadronicInteraction.hh deleted file mode 100755 index 88a7d293..00000000 --- a/G4STORK/include/StorkHadronicInteraction.hh +++ /dev/null @@ -1,170 +0,0 @@ -// -// StorkHadronicInteraction.h -// G4-STORK_AT -// -// Created by Andrew Tan on 2014-07-30. -// Copyright (c) 2014 andrewtan. All rights reserved. -// - -#ifndef __G4_STORK_AT__StorkHadronicInteraction__ -#define __G4_STORK_AT__StorkHadronicInteraction__ - -#include -#include "G4HadronicInteraction.hh" -#include "G4HadFinalState.hh" -#include "G4Material.hh" -#include "G4Nucleus.hh" -#include "G4Track.hh" -#include "G4HadProjectile.hh" -#include "G4ReactionDynamics.hh" - -class StorkHadronicInteraction: public G4HadronicInteraction -{ -public: // With description - - StorkHadronicInteraction(const G4String& modelName = "HadronicModel"); - - virtual ~StorkHadronicInteraction(); - - virtual G4HadFinalState *ApplyYourself(const G4HadProjectile &aTrack, - G4Nucleus & targetNucleus ) = 0; - // The interface to implement for final state production code. - - virtual G4double SampleInvariantT(const G4ParticleDefinition* p, - G4double plab, - G4int Z, G4int A); - // The interface to implement sampling of scattering or change exchange - - virtual G4bool IsApplicable(const G4HadProjectile &/*aTrack*/, - G4Nucleus & /*targetNucleus*/) - { return true;} - - inline G4double GetMinEnergy() const - { return theMinEnergy; } - - G4double GetMinEnergy( const G4Material *aMaterial, - const G4Element *anElement ) const; - - inline void SetMinEnergy( G4double anEnergy ) - { theMinEnergy = anEnergy; } - - void SetMinEnergy( G4double anEnergy, const G4Element *anElement ); - - void SetMinEnergy( G4double anEnergy, const G4Material *aMaterial ); - - inline G4double GetMaxEnergy() const - { return theMaxEnergy; } - - G4double GetMaxEnergy( const G4Material *aMaterial, - const G4Element *anElement ) const; - - inline void SetMaxEnergy( const G4double anEnergy ) - { theMaxEnergy = anEnergy; } - - void SetMaxEnergy( G4double anEnergy, const G4Element *anElement ); - - void SetMaxEnergy( G4double anEnergy, const G4Material *aMaterial ); - - inline const StorkHadronicInteraction* GetMyPointer() const - { return this; } - - virtual G4int GetVerboseLevel() const - { return verboseLevel; } - - virtual void SetVerboseLevel( G4int value ) - { verboseLevel = value; } - - inline const G4String& GetModelName() const - { return theModelName; } - - void DeActivateFor(const G4Material* aMaterial); - - inline void ActivateFor( const G4Material *aMaterial ) - { - Block(); - SetMaxEnergy(GetMaxEnergy(), aMaterial); - SetMinEnergy(GetMinEnergy(), aMaterial); - } - - void DeActivateFor( const G4Element *anElement ); - inline void ActivateFor( const G4Element *anElement ) - { - Block(); - SetMaxEnergy(GetMaxEnergy(), anElement); - SetMinEnergy(GetMinEnergy(), anElement); - } - - G4bool IsBlocked( const G4Material *aMaterial ) const; - G4bool IsBlocked( const G4Element *anElement) const; - - inline void SetRecoilEnergyThreshold(G4double val) - { recoilEnergyThreshold = val; } - - G4double GetRecoilEnergyThreshold() const - { return recoilEnergyThreshold;} - - inline G4bool operator==(const StorkHadronicInteraction &right ) const - { return ( this == (G4HadronicInteraction *) &right ); } - - inline G4bool operator!=(const StorkHadronicInteraction &right ) const - { return ( this != (G4HadronicInteraction *) &right ); } - - virtual const std::pair GetFatalEnergyCheckLevels() const; - - virtual std::pair GetEnergyMomentumCheckLevels() const; - - inline void SetEnergyMomentumCheckLevels(G4double relativeLevel, G4double absoluteLevel) - { epCheckLevels.first = relativeLevel; - epCheckLevels.second = absoluteLevel; } - - virtual void ModelDescription(std::ostream& outFile) const ; //=0; - -private: - - StorkHadronicInteraction(const G4HadronicInteraction &right ); - const G4HadronicInteraction& operator=(const G4HadronicInteraction &right); - -protected: - - inline void SetModelName(const G4String& nam) - { theModelName = nam; } - - inline G4bool IsBlocked() const { return isBlocked;} - inline void Block() { isBlocked = true; } - - G4HadFinalState theParticleChange; - // the G4HadFinalState object which is modified and returned - // by address by the ApplyYourself method, - // (instead of aParticleChange as found in G4VProcess) - - G4int verboseLevel; - // control flag for output messages - // 0: silent - // 1: warning messages - // 2: more - // (instead of verboseLevel as found in G4VProcess) - - // these two have global validity energy range - G4double theMinEnergy; - G4double theMaxEnergy; - - G4bool isBlocked; - -private: - - G4double recoilEnergyThreshold; - - G4String theModelName; - - std::pair epCheckLevels; - - std::vector > theMinEnergyList; - std::vector > theMaxEnergyList; - std::vector > theMinEnergyListElements; - std::vector > theMaxEnergyListElements; - std::vector theBlockedList; - std::vector theBlockedListElements; -}; - - -#endif /* defined(__G4_STORK_AT__StorkHadronicInteraction__) */ diff --git a/G4STORK/include/StorkHadronicProcess.hh b/G4STORK/include/StorkHadronicProcess.hh deleted file mode 100755 index 48fe828e..00000000 --- a/G4STORK/include/StorkHadronicProcess.hh +++ /dev/null @@ -1,71 +0,0 @@ -/* -StorkHadronicProcess.hh - -Created by: Liam Russell -Date: 29-02-2012 -Modified: 11-03-2012 - -This header contains a friend function for all the hadronic/neutron processes: - 1. StorkHadronFissionProcess - 2. StorkHadronElasticProcess - 3. StorkHadronCaptureProcess - 4. StorkNeutronInelasticProcess - -The friend function, StartTrackingHadronicProcess(), allows G4-STORK to set the -initial n-lambda (number of interaction lengths left) values for each process. -This is implemented as a friend function since the processes have different base -classes. - -*/ - - -#ifndef NSHADRONICPROCESS_H -#define NSHADRONICPROCESS_H - -// Include header files -#include "StorkPrimaryNeutronInfo.hh" -#include "StorkTrackInfo.hh" -#include "G4PrimaryParticle.hh" -#include "G4Track.hh" - - -// StartTrackingHadronicProcess() -// Sets the initial currentInteractionLength and -// theNumberOfInteractionLengthLeft (eta). Eta is set from the primary -// neutron data if there is any, or it is set to the default, -1.0. -inline void StartTrackingHadronicProcess(G4Track *aTrack, G4double &n_lambda, - G4int procIndex) -{ - // If this is not the first step of a track, return immediately - if(aTrack->GetCurrentStepNumber() > 0) return; - - // Get the primary particle user information - G4PrimaryParticle *aPrimary = aTrack->GetDynamicParticle()-> - GetPrimaryParticle(); - - // Initialize pointers - StorkTrackInfo *trackInfo = NULL; - StorkPrimaryNeutronInfo *pnInfo = NULL; - - // Check that the primary neutron exists. If so, set the primary info. - if(aPrimary) - { - pnInfo = dynamic_cast( - aPrimary->GetUserInformation()); - } - // Else check if the track has a track info object - else if((trackInfo = dynamic_cast( - aTrack->GetUserInformation()))) - { - pnInfo = trackInfo->GetStorkPrimaryNeutronInfo(); - } - - // Check that the primary neutron info exists - if(pnInfo) - { - // Set the number of interaction lengths left - n_lambda = pnInfo->GetEta(procIndex); - } -} - -#endif // NSHADRONICPROCESS_H diff --git a/G4STORK/include/StorkHeatTransfer.hh b/G4STORK/include/StorkHeatTransfer.hh deleted file mode 100755 index bc8e647a..00000000 --- a/G4STORK/include/StorkHeatTransfer.hh +++ /dev/null @@ -1,71 +0,0 @@ -/* -StorkHeatTransfer.hh - -Definition for StorkHeatTransfer class. - -This is the basics class that is used to keep track of the temperature of -the different geometries in the nuclear reactor. It's a simple grid representation -of the reactor where each mesh is given a specific temperature and the heat equation -is used to track keep track of heat transfer with time -*/ - -#ifndef STORKHEATTRANSFER_H -#define STORKHEATTRANSFER_H - -#include "StorkWorld.hh" -#include "StorkContainers.hh" -#include "StorkMaterialHT.hh" -#include "G4TransportationManager.hh" -#include -#include -#include "G4ParticleDefinition.hh" -#include "G4ParticleTable.hh" - -class StorkHeatTransfer -{ - public: - // Default constructor - StorkHeatTransfer(const StorkParseInput* fIn); - ~StorkHeatTransfer(void); - - void InitializeSlowpokeModel(const StorkParseInput* fIn); - void RunThermalCalculation(MSHSiteVector fissionSites); - void RunSlowpokeModel(); - void SetWorld(StorkWorld* world); - void SetFuelDimensions(G4ThreeVector fDim) {fuelDimensions = fDim;} - - - protected: - void CalcHeatDistribution(); - void UpdateFuelProperties(G4double FuelTemperatures[],G4double FuelDensities[],G4double FuelRadii[]); - G4double CalcFuelTemperature(G4double heatGeneration, G4double mass, G4double surfaceArea, G4double oldTemp, G4double heatcapacity); - G4double CalcFuelDensity(G4double temperature); - G4double CalcFuelRadius(G4double oldRadius, G4double oldDensity, G4double newDensity); - void SaveSLOWPOKEFuelProperties(G4String filename); - G4double CalcEffectiveHeatGenerated(G4double currentFissions); - - - protected: - StorkWorld* theWorld; - MSHSiteVector* fSites; - G4double reactorPower; - G4String worldname; - G4double dt; - G4double heatTransferCoeff; - G4double temp_infty; - std::map< G4String, G4double > fnDistribution; - std::vector fnMaterialList; - G4double effectiveFissionEnergy; - G4ThreeVector fuelDimensions; - G4bool createHeader; - G4bool saveMaterialData; - G4String saveMaterialfilename; - G4double fuelTempAvg; - G4double fuelDensityAvg; - G4double fuelRadiusAvg; - G4double fissionToEnergyCoeff; - G4double baselineFissionRate; - -}; - -#endif // STORKHEATTRANSFER_H diff --git a/G4STORK/include/StorkInterpManager.hh b/G4STORK/include/StorkInterpManager.hh deleted file mode 100755 index 62c900cf..00000000 --- a/G4STORK/include/StorkInterpManager.hh +++ /dev/null @@ -1,111 +0,0 @@ -/* -StorkInterpManager.hh - -Created by: Liam Russell -Date: 10-08-2012 -Modified: 11-03-2012 - -Header for StorkInterpManager class. Used to store and access interpolation -vectors based on a material and property being changed with respect to time. - -*/ - - -#ifndef NSINTERPMANAGER_H -#define NSINTERPMANAGER_H - -// Include header files -#include "StorkInterpVector.hh" -#include "StorkContainers.hh" - - -class StorkInterpManager -{ - public: - // Public member functions - - // Constructor and destructor - StorkInterpManager() {} - ~StorkInterpManager() {} - - // Create a vector of data points that interpolation can act upon - G4bool CreateInterpVector(G4String name, G4String dataFile, - MatPropPair mpPair, G4double uy = 1., - G4double ux = 1.) - { - MatPropInterpolator anInterpolator; - - // Set name in name vector - anInterpolator.first = name; - - // Set matProp pair - anInterpolator.second = mpPair; - - // Load interpolation vector from file - anInterpolator.third.InitInterpData(dataFile,uy,ux); - - // Set the units of the Y data - anInterpolator.fourth = uy; - - // adds the StorkTriple anInterpolator to the theInterps vector - theInterps.push_back(anInterpolator); - - return true; - } - - // Returns an element of theInterps the vector - const MatPropInterpolator* GetMatPropInterpolator(G4int index) const - { - return &(theInterps[index]); - } - - // Sets the [] class operator to return a reference to an element of the - // theInterps vector - const MatPropInterpolator* operator[] (G4int index) const - { - return &(theInterps[index]); - } - - // Get the number of interpolation vectors - G4int GetNumberOfInterpVectors() const - { - return G4int(theInterps.size()); - } - G4bool IsMatModify() const - { - G4bool matModify=false; - G4String propName; - for(G4int i=0; iGetEnumKeyword((theInterps[i].second).second); - - if((propName!="dimension")||(propName!="position")||(propName!="rotation")) - matModify=true; - } - return matModify; - } - // Get a property change vector of all changes to be made - StorkMatPropChangeVector GetStorkMatPropChanges(G4double time) const - { - StorkMatPropChangeVector theChanges; - StorkMatPropChange aChange; - - for(G4int i=0; i theInterps; - StorkMatPropManager* matPropEnumList; -}; - -#endif // NSINTERPMANAGER_H diff --git a/G4STORK/include/StorkInterpVector.hh b/G4STORK/include/StorkInterpVector.hh deleted file mode 100755 index b39da76a..00000000 --- a/G4STORK/include/StorkInterpVector.hh +++ /dev/null @@ -1,84 +0,0 @@ -/* -StorkInterpVector.hh - -Created by: Wesley Ford -Date: 23-05-2012 -Modified: 10-08-2012 - -Header for StorkInterpVector class, based off of the G4NeutronHPVector class. - -This class sets up an interpolation scheme from a given data file or data -vector and can interpolates data given to it using the GetY member function. - -*/ - -#ifndef NSINTERPVECTOR_H -#define NSINTERPVECTOR_H -#include "G4InterpolationManager.hh" -#include "G4NeutronHPInterpolator.hh" -#include -#include -#include "globals.hh" -#include -#include -#include "StorkMatPropManager.hh" - -typedef std::pair DataPoint; -typedef std::vector DataPointVec; - - -class StorkInterpVector -{ - public: - // Public member functions - - // Constructors (default, copy, initializing, and assignment operator) - StorkInterpVector(); - StorkInterpVector(const StorkInterpVector& right); - StorkInterpVector(G4String dataFile); - StorkInterpVector& operator=(const StorkInterpVector &right); - - // Destructor - virtual ~StorkInterpVector() {;} - - // Initialize interpolation data from file/stream - void InitInterpData(G4String dataFile = "TempData.txt", - G4double uy = 1., G4double ux = 1.); - void InitInterpData(std::ifstream&, G4double uy = 1., G4double ux = 1.); - - // Initialize interpolation data from vector of data - void InitInterpData(DataPointVec, G4InterpolationScheme); - - // Initialize interpolation manager - void InitInterpManager(G4InterpolationScheme, G4int); - - // Add data point to vector - void AddDataPoint(DataPoint); - - // Check if vector is not empty - G4bool HasData() const { return hasData; }; - - // Get interpolated value - G4double GetY(G4double xIn) const; - - // Integrate over entire vector - G4double Integrate(); - - - private: - // Private member functions - - void CopyVector(const StorkInterpVector &right); - void InitDataVector(std::ifstream&, G4double uy = 1., G4double ux = 1.); - - private: - // Private member variables - - G4InterpolationManager theInterpMan; // Interpolation manager - G4NeutronHPInterpolator theInt; // Interpolator - DataPointVec data; // Vector of data - G4int numPoints; // Number of data points - G4bool hasData; -}; - -#endif // NSINTERPVECTOR_H diff --git a/G4STORK/include/StorkMatPropChange.hh b/G4STORK/include/StorkMatPropChange.hh deleted file mode 100755 index 11dee7b5..00000000 --- a/G4STORK/include/StorkMatPropChange.hh +++ /dev/null @@ -1,74 +0,0 @@ -/* -StorkMatPropChange.hh - -Created by: Liam Russell -Date: 09-08-2012 -Modified: 11-03-2013 - -Definition of StorkMatPropChange class. - -The StorkMatPropChange is a marshallable container class that holds a new -(double) value for a given material-property pair. - -*/ - -#ifndef PROPERTYCHANGE_HH_INCLUDED -#define PROPERTYCHANGE_HH_INCLUDED - -#include "StorkContainers.hh" - -//MSH_BEGIN -class StorkMatPropChange -{ - public: - // Public member functions - - // Default constructor - StorkMatPropChange() - :matN(0), propN(0), change(0.0) - {} - - // Constructors - StorkMatPropChange(G4int mat, G4int p, G4double c) - :matN(mat), propN(p), change(c) - {} - - StorkMatPropChange(MatPropPair aPair, G4double c) - :matN(aPair.first), propN(aPair.second), change(c) - {} - - // Destructor - virtual ~StorkMatPropChange() {} - - // Overloaded set functions - void Set(G4int mat, G4int p, G4double c) - { - matN = mat; - propN = p; - change = c; - } - - void Set(MatPropPair aPair, G4double c) - { - matN = G4int(aPair.first); - propN = G4int(aPair.second); - change = c; - } - - // Get the material-property designation of the property change - MatPropPair GetMatPropPair() const - { - return MatPropPair(MatEnum(matN),PropEnum(propN)); - } - - - public: - // Public member variables - - G4int matN; //MSH: primitive - G4int propN; //MSH: primitive - G4double change; //MSH: primitive -}; -//MSH_END - -#endif // PROPERTYCHANGE_HH_INCLUDED diff --git a/G4STORK/include/StorkMatPropManager.hh b/G4STORK/include/StorkMatPropManager.hh deleted file mode 100755 index 644c2ce1..00000000 --- a/G4STORK/include/StorkMatPropManager.hh +++ /dev/null @@ -1,87 +0,0 @@ -/* -StorkMatPropManager.hh - -Created by: Liam Russell -Date: 17-08-2012 -Modified: 11-03-2013 - -This class manages the material/property enumerators which are defined below. -It assigns units to the properties and contains functions that return enumerator -keywords, enumerators, and units. - -This is a static class and may only be instantiated once. - - -NOTE: if a new material or property is added in the enumerators, the -corresponding names and units should be added to MAT_NAMES or PROP_NAMES, -PROP_UNITS and PROP_UNIT_NAMES. - -*/ - - -#ifndef STORKMATERIALPROPERTYMANAGER_H -#define STORKMATERIALPROPERTYMANAGER_H - - -// MatPropEnumerators - -// Material and property enumerators used to identify/change the properties -// of various materials -enum MatEnum {all=0, fuel, coolant, moderator, poison, controlrod, MAX_MATS}; -enum PropEnum {temperature=0, density, dimension, concentration, position, rotation, MAX_PROPS}; - -#include "G4UnitsTable.hh" -#include "G4SystemOfUnits.hh" - - -class StorkMatPropManager -{ - public: - // Public member functions - - // Get the current material-property manager - static StorkMatPropManager* GetStorkMatPropManager(); - - // Destructor - virtual ~StorkMatPropManager() {;} - - // Overloaded function that return enum keywords - G4String GetEnumKeyword(MatEnum aMat) const; - G4String GetEnumKeyword(PropEnum aProp) const; - - // Overloaded function that returns enum given a keyword - MatEnum ParseMatEnum(G4String key) const; - PropEnum ParsePropEnum(G4String key) const; - - // Get property units - G4double GetUnits(PropEnum aProp) const; - G4String GetUnitsName(PropEnum aProp) const; - G4String GetPropType(PropEnum aProp) const; - - // Set the units of a property - void SetUnits(PropEnum aProp, G4double value, G4String name); - - - private: - // Private member functions - - // Private default constructor - StorkMatPropManager() {;} - - // Capitalize a string - G4String Capitalize(G4String str) const; - - private: - // Private member data - - static StorkMatPropManager *theMPManager; - - static const G4String MAT_NAMES[MAX_MATS]; - static const G4String PROP_NAMES[MAX_PROPS]; - - static G4String thePropType[MAX_PROPS]; - static G4double thePropUnits[MAX_PROPS]; - static G4String theUnitNames[MAX_PROPS]; -}; - -#endif // STORKMATERIALPROPERTYMANAGER_H diff --git a/G4STORK/include/StorkMaterial.hh b/G4STORK/include/StorkMaterial.hh deleted file mode 100755 index 7d40fb12..00000000 --- a/G4STORK/include/StorkMaterial.hh +++ /dev/null @@ -1,91 +0,0 @@ -#ifndef StorkMaterial_HH -#define StorkMaterial_HH 1 - -#include - -#include "StorkElement.hh" -#include "G4Material.hh" - -//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... - -class StorkMaterial : public G4Material -{ -public: // with description - // - // Constructor to create a material from single element - // - StorkMaterial(const G4String& name, //its name - G4double z, //atomic number - G4double a, //mass of mole - G4double density, //density - G4State state = kStateUndefined, //solid,gas - G4double temp = CLHEP::STP_Temperature, //temperature - G4double pressure = CLHEP::STP_Pressure); //pressure - - // - // Constructor to create a material from a combination of elements - // and/or materials subsequently added via AddElement and/or AddMaterial - // - StorkMaterial(const G4String& name, //its name - G4double density, //density - G4int nComponents, //nbOfComponents - G4State state = kStateUndefined, //solid,gas - G4double temp = CLHEP::STP_Temperature, //temperature - G4double pressure = CLHEP::STP_Pressure); //pressure - - // - // Constructor to create a material from the base material - // - StorkMaterial(const G4String& name, //its name - G4double density, //density - StorkMaterial* baseMaterial, //base material - G4State state = kStateUndefined, //solid,gas - G4double temp = CLHEP::STP_Temperature, //temperature - G4double pressure = CLHEP::STP_Pressure); //pressure - - // - // Add an element, giving number of atoms - // - void AddElement(StorkElement* element, //the element - G4int nAtoms); //nb of atoms in - // a molecule - // - // Add an element or material, giving fraction of mass - // - void AddElement (StorkElement* element , //the element - G4double fraction); //fractionOfMass - - void AddMaterial(StorkMaterial* material, //the material - G4double fraction); //fractionOfMass - - ~StorkMaterial(); - // - //printing methods - // - /* - friend std::ostream& operator<<(std::ostream&, StorkMaterial*); - friend std::ostream& operator<<(std::ostream&, StorkMaterial&); - friend std::ostream& operator<<(std::ostream&, G4MaterialTable); - */ - -public: // without description - - G4int operator==(const StorkMaterial&) const; - G4int operator!=(const StorkMaterial&) const; - StorkMaterial(__void__&); - // Fake default constructor for usage restricted to direct object - // persistency for clients requiring preallocation of memory for - // persistifiable objects. - - - void SetTemperature(G4double matTemp, G4bool UpdateElemTemp); - StorkMaterial(StorkMaterial&); - const StorkMaterial& operator=(StorkMaterial&); - -private: - -}; - -//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... - -#endif diff --git a/G4STORK/include/StorkMaterialHT.hh b/G4STORK/include/StorkMaterialHT.hh deleted file mode 100755 index 6e4c50e7..00000000 --- a/G4STORK/include/StorkMaterialHT.hh +++ /dev/null @@ -1,66 +0,0 @@ -#ifndef StorkMaterialHT_H -#define StorkMaterialHT_H - -#include "G4Material.hh" - -class StorkMaterialHT: public G4Material -{ -public: - StorkMaterialHT(const G4String& name, - G4double density, - G4int nComponents, - G4double SHC = 0., - G4double TC = 0., - G4State state = kStateUndefined, - G4double temp = CLHEP::STP_Temperature, - G4double pressure = CLHEP::STP_Pressure): - G4Material(name, density, nComponents, state, temp, pressure) - { - specificHeatCapacity = SHC; - thermalConductivity = TC; - } - - StorkMaterialHT(const G4String& name, - G4double z, - G4double a, - G4double density, - G4double SHC = 0., - G4double TC = 0., - G4State state = kStateUndefined, - G4double temp = CLHEP::STP_Temperature, - G4double pressure = CLHEP::STP_Pressure): - G4Material(name, z, a, density, state, temp, pressure) - { - specificHeatCapacity = SHC; - thermalConductivity = TC; - } - - StorkMaterialHT(const G4String& name, - G4double density, - const G4Material* baseMaterial, - G4double SHC = 0., - G4double TC = 0., - G4State state = kStateUndefined, - G4double temp = CLHEP::STP_Temperature, - G4double pressure = CLHEP::STP_Pressure): - G4Material(name, density, baseMaterial, state, temp, pressure) - { - specificHeatCapacity = SHC; - thermalConductivity = TC; - } - - ~StorkMaterialHT(){;} - - // Returns wanted properties of the material - G4double GetVolumetricHeatCapacity(void) {return specificHeatCapacity*this->GetDensity();} - G4double GetSpecificHeatCapacity(void) { return specificHeatCapacity; } - G4double GetThermalConductivity(void) {return thermalConductivity; } - G4double GetThermalDiffusivity(void) {return thermalConductivity/(specificHeatCapacity*this->GetDensity());} - -protected: - // Stores propertieas of the material - G4double specificHeatCapacity; - G4double thermalConductivity; -}; - -#endif // StorkMaterialHT_H diff --git a/G4STORK/include/StorkNeutronData.hh b/G4STORK/include/StorkNeutronData.hh deleted file mode 100755 index e0e7bb71..00000000 --- a/G4STORK/include/StorkNeutronData.hh +++ /dev/null @@ -1,100 +0,0 @@ -/* -StorkNeutronData.hh - -Created by: Liam Russell -Date: 07-08-2011 -Modified: 11-03-2013 - -Definition for StorkNeutronData class. - -This is the basic container class used to store the survivor and delayed neutron -data. The class holds four pieces of data publicly: - 1. Global Time = the current simulation time the other data was recorded at - 2. Lifetime = the total simulation time since the hit that created the - neutron. For delayed neutrons, this is the initial fission - that set off the decay chain. - 3. Position = the position of the neutron at the global time. - 4. Momentum = the momentum of the neutron at the global time. - 5-8. Eta's = theNumberOfInteractionLengthLeft for the hadronic processes - 9. Discretionary (energy/weight/etc) -This class's main purpose is to be marshallable, and thereby, allow the -NeutronSources and NeutronList classes to be marshallable. Also, the member -variables are public to allow easy access. - -*/ - -#ifndef NEUTRONDATA_H -#define NEUTRONDATA_H - -#include "G4ThreeVector.hh" - - -//MSH_BEGIN -class StorkNeutronData -{ - public: - // Public member functions - - // Default constructor - StorkNeutronData() - { } - - // Constructor with first 4 values - StorkNeutronData(G4double in1, G4double in2, G4ThreeVector in3, - G4ThreeVector in4) - :first(in1),second(in2),third(in3),fourth(in4),fifth(-1.0),sixth(-1.0), - seventh(-1.0),eigth(-1.0),ninth(1.0) - { } - - // Constructor with all nine values - StorkNeutronData(G4double in1, G4double in2, G4ThreeVector in3, - G4ThreeVector in4, G4double in5, G4double in6, - G4double in7, G4double in8, G4double in9) - :first(in1),second(in2),third(in3),fourth(in4),fifth(in5),sixth(in6), - seventh(in7),eigth(in8),ninth(in9) - { } - - // Assignment operator - StorkNeutronData& operator=(const StorkNeutronData& other) - { - copy(other); - return *this; - } - - // Destructor - virtual ~StorkNeutronData() { } - - public: - // Public member data - - G4double first; //MSH: primitive - G4double second; //MSH: primitive - G4ThreeVector third; //MSH: primitive - G4ThreeVector fourth; //MSH: primitive - G4double fifth; //MSH: primitive - G4double sixth; //MSH: primitive - G4double seventh; //MSH: primitive - G4double eigth; //MSH: primitive - G4double ninth; //MSH: primitive - - - private: - // Private member functions - - // Copy helper function - void copy(const StorkNeutronData & other) - { - first = other.first; - second = other.second; - third = other.third; - fourth = other.fourth; - fifth = other.fifth; - sixth = other.sixth; - seventh = other.seventh; - eigth = other.eigth; - ninth = other.ninth; - } -}; -//MSH_END - -#endif // NEUTRONDATA_H diff --git a/G4STORK/include/StorkNeutronHPCSData.hh b/G4STORK/include/StorkNeutronHPCSData.hh deleted file mode 100755 index 506bdfde..00000000 --- a/G4STORK/include/StorkNeutronHPCSData.hh +++ /dev/null @@ -1,97 +0,0 @@ -/* -StorkNeutronHPCSData.hh - -Created by: Liam Russell -Date: 22-06-2011 -Modified: 17-02-2012 - -Header file for StorkNeutronHPCSData class. - -Modified version of G4NeutronHP****Data classes (elastic, inelastic, fission, -or capture). This class sets up the appropriate cross section data for one of -the four reactions and calculates Doppler broadened cross sections. - -The orginal version was modified to cover all four interaction types and it -allows for different temperatures in the cross sections. This can negate the -need for Doppler broadening which speeds up the calculation. - -*/ - -#ifndef NEUTRONHPCSDATA_H -#define NEUTRONHPCSDATA_H - -#include "G4NeutronHPCaptureData.hh" -#include "G4NeutronHPElasticData.hh" -#include "G4NeutronHPInelasticData.hh" -#include "G4NeutronHPFissionData.hh" - -#include "G4VCrossSectionDataSet.hh" -#include "G4DynamicParticle.hh" -#include "G4Element.hh" -#include "G4ParticleDefinition.hh" -#include "G4PhysicsTable.hh" -#include "G4SystemOfUnits.hh" - -#include "G4Neutron.hh" -#include "G4ElementTable.hh" -#include "StorkNeutronHPDataConstructor.hh" - -#include "G4Nucleus.hh" -#include "G4NucleiProperties.hh" -#include "G4Electron.hh" -#include "ElementNames.hh" - - -class StorkNeutronHPCSData : public G4VCrossSectionDataSet -{ - public: - - StorkNeutronHPCSData(char aType, G4String dirName, G4double FSTemp); - ~StorkNeutronHPCSData(); - - G4bool IsApplicable(const G4DynamicParticle*, const G4Element*); - - public: - - G4bool IsZAApplicable(const G4DynamicParticle* , G4double /*ZZ*/, - G4double /*AA*/) - { return false;} - - //G4bool IsElementApplicable(const G4DynamicParticle*, G4int, const G4Material*); - //G4double GetElementCrossSection(const G4DynamicParticle* dynPart, G4int Z, const G4Material* mat); - G4bool IsIsoApplicable( const G4DynamicParticle* dp , - G4int /*Z*/ , G4int /*A*/ , - const G4Element* /*elm*/ , - const G4Material* /*mat*/ ); - - G4double GetIsoCrossSection( const G4DynamicParticle* dp , - G4int /*Z*/ , G4int /*A*/ , - const G4Isotope* /*iso*/ , - const G4Element* element , - const G4Material* material ); - - G4double GetCrossSection(const G4DynamicParticle*, const G4Element*, - G4double aT); - void BuildPhysicsTable(const G4ParticleDefinition&) - {}; - void BuildPhysicsTable(const G4ParticleDefinition&, G4String dirName); - void DumpPhysicsTable(const G4ParticleDefinition&); - - - private: - - G4PhysicsTable * theCrossSections; - - G4int numMaxOL; - G4int numIL; - char reactionType; - - G4double ke_cache; - G4double xs_cache; - G4double fsTemp; - - const G4Element* element_cache; - const G4Material* material_cache; -}; - -#endif // NEUTRONHPCSDATA_H diff --git a/G4STORK/include/StorkNeutronHPCapture.hh b/G4STORK/include/StorkNeutronHPCapture.hh deleted file mode 100755 index 0a6c34af..00000000 --- a/G4STORK/include/StorkNeutronHPCapture.hh +++ /dev/null @@ -1,77 +0,0 @@ -// -// ******************************************************************** -// * License and Disclaimer * -// * * -// * The Geant4 software is copyright of the Copyright Holders of * -// * the Geant4 Collaboration. It is provided under the terms and * -// * conditions of the Geant4 Software License, included in the file * -// * LICENSE and available at http://cern.ch/geant4/license . These * -// * include a list of copyright holders. * -// * * -// * Neither the authors of this software system, nor their employing * -// * institutes,nor the agencies providing financial support for this * -// * work make any representation or warranty, express or implied, * -// * regarding this software system or assume any liability for its * -// * use. Please see the license in the file LICENSE and URL above * -// * for the full disclaimer and the limitation of liability. * -// * * -// * This code implementation is the result of the scientific and * -// * technical work of the GEANT4 collaboration. * -// * By using, copying, modifying or distributing the software (or * -// * any work based on the software) you agree to acknowledge its * -// * use in resulting scientific publications, and indicate your * -// * acceptance of all terms of the Geant4 Software license. * -// ******************************************************************** -// -// -// - // Hadronic Process: Very Low Energy Neutron X-Sections - // original by H.P. Wellisch, TRIUMF, 14-Feb-97 - // Builds and has the Cross-section data for one material. - -// Class Description -// Final state production model for a high precision (based on evaluated data -// libraries) description of neutron capture below 20 MeV; -// To be used in your physics list in case you need this physics. -// In this case you want to register an object of this class with -// the corresponding process. -// Class Description - End - -#ifndef StorkNeutronHPCapture_hh -#define StorkNeutronHPCapture_hh 1 - -#include "globals.hh" -#include "StorkNeutronHPChannel.hh" -#include "G4HadronicInteraction.hh" - -class StorkNeutronHPCapture : public G4HadronicInteraction -{ - public: - - StorkNeutronHPCapture(G4double finalStateTemp); - - ~StorkNeutronHPCapture(); - - G4HadFinalState * ApplyYourself(const G4HadProjectile& aTrack, G4Nucleus& aTargetNucleus); - - virtual const std::pair GetFatalEnergyCheckLevels() const; - - public: - G4int GetVerboseLevel() const; - void SetVerboseLevel( G4int ); - - private: - - G4double * xSec; - //G4NeutronHPChannel * theCapture; - std::vector theCapture; - G4String dirName; - G4int numEle; - G4double fsTemp; -// G4int it; - - G4HadFinalState theResult; - void addChannelForNewElement(); -}; - -#endif diff --git a/G4STORK/include/StorkNeutronHPChannel.hh b/G4STORK/include/StorkNeutronHPChannel.hh deleted file mode 100755 index d38cb59b..00000000 --- a/G4STORK/include/StorkNeutronHPChannel.hh +++ /dev/null @@ -1,168 +0,0 @@ -// -// ******************************************************************** -// * License and Disclaimer * -// * * -// * The Geant4 software is copyright of the Copyright Holders of * -// * the Geant4 Collaboration. It is provided under the terms and * -// * conditions of the Geant4 Software License, included in the file * -// * LICENSE and available at http://cern.ch/geant4/license . These * -// * include a list of copyright holders. * -// * * -// * Neither the authors of this software system, nor their employing * -// * institutes,nor the agencies providing financial support for this * -// * work make any representation or warranty, express or implied, * -// * regarding this software system or assume any liability for its * -// * use. Please see the license in the file LICENSE and URL above * -// * for the full disclaimer and the limitation of liability. * -// * * -// * This code implementation is the result of the scientific and * -// * technical work of the GEANT4 collaboration. * -// * By using, copying, modifying or distributing the software (or * -// * any work based on the software) you agree to acknowledge its * -// * use in resulting scientific publications, and indicate your * -// * acceptance of all terms of the Geant4 Software license. * -// ******************************************************************** -// -// -// - // Hadronic Process: Very Low Energy Neutron X-Sections - // original by H.P. Wellisch, TRIUMF, 14-Feb-97 - // Builds and has the Cross-section data for one element and channel. -// -// Bug fixes and workarounds in the destructor, F.W.Jones 06-Jul-1999 -// 070612 Fix memory leaking by T. Koi -// -// 080520 Delete unnecessary dependencies by T. Koi - -#ifndef StorkNeutronHPChannel_h -#define StorkNeutronHPChannel_h 1 -#include "globals.hh" -#include "G4NeutronHPIsoData.hh" -#include "G4NeutronHPVector.hh" -#include "G4Material.hh" -#include "G4HadProjectile.hh" -//#include "G4NeutronInelasticProcess.hh" -//#include "G4HadronFissionProcess.hh" -//#include "G4HadronElasticProcess.hh" -//#include "G4HadronCaptureProcess.hh" -#include "G4StableIsotopes.hh" -#include "G4NeutronHPCaptureFS.hh" -#include "G4NeutronHPFinalState.hh" -#include "G4Element.hh" -#include "G4WendtFissionFragmentGenerator.hh" - -class StorkNeutronHPChannel -{ -public: - - StorkNeutronHPChannel(G4double finalStateTemp) - : wendtFissionGenerator(getenv("G4NEUTRON_HP_USE_WENDT_FISSION_MODEL") == NULL ? NULL : G4WendtFissionFragmentGenerator::GetInstance()) - { - theChannelData = new G4NeutronHPVector; - theBuffer = 0; - theIsotopeWiseData = 0; - theFinalStates = 0; - active = 0; - registerCount = -1; - fsTemp = finalStateTemp; - } - - ~StorkNeutronHPChannel() - { - delete theChannelData; - // Following statement disabled to avoid SEGV - // theBuffer is also deleted as "theChannelData" in - // ~G4NeutronHPIsoData. FWJ 06-Jul-1999 - //if(theBuffer != 0) delete theBuffer; - if(theIsotopeWiseData != 0) delete [] theIsotopeWiseData; - // Deletion of FinalStates disabled to avoid endless looping - // in the destructor heirarchy. FWJ 06-Jul-1999 - //if(theFinalStates != 0) - //{ - // for(i=0; iHasFSData(); } - - inline G4bool HasAnyData(G4int isoNumber) { return theFinalStates[isoNumber]->HasAnyData(); } - - G4bool Register(G4NeutronHPFinalState *theFS); - - void Init(G4Element * theElement, const G4String dirName); - - void Init(G4Element * theElement, const G4String dirName, const G4String fsType); - - //void UpdateData(G4int A, G4int Z, G4int index, G4double abundance); - void UpdateData(G4int A, G4int Z, G4int index, G4double abundance) { G4int M = 0; UpdateData( A, Z, M, index, abundance); }; - void UpdateData(G4int A, G4int Z, G4int M, G4int index, G4double abundance); - - void Harmonise(G4NeutronHPVector *& theStore, G4NeutronHPVector * theNew); - - G4HadFinalState * ApplyYourself(const G4HadProjectile & theTrack, G4int isoNumber=-1); - - inline G4int GetNiso() {return niso;} - - inline G4double GetN(G4int i) {return theFinalStates[i]->GetN();} - inline G4double GetZ(G4int i) {return theFinalStates[i]->GetZ();} - inline G4double GetM(G4int i) {return theFinalStates[i]->GetM();} - - inline G4bool HasDataInAnyFinalState() - { - G4bool result = false; - G4int i; - for(i=0; iHasAnyData()) result = true; - } - return result; - } - -private: - G4NeutronHPVector * theChannelData; // total (element) cross-section for this channel - G4NeutronHPVector * theBuffer; - - G4NeutronHPIsoData * theIsotopeWiseData; // these are the isotope-wise cross-sections for each final state. - G4NeutronHPFinalState ** theFinalStates; // also these are isotope-wise pionters, parallel to the above. - G4bool * active; - G4int niso; - - G4StableIsotopes theStableOnes; - - G4String theDir; - G4String theFSType; - G4Element * theElement; - G4double fsTemp; - - G4int registerCount; - - G4WendtFissionFragmentGenerator* const wendtFissionGenerator; - -}; - -#endif diff --git a/G4STORK/include/StorkNeutronHPChannelList.hh b/G4STORK/include/StorkNeutronHPChannelList.hh deleted file mode 100755 index 9912c307..00000000 --- a/G4STORK/include/StorkNeutronHPChannelList.hh +++ /dev/null @@ -1,108 +0,0 @@ -// -// ******************************************************************** -// * License and Disclaimer * -// * * -// * The Geant4 software is copyright of the Copyright Holders of * -// * the Geant4 Collaboration. It is provided under the terms and * -// * conditions of the Geant4 Software License, included in the file * -// * LICENSE and available at http://cern.ch/geant4/license . These * -// * include a list of copyright holders. * -// * * -// * Neither the authors of this software system, nor their employing * -// * institutes,nor the agencies providing financial support for this * -// * work make any representation or warranty, express or implied, * -// * regarding this software system or assume any liability for its * -// * use. Please see the license in the file LICENSE and URL above * -// * for the full disclaimer and the limitation of liability. * -// * * -// * This code implementation is the result of the scientific and * -// * technical work of the GEANT4 collaboration. * -// * By using, copying, modifying or distributing the software (or * -// * any work based on the software) you agree to acknowledge its * -// * use in resulting scientific publications, and indicate your * -// * acceptance of all terms of the Geant4 Software license. * -// ******************************************************************** -// -// -// - // Hadronic Process: Very Low Energy Neutron X-Sections - // original by H.P. Wellisch, TRIUMF, 14-Feb-97 - // Builds and has the Cross-section data for one material. - -#ifndef StorkNeutronHPChannelList_h -#define StorkNeutronHPChannelList_h 1 - -#include "globals.hh" -#include "StorkNeutronHPChannel.hh" -#include "G4StableIsotopes.hh" - -class G4Element; -class G4HadFinalState; -class G4HadProjectile; -class G4NeutronHPFinalState; - -class StorkNeutronHPChannelList -{ - - public: - - StorkNeutronHPChannelList(G4int n, G4double finalStateTemp); - - StorkNeutronHPChannelList(G4double finalStateTemp); - - void Init(G4int n); - - ~StorkNeutronHPChannelList(); - - G4HadFinalState * ApplyYourself(const G4Element * theElement, const G4HadProjectile & aTrack); - - void Init(G4Element * anElement, const G4String & dirName); - - void Register(G4NeutronHPFinalState *theFS, const G4String &aName); - - inline G4double GetXsec(G4double anEnergy) - { - G4double result=0; - G4int i; - for(i=0; iGetXsec(anEnergy)); - } - return result; - } - - inline G4int GetNumberOfChannels() { return nChannels; } - - inline G4bool HasDataInAnyFinalState() - { - G4bool result = false; - G4int i; - for(i=0; iHasDataInAnyFinalState()) result = true; - } - return result; - } - inline void RestartRegistration() - { - allChannelsCreated = true; - theInitCount = 0; - } - private: - - static G4ThreadLocal G4int trycounter; - StorkNeutronHPChannel ** theChannels; - G4double fsTemp; - G4int nChannels; - G4String theDir; - G4Element * theElement; - - G4bool allChannelsCreated; - G4int theInitCount; - - G4StableIsotopes theStableOnes; - - G4HadFinalState unChanged; -}; - -#endif diff --git a/G4STORK/include/StorkNeutronHPDataConstructor.hh b/G4STORK/include/StorkNeutronHPDataConstructor.hh deleted file mode 100755 index 73dcdd35..00000000 --- a/G4STORK/include/StorkNeutronHPDataConstructor.hh +++ /dev/null @@ -1,88 +0,0 @@ -// -// ******************************************************************** -// * License and Disclaimer * -// * * -// * The Geant4 software is copyright of the Copyright Holders of * -// * the Geant4 Collaboration. It is provided under the terms and * -// * conditions of the Geant4 Software License, included in the file * -// * LICENSE and available at http://cern.ch/geant4/license . These * -// * include a list of copyright holders. * -// * * -// * Neither the authors of this software system, nor their employing * -// * institutes,nor the agencies providing financial support for this * -// * work make any representation or warranty, express or implied, * -// * regarding this software system or assume any liability for its * -// * use. Please see the license in the file LICENSE and URL above * -// * for the full disclaimer and the limitation of liability. * -// * * -// * This code implementation is the result of the scientific and * -// * technical work of the GEANT4 collaboration. * -// * By using, copying, modifying or distributing the software (or * -// * any work based on the software) you agree to acknowledge its * -// * use in resulting scientific publications, and indicate your * -// * acceptance of all terms of the Geant4 Software license. * -// ******************************************************************** -// -// -// - // Hadronic Process: Very Low Energy Neutron X-Sections - // original by H.P. Wellisch, TRIUMF, 14-Feb-97 - // Has the Cross-section data for all materials. - -#ifndef StorkNeutronHPDataConstructor_h -#define StorkNeutronHPDataConstructor_h 1 -#include "globals.hh" -#include "G4Element.hh" -#include "G4NeutronHPElasticData.hh" -#include "G4NeutronHPInelasticData.hh" -#include "G4NeutronHPFissionData.hh" -#include "G4NeutronHPCaptureData.hh" -#include "StorkNeutronHPElementData.hh" - -#include - -class StorkNeutronHPDataConstructor -{ -public: - - StorkNeutronHPDataConstructor(G4String dirName); - - ~StorkNeutronHPDataConstructor(); - - inline G4PhysicsVector * MakePhysicsVector(G4Element * thE, G4NeutronHPFissionData * theP, G4String dirName) - { - if ( numEle <= (G4int)thE->GetIndex() ) addPhysicsVector(dirName); - return DoPhysicsVector((*theData[thE->GetIndex()]).GetData(theP)); - } - inline G4PhysicsVector * MakePhysicsVector(G4Element * thE, G4NeutronHPCaptureData * theP, G4String dirName) - { - if ( numEle <= (G4int)thE->GetIndex() ) addPhysicsVector(dirName); - return DoPhysicsVector((*theData[thE->GetIndex()]).GetData(theP)); - } - inline G4PhysicsVector * MakePhysicsVector(G4Element * thE, G4NeutronHPElasticData * theP, G4String dirName) - { - if ( numEle <= (G4int)thE->GetIndex() ) addPhysicsVector(dirName); - return DoPhysicsVector((*theData[thE->GetIndex()]).GetData(theP)); - } - inline G4PhysicsVector * MakePhysicsVector(G4Element * thE, G4NeutronHPInelasticData * theP, G4String dirName) - { -// G4cout << "entered StorkNeutronHPDataConstructor::MakePhysicsVector!!!"<GetIndex()="<GetIndex()<GetIndex() ) addPhysicsVector(dirName); - return DoPhysicsVector((*theData[thE->GetIndex()]).GetData(theP)); - } - - G4PhysicsVector * DoPhysicsVector(G4NeutronHPVector * theVector); - - static StorkNeutronHPDataConstructor * Instance(G4String dirName); - -private: - - std::vector< StorkNeutronHPElementData* > theData; - G4int numEle; - void addPhysicsVector(G4String dirName); - G4String CSDirName; - -}; - -#endif diff --git a/G4STORK/include/StorkNeutronHPElastic.hh b/G4STORK/include/StorkNeutronHPElastic.hh deleted file mode 100755 index 28e416fc..00000000 --- a/G4STORK/include/StorkNeutronHPElastic.hh +++ /dev/null @@ -1,81 +0,0 @@ -// -// ******************************************************************** -// * License and Disclaimer * -// * * -// * The Geant4 software is copyright of the Copyright Holders of * -// * the Geant4 Collaboration. It is provided under the terms and * -// * conditions of the Geant4 Software License, included in the file * -// * LICENSE and available at http://cern.ch/geant4/license . These * -// * include a list of copyright holders. * -// * * -// * Neither the authors of this software system, nor their employing * -// * institutes,nor the agencies providing financial support for this * -// * work make any representation or warranty, express or implied, * -// * regarding this software system or assume any liability for its * -// * use. Please see the license in the file LICENSE and URL above * -// * for the full disclaimer and the limitation of liability. * -// * * -// * This code implementation is the result of the scientific and * -// * technical work of the GEANT4 collaboration. * -// * By using, copying, modifying or distributing the software (or * -// * any work based on the software) you agree to acknowledge its * -// * use in resulting scientific publications, and indicate your * -// * acceptance of all terms of the Geant4 Software license. * -// ******************************************************************** -// -// -// - // Hadronic Process: High Precision low E neutron tracking - // original by H.P. Wellisch, TRIUMF, 14-Feb-97 - // Builds and has the Cross-section data for one material. - -#ifndef StorkNeutronHPElastic_h -#define StorkNeutronHPElastic_h 1 - -// Class Description -// Final state production model for a high precision (based on evaluated data -// libraries) description of neutron elastic scattering below 20 MeV; -// To be used in your physics list in case you need this physics. -// In this case you want to register an object of this class with -// the corresponding process. -// Class Description - End - -#include "globals.hh" -#include "StorkNeutronHPChannel.hh" -#include "G4HadronicInteraction.hh" - -class StorkNeutronHPElastic : public G4HadronicInteraction -{ - public: - - StorkNeutronHPElastic(G4double finalStateTemp); - - ~StorkNeutronHPElastic(); - - G4HadFinalState * ApplyYourself(const G4HadProjectile& aTrack, G4Nucleus& aTargetNucleus); - - virtual const std::pair GetFatalEnergyCheckLevels() const; - - //G4int GetNiso() {return theElastic[0].GetNiso();} - G4int GetNiso() {return (*theElastic[0]).GetNiso();} - - void DoNotSuspend() {overrideSuspension = true;} - - public: - G4int GetVerboseLevel() const; - void SetVerboseLevel( G4int ); - - private: - - G4double * xSec; - //G4NeutronHPChannel * theElastic; - std::vector theElastic; - G4String dirName; - G4int numEle; - G4bool overrideSuspension; - G4double fsTemp; - - void addChannelForNewElement(); -}; - -#endif diff --git a/G4STORK/include/StorkNeutronHPElementData.hh b/G4STORK/include/StorkNeutronHPElementData.hh deleted file mode 100755 index e85d514f..00000000 --- a/G4STORK/include/StorkNeutronHPElementData.hh +++ /dev/null @@ -1,118 +0,0 @@ -// -// ******************************************************************** -// * License and Disclaimer * -// * * -// * The Geant4 software is copyright of the Copyright Holders of * -// * the Geant4 Collaboration. It is provided under the terms and * -// * conditions of the Geant4 Software License, included in the file * -// * LICENSE and available at http://cern.ch/geant4/license . These * -// * include a list of copyright holders. * -// * * -// * Neither the authors of this software system, nor their employing * -// * institutes,nor the agencies providing financial support for this * -// * work make any representation or warranty, express or implied, * -// * regarding this software system or assume any liability for its * -// * use. Please see the license in the file LICENSE and URL above * -// * for the full disclaimer and the limitation of liability. * -// * * -// * This code implementation is the result of the scientific and * -// * technical work of the GEANT4 collaboration. * -// * By using, copying, modifying or distributing the software (or * -// * any work based on the software) you agree to acknowledge its * -// * use in resulting scientific publications, and indicate your * -// * acceptance of all terms of the Geant4 Software license. * -// ******************************************************************** -// -// -// - // Hadronic Process: Very Low Energy Neutron X-Sections - // original by H.P. Wellisch, TRIUMF, 14-Feb-97 - // Builds and has the Cross-section data for one material. -// -// 080520 Delete unnecessary dependencies by T. Koi - -#ifndef StorkNeutronHPElementData_h -#define StorkNeutronHPElementData_h 1 -#include "globals.hh" -#include "StorkNeutronHPIsoData.hh" -#include "G4NeutronHPVector.hh" -#include "G4Material.hh" -#include "G4HadronCrossSections.hh" -#include "G4ReactionProduct.hh" -#include "G4Nucleus.hh" -//#include "G4NeutronInelasticProcess.hh" -//#include "G4HadronFissionProcess.hh" -//#include "G4HadronCaptureProcess.hh" -#include "G4NeutronHPElasticData.hh" -#include "G4NeutronHPFissionData.hh" -#include "G4NeutronHPCaptureData.hh" -#include "G4NeutronHPInelasticData.hh" -#include "G4StableIsotopes.hh" -#include -#include -#include "StorkElement.hh" - -class StorkNeutronHPElementData : public G4HadronCrossSections -{ -public: - - StorkNeutronHPElementData(G4String DirName); - StorkNeutronHPElementData(); - - ~StorkNeutronHPElementData(); - - void Init(G4Element * theElement); - - //void UpdateData(G4int A, G4int Z, G4int index, G4double abundance); - void UpdateData(G4int A, G4int Z, G4int index, G4double abundance) { G4int M=0; UpdateData( A, Z, M, index, abundance); }; - void UpdateData(G4int A, G4int Z, G4int M, G4int index, G4double abundance); -bool ExtractTemp(G4String name, G4double &temp); - void Harmonise(G4NeutronHPVector *& theStore, G4NeutronHPVector * theNew); - - void GetDirList(G4double temp, std::vector &csDataTempVec, std::vector &csDataNameVec); - - inline G4NeutronHPVector * GetData(G4NeutronHPFissionData * ) - {return theFissionData;} - inline G4NeutronHPVector * GetData(G4NeutronHPCaptureData * ) - {return theCaptureData;} - inline G4NeutronHPVector * GetData(G4NeutronHPElasticData * ) - {return theElasticData;} - inline G4NeutronHPVector * GetData(G4NeutronHPInelasticData * ) - {return theInelasticData;} - - G4NeutronHPVector * MakePhysicsVector(G4Element * theElement, - G4ParticleDefinition * theP, - G4NeutronHPFissionData* theSet); - - G4NeutronHPVector * MakePhysicsVector(G4Element * theElement, - G4ParticleDefinition * theP, - G4NeutronHPCaptureData * theSet); - - G4NeutronHPVector * MakePhysicsVector(G4Element * theElement, - G4ParticleDefinition * theP, - G4NeutronHPElasticData * theSet); - - G4NeutronHPVector * MakePhysicsVector(G4Element * theElement, - G4ParticleDefinition * theP, - G4NeutronHPInelasticData * theSet); - -private: - - G4NeutronHPVector * theFissionData; - G4NeutronHPVector * theCaptureData; - G4NeutronHPVector * theElasticData; - G4NeutronHPVector * theInelasticData; - G4double precision; - - G4NeutronHPVector * theBuffer; - - StorkNeutronHPIsoData * theIsotopeWiseData; - - G4StableIsotopes theStableOnes; - - G4String filename; - G4String dirName; - -}; - -#endif diff --git a/G4STORK/include/StorkNeutronHPFission.hh b/G4STORK/include/StorkNeutronHPFission.hh deleted file mode 100755 index d57c07bf..00000000 --- a/G4STORK/include/StorkNeutronHPFission.hh +++ /dev/null @@ -1,84 +0,0 @@ -// -// ******************************************************************** -// * License and Disclaimer * -// * * -// * The Geant4 software is copyright of the Copyright Holders of * -// * the Geant4 Collaboration. It is provided under the terms and * -// * conditions of the Geant4 Software License, included in the file * -// * LICENSE and available at http://cern.ch/geant4/license . These * -// * include a list of copyright holders. * -// * * -// * Neither the authors of this software system, nor their employing * -// * institutes,nor the agencies providing financial support for this * -// * work make any representation or warranty, express or implied, * -// * regarding this software system or assume any liability for its * -// * use. Please see the license in the file LICENSE and URL above * -// * for the full disclaimer and the limitation of liability. * -// * * -// * This code implementation is the result of the scientific and * -// * technical work of the GEANT4 collaboration. * -// * By using, copying, modifying or distributing the software (or * -// * any work based on the software) you agree to acknowledge its * -// * use in resulting scientific publications, and indicate your * -// * acceptance of all terms of the Geant4 Software license. * -// ******************************************************************** -// -// -// - // Hadronic Process: High Precision low E neutron tracking - // original by H.P. Wellisch, TRIUMF, 14-Feb-97 - // Builds and has the Cross-section data for one material. - -#ifndef StorkNeutronHPFission_h -#define StorkNeutronHPFission_h 1 - -// Class Description -// Final state production model for a high precision (based on evaluated data -// libraries) description of neutron induced fission below 20 MeV; -// Note that this model (by intent of avoiding the possibility of heating studies) does -// not provide the nuclear fragments. -// -// To be used in your physics list in case you need this physics. -// In this case you want to register an object of this class with -// the corresponding process. -// Class Description - End - -#include "globals.hh" -#include "StorkNeutronHPChannel.hh" -#include "G4HadronicInteraction.hh" - -#include "G4NeutronHPFissionFS.hh" - -class StorkNeutronHPFission : public G4HadronicInteraction -{ - public: - - StorkNeutronHPFission(G4double finalStateTemp); - - ~StorkNeutronHPFission(); - - G4HadFinalState * ApplyYourself(const G4HadProjectile& aTrack, G4Nucleus& aTargetNucleus); - - virtual const std::pair GetFatalEnergyCheckLevels() const; - - public: - G4int GetVerboseLevel() const; - void SetVerboseLevel( G4int ); - - private: - - G4NeutronHPFissionFS theFS; - - private: - - G4double * xSec; - //G4NeutronHPChannel * theFission; - std::vector theFission; - G4String dirName; - G4int numEle; - G4double fsTemp; - // static G4String theNames[3]; - void addChannelForNewElement(); -}; - -#endif diff --git a/G4STORK/include/StorkNeutronHPInelastic.hh b/G4STORK/include/StorkNeutronHPInelastic.hh deleted file mode 100755 index e148a0f3..00000000 --- a/G4STORK/include/StorkNeutronHPInelastic.hh +++ /dev/null @@ -1,152 +0,0 @@ -// -// ******************************************************************** -// * License and Disclaimer * -// * * -// * The Geant4 software is copyright of the Copyright Holders of * -// * the Geant4 Collaboration. It is provided under the terms and * -// * conditions of the Geant4 Software License, included in the file * -// * LICENSE and available at http://cern.ch/geant4/license . These * -// * include a list of copyright holders. * -// * * -// * Neither the authors of this software system, nor their employing * -// * institutes,nor the agencies providing financial support for this * -// * work make any representation or warranty, express or implied, * -// * regarding this software system or assume any liability for its * -// * use. Please see the license in the file LICENSE and URL above * -// * for the full disclaimer and the limitation of liability. * -// * * -// * This code implementation is the result of the scientific and * -// * technical work of the GEANT4 collaboration. * -// * By using, copying, modifying or distributing the software (or * -// * any work based on the software) you agree to acknowledge its * -// * use in resulting scientific publications, and indicate your * -// * acceptance of all terms of the Geant4 Software license. * -// ******************************************************************** -// -// -// - // Hadronic Process: High Precision low E neutron tracking - // original by H.P. Wellisch, TRIUMF, 14-Feb-97 - // Builds and has the Cross-section data for one material. - -#ifndef StorkNeutronHPInelastic_h -#define StorkNeutronHPInelastic_h 1 - -// Class Description -// Final state production model for a high precision (based on evaluated data -// libraries) description of neutron inelastic scattering below 20 MeV; -// 36 exclusive final states are consideded. -// To be used in your physics list in case you need this physics. -// In this case you want to register an object of this class with -// the corresponding process. -// Class Description - End - -#include "globals.hh" -#include "StorkNeutronHPChannel.hh" -#include "G4HadronicInteraction.hh" -#include "StorkNeutronHPChannelList.hh" - -#include "G4NeutronHP2AInelasticFS.hh" -#include "G4NeutronHP2N2AInelasticFS.hh" -#include "G4NeutronHP2NAInelasticFS.hh" -#include "G4NeutronHP2NDInelasticFS.hh" -#include "G4NeutronHP2NInelasticFS.hh" -#include "G4NeutronHP2NPInelasticFS.hh" -#include "G4NeutronHP2PInelasticFS.hh" -#include "G4NeutronHP3AInelasticFS.hh" -#include "G4NeutronHP3NAInelasticFS.hh" -#include "G4NeutronHP3NInelasticFS.hh" -#include "G4NeutronHP3NPInelasticFS.hh" -#include "G4NeutronHP4NInelasticFS.hh" -#include "G4NeutronHPAInelasticFS.hh" -#include "G4NeutronHPD2AInelasticFS.hh" -#include "G4NeutronHPDAInelasticFS.hh" -#include "G4NeutronHPDInelasticFS.hh" -#include "G4NeutronHPHe3InelasticFS.hh" -#include "G4NeutronHPN2AInelasticFS.hh" -#include "G4NeutronHPN2PInelasticFS.hh" -#include "G4NeutronHPN3AInelasticFS.hh" -#include "G4NeutronHPNAInelasticFS.hh" -#include "G4NeutronHPND2AInelasticFS.hh" -#include "G4NeutronHPNDInelasticFS.hh" -#include "G4NeutronHPNHe3InelasticFS.hh" -#include "G4NeutronHPNInelasticFS.hh" -#include "G4NeutronHPNPAInelasticFS.hh" -#include "G4NeutronHPNPInelasticFS.hh" -#include "G4NeutronHPNT2AInelasticFS.hh" -#include "G4NeutronHPNTInelasticFS.hh" -#include "G4NeutronHPNXInelasticFS.hh" -#include "G4NeutronHPPAInelasticFS.hh" -#include "G4NeutronHPPDInelasticFS.hh" -#include "G4NeutronHPPInelasticFS.hh" -#include "G4NeutronHPPTInelasticFS.hh" -#include "G4NeutronHPT2AInelasticFS.hh" -#include "G4NeutronHPTInelasticFS.hh" - -class StorkNeutronHPInelastic : public G4HadronicInteraction -{ - public: - - StorkNeutronHPInelastic(G4double finalStateTemp); - - ~StorkNeutronHPInelastic(); - - G4HadFinalState * ApplyYourself(const G4HadProjectile & aTrack, G4Nucleus & aTargetNucleus); - - virtual const std::pair GetFatalEnergyCheckLevels() const; - - public: - G4int GetVerboseLevel() const; - void SetVerboseLevel( G4int ); - - private: - - G4double * xSec; - //G4NeutronHPChannelList * theInelastic; // one List per element - std::vector theInelastic; // one List per element - G4String dirName; - G4int numEle; - G4double fsTemp; - void addChannelForNewElement(); - - private: - - G4NeutronHP2AInelasticFS the2AFS; - G4NeutronHP2N2AInelasticFS the2N2AFS; - G4NeutronHP2NAInelasticFS the2NAFS; - G4NeutronHP2NDInelasticFS the2NDFS; - G4NeutronHP2NInelasticFS the2NFS; - G4NeutronHP2NPInelasticFS the2NPFS; - G4NeutronHP2PInelasticFS the2PFS; - G4NeutronHP3AInelasticFS the3AFS; - G4NeutronHP3NAInelasticFS the3NAFS; - G4NeutronHP3NInelasticFS the3NFS; - G4NeutronHP3NPInelasticFS the3NPFS; - G4NeutronHP4NInelasticFS the4NFS; - G4NeutronHPAInelasticFS theAFS; - G4NeutronHPD2AInelasticFS theD2AFS; - G4NeutronHPDAInelasticFS theDAFS; - G4NeutronHPDInelasticFS theDFS; - G4NeutronHPHe3InelasticFS theHe3FS; - G4NeutronHPN2AInelasticFS theN2AFS; - G4NeutronHPN2PInelasticFS theN2PFS; - G4NeutronHPN3AInelasticFS theN3AFS; - G4NeutronHPNAInelasticFS theNAFS; - G4NeutronHPND2AInelasticFS theND2AFS; - G4NeutronHPNDInelasticFS theNDFS; - G4NeutronHPNHe3InelasticFS theNHe3FS; - G4NeutronHPNInelasticFS theNFS; - G4NeutronHPNPAInelasticFS theNPAFS; - G4NeutronHPNPInelasticFS theNPFS; - G4NeutronHPNT2AInelasticFS theNT2AFS; - G4NeutronHPNTInelasticFS theNTFS; - G4NeutronHPNXInelasticFS theNXFS; - G4NeutronHPPAInelasticFS thePAFS; - G4NeutronHPPDInelasticFS thePDFS; - G4NeutronHPPInelasticFS thePFS; - G4NeutronHPPTInelasticFS thePTFS; - G4NeutronHPT2AInelasticFS theT2AFS; - G4NeutronHPTInelasticFS theTFS; -}; - -#endif diff --git a/G4STORK/include/StorkNeutronHPIsoData.hh b/G4STORK/include/StorkNeutronHPIsoData.hh deleted file mode 100755 index 0ecd56a8..00000000 --- a/G4STORK/include/StorkNeutronHPIsoData.hh +++ /dev/null @@ -1,117 +0,0 @@ -// -// ******************************************************************** -// * License and Disclaimer * -// * * -// * The Geant4 software is copyright of the Copyright Holders of * -// * the Geant4 Collaboration. It is provided under the terms and * -// * conditions of the Geant4 Software License, included in the file * -// * LICENSE and available at http://cern.ch/geant4/license . These * -// * include a list of copyright holders. * -// * * -// * Neither the authors of this software system, nor their employing * -// * institutes,nor the agencies providing financial support for this * -// * work make any representation or warranty, express or implied, * -// * regarding this software system or assume any liability for its * -// * use. Please see the license in the file LICENSE and URL above * -// * for the full disclaimer and the limitation of liability. * -// * * -// * This code implementation is the result of the scientific and * -// * technical work of the GEANT4 collaboration. * -// * By using, copying, modifying or distributing the software (or * -// * any work based on the software) you agree to acknowledge its * -// * use in resulting scientific publications, and indicate your * -// * acceptance of all terms of the Geant4 Software license. * -// ******************************************************************** -// -// -// -#ifndef StorkNeutronHPIsoData_h -#define StorkNeutronHPIsoData_h 1 - - // Hadronic Process: Very Low Energy Neutron X-Sections - // original by H.P. Wellisch, TRIUMF, 14-Feb-97 - // Has the Cross-section data for on isotope. - -#include "globals.hh" -#include "G4ios.hh" -#include -// #include -#include -#include "G4NeutronHPVector.hh" -#include "StorkNeutronHPNames.hh" -#include "ElementNames.hh" - - -class StorkNeutronHPIsoData -{ -public: - - StorkNeutronHPIsoData() - { - theChannelData = 0; - theFissionData = 0; - theCaptureData = 0; - theElasticData = 0; - theInelasticData = 0; - } - - ~StorkNeutronHPIsoData(){if(theChannelData!=0) delete theChannelData;} - - inline G4double GetXsec(G4double energy) - { - return std::max(0., theChannelData->GetXsec(energy)); - } - - //G4bool Init(G4int A, G4int Z, G4double abun, G4String dirName, G4String aFSType); - G4bool Init(G4int A, G4int Z, G4double abun, G4String dirName, G4String aFSType){ G4int M = 0 ; return Init( A, Z, M, abun, dirName, aFSType); }; - G4bool Init(G4int A, G4int Z, G4int M, G4double abun, G4String dirName, G4String aFSType); - - //void Init(G4int A, G4int Z, G4double abun); //fill PhysicsVector for this Isotope - void Init(G4int A, G4int Z, G4double abun, G4String dirName) { G4int M =0; - Init( A, Z, M, abun, dirName); }; - void Init(G4int A, G4int Z, G4int M, G4double abun, G4String dirName); //fill PhysicsVector for this Isotope - - inline G4NeutronHPVector * MakeElasticData() - {return theElasticData;} - inline G4NeutronHPVector * MakeFissionData() - {return theFissionData;} - inline G4NeutronHPVector * MakeCaptureData() - {return theCaptureData;} - inline G4NeutronHPVector * MakeInelasticData() - {return theInelasticData;} - inline G4NeutronHPVector * MakeChannelData() - {return theChannelData;} - - G4bool FileExists(G4int A, G4int Z, G4String DirName ); - - inline void FillChannelData(G4NeutronHPVector * aBuffer) - { - if(theChannelData!=0) throw G4HadronicException(__FILE__, __LINE__, "IsoData has channel full already!!!"); - theChannelData = new G4NeutronHPVector; - for(G4int i=0; iGetVectorLength(); i++) - { - theChannelData->SetPoint(i, aBuffer->GetPoint(i)); - } - } - - inline void ThinOut(G4double precision) - { - if(theFissionData) theFissionData->ThinOut(precision); - if(theCaptureData) theCaptureData->ThinOut(precision); - if(theElasticData) theElasticData->ThinOut(precision); - if(theInelasticData) theInelasticData->ThinOut(precision); - } - -private: - - G4NeutronHPVector * theFissionData; - G4NeutronHPVector * theCaptureData; - G4NeutronHPVector * theElasticData; - G4NeutronHPVector * theInelasticData; - G4NeutronHPVector * theChannelData; - - G4String theFileName; - StorkNeutronHPNames theNames; -}; - -#endif diff --git a/G4STORK/include/StorkNeutronHPNames.hh b/G4STORK/include/StorkNeutronHPNames.hh deleted file mode 100755 index d9e524d8..00000000 --- a/G4STORK/include/StorkNeutronHPNames.hh +++ /dev/null @@ -1,72 +0,0 @@ -// -// ******************************************************************** -// * License and Disclaimer * -// * * -// * The Geant4 software is copyright of the Copyright Holders of * -// * the Geant4 Collaboration. It is provided under the terms and * -// * conditions of the Geant4 Software License, included in the file * -// * LICENSE and available at http://cern.ch/geant4/license . These * -// * include a list of copyright holders. * -// * * -// * Neither the authors of this software system, nor their employing * -// * institutes,nor the agencies providing financial support for this * -// * work make any representation or warranty, express or implied, * -// * regarding this software system or assume any liability for its * -// * use. Please see the license in the file LICENSE and URL above * -// * for the full disclaimer and the limitation of liability. * -// * * -// * This code implementation is the result of the scientific and * -// * technical work of the GEANT4 collaboration. * -// * By using, copying, modifying or distributing the software (or * -// * any work based on the software) you agree to acknowledge its * -// * use in resulting scientific publications, and indicate your * -// * acceptance of all terms of the Geant4 Software license. * -// ******************************************************************** -// -// -// -#ifndef StorkNeutronHPNames_h -#define StorkNeutronHPNames_h 1 - -#include "G4ios.hh" -#include -// #include -#include -#include "globals.hh" -#include "G4NeutronHPDataUsed.hh" - -class StorkNeutronHPNames -{ - public: - - StorkNeutronHPNames(){theMaxOffSet = 5;} - StorkNeutronHPNames(G4int maxOffSet){theMaxOffSet = maxOffSet;} - ~StorkNeutronHPNames(){} - - //G4NeutronHPDataUsed GetName(G4int A, G4int Z, G4String base, G4String rest, G4bool & active); - G4NeutronHPDataUsed GetName(G4int A, G4int Z, G4String base, G4String rest, G4bool & active) { G4int M = 0; return GetName( A, Z, M, base, rest, active); }; - G4NeutronHPDataUsed GetName(G4int A, G4int Z, G4int M, G4String base, G4String rest, G4bool & active); - G4String GetName(G4int i); - void SetMaxOffSet(G4int anOffset) { theMaxOffSet = anOffset; } - - public: - - static const G4String theString[100]; - G4int theMaxOffSet; - G4String itoa(int current) - { - const char theDigits[11] = "0123456789"; - G4String result; - int digit; - do - { - digit = current-10*(current/10); - result=theDigits[digit]+result; - current/=10; - } - while(current!=0); - return result; - } -}; - -#endif diff --git a/G4STORK/include/StorkNeutronInelasticProcess.hh b/G4STORK/include/StorkNeutronInelasticProcess.hh deleted file mode 100755 index e3202d6a..00000000 --- a/G4STORK/include/StorkNeutronInelasticProcess.hh +++ /dev/null @@ -1,70 +0,0 @@ -/* -StorkNeutronInelasticProcess.hh - -Created by: Liam Russell -Date: 29-02-2012 -Modified: 11-03-2013 - -Header file for StorkNeutronInelasticProcess class. - -This class is derived from G4NeutronInelasticProcess to modify the -StartTracking() function and to add a get function for -theNumberOfInteractionLenghtLeft member variable. - -*/ - -#ifndef STORKNEUTRONINELASTICPROCESS_H -#define STORKNEUTRONINELASTICPROCESS_H - -// Include header files -#include "G4NeutronInelasticProcess.hh" -#include "StorkHadronicProcess.hh" - -class StorkProcessManager; - -class StorkNeutronInelasticProcess : public G4NeutronInelasticProcess -{ - public: - // Public member functions - - // Constructor and destructor - StorkNeutronInelasticProcess(const G4String& processName = - "StorkNeutronInelastic") - :G4NeutronInelasticProcess(processName) - { -// SetVerboseLevel(2); - } - virtual ~StorkNeutronInelasticProcess() {;} - - // Set the number of interaction lengths left from previous run - virtual void StartTracking(G4Track *aTrack) - { - G4VProcess::StartTracking(aTrack); - StartTrackingHadronicProcess(aTrack, - theNumberOfInteractionLengthLeft, - procIndex); - } - - // Get the current number of interaction lengths left for the process - virtual G4double GetNumberOfInteractionLengthLeft(G4double - previousStepSize) - { - SubtractNumberOfInteractionLengthLeft(previousStepSize); - return theNumberOfInteractionLengthLeft; - } - - void SetProcessIndex(G4int ind) { procIndex = ind; } - - // Declare friend function - friend void StartTrackingHadronicProcess(G4Track *aTrack, - G4double &n_lambda, - G4int procIndex); - - private: - // Private member variables - - G4int procIndex; // Index of physics process (StorkProcessManager) -}; - - -#endif // STORKNEUTRONINELASTICPROCESS_H diff --git a/G4STORK/include/StorkNeutronPhysicsList.hh b/G4STORK/include/StorkNeutronPhysicsList.hh deleted file mode 100755 index 5c238a63..00000000 --- a/G4STORK/include/StorkNeutronPhysicsList.hh +++ /dev/null @@ -1,68 +0,0 @@ -/* -StorkNeutronPhysicsList.hh - -Created by: Liam Russell -Date: 23-02-2012 -Modified: 11-03-2013 - -Header file for StorkNeutronPhysicsList class. - -This class creates the physics processes for the simulation through process -builder classes. It also sets the energy range for each builder and the -available particles. - -*/ - -#ifndef STORKHPNEUTRONPHYSICSLIST_H -#define STORKHPNEUTRONPHYSICSLIST_H - -#include "G4VUserPhysicsList.hh" -#include "StorkHPNeutronBuilder.hh" -#include "StorkNeutronProcessBuilder.hh" -#include "G4NeutronBuilder.hh" -#include "G4BertiniNeutronBuilder.hh" -//#include "G4LEPNeutronBuilder.hh" -#include "StorkParseInput.hh" - -#ifdef G4USE_TOPC - #include "topc.h" - #include "G4HadronicProcessStore.hh" -#endif - - -class StorkNeutronPhysicsList : public G4VUserPhysicsList -{ - public: - // Public member functions - - // Constructor and destructor - StorkNeutronPhysicsList(const StorkParseInput* infile); - ~StorkNeutronPhysicsList(); - - - protected: - //Protected member functions - - void ConstructParticle(); // Set available particles - void ConstructProcess(); // Set available processes - void SetCuts(); - - - private: - // Private member variables - - // User inputs - G4String csDirName; - G4String fsDirName; - G4int kCalcType; - std::vector* periodicBCVec; - std::vector* reflectBCVec; - - // Neutron physics builders - StorkNeutronProcessBuilder *theNeutrons; - StorkHPNeutronBuilder *theHPNeutron; - G4BertiniNeutronBuilder *theBertiniNeutron; - //G4LEPNeutronBuilder *theLEPNeutron; -}; - -#endif // STORKHPNEUTRONPHYSICSLIST_H diff --git a/G4STORK/include/StorkNeutronProcessBuilder.hh b/G4STORK/include/StorkNeutronProcessBuilder.hh deleted file mode 100755 index d9eec282..00000000 --- a/G4STORK/include/StorkNeutronProcessBuilder.hh +++ /dev/null @@ -1,88 +0,0 @@ -/* -StorkNeutronProcessBuilder.hh - -Created by: Liam Russell -Date: 23-02-2012 -Modified: - -Header file for StorkNeutronProcessBuilder class. - -Based on G4NeutronBuilder, this builder class sets up all neutron physics -processes and models (fission, capture, elastic, inelastic, and step limiters). - -*/ - -#ifndef STORKNEUTRONPROCESSBUILDER_H -#define STORKNEUTRONPROCESSBUILDER_H - -// Include G4-STORK headers -#include "StorkHadronFissionProcess.hh" -#include "StorkHadronCaptureProcess.hh" -#include "StorkNeutronInelasticProcess.hh" -#include "StorkHadronElasticProcess.hh" -#include "StorkHPNeutronBuilder.hh" -#include "StorkTimeStepLimiter.hh" -#include "StorkUserBCStepLimiter.hh" -#include "StorkZeroBCStepLimiter.hh" - -// Include Geant4 headers -#include "G4VNeutronBuilder.hh" -//#include "G4HadronElastic.hh" -#include "G4LFission.hh" -#include "G4NeutronRadCapture.hh" -#include "G4ParticleDefinition.hh" -#include "G4ParticleTable.hh" -#include "G4ProcessManager.hh" -#include "globals.hh" -#include "G4DiffuseElastic.hh" - -#include "StorkMaterial.hh" -#include "G4LogicalVolumeStore.hh" -// Include other headers -#include -#include - - -class StorkNeutronProcessBuilder -{ - public: - // Public member functions - - StorkNeutronProcessBuilder(std::vector* pBCVec, std::vector* rBCVec, G4String FSDirName, G4int KCalcType); - ~StorkNeutronProcessBuilder(); - - // Build and register the models - void Build(); - void RegisterMe(G4VNeutronBuilder * aB) - { - theModelCollections.push_back(aB); - } - - bool ExtractTemp(G4String name, G4double &temp); - - - private: - // Private member variables - - StorkNeutronInelasticProcess * theNeutronInelastic; - StorkHadronFissionProcess * theNeutronFission; - StorkHadronCaptureProcess * theNeutronCapture; - StorkHadronElasticProcess * theNeutronElastic; - StorkTimeStepLimiter * theStepLimiter; - StorkUserBCStepLimiter * TheUserBoundaryCond; - StorkZeroBCStepLimiter * TheZeroBoundaryCond; - - G4DiffuseElastic *theHighElasticModel; - //G4ChipsElasticModel *theHighElasticModel; - //G4HadronElastic *theHighElasticModel; - G4LFission *theHighFissionModel; - G4NeutronRadCapture *theHighCaptureModel; - - std::vector theModelCollections; - - G4int kCalcType; - G4String fsDirName; - G4bool wasActivated; -}; - -#endif // STORKNEUTRONPROCESSBUILDER_H diff --git a/G4STORK/include/StorkNeutronSD.hh b/G4STORK/include/StorkNeutronSD.hh deleted file mode 100755 index 77429122..00000000 --- a/G4STORK/include/StorkNeutronSD.hh +++ /dev/null @@ -1,125 +0,0 @@ -/* -StorkNeutronSD.hh - -Created by: Liam Russell -Date: 22-06-2011 -Modified: 11-03-2013 - -Header file for the StorkNeutronSD class. - -The StorkNeutronSD class is used to tally all the important hits and to preserve -any surviving or delayed neutrons. It needs to be used for any region that -may produce or consume neutrons, or any regions where survivors have an -opportunity to enter back into multiplying regions. - -Much of the simulation control that allows for reactor simulations occurs in -the ProcessHits() function of the class. - -*/ - -#ifndef STORKNEUTRONSD_H -#define STORKNEUTRONSD_H - -// Include G4-STORK headers -#include "StorkTallyHit.hh" -#include "StorkRunManager.hh" -#include "StorkPrimaryNeutronInfo.hh" -#include "StorkContainers.hh" -#include "StorkTrackInfo.hh" -#include "StorkProcessManager.hh" - -// Include Geant4 headers -#include "G4Timer.hh" -#include "G4VSensitiveDetector.hh" -#include "G4Neutron.hh" -#include "G4Gamma.hh" -#include "G4VProcess.hh" -#include "G4Track.hh" -#include "G4Step.hh" -#include "G4StepPoint.hh" -#include "G4HCofThisEvent.hh" -#include "G4TouchableHistory.hh" -#include "G4SDManager.hh" -#include "G4SteppingControl.hh" -#include "G4ThreeVector.hh" -#include "G4UnitsTable.hh" -#include "G4ios.hh" - -// Class forward declarations -class StorkRunManager; - - -class StorkNeutronSD : public G4VSensitiveDetector -{ - public: - // Public member functions - - // Constructor and destructor - StorkNeutronSD(G4String name, G4int KCalcType, G4bool instD = false, G4bool initialD = false); - ~StorkNeutronSD() {;} - - void Initialize(G4HCofThisEvent *HCE); - G4bool ProcessHits(G4Step *aStep,G4TouchableHistory *ROhist); - void EndOfEvent(G4HCofThisEvent *HCE); - - // Save the surviors and delayed neutron (for future runs) - void SaveSurvivors(const G4Track *aTrack); - void SaveDelayed(const G4Track *sTrack); - - - private: - // Private member functions - - // Print totals for each reaction type (fission, capture, etc) - void PrintCounterTotals() const; - - - private: - // Private member variables - - // Manager pointers - G4int prevTrackID; - G4String hitProcess; - StorkRunManager *runMan; - StorkProcessManager *procMan; - - G4int kCalcType; - - TallyHC *tallyHitColl; // Collection of tally hits - G4int HCID1; // Index of the hit collection - G4bool periodicBC; // Periodic boundary flag - G4bool instantDelayed; // Flag to make delayed neutrons prompt - G4bool sourcefileDelayed; // Flag to produce delayed neutrons from previous fission data. - G4bool precursorDelayed; - - // G4bool logDelayedSpectrum; // Flag to saved delayed neutron spectrum - G4double runEnd; // Time at the end of the run - - G4double totalLifetime; // Total lifetime of lost neutrons - G4int nLoss; // Total number of lost neutrons - G4int nProd; // Total number of prompt neutrons produced - G4int dProd; // Total number of delayed neutrons produced - - DblVector fnEnergy; // Energies of incident neutron in fissions - SiteVector fSites; // Sites where fission occurs - NeutronSources survivors; // Saved survivors - NeutronSources delayed; // Saved delayed neutrons - - - // DIAGNOSTIC COUNTERS - G4int nCap; - G4int nEsc; - G4int nFiss; - G4int nInel; - -#ifdef G4TIMESD - // Performance timing variables - G4Timer sdTimer; - G4Timer phTimer; - G4int cycles; - G4double cycleTime; - G4double totalSDTime; -#endif -}; - -#endif // STORKNEUTRONSD_H diff --git a/G4STORK/include/StorkParallelRunManager.hh b/G4STORK/include/StorkParallelRunManager.hh deleted file mode 100755 index 44346e4f..00000000 --- a/G4STORK/include/StorkParallelRunManager.hh +++ /dev/null @@ -1,95 +0,0 @@ -/* -StorkParallelRunManager.hh - -Created by: Liam Russell -Date: 07-08-2011 -Modified: 11-03-2013 - -Header for the StorkParallelRunManager class. - -This is the parallel run manager and it is derived from the StorkRunManager -class. The TOPC toolkit is used to communicate between the master and slave -processes. The simulation starts with the beamOn function where it sets up the -intial pointers and run counters. Then it initializes the run (begin of run -action), and goes into the do event loop. - -The three main steps of the parallel do event loop are: - - 1. GenerateEventInput - Generate primaries, random seed and event number. - This primary data is sent to a slave process. - 2. DoEvent - Initialize event with primary data and excute. Return the - results to the master process as event data. - 3. CheckEventResults - Send the event data to the run action class (only - on the master). The run tallies and stores - the event data. - -After all events finish, the run ends (end of run action) and the run action -performs analysis and updates the primary generator action. - -*/ - -#ifdef G4USE_TOPC - -#ifndef STORKPARALLELRUNMANAGER_H -#define STORKPARALLELRUNMANAGER_H - -#include "topc.h" -#include "StorkRunManager.hh" -#include "MarshaledStorkEventData.h" -#include "MarshaledStorkPrimaryData.h" -#include "MarshaledObj.h" -#include "G4StateManager.hh" - - -class StorkParallelRunManager : public StorkRunManager -{ - public: - // Public member functions - - // Constructor and destructor - StorkParallelRunManager(const StorkParseInput* infile); - virtual ~StorkParallelRunManager(); - - // Start the simulation - virtual void BeamOn(G4int n_event, const char* macroFile=0, - G4int n_select=-1); - // Process all of the events for a run - virtual void DoEventLoop(G4int n_event, const char* macroFile=0, - G4int n_select=-1); - // Initialize the run - virtual void RunInitialization(); - - - protected: - // Protected member functions - - // TOP-C static callback functions (locatable by TOP-C code) - static TOPC_BUF myGenerateEventInput(); - static TOPC_BUF myDoEvent(void *input); - static TOPC_ACTION myCheckEventResult(void *input, void *output); - - // Implementations of TOP-C functions (contain the actual instructions) - TOPC_BUF GenerateEventInput(); - TOPC_BUF DoEvent(void *input); - TOPC_ACTION CheckEventResult(void *input, void *output); - - protected: - // Protected member variables - - // Static pointer to singleton run manager - static StorkParallelRunManager *myRunManager; - - G4int i_event; // Current event id (number) - G4int numEvents; // Total number of events - G4long *slaveSeeds; // Random number seeds for the slaves - - // Marshalled data classes (sending and recieving) - MarshaledStorkPrimaryData *sendMPD; - MarshaledStorkEventData *sendMED; - MarshaledStorkPrimaryData *recMPD; - MarshaledStorkEventData *recMED; -}; - -#endif // STORKPARALLELRUNMANAGER_H - -#endif // G4USE_TOPC diff --git a/G4STORK/include/StorkParseInput.hh b/G4STORK/include/StorkParseInput.hh deleted file mode 100755 index 4bf5a040..00000000 --- a/G4STORK/include/StorkParseInput.hh +++ /dev/null @@ -1,355 +0,0 @@ -/* -StorkParseInput.hh - -Created by: Liam Russell -Date: 13-06-2011 -Modified: 11-03-2013 - -Header file for StorkParseInput class. - -StorkParseInput class is designed to read the input file and store all the -information so that it can be used by other classes later (through Get -functions). The class also prints a formatted table of the input to a given -output stream. - -*/ - -#ifndef STORKPARSEINPUT_H -#define STORKPARSEINPUT_H - -#include -#include -#include "Randomize.hh" -#include "globals.hh" -#include "G4ThreeVector.hh" -#include "BZR_Version_Info.hh" -#include "G4String.hh" -#include "StorkInterpVector.hh" -#include -#include "StorkMatPropManager.hh" -#include "StorkContainers.hh" -#include "StorkMatPropChange.hh" -#include "StorkInterpManager.hh" -#include "G4SystemOfUnits.hh" -#include "StorkSixVector.hh" - - - -class StorkParseInput -{ - public: - // Public member functions - - // Constructor and destructor - StorkParseInput(G4bool master=true); - ~StorkParseInput(); - - // Read and print the parsed input file - G4bool ReadInputFile(G4String filename); - G4int ConvertSide(G4String side); - void PrintInput(std::ostream *output) const; // Print input values to stream - G4bool FinalizeInputs(); - - G4bool DirectoryExists( const char* pzPath ); - - // Add world with default values to ParseInput - void AddWorldType(G4String name, StorkMatPropChangeVector defaults); - - // Set the version of Geant4 - void SetG4VersionString(G4String ver) { g4Version = ver; } - - // Get/Set functions - void SetRequiredInputs(G4String worldNam, G4int numRuns, G4int numEvents, G4int numPrimariesPerEvent, G4double runDur); - - - G4String GetWorld() const { return worldName; } - void SetWorld(G4String worldNam); - - G4int GetReactorMaterial() const { return reactorMat; } - void SetReactorMaterial(G4int reactorMaterial); - - G4ThreeVector GetWorldDimensions() const; - void SetWorldDimensions(G4double dim) { theWorldProps[MatPropPair(all,dimension)]=dim; } - - G4int GetKCalcType() const { return kCalcType; } - void SetKCalcType(G4int KCalcType) { kCalcType = KCalcType; } - - G4String GetCSDirName() const { return csDirName; } - void SetCSDirName(G4String CSDirName) { csDirName=CSDirName; } - - G4String GetFSDirName() const { return fsDirName; } - void SetFSDirName(G4String FSDirName) { fsDirName=FSDirName; } - - G4double GetInitialEnergy() const { return initEnergy; } - void SetInitialEnergy(G4double initialEnergy) { initEnergy=initialEnergy; } - - G4ThreeVector GetInitialSourcePos() const { return initialSourcePos; } - void SetInitialSourcePos(G4ThreeVector initSourcePosition) { initialSourcePos=initSourcePosition; } - - G4String GetUniformDistributionShape() const { return uniDisShape; } - void SetUniformDistributionShape(G4String uniformDisShape) { uniDisShape=uniformDisShape; } - - - StorkSixVector GetUniformDistDim() const - { - return uniDisDim; - } - void SetUniformDistDim(StorkSixVector uniformDisDim) - { - uniDisDim=uniformDisDim; - } - - G4int GetNumberOfRuns() const { return numberOfRuns; } - void SetNumberOfRuns(G4int numOfRuns) { numberOfRuns=numOfRuns; } - - G4int GetNumberOfEvents() const { return numberOfEvents; } - void SetNumberOfEvents(G4int numOfEvents) { numberOfEvents=numOfEvents; } - - G4int GetNumberOfPrimariesPerEvent() const - { return numberOfPrimariesPerEvent; } - void SetNumberOfPrimariesPerEvent(G4int numPrimaries) { numberOfPrimariesPerEvent=numPrimaries; } - - G4double GetRunDuration() const { return runDuration; } - void SetRunDuration(G4double runDur) { runDuration=runDur; } - - const G4int* GetMeshSteps() const { return numSteps; } - void SetMeshSteps(G4int numberSteps[]) { numSteps[0]=numberSteps[0]; numSteps[1]=numberSteps[1]; numSteps[2]=numberSteps[2];} - - G4int GetNumberOfConvergenceRuns() const { return convRuns; } - void SetNumberOfConvergenceRuns(G4int convergRuns) { convRuns=convergRuns; } - - G4double GetConvergenceLimit() const { return limitSE; } - void SetConvergenceLimit(G4double limSE) { limitSE=limSE; } - - - // Log/Initial Source Files and Options - G4bool OverrideInitRandomSeed() const { return overrideInitRandomSeed; } - G4long GetRandomSeed() const { return randomSeed; } - void SetRandomSeed(G4long randSeed); - - G4bool SaveResultsToFile() const { return logData; } - G4String GetResultsFile() const { return logFile; } - void SetResultsFile(G4String logFil); - - G4int SaveSourcesInterval() const { return saveSources; } - void SetSaveSourcesInterval(G4int sourceInterval) { saveSources=sourceInterval; } - - G4String GetSourceFile() const { return sourceFile; } - void SetSourceFile(G4String sourceFil) { sourceFile=sourceFil; } - - G4bool LoadInitialSources() const { return loadSources; } - - G4String GetInitialSourceFile() const { return initialSourceFile; } - void SetInitialSourceFile(G4String SourceFile); - - G4bool GetPrecursorDelayed() const { return precursorDelayed; } - G4String GetInitialDelayedFile() const { return initialfissionDataFile; } - void SetInitialDelayedFile(G4String DelayedFile); - - G4bool SaveFissionData() const { return saveFissionData; } - G4String GetFissionDataFile() const { return fissionDataFile; } - void SetFissionDataFile(G4String fissionFile); - - G4bool SaveTemperature() const { return saveTempData; } - G4String GetTemperatureDataFile() const { return tempFileName; } - void SetTemperatureDataFile(G4String temperatureFile); - - // Interpolation and world property changes - G4bool GetInterpStartCond() const {return interpStart;} - void SetInterpStartCond(G4bool interpStartCond) { interpStart=interpStartCond; } - - const StorkInterpManager* GetNSInterpolationManager() const - { - return &theMPInterpMan; - } - void SetNSInterpolationManager(G4String mat, G4String prop, G4String interpDataFile); - - StorkMatPropChangeVector GetIntialWorldProperties() const - { - return initialWorldProps; - } - void SetIntialWorldProperties(G4String mat, G4String prop, G4double val); - - // Simulation options - G4bool GetInstantDelayed() const{return instantDelayed;} - void SetInstantDelayed(G4bool instantDelay) { instantDelayed=instantDelay; } - - void GetPeriodicBCVector(std::vector* &perBC) const{perBC = periodicBC;} - void SetPeriodicBCVector(std::vector* pBC) { (*periodicBC)=(*pBC); } - - void GetReflectBCVector(std::vector* &refBC) const{refBC = reflectBC;} - void SetReflectBCVector(std::vector* rBC) { (*reflectBC)=(*rBC); } - - G4bool GetRenormalizeAfterRun() const {return normalize;} - void SetRenormalizeAfterRun(G4bool renormalize) { normalize=renormalize; } - - G4bool GetUniformDistribution() const {return uniformDis;} - void SetUniformDistribution(G4bool uniformSourceDis) { uniformDis=uniformSourceDis; } - - G4bool GetRunThermalModel() const { return RunThermalModel; } - void SetRunThermalModel(G4bool tracking) {RunThermalModel=tracking;} - - G4bool GetUniformDistWithDim() const {return uniformDisWithDim;} - void SetUniformDistWithDim(G4bool uniDisWithDim) { uniformDisWithDim=uniDisWithDim; } - - G4bool GetInterp() const { return interp; } - void SetInterp(G4bool yesno) {interp=yesno;} - - G4bool GetNeutronFluxCalc() const { return neutronFluxCalc;} - void SetNeutronFluxCalc(G4bool neutronFlux) { neutronFluxCalc = neutronFlux;} - - G4bool GetSourceFileDelayed() const {return sourcefileDelayed;} - - const G4double* GetEnergyRange() const { return energyRange;} - - const G4double* GetFluxRegion() const {return fluxCalcRegion;} - - const G4String GetFluxCalcShape() const {return fluxCalcShape;} - - G4ThreeVector GetOrigin() const {return Origin;} - void SetOrigin(G4ThreeVector orig) { Origin = orig;} - - // Reactor Power Output - G4double GetReactorPower() const { return reactorPower; } - void SetReactorPower(G4double power) {reactorPower = power;} - - //Heat Transfer - G4double GetHeatTransferCoefficient() const {return htc;} - - G4double GetAmbientTemperature() const {return T_infty;} - - G4double GetBaselineFissionRate() const {return baselineFissionRate;} - - G4double GetFissionToEnergyCoefficient() const {return FissionToEnergy;} - - - // Logging output stream - std::ostream* GetLogOutputStream() const { return logStream; } - - - - private: - // Private member functions - - // Check the input for errors - G4bool ErrorChecking(); - - // Helper function for setting initial world properties - void SetInitialPropertiesVector(); - - // Print the material-property pair (as a string) with units - G4String PrintMatPropPair(MatPropPair mpPair) const; - - private: - - // Flag for master process - G4bool isMaster; - - // GEANT4 version string - G4String g4Version; - - // Flag to keep track of fission energy deposition - G4bool RunThermalModel; - G4bool interp; - // Reactor Power - G4double reactorPower; - - // World choice and seed for random number generator - InitialPropertyMap theWorldProps; - - // World properties - G4String worldName; - G4int reactorMat; - G4int kCalcType; - G4String csDirName; - G4String fsDirName; - G4long randomSeed; - G4bool overrideInitRandomSeed; - - // World options - G4bool uniformDis; - G4String uniDisShape; - G4bool uniformDisWithDim; - StorkSixVector uniDisDim; - G4bool interpStart; - G4bool instantDelayed; - std::vector *reflectBC; - std::vector *periodicBC; - G4bool normalize; - G4bool neutronFluxCalc; - - //Delayed neutron options. - G4int theDelayedOption; - G4bool sourcefileDelayed; - G4bool precursorDelayed; - - // Number of runs, events and primaries per event - G4int numberOfRuns; - G4int numberOfEvents; - G4int numberOfPrimariesPerEvent; - G4double runDuration; - - //Energy range and volume name for neutron flux calculation. - G4double energyRange[2]; - G4String fluxCalcShape; - G4double fluxCalcRegion[4]; - - //Origin - G4ThreeVector Origin; - - // Initial neutron energy (default source) in MeV - G4double initEnergy; - - //Heat Transfer Coefficient - G4double htc; - - //Ambient Temperature. - G4double T_infty; - - //Baseline flux - G4double baselineFissionRate; - - //Conversion coefficient from flux to power. - G4double FissionToEnergy; - - // Initial neutron start position - G4ThreeVector initialSourcePos; - - // Shannon entropy mesh and convergence limits - G4int numSteps[3]; - G4double limitSE; - G4int convRuns; - - // Input and output data flags and files - std::ofstream *logStream; // Logging file (results) - G4bool logData; - G4String logFile; - G4int saveSources; // Save sources to file - G4String sourceFile; - G4bool loadSources; // Load initial sources from file - G4String initialSourceFile; - G4bool saveFissionData; // Save fission data to file - G4String fissionDataFile; - G4String initialfissionDataFile; //Initial loaded fission data file - G4bool saveTempData; - G4String tempFileName; - G4bool initialFissionData; - - - // Vector of data profile identifiers and file names - std::vector > theDataProfiles; - - - // Path to neutron data - G4String datapath; - - // Manager for all property-material interpolation vectors - StorkInterpManager theMPInterpMan; - StorkMatPropChangeVector initialWorldProps; - StorkMatPropManager *theMPMan; - - // Map for user-added worlds - std::map userWorlds; -}; - -#endif // STORKPARSEINPUT_H diff --git a/G4STORK/include/StorkPeriodicBCStepLimiter.hh b/G4STORK/include/StorkPeriodicBCStepLimiter.hh deleted file mode 100755 index 3eb3ab7c..00000000 --- a/G4STORK/include/StorkPeriodicBCStepLimiter.hh +++ /dev/null @@ -1,74 +0,0 @@ -/* -StorkPeriodicBCStepLimiter.hh - -Created by: Wesley Ford -Date: 22-06-2012 -Modified: 11-03-2013 - -Header file for the StorkPeriodicBCStepLimiter class. - -The boundary step limiter implements inifinite boundary conditions assuming the -world volume is symmetric about the origin. - -This class is roughly based off of (and inherits from) the G4StepLimiter class. - -*/ - - -#ifndef STORKPERIODICBCLIMITER_H -#define STORKPERIODICBCLIMITER_H - -// Include G4-STORK headers -#include "StorkProcessManager.hh" -#include "StorkPrimaryNeutronInfo.hh" -#include "StorkTrackInfo.hh" - -// Include Geant4 headers -#include "G4StepLimiter.hh" -#include "G4Track.hh" -#include "G4Box.hh" -#include "G4VParticleChange.hh" -//#include "G4Plane.hh" -#include "G4VPhysicalVolume.hh" -#include "G4String.hh" -#include "globals.hh" -#include "G4ThreeVector.hh" -#include "G4ParticleDefinition.hh" -#include "G4LogicalVolume.hh" -#include "G4VSolid.hh" - - -class StorkPeriodicBCStepLimiter : public G4StepLimiter -{ - public: - // Public member functions - - // Constructor and destructor - StorkPeriodicBCStepLimiter(const G4String& processName = - "StorkPeriodicBCStepLimiter", - G4String worldPhysName="worldPhysical" ); - virtual ~StorkPeriodicBCStepLimiter() {;} - - virtual G4double PostStepGetPhysicalInteractionLength( - const G4Track& aTrack, - G4double previousStepSize, - G4ForceCondition *condition); - - virtual G4bool IsApplicable(const G4ParticleDefinition &particle); - - virtual G4VParticleChange* PostStepDoIt(const G4Track &aTrack, - const G4Step &aStep); - - - private: - //Private member variables - - G4String worldName; // Name of world physical volume - StorkProcessManager *nsProcMan; // Pointer to process manager - StorkPrimaryNeutronInfo *pnInfo; - StorkTrackInfo *trackInfo; - - -}; - -#endif // STORKPERIODICBCLIMITER_H diff --git a/G4STORK/include/StorkPeriodicBCTransform.hh b/G4STORK/include/StorkPeriodicBCTransform.hh deleted file mode 100755 index 98e486a1..00000000 --- a/G4STORK/include/StorkPeriodicBCTransform.hh +++ /dev/null @@ -1,17 +0,0 @@ -#ifndef STORKPERIODICBCTRANSFORM_HH -#define STORKPERIODICBCTRANSFORM_HH - -#include "StorkBCTransform.hh" - -class StorkPeriodicBCTransform: public StorkBCTransform -{ - public: - StorkPeriodicBCTransform(); - StorkPeriodicBCTransform(G4ThreeVector n1, G4ThreeVector n2); - virtual ~StorkPeriodicBCTransform(); - void InitializeTransform(G4ThreeVector n1, G4ThreeVector n2); - protected: - private: -}; - -#endif // STORKPERIODICBCTRANSFORM_HH diff --git a/G4STORK/include/StorkPrimaryData.hh b/G4STORK/include/StorkPrimaryData.hh deleted file mode 100755 index f26515ca..00000000 --- a/G4STORK/include/StorkPrimaryData.hh +++ /dev/null @@ -1,73 +0,0 @@ -/* -StorkPrimaryData.hh - -Created by: Liam Russell -Date: 07-08-2011 -Modified: 11-03-2013 - -Definition for StorkPrimaryData class. - -This is a marshallable container class that is used to pass source information -for an event from the master to a slave. The following information is stored - - 1. The primary neutrons of an event. - 2. The random seed of the event. - 3. The index number of the event. - 4. Any material-property changes that need to be implemented on the slave - at the beginning of the event. - -*/ - -#ifndef STORKPRIMARYDATA_H -#define STORKPRIMARYDATA_H - -#include "StorkContainers.hh" - - -//MSH_include_begin -#include "MarshaledStorkNeutronData.h" -#include "MarshaledStorkMatPropChange.h" -//MSH_include_end -//MSH_BEGIN -class StorkPrimaryData -{ - public: - // Public member functions - - // Constructor and destructor - StorkPrimaryData() - { - primaries = new NeutronSources(); - propChanges = new StorkMatPropChangeVector; - } - virtual ~StorkPrimaryData() - { - if(primaries) delete primaries; - if(propChanges) delete propChanges; - - primaries = NULL; - propChanges = NULL; - } - - public: - // Public member variables - - NeutronSources *primaries; /*MSH: ptr_as_array - [elementType: StorkNeutronData] - [elementCount: { $ELE_COUNT = $THIS->primaries->size(); }] - [elementGet: { $ELEMENT = (*($THIS->primaries))[$ELE_INDEX]; }] - [elementSet: { $THIS->primaries->push_back(*$ELEMENT); }] - */ - - G4long eventSeed; //MSH: primitive - G4int eventNum; //MSH: primitive - StorkMatPropChangeVector *propChanges; /*MSH: ptr_as_array - [elementType: StorkMatPropChange] - [elementCount: { $ELE_COUNT = $THIS->propChanges->size(); }] - [elementGet: { $ELEMENT = (*($THIS->propChanges))[$ELE_INDEX]; }] - [elementSet: { $THIS->propChanges->push_back(*$ELEMENT); }] - */ -}; -//MSH_END - -#endif // STORKPRIMARYDATA_H diff --git a/G4STORK/include/StorkPrimaryGeneratorAction.hh b/G4STORK/include/StorkPrimaryGeneratorAction.hh deleted file mode 100755 index aa5c38b1..00000000 --- a/G4STORK/include/StorkPrimaryGeneratorAction.hh +++ /dev/null @@ -1,189 +0,0 @@ -/* -StorkPrimaryGeneratorAction.hh - -Created by: Liam Russell -Date: 22-06-2011 -Modified: 11-03-2013 - -Header for StorkPrimaryGeneratorAction class. - -This class is responsible for creating the primary neutrons from either the -initial StorkPrimaryNeutronGenerator class or from the survivors. It also -renormalizes the neutron population at the start of a run by -duplicating/deleting survivors randomly from the survivors list. It may also -load the initial distribution from a file. - -*/ - -#ifndef STORKPRIMARYGENERATORACTION_H -#define STORKPRIMARYGENERATORACTION_H - -// Include G4-STORK headers -#include "StorkContainers.hh" -#include "StorkPrimaryData.hh" -#include "StorkPrimaryNeutronGenerator.hh" -#include "StorkRunManager.hh" -#include "StorkParseInput.hh" -#include "StorkWorld.hh" -#include "StorkRunManager.hh" -#include "StorkProcessManager.hh" -#include "StorkMaterial.hh" -#include "StorkDelayedNeutron.hh" -#include "StorkSixVector.hh" - -// Include Geant4 headers -#include "G4Timer.hh" -#include "G4VUserPrimaryGeneratorAction.hh" -#include "G4Event.hh" -#include "globals.hh" -#include "G4ParticleDefinition.hh" -#include "G4ParticleTable.hh" -#include "G4ios.hh" -#include "G4String.hh" -#include "Randomize.hh" -#include "G4TransportationManager.hh" -#include "G4Navigator.hh" -#include "G4Material.hh" -#include "G4DynamicParticle.hh" -#include "G4NeutronHPFissionData.hh" -#include "G4SystemOfUnits.hh" - -// Include other headers -#include -#include -#include -#include -#include - - -class StorkRunManager; - -class StorkPrimaryGeneratorAction : public G4VUserPrimaryGeneratorAction -{ - public: - // Public member fuctions - - // Constructor and destructor - StorkPrimaryGeneratorAction(const StorkParseInput* infile, - G4bool master); - ~StorkPrimaryGeneratorAction(); - - // Update the survivor and delayed neutron distributions (end of run) - void UpdateSourceDistributions(const NeutronSources *nSource, - const NeutronSources *dnSource); - // Initialize the primaries for the current run - void InitializeRun(); - // Generate primary neutrons for an event - void GeneratePrimaries(G4Event*); - // Set the primaries for the current event - void SetPrimaries(StorkPrimaryData *pData); - // Get the primary data for an event - StorkPrimaryData* GetPrimaryData(G4int eventNum); - - // Get the total number of primaries/delayed neutron primaries - G4int GetNumPrimaries(); - G4int GetNumDNPrimaries(); - - // Set the number of events per run - void SetNumEvents(G4int numE) { numEvents = numE; }; - // Create the initial neutron source - void InitialSource(); - - // Disable renormalization of the number of survivors at the start of - // each run - void DisableNormalization() { normalize = false; } - - std::vector GetPrecursors(); - - void AddPrecursors(MSHSiteVector fSites, DblVector fEnergy); - - private: - // Private member funtions - - // Load neutron primary source from file - void LoadSource(G4String fname); - - // Add the delayed neutrons that are born in the current run and were produced from precursors to the - // survivors - void AddCurrentDelayed(); - - // Renormalize the number of survivors to initial number of primaries - void RenormalizeSurvivors(G4int numMissing); - // Shuffle the order of the survivors - void ShuffleSurvivors(G4int numShuffle, NeutronSources *origSurvivors); - - // Produce uniformly distributed positions in the world volume - void UniformPosition(StorkNeutronData* input); - - - - - private: - - G4bool initialSource; // Flag denotes whether initial source has been - // created - G4String sourceFile; // Filename of source file - - G4bool sourcefileDelayed; // Flag denotes whether an initial - - G4bool precursorDelayed; //Flag to indicate if precursors are used. - // delayed distribution is to be used - G4String delayedSourceFile; // Filename for initial delayed source - - G4bool normalize; // Flag denotes whether population is - // renormalized at the start of a new run - G4bool instantDelayed; // Flag denotes whether delayed neutrons are - // produced instantaneously - - G4double initEnergy; // Initial energy of source neutrons - G4ThreeVector origin; - G4String shape; // The shape to be used for the Uniform Distribution - G4double runEnd; // End time of the run - G4int numPrimaries; // Number of primary particles per event - G4int realNumPrimaries; // True number of primaries if normalization is - //not used - G4int numDNeutrons; // The number of delayed neutrons produced. - - G4int numEvents; // Number of events per run - G4int numDNPrimaries; // Number of delayed neutron primaries in the - // current run - G4double runDuration; //Run duration in ns. - - G4int numEntries; //Number of fission entries. - - G4ParticleDefinition *neutron; // Particle definition for neutron - - NeutronSources survivors; // Survivors of last run, source - // distribution of current run - NeutronList dNeutrons; // Remaining delayed neutrons - NeutronSources::iterator primaryIt; - NeutronSources currPrimaries; // Primaries for the current event - - StorkPrimaryNeutronGenerator nGen; // Neutron generator - - StorkRunManager *runMan; // Pointer to the run manager - StorkPrimaryData *primaryData; - - G4bool uniformDis; // Uniform source distribution flag - std::vector Precursors; //Precursor population - - - StorkDelayedNeutron* delayedNeutronGenerator; //The delayed neutron generator, uses and tracks precursors. - - StorkHadronFissionProcess* theFissionProcess; - - SiteVector fSites; - DblVector fnEnergy; - G4Navigator *theNav; - - G4double adjustmentFactor; - - - -#ifdef G4TIMEPG - G4Timer genTimer; - G4double totalGenTime; -#endif -}; - -#endif // STORKPRIMARYGENERATORACTION_H diff --git a/G4STORK/include/StorkPrimaryNeutronGenerator.hh b/G4STORK/include/StorkPrimaryNeutronGenerator.hh deleted file mode 100755 index 116afbb3..00000000 --- a/G4STORK/include/StorkPrimaryNeutronGenerator.hh +++ /dev/null @@ -1,53 +0,0 @@ -/* -StorkPrimaryNeutronGenerator.hh - -Created by: Liam Russell -Date: 06-22-2011 -Modified: 11-03-2013 - -Header for StorkPrimaryNeutronGenerator class. - -This class generators primary vertices for the neutrons based on a list of -neutron sources. The generator creates a vertex for each primary neutron, even -duplicates. - -*/ - -#ifndef STORKNEUTRONGENERATOR_H -#define STORKNEUTRONGENERATOR_H - -#include "G4PrimaryParticle.hh" -#include "G4PrimaryVertex.hh" -#include "StorkPrimaryNeutronInfo.hh" -#include "G4ParticleDefinition.hh" -#include "G4ParticleTable.hh" -#include "G4Event.hh" -#include "StorkContainers.hh" - -class StorkPrimaryNeutronGenerator -{ - public: - // Public member functions - - // Constructor and Destructor - StorkPrimaryNeutronGenerator() {;} - ~StorkPrimaryNeutronGenerator() {;} - - // Generate the primaries for the event - void GeneratePrimaryVertices(G4Event *evt, NeutronSources *nSource); - - // Set the particle type to neutrons - inline void SetParticleType(G4ParticleDefinition *nType) - { - neutron = nType; - } - - - private: - // Private member variable - - G4ParticleDefinition *neutron; - -}; - -#endif // STORKNEUTRONGENERATOR_H diff --git a/G4STORK/include/StorkPrimaryNeutronInfo.hh b/G4STORK/include/StorkPrimaryNeutronInfo.hh deleted file mode 100755 index 602e215d..00000000 --- a/G4STORK/include/StorkPrimaryNeutronInfo.hh +++ /dev/null @@ -1,72 +0,0 @@ -/* -StorkPrimaryNeutronInfo.hh - -Created by: Liam Russell -Date: 22-06-2011 -Modified: 11-03-2012 - -Definition of StorkPrimaryNeutronInfo class. - -Used to store the lifetime (duration) of the neutron. For both delayed and -prompt neutrons this will be the time since the fission that created the -neutrons (relative to the current global time). This is saved in the -local time information of the track (using a User Tracking Action). - -*/ - -#ifndef STORKPRIMARYNEUTRONINFO_H -#define STORKPRIMARYNEUTRONINFO_H - -#include "G4VUserPrimaryParticleInformation.hh" -#include "globals.hh" - - -class StorkPrimaryNeutronInfo : public G4VUserPrimaryParticleInformation -{ - public: - // Public member functions - - // Constructor and destructor - StorkPrimaryNeutronInfo(G4int numProcess = 4) - { - numHadProcess = numProcess; - eta = new G4double[numProcess]; - lifetime = 0.0; - weight = 1.0; - } - ~StorkPrimaryNeutronInfo() - { - delete [] eta; - } - - void Print() const {;} - - // Set and get lifetime - void SetLifeTime(G4double lTime) { lifetime = lTime; }; - G4double GetLifeTime() { return lifetime; }; - - // Set and get eta values (number of interaction lengths left) - void SetEta(G4double *nArray) - { - for(G4int i=0; i -class StorkQuad -{ - public: - - // Data types - typedef T1 first_type; - typedef T2 second_type; - typedef T3 third_type; - typedef T4 fourth_type; - - T1 first; - T2 second; - T3 third; - T4 fourth; - - // Default Constructor and destructor - StorkQuad() - :first(T1()), second(T2()), third(T3()), fourth(T4()) {} - ~StorkQuad() {} - - // Constructor - StorkQuad(const T1& x, const T2& y, const T3& z, const T4& w) - : first(x), second(y), third(z), fourth(w) {} - - // Copy constructor - template - StorkQuad(const StorkQuad &p) - : first(p.first), second(p.second), third(p.third), fourth(p.fourth) {} -}; - -#endif // STORKQUAD_HH_INCLUDED diff --git a/G4STORK/include/StorkReflectBCTransform.hh b/G4STORK/include/StorkReflectBCTransform.hh deleted file mode 100755 index 3d277c70..00000000 --- a/G4STORK/include/StorkReflectBCTransform.hh +++ /dev/null @@ -1,17 +0,0 @@ -#ifndef STORKREFLECTBCTRANSFORM_HH -#define STORKREFLECTBCTRANSFORM_HH - -#include "StorkBCTransform.hh" - -class StorkReflectBCTransform: public StorkBCTransform -{ - public: - StorkReflectBCTransform(); - StorkReflectBCTransform(G4ThreeVector n1); - virtual ~StorkReflectBCTransform(); - void InitializeTransform(G4ThreeVector n1); - protected: - private: -}; - -#endif // STORKREFLECTBCTRANSFORM_HH diff --git a/G4STORK/include/StorkRunAction.hh b/G4STORK/include/StorkRunAction.hh deleted file mode 100755 index 096208ab..00000000 --- a/G4STORK/include/StorkRunAction.hh +++ /dev/null @@ -1,205 +0,0 @@ -/* -StorkRunAction.hh - -Created by: Liam Russell -Date: 22-06-2011 -Modified: 11-03-2013 - -Header for StorkRunAction class. - -This class is responsible for most of the analysis of the results. At the -beginning of a run, all of the variables and containers are reinitialized. -Additionally, the primary generator's survivors and delayed lists are updated. -During a run, each event is tallied: running totals are kept of important -quantities and the survivors and delayed neutron sources are stored in buffers. -At the end of a run, the buffers are collated into single lists of neutron -sources. Also, the results for quantities such as k_run and k_eff are -calculated and printed to the output stream (screen or file). - -*/ - - -#ifndef STORKRUNACTION_H -#define STORKRUNACTION_H - -// Include G4-STORK headers -#include "StorkPrimaryGeneratorAction.hh" -#include "StorkContainers.hh" -#include "StorkEventData.hh" -#include "StorkParseInput.hh" -#include "StorkMatPropManager.hh" -#include "StorkInterpManager.hh" -#include "StorkProcessManager.hh" -#include "StorkHadronFissionProcess.hh" - -// Include Geant4 headers -#include "G4Timer.hh" -#include "G4Run.hh" -#include "G4HCofThisEvent.hh" -#include "G4ThreeVector.hh" -#include "G4DataVector.hh" -#include "G4UserRunAction.hh" -#include "G4Neutron.hh" -#include "G4TransportationManager.hh" - -// Include other headers -#include -#include -#include -#include -#include - -// Class forward declaration -class StorkPrimaryGeneratorAction; - - -class StorkRunAction : public G4UserRunAction -{ - public: - // Public member functions - - // Constructor and destructor - StorkRunAction(StorkPrimaryGeneratorAction *genPtr, - const StorkParseInput *fIn); - ~StorkRunAction(); - - // Actions taken at the beginning and end of the current run - void BeginOfRunAction(const G4Run *aRun); - void EndOfRunAction(const G4Run *aRun); - - // Unpack and combine tally data from events - void TallyEvent(const StorkEventData *eventData); - void CollateNeutronSources(); - - - // Update the source distributions of StorkPrimaryGeneratorAction - void UpdateSourceDistributions(); - // Update the value of the variable material-properties - void UpdateWorldProperties(G4double *values); - - // Write the survivors and delayed neutrons of this run to a file - void SaveSources(G4String fname, G4int runID, G4double runEnd); - // Save fission data to a file - G4bool WriteFissionData(G4String fname,G4int start); - - G4bool DirectoryExists( const char* pzPath ); - - // Set functions - void SetWorldDimensions(G4ThreeVector worldDims) - { - worldSize = worldDims; - } - void SaveFissionData(G4bool yesNo = true) { saveFissionData = yesNo; } - - // Get functions - G4double* GetRunResults() { return runResults; }; - G4double GetShannonEntropy() { return shannonEntropy[0]; }; - MSHSiteVector GetCurrentFissionSites() { return CurrentfnSites; } - DblVector GetCurrentFissionEnergy() { return CurrentfnEnergy; } - - - private: - // Private member functions - - // Calculate the Shannon entropy of the current run - G4double CalcShannonEntropy(G4int ***sites, G4int total); - // Calculate the meshing index of a 3D position - Index3D SpatialIndex(G4ThreeVector position) const; - //Calculate the neutron flux of the core - G4double CalcNeutronFlux(); - // Erase function - // This method is needed for the temperature changing since we only - // want the temperature change to depend on fisson that occured this run - void ResetCurrentFissionData(); - - private: - // Private member variables - - G4int kCalcType; - - G4double keff; // k_eff for the current run - G4double krun; // k_run for the current run - G4double runDuration; // Duration of the run - G4int numEvents; // Number of events per run - G4int totalFS; // Total number of fission sites - G4double avgLifetime; // Average lifetime of lost neutrons - G4int numNProduced; // Number of neutrons produced - G4int numDelayProd; // Number of delayed neutrons produced - G4int numNLost; // Number of neutrons lost - G4double runResults[8]; // Run results passed to run manager - G4int numSites; // Number of fission sites at the end of each run. - G4int prevNumSites; // Number of fission sites of the previous run. - G4int runID; //Current run ID. - G4bool renormalize; //Boolean flag if renormalization is used. - G4int prevNumSurvivors; //Previous number of survivors - G4int saveInterval; //Source and fission site/energy save interval. - - G4double tUnit; // Time unit for output - G4String rndmInitializer; // File containing random seed (optional) - G4bool saveFissionData; // Flag for saving fission data - G4bool RunThermalModel; // Flag to know if fission energy deposition is being kept track of - G4int numFDCollectionRuns; // Number of runs of collected fission data - - G4double shannonEntropy[2]; // Shannon entropy (fission sites, - // survivors) - G4double maxShannonEntropy; // Maximum Shannon entropy - G4int numSpatialSteps[3]; // Number of RS spatial steps in each - // dimension (3D) - G4ThreeVector worldSize; // Size of world - - G4double neutronFlux; //Neutron flux. - G4double reactorPower; //Reactor power. - G4bool updatePrecursors; //Flag to update precursors if a initial delayed file was provided. - - G4bool neutronFluxCalc; //Flag to calculate neutron flux. - - G4double EnergyRange[2]; //Energy range of the neutron flux calc. - G4int fn_index; //Current index for fission site /energy. - G4int save_index; //Save index for fission site/energy. - G4ThreeVector Origin; //Current set origin. - G4double fluxCalcRegion[4]; //Flux region. - G4String fluxCalcShape; //Shape of the flux integration region. - - - // Output stream (file or stdout) - std::ostream *output; - - // Storage containers - NeutronSources survivors; - NeutronSources delayed; - NeutronSources *survivorsBuffer; - NeutronSources *delayedBuffer; - G4int ***fSites; - G4int ***sSites; - DblVector fnEnergies; - MSHSiteVector fnSites; - MSHSiteVector CurrentfnSites; - DblVector CurrentfnEnergy; - G4int numRuns; - G4int primariesPerRun; - - // Pointers to other classes - StorkPrimaryGeneratorAction *genAction; - const StorkParseInput *infile; - - // Timer for the run - G4Timer runTimer; - - // Variable material-property variables - WorldPropertyMap worldPropMap; - G4int* nameLen; - const StorkInterpManager *theMPInterpMan; - G4double* variableProps; - - //Flag to save the run data (fission data and survivor data) - G4bool saveRundata; - - -#ifdef G4TIMERA - // Performance timer - G4Timer runCalcTimer; - G4double totalRunCalcTime; -#endif -}; - -#endif // STORKRUNACTION_H diff --git a/G4STORK/include/StorkRunManager.hh b/G4STORK/include/StorkRunManager.hh deleted file mode 100755 index efbd0fc4..00000000 --- a/G4STORK/include/StorkRunManager.hh +++ /dev/null @@ -1,199 +0,0 @@ -/* -StorkRunManager.hh - -Created by: Liam Russell -Date: 22-06-2011 -Modified: 09-07-2012 - -Header for StorkRunManager class. - -This class is the single processor run manager. It is responsible for starting -the runs, generating the events, and passing information between the event, -run and primary generator actions. It also checks to make sure the source -distribtion converges within the given limit (default is 3%). - -*/ - -#ifndef STORKRUNMANAGER_H -#define STORKRUNMANAGER_H - -// Include G4-STORK header files -#include "StorkPrimaryGeneratorAction.hh" -#include "StorkRunAction.hh" -#include "StorkEventAction.hh" -#include "StorkHeatTransfer.hh" -#include "StorkWorld.hh" -#include "StorkInterpVector.hh" -#include "StorkParseInput.hh" -#include "StorkMatPropManager.hh" -#include "StorkContainers.hh" -#include "StorkInterpManager.hh" -#include "StorkMatPropChange.hh" - -// Include Geant4 header files -#include "G4RunManager.hh" -#include "G4UImanager.hh" -#include "G4Event.hh" -#include "G4DataVector.hh" -#include "G4HCofThisEvent.hh" -#include "G4EventManager.hh" - -// Include other header files -#include -#include -#include -#include - - -// Class forward declarations -class StorkPrimaryGeneratorAction; -class StorkRunAction; -class StorkEventAction; -class StorkWorld; - - -class StorkRunManager: public G4RunManager -{ - public: - // Public member functions - - // Constructor and destructor - StorkRunManager(const StorkParseInput* infile); - StorkRunManager(); - virtual ~StorkRunManager(); - - void InitializeRunData(const StorkParseInput* infile); - void InitializeRunData(G4double runDur, G4int numberRuns, G4int numSaveInterval, G4String saveFileName, G4bool interpStartCondition, - const StorkInterpManager* theMPInterpManager, G4double convergenceLim, G4int numConvRuns, G4bool saveFissionDataCond, - G4String fissionDataFile, std::ostream *logOutput, G4bool temperatureTracking,G4double nuclearReactorPower, - G4bool saveTemperature, G4String temperatureDataFile); - - // Starts the simulation - virtual void BeamOn(G4int n_event, const char* macroFile=0, - G4int n_select=-1); - // Process all events for each run - virtual void DoEventLoop(G4int n_event, const char* macroFile=0, - G4int n_select=-1); - // Initialize the simulation for the current run - virtual void RunInitialization(); - - // Set the total number of runs - void SetNumRuns(G4int num) { numRuns = num; } - - - // Print simulation averaged results to the output stream - void OutputResults(); - - // Save the source distribution of the current run to a file - void SaveSourceDistribution(G4String fname); - - //save the fission distribution of the current run to a file. - void SaveFissionDistribution(G4String name); - - // Get functions - G4double GetRunDuration() { return runDuration; } - G4double GetRunStart() { return runStart; } - G4double GetRunEnd() { return runEnd; } - G4bool GetSourceConvergence() { return sourceConverged; } - StorkWorld* GetWorld() const {return worldPointerCD;} - - - protected: - // Protected member functions - - // Add the results from the current run to the full and averaged results - void TallyRunResults(); - - // Check whether the source has converged - G4bool UpdateCheckSourceConvergence(); - - // Rebuild the world with new properties - void UpdateWorld(StorkMatPropChangeVector theChanges); - - // Get the current value of a variable material property - G4double GetWorldProperty(MatPropPair matProp); - - // Initialize variables at the start of the simulation - virtual void InitializeVar(G4int n_event); - - // Average the results from all runs with source convergence - void AverageRunResults(); - - protected: - // Protected member variables - StorkHeatTransfer* heatTransfer; - G4int numRuns; // Total number of runs for the simulation - - // G4double heatTransferCoefficient; - //G4double T_infinity; - - // Source distribution output - G4int saveInterval; // Interval at which source distribution is - // saved to file - G4String saveFile; // Base source distribution file name - G4int numRunOutputWidth; // Width of characters needed to write max - // runs - - // Fission distribution output - G4bool saveFissionData; // Flag to signal saving fission data - G4String fissionFile; // Output file for fission data - - // Run timing - G4double runDuration; // Duration of a run (ns) - G4double runStart; // Start time of the current run (ns) - G4double runEnd; // End time of the current run (ns) - - // Convergence variables - G4bool sourceConverged; // Flag indicates source has converged - G4double convergenceLimit; // Required convergence precision - G4double *seSelect; // Current selection of Shannon entropy - // being tested for convergence - - G4int totalConv; // Total number of SE values needed for - // convergence - G4int convergeStop; - G4int nConv; // Run when convergence achieved - - - // Material temperature output - G4bool saveMatTemp; // Flag to output the temperature of all materails - G4String matTempFile; // Output file for material temperature - G4bool RunThermalModel; // Flag to track fission and - // change energy acordingly - G4bool interp; - G4Navigator* theNavigator; // Navigator - G4double reactorPower; // Power output of the reactor - G4bool fMap; //Fission Map boolean flag. - MSHSiteVector fnSites; // Temporary storage for fission sites - - // Class pointers - StorkPrimaryGeneratorAction *genAction; - StorkRunAction *runAction; - StorkEventAction *eventAction; - StorkWorld *worldPointerCD; - static G4EventManager *EventMan; - const StorkInterpManager* theMPInterpMan; - - // Run action data - G4double* runData[8]; - G4double avgRunData[9]; - - // Interpolation of world parameters - G4bool interpStartCond; // Flag to start interpolation at first run - G4bool interpStarted; // Flag indicates interpolation started - G4int runInterpStarted; // Run number at start of interpolation - G4double timeOffset; // Time at start of interpolation - G4double *propValues; // Current values of variable world - // properties - - // Output stream (file or stdout) - std::ostream *output; - G4double frac; - - private: - - - -}; - -#endif // STORKRUNMANAGER_H diff --git a/G4STORK/include/StorkSixVector.hh b/G4STORK/include/StorkSixVector.hh deleted file mode 100755 index 759952b5..00000000 --- a/G4STORK/include/StorkSixVector.hh +++ /dev/null @@ -1,65 +0,0 @@ -#ifndef STORKSIXVECTOR_H -#define STORKSIXVECTOR_H - -template -class StorkSixVector -{ - public: - StorkSixVector() - { - for(G4int i=0;i<6;i++) - { - data[i]=0.; - } - } - ~StorkSixVector() - { - - } - StorkSixVector(T one,T two,T three,T four,T five,T six) - { - data[0]=one; - data[1]=two; - data[2]=three; - data[3]=four; - data[4]=five; - data[5]=six; - } - StorkSixVector(T* dataP) - { - for(G4int i=0;i<6;i++) - { - data[i]=dataP[i]; - } - } - T& operator [] (G4int a) - { - return (this->data[a]); - } - T operator [] (G4int a) const - { - return (this->data[a]); - } - StorkSixVector& operator = (T* dataP) - { - for(G4int i=0;i<6;i++) - { - data[i]=dataP[i]; - } - return *this; - } - StorkSixVector& operator = (StorkSixVector dataP) - { - for(G4int i=0;i<6;i++) - { - data[i]=dataP[i]; - } - return *this; - } - T data[6]; - protected: - private: - -}; - -#endif // STORKSIXVECTOR_H diff --git a/G4STORK/include/StorkSteppingAction.hh b/G4STORK/include/StorkSteppingAction.hh deleted file mode 100755 index 6878eb80..00000000 --- a/G4STORK/include/StorkSteppingAction.hh +++ /dev/null @@ -1,44 +0,0 @@ -// -// StorkSteppingAction.hh -// G4-STORK_AT -// -// Created by Andrew Tan on 2014-07-12. -// Copyright (c) 2014 andrewtan. All rights reserved. -// -#ifndef _STORKSTEPPINGACTION_H_ -#define _STORKSTEPPINGACTION_H_ - -#include "G4UserSteppingAction.hh" -#include "G4SteppingManager.hh" -#include "G4UserEventAction.hh" -#include "G4Step.hh" -#include "G4Track.hh" -#include "G4ProcessType.hh" -#include "G4HadronicProcessType.hh" -#include "G4TransportationManager.hh" -#include "StorkEventAction.hh" -#include "StorkHadProjectile.hh" -#include "StorkHadronFissionProcess.hh" -#include "StorkProcessManager.hh" -#include "G4FissionFragmentGenerator.hh" - -class StorkSteppingAction: public G4UserSteppingAction -{ - public: - StorkSteppingAction(StorkEventAction* eventAction); - virtual ~StorkSteppingAction(); - - //virtual void UserSteppingAction(const G4Step* theStep); - - protected: - - G4SteppingManager *SteppingMan; - StorkEventAction *myEventAction; - - - - - -}; - -#endif diff --git a/G4STORK/include/StorkTallyHit.hh b/G4STORK/include/StorkTallyHit.hh deleted file mode 100755 index b8227e38..00000000 --- a/G4STORK/include/StorkTallyHit.hh +++ /dev/null @@ -1,71 +0,0 @@ -/* -StorkTallyHit.hh - -Created by: Liam Russell -Date: 18-07-2011 -Modified: 11-03-2013 - -Header for StorkTallyHit class. - -Hit used for each SD to track the number of neutrons lost (capture, loss -or fission), the number of neutrons produced in n2n, and the lifetime of the -lost neutrons. - -*/ - -#ifndef STORKTALLYHIT_H -#define STORKTALLYHIT_H - -#include "G4VHit.hh" -#include "G4THitsCollection.hh" -#include "StorkContainers.hh" - - -class StorkTallyHit : public G4VHit -{ - public: - // Public member functions - - // Constructor and destructor - StorkTallyHit(); - ~StorkTallyHit() {;} - - // Print hit to screen - void Print(); - - // Get and set functions for member variables - void SetTotalLifetime(G4double life) { totalLifetime = life; } - G4double GetTotalLifetime() { return totalLifetime; } - void SetNLost(G4int numLost) { nLoss = numLost; } - G4int GetNLost() { return nLoss; } - void SetNProd(G4int numProd) { nProd = numProd; } - G4int GetNProd() { return nProd; } - void SetDProd(G4int numDelayProd) { dProd = numDelayProd; } - G4int GetDProd() { return dProd; } - - void SetFissionSites(SiteVector sites) { fSites = sites; } - const SiteVector* GetFissionSites() { return &fSites; } - void SetFissionEnergies(DblVector ens) { fnEnergy = ens; } - const DblVector* GetFissionEnergies() { return &fnEnergy; } - void SetSurvivors(NeutronSources sList) { survivors = sList; } - const NeutronSources* GetSurvivors() { return &survivors; } - void SetDelayed(NeutronSources dList) { delayed = dList; } - const NeutronSources* GetDelayed() { return &delayed; } - - - private: - // Private member variables - - G4double totalLifetime; // Total lifetime of lost neutrons - G4int nLoss; // Number of neutrons lost - G4int nProd; // Number of neutrons produced - G4int dProd; // Number of delayed neutrons produced - DblVector fnEnergy; // Fission incident neutron energies - SiteVector fSites; // Positions of fissions - NeutronSources survivors; // Survivors vector - NeutronSources delayed; // Delayed neutrons vector -}; - -typedef G4THitsCollection TallyHC; - -#endif // STORKTALLYHIT_H diff --git a/G4STORK/include/StorkTimeStepLimiter.hh b/G4STORK/include/StorkTimeStepLimiter.hh deleted file mode 100755 index 9e17faaa..00000000 --- a/G4STORK/include/StorkTimeStepLimiter.hh +++ /dev/null @@ -1,50 +0,0 @@ -/* -StorkTimeStepLimiter.hh - -Created by: Liam Russell -Date: 29-02-2012 -Modified: 2011 - -Header file for the StorkTimeStepLimiter class. - -The StorkTimeStepLimiter class is used to ensure particles cannot move past the -end of the current run (time limited). The proposed step is based on the current -velocity of the neutron and the time left in the run. This process is included -so that the neutrons stop at the end of the interval without undergoing an -interaction, and thus resetting the 'theNumberOfInteractionLengthLeft' counter. - -This class is roughly based off of (and inherits from) the G4StepLimiter class. - -*/ - -#ifndef NSSTEPLIMITER_H -#define NSSTEPLIMITER_H - -#include "G4StepLimiter.hh" -#include "G4Track.hh" -#include "StorkRunManager.hh" - - -class StorkTimeStepLimiter : public G4StepLimiter -{ - public: - // Public member functions - - // Constructors and destructors - StorkTimeStepLimiter(const G4String& processName = - "StorkTimeStepLimiter" ); - virtual ~StorkTimeStepLimiter() {;} - - // Get the max distance neutron can travel during the current run - virtual G4double PostStepGetPhysicalInteractionLength( - const G4Track& aTrack, - G4double previousStepSize, - G4ForceCondition *condition); - - private: - // Private member variables - - StorkRunManager *runMan; -}; - -#endif // NSSTEPLIMITER_H diff --git a/G4STORK/include/StorkTrackInfo.hh b/G4STORK/include/StorkTrackInfo.hh deleted file mode 100755 index 6e757a2f..00000000 --- a/G4STORK/include/StorkTrackInfo.hh +++ /dev/null @@ -1,62 +0,0 @@ -/* -StorkTrackInfo.hh - -Created by: Liam Russell -Date: 12-03-2012 -Modified: 11-03-2013 - -Implementation of StorkTrackInfo class. - -This class is used to attach a particle weight (for combing) to a track -by deriving it from the G4VUserTrackInformation class. The track information -also is used to StorkPrimaryNeutronInfo for neutrons created by the -StorkUserBCStepLimiter process. - -*/ - -#ifndef STORKTRACKINFO_H -#define STORKTRACKINFO_H - -#include "G4VUserTrackInformation.hh" -#include "StorkPrimaryNeutronInfo.hh" - - -class StorkTrackInfo : public G4VUserTrackInformation -{ - public: - // Public member functions - - // Constructor and destructor - StorkTrackInfo(G4double aNum = 1.0) - { - weight = aNum; - pnInfo = NULL; - } - virtual ~StorkTrackInfo() - { - if(pnInfo) delete pnInfo; - } - - // Get and set weight - void SetWeight(G4double pWeight) { weight = pWeight; }; - G4double GetWeight() { return weight; }; - - // Get and set primary neutron info - void SetStorkPrimaryNeutronInfo(StorkPrimaryNeutronInfo *pnInfoPtr) - { - pnInfo = pnInfoPtr; - } - StorkPrimaryNeutronInfo* GetStorkPrimaryNeutronInfo() const - { - return pnInfo; - } - - - private: - // Public member variables - - G4double weight; - StorkPrimaryNeutronInfo *pnInfo; -}; - -#endif // STORKTRACKINFO_H diff --git a/G4STORK/include/StorkTriple.hh b/G4STORK/include/StorkTriple.hh deleted file mode 100755 index 121cf698..00000000 --- a/G4STORK/include/StorkTriple.hh +++ /dev/null @@ -1,48 +0,0 @@ -/* -StorkTriple.hh - -Created by: Liam Russell -Date: 14-06-2011 -Modified: 11-03-2013 - -Template class designed to store three objects (can be different types). - -*/ - - -#ifndef STORKTRIPLE_HH_INCLUDED -#define STORKTRIPLE_HH_INCLUDED - - -template -class StorkTriple -{ - public: - - // Data types - typedef T1 first_type; - typedef T2 second_type; - typedef T3 third_type; - - T1 first; - T2 second; - T3 third; - - // Default constructor and destructor - StorkTriple() : first(T1()), second(T2()), third(T3()) {} - ~StorkTriple() {} - - // Constructor - StorkTriple(const T1& x, const T2& y, const T3& z) - : first(x), second(y), third(z) {} - - // Set data members - void Set(const T1& x, const T2& y, const T3& z) - { - first = x; - second = y; - third = z; - } -}; - -#endif // STORKTRIPLE_HH_INCLUDED diff --git a/G4STORK/include/StorkTripleFloat.hh b/G4STORK/include/StorkTripleFloat.hh deleted file mode 100755 index 857dcf66..00000000 --- a/G4STORK/include/StorkTripleFloat.hh +++ /dev/null @@ -1,42 +0,0 @@ -/* -StorkTripleFloat.hh - -Created by: Liam Russell -Date: 07-08-2011 -Modified: 17-02-2011 - -Class used to replace G4ThreeVector for simple data storage and marshalling. - -*/ - -#ifndef TRIPLEFLOAT_H -#define TRIPLEFLOAT_H - -#include "G4ThreeVector.hh" - -//MSH_BEGIN -class StorkTripleFloat -{ - public: - // Public member functions - - StorkTripleFloat() {} - StorkTripleFloat(G4ThreeVector &v3) { data = v3; }; - StorkTripleFloat(const G4ThreeVector &v3) { data = v3; } - ~StorkTripleFloat() {} - - G4double& operator[] (G4int i) { return data[i]; }; - G4ThreeVector GetData() {return data;} - - public: - // Public member variables - - G4ThreeVector data; //MSH: primitive - - void set(const G4ThreeVector coords) { data = coords;} - - -}; -//MSH_END - -#endif // TRIPLEFLOAT_H diff --git a/G4STORK/include/StorkUnion.hh b/G4STORK/include/StorkUnion.hh deleted file mode 100755 index 213eddab..00000000 --- a/G4STORK/include/StorkUnion.hh +++ /dev/null @@ -1,27 +0,0 @@ -#include "G4UnionSolid.hh" -#include "G4ThreeVector.hh" -#include "G4String.hh" -#include "G4VSolid.hh" -#include -#include - - -typedef std::pair solidPos; -typedef std::vector solidList; - -class StorkUnion -{ - public: - StorkUnion(solidList* List); - ~StorkUnion(void); - - solidPos GetUnionSolid(G4String name); - solidList GetSolidList(void) - { - return *Unions; - } - - - private: - solidList* Unions; -}; diff --git a/G4STORK/include/StorkUnionSolid.hh b/G4STORK/include/StorkUnionSolid.hh deleted file mode 100755 index 2532a030..00000000 --- a/G4STORK/include/StorkUnionSolid.hh +++ /dev/null @@ -1,164 +0,0 @@ -// -// ******************************************************************** -// * License and Disclaimer * -// * * -// * The Geant4 software is copyright of the Copyright Holders of * -// * the Geant4 Collaboration. It is provided under the terms and * -// * conditions of the Geant4 Software License, included in the file * -// * LICENSE and available at http://cern.ch/geant4/license . These * -// * include a list of copyright holders. * -// * * -// * Neither the authors of this software system, nor their employing * -// * institutes,nor the agencies providing financial support for this * -// * work make any representation or warranty, express or implied, * -// * regarding this software system or assume any liability for its * -// * use. Please see the license in the file LICENSE and URL above * -// * for the full disclaimer and the limitation of liability. * -// * * -// * This code implementation is the result of the scientific and * -// * technical work of the GEANT4 collaboration. * -// * By using, copying, modifying or distributing the software (or * -// * any work based on the software) you agree to acknowledge its * -// * use in resulting scientific publications, and indicate your * -// * acceptance of all terms of the Geant4 Software license. * -// ******************************************************************** -// -// -// $Id$ -// -// -// class StorkUnionSolid -// -// Class description: -// -// Class for description of union of two CSG solids. - -// History: -// -// 12.09.98 V.Grichine: created -// -// -------------------------------------------------------------------- -#ifndef STORKUNIONSOLID_HH -#define STORKUNIONSOLID_HH - -#include "G4BooleanSolid.hh" -#include "G4VSolid.hh" - -#include "StorkSixVector.hh" -#include "G4RotationMatrix.hh" -#include "G4ThreeVector.hh" -#include "G4Transform3D.hh" -#include "G4AffineTransform.hh" -#include - -enum ShapeEnum {cylUnit, cubicUnit, sphUnit}; -enum DirEnum {right, left, up, down, above, below}; - -class StorkUnionSolid : public G4BooleanSolid -{ - public: // with description - - StorkUnionSolid( const G4String& pName, G4VSolid* pSolidA , G4VSolid* pSolidB, ShapeEnum shape, StorkSixVector regDim, G4ThreeVector offset=G4ThreeVector(0.,0.,0.) ) ; - - StorkUnionSolid( const G4String& pName, G4VSolid* pSolidA, G4VSolid* pSolidB, G4RotationMatrix* rotMatrix, const G4ThreeVector& transVector, - ShapeEnum shape, StorkSixVector regDim, G4ThreeVector offset=G4ThreeVector(0.,0.,0.) ) ; - - StorkUnionSolid( const G4String& pName, G4VSolid* pSolidA , G4VSolid* pSolidB , const G4Transform3D& transform, - ShapeEnum shape, StorkSixVector regDim, G4ThreeVector offset=G4ThreeVector(0.,0.,0.) ) ; - -// StorkUnionSolid( StorkUnionSolid* solid, G4double addRegion[], ShapeEnum shape, DirEnum dir) ; - - virtual ~StorkUnionSolid() ; - - G4GeometryType GetEntityType() const ; - - G4VSolid* Clone() const; - - public: // without description - - StorkUnionSolid(__void__&); - // Fake default constructor for usage restricted to direct object - // persistency for clients requiring preallocation of memory for - // persistifiable objects. - - StorkUnionSolid(const StorkUnionSolid& rhs); - StorkUnionSolid& operator=(const StorkUnionSolid& rhs); - // Copy constructor and assignment operator. - - G4bool CalculateExtent( const EAxis pAxis, - const G4VoxelLimits& pVoxelLimit, - const G4AffineTransform& pTransform, - G4double& pMin, G4double& pMax ) const ; - - EInside Inside( const G4ThreeVector& p ) const ; - - G4ThreeVector SurfaceNormal( const G4ThreeVector& p ) const ; - - G4double DistanceToIn( const G4ThreeVector& p, - const G4ThreeVector& v ) const ; - - G4double DistanceToIn( const G4ThreeVector& p ) const ; - - G4double DistanceToIn( const G4ThreeVector& p, G4double minDist) const; - - G4double DistanceToOut( const G4ThreeVector& p, - const G4ThreeVector& v, - const G4bool calcNorm=false, - G4bool *validNorm=0, - G4ThreeVector *n=0 ) const ; - - G4double DistanceToOut( const G4ThreeVector& p ) const ; - - - G4bool InsideRegion( const G4ThreeVector& p ) const ; - - G4bool DistInRegion( const G4ThreeVector& p, - const G4ThreeVector& v ) const ; - - G4double DistInRegion( const G4ThreeVector& q) const ; - - void AddRegionToMe( DirEnum dir, StorkSixVector regionDim ); - - void ComputeDimensions( G4VPVParameterisation* p, - const G4int n, - const G4VPhysicalVolume* pRep ) ; - - void DescribeYourselfTo ( G4VGraphicsScene& scene ) const ; - G4Polyhedron* CreatePolyhedron () const ; - - ShapeEnum GetRegionShape() const - { - return regShape; - } - void SetRegionShape(ShapeEnum shape) - { - regShape=shape; - } - StorkSixVector GetRegionDim() const - { - return regDim; - } - void SetRegionDim(StorkSixVector regionDim) - { - regDim=regionDim; - } - G4ThreeVector const GetRegionOffSet() const - { - return regOffSet; - } - void SetRegionOffSet(G4ThreeVector offSet) - { - regOffSet=offSet; - } - //G4NURBS* CreateNURBS () const ; - - private: - - ShapeEnum regShape; - StorkSixVector regDim; - G4ThreeVector regOffSet; - - -}; - -#endif diff --git a/G4STORK/include/StorkUserBCStepLimiter.hh b/G4STORK/include/StorkUserBCStepLimiter.hh deleted file mode 100755 index 34c3888b..00000000 --- a/G4STORK/include/StorkUserBCStepLimiter.hh +++ /dev/null @@ -1,89 +0,0 @@ -/* -StorkUserBCStepLimiter.hh - -Created by: Wesley Ford -Date: 22-06-2012 -Modified: 11-03-2013 - -Header file for the StorkUserBCStepLimiter class. - -The boundary step limiter implements inifinite boundary conditions assuming the -world volume is symmetric about the origin. - -This class is roughly based off of (and inherits from) the G4StepLimiter class. - -*/ - - -#ifndef STORKPERIODICBCLIMITER_H -#define STORKPERIODICBCLIMITER_H - -// Include G4-STORK headers -#include "StorkProcessManager.hh" -#include "StorkPrimaryNeutronInfo.hh" -#include "StorkTrackInfo.hh" -#include "StorkPeriodicBCTransform.hh" -#include "StorkReflectBCTransform.hh" - -// Include Geant4 headers -#include "G4StepLimiter.hh" -#include "G4Track.hh" -#include "G4Box.hh" -#include "G4VParticleChange.hh" -//#include "G4Plane.hh" -#include "G4VPhysicalVolume.hh" -#include "G4String.hh" -#include "globals.hh" -#include "G4ThreeVector.hh" -#include "G4ParticleDefinition.hh" -#include "G4LogicalVolume.hh" -#include "G4VSolid.hh" - - -class StorkUserBCStepLimiter : public G4StepLimiter -{ - public: - // Public member functions - - // Constructor and destructor - StorkUserBCStepLimiter(std::vector* PeriodicBC, std::vector* ReflectBC, - const G4String& processName = "StorkUserBCStepLimiter", - G4String worldPhysName="worldPhysical" ); - - virtual ~StorkUserBCStepLimiter() - { - if(BCTransform) - { - for(G4int i=0; i<6; i++) - { - if(BCTransform[i]) - delete BCTransform[i]; - } - } - } - - virtual G4double PostStepGetPhysicalInteractionLength( - const G4Track& aTrack, - G4double previousStepSize, - G4ForceCondition *condition); - - virtual G4bool IsApplicable(const G4ParticleDefinition &particle); - - virtual G4VParticleChange* PostStepDoIt(const G4Track &aTrack, - const G4Step &aStep); - - G4ThreeVector GetNormal(int side); - - - private: - //Private member variables - - G4String worldName; // Name of world physical volume - StorkProcessManager *nsProcMan; // Pointer to process manager - StorkPrimaryNeutronInfo *pnInfo; - StorkTrackInfo *trackInfo; - StorkBCTransform* BCTransform[6]; - std::vector zeroSides; -}; - -#endif // STORKPERIODICBCLIMITER_H diff --git a/G4STORK/include/StorkVWorldConstructor.hh b/G4STORK/include/StorkVWorldConstructor.hh deleted file mode 100755 index f590ebc0..00000000 --- a/G4STORK/include/StorkVWorldConstructor.hh +++ /dev/null @@ -1,153 +0,0 @@ -/* -StorkVWorldConstructor.hh - -Created by: Liam Russell -Date: 23-05-2012 -Modified: 11-03-2013 - -Header for StorkVWorldConstructor class. - -This class is the base class used by all of the world constructor classes. -It contains some of the major functions common to all the world constructors. -The main purpose of this class is to simplify coding else where in the code -(using polymorphism) and to create a better defined hierarchy. -*/ - -#ifndef STORKWORLDCONSTRUCTOR_H -#define STORKWORLDCONSTRUCTOR_H - -// Include G4-STORK headers -#include "StorkMaterial.hh" -#include "StorkMatPropManager.hh" -#include "StorkContainers.hh" -#include "StorkParseInput.hh" -#include "StorkNeutronSD.hh" -#include "StorkMatPropManager.hh" -#include "StorkHeatTransfer.hh" - -// Include Geant4 headers -#include "G4PVPlacement.hh" -#include "G4LogicalVolume.hh" -#include "G4VPhysicalVolume.hh" -#include "G4VSolid.hh" -#include "globals.hh" -#include "G4ios.hh" -#include "G4Isotope.hh" -#include "G4Element.hh" -#include "StorkElement.hh" -#include "StorkMaterial.hh" -#include "G4Material.hh" -#include "G4NistManager.hh" -#include "G4SolidStore.hh" -#include "G4GeometryManager.hh" -#include "G4PhysicalVolumeStore.hh" -#include "G4LogicalVolumeStore.hh" -#include "G4VSensitiveDetector.hh" -#include "G4SDManager.hh" -#include "G4SDParticleFilter.hh" -#include "G4ParticleTable.hh" -#include "G4ThreeVector.hh" -#include "G4VisAttributes.hh" -#include "G4Colour.hh" -#include "G4SystemOfUnits.hh" - -// Include other headers -#include - - -class StorkNeutronSD; - -class StorkVWorldConstructor -{ - public: - // Public member functions - - // Constructor and destructor - StorkVWorldConstructor(); - virtual ~StorkVWorldConstructor(); - - // Create and update simulation world - virtual G4VPhysicalVolume* ConstructNewWorld(const StorkParseInput* infile); - virtual G4VPhysicalVolume* UpdateWorld(StorkMatPropChangeVector changes); - - - // Get the world material map - StorkMaterialMap* GetMaterialMap(void) { return &matMap; } - - // Check whether material-property is variable for this world - G4bool IsApplicable(MatPropPair matProp); - - // Get the current value of a material-property - G4double GetWorldProperty(MatPropPair matProp); - - // Get dimensions of smallest box enclosing world - virtual G4ThreeVector GetEncWorldDim() { return encWorldDim; } - G4ThreeVector GetReactorDim() { return reactorDim; } - - // Get the reactor logical volume - virtual G4LogicalVolume* GetWorldLogical() { return worldLogical; } - - // Output temperature of every material - void SaveMaterialTemperatureHeader(G4String fname); - void SaveMaterialTemperatures(G4String fname, G4int runNumber); - - // Get and Set funsctions - G4bool HasGeomChanged() {return geomChanged;} - void SetGeomChanged(G4bool value) {geomChanged = value;} - G4bool HasMatChanged() {return matChanged;} - void SetMatChanged(G4bool value) {matChanged = value;} - G4bool HasPhysChanged() {return physChanged;} - void SetPhysChanged(G4bool value) {physChanged = value;} - void SetFuelDimensions(G4ThreeVector value) {FuelDimensions = value;} - G4ThreeVector GetFuelDimensions() {return FuelDimensions;} - void SetFuelTemperatures(G4double ft[]) {for(G4int i =0; i<34;i++){ - FuelTemperatures[i] = ft[i];}} - G4double* GetFuelTemperatures() {return FuelTemperatures;} - G4double* GetFuelDensities() {return FuelDensities;} - G4double* GetFuelRadii() {return FuelRadii;} - - protected: - // Protected member functions - - // Construct and destroy simulation materials - virtual G4VPhysicalVolume* ConstructWorld()=0; - virtual void ConstructMaterials() = 0; - void DestroyMaterials(); - // Update the variable material-properties - G4bool UpdateWorldProperties(StorkMatPropChangeVector changes); - - protected: - // Protected member variables - - // Maps materials and properties - WorldPropertyMap variablePropMap; - StorkMaterialMap matMap; - StorkMatPropChangeVector initialChanges; - StorkMatPropManager *theMPMan; - - G4double FuelRadii[34]; - G4double FuelTemperatures[34]; - G4double FuelDensities[34]; - G4ThreeVector FuelDimensions; - - // Sensitive Detector - StorkNeutronSD *sDReactor; - - // Flags used in world update - G4bool geomChanged; - G4bool matChanged; - G4bool physChanged; - G4bool Initiation; - - // World variables - G4ThreeVector encWorldDim; - G4ThreeVector reactorDim; - G4LogicalVolume *worldLogical; - G4VPhysicalVolume *worldPhysical; - G4VisAttributes *worldVisAtt; - - // Output file character position tracker - std::vector *charPosition; -}; - -#endif // STORKWORLDCONSTRUCTOR_H diff --git a/G4STORK/include/StorkWorld.hh b/G4STORK/include/StorkWorld.hh deleted file mode 100755 index 2a279189..00000000 --- a/G4STORK/include/StorkWorld.hh +++ /dev/null @@ -1,115 +0,0 @@ -/* -StorkWorld.hh - -Created by: Liam Russell -Date: 17-02-2011 -Modified: 11-03-2013 - -Header for StorkWorld class. - -This class creates the simulation geometry and materials based on the input -file. The geometry is a sphere of various diameters and the materials are -either solid U235 or a homogeneous mixture of natural uranium and heavy water. -Additionally, it sets the sensisitive detector. - -*/ - -#ifndef STORKWORLD_H -#define STORKWORLD_H - -// Include G4-STORK headers -#include "StorkParseInput.hh" -#include "StorkMatPropManager.hh" -#include "StorkEventAction.hh" - -// Include Geant4 headers -#include "G4VUserDetectorConstruction.hh" -#include "G4VPhysicalVolume.hh" - - -// Type definition for world constructor map -class StorkVWorldConstructor; -typedef std::map StorkWorldMap; - - -class StorkWorld : public G4VUserDetectorConstruction -{ - public: - // Public member functions - - // Constructor and destructor - StorkWorld(); - StorkWorld(const StorkParseInput* infile); - ~StorkWorld(); - - void InitializeWorldData(G4String worlnam); - void InitializeWorldData(const StorkParseInput* infile); - - // Construct the world (called when simulation begins) - G4VPhysicalVolume* Construct(); - - // Dump the geometrical tree to G4cout - void DumpGeometricalTree(); - - // Update the world based on a vector of changes - G4VPhysicalVolume* UpdateWorld(StorkMatPropChangeVector theChanges); - - // Get the material map of the world - StorkMaterialMap* GetMaterialMap(void); - - // Get the dimensions of the smallest box enclosing the world - G4ThreeVector GetWorldBoxDimensions(); - - // Get the current value of a world property - G4double GetWorldProperty(MatPropPair matProp); - - // Get the logical volume of the world - G4LogicalVolume* GetWorldLogicalVolume(); - G4ThreeVector* GetThermalGrid(void); - - // Get major world dimensions - G4ThreeVector GetWorldDimensions(); - - // Add world type - void AddWorld(G4String name, StorkVWorldConstructor *aNewWorld); - - // World flag returners/modifiers - G4bool HasMatChanged(); - G4bool HasPhysChanged(); - void SetPhysChanged(G4bool value); - void SetMatChanged(G4bool value); - - // Outputs temperatures of all materials to file specified in StorkParseInput - void SaveMaterialTemperatures(G4String fname, G4int runNumber); - void SaveMaterialTemperatureHeader(G4String fname); - - G4ThreeVector GetFuelDimensions(); - G4double* GetFuelTemperatures(); - G4double* GetFuelDensities(); - G4double* GetFuelRadii(); - - private: - // Private member functions - - void DumpGeometricalTree(G4VPhysicalVolume *vol, G4int depth=0); - - private: - // Private member variables - - // Pointer to input file - const StorkParseInput* inFile; - - // Physical Volume - G4VPhysicalVolume *worldPhysical; - - // World constructor pointer - StorkVWorldConstructor *theWorld; - - // Map of available worlds - StorkWorldMap availableWorlds; - - // Dimensions of smallest box enclosing world - G4String worldName; -}; - -#endif // STORKWORLD_H diff --git a/G4STORK/include/StorkZeroBCStepLimiter.hh b/G4STORK/include/StorkZeroBCStepLimiter.hh deleted file mode 100755 index 091f4c4c..00000000 --- a/G4STORK/include/StorkZeroBCStepLimiter.hh +++ /dev/null @@ -1,55 +0,0 @@ -#ifndef STORKZEROBCSTEPLIMITER_HH -#define STORKZEROBCSTEPLIMITER_HH - -// Include G4-STORK headers -#include "StorkProcessManager.hh" -#include "StorkPrimaryNeutronInfo.hh" -#include "StorkTrackInfo.hh" -#include "StorkPeriodicBCTransform.hh" -#include "StorkReflectBCTransform.hh" - -// Include Geant4 headers -#include "G4StepLimiter.hh" -#include "G4Track.hh" -#include "G4Box.hh" -#include "G4VParticleChange.hh" -//#include "G4Plane.hh" -#include "G4VPhysicalVolume.hh" -#include "G4String.hh" -#include "globals.hh" -#include "G4ThreeVector.hh" -#include "G4ParticleDefinition.hh" -#include "G4LogicalVolume.hh" -#include "G4VSolid.hh" - -class StorkZeroBCStepLimiter : public G4StepLimiter -{ - public: - - StorkZeroBCStepLimiter(std::vector* PeriodicBC, std::vector* ReflectBC, - const G4String& processName = "StorkZeroBCStepLimiter", - G4String worldPhysName="worldPhysical"); - - virtual ~StorkZeroBCStepLimiter() - {}; - - virtual G4double PostStepGetPhysicalInteractionLength( - const G4Track& aTrack, - G4double previousStepSize, - G4ForceCondition *condition); - - virtual G4bool IsApplicable(const G4ParticleDefinition &particle); - - virtual G4VParticleChange* PostStepDoIt(const G4Track &aTrack, - const G4Step &aStep); - private: - //Private member variables - - G4String worldName; // Name of world physical volume - StorkProcessManager *nsProcMan; // Pointer to process manager - StorkPrimaryNeutronInfo *pnInfo; - StorkTrackInfo *trackInfo; - std::vector zeroSides; -}; - -#endif // STORKZEROBCSTEPLIMITER_HH diff --git a/G4STORK/include/TestConstructor.hh b/G4STORK/include/TestConstructor.hh deleted file mode 100755 index 1f4a75f9..00000000 --- a/G4STORK/include/TestConstructor.hh +++ /dev/null @@ -1,55 +0,0 @@ -#ifndef TestConstructor_H -#define TestConstructor_H - -// Include header files -#include "StorkVWorldConstructor.hh" -#include "StorkNeutronSD.hh" -#include "UnionBinaryTree.hh" -#include "G4SubtractionSolid.hh" -#include "G4IntersectionSolid.hh" -#include "G4ReflectionFactory.hh" -#include "G4ReflectedSolid.hh" -#include "G4Transform3D.hh" -#include "G4DisplacedSolid.hh" -#include "G4RotationMatrix.hh" -#include "G4AffineTransform.hh" -#include "G4PVReplica.hh" -#include "G4Para.hh" -#include "G4Box.hh" -#include "G4Tubs.hh" -#include -#include "G4NistManager.hh" - -class TestConstructor: public StorkVWorldConstructor -{ - public: - TestConstructor(); - virtual ~TestConstructor(); - - protected: - // Protected member functions - - virtual G4VPhysicalVolume* ConstructWorld(); - virtual void ConstructMaterials(); - - protected: - // Protected member variables - solidPos sheatheTubeLatPair; - G4VSolid* gridSlice; - G4VSolid* test; - G4ThreeVector originTubeSec[6]; - // Logical Volumes - G4LogicalVolume *cellLogical; - - G4LogicalVolume *zircGridLogical; - -// // Visualization attributes - G4VisAttributes *cellVisAtt; - - G4VisAttributes *zircGridVisAtt; - - -}; - -#endif // TestConstructor_H - diff --git a/G4STORK/include/UnionBinaryTree.hh b/G4STORK/include/UnionBinaryTree.hh deleted file mode 100755 index cfaf63f4..00000000 --- a/G4STORK/include/UnionBinaryTree.hh +++ /dev/null @@ -1,53 +0,0 @@ -#include "G4UnionSolid.hh" -#include "StorkUnionSolid.hh" -#include "G4ThreeVector.hh" -#include "G4String.hh" -#include "G4VSolid.hh" -#include "G4Tubs.hh" -#include "G4Box.hh" -#include "G4Sphere.hh" -#include "G4Orb.hh" -#include -#include -#include -#include "G4GeometryTolerance.hh" - - -typedef std::pair solidPos; -typedef std::pair, G4double> regionInfo; -typedef std::vector solidList; -typedef std::vector intVec; -typedef std::vector regList; -typedef std::vector::iterator solidListItr; -typedef std::vector::iterator regListItr; - -enum coorEnum {radSph=0, radCyl, phi, xDir, yDir, ZDir}; - -class UnionBinaryTree -{ - public: - UnionBinaryTree(solidList* List); - ~UnionBinaryTree(void); - - solidPos GetUnionSolid(G4String name, G4int equalP, ShapeEnum regShape, G4double unitRegionDim[], G4double regionDim[], G4double offset=0.0, coorEnum axis=radCyl, G4double order=1.0, G4double inPriority[]=NULL, G4bool delRepeatedEntries=false); - StorkSixVector AddRegion( StorkSixVector regionDim, StorkSixVector regionDim2, ShapeEnum shape, DirEnum dir ) ; - solidList GetSolidList(void) - { - return *Unions; - } - - - private: - solidList* Unions; - G4double* priority; - G4int numSolids; - regList regionList; - - void SortSolids(solidList* Temp1, regList* rList, solidList* ToBeAdded ); - void SortEqualSolids(solidList* Temp1, solidList* ToBeAdded); - void PriorityByVol(G4double offset); - void PriorityByPos(coorEnum axis, G4double dir, G4double offset); - void RemoveDuplicates(); - intVec createRegions(solidList* Temp1, ShapeEnum RegShape, G4double unitRegionDim[], G4double regionDim[]); - G4bool InsideRegion( const G4ThreeVector& p, ShapeEnum regShape, StorkSixVector regDim); -}; diff --git a/G4STORK/include/ZED2Constructor.hh b/G4STORK/include/ZED2Constructor.hh deleted file mode 100755 index fd7d3704..00000000 --- a/G4STORK/include/ZED2Constructor.hh +++ /dev/null @@ -1,177 +0,0 @@ - -/* -ZED2Constructor.hh - -Created by: Salma Mahzooni -Date: 26-07-2013 -Modified: 11-03-2013 - -Header for C6LatticeConstructor class. - -This class creates the simulation geometry for a CANDU 6 lattice cell. The -material and geometric composition of the lattice cell were taken from the -DRAGON manual[1]. - -Based on the "C6World" class created by Wesley Ford 10-05-2012. - -[1] G. Marleau, A. Hebert, and R. Roy, "A User Guide for DRAGON 3.06". Ecole -Polytechnique de Montreal, 2012, pp. 148-152. IGE-174 Rev. 10. - -*/ - -#ifndef ZED2Constructor_H -#define ZED2Constructor_H - -// Include header files -#include "StorkNeutronSD.hh" -#include "StorkVWorldConstructor.hh" -#include "G4UnionSolid.hh" -#include "G4Box.hh" -#include "G4Tubs.hh" -#include "G4Orb.hh" -#include "G4SubtractionSolid.hh" - - - -class ZED2Constructor : public StorkVWorldConstructor -{ - public: - // Public memeber functions - - // Constructor and destructor - ZED2Constructor(); - virtual ~ZED2Constructor(); - virtual G4VPhysicalVolume* ConstructNewWorld(const StorkParseInput* infile); - - - protected: - // Protected member functions - - // Material name enumerator - enum WorldMats - { e_U235=0, e_Godiva, e_UHW, NUM_MATERIALS }; - - // Private member functions - virtual G4VPhysicalVolume* ConstructWorld(); - virtual void ConstructMaterials(); - - protected: - // Protected member variables - - // Logical Volumes - G4LogicalVolume *worldLogical; - G4LogicalVolume *reactDimTubeLogical; - G4LogicalVolume *airTubeLogical; - G4LogicalVolume *vesselLogical; - G4LogicalVolume *tankLogical1; - G4LogicalVolume *ModLogical; - G4LogicalVolume *logicCalandria1; - G4LogicalVolume *logicGasAnn1; - G4LogicalVolume *logicPressure1; - G4LogicalVolume *logicCoolant1; - G4LogicalVolume *logicAir1; - G4LogicalVolume *logicRodA1; - G4LogicalVolume *logicRodB1; - G4LogicalVolume *logicSheathA1; - G4LogicalVolume *logicSheathB1; - G4LogicalVolume *logicEndPlate2; - G4LogicalVolume *logicEndPlate1; - G4LogicalVolume *logicCalandria1Mod; - G4LogicalVolume *logicGasAnn1Mod; - G4LogicalVolume *logicPressure1Mod; - G4LogicalVolume *logicCoolant1Mod; - G4LogicalVolume *logicRodA1Cut2; - G4LogicalVolume *logicRodB1Cut2; - G4LogicalVolume *logicSheathA1Cut2; - G4LogicalVolume *logicSheathB1Cut2; - G4LogicalVolume *logicEndPlate2Cut2; - G4LogicalVolume *logicRodA1Mod; - G4LogicalVolume *logicRodB1Mod; - G4LogicalVolume *logicSheathA1Mod; - G4LogicalVolume *logicSheathB1Mod; - G4LogicalVolume *logicEndPlate2Mod; - G4LogicalVolume *logicEndPlate1Mod; - G4LogicalVolume *logicRodA1Cut1; - G4LogicalVolume *logicRodB1Cut1; - G4LogicalVolume *logicSheathA1Cut1; - G4LogicalVolume *logicSheathB1Cut1; - G4LogicalVolume *logicEndPlate2Cut1; - G4LogicalVolume *logicCalandria1RU; - G4LogicalVolume *logicGasAnn1RU; - G4LogicalVolume *logicPressure1RU; - G4LogicalVolume *logicCoolant1RU; - G4LogicalVolume *logicAir1RU; - G4LogicalVolume *logicRodA1RU; - G4LogicalVolume *logicRodB1RU; - G4LogicalVolume *logicSheathA1RU; - G4LogicalVolume *logicSheathB1RU; - G4LogicalVolume *logicEndPlate2RU; - G4LogicalVolume *logicEndPlate1RU; - G4LogicalVolume *logicCalandria1ModRU; - G4LogicalVolume *logicGasAnn1ModRU; - G4LogicalVolume *logicPressure1ModRU; - G4LogicalVolume *logicCoolant1ModRU; - G4LogicalVolume *logicRodA1Cut2RU; - G4LogicalVolume *logicRodB1Cut2RU; - G4LogicalVolume *logicSheathA1Cut2RU; - G4LogicalVolume *logicSheathB1Cut2RU; - G4LogicalVolume *logicEndPlate2Cut2RU; - G4LogicalVolume *logicRodA1ModRU; - G4LogicalVolume *logicRodB1ModRU; - G4LogicalVolume *logicSheathA1ModRU; - G4LogicalVolume *logicSheathB1ModRU; - G4LogicalVolume *logicEndPlate2ModRU; - G4LogicalVolume *logicEndPlate1ModRU; - G4LogicalVolume *logicRodA1Cut1RU; - G4LogicalVolume *logicRodB1Cut1RU; - G4LogicalVolume *logicSheathA1Cut1RU; - G4LogicalVolume *logicSheathB1Cut1RU; - G4LogicalVolume *logicEndPlate2Cut1RU; - G4LogicalVolume *logicDumplineAl; - G4LogicalVolume *logicDumplineHW; - G4LogicalVolume *logicDumplineAlC; - G4LogicalVolume *logicDumplineHWC; - - - - // Visualization attributes - - G4VisAttributes * vesselVisAtt; - G4VisAttributes * tank1VisATT; - G4VisAttributes * ModVisAtt; - G4VisAttributes * fuelA1VisATT; - G4VisAttributes * fuelB1VisATT; - G4VisAttributes * sheathA1VisATT; - G4VisAttributes * sheathB1VisATT; - G4VisAttributes * Air1VisAtt; - G4VisAttributes * Coolant1VisAtt; - G4VisAttributes * Pressure1VisAtt; - G4VisAttributes * GasAnn1VisAtt; - G4VisAttributes * Calandria1VisAtt; - G4VisAttributes * EndPlate2VisATT; - G4VisAttributes * airTubeVisAtt; - G4VisAttributes * DumplineAlVisAtt; - G4VisAttributes * DumplineHWVisAtt; - G4VisAttributes * reactDimTubeVisAtt; - - - - - // Multifunctional Detector - //G4MultiFunctionalDetector *FluxScorer; - // Stored variables from infile - G4String materialID; - G4double matTemp; - G4double matDensity[NUM_MATERIALS]; - G4double reactorRadius; - G4double fuelTemp; - G4double fuelDensity; - G4double AirDensity; - G4double moderatorTemp; - G4double moderatorDensity; - G4double coolantDensity; - G4double coolantTemp; -}; - - -#endif // ZED2Constructor_H diff --git a/G4STORK/src/BareSphereConstructor.cc b/G4STORK/src/BareSphereConstructor.cc deleted file mode 100755 index 45950940..00000000 --- a/G4STORK/src/BareSphereConstructor.cc +++ /dev/null @@ -1,238 +0,0 @@ -/* -BareSphereConstructor.cc - -Created by: Liam Russell -Date: 23-05-2012 -Modified: 10-03-2013 - -Source code for the bare sphere geometry and materials. - -*/ - -#include "BareSphereConstructor.hh" - - -// Constructor -BareSphereConstructor::BareSphereConstructor() -: StorkVWorldConstructor(), reactorLogical(0) -{ - // Set default values for member variables - matTemp = 293.6*kelvin; - - // Set default material densities - matDensity[e_UHW] = -1.0*g/cm3; - matDensity[e_Godiva] = 18.7398*g/cm3; - matDensity[e_U235] = 18.75*g/cm3; - - reactorVisAtt=NULL; -} - - -// Destructor -BareSphereConstructor::~BareSphereConstructor() -{ - // Delete visualization attributes - if(reactorVisAtt) - delete reactorVisAtt; -} - - -// ConstructNewWorld() -// Build bare sphere world for the first time. Set default values and user -// inputs. Also set up the variable property map. -G4VPhysicalVolume* -BareSphereConstructor::ConstructNewWorld(const StorkParseInput* infile) -{ - G4int matIndex = 2; - - // Select material based on input file - switch(infile->GetReactorMaterial()) - { - case 2: - materialID = "UHW"; - matIndex = e_UHW; - reactorRadius = 87.5*cm; - break; - case 3: - materialID = "Godiva"; - matIndex = e_Godiva; - reactorRadius = 8.7*cm; - break; - default: // 92235 - materialID = "U235Mat"; - matIndex = e_U235; - reactorRadius = 8.7*cm; - break; - } - - // Set up variable property map - variablePropMap[MatPropPair(all,temperature)] = &matTemp; - variablePropMap[MatPropPair(all,density)] = &(matDensity[matIndex]); - variablePropMap[MatPropPair(all,dimension)] =&reactorRadius; - - - // Call base class ConstructNewWorld() to complete construction - return StorkVWorldConstructor::ConstructNewWorld(infile); -} - - -// ConstructWorld -// Construct the geometry and materials of the spheres given the inputs. -G4VPhysicalVolume* BareSphereConstructor::ConstructWorld() -{ - // Set local variables and enclosed world dimensions - reactorDim = G4ThreeVector(reactorRadius, 0, 0); - G4double buffer = 1.0*cm; - encWorldDim = 2.0 * G4ThreeVector(reactorRadius+buffer, - reactorRadius+buffer, - reactorRadius+buffer); - G4SolidStore* theSolids = G4SolidStore::GetInstance(); - - // Set up the materials (if necessary) - if(matChanged) - { - // Delete any existing materials - DestroyMaterials(); - // Create the materials - ConstructMaterials(); - } - - // Clean up volumes - G4GeometryManager::GetInstance()->OpenGeometry(); - G4PhysicalVolumeStore::GetInstance()->Clean(); - G4LogicalVolumeStore::GetInstance()->Clean(); - - // Set up the solids if necessary - if(geomChanged) - { - // Clean up solids - G4SolidStore::GetInstance()->Clean(); - - // Create world solid - new G4Orb("worldSphere", reactorRadius+buffer); - - // Create the reactor solid - new G4Orb("reactorSphere", reactorRadius); - - geomChanged = false; - } - - - // Create world volume - worldLogical = new G4LogicalVolume(theSolids->GetSolid("worldSphere"), - matMap["World"], "worldLogical",0,0,0); - worldPhysical = new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), worldLogical, - "worldPhysical",0,0,0); - - // Create the homogenous spherical reactor - reactorLogical = new G4LogicalVolume(theSolids->GetSolid("reactorSphere"), - matMap[materialID], "reactorLogical", - 0,0,0); - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), reactorLogical, - "reactorPhysical", worldLogical,0,0); - - - // Set reactor as sensitive detector - reactorLogical->SetSensitiveDetector(sDReactor); - - - // Set visualization attributes - - if(worldVisAtt) - delete worldVisAtt; - if(reactorVisAtt) - delete reactorVisAtt; - - worldVisAtt = new G4VisAttributes(G4Colour(1.,1.,1.)); - worldVisAtt->SetVisibility(false); - worldLogical->SetVisAttributes(worldVisAtt); - - reactorVisAtt = new G4VisAttributes(G4Colour(1.,0.,0.)); - reactorLogical->SetVisAttributes(reactorVisAtt); - - return worldPhysical; -} - - -// ConstructMaterials() -// Construct all the materials needed for the BareSphereConstructor. -void BareSphereConstructor::ConstructMaterials() -{ - G4double abunD20 = 100.0*perCent; - G4double abunU235 = 0.7204*perCent; - G4double abunU238 = 100.0*perCent - abunU235; - G4double massFracU = 10.73*perCent; - G4double massFracW = 100.0*perCent - massFracU; - - // Elements, isotopes and materials - G4Isotope *U234, *U235, *U238, *D2, *O16; - StorkElement *Uranium, *Oxygen, *Deuterium, *PureU235, *EU; - StorkMaterial *World, *UHW, *U235Mat, *HeavyWater, *Godiva; - - // Create the world environment - World = new StorkMaterial("Galactic", 1, 1, 1.e-25*g/cm3, kStateGas, - 2.73*kelvin, 3.e-18*pascal); - - // Make the uranium isotopes and element - U234 = new G4Isotope("U234", 92, 234, 234.0410*g/mole); - U235 = new G4Isotope("U235", 92, 235, 235.0439*g/mole); - U238 = new G4Isotope("U238", 92, 238, 238.0508*g/mole); - - Uranium = new StorkElement("Uranium", "U", 2); - Uranium->AddIsotope(U235, abunU235); - Uranium->AddIsotope(U238, abunU238); - - // Make heavy water isotopes and elements - D2 = new G4Isotope("D2", 1, 2, 2.014*g/mole); - Deuterium = new StorkElement("Deuterium", "D", 1); - Deuterium->AddIsotope(D2, 100*perCent); - - O16 = new G4Isotope("O16", 8, 16, 15.995*g/mole); - Oxygen = new StorkElement("Oxygen", "O", 1); - Oxygen->AddIsotope(O16, 100*perCent); - - // Make the U235 material - U235Mat = new StorkMaterial("U235 Material", matDensity[e_U235], 1, - kStateSolid, matTemp); - PureU235 = new StorkElement("Uranium-235","U235",1); - PureU235->AddIsotope(U235, 100*perCent); - U235Mat->AddElement(PureU235,1); - - // Make Godiva material - Godiva = new StorkMaterial("Godiva", matDensity[e_Godiva], 1, kStateSolid, - matTemp); - EU = new StorkElement("Enriched Uranium","EU",3); - EU->AddIsotope(U234, 1.0252*perCent); - EU->AddIsotope(U235, 93.7695*perCent); - EU->AddIsotope(U238, 5.2053*perCent); - Godiva->AddElement(EU,1); - - // Make the heavy water material - HeavyWater = new StorkMaterial("Heavy Water", 1.1056*g/cm3, 2, kStateLiquid, - matTemp); - HeavyWater->AddElement(Deuterium, 2); - HeavyWater->AddElement(Oxygen, 1); - - // Make the UHW material - if(matDensity[e_UHW] < 0) - { - matDensity[e_UHW] = (abunD20 * 1.1056*g/cm3) * massFracW + - (abunU235 * 18.75*g/cm3 + abunU238 * 18.9*g/cm3) * massFracU; - } - - UHW = new StorkMaterial("UHW", matDensity[e_UHW], 2, kStateSolid, matTemp); - UHW->AddMaterial(HeavyWater, massFracW); - UHW->AddElement(Uranium, massFracU); - - // Add materials to the map indexed by either ZA (format ZZAAA or ZZ) - // For composite materials: world is 0, heavy water is 1, UHW is 2 - matMap["World"] = World; - matMap["UHW"] = UHW; - matMap["Godiva"] = Godiva; - matMap["U235Mat"] = U235Mat; - - // Reset material changed flag - matChanged = false; - - return; -} diff --git a/G4STORK/src/C6LatticeConstructor.cc b/G4STORK/src/C6LatticeConstructor.cc deleted file mode 100755 index f5043e97..00000000 --- a/G4STORK/src/C6LatticeConstructor.cc +++ /dev/null @@ -1,526 +0,0 @@ -/* -C6LatticeConstructor.cc - -Created by: Liam Russell -Date: 23-05-2012 -Modified: 11-03-2013 - -Source code for the CANDU 6 lattice geometry and materials - -*/ - -#include "C6LatticeConstructor.hh" - - -// Constructor -C6LatticeConstructor::C6LatticeConstructor() -: StorkVWorldConstructor(), cellLogical(0), cTubeLogical(0), gasAnnLogical(0), - pressTubeLogical(0), coolantLogical(0), sheatheLogical(0), fuelLogical(0) -{ - // Set default member variables (from file or default values) - latticePitch = 28.575*cm; - fuelTemp = 859.99*kelvin; - fuelDensity = 10.5541*g/cm3; - coolantTemp = 561.285*kelvin; - coolantDensity = 0.8074*g/cm3; - moderatorTemp = 336.16*kelvin; - moderatorDensity = 1.08875*g/cm3; - - // Set up variable property map - variablePropMap[MatPropPair(fuel,temperature)] = &fuelTemp; - variablePropMap[MatPropPair(fuel,density)] = &fuelDensity; - variablePropMap[MatPropPair(coolant,temperature)] = &coolantTemp; - variablePropMap[MatPropPair(coolant,density)] = &coolantDensity; - variablePropMap[MatPropPair(moderator,temperature)] = &moderatorTemp; - variablePropMap[MatPropPair(moderator,density)] = &moderatorDensity; - variablePropMap[MatPropPair(all,dimension)] = &latticePitch; - - modVisAtt=NULL; - fuelVisAtt=NULL; - cTubeVisAtt=NULL; - pressTubeVisAtt=NULL; - gasAnnVisAtt=NULL; - coolantVisAtt=NULL; - sheatheVisAtt=NULL; -} - - -// Desturctor -C6LatticeConstructor::~C6LatticeConstructor() -{ - // Delete visualization attributes - if(modVisAtt) - delete modVisAtt; - if(fuelVisAtt) - delete fuelVisAtt; - if(cTubeVisAtt) - delete cTubeVisAtt; - if(pressTubeVisAtt) - delete pressTubeVisAtt; - if(gasAnnVisAtt) - delete gasAnnVisAtt; - if(coolantVisAtt) - delete coolantVisAtt; - if(sheatheVisAtt) - delete sheatheVisAtt; -} - - -// ConstructWorld() -// Construct the geometry and materials of the CANDU 6 lattice cell. -G4VPhysicalVolume* C6LatticeConstructor::ConstructWorld() -{ - // Lattic cell dimensions - G4double buffer = 1.0*cm; - reactorDim = G4ThreeVector(latticePitch/2.0,latticePitch/2.0, - 2.4765*cm); - encWorldDim = 2.0 * G4ThreeVector(reactorDim[0]+buffer,reactorDim[1]+buffer, - reactorDim[2]+buffer); - G4SolidStore* theSolids = G4SolidStore::GetInstance(); - - // Set static dimensions - - // Calandria Tube dimensions - G4double cTubeRadmax = 6.5875*cm; - G4double cTubeLen = reactorDim[2]; - - // Create the Gas Annulus - G4double gasAnnRadmax = 6.4478*cm; - G4double gasAnnLen = reactorDim[2]; - - // Create the Pressure Tube - G4double pressTubeRadmax = 5.6032*cm; - G4double pressTubeLen = reactorDim[2]; - - // Create the Coolant - G4double coolantRadmax = 5.1689*cm; - G4double coolantLen = reactorDim[2]; - - // Create the Sheathe - G4double sheatheRadmax = 0.6540*cm; -// G4double sheatheLen = reactorDim[2]-0.5*cm; - G4double sheatheLen = reactorDim[2]; - - // Fuel pin dimensions - G4double pinRad = 0.6122*cm; -// G4double pinLen = sheatheLen-1.*cm; - G4double pinLen = sheatheLen; - G4int rings = 4; - G4double ringRad[3] = {1.4885*cm,2.8755*cm,4.3305*cm}; - G4double secondRingOffset = 0.261799*radian; - - - // Set up the materials (if necessary) - if(matChanged) - { - // Delete any existing materials - DestroyMaterials(); - // Create the materials - ConstructMaterials(); - } - - // Clean up volumes - G4GeometryManager::GetInstance()->OpenGeometry(); - G4PhysicalVolumeStore::GetInstance()->Clean(); - G4LogicalVolumeStore::GetInstance()->Clean(); - - // Set up the solids if necessary - if(geomChanged) - { - // Clean up solids - G4SolidStore::GetInstance()->Clean(); - - // Create world solid - new G4Box("worldBox", reactorDim[0]+buffer, reactorDim[1]+buffer, - reactorDim[2]+buffer); - // Create the lattice cell solid - new G4Box("cellBox", reactorDim[0], reactorDim[1], reactorDim[2]); - // Create calandria tube - new G4Tubs("calTube", 0., cTubeRadmax, cTubeLen, 0., 2.0*CLHEP::pi); - // Create gas annulus - new G4Tubs("gasAnnTube", 0., gasAnnRadmax, gasAnnLen, 0., - 2.0*CLHEP::pi); - // Create pressure tube - new G4Tubs("pressTube", 0., pressTubeRadmax, pressTubeLen, 0., - 2.0*CLHEP::pi); - // Create coolant solid - new G4Tubs("coolantTube", 0., coolantRadmax, coolantLen, 0., - 2.0*CLHEP::pi); - // Create the sheathe for fuel pins - new G4Tubs("sheatheTube", 0., sheatheRadmax, sheatheLen, 0., - 2.0*CLHEP::pi); - // Create a fuel pins - new G4Tubs("pinCyl", 0., pinRad, pinLen, 0.,2.0*CLHEP::pi); - - geomChanged = false; - } - - // Create world volume - worldLogical = new G4LogicalVolume(theSolids->GetSolid("worldBox"), - matMap["Galactic"],"worldLogical",0,0,0); - worldPhysical = new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), worldLogical, - "worldPhysical",0,0,0); - - // Create the lattice cell (moderator) volume - cellLogical = new G4LogicalVolume(theSolids->GetSolid("cellBox"), - matMap["Moderator"],"cellLogical",0,0,0); - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), cellLogical,"cellPhysical", - worldLogical,0,0); - - // Create the Calandria Tube - cTubeLogical = new G4LogicalVolume(theSolids->GetSolid("calTube"), - matMap["CalandriaTube"], "cTubeLogical", - 0,0,0); - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), cTubeLogical,"cTubePhysical", - cellLogical,0,0); - - // Create the Gas Annulus - gasAnnLogical = new G4LogicalVolume(theSolids->GetSolid("gasAnnTube"), - matMap["AnnulusGas"], "gasAnnLogical", - 0,0,0); - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), gasAnnLogical, - "gasAnnPhysical",cTubeLogical,0,0); - - // Create the Pressure Tube - pressTubeLogical = new G4LogicalVolume(theSolids->GetSolid("pressTube"), - matMap["PressureTube"], - "pressTubeLogical",0,0,0); - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), pressTubeLogical, - "pressTubePhysical",gasAnnLogical,0,0); - - // Create the Coolant - coolantLogical = new G4LogicalVolume(theSolids->GetSolid("coolantTube"), - matMap["Coolant"], "coolantLogical", - 0,0,0); - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), coolantLogical, - "coolantPhysical",pressTubeLogical,0,0); - - // Create the Sheathe - sheatheLogical = new G4LogicalVolume(theSolids->GetSolid("sheatheTube"), - matMap["Sheathe"], "sheatheLogical", - 0,0,0); - - // Create a fuel - fuelLogical = new G4LogicalVolume(theSolids->GetSolid("pinCyl"), - matMap["Fuel"], "fuelLogical",0,0,0); - - - // Create fuel bundle - - // Rotation and translation of the rod and sheathe - std::stringstream volName; - - // Set name for sheathe physical volume - volName << 0; - - // Place centre pin - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), sheatheLogical, - "sheathePhysical " + volName.str(),coolantLogical,0,0); - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), fuelLogical,"fuelPhysical ", - sheatheLogical,0,0); - - - // Place pins for each ring - for( G4int j = 1; j < rings; j++ ) - { - for( G4int i = 0; i < j*6; i++ ) - { - // Reset string stream - volName.str(""); - - volName << j << "-" << i; - - if(j == 2) - { - - G4ThreeVector Tm(ringRad[j-1]*cos(2.0*CLHEP::pi*G4double(i)/ - G4double(j*6)+secondRingOffset), - ringRad[j-1]*sin(2.0*CLHEP::pi*G4double(i)/ - G4double(j*6)+secondRingOffset), - 0.); - new G4PVPlacement(0, Tm, sheatheLogical,"sheathePhysical " + - volName.str(),coolantLogical,0,0); - } - else - { - G4ThreeVector Tm(ringRad[j-1]*cos(2.0*CLHEP::pi*G4double(i)/ - G4double(j*6)), - ringRad[j-1]*sin(2.0*CLHEP::pi*G4double(i)/ - G4double(j*6)), 0.); - new G4PVPlacement(0, Tm, sheatheLogical,"sheathePhysical " + - volName.str(),coolantLogical,0,0); - } - - } - } - - - // Add sensitive detector to ALL logical volumes - worldLogical->SetSensitiveDetector( sDReactor ); - cellLogical->SetSensitiveDetector( sDReactor ); - cTubeLogical->SetSensitiveDetector( sDReactor ); - gasAnnLogical->SetSensitiveDetector( sDReactor ); - pressTubeLogical->SetSensitiveDetector( sDReactor ); - coolantLogical->SetSensitiveDetector( sDReactor ); - sheatheLogical->SetSensitiveDetector( sDReactor ); - fuelLogical->SetSensitiveDetector( sDReactor ); - - - // Set visualization attributes - - if(worldVisAtt) - delete worldVisAtt; - if(modVisAtt) - delete modVisAtt; - if(fuelVisAtt) - delete fuelVisAtt; - if(cTubeVisAtt) - delete cTubeVisAtt; - if(pressTubeVisAtt) - delete pressTubeVisAtt; - if(gasAnnVisAtt) - delete gasAnnVisAtt; - if(coolantVisAtt) - delete coolantVisAtt; - if(sheatheVisAtt) - delete sheatheVisAtt; - - worldVisAtt = new G4VisAttributes(G4Colour(1.,1.,1.)); - worldVisAtt->SetVisibility(false); - worldLogical->SetVisAttributes(worldVisAtt); - - modVisAtt = new G4VisAttributes(G4Colour(0.53,0.81,0.92)); - cellLogical->SetVisAttributes(modVisAtt); - - cTubeVisAtt = new G4VisAttributes(G4Colour(0,0,1)); - cTubeLogical->SetVisAttributes(cTubeVisAtt); - - gasAnnVisAtt = new G4VisAttributes(G4Colour(0.5,0.5,0.5)); - gasAnnLogical->SetVisAttributes(gasAnnVisAtt); - - pressTubeVisAtt = new G4VisAttributes(G4Colour(0,1,0)); - pressTubeLogical->SetVisAttributes(pressTubeVisAtt); - - coolantVisAtt = new G4VisAttributes(G4Colour(0,0.5,0.92)); - coolantLogical->SetVisAttributes(coolantVisAtt); - - sheatheVisAtt = new G4VisAttributes(G4Colour(1,0.55,0)); - sheatheLogical->SetVisAttributes(sheatheVisAtt); - - fuelVisAtt = new G4VisAttributes(G4Colour(1.,0.,0.)); - fuelLogical->SetVisAttributes(fuelVisAtt); - - - return worldPhysical; -} - - -// ConstructMaterials() -// Define and build the materials in the C6 lattice cell. -void C6LatticeConstructor::ConstructMaterials() -{ - // Elements, isotopes and materials - G4Isotope *U234, *U235, *U238, *O16, /* *O17, *O18,*/ *Fe54, *Fe56, *Fe57, - *Fe58, *B10, *Gd155, *Gd157, *Nb93, *Cr50, *Cr52, *Cr53, *Cr54, - *Ni58, *Ni60, *Ni64, *Zr90, *Zr91, *Zr92, *Zr94, *Zr96, - *C12, *C13; - G4Element *NU, *Oxygen, *H1, *D2, *Fe, *Gd, *Cr, *Ni, *Zr, *C, *Boron, - *Niobium; - G4Material *World, *Fuel, *H2O, *D2O, *Moderator, *Coolant, *PressureTube, - *AnnulusGas, *CalandriaTube, *Sheathe; - - - // Make the uranium isotopes and element - U234 = new G4Isotope("U234", 92, 234, 234.0410*g/mole); - U235 = new G4Isotope("U235", 92, 235, 235.0439*g/mole); - U238 = new G4Isotope("U238", 92, 238, 238.0508*g/mole); - - NU = new G4Element("Natural Uranium", "NU", 3); - NU->AddIsotope(U234, 0.0055*perCent); - NU->AddIsotope(U235, 0.7109*perCent); - NU->AddIsotope(U238, 99.2836*perCent); - - // Make hydrogen elements - H1 = new G4Element("Hydrogen", "H", 1); - H1->AddIsotope(new G4Isotope("H1", 1, 1, 1.008*g/mole), 1.0); - - D2 = new G4Element("Hydrogen", "H", 1); - D2->AddIsotope(new G4Isotope("H2", 1, 2, 2.014*g/mole), 1.0); - - // Make oxygen isotope and element - O16 = new G4Isotope("O16", 8, 16, 15.995*g/mole); -// O17 = new G4Isotope("O17", 8, 17, 16.999*g/mole); -// O18 = new G4Isotope("O18", 8, 18, 17.999*g/mole); - - Oxygen = new G4Element("Oxygen", "O", 1); - Oxygen->AddIsotope(O16, 100.*perCent); -// Oxygen->AddIsotope(O16, 99.757*perCent); -// Oxygen->AddIsotope(O17, 0.038*perCent); -// Oxygen->AddIsotope(O18, 0.205*perCent); - - //make iron isotopes and element - Fe54 = new G4Isotope("Fe54", 26, 54, 53.9396105*g/mole); - Fe56 = new G4Isotope("Fe56", 26, 56, 55.9349375*g/mole); - Fe57 = new G4Isotope("Fe57", 26, 57, 56.9353940*g/mole); - Fe58 = new G4Isotope("Fe58", 26, 58, 57.9332756*g/mole); - - Fe = new G4Element("Iron", "Fe", 4); - Fe->AddIsotope(Fe54, 5.80*perCent); - Fe->AddIsotope(Fe56, 91.72*perCent); - Fe->AddIsotope(Fe57, 2.20*perCent); - Fe->AddIsotope(Fe58, 0.28*perCent); - - //make boron isotopes and element - B10 = new G4Isotope("B10", 5, 10, 10.0129370*g/mole); - - Boron = new G4Element("Boron", "B", 1); - Boron->AddIsotope(B10, 100*perCent); - - //make gadolinium isotopes and element - Gd155 = new G4Isotope("Gd155", 64, 155, 154.9226220*g/mole); - Gd157 = new G4Isotope("Gd157", 64, 157, 156.9239601*g/mole); - - - Gd = new G4Element("Gadolinium", "Gd", 2); - Gd->AddIsotope(Gd155, 48.28373787*perCent); - Gd->AddIsotope(Gd157, 51.71626213*perCent); - - //make niobium isotopes and element - Nb93 = new G4Isotope("Nb93", 41, 93, 92.9063781*g/mole); - - Niobium = new G4Element("Niobium", "Nb", 1); - Niobium->AddIsotope(Nb93, 100*perCent); - - //make chromium isotopes and element - Cr50 = new G4Isotope("Cr50", 24, 50, 49.9460422*g/mole); - Cr52 = new G4Isotope("Cr52", 24, 52, 51.9405075*g/mole); - Cr53 = new G4Isotope("Cr53", 24, 53, 52.9406494*g/mole); - Cr54 = new G4Isotope("Cr54", 24, 54, 53.9388804*g/mole); - - Cr = new G4Element("Chromium", "Cr", 4); - Cr->AddIsotope(Cr50, 4.1737*perCent); - Cr->AddIsotope(Cr52, 83.7003*perCent); - Cr->AddIsotope(Cr53, 9.6726*perCent); - Cr->AddIsotope(Cr54, 2.4534*perCent); - - //make nickel isotopes and element - Ni58 = new G4Isotope("Ni58", 28, 58, 57.9353429*g/mole); - Ni60 = new G4Isotope("Ni60", 28, 60, 59.9307864*g/mole); - Ni64 = new G4Isotope("Ni64", 28, 64, 63.9279660*g/mole); - - Ni = new G4Element("Nickel", "Ni", 3); - Ni->AddIsotope(Ni58, 70.913*perCent); - Ni->AddIsotope(Ni60, 28.044*perCent); - Ni->AddIsotope(Ni64, 1.043*perCent); - - //make Zirconium isotopes and element - Zr90 = new G4Isotope("Zr90", 40, 90, 89.9047044*g/mole); - Zr91 = new G4Isotope("Zr91", 40, 91, 90.9056458*g/mole); - Zr92 = new G4Isotope("Zr92", 40, 92, 91.9050408*g/mole); - Zr94 = new G4Isotope("Zr94", 40, 94, 93.9063152*g/mole); - Zr96 = new G4Isotope("Zr96", 40, 96, 95.9082734*g/mole); - - Zr = new G4Element("Zirconium", "Zr", 5); - Zr->AddIsotope(Zr90, 50.706645*perCent); - Zr->AddIsotope(Zr91, 11.180922*perCent); - Zr->AddIsotope(Zr92, 17.277879*perCent); - Zr->AddIsotope(Zr94, 17.890875*perCent); - Zr->AddIsotope(Zr96, 2.943679*perCent); - - //make natural carbon element -// C = new G4Element("Carbon", "C", 6, 12.011*g/mole); - -// G4NistManager *nistMan = G4NistManager::Instance(); -// C = nistMan->FindOrBuildElement("C"); - - C12 = new G4Isotope("C12", 6, 12, 12.0*g/mole); - C13 = new G4Isotope("C13", 6, 13, 13.00335*g/mole); - - C = new G4Element("Carbon", "C", 2); - C->AddIsotope(C12, 98.83*perCent); - C->AddIsotope(C13, 1.07*perCent); - - - // Create the world material - World = new G4Material("Galactic", 1, 1, 1.e-25*g/cm3, kStateGas, - 2.73*kelvin, 3.e-18*pascal); - - // Create H20 material - H2O = new G4Material("Light Water", 1.*g/cm3, 2, kStateLiquid); - H2O->AddElement(H1,2); - H2O->AddElement(Oxygen,1); - - // Create D20 material - D2O = new G4Material("Heavy Water", 1.1*g/cm3, 2, kStateLiquid); - D2O->AddElement(D2,2); - D2O->AddElement(Oxygen,1); - - - // Create Coolant - Coolant = new G4Material("Coolant", coolantDensity, 2, kStateLiquid, - coolantTemp); - Coolant->AddMaterial(D2O, 99.3777*perCent); - Coolant->AddMaterial(H2O, 0.6223*perCent); - - //Create Pressure Tube - PressureTube = new G4Material("PressureTube", 6.5041*g/cm3, 6, kStateSolid, - 561.285*kelvin); - PressureTube->AddElement(Niobium,2.5800*perCent); - PressureTube->AddElement(Fe,0.04678*perCent); - PressureTube->AddElement(Cr,0.008088*perCent); - PressureTube->AddElement(Ni,0.0035*perCent); - PressureTube->AddElement(Boron,0.00002431*perCent); - PressureTube->AddElement(Zr,97.313*perCent); - - //Create Annulus Gas - AnnulusGas = new G4Material("AnnulusGas", 0.0012*g/cm3, 2, kStateGas, - 448.72*kelvin); - AnnulusGas->AddElement(C,27.11*perCent); - AnnulusGas->AddElement(Oxygen,72.89*perCent); - - //Create Calandra Tube - CalandriaTube = new G4Material("CalandriaTube", 6.4003*g/cm3, 5, - kStateSolid, 336.16*kelvin); - CalandriaTube->AddElement(Fe,0.1370624917*perCent); - CalandriaTube->AddElement(Ni,0.05583986327*perCent); - CalandriaTube->AddElement(Cr,0.1015166605*perCent); - CalandriaTube->AddElement(Zr,99.7055204*perCent); - CalandriaTube->AddElement(Boron,0.00006058385298*perCent); - - //Create Moderator - Moderator = new G4Material("Moderator", moderatorDensity, 2, kStateLiquid, - moderatorTemp); - Moderator->AddMaterial(D2O,99.95895058*perCent); - Moderator->AddMaterial(H2O,0.04104941778*perCent); - - //Create Fuel - Fuel = new G4Material("Fuel", fuelDensity, 2, kStateSolid, fuelTemp); - Fuel->AddElement(Oxygen,11.8502*perCent); - Fuel->AddElement(NU,88.1498*perCent); - - //Create Sheathe - Sheathe = new G4Material("Sheathe", 6.3918*g/cm3, 5, kStateSolid, - 561.285*kelvin); - Sheathe->AddElement(Zr,99.6781689*perCent); - Sheathe->AddElement(Fe,0.213200015*perCent); - Sheathe->AddElement(Cr,0.1015238119*perCent); - Sheathe->AddElement(Ni,0.007106666832*perCent); - Sheathe->AddElement(Boron,0.00006052849665*perCent); - - // Add materials to the map indexed by either ZA (format ZZAAA or ZZ) - // For composite materials: world is 0, heavy water is 1, UHW is 2 - matMap["Galactic"] = World; - matMap["H2O"] = H2O; - matMap["D2O"] = D2O; - matMap["Moderator"] = Moderator; - matMap["Fuel"] = Fuel; - matMap["Sheathe"] = Sheathe; - matMap["CalandriaTube"] = CalandriaTube; - matMap["AnnulusGas"] = AnnulusGas; - matMap["PressureTube"] = PressureTube; - matMap["Coolant"] = Coolant; - - matChanged = false; - - return; -} diff --git a/G4STORK/src/DebugConstructor.cc b/G4STORK/src/DebugConstructor.cc deleted file mode 100755 index f9e3df6f..00000000 --- a/G4STORK/src/DebugConstructor.cc +++ /dev/null @@ -1,1171 +0,0 @@ -#include "DebugConstructor.hh" - -DebugConstructor::DebugConstructor() -: StorkVWorldConstructor(), cellLogical(0), alumShellLogical(0), alumContLogical(0), D2OContLogical(0), reflectorLogical(0), insAlumLogical(0), insBeamLogical(0), - outSmallAlumLogical(0), outLargeAlumLogical(0), cadLinLogical(0), outSmallBeamLogical(0), outLargeBeamLogical(0), coreWaterLogical(0), - coreWaterSliceLogical(0), zircGridLogical(0), airGapsLatLogical(0), /*airGapsLatHLogical(0)*/ airGapsLatHRLogical(0), airGapsLatHR2Logical(0), fuelLatLogical(0), - /*fuelLatHLogical(0)*/ fuelLatHRLogical(0), fuelLatHR2Logical(0), contRodZirLogical(0), contRodAlumLogical(0), contRodCadLogical(0), contRodCentLogical(0) -{ - // Set default member variables (from file or default values) - contRodH = -199.86*cm; - - // Set up variable property map - variablePropMap[MatPropPair(controlrod,position)] = &contRodH; - - cellVisAtt=NULL; - alumShellVisAtt=NULL; - alumContVisAtt=NULL; - D2OContVisAtt=NULL; - reflectorVisAtt=NULL; - insAlumVisAtt=NULL; - insBeamVisAtt=NULL; - outSmallAlumVisAtt=NULL; - outLargeAlumVisAtt=NULL; - cadLinTubeVisAtt=NULL; - outSmallBeamVisAtt=NULL; - outLargeBeamVisAtt=NULL; - coreWaterVisAtt=NULL; - coreWaterSliceVisAtt=NULL; - airGapsLatVisAtt=NULL; - airGapsLatHVisAtt=NULL; - fuelLatVisAtt=NULL; - fuelLatHVisAtt=NULL; - contRodZirVisAtt=NULL; - contRodAlumVisAtt=NULL; - contRodCadVisAtt=NULL; - contRodCentVisAtt=NULL; - -} - -DebugConstructor::~DebugConstructor() -{ - // Delete visualization attributes - if(cellVisAtt) - delete cellVisAtt; - if(alumShellVisAtt) - delete alumShellVisAtt; - if(alumContVisAtt) - delete alumContVisAtt; - if(D2OContVisAtt) - delete D2OContVisAtt; - if(reflectorVisAtt) - delete reflectorVisAtt; - if(insAlumVisAtt) - delete insAlumVisAtt; - if(insBeamVisAtt) - delete insBeamVisAtt; - if(outSmallAlumVisAtt) - delete outSmallAlumVisAtt; - if(outLargeAlumVisAtt) - delete outLargeAlumVisAtt; - if(cadLinTubeVisAtt) - delete cadLinTubeVisAtt; - if(outSmallBeamVisAtt) - delete outSmallBeamVisAtt; - if(outLargeBeamVisAtt) - delete outLargeBeamVisAtt; - if(zircGridVisAtt) - delete zircGridVisAtt; - if(coreWaterVisAtt) - delete coreWaterVisAtt; - if(coreWaterSliceVisAtt) - delete coreWaterSliceVisAtt; - if(airGapsLatVisAtt) - delete airGapsLatVisAtt; - if(airGapsLatHVisAtt) - delete airGapsLatHVisAtt; - if(fuelLatVisAtt) - delete fuelLatVisAtt; - if(fuelLatHVisAtt) - delete fuelLatHVisAtt; - if(contRodZirVisAtt) - delete contRodZirVisAtt; - if(contRodAlumVisAtt) - delete contRodAlumVisAtt; - if(contRodCadVisAtt) - delete contRodCadVisAtt; - if(contRodCentVisAtt) - delete contRodCentVisAtt; - -} - -// ConstructWorld() -// Construct the geometry and materials of the SLOWPOKE Reactor. -G4VPhysicalVolume* DebugConstructor::ConstructWorld() -{ - - - G4SolidStore* theSolids = G4SolidStore::GetInstance(); - - // Aluminum tube position - G4double alumTubePos[4]={14.56182*cm, 0.4*CLHEP::pi, 0., 253.292*cm}; - G4double outAlumTubePos[4]={24.0*cm, 0.4*CLHEP::pi, 0.2*CLHEP::pi,20.834*cm}; - // distance between mother volumes and daughters - G4ThreeVector disCellToAlumShell = G4ThreeVector(-30.*cm,-30.*cm,11.5*cm); - G4ThreeVector disCellToAlumCont = G4ThreeVector(-30.*cm,-30.*cm,-228.958*cm); - G4ThreeVector disAlumContToD2OCont = G4ThreeVector(0.,0.,0.); - G4ThreeVector disCellToCadLin = G4ThreeVector(0.,0.,-228.958*cm); - G4ThreeVector disCadLinToOutAlumTube = G4ThreeVector(0.,0.,249.792*cm); - G4ThreeVector disCellToReflector = G4ThreeVector(-30.*cm,-30.*cm,-228.958*cm); - G4ThreeVector disCellToUpGrid = G4ThreeVector(-30.*cm, -30.*cm, -217.9465*cm); - G4ThreeVector disUpGridToLowGrid = G4ThreeVector(0.,0.,-22.5*cm); - G4ThreeVector disUpGridToSheathe = G4ThreeVector(0.,0.,-10.80975*cm); - G4ThreeVector disSheatheToAirGaps = G4ThreeVector(0.,0.,0.1395*cm); - G4ThreeVector disAirGapsToFuel = G4ThreeVector(0., 0., -0.0875*cm); - G4ThreeVector disCellToContRodZ = G4ThreeVector(-30.*cm, -30.*cm, -228.97075*cm); - G4ThreeVector disCellToContRodA = G4ThreeVector(-30.*cm, -30.*cm, contRodH); - G4ThreeVector disContRodAToContRodCad = G4ThreeVector(0., 0., -5.44*cm); - G4ThreeVector disContRodCadToContRodCent = G4ThreeVector(0., 0., 0.); - - // Set up the materials (if necessary) - if(matChanged) - { - // Delete any existing materials - DestroyMaterials(); - // Create the materials - ConstructMaterials(); - } - - // Clean up volumes - G4GeometryManager::GetInstance()->OpenGeometry(); - G4PhysicalVolumeStore::GetInstance()->Clean(); - G4LogicalVolumeStore::GetInstance()->Clean(); - - // Set up the solids if necessary - if(geomChanged) - { - // Clean up solids - G4SolidStore::GetInstance()->Clean(); - - // Set static dimensions - //Note the format for cylinder dimensions is (inner radius, outer radius, height) - - // Reactor pool dimensions - G4double buffer = 1.0*cm; - // reactor dimension specifies the dimension of the volume for the uniform distribution - reactorDim = G4ThreeVector(0., 11.049*cm, 22.748*cm); - - G4ThreeVector cellDim = G4ThreeVector(0., 133.0*cm, 564.0*cm); - - // World dimensions - encWorldDim = G4ThreeVector(cellDim[2]+buffer,cellDim[2]+buffer, cellDim[2]+buffer); - - // Aluminium Reactor Shell - G4double alumShellTubeDim[3] = {30.0*cm, 31.0*cm, 541.0*cm}; - G4double alumShellPlateDim[3] = {0.0*cm, 31.0*cm, 1*cm}; - - // D2O Column - G4double alumContPart1TubeDim[3] = {21.2344*cm+0.01, 30.0*cm-0.01, 22.748*cm}; - G4double alumContPart2TubeDim[3] = {0.*cm, 35.0*cm, 30*cm}; - G4ThreeVector alumContTrans = G4ThreeVector(1.530179074*cm, 0., 0.); - G4double D2OTubeDim[3] = {22.2344*cm, 29.0*cm, 20.6975*cm}; - - // Reflector dimensions - // made top shim a half circle which is is slightly off from the actual shape - G4double refAnnDim[3] = {11.049*cm+0.1, 21.2344*cm, 22.748*cm}; - G4double refBottomDim[3] = {0.0*cm, 16.113125*cm, 10.16*cm}; - G4double refTopDim[3] = {1.3890625*cm, 12.065*cm, 0.15875*cm}; - - // Beamtube dimensions - G4double smallBTubeDim[3] = {0.0*cm, 1.40208*cm, 515.332*cm}; - G4double smallLongBTubeDim[3] = {0.0*cm, 1.40208*cm, 522.332*cm}; - G4double largeBTubeDim[3] = {0.0*cm, 1.6*cm, 522.332*cm}; - // Aluminium Tube dimensions - G4double smallAlumTubeDim[3] = {0.0*cm, 1.56718*cm, 515.332*cm}; - G4double smallLongAlumTubeDim[3] = {0.0*cm, 1.56718*cm, 522.332*cm}; - G4double largeAlumTubeDim[3] = {0.0*cm, 1.905*cm, 522.332*cm}; - // Cadmium lining - G4double cadLinTubeDim[3] = {0.0*cm, 1.61798*cm, 22.748*cm}; - // Control Rod - G4double contRodCentTubeDim[3] = {0.0*cm, 0.09652*cm, 24.76*cm}; - G4double contRodCadTubeDim[3] = {0.0*cm, 0.14732*cm, 24.76*cm}; - G4double contRodAlumTubeDim[3] = {0.0*cm, 0.62357*cm, 40.64*cm}; - G4double contRodZirTubeDim[3] = {1.229*cm, 1.331*cm-.01, 23.2335*cm}; - - // Sheathe dimensions, height extends from bottom of lower grid plate to to the top of the top endcap - G4double sheatheDim[3] = {0., 0.262*cm , 23.6595*cm}; - // Sheathe dimensions, height extends from bottom of lower grid plate to to the top of the top endcap - G4double airGapDim[3] = {0., 0.212*cm , 23.1105*cm}; - // Fuel pin dimensions - G4double fuelPinDim[3] = {0., 0.2064*cm , 22.6975*cm}; - - //Lattice Matrix - G4int latticeMat[13][25] ={{7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7}, - {7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7}, - {7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 9, 8, 9, 8, 9, 8, 8, 7, 7, 7}, - {7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 9, 8, 9, 9, 8, 8, 9, 9, 8, 8, 8, 7, 7}, - {7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 9, 8, 9, 8, 9, 8, 9, 8, 8, 8, 7, 7}, - {7, 7, 7, 7, 7, 7, 7, 7, 8, 9, 9, 9, 9, 8, 8, 9, 9, 8, 8, 9, 9, 9, 9, 8, 7}, - {7, 7, 7, 7, 7, 7, 7, 8, 8, 9, 8, 8, 9, 8, 9, 8, 9, 8, 9, 8, 8, 9, 8, 8, 7}, - {7, 7, 7, 7, 7, 7, 8, 9, 8, 9, 8, 8, 8, 9, 8, 8, 9, 8, 8, 8, 9, 8, 9, 8, 7}, - {7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 9, 8, 9, 9, 9, 9, 8, 8, 8, 8, 7}, - {7, 7, 7, 7, 7, 9, 9, 9, 9, 8, 8, 8, 8, 9, 9, 8, 8, 8, 8, 9, 9, 9, 9, 7, 7}, - {7, 7, 7, 7, 8, 9, 8, 8, 9, 8, 9, 9, 9, 8, 9, 9, 9, 8, 9, 8, 8, 9, 8, 7, 7}, - {7, 7, 7, 8, 8, 9, 8, 8, 9, 8, 9, 8, 9, 9, 8, 9, 8, 9, 8, 8, 9, 8, 8, 7, 7}, - {7, 7, 7, 8, 8, 9, 9, 8, 9, 8, 8, 9, 7, 9, 8, 8, 9, 8, 9, 9, 8, 8, 7, 7, 7}}; - - // Lattice cell dimensions - // hole pattern format radius, angle of increment and the offset angle, check radius - G4double latticeCellDim[3] = {1.103667393*cm, 0.955804*cm, 0.279*cm}; - G4double gridPlateDim[3] = {1.331*cm, 11.049*cm, 0.279*cm}; - G4double lowGridHolesDim[3] = {0., 0.262*cm, 0.3*cm}; - G4double lowGridCentreHoleDim[3] = {0., 0.15*cm, 0.3*cm}; - G4double upperGridHolesDim[3]= {0., 0.19*cm, 0.3*cm}; - G4double holePat[3]= {0.637286*cm, CLHEP::pi/3, CLHEP::pi/6}; - G4double unitRegDim[6]={0, (gridPlateDim[1]-gridPlateDim[0])/10, 0., CLHEP::pi/(3*10), 0., 0.3*cm}; - G4double regDim[6]={gridPlateDim[0], gridPlateDim[1], CLHEP::pi/3, 2*CLHEP::pi/3, -gridPlateDim[2]/2, gridPlateDim[2]/2}; - - - //Geometry positioning data - std::stringstream latticeType1; - G4ThreeVector latCellPos; - G4ThreeVector holePos; - G4ThreeVector holeRPos; - - // Create world solid - new G4Box("worldBox", encWorldDim[0]/2, encWorldDim[1]/2, encWorldDim[2]/2); - - // Create cell solid - new G4Tubs("cellTube", 0., cellDim[1], cellDim[2]/2, 0., 2.0*CLHEP::pi); - - // Create Aluminium Shell - new G4Tubs("alumShellTube", alumShellTubeDim[0], alumShellTubeDim[1], alumShellTubeDim[2]/2, 0., 2.0*CLHEP::pi); - new G4Tubs("alumShellPlate", alumShellPlateDim[0], alumShellPlateDim[1], alumShellPlateDim[2]/2, 0., 2.0*CLHEP::pi); - new G4UnionSolid("alumShell", theSolids->GetSolid("alumShellTube"), theSolids->GetSolid("alumShellPlate"), 0, G4ThreeVector(0., 0., -271.*cm)); - - // Create D2O Column - new G4Tubs("alumContPart1Tube", alumContPart1TubeDim[0], alumContPart1TubeDim[1], alumContPart1TubeDim[2]/2, 0., 2.0*CLHEP::pi); - new G4Tubs("alumContPart2Tube", alumContPart2TubeDim[0], alumContPart2TubeDim[1], alumContPart2TubeDim[2]/2, 3.5319927*rad, 5.502385213*rad); - new G4SubtractionSolid("alumContTube", theSolids->GetSolid("alumContPart1Tube"), theSolids->GetSolid("alumContPart2Tube"), 0, alumContTrans); - new G4Tubs("D2OTube", D2OTubeDim[0], D2OTubeDim[1], D2OTubeDim[2]/2, 2.751192606*rad, 0.780800094*rad); - - // Create Reflector Solids - new G4Tubs("reflectTop", refTopDim[0], refTopDim[1], refTopDim[2]/2, 0., CLHEP::pi); - new G4Tubs("reflectAnnulus", refAnnDim[0], refAnnDim[1], refAnnDim[2]/2, 0., 2.0*CLHEP::pi); - new G4Tubs("reflectBottom", refBottomDim[0], refBottomDim[1], refBottomDim[2]/2, 0., 2.0*CLHEP::pi); - new G4UnionSolid("reflectorP1", theSolids->GetSolid("reflectAnnulus"), theSolids->GetSolid("reflectTop"), 0, G4ThreeVector(0., 0., 13.969375*cm)); - new G4UnionSolid("reflector", theSolids->GetSolid("reflectorP1"), theSolids->GetSolid("reflectBottom"), 0, G4ThreeVector(0., 0., -16.962*cm)); - - // Create Aluminium Tube Solids - new G4Tubs("smallAlumTube", smallAlumTubeDim[0], smallAlumTubeDim[1], smallAlumTubeDim[2]/2, 0., 2.0*CLHEP::pi); - new G4Tubs("smallLongAlumTube", smallLongAlumTubeDim[0], smallLongAlumTubeDim[1], smallLongAlumTubeDim[2]/2, 0., 2.0*CLHEP::pi); - new G4Tubs("largeAlumTube", largeAlumTubeDim[0], largeAlumTubeDim[1], largeAlumTubeDim[2]/2, 0., 2.0*CLHEP::pi); - - // Create Beam Tube Solids - new G4Tubs("smallBeamTube", smallBTubeDim[0], smallBTubeDim[1], smallBTubeDim[2]/2, 0., 2.0*CLHEP::pi); - new G4Tubs("smallLongBeamTube", smallLongBTubeDim[0], smallLongBTubeDim[1], smallLongBTubeDim[2]/2, 0., 2.0*CLHEP::pi); - new G4Tubs("cadLinTube", cadLinTubeDim[0], cadLinTubeDim[1], cadLinTubeDim[2]/2, 0., 2.0*CLHEP::pi); - new G4Tubs("largeBeamTube", largeBTubeDim[0], largeBTubeDim[1], largeBTubeDim[2]/2, 0., 2.0*CLHEP::pi); - - // Create Fuel Bundle - -// //create the mothervolume for a 1/3 slice of the fuel bundle (contains a reflected pair of 1/6 slices of the fuel bundle) - new G4Box("testBox", 0.5*cm, 0.5*cm, 0.5*cm); -// - //create the mothervolume containing the full fuel bundle (contains the replication of core water slice) - new G4Tubs("coreWater", contRodZirTubeDim[1], refAnnDim[0], sheatheDim[2]/2, 0., 2*CLHEP::pi); - //create the mothervolume for a 1/3 slice of the fuel bundle (contains a reflected pair of 1/6 slices of the fuel bundle) - new G4Tubs("coreWaterSlice", contRodZirTubeDim[1], refAnnDim[0], sheatheDim[2]/2, CLHEP::pi/3, 2*CLHEP::pi/3); - - //creates the base zirconium grid slice that the holes will be subtracted from to form the upper and lower grid plate - new G4Tubs("gridPlate", gridPlateDim[0], gridPlateDim[1], gridPlateDim[2]/2, CLHEP::pi/3, CLHEP::pi/3); - - // creates the three types of holes to be used to create the two hole patterns, the upGridHolesLat and lowGridHolesLat - new G4Tubs("upGridHole", upperGridHolesDim[0], upperGridHolesDim[1], upperGridHolesDim[2]/2, 0., 2.0*CLHEP::pi); - new G4Tubs("lowGridHole", lowGridHolesDim[0], lowGridHolesDim[1], lowGridHolesDim[2]/2, 0., 2.0*CLHEP::pi); - new G4Tubs("lowGridCentreHole", lowGridCentreHoleDim[0], lowGridCentreHoleDim[1], lowGridCentreHoleDim[2]/2, 0., 2.0*CLHEP::pi); - // Create the sheathe for fuel pins - new G4Tubs("sheatheTube", sheatheDim[0], sheatheDim[1], sheatheDim[2]/2, 0., 2.0*CLHEP::pi); - new G4Tubs("sheatheTubeHR", sheatheDim[0], sheatheDim[1], sheatheDim[2]/2, CLHEP::pi/3, CLHEP::pi); - new G4Tubs("sheatheTubeHR2", sheatheDim[0], sheatheDim[1], sheatheDim[2]/2, 5*CLHEP::pi/3, CLHEP::pi); - - // Create the Air Gaps between the fuel and the sheathe - new G4Tubs("airGaps", airGapDim[0], airGapDim[1], airGapDim[2]/2, 0., 2.0*CLHEP::pi); -// new G4Tubs("airGapsH", airGapDim[0], airGapDim[1], airGapDim[2]/2, 0., CLHEP::pi); - new G4Tubs("airGapsHR", airGapDim[0], airGapDim[1], airGapDim[2]/2, 2*CLHEP::pi/3, CLHEP::pi); - new G4Tubs("airGapsHR2", airGapDim[0], airGapDim[1], airGapDim[2]/2, CLHEP::pi/3, CLHEP::pi); - - // Create a fuel pins - new G4Tubs("fuelPin", fuelPinDim[0], fuelPinDim[1], fuelPinDim[2]/2, 0., 2.0*CLHEP::pi); -// new G4Tubs("fuelPinH", fuelPinDim[0], fuelPinDim[1], fuelPinDim[2]/2, 0., CLHEP::pi); - new G4Tubs("fuelPinHR", fuelPinDim[0], fuelPinDim[1], fuelPinDim[2]/2, 2*CLHEP::pi/3, CLHEP::pi); - new G4Tubs("fuelPinHR2", fuelPinDim[0], fuelPinDim[1], fuelPinDim[2]/2, CLHEP::pi/3, CLHEP::pi); - - solidList upperGridHoles; - solidList lowerGridHoles; - solidList sheatheTubes; - G4int i=3; - G4int j=12; - G4double rho; - G4double phi; - while (i<12) - { - while (j<25) - { - if(latticeMat[i][j]==8) - { - latCellPos.set(((12-i)*(-latticeCellDim[0]*0.5)+(j-12)*latticeCellDim[0]), ((12-i)*(latticeCellDim[1])), 0.); - for(G4int k=0; k<6; k++) - { - holeRPos.set(holePat[0]*cos(holePat[1]*(k)+holePat[2]), holePat[0]*sin(holePat[1]*(k)+holePat[2]),0.); - holePos=latCellPos+holeRPos; - phi = holePos.phi(); - rho = holePos.rho(); - - if((phi>=CLHEP::pi/3)&&(phi<=2*CLHEP::pi/3)&&(rho>gridPlateDim[0])&&(rhoGetSolid("upGridHole"), holePos)); - lowerGridHoles.push_back(std::make_pair(theSolids->GetSolid("lowGridHole"), holePos)); - } - } - latticeType1.str(""); - if(i==j) - latticeType1 << "HR"; - else if(j==12) - latticeType1 << "HR2"; - - sheatheTubes.push_back(std::make_pair(theSolids->GetSolid("sheatheTube"+latticeType1.str()), latCellPos)); - } - else if(latticeMat[i][j]==9) - { - latCellPos.set(((12-i)*(-latticeCellDim[0]*0.5)+(j-12)*latticeCellDim[0]), ((12-i)*(latticeCellDim[1])), 0.); - for(G4int k=0; k<6; k++) - { - holeRPos.set(holePat[0]*cos(holePat[1]*(k)+holePat[2]), holePat[0]*sin(holePat[1]*(k)+holePat[2]),0.); - holePos=latCellPos+holeRPos; - phi = holePos.phi(); - rho = holePos.rho(); - - if((phi>=CLHEP::pi/3)&&(phi<=2*CLHEP::pi/3)&&(rho>gridPlateDim[0])&&(rhoGetSolid("upGridHole"), holePos)); - lowerGridHoles.push_back(std::make_pair(theSolids->GetSolid("lowGridHole"), holePos)); - } - } - - lowerGridHoles.push_back(std::make_pair(theSolids->GetSolid("lowGridCentreHole"), latCellPos)); - } - j++; - } - j=12; - i++; - } - - UnionBinaryTree* upGridHolesLat = new UnionBinaryTree(&upperGridHoles); - //UnionBinaryTree* lowGridHolesLat = new UnionBinaryTree(&lowerGridHoles); - //UnionBinaryTree* sheatheTubeLat = new UnionBinaryTree(&sheatheTubes); - - solidPos upGridHolesLatPair = upGridHolesLat->GetUnionSolid("upGridHolesLat", 0, cylUnit, unitRegDim, regDim, 0.0, radCyl, 1.0, NULL, true); -// solidPos lowGridHolesLatPair = lowGridHolesLat->GetUnionSolid("lowGridHolesLat", 0, cylUnit, unitRegDim, regDim, 0.0, radCyl, 1.0, NULL, true); -// solidPos sheatheTubeLatPair = sheatheTubeLat->GetUnionSolid("sheatheTubeLat", 0, cylUnit, unitRegDim, regDim, 0.0, radCyl, 1.0, NULL, true); - - // creates the upGridPlate and the lowGridPlate from the unions of the upGridHolesLat and lowGridHolesLat with the base gridPlate - new G4SubtractionSolid("upGridPlate", theSolids->GetSolid("gridPlate"), upGridHolesLatPair.first, 0, upGridHolesLatPair.second); -// new G4SubtractionSolid("lowGridPlate", theSolids->GetSolid("gridPlate"), lowGridHolesLatPair.first, 0, lowGridHolesLatPair.second); -// -// // creates the zirconium grid slice (zircGridPlate) from the union of the upGridPlate and the lowGridPlate -// new G4UnionSolid("zircGridSliceP1", theSolids->GetSolid("upGridPlate"), theSolids->GetSolid("lowGridPlate"), 0, disUpGridToLowGrid); -// new G4UnionSolid("zircGridSlice", theSolids->GetSolid("zircGridSliceP1"), sheatheTubeLatPair.first, 0, sheatheTubeLatPair.second); - - - - //creates a reflection of the zirconium grid slice -// new G4ReflectedSolid("zircGridSliceRefl", theSolids->GetSolid("zircGridSlice") , G4ReflectY3D()); -// -// zRot->rotateZ(-CLHEP::pi/3); -// -// //creates the full ziconium grid by adding up the slices -// new G4UnionSolid("zircGridPlate1/3", theSolids->GetSolid("zircGridSlice"), theSolids->GetSolid("zircGridSliceRefl"), 0, G4ThreeVector(0.,0.,0.)); -// -// new G4UnionSolid("zircGridPlate2/3", theSolids->GetSolid("zircGridPlate1/3"), theSolids->GetSolid("zircGridPlate1/3"), G4Transform3D(*zRot, originHoleSec[0])); -// -// zRot->rotateZ(-2*CLHEP::pi/3); -// -// new G4UnionSolid("zircGridPlate", theSolids->GetSolid("zircGridPlate2/3"), theSolids->GetSolid("zircGridPlate1/3"), G4Transform3D(*zRot, originHoleSec[0])); - - - // Created the Control Rod Solids - new G4Tubs("contRodCentTube", contRodCentTubeDim[0], contRodCentTubeDim[1], contRodCentTubeDim[2]/2, 0., 2.0*CLHEP::pi); - new G4Tubs("contRodCadTube", contRodCadTubeDim[0], contRodCadTubeDim[1], contRodCadTubeDim[2]/2, 0., 2.0*CLHEP::pi); - new G4Tubs("contRodAlumTube", contRodAlumTubeDim[0], contRodAlumTubeDim[1], contRodAlumTubeDim[2]/2, 0., 2.0*CLHEP::pi); - new G4Tubs("contRodZirTube", contRodZirTubeDim[0], contRodZirTubeDim[1], contRodZirTubeDim[2]/2, 0., 2.0*CLHEP::pi); - - geomChanged = false; - latticeType1.str(""); - } - - //Initialize stringstream for volume naming purposes - std::stringstream volName; - // Initialize positioning objects - G4ThreeVector volPos; - - // Create world volume - worldLogical = new G4LogicalVolume(theSolids->GetSolid("worldBox"), - matMap["Galactic"],"worldLogical"); - worldPhysical = new G4PVPlacement(0, G4ThreeVector(0,0,0.), worldLogical, - "worldPhysical",0,0,0); - - // Create the lattice cell (moderator) volume - cellLogical = new G4LogicalVolume(theSolids->GetSolid("cellTube"), - matMap["H2O"],"cellLogical"); - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), cellLogical,"cellPhysical", - worldLogical,0,0); - - // all objects inside the cell are offset by (-30.0cm,-30cm,0) - //create aluminium shell - alumShellLogical = new G4LogicalVolume(theSolids->GetSolid("alumShell"), - matMap["AlAlloy1"],"alumShellLogical"); - new G4PVPlacement(0, disCellToAlumShell, alumShellLogical,"alumShellPhysical", - cellLogical,0,0); - - alumContLogical = new G4LogicalVolume(theSolids->GetSolid("alumContTube"), - matMap["AlAlloy2"],"alumContLogical"); - new G4PVPlacement(0, disCellToAlumCont, alumContLogical,"alumContPhysical", cellLogical,0,0); - - //create heavy water - D2OContLogical = new G4LogicalVolume(theSolids->GetSolid("D2OTube"), - matMap["D2O"],"D2OContLogical"); - new G4PVPlacement(0, disAlumContToD2OCont, D2OContLogical,"D2OContPhysical", - alumContLogical,0,0); - - //create aluminium container - reflectorLogical = new G4LogicalVolume(theSolids->GetSolid("reflector"), - matMap["Reflector"],"reflectorLogical"); - new G4PVPlacement(0, disCellToReflector, reflectorLogical,"reflectorPhysical", - cellLogical,0,0); - - insAlumLogical = new G4LogicalVolume(theSolids->GetSolid("smallAlumTube"), - matMap["AlAlloy3"],"insAlumLogical"); - - for (G4int i=0; i<5; i++) - { - volName.str(""); - volName << i; - volPos.set((alumTubePos[0]*cos(alumTubePos[1]*i+alumTubePos[2])), (alumTubePos[0]*sin(alumTubePos[1]*i+alumTubePos[2])), alumTubePos[3]); - new G4PVPlacement(0, volPos, insAlumLogical,"insAlumTubePhysical"+volName.str(), reflectorLogical,0,0); - } - - insBeamLogical = new G4LogicalVolume(theSolids->GetSolid("smallBeamTube"), - matMap["Air"],"insBeamLogical"); - new G4PVPlacement(0, G4ThreeVector(0., 0., 0.), insBeamLogical,"insBeamTubePhysical", - insAlumLogical,0,0); - - - outSmallAlumLogical = new G4LogicalVolume(theSolids->GetSolid("smallLongAlumTube"), - matMap["AlAlloy1"],"outAlumTubeLogical"); - outLargeAlumLogical = new G4LogicalVolume(theSolids->GetSolid("largeAlumTube"), - matMap["AlAlloy1"],"outAlumTubeLogical"); - cadLinLogical = new G4LogicalVolume(theSolids->GetSolid("cadLinTube"), - matMap["Cadmium"],"cadLinLogical"); - - volPos.set(outAlumTubePos[0]*cos(outAlumTubePos[2])-30.0*cm, - outAlumTubePos[0]*sin(outAlumTubePos[2])-30.0*cm, outAlumTubePos[3]); - - new G4PVPlacement(0, volPos, outLargeAlumLogical,"outLargeAlumTubePhysical", cellLogical,0,0); - - volPos.set(outAlumTubePos[0]*cos(outAlumTubePos[1]*3+outAlumTubePos[2])-30.0*cm, - outAlumTubePos[0]*sin(outAlumTubePos[1]*3+outAlumTubePos[2])-30.0*cm,0.); - - new G4PVPlacement(0, volPos+disCellToCadLin, cadLinLogical,"cadLinTubePhysical", cellLogical,0,0); - new G4PVPlacement(0, disCadLinToOutAlumTube, outSmallAlumLogical,"outSmallAlumTubePhysical2", cadLinLogical,0,0); - - volPos.set(outAlumTubePos[0]*cos(outAlumTubePos[1]*1+outAlumTubePos[2])-30.0*cm, - outAlumTubePos[0]*sin(outAlumTubePos[1]*1+outAlumTubePos[2])-30.0*cm, outAlumTubePos[3]); - - new G4PVPlacement(0, volPos, outSmallAlumLogical,"outSmallAlumTubePhysical1", cellLogical,0,0); - - volPos.set(outAlumTubePos[0]*cos(outAlumTubePos[1]*4+outAlumTubePos[2])-30.0*cm, - outAlumTubePos[0]*sin(outAlumTubePos[1]*4+outAlumTubePos[2])-30.0*cm, outAlumTubePos[3]); - - new G4PVPlacement(0, volPos, outSmallAlumLogical,"outSmallAlumTubePhysical3", cellLogical,0,0); - - - - outSmallBeamLogical = new G4LogicalVolume(theSolids->GetSolid("smallLongBeamTube"), - matMap["Air"],"outSmallBeamLogical"); - new G4PVPlacement(0, G4ThreeVector(0., 0., 0.), outSmallBeamLogical,"outSmallBeamTubePhysical", - outSmallAlumLogical,0,0); - outLargeBeamLogical = new G4LogicalVolume(theSolids->GetSolid("largeBeamTube"), - matMap["Air"],"outLargeBeamLogical"); - new G4PVPlacement(0, G4ThreeVector(0., 0., 0.), outLargeBeamLogical,"outLargeBeamTubePhysical", - outLargeAlumLogical,0,0); - - //Create fuel bundle - //mother volume for replicas -// coreWaterLogical = new G4LogicalVolume(theSolids->GetSolid("coreWater"), -// matMap["H2O"], "coreWaterLogical"); -// new G4PVPlacement(0, disCellToUpGrid+disUpGridToSheathe, coreWaterLogical,"coreWaterPhysical", -// cellLogical,0,0); -// -// //mother volume for the reflected pair of the fuel bundle slice -// coreWaterSliceLogical = new G4LogicalVolume(theSolids->GetSolid("coreWaterSlice"), -// matMap["H2O"], "coreWaterSliceLogical"); -// -// new G4PVPlacement(0, G4ThreeVector(0., 0., 0.), coreWaterSliceLogical,"coreWaterSlicePhysical", -// coreWaterLogical,0,0); - -// //create Zirconium grid plates - zircGridLogical = new G4LogicalVolume(theSolids->GetSolid("upGridPlate"), matMap["Zirconium"], "zircGridLogical"); - - new G4PVPlacement(0, disCellToUpGrid, zircGridLogical,"zircGridSlicePhysical", - cellLogical,0,0,0); - -//create Zirconium grid plates -// zircGridLogical = new G4LogicalVolume(theSolids->GetSolid("testBox"), matMap["Zirconium"], "zircGridLogical"); -// -// new G4PVPlacement(0, G4ThreeVector(-5.0*cm,0.,0.), zircGridLogical,"zircGridSlicePhysical", -// coreWaterSliceLogical,0,0,0); - -//// Create the air gaps -// airGapsLatLogical = new G4LogicalVolume(theSolids->GetSolid("airGaps"), -// matMap["Zirconium"], "airGapsLatLogical"); -// -//// airGapsLatHLogical = new G4LogicalVolume(theSolids->GetSolid("airGapsH"), -//// matMap["Zirconium"], "airGapsLatLogical"); -// -// airGapsLatHRLogical = new G4LogicalVolume(theSolids->GetSolid("airGapsHR"), -// matMap["Zirconium"], "airGapsLatLogical"); -// -// airGapsLatHR2Logical = new G4LogicalVolume(theSolids->GetSolid("airGapsHR2"), -// matMap["Zirconium"], "airGapsLat2Logical"); -// -// fuelLatLogical = new G4LogicalVolume(theSolids->GetSolid("fuelPin"), matMap["Fuel"], "fuelLatLogical"); -// new G4PVPlacement(0, disAirGapsToFuel, fuelLatLogical,"fuelLatPhysical", airGapsLatLogical,0,0,0); -// -//// fuelLatHLogical = new G4LogicalVolume(theSolids->GetSolid("fuelPinH"), matMap["Fuel"], "fuelLatHLogical"); -//// new G4PVPlacement(0, disAirGapsToFuel, fuelLatHLogical,"fuelLatHPhysical", airGapsLatHLogical,0,0,0); -// -// fuelLatHRLogical = new G4LogicalVolume(theSolids->GetSolid("fuelPinHR"), matMap["Fuel"], "fuelLatHRLogical"); -// new G4PVPlacement(0, disAirGapsToFuel, fuelLatHRLogical,"fuelLatHRPhysical", airGapsLatHRLogical,0,0,0); -// -// fuelLatHR2Logical = new G4LogicalVolume(theSolids->GetSolid("fuelPinHR2"), matMap["Fuel"], "fuelLatHR2Logical"); -// new G4PVPlacement(0, disAirGapsToFuel, fuelLatHR2Logical,"fuelLatHR2Physical", airGapsLatHR2Logical,0,0,0); -// -// G4int k=0; -// G4int i=3; -// G4int j=1; -// G4int g=13; -// G4bool check=false; -// -// while (i<22) -// { -// if(i>12) -// { -// g=g-1; -// check=true; -// } -// -// while (jPlace(G4ReflectY3D(), "reflZircGridSlice", -// zircGridLogical, coreWaterSliceLogical, 0, 0); - - //Replicate the mother volume of the reflected slices -// new G4PVReplica("zircGridPhysical", coreWaterSliceLogical, coreWaterLogical, kPhi, 3, 2*CLHEP::pi/3); - -// G4RotationMatrix* zRot = new G4RotationMatrix(); -// zRot->rotateZ(2*CLHEP::pi/3); -// -// new G4PVPlacement(G4Transform3D(*zRot, G4ThreeVector(0., 0., 0.)), coreWaterSliceLogical,"coreWaterSlicePhysical1", -// coreWaterLogical,0,0); -// -// new G4PVPlacement(0, G4ThreeVector(0., 0., 0.), coreWaterSliceLogical,"coreWaterSlicePhysical2", -// coreWaterLogical,0,0); -// -// zRot->rotateZ(2*CLHEP::pi/3); -// new G4PVPlacement(G4Transform3D(*zRot, G4ThreeVector(0., 0., 0.)), coreWaterSliceLogical,"coreWaterSlicePhysical3", -// coreWaterLogical,0,0); -// -// delete zRot; - - //Create the control rod - contRodZirLogical = new G4LogicalVolume(theSolids->GetSolid("contRodZirTube"), - matMap["Zirconium"], "contRodZirLogical"); - new G4PVPlacement(0, disCellToContRodZ, contRodZirLogical,"contRodZirPhysical", - cellLogical,0,0); - - contRodAlumLogical = new G4LogicalVolume(theSolids->GetSolid("contRodAlumTube"), - matMap["AlAlloy4"], "contRodAlumLogical"); - new G4PVPlacement(0, disCellToContRodA, contRodAlumLogical,"contRodAlumPhysical", - cellLogical,0,0); - - contRodCadLogical = new G4LogicalVolume(theSolids->GetSolid("contRodCadTube"), - matMap["Cadmium"], "contRodCadLogical"); - new G4PVPlacement(0, disContRodAToContRodCad, contRodCadLogical,"contRodCadPhysical", - contRodAlumLogical,0,0); - - contRodCentLogical = new G4LogicalVolume(theSolids->GetSolid("contRodCentTube"), - matMap["Air"], "contRodCentLogical"); - new G4PVPlacement(0, disContRodCadToContRodCent, contRodCentLogical,"contRodCentPhysical", - contRodCadLogical,0,0); - - // Add sensitive detector to ALL logical volumes - worldLogical->SetSensitiveDetector( sDReactor ); - cellLogical->SetSensitiveDetector( sDReactor ); - alumShellLogical->SetSensitiveDetector( sDReactor ); - alumContLogical->SetSensitiveDetector( sDReactor ); - D2OContLogical->SetSensitiveDetector( sDReactor ); - reflectorLogical->SetSensitiveDetector( sDReactor ); - insAlumLogical->SetSensitiveDetector( sDReactor ); - insBeamLogical->SetSensitiveDetector( sDReactor ); - outSmallAlumLogical->SetSensitiveDetector( sDReactor ); - outLargeAlumLogical->SetSensitiveDetector( sDReactor ); - cadLinLogical->SetSensitiveDetector( sDReactor ); - outSmallBeamLogical->SetSensitiveDetector( sDReactor ); - outLargeBeamLogical->SetSensitiveDetector( sDReactor ); -// coreWaterLogical->SetSensitiveDetector( sDReactor ); -// coreWaterSliceLogical->SetSensitiveDetector( sDReactor ); - zircGridLogical->SetSensitiveDetector( sDReactor ); -// airGapsLatLogical->SetSensitiveDetector( sDReactor ); -//// airGapsLatHLogical->SetSensitiveDetector( sDReactor ); -// airGapsLatHRLogical->SetSensitiveDetector( sDReactor ); -// airGapsLatHR2Logical->SetSensitiveDetector( sDReactor ); -// fuelLatLogical->SetSensitiveDetector( sDReactor ); -//// fuelLatHLogical->SetSensitiveDetector( sDReactor ); -// fuelLatHRLogical->SetSensitiveDetector( sDReactor ); -// fuelLatHR2Logical->SetSensitiveDetector( sDReactor ); - contRodZirLogical->SetSensitiveDetector( sDReactor ); - contRodAlumLogical->SetSensitiveDetector( sDReactor ); - contRodCadLogical->SetSensitiveDetector( sDReactor ); - contRodCentLogical->SetSensitiveDetector( sDReactor ); - - - // Set visualization attributes - - if(worldVisAtt) - delete worldVisAtt; - if(cellVisAtt) - delete cellVisAtt; - if(alumShellVisAtt) - delete alumShellVisAtt; - if(alumContVisAtt) - delete alumContVisAtt; - if(D2OContVisAtt) - delete D2OContVisAtt; - if(reflectorVisAtt) - delete reflectorVisAtt; - if(insAlumVisAtt) - delete insAlumVisAtt; - if(insBeamVisAtt) - delete insBeamVisAtt; - if(outSmallAlumVisAtt) - delete outSmallAlumVisAtt; - if(outLargeAlumVisAtt) - delete outLargeAlumVisAtt; - if(cadLinTubeVisAtt) - delete cadLinTubeVisAtt; - if(outSmallBeamVisAtt) - delete outSmallBeamVisAtt; - if(outLargeBeamVisAtt) - delete outLargeBeamVisAtt; - if(zircGridVisAtt) - delete zircGridVisAtt; - if(coreWaterVisAtt) - delete coreWaterVisAtt; - if(coreWaterSliceVisAtt) - delete coreWaterSliceVisAtt; - if(airGapsLatVisAtt) - delete airGapsLatVisAtt; - if(airGapsLatHVisAtt) - delete airGapsLatHVisAtt; - if(fuelLatVisAtt) - delete fuelLatVisAtt; - if(fuelLatHVisAtt) - delete fuelLatHVisAtt; - if(contRodZirVisAtt) - delete contRodZirVisAtt; - if(contRodAlumVisAtt) - delete contRodAlumVisAtt; - if(contRodCadVisAtt) - delete contRodCadVisAtt; - if(contRodCentVisAtt) - delete contRodCentVisAtt; - - worldVisAtt = new G4VisAttributes(G4Colour(1.,1.,1.)); - worldVisAtt->SetVisibility(false); - worldLogical->SetVisAttributes(worldVisAtt); - -// light blue - cellVisAtt = new G4VisAttributes(G4Colour(47.0/255.0,225.0/255.0,240.0/255.0)); - cellVisAtt->SetVisibility(false); - cellLogical->SetVisAttributes(cellVisAtt); - -//dark yellow - alumShellVisAtt = new G4VisAttributes(G4Colour(210.0/255.0,172.0/255.0,0.0/255.0)); - alumShellVisAtt->SetVisibility(false); - alumShellLogical->SetVisAttributes(alumShellVisAtt); - -//light orange - alumContVisAtt = new G4VisAttributes(G4Colour(255.0/255.0,173.0/255.0,0.0/255.0)); - alumContVisAtt->SetVisibility(false); - alumContLogical->SetVisAttributes(alumContVisAtt); - -//dark blue - D2OContVisAtt = new G4VisAttributes(G4Colour(0.,0.,210.0/255.0)); - D2OContVisAtt->SetVisibility(false); - D2OContLogical->SetVisAttributes(D2OContVisAtt); - -//dark gray - reflectorVisAtt = new G4VisAttributes(G4Colour(45.0/255.0,45.0/255.0,45.0/255.0)); - reflectorVisAtt->SetVisibility(false); - reflectorLogical->SetVisAttributes(reflectorVisAtt); - -//light purple - insAlumVisAtt = new G4VisAttributes(G4Colour(192.0/255.0,0.0/255.0,255.0/255.0)); - insAlumVisAtt->SetVisibility(false); - insAlumLogical->SetVisAttributes(insAlumVisAtt); - - insBeamVisAtt = new G4VisAttributes(G4Colour(183.0/255.0,230.0/255.0,240.0/255.0)); - insBeamVisAtt->SetVisibility(false); - insBeamLogical->SetVisAttributes(insBeamVisAtt); - -//dark purple - outSmallAlumVisAtt = new G4VisAttributes(G4Colour(70.0/255.0,0.0/255.0,74.0/255.0)); - outSmallAlumVisAtt->SetVisibility(false); - outSmallAlumLogical->SetVisAttributes(outSmallAlumVisAtt); - -//dark green - outLargeAlumVisAtt = new G4VisAttributes(G4Colour(63.0/255.0,119.0/255.0,0.0/255.0)); - outLargeAlumVisAtt->SetVisibility(false); - outLargeAlumLogical->SetVisAttributes(outLargeAlumVisAtt); - -//dark orange - cadLinTubeVisAtt = new G4VisAttributes(G4Colour(164.0/255.0,57.0/255.0,0.0/255.0)); - cadLinTubeVisAtt->SetVisibility(false); - cadLinLogical->SetVisAttributes(cadLinTubeVisAtt); - - outSmallBeamVisAtt = new G4VisAttributes(G4Colour(183.0/255.0,230.0/255.0,240.0/255.0)); - outSmallBeamVisAtt->SetVisibility(false); - outSmallBeamLogical->SetVisAttributes(outSmallBeamVisAtt); - - outLargeBeamVisAtt = new G4VisAttributes(G4Colour(183.0/255.0,230.0/255.0,240.0/255.0)); - outLargeBeamVisAtt->SetVisibility(false); - outLargeBeamLogical->SetVisAttributes(outLargeBeamVisAtt); - -// coreWaterVisAtt = new G4VisAttributes(G4Colour(47.0/255.0,225.0/255.0,240.0/255.0)); -// coreWaterVisAtt->SetVisibility(false); -// coreWaterLogical->SetVisAttributes(coreWaterVisAtt); -// -// coreWaterSliceVisAtt = new G4VisAttributes(G4Colour(47.0/255.0,225.0/255.0,240.0/255.0)); -// coreWaterSliceVisAtt->SetVisibility(true); -// coreWaterSliceLogical->SetVisAttributes(coreWaterSliceVisAtt); - - zircGridVisAtt = new G4VisAttributes(G4Colour(0.,0.,1.)); - zircGridVisAtt->SetVisibility(true); - zircGridLogical->SetVisAttributes(zircGridVisAtt); - -// airGapsLatVisAtt = new G4VisAttributes(G4Colour(0.0/255.0,255.0/255.0,0.0/255.0)); -// airGapsLatVisAtt->SetVisibility(true); -// airGapsLatLogical->SetVisAttributes(airGapsLatVisAtt); -//// airGapsLatHLogical->SetVisAttributes(airGapsLatVisAtt); -// airGapsLatHRLogical->SetVisAttributes(airGapsLatVisAtt); -// airGapsLatHR2Logical->SetVisAttributes(airGapsLatVisAtt); -// -// fuelLatVisAtt = new G4VisAttributes(G4Colour(1.,0.,0.)); -// fuelLatVisAtt->SetVisibility(true); -// fuelLatLogical->SetVisAttributes(fuelLatVisAtt); -//// fuelLatHLogical->SetVisAttributes(fuelLatVisAtt); -// fuelLatHRLogical->SetVisAttributes(fuelLatVisAtt); -// fuelLatHR2Logical->SetVisAttributes(fuelLatVisAtt); - -//bright red - contRodZirVisAtt = new G4VisAttributes(G4Colour(1.,0.,0.)); - contRodZirVisAtt->SetVisibility(false); - contRodZirLogical->SetVisAttributes(contRodZirVisAtt); - -//bright yellow - contRodAlumVisAtt = new G4VisAttributes(G4Colour(255.0/255.0,255.0/255.0,0.0/255.0)); - contRodAlumVisAtt->SetVisibility(false); - contRodAlumLogical->SetVisAttributes(contRodAlumVisAtt); - -//bright green - contRodCadVisAtt = new G4VisAttributes(G4Colour(0.0/255.0,255.0/255.0,0.0/255.0)); - contRodCadVisAtt->SetVisibility(false); - contRodCadLogical->SetVisAttributes(contRodCadVisAtt); - -//dark red - contRodCentVisAtt = new G4VisAttributes(G4Colour(119.0/255.0,0.0/255.0,0.0/255.0)); - contRodCentVisAtt->SetVisibility(false); - contRodCentLogical->SetVisAttributes(contRodCentVisAtt); - - return worldPhysical; -} - - -// ConstructMaterials() -// Define and build the materials in the C6 lattice cell. -void DebugConstructor::ConstructMaterials() -{ -// Density Of Defined Materials - G4double ReflectorDensity = 1.85*g/cm3; - G4double LWDensity = 0.998*g/cm3; - G4double FuelDensity = 10.6*g/cm3; - G4double AirDensity = 5.0807e-5*g/cm3; - G4double ZrDensity = 6.49*g/cm3; - G4double AlAlloyDensity = 2.70*g/cm3; - G4double CadmiumDensity = 8.65*g/cm3; - G4double HWDensity = 1.105*g/cm3; - - // Temperature Of Defined Materials - // using data from 20043405 - G4double ReflectorTemp=(22.5+273.15); - G4double LWTemp=(30.6+273.15); - G4double FuelTemp=(57.32+273.15); - G4double AirTemp=(18.0+273.15); - G4double ZrTemp=(52.14+273.15); - G4double AlAlloyTemp1=(20.0+273.15); - G4double AlAlloyTemp2=(21.0+273.15); - G4double AlAlloyTemp3=(22.0+273.15); - G4double AlAlloyTemp4=(48.0+273.15); - G4double CadmiumTemp=(50.0+273.15); - G4double HWTemp=(20.5+273.15); - - // Defining all the pointers - G4Isotope *C12, *C13, *N14, *N15, *O16, *O17, /*O18,*/ *Mg24, - *Mg25, *Mg26, *Al27, *Si28, *Si29, *Si30, *Cr50, - *Cr52, *Cr53, *Cr54, *Mn55, *Fe54, *Fe56, *Fe57, - *Fe58, *Cu63, *Cu65, *Zr90, *Zr91, *Zr92, *Zr94, - *Zr96, *Cd106, *Cd108, *Cd110, *Cd111, *Cd112, - *Cd113, *Cd114, *Cd116, *U235, *U238; - G4Element *H1, *D2, *Be, *Li6, *Li7, *B10, *B11, *C, *N, *Oxygen, - *Mg, *Al, *Si, *Cr, *Mn, *Fe, *Cu, *Zirc, *ECd112, - *ECd113, *Cd, *In115, *Sm148, *Sm149, *Sm150, *Sm152, - *Gd155, *Gd157, *Eu151, *Eu153, *Ir191, *Ir193,*LEU; - G4Material *World, *Air, *Reflector, *LW, *Fuel, *Zr, *AlAlloy1, - *AlAlloy2, *AlAlloy3, *AlAlloy4, *Cadmium, *HW; - -// G4NistManager* manager = G4NistManager::Instance(); - - // Hydrogen And Isotopes - H1 = new G4Element("Hydrogen1", "H1", 1); - H1->AddIsotope(new G4Isotope("H1", 1, 1, 1.0078250321*g/mole), 1); - D2 = new G4Element("Hydrogen2", "H2", 1); - D2->AddIsotope(new G4Isotope("H2", 1, 2, 2.0141017780*g/mole), 1); - - // Lithium Isotopes - Li6 = new G4Element("Lithium6", "Li6", 1); - Li6->AddIsotope(new G4Isotope("Li6", 3, 6, 6.0151223*g/mole), 1); - Li7 = new G4Element("Lithium7", "Li7", 1); - Li7->AddIsotope(new G4Isotope("Li7", 3, 7, 7.0160040*g/mole), 1); - - // Berylium And Isotopes - Be = new G4Element("Berylium", "Be", 1); - Be->AddIsotope(new G4Isotope("Be9", 4, 9, 9.0121822*g/mole), 1); - - // Boron Isotopes - B10 = new G4Element("Boron10", "B10", 1); - B10->AddIsotope(new G4Isotope("B10", 5, 10, 10.012937*g/mole), 1); - B11 = new G4Element("Boron11", "B11", 1); - B11->AddIsotope(new G4Isotope("B11", 5, 11, 11.009305*g/mole), 1); - - // Making Carbon isotopes - C12 = new G4Isotope("C12", 6, 12, 12.000000*g/mole); - C13 = new G4Isotope("C13", 6, 13, 13.003354*g/mole); - - // Naturally occuring Carbon -// C = manager->FindOrBuildElement(6); - C = new G4Element("Carbon", "C", 2); - C->AddIsotope(C12, 98.93*perCent); - C->AddIsotope(C13, 1.07*perCent); - - // Nitrogen Isotopes - N14 = new G4Isotope("N14", 7, 14, 14.0030740052*g/mole); - N15 = new G4Isotope("N15", 7, 15, 15.0001088984*g/mole); - - // Naturally occuring Nitrogen - N = new G4Element("Nitrogen", "N", 2); - N->AddIsotope(N14, 99.632*perCent); - N->AddIsotope(N15, 0.368*perCent); - - // Make oxygen isotope and element - O16 = new G4Isotope("O16", 8, 16, 15.995*g/mole); - O17 = new G4Isotope("O17", 8, 17, 16.999*g/mole); -// O18 = new G4Isotope("O18", 8, 18, 17.999*g/mole); - - // Natural occuring oxygen - Oxygen = new G4Element("Oxygen", "O", 2); - Oxygen->AddIsotope(O16, 99.962*perCent); - Oxygen->AddIsotope(O17, 0.038*perCent); -// Oxygen->AddIsotope(O18, 0.205*perCent); - - // Magnesium Isotopes - Mg24 = new G4Isotope("Mg24", 12, 24, 23.9850423*g/mole); - Mg25 = new G4Isotope("Mg25", 12, 25, 24.9858374*g/mole); - Mg26 = new G4Isotope("Mg26", 12, 26, 25.9825937*g/mole); - - // Naturally Occuring Magnesium - Mg = new G4Element("Magnesium", "Mg", 3); - Mg->AddIsotope(Mg24, 78.99*perCent); - Mg->AddIsotope(Mg25, 10.00*perCent); - Mg->AddIsotope(Mg26, 11.01*perCent); - - // Making Aluminum Isotopes - Al27 = new G4Isotope("Al27", 13, 27, 26.9815386*g/mole); - - // Naturally occuring Aluminum - Al = new G4Element("Aluminum", "Al", 1); - Al->AddIsotope(Al27, 1); - - // Making Silicon Isotopes - Si28 = new G4Isotope("Si28", 14, 28, 27.9769271*g/mole); - Si29 = new G4Isotope("Si29", 14, 29, 28.9764949*g/mole); - Si30 = new G4Isotope("Si30", 14, 30, 29.9737707*g/mole); - - // Naturally occuring Silicon - Si = new G4Element("Silicon", "Si", 3); - Si->AddIsotope(Si28, 92.2297*perCent); - Si->AddIsotope(Si29, 4.6832*perCent); - Si->AddIsotope(Si30, 3.0871*perCent); - - // Chromium Isotopes - Cr50 = new G4Isotope("Cr50", 24, 50, 49.9460464*g/mole); - Cr52 = new G4Isotope("Cr52", 24, 52, 51.9405098*g/mole); - Cr53 = new G4Isotope("Cr53", 24, 53, 52.9406513*g/mole); - Cr54 = new G4Isotope("Cr54", 24, 54, 53.9388825*g/mole); - - // Naturally Occuring Chromium - Cr = new G4Element("Chromium", "Cr", 4); - Cr->AddIsotope(Cr50, 4.345*perCent); - Cr->AddIsotope(Cr52, 83.789*perCent); - Cr->AddIsotope(Cr53, 9.501*perCent); - Cr->AddIsotope(Cr54, 2.365*perCent); - - // Manganese Isotopes - Mn55 = new G4Isotope("Mn55", 25, 55, 54.9380471*g/mole); - - // Naturally occuring Manganese - Mn = new G4Element("Manganese", "Mn", 1); - Mn->AddIsotope(Mn55, 1.); - - // Making Iron Isotopes - Fe54 = new G4Isotope("Fe54", 26, 54, 53.9396127*g/mole); - Fe56 = new G4Isotope("Fe56", 26, 56, 55.9349393*g/mole); - Fe57 = new G4Isotope("Fe57", 26, 57, 56.9353958*g/mole); - Fe58 = new G4Isotope("Fe58", 26, 58, 57.9332773*g/mole); - - // Naturally Occuring Iron - Fe = new G4Element("Iron", "Fe", 4); - Fe->AddIsotope(Fe54, 5.845*perCent); - Fe->AddIsotope(Fe56, 91.754*perCent); - Fe->AddIsotope(Fe57, 2.119*perCent); - Fe->AddIsotope(Fe58, 0.282*perCent); - - // Copper Isotopes - Cu63 = new G4Isotope("Cu63", 29, 63, 62.9295989*g/mole); - Cu65 = new G4Isotope("Cu65", 29, 65, 64.9277929*g/mole); - - // Naturally Occuring Copper - Cu = new G4Element("Copper", "Cu", 2); - Cu->AddIsotope(Cu63, 69.17*perCent); - Cu->AddIsotope(Cu65, 30.83*perCent); - - // Making Zirconium isotopes and elements - Zr90 = new G4Isotope("Zr90", 40, 90, 89.9047044*g/mole); - Zr91 = new G4Isotope("Zr91", 40, 91, 90.9056458*g/mole); - Zr92 = new G4Isotope("Zr92", 40, 92, 91.9050408*g/mole); - Zr94 = new G4Isotope("Zr94", 40, 94, 93.9063152*g/mole); - Zr96 = new G4Isotope("Zr96", 40, 96, 95.9082734*g/mole); - - // Natural Zirconium composition - Zirc = new G4Element("Zirconium", "Zr", 5); - Zirc->AddIsotope(Zr90, 50.706645*perCent); - Zirc->AddIsotope(Zr91, 11.180922*perCent); - Zirc->AddIsotope(Zr92, 17.277879*perCent); - Zirc->AddIsotope(Zr94, 17.890875*perCent); - Zirc->AddIsotope(Zr96, 2.943679*perCent); - - // Cadmium Isotopes - Cd106 = new G4Isotope("Cd106", 48, 106, 105.906461*g/mole); - Cd108 = new G4Isotope("Cd108", 48, 108, 107.904176*g/mole); - Cd110 = new G4Isotope("Cd110", 48, 110, 109.903005*g/mole); - Cd111 = new G4Isotope("Cd111", 48, 111, 110.904182*g/mole); - Cd112 = new G4Isotope("Cd112", 48, 112, 111.902757*g/mole); - Cd113 = new G4Isotope("Cd113", 48, 113, 112.904400*g/mole); - Cd114 = new G4Isotope("Cd114", 48, 114, 113.903357*g/mole); - Cd116 = new G4Isotope("Cd116", 48, 116, 115.904755*g/mole); - - - // Cadmium Isotopes - ECd112 = new G4Element("Cadmium112", "Cd112", 1); - ECd112->AddIsotope(Cd112, 1); - ECd113 = new G4Element("Cadmium113", "Cd113", 1); - ECd113->AddIsotope(Cd113, 1); - - // Naturally Occuring Cadmium - Cd = new G4Element("Cadmium", "Cd", 8); - Cd->AddIsotope(Cd106, 1.25*perCent); - Cd->AddIsotope(Cd108, 0.89*perCent); - Cd->AddIsotope(Cd110, 12.49*perCent); - Cd->AddIsotope(Cd111, 12.80*perCent); - Cd->AddIsotope(Cd112, 24.13*perCent); - Cd->AddIsotope(Cd113, 12.22*perCent); - Cd->AddIsotope(Cd114, 28.73*perCent); - Cd->AddIsotope(Cd116, 7.49*perCent); - - // Indium Isotopes - In115 = new G4Element("Indium115", "In115", 1); - In115->AddIsotope(new G4Isotope("In115", 49, 115, 114.903882*g/mole), 1); - - // Samarium Isotopes (Note: Could not get info on Sm137) - Sm148 = new G4Element("Samatium148", "Am148", 1); - Sm148->AddIsotope(new G4Isotope("Sm148", 62, 148, 147.914819*g/mole), 1); - Sm149 = new G4Element("Samatium149", "Am149", 1); - Sm149->AddIsotope(new G4Isotope("Sm149", 62, 149, 149.917180*g/mole), 1); - Sm150 = new G4Element("Samatium150", "Am150", 1); - Sm150->AddIsotope(new G4Isotope("Sm150", 62, 150, 149.917273*g/mole), 1); - Sm152 = new G4Element("Samatium152", "Am152", 1); - Sm152->AddIsotope(new G4Isotope("Sm152", 62, 152, 151.919728*g/mole), 1); - - // Gadolium Isotopes - Gd155 = new G4Element("Gadolinium155", "Gd155", 1); - Gd155->AddIsotope(new G4Isotope("Gd155", 64, 155, 154.922618*g/mole), 1); - Gd157 = new G4Element("Gadolinium157", "Gd157", 1); - Gd157->AddIsotope(new G4Isotope("Gd157", 64, 157, 156.923956*g/mole), 1); - - // Europium Isotopes - Eu151 = new G4Element("Europium151", "Eu151", 1); - Eu151->AddIsotope(new G4Isotope("Eu151", 63, 151, 150.919702*g/mole), 1); - Eu153 = new G4Element("Europium153", "Eu153", 1); - Eu153->AddIsotope(new G4Isotope("Eu153", 63, 153, 152.921225*g/mole), 1); - - // Iridium Isotopes - Ir191 = new G4Element("Iridium191", "Ir191", 1); - Ir191->AddIsotope(new G4Isotope("Ir191", 77, 191, 190.960584*g/mole), 1); - Ir193 = new G4Element("Iridium193", "Ir193", 1); - Ir193->AddIsotope(new G4Isotope("Ir193", 77, 193, 192.962917*g/mole), 1); - - // Making the Uranium isotopes - U235 = new G4Isotope("U235", 92, 235, 235.0439*g/mole); - U238 = new G4Isotope("U238", 92, 238, 238.0508*g/mole); - - // Low Enriched Uranium (LEU) - LEU = new G4Element("Low Enriched Uranium", "LEU", 2); - LEU->AddIsotope(U235, 19.89*perCent); - LEU->AddIsotope(U238, 80.11*perCent); - - // (Marteial #0) Void Material - World = new G4Material("Galactic", 1, 1, 1.e-25*g/cm3, kStateGas, - 2.73*kelvin, 3.e-18*pascal); - - // (Material #1) Beryllium Sheild with Impurities - Reflector = new G4Material("Reflector", ReflectorDensity, 17, kStateSolid, ReflectorTemp); - Reflector->AddElement(Be, 0.9953863); - Reflector->AddElement(Oxygen, 9.70113e-6); - Reflector->AddElement(Al, 1.010534e-3); - Reflector->AddElement(C, 1.515802e-3); - Reflector->AddElement(Fe, 1.31695e-3); - Reflector->AddElement(Si, 6.063207e-4); - Reflector->AddElement(B10, 4.345298e-7); - Reflector->AddElement(B11, 1.616855e-6); - Reflector->AddElement(Mn, 1.515802e-4); - Reflector->AddElement(Cd, 7.376901e-7); - Reflector->AddElement(Li6, 1.313695e-7); - Reflector->AddElement(Li7, 1.92001e-6); - Reflector->AddElement(Sm149, 6.497736e-7); - Reflector->AddElement(Gd155, 3.53687e-8); - Reflector->AddElement(Gd157, 3.132657e-8); - Reflector->AddElement(Eu151, 2.425283e-7); - Reflector->AddElement(Eu153, 2.627389e-7); - - // (Material #2) Light Water - LW = new G4Material("LightWater", LWDensity, 2, kStateLiquid, LWTemp); - LW->AddElement(Oxygen, 1); - LW->AddElement(H1, 2); - - // (Material #3) Fuel Rods (19.95% Enriched Uranium in (UO2)) - Fuel = new G4Material("Fuel", FuelDensity, 2, kStateSolid, FuelTemp); - Fuel->AddElement(Oxygen, 2); - Fuel->AddElement(LEU, 1); - - // (Material #4) Air - Air = new G4Material("Air", AirDensity, 2, kStateGas, AirTemp); - Air->AddElement(Oxygen, 0.21174); - Air->AddElement(N, 0.78826); - // (Material #5) Zr - Zr = new G4Material("Zirconium", ZrDensity, 1, kStateSolid, ZrTemp); - Zr->AddElement(Zirc, 1); - - // (Material #6) Aluminum with impurities - AlAlloy1 = new G4Material("Aluminum Alloy", AlAlloyDensity, 5, kStateSolid, AlAlloyTemp1); - AlAlloy1->AddElement(Al, 0.9792); - AlAlloy1->AddElement(Si, 0.0060); - AlAlloy1->AddElement(Cu, 0.0028); - AlAlloy1->AddElement(Mg, 0.0100); - AlAlloy1->AddElement(Cr, 0.0020); - - AlAlloy2 = new G4Material("Aluminum Alloy", AlAlloyDensity, 5, kStateSolid, AlAlloyTemp2); - AlAlloy2->AddElement(Al, 0.9792); - AlAlloy2->AddElement(Si, 0.0060); - AlAlloy2->AddElement(Cu, 0.0028); - AlAlloy2->AddElement(Mg, 0.0100); - AlAlloy2->AddElement(Cr, 0.0020); - - AlAlloy3 = new G4Material("Aluminum Alloy", AlAlloyDensity, 5, kStateSolid, AlAlloyTemp3); - AlAlloy3->AddElement(Al, 0.9792); - AlAlloy3->AddElement(Si, 0.0060); - AlAlloy3->AddElement(Cu, 0.0028); - AlAlloy3->AddElement(Mg, 0.0100); - AlAlloy3->AddElement(Cr, 0.0020); - - AlAlloy4 = new G4Material("Aluminum Alloy", AlAlloyDensity, 5, kStateSolid, AlAlloyTemp4); - AlAlloy4->AddElement(Al, 0.9792); - AlAlloy4->AddElement(Si, 0.0060); - AlAlloy4->AddElement(Cu, 0.0028); - AlAlloy4->AddElement(Mg, 0.0100); - AlAlloy4->AddElement(Cr, 0.0020); - - // (Material #7) Cadmium - Cadmium = new G4Material("Cadmium", CadmiumDensity, 1, kStateSolid, CadmiumTemp); - Cadmium->AddElement(Cd, 1); - - // (Materail #8) Heavy Water - HW = new G4Material("Heavy Water", HWDensity, 2, kStateLiquid, HWTemp); - HW->AddElement(D2, 2); - HW->AddElement(Oxygen, 1); - - - // Add materials to the map indexed by either ZA (format ZZAAA or ZZ) - // For composite materials: world is 0, heavy water is 1, UHW is 2 - matMap["Galactic"] = World; - matMap["H2O"] = LW; - matMap["D2O"] = HW; - matMap["Fuel"] = Fuel; - matMap["Zirconium"] = Zr; - matMap["AlAlloy1"] = AlAlloy1; - matMap["AlAlloy2"] = AlAlloy2; - matMap["AlAlloy3"] = AlAlloy3; - matMap["AlAlloy4"] = AlAlloy4; - matMap["Reflector"] = Reflector; - matMap["Cadmium"] = Cadmium; - matMap["Air"] = Air; - - matChanged = false; - - return; -} diff --git a/G4STORK/src/ElementNames.cc b/G4STORK/src/ElementNames.cc deleted file mode 100755 index 3fadc5ce..00000000 --- a/G4STORK/src/ElementNames.cc +++ /dev/null @@ -1,209 +0,0 @@ -#include "../include/ElementNames.hh" - -string* ElementNames::elementName=NULL; - -using namespace std; - -ElementNames::ElementNames() -{ - //elementName=NULL; -} - -ElementNames::~ElementNames() -{ - //dtor -} - -void ElementNames::ClearStore() -{ - if(elementName != NULL) - delete [] elementName; -} - -void ElementNames::SetElementNames() -{ - elementName = new string[119]; - - elementName[0] = "Error"; - elementName[1] = "Hydrogen"; - elementName[2] = "Helium"; - elementName[3] = "Lithium"; - elementName[4] = "Beryllium"; - elementName[5] = "Boron"; - elementName[6] = "Carbon"; - elementName[7] = "Nitrogen"; - elementName[8] = "Oxygen"; - elementName[9] = "Fluorine"; - elementName[10] = "Neon"; - elementName[11] = "Sodium"; - elementName[12] = "Magnesium"; - elementName[13] = "Aluminum"; - elementName[14] = "Silicon"; - elementName[15] = "Phosphorous"; - elementName[16] = "Sulfur"; - elementName[17] = "Chlorine"; - elementName[18] = "Argon"; - elementName[19] = "Potassium"; - elementName[20] = "Calcium"; - elementName[21] = "Scandium"; - elementName[22] = "Titanium"; - elementName[23] = "Vanadium"; - elementName[24] = "Chromium"; - elementName[25] = "Manganese"; - elementName[26] = "Iron"; - elementName[27] = "Cobalt"; - elementName[28] = "Nickel"; - elementName[29] = "Copper"; - elementName[30] = "Zinc"; - elementName[31] = "Gallium"; - elementName[32] = "Germanium"; - elementName[33] = "Arsenic"; - elementName[34] = "Selenium"; - elementName[35] = "Bromine"; - elementName[36] = "Krypton"; - elementName[37] = "Rubidium"; - elementName[38] = "Strontium"; - elementName[39] = "Yttrium"; - elementName[40] = "Zirconium"; - elementName[41] = "Niobium"; - elementName[42] = "Molybdenum"; - elementName[43] = "Technetium"; - elementName[44] = "Ruthenium"; - elementName[45] = "Rhodium"; - elementName[46] = "Palladium"; - elementName[47] = "Silver"; - elementName[48] = "Cadmium"; - elementName[49] = "Indium"; - elementName[50] = "Tin"; - elementName[51] = "Antimony"; - elementName[52] = "Tellurium"; - elementName[53] = "Iodine"; - elementName[54] = "Xenon"; - elementName[55] = "Cesium"; - elementName[56] = "Barium"; - elementName[57] = "Lanthanum"; - elementName[58] = "Cerium"; - elementName[59] = "Praseodymium"; - elementName[60] = "Neodymium"; - elementName[61] = "Promethium"; - elementName[62] = "Samarium"; - elementName[63] = "Europium"; - elementName[64] = "Gadolinium"; - elementName[65] = "Terbium"; - elementName[66] = "Dysprosium"; - elementName[67] = "Holmium"; - elementName[68] = "Erbium"; - elementName[69] = "Thulium"; - elementName[70] = "Ytterbium"; - elementName[71] = "Lutetium"; - elementName[72] = "Hafnium"; - elementName[73] = "Tantalum"; - elementName[74] = "Tungsten"; - elementName[75] = "Rhenium"; - elementName[76] = "Osmium"; - elementName[77] = "Iridium"; - elementName[78] = "Platinum"; - elementName[79] = "Gold"; - elementName[80] = "Mercury"; - elementName[81] = "Thallium"; - elementName[82] = "Lead"; - elementName[83] = "Bismuth"; - elementName[84] = "Polonium"; - elementName[85] = "Astatine"; - elementName[86] = "Radon"; - elementName[87] = "Francium"; - elementName[88] = "Radium"; - elementName[89] = "Actinium"; - elementName[90] = "Thorium"; - elementName[91] = "Protactinium"; - elementName[92] = "Uranium"; - elementName[93] = "Neptunium"; - elementName[94] = "Plutonium"; - elementName[95] = "Americium"; - elementName[96] = "Curium"; - elementName[97] = "Berkelium"; - elementName[98] = "Californium"; - elementName[99] = "Einsteinium"; - elementName[100] = "Fermium"; - elementName[101] = "Mendelevium"; - elementName[102] = "Nobelium"; - elementName[103] = "Lawrencium"; - elementName[104] = "Rutherfordium"; - elementName[105] = "Dubnium"; - elementName[106] = "Seaborgium"; - elementName[107] = "Bohrium"; - elementName[108] = "Hassium"; - elementName[109] = "Meitnerium"; - elementName[110] = "Darmstadtium"; - elementName[111] = "Roentgenium"; - elementName[112] = "Copernicium"; - elementName[113] = "Ununtrium"; - elementName[114] = "Flerovium"; - elementName[115] = "Ununpentium"; - elementName[116] = "Livermorium"; - elementName[117] = "Ununseptium"; - elementName[118] = "Ununoctium"; - -} - -bool ElementNames::CheckName(string name, int Z) -{ - - if(elementName != NULL) - { - if(name.substr((name.length()-2),2)==".z") - { - name.erase((name.length()-2),2); - } - - if(Z==0) - return false; - - if(name == elementName[Z]) - return true; - else - { - name[0] = name[0]*('A'-'a'); - if(name == elementName[Z]) - return true; - } - } - else - { - cout << "### Error SetElementNames() has not been yet ###" << endl; - } - - - return false; - -} - -bool ElementNames::CheckName(string name) -{ - if(elementName != NULL) - { - if(name.substr((name.length()-2),2)==".z") - { - name.erase((name.length()-2),2); - } - - for(int i=0; i<119; i++) - { - if(name == elementName[i]) - return true; - else - { - name[0] = name[0]+('A'-'a'); - if(name == elementName[i]) - return true; - } - } - } - else - { - cout << "### Error SetElementNames() has not been yet ###" << endl; - } - - return false; - -} diff --git a/G4STORK/src/GuillaumeConstructor.cc b/G4STORK/src/GuillaumeConstructor.cc deleted file mode 100755 index a210e8e0..00000000 --- a/G4STORK/src/GuillaumeConstructor.cc +++ /dev/null @@ -1,1024 +0,0 @@ -#include "GuillaumeConstructor.hh" - -GuillaumeConstructor::GuillaumeConstructor() -: StorkVWorldConstructor(), ZirconiumLogical(0), WaterHolesLowerLogical(0), WaterHolesUpperLogical(0), -AirGapLogical(0), FuelRodLogical(0), LowerPinLogical(0), ReflectorLogical(0), D2OContainerLogical(0), -D2OLogical(0), contRodZirLogical(0), contRodAlumLogical(0), contRodCadLogical(0), contRodCentLogical(0), -insAlumLogical(0), insBeamLogical(0), outSmallAlumLogical(0), outLargeAlumLogical(0), cadLinLogical(0), -outSmallBeamLogical(0), outLargeBeamLogical(0), alumShellLogical(0), cellLogical(0) -{ - // Set default member variables (from file or default values) - latticePitch = 28.575*cm; - fuelTemp = 859.99*kelvin; - fuelDensity = 10.5541*g/cm3; - moderatorTemp = 336.16*kelvin; - moderatorDensity = 1.08875*g/cm3; - - // Set up variable property map - variablePropMap[MatPropPair(fuel,temperature)] = &fuelTemp; - variablePropMap[MatPropPair(fuel,density)] = &fuelDensity; - variablePropMap[MatPropPair(moderator,temperature)] = &moderatorTemp; - variablePropMap[MatPropPair(moderator,density)] = &moderatorDensity; - variablePropMap[MatPropPair(all,dimension)] = &latticePitch; - - cellVisAtt=NULL; - alumShellVisAtt=NULL; - D2OContainerAtt=NULL; - insAlumVisAtt=NULL; - insBeamVisAtt=NULL; - outSmallAlumVisAtt=NULL; - outLargeAlumVisAtt=NULL; - cadLinTubeVisAtt=NULL; - outSmallBeamVisAtt=NULL; - outLargeBeamVisAtt=NULL; - ReflectorAtt=NULL; - D2OAtt=NULL; - LowerPinAtt=NULL; - WaterHolesUpperAtt=NULL; - WaterHolesLowerAtt=NULL; - ZirconiumAtt=NULL; - AirGapAtt=NULL; - FuelRodAtt=NULL; - contRodZirVisAtt=NULL; - contRodAlumVisAtt=NULL; - contRodCadVisAtt=NULL; - contRodCentVisAtt=NULL; -} - -GuillaumeConstructor::~GuillaumeConstructor() -{ - // Delete visualization attributes - if(ZirconiumAtt) - delete ZirconiumAtt; - if(WaterHolesLowerAtt) - delete WaterHolesLowerAtt; - if(WaterHolesUpperAtt) - delete WaterHolesUpperAtt; - if(AirGapAtt) - delete AirGapAtt; - if(FuelRodAtt) - delete FuelRodAtt; - if(LowerPinAtt) - delete LowerPinAtt; - if(ReflectorAtt) - delete ReflectorAtt; - if(D2OContainerAtt) - delete D2OContainerAtt; - if(D2OAtt) - delete D2OAtt; - if(contRodZirVisAtt) - delete contRodZirVisAtt; - if(contRodAlumVisAtt) - delete contRodAlumVisAtt; - if(contRodCadVisAtt) - delete contRodCadVisAtt; - if(contRodCentVisAtt) - delete contRodCentVisAtt; - if(insAlumVisAtt) - delete insAlumVisAtt; - if(insBeamVisAtt) - delete insBeamVisAtt; - if(outSmallAlumVisAtt) - delete outSmallAlumVisAtt; - if(outLargeAlumVisAtt) - delete outLargeAlumVisAtt; - if(cadLinTubeVisAtt) - delete cadLinTubeVisAtt; - if(outSmallBeamVisAtt) - delete outSmallBeamVisAtt; - if(outLargeBeamVisAtt) - delete outLargeBeamVisAtt; - if(alumShellVisAtt) - delete alumShellVisAtt; - if(cellVisAtt) - delete cellVisAtt; -} - -// ConstructWorld() -// Construct the geometry and materials of the Guillaume Reactor. -G4VPhysicalVolume* GuillaumeConstructor::ConstructWorld() -{ - - - G4SolidStore* theSolids = G4SolidStore::GetInstance(); - - // Set static dimensions - //Note the format for cylinder dimensions is (inner radius, outer radius, height) - - // Reactor pool dimensions - G4double buffer = 1.0*cm; - reactorDim = G4ThreeVector(0., 133.0*cm, 564.0*cm); - - // World dimensions - encWorldDim = 2.0*G4ThreeVector(reactorDim[1]+buffer,reactorDim[1]+buffer, reactorDim[2]/2+buffer); - - // Reflector dimensions - G4double refAnnDim[3] = {11.049*cm, 21.2344*cm, 22.748*cm}; - G4double refBottomDim[3] = {0.0*cm, 16.113125*cm, 10.16*cm}; - G4double refTopDim[3] = {1.3890625*cm, 12.065*cm, 0.15875*cm}; - - // D2O Colum Container and Water - G4double D20ContainerDim[3] = {21.2344*cm, 30*cm, 22.748*cm}; - G4double D20Dim[3] = {22.2344*cm, 29*cm, 20.6975*cm}; - - // Beamtube dimensions - G4double smallBTubeDim[3] = {0.0*cm, 1.40208*cm, 515.332*cm}; - G4double smallLongBTubeDim[3] = {0.0*cm, 1.40208*cm, 522.332*cm}; - G4double largeBTubeDim[3] = {0.0*cm, 1.6*cm, 515.332*cm}; - - // Aluminum Tube dimensions - G4double smallAlumTubeDim[3] = {0.0*cm, 1.56718*cm, 515.332*cm}; - G4double smallLongAlumTubeDim[3] = {0.0*cm, 1.56718*cm, 522.332*cm}; - G4double largeAlumTubeDim[3] = {0.0*cm, 1.905*cm, 515.332*cm}; - G4double alumTubePos[3]={14.56182*cm, 0.4*CLHEP::pi, 0.}; - G4double outAlumTubePos[3]={24.0*cm, 0.4*CLHEP::pi, 0.2*CLHEP::pi}; - - // Aluminium Reactor Shell - G4double alumShellTubeDim[3] = {30.0*cm, 31.0*cm, 541.0*cm}; - G4double alumShellPlateDim[3] = {0.0*cm, 31.0*cm, 1*cm}; - - // Cadmium lining - G4double cadLinTubeDim[3] = {1.56718*cm, 1.61798*cm, 22.748*cm}; - - // Control Rod - G4double contRodCentTubeDim[3] = {0.0*cm, 0.09652*cm, 24.76*cm}; - G4double contRodCadTubeDim[3] = {0.0*cm, 0.14732*cm, 24.76*cm}; - G4double contRodAlumTubeDim[3] = {0.0*cm, 0.62357*cm, 40.64*cm}; - G4double contRodZirTubeDim[3] = {1.229*cm, 1.331*cm, 23.2335*cm}; - - /* Begining Of Reactor Core Dimensions*/ - // Zirconium lower/upper plate dimensions - G4double LowerZrDim[3] = {1.331*cm, 11.049*cm, 0.279*cm}; - G4double UpperZrDim[3] = {LowerZrDim[0], LowerZrDim[1], LowerZrDim[2]}; - - // Zirconium holes lower/upper plate - G4double WaterHolesLowerZrDim[3] = {0., 0.262*cm, LowerZrDim[2]}; - G4double WaterHolesUpperZrDim[3] = {0., 0.19*cm, UpperZrDim[2]}; - G4double PinHolesDim[3] = {0., 0.15*cm, LowerZrDim[2]}; - - // Hole Position lower/upper plate - G4double LowerZrHolePos[4] = {0.551815*cm, 0.318516*cm, 0.0, 0.637286*cm}; - G4double UpperZrHolePos[4] = {0.551815*cm, 0.318516*cm, 0.0, 0.637286*cm}; - - // Zirconium Rod/Air Gap/Fuel Dimensions - G4double ZirconiumRodDim[3] = {0., 0.262*cm, 23.3805*cm}; - G4double AirGapDim[3] = {0., 0.212*cm, 23.1105*cm}; - G4double FuelRodDim[3] = {0., 0.2064*cm, 22.6975*cm}; - /* End Of Reactor Core Dimensions*/ - - // Lattice Matrix - G4double latticeMat[25][25] ={{7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7}, - {7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7}, - {7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 9, 8, 9, 8, 9, 8, 8, 7, 7, 7}, - {7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 9, 8, 9, 9, 8, 8, 9, 9, 8, 8, 8, 7, 7}, - {7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 9, 8, 9, 8, 9, 8, 9, 8, 8, 8, 7, 7}, - {7, 7, 7, 7, 7, 7, 7, 7, 8, 9, 9, 9, 9, 8, 8, 9, 9, 8, 8, 9, 9, 9, 9, 8, 7}, - {7, 7, 7, 7, 7, 7, 7, 8, 8, 9, 8, 8, 9, 8, 9, 8, 9, 8, 9, 8, 8, 9, 8, 8, 7}, - {7, 7, 7, 7, 7, 7, 8, 9, 8, 9, 8, 8, 8, 9, 8, 8, 9, 8, 8, 8, 9, 8, 9, 8, 7}, - {7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 9, 8, 9, 9, 9, 9, 8, 8, 8, 8, 7}, - {7, 7, 7, 7, 7, 9, 9, 9, 9, 8, 8, 8, 8, 9, 9, 8, 8, 8, 8, 9, 9, 9, 9, 7, 7}, - {7, 7, 7, 7, 8, 9, 8, 8, 9, 8, 9, 9, 9, 8, 9, 9, 9, 8, 9, 8, 8, 9, 8, 7, 7}, - {7, 7, 7, 8, 8, 9, 8, 8, 9, 8, 9, 8, 9, 9, 8, 9, 8, 9, 8, 8, 9, 8, 8, 7, 7}, - {7, 7, 7, 8, 8, 9, 9, 8, 9, 8, 8, 9, 7, 9, 8, 8, 9, 8, 9, 9, 8, 8, 7, 7, 7}, - {7, 7, 8, 8, 9, 8, 8, 9, 8, 9, 8, 9, 9, 8, 9, 8, 9, 8, 8, 9, 8, 8, 7, 7, 7}, - {7, 7, 8, 9, 8, 8, 9, 8, 9, 9, 9, 8, 9, 9, 9, 8, 9, 8, 8, 9, 8, 7, 7, 7, 7}, - {7, 9, 9, 9, 9, 9, 8, 8, 8, 8, 9, 9, 8, 8, 8, 8, 9, 9, 9, 9, 7, 7, 7, 7, 7}, - {7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 9, 8, 9, 9, 9, 9, 8, 8, 8, 8, 7, 7, 7, 7, 7}, - {7, 8, 9, 8, 9, 8, 8, 8, 9, 8, 8, 9, 8, 8, 8, 9, 8, 9, 8, 7, 7, 7, 7, 7, 7}, - {7, 8, 8, 9, 8, 8, 9, 8, 9, 8, 9, 8, 9, 8, 8, 9, 8, 8, 7, 7, 7, 7, 7, 7, 7}, - {7, 8, 9, 9, 9, 9, 8, 8, 9, 9, 8, 8, 9, 9, 9, 9, 8, 7, 7, 7, 7, 7, 7, 7, 7}, - {7, 7, 8, 8, 8, 9, 8, 9, 8, 9, 8, 9, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7}, - {7, 7, 8, 8, 8, 9, 9, 8, 8, 9, 9, 8, 9, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7}, - {7, 7, 7, 8, 8, 9, 8, 9, 8, 9, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7}, - {7, 7, 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7}, - {7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7}}; - - // Set up the materials (if necessary) - if(matChanged) - { - // Delete any existing materials - DestroyMaterials(); - // Create the materials - ConstructMaterials(); - } - - // Clean up volumes - G4GeometryManager::GetInstance()->OpenGeometry(); - G4PhysicalVolumeStore::GetInstance()->Clean(); - G4LogicalVolumeStore::GetInstance()->Clean(); - - - // Set up the solids if necessary - if(geomChanged) - { - // Clean up solids - G4SolidStore::GetInstance()->Clean(); - - // Create world solid - new G4Box("worldBox", encWorldDim[0]/2, encWorldDim[1]/2, encWorldDim[2]/2); - - // Tub Made of Water - new G4Tubs("cellTube", 0., reactorDim[1], reactorDim[2]/2, 0., 2.0*CLHEP::pi); - - // Create Aluminium Shell - new G4Tubs("alumShellTube", alumShellTubeDim[0], alumShellTubeDim[1], alumShellTubeDim[2]/2, 0., 2.0*CLHEP::pi); - new G4Tubs("alumShellPlate", alumShellPlateDim[0], alumShellPlateDim[1], alumShellPlateDim[2]/2, 0., 2.0*CLHEP::pi); - new G4UnionSolid("alumShell", theSolids->GetSolid("alumShellPlate"), theSolids->GetSolid("alumShellTube"), 0, G4ThreeVector(0., 0., 271.*cm)); - - - // Create Reflector Solids - new G4Tubs("reflectTop", refTopDim[0], refTopDim[1], refTopDim[2]/2, 0., CLHEP::pi); - new G4Tubs("reflectAnnulus", refAnnDim[0], refAnnDim[1], refAnnDim[2]/2, 0., 2.0*CLHEP::pi); - new G4Tubs("reflectBottom", refBottomDim[0], refBottomDim[1], refBottomDim[2]/2, 0., 2.0*CLHEP::pi); - new G4UnionSolid("reflector0", theSolids->GetSolid("reflectAnnulus"), theSolids->GetSolid("reflectTop"), 0, G4ThreeVector(0., 0., 13.969375*cm)); - new G4UnionSolid("reflector", theSolids->GetSolid("reflector0"), theSolids->GetSolid("reflectBottom"), 0, G4ThreeVector(0., 0., -16.962*cm)); - - // D20 Container - new G4Tubs("D2OContainer1", D20ContainerDim[0], D20ContainerDim[1], D20ContainerDim[2]/2, 1.570796327*rad, 4.712388980*rad); - new G4Tubs("D2OContainer2", 0., D20ContainerDim[1]+1.082*cm, D20ContainerDim[2]/2, 2.751192606*rad, 0.7808000945*rad); - new G4IntersectionSolid("D2OContainer", theSolids->GetSolid("D2OContainer1"), theSolids->GetSolid("D2OContainer2"), 0, G4ThreeVector(1.082*cm,0.,0.)); - new G4Tubs("D2O", D20Dim[0], D20Dim[1], D20Dim[2]/2, 2.751192606*rad, 0.7808000945*rad); - - // Create Aluminium Tube Solids - new G4Tubs("smallAlumTube", smallAlumTubeDim[0], smallAlumTubeDim[1], smallAlumTubeDim[2]/2, 0., 2.0*CLHEP::pi); - new G4Tubs("smallLongAlumTube", smallLongAlumTubeDim[0], smallLongAlumTubeDim[1], smallLongAlumTubeDim[2]/2, 0., 2.0*CLHEP::pi); - new G4Tubs("largeAlumTube", largeAlumTubeDim[0], largeAlumTubeDim[1], largeAlumTubeDim[2]/2, 0., 2.0*CLHEP::pi); - - // Create Beam Tube Solids - new G4Tubs("smallBeamTube", smallBTubeDim[0], smallBTubeDim[1], smallBTubeDim[2]/2, 0., 2.0*CLHEP::pi); - new G4Tubs("smallLongBeamTube", smallLongBTubeDim[0], smallLongBTubeDim[1], smallLongBTubeDim[2]/2, 0., 2.0*CLHEP::pi); - new G4Tubs("cadLinTube", cadLinTubeDim[0], cadLinTubeDim[1], cadLinTubeDim[2]/2, 0., 2.0*CLHEP::pi); - new G4Tubs("largeBeamTube", largeBTubeDim[0], largeBTubeDim[1], largeBTubeDim[2]/2, 0., 2.0*CLHEP::pi); - - // Create Control Rod Solids - new G4Tubs("contRodCentTube", contRodCentTubeDim[0], contRodCentTubeDim[1], contRodCentTubeDim[2]/2, 0., 2.0*CLHEP::pi); - new G4Tubs("contRodCadTube", contRodCadTubeDim[0], contRodCadTubeDim[1], contRodCadTubeDim[2]/2, 0., 2.0*CLHEP::pi); - new G4Tubs("contRodAlumTube", contRodAlumTubeDim[0], contRodAlumTubeDim[1], contRodAlumTubeDim[2]/2, 0., 2.0*CLHEP::pi); - new G4Tubs("contRodZirTube", contRodZirTubeDim[0], contRodZirTubeDim[1], contRodZirTubeDim[2]/2, 0., 2.0*CLHEP::pi); - - /* Beginning Of Reactor Core Geometries*/ - // Create zirconium lower and upper plate - new G4Tubs("LowerZrTub", LowerZrDim[0], LowerZrDim[1], LowerZrDim[2]/2, 0, 2.0*CLHEP::pi); - new G4Tubs("UpperZrTub", UpperZrDim[0], UpperZrDim[1], UpperZrDim[2]/2, 0, 2.0*CLHEP::pi); - - // Water Holes lower and upper Zr plate - new G4Tubs("WaterHolesLower", WaterHolesLowerZrDim[0], WaterHolesLowerZrDim[1], WaterHolesLowerZrDim[2]/2, 0, 2.0*CLHEP::pi); - new G4Tubs("WaterHolesUpper", WaterHolesUpperZrDim[0], WaterHolesUpperZrDim[1], WaterHolesUpperZrDim[2]/2, 0, 2.0*CLHEP::pi); - - // Pin Holes Lower Zr Plate - new G4Tubs("PinHolesLower", PinHolesDim[0], PinHolesDim[1], PinHolesDim[2]/2, 0, 2.0*CLHEP::pi); - - // Zirconium Rods - new G4Tubs("ZirconiumRod", ZirconiumRodDim[0], ZirconiumRodDim[1], ZirconiumRodDim[2]/2+1*mm, 0, 2.0*CLHEP::pi); - new G4Tubs("AirGapRod", AirGapDim[0], AirGapDim[1], AirGapDim[2]/2, 0, 2.0*CLHEP::pi); - new G4Tubs("FuelRod", FuelRodDim[0], FuelRodDim[1], FuelRodDim[2]/2, 0, 2.0*CLHEP::pi); - - // Making a union of every part of the core that is made of zirconium - Zirconium = new G4UnionSolid("Zirconium", theSolids->GetSolid("LowerZrTub"), theSolids->GetSolid("UpperZrTub"), 0, G4ThreeVector(0,0,22.5*cm)); - for(G4int y=1; y<24; y++) - { - for(G4int x=1; x<24; x++) - { - if(latticeMat[y][x] == 8) - { - - G4double Center[2] = {((y-12)*0.551833696+(x-12)*1.103632018)*cm, (12-y)*0.955804*cm}; - // The extra 1mm is there sch that the two volumes not share the same surface. - // This would lead to an undefined scenario. - Zirconium = new G4UnionSolid("ZirconiumRods", Zirconium, theSolids->GetSolid("ZirconiumRod"), 0, - G4ThreeVector(Center[0],Center[1],(ZirconiumRodDim[2]+LowerZrDim[2]-1*mm)/2)); - } - } - } - /* End Of Reactor Core Geometries */ - - geomChanged = false; - } - // Position vector - G4ThreeVector holePos; - - // Create world volume - worldLogical = new G4LogicalVolume(theSolids->GetSolid("worldBox"), matMap["Galactic"],"worldLogical"); - worldPhysical = new G4PVPlacement(0, G4ThreeVector(0,0,0), worldLogical, "worldPhysical", 0, 0, 0); - - // Create the lattice cell (moderator) volume - cellLogical = new G4LogicalVolume(theSolids->GetSolid("cellTube"),matMap["H2O"],"cellLogical"); - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), cellLogical,"cellPhysical",worldLogical,0,0); - - //create aluminium shell - alumShellLogical = new G4LogicalVolume(theSolids->GetSolid("alumShell"),matMap["AlAlloy1"],"alumShellLogical"); - new G4PVPlacement(0, G4ThreeVector(0.,0.,22.5*cm-reactorDim[2]/2), alumShellLogical,"alumShellPhysical",cellLogical,0,0); - - // Reflector Logical Volume is being created - ReflectorLogical = new G4LogicalVolume(theSolids->GetSolid("reflector"), matMap["Reflector"],"ReflectorLogical"); - new G4PVPlacement(0, G4ThreeVector(0, 0, 53.042*cm-reactorDim[2]/2), ReflectorLogical, "ReflectorPhysical", cellLogical, 0, 0); - - // Outter Tubes - outSmallAlumLogical = new G4LogicalVolume(theSolids->GetSolid("smallLongAlumTube"),matMap["AlAlloy1"],"outAlumTubeLogical"); - holePos.set(outAlumTubePos[0]*cos(outAlumTubePos[1]*4+outAlumTubePos[2]),outAlumTubePos[0]*sin(outAlumTubePos[1]*4+outAlumTubePos[2]),302.834*cm-reactorDim[2]/2); - new G4PVPlacement(0, holePos, outSmallAlumLogical,"outSmallAlumTubePhysical1", cellLogical,0,0); - holePos.set(outAlumTubePos[0]*cos(outAlumTubePos[1]*1+outAlumTubePos[2]),outAlumTubePos[0]*sin(outAlumTubePos[1]*1+outAlumTubePos[2]),302.834*cm-reactorDim[2]/2); - new G4PVPlacement(0, holePos, outSmallAlumLogical,"outSmallAlumTubePhysical2", cellLogical,0,0); - outLargeAlumLogical = new G4LogicalVolume(theSolids->GetSolid("largeAlumTube"),matMap["AlAlloy1"],"outAlumTubeLogical"); - holePos.set(outAlumTubePos[0]*cos(outAlumTubePos[2]),outAlumTubePos[0]*sin(outAlumTubePos[2]), 302.834*cm-reactorDim[2]/2); - new G4PVPlacement(0, holePos, outLargeAlumLogical,"outLargeAlumTubePhysical", cellLogical,0,0); - cadLinLogical = new G4LogicalVolume(theSolids->GetSolid("cadLinTube"),matMap["Cadmium"],"cadLinLogical"); - holePos.set(outAlumTubePos[0]*cos(outAlumTubePos[1]*3+outAlumTubePos[2]),outAlumTubePos[0]*sin(outAlumTubePos[1]*3+outAlumTubePos[2]),302.834*cm-reactorDim[2]/2); - new G4PVPlacement(0, holePos, cadLinLogical,"cadLinTube", cellLogical,0,0); - new G4PVPlacement(0, holePos, outSmallAlumLogical,"outSmallAlumTubePhysical3", cellLogical,0,0); - outSmallBeamLogical = new G4LogicalVolume(theSolids->GetSolid("smallLongBeamTube"),matMap["Air"],"outSmallBeamLogical"); - new G4PVPlacement(0, G4ThreeVector(0., 0., 0.), outSmallBeamLogical,"outSmallBeamTubePhysical",outSmallAlumLogical,0,0); - outLargeBeamLogical = new G4LogicalVolume(theSolids->GetSolid("largeBeamTube"),matMap["Air"],"outLargeBeamLogical"); - new G4PVPlacement(0, G4ThreeVector(0., 0., 0.), outLargeBeamLogical,"outLargeBeamTubePhysical",outLargeAlumLogical,0,0); - - // Inner Irradiation Tubes - insAlumLogical = new G4LogicalVolume(theSolids->GetSolid("smallAlumTube"),matMap["AlAlloy3"],"insAlumLogical"); - G4int copy =0; - for (G4int i=0; i<5; i++) - { - holePos.set((alumTubePos[0]*cos(alumTubePos[1]*i+alumTubePos[2])), (alumTubePos[0]*sin(alumTubePos[1]*i+alumTubePos[2])), 253.292*cm); - new G4PVPlacement(0, holePos, insAlumLogical,"insAlumTubePhysical",ReflectorLogical, copy, 0); - copy++; - } - - insBeamLogical = new G4LogicalVolume(theSolids->GetSolid("smallBeamTube"),matMap["Air"],"insBeamLogical"); - new G4PVPlacement(0, G4ThreeVector(0., 0., 0.), insBeamLogical,"insBeamTubePhysical",insAlumLogical,0,0); - - // D20 Container - D2OContainerLogical = new G4LogicalVolume(theSolids->GetSolid("D2OContainer"), matMap["AlAlloy2"],"D2OContainerLogical"); - new G4PVPlacement(0, G4ThreeVector(0, 0, 53.042*cm-reactorDim[2]/2), D2OContainerLogical, "D2OPhysical", cellLogical, 0, 0); - D2OLogical = new G4LogicalVolume(theSolids->GetSolid("D2O"), matMap["D2O"],"D2OLogical"); - new G4PVPlacement(0, G4ThreeVector(0, 0, 0.25375*cm), D2OLogical, "D2OPhysical", D2OContainerLogical, 0, 0); - - // Create the control rod - contRodZirLogical = new G4LogicalVolume(theSolids->GetSolid("contRodZirTube"),matMap["Zirconium"], "contRodZirLogical"); - new G4PVPlacement(0, G4ThreeVector(0., 0., 53.02925*cm-reactorDim[2]/2), contRodZirLogical,"contRodZirPhysical",cellLogical,0,0); - contRodAlumLogical = new G4LogicalVolume(theSolids->GetSolid("contRodAlumTube"),matMap["AlAlloy4"], "contRodAlumLogical"); - new G4PVPlacement(0, G4ThreeVector(0., 0., 82.14*cm-reactorDim[2]/2), contRodAlumLogical,"contRodAlumPhysical",cellLogical,0,0); - contRodCadLogical = new G4LogicalVolume(theSolids->GetSolid("contRodCadTube"),matMap["Cadmium"], "contRodCadLogical"); - new G4PVPlacement(0, G4ThreeVector(0., 0., -5.44*cm), contRodCadLogical,"contRodCadPhysical",contRodAlumLogical,0,0); - contRodCentLogical = new G4LogicalVolume(theSolids->GetSolid("contRodCentTube"),matMap["Air"], "contRodCentLogical"); - new G4PVPlacement(0, G4ThreeVector(0., 0., 0.), contRodCentLogical,"contRodCentPhysical",contRodCadLogical,0,0); - - // Creates zirconium ensemble - ZirconiumLogical = new G4LogicalVolume(Zirconium, matMap["Zirconium"], "ZirconiumLogical"); - new G4PVPlacement(0, G4ThreeVector(0, 0, 41.5535*cm-reactorDim[2]/2), ZirconiumLogical, "ZirconiumPhysical", cellLogical, 0, 0); - - /* Placing all the logical volumes */ - // Creating holes in lower and Upper Zirconium Plate - WaterHolesLowerLogical = new G4LogicalVolume(theSolids->GetSolid("WaterHolesLower"), matMap["H2O"], "WaterHolesLowerLogical"); - WaterHolesUpperLogical = new G4LogicalVolume(theSolids->GetSolid("WaterHolesUpper"), matMap["H2O"], "WaterHolesUpperLogical"); - - // Creating Air Gap in fuel Assemblie and fuel rod elements - AirGapLogical = new G4LogicalVolume(theSolids->GetSolid("AirGapRod"), matMap["Air"], "AirGapLogical"); - FuelRodLogical = new G4LogicalVolume(theSolids->GetSolid("FuelRod"), matMap["Fuel"], "FuelRodLogical"); - - // Creating the logical volume for the pins - LowerPinLogical = new G4LogicalVolume(theSolids->GetSolid("PinHolesLower"), matMap["H2O"], "LowerPinLogical"); - - // Placing the Fuel Rod in the center of the Air Gap - new G4PVPlacement(0, G4ThreeVector(0,0,-0.0875*cm), FuelRodLogical, "FuelRodPhysical", AirGapLogical, 0, 0); - - G4bool *neighbour; - G4int copynum = 0, AirGapNum = 0, LowerPinNum = 0; - for(G4int y=1; y<24; y++) - { - for(G4int x=1; x<24; x++) - { - if(latticeMat[y][x] != 7) - { - G4double Center[2] = {((y-12)*0.551833696+(x-12)*1.103632018)*cm, (12-y)*0.955804*cm}; - if(latticeMat[y-1][x] != 7 && latticeMat[y][x-1] != 7) - { - G4bool DUMMY[6] = {0,0,1,1,1,0}; - neighbour = DUMMY; - } - else if(latticeMat[y-1][x] != 7) - { - G4bool DUMMY[6] = {0,1,1,1,1,0}; - neighbour = DUMMY; - } - else if(latticeMat[y][x-1] != 7) - { - G4bool DUMMY[6] = {0,0,1,1,1,1}; - neighbour = DUMMY; - } - else - { - G4bool DUMMY[6] = {1,1,1,1,1,1}; - neighbour = DUMMY; - } - - - // Removes the upper left hole - if(neighbour[0]) - { - if( sqrt((Center[0]-LowerZrHolePos[0])*(Center[0]-LowerZrHolePos[0])+(Center[1]+LowerZrHolePos[1])*(Center[1]+LowerZrHolePos[1]))+WaterHolesLowerZrDim[1] < 11.049*cm - && sqrt((Center[0]-LowerZrHolePos[0])*(Center[0]-LowerZrHolePos[0])+(Center[1]+LowerZrHolePos[1])*(Center[1]+LowerZrHolePos[1]))-WaterHolesLowerZrDim[1] > 1.331*cm) - { - new G4PVPlacement(0, G4ThreeVector(Center[0]-LowerZrHolePos[0],Center[1]+LowerZrHolePos[1],0), - WaterHolesLowerLogical, "LowerHolesPhysical", ZirconiumLogical, copynum,0); - new G4PVPlacement(0, G4ThreeVector(Center[0]-UpperZrHolePos[0],Center[1]+UpperZrHolePos[1],22.5*cm), - WaterHolesUpperLogical, "UpperHolesPhysical", ZirconiumLogical, copynum,0); - copynum++; - } - } - - // Removes the lower left hole - if(neighbour[1]) - { - if( sqrt((Center[0]-LowerZrHolePos[0])*(Center[0]-LowerZrHolePos[0])+(Center[1]-LowerZrHolePos[1])*(Center[1]-LowerZrHolePos[1]))+WaterHolesLowerZrDim[1] < 11.049*cm - && sqrt((Center[0]-LowerZrHolePos[0])*(Center[0]-LowerZrHolePos[0])+(Center[1]-LowerZrHolePos[1])*(Center[1]-LowerZrHolePos[1]))-WaterHolesLowerZrDim[1] > 1.331*cm) - { - new G4PVPlacement(0, G4ThreeVector(Center[0]-LowerZrHolePos[0],Center[1]-LowerZrHolePos[1],0), - WaterHolesLowerLogical, "LowerHolesPhysical", ZirconiumLogical, copynum,0); - new G4PVPlacement(0, G4ThreeVector(Center[0]-UpperZrHolePos[0],Center[1]-UpperZrHolePos[1],22.5*cm), - WaterHolesUpperLogical, "UpperHolesPhysical", ZirconiumLogical, copynum,0); - copynum++; - } - } - - // Removes the lower center hole - if(neighbour[2]) - { - if( sqrt((Center[0]-LowerZrHolePos[2])*(Center[0]-LowerZrHolePos[2])+(Center[1]-LowerZrHolePos[3])*(Center[1]-LowerZrHolePos[3]))+WaterHolesLowerZrDim[1] < 11.049*cm - && sqrt((Center[0]-LowerZrHolePos[2])*(Center[0]-LowerZrHolePos[2])+(Center[1]-LowerZrHolePos[3])*(Center[1]-LowerZrHolePos[3]))-WaterHolesLowerZrDim[1] > 1.331*cm) - { - new G4PVPlacement(0, G4ThreeVector(Center[0]-LowerZrHolePos[2],Center[1]-LowerZrHolePos[3],0), - WaterHolesLowerLogical, "LowerHolesPhysical", ZirconiumLogical, copynum,0); - new G4PVPlacement(0, G4ThreeVector(Center[0]-UpperZrHolePos[2],Center[1]-UpperZrHolePos[3],22.5*cm), - WaterHolesUpperLogical, "UpperHolesPhysical", ZirconiumLogical, copynum,0); - copynum++; - } - } - - // Removes the lower right hole - if(neighbour[3]) - { - if( sqrt((Center[0]+LowerZrHolePos[0])*(Center[0]+LowerZrHolePos[0])+(Center[1]-LowerZrHolePos[1])*(Center[1]-LowerZrHolePos[1]))+WaterHolesLowerZrDim[1] < 11.049*cm - && sqrt((Center[0]+LowerZrHolePos[0])*(Center[0]+LowerZrHolePos[0])+(Center[1]-LowerZrHolePos[1])*(Center[1]-LowerZrHolePos[1]))-WaterHolesLowerZrDim[1] > 1.331*cm) - { - new G4PVPlacement(0, G4ThreeVector(Center[0]+LowerZrHolePos[0],Center[1]-LowerZrHolePos[1],0), - WaterHolesLowerLogical, "LowerHolesPhysical", ZirconiumLogical, copynum,0); - new G4PVPlacement(0, G4ThreeVector(Center[0]+UpperZrHolePos[0],Center[1]-UpperZrHolePos[1],22.5*cm), - WaterHolesUpperLogical, "UpperHolesPhysical", ZirconiumLogical, copynum,0); - copynum++; - } - } - - // Removes the upper right hole - if(neighbour[4]) - { - if( sqrt((Center[0]+LowerZrHolePos[0])*(Center[0]+LowerZrHolePos[0])+(Center[1]+LowerZrHolePos[1])*(Center[1]+LowerZrHolePos[1]))+WaterHolesLowerZrDim[1] < 11.049*cm - && sqrt((Center[0]+LowerZrHolePos[0])*(Center[0]+LowerZrHolePos[0])+(Center[1]+LowerZrHolePos[1])*(Center[1]+LowerZrHolePos[1]))-WaterHolesLowerZrDim[1] > 1.331*cm) - { - new G4PVPlacement(0, G4ThreeVector(Center[0]+LowerZrHolePos[0],Center[1]+LowerZrHolePos[1],0), - WaterHolesLowerLogical, "LowerHolesPhysical", ZirconiumLogical, copynum,0); - new G4PVPlacement(0, G4ThreeVector(Center[0]+UpperZrHolePos[0],Center[1]+UpperZrHolePos[1],22.5*cm), - WaterHolesUpperLogical, "UpperHolesPhysical", ZirconiumLogical, copynum,0); - copynum++; - } - } - - // Removes the upper center hole - if(neighbour[5]) - { - if( sqrt((Center[0]+LowerZrHolePos[2])*(Center[0]+LowerZrHolePos[2])+(Center[1]+LowerZrHolePos[3])*(Center[1]+LowerZrHolePos[3]))+WaterHolesLowerZrDim[1] < 11.049*cm - && sqrt((Center[0]+LowerZrHolePos[2])*(Center[0]+LowerZrHolePos[2])+(Center[1]+LowerZrHolePos[3])*(Center[1]+LowerZrHolePos[3]))-WaterHolesLowerZrDim[1] > 1.331*cm) - { - new G4PVPlacement(0, G4ThreeVector(Center[0]+LowerZrHolePos[2],Center[1]+LowerZrHolePos[3], 0), - WaterHolesLowerLogical, "LowerHolesPhysical", ZirconiumLogical, copynum, 0); - new G4PVPlacement(0, G4ThreeVector(Center[0]+UpperZrHolePos[2],Center[1]+UpperZrHolePos[3], 22.5*cm), - WaterHolesUpperLogical, "UpperHolesPhysical", ZirconiumLogical, copynum, 0); - copynum++; - } - } - - if(latticeMat[x][y] == 8) - { - new G4PVPlacement(0, G4ThreeVector(Center[0], Center[1], 11.82975*cm), AirGapLogical, "AirGapPhysical", ZirconiumLogical, AirGapNum, 0); - AirGapNum++; - } - else - { - if(Center[0]*Center[0]+ Center[1]*Center[1] > (1.331*cm)*(1.331*cm)) - { - new G4PVPlacement(0, G4ThreeVector(Center[0], Center[1], 0), LowerPinLogical, "LowerPinPhysical", ZirconiumLogical, LowerPinNum, 0); - LowerPinNum++; - } - } - } - } - } - - - // Add sensitive detector to ALL logical volumes - worldLogical->SetSensitiveDetector( sDReactor ); - ZirconiumLogical->SetSensitiveDetector( sDReactor ); - WaterHolesLowerLogical->SetSensitiveDetector( sDReactor ); - WaterHolesUpperLogical->SetSensitiveDetector( sDReactor ); - AirGapLogical->SetSensitiveDetector( sDReactor ); - FuelRodLogical->SetSensitiveDetector( sDReactor ); - LowerPinLogical->SetSensitiveDetector( sDReactor ); - ReflectorLogical->SetSensitiveDetector( sDReactor ); - D2OContainerLogical->SetSensitiveDetector( sDReactor ); - D2OLogical->SetSensitiveDetector( sDReactor ); - contRodZirLogical->SetSensitiveDetector( sDReactor ); - contRodAlumLogical->SetSensitiveDetector( sDReactor ); - contRodCadLogical->SetSensitiveDetector( sDReactor ); - contRodCentLogical->SetSensitiveDetector( sDReactor ); - insAlumLogical->SetSensitiveDetector( sDReactor ); - insBeamLogical->SetSensitiveDetector( sDReactor ); - outSmallAlumLogical->SetSensitiveDetector( sDReactor ); - outLargeAlumLogical->SetSensitiveDetector( sDReactor ); - cadLinLogical->SetSensitiveDetector( sDReactor ); - outSmallBeamLogical->SetSensitiveDetector( sDReactor ); - outLargeBeamLogical->SetSensitiveDetector( sDReactor ); - alumShellLogical->SetSensitiveDetector( sDReactor ); - cellLogical->SetSensitiveDetector( sDReactor ); - - /* This is where all the visualizaion attributes are made */ - // World Visualization - - if(worldVisAtt) - delete worldVisAtt; - if(ZirconiumAtt) - delete ZirconiumAtt; - if(WaterHolesLowerAtt) - delete WaterHolesLowerAtt; - if(WaterHolesUpperAtt) - delete WaterHolesUpperAtt; - if(AirGapAtt) - delete AirGapAtt; - if(FuelRodAtt) - delete FuelRodAtt; - if(LowerPinAtt) - delete LowerPinAtt; - if(ReflectorAtt) - delete ReflectorAtt; - if(D2OContainerAtt) - delete D2OContainerAtt; - if(D2OAtt) - delete D2OAtt; - if(contRodZirVisAtt) - delete contRodZirVisAtt; - if(contRodAlumVisAtt) - delete contRodAlumVisAtt; - if(contRodCadVisAtt) - delete contRodCadVisAtt; - if(contRodCentVisAtt) - delete contRodCentVisAtt; - if(insAlumVisAtt) - delete insAlumVisAtt; - if(insBeamVisAtt) - delete insBeamVisAtt; - if(outSmallAlumVisAtt) - delete outSmallAlumVisAtt; - if(outLargeAlumVisAtt) - delete outLargeAlumVisAtt; - if(cadLinTubeVisAtt) - delete cadLinTubeVisAtt; - if(outSmallBeamVisAtt) - delete outSmallBeamVisAtt; - if(outLargeBeamVisAtt) - delete outLargeBeamVisAtt; - if(alumShellVisAtt) - delete alumShellVisAtt; - if(cellVisAtt) - delete cellVisAtt; - - worldVisAtt = new G4VisAttributes(G4Colour(0.,0.,210.0/255.0)); - worldVisAtt->SetVisibility(false); - worldLogical->SetVisAttributes(worldVisAtt); - - // Water Tub Visualization - cellVisAtt = new G4VisAttributes(G4Colour(47.0/255.0,225.0/255.0,240.0/255.0)); - cellLogical->SetVisAttributes(cellVisAtt); - - // Aluminum Reactor Shell Visualization - alumShellVisAtt = new G4VisAttributes(G4Colour(150.0/255.0,150.0/255.0,150.0/255.0)); - alumShellLogical->SetVisAttributes(alumShellVisAtt); - - // Zirconium Visualization - ZirconiumAtt = new G4VisAttributes(G4Colour(0.,0.,0.)); - ZirconiumLogical->SetVisAttributes(ZirconiumAtt); - - // Lowwer Hole Visualization - WaterHolesLowerAtt = new G4VisAttributes(G4Colour(0.,0.,1.)); - WaterHolesLowerLogical->SetVisAttributes(WaterHolesLowerAtt); - - // Upper Hole Visualization - WaterHolesUpperAtt = new G4VisAttributes(G4Colour(0.,0.,1.)); - WaterHolesUpperLogical->SetVisAttributes(WaterHolesUpperAtt); - - // Air Gap Visualization - AirGapAtt = new G4VisAttributes(G4Colour(1.,0.,0.)); - AirGapLogical->SetVisAttributes(AirGapAtt); - - // Fuel Visualization - FuelRodAtt = new G4VisAttributes(G4Colour(0.,1.,0.)); - FuelRodLogical->SetVisAttributes(FuelRodAtt); - - // Lower Pin Visualization - LowerPinAtt = new G4VisAttributes(G4Colour(0.,0.,1.)); - LowerPinLogical->SetVisAttributes(LowerPinAtt); - - // Reflector Visualization - ReflectorAtt = new G4VisAttributes(G4Colour(0.,0.5,0.5)); - ReflectorLogical->SetVisAttributes(ReflectorAtt); - - - // D2O Column and Water Visualization - D2OContainerAtt = new G4VisAttributes(G4Colour(0.5,0.5,0.)); - D2OContainerLogical->SetVisAttributes(D2OContainerAtt); - D2OAtt = new G4VisAttributes(G4Colour(0.,0.,1.)); - D2OLogical->SetVisAttributes(D2OAtt); - - // Control Rod Visualization - contRodZirVisAtt = new G4VisAttributes(G4Colour(0.,0.,0.)); - contRodZirLogical->SetVisAttributes(contRodZirVisAtt); - - contRodAlumVisAtt = new G4VisAttributes(G4Colour(0.5,0.5,0.5)); - contRodAlumLogical->SetVisAttributes(contRodAlumVisAtt); - - contRodCadVisAtt = new G4VisAttributes(G4Colour(195.0/255.0,174.0/255.0,238.0/255.0)); - contRodCadLogical->SetVisAttributes(contRodCadVisAtt); - - contRodCentVisAtt = new G4VisAttributes(G4Colour(1.,0.,0.)); - contRodCentLogical->SetVisAttributes(contRodCentVisAtt); - - // Irradiations Sites Visualization - insAlumVisAtt = new G4VisAttributes(G4Colour(150.0/255.0,150.0/255.0,150.0/255.0)); - insAlumVisAtt->SetVisibility(false); - insAlumLogical->SetVisAttributes(insAlumVisAtt); - - insBeamVisAtt = new G4VisAttributes(G4Colour(183.0/255.0,230.0/255.0,240.0/255.0)); - insBeamLogical->SetVisAttributes(insBeamVisAtt); - - outSmallAlumVisAtt = new G4VisAttributes(G4Colour(150.0/255.0,150.0/255.0,150/255.0)); - outSmallAlumLogical->SetVisAttributes(outSmallAlumVisAtt); - - outLargeAlumVisAtt = new G4VisAttributes(G4Colour(150.0/255.0,150.0/255.0,150.0/255.0)); - outLargeAlumLogical->SetVisAttributes(outLargeAlumVisAtt); - - cadLinTubeVisAtt = new G4VisAttributes(G4Colour(195.0/255.0,174.0/255.0,238.0/255.0)); - cadLinLogical->SetVisAttributes(cadLinTubeVisAtt); - - outSmallBeamVisAtt = new G4VisAttributes(G4Colour(183.0/255.0,230.0/255.0,240.0/255.0)); - outSmallBeamLogical->SetVisAttributes(outSmallBeamVisAtt); - - outLargeBeamVisAtt = new G4VisAttributes(G4Colour(183.0/255.0,230.0/255.0,240.0/255.0)); - outLargeBeamLogical->SetVisAttributes(outLargeBeamVisAtt); - - return worldPhysical; -} - - -// ConstructMaterials() -// Define and build the materials in the C6 lattice cell. -void GuillaumeConstructor::ConstructMaterials() -{ - // Density Of Defined Materials - G4double ReflectorDensity = 1.85*g/cm3; - G4double LWDensity = 0.998*g/cm3; - G4double FuelDensity = 10.6*g/cm3; - G4double AirDensity = 5.0807e-5*g/cm3; - G4double ZrDensity = 6.49*g/cm3; - G4double AlAlloyDensity = 2.70*g/cm3; - G4double CadmiumDensity = 8.65*g/cm3; - G4double HWDensity = 1.105*g/cm3; - - // Temperature Of Defined Materials - // using data from 20043405 - G4double ReflectorTemp=(22.5+273.15)*kelvin; - G4double LWTemp=(30.6+273.15)*kelvin; - G4double FuelTemp=(57.32+273.15)*kelvin; - G4double AirTemp=(18.0+273.15)*kelvin; - G4double ZrTemp=(52.14+273.15)*kelvin; - G4double AlAlloyTemp1=(20.0+273.15)*kelvin; - G4double AlAlloyTemp2=(21.0+273.15)*kelvin; - G4double AlAlloyTemp3=(22.0+273.15)*kelvin; - G4double AlAlloyTemp4=(48.0+273.15)*kelvin; - G4double CadmiumTemp=(50.0+273.15)*kelvin; - G4double HWTemp=(20.5+273.15)*kelvin; - - // Defining all the pointers - G4Isotope *C12, *C13, *N14, *N15, *O16, *O17, *O18, *Mg24, - *Mg25, *Mg26, *Al27, *Si28, *Si29, *Si30, *Cr50, - *Cr52, *Cr53, *Cr54, *Mn55, *Fe54, *Fe56, *Fe57, - *Fe58, *Cu63, *Cu65, *Zr90, *Zr91, *Zr92, *Zr94, - *Zr96, *Cd106, *Cd108, *Cd110, *Cd111, *Cd112, - *Cd113, *Cd114, *Cd116, *U235, *U238; - G4Element *H1, *D2, *Be, *Li6, *Li7, *B10, *B11, *C, *N, *Oxygen, - *Mg, *Al, *Si, *Cr, *Mn, *Fe, *Cu, *Zirc, *ECd112, - *ECd113, *Cd, *In115, *Sm148, *Sm149, *Sm150, *Sm152, - *Gd155, *Gd157, *Eu151, *Eu153, *Ir191, *Ir193,*LEU; - G4Material *World, *Air, *Reflector, *LW, *Fuel, *Zr, *AlAlloy1, - *AlAlloy2, *AlAlloy3, *AlAlloy4, *Cadmium, *HW; - - // Hydrogen And Isotopes - H1 = new G4Element("Hydrogen1", "H1", 1); - H1->AddIsotope(new G4Isotope("H1", 1, 1, 1.0078250321*g/mole), 1); - D2 = new G4Element("Hydrogen2", "H2", 1); - D2->AddIsotope(new G4Isotope("H2", 1, 2, 2.0141017780*g/mole), 1); - - // Lithium Isotopes - Li6 = new G4Element("Lithium6", "Li6", 1); - Li6->AddIsotope(new G4Isotope("Li6", 3, 6, 6.0151223*g/mole), 1); - Li7 = new G4Element("Lithium7", "Li7", 1); - Li7->AddIsotope(new G4Isotope("Li7", 3, 7, 7.0160040*g/mole), 1); - - // Berylium And Isotopes - Be = new G4Element("Berylium", "Be", 1); - Be->AddIsotope(new G4Isotope("Be9", 4, 9, 9.0121822*g/mole), 1); - - // Boron Isotopes - B10 = new G4Element("Boron10", "B10", 1); - B10->AddIsotope(new G4Isotope("B10", 5, 10, 10.012937*g/mole), 1); - B11 = new G4Element("Boron11", "B11", 1); - B11->AddIsotope(new G4Isotope("B11", 5, 11, 11.009305*g/mole), 1); - - // Making Carbon isotopes - C12 = new G4Isotope("C12", 6, 12, 12.000000*g/mole); - C13 = new G4Isotope("C13", 6, 13, 13.003354*g/mole); - - // Naturally occuring Carbon - C = new G4Element("Carbon", "C", 2); - C->AddIsotope(C12, 98.93*perCent); - C->AddIsotope(C13, 1.07*perCent); - - // Nitrogen Isotopes - N14 = new G4Isotope("N14", 7, 14, 14.0030740052*g/mole); - N15 = new G4Isotope("N15", 7, 15, 15.0001088984*g/mole); - - // Naturally occuring Nitrogen - N = new G4Element("Nitrogen", "N", 2); - N->AddIsotope(N14, 99.632*perCent); - N->AddIsotope(N15, 0.368*perCent); - - // Make oxygen isotope and element - O16 = new G4Isotope("O16", 8, 16, 15.995*g/mole); - O17 = new G4Isotope("O17", 8, 17, 16.999*g/mole); - O18 = new G4Isotope("O18", 8, 18, 17.999*g/mole); - - // Natural occuring oxygen - Oxygen = new G4Element("Oxygen", "O", 3); - Oxygen->AddIsotope(O16, 99.757*perCent); - Oxygen->AddIsotope(O17, 0.038*perCent); - Oxygen->AddIsotope(O18, 0.205*perCent); - - // Magnesium Isotopes - Mg24 = new G4Isotope("Mg24", 12, 24, 23.9850423*g/mole); - Mg25 = new G4Isotope("Mg25", 12, 25, 24.9858374*g/mole); - Mg26 = new G4Isotope("Mg26", 12, 26, 25.9825937*g/mole); - - // Naturally Occuring Magnesium - Mg = new G4Element("Magnesium", "Mg", 3); - Mg->AddIsotope(Mg24, 78.99*perCent); - Mg->AddIsotope(Mg25, 10.00*perCent); - Mg->AddIsotope(Mg26, 11.01*perCent); - - // Making Aluminum Isotopes - Al27 = new G4Isotope("Al27", 13, 27, 26.9815386*g/mole); - - // Naturally occuring Aluminum - Al = new G4Element("Aluminum", "Al", 1); - Al->AddIsotope(Al27, 1); - - // Making Silicon Isotopes - Si28 = new G4Isotope("Si28", 14, 28, 27.9769271*g/mole); - Si29 = new G4Isotope("Si29", 14, 29, 28.9764949*g/mole); - Si30 = new G4Isotope("Si30", 14, 30, 29.9737707*g/mole); - - // Naturally occuring Silicon - Si = new G4Element("Silicon", "Si", 3); - Si->AddIsotope(Si28, 92.2297*perCent); - Si->AddIsotope(Si29, 4.6832*perCent); - Si->AddIsotope(Si30, 3.0871*perCent); - - // Chromium Isotopes - Cr50 = new G4Isotope("Cr50", 24, 50, 49.9460464*g/mole); - Cr52 = new G4Isotope("Cr52", 24, 52, 51.9405098*g/mole); - Cr53 = new G4Isotope("Cr53", 24, 53, 52.9406513*g/mole); - Cr54 = new G4Isotope("Cr54", 24, 54, 53.9388825*g/mole); - - // Naturally Occuring Chromium - Cr = new G4Element("Chromium", "Cr", 4); - Cr->AddIsotope(Cr50, 4.345*perCent); - Cr->AddIsotope(Cr52, 83.789*perCent); - Cr->AddIsotope(Cr53, 9.501*perCent); - Cr->AddIsotope(Cr54, 2.365*perCent); - - // Manganese Isotopes - Mn55 = new G4Isotope("Mn55", 25, 55, 54.9380471*g/mole); - - // Naturally occuring Manganese - Mn = new G4Element("Manganese", "Mn", 1); - Mn->AddIsotope(Mn55, 1.); - - // Making Iron Isotopes - Fe54 = new G4Isotope("Fe54", 26, 54, 53.9396127*g/mole); - Fe56 = new G4Isotope("Fe56", 26, 56, 55.9349393*g/mole); - Fe57 = new G4Isotope("Fe57", 26, 57, 56.9353958*g/mole); - Fe58 = new G4Isotope("Fe58", 26, 58, 57.9332773*g/mole); - - // Naturally Occuring Iron - Fe = new G4Element("Iron", "Fe", 4); - Fe->AddIsotope(Fe54, 5.845*perCent); - Fe->AddIsotope(Fe56, 91.754*perCent); - Fe->AddIsotope(Fe57, 2.119*perCent); - Fe->AddIsotope(Fe58, 0.282*perCent); - - // Copper Isotopes - Cu63 = new G4Isotope("Cu63", 29, 63, 62.9295989*g/mole); - Cu65 = new G4Isotope("Cu65", 29, 66, 64.9277929*g/mole); - - // Naturally Occuring Copper - Cu = new G4Element("Copper", "Cu", 2); - Cu->AddIsotope(Cu63, 69.17*perCent); - Cu->AddIsotope(Cu65, 30.83*perCent); - - // Making Zirconium isotopes and elements - Zr90 = new G4Isotope("Zr90", 40, 90, 89.9047044*g/mole); - Zr91 = new G4Isotope("Zr91", 40, 91, 90.9056458*g/mole); - Zr92 = new G4Isotope("Zr92", 40, 92, 91.9050408*g/mole); - Zr94 = new G4Isotope("Zr94", 40, 94, 93.9063152*g/mole); - Zr96 = new G4Isotope("Zr96", 40, 96, 95.9082734*g/mole); - - // Natural Zirconium composition - Zirc = new G4Element("Zirconium", "Zr", 5); - Zirc->AddIsotope(Zr90, 50.706645*perCent); - Zirc->AddIsotope(Zr91, 11.180922*perCent); - Zirc->AddIsotope(Zr92, 17.277879*perCent); - Zirc->AddIsotope(Zr94, 17.890875*perCent); - Zirc->AddIsotope(Zr96, 2.943679*perCent); - - // Cadmium Isotopes - Cd106 = new G4Isotope("Cd106", 48, 106, 105.906461*g/mole); - Cd108 = new G4Isotope("Cd108", 48, 108, 107.904176*g/mole); - Cd110 = new G4Isotope("Cd110", 48, 110, 109.903005*g/mole); - Cd111 = new G4Isotope("Cd111", 48, 111, 110.904182*g/mole); - Cd112 = new G4Isotope("Cd112", 48, 112, 111.902757*g/mole); - Cd113 = new G4Isotope("Cd113", 48, 113, 112.904400*g/mole); - Cd114 = new G4Isotope("Cd114", 48, 114, 113.903357*g/mole); - Cd116 = new G4Isotope("Cd116", 48, 116, 115.904755*g/mole); - - - // Cadmium Isotopes - ECd112 = new G4Element("Cadmium112", "Cd112", 1); - ECd112->AddIsotope(Cd112, 1); - ECd113 = new G4Element("Cadmium113", "Cd113", 1); - ECd113->AddIsotope(Cd113, 1); - - // Naturally Occuring Cadmium - Cd = new G4Element("Cadmium", "Cd", 8); - Cd->AddIsotope(Cd106, 1.25*perCent); - Cd->AddIsotope(Cd108, 0.89*perCent); - Cd->AddIsotope(Cd110, 12.49*perCent); - Cd->AddIsotope(Cd111, 12.80*perCent); - Cd->AddIsotope(Cd112, 24.13*perCent); - Cd->AddIsotope(Cd113, 12.22*perCent); - Cd->AddIsotope(Cd114, 28.73*perCent); - Cd->AddIsotope(Cd116, 7.49*perCent); - - // Indium Isotopes - In115 = new G4Element("Indium115", "In115", 1); - In115->AddIsotope(new G4Isotope("In115", 49, 115, 114.903882*g/mole), 1); - - // Samarium Isotopes (Note: Could not get info on Sm137) - Sm148 = new G4Element("Samatium148", "Am148", 1); - Sm148->AddIsotope(new G4Isotope("Sm148", 62, 148, 147.914819*g/mole), 1); - Sm149 = new G4Element("Samatium149", "Am149", 1); - Sm149->AddIsotope(new G4Isotope("Sm149", 62, 149, 149.917180*g/mole), 1); - Sm150 = new G4Element("Samatium150", "Am150", 1); - Sm150->AddIsotope(new G4Isotope("Sm150", 62, 150, 149.917273*g/mole), 1); - Sm152 = new G4Element("Samatium152", "Am152", 1); - Sm152->AddIsotope(new G4Isotope("Sm152", 62, 152, 151.919728*g/mole), 1); - - // Gadolium Isotopes - Gd155 = new G4Element("Gadolinium155", "Gd155", 1); - Gd155->AddIsotope(new G4Isotope("Gd155", 64, 155, 154.922618*g/mole), 1); - Gd157 = new G4Element("Gadolinium157", "Gd157", 1); - Gd157->AddIsotope(new G4Isotope("Gd157", 64, 157, 156.923956*g/mole), 1); - - // Europium Isotopes - Eu151 = new G4Element("Europium151", "Eu151", 1); - Eu151->AddIsotope(new G4Isotope("Eu151", 63, 151, 150.919702*g/mole), 1); - Eu153 = new G4Element("Europium153", "Eu153", 1); - Eu153->AddIsotope(new G4Isotope("Eu153", 63, 153, 152.921225*g/mole), 1); - - // Iridium Isotopes - Ir191 = new G4Element("Iridium191", "Ir191", 1); - Ir191->AddIsotope(new G4Isotope("Ir191", 77, 191, 190.960584*g/mole), 1); - Ir193 = new G4Element("Iridium193", "Ir193", 1); - Ir193->AddIsotope(new G4Isotope("Ir193", 77, 193, 192.962917*g/mole), 1); - - // Making the Uranium isotopes - U235 = new G4Isotope("U235", 92, 235, 235.0439*g/mole); - U238 = new G4Isotope("U238", 92, 238, 238.0508*g/mole); - - // Low Enriched Uranium (LEU) - LEU = new G4Element("Low Enriched Uranium", "LEU", 2); - LEU->AddIsotope(U235, 19.89*perCent); - LEU->AddIsotope(U238, 80.11*perCent); - - // (Marteial #0) Void Material - World = new G4Material("Galactic", 1, 1, 1.e-25*g/cm3, kStateGas, - 2.73*kelvin, 3.e-18*pascal); - - // (Material #1) Beryllium Sheild with Impurities - Reflector = new G4Material("Reflector", ReflectorDensity, 17, kStateSolid, ReflectorTemp); - Reflector->AddElement(Be, 0.9953863); - Reflector->AddElement(Oxygen, 9.70113e-6); - Reflector->AddElement(Al, 1.010534e-3); - Reflector->AddElement(C, 1.515802e-3); - Reflector->AddElement(Fe, 1.31695e-3); - Reflector->AddElement(Si, 6.063207e-4); - Reflector->AddElement(B10, 4.345298e-7); - Reflector->AddElement(B11, 1.616855e-6); - Reflector->AddElement(Mn, 1.515802e-4); - Reflector->AddElement(Cd, 7.376901e-7); - Reflector->AddElement(Li6, 1.313695e-7); - Reflector->AddElement(Li7, 1.92001e-6); - Reflector->AddElement(Sm149, 6.497736e-7); - Reflector->AddElement(Gd155, 3.53687e-8); - Reflector->AddElement(Gd157, 3.132657e-8); - Reflector->AddElement(Eu151, 2.425283e-7); - Reflector->AddElement(Eu151, 2.627389e-7); - - // (Material #2) Light Water - LW = new G4Material("LightWater", LWDensity, 2, kStateLiquid, LWTemp); - LW->AddElement(Oxygen, 1); - LW->AddElement(H1, 2); - - // (Material #3) Fuel Rods (19.95% Enriched Uranium in (UO2)) - Fuel = new G4Material("Fuel", FuelDensity, 2, kStateSolid, FuelTemp); - Fuel->AddElement(Oxygen, 2); - Fuel->AddElement(LEU, 1); - - // (Material #4) Air - Air = new G4Material("Air", AirDensity, 2, kStateGas, AirTemp); - Air->AddElement(Oxygen, 0.21174); - Air->AddElement(N, 0.78826); - // (Material #5) Zr - Zr = new G4Material("Zirconium", ZrDensity, 1, kStateSolid, ZrTemp); - Zr->AddElement(Zirc, 1); - - // (Material #6) Aluminum with impurities - AlAlloy1 = new G4Material("Aluminum Alloy", AlAlloyDensity, 5, kStateSolid, AlAlloyTemp1); - AlAlloy1->AddElement(Al, 0.9792); - AlAlloy1->AddElement(Si, 0.0060); - AlAlloy1->AddElement(Cu, 0.0028); - AlAlloy1->AddElement(Mg, 0.0100); - AlAlloy1->AddElement(Cr, 0.0020); - - AlAlloy2 = new G4Material("Aluminum Alloy", AlAlloyDensity, 5, kStateSolid, AlAlloyTemp2); - AlAlloy2->AddElement(Al, 0.9792); - AlAlloy2->AddElement(Si, 0.0060); - AlAlloy2->AddElement(Cu, 0.0028); - AlAlloy2->AddElement(Mg, 0.0100); - AlAlloy2->AddElement(Cr, 0.0020); - - AlAlloy3 = new G4Material("Aluminum Alloy", AlAlloyDensity, 5, kStateSolid, AlAlloyTemp3); - AlAlloy3->AddElement(Al, 0.9792); - AlAlloy3->AddElement(Si, 0.0060); - AlAlloy3->AddElement(Cu, 0.0028); - AlAlloy3->AddElement(Mg, 0.0100); - AlAlloy3->AddElement(Cr, 0.0020); - - AlAlloy4 = new G4Material("Aluminum Alloy", AlAlloyDensity, 5, kStateSolid, AlAlloyTemp4); - AlAlloy4->AddElement(Al, 0.9792); - AlAlloy4->AddElement(Si, 0.0060); - AlAlloy4->AddElement(Cu, 0.0028); - AlAlloy4->AddElement(Mg, 0.0100); - AlAlloy4->AddElement(Cr, 0.0020); - - // (Material #7) Cadmium - Cadmium = new G4Material("Cadmium", CadmiumDensity, 1, kStateSolid, CadmiumTemp); - Cadmium->AddElement(Cd, 1); - - // (Materail #8) Heavy Water - HW = new G4Material("Heavy Water", HWDensity, 2, kStateLiquid, HWTemp); - HW->AddElement(D2, 2); - HW->AddElement(Oxygen, 1); - - - // Add materials to the map indexed by either ZA (format ZZAAA or ZZ) - // For composite materials: world is 0, heavy water is 1, UHW is 2 - matMap["Galactic"] = World; - matMap["H2O"] = LW; - matMap["D2O"] = HW; - matMap["Fuel"] = Fuel; - matMap["Zirconium"] = Zr; - matMap["AlAlloy1"] = AlAlloy1; - matMap["AlAlloy2"] = AlAlloy2; - matMap["AlAlloy3"] = AlAlloy3; - matMap["AlAlloy4"] = AlAlloy4; - matMap["Reflector"] = Reflector; - matMap["Cadmium"] = Cadmium; - matMap["Air"] = Air; - - matChanged = false; - - return; -} diff --git a/G4STORK/src/HeatTransfer.cc b/G4STORK/src/HeatTransfer.cc deleted file mode 100755 index 007427aa..00000000 --- a/G4STORK/src/HeatTransfer.cc +++ /dev/null @@ -1,90 +0,0 @@ -// -// HeatTransfer.cc -// G4-STORK-1.0 -// -// Created by Andrew Tan on 2014-11-09. -// Copyright (c) 2014 andrewtan. All rights reserved. -// - -#include "HeatTransfer.h" - -//Constructor -HeatTransfer::HeatTransfer(const G4LogicalVolume* FuelRod,const G4double Fo, const G4double Bi, const G4double T_Inf, const G4int NumSpatialSteps, const G4double heat) -{ - G4Tubs* theSolid = dynamic_cast(FuelRod->GetSolid()); - StorkMaterialHT* theMaterial = dynamic_cast(FuelRod->GetMaterial()); - G4double radius = theSolid->GetInnerRadius(); - - numSteps = NumSpatialSteps; - HeatFlux = heat; - FourierNumber = Fo; - BiotNumber = Bi; - CoolentTemp = T_Inf; - avgTemperature = theMaterial->GetTemperature(); - spatialStep = G4double(radius/numSteps); - - thermalConductivity = theMaterial->GetThermalConductivity(); - thermalDiffusivity = theMaterial->GetThermalDiffusivity(); - - timeStep = (1/thermalDiffusivity)*FourierNumber*spatialStep*spatialStep; - - InitialCondition = std::vector (avgTemperature,numSteps); - -} - -//Destructor -HeatTransfer::~HeatTransfer() -{ -} - -std::vector HeatTransfer::ExplicitMethod(std::vector array) -{ - - //Begin explicit method heat transfer - - G4double temp = FourierNumber*(2*array[1]+(1/thermalConductivity)*heatGeneration*spatialStep*spatialStep)+(1-2*FourierNumber)*array[0]; - - Output.push_back(temp); - - for(G4int i = 1; i<(numSteps-1);i++) - { - temp = FourierNumber*(array[i-1]+array[i+1]+(1/thermalConductivity)*heatGeneration*spatialStep*spatialStep) + (1 - 2*FourierNumber)*array[i]; - Output.push_back(temp); - - } - temp = 2*FourierNumber*(array[numSteps-2] + BiotNumber*CoolentTemp + (0.5/thermalConductivity)*heatGeneration*spatialStep*spatialStep) + (1 - 2*FourierNumber - 2*BiotNumber*FourierNumber)*array[numSteps-1]; - Output.push_back(temp); - - return Output; -} - -G4bool HeatTransfer::PrecisionCheck(std::vector array1, std::vector array2,G4int precision) -{ - if(array1.size() != array2.size()){ - G4cout<< "Error: arrays are different sizes!" << G4endl; - return false; - } - G4int size = array1.size(); - - for(G4int i = 0; ipow(10,precision)) - { - return false; - } - } - return true; -} - -void HeatTransfer::ConvergenceRun(std::vector array_, G4int precision) -{ - std::vector temparray1 = ExplicitMethod(array_); - std::vector temparray2; - G4bool converged = false; - while(!converged){ - temparray2 = ExplicitMethod(temparray1); - converged = PrecisionCheck(temparray1, temparray2, precision); - temparray1 = temparray2; - } -} - diff --git a/G4STORK/src/HeatTransfer.h b/G4STORK/src/HeatTransfer.h deleted file mode 100755 index ab2ca36a..00000000 --- a/G4STORK/src/HeatTransfer.h +++ /dev/null @@ -1,55 +0,0 @@ -// -// HeatTransfer.h -// G4-STORK-1.0 -// -// Created by Andrew Tan on 2014-11-09. -// Copyright (c) 2014 andrewtan. All rights reserved. -// - -#ifndef __G4_STORK_1_0__HeatTransfer__ -#define __G4_STORK_1_0__HeatTransfer__ - -#include -#include "StorkContainers.hh" -#include "StorkMaterialHT.hh" -#include "G4TransportationManager.hh" -#include "G4Tubs.hh" -#include "G4VSolid.hh" - -class HeatTransfer -{ -public: - HeatTransfer(const G4LogicalVolume* FuelRod,const G4double Fo, const G4double Bi, const G4double T_Inf, const G4int SpatialSteps, const G4double heat); - - ~HeatTransfer(); - void Initialize(const G4double Fo, const G4double Bi, const G4double T_Inf, const G4int SpatialSteps); - void SetHeatGeneration(); - void GetFissionSites(); - void OutputResults(); - void SetMaterialProperties(); - void StartCalculation(); - void ConvergenceRun(std::vector array_, G4int precision); - std::vector ExplicitMethod(std::vector array_); - G4bool PrecisionCheck(std::vector array1, std::vector array2, G4int precision); - - - -protected: - - G4double timeStep; - G4double spatialStep; - G4double FourierNumber; - G4double BiotNumber; - G4double thermalDiffusivity; - G4double thermalConductivity; - G4double avgTemperature; - G4double HeatTransferCoefficient; - G4double HeatFlux; - G4double CoolentTemp; - G4double heatGeneration; - G4int numSteps; - std::vector InitialCondition; - std::vector Output; -}; - -#endif /* defined(__G4_STORK_1_0__HeatTransfer__) */ diff --git a/G4STORK/src/InfiniteUniformLatticeConstructor.cc b/G4STORK/src/InfiniteUniformLatticeConstructor.cc deleted file mode 100755 index 66085032..00000000 --- a/G4STORK/src/InfiniteUniformLatticeConstructor.cc +++ /dev/null @@ -1,230 +0,0 @@ - -/* -InfiniteUniformLatticeConstructor.cc - -Created by: Liam Russell -Date: 23-05-2012 -Modified: 11-03-2013 - -Source code for the InfiniteUniformLatticeConstructor class. - -*/ - -#include "InfiniteUniformLatticeConstructor.hh" - - -// Constructor -InfiniteUniformLatticeConstructor::InfiniteUniformLatticeConstructor() -: StorkVWorldConstructor(), reactorLogical(0) -{ - // Set default member variables - matTemp = 293.6*kelvin; - matDensity = 18.9*g/cm3; - u235Conc = 0.05*perCent; - hwConc = 90.0*perCent; - latticePitch = 100*cm; - - reactorVisAtt=NULL; -} - - -// Destructor -InfiniteUniformLatticeConstructor::~InfiniteUniformLatticeConstructor() -{ - // Delete visualization attributes - if(reactorVisAtt) - delete reactorVisAtt; -} - - -// ConstructNewWorld() -// Build the infinite uniform lattice for the first time. Set the user input -// choices and the variable properties map. -G4VPhysicalVolume* InfiniteUniformLatticeConstructor::ConstructNewWorld( - const StorkParseInput* infile) -{ - // Select material based on input file - switch(infile->GetReactorMaterial()) - { - case 9: - materialID = "EU"; - break; - default: - materialID = "UHW"; - break; - - } - - // Set up variable property map - variablePropMap[MatPropPair(all,temperature)] = &matTemp; - variablePropMap[MatPropPair(all,density)] = &matDensity; - variablePropMap[MatPropPair(all,dimension)] = &latticePitch; - variablePropMap[MatPropPair(fuel,concentration)] = &u235Conc; - variablePropMap[MatPropPair(moderator,concentration)] = &hwConc; - - - // Call base class ConstructNewWorld() to complete construction - return StorkVWorldConstructor::ConstructNewWorld(infile); -} - - -// ConstructWorld() -// Build the materials and geometry for the infinite uniform lattice. -G4VPhysicalVolume* InfiniteUniformLatticeConstructor::ConstructWorld() -{ - // local variables and enclosed world dimensions - G4double buffer = 1.0*cm; - G4double side = latticePitch/2.0; - reactorDim = G4ThreeVector(side, side, side); - encWorldDim = 2.0 * G4ThreeVector(side+buffer,side+buffer,side+buffer); - G4SolidStore* theSolids = G4SolidStore::GetInstance(); - - // Set up the materials (if necessary) - if(matChanged) - { - // Delete any existing materials - DestroyMaterials(); - // Create the materials - ConstructMaterials(); - } - - // Clean up volumes - G4GeometryManager::GetInstance()->OpenGeometry(); - G4PhysicalVolumeStore::GetInstance()->Clean(); - G4LogicalVolumeStore::GetInstance()->Clean(); - - // Set up the solids if necessary - if(geomChanged) - { - // Clean up solids - G4SolidStore::GetInstance()->Clean(); - - // Create world box - new G4Box("worldCube", side+buffer, side+buffer, side+buffer); - // Create lattice cell - new G4Box("FuelCube", side, side, side); - - geomChanged = false; - } - - // Create world volume - worldLogical = new G4LogicalVolume(theSolids->GetSolid("worldCube"), - matMap["World"],"worldLogical",0,0,0); - worldPhysical = new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), worldLogical, - "worldPhysical",0,0,0); - - // Create the homogenous cube reactor - reactorLogical = new G4LogicalVolume(theSolids->GetSolid("FuelCube"), - matMap[materialID],"reactorLogical", - 0,0,0); - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), reactorLogical, - "reactorPhysical", worldLogical,0,0); - - - // Add sensitive detector to ALL logical volumes - worldLogical->SetSensitiveDetector( sDReactor ); - reactorLogical->SetSensitiveDetector( sDReactor ); - - // Set visualization attributes - - if(worldVisAtt) - delete worldVisAtt; - if(reactorVisAtt) - delete reactorVisAtt; - - worldVisAtt = new G4VisAttributes(G4Colour(1.,1.,1.)); - worldVisAtt->SetVisibility(false); - worldLogical->SetVisAttributes(worldVisAtt); - - reactorVisAtt = new G4VisAttributes(G4Colour(1.,0.,0.)); - reactorLogical->SetVisAttributes(reactorVisAtt); - - - return worldPhysical; -} - - -// ConstructMaterials() -// Define and build all materials for the infinite uniform lattice. -void InfiniteUniformLatticeConstructor::ConstructMaterials() -{ - G4double massFracU = 10.73*perCent; - G4double massFracW = 100.0*perCent - massFracU; - G4double abunD20 = hwConc; - G4double abunH20 = 1.0-hwConc; - G4double abunU235 = u235Conc; - G4double abunU238 = 1.0-u235Conc; - G4double density; - - // Elements, isotopes and materials - G4Isotope *H, *D2, *O16, *U235, *U238; - G4Element *Uranium, *Oxygen, *Deuterium, *Hydrogen, *UMod; - G4Material *World, *UHW, *LightWater, *HeavyWater, *EU; - - - // Create the world environment - World = new G4Material("Galactic", 1, 1, 1.e-25*g/cm3, kStateGas, - 2.73*kelvin, 3.e-18*pascal); - - // Make uranium isotopes and elements - - U235 = new G4Isotope("U235", 92, 235, 235.0439*g/mole); - U238 = new G4Isotope("U238", 92, 238, 238.0508*g/mole); - - Uranium = new G4Element("Uranium", "U", 2); - Uranium->AddIsotope(U235, 0.7204*perCent); - Uranium->AddIsotope(U238, 100.0*perCent-0.7204*perCent); - - UMod = new G4Element("UraniumMix", "UMod", 2); - UMod->AddIsotope(U235, abunU235); - UMod->AddIsotope(U238, abunU238); - - //Make natural Hydrogen - H = new G4Isotope("H", 1, 1, 1.008*g/mole); - Hydrogen = new G4Element("Hydrogen", "H", 1); - Hydrogen->AddIsotope(H, 100.*perCent); - - // Make heavy water isotopes and elements - D2 = new G4Isotope("D2", 1, 2, 2.014*g/mole); - Deuterium = new G4Element("Deuterium", "D", 1); - Deuterium->AddIsotope(D2, 100.*perCent); - - O16 = new G4Isotope("O16", 8, 16, 15.995*g/mole); - Oxygen = new G4Element("Oxygen", "O", 1); - Oxygen->AddIsotope(O16, 100*perCent); - - // Make the heavy water material - HeavyWater = new G4Material("Heavy Water", 1.1056*g/cm3, 2, kStateLiquid, - matTemp); - HeavyWater->AddElement(Deuterium, 2); - HeavyWater->AddElement(Oxygen, 1); - - LightWater = new G4Material("Light Water", 1.0*g/cm3, 2, kStateLiquid, - matTemp); - LightWater->AddElement(Hydrogen, 2); - LightWater->AddElement(Oxygen, 1); - - density = massFracW*(abunD20*1.1056*g/cm3 + abunH20*1.0*g/cm3) + - massFracU*(0.7204*perCent*18.75*g/cm3 + - (99.2796*perCent)*18.9*g/cm3); - - UHW = new G4Material("UHW", density, 3, kStateLiquid, matTemp); - UHW->AddMaterial(HeavyWater, abunD20); - UHW->AddMaterial(LightWater, abunH20); - UHW->AddElement(Uranium, massFracU); - - EU = new G4Material("EU", matDensity, 1, kStateSolid, matTemp); - EU->AddElement(UMod, 100.*perCent); - - // Add materials to the map - matMap["World"] = World; - matMap["UHW"] = UHW; - matMap["EU"] = EU; - - // Reset material change flag - matChanged = false; - - return; -} - - diff --git a/G4STORK/src/Q_ZED2Constructor.cc b/G4STORK/src/Q_ZED2Constructor.cc deleted file mode 100755 index 9db718f8..00000000 --- a/G4STORK/src/Q_ZED2Constructor.cc +++ /dev/null @@ -1,1195 +0,0 @@ - -/* -Q_ZED2Constructor.cc - -Created by: Salma Mahzooni -Date: 26-07-2013 -Modified: 06-12-2014 - -Source code for the ZED2 geometry and materials - -*/ - -#include "Q_ZED2Constructor.hh" - - -// Constructor -Q_ZED2Constructor::Q_ZED2Constructor() -: StorkVWorldConstructor() -{ - // Set default values for member variables - matTemp = 299.51*kelvin; - - vesselVisAtt=NULL; - tank1VisATT=NULL; - ModVisAtt=NULL; - fuelA1VisATT=NULL; - fuelB1VisATT=NULL; - sheathA1VisATT=NULL; - sheathB1VisATT=NULL; - Air1VisAtt=NULL; - Coolant1VisAtt=NULL; - Pressure1VisAtt=NULL; - GasAnn1VisAtt=NULL; - Calandria1VisAtt=NULL; - EndPlate2VisATT=NULL; - airTubeVisAtt=NULL; -} - - -// Destructor -Q_ZED2Constructor::~Q_ZED2Constructor() -{ - // Delete visualization attributes - if(vesselVisAtt) - delete vesselVisAtt; - if(tank1VisATT) - delete tank1VisATT; - if(ModVisAtt) - delete ModVisAtt; - if(fuelA1VisATT) - delete fuelA1VisATT; - if(fuelB1VisATT) - delete fuelB1VisATT; - if(sheathA1VisATT) - delete sheathA1VisATT; - if(sheathB1VisATT) - delete sheathB1VisATT; - if(Air1VisAtt) - delete Air1VisAtt; - if(Coolant1VisAtt) - delete Coolant1VisAtt; - if(Pressure1VisAtt) - delete Pressure1VisAtt; - if(GasAnn1VisAtt) - delete GasAnn1VisAtt; - if(Calandria1VisAtt) - delete Calandria1VisAtt; - if(EndPlate2VisATT) - delete EndPlate2VisATT; - if(airTubeVisAtt) - delete airTubeVisAtt; - - -} - - -// ConstructNewWorld() -G4VPhysicalVolume* -Q_ZED2Constructor::ConstructNewWorld(const StorkParseInput* infile) -{ - - // Call base class ConstructNewWorld() to complete construction - return StorkVWorldConstructor::ConstructNewWorld(infile); -} - - -// ConstructWorld -// Construct the geometry and materials of the spheres given the inputs. -G4VPhysicalVolume* Q_ZED2Constructor::ConstructWorld() -{ - - - - // Set local variables and enclosed world dimensions - reactorDim = G4ThreeVector(0.*cm, 231.806*cm/2. ,405.4*cm/2.); - G4double buffer = 1.0*cm; - encWorldDim = G4ThreeVector(2.*reactorDim[1]+buffer, 2.*reactorDim[1]+buffer, 2*reactorDim[2]+buffer); - G4SolidStore* theSolids = G4SolidStore::GetInstance(); - - //Defining the graphite wall and bottom - G4double Graphitewall[3] ={0.*cm, 231.806*cm, 315.4*cm/2.}; - G4double Graphitebott[3] = {0., 231.806*cm,90.0*cm/2.}; - - // Create Dimensions of Calandria Tank - G4double CalandriaDim1[3] = { 0.*cm, 168.635*cm, 315.4*cm/2.-2.69*cm/2.}; - G4double BotReacTankDim[3] = {0.*cm, 168.635*cm, 2.69*cm/2.}; - - // Defining the dimensions of the moderator - // Defining the dimensions of the moderator - G4double ModHeight = 132.707*cm; - G4double distbtwflrtofuel = 10.1124*cm; - G4double RodHeight = 2.0*CalandriaDim1[2]-distbtwflrtofuel; - G4double MTankDim[3] = {0.*cm, 168.0*cm, ModHeight}; - G4double TubeAirFuel[3] = {0.0*cm, 168.0*cm, (2*CalandriaDim1[2]-ModHeight)/2.}; - - - // Create Dimensions of Fuel Assembly - G4double CalendriaT1Dim[3] = {0.0*cm, 12.74*cm, RodHeight}; - G4double GasAnn1Dim[3] = {0.0*cm, 12.46*cm, RodHeight}; - G4double PressureT1Dim[3] = {0.0*cm, 10.78*cm, RodHeight}; - G4double Coolant1Dim[3] = {0.0*cm, 10.19*cm, (5.*(49.51*cm))}; - G4double Air1Dim[3] = {0.0*cm, 10.19*cm, RodHeight-(5.*(49.51*cm))}; - G4double EndPlate2[3] = { 0.0*cm, 4.585*cm, 0.16*cm/2.0}; - G4double FuelRodADim1[3] = {0.0*cm, 1.264*cm,48.25*cm/2.}; - G4double FuelRodBDim1[3] = {0.0*cm, 1.070*cm,48.0*cm/2.}; - G4double SheathADim1[3] = {0.0*cm, 1.350*cm, 49.19*cm/2.}; - G4double SheathBDim1[3] = {0.0*cm, 1.150*cm, 49.19*cm/2.}; - - // Create the ring for fuel pins placement - G4int rings = 4; - G4double ringRad[3] = {1.734*cm,3.075*cm,4.384*cm}; - G4double secondRingOffset = 0.261799*radian; - - - G4double topCalandriatoModH = 2.*CalandriaDim1[2]-ModHeight; - G4double AirinCT = RodHeight-Coolant1Dim[2]; - G4double topFueltoModH = topCalandriatoModH-AirinCT; - G4double FuelinModH = Coolant1Dim[2]-(topFueltoModH); - G4int ModFuelIntersectPin = floor((((topFueltoModH)/10.)/49.51*cm)/10.); - G4int NumOfFuelBunInMod = floor((((FuelinModH)/10.)/49.51*cm)/10.); - G4double FullFuelBunInAir = ModFuelIntersectPin*49.51*cm; - G4double ModFuelIntersectPos = (topFueltoModH-FullFuelBunInAir-0.16*cm); - G4double CutFuelBunInMod = 49.19*cm-ModFuelIntersectPos; - -// Positions of the fuel bundles - G4double Pich[2] = {24.5*cm, 24.5*cm}; - G4double XPos[] = { - Pich[0]/2,Pich[0]/2,Pich[0]/2,Pich[0]/2, - 3*Pich[0]/2, 3*Pich[0]/2, 3*Pich[0]/2, 3*Pich[0]/2, - 5*Pich[0]/2,5*Pich[0]/2,5*Pich[0]/2, - 7*Pich[0]/2,7*Pich[0]/2}; - - G4double YPos[] = { - Pich[1]/2, 3.*Pich[1]/2, 5.*Pich[1]/2, 7.*Pich[1]/2, - Pich[1]/2, 3.*Pich[1]/2, 5.*Pich[1]/2, 7.*Pich[1]/2, - Pich[1]/2, 3.*Pich[1]/2, 5.*Pich[1]/2, - Pich[1]/2, 3.*Pich[1]/2 - }; - - - // Set up the materials (if necessary) - if(matChanged) - { - // Delete any existing materials - DestroyMaterials(); - // Create the materials - ConstructMaterials(); - } - - // Clean up volumes - G4GeometryManager::GetInstance()->OpenGeometry(); - G4PhysicalVolumeStore::GetInstance()->Clean(); - G4LogicalVolumeStore::GetInstance()->Clean(); - - // Set up the solids if necessary - if(geomChanged) - { - // Clean up solids - G4SolidStore::GetInstance()->Clean(); - - // Create world solid - new G4Box("ZED2World", encWorldDim[0]/2., encWorldDim[1]/2. , encWorldDim[2]/2.); - // Create the air above the moderator - new G4Tubs("AirTube", TubeAirFuel[0], TubeAirFuel[1], TubeAirFuel[2], 0., CLHEP::pi/2.0); - - - // Create Graphite Reflector solid - new G4Tubs("graphitewall", Graphitewall[0], Graphitewall[1], Graphitewall[2], 0., CLHEP::pi/2.0); - new G4Tubs("graphitebott", Graphitewall[0], Graphitewall[1], Graphitebott[2], 0., CLHEP::pi/2.0); - new G4UnionSolid("graphitewall+graphitebott", theSolids->GetSolid("graphitewall"), theSolids->GetSolid("graphitebott"), 0, G4ThreeVector(0.,0.,-Graphitewall[2]-Graphitebott[2])); - // Create Sheilding walls - //new G4Tubs("sheildingwall", Shieldingwall[0], Shieldingwall[1], Shieldingwall[2], 0., 2.0*CLHEP::pi); - - // Create the Calandria solids 1 - new G4Tubs("calandriashell", CalandriaDim1[0], CalandriaDim1[1], CalandriaDim1[2], 0., CLHEP::pi/2.0); - new G4Tubs("calandriabott", BotReacTankDim[0], BotReacTankDim[1], BotReacTankDim[2], 0., CLHEP::pi/2.0); - new G4UnionSolid("calandriashell+calandriabott", theSolids->GetSolid("calandriashell"), theSolids->GetSolid("calandriabott"), 0, G4ThreeVector(0,0,(-CalandriaDim1[2]-BotReacTankDim[2]))); - - // Create Moderator solid - new G4Tubs("ModSphere", MTankDim[0], MTankDim[1], MTankDim[2]/2., 0., CLHEP::pi/2.0); - - // Create the air above the coolant tube solid - new G4Tubs("AirTube1", Air1Dim[0]/2, Air1Dim[1]/2, Air1Dim[2]/2., 0., 2.0*CLHEP::pi); - - // Create the Calandria tube - new G4Tubs("CalandriaTubedwnCut1", CalendriaT1Dim[0]/2, CalendriaT1Dim[1]/2, (CalendriaT1Dim[2]-topCalandriatoModH)/2., 0., 2.0*CLHEP::pi); - new G4Tubs("CalandriaTubedwnCut2", CalendriaT1Dim[0]/2, CalendriaT1Dim[1]/2, topCalandriatoModH/2., 0., 2.0*CLHEP::pi); - - // Create the GasAnn tube solid - new G4Tubs("GasAnnTube1Cut1", GasAnn1Dim[0]/2, GasAnn1Dim[1]/2, (GasAnn1Dim[2]-topCalandriatoModH)/2., 0., 2.0*CLHEP::pi); - new G4Tubs("GasAnnTube1Cut2", GasAnn1Dim[0]/2, GasAnn1Dim[1]/2, topCalandriatoModH/2., 0., 2.0*CLHEP::pi); - - // Create the pressure tube solid - new G4Tubs("PressureTubedwnCut1", PressureT1Dim[0]/2, PressureT1Dim[1]/2, (GasAnn1Dim[2]-topCalandriatoModH)/2, 0., 2.0*CLHEP::pi); - new G4Tubs("PressureTubedwnCut2", PressureT1Dim[0]/2, PressureT1Dim[1]/2, topCalandriatoModH/2., 0., 2.0*CLHEP::pi); - - // Create the coolant tube solid - new G4Tubs("CoolantTube1Cut1", Coolant1Dim[0]/2, Coolant1Dim[1]/2, FuelinModH/2., 0., 2.0*CLHEP::pi); - new G4Tubs("CoolantTube1Cut2", Coolant1Dim[0]/2, Coolant1Dim[1]/2, topFueltoModH/2., 0., 2.0*CLHEP::pi); - - // Create outer fuel bunndles solid - new G4Tubs("FuelTubeB1", FuelRodBDim1[0]/2, FuelRodBDim1[1]/2, FuelRodBDim1[2], 0., 2.0*CLHEP::pi); - new G4Tubs("FuelTubeB1Cut1", FuelRodBDim1[0]/2, FuelRodBDim1[1]/2, CutFuelBunInMod/2., 0., 2.0*CLHEP::pi); - new G4Tubs("FuelTubeB1Cut2", FuelRodBDim1[0]/2, FuelRodBDim1[1]/2, ModFuelIntersectPos/2., 0., 2.0*CLHEP::pi); - - - // Create inner fuel bunndles solid - new G4Tubs("FuelTubeA1", FuelRodADim1[0]/2, FuelRodADim1[1]/2, FuelRodADim1[2], 0., 2.0*CLHEP::pi); - new G4Tubs("FuelTubeA1Cut1", FuelRodADim1[0]/2, FuelRodADim1[1]/2, CutFuelBunInMod/2., 0., 2.0*CLHEP::pi); - new G4Tubs("FuelTubeA1Cut2", FuelRodADim1[0]/2, FuelRodADim1[1]/2, ModFuelIntersectPos/2., 0., 2.0*CLHEP::pi); - - - // Create outer Zr-4 sheath solid - new G4Tubs("SheathB1", SheathBDim1[0]/2, SheathBDim1[1]/2, SheathBDim1[2], 0., 2.0*CLHEP::pi); - new G4Tubs("SheathB1Cut1", SheathBDim1[0]/2, SheathBDim1[1]/2, CutFuelBunInMod/2., 0., 2.0*CLHEP::pi); - new G4Tubs("SheathB1Cut2", SheathBDim1[0]/2, SheathBDim1[1]/2, ModFuelIntersectPos/2., 0., 2.0*CLHEP::pi); - - // Create inner Zr-4 sheath solid - new G4Tubs("SheathA1", SheathADim1[0]/2, SheathADim1[1]/2, SheathADim1[2], 0., 2.0*CLHEP::pi); - new G4Tubs("SheathA1Cut1", SheathADim1[0]/2, SheathADim1[1]/2, CutFuelBunInMod/2., 0., 2.0*CLHEP::pi); - new G4Tubs("SheathA1Cut2", SheathADim1[0]/2, SheathADim1[1]/2, ModFuelIntersectPos/2., 0., 2.0*CLHEP::pi); - - // Create the end plate - new G4Tubs("EndPlate2", EndPlate2[0], EndPlate2[1], EndPlate2[2], 0., 2.0*CLHEP::pi); - new G4Tubs("EndPlate1", EndPlate2[0], EndPlate2[1], EndPlate2[2], 0., 2.0*CLHEP::pi); - - - - geomChanged = false; - } - - - // Create world volume - worldLogical = new G4LogicalVolume(theSolids->GetSolid("ZED2World"),matMap["World"], "worldLogical",0,0,0); - worldPhysical = new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), worldLogical,"worldPhysical",0,0,0); - - // Create Reflector volume - vesselLogical = new G4LogicalVolume(theSolids->GetSolid("graphitewall+graphitebott"), matMap["Graphite"], "VesselLogical", 0, 0, 0); - new G4PVPlacement(0,G4ThreeVector(-reactorDim[1],-reactorDim[1],Graphitebott[2]), vesselLogical, "VesselPhysical",worldLogical , 0, 0); - - // Create Calandrai volume in mother air volume - tankLogical1 = new G4LogicalVolume(theSolids->GetSolid("calandriashell+calandriabott"), matMap["Al57S"], "VesselLogical1", 0, 0, 0); - new G4PVPlacement(0, G4ThreeVector(0.,0.,BotReacTankDim[2]), tankLogical1,"CalandriaPhysical1", vesselLogical,0,0); - - // Create Moderator volume - ModLogical = new G4LogicalVolume(theSolids->GetSolid("ModSphere"),matMap["Moderator"], "ModLogical",0,0,0); - new G4PVPlacement(0, G4ThreeVector(0.,0.,MTankDim[2]/2-CalandriaDim1[2]), ModLogical, "ModPhysical", tankLogical1, false,0); - - //Create Air above the moderator - airTubeLogical = new G4LogicalVolume(theSolids->GetSolid("AirTube"),matMap["Air"], "airTubeLogical",0,0,0); - new G4PVPlacement(0, G4ThreeVector(0.,0., TubeAirFuel[2]+MTankDim[2]-CalandriaDim1[2]), airTubeLogical, "airTubePhysical", tankLogical1,0,0); - - std::stringstream volName; - - logicCalandria1 = new G4LogicalVolume(theSolids->GetSolid("CalandriaTubedwnCut2"), matMap["AlCalT"], "CalandriaTube1LogicalCut2", 0, 0, 0); - for (G4int i=0; i<13; i++) - { - // Create calandria tubes in mother air volume - volName.str(""); - volName.clear(); - volName << i; - new G4PVPlacement (0, G4ThreeVector(XPos[i],YPos[i],0.), logicCalandria1, "CalandriaTube1PhysicalCut2"+volName.str(), airTubeLogical, false, 0); - } - // Create gas annulus tubes in mother air volume - logicGasAnn1 = new G4LogicalVolume(theSolids->GetSolid("GasAnnTube1Cut2"), matMap["Air"], "GasAnnTube1Logical", 0, 0, 0); - new G4PVPlacement (0, G4ThreeVector(0,0,0), logicGasAnn1, "GasAnnTube1PhysicalCut2", logicCalandria1, false, 0); - - // Create pressure tubes in mother air volume - logicPressure1 = new G4LogicalVolume(theSolids->GetSolid("PressureTubedwnCut2"), matMap["AlPresT"], "PressureTube1Logical", 0, 0, 0); - new G4PVPlacement (0, G4ThreeVector(0,0,0), logicPressure1, "PressureTube1PhysicalCut2", logicGasAnn1, false, 0); - - // Create lower coolant in mother air volume - logicCoolant1 = new G4LogicalVolume(theSolids->GetSolid("CoolantTube1Cut2"), matMap["Air"], "Coolant1Logical", 0, 0, 0); - new G4PVPlacement (0, G4ThreeVector(0,0,-topCalandriatoModH/2.+topFueltoModH/2.), logicCoolant1, "Coolant1PhysicalCut2", logicPressure1, false, 0); - - // Create air - logicAir1 = new G4LogicalVolume(theSolids->GetSolid("AirTube1"), matMap["Air"], "Air1Logical", 0, 0, 0); - new G4PVPlacement (0, G4ThreeVector(0,0,-topCalandriatoModH/2.+topFueltoModH+Air1Dim[2]/2.0), logicAir1, "Air1Physical", logicPressure1, false, 0); - - // Create inner/outer FULL fuel bunndles and sheath in air volume - logicRodA1 = new G4LogicalVolume(theSolids->GetSolid("FuelTubeA1"), matMap["LEUMat"], "FuelRodA1Logical", 0, 0, 0); - logicRodB1 = new G4LogicalVolume(theSolids->GetSolid("FuelTubeB1"), matMap["LEUMat"], "FuelRodB1Logical", 0, 0, 0); - logicSheathA1 = new G4LogicalVolume(theSolids->GetSolid("SheathA1"), matMap["Zr4"], "SheathA1Logical", 0, 0, 0); - logicSheathB1 = new G4LogicalVolume(theSolids->GetSolid("SheathB1"), matMap["Zr4"], "SheathB1Logical", 0, 0, 0); - logicEndPlate1 = new G4LogicalVolume(theSolids->GetSolid("EndPlate1"), matMap["Zr4"], "EndPlate1", 0, 0, 0); - logicEndPlate2 = new G4LogicalVolume(theSolids->GetSolid("EndPlate2"), matMap["Zr4"], "EndPlate2", 0, 0, 0); - - for (G4int l=0; lGetSolid("FuelTubeA1Cut2"), matMap["LEUMat"], "FuelRodA1LogicalCut2", 0, 0, 0); - logicRodB1Cut2 = new G4LogicalVolume(theSolids->GetSolid("FuelTubeB1Cut2"), matMap["LEUMat"], "FuelRodB1LogicalCut2", 0, 0, 0); - logicSheathA1Cut2 = new G4LogicalVolume(theSolids->GetSolid("SheathA1Cut2"), matMap["Zr4"], "SheathA1Logicalcut2", 0, 0, 0); - logicSheathB1Cut2 = new G4LogicalVolume(theSolids->GetSolid("SheathB1Cut2"), matMap["Zr4"], "SheathB1LogicalCut2", 0, 0, 0); - logicEndPlate2Cut2 = new G4LogicalVolume(theSolids->GetSolid("EndPlate2"), matMap["Zr4"], "EndPlate2Cut2", 0, 0, 0); - // Rotation and translation of the rod and sheathe - - // Set name for sheathe physical volume - - volName.str(""); - volName << 0; - - // place the center pin in air - new G4PVPlacement(0, G4ThreeVector(0,0,-topFueltoModH/2.+ModFuelIntersectPos/2.), logicSheathA1Cut2,"sheathePhysicalCut2 " + volName.str(), logicCoolant1,0,0); - new G4PVPlacement(0, G4ThreeVector(0,0,0), logicRodA1Cut2,"fuelPhysicalCut2A", logicSheathA1Cut2,0,0); - new G4PVPlacement(0, G4ThreeVector(0,0,0), logicRodB1Cut2,"fuelPhysicalCut2B", logicSheathB1Cut2,0,0); - - - - - for( G4int j = 1; j < rings; j++ ) - { - for( G4int k = 0; k < j*6; k++ ) - { - // Reset string stream - volName.str(""); - - volName << j << "-" << k; - - if(j == 2) - { - G4ThreeVector Tm(ringRad[j-1]*cos(2.0*CLHEP::pi*G4double(k)/G4double(j*6)+secondRingOffset), ringRad[j-1]*sin(2.0*CLHEP::pi*G4double(k)/G4double(j*6)+secondRingOffset),-topFueltoModH/2.+ModFuelIntersectPos/2.); - new G4PVPlacement(0, Tm, logicSheathB1Cut2,"sheathePhysicalCut2 " +volName.str(),logicCoolant1,0,0); - - } - else if (j == 1) - { - G4ThreeVector Tm(ringRad[j-1]*cos(2.0*CLHEP::pi*G4double(k)/G4double(j*6)), ringRad[j-1]*sin(2.0*CLHEP::pi*G4double(k)/G4double(j*6)),-topFueltoModH/2.+ModFuelIntersectPos/2.); - new G4PVPlacement(0, Tm, logicSheathA1Cut2,"sheathePhysicalCut2 " +volName.str(),logicCoolant1,0,0); - } - else - { - G4ThreeVector Tm(ringRad[j-1]*cos(2.0*CLHEP::pi*G4double(k)/G4double(j*6)), ringRad[j-1]*sin(2.0*CLHEP::pi*G4double(k)/G4double(j*6)),-topFueltoModH/2.+ModFuelIntersectPos/2.); - new G4PVPlacement(0, Tm, logicSheathB1Cut2,"sheathePhysicalCut2 " +volName.str(),logicCoolant1,0,0); - } - } - } - - - // Make the end plates 2 - G4ThreeVector EP2(0,0,-topFueltoModH/2.+ModFuelIntersectPos+0.08*cm); - new G4PVPlacement(0, EP2, logicEndPlate2Cut2,"EndPlate2Physical1Cut2",logicCoolant1,0,0); - - - - - - // *********Create Calandrai volume in moderator volume************* - logicCalandria1Mod = new G4LogicalVolume(theSolids->GetSolid("CalandriaTubedwnCut1"), matMap["AlCalT"], "CalandriaTube1ModLogical", 0, 0, 0); - for (G4int i=0; i<13; i++) - { - // Create calandria tubes in moderator volume -reactorDim[2]+2.*Graphitebott[2]+2.*BotReacTankDim[2]+distbtwflrtofuel+(CalendriaT1Dim[2]-topFueltoModH)/2.MTankDim[2] - volName.str(""); - volName.clear(); - volName << i; - new G4PVPlacement (0, G4ThreeVector(XPos[i],YPos[i],distbtwflrtofuel/2.), logicCalandria1Mod, "CalandriaTube1ModPhysicalCut1"+volName.str(), ModLogical, false, 0); - } - // Create gas annulus tubes in moderator volume - logicGasAnn1Mod = new G4LogicalVolume(theSolids->GetSolid("GasAnnTube1Cut1"), matMap["Air"], "GasAnnTube1Logical", 0, 0, 0); - new G4PVPlacement (0, G4ThreeVector(0,0,0), logicGasAnn1Mod, "GasAnnTube1PhysicalCut1", logicCalandria1Mod, false, 0); - - // Create pressure tubes in moderator volume - logicPressure1Mod = new G4LogicalVolume(theSolids->GetSolid("PressureTubedwnCut1"), matMap["AlPresT"], "PressureTube1Logical", 0, 0, 0); - new G4PVPlacement (0, G4ThreeVector(0,0,0), logicPressure1Mod, "PressureTube1PhysicalCut1", logicGasAnn1Mod, false, 0); - - // Create lower coolant in moderator volume - logicCoolant1Mod = new G4LogicalVolume(theSolids->GetSolid("CoolantTube1Cut1"), matMap["Air"], "Coolant1Logical", 0, 0, 0); - new G4PVPlacement (0, G4ThreeVector(0,0,0), logicCoolant1Mod, "Coolant1PhysicalCut1", logicPressure1Mod, false, 0); - - // Create inner/outer fuel bunndle and sheath in Moderator volume - logicRodA1Mod = new G4LogicalVolume(theSolids->GetSolid("FuelTubeA1"), matMap["LEUMat"], "FuelRodA1LogicalMod", 0, 0, 0); - logicRodB1Mod = new G4LogicalVolume(theSolids->GetSolid("FuelTubeB1"), matMap["LEUMat"], "FuelRodB1LogicalMod", 0, 0, 0); - logicSheathA1Mod = new G4LogicalVolume(theSolids->GetSolid("SheathA1"), matMap["Zr4"], "SheathA1LogicalMod", 0, 0, 0); - logicSheathB1Mod = new G4LogicalVolume(theSolids->GetSolid("SheathB1"), matMap["Zr4"], "SheathB1LogicalMod", 0, 0, 0); - logicEndPlate1Mod = new G4LogicalVolume(theSolids->GetSolid("EndPlate1"), matMap["Zr4"], "EndPlate1Mod", 0, 0, 0); - logicEndPlate2Mod = new G4LogicalVolume(theSolids->GetSolid("EndPlate2"), matMap["Zr4"], "EndPlate2Mod", 0, 0, 0); - - for (G4int l=0; lGetSolid("FuelTubeA1Cut1"), matMap["LEUMat"], "FuelRodA1LogicalCut1", 0, 0, 0); - logicRodB1Cut1 = new G4LogicalVolume(theSolids->GetSolid("FuelTubeB1Cut1"), matMap["LEUMat"], "FuelRodB1LogicalCut1", 0, 0, 0); - logicSheathA1Cut1 = new G4LogicalVolume(theSolids->GetSolid("SheathA1Cut1"), matMap["Zr4"], "SheathA1LogicalCut1", 0, 0, 0); - logicSheathB1Cut1 = new G4LogicalVolume(theSolids->GetSolid("SheathB1Cut1"), matMap["Zr4"], "SheathB1LogicalCut1", 0, 0, 0); - logicEndPlate2Cut1 = new G4LogicalVolume(theSolids->GetSolid("EndPlate2"), matMap["Zr4"], "EndPlate2Cut1", 0, 0, 0); - - // place the center pin for the cut fuel bundle in the moderator - new G4PVPlacement(0, G4ThreeVector(0,0, (-FuelinModH/2.+(NumOfFuelBunInMod*49.51*cm)+2.*EndPlate2[2]+CutFuelBunInMod/2. )), logicSheathA1Cut1,"sheathePhysicalCut1 " + volName.str(), logicCoolant1Mod,0,0); - new G4PVPlacement(0, G4ThreeVector(0,0,0), logicRodA1Cut1,"fuelPhysicalCut1A ", logicSheathA1Cut1,0,0); - new G4PVPlacement(0, G4ThreeVector(0,0,0), logicRodB1Cut1,"fuelPhysicalCut1B ", logicSheathB1Cut1,0,0); - - - - - // Make the end plates 2 - G4ThreeVector EP(0,0,(-FuelinModH/2.+(NumOfFuelBunInMod*49.51*cm)+0.08*cm)); - new G4PVPlacement(0, EP, logicEndPlate2Cut1,"EndPlate2Physical1Cut1 ",logicCoolant1Mod,0,0); - - for( G4int j = 1; j < rings; j++ ) - { - for( G4int k = 0; k < j*6; k++ ) - { - // Reset string stream - volName.str(""); - - volName << j << "-" << k; - - if(j == 2) - { - G4ThreeVector Tm(ringRad[j-1]*cos(2.0*CLHEP::pi*G4double(k)/G4double(j*6)+secondRingOffset), ringRad[j-1]*sin(2.0*CLHEP::pi*G4double(k)/G4double(j*6)+secondRingOffset),(-FuelinModH/2.+(NumOfFuelBunInMod*49.51*cm)+2.*EndPlate2[2]+CutFuelBunInMod/2. )); - // place the fuel for the cut fuel bundle in the moderator - new G4PVPlacement(0, Tm, logicSheathB1Cut1,"sheathePhysicalCut1 " +volName.str(),logicCoolant1Mod,0,0); - - } - else if (j == 1) - { - G4ThreeVector Tm(ringRad[j-1]*cos(2.0*CLHEP::pi*G4double(k)/G4double(j*6)), ringRad[j-1]*sin(2.0*CLHEP::pi*G4double(k)/G4double(j*6)),(-FuelinModH/2.+(NumOfFuelBunInMod*49.51*cm)+2.*EndPlate2[2]+CutFuelBunInMod/2. )); - new G4PVPlacement(0, Tm, logicSheathA1Cut1,"sheathePhysicalCut1 " +volName.str(),logicCoolant1Mod,0,0); - } - else - { - G4ThreeVector Tm(ringRad[j-1]*cos(2.0*CLHEP::pi*G4double(k)/G4double(j*6)), ringRad[j-1]*sin(2.0*CLHEP::pi*G4double(k)/G4double(j*6)),(-FuelinModH/2.+(NumOfFuelBunInMod*49.51*cm)+2.*EndPlate2[2]+CutFuelBunInMod/2. )); - // place the fuel for the cut fuel bundle in the moderator - new G4PVPlacement(0, Tm, logicSheathB1Cut1,"sheathePhysicalCut1 " +volName.str(),logicCoolant1Mod,0,0); - } - } - } - - - - - - // Set reactor as sensitive detector - worldLogical->SetSensitiveDetector( sDReactor ); - airTubeLogical->SetSensitiveDetector( sDReactor ); - vesselLogical->SetSensitiveDetector( sDReactor ); - tankLogical1->SetSensitiveDetector( sDReactor ); - ModLogical->SetSensitiveDetector( sDReactor ); - logicCalandria1->SetSensitiveDetector( sDReactor ); - logicGasAnn1->SetSensitiveDetector( sDReactor ); - logicPressure1->SetSensitiveDetector( sDReactor ); - logicCoolant1->SetSensitiveDetector( sDReactor ); - logicAir1->SetSensitiveDetector( sDReactor ); - logicRodA1->SetSensitiveDetector( sDReactor ); - logicRodB1->SetSensitiveDetector( sDReactor ); - logicSheathA1->SetSensitiveDetector( sDReactor ); - logicSheathB1->SetSensitiveDetector( sDReactor ); - logicEndPlate2->SetSensitiveDetector( sDReactor ); - logicEndPlate1->SetSensitiveDetector( sDReactor ); - logicCalandria1Mod->SetSensitiveDetector( sDReactor ); - logicGasAnn1Mod->SetSensitiveDetector( sDReactor ); - logicPressure1Mod->SetSensitiveDetector( sDReactor ); - logicCoolant1Mod->SetSensitiveDetector( sDReactor ); - logicRodA1Cut2->SetSensitiveDetector( sDReactor ); - logicRodB1Cut2->SetSensitiveDetector( sDReactor ); - logicSheathA1Cut2->SetSensitiveDetector( sDReactor ); - logicSheathB1Cut2->SetSensitiveDetector( sDReactor ); - logicEndPlate2Cut2->SetSensitiveDetector( sDReactor ); - logicRodA1Mod->SetSensitiveDetector( sDReactor ); - logicRodB1Mod->SetSensitiveDetector( sDReactor ); - logicSheathA1Mod->SetSensitiveDetector( sDReactor ); - logicSheathB1Mod->SetSensitiveDetector( sDReactor ); - logicEndPlate2Mod->SetSensitiveDetector( sDReactor ); - logicEndPlate1Mod->SetSensitiveDetector( sDReactor ); - logicRodA1Cut1->SetSensitiveDetector( sDReactor ); - logicRodB1Cut1->SetSensitiveDetector( sDReactor ); - logicSheathA1Cut1->SetSensitiveDetector( sDReactor ); - logicSheathB1Cut1->SetSensitiveDetector( sDReactor ); - logicEndPlate2Cut1->SetSensitiveDetector( sDReactor ); - - - - // Set visualization attributes - - if(worldVisAtt) - delete worldVisAtt; - if(vesselVisAtt) - delete vesselVisAtt; - if(tank1VisATT) - delete tank1VisATT; - if(ModVisAtt) - delete ModVisAtt; - if(fuelA1VisATT) - delete fuelA1VisATT; - if(fuelB1VisATT) - delete fuelB1VisATT; - if(sheathA1VisATT) - delete sheathA1VisATT; - if(sheathB1VisATT) - delete sheathB1VisATT; - if(Air1VisAtt) - delete Air1VisAtt; - if(Coolant1VisAtt) - delete Coolant1VisAtt; - if(Pressure1VisAtt) - delete Pressure1VisAtt; - if(GasAnn1VisAtt) - delete GasAnn1VisAtt; - if(Calandria1VisAtt) - delete Calandria1VisAtt; - if(EndPlate2VisATT) - delete EndPlate2VisATT; - if(airTubeVisAtt) - delete airTubeVisAtt; - - worldVisAtt = new G4VisAttributes(G4Colour(0.5, 1., 0.5)); - worldVisAtt->SetVisibility(true); - worldLogical->SetVisAttributes(worldVisAtt); - //reactDimTubeLogical->SetVisAttributes(worldVisAtt); - - airTubeVisAtt = new G4VisAttributes(G4Colour(0., 1., 0.5)); - airTubeVisAtt->SetVisibility(true); - airTubeLogical->SetVisAttributes(airTubeVisAtt); - - vesselVisAtt= new G4VisAttributes(G4Colour(1.0,0.0,0.0)); - vesselVisAtt->SetForceSolid(false); - vesselVisAtt->SetVisibility(true); - vesselLogical->SetVisAttributes(vesselVisAtt); - - tank1VisATT= new G4VisAttributes(G4Colour(1.0,1.0,0.0)); - tank1VisATT->SetForceSolid(false); - tank1VisATT->SetVisibility(true); - tankLogical1->SetVisAttributes(tank1VisATT); - - ModVisAtt = new G4VisAttributes(G4Colour(0.,1.,0.)); - ModVisAtt->SetVisibility(true); - ModVisAtt->SetForceSolid(false); - ModLogical->SetVisAttributes(ModVisAtt); - - Calandria1VisAtt = new G4VisAttributes(G4Colour(1., 0., 1.)); - Calandria1VisAtt->SetForceSolid(false); - Calandria1VisAtt->SetVisibility(false); - logicCalandria1->SetVisAttributes(Calandria1VisAtt); - logicCalandria1Mod->SetVisAttributes(Calandria1VisAtt); - - - GasAnn1VisAtt = new G4VisAttributes(G4Colour(1., 0., 0.)); - GasAnn1VisAtt->SetForceSolid(false); - GasAnn1VisAtt->SetVisibility(false); - logicGasAnn1->SetVisAttributes(GasAnn1VisAtt); - logicGasAnn1Mod->SetVisAttributes(GasAnn1VisAtt); - - - - Pressure1VisAtt = new G4VisAttributes(G4Colour(0., 1., 0.)); - Pressure1VisAtt->SetForceSolid(false); - Pressure1VisAtt->SetVisibility(false); - logicPressure1->SetVisAttributes(Pressure1VisAtt); - logicPressure1Mod->SetVisAttributes(Pressure1VisAtt); - - - Coolant1VisAtt = new G4VisAttributes(G4Colour(0.53, 0.81, 0.92)); - Coolant1VisAtt->SetForceSolid(false); - Coolant1VisAtt->SetVisibility(false); - logicCoolant1->SetVisAttributes(Coolant1VisAtt); - logicCoolant1Mod->SetVisAttributes(Coolant1VisAtt); - - Air1VisAtt = new G4VisAttributes(G4Colour(0., 1., 0.5)); - Air1VisAtt->SetForceSolid(false); - Air1VisAtt->SetVisibility(true); - logicAir1->SetVisAttributes(Air1VisAtt); - //logicAir1RU->SetVisAttributes(Air1VisAtt); - - fuelA1VisATT = new G4VisAttributes(G4Colour(0.0, 0.0 ,1.0)); - fuelA1VisATT->SetForceSolid(false); - fuelA1VisATT->SetVisibility(true); - logicRodA1->SetVisAttributes(fuelA1VisATT); - logicRodA1Cut2->SetVisAttributes(fuelA1VisATT); - logicRodA1Mod->SetVisAttributes(fuelA1VisATT); - logicRodA1Cut1->SetVisAttributes(fuelA1VisATT); - - fuelB1VisATT = new G4VisAttributes(G4Colour(0,0.5,0.92)); - fuelB1VisATT->SetForceSolid(false); - fuelB1VisATT->SetVisibility(true); - logicRodB1->SetVisAttributes(fuelB1VisATT); - logicRodB1Cut2->SetVisAttributes(fuelB1VisATT); - logicRodB1Mod->SetVisAttributes(fuelB1VisATT); - logicRodB1Cut1->SetVisAttributes(fuelB1VisATT); - - sheathA1VisATT = new G4VisAttributes(G4Colour(0.5, 0.0 ,1.0)); - sheathA1VisATT->SetForceSolid(false); - sheathA1VisATT->SetVisibility(false); - logicSheathA1->SetVisAttributes(sheathA1VisATT); - logicSheathA1Cut2->SetVisAttributes(sheathA1VisATT); - logicSheathA1Mod->SetVisAttributes(sheathA1VisATT); - logicSheathA1Cut1->SetVisAttributes(sheathA1VisATT); - - sheathB1VisATT = new G4VisAttributes(G4Colour(1.0, 0.5 ,1.0)); - sheathB1VisATT->SetForceSolid(false); - sheathB1VisATT->SetVisibility(false); - logicSheathB1->SetVisAttributes(sheathB1VisATT); - logicSheathB1Cut2->SetVisAttributes(sheathB1VisATT); - logicSheathB1Mod->SetVisAttributes(sheathB1VisATT); - logicSheathB1Cut1->SetVisAttributes(sheathB1VisATT); - - - EndPlate2VisATT = new G4VisAttributes(G4Colour(0.5, 0.5, 0.5)); - EndPlate2VisATT->SetForceSolid(false); - EndPlate2VisATT->SetVisibility(true); - logicEndPlate2->SetVisAttributes(EndPlate2VisATT); - logicEndPlate1->SetVisAttributes(EndPlate2VisATT); - logicEndPlate2Cut2->SetVisAttributes(EndPlate2VisATT); - logicEndPlate2Mod->SetVisAttributes(EndPlate2VisATT); - logicEndPlate1Mod->SetVisAttributes(EndPlate2VisATT); - logicEndPlate2Cut1->SetVisAttributes(EndPlate2VisATT); - - return worldPhysical; -} - - -// ConstructMaterials() -// Construct all the materials needed for the Q_ZED2Constructor. -void Q_ZED2Constructor::ConstructMaterials() -{ - // Elements, isotopes and materials - G4Isotope *U234, *U235, *U238, *U236, *D2, *O16, *O17, - *Fe54, *Fe56, *Fe57, *Fe58, *Cr50, *Cr52, *Cr53, *Cr54, - *Si28, *Si29, *Si30, *Cu63, *Cu65, *Mn55, *Mg24, - *Mg25, *Mg26, *Zn64, *Zn66, *Zn67, *Zn68, *Zn70, - *Al27, *Ti46, *Ti47, *Ti48, *Ti49, *Ti50, *Na23, - *Ga69, *Ga71, *H1, *C12, *C13, *Zr90, *Zr91, - *Zr92, *Zr94, *Zr96, *Sn112, *Sn114, *Sn115, *Sn116, - *Sn117, *Sn118, *Sn119, *Sn120, *Sn122, *Sn124, - *Ca40, *Ca42, *Ca43, *Ca44, *Ca46, *Ca48, *B10, *B11, - *Li6, *Li7, *Gd152,*Gd154, *Gd155, *Gd156, *Gd157, - *Gd158, *Gd160,*V50, *V51; - G4Element *Oxygen, *Deuterium, *LEU, - *Cr, *Fe, *Si, *Cu, *Mn, *Mg, *Zn, *Al, - *Ti, *Na, *Ga, *Hydrogen, *C, *Zr, *Sn, *Ca, - *B, *Li, *Gd, *V, - *FeAl, *CuAl,*FeZr, *CrZr, *OxygenZr, - *OxygenLEU, *OxygenLW; - G4Material *World, *LEUMat, - *Aluminum57S, *AlPresT, *AlCalT, *H2O, *D2O, - *AnnulusGas, *Zr4, *Air, *Moderator, *Graphite; - - // Create the world environment - World = new G4Material("Galactic", 1, 1, 1.e-25*g/cm3, kStateGas,2.73*kelvin, 3.e-18*pascal); - - - //make Calcium isotopes and element - Ca40 = new G4Isotope("Ca40", 20, 40, 39.9625906*g/mole); - Ca42 = new G4Isotope("Ca42", 20, 42, 41.9586176*g/mole); - Ca43 = new G4Isotope("Ca43", 20, 43, 42.9587662*g/mole); - Ca44 = new G4Isotope("Ca44", 20, 44, 43.9554806*g/mole); - Ca46 = new G4Isotope("Ca46", 20, 46, 45.953689*g/mole); - Ca48 = new G4Isotope("Ca48", 20, 48, 47.952533*g/mole); - - Ca = new G4Element("Calcium", "Ca", 6); - Ca->AddIsotope(Ca40, 96.941*perCent); - Ca->AddIsotope(Ca42, 0.647*perCent); - Ca->AddIsotope(Ca43, 0.135*perCent); - Ca->AddIsotope(Ca44, 2.086*perCent); - Ca->AddIsotope(Ca46, 0.004*perCent); - Ca->AddIsotope(Ca48, 0.187*perCent); - - //make Boron isotopes and element - B10 = new G4Isotope("B10", 5, 10, 10.012937*g/mole); - B11 = new G4Isotope("B11", 5, 11, 11.009305*g/mole); - - B = new G4Element("Boron", "B", 2); - B->AddIsotope(B10, 19.9*perCent); - B->AddIsotope(B11, 80.1*perCent); - - //make Lithium isotopes and element - Li6 = new G4Isotope("Li6", 3, 6, 6.0151223*g/mole); - Li7 = new G4Isotope("Li7", 3, 7, 7.0160040*g/mole); - - Li = new G4Element("Lithium", "Li", 2); - Li->AddIsotope(Li6, 7.59 *perCent); - Li->AddIsotope(Li7, 92.41*perCent); - - //make Vanadium isotopes and element - V50 = new G4Isotope("V50", 23, 50, 49.9471609 *g/mole); - V51 = new G4Isotope("V51", 23, 51, 50.9439617 *g/mole); - - V = new G4Element("Vanadium", "V", 2); - V->AddIsotope(V50, 0.250 *perCent); - V->AddIsotope(V51, 99.750*perCent); - - - - - //make chromium isotopes and element - Cr50 = new G4Isotope("Cr50", 24, 50, 49.9460422*g/mole); - Cr52 = new G4Isotope("Cr52", 24, 52, 51.9405075*g/mole); - Cr53 = new G4Isotope("Cr53", 24, 53, 52.9406494*g/mole); - Cr54 = new G4Isotope("Cr54", 24, 54, 53.9388804*g/mole); - - Cr = new G4Element("Chromium", "Cr", 4); - Cr->AddIsotope(Cr50, 4.1737*perCent); - Cr->AddIsotope(Cr52, 83.7003*perCent); - Cr->AddIsotope(Cr53, 9.6726*perCent); - Cr->AddIsotope(Cr54, 2.4534*perCent); - - CrZr = new G4Element("Chromium", "Cr", 4); - CrZr->AddIsotope(Cr50, 4.10399884*perCent); - CrZr->AddIsotope(Cr52, 82.20818453*perCent); - CrZr->AddIsotope(Cr53, 9.50012786*perCent); - CrZr->AddIsotope(Cr54, 4.18768878*perCent); - - - //make iron isotopes and element - Fe54 = new G4Isotope("Fe54", 26, 54, 53.9396105*g/mole); - Fe56 = new G4Isotope("Fe56", 26, 56, 55.9349375*g/mole); - Fe57 = new G4Isotope("Fe57", 26, 57, 56.9353940*g/mole); - Fe58 = new G4Isotope("Fe58", 26, 58, 57.9332756*g/mole); - - Fe = new G4Element("Iron", "Fe", 4); - Fe->AddIsotope(Fe54, 5.80*perCent); - Fe->AddIsotope(Fe56, 91.72*perCent); - Fe->AddIsotope(Fe57, 2.20*perCent); - Fe->AddIsotope(Fe58, 0.28*perCent); - - //make iron element for Aluminium material in ZED-2 - FeAl = new G4Element("Iron", "Fe", 4); - FeAl->AddIsotope(Fe54, 0.02340*perCent); - FeAl->AddIsotope(Fe56, 0.36700*perCent); - FeAl->AddIsotope(Fe57, 0.00848*perCent); - FeAl->AddIsotope(Fe58, 0.00112*perCent); - - //make iron element for Aluminium material in ZED-2 - FeZr = new G4Element("Iron", "Fe", 4); - FeZr->AddIsotope(Fe54, 5.60198907*perCent); - FeZr->AddIsotope(Fe56, 91.9458541*perCent); - FeZr->AddIsotope(Fe57, 2.14094671*perCent); - FeZr->AddIsotope(Fe58, 0.31121012*perCent); - - //make Silicon isotopes and element - Si28 = new G4Isotope("Si28", 14, 28, 27.9769271*g/mole); - Si29 = new G4Isotope("Si29", 14, 29, 28.9764949*g/mole); - Si30 = new G4Isotope("Si30", 14, 30, 29.9737707*g/mole); - - Si = new G4Element("Silicon", "Si", 3); - Si->AddIsotope(Si28, 92.23*perCent); - Si->AddIsotope(Si29, 4.67*perCent); - Si->AddIsotope(Si30, 3.1*perCent); - - //make Magnesium isotopes and element - Mg24 = new G4Isotope("Mg24", 12, 24, 23.9850423*g/mole); - Mg25 = new G4Isotope("Mg25", 12, 25, 24.9858374*g/mole); - Mg26 = new G4Isotope("Mg26", 12, 26, 25.9825937 *g/mole); - - Mg = new G4Element("Magnesium", "Mg", 3); - Mg->AddIsotope(Mg24, 78.99*perCent); - Mg->AddIsotope(Mg25, 10.00*perCent); - Mg->AddIsotope(Mg26, 11.01*perCent); - - //make Manganese isotopes and element - Mn55 = new G4Isotope("Mn55", 25, 55, 54.9380471*g/mole); - - Mn = new G4Element("Manganese", "Mn", 1); - Mn->AddIsotope(Mn55, 100.00*perCent); - - //make Copper isotopes and element - Cu63 = new G4Isotope("Cu63", 29, 63, 62.9295989*g/mole); - Cu65 = new G4Isotope("Cu65", 29, 65, 64.9277929 *g/mole); - - Cu = new G4Element("Copper", "Cu", 2); - Cu->AddIsotope(Cu63, 69.17*perCent); - Cu->AddIsotope(Cu65, 30.83*perCent); - - //make copper for Al - CuAl = new G4Element("Copper", "Cu", 2); - CuAl->AddIsotope(Cu63, 0.01383*perCent); - CuAl->AddIsotope(Cu65, 0.00617*perCent); - - //make Aluminum isotopes and element - Al27 = new G4Isotope("Al27", 13, 27, 26.9815386 *g/mole); - - Al = new G4Element("Aluminum", "Al", 1); - Al->AddIsotope(Al27, 100.00*perCent); - - //make Zirconium isotopes and element - Zr90 = new G4Isotope("Zr90", 40, 90, 89.9047026*g/mole); - Zr91 = new G4Isotope("Zr91", 40, 91, 90.9056439*g/mole); - Zr92 = new G4Isotope("Zr92", 40, 92, 91.9050386*g/mole); - Zr94 = new G4Isotope("Zr94", 40, 94, 93.9063148*g/mole); - Zr96 = new G4Isotope("Zr96", 40, 96, 95.908275*g/mole); - - - - Zr = new G4Element("Zirconium", "Zr", 5); - Zr->AddIsotope(Zr90, 0.5075558873*perCent); //ATM% - Zr->AddIsotope(Zr91, 0.1116101232*perCent); - Zr->AddIsotope(Zr92, 0.1722780975*perCent); - Zr->AddIsotope(Zr94, 0.1791179604*perCent); - Zr->AddIsotope(Zr96, 0.0294379317*perCent); - - - //make Zinc isotopes and element - Zn64 = new G4Isotope("Zn64", 30, 64, 63.9291448*g/mole); - Zn66 = new G4Isotope("Zn66", 30, 66, 65.9260347*g/mole); - Zn67 = new G4Isotope("Zn67", 30, 67, 66.9271291*g/mole); - Zn68 = new G4Isotope("Zn68", 30, 68, 67.9248459*g/mole); - Zn70 = new G4Isotope("Zn70", 30, 70, 69.925325*g/mole); - - Zn = new G4Element("Zinc", "Zn", 5); - Zn->AddIsotope(Zn64, 48.63*perCent); - Zn->AddIsotope(Zn66, 27.90*perCent); - Zn->AddIsotope(Zn67, 4.10*perCent); - Zn->AddIsotope(Zn68, 18.75*perCent); - Zn->AddIsotope(Zn70, 0.62*perCent); - - //make Tin isotopes and element - Sn112 = new G4Isotope("Sn112", 50, 112, 111.904826*g/mole); - Sn114 = new G4Isotope("Sn114", 50, 114, 113.902784*g/mole); - Sn115 = new G4Isotope("Sn115", 50, 115, 114.903348*g/mole); - Sn116 = new G4Isotope("Sn116", 50, 116, 115.901747*g/mole); - Sn117 = new G4Isotope("Sn117", 50, 117, 116.902956*g/mole); - Sn118 = new G4Isotope("Sn118", 50, 118, 117.901609*g/mole); - Sn119 = new G4Isotope("Sn119", 50, 119, 118.903311*g/mole); - Sn120 = new G4Isotope("Sn120", 50, 120, 119.9021991*g/mole); - Sn122 = new G4Isotope("Sn122", 50, 122, 121.9034404*g/mole); - Sn124 = new G4Isotope("Sn124", 50, 124, 123.9052743*g/mole); - - Sn = new G4Element("Tin", "Sn", 10); - Sn->AddIsotope(Sn112, 0.97*perCent); - Sn->AddIsotope(Sn114, 0.66*perCent); - Sn->AddIsotope(Sn115, 0.34*perCent); - Sn->AddIsotope(Sn116, 14.54*perCent); - Sn->AddIsotope(Sn117, 7.68*perCent); - Sn->AddIsotope(Sn118, 24.22*perCent); - Sn->AddIsotope(Sn119, 8.59*perCent); - Sn->AddIsotope(Sn120, 32.58*perCent); - Sn->AddIsotope(Sn122, 4.63*perCent); - Sn->AddIsotope(Sn124, 0.0*perCent); - - // Soudium Isotopes - Na23 = new G4Isotope("Na23", 11, 23, 22.9897677*g/mole); - - // Naturally occuring Soudiium - Na = new G4Element("Soudium", "Na", 1); - Na->AddIsotope(Na23, 1.); - - // Gallium Isotopes - Ga69 = new G4Isotope("Ga69", 31, 69, 68.9255809*g/mole); - Ga71 = new G4Isotope("Ga71", 31, 71, 70.9247005*g/mole); - - // Naturally Occuring Gallium - Ga = new G4Element("Gallium", "Ga", 2); - Ga->AddIsotope(Ga69, 60.108*perCent); - Ga->AddIsotope(Ga71, 39.892*perCent); - - - //make Gadolinium isotopes and element - Gd152 = new G4Isotope("Gd152", 64, 152, 151.919786*g/mole); - Gd154 = new G4Isotope("Gd154", 64, 154, 153.920861*g/mole); - Gd155 = new G4Isotope("Gd155", 64, 155, 154.922618*g/mole); - Gd156 = new G4Isotope("Gd156", 64, 156, 155.922118*g/mole); - Gd157 = new G4Isotope("Gd157", 64, 157, 156.923956*g/mole); - Gd158 = new G4Isotope("Gd158", 64, 158, 157.924019*g/mole); - Gd160 = new G4Isotope("Gd160", 64, 160, 159.927049*g/mole); - - - Gd = new G4Element("Gadolinium", "Gd", 7); - Gd->AddIsotope(Gd152, 0.20*perCent); - Gd->AddIsotope(Gd154, 2.18*perCent); - Gd->AddIsotope(Gd155, 14.80*perCent); - Gd->AddIsotope(Gd156, 20.47*perCent); - Gd->AddIsotope(Gd157, 15.65*perCent); - Gd->AddIsotope(Gd158, 24.84*perCent); - Gd->AddIsotope(Gd160, 21.86*perCent); - - - //make titanium isotopes and element - Ti46 = new G4Isotope("Ti46", 22, 46, 45.9526294*g/mole); - Ti47 = new G4Isotope("Ti47", 22, 47, 46.9517640*g/mole); - Ti48 = new G4Isotope("Ti48", 22, 48, 47.9479473*g/mole); - Ti49 = new G4Isotope("Ti49", 22, 49, 48.9478711*g/mole); - Ti50 = new G4Isotope("Ti50", 22, 50, 49.9447921*g/mole); - - Ti = new G4Element("Titanium", "Zn", 5); - Ti->AddIsotope(Ti46, 8.25*perCent); - Ti->AddIsotope(Ti47, 7.44*perCent); - Ti->AddIsotope(Ti48, 73.72*perCent); - Ti->AddIsotope(Ti49, 5.41*perCent); - Ti->AddIsotope(Ti50, 5.18*perCent); - - //make Carbon isotopes and element - C12 = new G4Isotope("C12", 6, 12, 12.0*g/mole); - C13 = new G4Isotope("C13", 6, 13, 13.00335*g/mole); - - C = new G4Element("Carbon", "C", 2); - C->AddIsotope(C12, 98.83*perCent); - C->AddIsotope(C13, 1.07*perCent); - - - // Make the uranium isotopes and element - U234 = new G4Isotope("U234", 92, 234, 234.0410*g/mole); - U235 = new G4Isotope("U235", 92, 235, 235.0439*g/mole); - U236 = new G4Isotope("U236", 92, 236, 236.0456*g/mole); - U238 = new G4Isotope("U238", 92, 238, 238.0508*g/mole); - - - - // Make hydrogen isotopes and elements - H1 = new G4Isotope("H1", 1, 1, 1.0078*g/mole); - Hydrogen = new G4Element("Hydrogen", "H", 1); - Hydrogen->AddIsotope(H1, 100*perCent); - - - D2 = new G4Isotope("D2", 1, 2, 2.014*g/mole); - Deuterium = new G4Element("Deuterium", "D", 1); - Deuterium->AddIsotope(D2, 100*perCent); - - // Make Oxygen isotopes and elements - O16 = new G4Isotope("O16", 8, 16, 15.9949146*g/mole); - O17 = new G4Isotope("O17", 8, 17, 16.9991312*g/mole); - // O18 = new G4Isotope("O18", 8, 18, 17.9991603*g/mole); - Oxygen = new G4Element("Oxygen", "O", 2); - Oxygen->AddIsotope(O16, 99.963868927*perCent); - Oxygen->AddIsotope(O17, 0.036131072*perCent); - - OxygenZr = new G4Element("Oxygen", "O", 1); - OxygenZr->AddIsotope(O16, 0.688463*perCent); - - OxygenLEU = new G4Element("Oxygen", "O", 1); - OxygenLEU->AddIsotope(O16, 100.0*perCent); - - // Making Oxygen for the heavy water - /*OxygenMod = new G4Element("OxygenMod", "OM", 2); - OxygenMod->AddIsotope(O16, 33.313111651*perCent); - OxygenMod->AddIsotope(O17, 0.020000116*perCent);*/ - - // Making Oxygen for the light water - OxygenLW = new G4Element("OxygenLW", "OLW", 2); - OxygenLW->AddIsotope(O16, 99.995998592*perCent);; - OxygenLW->AddIsotope(O17, 0.004001407*perCent); - - - // Making hydrogen for the lightwater - Hydrogen = new G4Element("HydrogenLW", "HLW", 1); - Hydrogen->AddIsotope(H1, 100*perCent); - - - LEU = new G4Element("Low Enriched Uranium","LEU",4); - LEU->AddIsotope(U234, 0.007432*perCent); - LEU->AddIsotope(U235, 0.9583*perCent); - LEU->AddIsotope(U236, 0.000239*perCent); - LEU->AddIsotope(U238, 99.0341*perCent); - - - // Make the LEU material - LEUMat = new G4Material("U235 Material", 10.52*g/cm3, 2,kStateSolid, 299.51*kelvin); - LEUMat->AddElement(LEU,88.146875681*perCent); - LEUMat->AddElement(OxygenLEU,11.853119788*perCent); - - - - // Create H20 material - H2O = new G4Material("Light Water", 0.99745642056*g/cm3, 2, kStateLiquid); - H2O->AddElement(OxygenLW, 1); - H2O->AddElement(Hydrogen, 2); - - D2O = new G4Material("Heavy Water", 1.10480511492*g/cm3, 2, kStateLiquid); - D2O->AddElement(Oxygen, 1); - D2O->AddElement(Deuterium, 2); - -// Graphite = new G4Material("Graphite", 6., 12.0107*g/mole, 1.64*g/cm3); - Graphite = new G4Material("Graphite", 1.64*g/cm3, 5, kStateSolid); - Graphite->AddElement(Li, 1.7e-5*perCent); - Graphite->AddElement(B, 3.e-5*perCent); - Graphite->AddElement(C, 99.99697797*perCent); - Graphite->AddElement(V, 0.00300031*perCent); - Graphite->AddElement(Gd, 2.e-5*perCent); - - - - // Make Argon - G4Element* Ar = new G4Element("Argon", "Ar", 18., 39.948*g/mole); - // Make Argon - G4Element* N = new G4Element("Nitrogen", "N", 7., 14.01*g/mole); - - - - - //Create Aluminum57S (Reactor Calandria) - Aluminum57S = new G4Material("Aluminuum 57S", 2.7*g/cm3, 8, kStateSolid); - Aluminum57S->AddElement(Al, 96.7*perCent); - Aluminum57S->AddElement(Si, 0.25*perCent); - Aluminum57S->AddElement(Fe, 0.4*perCent); - Aluminum57S->AddElement(Cu, 0.1*perCent); - Aluminum57S->AddElement(Mn, 0.1*perCent); - Aluminum57S->AddElement(Mg, 2.2*perCent); - Aluminum57S->AddElement(Cr, 0.15*perCent); - Aluminum57S->AddElement(Zn, 0.1*perCent); - - //Create AlPresT (pressure Tube) -// AlPresT = new G4Material("Aluminuum 6061", 2.712631*g/cm3, 8, kStateSolid); - AlPresT = new G4Material("Aluminuum 6061", 2.712631*g/cm3, 8, kStateSolid); - - AlPresT->AddElement(Al, 99.1244424*perCent); - AlPresT->AddElement(Si, 0.5922414*perCent); - AlPresT->AddElement(Fe, 0.1211379*perCent); - AlPresT->AddElement(Cu, 0.0018171*perCent); - AlPresT->AddElement(Mn, 0.0383626*perCent); - //AlPresT->AddElement(Mg, 0.7000*perCent); - AlPresT->AddElement(Cr, 0.1211405*perCent); - AlPresT->AddElement(Li, 0.00075712*perCent); - AlPresT->AddElement(B, 0.00010095*perCent); - //AlPresT->AddElement(Zn, 0.0230*perCent); - //AlPresT->AddElement(Na, 0.0090*perCent); - //AlPresT->AddElement(Ga, 0.0120*perCent); - //AlPresT->AddElement(Ti, 0.0110*perCent); - - //Create AlCalT (calandria Tube) -// AlCalT = new G4Material("Aluminuum 6063", 2.684951*g/cm3, 8, kStateSolid); - AlCalT = new G4Material("Aluminuum 6063", 2.684951*g/cm3, 8, kStateSolid); - AlCalT->AddElement(Al, 99.18675267*perCent); - AlCalT->AddElement(Si, 0.509640251*perCent); - AlCalT->AddElement(Fe, 0.241396625*perCent); - AlCalT->AddElement(Li, 0.00754387*perCent); - AlCalT->AddElement(B, 0.000100586*perCent); - //AlCalT->AddElement(Cu, 0.0590*perCent); - AlCalT->AddElement(Mn, 0.041228175*perCent); - //AlCalT->AddElement(Mg, 0.5400*perCent); - //AlCalT->AddElement(Cr, 0.0100*perCent); - //AlCalT->AddElement(Zn, 0.0340*perCent); - //AlCalT->AddElement(Na, 0.0170*perCent); - AlCalT->AddElement(Gd, 0.000010059*perCent); - AlCalT->AddElement(Ti, 0.041228175*perCent); - - - Moderator = new G4Material("Moderator", 1.102597*g/cm3, 2, kStateLiquid, 299.51*kelvin); - Moderator->AddMaterial(D2O, 98.705*perCent); - Moderator->AddMaterial(H2O, 1.295*perCent); - - //Create Annulus Gas - AnnulusGas = new G4Material("AnnulusGas", 0.0012*g/cm3, 2, kStateGas/*, - 448.72*kelvin*/); - AnnulusGas->AddElement(C,27.11*perCent); - AnnulusGas->AddElement(Oxygen,72.89*perCent); - - - Zr4 = new G4Material("Zircaloy-4", 6.55*g/cm3, 4, kStateSolid); - Zr4->AddElement(Oxygen, 0.12*perCent); - Zr4->AddElement(CrZr, 0.11*perCent); - Zr4->AddElement(FeZr, 0.22*perCent); - Zr4->AddElement(Zr, 99.58*perCent); - - // Make Air - Air = new G4Material("Air", 1.29*mg/cm3, 5, kStateGas); - Air->AddElement(N, 74.74095914*perCent); - Air->AddElement(Oxygen, 23.49454694*perCent); - Air->AddElement(Ar, 1.274547311*perCent); - Air->AddElement(Li, 0.474350981*perCent); - Air->AddElement(C, 0.015595629*perCent); - //Air->AddElement(Hydrogen, 0.009895657); - - - - - - // Add materials to the map indexed by either ZA (format ZZAAA or ZZ) - // For composite materials: world is 0, heavy water is 1, UHW is 2 - matMap["World"] = World; - matMap["LEUMat"] = LEUMat; - matMap["Graphite"] = Graphite; - matMap["Al57S"] = Aluminum57S; - matMap["AlPresT"] = AlPresT; - matMap["AlCalT"] = AlCalT; - matMap["Zr4"] = Zr4; - matMap["Air"] = Air; - matMap["Moderator"] = Moderator; - matMap["Coolant"] = H2O; - - - - matChanged = false; - - return; -} - diff --git a/G4STORK/src/SCWRConstructor.cc b/G4STORK/src/SCWRConstructor.cc deleted file mode 100755 index 2dd92e34..00000000 --- a/G4STORK/src/SCWRConstructor.cc +++ /dev/null @@ -1,1090 +0,0 @@ -/* -SCWRConstructor.cc - -Created by: Wesley Ford -Date: 23-05-2012 -Modified: 11-03-2013 - -Source code for the CANDU 6 lattice geometry and materials - -*/ - -#include "SCWRConstructor.hh" - -// Constructor -SCWRConstructor::SCWRConstructor() -: StorkVWorldConstructor(), cellLogical(0), pressTubeLogical1(0), pressTubeLogical2(0), pressTubeLogical3(0), pressTubeLogical4(0), outLinerLogical(0), insulatorLogical1(0), - insulatorLogical2(0), insulatorLogical3(0), insulatorLogical4(0), linerLogical(0), coolantLogical(0), outSheatheLogical(0), inSheatheLogical(0), outFuelLogical1(0), - outFuelLogical2(0), outFuelLogical3(0), outFuelLogical4(0), inFuelLogical1(0), inFuelLogical2(0), inFuelLogical3(0), inFuelLogical4(0), /*outFlowTubeLogical(0), flowTubeLogical1(0), flowTubeLogical2(0), inFlowTubeLogical(0)*/ flowTubeLogical(0), - centralCoolantLogical(0) -{ - // Set default member variables (from file or default values) - - - - // Set up variable property map - /* - variablePropMap[MatPropPair(fuel,temperature)] = &fuelTemp; - variablePropMap[MatPropPair(fuel,density)] = &fuelDensity; - variablePropMap[MatPropPair(coolant,temperature)] = &coolantTemp; - variablePropMap[MatPropPair(coolant,density)] = &coolantDensity; - variablePropMap[MatPropPair(moderator,temperature)] = &moderatorTemp; - variablePropMap[MatPropPair(moderator,density)] = &moderatorDensity; - variablePropMap[MatPropPair(all,dimension)] = &latticePitch; - */ - cellVisAtt=NULL; - pressTubeVisAtt=NULL; - outLinerVisAtt=NULL; - insulatorVisAtt=NULL; - linerVisAtt=NULL; - coolantVisAtt=NULL; - outSheatheVisAtt=NULL; - inSheatheVisAtt=NULL; - outFuelVisAtt=NULL; - inFuelVisAtt=NULL; - flowTubeVisAtt=NULL; - centralCoolantVisAtt=NULL; - - // Stored variables from infile - latticePitch= 25.*cm; - - moderatorTemp=342.8200*kelvin; - moderatorDensity=1.0851*g/cm3; - - pressTubeTemp[0]=459.8850*kelvin; - pressTubeTemp[1]=441.8700*kelvin; - pressTubeTemp[2]=424.2300*kelvin; - pressTubeTemp[3]=406.9300*kelvin; - - pressTubeDensity=6.52*g/cm3; - - outLinerTemp=470.5200*kelvin; - outLinerDensity=6.52*g/cm3; - - insulatorTemp[0]=643.2050*kelvin; - insulatorTemp[1]=592.4750*kelvin; - insulatorTemp[2]=543.2950*kelvin; - insulatorTemp[3]=495.5700*kelvin; - insulatorDensity=5.83*g/cm3; - - linerTemp=670.2600*kelvin; - linerDensity=7.9*g/cm3; - - coolantTemp=680.62*kelvin; - //coolantDensity=0.1512*g/cm3; - coolantDensity=0.001*g/cm3; - - inSheatheTemp=768.8200*kelvin; - inSheatheDensity=7.9*g/cm3; - - outSheatheTemp=780.9300*kelvin; - outSheatheDensity=7.9*g/cm3; - - innerFuelTemp[0]=1389.8000*kelvin; - innerFuelTemp[1]=1288.6600*kelvin; - innerFuelTemp[2]=1118.6700*kelvin; - innerFuelTemp[3]=899.625*kelvin; - innerFuelDensity=9.91*g/cm3; - - outerFuelTemp[0]=1625.0500*kelvin; - outerFuelTemp[1]=1480.2500*kelvin; - outerFuelTemp[2]=1241.7850*kelvin; - outerFuelTemp[3]=945.8700*kelvin; - outerFuelDensity=9.87*g/cm3; - - flowTubeTemp=659.1800*kelvin; - flowTubeDensity=7.9*g/cm3; - - centralCoolantTemp=629.0100*kelvin; - //centralCoolantDensity=0.6059*g/cm3; - centralCoolantDensity=0.001*g/cm3; -} - - -// Desturctor -SCWRConstructor::~SCWRConstructor() -{ - // Delete visualization attributes - if(cellVisAtt) - delete cellVisAtt; - if(pressTubeVisAtt) - delete pressTubeVisAtt; - if(outLinerVisAtt) - delete outLinerVisAtt; - if(insulatorVisAtt) - delete insulatorVisAtt; - if(linerVisAtt) - delete linerVisAtt; - if(coolantVisAtt) - delete coolantVisAtt; - if(outSheatheVisAtt) - delete outSheatheVisAtt; - if(inSheatheVisAtt) - delete inSheatheVisAtt; - if(outFuelVisAtt) - delete outFuelVisAtt; - if(inFuelVisAtt) - delete inFuelVisAtt; - //if(outFlowTubeVisAtt) -// delete outFlowTubeVisAtt; - if(flowTubeVisAtt) - delete flowTubeVisAtt; - //if(inFlowTubeVisAtt) -// delete inFlowTubeVisAtt; - if(centralCoolantVisAtt) - delete centralCoolantVisAtt; -} - - -// ConstructWorld() -// Construct the geometry and materials of the CANDU 6 lattice cell. -G4VPhysicalVolume* SCWRConstructor::ConstructWorld() -{ - // Lattic cell dimensions - G4double buffer = 1.0*cm; - reactorDim = G4ThreeVector(latticePitch/2.0,latticePitch/2.0,latticePitch/2.0); - - encWorldDim = 2.0 * G4ThreeVector(reactorDim[0]+buffer,reactorDim[1]+buffer, - reactorDim[2]+buffer); - - G4SolidStore* theSolids = G4SolidStore::GetInstance(); - - - // Set static dimensions - - // Pressure Tube dimensions - G4double pressTube1Radmax = 8.15*cm; - G4double pressTube2Radmax = 8.45*cm; - G4double pressTube3Radmax = 8.75*cm; - G4double pressTube4Radmax = 9.05*cm; - G4double pressTubeLen = reactorDim[2]; - - // outer liner dimensions - G4double outLinerRadmax = 7.85*cm; - G4double outLinerLen = reactorDim[2]; - - // insulator dimensions - G4double insulator1Radmax = 7.388*cm; - G4double insulator2Radmax = 7.525*cm; - G4double insulator3Radmax = 7.663*cm; - G4double insulator4Radmax = 7.8*cm; - G4double insulatorLen = reactorDim[2]; - - // liner dimensions - G4double linerRadmax = 7.25*cm; - G4double linerLen = reactorDim[2]; - - // coolant dimensions - G4double coolantRadmax = 7.2*cm; - G4double coolantLen = reactorDim[2]; - - // outer sheathe dimensions - G4double outSheatheRadmax = 0.5*cm; - G4double outSheatheLen = reactorDim[2]; - - // inner sheathe dimensions - G4double inSheatheRadmax = 0.475*cm; - G4double inSheatheLen = reactorDim[2]; - - G4double ringRad[2] = {6.575*cm,5.4*cm}; - //G4double secondRingOffset = 0.*radian; - - // outer fuel dimensions - G4double outFuel1Radmax = 0.11*cm; - G4double outFuel2Radmax = 0.22*cm; - G4double outFuel3Radmax = 0.33*cm; - G4double outFuel4Radmax = 0.44*cm; - G4double outFuelLen = reactorDim[2]; - - // inner fuel dimensions - G4double inFuel1Radmax = 0.104*cm; - G4double inFuel2Radmax = 0.208*cm; - G4double inFuel3Radmax = 0.311*cm; - G4double inFuel4Radmax = 0.415*cm; - G4double inFuelLen = reactorDim[2]; - -// // outer fuel dimensions -// G4double outFlowTubeRadmax = 4.7*cm; -// G4double outFlowTubeLen = reactorDim[2]; - - // Pressure Tube dimensions -// G4double flowTube1Radmax = 4.65*cm; -// G4double flowTube2Radmax = 4.7*cm; - G4double flowTubeRadmax = 4.7*cm; - G4double flowTubeLen = reactorDim[2]; - -// // inner fuel dimensions -// G4double inFlowTubeRadmax = 3.65*cm; -// G4double inFlowTubeLen = reactorDim[2]; - - // central coolant dimensions - G4double centralCoolantRadmax = 4.6*cm; - G4double centralCoolantLen = reactorDim[2]; - - // Set up the materials (if necessary) - if(matChanged) - { - // Delete any existing materials - DestroyMaterials(); - // Create the materials - ConstructMaterials(); - } - - // Clean up volumes - G4GeometryManager::GetInstance()->OpenGeometry(); - G4PhysicalVolumeStore::GetInstance()->Clean(); - G4LogicalVolumeStore::GetInstance()->Clean(); - - // Set up the solids if necessary - if(geomChanged) - { - // Clean up solids - G4SolidStore::GetInstance()->Clean(); - - // Create world solid - new G4Box("worldBox", reactorDim[0]+buffer, reactorDim[1]+buffer, - reactorDim[2]+buffer); - // Create the lattice cell solid - new G4Box("cellBox", reactorDim[0], reactorDim[1], reactorDim[2]); - - // Create pressure tube - new G4Tubs("pressTube1", 0., pressTube1Radmax, pressTubeLen, 0., - 2.0*CLHEP::pi); - - new G4Tubs("pressTube2", 0., pressTube2Radmax, pressTubeLen, 0., - 2.0*CLHEP::pi); - - new G4Tubs("pressTube3", 0., pressTube3Radmax, pressTubeLen, 0., - 2.0*CLHEP::pi); - - new G4Tubs("pressTube4", 0., pressTube4Radmax, pressTubeLen, 0., - 2.0*CLHEP::pi); - - // Create outer liner tube - new G4Tubs("outLinerTube", 0., outLinerRadmax, outLinerLen, 0., 2.0*CLHEP::pi); - // Create insulator - - new G4Tubs("insulatorTube1", 0., insulator1Radmax, insulatorLen, 0., - 2.0*CLHEP::pi); - - new G4Tubs("insulatorTube2", 0., insulator2Radmax, insulatorLen, 0., - 2.0*CLHEP::pi); - - new G4Tubs("insulatorTube3", 0., insulator3Radmax, insulatorLen, 0., - 2.0*CLHEP::pi); - - new G4Tubs("insulatorTube4", 0., insulator4Radmax, insulatorLen, 0., - 2.0*CLHEP::pi); - - // Create liner tube - new G4Tubs("linerTube", 0., linerRadmax, linerLen, 0., - 2.0*CLHEP::pi); - // Create coolant solid - new G4Tubs("coolantTube", 0., coolantRadmax, coolantLen, 0., - 2.0*CLHEP::pi); - // Create the sheathe for fuel pins - new G4Tubs("outSheatheTube", 0., outSheatheRadmax, outSheatheLen, 0., - 2.0*CLHEP::pi); - // Create the sheathe for fuel pins - new G4Tubs("inSheatheTube", 0., inSheatheRadmax, inSheatheLen, 0., - 2.0*CLHEP::pi); - - // Create outer fuel pins - new G4Tubs("outFuelCyl1", 0., outFuel1Radmax, outFuelLen, 0.,2.0*CLHEP::pi); - - new G4Tubs("outFuelCyl2", 0., outFuel2Radmax, outFuelLen, 0.,2.0*CLHEP::pi); - - new G4Tubs("outFuelCyl3", 0., outFuel3Radmax, outFuelLen, 0.,2.0*CLHEP::pi); - - new G4Tubs("outFuelCyl4", 0., outFuel4Radmax, outFuelLen, 0.,2.0*CLHEP::pi); - - // Create inner fuel pins - new G4Tubs("inFuelCyl1", 0., inFuel1Radmax, inFuelLen, 0., 2.0*CLHEP::pi); - - new G4Tubs("inFuelCyl2", 0., inFuel2Radmax, inFuelLen, 0., 2.0*CLHEP::pi); - - new G4Tubs("inFuelCyl3", 0., inFuel3Radmax, inFuelLen, 0., 2.0*CLHEP::pi); - - new G4Tubs("inFuelCyl4", 0., inFuel4Radmax, inFuelLen, 0., 2.0*CLHEP::pi); - - -// // Create outter flow tube -// new G4Tubs("outFlowTube", 0., outFlowTubeRadmax, outFlowTubeLen, 0., -// 2.0*CLHEP::pi); - - // Create flow tube -// new G4Tubs("flowTube1", 0., flowTube1Radmax, flowTubeLen, 0., -// 2.0*CLHEP::pi); -// -// new G4Tubs("flowTube2", 0., flowTube2Radmax, flowTubeLen, 0., -// 2.0*CLHEP::pi); - - new G4Tubs("flowTube", 0., flowTubeRadmax, flowTubeLen, 0., - 2.0*CLHEP::pi); - -// // Create inner flow tube -// new G4Tubs("inFlowTube", 0., inFlowTubeRadmax, inFlowTubeLen, 0., -// 2.0*CLHEP::pi); - // Create the central coolant - new G4Tubs("centralCoolantCyl", 0., centralCoolantRadmax, centralCoolantLen, 0., - 2.0*CLHEP::pi); - - geomChanged = false; - } - - // Create world volume - worldLogical = new G4LogicalVolume(theSolids->GetSolid("worldBox"), - matMap["Galactic"],"worldLogical",0,0,0); - - worldPhysical = new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), worldLogical, - "worldPhysical",0,0,0); - - // Create the lattice cell (moderator) volume - cellLogical = new G4LogicalVolume(theSolids->GetSolid("cellBox"), - matMap["Moderator"],"cellLogical",0,0,0); - - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), cellLogical,"cellPhysical", - worldLogical,0,0); - - // Create the Pressure Tube - pressTubeLogical1 = new G4LogicalVolume(theSolids->GetSolid("pressTube1"), - matMap["PressTube1"], "pressTubeLogical1",0,0,0); - - pressTubeLogical2 = new G4LogicalVolume(theSolids->GetSolid("pressTube2"), - matMap["PressTube2"], "pressTubeLogical2",0,0,0); - - pressTubeLogical3 = new G4LogicalVolume(theSolids->GetSolid("pressTube3"), - matMap["PressTube3"], "pressTubeLogical3",0,0,0); - - pressTubeLogical4 = new G4LogicalVolume(theSolids->GetSolid("pressTube4"), - matMap["PressTube4"], "pressTubeLogical4",0,0,0); - - - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), pressTubeLogical4, - "pressTubePhysical4",cellLogical,0,0); - - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), pressTubeLogical3, - "pressTubePhysical3",pressTubeLogical4,0,0); - - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), pressTubeLogical2, - "pressTubePhysical2",pressTubeLogical3,0,0); - - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), pressTubeLogical1, - "pressTubePhysical1",pressTubeLogical2,0,0); - - // Create the Pressure Tube - outLinerLogical = new G4LogicalVolume(theSolids->GetSolid("outLinerTube"), - matMap["OutLiner"], "outLinerLogical",0,0,0); - - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), outLinerLogical, - "outLinerPhysical",pressTubeLogical1,0,0); - // Create the Pressure Tube - insulatorLogical1 = new G4LogicalVolume(theSolids->GetSolid("insulatorTube1"), - matMap["Insulator1"], "insulatorLogical1",0,0,0); - - insulatorLogical2 = new G4LogicalVolume(theSolids->GetSolid("insulatorTube2"), - matMap["Insulator2"], "insulatorLogical2",0,0,0); - - insulatorLogical3 = new G4LogicalVolume(theSolids->GetSolid("insulatorTube3"), - matMap["Insulator3"], "insulatorLogical3",0,0,0); - - insulatorLogical4 = new G4LogicalVolume(theSolids->GetSolid("insulatorTube4"), - matMap["Insulator4"], "insulatorLogical4",0,0,0); - - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), insulatorLogical4, - "insulatorPhysical4",outLinerLogical,0,0); - - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), insulatorLogical3, - "insulatorPhysical3",insulatorLogical4,0,0); - - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), insulatorLogical2, - "insulatorPhysical2",insulatorLogical3,0,0); - - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), insulatorLogical1, - "insulatorPhysical1",insulatorLogical2,0,0); - - // Create the Pressure Tube - linerLogical = new G4LogicalVolume(theSolids->GetSolid("linerTube"), - matMap["Liner"], "linerLogical",0,0,0); - - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), linerLogical, - "linerPhysical",insulatorLogical1,0,0); - - // Create the Coolant - coolantLogical = new G4LogicalVolume(theSolids->GetSolid("coolantTube"), - matMap["Coolant"], "coolantLogical",0,0,0); - - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), coolantLogical, - "coolantPhysical",linerLogical,0,0); - - // Create the Sheathe - outSheatheLogical = new G4LogicalVolume(theSolids->GetSolid("outSheatheTube"), - matMap["OutSheathe"], "outSheatheLogical",0,0,0); - - inSheatheLogical = new G4LogicalVolume(theSolids->GetSolid("inSheatheTube"), - matMap["InSheathe"], "inSheatheLogical",0,0,0); - - - // Create a fuel - outFuelLogical1 = new G4LogicalVolume(theSolids->GetSolid("outFuelCyl1"), - matMap["OuterFuel1"], "outFuelLogical1",0,0,0); - // Create a fuel - outFuelLogical2 = new G4LogicalVolume(theSolids->GetSolid("outFuelCyl2"), - matMap["OuterFuel2"], "outFuelLogical2",0,0,0); - // Create a fuel - outFuelLogical3 = new G4LogicalVolume(theSolids->GetSolid("outFuelCyl3"), - matMap["OuterFuel3"], "outFuelLogical3",0,0,0); - // Create a fuel - outFuelLogical4 = new G4LogicalVolume(theSolids->GetSolid("outFuelCyl4"), - matMap["OuterFuel4"], "outFuelLogical4",0,0,0); - - - // Create a fuel - inFuelLogical1 = new G4LogicalVolume(theSolids->GetSolid("inFuelCyl1"), - matMap["InnerFuel1"], "inFuelLogical1",0,0,0); - - inFuelLogical2 = new G4LogicalVolume(theSolids->GetSolid("inFuelCyl2"), - matMap["InnerFuel2"], "inFuelLogical2",0,0,0); - - inFuelLogical3 = new G4LogicalVolume(theSolids->GetSolid("inFuelCyl3"), - matMap["InnerFuel3"], "inFuelLogical3",0,0,0); - - inFuelLogical4 = new G4LogicalVolume(theSolids->GetSolid("inFuelCyl4"), - matMap["InnerFuel4"], "inFuelLogical4",0,0,0); - -// // Create the Pressure Tube -// outFlowTubeLogical = new G4LogicalVolume(theSolids->GetSolid("outFlowTube"), -// matMap["OutFlowTube"], "outFlowTubeLogical",0,0,0); -// -// new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), outFlowTubeLogical, -// "outFlowTubePhysical",coolantLogical,0,0); -// -// -// // Create the Pressure Tube -// flowTubeLogical1 = new G4LogicalVolume(theSolids->GetSolid("flowTube1"), -// matMap["FlowTube1"], "flowTubeLogical1",0,0,0); -// -// // Create the Pressure Tube -// flowTubeLogical2 = new G4LogicalVolume(theSolids->GetSolid("flowTube2"), -// matMap["FlowTube2"], "flowTubeLogical2",0,0,0); -// -// new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), flowTubeLogical2, -// "flowTubePhysical2",outFlowTubeLogical,0,0); -// -// new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), flowTubeLogical1, -// "flowTubePhysical1",flowTubeLogical2,0,0); - - flowTubeLogical = new G4LogicalVolume(theSolids->GetSolid("flowTube"), - matMap["FlowTube"], "flowTubeLogical",0,0,0); - - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), flowTubeLogical, - "flowTubePhysical",coolantLogical,0,0); - - -// // Create the Pressure Tube -// inFlowTubeLogical = new G4LogicalVolume(theSolids->GetSolid("inFlowTube"), -// matMap["InFlowTube"], "inFlowTubeLogical",0,0,0); -// -// new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), inFlowTubeLogical, -// "inFlowTubePhysical",flowTubeLogical1,0,0); - - // Create the Pressure Tube - centralCoolantLogical = new G4LogicalVolume(theSolids->GetSolid("centralCoolantCyl"), - matMap["CentralCoolant"], "centralCoolantLogical",0,0,0); - - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), centralCoolantLogical, - "centralCoolantPhysical",flowTubeLogical,0,0); - - - // Create fuel bundle - - // Rotation and translation of the rod and sheathe - std::stringstream volName; - - // Set name for sheathe physical volume - volName << 0; - - // Place pins for outer ring - for( G4int i = 0; i < 32; i++ ) - { - // Reset string stream - volName.str(""); - - volName << i; - - G4ThreeVector Tm(ringRad[0]*cos(2.0*i*CLHEP::pi/32), - ringRad[0]*sin(2.0*i*CLHEP::pi/32), 0.); - - new G4PVPlacement(0, Tm, outSheatheLogical,"outSheathePhysical " + - volName.str(),coolantLogical,0,0); - - } - - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), outFuelLogical4,"outFuelPhysical4", - outSheatheLogical,0,0); - - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), outFuelLogical3,"outFuelPhysical3", - outFuelLogical4,0,0); - - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), outFuelLogical2,"outFuelPhysical2", - outFuelLogical3,0,0); - - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), outFuelLogical1,"outFuelPhysical1", - outFuelLogical2,0,0); - - // Place pins for inner ring - for( G4int i = 0; i < 32; i++ ) - { - // Reset string stream - volName.str(""); - - volName << i; - - G4ThreeVector Tm(ringRad[1]*cos(2.0*i*CLHEP::pi/32), - ringRad[1]*sin(2.0*i*CLHEP::pi/32), 0.); - - new G4PVPlacement(0, Tm, inSheatheLogical,"inSheathePhysical " + - volName.str(),coolantLogical,0,0); - - } - - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), inFuelLogical4,"inFuelPhysical4", - inSheatheLogical,0,0); - - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), inFuelLogical3,"inFuelPhysical3", - inFuelLogical4,0,0); - - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), inFuelLogical2,"inFuelPhysical2", - inFuelLogical3,0,0); - - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), inFuelLogical1,"inFuelPhysical1", - inFuelLogical2,0,0); - - // Add sensitive detector to ALL logical volumes - worldLogical->SetSensitiveDetector( sDReactor ); - cellLogical->SetSensitiveDetector( sDReactor ); - pressTubeLogical1->SetSensitiveDetector( sDReactor ); - pressTubeLogical2->SetSensitiveDetector( sDReactor ); - pressTubeLogical3->SetSensitiveDetector( sDReactor ); - pressTubeLogical4->SetSensitiveDetector( sDReactor ); - outLinerLogical->SetSensitiveDetector( sDReactor ); - insulatorLogical1->SetSensitiveDetector( sDReactor ); - insulatorLogical2->SetSensitiveDetector( sDReactor ); - insulatorLogical3->SetSensitiveDetector( sDReactor ); - insulatorLogical4->SetSensitiveDetector( sDReactor ); - linerLogical->SetSensitiveDetector( sDReactor ); - coolantLogical->SetSensitiveDetector( sDReactor ); - outSheatheLogical->SetSensitiveDetector( sDReactor ); - inSheatheLogical->SetSensitiveDetector( sDReactor ); - outFuelLogical1->SetSensitiveDetector( sDReactor ); - outFuelLogical2->SetSensitiveDetector( sDReactor ); - outFuelLogical3->SetSensitiveDetector( sDReactor ); - outFuelLogical4->SetSensitiveDetector( sDReactor ); - inFuelLogical1->SetSensitiveDetector( sDReactor ); - inFuelLogical2->SetSensitiveDetector( sDReactor ); - inFuelLogical3->SetSensitiveDetector( sDReactor ); - inFuelLogical4->SetSensitiveDetector( sDReactor ); -// outFlowTubeLogical->SetSensitiveDetector( sDReactor ); -// flowTubeLogical1->SetSensitiveDetector( sDReactor ); -// flowTubeLogical2->SetSensitiveDetector( sDReactor ); - flowTubeLogical->SetSensitiveDetector( sDReactor ); -// inFlowTubeLogical->SetSensitiveDetector( sDReactor ); - centralCoolantLogical->SetSensitiveDetector( sDReactor ); - - - // Set visualization attributes - - if(worldVisAtt) - delete worldVisAtt; - if(cellVisAtt) - delete cellVisAtt; - if(pressTubeVisAtt) - delete pressTubeVisAtt; - if(outLinerVisAtt) - delete outLinerVisAtt; - if(insulatorVisAtt) - delete insulatorVisAtt; - if(linerVisAtt) - delete linerVisAtt; - if(coolantVisAtt) - delete coolantVisAtt; - if(outSheatheVisAtt) - delete outSheatheVisAtt; - if(inSheatheVisAtt) - delete inSheatheVisAtt; - if(outFuelVisAtt) - delete outFuelVisAtt; - if(inFuelVisAtt) - delete inFuelVisAtt; - //if(outFlowTubeVisAtt) -// delete outFlowTubeVisAtt; - if(flowTubeVisAtt) - delete flowTubeVisAtt; - //if(inFlowTubeVisAtt) -// delete inFlowTubeVisAtt; - if(centralCoolantVisAtt) - delete centralCoolantVisAtt; - - worldVisAtt = new G4VisAttributes(G4Colour(1.,1.,1.)); - worldVisAtt->SetVisibility(false); - worldLogical->SetVisAttributes(worldVisAtt); - - cellVisAtt = new G4VisAttributes(G4Colour(0,0,1)); - cellVisAtt->SetVisibility(1); - cellLogical->SetVisAttributes(cellVisAtt); - - pressTubeVisAtt = new G4VisAttributes(G4Colour(1,0,0)); - pressTubeVisAtt->SetVisibility(1); - pressTubeLogical1->SetVisAttributes(pressTubeVisAtt); - pressTubeLogical2->SetVisAttributes(pressTubeVisAtt); - pressTubeLogical3->SetVisAttributes(pressTubeVisAtt); - pressTubeLogical4->SetVisAttributes(pressTubeVisAtt); - - outLinerVisAtt = new G4VisAttributes(G4Colour(1,0.5,0)); - outLinerVisAtt->SetVisibility(1); - outLinerLogical->SetVisAttributes(outLinerVisAtt); - - insulatorVisAtt = new G4VisAttributes(G4Colour(1,1,0.5)); - insulatorVisAtt->SetVisibility(1); - insulatorLogical1->SetVisAttributes(insulatorVisAtt); - insulatorLogical2->SetVisAttributes(insulatorVisAtt); - insulatorLogical3->SetVisAttributes(insulatorVisAtt); - insulatorLogical4->SetVisAttributes(insulatorVisAtt); - - linerVisAtt = new G4VisAttributes(G4Colour(0,1,0)); - linerVisAtt->SetVisibility(1); - linerLogical->SetVisAttributes(linerVisAtt); - - coolantVisAtt = new G4VisAttributes(G4Colour(0,1,1)); - coolantVisAtt->SetVisibility(1); - coolantLogical->SetVisAttributes(coolantVisAtt); - - outSheatheVisAtt = new G4VisAttributes(G4Colour(0.5,0,1)); - outSheatheVisAtt->SetVisibility(true); - outSheatheLogical->SetVisAttributes(outSheatheVisAtt); - - inSheatheVisAtt = new G4VisAttributes(G4Colour(1,0,1)); - inSheatheVisAtt->SetVisibility(true); - inSheatheLogical->SetVisAttributes(inSheatheVisAtt); - - outFuelVisAtt = new G4VisAttributes(G4Colour(1.,0.,0.)); - outFuelVisAtt->SetVisibility(true); - outFuelLogical1->SetVisAttributes(outFuelVisAtt); - outFuelLogical2->SetVisAttributes(outFuelVisAtt); - outFuelLogical3->SetVisAttributes(outFuelVisAtt); - outFuelLogical4->SetVisAttributes(outFuelVisAtt); - - inFuelVisAtt = new G4VisAttributes(G4Colour(1.,0.5,0.)); - inFuelVisAtt->SetVisibility(true); - inFuelLogical1->SetVisAttributes(inFuelVisAtt); - inFuelLogical2->SetVisAttributes(inFuelVisAtt); - inFuelLogical3->SetVisAttributes(inFuelVisAtt); - inFuelLogical4->SetVisAttributes(inFuelVisAtt); - -// outFlowTubeVisAtt = new G4VisAttributes(G4Colour(1,1,0)); -// outFlowTubeLogical->SetVisAttributes(outFlowTubeVisAtt); -// - flowTubeVisAtt = new G4VisAttributes(G4Colour(0,1,0)); - flowTubeVisAtt->SetVisibility(1); - flowTubeLogical->SetVisAttributes(flowTubeVisAtt); -// flowTubeLogical1->SetVisAttributes(flowTubeVisAtt); -// flowTubeLogical2->SetVisAttributes(flowTubeVisAtt); -// -// inFlowTubeVisAtt = new G4VisAttributes(G4Colour(0.5,0.,1.)); -// inFlowTubeLogical->SetVisAttributes(inFlowTubeVisAtt); - - centralCoolantVisAtt = new G4VisAttributes(G4Colour(0.,1.,1.)); - centralCoolantVisAtt->SetVisibility(1); - centralCoolantLogical->SetVisAttributes(centralCoolantVisAtt); - - - - return worldPhysical; -} - - -// ConstructMaterials() -// Define and build the materials in the C6 lattice cell. -void SCWRConstructor::ConstructMaterials() -{ - // Elements, isotopes and materials - G4Isotope *H1, *H2, *C12, *C13, *O16, *Si28, *Si29, *Si30, *P31, *S32, *S33, *S34, *S36, - *Cr50, *Cr52, *Cr53, *Cr54, *Mn55, *Fe54, *Fe56, *Fe57, *Fe58, *Ni58, *Ni60, *Ni64, - *Nb93, *Y89, *Mo92, *Mo94, *Mo95, *Mo96, *Mo97, *Mo98, *Mo100, - *Sn112, *Sn114, *Sn115, *Sn116, *Sn117, *Sn118, *Sn119, *Sn120, *Sn122, *Sn124, - *Zr90, *Zr91, *Zr92, *Zr94, *Zr96, *Th232, *Pu238, *Pu239, *Pu240, *Pu241, *Pu242; - - G4Element *H, *D, *C, *Oxygen, *Si, *P, *S, *Cr, *Mn, *Fe, *Ni, *Nb, *Y, *Mo, *Sn, *Zr, *Th, *Pu; - - G4Material *World, *Moderator, *PressTube1, *PressTube2, *PressTube3, *PressTube4, *OutLiner, *Insulator1, *Insulator2, *Insulator3, *Insulator4, *Liner, *OutSheathe, *InSheathe, - *OuterFuel1, *OuterFuel2, *OuterFuel3, *OuterFuel4, *InnerFuel1, *InnerFuel2, *InnerFuel3, *InnerFuel4, /*OutFlowTube, *FlowTube1, *FlowTube2, *InFlowTube,*/ *FlowTube, *CentralCoolant ,*ExelLiner, - *ZircSteel, *ZircHydrid, *OuterFuel, *InnerFuel, *H2O, *D2O, *Coolant, *Insulator; - - - // Make hydrogen elements - H1 = new G4Isotope("H1", 1, 1, 1.008*g/mole); - H = new G4Element("Hydrogen", "H", 1); - H->AddIsotope(H1, 1.0); - - H2 = new G4Isotope("H2", 1, 2, 2.014*g/mole); - D = new G4Element("Deterium", "D", 1); - D->AddIsotope(H2, 1.0); - - C12 = new G4Isotope("C12", 6, 12, 12.0*g/mole); - C13 = new G4Isotope("C13", 6, 13, 13.00335*g/mole); - - C = new G4Element("Carbon", "C", 2); - C->AddIsotope(C12, 98.83*perCent); - C->AddIsotope(C13, 1.07*perCent); - - - // Make oxygen isotope and element - O16 = new G4Isotope("O16", 8, 16, 15.995*g/mole); - - Oxygen = new G4Element("Oxygen", "O", 1); - Oxygen->AddIsotope(O16, 100.*perCent); - - Si28 = new G4Isotope("Si28", 14, 28, 27.9769*g/mole); - Si29 = new G4Isotope("Si29", 14, 29, 28.9765*g/mole); - Si30 = new G4Isotope("Si30", 14, 28, 29.9738*g/mole); - - Si = new G4Element("Silicon", "Si", 3); - Si->AddIsotope(Si28, 92.223*perCent); - Si->AddIsotope(Si29, 4.685*perCent); - Si->AddIsotope(Si30, 3.092*perCent); - - // Make oxygen isotope and element - P31 = new G4Isotope("P31", 15, 31, 30.97376*g/mole); - - P = new G4Element("Phosphorus", "P", 1); - P->AddIsotope(P31, 100.*perCent); - - S32 = new G4Isotope("S32", 16, 32, 31.9721*g/mole); - S33 = new G4Isotope("S33", 16, 33, 32.9715*g/mole); - S34 = new G4Isotope("S34", 16, 34, 33.9679*g/mole); - S36 = new G4Isotope("S36", 16, 36, 35.9679*g/mole); - - S = new G4Element("Sulphur", "S", 4); - S->AddIsotope(S32, 94.93*perCent); - S->AddIsotope(S33, 0.76*perCent); - S->AddIsotope(S34, 4.29*perCent); - S->AddIsotope(S36, 0.02*perCent); - - //make chromium isotopes and element - Cr50 = new G4Isotope("Cr50", 24, 50, 49.9460422*g/mole); - Cr52 = new G4Isotope("Cr52", 24, 52, 51.9405075*g/mole); - Cr53 = new G4Isotope("Cr53", 24, 53, 52.9406494*g/mole); - Cr54 = new G4Isotope("Cr54", 24, 54, 53.9388804*g/mole); - - Cr = new G4Element("Chromium", "Cr", 4); - Cr->AddIsotope(Cr50, 4.1737*perCent); - Cr->AddIsotope(Cr52, 83.7003*perCent); - Cr->AddIsotope(Cr53, 9.6726*perCent); - Cr->AddIsotope(Cr54, 2.4534*perCent); - - //make chromium isotopes and element - Mn55 = new G4Isotope("Mn55", 25, 55, 54.9380*g/mole); - - Mn = new G4Element("Manganese", "Mn", 1); - Mn->AddIsotope(Mn55, 100.*perCent); - - //make iron isotopes and element - Fe54 = new G4Isotope("Fe54", 26, 54, 53.9396105*g/mole); - Fe56 = new G4Isotope("Fe56", 26, 56, 55.9349375*g/mole); - Fe57 = new G4Isotope("Fe57", 26, 57, 56.9353940*g/mole); - Fe58 = new G4Isotope("Fe58", 26, 58, 57.9332756*g/mole); - - Fe = new G4Element("Iron", "Fe", 4); - Fe->AddIsotope(Fe54, 5.80*perCent); - Fe->AddIsotope(Fe56, 91.72*perCent); - Fe->AddIsotope(Fe57, 2.20*perCent); - Fe->AddIsotope(Fe58, 0.28*perCent); - - //make nickel isotopes and element - Ni58 = new G4Isotope("Ni58", 28, 58, 57.9353429*g/mole); - Ni60 = new G4Isotope("Ni60", 28, 60, 59.9307864*g/mole); - Ni64 = new G4Isotope("Ni64", 28, 64, 63.9279660*g/mole); - - Ni = new G4Element("Nickel", "Ni", 3); - Ni->AddIsotope(Ni58, 70.913*perCent); - Ni->AddIsotope(Ni60, 28.044*perCent); - Ni->AddIsotope(Ni64, 1.043*perCent); - - //make niobium isotopes and element - Nb93 = new G4Isotope("Nb93", 41, 93, 92.9063781*g/mole); - - Nb = new G4Element("Niobium", "Nb", 1); - Nb->AddIsotope(Nb93, 100*perCent); - - Y89 = new G4Isotope("Y89", 39, 89, 99.9058*g/mole); - - Y = new G4Element("Yttrium", "Y", 1); - Y->AddIsotope(Y89, 100.*perCent); - - //make Zirconium isotopes and element - Mo92 = new G4Isotope("Mo92", 42, 92, 91.9068*g/mole); - Mo94 = new G4Isotope("Mo94", 42, 94, 93.9051*g/mole); - Mo95 = new G4Isotope("Mo95", 42, 95, 94.9058*g/mole); - Mo96 = new G4Isotope("Mo96", 42, 96, 95.9047*g/mole); - Mo97 = new G4Isotope("Mo97", 42, 97, 96.9060*g/mole); - Mo98 = new G4Isotope("Mo98", 42, 98, 97.9054*g/mole); - Mo100 = new G4Isotope("Mo100", 42, 100, 99.9075*g/mole); - - Mo = new G4Element("Molybdenum", "Mo", 7); - Mo->AddIsotope(Mo92, 14.77*perCent); - Mo->AddIsotope(Mo94, 9.23*perCent); - Mo->AddIsotope(Mo95, 15.9*perCent); - Mo->AddIsotope(Mo96, 16.68*perCent); - Mo->AddIsotope(Mo97, 9.56*perCent); - Mo->AddIsotope(Mo98, 24.19*perCent); - Mo->AddIsotope(Mo100, 9.67*perCent); - - Sn112 = new G4Isotope("Sn112", 50, 112, 111.9048*g/mole); - Sn114 = new G4Isotope("Sn114", 50, 114, 113.9028*g/mole); - Sn115 = new G4Isotope("Sn115", 50, 115, 114.9033*g/mole); - Sn116 = new G4Isotope("Sn116", 50, 116, 115.9017*g/mole); - Sn117 = new G4Isotope("Sn117", 50, 117, 116.9030*g/mole); - Sn118 = new G4Isotope("Sn118", 50, 118, 117.9016*g/mole); - Sn119 = new G4Isotope("Sn119", 50, 119, 118.9033*g/mole); - Sn120 = new G4Isotope("Sn120", 50, 120, 119.9022*g/mole); - Sn122 = new G4Isotope("Sn122", 50, 122, 121.9034*g/mole); - Sn124 = new G4Isotope("Sn124", 50, 124, 123.9053*g/mole); - - Sn = new G4Element("Tin", "Sn", 10); - Sn->AddIsotope(Sn112, 0.97*perCent); - Sn->AddIsotope(Sn114, 0.66*perCent); - Sn->AddIsotope(Sn115, 0.34*perCent); - Sn->AddIsotope(Sn116, 14.54*perCent); - Sn->AddIsotope(Sn117, 7.68*perCent); - Sn->AddIsotope(Sn118, 24.22*perCent); - Sn->AddIsotope(Sn119, 8.59*perCent); - Sn->AddIsotope(Sn120, 32.58*perCent); - Sn->AddIsotope(Sn122, 4.63*perCent); - Sn->AddIsotope(Sn124, 5.79*perCent); - - //make Zirconium isotopes and element - Zr90 = new G4Isotope("Zr90", 40, 90, 89.9047044*g/mole); - Zr91 = new G4Isotope("Zr91", 40, 91, 90.9056458*g/mole); - Zr92 = new G4Isotope("Zr92", 40, 92, 91.9050408*g/mole); - Zr94 = new G4Isotope("Zr94", 40, 94, 93.9063152*g/mole); - Zr96 = new G4Isotope("Zr96", 40, 96, 95.9082734*g/mole); - - Zr = new G4Element("Zirconium", "Zr", 5); - Zr->AddIsotope(Zr90, 50.706645*perCent); - Zr->AddIsotope(Zr91, 11.180922*perCent); - Zr->AddIsotope(Zr92, 17.277879*perCent); - Zr->AddIsotope(Zr94, 17.890875*perCent); - Zr->AddIsotope(Zr96, 2.943679*perCent); - - Th232 = new G4Isotope("Th232", 90, 232, 232.0381*g/mole); - - Th = new G4Element("Thorium", "Th", 1); - Th->AddIsotope(Th232, 100.*perCent); - - //make Zirconium isotopes and element - Pu238 = new G4Isotope("Pu238", 94, 238, 238.0496*g/mole); - Pu239 = new G4Isotope("Pu239", 94, 239, 239.0522*g/mole); - Pu240 = new G4Isotope("Pu240", 94, 240, 240.0538*g/mole); - Pu241 = new G4Isotope("Pu241", 94, 241, 241.0569*g/mole); - Pu242 = new G4Isotope("Pu242", 94, 242, 242.0587*g/mole); - -// fixed the isotope compositon so that it is interms of abundance instead of weight percentage - Pu = new G4Element("Plutonium", "Pu", 5); - Pu->AddIsotope(Pu238, 2.77*perCent); - Pu->AddIsotope(Pu239, 52.11*perCent); - Pu->AddIsotope(Pu240, 22.93*perCent); - Pu->AddIsotope(Pu241, 15.15*perCent); - Pu->AddIsotope(Pu242, 7.03*perCent); - - // Create the world material - World = new G4Material("Galactic", 1, 1, 1.e-25*g/cm3, kStateGas, - 2.73*kelvin, 3.e-18*pascal); - - // Create H20 material - H2O = new G4Material("LightWater", 1.*g/cm3, 2, kStateLiquid); - H2O->AddElement(H,2); - H2O->AddElement(Oxygen,1); - - // Create D20 material - D2O = new G4Material("HeavyWater", 1.1*g/cm3, 2, kStateLiquid); - D2O->AddElement(D,2); - D2O->AddElement(Oxygen,1); - - - // Create Coolant - Coolant = new G4Material("Coolant", coolantDensity, 1, kStateLiquid, - coolantTemp); - Coolant->AddMaterial(H2O, 100*perCent); - - //Create Moderator - Moderator = new G4Material("Moderator", moderatorDensity, 2, kStateLiquid, - moderatorTemp); - Moderator->AddMaterial(D2O,99.833*perCent); - Moderator->AddMaterial(H2O,0.167*perCent); - - //Create Moderator - ExelLiner = new G4Material("ExelLiner", 1, 4, kStateSolid, - 1); - ExelLiner->AddElement(Sn,3.5*perCent); - ExelLiner->AddElement(Mo,0.8*perCent); - ExelLiner->AddElement(Nb,0.8*perCent); - ExelLiner->AddElement(Zr,94.9*perCent); - - ZircSteel = new G4Material("ZircSteel", 1, 10, kStateSolid, 1); - ZircSteel->AddElement(C,0.034*perCent); - ZircSteel->AddElement(Si,0.51*perCent); - ZircSteel->AddElement(Mn,0.74*perCent); - ZircSteel->AddElement(P,0.016*perCent); - ZircSteel->AddElement(S,0.002*perCent); - ZircSteel->AddElement(Ni,20.82*perCent); - ZircSteel->AddElement(Cr,25.04*perCent); - ZircSteel->AddElement(Fe,51.738*perCent); - ZircSteel->AddElement(Mo,0.51*perCent); - ZircSteel->AddElement(Zr,0.59*perCent); - - ZircHydrid = new G4Material("ZircHydrid", 1, 2, kStateSolid, 1); - ZircHydrid->AddElement(Zr,98.26*perCent); - ZircHydrid->AddElement(H,1.74*perCent); - - Insulator = new G4Material("Insulator", 1, 3, kStateSolid, 1); - Insulator->AddElement(Zr,66.63*perCent); - Insulator->AddElement(Y,7.87*perCent); - Insulator->AddElement(Oxygen,25.5*perCent); - - //Create Fuel - OuterFuel = new G4Material("OuterFuel", 1, 3, kStateSolid, 1); - OuterFuel->AddElement(Oxygen,12.08*perCent); - OuterFuel->AddElement(Pu,10.59*perCent); - OuterFuel->AddElement(Th,77.34*perCent); - - InnerFuel = new G4Material("InnerFuel", 1, 3, kStateSolid, 1); - InnerFuel->AddElement(Oxygen,12.07*perCent); - InnerFuel->AddElement(Pu,13.23*perCent); - InnerFuel->AddElement(Th,74.7*perCent); - - -// InFlowTube = new G4Material("InFlowTube", inFlowTubeDensity, 1, kStateSolid, inFlowTubeTemp); -// InFlowTube->AddMaterial(ZircSteel,100*perCent); - -// OutFlowTube = new G4Material("OutFlowTube", outFlowTubeDensity, 1, kStateSolid, outFlowTubeTemp); -// OutFlowTube->AddMaterial(ZircSteel,100*perCent); - - OutSheathe = new G4Material("OutSheathe", outSheatheDensity, 1, kStateSolid, outSheatheTemp); - OutSheathe->AddMaterial(ZircSteel,100*perCent); - - InSheathe = new G4Material("InSheathe", inSheatheDensity, 1, kStateSolid, inSheatheTemp); - InSheathe->AddMaterial(ZircSteel,100*perCent); - - Liner = new G4Material("Liner", linerDensity, 1, kStateSolid, linerTemp); - Liner->AddMaterial(ZircSteel,100*perCent); - - - -// FlowTube1 = new G4Material("FlowTube1", flowTubeDensity, 1, kStateSolid, flowTubeTemp[0]); -// FlowTube1->AddMaterial(ZircSteel,100*perCent); -// -// FlowTube2 = new G4Material("FlowTube2", flowTubeDensity, 1, kStateSolid, flowTubeTemp[1]); -// FlowTube2->AddMaterial(ZircSteel,100*perCent); -// - FlowTube = new G4Material("FlowTube", flowTubeDensity, 1, kStateSolid, flowTubeTemp); - FlowTube->AddMaterial(ZircSteel,100*perCent); - - - - - PressTube1 = new G4Material("PressTube1", pressTubeDensity, 1, kStateSolid, pressTubeTemp[0]); - PressTube1->AddMaterial(ExelLiner,100*perCent); - - PressTube2 = new G4Material("PressTube2", pressTubeDensity, 1, kStateSolid, pressTubeTemp[1]); - PressTube2->AddMaterial(ExelLiner,100*perCent); - - PressTube3 = new G4Material("PressTube3", pressTubeDensity, 1, kStateSolid, pressTubeTemp[2]); - PressTube3->AddMaterial(ExelLiner,100*perCent); - - PressTube4 = new G4Material("PressTube4", pressTubeDensity, 1, kStateSolid, pressTubeTemp[3]); - PressTube4->AddMaterial(ExelLiner,100*perCent); - - OutLiner = new G4Material("OutLiner", outLinerDensity, 1, kStateSolid, outLinerTemp); - OutLiner->AddMaterial(ExelLiner,100*perCent); - - - - Insulator1 = new G4Material("Insulator1", insulatorDensity, 1, kStateSolid, insulatorTemp[0]); - Insulator1->AddMaterial(Insulator,100*perCent); - - Insulator2 = new G4Material("Insulator2", insulatorDensity, 1, kStateSolid, insulatorTemp[1]); - Insulator2->AddMaterial(Insulator,100*perCent); - - Insulator3 = new G4Material("Insulator3", insulatorDensity, 1, kStateSolid, insulatorTemp[2]); - Insulator3->AddMaterial(Insulator,100*perCent); - - Insulator4 = new G4Material("Insulator4", insulatorDensity, 1, kStateSolid, insulatorTemp[3]); - Insulator4->AddMaterial(Insulator,100*perCent); - - - InnerFuel1 = new G4Material("InnerFuel1", innerFuelDensity, 1, kStateSolid, innerFuelTemp[0]); - InnerFuel1->AddMaterial(InnerFuel,100*perCent); - - InnerFuel2 = new G4Material("InnerFuel2", innerFuelDensity, 1, kStateSolid, innerFuelTemp[1]); - InnerFuel2->AddMaterial(InnerFuel,100*perCent); - - InnerFuel3 = new G4Material("InnerFuel3", innerFuelDensity, 1, kStateSolid, innerFuelTemp[2]); - InnerFuel3->AddMaterial(InnerFuel,100*perCent); - - InnerFuel4 = new G4Material("InnerFuel4", innerFuelDensity, 1, kStateSolid, innerFuelTemp[3]); - InnerFuel4->AddMaterial(InnerFuel,100*perCent); - - - - OuterFuel1 = new G4Material("OuterFuel1", outerFuelDensity, 1, kStateSolid, outerFuelTemp[0]); - OuterFuel1->AddMaterial(OuterFuel,100*perCent); - - OuterFuel2 = new G4Material("OuterFuel2", outerFuelDensity, 1, kStateSolid, outerFuelTemp[1]); - OuterFuel2->AddMaterial(OuterFuel,100*perCent); - - OuterFuel3 = new G4Material("OuterFuel3", outerFuelDensity, 1, kStateSolid, outerFuelTemp[2]); - OuterFuel3->AddMaterial(OuterFuel,100*perCent); - - OuterFuel4 = new G4Material("OuterFuel4", outerFuelDensity, 1, kStateSolid, outerFuelTemp[3]); - OuterFuel4->AddMaterial(OuterFuel,100*perCent); - - CentralCoolant = new G4Material("CentralCoolant", centralCoolantDensity, 1, kStateLiquid, centralCoolantTemp); - CentralCoolant->AddMaterial(Coolant, 100*perCent); - - - // Add materials to the map indexed by either ZA (format ZZAAA or ZZ) - // For composite materials: world is 0, heavy water is 1, UHW is 2 - matMap["Galactic"] = World; - matMap["Moderator"] = Moderator; - matMap["PressTube1"] = PressTube1; - matMap["PressTube2"] = PressTube2; - matMap["PressTube3"] = PressTube3; - matMap["PressTube4"] = PressTube4; - matMap["OutLiner"] = OutLiner; - matMap["Insulator1"] = Insulator1; - matMap["Insulator2"] = Insulator2; - matMap["Insulator3"] = Insulator3; - matMap["Insulator4"] = Insulator4; - matMap["Liner"] = Liner; - matMap["Coolant"] = Coolant; - matMap["OutSheathe"] = OutSheathe; - matMap["InSheathe"] = InSheathe; - matMap["OuterFuel1"] = OuterFuel1; - matMap["OuterFuel2"] = OuterFuel2; - matMap["OuterFuel3"] = OuterFuel3; - matMap["OuterFuel4"] = OuterFuel4; - matMap["InnerFuel1"] = InnerFuel1; - matMap["InnerFuel2"] = InnerFuel2; - matMap["InnerFuel3"] = InnerFuel3; - matMap["InnerFuel4"] = InnerFuel4; -// matMap["OutFlowTube"] = OutFlowTube; -// matMap["FlowTube1"] = FlowTube1; -// matMap["FlowTube2"] = FlowTube2; - matMap["FlowTube"] = FlowTube; -// matMap["InFlowTube"] = InFlowTube; - matMap["CentralCoolant"] = CentralCoolant; - - matChanged = false; - - return; -} diff --git a/G4STORK/src/SCWRDopplerConstructor.cc b/G4STORK/src/SCWRDopplerConstructor.cc deleted file mode 100755 index 3c5920d3..00000000 --- a/G4STORK/src/SCWRDopplerConstructor.cc +++ /dev/null @@ -1,890 +0,0 @@ -/* -SCWRDopplerConstructor.cc - -Created by: Wesley Ford -Date: 23-05-2012 -Modified: 11-03-2013 - -Source code for the CANDU 6 lattice geometry and materials - -*/ - -#include "SCWRDopplerConstructor.hh" - -// Constructor -SCWRDopplerConstructor::SCWRDopplerConstructor() -: StorkVWorldConstructor(), cellLogical(0), pressTubeLogical(0), outLinerLogical(0), insulatorLogical(0), - linerLogical(0), coolantLogical(0), outSheatheLogical(0), outSheatheLogicalH1(0), outSheatheLogicalH2(0), - inSheatheLogical(0), inSheatheLogicalH1(0), inSheatheLogicalH2(0), outFuelLogical(0), outFuelLogicalH1(0), - outFuelLogicalH2(0), inFuelLogical(0), inFuelLogicalH1(0), inFuelLogicalH2(0), centralCoolantLogical(0) -{ - // Set default member variables (from file or default values) - - - - // Set up variable property map - /* - variablePropMap[MatPropPair(fuel,temperature)] = &fuelTemp; - variablePropMap[MatPropPair(fuel,density)] = &fuelDensity; - variablePropMap[MatPropPair(coolant,temperature)] = &coolantTemp; - variablePropMap[MatPropPair(coolant,density)] = &coolantDensity; - variablePropMap[MatPropPair(moderator,temperature)] = &moderatorTemp; - variablePropMap[MatPropPair(moderator,density)] = &moderatorDensity; - variablePropMap[MatPropPair(all,dimension)] = &latticePitch; - */ - cellVisAtt=NULL; - pressTubeVisAtt=NULL; - outLinerVisAtt=NULL; - insulatorVisAtt=NULL; - linerVisAtt=NULL; - coolantVisAtt=NULL; - outSheatheVisAtt=NULL; - inSheatheVisAtt=NULL; - outFuelVisAtt=NULL; - inFuelVisAtt=NULL; - flowTubeVisAtt=NULL; - centralCoolantVisAtt=NULL; - - latticePitch= 25.*cm; - - /* - moderatorTemp=342.00*kelvin; - moderatorDensity=1.0851*g/cm3; - - pressTubeTemp=416.74*kelvin; - pressTubeDensity=6.52*g/cm3; - - outLinerTemp=470.5200*kelvin; - outLinerDensity=6.52*g/cm3; - - insulatorTemp=557.17*kelvin; - insulatorDensity=5.83*g/cm3; - - linerTemp=671.8*kelvin; - linerDensity=7.9*g/cm3; - - coolantTemp=681.79*kelvin; - //coolantDensity=0.14933*g/cm3; - coolantDensity=0.001*g/cm3; - - inSheatheTemp=756.30*kelvin; - inSheatheDensity=7.9*g/cm3; - - outSheatheTemp=756.30*kelvin; - outSheatheDensity=7.9*g/cm3; - - innerFuelTemp=1420.62*kelvin; - innerFuelDensity=9.91*g/cm3; - - outerFuelTemp=1420.62*kelvin; - outerFuelDensity=9.87*g/cm3; - - flowTubeTemp=657.79*kelvin; - flowTubeDensity=7.9*g/cm3; - - centralCoolantTemp=633.79*kelvin; - //centralCoolantDensity=0.58756*g/cm3; - centralCoolantDensity=0.001*g/cm3; - */ - - // update temperature and density data at h=1.75cm - moderatorTemp=300.00*kelvin; - moderatorDensity=1.0851*g/cm3; - - pressTubeTemp=414.12*kelvin; - pressTubeDensity=6.52*g/cm3; - - outLinerTemp=658.95*kelvin; - outLinerDensity=6.52*g/cm3; - - insulatorTemp=549.11*kelvin; - insulatorDensity=5.83*g/cm3; - - linerTemp=658.95*kelvin; - linerDensity=7.9*g/cm3; - - coolantTemp=666.64*kelvin; - //coolantDensity=0.21395*g/cm3; - coolantDensity=0.001*g/cm3; - - inSheatheTemp=706.93*kelvin; - inSheatheDensity=7.9*g/cm3; - - outSheatheTemp=706.93*kelvin; - outSheatheDensity=7.9*g/cm3; - - innerFuelTemp=1410.09*kelvin; - innerFuelDensity=9.91*g/cm3; - - outerFuelTemp=1410.09*kelvin; - outerFuelDensity=9.87*g/cm3; - - flowTubeTemp=658.95*kelvin; - flowTubeDensity=7.9*g/cm3; - - centralCoolantTemp=635.32*kelvin; - centralCoolantDensity=0.58374*g/cm3; - //centralCoolantDensity=0.001*g/cm3; -} - - -// Desturctor -SCWRDopplerConstructor::~SCWRDopplerConstructor() -{ - // Delete visualization attributes - if(cellVisAtt) - delete cellVisAtt; - if(pressTubeVisAtt) - delete pressTubeVisAtt; - if(outLinerVisAtt) - delete outLinerVisAtt; - if(insulatorVisAtt) - delete insulatorVisAtt; - if(linerVisAtt) - delete linerVisAtt; - if(coolantVisAtt) - delete coolantVisAtt; - if(outSheatheVisAtt) - delete outSheatheVisAtt; - if(inSheatheVisAtt) - delete inSheatheVisAtt; - if(outFuelVisAtt) - delete outFuelVisAtt; - if(inFuelVisAtt) - delete inFuelVisAtt; -// delete outFlowTubeVisAtt; - if(flowTubeVisAtt) - delete flowTubeVisAtt; -// delete inFlowTubeVisAtt; - if(centralCoolantVisAtt) - delete centralCoolantVisAtt; -} - - -//Checked geometry dimensions against Jasons - -// ConstructWorld() -// Construct the geometry and materials of the CANDU 6 lattice cell. -G4VPhysicalVolume* SCWRDopplerConstructor::ConstructWorld() -{ - // Lattic cell dimensions - G4double buffer = 1.0*cm; - reactorDim = G4ThreeVector(latticePitch/4.0,latticePitch/4.0,latticePitch/2.0); - - encWorldDim = 2.0 * G4ThreeVector(reactorDim[0]+buffer,reactorDim[1]+buffer, - reactorDim[2]+buffer); - - G4SolidStore* theSolids = G4SolidStore::GetInstance(); - - - // Set static dimensions - - // Pressure Tube dimension - G4double pressTubeRadmax = 9.05*cm; - G4double pressTubeLen = reactorDim[2]; - - // outer liner dimensions - G4double outLinerRadmax = 7.85*cm; - G4double outLinerLen = reactorDim[2]; - - // insulator dimensions - G4double insulatorRadmax = 7.8*cm; - G4double insulatorLen = reactorDim[2]; - - // liner dimensions - G4double linerRadmax = 7.25*cm; - G4double linerLen = reactorDim[2]; - - // coolant dimensions - G4double coolantRadmax = 7.2*cm; - G4double coolantLen = reactorDim[2]; - - // outer sheathe dimensions - G4double outSheatheRadmax = 0.5*cm; - G4double outSheatheLen = reactorDim[2]; - - // inner sheathe dimensions - G4double inSheatheRadmax = 0.475*cm; - G4double inSheatheLen = reactorDim[2]; - - G4double ringRad[2] = {6.575*cm,5.4*cm}; - //G4double secondRingOffset = 0.*radian; - - // outer fuel dimensions - G4double outFuelRadmax = 0.44*cm; - G4double outFuelLen = reactorDim[2]; - - // inner fuel dimensions - G4double inFuelRadmax = 0.415*cm; - G4double inFuelLen = reactorDim[2]; - - G4double flowTubeRadmax = 4.7*cm; - G4double flowTubeLen = reactorDim[2]; - - // central coolant dimensions - G4double centralCoolantRadmax = 4.6*cm; - G4double centralCoolantLen = reactorDim[2]; - - // Set up the materials (if necessary) - if(matChanged) - { - // Delete any existing materials - DestroyMaterials(); - // Create the materials - ConstructMaterials(); - } - - // Clean up volumes - G4GeometryManager::GetInstance()->OpenGeometry(); - G4PhysicalVolumeStore::GetInstance()->Clean(); - G4LogicalVolumeStore::GetInstance()->Clean(); - - // Set up the solids if necessary - if(geomChanged) - { - // Clean up solids - G4SolidStore::GetInstance()->Clean(); - - // Create world solid - new G4Box("worldBox", encWorldDim[0]/2, encWorldDim[1]/2, - encWorldDim[2]/2); - - // Create the lattice cell solid - new G4Box("cellBox", reactorDim[0], reactorDim[1], reactorDim[2]); - - // Create Pressure Tube - new G4Tubs("pressTube", 0., pressTubeRadmax, pressTubeLen, 0., - 0.5*CLHEP::pi); - - // Create outer liner tube - new G4Tubs("outLinerTube", 0., outLinerRadmax, outLinerLen, 0., 0.5*CLHEP::pi); - - // Create insulator - new G4Tubs("insulatorTube", 0., insulatorRadmax, insulatorLen, 0., - 0.5*CLHEP::pi); - - // Create liner tube - new G4Tubs("linerTube", 0., linerRadmax, linerLen, 0., - 0.5*CLHEP::pi); - - // Create coolant solid - new G4Tubs("coolantTube", 0., coolantRadmax, coolantLen, 0., - 0.5*CLHEP::pi); - - // Create the sheathe for fuel pins - new G4Tubs("outSheatheTube", 0., outSheatheRadmax, outSheatheLen, 0.,2.0*CLHEP::pi); - - new G4Tubs("outSheatheTubeH1", 0., outSheatheRadmax, outSheatheLen, 0.,1.0*CLHEP::pi); - - new G4Tubs("outSheatheTubeH2", 0., outSheatheRadmax, outSheatheLen, -0.5*CLHEP::pi, 1.0*CLHEP::pi); - - // Create the sheathe for fuel pins - new G4Tubs("inSheatheTube", 0., inSheatheRadmax, inSheatheLen, 0.,2.0*CLHEP::pi); - - new G4Tubs("inSheatheTubeH1", 0., inSheatheRadmax, inSheatheLen, 0.,1.0*CLHEP::pi); - - new G4Tubs("inSheatheTubeH2", 0., inSheatheRadmax, inSheatheLen, -0.5*CLHEP::pi, 1.0*CLHEP::pi); - - // Create outer fuel pins - new G4Tubs("outFuelCyl", 0., outFuelRadmax, outFuelLen, 0.,2.0*CLHEP::pi); - - new G4Tubs("outFuelCylH1", 0., outFuelRadmax, outFuelLen, 0.,1.0*CLHEP::pi); - - new G4Tubs("outFuelCylH2", 0., outFuelRadmax, outFuelLen, -0.5*CLHEP::pi, 1.0*CLHEP::pi); - - // Create inner fuel pins - new G4Tubs("inFuelCyl", 0., inFuelRadmax, inFuelLen, 0., 2.0*CLHEP::pi); - - new G4Tubs("inFuelCylH1", 0., inFuelRadmax, inFuelLen, 0., 1.0*CLHEP::pi); - - new G4Tubs("inFuelCylH2", 0., inFuelRadmax, inFuelLen, -0.5*CLHEP::pi, 1.0*CLHEP::pi); - - new G4Tubs("flowTube", 0., flowTubeRadmax, flowTubeLen, 0., 0.5*CLHEP::pi); - - // Create the central coolant - new G4Tubs("centralCoolantCyl", 0., centralCoolantRadmax, centralCoolantLen, 0., 0.5*CLHEP::pi); - - geomChanged = false; - } - - // Create world volume - worldLogical = new G4LogicalVolume(theSolids->GetSolid("worldBox"), - matMap["Galactic"],"worldLogical",0,0,0); - - worldPhysical = new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), worldLogical, - "worldPhysical",0,0,0); - - // Create the lattice cell (moderator) volume - cellLogical = new G4LogicalVolume(theSolids->GetSolid("cellBox"), - matMap["Moderator"],"cellLogical",0,0,0); - - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), cellLogical,"cellPhysical", - worldLogical,0,0); - - // Create the Pressure Tube - pressTubeLogical = new G4LogicalVolume(theSolids->GetSolid("pressTube"), - matMap["PressTube"], "pressTubeLogical",0,0,0); - - - new G4PVPlacement(0, G4ThreeVector(-reactorDim[0],-reactorDim[1],0.), pressTubeLogical, - "pressTubePhysical",cellLogical,0,0); - - // Create the Pressure Tube - outLinerLogical = new G4LogicalVolume(theSolids->GetSolid("outLinerTube"), - matMap["OutLiner"], "outLinerLogical",0,0,0); - - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), outLinerLogical, - "outLinerPhysical",pressTubeLogical,0,0); - - // Create the insulator - insulatorLogical = new G4LogicalVolume(theSolids->GetSolid("insulatorTube"), - matMap["Insulator"], "insulatorLogical",0,0,0); - - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), insulatorLogical, - "insulatorPhysical",outLinerLogical,0,0); - - // Create the Pressure Tube - linerLogical = new G4LogicalVolume(theSolids->GetSolid("linerTube"), - matMap["Liner"], "linerLogical",0,0,0); - - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), linerLogical, - "linerPhysical",insulatorLogical,0,0); - - // Create the Coolant - coolantLogical = new G4LogicalVolume(theSolids->GetSolid("coolantTube"), - matMap["Coolant"], "coolantLogical",0,0,0); - - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), coolantLogical, - "coolantPhysical",linerLogical,0,0); - - // Create the Sheathe - outSheatheLogical = new G4LogicalVolume(theSolids->GetSolid("outSheatheTube"), - matMap["OutSheathe"], "outSheatheLogical",0,0,0); - - outSheatheLogicalH1 = new G4LogicalVolume(theSolids->GetSolid("outSheatheTubeH1"), - matMap["OutSheathe"], "outSheatheLogicalH1",0,0,0); - - outSheatheLogicalH2 = new G4LogicalVolume(theSolids->GetSolid("outSheatheTubeH2"), - matMap["OutSheathe"], "outSheatheLogicalH2",0,0,0); - - - inSheatheLogical = new G4LogicalVolume(theSolids->GetSolid("inSheatheTube"), - matMap["InSheathe"], "inSheatheLogical",0,0,0); - - inSheatheLogicalH1 = new G4LogicalVolume(theSolids->GetSolid("inSheatheTubeH1"), - matMap["InSheathe"], "inSheatheLogicalH1",0,0,0); - - inSheatheLogicalH2 = new G4LogicalVolume(theSolids->GetSolid("inSheatheTubeH2"), - matMap["InSheathe"], "inSheatheLogicalH2",0,0,0); - - // Create a fuel - outFuelLogical = new G4LogicalVolume(theSolids->GetSolid("outFuelCyl"), - matMap["OuterFuel"], "outFuelLogical",0,0,0); - - outFuelLogicalH1 = new G4LogicalVolume(theSolids->GetSolid("outFuelCylH1"), - matMap["OuterFuel"], "outFuelLogicalH1",0,0,0); - - outFuelLogicalH2 = new G4LogicalVolume(theSolids->GetSolid("outFuelCylH2"), - matMap["OuterFuel"], "outFuelLogicalH2",0,0,0); - - // Create a fuel - inFuelLogical = new G4LogicalVolume(theSolids->GetSolid("inFuelCyl"), - matMap["InnerFuel"], "inFuelLogical",0,0,0); - - inFuelLogicalH1 = new G4LogicalVolume(theSolids->GetSolid("inFuelCylH1"), - matMap["InnerFuel"], "inFuelLogicalH1",0,0,0); - - inFuelLogicalH2 = new G4LogicalVolume(theSolids->GetSolid("inFuelCylH2"), - matMap["InnerFuel"], "inFuelLogicalH2",0,0,0); - - - flowTubeLogical = new G4LogicalVolume(theSolids->GetSolid("flowTube"), - matMap["FlowTube"], "flowTubeLogical",0,0,0); - - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), flowTubeLogical, - "flowTubePhysical",coolantLogical,0,0); - - // Create the Pressure Tube - centralCoolantLogical = new G4LogicalVolume(theSolids->GetSolid("centralCoolantCyl"), - matMap["CentralCoolant"], "centralCoolantLogical",0,0,0); - - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), centralCoolantLogical, - "centralCoolantPhysical",flowTubeLogical,0,0); - - - // Create fuel bundle - - // Rotation and translation of the rod and sheathe - std::stringstream volName; - - // Set name for sheathe physical volume - volName << 0; - - new G4PVPlacement(0, G4ThreeVector(ringRad[0],0.,0.), outSheatheLogicalH1, "outSheathePhysicalH1",coolantLogical,0,0); - - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), outFuelLogicalH1,"outFuelPhysicalH1", - outSheatheLogicalH1,0,0); - - // Place pins for outer ring - for( G4int i = 1; i < 8; i++ ) - { - // Reset string stream - volName.str(""); - - volName << i; - - G4ThreeVector Tm(ringRad[0]*cos(2.0*i*CLHEP::pi/32), - ringRad[0]*sin(2.0*i*CLHEP::pi/32), 0.); - - new G4PVPlacement(0, Tm, outSheatheLogical,"outSheathePhysical " + - volName.str(),coolantLogical,0,0); - - } - - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), outFuelLogical,"outFuelPhysical", - outSheatheLogical,0,0); - - new G4PVPlacement(0, G4ThreeVector(0.,ringRad[0],0.), outSheatheLogicalH2, "outSheathePhysicalH2",coolantLogical,0,0); - - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), outFuelLogicalH2,"outFuelPhysicalH2", - outSheatheLogicalH2,0,0); - - - new G4PVPlacement(0, G4ThreeVector(ringRad[1],0.,0.), inSheatheLogicalH1, "inSheathePhysicalH1",coolantLogical,0,0); - - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), inFuelLogicalH1,"inFuelPhysicalH1", - inSheatheLogicalH1,0,0); - - // Place pins for inner ring - for( G4int i = 1; i < 8; i++ ) - { - // Reset string stream - volName.str(""); - - volName << i; - - G4ThreeVector Tm(ringRad[1]*cos(2.0*i*CLHEP::pi/32), - ringRad[1]*sin(2.0*i*CLHEP::pi/32), 0.); - - new G4PVPlacement(0, Tm, inSheatheLogical,"inSheathePhysical " + - volName.str(),coolantLogical,0,0); - - } - - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), inFuelLogical,"inFuelPhysical", - inSheatheLogical,0,0); - - new G4PVPlacement(0, G4ThreeVector(0.,ringRad[1],0.), inSheatheLogicalH2, "inSheathePhysicalH2",coolantLogical,0,0); - - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), inFuelLogicalH2,"inFuelPhysicalH2", - inSheatheLogicalH2,0,0); - - - // Add sensitive detector to ALL logical volumes - worldLogical->SetSensitiveDetector( sDReactor ); - cellLogical->SetSensitiveDetector( sDReactor ); - pressTubeLogical->SetSensitiveDetector( sDReactor ); - outLinerLogical->SetSensitiveDetector( sDReactor ); - insulatorLogical->SetSensitiveDetector( sDReactor ); - linerLogical->SetSensitiveDetector( sDReactor ); - coolantLogical->SetSensitiveDetector( sDReactor ); - outSheatheLogical->SetSensitiveDetector( sDReactor ); - outSheatheLogicalH1->SetSensitiveDetector( sDReactor ); - outSheatheLogicalH2->SetSensitiveDetector( sDReactor ); - inSheatheLogical->SetSensitiveDetector( sDReactor ); - inSheatheLogicalH1->SetSensitiveDetector( sDReactor ); - inSheatheLogicalH2->SetSensitiveDetector( sDReactor ); - outFuelLogical->SetSensitiveDetector( sDReactor ); - outFuelLogicalH1->SetSensitiveDetector( sDReactor ); - outFuelLogicalH2->SetSensitiveDetector( sDReactor ); - inFuelLogical->SetSensitiveDetector( sDReactor ); - inFuelLogicalH1->SetSensitiveDetector( sDReactor ); - inFuelLogicalH2->SetSensitiveDetector( sDReactor ); - flowTubeLogical->SetSensitiveDetector( sDReactor ); - centralCoolantLogical->SetSensitiveDetector( sDReactor ); - - - // Set visualization attributes - - if(worldVisAtt) - delete worldVisAtt; - if(cellVisAtt) - delete cellVisAtt; - if(pressTubeVisAtt) - delete pressTubeVisAtt; - if(outLinerVisAtt) - delete outLinerVisAtt; - if(insulatorVisAtt) - delete insulatorVisAtt; - if(linerVisAtt) - delete linerVisAtt; - if(coolantVisAtt) - delete coolantVisAtt; - if(outSheatheVisAtt) - delete outSheatheVisAtt; - if(inSheatheVisAtt) - delete inSheatheVisAtt; - if(outFuelVisAtt) - delete outFuelVisAtt; - if(inFuelVisAtt) - delete inFuelVisAtt; -// delete outFlowTubeVisAtt; - if(flowTubeVisAtt) - delete flowTubeVisAtt; -// delete inFlowTubeVisAtt; - if(centralCoolantVisAtt) - delete centralCoolantVisAtt; - - worldVisAtt = new G4VisAttributes(G4Colour(1.,1.,1.)); - worldVisAtt->SetVisibility(false); - worldLogical->SetVisAttributes(worldVisAtt); - - cellVisAtt = new G4VisAttributes(G4Colour(0,0,1)); - cellVisAtt->SetVisibility(1); - cellLogical->SetVisAttributes(cellVisAtt); - - pressTubeVisAtt = new G4VisAttributes(G4Colour(1,0,0)); - pressTubeVisAtt->SetVisibility(1); - pressTubeLogical->SetVisAttributes(pressTubeVisAtt); - - outLinerVisAtt = new G4VisAttributes(G4Colour(1,0.5,0)); - outLinerVisAtt->SetVisibility(1); - outLinerLogical->SetVisAttributes(outLinerVisAtt); - - insulatorVisAtt = new G4VisAttributes(G4Colour(1,1,0.5)); - insulatorVisAtt->SetVisibility(1); - insulatorLogical->SetVisAttributes(insulatorVisAtt); - - linerVisAtt = new G4VisAttributes(G4Colour(0,1,0)); - linerVisAtt->SetVisibility(1); - linerLogical->SetVisAttributes(linerVisAtt); - - coolantVisAtt = new G4VisAttributes(G4Colour(0,1,1)); - coolantVisAtt->SetVisibility(1); - coolantLogical->SetVisAttributes(coolantVisAtt); - - outSheatheVisAtt = new G4VisAttributes(G4Colour(0.5,0,1)); - outSheatheVisAtt->SetVisibility(true); - outSheatheLogical->SetVisAttributes(outSheatheVisAtt); - outSheatheLogicalH1->SetVisAttributes(outSheatheVisAtt); - outSheatheLogicalH2->SetVisAttributes(outSheatheVisAtt); - - inSheatheVisAtt = new G4VisAttributes(G4Colour(1,0,1)); - inSheatheVisAtt->SetVisibility(true); - inSheatheLogical->SetVisAttributes(inSheatheVisAtt); - inSheatheLogicalH1->SetVisAttributes(inSheatheVisAtt); - inSheatheLogicalH2->SetVisAttributes(inSheatheVisAtt); - - outFuelVisAtt = new G4VisAttributes(G4Colour(1.,0.,0.)); - outFuelVisAtt->SetVisibility(true); - outFuelLogical->SetVisAttributes(outFuelVisAtt); - outFuelLogicalH1->SetVisAttributes(outFuelVisAtt); - outFuelLogicalH2->SetVisAttributes(outFuelVisAtt); - - inFuelVisAtt = new G4VisAttributes(G4Colour(1.,0.5,0.)); - inFuelVisAtt->SetVisibility(true); - inFuelLogical->SetVisAttributes(inFuelVisAtt); - inFuelLogicalH1->SetVisAttributes(inFuelVisAtt); - inFuelLogicalH2->SetVisAttributes(inFuelVisAtt); - - flowTubeVisAtt = new G4VisAttributes(G4Colour(0,1,0)); - flowTubeVisAtt->SetVisibility(1); - flowTubeLogical->SetVisAttributes(flowTubeVisAtt); - - centralCoolantVisAtt = new G4VisAttributes(G4Colour(0.,1.,1.)); - centralCoolantVisAtt->SetVisibility(1); - centralCoolantLogical->SetVisAttributes(centralCoolantVisAtt); - - - - return worldPhysical; -} - - -// ConstructMaterials() -// Define and build the materials in the C6 lattice cell. -void SCWRDopplerConstructor::ConstructMaterials() -{ - // Elements, isotopes and materials - G4Isotope *H1, *H2, *C12, *C13, *O16, *Si28, *Si29, *Si30, *P31, *S32, *S33, *S34, *S36, - *Cr50, *Cr52, *Cr53, *Cr54, *Mn55, *Fe54, *Fe56, *Fe57, *Fe58, *Ni58, *Ni60, *Ni61, - *Ni62, *Ni64, *Nb93, *Y89, *Mo92, *Mo94, *Mo95, *Mo96, *Mo97, *Mo98, *Mo100, - *Sn112, *Sn114, *Sn115, *Sn116, *Sn117, *Sn118, *Sn119, *Sn120, *Sn122, *Sn124, - *Zr90, *Zr91, *Zr92, *Zr94, *Zr96, *U234, *U235, *U238; - - StorkElement *H, *D, *C, *Oxygen, *Si, *P, *S, *Cr, *Mn, *Fe, *Ni, *Nb, *Y, *Mo, *Sn, *Zr, *NU; - - StorkMaterial *World, *Moderator, *PressTube, *OutLiner, *Insulator, *Liner, *OutSheathe, *InSheathe, - *OuterFuel, *InnerFuel, *FlowTube, *CentralCoolant ,*ExelLiner, - *ZircSteel, /*ZircHydrid,*/ *H2O, *D2O, *Coolant; - - H1 = new G4Isotope("H1", 1, 1, 1.008*g/mole); - H = new StorkElement("Hydrogen", "H", 1); - H->AddIsotope(H1, 1.0); - - H2 = new G4Isotope("H2", 1, 2, 2.014*g/mole); - D = new StorkElement("Deterium", "D", 1); - D->AddIsotope(H2, 1.0); - - C12 = new G4Isotope("C12", 6, 12, 12.0*g/mole); - C13 = new G4Isotope("C13", 6, 13, 13.0033548378*g/mole); - - C = new StorkElement("Carbon", "C", 2); - C->AddIsotope(C12, 98.93*perCent); - C->AddIsotope(C13, 1.07*perCent); - - - // Make oxygen isotope and element - O16 = new G4Isotope("O16", 8, 16, 15.995*g/mole); - - Oxygen = new StorkElement("Oxygen", "O", 1); - Oxygen->AddIsotope(O16, 100.*perCent); - - Si28 = new G4Isotope("Si28", 14, 28, 27.9769*g/mole); - Si29 = new G4Isotope("Si29", 14, 29, 28.9765*g/mole); - Si30 = new G4Isotope("Si30", 14, 28, 29.9738*g/mole); - - Si = new StorkElement("Silicon", "Si", 3); - Si->AddIsotope(Si28, 92.223*perCent); - Si->AddIsotope(Si29, 4.685*perCent); - Si->AddIsotope(Si30, 3.092*perCent); - - // Make oxygen isotope and element - P31 = new G4Isotope("P31", 15, 31, 30.97376*g/mole); - - P = new StorkElement("Phosphorus", "P", 1); - P->AddIsotope(P31, 100.*perCent); - - S32 = new G4Isotope("S32", 16, 32, 31.9721*g/mole); - S33 = new G4Isotope("S33", 16, 33, 32.9715*g/mole); - S34 = new G4Isotope("S34", 16, 34, 33.9679*g/mole); - S36 = new G4Isotope("S36", 16, 36, 35.9679*g/mole); - - S = new StorkElement("Sulphur", "S", 4); - S->AddIsotope(S32, 94.93*perCent); - S->AddIsotope(S33, 0.76*perCent); - S->AddIsotope(S34, 4.29*perCent); - S->AddIsotope(S36, 0.02*perCent); - - //make chromium isotopes and element - Cr50 = new G4Isotope("Cr50", 24, 50, 49.9460422*g/mole); - Cr52 = new G4Isotope("Cr52", 24, 52, 51.9405075*g/mole); - Cr53 = new G4Isotope("Cr53", 24, 53, 52.9406494*g/mole); - Cr54 = new G4Isotope("Cr54", 24, 54, 53.9388804*g/mole); - - Cr = new StorkElement("Chromium", "Cr", 4); - Cr->AddIsotope(Cr50, 4.345*perCent); - Cr->AddIsotope(Cr52, 83.789*perCent); - Cr->AddIsotope(Cr53, 9.501*perCent); - Cr->AddIsotope(Cr54, 2.365*perCent); - - //make chromium isotopes and element - Mn55 = new G4Isotope("Mn55", 25, 55, 54.9380*g/mole); - - Mn = new StorkElement("Manganese", "Mn", 1); - Mn->AddIsotope(Mn55, 100.*perCent); - - //make iron isotopes and element - Fe54 = new G4Isotope("Fe54", 26, 54, 53.9396105*g/mole); - Fe56 = new G4Isotope("Fe56", 26, 56, 55.9349375*g/mole); - Fe57 = new G4Isotope("Fe57", 26, 57, 56.9353940*g/mole); - Fe58 = new G4Isotope("Fe58", 26, 58, 57.9332756*g/mole); - - Fe = new StorkElement("Iron", "Fe", 4); - Fe->AddIsotope(Fe54, 5.845*perCent); - Fe->AddIsotope(Fe56, 91.754*perCent); - Fe->AddIsotope(Fe57, 2.119*perCent); - Fe->AddIsotope(Fe58, 0.282*perCent); - - //make nickel isotopes and element - Ni58 = new G4Isotope("Ni58", 28, 58, 57.9353429*g/mole); - Ni60 = new G4Isotope("Ni60", 28, 60, 59.9307864*g/mole); - Ni61 = new G4Isotope("Ni61", 28, 61, 60.9310560*g/mole); - Ni62 = new G4Isotope("Ni62", 28, 62, 61.9283451*g/mole); - Ni64 = new G4Isotope("Ni64", 28, 64, 63.9279660*g/mole); - - Ni = new StorkElement("Nickel", "Ni", 5); - Ni->AddIsotope(Ni58, 68.0769*perCent); - Ni->AddIsotope(Ni60, 26.2231*perCent); - Ni->AddIsotope(Ni61, 1.1399*perCent); - Ni->AddIsotope(Ni62, 3.6345*perCent); - Ni->AddIsotope(Ni64, 0.9256*perCent); - - //make niobium isotopes and element - Nb93 = new G4Isotope("Nb93", 41, 93, 92.9063781*g/mole); - - Nb = new StorkElement("Niobium", "Nb", 1); - Nb->AddIsotope(Nb93, 100*perCent); - - Y89 = new G4Isotope("Y89", 39, 89, 99.9058*g/mole); - - Y = new StorkElement("Yttrium", "Y", 1); - Y->AddIsotope(Y89, 100.*perCent); - - //make Zirconium isotopes and element - Mo92 = new G4Isotope("Mo92", 42, 92, 91.9068*g/mole); - Mo94 = new G4Isotope("Mo94", 42, 94, 93.9051*g/mole); - Mo95 = new G4Isotope("Mo95", 42, 95, 94.9058*g/mole); - Mo96 = new G4Isotope("Mo96", 42, 96, 95.9047*g/mole); - Mo97 = new G4Isotope("Mo97", 42, 97, 96.9060*g/mole); - Mo98 = new G4Isotope("Mo98", 42, 98, 97.9054*g/mole); - Mo100 = new G4Isotope("Mo100", 42, 100, 99.9075*g/mole); - - Mo = new StorkElement("Molybdenum", "Mo", 7); - Mo->AddIsotope(Mo92, 14.77*perCent); - Mo->AddIsotope(Mo94, 9.23*perCent); - Mo->AddIsotope(Mo95, 15.9*perCent); - Mo->AddIsotope(Mo96, 16.68*perCent); - Mo->AddIsotope(Mo97, 9.56*perCent); - Mo->AddIsotope(Mo98, 24.19*perCent); - Mo->AddIsotope(Mo100, 9.67*perCent); - - Sn112 = new G4Isotope("Sn112", 50, 112, 111.9048*g/mole); - Sn114 = new G4Isotope("Sn114", 50, 114, 113.9028*g/mole); - Sn115 = new G4Isotope("Sn115", 50, 115, 114.9033*g/mole); - Sn116 = new G4Isotope("Sn116", 50, 116, 115.9017*g/mole); - Sn117 = new G4Isotope("Sn117", 50, 117, 116.9030*g/mole); - Sn118 = new G4Isotope("Sn118", 50, 118, 117.9016*g/mole); - Sn119 = new G4Isotope("Sn119", 50, 119, 118.9033*g/mole); - Sn120 = new G4Isotope("Sn120", 50, 120, 119.9022*g/mole); - Sn122 = new G4Isotope("Sn122", 50, 122, 121.9034*g/mole); - Sn124 = new G4Isotope("Sn124", 50, 124, 123.9053*g/mole); - - Sn = new StorkElement("Tin", "Sn", 10); - Sn->AddIsotope(Sn112, 0.97*perCent); - Sn->AddIsotope(Sn114, 0.66*perCent); - Sn->AddIsotope(Sn115, 0.34*perCent); - Sn->AddIsotope(Sn116, 14.54*perCent); - Sn->AddIsotope(Sn117, 7.68*perCent); - Sn->AddIsotope(Sn118, 24.22*perCent); - Sn->AddIsotope(Sn119, 8.59*perCent); - Sn->AddIsotope(Sn120, 32.58*perCent); - Sn->AddIsotope(Sn122, 4.63*perCent); - Sn->AddIsotope(Sn124, 5.79*perCent); - - //make Zirconium isotopes and element - Zr90 = new G4Isotope("Zr90", 40, 90, 89.9047044*g/mole); - Zr91 = new G4Isotope("Zr91", 40, 91, 90.9056458*g/mole); - Zr92 = new G4Isotope("Zr92", 40, 92, 91.9050408*g/mole); - Zr94 = new G4Isotope("Zr94", 40, 94, 93.9063152*g/mole); - Zr96 = new G4Isotope("Zr96", 40, 96, 95.9082734*g/mole); - - Zr = new StorkElement("Zirconium", "Zr", 5); - Zr->AddIsotope(Zr90, 51.45*perCent); - Zr->AddIsotope(Zr91, 11.22*perCent); - Zr->AddIsotope(Zr92, 17.15*perCent); - Zr->AddIsotope(Zr94, 17.38*perCent); - Zr->AddIsotope(Zr96, 2.80*perCent); - - // Make the uranium isotopes and element - U234 = new G4Isotope("U234", 92, 234, 234.0410*g/mole); - U235 = new G4Isotope("U235", 92, 235, 235.0439*g/mole); - U238 = new G4Isotope("U238", 92, 238, 238.0508*g/mole); - - NU = new StorkElement("Natural Uranium", "NU", 3); - NU->AddIsotope(U234, 0.0055*perCent); - NU->AddIsotope(U235, 0.7109*perCent); - NU->AddIsotope(U238, 99.2836*perCent); - - // Create the world material - World = new StorkMaterial("Galactic", 1, 1, 1.e-25*g/cm3, kStateGas, - 2.73*kelvin, 3.e-18*pascal); - - // Create H20 material - H2O = new StorkMaterial("LightWater", 1.*g/cm3, 2, kStateLiquid, coolantTemp); - H2O->AddElement(H,2); - H2O->AddElement(Oxygen,1); - - // Create D20 material - D2O = new StorkMaterial("HeavyWater", 1.1*g/cm3, 2, kStateLiquid, moderatorTemp); - D2O->AddElement(D,2); - D2O->AddElement(Oxygen,1); - - - // Create Coolant - Coolant = new StorkMaterial("Coolant", coolantDensity, 1, kStateLiquid, - coolantTemp); - Coolant->AddMaterial(H2O, 100*perCent); - - //Create Moderator - Moderator = new StorkMaterial("Moderator", moderatorDensity, 2, kStateLiquid, - moderatorTemp); - Moderator->AddMaterial(D2O,99.833*perCent); - Moderator->AddMaterial(H2O,0.167*perCent); - - //Create Moderator - ExelLiner = new StorkMaterial("ExelLiner", 1, 4, kStateSolid, pressTubeTemp); - ExelLiner->AddElement(Sn,3.5*perCent); - ExelLiner->AddElement(Mo,0.8*perCent); - ExelLiner->AddElement(Nb,0.8*perCent); - ExelLiner->AddElement(Zr,94.9*perCent); - - ZircSteel = new StorkMaterial("ZircSteel", 1, 10, kStateSolid, outSheatheTemp); - ZircSteel->AddElement(C,0.034*perCent); - ZircSteel->AddElement(Si,0.51*perCent); - ZircSteel->AddElement(Mn,0.74*perCent); - ZircSteel->AddElement(P,0.016*perCent); - ZircSteel->AddElement(S,0.002*perCent); - ZircSteel->AddElement(Ni,20.82*perCent); - ZircSteel->AddElement(Cr,25.04*perCent); - ZircSteel->AddElement(Fe,51.738*perCent); - ZircSteel->AddElement(Mo,0.51*perCent); - ZircSteel->AddElement(Zr,0.59*perCent); - - - Insulator = new StorkMaterial("Insulator", insulatorDensity, 3, kStateSolid, insulatorTemp); - Insulator->AddElement(Zr,66.63*perCent); - Insulator->AddElement(Y,7.87*perCent); - Insulator->AddElement(Oxygen,25.5*perCent); - - //Create Fuel - OuterFuel = new StorkMaterial("OuterFuel", outerFuelDensity, 3, kStateSolid, outerFuelTemp); - OuterFuel->AddElement(Oxygen,12.08*perCent); - OuterFuel->AddElement(NU,87.92*perCent); - - InnerFuel = new StorkMaterial("InnerFuel", innerFuelDensity, 3, kStateSolid, innerFuelTemp); - InnerFuel->AddElement(Oxygen,12.07*perCent); - InnerFuel->AddElement(NU,87.93*perCent); - - OutSheathe = new StorkMaterial("OutSheathe", outSheatheDensity, 1, kStateSolid, outSheatheTemp); - OutSheathe->AddMaterial(ZircSteel,100*perCent); - - InSheathe = new StorkMaterial("InSheathe", inSheatheDensity, 1, kStateSolid, inSheatheTemp); - InSheathe->AddMaterial(ZircSteel,100*perCent); - - Liner = new StorkMaterial("Liner", linerDensity, 1, kStateSolid, linerTemp); - Liner->AddMaterial(ZircSteel,100*perCent); - - FlowTube = new StorkMaterial("FlowTube", flowTubeDensity, 1, kStateSolid, flowTubeTemp); - FlowTube->AddMaterial(ZircSteel,100*perCent); - - PressTube = new StorkMaterial("PressTube", pressTubeDensity, 1, kStateSolid, pressTubeTemp); - PressTube->AddMaterial(ExelLiner,100*perCent); - - OutLiner = new StorkMaterial("OutLiner", outLinerDensity, 1, kStateSolid, outLinerTemp); - OutLiner->AddMaterial(ExelLiner,100*perCent); - - CentralCoolant = new StorkMaterial("CentralCoolant", centralCoolantDensity, 1, kStateLiquid, centralCoolantTemp); - CentralCoolant->AddMaterial(Coolant, 100*perCent); - - - // Add materials to the map indexed by either ZA (format ZZAAA or ZZ) - // For composite materials: world is 0, heavy water is 1, UHW is 2 - matMap["Galactic"] = World; - matMap["Moderator"] = Moderator; - matMap["PressTube"] = PressTube; - matMap["OutLiner"] = OutLiner; - matMap["Insulator"] = Insulator; - matMap["Liner"] = Liner; - matMap["Coolant"] = Coolant; - matMap["OutSheathe"] = OutSheathe; - matMap["InSheathe"] = InSheathe; - matMap["OuterFuel"] = OuterFuel; - matMap["InnerFuel"] = InnerFuel; - matMap["FlowTube"] = FlowTube; - matMap["CentralCoolant"] = CentralCoolant; - - matChanged = false; - - return; -} diff --git a/G4STORK/src/SCWRJasonConstructor.cc b/G4STORK/src/SCWRJasonConstructor.cc deleted file mode 100755 index a1bc426a..00000000 --- a/G4STORK/src/SCWRJasonConstructor.cc +++ /dev/null @@ -1,875 +0,0 @@ -/* -SCWRJasonConstructor.cc - -Created by: Wesley Ford -Date: 23-05-2012 -Modified: 11-03-2013 - -Source code for the CANDU 6 lattice geometry and materials - -*/ - -#include "SCWRJasonConstructor.hh" - -// Constructor -SCWRJasonConstructor::SCWRJasonConstructor() -: StorkVWorldConstructor(), cellLogical(0), pressTubeLogical(0), outLinerLogical(0), insulatorLogical(0), - linerLogical(0), coolantLogical(0), outSheatheLogical(0), outSheatheLogicalH1(0), outSheatheLogicalH2(0), - inSheatheLogical(0), inSheatheLogicalH1(0), inSheatheLogicalH2(0), outFuelLogical(0), outFuelLogicalH1(0), - outFuelLogicalH2(0), inFuelLogical(0), inFuelLogicalH1(0), inFuelLogicalH2(0), centralCoolantLogical(0) -{ - // Set default member variables (from file or default values) - - - - // Set up variable property map - /* - variablePropMap[MatPropPair(fuel,temperature)] = &fuelTemp; - variablePropMap[MatPropPair(fuel,density)] = &fuelDensity; - variablePropMap[MatPropPair(coolant,temperature)] = &coolantTemp; - variablePropMap[MatPropPair(coolant,density)] = &coolantDensity; - variablePropMap[MatPropPair(moderator,temperature)] = &moderatorTemp; - variablePropMap[MatPropPair(moderator,density)] = &moderatorDensity; - variablePropMap[MatPropPair(all,dimension)] = &latticePitch; - */ - - cellVisAtt=NULL; - pressTubeVisAtt=NULL; - outLinerVisAtt=NULL; - insulatorVisAtt=NULL; - linerVisAtt=NULL; - coolantVisAtt=NULL; - outSheatheVisAtt=NULL; - inSheatheVisAtt=NULL; - outFuelVisAtt=NULL; - inFuelVisAtt=NULL; - flowTubeVisAtt=NULL; - centralCoolantVisAtt=NULL; - - latticePitch= 25.*cm; - - moderatorTemp=342.00*kelvin; - moderatorDensity=1.0851*g/cm3; - - pressTubeTemp=416.74*kelvin; - pressTubeDensity=6.52*g/cm3; - - outLinerTemp=470.5200*kelvin; - outLinerDensity=6.52*g/cm3; - - insulatorTemp=557.17*kelvin; - insulatorDensity=5.83*g/cm3; - - linerTemp=671.8*kelvin; - linerDensity=7.9*g/cm3; - - coolantTemp=681.79*kelvin; - //coolantDensity=0.14933*g/cm3; - coolantDensity=0.001*g/cm3; - - inSheatheTemp=756.30*kelvin; - inSheatheDensity=7.9*g/cm3; - - outSheatheTemp=756.30*kelvin; - outSheatheDensity=7.9*g/cm3; - - innerFuelTemp=1420.62*kelvin; - innerFuelDensity=9.91*g/cm3; - - outerFuelTemp=1420.62*kelvin; - outerFuelDensity=9.87*g/cm3; - - flowTubeTemp=657.79*kelvin; - flowTubeDensity=7.9*g/cm3; - - centralCoolantTemp=633.79*kelvin; - //centralCoolantDensity=0.58756*g/cm3; - centralCoolantDensity=0.001*g/cm3; -} - - -// Desturctor -SCWRJasonConstructor::~SCWRJasonConstructor() -{ - // Delete visualization attributes - if(cellVisAtt) - delete cellVisAtt; - if(pressTubeVisAtt) - delete pressTubeVisAtt; - if(outLinerVisAtt) - delete outLinerVisAtt; - if(insulatorVisAtt) - delete insulatorVisAtt; - if(linerVisAtt) - delete linerVisAtt; - if(coolantVisAtt) - delete coolantVisAtt; - if(outSheatheVisAtt) - delete outSheatheVisAtt; - if(inSheatheVisAtt) - delete inSheatheVisAtt; - if(outFuelVisAtt) - delete outFuelVisAtt; - if(inFuelVisAtt) - delete inFuelVisAtt; - //if(outFlowTubeVisAtt) -// delete outFlowTubeVisAtt; - if(flowTubeVisAtt) - delete flowTubeVisAtt; - //if(inFlowTubeVisAtt) -// delete inFlowTubeVisAtt; - if(centralCoolantVisAtt) - delete centralCoolantVisAtt; -} - - -//Checked geometry dimensions against Jasons - -// ConstructWorld() -// Construct the geometry and materials of the CANDU 6 lattice cell. -G4VPhysicalVolume* SCWRJasonConstructor::ConstructWorld() -{ - // Lattic cell dimensions - G4double buffer = 1.0*cm; - reactorDim = G4ThreeVector(latticePitch/4.0,latticePitch/4.0,latticePitch/2.0); - - encWorldDim = 2.0 * G4ThreeVector(reactorDim[0]+buffer,reactorDim[1]+buffer, - reactorDim[2]+buffer); - - G4SolidStore* theSolids = G4SolidStore::GetInstance(); - - - // Set static dimensions - - // Pressure Tube dimension - G4double pressTubeRadmax = 9.05*cm; - G4double pressTubeLen = reactorDim[2]; - - // outer liner dimensions - G4double outLinerRadmax = 7.85*cm; - G4double outLinerLen = reactorDim[2]; - - // insulator dimensions - G4double insulatorRadmax = 7.8*cm; - G4double insulatorLen = reactorDim[2]; - - // liner dimensions - G4double linerRadmax = 7.25*cm; - G4double linerLen = reactorDim[2]; - - // coolant dimensions - G4double coolantRadmax = 7.2*cm; - G4double coolantLen = reactorDim[2]; - - // outer sheathe dimensions - G4double outSheatheRadmax = 0.5*cm; - G4double outSheatheLen = reactorDim[2]; - - // inner sheathe dimensions - G4double inSheatheRadmax = 0.475*cm; - G4double inSheatheLen = reactorDim[2]; - - G4double ringRad[2] = {6.575*cm,5.4*cm}; - //G4double secondRingOffset = 0.*radian; - - // outer fuel dimensions - G4double outFuelRadmax = 0.44*cm; - G4double outFuelLen = reactorDim[2]; - - // inner fuel dimensions - G4double inFuelRadmax = 0.415*cm; - G4double inFuelLen = reactorDim[2]; - - G4double flowTubeRadmax = 4.7*cm; - G4double flowTubeLen = reactorDim[2]; - - // central coolant dimensions - G4double centralCoolantRadmax = 4.6*cm; - G4double centralCoolantLen = reactorDim[2]; - - // Set up the materials (if necessary) - if(matChanged) - { - // Delete any existing materials - DestroyMaterials(); - // Create the materials - ConstructMaterials(); - } - - // Clean up volumes - G4GeometryManager::GetInstance()->OpenGeometry(); - G4PhysicalVolumeStore::GetInstance()->Clean(); - G4LogicalVolumeStore::GetInstance()->Clean(); - - // Set up the solids if necessary - if(geomChanged) - { - // Clean up solids - G4SolidStore::GetInstance()->Clean(); - - // Create world solid - new G4Box("worldBox", encWorldDim[0]/2, encWorldDim[1]/2, - encWorldDim[2]/2); - - // Create the lattice cell solid - new G4Box("cellBox", reactorDim[0], reactorDim[1], reactorDim[2]); - - // Create Pressure Tube - new G4Tubs("pressTube", 0., pressTubeRadmax, pressTubeLen, 0., - 0.5*CLHEP::pi); - - // Create outer liner tube - new G4Tubs("outLinerTube", 0., outLinerRadmax, outLinerLen, 0., 0.5*CLHEP::pi); - - // Create insulator - new G4Tubs("insulatorTube", 0., insulatorRadmax, insulatorLen, 0., - 0.5*CLHEP::pi); - - // Create liner tube - new G4Tubs("linerTube", 0., linerRadmax, linerLen, 0., - 0.5*CLHEP::pi); - - // Create coolant solid - new G4Tubs("coolantTube", 0., coolantRadmax, coolantLen, 0., - 0.5*CLHEP::pi); - - // Create the sheathe for fuel pins - new G4Tubs("outSheatheTube", 0., outSheatheRadmax, outSheatheLen, 0.,2.0*CLHEP::pi); - - new G4Tubs("outSheatheTubeH1", 0., outSheatheRadmax, outSheatheLen, 0.,1.0*CLHEP::pi); - - new G4Tubs("outSheatheTubeH2", 0., outSheatheRadmax, outSheatheLen, -0.5*CLHEP::pi, 1.0*CLHEP::pi); - - // Create the sheathe for fuel pins - new G4Tubs("inSheatheTube", 0., inSheatheRadmax, inSheatheLen, 0.,2.0*CLHEP::pi); - - new G4Tubs("inSheatheTubeH1", 0., inSheatheRadmax, inSheatheLen, 0.,1.0*CLHEP::pi); - - new G4Tubs("inSheatheTubeH2", 0., inSheatheRadmax, inSheatheLen, -0.5*CLHEP::pi, 1.0*CLHEP::pi); - - // Create outer fuel pins - new G4Tubs("outFuelCyl", 0., outFuelRadmax, outFuelLen, 0.,2.0*CLHEP::pi); - - new G4Tubs("outFuelCylH1", 0., outFuelRadmax, outFuelLen, 0.,1.0*CLHEP::pi); - - new G4Tubs("outFuelCylH2", 0., outFuelRadmax, outFuelLen, -0.5*CLHEP::pi, 1.0*CLHEP::pi); - - // Create inner fuel pins - new G4Tubs("inFuelCyl", 0., inFuelRadmax, inFuelLen, 0., 2.0*CLHEP::pi); - - new G4Tubs("inFuelCylH1", 0., inFuelRadmax, inFuelLen, 0., 1.0*CLHEP::pi); - - new G4Tubs("inFuelCylH2", 0., inFuelRadmax, inFuelLen, -0.5*CLHEP::pi, 1.0*CLHEP::pi); - - new G4Tubs("flowTube", 0., flowTubeRadmax, flowTubeLen, 0., 0.5*CLHEP::pi); - - // Create the central coolant - new G4Tubs("centralCoolantCyl", 0., centralCoolantRadmax, centralCoolantLen, 0., 0.5*CLHEP::pi); - - geomChanged = false; - } - - // Create world volume - worldLogical = new G4LogicalVolume(theSolids->GetSolid("worldBox"), - matMap["Galactic"],"worldLogical",0,0,0); - - worldPhysical = new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), worldLogical, - "worldPhysical",0,0,0); - - // Create the lattice cell (moderator) volume - cellLogical = new G4LogicalVolume(theSolids->GetSolid("cellBox"), - matMap["Moderator"],"cellLogical",0,0,0); - - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), cellLogical,"cellPhysical", - worldLogical,0,0); - - // Create the Pressure Tube - pressTubeLogical = new G4LogicalVolume(theSolids->GetSolid("pressTube"), - matMap["PressTube"], "pressTubeLogical",0,0,0); - - - new G4PVPlacement(0, G4ThreeVector(-reactorDim[0],-reactorDim[1],0.), pressTubeLogical, - "pressTubePhysical",cellLogical,0,0); - - // Create the Pressure Tube - outLinerLogical = new G4LogicalVolume(theSolids->GetSolid("outLinerTube"), - matMap["OutLiner"], "outLinerLogical",0,0,0); - - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), outLinerLogical, - "outLinerPhysical",pressTubeLogical,0,0); - - // Create the insulator - insulatorLogical = new G4LogicalVolume(theSolids->GetSolid("insulatorTube"), - matMap["Insulator"], "insulatorLogical",0,0,0); - - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), insulatorLogical, - "insulatorPhysical",outLinerLogical,0,0); - - // Create the Pressure Tube - linerLogical = new G4LogicalVolume(theSolids->GetSolid("linerTube"), - matMap["Liner"], "linerLogical",0,0,0); - - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), linerLogical, - "linerPhysical",insulatorLogical,0,0); - - // Create the Coolant - coolantLogical = new G4LogicalVolume(theSolids->GetSolid("coolantTube"), - matMap["Coolant"], "coolantLogical",0,0,0); - - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), coolantLogical, - "coolantPhysical",linerLogical,0,0); - - // Create the Sheathe - outSheatheLogical = new G4LogicalVolume(theSolids->GetSolid("outSheatheTube"), - matMap["OutSheathe"], "outSheatheLogical",0,0,0); - - outSheatheLogicalH1 = new G4LogicalVolume(theSolids->GetSolid("outSheatheTubeH1"), - matMap["OutSheathe"], "outSheatheLogicalH1",0,0,0); - - outSheatheLogicalH2 = new G4LogicalVolume(theSolids->GetSolid("outSheatheTubeH2"), - matMap["OutSheathe"], "outSheatheLogicalH2",0,0,0); - - - inSheatheLogical = new G4LogicalVolume(theSolids->GetSolid("inSheatheTube"), - matMap["InSheathe"], "inSheatheLogical",0,0,0); - - inSheatheLogicalH1 = new G4LogicalVolume(theSolids->GetSolid("inSheatheTubeH1"), - matMap["InSheathe"], "inSheatheLogicalH1",0,0,0); - - inSheatheLogicalH2 = new G4LogicalVolume(theSolids->GetSolid("inSheatheTubeH2"), - matMap["InSheathe"], "inSheatheLogicalH2",0,0,0); - - // Create a fuel - outFuelLogical = new G4LogicalVolume(theSolids->GetSolid("outFuelCyl"), - matMap["OuterFuel"], "outFuelLogical",0,0,0); - - outFuelLogicalH1 = new G4LogicalVolume(theSolids->GetSolid("outFuelCylH1"), - matMap["OuterFuel"], "outFuelLogicalH1",0,0,0); - - outFuelLogicalH2 = new G4LogicalVolume(theSolids->GetSolid("outFuelCylH2"), - matMap["OuterFuel"], "outFuelLogicalH2",0,0,0); - - // Create a fuel - inFuelLogical = new G4LogicalVolume(theSolids->GetSolid("inFuelCyl"), - matMap["InnerFuel"], "inFuelLogical",0,0,0); - - inFuelLogicalH1 = new G4LogicalVolume(theSolids->GetSolid("inFuelCylH1"), - matMap["InnerFuel"], "inFuelLogicalH1",0,0,0); - - inFuelLogicalH2 = new G4LogicalVolume(theSolids->GetSolid("inFuelCylH2"), - matMap["InnerFuel"], "inFuelLogicalH2",0,0,0); - - - flowTubeLogical = new G4LogicalVolume(theSolids->GetSolid("flowTube"), - matMap["FlowTube"], "flowTubeLogical",0,0,0); - - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), flowTubeLogical, - "flowTubePhysical",coolantLogical,0,0); - - // Create the Pressure Tube - centralCoolantLogical = new G4LogicalVolume(theSolids->GetSolid("centralCoolantCyl"), - matMap["CentralCoolant"], "centralCoolantLogical",0,0,0); - - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), centralCoolantLogical, - "centralCoolantPhysical",flowTubeLogical,0,0); - - - // Create fuel bundle - - // Rotation and translation of the rod and sheathe - std::stringstream volName; - - // Set name for sheathe physical volume - volName << 0; - - new G4PVPlacement(0, G4ThreeVector(ringRad[0],0.,0.), outSheatheLogicalH1, "outSheathePhysicalH1",coolantLogical,0,0); - - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), outFuelLogicalH1,"outFuelPhysicalH1", - outSheatheLogicalH1,0,0); - - // Place pins for outer ring - for( G4int i = 1; i < 8; i++ ) - { - // Reset string stream - volName.str(""); - - volName << i; - - G4ThreeVector Tm(ringRad[0]*cos(2.0*i*CLHEP::pi/32), - ringRad[0]*sin(2.0*i*CLHEP::pi/32), 0.); - - new G4PVPlacement(0, Tm, outSheatheLogical,"outSheathePhysical " + - volName.str(),coolantLogical,0,0); - - } - - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), outFuelLogical,"outFuelPhysical", - outSheatheLogical,0,0); - - new G4PVPlacement(0, G4ThreeVector(0.,ringRad[0],0.), outSheatheLogicalH2, "outSheathePhysicalH2",coolantLogical,0,0); - - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), outFuelLogicalH2,"outFuelPhysicalH2", - outSheatheLogicalH2,0,0); - - - new G4PVPlacement(0, G4ThreeVector(ringRad[1],0.,0.), inSheatheLogicalH1, "inSheathePhysicalH1",coolantLogical,0,0); - - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), inFuelLogicalH1,"inFuelPhysicalH1", - inSheatheLogicalH1,0,0); - - // Place pins for inner ring - for( G4int i = 1; i < 8; i++ ) - { - // Reset string stream - volName.str(""); - - volName << i; - - G4ThreeVector Tm(ringRad[1]*cos(2.0*i*CLHEP::pi/32), - ringRad[1]*sin(2.0*i*CLHEP::pi/32), 0.); - - new G4PVPlacement(0, Tm, inSheatheLogical,"inSheathePhysical " + - volName.str(),coolantLogical,0,0); - - } - - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), inFuelLogical,"inFuelPhysical", - inSheatheLogical,0,0); - - new G4PVPlacement(0, G4ThreeVector(0.,ringRad[1],0.), inSheatheLogicalH2, "inSheathePhysicalH2",coolantLogical,0,0); - - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), inFuelLogicalH2,"inFuelPhysicalH2", - inSheatheLogicalH2,0,0); - - - // Add sensitive detector to ALL logical volumes - worldLogical->SetSensitiveDetector( sDReactor ); - cellLogical->SetSensitiveDetector( sDReactor ); - pressTubeLogical->SetSensitiveDetector( sDReactor ); - outLinerLogical->SetSensitiveDetector( sDReactor ); - insulatorLogical->SetSensitiveDetector( sDReactor ); - linerLogical->SetSensitiveDetector( sDReactor ); - coolantLogical->SetSensitiveDetector( sDReactor ); - outSheatheLogical->SetSensitiveDetector( sDReactor ); - outSheatheLogicalH1->SetSensitiveDetector( sDReactor ); - outSheatheLogicalH2->SetSensitiveDetector( sDReactor ); - inSheatheLogical->SetSensitiveDetector( sDReactor ); - inSheatheLogicalH1->SetSensitiveDetector( sDReactor ); - inSheatheLogicalH2->SetSensitiveDetector( sDReactor ); - outFuelLogical->SetSensitiveDetector( sDReactor ); - outFuelLogicalH1->SetSensitiveDetector( sDReactor ); - outFuelLogicalH2->SetSensitiveDetector( sDReactor ); - inFuelLogical->SetSensitiveDetector( sDReactor ); - inFuelLogicalH1->SetSensitiveDetector( sDReactor ); - inFuelLogicalH2->SetSensitiveDetector( sDReactor ); - flowTubeLogical->SetSensitiveDetector( sDReactor ); - centralCoolantLogical->SetSensitiveDetector( sDReactor ); - - - // Set visualization attributes - - if(worldVisAtt) - delete worldVisAtt; - if(cellVisAtt) - delete cellVisAtt; - if(pressTubeVisAtt) - delete pressTubeVisAtt; - if(outLinerVisAtt) - delete outLinerVisAtt; - if(insulatorVisAtt) - delete insulatorVisAtt; - if(linerVisAtt) - delete linerVisAtt; - if(coolantVisAtt) - delete coolantVisAtt; - if(outSheatheVisAtt) - delete outSheatheVisAtt; - if(inSheatheVisAtt) - delete inSheatheVisAtt; - if(outFuelVisAtt) - delete outFuelVisAtt; - if(inFuelVisAtt) - delete inFuelVisAtt; - //if(outFlowTubeVisAtt) -// delete outFlowTubeVisAtt; - if(flowTubeVisAtt) - delete flowTubeVisAtt; - //if(inFlowTubeVisAtt) -// delete inFlowTubeVisAtt; - if(centralCoolantVisAtt) - delete centralCoolantVisAtt; - - worldVisAtt = new G4VisAttributes(G4Colour(1.,1.,1.)); - worldVisAtt->SetVisibility(false); - worldLogical->SetVisAttributes(worldVisAtt); - - cellVisAtt = new G4VisAttributes(G4Colour(0,0,1)); - cellVisAtt->SetVisibility(1); - cellLogical->SetVisAttributes(cellVisAtt); - - pressTubeVisAtt = new G4VisAttributes(G4Colour(1,0,0)); - pressTubeVisAtt->SetVisibility(1); - pressTubeLogical->SetVisAttributes(pressTubeVisAtt); - - outLinerVisAtt = new G4VisAttributes(G4Colour(1,0.5,0)); - outLinerVisAtt->SetVisibility(1); - outLinerLogical->SetVisAttributes(outLinerVisAtt); - - insulatorVisAtt = new G4VisAttributes(G4Colour(1,1,0.5)); - insulatorVisAtt->SetVisibility(1); - insulatorLogical->SetVisAttributes(insulatorVisAtt); - - linerVisAtt = new G4VisAttributes(G4Colour(0,1,0)); - linerVisAtt->SetVisibility(1); - linerLogical->SetVisAttributes(linerVisAtt); - - coolantVisAtt = new G4VisAttributes(G4Colour(0,1,1)); - coolantVisAtt->SetVisibility(1); - coolantLogical->SetVisAttributes(coolantVisAtt); - - outSheatheVisAtt = new G4VisAttributes(G4Colour(0.5,0,1)); - outSheatheVisAtt->SetVisibility(true); - outSheatheLogical->SetVisAttributes(outSheatheVisAtt); - outSheatheLogicalH1->SetVisAttributes(outSheatheVisAtt); - outSheatheLogicalH2->SetVisAttributes(outSheatheVisAtt); - - inSheatheVisAtt = new G4VisAttributes(G4Colour(1,0,1)); - inSheatheVisAtt->SetVisibility(true); - inSheatheLogical->SetVisAttributes(inSheatheVisAtt); - inSheatheLogicalH1->SetVisAttributes(inSheatheVisAtt); - inSheatheLogicalH2->SetVisAttributes(inSheatheVisAtt); - - outFuelVisAtt = new G4VisAttributes(G4Colour(1.,0.,0.)); - outFuelVisAtt->SetVisibility(true); - outFuelLogical->SetVisAttributes(outFuelVisAtt); - outFuelLogicalH1->SetVisAttributes(outFuelVisAtt); - outFuelLogicalH2->SetVisAttributes(outFuelVisAtt); - - inFuelVisAtt = new G4VisAttributes(G4Colour(1.,0.5,0.)); - inFuelVisAtt->SetVisibility(true); - inFuelLogical->SetVisAttributes(inFuelVisAtt); - inFuelLogicalH1->SetVisAttributes(inFuelVisAtt); - inFuelLogicalH2->SetVisAttributes(inFuelVisAtt); - - flowTubeVisAtt = new G4VisAttributes(G4Colour(0,1,0)); - flowTubeVisAtt->SetVisibility(1); - flowTubeLogical->SetVisAttributes(flowTubeVisAtt); - - centralCoolantVisAtt = new G4VisAttributes(G4Colour(0.,1.,1.)); - centralCoolantVisAtt->SetVisibility(1); - centralCoolantLogical->SetVisAttributes(centralCoolantVisAtt); - - - - return worldPhysical; -} - - -// ConstructMaterials() -// Define and build the materials in the C6 lattice cell. -void SCWRJasonConstructor::ConstructMaterials() -{ - // Elements, isotopes and materials - G4Isotope *H1, *H2, *C12, *C13, *O16, *Si28, *Si29, *Si30, *P31, *S32, /*S33, *S34, *S36,*/ - *Cr50, *Cr52, *Cr53, *Cr54, *Mn55, *Fe54, *Fe56, *Fe57, *Fe58, *Ni58, *Ni60, *Ni61, - *Ni62, *Ni64, *Nb93, *Y89, *Mo92, *Mo94, *Mo95, *Mo96, *Mo97, *Mo98, *Mo100, - *Sn112, *Sn114, *Sn115, *Sn116, *Sn117, *Sn118, *Sn119, *Sn120, *Sn122, *Sn124, - *Zr90, *Zr91, *Zr92, *Zr94, *Zr96, *Th232, *Pu238, *Pu239, *Pu240, *Pu241, *Pu242; - - G4Element *H, *D, *C, *Oxygen, *Si, *P, *S, *Cr, *Mn, *Fe, *Ni, *Nb, *Y, *Mo, *Sn, *Zr, *Th, *Pu; - - G4Material *World, *Moderator, *PressTube, *OutLiner, *Insulator, *Liner, *OutSheathe, *InSheathe, - *OuterFuel, *InnerFuel, *FlowTube, *CentralCoolant ,*ExelLiner, - *ZircSteel, *ZircHydrid, *H2O, *D2O, *Coolant; - - // check material compositions against jasons files for inconsistancies - // Checked, inner fuel and outer fuel - // checked temperature and density - // need to check geometry as well - // checked all the isotope and material compositions against AECL and wikipedia get Jasons abundance list - H1 = new G4Isotope("H1", 1, 1, 1.008*g/mole); - H = new G4Element("Hydrogen", "H", 1); - H->AddIsotope(H1, 1.0); - - H2 = new G4Isotope("H2", 1, 2, 2.014*g/mole); - D = new G4Element("Deterium", "D", 1); - D->AddIsotope(H2, 1.0); - - C12 = new G4Isotope("C12", 6, 12, 12.0*g/mole); - C13 = new G4Isotope("C13", 6, 13, 13.0033548378*g/mole); - - C = new G4Element("Carbon", "C", 2); - C->AddIsotope(C12, 98.93*perCent); - C->AddIsotope(C13, 1.07*perCent); - - - // Make oxygen isotope and element - O16 = new G4Isotope("O16", 8, 16, 15.995*g/mole); - - Oxygen = new G4Element("Oxygen", "O", 1); - Oxygen->AddIsotope(O16, 100.*perCent); - - Si28 = new G4Isotope("Si28", 14, 28, 27.9769*g/mole); - Si29 = new G4Isotope("Si29", 14, 29, 28.9765*g/mole); - Si30 = new G4Isotope("Si30", 14, 28, 29.9738*g/mole); - - Si = new G4Element("Silicon", "Si", 3); - Si->AddIsotope(Si28, 92.223*perCent); - Si->AddIsotope(Si29, 4.685*perCent); - Si->AddIsotope(Si30, 3.092*perCent); - - // Make oxygen isotope and element - P31 = new G4Isotope("P31", 15, 31, 30.97376*g/mole); - - P = new G4Element("Phosphorus", "P", 1); - P->AddIsotope(P31, 100.*perCent); - - S32 = new G4Isotope("S32", 16, 32, 31.9721*g/mole); - /*S33 = new G4Isotope("S33", 16, 33, 32.9715*g/mole); - S34 = new G4Isotope("S34", 16, 34, 33.9679*g/mole); - S36 = new G4Isotope("S36", 16, 36, 35.9679*g/mole);*/ - - S = new G4Element("Sulphur", "S", 1); - S->AddIsotope(S32, 100.0*perCent); - /*S->AddIsotope(S33, 0.76*perCent); - S->AddIsotope(S34, 4.29*perCent); - S->AddIsotope(S36, 0.02*perCent);*/ - - //make chromium isotopes and element - Cr50 = new G4Isotope("Cr50", 24, 50, 49.9460422*g/mole); - Cr52 = new G4Isotope("Cr52", 24, 52, 51.9405075*g/mole); - Cr53 = new G4Isotope("Cr53", 24, 53, 52.9406494*g/mole); - Cr54 = new G4Isotope("Cr54", 24, 54, 53.9388804*g/mole); - - Cr = new G4Element("Chromium", "Cr", 4); - Cr->AddIsotope(Cr50, 4.345*perCent); - Cr->AddIsotope(Cr52, 83.789*perCent); - Cr->AddIsotope(Cr53, 9.501*perCent); - Cr->AddIsotope(Cr54, 2.365*perCent); - - //make chromium isotopes and element - Mn55 = new G4Isotope("Mn55", 25, 55, 54.9380*g/mole); - - Mn = new G4Element("Manganese", "Mn", 1); - Mn->AddIsotope(Mn55, 100.*perCent); - - //make iron isotopes and element - Fe54 = new G4Isotope("Fe54", 26, 54, 53.9396105*g/mole); - Fe56 = new G4Isotope("Fe56", 26, 56, 55.9349375*g/mole); - Fe57 = new G4Isotope("Fe57", 26, 57, 56.9353940*g/mole); - Fe58 = new G4Isotope("Fe58", 26, 58, 57.9332756*g/mole); - - Fe = new G4Element("Iron", "Fe", 4); - Fe->AddIsotope(Fe54, 5.845*perCent); - Fe->AddIsotope(Fe56, 91.754*perCent); - Fe->AddIsotope(Fe57, 2.119*perCent); - Fe->AddIsotope(Fe58, 0.282*perCent); - - //make nickel isotopes and element - Ni58 = new G4Isotope("Ni58", 28, 58, 57.9353429*g/mole); - Ni60 = new G4Isotope("Ni60", 28, 60, 59.9307864*g/mole); - Ni61 = new G4Isotope("Ni61", 28, 61, 60.9310560*g/mole); - Ni62 = new G4Isotope("Ni62", 28, 62, 61.9283451*g/mole); - Ni64 = new G4Isotope("Ni64", 28, 64, 63.9279660*g/mole); - - Ni = new G4Element("Nickel", "Ni", 5); - Ni->AddIsotope(Ni58, 68.0769*perCent); - Ni->AddIsotope(Ni60, 26.2231*perCent); - Ni->AddIsotope(Ni61, 1.1399*perCent); - Ni->AddIsotope(Ni62, 3.6345*perCent); - Ni->AddIsotope(Ni64, 0.9256*perCent); - - //make niobium isotopes and element - Nb93 = new G4Isotope("Nb93", 41, 93, 92.9063781*g/mole); - - Nb = new G4Element("Niobium", "Nb", 1); - Nb->AddIsotope(Nb93, 100*perCent); - - Y89 = new G4Isotope("Y89", 39, 89, 99.9058*g/mole); - - Y = new G4Element("Yttrium", "Y", 1); - Y->AddIsotope(Y89, 100.*perCent); - - //make Zirconium isotopes and element - Mo92 = new G4Isotope("Mo92", 42, 92, 91.9068*g/mole); - Mo94 = new G4Isotope("Mo94", 42, 94, 93.9051*g/mole); - Mo95 = new G4Isotope("Mo95", 42, 95, 94.9058*g/mole); - Mo96 = new G4Isotope("Mo96", 42, 96, 95.9047*g/mole); - Mo97 = new G4Isotope("Mo97", 42, 97, 96.9060*g/mole); - Mo98 = new G4Isotope("Mo98", 42, 98, 97.9054*g/mole); - Mo100 = new G4Isotope("Mo100", 42, 100, 99.9075*g/mole); - - Mo = new G4Element("Molybdenum", "Mo", 7); - Mo->AddIsotope(Mo92, 14.77*perCent); - Mo->AddIsotope(Mo94, 9.23*perCent); - Mo->AddIsotope(Mo95, 15.9*perCent); - Mo->AddIsotope(Mo96, 16.68*perCent); - Mo->AddIsotope(Mo97, 9.56*perCent); - Mo->AddIsotope(Mo98, 24.19*perCent); - Mo->AddIsotope(Mo100, 9.67*perCent); - - Sn112 = new G4Isotope("Sn112", 50, 112, 111.9048*g/mole); - Sn114 = new G4Isotope("Sn114", 50, 114, 113.9028*g/mole); - Sn115 = new G4Isotope("Sn115", 50, 115, 114.9033*g/mole); - Sn116 = new G4Isotope("Sn116", 50, 116, 115.9017*g/mole); - Sn117 = new G4Isotope("Sn117", 50, 117, 116.9030*g/mole); - Sn118 = new G4Isotope("Sn118", 50, 118, 117.9016*g/mole); - Sn119 = new G4Isotope("Sn119", 50, 119, 118.9033*g/mole); - Sn120 = new G4Isotope("Sn120", 50, 120, 119.9022*g/mole); - Sn122 = new G4Isotope("Sn122", 50, 122, 121.9034*g/mole); - Sn124 = new G4Isotope("Sn124", 50, 124, 123.9053*g/mole); - - Sn = new G4Element("Tin", "Sn", 10); - Sn->AddIsotope(Sn112, 0.97*perCent); - Sn->AddIsotope(Sn114, 0.66*perCent); - Sn->AddIsotope(Sn115, 0.34*perCent); - Sn->AddIsotope(Sn116, 14.54*perCent); - Sn->AddIsotope(Sn117, 7.68*perCent); - Sn->AddIsotope(Sn118, 24.22*perCent); - Sn->AddIsotope(Sn119, 8.59*perCent); - Sn->AddIsotope(Sn120, 32.58*perCent); - Sn->AddIsotope(Sn122, 4.63*perCent); - Sn->AddIsotope(Sn124, 5.79*perCent); - - //make Zirconium isotopes and element - Zr90 = new G4Isotope("Zr90", 40, 90, 89.9047044*g/mole); - Zr91 = new G4Isotope("Zr91", 40, 91, 90.9056458*g/mole); - Zr92 = new G4Isotope("Zr92", 40, 92, 91.9050408*g/mole); - Zr94 = new G4Isotope("Zr94", 40, 94, 93.9063152*g/mole); - Zr96 = new G4Isotope("Zr96", 40, 96, 95.9082734*g/mole); - - Zr = new G4Element("Zirconium", "Zr", 5); - Zr->AddIsotope(Zr90, 51.45*perCent); - Zr->AddIsotope(Zr91, 11.22*perCent); - Zr->AddIsotope(Zr92, 17.15*perCent); - Zr->AddIsotope(Zr94, 17.38*perCent); - Zr->AddIsotope(Zr96, 2.80*perCent); - - Th232 = new G4Isotope("Th232", 90, 232, 232.0381*g/mole); - - Th = new G4Element("Thorium", "Th", 1); - Th->AddIsotope(Th232, 100.*perCent); - - //make Plutonium isotopes and element - Pu238 = new G4Isotope("Pu238", 94, 238, 238.0496*g/mole); - Pu239 = new G4Isotope("Pu239", 94, 239, 239.0522*g/mole); - Pu240 = new G4Isotope("Pu240", 94, 240, 240.0538*g/mole); - Pu241 = new G4Isotope("Pu241", 94, 241, 241.0569*g/mole); - Pu242 = new G4Isotope("Pu242", 94, 242, 242.0587*g/mole); - -// fixed the isotope compositon so that it is interms of abundance instead of weight percentage - Pu = new G4Element("Plutonium", "Pu", 5); - Pu->AddIsotope(Pu238, 2.77*perCent); - Pu->AddIsotope(Pu239, 52.11*perCent); - Pu->AddIsotope(Pu240, 22.93*perCent); - Pu->AddIsotope(Pu241, 15.15*perCent); - Pu->AddIsotope(Pu242, 7.03*perCent); - - // Create the world material - World = new G4Material("Galactic", 1, 1, 1.e-25*g/cm3, kStateGas, - 2.73*kelvin, 3.e-18*pascal); - - // Create H20 material - H2O = new G4Material("LightWater", 1.*g/cm3, 2, kStateLiquid); - H2O->AddElement(H,2); - H2O->AddElement(Oxygen,1); - - // Create D20 material - D2O = new G4Material("HeavyWater", 1.1*g/cm3, 2, kStateLiquid); - D2O->AddElement(D,2); - D2O->AddElement(Oxygen,1); - - - // Create Coolant - Coolant = new G4Material("Coolant", coolantDensity, 1, kStateLiquid, coolantTemp); - Coolant->AddMaterial(H2O, 100*perCent); - - //Create Moderator - Moderator = new G4Material("Moderator", moderatorDensity, 2, kStateLiquid, - moderatorTemp); - Moderator->AddMaterial(D2O,99.833*perCent); - Moderator->AddMaterial(H2O,0.167*perCent); - - //Create Moderator - ExelLiner = new G4Material("ExelLiner", 1, 4, kStateSolid, - 1); - ExelLiner->AddElement(Sn,3.5*perCent); - ExelLiner->AddElement(Mo,0.8*perCent); - ExelLiner->AddElement(Nb,0.8*perCent); - ExelLiner->AddElement(Zr,94.9*perCent); - - ZircSteel = new G4Material("ZircSteel", 1, 10, kStateSolid, - 1); - ZircSteel->AddElement(C,0.034*perCent); - ZircSteel->AddElement(Si,0.51*perCent); - ZircSteel->AddElement(Mn,0.74*perCent); - ZircSteel->AddElement(P,0.016*perCent); - ZircSteel->AddElement(S,0.002*perCent); - ZircSteel->AddElement(Ni,20.82*perCent); - ZircSteel->AddElement(Cr,25.04*perCent); - ZircSteel->AddElement(Fe,51.738*perCent); - ZircSteel->AddElement(Mo,0.51*perCent); - ZircSteel->AddElement(Zr,0.59*perCent); - - ZircHydrid = new G4Material("ZircHydrid", 1, 2, kStateSolid, 1); - ZircHydrid->AddElement(Zr,98.26*perCent); - ZircHydrid->AddElement(H,1.74*perCent); - - Insulator = new G4Material("Insulator", insulatorDensity, 3, kStateSolid, insulatorTemp); - Insulator->AddElement(Zr,66.63*perCent); - Insulator->AddElement(Y,7.87*perCent); - Insulator->AddElement(Oxygen,25.5*perCent); - - //Create Fuel - OuterFuel = new G4Material("OuterFuel", outerFuelDensity, 3, kStateSolid, outerFuelTemp); - OuterFuel->AddElement(Oxygen,12.08*perCent); - OuterFuel->AddElement(Pu,10.59*perCent); - OuterFuel->AddElement(Th,77.34*perCent); - - InnerFuel = new G4Material("InnerFuel", innerFuelDensity, 3, kStateSolid, innerFuelTemp); - InnerFuel->AddElement(Oxygen,12.07*perCent); - InnerFuel->AddElement(Pu,13.23*perCent); - InnerFuel->AddElement(Th,74.7*perCent); - - OutSheathe = new G4Material("OutSheathe", outSheatheDensity, 1, kStateSolid, outSheatheTemp); - OutSheathe->AddMaterial(ZircSteel,100*perCent); - - InSheathe = new G4Material("InSheathe", inSheatheDensity, 1, kStateSolid, inSheatheTemp); - InSheathe->AddMaterial(ZircSteel,100*perCent); - - Liner = new G4Material("Liner", linerDensity, 1, kStateSolid, linerTemp); - Liner->AddMaterial(ZircSteel,100*perCent); - - FlowTube = new G4Material("FlowTube", flowTubeDensity, 1, kStateSolid, flowTubeTemp); - FlowTube->AddMaterial(ZircSteel,100*perCent); - - PressTube = new G4Material("PressTube", pressTubeDensity, 1, kStateSolid, pressTubeTemp); - PressTube->AddMaterial(ExelLiner,100*perCent); - - OutLiner = new G4Material("OutLiner", outLinerDensity, 1, kStateSolid, outLinerTemp); - OutLiner->AddMaterial(ExelLiner,100*perCent); - - CentralCoolant = new G4Material("CentralCoolant", centralCoolantDensity, 1, kStateLiquid, centralCoolantTemp); - CentralCoolant->AddMaterial(Coolant, 100*perCent); - - - // Add materials to the map indexed by either ZA (format ZZAAA or ZZ) - // For composite materials: world is 0, heavy water is 1, UHW is 2 - matMap["Galactic"] = World; - matMap["Moderator"] = Moderator; - matMap["PressTube"] = PressTube; - matMap["OutLiner"] = OutLiner; - matMap["Insulator"] = Insulator; - matMap["Liner"] = Liner; - matMap["Coolant"] = Coolant; - matMap["OutSheathe"] = OutSheathe; - matMap["InSheathe"] = InSheathe; - matMap["OuterFuel"] = OuterFuel; - matMap["InnerFuel"] = InnerFuel; - matMap["FlowTube"] = FlowTube; - matMap["CentralCoolant"] = CentralCoolant; - - matChanged = false; - - return; -} diff --git a/G4STORK/src/SLOWPOKEConstructor.cc b/G4STORK/src/SLOWPOKEConstructor.cc deleted file mode 100755 index 3006508b..00000000 --- a/G4STORK/src/SLOWPOKEConstructor.cc +++ /dev/null @@ -1,1104 +0,0 @@ - -#include "SLOWPOKEConstructor.hh" - -SLOWPOKEConstructor::SLOWPOKEConstructor() -: StorkVWorldConstructor(), ZirconiumLogical1(0), ZirconiumLogical2(0), ZirconiumLogical3(0), AirGapLogical(0), -FuelRodLogical(0), ReflectorLogical(0), D2OContainerLogical(0),D2OLogical(0), -contRodZirLogical(0), contRodAlumLogical(0), contRodCadLogical(0), contRodCentLogical(0), -insAlumLogical(0), insBeamLogical(0), outSmallAlumLogical(0), outLargeAlumLogical(0), cadLinLogical(0), -outSmallBeamLogical(0), outLargeBeamLogical(0), alumShellLogical(0), cellLogical(0) -{ - // Set default member variables (from file or default values) - //Rod in (20.66cm - Rod In), (0.00cm - Rod Out) - ControlRodPosition = 0.00*cm ; - - // ControlRodPosition = 20.66*cm ; - - //Set initial T.H. properties of fuel and geometry. - FuelRadius = 0.2064*cm; - FuelTemp = (25 + 273.15)*kelvin; - FuelDensity = 10.6*g/cm3; - - //Initialize property vectors. - for(G4int i = 0; i<34; i++){ - FuelDensities[i] = FuelDensity; - FuelTemperatures[i] = FuelTemp; - FuelRadii[i] = FuelRadius; - } - - - // Set up variable property map - variablePropMap[MatPropPair(controlrod,position)] = &ControlRodPosition; - variablePropMap[MatPropPair(fuel,temperature)] = &FuelTemp; - variablePropMap[MatPropPair(moderator,temperature)] = &moderatorTemp; - -} - -SLOWPOKEConstructor::~SLOWPOKEConstructor() -{ - // Delete visualization attributes - if (ZirconiumAtt1) - delete ZirconiumAtt1; - if (ZirconiumAtt2) - delete ZirconiumAtt2; - if (ZirconiumAtt3) - delete ZirconiumAtt3; - if (AirGapAtt) - delete AirGapAtt; - if (FuelRodAtt) - delete FuelRodAtt; - if (ReflectorAtt) - delete ReflectorAtt; - if (D2OContainerAtt) - delete D2OContainerAtt; - if (D2OAtt) - delete D2OAtt; - if (contRodZirVisAtt) - delete contRodZirVisAtt; - if (contRodAlumVisAtt) - delete contRodAlumVisAtt; - if (contRodCadVisAtt) - delete contRodCadVisAtt; - if (contRodCentVisAtt) - delete contRodCentVisAtt; - if (insAlumVisAtt) - delete insAlumVisAtt; - if (insBeamVisAtt) - delete insBeamVisAtt; - if (outSmallAlumVisAtt) - delete outSmallAlumVisAtt; - if (outLargeAlumVisAtt) - delete outLargeAlumVisAtt; - if (cadLinTubeVisAtt) - delete cadLinTubeVisAtt; - if (outSmallBeamVisAtt) - delete outSmallBeamVisAtt; - if (outLargeBeamVisAtt) - delete outLargeBeamVisAtt; - if (alumShellVisAtt) - delete alumShellVisAtt; - if (cellVisAtt) - delete cellVisAtt; - - //if(FissionMap) { delete FissionMap; } -} - - -// ConstructWorld() -// Construct the geometry and materials of the Guillaume Reactor. -G4VPhysicalVolume* SLOWPOKEConstructor::ConstructWorld() -{ - G4SolidStore* theSolids = G4SolidStore::GetInstance(); - - // Set static dimensions of all the geometries - // Note the format for cylinder dimensions is (inner radius, outer radius, height) - - // Reactor pool dimensions - reactorDim = G4ThreeVector(0., 133.0*cm, 564.0*cm); - - // World dimensions - G4double buffer = 1.0*cm; - encWorldDim = 2.0*G4ThreeVector(reactorDim[1]+buffer,reactorDim[1]+buffer, reactorDim[2]/2+buffer); - - // Reflector dimensions - G4double refAnnDim[3] = {11.049*cm, 21.2344*cm, 22.748*cm}; - G4double refBottomDim[3] = {0.0*cm, 16.113125*cm, 10.16*cm}; - G4double refTopDim[3] = {1.3890625*cm, 12.065*cm, 0.15875*cm}; - - // D2O colum container and heavy water - G4double D20ContainerDim[3] = {21.2344*cm, 30*cm, 22.748*cm}; - G4double D20Dim[3] = {22.2344*cm, 29*cm, 20.6975*cm}; - - // Beamtube dimensions - G4double smallBTubeDim[3] = {0.0*cm, 1.40208*cm, 515.332*cm}; - G4double smallLongBTubeDim[3] = {0.0*cm, 1.40208*cm, 522.332*cm}; - G4double largeBTubeDim[3] = {0.0*cm, 1.6*cm, 515.332*cm}; - - // Aluminum tube dimensions - G4double smallAlumTubeDim[3] = {0.0*cm, 1.56718*cm, 515.332*cm}; - G4double smallLongAlumTubeDim[3] = {0.0*cm, 1.56718*cm, 522.332*cm}; - G4double largeAlumTubeDim[3] = {0.0*cm, 1.905*cm, 515.332*cm}; - G4double alumTubePos[3]={14.56182*cm, 0.4*CLHEP::pi, 0.}; - G4double outAlumTubePos[3]={24.0*cm, 0.4*CLHEP::pi, 0.2*CLHEP::pi}; - - // Cadmium lining - G4double cadLinTubeDim[3] = {1.56718*cm, 1.61798*cm, 22.748*cm}; - - // Aluminium Reactor Shell - G4double alumShellTubeDim[3] = {30.0*cm, 31.0*cm, 541.0*cm}; - G4double alumShellPlateDim[3] = {0.0*cm, 31.0*cm, 1*cm}; - - // Control Rod (Aluminum shell, cadmium rod and air gap) - G4double contRodCentTubeDim[3] = {0.0*cm, 0.09652*cm, 24.76*cm}; - G4double contRodCadTubeDim[3] = {0.0*cm, 0.14732*cm, 24.76*cm}; - G4double contRodAlumTubeDim[3] = {0.0*cm, 0.62357*cm, 40.64*cm}; - G4double contRodZirTubeDim[3] = {1.229*cm, 1.331*cm, 23.2335*cm}; - - /* Begining Of Reactor Core Dimensions */ - // Zirconium lower/upper plate dimensions - G4double LowerZrDim[5] = {1.331*cm, 11.049*cm, 0.279*cm, CLHEP::pi/3, CLHEP::pi/3}; - G4double UpperZrDim[5] = {LowerZrDim[0], LowerZrDim[1], LowerZrDim[2], LowerZrDim[3], LowerZrDim[4]}; - - // Zirconium holes lower/upper plate - G4double WaterHolesLowerZrDim[3] = {0., 0.262*cm, LowerZrDim[2]+1*mm}; - G4double WaterHolesUpperZrDim[3] = {0., 0.19*cm, UpperZrDim[2]+1*mm}; - G4double PinHolesDim[3] = {0., 0.15*cm, LowerZrDim[2]+1*mm}; - - // Hole Position lower/upper plate - G4double holePat[3]= {0.637286*cm, CLHEP::pi/3, 5*CLHEP::pi/6}; - - // Zirconium Rod/Air Gap/Fuel Dimensions - G4double ZirconiumRodDim[3] = {0., 0.262*cm, 23.3805*cm}; - G4double AirGapDim[3] = {0., 0.212*cm, 23.1105*cm}; - G4double FuelRodDim[3] = {0., 0.2064*cm, 22.6975*cm}; - SetFuelDimensions(G4ThreeVector(FuelRodDim[0],FuelRodDim[1],FuelRodDim[2])); - - // Top Zirconium rod - G4double Center1[2] = {(3-12)*0.551833696*cm, (12-3)*0.955804*cm}; - // Buttom Zirconium rod - G4double Center2[2] = {(10-12)*0.551833696*cm, (12-10)*0.955804*cm}; - - /* End Of Reactor Core Dimensions */ - // Lattice Matrix - G4double latticeMat[25][25] ={{7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7}, - {7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7}, - {7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 9, 8, 9, 8, 9, 8, 8, 7, 7, 7}, - {7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 9, 8, 9, 9, 8, 8, 9, 9, 8, 9, 8, 7, 7}, - {7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 9, 8, 9, 8, 9, 8, 9, 8, 8, 8, 7, 7}, - {7, 7, 7, 7, 7, 7, 7, 7, 8, 9, 9, 9, 9, 8, 8, 9, 9, 8, 8, 9, 9, 9, 9, 8, 7}, - {7, 7, 7, 7, 7, 7, 7, 8, 8, 9, 8, 8, 9, 8, 9, 8, 9, 8, 9, 8, 8, 9, 8, 8, 7}, - {7, 7, 7, 7, 7, 7, 8, 9, 8, 9, 8, 8, 8, 9, 8, 8, 9, 8, 8, 8, 9, 8, 9, 8, 7}, - {7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 9, 8, 9, 9, 9, 9, 8, 8, 8, 8, 7}, - {7, 7, 7, 7, 7, 9, 9, 9, 9, 8, 8, 8, 8, 9, 9, 8, 8, 8, 8, 9, 9, 9, 9, 7, 7}, - {7, 7, 7, 7, 8, 9, 8, 8, 9, 8, 9, 9, 9, 8, 9, 9, 9, 8, 9, 8, 8, 9, 8, 7, 7}, - {7, 7, 7, 8, 8, 9, 8, 8, 9, 8, 9, 8, 9, 9, 8, 9, 8, 9, 8, 8, 9, 8, 8, 7, 7}, - {7, 7, 7, 8, 8, 9, 9, 8, 9, 8, 8, 9, 7, 9, 8, 8, 9, 8, 9, 9, 8, 8, 7, 7, 7}, - {7, 7, 8, 8, 9, 8, 8, 9, 8, 9, 8, 9, 9, 8, 9, 8, 9, 8, 8, 9, 8, 8, 7, 7, 7}, - {7, 7, 8, 9, 8, 8, 9, 8, 9, 9, 9, 8, 9, 9, 9, 8, 9, 8, 8, 9, 8, 7, 7, 7, 7}, - {7, 9, 9, 9, 9, 9, 8, 8, 8, 8, 9, 9, 8, 8, 8, 8, 9, 9, 9, 9, 7, 7, 7, 7, 7}, - {7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 9, 8, 9, 9, 9, 9, 8, 8, 8, 8, 7, 7, 7, 7, 7}, - {7, 8, 9, 8, 9, 8, 8, 8, 9, 8, 8, 9, 8, 8, 8, 9, 8, 9, 8, 7, 7, 7, 7, 7, 7}, - {7, 8, 8, 9, 8, 8, 9, 8, 9, 8, 9, 8, 9, 8, 8, 9, 8, 8, 7, 7, 7, 7, 7, 7, 7}, - {7, 8, 9, 9, 9, 9, 8, 8, 9, 9, 8, 8, 9, 9, 9, 9, 8, 7, 7, 7, 7, 7, 7, 7, 7}, - {7, 7, 8, 8, 8, 9, 8, 9, 8, 9, 8, 9, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7}, - {7, 7, 8, 8, 8, 9, 9, 8, 8, 9, 9, 8, 9, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7}, - {7, 7, 7, 8, 8, 9, 8, 9, 8, 9, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7}, - {7, 7, 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7}, - {7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7}}; - - // Set up the materials (if necessary) - if(matChanged) - { - // Delete any existing materials - DestroyMaterials(); - // Create the materials - ConstructMaterials(); - } - - // Clean up volumes - G4GeometryManager::GetInstance()->OpenGeometry(); - G4PhysicalVolumeStore::GetInstance()->Clean(); - G4LogicalVolumeStore::GetInstance()->Clean(); - - - // Set up the solids if necessary - if(geomChanged) - { - // Clean up solids - G4SolidStore::GetInstance()->Clean(); - G4ThreeVector HolePos[6]; - for(G4int i=0; i<6; i++) - { - HolePos[i] = G4ThreeVector(holePat[0]*cos(holePat[2]+i*holePat[1]), holePat[0]*sin(holePat[2]+i*holePat[1]), 0.); - } - - // Create world solid - new G4Box("worldBox", encWorldDim[0]/2, encWorldDim[1]/2, encWorldDim[2]/2); - - // Create water pool - new G4Tubs("cellTube", 0., reactorDim[1], reactorDim[2]/2, 0., 2.0*CLHEP::pi); - - // Create aluminium shell - new G4Tubs("alumShellTube", alumShellTubeDim[0], alumShellTubeDim[1], alumShellTubeDim[2]/2, 0., 2.0*CLHEP::pi); - new G4Tubs("alumShellPlate", alumShellPlateDim[0], alumShellPlateDim[1], alumShellPlateDim[2]/2, 0., 2.0*CLHEP::pi); - new G4UnionSolid("alumShell", theSolids->GetSolid("alumShellPlate"), theSolids->GetSolid("alumShellTube"), 0, G4ThreeVector(0., 0., 271.*cm)); - - - // Create reflector solids - new G4Tubs("reflectTop", refTopDim[0], refTopDim[1], refTopDim[2]/2, 0., CLHEP::pi); - new G4Tubs("reflectAnnulus", refAnnDim[0], refAnnDim[1], refAnnDim[2]/2, 0., 2.0*CLHEP::pi); - new G4Tubs("reflectBottom", refBottomDim[0], refBottomDim[1], refBottomDim[2]/2, 0., 2.0*CLHEP::pi); - new G4UnionSolid("reflector0", theSolids->GetSolid("reflectAnnulus"), theSolids->GetSolid("reflectTop"), 0, G4ThreeVector(0., 0., 13.969375*cm)); - new G4UnionSolid("reflector", theSolids->GetSolid("reflector0"), theSolids->GetSolid("reflectBottom"), 0, G4ThreeVector(0., 0., -16.962*cm)); - - // D20 container - new G4Tubs("D2OContainer1", D20ContainerDim[0], D20ContainerDim[1], D20ContainerDim[2]/2, 1.570796327*rad, 4.712388980*rad); - new G4Tubs("D2OContainer2", 0., D20ContainerDim[1]+1.082*cm, D20ContainerDim[2]/2, 2.751192606*rad, 0.7808000945*rad); - new G4IntersectionSolid("D2OContainer", theSolids->GetSolid("D2OContainer1"), theSolids->GetSolid("D2OContainer2"), 0, G4ThreeVector(1.082*cm,0.,0.)); - new G4Tubs("D2O", D20Dim[0], D20Dim[1], D20Dim[2]/2, 2.751192606*rad, 0.7808000945*rad); - - // Create aluminium tube solids - new G4Tubs("smallAlumTube", smallAlumTubeDim[0], smallAlumTubeDim[1], smallAlumTubeDim[2]/2, 0., 2.0*CLHEP::pi); - new G4Tubs("smallLongAlumTube", smallLongAlumTubeDim[0], smallLongAlumTubeDim[1], smallLongAlumTubeDim[2]/2, 0., 2.0*CLHEP::pi); - new G4Tubs("largeAlumTube", largeAlumTubeDim[0], largeAlumTubeDim[1], largeAlumTubeDim[2]/2, 0., 2.0*CLHEP::pi); - - // Create beam tube solids - new G4Tubs("smallBeamTube", smallBTubeDim[0], smallBTubeDim[1], smallBTubeDim[2]/2, 0., 2.0*CLHEP::pi); - new G4Tubs("smallLongBeamTube", smallLongBTubeDim[0], smallLongBTubeDim[1], smallLongBTubeDim[2]/2, 0., 2.0*CLHEP::pi); - new G4Tubs("cadLinTube", cadLinTubeDim[0], cadLinTubeDim[1], cadLinTubeDim[2]/2, 0., 2.0*CLHEP::pi); - new G4Tubs("largeBeamTube", largeBTubeDim[0], largeBTubeDim[1], largeBTubeDim[2]/2, 0., 2.0*CLHEP::pi); - - // Create control rod solids - new G4Tubs("contRodCentTube", contRodCentTubeDim[0], contRodCentTubeDim[1], contRodCentTubeDim[2]/2, 0., 2.0*CLHEP::pi); - new G4Tubs("contRodCadTube", contRodCadTubeDim[0], contRodCadTubeDim[1], contRodCadTubeDim[2]/2, 0., 2.0*CLHEP::pi); - new G4Tubs("contRodAlumTube", contRodAlumTubeDim[0], contRodAlumTubeDim[1], contRodAlumTubeDim[2]/2, 0., 2.0*CLHEP::pi); - new G4Tubs("contRodZirTube", contRodZirTubeDim[0], contRodZirTubeDim[1], contRodZirTubeDim[2]/2, 0., 2.0*CLHEP::pi); - - // Create zirconium lower and upper plate - new G4Tubs("LowerZrTub", LowerZrDim[0], LowerZrDim[1], LowerZrDim[2]/2, LowerZrDim[3], LowerZrDim[4]); - new G4Tubs("UpperZrTub", UpperZrDim[0], UpperZrDim[1], UpperZrDim[2]/2, UpperZrDim[3], UpperZrDim[4]); - - // Water holes lower and upper Zr plate - new G4Tubs("WaterHolesLower", WaterHolesLowerZrDim[0], WaterHolesLowerZrDim[1], WaterHolesLowerZrDim[2]/2, 0, 2.0*CLHEP::pi); - new G4Tubs("WaterHolesUpper", WaterHolesUpperZrDim[0], WaterHolesUpperZrDim[1], WaterHolesUpperZrDim[2]/2, 0, 2.0*CLHEP::pi); - - // Pin holes lower Zr plate - new G4Tubs("PinHolesLower", PinHolesDim[0], PinHolesDim[1], PinHolesDim[2]/2, 0, 2.0*CLHEP::pi); - - // Zirconium Rods - new G4Tubs("ZirconiumRod", ZirconiumRodDim[0], ZirconiumRodDim[1], ZirconiumRodDim[2]/2+1*mm, 0, 2.0*CLHEP::pi); - new G4Tubs("AirGapRod", AirGapDim[0], AirGapDim[1], AirGapDim[2]/2, 0, 2.0*CLHEP::pi); - - std::stringstream name; - - for(G4int i = 0; i<34; i++){ - name.str(""); - name << "FuelRod" << i ; - new G4Tubs(name.str(), FuelRodDim[0], FuelRadii[i], FuelRodDim[2]/2, 0, 2.0*CLHEP::pi); - } - - - // These list will be used to store all the holes solid and position in - // the upper grid, and lower grid. Also, the zirconium rods to be added - // and removed are kept track of. In a list containing a vector pointing - // to the center of the solid and a pointer to the solid itself. - solidList *theUpperHoles = new solidList(); - solidList *theLowerHoles = new solidList(); - solidList *theZirconiumMinus = new solidList(); - solidList *theZirconiumRods = new solidList(); - - // neighbour is used to keep track of the holes that were previously add so - // that no overlap takes place - G4bool *neighbour; - for(G4int i=1; i<24; i++) - { - for(G4int j=1; j<24; j++) - { - if(latticeMat[i][j] != 7) - { - // Center sotres the x and y coordinate of the lattice cell that is being tracked. - G4double Center[2] = {((i-12)*0.551833696+(j-12)*1.103632018)*cm, (12-i)*0.955804*cm}; - if(latticeMat[i-1][j] != 7 && latticeMat[i][j-1] != 7) - { - G4bool DUMMY[6] = {0,0,1,1,1,0}; - neighbour = DUMMY; - } - else if(latticeMat[i-1][j] != 7) - { - G4bool DUMMY[6] = {0,1,1,1,1,0}; - neighbour = DUMMY; - } - else if(latticeMat[i][j-1] != 7) - { - G4bool DUMMY[6] = {0,0,1,1,1,1}; - neighbour = DUMMY; - } - else - { - G4bool DUMMY[6] = {1,1,1,1,1,1}; - neighbour = DUMMY; - } - - // Once the holes not added have been determined the program goes through and - // adds only the holes that are inside the pie slice that we want to create - for(G4int k = 1; k<6; k++) - { - if(neighbour[k]) - { - G4double x = HolePos[k].getX()+Center[0], y = HolePos[k].getY()+Center[1]; - G4double radius = sqrt(x*x+y*y); - if(radius+WaterHolesLowerZrDim[1] < refAnnDim[0] && radius-WaterHolesLowerZrDim[1] > contRodZirTubeDim[1] - && x-WaterHolesLowerZrDim[1] < radius*cos(LowerZrDim[3]) - && x+WaterHolesLowerZrDim[1] > radius*cos(LowerZrDim[3]+LowerZrDim[4]) && y > 0) - { - theLowerHoles->push_back(std::make_pair(theSolids->GetSolid("WaterHolesLower"), G4ThreeVector(x, y, 0.))); - } - if(radius+WaterHolesUpperZrDim[1] < refAnnDim[0] && radius-WaterHolesUpperZrDim[1] > contRodZirTubeDim[1] - && x-WaterHolesUpperZrDim[1] < radius*cos(LowerZrDim[3]) - && x+WaterHolesUpperZrDim[1] > radius*cos(LowerZrDim[3]+LowerZrDim[4]) && y > 0) - { - theUpperHoles->push_back(std::make_pair(theSolids->GetSolid("WaterHolesUpper"), G4ThreeVector(x, y, 0.))); - } - } - } - - // If the material number is 9 then no rod is added, but a pin hole is added to the lower grid - if(latticeMat[i][j] == 9) - { - G4double x = Center[0], y = Center[1]; - G4double radius = sqrt(x*x+y*y); - if(radius > contRodZirTubeDim[1] && x-PinHolesDim[1] < radius*cos(LowerZrDim[3]) - && x+PinHolesDim[1] > radius*cos(LowerZrDim[3]+LowerZrDim[4]) && y > 0) - { - //G4cout << "x:" << x << "y:" << y; - theLowerHoles->push_back(std::make_pair(theSolids->GetSolid("PinHolesLower"), G4ThreeVector(x, y, 0.))); - } - } - - // If the material number is 8, then a zirconium rod is added - else - { - G4double x = Center[0], y = Center[1]; - G4double radius = sqrt(x*x+y*y); - if(x+ZirconiumRodDim[1] < radius*cos(LowerZrDim[3]) && x+ZirconiumRodDim[1] > radius*cos(LowerZrDim[3]+LowerZrDim[4]) && y > 0) - { - theZirconiumRods->push_back(std::make_pair(theSolids->GetSolid("ZirconiumRod"), G4ThreeVector(x, y, 0))); - } - else if(x-ZirconiumRodDim[1] < radius*cos(LowerZrDim[3]) && x-ZirconiumRodDim[1] > radius*cos(LowerZrDim[3]+LowerZrDim[4]) && y > 0) - { - theZirconiumMinus->push_back(std::make_pair(theSolids->GetSolid("ZirconiumRod"), G4ThreeVector(x, y, 0))); - } - } - } - } - } - - - - // First the union of the holes in the lower plate is formed. - StorkUnion* TheSolid = new StorkUnion(theLowerHoles); - solidPos Temp1 = TheSolid->GetUnionSolid("LowerZrHoles"); - // The holes are then substracted from the lower grid. - new G4SubtractionSolid("LowerZirconiumPlate1/6", theSolids->GetSolid("LowerZrTub"), Temp1.first, 0, Temp1.second); - delete TheSolid; - - // The union of the holes on the top grid is taken - TheSolid = new StorkUnion(theUpperHoles); - Temp1 = TheSolid->GetUnionSolid("UpperZrHoles"); - // The holes are then substracted from upper grid - new G4SubtractionSolid("UpperZirconiumPlate1/6", theSolids->GetSolid("UpperZrTub"), Temp1.first, 0, Temp1.second); - delete TheSolid; - - - // Finaly the upper grid is added to the lower grid both allready have their holes - new G4UnionSolid("ZirconiumWithoutRods1/6", theSolids->GetSolid("LowerZirconiumPlate1/6"), theSolids->GetSolid("UpperZirconiumPlate1/6"), 0, G4ThreeVector(0.,0., 22.5*cm)); - - // The Zr rod to be substracted union is now created - TheSolid = new StorkUnion(theZirconiumMinus); - Temp1 = TheSolid->GetUnionSolid("UpperZrHoles"); - // The rods are then substracted from the upper and the lower plates - new G4SubtractionSolid("ZirconiumWithoutRodsMinus1/6", theSolids->GetSolid("ZirconiumWithoutRods1/6"), Temp1.first, 0, Temp1.second+G4ThreeVector(0., 0., (ZirconiumRodDim[2]+LowerZrDim[2]-1*mm)/2)); - delete TheSolid; - - // The Zr rod to be added are now unionized - TheSolid = new StorkUnion(theZirconiumRods); - Temp1 = TheSolid->GetUnionSolid("ZrTubs"); - // The Zr union is added to the lower plate and upper plate - new G4UnionSolid("Zirconium1/6-", theSolids->GetSolid("ZirconiumWithoutRodsMinus1/6"), Temp1.first, 0, Temp1.second+G4ThreeVector(0., 0., (ZirconiumRodDim[2]+LowerZrDim[2]-1*mm)/2)); - delete TheSolid; - - - - /* - There are three pie slices to be created all with minor differences (one added rod, one missing rod). - The Zirconium1/6- solid is the base for all of the grids, but the needed extra rods are added in the - following section. - */ - - // First pie slice of the reactor core - new G4SubtractionSolid("Zirconium1/6", theSolids->GetSolid("Zirconium1/6-"), theSolids->GetSolid("ZirconiumRod"), 0, G4ThreeVector(-Center1[0], Center1[1], (ZirconiumRodDim[2]+LowerZrDim[2]-1*mm)/2)); - - // Second pie slice of the reactor core - new G4UnionSolid("Zirconium2/6+", theSolids->GetSolid("Zirconium1/6-"), theSolids->GetSolid("ZirconiumRod"), 0, G4ThreeVector(Center1[0], Center1[1], (ZirconiumRodDim[2]+LowerZrDim[2]-1*mm)/2)); - new G4UnionSolid("Zirconium2/6", theSolids->GetSolid("Zirconium2/6+"), theSolids->GetSolid("ZirconiumRod"), 0, G4ThreeVector(Center2[0], Center2[1], (ZirconiumRodDim[2]+LowerZrDim[2]-1*mm)/2)); - - // Third pie slice of the reactor core - new G4UnionSolid("Zirconium3/6+", theSolids->GetSolid("Zirconium1/6-"), theSolids->GetSolid("ZirconiumRod"), 0, G4ThreeVector(Center1[0], Center1[1], (ZirconiumRodDim[2]+LowerZrDim[2]-1*mm)/2)); - new G4SubtractionSolid("Zirconium3/6-", theSolids->GetSolid("Zirconium3/6+"), theSolids->GetSolid("ZirconiumRod"), 0, G4ThreeVector(-Center1[0], Center1[1], (ZirconiumRodDim[2]+LowerZrDim[2]-1*mm)/2)); - new G4SubtractionSolid("Zirconium3/6", theSolids->GetSolid("Zirconium3/6-"), theSolids->GetSolid("ZirconiumRod"), 0, G4ThreeVector(-Center2[0], Center2[1], (ZirconiumRodDim[2]+LowerZrDim[2]-1*mm)/2)); - geomChanged = false; - } - // Position vector - G4ThreeVector holePos; - - // Create world volume - worldLogical = new G4LogicalVolume(theSolids->GetSolid("worldBox"), matMap["Galactic"],"worldLogical"); - worldPhysical = new G4PVPlacement(0, G4ThreeVector(0,0,0), worldLogical, "worldPhysical", 0, 0, 0); - - // Create the lattice cell (moderator) volume - cellLogical = new G4LogicalVolume(theSolids->GetSolid("cellTube"),matMap["H2O"],"cellLogical"); - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), cellLogical,"cellPhysical",worldLogical,0,0); - - // Create aluminium shell - alumShellLogical = new G4LogicalVolume(theSolids->GetSolid("alumShell"),matMap["AlAlloy1"],"alumShellLogical"); - new G4PVPlacement(0, G4ThreeVector(-30*cm,-30*cm,22.5*cm-reactorDim[2]/2), alumShellLogical,"alumShellPhysical",cellLogical,0,0); - - // Reflector Logical Volume is being created - ReflectorLogical = new G4LogicalVolume(theSolids->GetSolid("reflector"), matMap["Reflector"],"ReflectorLogical"); - new G4PVPlacement(0, G4ThreeVector(-30*cm,-30*cm, 53.042*cm-reactorDim[2]/2), ReflectorLogical, "ReflectorPhysical", cellLogical, 0, 0); - - // Outter Tubes - outSmallAlumLogical = new G4LogicalVolume(theSolids->GetSolid("smallLongAlumTube"),matMap["AlAlloy1"],"outAlumTubeLogical"); - holePos.set(outAlumTubePos[0]*cos(outAlumTubePos[1]*4+outAlumTubePos[2])-30*cm,-30*cm+outAlumTubePos[0]*sin(outAlumTubePos[1]*4+outAlumTubePos[2]),302.834*cm-reactorDim[2]/2); - new G4PVPlacement(0, holePos, outSmallAlumLogical,"outSmallAlumTubePhysical1", cellLogical,0,0); - holePos.set(-30*cm+outAlumTubePos[0]*cos(outAlumTubePos[1]*1+outAlumTubePos[2]),-30*cm+outAlumTubePos[0]*sin(outAlumTubePos[1]*1+outAlumTubePos[2]),302.834*cm-reactorDim[2]/2); - new G4PVPlacement(0, holePos, outSmallAlumLogical,"outSmallAlumTubePhysical2", cellLogical,0,0); - outLargeAlumLogical = new G4LogicalVolume(theSolids->GetSolid("largeAlumTube"),matMap["AlAlloy1"],"outAlumTubeLogical"); - holePos.set(-30*cm+outAlumTubePos[0]*cos(outAlumTubePos[2]),-30*cm+outAlumTubePos[0]*sin(outAlumTubePos[2]), 302.834*cm-reactorDim[2]/2); - new G4PVPlacement(0, holePos, outLargeAlumLogical,"outLargeAlumTubePhysical", cellLogical,0,0); - cadLinLogical = new G4LogicalVolume(theSolids->GetSolid("cadLinTube"),matMap["Cadmium"],"cadLinLogical"); - holePos.set(-30*cm+outAlumTubePos[0]*cos(outAlumTubePos[1]*3+outAlumTubePos[2]),-30*cm+outAlumTubePos[0]*sin(outAlumTubePos[1]*3+outAlumTubePos[2]),302.834*cm-reactorDim[2]/2); - new G4PVPlacement(0, holePos, cadLinLogical,"cadLinTube", cellLogical,0,0); - new G4PVPlacement(0, holePos, outSmallAlumLogical,"outSmallAlumTubePhysical3", cellLogical,0,0); - outSmallBeamLogical = new G4LogicalVolume(theSolids->GetSolid("smallLongBeamTube"),matMap["Air"],"outSmallBeamLogical"); - new G4PVPlacement(0, G4ThreeVector(0., 0., 0.), outSmallBeamLogical,"outSmallBeamTubePhysical",outSmallAlumLogical,0,0); - outLargeBeamLogical = new G4LogicalVolume(theSolids->GetSolid("largeBeamTube"),matMap["Air"],"outLargeBeamLogical"); - new G4PVPlacement(0, G4ThreeVector(0., 0., 0.), outLargeBeamLogical,"outLargeBeamTubePhysical",outLargeAlumLogical,0,0); - - // Inner Irradiation Tubes - insAlumLogical = new G4LogicalVolume(theSolids->GetSolid("smallAlumTube"),matMap["AlAlloy3"],"insAlumLogical"); - G4int copyNum=0; - for (G4int i=0; i<5; i++) - { - holePos.set((alumTubePos[0]*cos(alumTubePos[1]*i+alumTubePos[2])), (alumTubePos[0]*sin(alumTubePos[1]*i+alumTubePos[2])), 253.292*cm); - new G4PVPlacement(0, holePos, insAlumLogical,"insAlumTubePhysical", ReflectorLogical, copyNum, 0); - copyNum++; - } - - // The air is placed inside the irradiation tubes - insBeamLogical = new G4LogicalVolume(theSolids->GetSolid("smallBeamTube"),matMap["Air"],"insBeamLogical"); - new G4PVPlacement(0, G4ThreeVector(0., 0., 0.), insBeamLogical,"insBeamTubePhysical",insAlumLogical,0,0); - - // D20 Container - D2OContainerLogical = new G4LogicalVolume(theSolids->GetSolid("D2OContainer"), matMap["AlAlloy2"],"D2OContainerLogical"); - new G4PVPlacement(0, G4ThreeVector(0-30*cm, 0-30*cm, 53.042*cm-reactorDim[2]/2), D2OContainerLogical, "D2OPhysical", cellLogical, 0, 0); - D2OLogical = new G4LogicalVolume(theSolids->GetSolid("D2O"), matMap["D2O"],"D2OLogical"); - new G4PVPlacement(0, G4ThreeVector(0, 0, 0.25375*cm), D2OLogical, "D2OPhysical", D2OContainerLogical, 0, 0); - - // Creates the zirconium guide - contRodZirLogical = new G4LogicalVolume(theSolids->GetSolid("contRodZirTube"),matMap["Zirconium"], "contRodZirLogical"); - new G4PVPlacement(0, G4ThreeVector(0.-30*cm, 0.-30*cm, 53.02925*cm-reactorDim[2]/2), contRodZirLogical,"contRodZirPhysical",cellLogical,0,0); - - // Create the control rod - contRodAlumLogical = new G4LogicalVolume(theSolids->GetSolid("contRodAlumTube"),matMap["AlAlloy4"], "contRodAlumLogical"); - new G4PVPlacement(0, G4ThreeVector(0.-30*cm, 0.-30*cm, 82.14*cm-reactorDim[2]/2-ControlRodPosition), contRodAlumLogical,"contRodAlumPhysical",cellLogical,0,0); - contRodCadLogical = new G4LogicalVolume(theSolids->GetSolid("contRodCadTube"),matMap["Cadmium"], "contRodCadLogical"); - new G4PVPlacement(0, G4ThreeVector(0., 0., -5.44*cm), contRodCadLogical,"contRodCadPhysical",contRodAlumLogical,0,0); - contRodCentLogical = new G4LogicalVolume(theSolids->GetSolid("contRodCentTube"),matMap["Air"], "contRodCentLogical"); - - new G4PVPlacement(0, G4ThreeVector(0., 0., 0.), contRodCentLogical,"contRodCentPhysical",contRodCadLogical,0,0); - - // Creates the three zirconium pie slice which together form half of the reactor core. - ZirconiumLogical1 = new G4LogicalVolume(theSolids->GetSolid("Zirconium1/6"), matMap["Zirconium"], "ZirconiumLogical1"); - ZirconiumLogical2 = new G4LogicalVolume(theSolids->GetSolid("Zirconium2/6"), matMap["Zirconium"], "ZirconiumLogical2"); - ZirconiumLogical3 = new G4LogicalVolume(theSolids->GetSolid("Zirconium3/6"), matMap["Zirconium"], "ZirconiumLogical3"); - - // Adding the fuel rods to all of the common rods of the three pie slices - G4int AirGapNum = 0; - std::stringstream Material; - std::stringstream FuelName; - for(G4int y=1; y<24; y++) - { - for(G4int x=1; x<24; x++) - { - G4double Center[2] = {((y-12)*0.551833696+(x-12)*1.103632018)*cm, (12-y)*0.955804*cm}; - - G4double radius = sqrt(Center[0]*Center[0]+Center[1]*Center[1]); - if(latticeMat[y][x] == 8 && Center[0]+ZirconiumRodDim[1] < radius*cos(LowerZrDim[3]) - && Center[0]+ZirconiumRodDim[1] > radius*cos(LowerZrDim[3]+LowerZrDim[4]) && Center[1] > 0) - { - // Associating right material with volume - Material.str(""); - Material << "Fuel" << AirGapNum; - FuelName.str(""); - FuelName << "FuelRod" << AirGapNum; - - // Creating Air Gap in fuel Assemblie and fuel rod elements - AirGapLogical = new G4LogicalVolume(theSolids->GetSolid("AirGapRod"), matMap["Air"], "AirGapLogical"); - FuelRodLogical = new G4LogicalVolume(theSolids->GetSolid(FuelName.str()), matMap[Material.str()], "FuelRodLogical"); - new G4PVPlacement(0, G4ThreeVector(0,0,-0.0875*cm), FuelRodLogical, "FuelRodPhysical", AirGapLogical, 0, 0); - - new G4PVPlacement(0, G4ThreeVector(Center[0], Center[1], 11.82975*cm), AirGapLogical, "AirGapPhysical", ZirconiumLogical1, 0, 0); - new G4PVPlacement(0, G4ThreeVector(Center[0], Center[1], 11.82975*cm), AirGapLogical, "AirGapPhysical", ZirconiumLogical2, 0, 0); - new G4PVPlacement(0, G4ThreeVector(Center[0], Center[1], 11.82975*cm), AirGapLogical, "AirGapPhysical", ZirconiumLogical3, 0, 0); - AirGapNum++; - - AirGapLogical->SetSensitiveDetector( sDReactor ); - FuelRodLogical->SetSensitiveDetector( sDReactor ); - - // Air Gap Visualization - AirGapAtt = new G4VisAttributes(G4Colour(1.,0.,0.)); - AirGapAtt->SetVisibility(false); - AirGapLogical->SetVisAttributes(AirGapAtt); - - // Fuel Visualization - FuelRodAtt = new G4VisAttributes(G4Colour(0.,1.,0.)); - FuelRodAtt->SetVisibility(false); - FuelRodLogical->SetVisAttributes(FuelRodAtt); - } - } - } - - // Creating the right material for the fuel rod - Material.str(""); - Material << "Fuel" << AirGapNum; - - // Creating Air Gap in fuel Assemblie and fuel rod elements - AirGapLogical = new G4LogicalVolume(theSolids->GetSolid("AirGapRod"), matMap["Air"], "AirGapLogical32"); - FuelRodLogical = new G4LogicalVolume(theSolids->GetSolid("FuelRod32"), matMap[Material.str()], "FuelRodLogical32"); - new G4PVPlacement(0, G4ThreeVector(0, 0, -0.0875*cm), FuelRodLogical, "FuelRodPhysical32", AirGapLogical, 0, 0); - - - - // Adding one rod in the third pie slice - new G4PVPlacement(0, G4ThreeVector(Center1[0], Center1[1], 11.82975*cm), AirGapLogical, "AirGapPhysical32", ZirconiumLogical3, 0, 0); - // Ading the fuel to only the pie slices that need extra. - // Note no extra rods need to be added to the first grid. - // Adding two rods in the second pie slice - new G4PVPlacement(0, G4ThreeVector(Center1[0], Center1[1], 11.82975*cm), AirGapLogical, "AirGapPhysical32", ZirconiumLogical2, 0, 0); - - AirGapLogical->SetSensitiveDetector( sDReactor ); - FuelRodLogical->SetSensitiveDetector( sDReactor ); - - // Air Gap Visualization - AirGapAtt = new G4VisAttributes(G4Colour(1.,0.,0.)); - AirGapAtt->SetVisibility(false); - AirGapLogical->SetVisAttributes(AirGapAtt); - - // Fuel Visualization - FuelRodAtt = new G4VisAttributes(G4Colour(0.,1.,0.)); - FuelRodAtt->SetVisibility(false); - FuelRodLogical->SetVisAttributes(FuelRodAtt); - - // Creating the right material for the fuel rod - AirGapNum++; - Material.str(""); - Material << "Fuel" << AirGapNum; - - // Creating Air Gap in fuel Assemblie and fuel rod elements - AirGapLogical = new G4LogicalVolume(theSolids->GetSolid("AirGapRod"), matMap["Air"], "AirGapLogical33"); - FuelRodLogical = new G4LogicalVolume(theSolids->GetSolid("FuelRod33"), matMap[Material.str()], "FuelRodLogical33"); - new G4PVPlacement(0, G4ThreeVector(0, 0, -0.0875*cm), FuelRodLogical, "FuelRodPhysical33", AirGapLogical, 0, 0); - - new G4PVPlacement(0, G4ThreeVector(Center2[0], Center2[1], 11.82975*cm), AirGapLogical, "AirGapPhysical33", ZirconiumLogical2, 0, AirGapNum+1); - - - // Placing the pie slices where they belong - std::stringstream PhysicalName; - G4RotationMatrix* zRot; - G4int copynum = 0; - for(G4int i=0; i<6; i++) - { - PhysicalName.str(""); - zRot = new G4RotationMatrix; - zRot->rotateZ(-i*CLHEP::pi/3); - if(i == 0 || i == 3) - { - PhysicalName << "ZirconiumPhysical1-"<< copynum; - new G4PVPlacement(zRot, G4ThreeVector(-30*cm, -30*cm, 41.5535*cm-reactorDim[2]/2), ZirconiumLogical1, PhysicalName.str(), cellLogical, 0, copynum); - } - else if(i == 1 || i==4) - { - PhysicalName << "ZirconiumPhysical2-" << copynum; - new G4PVPlacement(zRot, G4ThreeVector(-30*cm, -30*cm, 41.5535*cm-reactorDim[2]/2), ZirconiumLogical2, PhysicalName.str(), cellLogical, 0, copynum); - } - else if(i == 2 || i == 5) - { - PhysicalName << "ZirconiumPhysical3-" << copynum; - new G4PVPlacement(zRot, G4ThreeVector(-30*cm, -30*cm, 41.5535*cm-reactorDim[2]/2), ZirconiumLogical3, PhysicalName.str(), cellLogical, 0, copynum); - copynum++; - } - } - - // Add sensitive detector to ALL logical volumes - worldLogical->SetSensitiveDetector( sDReactor ); - ZirconiumLogical1->SetSensitiveDetector( sDReactor ); - ZirconiumLogical2->SetSensitiveDetector( sDReactor ); - ZirconiumLogical3->SetSensitiveDetector( sDReactor ); - AirGapLogical->SetSensitiveDetector( sDReactor ); - FuelRodLogical->SetSensitiveDetector( sDReactor ); - ReflectorLogical->SetSensitiveDetector( sDReactor ); - D2OContainerLogical->SetSensitiveDetector( sDReactor ); - D2OLogical->SetSensitiveDetector( sDReactor ); - contRodZirLogical->SetSensitiveDetector( sDReactor ); - contRodAlumLogical->SetSensitiveDetector( sDReactor ); - contRodCadLogical->SetSensitiveDetector( sDReactor ); - contRodCentLogical->SetSensitiveDetector( sDReactor ); - insAlumLogical->SetSensitiveDetector( sDReactor ); - insBeamLogical->SetSensitiveDetector( sDReactor ); - outSmallAlumLogical->SetSensitiveDetector( sDReactor ); - outLargeAlumLogical->SetSensitiveDetector( sDReactor ); - cadLinLogical->SetSensitiveDetector( sDReactor ); - outSmallBeamLogical->SetSensitiveDetector( sDReactor ); - outLargeBeamLogical->SetSensitiveDetector( sDReactor ); - alumShellLogical->SetSensitiveDetector( sDReactor ); - cellLogical->SetSensitiveDetector( sDReactor ); - - /* This is where all the visualizaion attributes are made */ - // World Visualization - worldVisAtt = new G4VisAttributes(G4Colour(0.5,0.5,0.5)); - worldVisAtt->SetVisibility(false); - worldLogical->SetVisAttributes(worldVisAtt); - - // Water Tub Visualization - cellVisAtt = new G4VisAttributes(G4Colour(0., 0., 1.)); - cellVisAtt->SetVisibility(false); - cellLogical->SetVisAttributes(cellVisAtt); - - // Aluminum Reactor Shell Visualization - alumShellVisAtt = new G4VisAttributes(G4Colour(173./255,178./255,189./255)); - alumShellVisAtt->SetVisibility(false); - alumShellLogical->SetVisAttributes(alumShellVisAtt); - - // Zirconium Visualization - ZirconiumAtt1 = new G4VisAttributes(G4Colour(0.,0.,0.)); - ZirconiumAtt2 = new G4VisAttributes(G4Colour(0.,0.,0.)); - ZirconiumAtt3 = new G4VisAttributes(G4Colour(0.,0.,0.)); - ZirconiumAtt1->SetVisibility(false); - ZirconiumAtt2->SetVisibility(false); - ZirconiumAtt3->SetVisibility(false); - ZirconiumLogical1->SetVisAttributes(ZirconiumAtt1); - ZirconiumLogical2->SetVisAttributes(ZirconiumAtt2); - ZirconiumLogical3->SetVisAttributes(ZirconiumAtt3); - - // Air Gap Visualization - AirGapAtt = new G4VisAttributes(G4Colour(1.,0.,0.)); - AirGapAtt->SetVisibility(false); - AirGapLogical->SetVisAttributes(AirGapAtt); - - // Fuel Visualization - FuelRodAtt = new G4VisAttributes(G4Colour(0.,1.,0.)); - FuelRodAtt->SetVisibility(false); - FuelRodLogical->SetVisAttributes(FuelRodAtt); - - // Reflector Visualization - ReflectorAtt = new G4VisAttributes(G4Colour(205./255,127./255,50./255)); - ReflectorAtt->SetVisibility(false); - ReflectorLogical->SetVisAttributes(ReflectorAtt); - - - // D2O Column and Water Visualization - D2OContainerAtt = new G4VisAttributes(G4Colour(173./255,178./255,189./255)); - D2OContainerAtt->SetVisibility(false); - D2OContainerLogical->SetVisAttributes(D2OContainerAtt); - D2OAtt = new G4VisAttributes(G4Colour(135./255,206./255,255./255)); - D2OAtt->SetVisibility(false); - D2OLogical->SetVisAttributes(D2OAtt); - - // Control Rod Visualization - contRodZirVisAtt = new G4VisAttributes(G4Colour(0.,0.,0.)); - contRodZirVisAtt->SetVisibility(false); - contRodZirLogical->SetVisAttributes(contRodZirVisAtt); - - contRodAlumVisAtt = new G4VisAttributes(G4Colour(173./255,178./255,189./255)); - contRodAlumVisAtt->SetVisibility(false); - contRodAlumLogical->SetVisAttributes(contRodAlumVisAtt); - - contRodCadVisAtt = new G4VisAttributes(G4Colour(237./255,135./255.0,45./255.0)); - contRodCadVisAtt->SetVisibility(false); - contRodCadLogical->SetVisAttributes(contRodCadVisAtt); - - contRodCentVisAtt = new G4VisAttributes(G4Colour(1.,0.,0.)); - contRodCentVisAtt->SetVisibility(false); - contRodCentLogical->SetVisAttributes(contRodCentVisAtt); - - // Irradiations Sites Visualization - insAlumVisAtt = new G4VisAttributes(G4Colour(173./255,178./255,189./255)); - insAlumVisAtt->SetVisibility(false); - insAlumLogical->SetVisAttributes(insAlumVisAtt); - - insBeamVisAtt = new G4VisAttributes(G4Colour(1., 0., 0.)); - insBeamVisAtt->SetVisibility(false); - insBeamLogical->SetVisAttributes(insBeamVisAtt); - - outSmallAlumVisAtt = new G4VisAttributes(G4Colour(173./255,178./255,189./255)); - outSmallAlumVisAtt->SetVisibility(false); - outSmallAlumLogical->SetVisAttributes(outSmallAlumVisAtt); - - outLargeAlumVisAtt = new G4VisAttributes(G4Colour(173./255,178./255,189./255)); - outLargeAlumVisAtt->SetVisibility(false); - outLargeAlumLogical->SetVisAttributes(outLargeAlumVisAtt); - - cadLinTubeVisAtt = new G4VisAttributes(G4Colour(237./255,135./255.0,45./255.0)); - cadLinTubeVisAtt->SetVisibility(false); - cadLinLogical->SetVisAttributes(cadLinTubeVisAtt); - - outSmallBeamVisAtt = new G4VisAttributes(G4Colour(1.,0.,0.)); - outSmallBeamVisAtt->SetVisibility(false); - outSmallBeamLogical->SetVisAttributes(outSmallBeamVisAtt); - - outLargeBeamVisAtt = new G4VisAttributes(G4Colour(1.,0.,0.)); - outLargeBeamVisAtt->SetVisibility(false); - outLargeBeamLogical->SetVisAttributes(outLargeBeamVisAtt); - - return worldPhysical; -} - - -// ConstructMaterials() -// Define and build the materials in the C6 lattice cell. -void SLOWPOKEConstructor::ConstructMaterials() -{ - // Density Of Defined Materials - G4double ReflectorDensity = 1.85*g/cm3; - G4double LWDensity = 0.998*g/cm3; - // G4double FuelDensity = 10.6*g/cm3; - G4double AirDensity = 5.0807e-5*g/cm3; - G4double ZrDensity = 6.49*g/cm3; - G4double AlAlloyDensity = 2.70*g/cm3; - G4double CadmiumDensity = 8.65*g/cm3; - G4double HWDensity = 1.105*g/cm3; - - // Temperature Of Defined Materials - // using data from 20043405 - G4double ReflectorTemp=(22.5+273.15)*kelvin; - G4double LWTemp=(30.6+273.15)*kelvin; - G4double AirTemp=(18.0+273.15)*kelvin; - G4double ZrTemp=(52.14+273.15)*kelvin; - G4double AlAlloyTemp1=(20.0+273.15)*kelvin; - G4double AlAlloyTemp2=(21.0+273.15)*kelvin; - G4double AlAlloyTemp3=(22.0+273.15)*kelvin; - G4double AlAlloyTemp4=(48.0+273.15)*kelvin; - G4double CadmiumTemp=(50.0+273.15)*kelvin; - G4double HWTemp=(20.5+273.15)*kelvin; - - // Defining all the pointers - G4Isotope *C12, *C13, *N14, *N15, *O16, *O17, *O18, *Mg24, - *Mg25, *Mg26, *Al27, *Si28, *Si29, *Si30, *Cr50, - *Cr52, *Cr53, *Cr54, *Mn55, *Fe54, *Fe56, *Fe57, - *Fe58, *Cu63, *Cu65, *Zr90, *Zr91, *Zr92, *Zr94, - *Zr96, *Cd106, *Cd108, *Cd110, *Cd111, *Cd112, - *Cd113, *Cd114, *Cd116, *U235, *U238; - G4Element *H1, *D2, *Be, *Li6, *Li7, *B10, *B11, *C, *N, *Oxygen, - *Mg, *Al, *Si, *Cr, *Mn, *Fe, *Cu, *Zirc, *ECd112, - *ECd113, *Cd, *In115, *Sm148, *Sm149, *Sm150, *Sm152, - *Gd155, *Gd157, *Eu151, *Eu153, *Ir191, *Ir193,*LEU; - G4Material *World, *Air, *Reflector, *LW, *Fuel, *Zr, *AlAlloy1, - *AlAlloy2, *AlAlloy3, *AlAlloy4, *Cadmium, *HW; - - // Hydrogen And Isotopes - H1 = new G4Element("Hydrogen1", "H1", 1); - H1->AddIsotope(new G4Isotope("H1", 1, 1, 1.0078250321*g/mole), 1); - D2 = new G4Element("Hydrogen2", "H2", 1); - D2->AddIsotope(new G4Isotope("H2", 1, 2, 2.0141017780*g/mole), 1); - - // Lithium Isotopes - Li6 = new G4Element("Lithium6", "Li6", 1); - Li6->AddIsotope(new G4Isotope("Li6", 3, 6, 6.0151223*g/mole), 1); - Li7 = new G4Element("Lithium7", "Li7", 1); - Li7->AddIsotope(new G4Isotope("Li7", 3, 7, 7.0160040*g/mole), 1); - - // Berylium And Isotopes - Be = new G4Element("Berylium", "Be", 1); - Be->AddIsotope(new G4Isotope("Be9", 4, 9, 9.0121822*g/mole), 1); - - // Boron Isotopes - B10 = new G4Element("Boron10", "B10", 1); - B10->AddIsotope(new G4Isotope("B10", 5, 10, 10.012937*g/mole), 1); - B11 = new G4Element("Boron11", "B11", 1); - B11->AddIsotope(new G4Isotope("B11", 5, 11, 11.009305*g/mole), 1); - - // Making Carbon isotopes - C12 = new G4Isotope("C12", 6, 12, 12.000000*g/mole); - C13 = new G4Isotope("C13", 6, 13, 13.003354*g/mole); - - // Naturally occuring Carbon - C = new G4Element("Carbon", "C", 2); - C->AddIsotope(C12, 98.93*perCent); - C->AddIsotope(C13, 1.07*perCent); - - // Nitrogen Isotopes - N14 = new G4Isotope("N14", 7, 14, 14.0030740052*g/mole); - N15 = new G4Isotope("N15", 7, 15, 15.0001088984*g/mole); - - // Naturally occuring Nitrogen - N = new G4Element("Nitrogen", "N", 2); - N->AddIsotope(N14, 99.632*perCent); - N->AddIsotope(N15, 0.368*perCent); - - // Make oxygen isotope and element - O16 = new G4Isotope("O16", 8, 16, 15.995*g/mole); - O17 = new G4Isotope("O17", 8, 17, 16.999*g/mole); - O18 = new G4Isotope("O18", 8, 18, 17.999*g/mole); - - // Natural occuring oxygen - Oxygen = new G4Element("Oxygen", "O", 3); - Oxygen->AddIsotope(O16, 99.757*perCent); - Oxygen->AddIsotope(O17, 0.038*perCent); - Oxygen->AddIsotope(O18, 0.205*perCent); - - // Magnesium Isotopes - Mg24 = new G4Isotope("Mg24", 12, 24, 23.9850423*g/mole); - Mg25 = new G4Isotope("Mg25", 12, 25, 24.9858374*g/mole); - Mg26 = new G4Isotope("Mg26", 12, 26, 25.9825937*g/mole); - - // Naturally Occuring Magnesium - Mg = new G4Element("Magnesium", "Mg", 3); - Mg->AddIsotope(Mg24, 78.99*perCent); - Mg->AddIsotope(Mg25, 10.00*perCent); - Mg->AddIsotope(Mg26, 11.01*perCent); - - // Making Aluminum Isotopes - Al27 = new G4Isotope("Al27", 13, 27, 26.9815386*g/mole); - - // Naturally occuring Aluminum - Al = new G4Element("Aluminum", "Al", 1); - Al->AddIsotope(Al27, 1); - - // Making Silicon Isotopes - Si28 = new G4Isotope("Si28", 14, 28, 27.9769271*g/mole); - Si29 = new G4Isotope("Si29", 14, 29, 28.9764949*g/mole); - Si30 = new G4Isotope("Si30", 14, 30, 29.9737707*g/mole); - - // Naturally occuring Silicon - Si = new G4Element("Silicon", "Si", 3); - Si->AddIsotope(Si28, 92.2297*perCent); - Si->AddIsotope(Si29, 4.6832*perCent); - Si->AddIsotope(Si30, 3.0871*perCent); - - // Chromium Isotopes - Cr50 = new G4Isotope("Cr50", 24, 50, 49.9460464*g/mole); - Cr52 = new G4Isotope("Cr52", 24, 52, 51.9405098*g/mole); - Cr53 = new G4Isotope("Cr53", 24, 53, 52.9406513*g/mole); - Cr54 = new G4Isotope("Cr54", 24, 54, 53.9388825*g/mole); - - // Naturally Occuring Chromium - Cr = new G4Element("Chromium", "Cr", 4); - Cr->AddIsotope(Cr50, 4.345*perCent); - Cr->AddIsotope(Cr52, 83.789*perCent); - Cr->AddIsotope(Cr53, 9.501*perCent); - Cr->AddIsotope(Cr54, 2.365*perCent); - - // Manganese Isotopes - Mn55 = new G4Isotope("Mn55", 25, 55, 54.9380471*g/mole); - - // Naturally occuring Manganese - Mn = new G4Element("Manganese", "Mn", 1); - Mn->AddIsotope(Mn55, 1.); - - // Making Iron Isotopes - Fe54 = new G4Isotope("Fe54", 26, 54, 53.9396127*g/mole); - Fe56 = new G4Isotope("Fe56", 26, 56, 55.9349393*g/mole); - Fe57 = new G4Isotope("Fe57", 26, 57, 56.9353958*g/mole); - Fe58 = new G4Isotope("Fe58", 26, 58, 57.9332773*g/mole); - - // Naturally Occuring Iron - Fe = new G4Element("Iron", "Fe", 4); - Fe->AddIsotope(Fe54, 5.845*perCent); - Fe->AddIsotope(Fe56, 91.754*perCent); - Fe->AddIsotope(Fe57, 2.119*perCent); - Fe->AddIsotope(Fe58, 0.282*perCent); - - // Copper Isotopes - Cu63 = new G4Isotope("Cu63", 29, 63, 62.9295989*g/mole); - Cu65 = new G4Isotope("Cu65", 29, 66, 64.9277929*g/mole); - - // Naturally Occuring Copper - Cu = new G4Element("Copper", "Cu", 2); - Cu->AddIsotope(Cu63, 69.17*perCent); - Cu->AddIsotope(Cu65, 30.83*perCent); - - // Making Zirconium isotopes and elements - Zr90 = new G4Isotope("Zr90", 40, 90, 89.9047044*g/mole); - Zr91 = new G4Isotope("Zr91", 40, 91, 90.9056458*g/mole); - Zr92 = new G4Isotope("Zr92", 40, 92, 91.9050408*g/mole); - Zr94 = new G4Isotope("Zr94", 40, 94, 93.9063152*g/mole); - Zr96 = new G4Isotope("Zr96", 40, 96, 95.9082734*g/mole); - - // Natural Zirconium composition - Zirc = new G4Element("Zirconium", "Zr", 5); - Zirc->AddIsotope(Zr90, 50.706645*perCent); - Zirc->AddIsotope(Zr91, 11.180922*perCent); - Zirc->AddIsotope(Zr92, 17.277879*perCent); - Zirc->AddIsotope(Zr94, 17.890875*perCent); - Zirc->AddIsotope(Zr96, 2.943679*perCent); - - // Cadmium Isotopes - Cd106 = new G4Isotope("Cd106", 48, 106, 105.906461*g/mole); - Cd108 = new G4Isotope("Cd108", 48, 108, 107.904176*g/mole); - Cd110 = new G4Isotope("Cd110", 48, 110, 109.903005*g/mole); - Cd111 = new G4Isotope("Cd111", 48, 111, 110.904182*g/mole); - Cd112 = new G4Isotope("Cd112", 48, 112, 111.902757*g/mole); - Cd113 = new G4Isotope("Cd113", 48, 113, 112.904400*g/mole); - Cd114 = new G4Isotope("Cd114", 48, 114, 113.903357*g/mole); - Cd116 = new G4Isotope("Cd116", 48, 116, 115.904755*g/mole); - - - // Cadmium Isotopes - ECd112 = new G4Element("Cadmium112", "Cd112", 1); - ECd112->AddIsotope(Cd112, 1); - ECd113 = new G4Element("Cadmium113", "Cd113", 1); - ECd113->AddIsotope(Cd113, 1); - - // Naturally Occuring Cadmium - Cd = new G4Element("Cadmium", "Cd", 8); - Cd->AddIsotope(Cd106, 1.25*perCent); - Cd->AddIsotope(Cd108, 0.89*perCent); - Cd->AddIsotope(Cd110, 12.49*perCent); - Cd->AddIsotope(Cd111, 12.80*perCent); - Cd->AddIsotope(Cd112, 24.13*perCent); - Cd->AddIsotope(Cd113, 12.22*perCent); - Cd->AddIsotope(Cd114, 28.73*perCent); - Cd->AddIsotope(Cd116, 7.49*perCent); - - // Indium Isotopes - In115 = new G4Element("Indium115", "In115", 1); - In115->AddIsotope(new G4Isotope("In115", 49, 115, 114.903882*g/mole), 1); - - // Samarium Isotopes (Note: Could not get info on Sm137) - Sm148 = new G4Element("Samatium148", "Am148", 1); - Sm148->AddIsotope(new G4Isotope("Sm148", 62, 148, 147.914819*g/mole), 1); - Sm149 = new G4Element("Samatium149", "Am149", 1); - Sm149->AddIsotope(new G4Isotope("Sm149", 62, 149, 149.917180*g/mole), 1); - Sm150 = new G4Element("Samatium150", "Am150", 1); - Sm150->AddIsotope(new G4Isotope("Sm150", 62, 150, 149.917273*g/mole), 1); - Sm152 = new G4Element("Samatium152", "Am152", 1); - Sm152->AddIsotope(new G4Isotope("Sm152", 62, 152, 151.919728*g/mole), 1); - - // Gadolium Isotopes - Gd155 = new G4Element("Gadolinium155", "Gd155", 1); - Gd155->AddIsotope(new G4Isotope("Gd155", 64, 155, 154.922618*g/mole), 1); - Gd157 = new G4Element("Gadolinium157", "Gd157", 1); - Gd157->AddIsotope(new G4Isotope("Gd157", 64, 157, 156.923956*g/mole), 1); - - // Europium Isotopes - Eu151 = new G4Element("Europium151", "Eu151", 1); - Eu151->AddIsotope(new G4Isotope("Eu151", 63, 151, 150.919702*g/mole), 1); - Eu153 = new G4Element("Europium153", "Eu153", 1); - Eu153->AddIsotope(new G4Isotope("Eu153", 63, 153, 152.921225*g/mole), 1); - - // Iridium Isotopes - Ir191 = new G4Element("Iridium191", "Ir191", 1); - Ir191->AddIsotope(new G4Isotope("Ir191", 77, 191, 190.960584*g/mole), 1); - Ir193 = new G4Element("Iridium193", "Ir193", 1); - Ir193->AddIsotope(new G4Isotope("Ir193", 77, 193, 192.962917*g/mole), 1); - - // Making the Uranium isotopes - U235 = new G4Isotope("U235", 92, 235, 235.0439*g/mole); - U238 = new G4Isotope("U238", 92, 238, 238.0508*g/mole); - - // Low Enriched Uranium (LEU) - LEU = new G4Element("Low Enriched Uranium", "LEU", 2); - LEU->AddIsotope(U235, 19.89*perCent); - LEU->AddIsotope(U238, 80.11*perCent); - - // (Marteial #0) Void Material - World = new StorkMaterialHT("Galactic", 1, 1, 1.e-25*g/cm3, 0*joule/g/kelvin, 0.0*joule/(s*m*kelvin), kStateGas, - 2.73*kelvin, 3.e-18*pascal); - - // (Material #1) Beryllium Sheild with Impurities - Reflector = new StorkMaterialHT("Reflector", ReflectorDensity, 17, 1.83*joule/g/kelvin, 218*joule/(s*m*kelvin), kStateSolid, ReflectorTemp); - Reflector->AddElement(Be, 0.9953863); - Reflector->AddElement(Oxygen, 9.70113e-6); - Reflector->AddElement(Al, 1.010534e-3); - Reflector->AddElement(C, 1.515802e-3); - Reflector->AddElement(Fe, 1.31695e-3); - Reflector->AddElement(Si, 6.063207e-4); - Reflector->AddElement(B10, 4.345298e-7); - Reflector->AddElement(B11, 1.616855e-6); - Reflector->AddElement(Mn, 1.515802e-4); - Reflector->AddElement(Cd, 7.376901e-7); - Reflector->AddElement(Li6, 1.313695e-7); - Reflector->AddElement(Li7, 1.92001e-6); - Reflector->AddElement(Sm149, 6.497736e-7); - Reflector->AddElement(Gd155, 3.53687e-8); - Reflector->AddElement(Gd157, 3.132657e-8); - Reflector->AddElement(Eu151, 2.425283e-7); - Reflector->AddElement(Eu153, 2.627389e-7); - - // (Material #2) Light Water - LW = new StorkMaterialHT("H2O", LWDensity, 2, 4.1813*joule/g/kelvin, 0.5984*joule/(s*m*kelvin), kStateLiquid, LWTemp); - LW->AddElement(Oxygen, 1); - LW->AddElement(H1, 2); - - // (Material #4) Air - Air = new StorkMaterialHT("Air", AirDensity, 2, 1.0035*joule/g/kelvin, 0.024*joule/(s*m*kelvin), kStateGas, AirTemp); - Air->AddElement(Oxygen, 0.21174); - Air->AddElement(N, 0.78826); - - // (Material #5) Zr - Zr = new StorkMaterialHT("Zirconium", ZrDensity, 1, 0.278*joule/g/kelvin, 8.625*joule/(s*m*kelvin), kStateSolid, ZrTemp); - Zr->AddElement(Zirc, 1); - - // (Material #6) Aluminum with impurities - AlAlloy1 = new StorkMaterialHT("AlAlloy1", AlAlloyDensity, 5, 0.897*joule/g/kelvin, 205*joule/(s*m*kelvin), kStateSolid, AlAlloyTemp1); - AlAlloy1->AddElement(Al, 0.9792); - AlAlloy1->AddElement(Si, 0.0060); - AlAlloy1->AddElement(Cu, 0.0028); - AlAlloy1->AddElement(Mg, 0.0100); - AlAlloy1->AddElement(Cr, 0.0020); - - AlAlloy2 = new StorkMaterialHT("AlAlloy2", AlAlloyDensity, 5, 0.897*joule/g/kelvin, 205*joule/(s*m*kelvin), kStateSolid, AlAlloyTemp2); - AlAlloy2->AddElement(Al, 0.9792); - AlAlloy2->AddElement(Si, 0.0060); - AlAlloy2->AddElement(Cu, 0.0028); - AlAlloy2->AddElement(Mg, 0.0100); - AlAlloy2->AddElement(Cr, 0.0020); - - AlAlloy3 = new StorkMaterialHT("AlAlloy3", AlAlloyDensity, 5, 0.897*joule/g/kelvin, 205*joule/(s*m*kelvin), kStateSolid, AlAlloyTemp3); - AlAlloy3->AddElement(Al, 0.9792); - AlAlloy3->AddElement(Si, 0.0060); - AlAlloy3->AddElement(Cu, 0.0028); - AlAlloy3->AddElement(Mg, 0.0100); - AlAlloy3->AddElement(Cr, 0.0020); - - AlAlloy4 = new StorkMaterialHT("AlAlloy4", AlAlloyDensity, 5, 0.897*joule/g/kelvin, 205*joule/(s*m*kelvin), kStateSolid, AlAlloyTemp4); - AlAlloy4->AddElement(Al, 0.9792); - AlAlloy4->AddElement(Si, 0.0060); - AlAlloy4->AddElement(Cu, 0.0028); - AlAlloy4->AddElement(Mg, 0.0100); - AlAlloy4->AddElement(Cr, 0.0020); - - // (Material #7) Cadmium - Cadmium = new StorkMaterialHT("Cadmium", CadmiumDensity, 1, 0.231*joule/g/kelvin, 92*joule/(s*m*kelvin), kStateSolid, CadmiumTemp); - Cadmium->AddElement(Cd, 1); - - // (Materail #8) Heavy Water - HW = new StorkMaterialHT("D2O", HWDensity, 2, 4.224211211*joule/g/kelvin, 0.589*joule/(s*m*kelvin), kStateLiquid, HWTemp); - HW->AddElement(D2, 2); - HW->AddElement(Oxygen, 1); - - - // Add materials to the map indexed by either ZA (format ZZAAA or ZZ) - // For composite materials: world is 0, heavy water is 1, UHW is 2 - matMap["Galactic"] = World; - matMap["H2O"] = LW; - matMap["D2O"] = HW; - matMap["Zirconium"] = Zr; - matMap["AlAlloy1"] = AlAlloy1; - matMap["AlAlloy2"] = AlAlloy2; - matMap["AlAlloy3"] = AlAlloy3; - matMap["AlAlloy4"] = AlAlloy4; - matMap["Reflector"] = Reflector; - matMap["Cadmium"] = Cadmium; - matMap["Air"] = Air; - - - // (Material #3) Fuel Rods (19.95% Enriched Uranium in (UO2)) - std::stringstream matName; - for(G4int i = 0; i <34; i++) - { - matName.str(""); - matName << "Fuel" << i; - Fuel = new StorkMaterialHT(matName.str(), FuelDensities[i], 2, 0.2411519506*joule/g/kelvin, 21.5*joule/(s*m*kelvin), kStateSolid, FuelTemperatures[i]); - Fuel->AddElement(Oxygen, 2); - Fuel->AddElement(LEU, 1); - - matMap[matName.str()] = Fuel; - } - - - matChanged = false; - - return; -} diff --git a/G4STORK/src/STORKBooleanSolid.cc b/G4STORK/src/STORKBooleanSolid.cc deleted file mode 100755 index 585db02b..00000000 --- a/G4STORK/src/STORKBooleanSolid.cc +++ /dev/null @@ -1,314 +0,0 @@ -// -// ******************************************************************** -// * License and Disclaimer * -// * * -// * The Geant4 software is copyright of the Copyright Holders of * -// * the Geant4 Collaboration. It is provided under the terms and * -// * conditions of the Geant4 Software License, included in the file * -// * LICENSE and available at http://cern.ch/geant4/license . These * -// * include a list of copyright holders. * -// * * -// * Neither the authors of this software system, nor their employing * -// * institutes,nor the agencies providing financial support for this * -// * work make any representation or warranty, express or implied, * -// * regarding this software system or assume any liability for its * -// * use. Please see the license in the file LICENSE and URL above * -// * for the full disclaimer and the limitation of liability. * -// * * -// * This code implementation is the result of the scientific and * -// * technical work of the GEANT4 collaboration. * -// * By using, copying, modifying or distributing the software (or * -// * any work based on the software) you agree to acknowledge its * -// * use in resulting scientific publications, and indicate your * -// * acceptance of all terms of the Geant4 Software license. * -// ******************************************************************** -// -// -// $Id$ -// -// Implementation for the abstract base class for solids created by boolean -// operations between other solids -// -// History: -// -// 10.09.98 V.Grichine, created -// -// -------------------------------------------------------------------- - -#include "STORKBooleanSolid.hh" -#include "G4VSolid.hh" -#include "G4Polyhedron.hh" -#include "HepPolyhedronProcessor.h" -#include "Randomize.hh" - -////////////////////////////////////////////////////////////////// -// -// Constructor - -STORKBooleanSolid::STORKBooleanSolid( const G4String& pName, - G4VSolid* pSolidA , - G4VSolid* pSolidB ) : - G4VSolid(pName), fAreaRatio(0.), fStatistics(1000000), fCubVolEpsilon(0.001), - fAreaAccuracy(-1.), fCubicVolume(0.), fSurfaceArea(0.), - fpPolyhedron(0), createdDisplacedSolid(false) -{ - fPtrSolidA = pSolidA ; - fPtrSolidB = pSolidB ; -} - -////////////////////////////////////////////////////////////////// -// -// Constructor - -STORKBooleanSolid::STORKBooleanSolid( const G4String& pName, - G4VSolid* pSolidA , - G4VSolid* pSolidB , - G4RotationMatrix* rotMatrix, - const G4ThreeVector& transVector ) : - G4VSolid(pName), fAreaRatio(0.), fStatistics(1000000), fCubVolEpsilon(0.001), - fAreaAccuracy(-1.), fCubicVolume(0.), fSurfaceArea(0.), - fpPolyhedron(0), createdDisplacedSolid(true) -{ - fPtrSolidA = pSolidA ; - fPtrSolidB = new G4DisplacedSolid("placedB",pSolidB,rotMatrix,transVector) ; -} - -////////////////////////////////////////////////////////////////// -// -// Constructor - -STORKBooleanSolid::STORKBooleanSolid( const G4String& pName, - G4VSolid* pSolidA , - G4VSolid* pSolidB , - const G4Transform3D& transform ) : - G4VSolid(pName), fAreaRatio(0.), fStatistics(1000000), fCubVolEpsilon(0.001), - fAreaAccuracy(-1.), fCubicVolume(0.), fSurfaceArea(0.), - fpPolyhedron(0), createdDisplacedSolid(true) -{ - fPtrSolidA = pSolidA ; - fPtrSolidB = new G4DisplacedSolid("placedB",pSolidB,transform) ; -} - -/////////////////////////////////////////////////////////////// -// -// Fake default constructor - sets only member data and allocates memory -// for usage restricted to object persistency. - -STORKBooleanSolid::STORKBooleanSolid( __void__& a ) - : G4VSolid(a), fPtrSolidA(0), fPtrSolidB(0), fAreaRatio(0.), - fStatistics(1000000), fCubVolEpsilon(0.001), - fAreaAccuracy(-1.), fCubicVolume(0.), fSurfaceArea(0.), - fpPolyhedron(0), createdDisplacedSolid(false) -{ -} - -/////////////////////////////////////////////////////////////// -// -// Destructor deletes transformation contents of the created displaced solid - -STORKBooleanSolid::~STORKBooleanSolid() -{ - if(createdDisplacedSolid) - { - ((G4DisplacedSolid*)fPtrSolidB)->CleanTransformations(); - } - delete fpPolyhedron; -} - -/////////////////////////////////////////////////////////////// -// -// Copy constructor - -STORKBooleanSolid::STORKBooleanSolid(const STORKBooleanSolid& rhs) - : G4VSolid (rhs), fPtrSolidA(rhs.fPtrSolidA), fPtrSolidB(rhs.fPtrSolidB), - fAreaRatio(rhs.fAreaRatio), - fStatistics(rhs.fStatistics), fCubVolEpsilon(rhs.fCubVolEpsilon), - fAreaAccuracy(rhs.fAreaAccuracy), fCubicVolume(rhs.fCubicVolume), - fSurfaceArea(rhs.fSurfaceArea), fpPolyhedron(0), - createdDisplacedSolid(rhs.createdDisplacedSolid) -{ -} - -/////////////////////////////////////////////////////////////// -// -// Assignment operator - -STORKBooleanSolid& STORKBooleanSolid::operator = (const STORKBooleanSolid& rhs) -{ - // Check assignment to self - // - if (this == &rhs) { return *this; } - - // Copy base class data - // - G4VSolid::operator=(rhs); - - // Copy data - // - fPtrSolidA= rhs.fPtrSolidA; fPtrSolidB= rhs.fPtrSolidB; - fAreaRatio= rhs.fAreaRatio; - fStatistics= rhs.fStatistics; fCubVolEpsilon= rhs.fCubVolEpsilon; - fAreaAccuracy= rhs.fAreaAccuracy; fCubicVolume= rhs.fCubicVolume; - fSurfaceArea= rhs.fSurfaceArea; fpPolyhedron= 0; - createdDisplacedSolid= rhs.createdDisplacedSolid; - - return *this; -} - -/////////////////////////////////////////////////////////////// -// -// If Solid is made up from a Boolean operation of two solids, -// return the corresponding solid (for no=0 and 1) -// If the solid is not a "Boolean", return 0 - -const G4VSolid* STORKBooleanSolid::GetConstituentSolid(G4int no) const -{ - const G4VSolid* subSolid=0; - if( no == 0 ) - subSolid = fPtrSolidA; - else if( no == 1 ) - subSolid = fPtrSolidB; - else - { - DumpInfo(); - G4Exception("STORKBooleanSolid::GetConstituentSolid()", - "GeomSolids0002", FatalException, "Invalid solid index."); - } - - return subSolid; -} - -/////////////////////////////////////////////////////////////// -// -// If Solid is made up from a Boolean operation of two solids, -// return the corresponding solid (for no=0 and 1) -// If the solid is not a "Boolean", return 0 - -G4VSolid* STORKBooleanSolid::GetConstituentSolid(G4int no) -{ - G4VSolid* subSolid=0; - if( no == 0 ) - subSolid = fPtrSolidA; - else if( no == 1 ) - subSolid = fPtrSolidB; - else - { - DumpInfo(); - G4Exception("STORKBooleanSolid::GetConstituentSolid()", - "GeomSolids0002", FatalException, "Invalid solid index."); - } - - return subSolid; -} - -////////////////////////////////////////////////////////////////////////// -// -// Returns entity type - -G4GeometryType STORKBooleanSolid::GetEntityType() const -{ - return G4String("STORKBooleanSolid"); -} - -////////////////////////////////////////////////////////////////////////// -// -// Stream object contents to an output stream - -std::ostream& STORKBooleanSolid::StreamInfo(std::ostream& os) const -{ - os << "-----------------------------------------------------------\n" - << " *** Dump for Boolean solid - " << GetName() << " ***\n" - << " ===================================================\n" - << " Solid type: " << GetEntityType() << "\n" - << " Parameters of constituent solids: \n" - << "===========================================================\n"; - fPtrSolidA->StreamInfo(os); - fPtrSolidB->StreamInfo(os); - os << "===========================================================\n"; - - return os; -} - -////////////////////////////////////////////////////////////////////////// -// -// Returns a point (G4ThreeVector) randomly and uniformly selected -// on the solid surface -// - -G4ThreeVector STORKBooleanSolid::GetPointOnSurface() const -{ - G4double rand; - G4ThreeVector p; - - do - { - rand = G4UniformRand(); - - if (rand < GetAreaRatio()) { p = fPtrSolidA->GetPointOnSurface(); } - else { p = fPtrSolidB->GetPointOnSurface(); } - } while (Inside(p) != kSurface); - - return p; -} - -////////////////////////////////////////////////////////////////////////// -// -// Returns polyhedron for visualization - -G4Polyhedron* STORKBooleanSolid::GetPolyhedron () const -{ - if (!fpPolyhedron || - fpPolyhedron->GetNumberOfRotationStepsAtTimeOfCreation() != - fpPolyhedron->GetNumberOfRotationSteps()) - { - delete fpPolyhedron; - fpPolyhedron = CreatePolyhedron(); - } - return fpPolyhedron; -} - -////////////////////////////////////////////////////////////////////////// -// -// Stacks polyhedra for processing. Returns top polyhedron. - -G4Polyhedron* -STORKBooleanSolid::StackPolyhedron(HepPolyhedronProcessor& processor, - const G4VSolid* solid) const -{ - HepPolyhedronProcessor::Operation operation; - const G4String& type = solid->GetEntityType(); - if (type == "G4UnionSolid") - { operation = HepPolyhedronProcessor::UNION; } - else if (type == "StorkUnionSolid") - { operation = HepPolyhedronProcessor::UNION; } - else if (type == "G4IntersectionSolid") - { operation = HepPolyhedronProcessor::INTERSECTION; } - else if (type == "G4SubtractionSolid") - { operation = HepPolyhedronProcessor::SUBTRACTION; } - else - { - std::ostringstream message; - message << "Solid - " << solid->GetName() - << " - Unrecognised composite solid" << G4endl - << " Returning NULL !"; - G4Exception("StackPolyhedron()", "GeomSolids1001", JustWarning, message); - return 0; - } - - G4Polyhedron* top = 0; - const G4VSolid* solidA = solid->GetConstituentSolid(0); - const G4VSolid* solidB = solid->GetConstituentSolid(1); - - if (solidA->GetConstituentSolid(0)) - { - top = StackPolyhedron(processor, solidA); - } - else - { - top = solidA->GetPolyhedron(); - } - G4Polyhedron* operand = solidB->GetPolyhedron(); - processor.push_back (operation, *operand); - - return top; -} diff --git a/G4STORK/src/StorkBCTransform.cc b/G4STORK/src/StorkBCTransform.cc deleted file mode 100755 index 05f6a3e6..00000000 --- a/G4STORK/src/StorkBCTransform.cc +++ /dev/null @@ -1,27 +0,0 @@ -#include "StorkBCTransform.hh" - -StorkBCTransform::StorkBCTransform() -{ - //ctor -} - -StorkBCTransform::~StorkBCTransform() -{ - //dtor -} - -void StorkBCTransform::Transform(G4ThreeVector &pos, G4ThreeVector &mom) -{ - G4ThreeVector newPos=G4ThreeVector(0.,0.,0.), newMom=G4ThreeVector(0.,0.,0.); - for(int i=0; i<3; i++) - { - for(int j=0; j<3; j++) - { - newPos[i]+=TransPos[i][j]*pos[j]; - newMom[i]+=TransMom[i][j]*mom[j]; - } - } - - pos=newPos; - mom=newMom; -} diff --git a/G4STORK/src/StorkDelayedNeutron.cc b/G4STORK/src/StorkDelayedNeutron.cc deleted file mode 100755 index e7c2ecaf..00000000 --- a/G4STORK/src/StorkDelayedNeutron.cc +++ /dev/null @@ -1,284 +0,0 @@ -/* -StorkDelayedNeutron Class - -Written By: Andrew Tan -Date: August 25, 2015 - -Last Edit: -*/ - -#include "StorkDelayedNeutron.hh" - -StorkDelayedNeutron::StorkDelayedNeutron(G4String dnFilename,G4double runduration, G4int numPrimaries) -{ - //Set the fission file name. - delayedSourceFile = dnFilename; - - //Get the run Duration - runDuration = runduration; - - //Get neutron particle object - G4ParticleTable* pTable = G4ParticleTable::GetParticleTable(); - neutron = pTable->FindParticle("neutron"); - - //Setup initial precursor population - GetInitialPrecursors(numPrimaries); - - -} - -StorkDelayedNeutron::~StorkDelayedNeutron() -{ - -} - -G4bool StorkDelayedNeutron::GetInitialPrecursors(G4int numPrimaries) -{ - // Local variables - char line[256]; - G4int numRuns; - G4int numEntries; - G4double primariesPerRun; - G4double runTime; - G4double adjustmentFactor; - G4bool createPrecursors = true; - Precursors.resize(6); - - - // Load data from file - std::ifstream dnfile(delayedSourceFile); - - // Check if file opened properly - if(!dnfile.good()) - { - G4cerr << "*** WARNING: Unable to open initial delayed neutron file:" - << delayedSourceFile << G4endl; - return false; - } - - // Skip header lines - while(dnfile.peek() == '#') - dnfile.getline(line,256); - - //Read in precursor data if nonzero. - for(G4int i = 0; i<6; i++){ - dnfile >> Precursors[i]; - if(Precursors[i]!=0) createPrecursors = false; - } - - - // Read in delayed neutron distribution parameters - // Number of entries, runtime, number of runs collected over, primaries per run. - dnfile >> numEntries >> runTime >> numRuns >> primariesPerRun ; - - - // Resize the fission vectors. - fSites.resize(numEntries); - fEnergy.resize(numEntries); - - - // Read in fission data. - for(G4int i=0; i> fSites[i][0] >> fSites[i][1] >> fSites[i][2] >> fEnergy[i]; - - } - - //Create the precursors if needed. - if(createPrecursors){ - //Total time of previous simulation. - G4double totalTime = pow(10,-9)*numRuns*runTime; - //Iterate through fission sites and energies to create precursors. - // Will need to change this method. Precursor populations should be directly calculated. - - G4int totalPrecursors = G4int(numEntries*TotPrecursorConstants/totalTime); - - for(G4int i=0; iGetPDGMass(); - G4ThreeVector theMomDir; - G4double nMom; - NeutronSources dNeutrons; - StorkNeutronData theDelayed; - - - for(G4int i=0; i<6; i++){ - - for(G4int j = 0; j< Precursors[i] ; j++){ - - //Roulette to find the time of decay. - G4double r = G4UniformRand(); - G4double TimeOfDecay = (-log(r)/DecayConstants[0][i])*pow(10,9); - - //Check if within upcoming run if so decay a precursor and create a delayed neutron. - if (TimeOfDecayGetFissionNucleus(fEnergy,fSite).GetIsotope()->GetName(); - G4int index; - - //Select the correct data (using the index). - if(iso == "U235"){ - if(fEnergy<0.0000005) index = 0; - else index = 3; - - } - else if(iso == "U238"){ - index = 6; - - } - else if(iso == "U233"){ - if(fEnergy<0.0000005) index = 2; - else index = 5; - - } - else if(iso == "Pu239"){ - if(fEnergy<0.0000005) index = 1; - else index = 4; - } - else if(iso == "Pu240"){ - index = 7; - } - else if(iso == "Th232"){ - index = 8; - } - else { - index = 0; - } - return index; -} - */ - - diff --git a/G4STORK/src/StorkElement.cc b/G4STORK/src/StorkElement.cc deleted file mode 100755 index 964ba156..00000000 --- a/G4STORK/src/StorkElement.cc +++ /dev/null @@ -1,300 +0,0 @@ -// -// ******************************************************************** -// * License and Disclaimer * -// * * -// * The Geant4 software is copyright of the Copyright Holders of * -// * the Geant4 Collaboration. It is provided under the terms and * -// * conditions of the Geant4 Software License, included in the file * -// * LICENSE and available at http://cern.ch/geant4/license . These * -// * include a list of copyright holders. * -// * * -// * Neither the authors of this software system, nor their employing * -// * institutes,nor the agencies providing financial support for this * -// * work make any representation or warranty, express or implied, * -// * regarding this software system or assume any liability for its * -// * use. Please see the license in the file LICENSE and URL above * -// * for the full disclaimer and the limitation of liability. * -// * * -// * This code implementation is the result of the scientific and * -// * technical work of the GEANT4 collaboration. * -// * By using, copying, modifying or distributing the software (or * -// * any work based on the software) you agree to acknowledge its * -// * use in resulting scientific publications, and indicate your * -// * acceptance of all terms of the Geant4 Software license. * -// ******************************************************************** -// -// -// $Id: StorkElement.cc 81839 2014-06-06 08:47:44Z gcosmo $ -// -//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... - -// 26-06-96: Code uses operators (+=, *=, ++, -> etc.) correctly, P. Urban -// 09-07-96: new data members added by L.Urban -// 17-01-97: aesthetic rearrangement, M.Maire -// 20-01-97: Compute Tsai's formula for the rad length, M.Maire -// 21-01-97: remove mixture flag, M.Maire -// 24-01-97: ComputeIonisationParameters(). -// new data member: fTaul, M.Maire -// 29-01-97: Forbidden to create Element with Z<1 or N Shell; GetBindingEnergy() (mma) -// 09-03-01: assignement operator revised (mma) -// 02-05-01: check identical Z in AddIsotope (marc) -// 03-05-01: flux.precision(prec) at begin/end of operator<< -// 13-09-01: suppression of the data member fIndexInTable -// 14-09-01: fCountUse: nb of materials which use this element -// 26-02-02: fIndexInTable renewed -// 30-03-05: warning in GetElement(elementName) -// 15-11-05: GetElement(elementName, G4bool warning=true) -// 17-10-06: Add fNaturalAbundances (V.Ivanchenko) -// 27-07-07: improve destructor (V.Ivanchenko) -// 18-10-07: move definition of material index to ComputeDerivedQuantities (VI) -// 25.10.11: new scheme for G4Exception (mma) -// 05-03-12: always create isotope vector (V.Ivanchenko) - -//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... - -#include -#include - -#include "StorkElement.hh" -#include "G4AtomicShells.hh" -#include "G4NistManager.hh" -#include "G4PhysicalConstants.hh" -#include "G4SystemOfUnits.hh" - -//G4ElementTable StorkElement::theElementTable; - -//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... - -// Constructor to Generate an element from scratch - -StorkElement::StorkElement(const G4String& name, const G4String& symbol, G4double zeff, G4double aeff) - : G4Element(name, symbol, zeff, aeff) -{ - temperature = -1; - csDataTemp = -1; -} - -//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... - -// Constructor to Generate element from a List of 'nIsotopes' isotopes, added -// via AddIsotope - -StorkElement::StorkElement(const G4String& name, const G4String& symbol, G4int nIsotopes) - : G4Element( name, symbol, nIsotopes) -{ - temperature = -1; - csDataTemp = -1; -} - -//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... - -// Fake default constructor - sets only member data and allocates memory -// for usage restricted to object persistency - -StorkElement::StorkElement( __void__& fake) - : G4Element(fake) -{ - temperature = -1; - csDataTemp = -1; -} - -//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... - -StorkElement::~StorkElement() -{ - -} - -//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... - -bool StorkElement::Exists(G4double temp, G4int &index) -{ - std::stringstream ss; - ss.str(""); - ss<<'T'<0)&&(pos2>0)&&(pos2>pos)) - check= elemName.substr(pos, pos2-pos+1); - - if(check==G4String(ss.str())) - { - elemName=elemName.substr(0, elemName.find_last_of('T')); - } - G4ElementTable *elemTable = (dynamic_cast(const_cast(this)))->GetElementTable(); - for(G4int i=0; isize()); i++) - { - StorkElement *elem = dynamic_cast ((*elemTable)[i]); - if(elem) - { - ss.str(""); - ss.clear(); - ss<<'T'<GetTemperature()<<'k'; - G4String elemName2 = elem->GetName(); check=""; - pos=elemName2.find_last_of('T'); pos2=elemName2.find_last_of('k'); - - if((pos>0)&&(pos2>0)&&(pos2>pos)) - check= elemName2.substr(pos, pos2-pos+1); - - if(check==G4String(ss.str())) - { - elemName2=elemName2.substr(0, elemName2.find_last_of('T')); - } - - if((elemName2==elemName)&&(elem->GetTemperature()==temp)) - { - index=i; - return true; - } - } - } - - return false; -} - -//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... - - -StorkElement::StorkElement(StorkElement& right): G4Element(right.GetName(), - right.GetSymbol(), right.GetIsotopeVector()->size()) -{ - G4IsotopeVector* isoVec = right.GetIsotopeVector(); - G4double* relVec = right.GetRelativeAbundanceVector(); - - for(G4int i=0; isize()); i++) - { - this->AddIsotope((*isoVec)[i], relVec[i]); - } - temperature = right.GetTemperature(); - csDataTemp = right.GetCSDataTemp(); -} - -StorkElement::StorkElement(G4Element& right): G4Element(right.GetName(), - right.GetSymbol(), right.GetIsotopeVector()->size()) -{ - G4IsotopeVector* isoVec = right.GetIsotopeVector(); - G4double* relVec = right.GetRelativeAbundanceVector(); - - for(G4int i=0; isize()); i++) - { - this->AddIsotope((*isoVec)[i], relVec[i]); - } - temperature = -1; - csDataTemp = -1; -} - -//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... - -const StorkElement& StorkElement::operator=( StorkElement& right) -{ - if (this != &right) - { - G4ElementTable *elemTable = (G4ElementTable*)G4Element::GetElementTable(); - int j = this->GetIndex(); - G4String realName = this->GetName(); - - this->~StorkElement(); - elemTable->erase(elemTable->begin()+j); - - std::vector tempElemTable(elemTable->begin()+j, elemTable->end()); - elemTable->erase(elemTable->begin()+j, elemTable->end()); - - new (this) StorkElement(realName, right.GetSymbol(), right.GetIsotopeVector()->size()); - - elemTable->insert(elemTable->end(), tempElemTable.begin(), tempElemTable.end()); - G4IsotopeVector* isoVec = right.GetIsotopeVector(); - G4double* relVec = right.GetRelativeAbundanceVector(); - - for(G4int i=0; isize()); i++) - { - this->AddIsotope((*isoVec)[i], relVec[i]); - } - temperature = right.GetTemperature(); - csDataTemp = right.GetCSDataTemp(); - } - return *this; -} - -//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... - -G4int StorkElement::operator==(const StorkElement& right) const -{ - return (this == (StorkElement*) &right); -} - -//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... - -G4int StorkElement::operator!=(const StorkElement& right) const -{ - return (this != (StorkElement*) &right); -} - -//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... -/* -std::ostream& operator<<(std::ostream& flux, StorkElement* elem) -{ - G4Element* element = dynamic_cast(elem) - - std::ios::fmtflags mode = flux.flags(); - flux.setf(std::ios::fixed,std::ios::floatfield); - G4long prec = flux.precision(3); - - flux - << " Element: " << element->GetName() << " (" << element->fSymbol << ")" - << " Z = " << std::setw(4) << std::setprecision(1) << element->fZeff - << " N = " << std::setw(5) << std::setprecision(1) << element->fNeff - << " A = " << std::setw(6) << std::setprecision(2) - << (element->fAeff)/(g/mole) << " g/mole"; - - for (size_t i=0; ifNumberOfIsotopes; i++) - flux - << "\n ---> " << (*(element->theIsotopeVector))[i] - << " abundance: " << std::setw(6) << std::setprecision(2) - << (element->fRelativeAbundanceVector[i])/perCent << " %"; - - flux.precision(prec); - flux.setf(mode,std::ios::floatfield); - return flux; -} - -//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... - - std::ostream& operator<<(std::ostream& flux, StorkElement& element) -{ - flux << &element; - return flux; -} - -//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... - -std::ostream& operator<<(std::ostream& flux, G4ElementTable ElementTable, G4bool Stork) -{ - //Dump info for all known elements - flux << "\n***** Table : Nb of elements = " << ElementTable.size() - << " *****\n" << G4endl; - if(Stork) - { - for (size_t i=0; i(ElementTable[i])<< G4endl << G4endl; - } - } - - else - { - for (size_t i=0; iGetCollectionID(SDname + "/Tally"); - - // Clear containers - if(eventData) delete eventData; - eventData = NULL; -} - - -// EndOfEventAction() -// Actions taken at the end of each event. Convert the tally hit collection -// data to a StorkEventData container. -void StorkEventAction::EndOfEventAction(const G4Event *anEvent) -{ -#ifdef G4TIMEEA - G4Timer calcTimer; - calcTimer.Start(); -#endif - - // Local variables - G4int numElements = 0; // Number of elements in a hit collection - const SiteVector *fSiteVector = NULL; - const DblVector *fnEnergy = NULL; - const NeutronSources *survivors = NULL; - const NeutronSources *delayed = NULL; - StorkTallyHit *aTally = NULL; - - // Create a new event data container - if(eventData) delete eventData; - eventData = NULL; - eventData = new StorkEventData(); - eventData->eventNum = anEvent->GetEventID(); - - // Get the hit collection for this event - G4HCofThisEvent *HCE = anEvent->GetHCofThisEvent(); - - // Get the individual hit collections - TallyHC *tFuelHC = (TallyHC*)(HCE->GetHC(tfHCID)); -// TallyHC *tModHC = (TallyHC*)(HCE->GetHC(tmHCID)); - - // Unpack the tally hit - if(tFuelHC) - { - // Set the tally hit pointer to the first (and only) hit in the - // collection - aTally = (*tFuelHC)[0]; - - // Get pointers to the survivors and delayed neutrons - survivors = aTally->GetSurvivors(); - delayed = aTally->GetDelayed(); - fnEnergy = aTally->GetFissionEnergies(); - - // Insert these into the event data structure - eventData->survivors->insert(eventData->survivors->begin(), - survivors->begin(),survivors->end()); - eventData->delayed->insert(eventData->delayed->begin(), - delayed->begin(),delayed->end()); - eventData->fnEnergy->insert(eventData->fnEnergy->begin(), - fnEnergy->begin(),fnEnergy->end()); - - // Get a pointer to the site vector and find the number of sites - fSiteVector = (*tFuelHC)[0]->GetFissionSites(); - numElements = fSiteVector->size(); - - // Copy the contents of the site vector into the event data container - eventData->fSites->reserve(numElements); - - for(G4int i=0; ifSites->push_back(StorkTripleFloat((*fSiteVector)[i])); - } - - eventData->numNProd += (*tFuelHC)[0]->GetNProd(); - eventData->numNLost += (*tFuelHC)[0]->GetNLost(); - eventData->numDProd += (*tFuelHC)[0]->GetDProd(); - - eventData->totalLifetime += (*tFuelHC)[0]->GetTotalLifetime(); - } - -#ifdef G4TIMEEA - calcTimer.Stop(); - eventTimer.Stop(); - - G4cout << "Event Timing:" << G4endl - << "Total time: " << eventTimer << G4endl - << "Calculation time: " << calcTimer << G4endl; -#endif -} diff --git a/G4STORK/src/StorkHPNeutronBuilder.cc b/G4STORK/src/StorkHPNeutronBuilder.cc deleted file mode 100755 index 74ea9413..00000000 --- a/G4STORK/src/StorkHPNeutronBuilder.cc +++ /dev/null @@ -1,184 +0,0 @@ -/* -StorkHPNeutronBuilder.cc - -Created by: Liam Russell -Date: 23-02-2012 -Modified: 11-03-2013 - -Source code for StorkHPNeutronBuilder class. - -*/ - - -// Include header file -#include "StorkHPNeutronBuilder.hh" - -// Constructor -StorkHPNeutronBuilder::StorkHPNeutronBuilder(G4String dir) -{ - // Set temperature for cross sections - dirName = dir; - - // Set default FS temperature - fsTemp=0.; - - // Initialize the applicability limits - theMin = theIMin = 0.*MeV; - theMax = theIMax = 20.*MeV; - - // Initialize data pointers - theHPCaptureData = 0; - theHPInelasticData = 0; - theHPElasticData = 0; - theHPFissionData = 0; - HPCaptureData = 0; - HPInelasticData = 0; - HPElasticData = 0; - HPFissionData = 0; - nElasticModel = 0; - nInelasticModel = 0; - nFissionModel = 0; - nCaptureModel = 0; - - // Insure that the slave processes do not output the physics process table -#ifdef G4USE_TOPC - if(!TOPC_is_master()) - { - G4HadronicProcessStore *theStore = G4HadronicProcessStore::Instance(); - theStore->SetVerbose(0); - } -#endif -} - -// Destructor -StorkHPNeutronBuilder::~StorkHPNeutronBuilder() -{ - // Delete the cross section data - if(theHPCaptureData!=NULL) - delete theHPCaptureData; - if(theHPInelasticData!=NULL) - delete theHPInelasticData; - if(theHPFissionData!=NULL) - delete theHPFissionData; - if(theHPElasticData!=NULL) - delete theHPElasticData; - if(HPCaptureData!=NULL) - delete HPCaptureData; - if(HPInelasticData!=NULL) - delete HPInelasticData; - if(HPFissionData!=NULL) - delete HPFissionData; - if(HPElasticData!=NULL) - delete HPElasticData; -} - - -// Build( Elastic Process ) -// Build the elastic model and data. -// Set the limits of applicability for the model -void StorkHPNeutronBuilder::Build(G4HadronElasticProcess *aP) -{ - // Create the model and data - if(nElasticModel==0) nElasticModel = new StorkNeutronHPElastic(fsTemp); - if(theHPElasticData==0&&HPElasticData==0) - { - if(dirName == "DEFAULT") - theHPElasticData = new G4NeutronHPElasticData(); - else - HPElasticData = new StorkNeutronHPCSData('E', dirName, fsTemp); - } - - - // Set the limits of the model - nElasticModel->SetMinEnergy(theMin); - nElasticModel->SetMaxEnergy(theMax); - - // Register both - if(dirName == "DEFAULT") - aP->AddDataSet(theHPElasticData); - else - aP->AddDataSet(HPElasticData); - aP->RegisterMe(nElasticModel); -} - - -// Build( Inelastic Process ) -// Build the elastic model and data. -// Set the limits of applicability for the model -void StorkHPNeutronBuilder::Build(G4NeutronInelasticProcess *aP) -{ - // Create the model and data - if(nInelasticModel==0) nInelasticModel = new StorkNeutronHPInelastic(fsTemp); - if(theHPInelasticData==0&&HPInelasticData==0) - { - if(dirName == "DEFAULT") - theHPInelasticData = new G4NeutronHPInelasticData(); - else - HPInelasticData = new StorkNeutronHPCSData('I', dirName, fsTemp); - } - // Set the limits of the model - nInelasticModel->SetMinEnergy(theIMin); - nInelasticModel->SetMaxEnergy(theIMax); - - // Register both - if(dirName == "DEFAULT") - aP->AddDataSet(theHPInelasticData); - else - aP->AddDataSet(HPInelasticData); - aP->RegisterMe(nInelasticModel); -} - - -// Build( Fission Process ) -// Build the elastic model and data. -// Set the limits of applicability for the model -void StorkHPNeutronBuilder::Build(G4HadronFissionProcess *aP) -{ - // Create the model and data - if(nFissionModel==0) nFissionModel = new StorkNeutronHPFission(fsTemp); - if(theHPFissionData==0&&HPFissionData==0) - { - if(dirName == "DEFAULT") - theHPFissionData = new G4NeutronHPFissionData(); - else - HPFissionData = new StorkNeutronHPCSData('F', dirName, fsTemp); - } - // Set the limits of the model - nFissionModel->SetMinEnergy(theMin); - nFissionModel->SetMaxEnergy(theMax); - // Register both - if(dirName == "DEFAULT") - aP->AddDataSet(theHPFissionData); - else - aP->AddDataSet(HPFissionData); - aP->RegisterMe(nFissionModel); -} - - -// Build( Capture Process ) -// Build the elastic model and data. -// Set the limits of applicability for the model -void StorkHPNeutronBuilder::Build(G4HadronCaptureProcess *aP) -{ - // Create the model and data - if(nCaptureModel==0) nCaptureModel = new StorkNeutronHPCapture(fsTemp); - if(theHPCaptureData==0&&HPCaptureData==0) - { - if(dirName == "DEFAULT") - theHPCaptureData = new G4NeutronHPCaptureData(); - else - HPCaptureData = new StorkNeutronHPCSData('C', dirName, fsTemp); - } - // Set the limits of the model - nCaptureModel->SetMinEnergy(theMin); - nCaptureModel->SetMaxEnergy(theMax); - - // Register both - if(dirName == "DEFAULT") - aP->AddDataSet(theHPCaptureData); - else - aP->AddDataSet(HPCaptureData); - aP->RegisterMe(nCaptureModel); -} - - diff --git a/G4STORK/src/StorkHadProjectile.cc b/G4STORK/src/StorkHadProjectile.cc deleted file mode 100755 index 77239561..00000000 --- a/G4STORK/src/StorkHadProjectile.cc +++ /dev/null @@ -1,60 +0,0 @@ -// -// StorkHadProjectile.cc -// G4-STORK_AT -// -// Created by Andrew Tan on 2014-07-30. -// Copyright (c) 2014 andrewtan. All rights reserved. -// - -#include "StorkHadProjectile.hh" - - -StorkHadProjectile::StorkHadProjectile() -{ - theMat = 0; - theDef = 0; - theTime = 0.0; - theBoundEnergy = 0.0; -} - -StorkHadProjectile::StorkHadProjectile(const G4Track &aT) -{ - Initialise(aT); -} - -StorkHadProjectile::StorkHadProjectile(const G4DynamicParticle &aT, const G4Material *Mat = NULL) -: -theOrgMom(aT.Get4Momentum()), -theDef(aT.GetDefinition()) -{ - G4LorentzRotation toZ; - toZ.rotateZ(-theOrgMom.phi()); - toZ.rotateY(-theOrgMom.theta()); - theMom = toZ*theOrgMom; - toLabFrame = toZ.inverse(); - theTime = 0.0; - theBoundEnergy = 0.0; - theMat = Mat; -} - -StorkHadProjectile::~StorkHadProjectile() -{} - -void StorkHadProjectile::Initialise(const G4Track &aT) -{ - theMat = aT.GetMaterial(); - theOrgMom = aT.GetDynamicParticle()->Get4Momentum(); - theDef = aT.GetDefinition(); - - G4LorentzRotation toZ; - toZ.rotateZ(-theOrgMom.phi()); - toZ.rotateY(-theOrgMom.theta()); - theMom = toZ*theOrgMom; - toLabFrame = toZ.inverse(); - - //VI time of interaction starts from zero - // not global time of a track - theTime = 0.0; - theBoundEnergy = 0.0; -} - diff --git a/G4STORK/src/StorkHadronicInteraction.cc b/G4STORK/src/StorkHadronicInteraction.cc deleted file mode 100755 index 3b544d33..00000000 --- a/G4STORK/src/StorkHadronicInteraction.cc +++ /dev/null @@ -1,222 +0,0 @@ -// -// StorkHadronicInteraction.cpp -// G4-STORK_AT -// -// Created by Andrew Tan on 2014-07-30. -// Copyright (c) 2014 andrewtan. All rights reserved. -// - -#include "StorkHadronicInteraction.hh" -#include "G4HadronicInteraction.hh" -#include "G4SystemOfUnits.hh" -#include "G4HadronicInteractionRegistry.hh" -#include "G4HadronicException.hh" - -StorkHadronicInteraction::StorkHadronicInteraction(const G4String& modelName) : -verboseLevel(0), theMinEnergy(0.0), theMaxEnergy(25.0*GeV), -isBlocked(false), recoilEnergyThreshold(0.0), theModelName(modelName), -epCheckLevels(DBL_MAX, DBL_MAX) -{ - G4HadronicInteractionRegistry::Instance()->RegisterMe(this); -} - - -StorkHadronicInteraction::~StorkHadronicInteraction() -{ - G4HadronicInteractionRegistry::Instance()->RemoveMe(this); -} - - -G4double -StorkHadronicInteraction::SampleInvariantT(const G4ParticleDefinition*, - G4double, G4int, G4int) -{ - return 0.0; -} - -G4double StorkHadronicInteraction::GetMinEnergy( - const G4Material *aMaterial, const G4Element *anElement ) const -{ - if( IsBlocked(aMaterial) ) { return 0.0; } - if( IsBlocked(anElement) ) { return 0.0; } - size_t length = theMinEnergyListElements.size(); - if(0 < length) { - for(size_t i=0; i 1 ) { - G4cout << "*** Warning from HadronicInteraction::GetMinEnergy" << G4endl - << " material " << aMaterial->GetName() - << " not found in min energy List" << G4endl; - } - return theMinEnergy; -} - -void StorkHadronicInteraction::SetMinEnergy(G4double anEnergy, - const G4Element *anElement ) -{ - if( IsBlocked(anElement) ) { - G4cout << "*** Warning from HadronicInteraction::SetMinEnergy" << G4endl - << " The model is not active for the Element " - << anElement->GetName() << "." << G4endl; - } - size_t length = theMinEnergyListElements.size(); - if(0 < length) { - for(size_t i=0; i(anEnergy, anElement)); -} - -void StorkHadronicInteraction::SetMinEnergy(G4double anEnergy, - const G4Material *aMaterial ) -{ - if( IsBlocked(aMaterial) ) { - G4cout << "*** Warning from HadronicInteraction::SetMinEnergy" << G4endl - << " The model is not active for the Material " - << aMaterial->GetName() << "." << G4endl; - } - size_t length = theMinEnergyList.size(); - if(0 < length) { - for(size_t i=0; i(anEnergy, aMaterial)); -} - -G4double StorkHadronicInteraction::GetMaxEnergy(const G4Material *aMaterial, - const G4Element *anElement ) const -{ - if( IsBlocked(aMaterial) ) { return 0.0; } - if( IsBlocked(anElement) ) { return 0.0; } - size_t length = theMaxEnergyListElements.size(); - if(0 < length) { - for(size_t i=0; i 1 ) { - G4cout << "*** Warning from HadronicInteraction::GetMaxEnergy" << G4endl - << " material " << aMaterial->GetName() - << " not found in min energy List" << G4endl; - } - return theMaxEnergy; -} - -void StorkHadronicInteraction::SetMaxEnergy(G4double anEnergy, - const G4Element *anElement ) -{ - if( IsBlocked(anElement) ) { - G4cout << "*** Warning from HadronicInteraction::SetMaxEnergy" << G4endl - << "Warning: The model is not active for the Element " - << anElement->GetName() << "." << G4endl; - } - size_t length = theMaxEnergyListElements.size(); - if(0 < length) { - for(size_t i=0; i(anEnergy, anElement)); -} - -void StorkHadronicInteraction::SetMaxEnergy(G4double anEnergy, - const G4Material *aMaterial ) -{ - if( IsBlocked(aMaterial) ) { - G4cout << "*** Warning from HadronicInteraction::SetMaxEnergy" << G4endl - << "Warning: The model is not active for the Material " - << aMaterial->GetName() << "." << G4endl; - } - size_t length = theMaxEnergyList.size(); - if(0 < length) { - for(size_t i=0; i(anEnergy, aMaterial)); -} - -void StorkHadronicInteraction::DeActivateFor( const G4Material *aMaterial ) -{ - theBlockedList.push_back(aMaterial); -} - -void G4HadronicInteraction::DeActivateFor( const G4Element *anElement ) -{ - theBlockedListElements.push_back(anElement); -} - - -G4bool StorkHadronicInteraction::IsBlocked(const G4Material* aMaterial) const -{ - for (size_t i=0; i StorkHadronicInteraction::GetFatalEnergyCheckLevels() const -{ - // default level of Check - return std::pair(2.*perCent, 1. * GeV); -} - -std::pair -StorkHadronicInteraction::GetEnergyMomentumCheckLevels() const -{ - return epCheckLevels; -} - - -void StorkHadronicInteraction::ModelDescription(std::ostream& outFile) const -{ - outFile << "The description for this model has not been written yet.\n"; -} - diff --git a/G4STORK/src/StorkHeatTransfer.cc b/G4STORK/src/StorkHeatTransfer.cc deleted file mode 100755 index 6ec76517..00000000 --- a/G4STORK/src/StorkHeatTransfer.cc +++ /dev/null @@ -1,304 +0,0 @@ -#include "StorkHeatTransfer.hh" -// Constructor -StorkHeatTransfer::StorkHeatTransfer(const StorkParseInput* fIn) -{ - - worldname = fIn->GetWorld(); - - if(worldname == "SLOWPOKE") - InitializeSlowpokeModel(fIn); - - -} -// Destructor -StorkHeatTransfer::~StorkHeatTransfer(void) -{ -} - -void StorkHeatTransfer::InitializeSlowpokeModel(const StorkParseInput* input) -{ - dt = input->GetRunDuration(); - heatTransferCoeff = input->GetHeatTransferCoefficient(); - temp_infty = input->GetAmbientTemperature(); - saveMaterialData = input->SaveTemperature(); - saveMaterialfilename = input->GetTemperatureDataFile(); - fissionToEnergyCoeff = input->GetFissionToEnergyCoefficient(); - baselineFissionRate = input->GetBaselineFissionRate(); - createHeader = true; - return; -} - -void StorkHeatTransfer::RunThermalCalculation(MSHSiteVector fissionSites) -{ - fSites = &(fissionSites); - - if(worldname == "SLOWPOKE"){ - RunSlowpokeModel(); - } - - return; -} - -void StorkHeatTransfer::RunSlowpokeModel() -{ - - SetFuelDimensions(theWorld->GetFuelDimensions()); - CalcHeatDistribution(); - - UpdateFuelProperties(theWorld->GetFuelTemperatures(),theWorld->GetFuelDensities(),theWorld->GetFuelRadii()); - - if(saveMaterialData) - SaveSLOWPOKEFuelProperties(saveMaterialfilename); - - theWorld->SetPhysChanged(true); - theWorld->SetMatChanged(true); - - return; -} - -// -void StorkHeatTransfer::UpdateFuelProperties(G4double FuelTemperatures[],G4double* /*FuelDensities[]*/,G4double FuelRadii[]) -{ - - //Initialize variables. - StorkMaterialHT *material; - G4double newTemperature; -// G4double newDensity; -// G4double newRadius; - G4double oldDensity; - G4String fuelNum; - const char * num; - G4double heatCapacity; - G4double mass; - G4double surfaceArea; - G4double HeatInMaterial; - G4int size = fnDistribution.size(); - fuelTempAvg = fuelDensityAvg = fuelRadiusAvg = 0.0; - - G4double TotalRunFissions = fSites->size(); - - G4double heatGenerated = CalcEffectiveHeatGenerated(TotalRunFissions); - - //Get material map. - StorkMaterialMap *matMap = theWorld->GetMaterialMap(); - - //Iterate through fission material list. - std::map< G4String, G4double >::iterator it; - for(it = fnDistribution.begin(); it != fnDistribution.end(); it++){ - - //Get the fuel name and number ID; - fuelNum = (it->first); - - num = (fuelNum.erase(0,4)).c_str(); - - G4int i = std::atoi(num); - - //Calculate the heat generated in each material. - HeatInMaterial = heatGenerated*(it->second); - - //Get material. - material = static_cast((*matMap)[it->first]); - - //Fuel dimensions in mm convert to cm. - G4double radius = FuelRadii[i]*pow(10,-1); - G4double length = fuelDimensions[2]*pow(10,-1); - - //Get material and geometric properties. - heatCapacity = material->GetSpecificHeatCapacity()*pow(10,9); - oldDensity = material->GetDensity()*cm3/g; - mass = oldDensity*CLHEP::pi*length*radius*radius; - surfaceArea = 2*CLHEP::pi*length*radius; - - //Calculate new material properties. - newTemperature = CalcFuelTemperature(HeatInMaterial, mass, surfaceArea, FuelTemperatures[i], heatCapacity); - //newDensity = CalcFuelDensity(newTemperature); - //newRadius = CalcFuelRadius(FuelRadii[i], oldDensity, newDensity); - - //Set the new fuel properties. - FuelTemperatures[i] = newTemperature; - //FuelDensities[i] = newDensity; - //FuelRadii[i] = newRadius; - - //Calculate averages. - if(saveMaterialData){ - fuelTempAvg += G4double(newTemperature/size); - // fuelDensityAvg += newDensity/size; - // fuelRadiusAvg += newRadius/size; - } - - } - - - return; -} - -void StorkHeatTransfer::CalcHeatDistribution(){ - - - //Get the total number of fissions. - G4int numberOfFissions = fSites->size(); - - //Percentage per fission - G4double fPercent = (1./numberOfFissions); - - //Create material list flag. - //G4bool createList = false; - - //Clear the distribution map. - fnDistribution.clear(); - - //Get pointer to the Navigator - G4Navigator* theNavigator = G4TransportationManager::GetTransportationManager()->GetNavigatorForTracking(); - theNavigator->ResetStackAndState(); - -// if(fnMaterialList.size() == 0) -// createList = true; - - std::vector::iterator itr = fSites->begin(); - - //Iterate through all fission sites of the run. - for(; itr!=fSites->end(); itr++){ - - G4ThreeVector site = itr->GetData(); - - //Get the material. - G4String currentMaterialName = theNavigator->LocateGlobalPointAndSetup(site)->GetLogicalVolume()->GetMaterial()->GetName(); - - //Check to see if it is already in the material list, else create it. - if(fnDistribution[currentMaterialName]){ - fnDistribution[currentMaterialName] += fPercent; - } - else - fnDistribution[currentMaterialName] = fPercent; - - } - - //Calculate the effective fission energy. - - return; - -} - -//Calculates new temperature based on heat generation. Uses FUELPIN solver method. -G4double StorkHeatTransfer::CalcFuelTemperature(G4double heatGeneration, G4double mass, G4double surfaceArea, G4double oldTemp, G4double heatcapacity){ - - //Initialize with proper units. - G4double newTemperature; - //htc in J/cm2*K - G4double htc = heatTransferCoeff*pow(10,-4); - //t left in ns - G4double t = dt*pow(10,-9); - - //Calculate coefficients for new temperature. - G4double a = -htc*surfaceArea/(mass*heatcapacity); - G4double bu = (heatGeneration + htc*surfaceArea*temp_infty)/(mass*heatcapacity); - - //Calculate new temperature. - newTemperature = oldTemp*exp(-a*t) + (1 - exp(-a*t))*(bu/a); - - return newTemperature*kelvin; -} - -// Calculates new density (U2O) based on temperature. http://web.ornl.gov/~webworks/cpr/v823/rpt/109264.pdf -G4double StorkHeatTransfer::CalcFuelDensity(G4double temperature){ - - //Initialize variables. - G4double density, a, b, c, d ,e, t; - t = temperature; - // a = 10970; - a = 6.6160*pow(10,19); - b = 9.99672*pow(10,-1); - c = 1.179*pow(10,-5); - d = -2.429*pow(10,-9); - e = 1.219*pow(10,-12); - - //Calculate using empirical formula. - density = a*pow( (b + c*t + d*pow(t,2) + e*pow(t,3)) ,-3); - - return density; -} - -G4double StorkHeatTransfer::CalcFuelRadius(G4double oldRadius, G4double oldDensity, G4double newDensity) -{ - G4double newRadius = oldRadius*pow( oldDensity/newDensity, 0.5); - if(newRadius>0.212*cm){ - G4cerr << "WARNING: Fuel is expanding beyond limits!" << G4endl; - return oldRadius; - } - - return newRadius; - -} - -void StorkHeatTransfer::SetWorld(StorkWorld* world) -{ - theWorld = world; -} - -void StorkHeatTransfer::SaveSLOWPOKEFuelProperties(G4String filename) -{ - if(createHeader){ - // Declare and open file stream - std::ofstream outFile(filename.c_str(),std::ofstream::app); - - // Check that stream is ready for use - if(!outFile.good()) - { - G4cerr << G4endl << "ERROR: Could not write material temperatures to file. " << G4endl - << "Improper file name: " << filename << G4endl - << "Continuing program without material temperature data output" << G4endl; - - return; - } - outFile.fill(' '); - outFile << " *** SLOWPOKE REACTOR - LUMPED PARAMETER THERMAL MODEL *** " << G4endl; - outFile << " VERSION - 1.0 - DATE: 07/14/2015 " << G4endl; - - outFile << std::setw(18) << " Avg. Fuel Temperature " - << std::setw(18) << " Avg. Fuel Density " - << std::setw(18) << " Avg. Fuel Volume " - << G4endl - << "----------------------------------------------------------------" - << G4endl; - - outFile.close(); - createHeader = false; - } - - std::ofstream outFile(filename.c_str(),std::ofstream::app); - - if(!outFile.good()){ - G4cerr << G4endl << "ERROR: Could not write material temperatures to file. " << G4endl - << "Improper file name: " << filename << G4endl - << "Continuing simulation without material temperature data output" << G4endl; - } - else{ - - outFile << std::setw(18) << fuelTempAvg - << std::setw(18) << fuelDensityAvg - << std::setw(18) << fuelRadiusAvg - << G4endl; - - outFile.close(); - - } - - return; - -} - -G4double StorkHeatTransfer::CalcEffectiveHeatGenerated(G4double currentFissions) -{ - //Get the corresponding baseline fissions. - G4double baselineFissions = baselineFissionRate*dt; - - //If the current rate is less than the baseline than return no heat generated. - if(currentFissions> numPoints; - - // Read in the points and send the pair to the data vector - for(G4int i=0; i> x >> y; - - x *= ux; - y *= uy; - - point = std::make_pair(x,y); - data.push_back(point); - } -} - - -// AddDataPoint() -// Adds a data point on to the data vector -void StorkInterpVector::AddDataPoint(DataPoint point) -{ - DataPointVec::iterator itr = data.begin(); - - // Find the proper place to insert data point - for(; itr != data.end(); itr++) - { - if(point.first > itr->first) - break; - } - - // Add data point and increment the number of points - data.insert(itr,point); - numPoints++; -} - - -// GetY() -// Find the interpolated y-value relative to a given x-value -G4double StorkInterpVector::GetY(G4double xIn) const -{ - // Check if the StorkInterpVector has data - if(!hasData) return DBL_MIN; - - // Local variables - G4int i=1; - G4InterpolationScheme aScheme = LINLIN; - - // Check if the given x-value is outside the data range - // If so return the first/last y-value respectively - if(xIn < data[0].first) - { - return data[0].second; - } - else if(xIn >= data[numPoints-1].first) - { - return data[numPoints-1].second; - } - - // Find the upper bound of the given x-value - for(; i 2) - { - key.toLower(); - - for(G4int i=0; i 2) - { - key.toLower(); - - for(G4int i=0; i - -#include "StorkMaterial.hh" -#include "G4NistManager.hh" -#include "G4UnitsTable.hh" -#include "G4PhysicalConstants.hh" -#include "G4SystemOfUnits.hh" - -//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... - -// Constructor to create a material from scratch - - -StorkMaterial::StorkMaterial(const G4String& name, G4double z, - G4double a, G4double density, - G4State state, G4double temp, G4double pressure) - : G4Material(name, z, a, density, state, temp, pressure) -{ - G4int index; - G4Material* mat = dynamic_cast(this); - G4ElementVector* elemVec = const_cast(mat->GetElementVector()); - - (*elemVec)[0]->GetElementTable()->pop_back(); - - StorkElement* elem = new StorkElement(*((*elemVec)[0])); - delete (*elemVec)[0]; - //When a G4Element object is deleted it sets the pointer in the G4ElementTable in the index that the element was added to when it was created to zero, so we must reAdd the new StorkElement here - elem->GetElementTable()->back()=elem; - elem->SetTemperature(-1); - - if(elem->Exists(temp,index)) - { - (*elemVec)[0]=(*((*elemVec)[0]->GetElementTable()))[index]; - delete elem; - (*elemVec)[0]->GetElementTable()->pop_back(); - } - else - { - elem->SetTemperature(temp); - std::stringstream ss; - ss.str(""); - ss<<'T'<GetTemperature()<<'k'; - G4String elemName = name+ss.str(); - elem->SetName(elemName); - (*elemVec)[0]=elem; - } -} - -//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... - -// Constructor to create a material from a List of constituents -// (elements and/or materials) added with AddElement or AddMaterial - -StorkMaterial::StorkMaterial(const G4String& name, G4double density, - G4int nComponents, - G4State state, G4double temp, G4double pressure) - : G4Material(name, density, nComponents, state, temp, pressure) -{ - -} - -//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... - -// Constructor to create a material from base material - -StorkMaterial::StorkMaterial(const G4String& name, G4double density, - StorkMaterial* bmat, - G4State state, G4double temp, G4double pressure) - : G4Material(name, density, 1, state, temp, pressure) -{ - this->AddMaterial(bmat, 1.); -} - -//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... - -// Fake default constructor - sets only member data and allocates memory -// for usage restricted to object persistency - -StorkMaterial::StorkMaterial(__void__& fake) - : G4Material(fake) -{ -} - -//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... - -StorkMaterial::~StorkMaterial() -{ - // G4cout << "### Destruction of material " << fName << " started" <(this); - - if(element->GetTemperature()<0.) - { - std::stringstream ss; - ss.str(""); - ss<<'T'<SetTemperature(GetTemperature()); - element->SetName(element->GetName()+ss.str()); - mat->AddElement((element), nAtoms); - } - else if(element->Exists(GetTemperature(),index)) - { - mat->AddElement(dynamic_cast((*(element->GetElementTable()))[index]), nAtoms); - } - else - { - std::stringstream ss; - ss.str(""); - ss<<'T'<GetTemperature()<<'k'; - G4String elemName = element->GetName(), check; - int pos=elemName.find_last_of('T'), pos2=elemName.find_last_of('k'); - - if((pos>0)&&(pos2>0)&&(pos2>pos)) - check= elemName.substr(pos, pos2-pos+1); - - StorkElement *newElem = new StorkElement(*element); - - if(check==G4String(ss.str())) - { - ss.str(""); - ss.clear(); - ss<<'T'<SetName(elemName.substr(0, elemName.find_last_of('T'))+ss.str()); - } - else - { - ss.str(""); - ss.clear(); - ss<<'T'<SetName(element->GetName()+ss.str()); - } - newElem->SetTemperature(GetTemperature()); - mat->AddElement((newElem), nAtoms); - } - -} - -//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... - -// AddElement -- composition by fraction of mass - -void StorkMaterial::AddElement(StorkElement* element, G4double fraction) -{ - G4Material* mat = dynamic_cast(this); - // filling ... - G4int index; - if(element->GetTemperature()<0.) - { - element->SetTemperature(GetTemperature()); - std::stringstream elemName; - elemName << element->GetName() << 'T' << element->GetTemperature() << 'k'; - element->SetName(elemName.str()); - mat->AddElement((element), fraction); - } - else if(element->Exists(GetTemperature(),index)) - { - mat->AddElement(dynamic_cast((*(element->GetElementTable()))[index]), fraction); - } - else - { - std::stringstream ss; - ss.str(""); - ss<<'T'<GetTemperature()<<'k'; - G4String elemName = element->GetName(), check; - int pos=elemName.find_last_of('T'), pos2=elemName.find_last_of('k'); - - if((pos>0)&&(pos2>0)&&(pos2>pos)) - check= elemName.substr(pos, pos2-pos+1); - - StorkElement *newElem = new StorkElement(*element); - - if(check==G4String(ss.str())) - { - ss.str(""); - ss.clear(); - ss<<'T'<SetName(elemName.substr(0, elemName.find_last_of('T'))+ss.str()); - } - else - { - ss.str(""); - ss.clear(); - ss<<'T'<SetName(element->GetName()+ss.str()); - } - newElem->SetTemperature(GetTemperature()); - mat->AddElement((newElem), fraction); - } -} - -//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... - -// AddMaterial -- composition by fraction of mass - -void StorkMaterial::AddMaterial(StorkMaterial* material, G4double fraction) -{ - -G4int index; - -G4Material* mat = dynamic_cast(this); -G4Material* mat2 = dynamic_cast(material); -G4String name = mat->GetName()+"-"+mat2->GetName(); -G4Material* temp = new G4Material(name, mat2->GetDensity(), mat2->GetNumberOfElements(), mat2->GetState(), mat2->GetTemperature(), mat2->GetPressure()); -const G4double* fracVec = mat2->GetFractionVector(); - -for (size_t elm=0; elmGetNumberOfElements(); ++elm) -{ - StorkElement* element = static_cast((*(mat2->GetElementVector()))[elm]); - if(element->Exists(this->GetTemperature(), index)) - { - temp->AddElement(dynamic_cast((*(element->GetElementTable()))[index]), fracVec[elm]); - } - else - { - std::stringstream ss; - ss.str(""); - ss<<'T'<GetTemperature()<<'k'; - G4String elemName = element->GetName(), check=""; - int pos=elemName.find_last_of('T'), pos2=elemName.find_last_of('k'); - - if((pos>0)&&(pos2>0)&&(pos2>pos)) - check= elemName.substr(pos, pos2-pos+1); - - StorkElement *newElem = new StorkElement(*element); - - if(check==G4String(ss.str())) - { - ss.str(""); - ss.clear(); - ss<<'T'<GetTemperature()<<'k'; - newElem->SetName(elemName.substr(0, elemName.find_last_of('T'))+ss.str()); - } - else - { - ss.str(""); - ss.clear(); - ss<<'T'<GetTemperature()<<'k'; - newElem->SetName(element->GetName()+ss.str()); - } - newElem->SetTemperature(this->GetTemperature()); - temp->AddElement((newElem), fracVec[elm]); - } -} - -mat->AddMaterial(temp, fraction); -delete temp; -(G4Material::GetMaterialTable())->pop_back(); -} - -//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... - -void StorkMaterial::SetTemperature(G4double matTemp, G4bool UpdateElemTemp) -{ - //this should work but seems to change results, even when we use an alternative method by reassigning the logical volumes to point to new materials with the desired properties - // need to fix when UpdateElemTemp=true - G4MaterialTable *matTable = (G4MaterialTable*)G4Material::GetMaterialTable(); - int j = this->GetIndex(); - - StorkMaterial *tempMat = new StorkMaterial(this->GetName()+"1", this->GetDensity(), this->GetNumberOfElements(), this->GetState(), this->GetTemperature(), this->GetPressure()); - - G4Material* g4Mat2 = dynamic_cast(tempMat); - G4ElementVector* elemVec2 = const_cast (this->GetElementVector()); - G4double* fracVec2 = const_cast (this->GetFractionVector()); - for(G4int k=0; kGetNumberOfElements()); k++) - { - g4Mat2->AddElement(dynamic_cast((*elemVec2)[k]), fracVec2[k]); - } - - this->~StorkMaterial(); - matTable->erase(matTable->begin()+j); - G4String realName = (tempMat->GetName()).substr(0, (tempMat->GetName()).size()-1); - - std::vector tempMatTable(matTable->begin()+j, matTable->end()); - matTable->erase(matTable->begin()+j, matTable->end()); - - if(UpdateElemTemp) - new (this) StorkMaterial(realName, tempMat->GetDensity(), tempMat, tempMat->GetState(), matTemp, tempMat->GetPressure()); - else - new (this) StorkMaterial(realName, tempMat->GetDensity(), tempMat->GetNumberOfElements(), tempMat->GetState(), matTemp, tempMat->GetPressure()); - - matTable->insert(matTable->end(), tempMatTable.begin(), tempMatTable.end()); - - if(!UpdateElemTemp) - { - G4Material* g4Mat = dynamic_cast(this); - G4ElementVector* elemVec = const_cast (tempMat->GetElementVector()); - G4double* fracVec = const_cast (tempMat->GetFractionVector()); - for(G4int k=0; kGetNumberOfElements()); k++) - { - g4Mat->AddElement(dynamic_cast((*elemVec)[k]), fracVec[k]); - } - } - - delete tempMat; - matTable->pop_back(); -} - -//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... - -StorkMaterial::StorkMaterial(StorkMaterial& right): G4Material(right.GetName(), right.GetDensity(), - right.GetNumberOfElements(), right.GetState(), right.GetTemperature(), right.GetPressure()) -{ - G4ElementVector* elemVec = const_cast (right.GetElementVector()); - G4double* fracVec = const_cast (right.GetFractionVector()); - for(G4int i=0; iAddElement(dynamic_cast((*elemVec)[i]), fracVec[i]); - } - -} - -//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... - -const StorkMaterial& StorkMaterial::operator=(StorkMaterial& right) -{ - if (this != &right) - { - G4MaterialTable *matTable = (G4MaterialTable*)G4Material::GetMaterialTable(); - int j = this->GetIndex(); - G4String realName = this->GetName(); - - this->~StorkMaterial(); - matTable->erase(matTable->begin()+j); - - std::vector tempMatTable(matTable->begin()+j, matTable->end()); - matTable->erase(matTable->begin()+j, matTable->end()); - - new (this) StorkMaterial(realName, right.GetDensity(), &right, right.GetState(), right.GetTemperature(), right.GetPressure()); - - matTable->insert(matTable->end(), tempMatTable.begin(), tempMatTable.end()); - } - return *this; -} - -//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... - -G4int StorkMaterial::operator==(const StorkMaterial& right) const -{ - return (this == (StorkMaterial *) &right); -} - -//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... - -G4int StorkMaterial::operator!=(const StorkMaterial& right) const -{ - return (this != (StorkMaterial *) &right); -} -//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... diff --git a/G4STORK/src/StorkNeutronHPCSData.cc b/G4STORK/src/StorkNeutronHPCSData.cc deleted file mode 100755 index 84c96f68..00000000 --- a/G4STORK/src/StorkNeutronHPCSData.cc +++ /dev/null @@ -1,323 +0,0 @@ -/* -StorkNeutronHPCSData.cc - -Created by: Liam Russell -Date: 22-06-2011 -Modified: 17-02-2012 - -Source code for StorkNeutronHPCSData class. - -*/ - - -// Include header file - -#include "StorkNeutronHPCSData.hh" - - -G4bool StorkNeutronHPCSData::IsApplicable(const G4DynamicParticle*aP, - const G4Element*) -{ - G4bool result = true; - G4double eKin = aP->GetKineticEnergy(); - if(eKin>20*MeV||aP->GetDefinition()!=G4Neutron::Neutron()) result = false; - return result; -} - - -StorkNeutronHPCSData::StorkNeutronHPCSData(char aType, G4String dirName, G4double FSTemp) -{ - // TKDB - theCrossSections = 0; -// numMaxOL = OL; - numMaxOL = INT_MAX; - reactionType = aType; - fsTemp = FSTemp; - - BuildPhysicsTable(*G4Neutron::Neutron(), dirName); -} - - -StorkNeutronHPCSData::~StorkNeutronHPCSData() -{ - // TKDB - if ( theCrossSections != 0 ) - theCrossSections->clearAndDestroy(); - delete theCrossSections; -} - -G4bool StorkNeutronHPCSData::IsIsoApplicable( const G4DynamicParticle* dp , - G4int /*Z*/ , G4int /*A*/ , - const G4Element* /*elm*/ , - const G4Material* /*mat*/ ) -{ - - G4double eKin = dp->GetKineticEnergy(); - if ( eKin > GetMaxKinEnergy() - || eKin < GetMinKinEnergy() - || dp->GetDefinition() != G4Neutron::Neutron() ) return false; - - return true; -} - - -/*G4bool StorkNeutronHPCSData::IsElementApplicable(const G4DynamicParticle*, G4int, const G4Material*) -{ - G4double eKin = dp->GetKineticEnergy(); - if ( eKin > GetMaxKinEnergy() - || eKin < GetMinKinEnergy() - || dp->GetDefinition() != G4Neutron::Neutron() ) return false; - - return true; -}*/ - -G4double StorkNeutronHPCSData::GetIsoCrossSection( const G4DynamicParticle* dp , - G4int /*Z*/ , G4int /*A*/ , - const G4Isotope* /*iso*/ , - const G4Element* element , - const G4Material* material ) -{ - if ( dp->GetKineticEnergy() == ke_cache && element == element_cache && material == material_cache ) return xs_cache; - - ke_cache = dp->GetKineticEnergy(); - element_cache = element; - material_cache = material; - G4double xs = GetCrossSection( dp , element , material->GetTemperature() ); - xs_cache = xs; - return xs; -} - -/*G4double StorkNeutronHPCSData::GetElementCrossSection(const G4DynamicParticle* dynPart, G4int Z, const G4Material* mat) -{ - if ( dp->GetKineticEnergy() == ke_cache && mat == material_cache ) return xs_cache; - - ke_cache = dp->GetKineticEnergy(); - material_cache = mat; - G4double xs = GetCrossSection( dp , element , mat->GetTemperature() ); - xs_cache = xs; - return xs; -}*/ - - -void StorkNeutronHPCSData::BuildPhysicsTable(const G4ParticleDefinition& aP, G4String dirName) -{ - - if(&aP!=G4Neutron::Neutron()) - throw G4HadronicException(__FILE__, __LINE__, - "Attempt to use NeutronHP data for particles other than neutrons!!!"); - - - size_t numberOfElements = G4Element::GetNumberOfElements(); - - if ( theCrossSections == 0 ) - theCrossSections = new G4PhysicsTable( numberOfElements ); - else - return; // Skip this if table is already built *** - - /* *** I have NO idea why this is not standard behaviour!!!! If this return - is not included, every time the physics is rebuilt, another new data set - is added. This results in all physical memory being consumed. - -Liam 20/08/2012 - */ - - // Null pointers to tell G4NeutronHPElementData what type of data to return - G4NeutronHPCaptureData *Cptr = NULL; - G4NeutronHPFissionData *Fptr = NULL; - G4NeutronHPElasticData *Eptr = NULL; - G4NeutronHPInelasticData *Iptr = NULL; - - ElementNames elemNames; - elemNames.SetElementNames(); - - // make a PhysicsVector for each element - static const G4ElementTable *theElementTable = G4Element::GetElementTable(); - for( size_t i=0; iMakePhysicsVector((*theElementTable)[i], Cptr, dirName); - break; - case 'E': - physVec = StorkNeutronHPDataConstructor:: - Instance(dirName)->MakePhysicsVector((*theElementTable)[i], Eptr, dirName); - break; - case 'I': - physVec = StorkNeutronHPDataConstructor:: - Instance(dirName)->MakePhysicsVector((*theElementTable)[i], Iptr, dirName); - break; - case 'F': - physVec = StorkNeutronHPDataConstructor:: - Instance(dirName)->MakePhysicsVector((*theElementTable)[i], Fptr, dirName); - break; - } - - theCrossSections->push_back(physVec); - } - - elemNames.ClearStore(); -} - - -void StorkNeutronHPCSData::DumpPhysicsTable(const G4ParticleDefinition& aP) -{ - if(&aP!=G4Neutron::Neutron()) - throw G4HadronicException(__FILE__, __LINE__, - "Attempt to use NeutronHP data for particles other than neutrons!!!"); - - - // Dump element based cross section range 10e-5 eV to 20 MeV 10 point per - // decade in barn - G4String type; - - // Set the reaction type - switch(reactionType) - { - case 'C': - type = "Capture "; - break; - case 'E': - type = "Elastic "; - break; - case 'I': - type = "Inelastic "; - break; - case 'F': - type = "Fission "; - break; - } - - G4cout << G4endl << G4endl << type << "Cross Section of Neutron HP"<< G4endl - << "(Pointwise cross-section at 0 Kelvin.)" << G4endl << G4endl - << "Name of Element" << G4endl << "Energy[eV] XS[barn]" << G4endl - << G4endl; - - size_t numberOfElements = G4Element::GetNumberOfElements(); - static const G4ElementTable *theElementTable = G4Element::GetElementTable(); - - for ( size_t i = 0 ; i < numberOfElements ; ++i ) - { - - G4cout << (*theElementTable)[i]->GetName() << G4endl; - - for (G4int ie = 0 ; ie < 130 ; ie++ ) - { - G4double eKinetic = 1.0e-5 * std::pow ( 10.0 , ie/10.0 ) *eV; - G4bool outOfRange = false; - - if ( eKinetic < 20*MeV ) - { - G4cout << eKinetic/eV << " " - << (*((*theCrossSections)(i))).GetValue(eKinetic,outOfRange)/barn - << G4endl; - } - } - - G4cout << G4endl; - } -} - - -G4double StorkNeutronHPCSData:: -GetCrossSection(const G4DynamicParticle* aP, const G4Element* elem, G4double /*aT*/) -{ - StorkElement *anE = dynamic_cast (const_cast(elem)); - - if(reactionType == 'F' && anE->GetZ() < 90) return 0; - - G4bool outOfRange; - G4int index = anE->GetIndex(); - - // prepare neutron - G4double eKinetic = aP->GetKineticEnergy(); - G4ReactionProduct theNeutron( aP->GetDefinition() ); - theNeutron.SetMomentum( aP->GetMomentum() ); - theNeutron.SetKineticEnergy( eKinetic ); - G4ThreeVector neutronVelocity = - 1./G4Neutron::Neutron()->GetPDGMass()*theNeutron.GetMomentum(); - - // prepare thermal nucleus - G4Nucleus aNuc; - G4double xSection; - G4double eps = 0.0001; - G4double theA = anE->GetN(); - G4double theZ = anE->GetZ(); - G4double eleMass; - - eleMass = (G4NucleiProperties::GetNuclearMass(static_cast(theA+eps), - static_cast(theZ+eps))) / G4Neutron::Neutron()->GetPDGMass(); - - if(anE->GetCSDataTemp()==-1) - return 0.; - - // Find the temperature difference between the temperature the cross - // section was evaluated at versus the temperature of the material - G4double tempDiff = anE->GetTemperature() - anE->GetCSDataTemp(); - - // If there is no temperature difference, return the cross section directly - if(std::abs(tempDiff) <= 0.1) - { - xSection = (*((*theCrossSections)(index))).GetValue(eKinetic, outOfRange); - //G4cout << "For element Z: " << theZ << " A: " << theA << " for reaction type: " << reactionType << " at energy: " << eKinetic << " the cross-section is " << xSection << endl; - return xSection; - } - - // Declarations for averaging loop - G4ReactionProduct boosted; // neutron in rest frame of nucleus - G4double aXsection; // random xsec value - G4double result = 0; // final averaged cross section - G4double buffer = 1; // temporary value for previous average - G4int counter = 0; // counts the number averaged xsec sets - - // Reset the loop counters if standard Doppler broadening is being used -// if(std::abs(numMaxOL - INT_MAX) < 1) -// { -// numIL = G4int(std::max(10.,tempDiff/60.*kelvin)); -// } - - numIL = G4int(std::max(10.,tempDiff/60.*kelvin)); - //numIL = 1; - - // Find the Doppler broadened cross section - while((counter < numMaxOL) && (std::abs((buffer-result/(std::max(1,counter)*numIL))/std::max(1.0,buffer)) > 0.03)) - { - if(counter) - buffer = result/(numIL*counter); - else - buffer = 0; - - for(G4int i=0; i < numIL; i++) - { - // Create a random nucleus of the target element - G4ReactionProduct aThermalNuc = aNuc.GetThermalNucleus(eleMass, - tempDiff); - - // Find the neutron in the rest frame of the nucleus - boosted.Lorentz(theNeutron, aThermalNuc); - G4double theEkin = boosted.GetKineticEnergy(); - - // Find the cross-section of the element at the energy of the - // neutron IN THE REST FRAME OF THE NUCLEUS - aXsection = - (*((*theCrossSections)(index))).GetValue(theEkin, outOfRange); - - // Velocity correction - G4ThreeVector targetVelocity = - 1./aThermalNuc.GetMass()*aThermalNuc.GetMomentum(); - aXsection *= - (targetVelocity-neutronVelocity).mag()/neutronVelocity.mag(); - - // Add cross section to results - result += aXsection; - } - - counter++; - } - - xSection = result/(numIL*counter); - //G4cout << "For element Z: " << theZ << " A: " << theA << " for reaction type: " << reactionType << " at energy: " << eKinetic << " the cross-section is " << xSection << endl; - return xSection; -} diff --git a/G4STORK/src/StorkNeutronHPCapture.cc b/G4STORK/src/StorkNeutronHPCapture.cc deleted file mode 100755 index f7647b68..00000000 --- a/G4STORK/src/StorkNeutronHPCapture.cc +++ /dev/null @@ -1,179 +0,0 @@ -// -// ******************************************************************** -// * License and Disclaimer * -// * * -// * The Geant4 software is copyright of the Copyright Holders of * -// * the Geant4 Collaboration. It is provided under the terms and * -// * conditions of the Geant4 Software License, included in the file * -// * LICENSE and available at http://cern.ch/geant4/license . These * -// * include a list of copyright holders. * -// * * -// * Neither the authors of this software system, nor their employing * -// * institutes,nor the agencies providing financial support for this * -// * work make any representation or warranty, express or implied, * -// * regarding this software system or assume any liability for its * -// * use. Please see the license in the file LICENSE and URL above * -// * for the full disclaimer and the limitation of liability. * -// * * -// * This code implementation is the result of the scientific and * -// * technical work of the GEANT4 collaboration. * -// * By using, copying, modifying or distributing the software (or * -// * any work based on the software) you agree to acknowledge its * -// * use in resulting scientific publications, and indicate your * -// * acceptance of all terms of the Geant4 Software license. * -// ******************************************************************** -// -// neutron_hp -- source file -// J.P. Wellisch, Nov-1996 -// A prototype of the low energy neutron transport model. -// -// 070523 bug fix for G4FPE_DEBUG on by A. Howard ( and T. Koi) -// -#include "StorkNeutronHPCapture.hh" -#include "G4NeutronHPManager.hh" -#include "G4SystemOfUnits.hh" -#include "G4NeutronHPCaptureFS.hh" -#include "G4NeutronHPDeExGammas.hh" -#include "G4ParticleTable.hh" -#include "G4IonTable.hh" - - StorkNeutronHPCapture::StorkNeutronHPCapture(G4double finalStateTemp) - :G4HadronicInteraction("NeutronHPCapture") - { - SetMinEnergy( 0.0 ); - SetMaxEnergy( 20.*MeV ); - fsTemp = finalStateTemp; -// G4cout << "Capture : start of construction!!!!!!!!"<::iterator - ite = theCapture.begin() ; ite != theCapture.end() ; ite++ ) - { - delete *ite; - } - theCapture.clear(); - } - - #include "G4NeutronHPThermalBoost.hh" - G4HadFinalState * StorkNeutronHPCapture::ApplyYourself(const G4HadProjectile& aTrack, G4Nucleus& aNucleus ) - { - - if ( numEle < (G4int)G4Element::GetNumberOfElements() ) addChannelForNewElement(); - - G4NeutronHPManager::GetInstance()->OpenReactionWhiteBoard(); - if(getenv("NeutronHPCapture")) G4cout <<" ####### StorkNeutronHPCapture called"<GetNumberOfElements(); - G4int index = theMaterial->GetElement(0)->GetIndex(); - if(n!=1) - { - xSec = new G4double[n]; - G4double sum=0; - G4int i; - const G4double * NumAtomsPerVolume = theMaterial->GetVecNbOfAtomsPerVolume(); - G4double rWeight; - G4NeutronHPThermalBoost aThermalE; - for (i=0; iGetElement(i)->GetIndex(); - rWeight = NumAtomsPerVolume[i]; - //xSec[i] = theCapture[index].GetXsec(aThermalE.GetThermalEnergy(aTrack, - xSec[i] = (*theCapture[index]).GetXsec(aThermalE.GetThermalEnergy(aTrack, - theMaterial->GetElement(i), - std::max(0., theMaterial->GetTemperature()-fsTemp))); - xSec[i] *= rWeight; - sum+=xSec[i]; - } - G4double random = G4UniformRand(); - G4double running = 0; - for (i=0; iGetElement(i)->GetIndex(); - //if(random<=running/sum) break; - if( sum == 0 || random <= running/sum ) break; - } - if(i==n) i=std::max(0, n-1); - delete [] xSec; - } - - //return theCapture[index].ApplyYourself(aTrack); - //G4HadFinalState* result = theCapture[index].ApplyYourself(aTrack); - G4HadFinalState* result = (*theCapture[index]).ApplyYourself(aTrack); - - //Overwrite target parameters - aNucleus.SetParameters(G4NeutronHPManager::GetInstance()->GetReactionWhiteBoard()->GetTargA(),G4NeutronHPManager::GetInstance()->GetReactionWhiteBoard()->GetTargZ()); - const G4Element* target_element = (*G4Element::GetElementTable())[index]; - const G4Isotope* target_isotope=NULL; - G4int iele = target_element->GetNumberOfIsotopes(); - for ( G4int j = 0 ; j != iele ; j++ ) { - target_isotope=target_element->GetIsotope( j ); - if ( target_isotope->GetN() == G4NeutronHPManager::GetInstance()->GetReactionWhiteBoard()->GetTargA() ) break; - } - //G4cout << "Target Material of this reaction is " << theMaterial->GetName() << G4endl; - //G4cout << "Target Element of this reaction is " << target_element->GetName() << G4endl; - //G4cout << "Target Isotope of this reaction is " << target_isotope->GetName() << G4endl; - aNucleus.SetIsotope( target_isotope ); - - G4NeutronHPManager::GetInstance()->CloseReactionWhiteBoard(); - return result; - } - -const std::pair StorkNeutronHPCapture::GetFatalEnergyCheckLevels() const -{ - //return std::pair(10*perCent,10*GeV); - return std::pair(10*perCent,DBL_MAX); -} - -void StorkNeutronHPCapture::addChannelForNewElement() -{ - G4NeutronHPCaptureFS* theFS = new G4NeutronHPCaptureFS; - for ( G4int i = numEle ; i < (G4int)G4Element::GetNumberOfElements() ; i++ ) - { - G4cout << "StorkNeutronHPCapture Prepairing Data for the new element of " << (*(G4Element::GetElementTable()))[i]->GetName() << G4endl; - theCapture.push_back( new StorkNeutronHPChannel(fsTemp) ); - (*theCapture[i]).Init((*(G4Element::GetElementTable()))[i], dirName); - (*theCapture[i]).Register(theFS); - } - delete theFS; - numEle = (G4int)G4Element::GetNumberOfElements(); -} - -G4int StorkNeutronHPCapture::GetVerboseLevel() const -{ - return G4NeutronHPManager::GetInstance()->GetVerboseLevel(); -} -void StorkNeutronHPCapture::SetVerboseLevel( G4int newValue ) -{ - G4NeutronHPManager::GetInstance()->SetVerboseLevel(newValue); -} diff --git a/G4STORK/src/StorkNeutronHPChannel.cc b/G4STORK/src/StorkNeutronHPChannel.cc deleted file mode 100755 index 83b4d778..00000000 --- a/G4STORK/src/StorkNeutronHPChannel.cc +++ /dev/null @@ -1,306 +0,0 @@ -// -// ******************************************************************** -// * License and Disclaimer * -// * * -// * The Geant4 software is copyright of the Copyright Holders of * -// * the Geant4 Collaboration. It is provided under the terms and * -// * conditions of the Geant4 Software License, included in the file * -// * LICENSE and available at http://cern.ch/geant4/license . These * -// * include a list of copyright holders. * -// * * -// * Neither the authors of this software system, nor their employing * -// * institutes,nor the agencies providing financial support for this * -// * work make any representation or warranty, express or implied, * -// * regarding this software system or assume any liability for its * -// * use. Please see the license in the file LICENSE and URL above * -// * for the full disclaimer and the limitation of liability. * -// * * -// * This code implementation is the result of the scientific and * -// * technical work of the GEANT4 collaboration. * -// * By using, copying, modifying or distributing the software (or * -// * any work based on the software) you agree to acknowledge its * -// * use in resulting scientific publications, and indicate your * -// * acceptance of all terms of the Geant4 Software license. * -// ******************************************************************** -// -// neutron_hp -- source file -// J.P. Wellisch, Nov-1996 -// A prototype of the low energy neutron transport model. -// -// 070523 bug fix for G4FPE_DEBUG on by A. Howard ( and T. Koi) -// 071031 bug fix T. Koi on behalf of A. Howard -// 081203 bug fix in Register method by T. Koi -// -#include - -#include "StorkNeutronHPChannel.hh" -#include "globals.hh" -#include "G4SystemOfUnits.hh" -#include "G4NeutronHPFinalState.hh" -#include "G4HadTmpUtil.hh" - -#include "G4NeutronHPManager.hh" -#include "G4NeutronHPReactionWhiteBoard.hh" - - G4double StorkNeutronHPChannel::GetXsec(G4double energy) - { - return std::max(0., theChannelData->GetXsec(energy)); - } - - G4double StorkNeutronHPChannel::GetWeightedXsec(G4double energy, G4int isoNumber) - { - return theIsotopeWiseData[isoNumber].GetXsec(energy); - } - - G4double StorkNeutronHPChannel::GetFSCrossSection(G4double energy, G4int isoNumber) - { - return theFinalStates[isoNumber]->GetXsec(energy); - } - - void StorkNeutronHPChannel:: - Init(G4Element * anElement, const G4String dirName, const G4String aFSType) - { - theFSType = aFSType; - Init(anElement, dirName); - } - - void StorkNeutronHPChannel::Init(G4Element * anElement, const G4String dirName) - { - theDir = dirName; - theElement = anElement; - } - - G4bool StorkNeutronHPChannel::Register(G4NeutronHPFinalState *theFS) - { - registerCount++; - G4int Z = G4lrint(theElement->GetZ()); - - Z = Z-registerCount; - if ( registerCount > 5 ) throw G4HadronicException(__FILE__, __LINE__, "Channel: Do not know what to do with this material"); // for Elastic, Capture, Fission case - if ( Z < 1 ) return false; -/* - if(registerCount<5) - { - Z = Z-registerCount; - } -*/ - //if(Z=theElement->GetZ()-5) throw G4HadronicException(__FILE__, __LINE__, "Channel: Do not know what to do with this material"); - // Bug fix by TK on behalf of AH - if ( Z <=theElement->GetZ()-5 ) throw G4HadronicException(__FILE__, __LINE__, "Channel: Do not know what to do with this material"); - G4int count = 0; - if(registerCount==0) count = theElement->GetNumberOfIsotopes(); - if(count == 0||registerCount!=0) count += - theStableOnes.GetNumberOfIsotopes(Z); - niso = count; - delete [] theIsotopeWiseData; - theIsotopeWiseData = new G4NeutronHPIsoData [niso]; - delete [] active; - active = new G4bool[niso]; - - delete [] theFinalStates; - theFinalStates = new G4NeutronHPFinalState * [niso]; - delete theChannelData; - theChannelData = new G4NeutronHPVector; - for(G4int i=0; iNew(); - } - count = 0; - G4int nIsos = niso; - if(theElement->GetNumberOfIsotopes()!=0&®isterCount==0) - { - for (G4int i1=0; i1GetIsotope(i1)->GetN(); - G4int M = theElement->GetIsotope(i1)->Getm(); - G4double frac = theElement->GetRelativeAbundanceVector()[i1]/perCent; - //theFinalStates[i1]->SetA_Z(A, Z); - //UpdateData(A, Z, count++, frac); - theFinalStates[i1]->SetA_Z(A, Z, M); - UpdateData(A, Z, M, count++, frac); - } - } else { - //G4cout <<" Init: mean case: " - // <SetA_Z(A, Z); - UpdateData(A, Z, count++, frac); - } - } - G4bool result = HasDataInAnyFinalState(); - return result; - } - - //void StorkNeutronHPChannel::UpdateData(G4int A, G4int Z, G4int index, G4double abundance) - void StorkNeutronHPChannel::UpdateData(G4int A, G4int Z, G4int M, G4int index, G4double abundance) - { - // Initialze the G4FissionFragment generator for this isomer if needed - if(wendtFissionGenerator) - { - wendtFissionGenerator->InitializeANucleus(A, Z, M, theDir); - } - - theFinalStates[index]->Init(A, Z, M, theDir, theFSType); - if(!theFinalStates[index]->HasAnyData()) return; // nothing there for exactly this isotope. - - // the above has put the X-sec into the FS - theBuffer = 0; - if(theFinalStates[index]->HasXsec()) - { - theBuffer = theFinalStates[index]->GetXsec(); - theBuffer->Times(abundance/100.); - theIsotopeWiseData[index].FillChannelData(theBuffer); - } - else // get data from CrossSection directory - { - G4String tString = "/CrossSection"; - //active[index] = theIsotopeWiseData[index].Init(A, Z, abundance, theDir, tString); - active[index] = theIsotopeWiseData[index].Init(A, Z, M, abundance, theDir, tString); - if(active[index]) theBuffer = theIsotopeWiseData[index].MakeChannelData(); - } - if(theBuffer != 0) Harmonise(theChannelData, theBuffer); - } - - void StorkNeutronHPChannel::Harmonise(G4NeutronHPVector *& theStore, G4NeutronHPVector * theNew) - { - G4int s_tmp = 0, n=0, m_tmp=0; - G4NeutronHPVector * theMerge = new G4NeutronHPVector; - G4NeutronHPVector * anActive = theStore; - G4NeutronHPVector * aPassive = theNew; - G4NeutronHPVector * tmp; - G4int a = s_tmp, p = n, t; - while (aGetVectorLength()&&pGetVectorLength()) - { - if(anActive->GetEnergy(a) <= aPassive->GetEnergy(p)) - { - G4double xa = anActive->GetEnergy(a); - theMerge->SetData(m_tmp, xa, anActive->GetXsec(a)+std::max(0., aPassive->GetXsec(xa)) ); - m_tmp++; - a++; - G4double xp = aPassive->GetEnergy(p); - if( std::abs(std::abs(xp-xa)/xa)<0.001 ) - { - p++; - } - } else { - tmp = anActive; t=a; - anActive = aPassive; a=p; - aPassive = tmp; p=t; - } - } - while (a!=anActive->GetVectorLength()) - { - theMerge->SetData(m_tmp++, anActive->GetEnergy(a), anActive->GetXsec(a)); - a++; - } - while (p!=aPassive->GetVectorLength()) - { - if(std::abs(theMerge->GetEnergy(std::max(0,m_tmp-1))-aPassive->GetEnergy(p))/aPassive->GetEnergy(p)>0.001) - theMerge->SetData(m_tmp++, aPassive->GetEnergy(p), aPassive->GetXsec(p)); - p++; - } - delete theStore; - theStore = theMerge; - } - -#include "G4NeutronHPThermalBoost.hh" - - G4HadFinalState * StorkNeutronHPChannel:: - ApplyYourself(const G4HadProjectile & theTrack, G4int anIsotope) - { -// G4cout << "StorkNeutronHPChannel::ApplyYourself+"<Initialize+"<Initialize-"<(niso*G4UniformRand()); - } - else - { -// G4cout << "Are we still here? "<GetNiso(); - if(numberOfIsos!=0) break; - } - G4double * running= new G4double [numberOfIsos]; - running[0] = 0; - for(i=0;iHasAnyData(i)) - { - running[i] +=theChannels[ii]->GetWeightedXsec(aThermalE.GetThermalEnergy(aTrack, - theChannels[ii]->GetN(i), - theChannels[ii]->GetZ(i), - std::max(0., aTrack.GetMaterial()->GetTemperature()-fsTemp)), - i); - } - } - } - G4int isotope=nChannels-1; - G4double random=G4UniformRand(); - for(i=0;iHasAnyData(isotope)) - { - running[i] += theChannels[i]->GetFSCrossSection(aThermalE.GetThermalEnergy(aTrack, - theChannels[i]->GetN(isotope), - theChannels[i]->GetZ(isotope), - std::max(0., aTrack.GetMaterial()->GetTemperature()-fsTemp)), - isotope); - targA=(G4int)theChannels[i]->GetN(isotope); //Will be simply used the last valid value - targZ=(G4int)theChannels[i]->GetZ(isotope); - } - } - - //TK120607 - if ( running[nChannels-1] == 0 ) - { - //This happened usually by the miss match between the cross section data and model - if ( targA == -1 && targZ == -1 ) { - throw G4HadronicException(__FILE__, __LINE__, "NeutronHP model encounter lethal discrepancy with cross section data"); - } - - //TK121106 - G4cout << "Warning from NeutronHP: could not find proper reaction channel. This may cause by inconsistency between cross section and model. Unchanged final states are returned." << G4endl; - unChanged.Clear(); - - //For Ep Check create unchanged final state including rest target - G4ParticleDefinition* targ_pd = G4IonTable::GetIonTable()->GetIon ( targZ , targA , 0.0 ); - G4DynamicParticle* targ_dp = new G4DynamicParticle( targ_pd , G4ThreeVector(1,0,0), 0.0 ); - unChanged.SetEnergyChange(aTrack.GetKineticEnergy()); - unChanged.SetMomentumChange(aTrack.Get4Momentum().vect() ); - unChanged.AddSecondary(targ_dp); - //TK121106 - G4NeutronHPManager::GetInstance()->GetReactionWhiteBoard()->SetTargA( targA ); - G4NeutronHPManager::GetInstance()->GetReactionWhiteBoard()->SetTargZ( targZ ); - return &unChanged; - } - //TK120607 - - - G4int lChan=0; - random=G4UniformRand(); - for(i=0; iApplyYourself(aTrack, isotope); - } - - void StorkNeutronHPChannelList::Init(G4Element * anElement, const G4String & dirName) - { - theDir = dirName; -// G4cout << theDir << G4endl; - theElement = anElement; -// G4cout << theElement << G4endl; - ; - } - - void StorkNeutronHPChannelList::Register(G4NeutronHPFinalState * theFS, - const G4String & aName) - { - if(!allChannelsCreated) - { - if(nChannels!=0) - { - StorkNeutronHPChannel ** theBuffer = new StorkNeutronHPChannel * [nChannels+1]; - G4int i; - for(i=0; iInit(theElement, theDir, name); - nChannels++; - } - - theChannels[theInitCount]->Register(theFS); - theInitCount++; - } diff --git a/G4STORK/src/StorkNeutronHPDataConstructor.cc b/G4STORK/src/StorkNeutronHPDataConstructor.cc deleted file mode 100755 index c56fe9e5..00000000 --- a/G4STORK/src/StorkNeutronHPDataConstructor.cc +++ /dev/null @@ -1,91 +0,0 @@ -// -// ******************************************************************** -// * License and Disclaimer * -// * * -// * The Geant4 software is copyright of the Copyright Holders of * -// * the Geant4 Collaboration. It is provided under the terms and * -// * conditions of the Geant4 Software License, included in the file * -// * LICENSE and available at http://cern.ch/geant4/license . These * -// * include a list of copyright holders. * -// * * -// * Neither the authors of this software system, nor their employing * -// * institutes,nor the agencies providing financial support for this * -// * work make any representation or warranty, express or implied, * -// * regarding this software system or assume any liability for its * -// * use. Please see the license in the file LICENSE and URL above * -// * for the full disclaimer and the limitation of liability. * -// * * -// * This code implementation is the result of the scientific and * -// * technical work of the GEANT4 collaboration. * -// * By using, copying, modifying or distributing the software (or * -// * any work based on the software) you agree to acknowledge its * -// * use in resulting scientific publications, and indicate your * -// * acceptance of all terms of the Geant4 Software license. * -// ******************************************************************** -// -// neutron_hp -- source file -// J.P. Wellisch, Nov-1996 -// A prototype of the low energy neutron transport model. -// -#include "StorkNeutronHPDataConstructor.hh" -#include "G4LPhysicsFreeVector.hh" - - StorkNeutronHPDataConstructor::StorkNeutronHPDataConstructor(G4String dirName) - { - CSDirName=dirName; - numEle = G4Element::GetNumberOfElements(); - for ( G4int i = 0 ; i < numEle ; i++ ) theData.push_back ( new StorkNeutronHPElementData(CSDirName) ); -// G4cout << "StorkNeutronHPDataConstructor::StorkNeutronHPDataConstructor(): numEle="<::iterator it = theData.begin() ; it != theData.end() ; it++ ) - { - if(*it) - delete *it; - } - theData.clear(); - } - - StorkNeutronHPDataConstructor * StorkNeutronHPDataConstructor::Instance(G4String dirName) - { - static G4ThreadLocal StorkNeutronHPDataConstructor *theCrossSectionData_G4MT_TLS_ = 0 ; - if (!theCrossSectionData_G4MT_TLS_) - theCrossSectionData_G4MT_TLS_ = new StorkNeutronHPDataConstructor(dirName) ; - StorkNeutronHPDataConstructor &theCrossSectionData = *theCrossSectionData_G4MT_TLS_; - return &theCrossSectionData; - } - - G4PhysicsVector * StorkNeutronHPDataConstructor::DoPhysicsVector(G4NeutronHPVector * theVector) - { -// G4cout << "Entered StorkNeutronHPDataConstructor::DoPhysicsVector."<GetVectorLength(); -// G4cout <<"zahl der energie-punkte "<< len<GetX(0); - G4double emax = theVector->GetX(len-1); -// G4cout <<"zahl der energie-punkte "<< len<<" "<> dummy; - G4LPhysicsFreeVector * theResult = new G4LPhysicsFreeVector(len, emin, emax); - for (G4int i=0; iPutValues(i, theVector->GetX(i), theVector->GetY(i)); - } - return theResult; - } - -void StorkNeutronHPDataConstructor::addPhysicsVector(G4String dirName) -{ - for ( G4int i = numEle; i < (G4int)G4Element::GetNumberOfElements() ; i++ ) - { - theData.push_back ( new StorkNeutronHPElementData(dirName) ); - (*theData[i]).Init((*(G4Element::GetElementTable()))[i]); - } - numEle = G4Element::GetNumberOfElements(); -} diff --git a/G4STORK/src/StorkNeutronHPElastic.cc b/G4STORK/src/StorkNeutronHPElastic.cc deleted file mode 100755 index a78ce75c..00000000 --- a/G4STORK/src/StorkNeutronHPElastic.cc +++ /dev/null @@ -1,170 +0,0 @@ -// -// ******************************************************************** -// * License and Disclaimer * -// * * -// * The Geant4 software is copyright of the Copyright Holders of * -// * the Geant4 Collaboration. It is provided under the terms and * -// * conditions of the Geant4 Software License, included in the file * -// * LICENSE and available at http://cern.ch/geant4/license . These * -// * include a list of copyright holders. * -// * * -// * Neither the authors of this software system, nor their employing * -// * institutes,nor the agencies providing financial support for this * -// * work make any representation or warranty, express or implied, * -// * regarding this software system or assume any liability for its * -// * use. Please see the license in the file LICENSE and URL above * -// * for the full disclaimer and the limitation of liability. * -// * * -// * This code implementation is the result of the scientific and * -// * technical work of the GEANT4 collaboration. * -// * By using, copying, modifying or distributing the software (or * -// * any work based on the software) you agree to acknowledge its * -// * use in resulting scientific publications, and indicate your * -// * acceptance of all terms of the Geant4 Software license. * -// ******************************************************************** -// -// neutron_hp -- source file -// J.P. Wellisch, Nov-1996 -// A prototype of the low energy neutron transport model. -// -// 070523 bug fix for G4FPE_DEBUG on by A. Howard ( and T. Koi) -// 080319 Compilation warnings - gcc-4.3.0 fix by T. Koi -// -#include "StorkNeutronHPElastic.hh" -#include "G4SystemOfUnits.hh" -#include "G4NeutronHPElasticFS.hh" -#include "G4NeutronHPManager.hh" - - StorkNeutronHPElastic::StorkNeutronHPElastic(G4double finalStateTemp) - :G4HadronicInteraction("NeutronHPElastic") - { - overrideSuspension = false; - G4NeutronHPElasticFS * theFS = new G4NeutronHPElasticFS; - fsTemp = finalStateTemp; - if(!getenv("G4NEUTRONHPDATA")) - throw G4HadronicException(__FILE__, __LINE__, "Please setenv G4NEUTRONHPDATA to point to the neutron cross-section files."); - dirName = getenv("G4NEUTRONHPDATA"); - G4String tString = "/Elastic"; - dirName = dirName + tString; -// G4cout <<"StorkNeutronHPElastic::StorkNeutronHPElastic testit "<::iterator - it = theElastic.begin() ; it != theElastic.end() ; it++ ) - { - delete *it; - } - theElastic.clear(); - } - - #include "G4NeutronHPThermalBoost.hh" - - G4HadFinalState * StorkNeutronHPElastic::ApplyYourself(const G4HadProjectile& aTrack, G4Nucleus& aNucleus ) - { - - if ( numEle < (G4int)G4Element::GetNumberOfElements() ) addChannelForNewElement(); - - G4NeutronHPManager::GetInstance()->OpenReactionWhiteBoard(); - const G4Material * theMaterial = aTrack.GetMaterial(); - G4int n = theMaterial->GetNumberOfElements(); - G4int index = theMaterial->GetElement(0)->GetIndex(); - if(n!=1) - { - G4int i; - xSec = new G4double[n]; - G4double sum=0; - const G4double * NumAtomsPerVolume = theMaterial->GetVecNbOfAtomsPerVolume(); - G4double rWeight; - G4NeutronHPThermalBoost aThermalE; - for (i=0; iGetElement(i)->GetIndex(); - rWeight = NumAtomsPerVolume[i]; - //xSec[i] = theElastic[index].GetXsec(aThermalE.GetThermalEnergy(aTrack, - xSec[i] = (*theElastic[index]).GetXsec(aThermalE.GetThermalEnergy(aTrack, - theMaterial->GetElement(i), - std::max(0., theMaterial->GetTemperature()-fsTemp))); - xSec[i] *= rWeight; - sum+=xSec[i]; - } - G4double random = G4UniformRand(); - G4double running = 0; - for (i=0; iGetElement(i)->GetIndex(); - //if(random<=running/sum) break; - if( sum == 0 || random <= running/sum ) break; - } - delete [] xSec; - // it is element-wise initialised. - } - //G4HadFinalState* finalState = theElastic[index].ApplyYourself(aTrack); - G4HadFinalState* finalState = (*theElastic[index]).ApplyYourself(aTrack); - if (overrideSuspension) finalState->SetStatusChange(isAlive); - - //Overwrite target parameters - aNucleus.SetParameters(G4NeutronHPManager::GetInstance()->GetReactionWhiteBoard()->GetTargA(),G4NeutronHPManager::GetInstance()->GetReactionWhiteBoard()->GetTargZ()); - const G4Element* target_element = (*G4Element::GetElementTable())[index]; - const G4Isotope* target_isotope=NULL; - G4int iele = target_element->GetNumberOfIsotopes(); - for ( G4int j = 0 ; j != iele ; j++ ) { - target_isotope=target_element->GetIsotope( j ); - if ( target_isotope->GetN() == G4NeutronHPManager::GetInstance()->GetReactionWhiteBoard()->GetTargA() ) break; - } - //G4cout << "Target Material of this reaction is " << theMaterial->GetName() << G4endl; - //G4cout << "Target Element of this reaction is " << target_element->GetName() << G4endl; - //G4cout << "Target Isotope of this reaction is " << target_isotope->GetName() << G4endl; - aNucleus.SetIsotope( target_isotope ); - - G4NeutronHPManager::GetInstance()->CloseReactionWhiteBoard(); - return finalState; - } - -const std::pair StorkNeutronHPElastic::GetFatalEnergyCheckLevels() const -{ - //return std::pair(10*perCent,10*GeV); - return std::pair(10*perCent,DBL_MAX); -} - -void StorkNeutronHPElastic::addChannelForNewElement() -{ - G4NeutronHPElasticFS* theFS = new G4NeutronHPElasticFS; - for ( G4int i = numEle ; i < (G4int)G4Element::GetNumberOfElements() ; i++ ) - { - G4cout << "StorkNeutronHPElastic Prepairing Data for the new element of " << (*(G4Element::GetElementTable()))[i]->GetName() << G4endl; - theElastic.push_back( new StorkNeutronHPChannel(fsTemp) ); - (*theElastic[i]).Init((*(G4Element::GetElementTable()))[i], dirName); - while(!(*theElastic[i]).Register(theFS)) ; - } - delete theFS; - numEle = (G4int)G4Element::GetNumberOfElements(); -} - -G4int StorkNeutronHPElastic::GetVerboseLevel() const -{ - return G4NeutronHPManager::GetInstance()->GetVerboseLevel(); -} -void StorkNeutronHPElastic::SetVerboseLevel( G4int newValue ) -{ - G4NeutronHPManager::GetInstance()->SetVerboseLevel(newValue); -} diff --git a/G4STORK/src/StorkNeutronHPElementData.cc b/G4STORK/src/StorkNeutronHPElementData.cc deleted file mode 100755 index 59f8e060..00000000 --- a/G4STORK/src/StorkNeutronHPElementData.cc +++ /dev/null @@ -1,421 +0,0 @@ -// -// ******************************************************************** -// * License and Disclaimer * -// * * -// * The Geant4 software is copyright of the Copyright Holders of * -// * the Geant4 Collaboration. It is provided under the terms and * -// * conditions of the Geant4 Software License, included in the file * -// * LICENSE and available at http://cern.ch/geant4/license . These * -// * include a list of copyright holders. * -// * * -// * Neither the authors of this software system, nor their employing * -// * institutes,nor the agencies providing financial support for this * -// * work make any representation or warranty, express or implied, * -// * regarding this software system or assume any liability for its * -// * use. Please see the license in the file LICENSE and URL above * -// * for the full disclaimer and the limitation of liability. * -// * * -// * This code implementation is the result of the scientific and * -// * technical work of the GEANT4 collaboration. * -// * By using, copying, modifying or distributing the software (or * -// * any work based on the software) you agree to acknowledge its * -// * use in resulting scientific publications, and indicate your * -// * acceptance of all terms of the Geant4 Software license. * -// ******************************************************************** -// -// neutron_hp -- source file -// J.P. Wellisch, Nov-1996 -// A prototype of the low energy neutron transport model. -// -// 02-08-06 Modified Harmonise to reslove cross section trouble at high-end. T. KOI -// -#include "StorkNeutronHPElementData.hh" -#include "G4SystemOfUnits.hh" - - StorkNeutronHPElementData::StorkNeutronHPElementData(G4String DirName) - { - precision = 0.02; - theFissionData = new G4NeutronHPVector; - theCaptureData = new G4NeutronHPVector; - theElasticData = new G4NeutronHPVector; - theInelasticData = new G4NeutronHPVector; - theIsotopeWiseData = NULL; - theBuffer = NULL; - if(DirName[G4int(DirName.size()-1)]!='/') - DirName.push_back('/'); - dirName=DirName; - - } - - StorkNeutronHPElementData::StorkNeutronHPElementData() - { - precision = 0.02; - theFissionData = new G4NeutronHPVector; - theCaptureData = new G4NeutronHPVector; - theElasticData = new G4NeutronHPVector; - theInelasticData = new G4NeutronHPVector; - theIsotopeWiseData = NULL; - theBuffer = NULL; - - } - - StorkNeutronHPElementData::~StorkNeutronHPElementData() - { - if(theFissionData) - delete theFissionData; - if(theCaptureData) - delete theCaptureData; - if(theElasticData) - delete theElasticData; - if(theInelasticData) - delete theInelasticData; - if(theIsotopeWiseData) - delete [] theIsotopeWiseData; - } - - void StorkNeutronHPElementData::Init(G4Element * theElement) - { - StorkElement *elem = dynamic_cast(theElement); - G4int count = theElement->GetNumberOfIsotopes(); - if(count == 0) - count += theStableOnes.GetNumberOfIsotopes(static_cast(theElement->GetZ())); - - if(theIsotopeWiseData) - delete theIsotopeWiseData; - - theIsotopeWiseData = new StorkNeutronHPIsoData[count]; - std::vector csDataTempVec; - std::vector csDataNameVec; - // filename = ein data-set je isotope. - count = 0; - G4int nIso = theElement->GetNumberOfIsotopes(); - G4int Z = static_cast (theElement->GetZ()); - G4double temp = elem->GetTemperature(); - - GetDirList(temp, csDataTempVec, csDataNameVec); - //G4int i1; - if(nIso!=0) - { - - bool check=false; - G4int index; - for(G4int i=0; iGetIsotope(i1)->GetN(); - if(!theIsotopeWiseData[0].FileExists(A, Z, dirName+csDataNameVec[i])) - break; - else if(i1==nIso-1) - check=true; - } - - if(check) - { - index=i; - break; - } - - } - - if(check) - { - dirName=dirName+csDataNameVec[index]; - elem->SetCSDataTemp(csDataTempVec[index]); - for (G4int i1=0; i1GetIsotope(i1)->GetN(); - G4int M = theElement->GetIsotope(i1)->Getm(); - G4double frac = theElement->GetRelativeAbundanceVector()[i1]/perCent; - //UpdateData(A, Z, count++, frac); - UpdateData(A, Z, M, count++, frac); - } - } - else - { - G4cout << "\n None of the given cross-section data directories contianed all of the isotope data for " << theElement->GetName() << G4endl; - } - - } - - else{ - // G4cout <<" Init: theStableOnes case: Z="<GetZ())<(theElement->GetZ()) ); i1++) - { - // G4cout <<" Init: normal case"<GetIsotope(i1)->GetN(); - if(!theIsotopeWiseData[0].FileExists(A, Z, dirName+csDataNameVec[i])) - break; - else if(i1==nIso-1) - check=true; - } - - if(check) - { - index=i; - break; - } - - } - - if(check) - { - dirName=dirName+csDataNameVec[index]; - elem->SetCSDataTemp(csDataTempVec[index]); - for(G4int i1=0; i1(theElement->GetZ()) ); i1++) - { - // G4cout <<" Init: theStableOnes in the loop"<GetName() << G4endl; - } - } - theElasticData->ThinOut(precision); - theInelasticData->ThinOut(precision); - theCaptureData->ThinOut(precision); - theFissionData->ThinOut(precision); - } - - void StorkNeutronHPElementData::GetDirList(G4double temp, std::vector &csDataTempVec, std::vector &csDataNameVec) - { - G4double tempData; - G4String nameData; - - DIR *dir; - struct dirent *ent; - if ((dir = opendir (dirName.c_str())) != NULL) - { - /* print all the files and directories within directory */ - while ((ent = readdir (dir)) != NULL) - { - if(ExtractTemp(ent->d_name, tempData)) - { - csDataNameVec.push_back(ent->d_name); - csDataTempVec.push_back(tempData); - } - } - closedir(dir); - } - else - { - G4cout << "\n### Error: could not open directory " << dirName << " to extract cross section data ###" << G4endl; - } - if(csDataTempVec.size()==0) - { - G4cout << "\n### Error: no directories with the proper name format were found in the given cross section data directory ###" << G4endl; - } - for(G4int i=0; i(temp+0.1)) - { - csDataTempVec.erase (csDataTempVec.begin()+i); - csDataNameVec.erase (csDataNameVec.begin()+i); - i--; - } - } - for(G4int i=0; iabs(temp-csDataTempVec[j])) - { - tempData=csDataTempVec[i]; - nameData=csDataNameVec[i]; - csDataTempVec[i]=csDataTempVec[j]; - csDataNameVec[i]=csDataNameVec[j]; - csDataTempVec[j]=tempData; - csDataNameVec[j]=nameData; - } - } - } - } - - //void StorkNeutronHPElementData::UpdateData(G4int A, G4int Z, G4int index, G4double abundance) - void StorkNeutronHPElementData::UpdateData(G4int A, G4int Z, G4int M, G4int index, G4double abundance) - { - //Reads in the Data, using StorkNeutronHPIsoData[], and its Init -// G4cout << "entered: ElementWiseData::UpdateData"<GetVectorLength()<GetVectorLength()<GetVectorLength()<GetVectorLength()<GetVectorLength()<GetVectorLength()<GetVectorLength()<GetVectorLength()<=0) - { - if(check) - { - if(((name[index]>='0')&&(name[index]<='9'))||(name[index]>='.')) - { - startPos--; - } - else - { - break; - } - } - else - { - if((name[index]>='0')&&(name[index]<='9')) - { - if((index+1==int(name.size()))||!((name[index+1]=='k')||(name[index+1]=='K'))) - { - return false; - } - check = true; - startPos=endPos=index; - } - } - index--; - } - - if(endPos>=startPos) - { - G4String temperature = name.substr(startPos, endPos-startPos+1); - ss.str(temperature); - ss >> temp; - } - - return check; - } - - void StorkNeutronHPElementData::Harmonise(G4NeutronHPVector *& theStore, G4NeutronHPVector * theNew) - { - if(theNew == 0) { return; } - G4int s_tmp = 0, n=0, m_tmp=0; - G4NeutronHPVector * theMerge = new G4NeutronHPVector(theStore->GetVectorLength()); -// G4cout << "Harmonise 1: "<GetEnergy(s)<<" "<GetEnergy(0)<GetEnergy(s_tmp)GetEnergy(0)&&s_tmpGetVectorLength() ) - { - theMerge->SetData(m_tmp++, theStore->GetEnergy(s_tmp), theStore->GetXsec(s_tmp)); - s_tmp++; - } - G4NeutronHPVector *active = theStore; - G4NeutronHPVector * passive = theNew; - G4NeutronHPVector * tmp; - G4int a = s_tmp, p = n, t; -// G4cout << "Harmonise 2: "<GetVectorLength()<<" "<GetVectorLength()<GetVectorLength()&&pGetVectorLength()) - { - if(active->GetEnergy(a) <= passive->GetEnergy(p)) - { - theMerge->SetData(m_tmp, active->GetEnergy(a), active->GetXsec(a)); - G4double x = theMerge->GetEnergy(m_tmp); - G4double y = std::max(0., passive->GetXsec(x)); - theMerge->SetData(m_tmp, x, theMerge->GetXsec(m_tmp)+y); - m_tmp++; - a++; - } else { -// G4cout << "swapping in Harmonise"<GetVectorLength()<<" "<GetVectorLength()) - { - theMerge->SetData(m_tmp++, active->GetEnergy(a), active->GetXsec(a)); - a++; - } -// G4cout << "Harmonise 4: "<< p <<" "<GetVectorLength()<<" "<GetVectorLength()) - { - // Modified by T. KOI - //theMerge->SetData(m++, passive->GetEnergy(p), passive->GetXsec(p)); - G4double x = passive->GetEnergy(p); - G4double y = std::max(0., active->GetXsec(x)); - theMerge->SetData(m_tmp++, x, passive->GetXsec(p)+y); - p++; - } -// G4cout <<"Harmonise 5: "<< theMerge->GetVectorLength() << " " << m << G4endl; - delete theStore; - theStore = theMerge; -// G4cout <<"Harmonise 6: "<< theStore->GetVectorLength() << " " << m << G4endl; - } - - G4NeutronHPVector * StorkNeutronHPElementData::MakePhysicsVector(G4Element * theElement, - G4ParticleDefinition * theP, - G4NeutronHPFissionData* theSet) - { - if(theP != G4Neutron::Neutron()) throw G4HadronicException(__FILE__, __LINE__, "not a neutron"); - Init ( theElement ); - return GetData(theSet); - } - G4NeutronHPVector * StorkNeutronHPElementData::MakePhysicsVector(G4Element * theElement, - G4ParticleDefinition * theP, - G4NeutronHPCaptureData * theSet) - { - if(theP != G4Neutron::Neutron()) throw G4HadronicException(__FILE__, __LINE__, "not a neutron"); - Init ( theElement ); - return GetData(theSet); - } - G4NeutronHPVector * StorkNeutronHPElementData::MakePhysicsVector(G4Element * theElement, - G4ParticleDefinition * theP, - G4NeutronHPElasticData * theSet) - { - if(theP != G4Neutron::Neutron()) throw G4HadronicException(__FILE__, __LINE__, "not a neutron"); - Init ( theElement ); - return GetData(theSet); - } - G4NeutronHPVector * StorkNeutronHPElementData::MakePhysicsVector(G4Element * theElement, - G4ParticleDefinition * theP, - G4NeutronHPInelasticData * theSet) - { - if(theP != G4Neutron::Neutron()) throw G4HadronicException(__FILE__, __LINE__, "not a neutron"); - Init ( theElement ); - return GetData(theSet); - } diff --git a/G4STORK/src/StorkNeutronHPFission.cc b/G4STORK/src/StorkNeutronHPFission.cc deleted file mode 100755 index 52878fb8..00000000 --- a/G4STORK/src/StorkNeutronHPFission.cc +++ /dev/null @@ -1,176 +0,0 @@ -// -// ******************************************************************** -// * License and Disclaimer * -// * * -// * The Geant4 software is copyright of the Copyright Holders of * -// * the Geant4 Collaboration. It is provided under the terms and * -// * conditions of the Geant4 Software License, included in the file * -// * LICENSE and available at http://cern.ch/geant4/license . These * -// * include a list of copyright holders. * -// * * -// * Neither the authors of this software system, nor their employing * -// * institutes,nor the agencies providing financial support for this * -// * work make any representation or warranty, express or implied, * -// * regarding this software system or assume any liability for its * -// * use. Please see the license in the file LICENSE and URL above * -// * for the full disclaimer and the limitation of liability. * -// * * -// * This code implementation is the result of the scientific and * -// * technical work of the GEANT4 collaboration. * -// * By using, copying, modifying or distributing the software (or * -// * any work based on the software) you agree to acknowledge its * -// * use in resulting scientific publications, and indicate your * -// * acceptance of all terms of the Geant4 Software license. * -// ******************************************************************** -// -// neutron_hp -- source file -// J.P. Wellisch, Nov-1996 -// A prototype of the low energy neutron transport model. -// -// 070523 bug fix for G4FPE_DEBUG on by A. Howard ( and T. Koi) -// 08-08-06 delete unnecessary and harmed declaration; Bug Report[857] -// -#include "StorkNeutronHPFission.hh" -#include "G4SystemOfUnits.hh" - -#include "G4NeutronHPManager.hh" - - StorkNeutronHPFission::StorkNeutronHPFission(G4double finalStateTemp) - :G4HadronicInteraction("NeutronHPFission") - { - SetMinEnergy( 0.0 ); - SetMaxEnergy( 20.*MeV ); - fsTemp = finalStateTemp; - if(!getenv("G4NEUTRONHPDATA")) - throw G4HadronicException(__FILE__, __LINE__, "Please setenv G4NEUTRONHPDATA to point to the neutron cross-section files."); - dirName = getenv("G4NEUTRONHPDATA"); - G4String tString = "/Fission"; - dirName = dirName + tString; - numEle = G4Element::GetNumberOfElements(); - //theFission = new StorkNeutronHPChannel[numEle]; - - //for (G4int i=0; iGetZ()>89) - // if((*(G4Element::GetElementTable()))[i]->GetZ()>87) //TK modified for ENDF-VII - // { - // theFission[i].Init((*(G4Element::GetElementTable()))[i], dirName); - // theFission[i].Register(&theFS); - // } - //} - - for ( G4int i = 0 ; i < numEle ; i++ ) - { - theFission.push_back( new StorkNeutronHPChannel(fsTemp) ); - if((*(G4Element::GetElementTable()))[i]->GetZ()>87) //TK modified for ENDF-VII - { - (*theFission[i]).Init((*(G4Element::GetElementTable()))[i], dirName); - (*theFission[i]).Register(&theFS); - } - } - } - - StorkNeutronHPFission::~StorkNeutronHPFission() - { - //delete [] theFission; - for ( std::vector::iterator - it = theFission.begin() ; it != theFission.end() ; it++ ) - { - delete *it; - } - theFission.clear(); - } - - #include "G4NeutronHPThermalBoost.hh" - G4HadFinalState * StorkNeutronHPFission::ApplyYourself(const G4HadProjectile& aTrack, G4Nucleus& aNucleus ) - { - - if ( numEle < (G4int)G4Element::GetNumberOfElements() ) addChannelForNewElement(); - - G4NeutronHPManager::GetInstance()->OpenReactionWhiteBoard(); - // error here, aTrack.GetMaterial has not been set before hand since the G4HadProjectile was created from a dynamic particle, not the track - const G4Material * theMaterial = aTrack.GetMaterial(); - G4int n = theMaterial->GetNumberOfElements(); - G4int index = theMaterial->GetElement(0)->GetIndex(); - if(n!=1) - { - xSec = new G4double[n]; - G4double sum=0; - G4int i; - const G4double * NumAtomsPerVolume = theMaterial->GetVecNbOfAtomsPerVolume(); - G4double rWeight; - G4NeutronHPThermalBoost aThermalE; - for (i=0; iGetElement(i)->GetIndex(); - rWeight = NumAtomsPerVolume[i]; - xSec[i] = (*theFission[index]).GetXsec(aThermalE.GetThermalEnergy(aTrack, - theMaterial->GetElement(i), - std::max(0., theMaterial->GetTemperature()-fsTemp))); - xSec[i] *= rWeight; - sum+=xSec[i]; - } - G4double random = G4UniformRand(); - G4double running = 0; - for (i=0; iGetElement(i)->GetIndex(); - //if(random<=running/sum) break; - if( sum == 0 || random <= running/sum ) break; - } - delete [] xSec; - } - //return theFission[index].ApplyYourself(aTrack); //-2:Marker for Fission - G4HadFinalState* result = (*theFission[index]).ApplyYourself(aTrack,-2); - - //Overwrite target parameters - aNucleus.SetParameters(G4NeutronHPManager::GetInstance()->GetReactionWhiteBoard()->GetTargA(),G4NeutronHPManager::GetInstance()->GetReactionWhiteBoard()->GetTargZ()); - const G4Element* target_element = (*G4Element::GetElementTable())[index]; - const G4Isotope* target_isotope=NULL; - G4int iele = target_element->GetNumberOfIsotopes(); - for ( G4int j = 0 ; j != iele ; j++ ) { - target_isotope=target_element->GetIsotope( j ); - if ( target_isotope->GetN() == G4NeutronHPManager::GetInstance()->GetReactionWhiteBoard()->GetTargA() ) break; - } - //G4cout << "Target Material of this reaction is " << theMaterial->GetName() << G4endl; - //G4cout << "Target Element of this reaction is " << target_element->GetName() << G4endl; - //G4cout << "Target Isotope of this reaction is " << target_isotope->GetName() << G4endl; - aNucleus.SetIsotope( target_isotope ); - - G4NeutronHPManager::GetInstance()->CloseReactionWhiteBoard(); - return result; - } - -const std::pair StorkNeutronHPFission::GetFatalEnergyCheckLevels() const -{ - // max energy non-conservation is mass of heavy nucleus - //return std::pair(5*perCent,250*GeV); - return std::pair(5*perCent,DBL_MAX); -} - - - -void StorkNeutronHPFission::addChannelForNewElement() -{ - for ( G4int i = numEle ; i < (G4int)G4Element::GetNumberOfElements() ; i++ ) - { - theFission.push_back( new StorkNeutronHPChannel(fsTemp) ); - if ( (*(G4Element::GetElementTable()))[i]->GetZ() > 87 ) //TK modified for ENDF-VII - { - G4cout << "StorkNeutronHPFission Prepairing Data for the new element of " << (*(G4Element::GetElementTable()))[i]->GetName() << G4endl; - (*theFission[i]).Init((*(G4Element::GetElementTable()))[i], dirName); - (*theFission[i]).Register(&theFS); - } - } - numEle = (G4int)G4Element::GetNumberOfElements(); -} - -G4int StorkNeutronHPFission::GetVerboseLevel() const -{ - return G4NeutronHPManager::GetInstance()->GetVerboseLevel(); -} -void StorkNeutronHPFission::SetVerboseLevel( G4int newValue ) -{ - G4NeutronHPManager::GetInstance()->SetVerboseLevel(newValue); -} diff --git a/G4STORK/src/StorkNeutronHPInelastic.cc b/G4STORK/src/StorkNeutronHPInelastic.cc deleted file mode 100755 index 7a25413c..00000000 --- a/G4STORK/src/StorkNeutronHPInelastic.cc +++ /dev/null @@ -1,353 +0,0 @@ -// -// ******************************************************************** -// * License and Disclaimer * -// * * -// * The Geant4 software is copyright of the Copyright Holders of * -// * the Geant4 Collaboration. It is provided under the terms and * -// * conditions of the Geant4 Software License, included in the file * -// * LICENSE and available at http://cern.ch/geant4/license . These * -// * include a list of copyright holders. * -// * * -// * Neither the authors of this software system, nor their employing * -// * institutes,nor the agencies providing financial support for this * -// * work make any representation or warranty, express or implied, * -// * regarding this software system or assume any liability for its * -// * use. Please see the license in the file LICENSE and URL above * -// * for the full disclaimer and the limitation of liability. * -// * * -// * This code implementation is the result of the scientific and * -// * technical work of the GEANT4 collaboration. * -// * By using, copying, modifying or distributing the software (or * -// * any work based on the software) you agree to acknowledge its * -// * use in resulting scientific publications, and indicate your * -// * acceptance of all terms of the Geant4 Software license. * -// ******************************************************************** -// -// this code implementation is the intellectual property of -// neutron_hp -- source file -// J.P. Wellisch, Nov-1996 -// A prototype of the low energy neutron transport model. -// -// By copying, distributing or modifying the Program (or any work -// based on the Program) you indicate your acceptance of this statement, -// and all its terms. -// -// -// 070523 bug fix for G4FPE_DEBUG on by A. Howard (and T. Koi) -// 081203 limit maximum trial for creating final states add protection for 1H isotope case by T. Koi -// -#include "StorkNeutronHPInelastic.hh" -#include "G4SystemOfUnits.hh" - -#include "G4NeutronHPManager.hh" - - StorkNeutronHPInelastic::StorkNeutronHPInelastic(G4double finalStateTemp) - :G4HadronicInteraction("NeutronHPInelastic") - { - SetMinEnergy( 0.0 ); - SetMaxEnergy( 20.*MeV ); - fsTemp = finalStateTemp; - G4int istatus; -#if defined WIN32-VC - istatus = system("echo %G4NEUTRONHPDATA%"); -#else - istatus = system("echo $G4NEUTRONHPDATA"); -#endif - if ( istatus < 0 ) - { - G4cout << "Warning! system(\"echo $G4NEUTRONHPDATA\") returns error value at StorkNeutronHPInelastic" << G4endl; - } - -// G4cout << " entering StorkNeutronHPInelastic constructor"<GetNumberOfIsotopes() == 1 ) - { - if ( (*(G4Element::GetElementTable()))[i]->GetIsotope( 0 )->GetZ() == 1 && (*(G4Element::GetElementTable()))[i]->GetIsotope( 0 )->GetN() == 1 ) exceptional = true; //1H - } - if ( !exceptional ) throw G4HadronicException(__FILE__, __LINE__, "Channel: Do not know what to do with this element"); - } - } -*/ - - for (G4int i=0; iGetNumberOfIsotopes() == 1 ) - { - if ( (*(G4Element::GetElementTable()))[i]->GetIsotope( 0 )->GetZ() == 1 && (*(G4Element::GetElementTable()))[i]->GetIsotope( 0 )->GetN() == 1 ) exceptional = true; //1H - } - if ( !exceptional ) throw G4HadronicException(__FILE__, __LINE__, "Channel: Do not know what to do with this element"); - } - - } - } - - StorkNeutronHPInelastic::~StorkNeutronHPInelastic() - { -// delete [] theInelastic; - for ( std::vector::iterator - it = theInelastic.begin() ; it != theInelastic.end() ; it++ ) - { - delete *it; - } - theInelastic.clear(); - } - - #include "G4NeutronHPThermalBoost.hh" - - G4HadFinalState * StorkNeutronHPInelastic::ApplyYourself(const G4HadProjectile& aTrack, G4Nucleus& aNucleus ) - { - if ( numEle < (G4int)G4Element::GetNumberOfElements() ) addChannelForNewElement(); - G4NeutronHPManager::GetInstance()->OpenReactionWhiteBoard(); - const G4Material * theMaterial = aTrack.GetMaterial(); - G4int n = theMaterial->GetNumberOfElements(); - G4int index = theMaterial->GetElement(0)->GetIndex(); - G4int it=0; - if(n!=1) - { - xSec = new G4double[n]; - G4double sum=0; - G4int i; - const G4double * NumAtomsPerVolume = theMaterial->GetVecNbOfAtomsPerVolume(); - G4double rWeight; - G4NeutronHPThermalBoost aThermalE; - for (i=0; iGetElement(i)->GetIndex(); - rWeight = NumAtomsPerVolume[i]; - //xSec[i] = theInelastic[index].GetXsec(aThermalE.GetThermalEnergy(aTrack, - xSec[i] = (*theInelastic[index]).GetXsec(aThermalE.GetThermalEnergy(aTrack, - theMaterial->GetElement(i), - std::max(0., theMaterial->GetTemperature()-fsTemp))); - xSec[i] *= rWeight; - sum+=xSec[i]; - } - G4double random = G4UniformRand(); - G4double running = 0; - for (i=0; iGetElement(i)->GetIndex(); - it = i; - //if(random<=running/sum) break; - if( sum == 0 || random<=running/sum) break; - } - delete [] xSec; - } - - //return theInelastic[index].ApplyYourself(theMaterial->GetElement(it), aTrack); - G4HadFinalState* result = (*theInelastic[index]).ApplyYourself(theMaterial->GetElement(it), aTrack); - - //Overwrite target parameters - aNucleus.SetParameters(G4NeutronHPManager::GetInstance()->GetReactionWhiteBoard()->GetTargA(),G4NeutronHPManager::GetInstance()->GetReactionWhiteBoard()->GetTargZ()); - const G4Element* target_element = (*G4Element::GetElementTable())[index]; - const G4Isotope* target_isotope=NULL; - G4int iele = target_element->GetNumberOfIsotopes(); - for ( G4int j = 0 ; j != iele ; j++ ) { - target_isotope=target_element->GetIsotope( j ); - if ( target_isotope->GetN() == G4NeutronHPManager::GetInstance()->GetReactionWhiteBoard()->GetTargA() ) break; - } - //G4cout << "Target Material of this reaction is " << theMaterial->GetName() << G4endl; - //G4cout << "Target Element of this reaction is " << target_element->GetName() << G4endl; - //G4cout << "Target Isotope of this reaction is " << target_isotope->GetName() << G4endl; - aNucleus.SetIsotope( target_isotope ); - - G4NeutronHPManager::GetInstance()->CloseReactionWhiteBoard(); - return result; - } - -const std::pair StorkNeutronHPInelastic::GetFatalEnergyCheckLevels() const -{ - // max energy non-conservation is mass of heavy nucleus -// if ( getenv("G4NEUTRONHP_DO_NOT_ADJUST_FINAL_STATE") ) return std::pair(5*perCent,250*GeV); - // This should be same to the hadron default value -// return std::pair(10*perCent,10*GeV); - return std::pair(10*perCent,DBL_MAX); -} - -void StorkNeutronHPInelastic::addChannelForNewElement() -{ - for ( G4int i = numEle ; i < (G4int)G4Element::GetNumberOfElements() ; i++ ) - { - G4cout << "StorkNeutronHPInelastic Prepairing Data for the new element of " << (*(G4Element::GetElementTable()))[i]->GetName() << G4endl; - - theInelastic.push_back( new StorkNeutronHPChannelList(fsTemp) ); - (*theInelastic[i]).Init((*(G4Element::GetElementTable()))[i], dirName); - G4int itry = 0; - do - { - (*theInelastic[i]).Register(&theNFS, "F01"); // has - (*theInelastic[i]).Register(&theNXFS, "F02"); - (*theInelastic[i]).Register(&the2NDFS, "F03"); - (*theInelastic[i]).Register(&the2NFS, "F04"); // has, E Done - (*theInelastic[i]).Register(&the3NFS, "F05"); // has, E Done - (*theInelastic[i]).Register(&theNAFS, "F06"); - (*theInelastic[i]).Register(&theN3AFS, "F07"); - (*theInelastic[i]).Register(&the2NAFS, "F08"); - (*theInelastic[i]).Register(&the3NAFS, "F09"); - (*theInelastic[i]).Register(&theNPFS, "F10"); - (*theInelastic[i]).Register(&theN2AFS, "F11"); - (*theInelastic[i]).Register(&the2N2AFS, "F12"); - (*theInelastic[i]).Register(&theNDFS, "F13"); - (*theInelastic[i]).Register(&theNTFS, "F14"); - (*theInelastic[i]).Register(&theNHe3FS, "F15"); - (*theInelastic[i]).Register(&theND2AFS, "F16"); - (*theInelastic[i]).Register(&theNT2AFS, "F17"); - (*theInelastic[i]).Register(&the4NFS, "F18"); // has, E Done - (*theInelastic[i]).Register(&the2NPFS, "F19"); - (*theInelastic[i]).Register(&the3NPFS, "F20"); - (*theInelastic[i]).Register(&theN2PFS, "F21"); - (*theInelastic[i]).Register(&theNPAFS, "F22"); - (*theInelastic[i]).Register(&thePFS, "F23"); - (*theInelastic[i]).Register(&theDFS, "F24"); - (*theInelastic[i]).Register(&theTFS, "F25"); - (*theInelastic[i]).Register(&theHe3FS, "F26"); - (*theInelastic[i]).Register(&theAFS, "F27"); - (*theInelastic[i]).Register(&the2AFS, "F28"); - (*theInelastic[i]).Register(&the3AFS, "F29"); - (*theInelastic[i]).Register(&the2PFS, "F30"); - (*theInelastic[i]).Register(&thePAFS, "F31"); - (*theInelastic[i]).Register(&theD2AFS, "F32"); - (*theInelastic[i]).Register(&theT2AFS, "F33"); - (*theInelastic[i]).Register(&thePDFS, "F34"); - (*theInelastic[i]).Register(&thePTFS, "F35"); - (*theInelastic[i]).Register(&theDAFS, "F36"); - (*theInelastic[i]).RestartRegistration(); - itry++; - } - while( !(*theInelastic[i]).HasDataInAnyFinalState() && itry < 6 ); - // 6 is corresponding to the value(5) of G4NeutronHPChannel. TK - - if ( itry == 6 ) - { - // No Final State at all. - G4bool exceptional = false; - if ( (*(G4Element::GetElementTable()))[i]->GetNumberOfIsotopes() == 1 ) - { - if ( (*(G4Element::GetElementTable()))[i]->GetIsotope( 0 )->GetZ() == 1 && (*(G4Element::GetElementTable()))[i]->GetIsotope( 0 )->GetN() == 1 ) exceptional = true; //1H - } - if ( !exceptional ) throw G4HadronicException(__FILE__, __LINE__, "Channel: Do not know what to do with this element"); - } - } - - numEle = (G4int)G4Element::GetNumberOfElements(); -} - -G4int StorkNeutronHPInelastic::GetVerboseLevel() const -{ - return G4NeutronHPManager::GetInstance()->GetVerboseLevel(); -} -void StorkNeutronHPInelastic::SetVerboseLevel( G4int newValue ) -{ - G4NeutronHPManager::GetInstance()->SetVerboseLevel(newValue); -} diff --git a/G4STORK/src/StorkNeutronHPIsoData.cc b/G4STORK/src/StorkNeutronHPIsoData.cc deleted file mode 100755 index 473fbc80..00000000 --- a/G4STORK/src/StorkNeutronHPIsoData.cc +++ /dev/null @@ -1,217 +0,0 @@ -// -// ******************************************************************** -// * License and Disclaimer * -// * * -// * The Geant4 software is copyright of the Copyright Holders of * -// * the Geant4 Collaboration. It is provided under the terms and * -// * conditions of the Geant4 Software License, included in the file * -// * LICENSE and available at http://cern.ch/geant4/license . These * -// * include a list of copyright holders. * -// * * -// * Neither the authors of this software system, nor their employing * -// * institutes,nor the agencies providing financial support for this * -// * work make any representation or warranty, express or implied, * -// * regarding this software system or assume any liability for its * -// * use. Please see the license in the file LICENSE and URL above * -// * for the full disclaimer and the limitation of liability. * -// * * -// * This code implementation is the result of the scientific and * -// * technical work of the GEANT4 collaboration. * -// * By using, copying, modifying or distributing the software (or * -// * any work based on the software) you agree to acknowledge its * -// * use in resulting scientific publications, and indicate your * -// * acceptance of all terms of the Geant4 Software license. * -// ******************************************************************** -// -// neutron_hp -- source file -// J.P. Wellisch, Nov-1996 -// A prototype of the low energy neutron transport model. -// -//080901 Avoiding troubles which caused by G4PhysicsVecotor of length 0 by T. Koi -// -#include "StorkNeutronHPIsoData.hh" -#include "G4NeutronHPManager.hh" -#include "G4SystemOfUnits.hh" -#include "G4NeutronHPDataUsed.hh" - - //G4bool StorkNeutronHPIsoData::Init(G4int A, G4int Z, G4double abun, G4String dirName, G4String aFSType) - G4bool StorkNeutronHPIsoData::Init(G4int A, G4int Z, G4int M, G4double abun, G4String dirName, G4String aFSType) - { - theChannelData = 0; - - G4double abundance = abun/100.; - G4String filename; - G4bool result = true; - //G4NeutronHPDataUsed aFile = theNames.GetName(A, Z, dirName, aFSType, result); - G4NeutronHPDataUsed aFile = theNames.GetName(A, Z, M, dirName, aFSType, result); - filename = aFile.GetName(); - //G4cout << "File name: " << filename << " for Z: " << Z << " and A: " << A << endl; -// if(filename=="") return false; - //std::ifstream theChannel(filename); - std::istringstream theChannel(filename,std::ios::in); - G4NeutronHPManager::GetInstance()->GetDataStream(filename,theChannel); - - if(Z==1 && (aFile.GetZ()!=Z || std::abs(aFile.GetA()-A)>0.0001) ) - { - if(getenv("NeutronHPNamesLogging")) G4cout << "Skipped = "<< filename <<" "<> dummy >> dummy; - theChannelData = new G4NeutronHPVector; - G4int nData; - theChannel >> nData; - theChannelData->Init(theChannel, nData, eV, abundance*barn); -// G4cout << "Channel Data Statistics: "<GetVectorLength()<> hpw; -// theChannelData->Dump(); - //theChannel.close(); - return result; - } - - //void StorkNeutronHPIsoData::Init(G4int A, G4int Z, G4double abun) //fill PhysicsVector for this Isotope - void StorkNeutronHPIsoData::Init(G4int A, G4int Z, G4int M, G4double abun, G4String dirName) //fill PhysicsVector for this Isotope - { - G4String baseName; - if (dirName=="DEFAULT") - { - if(!getenv("G4NEUTRONHPDATA")) - throw G4HadronicException(__FILE__, __LINE__, "Please setenv G4NEUTRONHPDATA to point to the neutron cross-section files."); - baseName = getenv("G4NEUTRONHPDATA"); - dirName = baseName+"/Fission"; - } - else - { - baseName = dirName; - dirName = baseName+"/Fission"; - } - //if(Z>89) - if(Z>87) //TK Modifed for ENDF VII.0 - { - //Init(A, Z, abun, dirName, "/CrossSection/"); - Init(A, Z, M, abun, dirName, "/CrossSection"); - } - else - { - theChannelData = new G4NeutronHPVector; - } - theFissionData = theChannelData; - theChannelData = 0; // fast fix for double delete; revisit later. @@@@@@@ - dirName = baseName+"/Capture"; - //Init(A, Z, abun, dirName, "/CrossSection/"); - Init(A, Z, M, abun, dirName, "/CrossSection"); - theCaptureData = theChannelData; - theChannelData = 0; - dirName = baseName+"/Elastic"; - //Init(A, Z, abun, dirName, "/CrossSection/"); - Init(A, Z, M, abun, dirName, "/CrossSection"); - theElasticData = theChannelData; - theChannelData = 0; - dirName = baseName+"/Inelastic"; - //Init(A, Z, abun, dirName, "/CrossSection/"); - Init(A, Z, M, abun, dirName, "/CrossSection"); - theInelasticData = theChannelData; - theChannelData = 0; - -// if(theInelasticData!=0) G4cout << "Inelastic Data Statistics: "<GetVectorLength()<GetVectorLength()<GetVectorLength()<GetVectorLength()<Dump(); -// G4cout << "Elastic data"<Dump(); -// G4cout << "Capture data"<Dump(); -// G4cout << "Fission data"<Dump(); - - } - - G4bool StorkNeutronHPIsoData::FileExists(G4int A, G4int Z, G4String DirName ) - { - G4String processes[4] = {"/Inelastic", "/Elastic", "/Capture", "/Fission"}; - G4String filename; - ElementNames elemNames; - std::stringstream stream; - std::ifstream *in; - - for(G4int i =0; i<4; i++) - { - if(!((Z<88)&&(i==3))) - { - stream.str(""); - stream.clear(); - stream << DirName << processes[i] << "/CrossSection/" << Z << "_" << A << "_" << elemNames.GetName(Z); - filename = stream.str(); - - in = new std::ifstream ( filename.c_str() ); - if(!(in->good())) - { - in->close(); - delete in; - filename+=".z"; - in = new std::ifstream ( filename.c_str() , std::ios::binary ); - if(!(in->good())) - { - in->close(); - delete in; - stream.str(""); - stream.clear(); - stream << DirName << processes[i] << "/CrossSection/" << Z << "_" << "nat" << "_" << elemNames.GetName(Z); - filename = stream.str(); - - in = new std::ifstream ( filename.c_str() ); - if(!(in->good())) - { - in->close(); - delete in; - filename+=".z"; - in = new std::ifstream ( filename.c_str() , std::ios::binary ); - if(!(in->good())) - { - in->close(); - delete in; - return false; - } - else - { - in->close(); - delete in; - } - } - else - { - in->close(); - delete in; - } - - } - else - { - in->close(); - delete in; - } - } - else - { - in->close(); - delete in; - - } - - } - } - - return true; - } - diff --git a/G4STORK/src/StorkNeutronHPNames.cc b/G4STORK/src/StorkNeutronHPNames.cc deleted file mode 100755 index fe5da8a2..00000000 --- a/G4STORK/src/StorkNeutronHPNames.cc +++ /dev/null @@ -1,387 +0,0 @@ -// -// ******************************************************************** -// * License and Disclaimer * -// * * -// * The Geant4 software is copyright of the Copyright Holders of * -// * the Geant4 Collaboration. It is provided under the terms and * -// * conditions of the Geant4 Software License, included in the file * -// * LICENSE and available at http://cern.ch/geant4/license . These * -// * include a list of copyright holders. * -// * * -// * Neither the authors of this software system, nor their employing * -// * institutes,nor the agencies providing financial support for this * -// * work make any representation or warranty, express or implied, * -// * regarding this software system or assume any liability for its * -// * use. Please see the license in the file LICENSE and URL above * -// * for the full disclaimer and the limitation of liability. * -// * * -// * This code implementation is the result of the scientific and * -// * technical work of the GEANT4 collaboration. * -// * By using, copying, modifying or distributing the software (or * -// * any work based on the software) you agree to acknowledge its * -// * use in resulting scientific publications, and indicate your * -// * acceptance of all terms of the Geant4 Software license. * -// ******************************************************************** -// -// neutron_hp -- source file -// J.P. Wellisch, Nov-1996 -// A prototype of the low energy neutron transport model. -// -// 24-Jan-07 Enable to use exact data only and add warnig when substitute file is used T. Koi -// 30-Jan-07 Modified method of searching substitute isotope data by T. Koi -// 07-06-12 fix memory leaking by T. Koi -// 07-06-25 Change data selection logic when G4NEUTRONHP_SKIP_MISSING_ISOTOPES is turn on -// Natural Abundance data are allowed. by T. Koi -// 07-07-06 Allow _nat_ final state even for isotoped cross sections by T. Koi -// 08-09-01 Add protection that deuteron data do not selected for hydrogen and so on by T. Koi -// -#include "StorkNeutronHPNames.hh" -#include "G4NeutronHPManager.hh" -#include "G4SandiaTable.hh" -#include "G4HadronicException.hh" -#include - - const G4String StorkNeutronHPNames::theString[100] = {"Hydrogen", "Helium", - "Lithium", "Berylium", "Boron", "Carbon", "Nitrogen", "Oxygen", "Fluorine", - "Neon", "Sodium", "Magnesium", "Aluminum", "Silicon", "Phosphorous", - "Sulfur", "Chlorine", "Argon", "Potassium", "Calcium", "Scandium", - "Titanium", "Vanadium", "Chromium", "Manganese", "Iron", "Cobalt", "Nickel", - "Copper", "Zinc", "Gallium", "Germanium", "Arsenic", "Selenium", "Bromine", - "Krypton", "Rubidium", "Strontium", "Yttrium", "Zirconium", "Niobium", - "Molybdenum", "Technetium", "Ruthenium", "Rhodium", "Palladium", "Silver", - "Cadmium", "Indium", "Tin", "Antimony", "Tellurium", "Iodine", "Xenon", - "Cesium", "Barium", "Lanthanum", "Cerium", "Praseodymium", "Neodymium", - "Promethium", "Samarium", "Europium", "Gadolinium", "Terbium", "Dysprosium", - "Holmium", "Erbium", "Thulium", "Ytterbium", "Lutetium", "Hafnium", - "Tantalum", "Tungsten", "Rhenium", "Osmium", "Iridium", "Platinium", "Gold", - "Mercury", "Thallium", "Lead", "Bismuth", "Polonium", "Astatine", "Radon", - "Francium", "Radium", "Actinium", "Thorium", "Protactinium", "Uranium", - "Neptunium", "Plutonium", "Americium", "Curium", "Berkelium", "Californium", - "Einsteinium","Fermium"}; - - - G4String StorkNeutronHPNames::GetName(G4int i) { return theString[i]; } - -//G4NeutronHPDataUsed StorkNeutronHPNames::GetName(G4int A, G4int Z, G4String base, G4String rest, G4bool & aFlag) -G4NeutronHPDataUsed StorkNeutronHPNames::GetName(G4int A, G4int Z, G4int M, G4String base, G4String rest, G4bool & aFlag) -{ - - G4int verboseLevel = G4NeutronHPManager::GetInstance()->GetVerboseLevel(); - - //G4cout << Z << " " << A << " " << M << " " << base << " " << rest << G4endl; - - //Excited isomer indicator - std::stringstream ss; - G4String sM; - if ( M > 0 ) - { - ss << "m"; - ss << M; - ss >> sM; - ss.clear(); - } - - G4NeutronHPDataUsed result; - aFlag = true; -if(getenv("NeutronHPNames")) G4cout << "Names::GetName entered for Z = " << Z << ", A = " << A <92.5&&!getenv("AllowForHeavyElements") ) - { - //G4cerr << "Please contact Hans-Peter.Wellisch@cern.ch"<92 are not provided"); - } - - G4String * theName = 0; - G4String theFileName(""); - -// G4int inc = 1; - - G4int flip_Z = 1; - G4int delta_Z = 0; - - G4int flip_A = 1; - G4int delta_A = 0; - - //std::ifstream * check = new std::ifstream(".dummy"); - std::istringstream* check = NULL; - G4bool first = true; -if(getenv("NeutronHPNames")) G4cout << "entered GetName!!!"<close(); - delete check; - } - - //check = new std::ifstream(*theName); - check = new std::istringstream(std::ios::in); - G4NeutronHPManager::GetInstance()->GetDataStream(*theName,*check); - if ( !(*check) ) - { - //check->close(); - delete check; - check = 0; - aFlag = false; - if ( first ) - { - aFlag = true; - first = false; - biff = new G4String(); // delete here as theName - *biff = base+"/CrossSection/"+itoa(myZ)+"_"+"nat"+"_"+theString[myZ-1]; - if(theName!=0) delete theName; - theName = biff; -if(getenv("NeutronHPNames")) G4cout <<"HPWD 2 "<<*theName<GetDataStream(*theName,*check); - if ( !(*check) ) - { - //check->close(); - delete check; - check = 0; - aFlag = false; - } - else - { - biff = new G4String(); // delete here as theName - if(theName!=0) delete theName; - *biff = base+"/"+rest+"/"+itoa(myZ)+"_"+"nat"+"_"+theString[myZ-1]; - if ( rest=="/CrossSection" ) *biff = base+rest+"/"+itoa(myZ)+"_"+"nat"+"_"+theString[myZ-1]; - theName = biff; -if(getenv("NeutronHPNames")) G4cout <<"HPWD 3 "<<*theName<GetDataStream(fileName,*file); - - if ( *file ) - { - -// isotope FS -if(getenv("NeutronHPNames")) G4cout <<"HPWD 4b1 "<<*theName<GetDataStream(fileName,*file); - if ( *file ) - { - -// FS neither isotope nor _nat_ -if(getenv("NeutronHPNames")) G4cout <<"HPWD 4b2a "<<*theName<theMaxOffSet||myZ==0||myA==0) - if ( delta_Z > theMaxOffSet ) - { - //if ( inc > 0 ) - //{ - // inc*= -1; - // myZ = Z; - // myA = A; - //} - //else - //{ - G4cout <<"StorkNeutronHPNames: Sorry, this material does not come near to any data."< theMaxOffSet ) - if ( delta_A > 2*theMaxOffSet ) - { - delta_A = 0; - flip_A = 1; - - first = true; - - if ( flip_Z > 0 ) - { - delta_Z +=1; - } - myZ = Z + flip_Z * delta_Z; - flip_Z *= -1; - - myA = A; - if ( myZ > 100 ) - { - myZ = 100; - } - if ( myZ < 1 ) - { - myZ = 1; - } - -// myZ += inc; - } - else - { - if ( flip_A > 0 ) - { - delta_A += 1; - } - myA = A + flip_A * delta_A; - flip_A *= -1; - - if ( myA < 1 ) - { - myA = 1; - } - -// myA += inc; - } - - } - while( myZ == 0 || myA == 0 ); // No meaning - - } - while((!check) || (!(*check))); - - if(getenv("NeutronHPNamesLogging") || getenv("NeutronHPNames")) - { - G4cout << "Names::GetName: last theName proposal = "<< G4endl; - G4cout << *theName <<" "< 0 ) { - G4cout << "NeutronHP: " << reac << " file for Z = " << Z << ", A = " << A << " is not found and CrossSection set to 0." << G4endl; - } - G4String new_name = base+"/"+rest+"/"+"0_0_Zero"; - result.SetName( new_name ); - } - else - { - //080901 Add protection that deuteron data do not selected for hydrogen and so on by T. Koi - if ( ( reac.find("Inelastic") != reac.size() && ( (Z == 1 && A == 1) || (Z == 2 && A == 4) ) ) - || ( reac.find("Capture") != reac.size() && ( (Z == 1 && A == 3) || (Z == 2 && A == 4) ) ) - || ( reac.find("Fission") != reac.size() && ( (Z == 88 && A == 224) || (Z == 88 && A == 225) || (Z == 89 && A == 225) || (Z == 88 && A == 226) ) ) ) - - { - G4String new_name = base+"/"+rest+"/"+"0_0_Zero"; - result.SetName( new_name ); - } - else - { - if ( verboseLevel > 1 ) { - G4cout << "NeutronHP: " << reac << " file for Z = " << Z << ", A = " << A << " is not found and NeutronHP will use " << result.GetName() << G4endl; - } - } - } - } - } - - delete theName; - if(aFlag) - { - //check->close(); - delete check; - check = NULL; - } - return result; - } diff --git a/G4STORK/src/StorkNeutronPhysicsList.cc b/G4STORK/src/StorkNeutronPhysicsList.cc deleted file mode 100755 index f5c94e4c..00000000 --- a/G4STORK/src/StorkNeutronPhysicsList.cc +++ /dev/null @@ -1,114 +0,0 @@ -/* -StorkNeutronPhysicsList.cc - -Created by: Liam Russell -Date: 23-02-2012 -Modified: 11-03-2013 - -Source code for StorkNeutronPhysicsList class. - -*/ - - -// Include header file -#include "StorkNeutronPhysicsList.hh" - - -// Constructor -StorkNeutronPhysicsList::StorkNeutronPhysicsList(const StorkParseInput* infile) -{ - SetVerboseLevel(0); - - csDirName = infile->GetCSDirName(); - fsDirName = infile->GetFSDirName(); - kCalcType = infile->GetKCalcType(); - infile->GetPeriodicBCVector(periodicBCVec); - infile->GetReflectBCVector(reflectBCVec); - - // Insure that the slave processes do not output the physics process table -#ifdef G4USE_TOPC - if(!TOPC_is_master()) - { - G4HadronicProcessStore *theStore = G4HadronicProcessStore::Instance(); - theStore->SetVerbose(0); - } -#endif -} - - -// Destructor -StorkNeutronPhysicsList::~StorkNeutronPhysicsList() -{ - delete theHPNeutron; - //delete theLEPNeutron; - delete theBertiniNeutron; - delete theNeutrons; -} - - -// ConstructParticle() -void StorkNeutronPhysicsList::ConstructParticle() -{ - // Construct relevant particles for the physics list - G4Geantino::GeantinoDefinition(); - G4GenericIon::GenericIonDefinition(); - G4Neutron::NeutronDefinition(); - G4Deuteron::DeuteronDefinition(); - G4Triton::TritonDefinition(); - G4Gamma::GammaDefinition(); - G4Proton::ProtonDefinition(); - G4AntiProton::AntiProtonDefinition(); - G4PionPlus::PionPlusDefinition(); - G4PionZero::PionZeroDefinition(); - G4PionMinus::PionMinusDefinition(); - G4KaonPlus::KaonPlusDefinition(); - G4KaonZero::KaonZeroDefinition(); - G4KaonMinus::KaonMinusDefinition(); - G4KaonZeroShort::KaonZeroShortDefinition(); - G4KaonZeroLong::KaonZeroLongDefinition(); - G4Alpha::AlphaDefinition(); - G4Electron::ElectronDefinition(); - G4Positron::PositronDefinition(); -} - - -// ConstructProcess() -// Construct the HP processes for neutron energies in [0,20) MeV and the -// Bertini processes for neutron energies in [20,inf) MeV. -// Also add transportation. -void StorkNeutronPhysicsList::ConstructProcess() -{ - // Create the Bertini neutron processes ( > 20 MeV) - theNeutrons = new StorkNeutronProcessBuilder(periodicBCVec, reflectBCVec, fsDirName, kCalcType); - - // Create and register the builders - theNeutrons->RegisterMe(theHPNeutron = new StorkHPNeutronBuilder(csDirName)); - theNeutrons->RegisterMe(theBertiniNeutron = new G4BertiniNeutronBuilder); - //theNeutrons->RegisterMe(theLEPNeutron = new G4LEPNeutronBuilder); - - // Set the minimum and maximum energies for the NeutronHP processes - theHPNeutron->SetMinEnergy(0.*eV); - theHPNeutron->SetMaxEnergy(20.*MeV); - - // Set the minimum and maximum energies for the Bertini processes - theBertiniNeutron->SetMinEnergy(20.0*MeV); - theBertiniNeutron->SetMaxEnergy(9.9*GeV); - - /* // Set the minimum and maximum energies for the LEP processes - theLEPNeutron->SetMinEnergy(20.0*MeV); - theLEPNeutron->SetMinInelasticEnergy(9.5*GeV); - theLEPNeutron->SetMaxInelasticEnergy(25.*GeV); - */ - // Build the models and data - theNeutrons->Build(); - - // Add the transportation process - AddTransportation(); -} - - -// SetCuts() -void StorkNeutronPhysicsList::SetCuts() -{ - SetCutsWithDefault(); -} diff --git a/G4STORK/src/StorkNeutronProcessBuilder.cc b/G4STORK/src/StorkNeutronProcessBuilder.cc deleted file mode 100755 index 03f61a84..00000000 --- a/G4STORK/src/StorkNeutronProcessBuilder.cc +++ /dev/null @@ -1,177 +0,0 @@ -/* -StorkNeutronProcessBuilder.cc - -Created by: Liam Russell -Date: 23-02-2012 -Modified: 11-03-2013 - -Source code for StorkNeutronProcessBuilder class. - -*/ - - -// Include header file -#include "StorkNeutronProcessBuilder.hh" - - -// Constructor -StorkNeutronProcessBuilder::StorkNeutronProcessBuilder(std::vector* pBCVec, std::vector* rBCVec, G4String FSDirName, G4int KCalcType) -:wasActivated(false) -{ - // Create the physics processes - theNeutronElastic = new StorkHadronElasticProcess; - theNeutronInelastic = new StorkNeutronInelasticProcess; - theNeutronCapture = new StorkHadronCaptureProcess; - theNeutronFission = new StorkHadronFissionProcess; - theStepLimiter = new StorkTimeStepLimiter; - TheUserBoundaryCond = new StorkUserBCStepLimiter(pBCVec,rBCVec); - TheZeroBoundaryCond = new StorkZeroBCStepLimiter(pBCVec,rBCVec); - - kCalcType = KCalcType; - fsDirName=FSDirName; -} - - -// Destructor -StorkNeutronProcessBuilder::~StorkNeutronProcessBuilder() -{ - // Delete the processes - if(theNeutronElastic) - delete theNeutronElastic; - if(theNeutronInelastic) - delete theNeutronInelastic; - if(theNeutronCapture) - delete theNeutronCapture; - if(theNeutronFission) - delete theNeutronFission; - if(theStepLimiter) - delete theStepLimiter; - if(TheUserBoundaryCond) - delete TheUserBoundaryCond; - if(TheZeroBoundaryCond) - delete TheZeroBoundaryCond; -} - - -// Build() -// Build the data and models for the neutron processes -void StorkNeutronProcessBuilder::Build() -{ - G4double fsTemp=0.; - wasActivated = true; - StorkHPNeutronBuilder *aHPBuilder; - - if(fsDirName!="DEFAULT") - { - if(fsDirName[fsDirName.size()-1]=='/') - fsDirName.erase(fsDirName.size()-1); - ExtractTemp(fsDirName, fsTemp); - setenv("G4NEUTRONHPDATA",fsDirName,1); - std::vector::iterator i; - for(i=theModelCollections.begin(); i!=theModelCollections.end(); i++) - { - aHPBuilder = dynamic_cast(*i); - if(aHPBuilder) - aHPBuilder->SetFSTemperature(fsTemp); - } - } - - // Build the models and data for the neutron processes (all energies) - std::vector::iterator i; - for(i=theModelCollections.begin(); i!=theModelCollections.end(); i++) - { - aHPBuilder = dynamic_cast(*i); - - // Only build low energy models for the elastic processes - if(aHPBuilder) - (*i)->Build(theNeutronElastic); - - (*i)->Build(theNeutronInelastic); - (*i)->Build(theNeutronCapture); - (*i)->Build(theNeutronFission); - } - - // Create the high energy elastic model - theHighElasticModel = new G4DiffuseElastic(); - theHighElasticModel->SetMinEnergy(20.0*MeV); - theHighElasticModel->SetMaxEnergy(20000.*GeV); - - // Register model with elastic process - theNeutronElastic->RegisterMe(theHighElasticModel); - - // Create the high energy fission model - theHighFissionModel = new G4LFission(); - - // Set the minimum energy limit - theHighFissionModel->SetMinEnergy(20.0*MeV); - theHighFissionModel->SetMaxEnergy(20000.*GeV); - - // Register model with fission process - theNeutronFission->RegisterMe(theHighFissionModel); - - theHighCaptureModel = new G4NeutronRadCapture(); - - // Set the minimum energy limit - theHighCaptureModel->SetMinEnergy(20.0*MeV); - theHighCaptureModel->SetMaxEnergy(20000.*GeV); - - - // Register model with fission process - theNeutronCapture->RegisterMe(theHighCaptureModel); - - // Add processes to the process manager - G4ProcessManager * theProcMan = G4Neutron::Neutron()->GetProcessManager(); - - theProcMan->AddDiscreteProcess(theNeutronElastic); - theProcMan->AddDiscreteProcess(theNeutronInelastic); - theProcMan->AddDiscreteProcess(theNeutronCapture); - theProcMan->AddDiscreteProcess(theNeutronFission); - if(kCalcType!=2) - theProcMan->AddDiscreteProcess(theStepLimiter); - theProcMan->AddDiscreteProcess(TheUserBoundaryCond); - theProcMan->AddDiscreteProcess(TheZeroBoundaryCond); -} - -bool StorkNeutronProcessBuilder::ExtractTemp(G4String name, G4double &temp) -{ - bool check = false; - std::stringstream ss; - G4int index = name.size()-1, startPos=1, endPos=0; - while(index>=0) - { - if(check) - { - if(((name[index]>='0')&&(name[index]<='9'))||(name[index]=='.')) - { - startPos--; - } - else - { - break; - } - } - else - { - if((name[index]>='0')&&(name[index]<='9')) - { - if((index+1==int(name.size()))||!((name[index+1]=='k')||(name[index+1]=='K'))) - { - return false; - } - check = true; - startPos=endPos=index; - } - } - index--; - } - - if(endPos>=startPos) - { - G4String temperature = name.substr(startPos, endPos-startPos+1); - ss.str(temperature); - ss >> temp; - } - - return check; -} - diff --git a/G4STORK/src/StorkNeutronSD.cc b/G4STORK/src/StorkNeutronSD.cc deleted file mode 100755 index 6673508a..00000000 --- a/G4STORK/src/StorkNeutronSD.cc +++ /dev/null @@ -1,484 +0,0 @@ -/* -StorkNeutronSD.cc - -Created by: Liam Russell -Date: 22-06-2011 -Modified: 11-03-2013 - -Source code file for StorkNeutronSD class. - -*/ - - -// Include header file - -#include "StorkNeutronSD.hh" - - -// Constructor - -StorkNeutronSD::StorkNeutronSD(G4String name, G4int KCalcType, G4bool instD, G4bool sourcefileD) -:G4VSensitiveDetector(name), kCalcType(KCalcType), instantDelayed(instD), sourcefileDelayed(sourcefileD) -{ - // Set collection name and initialize ID - collectionName.insert("Tally"); - HCID1 = -1; - - // Get a pointer to the run manager and process manager - runMan = dynamic_cast(G4RunManager::GetRunManager()); - - // Set process manager pointer to NULL - procMan = NULL; -} - - -// Initialize() -// Initialize the sensitive detector member variables for the current event. -void StorkNeutronSD::Initialize(G4HCofThisEvent *HCE) -{ -#ifdef G4TIMESD - sdTimer.Start(); -#endif - - // Make a new tally hit collection for this detector - tallyHitColl = new TallyHC(SensitiveDetectorName, collectionName[0]); - - if(HCID1 < 0) - HCID1 = G4SDManager::GetSDMpointer()->GetCollectionID(tallyHitColl); - - - // Add the losses to the hit collection for this event - HCE->AddHitsCollection(HCID1,tallyHitColl); - - // Get the new run end time - runEnd = runMan->GetRunEnd(); - - // Initialize and clear the member variables - nLoss = nProd = dProd = 0; - totalLifetime = 0.0; - fSites.clear(); - fnEnergy.clear(); - survivors.clear(); - delayed.clear(); - prevTrackID = -1; - -#ifdef STORK_EXPLICIT_LOSS - nCap = nFiss = nEsc = nInel = 0; -#endif - -#ifdef G4TIMESD - cycles = 0; - cycleTime = 0.0; - sdTimer.Stop(); - totalSDTime = sdTimer.GetRealElapsed(); -#endif - - // Get pointer to StorkProcessManager - procMan = StorkProcessManager::GetStorkProcessManagerPtr(); -} - - -// ProcessHits() -// Determine which reaction type of each hit. Tally neutrons produced and lost, -// and lifetime of lost neutrons. Also record fission sites/energy and save -// survivors and delayed neutrons. -// Kill any non-neutron particles produced. -G4bool StorkNeutronSD::ProcessHits(G4Step *aStep, G4TouchableHistory*) -{ -#ifdef G4TIMESD - phTimer.Start(); -#endif - - // Get the track for the current particle - G4Track *aTrack = aStep->GetTrack(); - - // Particle type involved in hit - G4ParticleDefinition* hitDefinition = aTrack->GetDefinition(); - - // Only track hits by neutrons - // Kill any particles that are not neutrons and return - if(hitDefinition != G4Neutron::NeutronDefinition()) - { - aTrack->SetTrackStatus(fKillTrackAndSecondaries); - -#ifdef G4TIMESD - phTimer.Stop(); - cycleTime += phTimer.GetRealElapsed(); - cycles++; -#endif - - return true; - } - - // Find data necessary to record the hit - - // The pre and post step inside the SD - G4StepPoint *preStepPoint = aStep->GetPreStepPoint(); - G4StepPoint *postStepPoint = aStep->GetPostStepPoint(); - - // Find the time of the hit - G4double hitTime = postStepPoint->GetGlobalTime(); - // Find the lifetime of the track - G4double lifetime = postStepPoint->GetLocalTime(); - - // Set up other variables to be used later - G4TrackVector *trackVector; - std::vector::iterator itr; - - - // If the neutron is a primary neutron, on its first step, fix the lifetime - // Also add the track info (fission generation) - if(!aTrack->GetParentID() && aTrack->GetCurrentStepNumber() == 1) - { - // Get the primary particle user information - StorkPrimaryNeutronInfo *pnInfo = dynamic_cast( - aTrack->GetDynamicParticle()-> - GetPrimaryParticle()-> - GetUserInformation()); - - // Set the lifetime of the primary track - lifetime += pnInfo->GetLifeTime(); - aTrack->SetLocalTime(lifetime); - postStepPoint->AddLocalTime(pnInfo->GetLifeTime()); - - // Set the weight of the particle - aTrack->SetUserInformation(new StorkTrackInfo(pnInfo->GetWeight())); - } - - // Find the process used in the hit (if it is defined) - hitProcess = ""; - if(postStepPoint->GetProcessDefinedStep() != 0) - { - hitProcess = postStepPoint->GetProcessDefinedStep()->GetProcessName(); - } - - // If the time is beyond the simulation time, the kill the track and - // any secondaries (stops simulation from running forever) - // Save the neutron as a survivor - if(hitProcess == "StorkTimeStepLimiter") - { - SaveSurvivors(aTrack); - - aTrack->SetTrackStatus(fKillTrackAndSecondaries); - -#ifdef G4TIMESD - phTimer.Stop(); - cycleTime += phTimer.GetRealElapsed(); - cycles++; -#endif - - return true; - } - - if(kCalcType != 2) - { - if(hitTime > runEnd) - { - G4cout << "*** ERROR particle exists beyond run end: " - << hitTime << " > " << runEnd << G4endl; - } - } - - - // Record the site of the fission and the lifetime of the incident neutron. - // Also update the neutron production and loss totals, and save any delayed - // neutron daughters. - if(hitProcess == "StorkHadronFission") - { - trackVector = const_cast(aStep->GetSecondary()); - itr = trackVector->begin(); - - // Record number of daughter neutrons - for( ; itr != trackVector->end(); itr++) - { - // Check if secondary is a neutron - if((*itr)->GetDefinition() == G4Neutron::NeutronDefinition()) - { - // Check if the neutron is a delayed neutron - if((*itr)->GetGlobalTime() > hitTime) - { - // Correct the lifetime of the delayed neutron - (*itr)->SetLocalTime((*itr)->GetGlobalTime() - hitTime); - - // Correct global time to produce instantaneously - if(instantDelayed) - { - (*itr)->SetGlobalTime(hitTime); - if(kCalcType == 2) - { - SaveSurvivors((*itr)); - (*itr)->SetTrackStatus(fKillTrackAndSecondaries); - } - } - // Otherwise save (and kill) the delayed neutron for later - else - { - SaveDelayed(*itr); - (*itr)->SetTrackStatus(fKillTrackAndSecondaries); - } - - // Increment delayed neutron production counter - dProd++; - } - else if(kCalcType == 2) - { - SaveSurvivors((*itr)); - (*itr)->SetTrackStatus(fKillTrackAndSecondaries); - } - - // Increment neutron production counter - nProd++; - } - // Stop and kill particle if it is not a neutron - else - { - (*itr)->SetTrackStatus(fKillTrackAndSecondaries); - } - } - - // Record tally info - nLoss++; - totalLifetime += lifetime; - fSites.push_back(postStepPoint->GetPosition()); - - // changed fnenergy to collect the energy from the poststeppoint instead of the presteppoint - //fnEnergy.push_back(postStepPoint->GetKineticEnergy()); - - fnEnergy.push_back(preStepPoint->GetKineticEnergy()); - - #ifdef STORK_EXPLICIT_LOSS - nFiss++; - #endif - - if(kCalcType == 2) - { - #ifdef G4TIMESD - phTimer.Stop(); - cycleTime += phTimer.GetRealElapsed(); - cycles++; - #endif - - return true; - } - } - // If the neutron is captured, update the loss counter and record the - // lifetime. - else if(hitProcess == "StorkHadronCapture") - { - nLoss++; - totalLifetime += lifetime; - - // Kill any non-neutron (all) secondaries - trackVector = const_cast(aStep->GetSecondary()); - itr = trackVector->begin(); - - for( ; itr != trackVector->end(); itr++) - { - (*itr)->SetTrackStatus(fKillTrackAndSecondaries); - } - -#ifdef STORK_EXPLICIT_LOSS - nCap++; -#endif - } - - // If an inelastic collision occurs, set the first daughter to be the - // incident neutron, and then any others (n,2n; etc.) are simply - // daughter neutrons. Update the production and loss totals. - else if(hitProcess == "StorkNeutronInelastic") - { - G4bool nMulti = false; - - trackVector = const_cast(aStep->GetSecondary()); - itr = trackVector->begin(); - - for( ; itr != trackVector->end(); itr++) - { - // Set the neutrons lifetime to that of the current neutron - if((*itr)->GetDefinition() == G4Neutron::NeutronDefinition()) - { - if(nMulti) - { - nProd++; - } - else - { - nMulti = true; - (*itr)->SetLocalTime(lifetime); - } - } - // Kill secondary particle if it is not a neutron - else - { - (*itr)->SetTrackStatus(fKillTrackAndSecondaries); - } - } - - // Check for inelastic collisions where neutron is killed - if(!nMulti) - { - nLoss++; - totalLifetime += lifetime; - -#ifdef STORK_EXPLICIT_LOSS - nInel++; -#endif - } - } - // If an elastic collision occurs kill any secondaries (uranium atom, etc.) - else if(hitProcess == "StorkHadronElastic") - { - trackVector = const_cast(aStep->GetSecondary()); - itr = trackVector->begin(); - - for( ; itr != trackVector->end(); itr++) - { - if((*itr)->GetDefinition() != G4Neutron::NeutronDefinition()) - { - (*itr)->SetTrackStatus(fKillTrackAndSecondaries); - } - else - { - nProd++; - } - } - } - // If the neutron leaves the simulation world, update the loss counter and - // lifetime total. - else if(hitProcess == "StorkZeroBCStepLimiter") - { - nLoss++; - totalLifetime += lifetime; - - // Kill the neutron - aTrack->SetTrackStatus(fKillTrackAndSecondaries); - - #ifdef STORK_EXPLICIT_LOSS - nEsc++; - #endif - } - else - { - if(hitProcess != "Transportation" && - hitProcess != "StorkUserBCStepLimiter") - G4cerr << "***WARNING: Untracked process is" << hitProcess << G4endl; - } - -#ifdef G4TIMESD - phTimer.Stop(); - cycleTime += phTimer.GetRealElapsed(); - cycles++; -#endif - - return true; -} - - -// SaveSurvivors() -// Finds the position, lifetime and momentum of the particle at the run -// threshold (end of the run) -// Assumes that velocity doesn't change during flight (shouldn't because no -// along step processes active) -void StorkNeutronSD::SaveSurvivors(const G4Track *aTrack) -{ - // Get size of last step - if(aTrack->GetStep()) - { - G4double previousStepSize = aTrack->GetStep()->GetStepLength(); - - // Get the number of interaction length left data - G4double *n_lambda = procMan-> - GetNumberOfInteractionLengthsLeft(previousStepSize); - - // Create the survivor record - StorkNeutronData aSurvivor(runEnd, aTrack->GetLocalTime(), - aTrack->GetPosition(), aTrack->GetMomentum(), - n_lambda[0], n_lambda[1], n_lambda[2], n_lambda[3], 1.0); - - // Add the survivor to the list - survivors.push_back(aSurvivor); - } - else - { - // Create the survivor record - StorkNeutronData aSurvivor(runEnd, aTrack->GetLocalTime(), - aTrack->GetPosition(), aTrack->GetMomentum(), - -1.0, -1.0, -1.0, -1.0, 1.0); - - // Add the survivor to the list - survivors.push_back(aSurvivor); - } -} - - -// SaveDelayed() -// Adds a delayed neutron entry to the Delayed neutron list. -// Corrects the lifetime to be time since fission that "created it". -void StorkNeutronSD::SaveDelayed(const G4Track *aTrack) -{ - // Create a neutron data container for the delayed neutron and put it in - // the delayed list. - // lifetime is time of neutron birth is time of creating fission. - StorkNeutronData aDelayed(aTrack->GetGlobalTime(), aTrack->GetLocalTime(), - aTrack->GetPosition(), aTrack->GetMomentum(), - -1.0, -1.0, -1.0, -1.0, - -1.0*runMan->GetCurrentRun()->GetRunID()); - - delayed.push_back(aDelayed); -} - - -// EndOfEvent() -// Create the tally hit and add it to the collection -void StorkNeutronSD::EndOfEvent(G4HCofThisEvent*) -{ -#ifdef G4TIMESD - sdTimer.Start(); -#endif - - StorkTallyHit *tHit = new StorkTallyHit(); - - tHit->SetTotalLifetime(totalLifetime); - tHit->SetNLost(nLoss); - tHit->SetNProd(nProd); - tHit->SetDProd(dProd); - tHit->SetFissionSites(fSites); - tHit->SetFissionEnergies(fnEnergy); - tHit->SetSurvivors(survivors); - tHit->SetDelayed(delayed); - - tallyHitColl->insert(tHit); - -#ifdef G4TIMESD - sdTimer.Stop(); - - totalSDTime += sdTimer.GetRealElapsed() + cycleTime; - - // Output timing data for SD - G4cout << "Sensitive Detector Timing:" << G4endl - << "Total time taken for SD in this event = " << totalSDTime << "s" - << G4endl - << "Total time take to process hits = " << cycleTime << "s" << G4endl - << "Average time for each hit = " << cycleTime/G4double(cycles) - << "s" << G4endl; -#endif - -#ifdef STORK_EXPLICIT_LOSS - PrintCounterTotals(); -#endif - -} - - -// PrintCounterTotals() -// Diagnostic function to get the specific loss/production totals -void StorkNeutronSD::PrintCounterTotals() const -{ - G4cout << "Event totals:" << G4endl - << "Production: " << nProd << G4endl - << "Total Loss: " << nLoss << G4endl - << "Escapes: " << nEsc << G4endl - << "Fissions: " << nFiss << G4endl - << "Captures: " << nCap << G4endl - << "Inelastic Loss: " << nInel << G4endl; -} diff --git a/G4STORK/src/StorkParallelRunManager.cc b/G4STORK/src/StorkParallelRunManager.cc deleted file mode 100755 index 52e45205..00000000 --- a/G4STORK/src/StorkParallelRunManager.cc +++ /dev/null @@ -1,319 +0,0 @@ -/* -StorkParallelRunManager.cc - -Created by: Liam Russell -Date: 07-08-2011 -Modified: 11-03-2013 - -Source code for the StorkParallelRunManager class. - -*/ - -#ifdef G4USE_TOPC - - -// Include header file - -#include "StorkParallelRunManager.hh" - - -// Deal with static variables and functions -StorkParallelRunManager* StorkParallelRunManager::myRunManager = 0; - -// Static callback functions -TOPC_BUF StorkParallelRunManager::myGenerateEventInput() -{ - return myRunManager->GenerateEventInput(); -} - -TOPC_BUF StorkParallelRunManager::myDoEvent(void *input) -{ - return myRunManager->DoEvent(input); -} - -TOPC_ACTION StorkParallelRunManager::myCheckEventResult(void *input, - void *outputData) -{ - return myRunManager->CheckEventResult(input,outputData); -} - - -// Constructor -// Calls the constructor of the base class (StorkRunManager) to set member data -StorkParallelRunManager::StorkParallelRunManager(const StorkParseInput* infile) -:StorkRunManager(infile) -{ - i_event = numEvents = 0; - - // Set the marshaling object pointers to NULL - recMED = sendMED = NULL; - recMPD = sendMPD = NULL; - - // Set seeds pointer to null - slaveSeeds = NULL; -} - - -// Destructor -// Deletes any dynamically allocated data -StorkParallelRunManager::~StorkParallelRunManager() -{ - // Delete the marshaling objects - if(recMED) delete recMED; - if(recMPD) delete recMPD; - if(sendMED) delete sendMED; - if(sendMPD) delete sendMPD; - - // Delete the seeds - if(slaveSeeds) delete [] slaveSeeds; - - // Set the pointers to NULL - recMED = sendMED = NULL; - recMPD = sendMPD = NULL; - slaveSeeds = NULL; -} - - -// BeamOn() -// Begins the simulation. -void StorkParallelRunManager::BeamOn(G4int n_event, const char* macroFile, - G4int n_select) -{ - G4bool cond = ConfirmBeamOnCondition(); - if(cond) - { - InitializeVar(n_event); - EventMan = G4EventManager::GetEventManager(); - - // Set the number of events in the primary generator action - genAction->SetNumEvents(n_event); - - if(n_event>0) - { - while(runIDCounter < numRuns) - { - // Only initialize run now on the master, the slaves must - // initialize AFTER any geometry changes proposed by the master - if(TOPC_is_master()) RunInitialization(); - - // Process events and terminate run - DoEventLoop(n_event,macroFile,n_select); - RunTermination(); - - // Update the source distributions of the primary generator on - // the master, and tally the run results - if(TOPC_is_master()) - { - TallyRunResults(); - - if (sourceConverged) - G4cout << G4endl << "#### Souce Has Converged #####" << G4endl; - else - G4cout << G4endl << "#### Souce Has Not Converged #####" << G4endl; - - runAction->UpdateSourceDistributions(); - } - - runStart += runDuration; - runEnd += runDuration; - - // Save the source distribution if the given interval of runs - // has passed - if(TOPC_is_master() && saveInterval > 0 - && !(runIDCounter%saveInterval)){ - SaveSourceDistribution(saveFile); - if(saveFissionData) SaveFissionDistribution(fissionFile); - } - } - - // Save the final source distribution if the save interval is not - // zero and it has not been just saved - if(TOPC_is_master() && saveInterval && (runIDCounter%saveInterval || - saveInterval == 1)){ - SaveSourceDistribution(saveFile); - if(saveFissionData) SaveFissionDistribution(fissionFile); - } - } - } -} - - -// RunInitialization() -// Initialize the master using the StorkRunManager function. The slaves only -// need the basic G4RunManager initialization. -void StorkParallelRunManager::RunInitialization() -{ - if(TOPC_is_master()) - { - StorkRunManager::RunInitialization(); - } - else - { - G4RunManager::RunInitialization(); - } -} - - -// DoEventLoop() -// Override G4RunManager::DoEventLoop() -// Generate seeds for the slaves and start parallel processing. -void StorkParallelRunManager::DoEventLoop(G4int n_event, const char*, G4int) -{ - // Make the run manager availble to the callback functions - myRunManager = this; - - // Event loop - i_event = 0; - numEvents = n_event; - - // Initialize the current run - if(TOPC_is_master()) - { - genAction->InitializeRun(); - if(slaveSeeds) delete [] slaveSeeds; - slaveSeeds = new G4long[numEvents]; - - // Generate new random seeds for each event - for(G4int i=0; i= numEvents) return NOTASK; - - // Marshal the primary data (delete any data that already exists) - if(sendMPD) delete sendMPD; - StorkPrimaryData *primaryData = genAction->GetPrimaryData(i_event); - - // If no primary data received, do not send task - if(!primaryData) return NOTASK; - - // Clear any previous property changes, and create a local property change - primaryData->propChanges->clear(); - StorkMatPropChange change; - - // If interpolation has started, find the updated values for each property - if(interpStarted) - { - // the updated material properties are stored in the primarydata class - for(G4int i=0; i < theMPInterpMan->GetNumberOfInterpVectors(); i++) - { - // Set the property change (material, property, - // current (updated) world condition - change.Set(((*theMPInterpMan)[i])->second, - propValues[i]); - - primaryData->propChanges->push_back(change); - } - } - - - // Set primary seed and event number - primaryData->eventSeed = slaveSeeds[i_event]; - primaryData->eventNum = i_event; - sendMPD = new MarshaledStorkPrimaryData(primaryData); - - // Increment the event counter - i_event++; - - return TOPC_MSG(sendMPD->getBuffer(), sendMPD->getBufferSize()); -} - - -// DoEvent() -// Use the marshaled input to simulate the event on the slave -// Marshal the event data and return it to the master -TOPC_BUF StorkParallelRunManager::DoEvent(void *input) -{ - // Unmarshal the primary data buffer (delete any data that exists) - if(recMPD) delete recMPD; - recMPD = new MarshaledStorkPrimaryData(input); - - // Unmarshal the buffer and set the primaries in the generator action - StorkPrimaryData *primaryData = recMPD->unmarshal(); - genAction->SetPrimaries(primaryData); - - // Set the random seed - CLHEP::HepRandom::setTheSeed(primaryData->eventSeed); - - // Set the event number given by the master - G4int eventID = primaryData->eventNum; - - // Update world and initialize run for slaves (on the first event of the - // run!) - if(!TOPC_is_master() && - G4StateManager::GetStateManager()->GetCurrentState() == G4State_Idle) - { - // Exctracts data from the primary data class and sends it to the world - // to modify the world properties - if(G4int(primaryData->propChanges->size()) > 0) - { - UpdateWorld(*(primaryData->propChanges)); - } - - RunInitialization(); - } - - //newly added - if(primaryData) - delete primaryData; - - // Run the current event - currentEvent = GenerateEvent(eventID); - eventManager->ProcessOneEvent(currentEvent); - AnalyzeEvent(currentEvent); - - StackPreviousEvent(currentEvent); - currentEvent = 0; - - // Delete any event data stored in the sending event data pointer - if(sendMED) delete sendMED; - - // Marshal the data - sendMED = new MarshaledStorkEventData(eventAction->GetEventData()); - - return TOPC_MSG(sendMED->getBuffer(), sendMED->getBufferSize()); -} - - -// CheckEventResult() -// Updates the run with the results of the event. -// Executes on the master. -TOPC_ACTION StorkParallelRunManager::CheckEventResult(void *input, void *outputData) -{ - if(input == NULL) return NO_ACTION; - else if(outputData == NULL) - { - G4cerr << "Master Check: No output for event" << G4endl; - return NO_ACTION; - } - - // Delete any event data stored in the receiving event data pointer - if(recMED) delete recMED; - - // Recreate the marshalled event data - recMED = new MarshaledStorkEventData(outputData); - - // Tally the event data in the run action - //newly added - StorkEventData *eventData = recMED->unmarshal(); - runAction->TallyEvent(eventData); - //newly added - delete eventData; - - return NO_ACTION; -} - -#endif // G4USE_TOPC diff --git a/G4STORK/src/StorkParseInput.cc b/G4STORK/src/StorkParseInput.cc deleted file mode 100755 index 5576f7ac..00000000 --- a/G4STORK/src/StorkParseInput.cc +++ /dev/null @@ -1,1176 +0,0 @@ -/* -StorkParseInput.cc - -Created by: Liam Russell -Date: July 13, 2011 -Modified: July 09, 2012 - -Source code file for StorkParseInput class. - -*/ - - -// Include header file - -#include "StorkParseInput.hh" - -StorkParseInput::StorkParseInput(G4bool master) -: isMaster(master) -{ - // Default values - worldName = "Unknown"; - reactorMat = 0; - kCalcType = 0; - csDirName = "DEFAULT"; - fsDirName = "DEFAULT"; - - numSteps[0]=20; - numSteps[1]=20; - numSteps[2]=20; - - initEnergy = 1.*MeV; - initialSourcePos.set(0.,0.,0.); - randomSeed = 0; - saveSources = 0; - numberOfEvents =0; - numberOfPrimariesPerEvent=0; - numberOfRuns=0; - limitSE = 2.0; - convRuns = 25; - reactorPower = 0; - htc = 0.; - T_infty = 20; - Origin.set(0.,0.,0.); - - reflectBC = new std::vector; - periodicBC = new std::vector; - - // Set default flags - loadSources=false; - logData=false; - instantDelayed=false; - sourcefileDelayed=false; - precursorDelayed=false; - normalize = true; - uniformDis = false; - uniformDisWithDim = false; - interpStart = false; - saveFissionData = false; - overrideInitRandomSeed = false; - RunThermalModel = false; - saveTempData = false; - interp = false; - neutronFluxCalc = false; - initialFissionData=false; - - // Set null file names - logFile = ""; - sourceFile = ""; - initialSourceFile = ""; - - // Set default output stream (G4cout) - logStream = (std::ofstream*)&G4cout; - - // Get a pointer to the material/property manager - theMPMan = StorkMatPropManager::GetStorkMatPropManager(); -} - - -StorkParseInput::~StorkParseInput() -{ - if(logData) - { - logStream->close(); - delete logStream; - logStream = NULL; - } - - if(reflectBC) - delete reflectBC; - if(periodicBC) - delete periodicBC; - - if(theMPMan) - delete theMPMan; -} - -G4bool StorkParseInput::FinalizeInputs() -{ - //Check to make sure necessary input data has been given - - //initialize local variables - G4int pos; - - // Check whether world was set properly - if(worldName == "Unknown") - { - G4cerr << "Missing world type from input file \n"; - return false; - } - // Check whether other mandatory data was set - else if(numberOfEvents==0 || numberOfPrimariesPerEvent==0 || - numberOfRuns==0 || runDuration==0) - { - G4cerr << "Missing simulation data from input file \n"; - return false; - } - - // Set the saveSources interval to total number of runs if not set by user - if(saveSources < 0) - { - saveSources=numberOfRuns; - } -/* // Reset interpStart flag if no interpolations set - if(interpStart && theMPInterpMan.GetNumberOfInterpVectors() == 0) - { - interpStart = false; - }*/ - // Set the random seed if not set by the input file - if(isMaster && randomSeed <= 0) - { - srand(time(NULL)); - randomSeed = rand(); - } - - // Open the logging file (if necessary) - if(isMaster && logData) - { - logStream = new std::ofstream(logFile, std::ios_base::app); - } - - // Set other file names if not given using logging file name - if(logData) - { - if(saveSources && sourceFile == "") - { - pos = logFile.find_last_of("/"); - - sourceFile = logFile.substr(0,pos) + "/Src-" + - logFile.substr(pos+1,logFile.length()-1); - } - - - if(saveFissionData && fissionDataFile == "") - { - pos = logFile.find_last_of("/"); - - fissionDataFile = logFile.substr(0,pos) + "/Fission-" + - logFile.substr(pos+1,logFile.length()-1); - } - } - - - // Set the temperature of the neutron cross section data - if(!getenv("G4NEUTRONHPDATA")) - { - G4cerr << "Environment variable for Neutron HP data not set." << G4endl; - return false; - } - - // Set the units of input data - runDuration *= ns; - initEnergy *= MeV; - // Create the inital properties vector from the world property map - SetInitialPropertiesVector(); - - return ErrorChecking(); -} - -void StorkParseInput::SetRequiredInputs(G4String worldNam, G4int numRuns, G4int numEvents, G4int numPrimariesPerEvent, G4double runDur) -{ - SetWorld(worldNam); - numberOfRuns=numRuns; - numberOfEvents=numEvents; - numberOfPrimariesPerEvent=numPrimariesPerEvent; - runDuration=runDur; -} - -void StorkParseInput::SetWorld(G4String worldNam) -{ - if(worldNam=="Sphere") - { - reactorMat=92235; - theWorldProps[MatPropPair(all,dimension)] = 8.7*cm; - theWorldProps[MatPropPair(all,temperature)] = 293.6*kelvin; - } - else if(worldNam=="C6Lattice") - { - reactorMat=6; - for(int i=0; i<6; i++) - { - periodicBC->push_back(i); - } - theWorldProps[MatPropPair(all,dimension)] = 28.575*cm; - } - else if(worldNam=="Cube") - { - reactorMat=8; - for(int i=0; i<6; i++) - { - periodicBC->push_back(i); - } - uniformDis = true; - - theWorldProps[MatPropPair(all,dimension)] = 50.*cm; - theWorldProps[MatPropPair(fuel,concentration)] = 0.7204*perCent; - theWorldProps[MatPropPair(moderator,concentration)] = 90.0*perCent; - } - else if(worldNam=="SLOWPOKE") - { - } - else if(userWorlds.find(worldNam) != userWorlds.end()) - { - StorkMatPropChangeVector defaults = userWorlds[worldNam]; - - for(G4int i=0; i < G4int(defaults.size()); i++) - { - theWorldProps[defaults[i].GetMatPropPair()] = defaults[i].change; - } - } - else - { - worldName = "Unknown"; - } -} - -void StorkParseInput::SetReactorMaterial(G4int reactorMaterial) -{ - if ((worldName=="Sphere")||(worldName=="Cube")) - reactorMat=reactorMaterial; - else - G4cout<<"Cannot select material for this world"; - } - -//Set source distribution and save options -void StorkParseInput::SetRandomSeed(G4long randSeed) -{ - randomSeed=randSeed; - overrideInitRandomSeed=true; -} - -void StorkParseInput::SetResultsFile(G4String logFil) -{ - logFile=logFil; - logData=true; -} - -void StorkParseInput::SetInitialSourceFile(G4String SourceFile) -{ - initialSourceFile=SourceFile; - loadSources=true; -} - -void StorkParseInput::SetInitialDelayedFile(G4String DelayedFile) -{ - initialfissionDataFile=DelayedFile; - precursorDelayed=true; -} - -void StorkParseInput::SetFissionDataFile(G4String fissionFile) -{ - fissionDataFile=fissionFile; - saveFissionData=true; -} - - -void StorkParseInput::SetTemperatureDataFile(G4String temperatureFile) -{ - tempFileName = temperatureFile; - saveTempData = true; -} - -void StorkParseInput::SetNSInterpolationManager(G4String mat, G4String prop, G4String interpDataFile) -{ - // Parse the strings - MatPropPair mpPair (theMPMan->ParseMatEnum(mat), theMPMan->ParsePropEnum(prop)); - G4String mpString = PrintMatPropPair(mpPair); - - // Store the data file name - std::pair dataFile ("# " + mpString, interpDataFile); - theDataProfiles.push_back(dataFile); - - // Create a new interpolation vector from the data file - theMPInterpMan.CreateInterpVector(mpString.strip(':'), - dataFile.second, mpPair, - theMPMan->GetUnits(mpPair.second)); -} - -void StorkParseInput::SetIntialWorldProperties(G4String mat, G4String prop, G4double newValue) -{ - // Parse the strings - MatPropPair mpPair (theMPMan->ParseMatEnum(mat), theMPMan->ParsePropEnum(prop)); - - // Add the property to the world property map - theWorldProps[mpPair] = newValue*theMPMan->GetUnits(mpPair.second); -} - -// ReadInputFile() -// Reads the input file and sets the material temperature based on the -// loaction of the input data. -G4bool StorkParseInput::ReadInputFile(G4String filename) -{ - std::ifstream infile(filename.c_str(),std::ifstream::in); - - // Data file identifier and name - std::pair dataFile; - MatPropPair mpPair; - G4String mat, prop, mpString; - G4double newValue; - G4int pos; - - if(!infile.good()) - return false; - - char line[256]; - G4String keyWord; - - //Goes through input file and extracts parameters need to initialize the simualtion - while(infile.good()) - { - - // Get keyword - infile >> std::ws >> keyWord; - - // Skip empty or comment lines - if((keyWord[0]=='#')||(keyWord=="")) - { - infile.getline(line,256); - } - - // World selection - else if(keyWord=="WORLD") - { - infile >> std::ws >> keyWord; - worldName = keyWord; - - if(keyWord=="Sphere") - { - reactorMat=92235; - theWorldProps[MatPropPair(all,dimension)] = 8.7*cm; - theWorldProps[MatPropPair(all,temperature)] = 293.6*kelvin; - } - else if(keyWord=="C6Lattice") - { - reactorMat=6; - - for(int i=0; i<6; i++) - { - periodicBC->push_back(i); - } - - theWorldProps[MatPropPair(all,dimension)] = 28.575*cm; - } - else if(keyWord=="Cube") - { - reactorMat=8; - for(int i=0; i<6; i++) - { - periodicBC->push_back(i); - } - uniformDis = true; - - theWorldProps[MatPropPair(all,dimension)] = 50.*cm; - theWorldProps[MatPropPair(fuel,concentration)] = 0.7204*perCent; - theWorldProps[MatPropPair(moderator,concentration)] = 90.0*perCent; - } - else if(keyWord=="ZED2") - { - - } - else if(keyWord=="SLOWPOKE") - { - } - else if(keyWord=="SCWR") - { - - } - else if(keyWord=="SCWRDoppler") - { - - } - else if(keyWord=="SCWRJason") - { - - } - else if(keyWord=="Test") - { - - } - else if(keyWord=="Q_ZED2") - { - - } - else if(userWorlds.find(keyWord) != userWorlds.end()) - { - StorkMatPropChangeVector defaults = userWorlds[keyWord]; - - for(G4int i=0; i < G4int(defaults.size()); i++) - { - theWorldProps[defaults[i].GetMatPropPair()] = defaults[i].change; - } - } - else - { - worldName = "Unknown"; - } - } - else if(keyWord=="MAT"&&(worldName == "Sphere" || worldName == "Cube")) - { - infile >> reactorMat; - } - - // Keff calculation method - else if(keyWord=="K_CALC") - { - G4String kCalc; - infile >> kCalc; - - if(kCalc == "K_Dynamic") - { - kCalcType = 0; - } - else if(kCalc == "K_Time_Absorption") - { - kCalcType = 1; - } - else if(kCalc == "K_Generational") - { - kCalcType = 2; - } - - } - - // CS Data File Location - else if(keyWord=="CS_DATA_DIR") - { - infile >> csDirName; - } - // Final State Data Location - else if(keyWord=="FS_DATA_DIR") - { - infile >> fsDirName; - } - - // Shannon Entropy - else if(keyWord=="SE_MESH") - { - infile >> numSteps[0] >> numSteps[1] >> numSteps[2]; - } - else if(keyWord == "SE_NUM_CONV_RUNS") - { - infile >> convRuns; - } - else if(keyWord == "SE_CONV_LIMIT") - { - infile >> limitSE; - } - - - //Initial Particles - else if(keyWord=="NEUTRON_ENERGY") - { - infile >> initEnergy; - } - else if(keyWord=="INITIAL_SOURCE_FILE") - { - infile >> initialSourceFile; - loadSources=true; - } - else if(keyWord=="INITIAL_FISSION_DATA_FILE") - { - infile >> initialfissionDataFile; - initialFissionData=true; - } - - - //Runs - else if(keyWord=="NUM_RUNS") - { - infile >> numberOfRuns; - } - else if(keyWord=="NUM_EVENTS") - { - infile >> numberOfEvents; - } - else if(keyWord=="NUM_PRIMARY_PER_EVENT") - { - infile >> numberOfPrimariesPerEvent; - } - else if(keyWord=="RUN_DURATION") - { - infile >> runDuration; - } - - - //Options - else if(keyWord=="SEED") - { - infile >> randomSeed; - overrideInitRandomSeed = true; - } - else if(keyWord=="PERIODIC_BC") - { - G4int nPBCSides; - infile >> nPBCSides; - G4String side; - for(int i=0; i> side; - periodicBC->push_back(ConvertSide(side)); - } - } - else if(keyWord=="REFLECT_BC") - { - G4int nRBCSides; - infile >> nRBCSides; - G4String side; - for(int i=0; i> side; - reflectBC->push_back(ConvertSide(side)); - } - } - else if(keyWord=="RENORMALIZE") - { - infile >> normalize; - } - else if(keyWord=="DELAYED_OPTION") - { - infile >> theDelayedOption; - if(theDelayedOption == 1) - instantDelayed = true; - else if (theDelayedOption == 2) - sourcefileDelayed = true; - else if (theDelayedOption == 3) - precursorDelayed = true; - } - else if(keyWord=="UNIFORM_DISTRIBUTION") - { - infile >> uniformDis >> uniDisShape; - } - else if(keyWord=="UNIFORM_DIST_WITH_DIM") - { - G4double tempDim[6]; - infile >> uniformDis >> uniDisShape >> uniformDisWithDim >> tempDim[0] >> tempDim[1] >> tempDim[2] >> tempDim[3] >> tempDim[4] >> tempDim[5]; - uniDisDim = tempDim; - } - else if(keyWord=="INITIAL_SOURCE_POS") - { - infile >> initialSourcePos[0] >> initialSourcePos[1] >> initialSourcePos[2]; - } - else if(keyWord=="INTERP_START_COND") - { - infile >> interpStart; - } - else if(keyWord=="NEUTRON_FLUX_CALC") - { - infile >> fluxCalcShape >> energyRange[0] >> energyRange[1] >> fluxCalcRegion[0] - >> fluxCalcRegion[1] >> fluxCalcRegion[2]>> fluxCalcRegion[3]; - neutronFluxCalc = true; - - } - else if(keyWord=="SET_ORIGIN") - { - infile >> Origin[0] >> Origin[1] >> Origin[2]; - } - - // Logging - else if(keyWord=="OUTPUT_LOG") - { - infile >> logFile; - logData=true; - } - else if(keyWord=="OUTPUT_SOURCE") - { - saveSources=-1; - - while(infile.peek() == ' ' || infile.peek() == '\t') - infile.get(); - - if(infile.peek() == '\n') - infile.getline(line,256); - else - infile >> sourceFile; - } - else if(keyWord=="OUTPUT_SRC_FREQ") - { - infile >> saveSources; - } - else if(keyWord == "OUTPUT_FISSION") - { - infile >> fissionDataFile; - saveFissionData = true; - } - //Thermal model variables - else if(keyWord=="RUN_THERMAL_MODEL") - { - infile >> RunThermalModel; - } - else if(keyWord=="REACTOR_POWER") - { - infile >> reactorPower; - } - else if(keyWord == "OUTPUT_PROPERTIES") - { - infile >> tempFileName; - saveTempData = true; - } - else if(keyWord == "SET_HEAT_TRANSFER_COEFFICIENT") - { - infile >> htc; - } - else if(keyWord == "SET_AMBIENT_TEMPERATURE") - { - infile >> T_infty; - } - else if(keyWord == "SET_BASELINE_FISSION_RATE") - { - infile >> baselineFissionRate; - } - else if(keyWord == "SET_FISSION_TO_ENERGY_COEFFICIENT") - { - infile >> FissionToEnergy; - } - - // World data (initial and interpolation) - else if(keyWord == "INTERPOLATION_DATA") - { - // Read the material and property - infile >> mat >> prop; - - // Parse the strings - mpPair.first = theMPMan->ParseMatEnum(mat); - mpPair.second = theMPMan->ParsePropEnum(prop); - mpString = PrintMatPropPair(mpPair); - - // Store the data file name - dataFile.first = "# " + mpString; - infile >> dataFile.second; - theDataProfiles.push_back(dataFile); - - // Create a new interpolation vector from the data file - theMPInterpMan.CreateInterpVector(mpString.strip(':'), - dataFile.second, mpPair, - theMPMan->GetUnits(mpPair.second)); - - // Sets the interpolation data falg to high - interp = true; - } - else if(keyWord=="SET_WORLD_PROP") - { - // Read the material and property - infile >> mat >> prop >> newValue; - - // Parse the strings - mpPair.first = theMPMan->ParseMatEnum(mat); - mpPair.second = theMPMan->ParsePropEnum(prop); - - // Add the property to the world property map - theWorldProps[mpPair] = newValue*theMPMan->GetUnits(mpPair.second); - } - - // Error if unknown keyword - else - { - G4cerr << "*** WARNING: Unrecognized or inapplicable keyword: " - << keyWord << G4endl; - } - - // Reset keyword - keyWord = ""; - } - - // Close the input file - infile.close(); - - - //Check to make sure necessary input data has been given - - // Check whether world was set properly - if(worldName == "Unknown") - { - G4cerr << "Missing world type from input file \n"; - return false; - } - // Check whether other mandatory data was set - else if(numberOfEvents==0 || numberOfPrimariesPerEvent==0 || - numberOfRuns==0 || runDuration==0) - { - G4cerr << "Missing simulation data from input file \n"; - return false; - } - - // Set the saveSources interval to total number of runs if not set by user - if(saveSources < 0) - { - saveSources=numberOfRuns; - } - /*// Reset interpStart flag if no interpolations set - if(interpStart && theMPInterpMan.GetNumberOfInterpVectors() == 0) - { - interpStart = false; - }*/ - // Set the random seed if not set by the input file - if(isMaster && randomSeed <= 0) - { - srand(time(NULL)); - randomSeed = rand(); - } - - // Open the logging file (if necessary) - G4String logDir; - if(isMaster && logData) - { - pos = logFile.find_last_of("/"); - logDir = logFile.substr(0,pos); - - if(!(DirectoryExists((logDir).c_str()))) - { - system( ("mkdir -p -m=666 "+logDir).c_str()); - if(DirectoryExists((logDir).c_str())) - { - G4cout << "created directory " << logDir << "\n" << G4endl; - } - else - { - G4cout << "\nError: could not create directory " << logDir << "\n" << G4endl; - return false; - } - } - logStream = new std::ofstream(logFile, std::ios_base::app); - } - - // Set other file names if not given using logging file name - if(logData) - { - if(saveSources && sourceFile == "") - { - pos = logDir.find_last_of("/"); - sourceFile = logDir.substr(0,pos) + "/SourceFiles/"; - if(!(DirectoryExists((sourceFile).c_str()))) - { - system( ("mkdir -p -m=666 "+sourceFile).c_str()); - if(DirectoryExists((sourceFile).c_str())) - { - G4cout << "created directory " << sourceFile << "\n" << G4endl; - } - else - { - G4cout << "\nError: could not create directory " << sourceFile << "\n" << G4endl; - return false; - } - } - pos = logFile.find_last_of("/"); - sourceFile += "Src-" + logFile.substr(pos+1,logFile.length()-1); - } - - - if(saveFissionData && fissionDataFile == "") - { - pos = logDir.find_last_of("/"); - fissionDataFile = logDir.substr(0,pos) + "/FissionFiles/"; - if(!(DirectoryExists((fissionDataFile).c_str()))) - { - system( ("mkdir -p -m=666 "+fissionDataFile).c_str()); - if(DirectoryExists((fissionDataFile).c_str())) - { - G4cout << "created directory " << fissionDataFile << "\n" << G4endl; - } - else - { - G4cout << "\nError: could not create directory " << fissionDataFile << "\n" << G4endl; - return false; - } - } - pos = logFile.find_last_of("/"); - fissionDataFile += "Fission-" + logFile.substr(pos+1,logFile.length()-1); - } - } - - - // Set the temperature of the neutron cross section data - if(!getenv("G4NEUTRONHPDATA")) - { - G4cerr << "Environment variable for Neutron HP data not set." << G4endl; - return false; - } - - // Set the units of input data - runDuration *= ns; - initEnergy *= MeV; - - // Create the inital properties vector from the world property map - SetInitialPropertiesVector(); - - return ErrorChecking(); -} - -G4int StorkParseInput::ConvertSide(G4String side) -{ - G4int sideNum=0; - G4bool check1=false, check2=false; - for(G4int i=0; ifill(' '); - output->setf(std::ios_base::left); - - // Outputs Geant4 and NStable version info and current time - *output << "# ---------------------------------------------------------" - << G4endl << "#" << G4endl - << "# Geant 4 Simulation of Neutron Stability" << G4endl - << "#" << G4endl - << "#" << g4Version << G4endl - << "# Neutron Stability rev." << BZR_REVNO - << " (Bazaar build date " << BZR_BUILD_DATE << ")" << G4endl - << "#" << G4endl - << "# Current time: \t" << currentTime - << "# " << G4endl; - - // Outputs the initial parameters needed to create the world and start the - // run manager - *output << "## World Choice: " << G4endl - << std::setw(37) << "# World: " << worldName << G4endl - << std::setw(37) << "# Reactor Material: " << reactorMat << G4endl - << std::setw(37) << "# Shannon entropy mesh: " << "(" << numSteps[0] << ", " - << numSteps[1] << ", " << numSteps[2] << ")" << G4endl - << "#" << G4endl; - - // Ouput the run options - *output << "## Run Options:" << G4endl - << std::setw(37) << "# Number of runs: " << numberOfRuns << G4endl - << std::setw(37) << "# Number of primaries per Event: " - << numberOfPrimariesPerEvent << G4endl - << std::setw(37) << "# Number of events: " << numberOfEvents << G4endl - << std::setw(37) << "# Run duration (ns): " << runDuration << G4endl - << std::setw(37) << "# Initial Neutron Energy (MeV): "; - if(loadSources) - *output << "N/A"; - else - *output << initEnergy; - - if(overrideInitRandomSeed) - *output << G4endl << std::setw(37) << "# Random Seed: " << randomSeed; - - *output << G4endl << "#" << G4endl; - - // Outputs world properties - *output << "## World Properties:"; - for(G4int i=0; i < G4int(initialWorldProps.size()); i++) - { - *output << G4endl << "# "<< std::setw(35) - << PrintMatPropPair(initialWorldProps[i].GetMatPropPair()) - << initialWorldProps[i].change / - theMPMan->GetUnits((PropEnum)initialWorldProps[i].propN); - } - - // Outputs the nuclear data and simulation options - *output << G4endl << "#" << G4endl - << "## Nuclear Data Options:" << G4endl - << std::setw(37) << "# Data Library: " << datapath << G4endl - << "#" << G4endl; - - // Outputs warning if renormalization is turned off - if(!normalize) - *output << std::setw(37) << "# *** Renormalize after run:" << "NO ***" - << G4endl << "#" << G4endl; - - // Outputs the input and output files to be used - if(logData || saveSources || loadSources || saveFissionData) - { - *output << "## Log Files:" << G4endl; - - if(logData) - { - *output << std::setw(37) << "# Logging File: " - << logFile << G4endl; - } - - - if(saveSources!=0) - { - *output << std::setw(37) << "# Output source file: " - << sourceFile << G4endl - << std::setw(37) << "# Save source distribution interval: " - << saveSources << G4endl; - } - - if(saveFissionData) - { - *output << std::setw(37) << "# Output fission data file: " - << fissionDataFile << G4endl; - } - - if(loadSources) - { - *output << std::setw(37) << "# Initial source file: " - << initialSourceFile << G4endl; - } - - *output << "#" << G4endl; - } - - - // Outputs the file names of the interpolation files to be used - if(theDataProfiles.size() > 0) - { - *output << "## Interpolation Data Files:" << G4endl; - - for(G4int i=0; i < G4int(theDataProfiles.size()); i++) - { - *output << std::setw(37) << theDataProfiles[i].first - << theDataProfiles[i].second << G4endl; - } - - *output << "#" << G4endl; - } -} - - -// GetWorldDimensions() -// Gets the size of the smallest box surrounding the world -G4ThreeVector StorkParseInput::GetWorldDimensions() const -{ - G4double maxDim = theWorldProps.find(MatPropPair(all,dimension))->second; - - if(reactorMat == 6) - { - maxDim += 2.0; - } - else - { - maxDim = 2.0*(maxDim + 1.0); - } - - return G4ThreeVector(maxDim,maxDim,maxDim); -} - - -// SetInitialProperty() -// Set up the initial properties for the given world -void StorkParseInput::SetInitialPropertiesVector() -{ - // Build property change vector based on world properties map - InitialPropertyMap::iterator itr = theWorldProps.begin(); - - for(; itr != theWorldProps.end(); itr++) - { - initialWorldProps.push_back(StorkMatPropChange(itr->first,itr->second)); - } -} - - -// PrintMatPropPair() -// Get a string for printing a material property pair with the appropriate units -G4String StorkParseInput::PrintMatPropPair(MatPropPair mpPair) const -{ - std::stringstream buff; - - // Print material type - buff << theMPMan->GetEnumKeyword(mpPair.first) << "/"; - - // Print property (if dimension and all, print "Radius" or "Pitch") - if(mpPair.second == dimension && mpPair.first == all) - { - if(worldName == "Sphere") - buff << "Radius"; - else - buff << "Pitch"; - } - else - { - buff << theMPMan->GetEnumKeyword(mpPair.second); - } - - // Print units - buff << " (" << theMPMan->GetUnitsName(mpPair.second) << "):"; - - - return buff.str(); -} - - -// ErrorChecking() -// Check to see if there are errors in the data passed from the input file -G4bool StorkParseInput::ErrorChecking() -{ - G4bool test = true; - - if(randomSeed<0) - { - test=false; - G4cerr << "*** ERROR: Invalid random seed: " << randomSeed << G4endl; - } - - if(reactorMat<0 || reactorMat>104000) - { - test=false; - G4cerr << "*** ERROR: Invalid reactor material: " << reactorMat - << G4endl; - } - - if(numberOfEvents<=0||numberOfPrimariesPerEvent<=0||numberOfRuns<=0) - { - test=false; - G4cerr << "*** ERROR: Invalid number of events/primaries/runs: " - << numberOfEvents << "/" - << numberOfPrimariesPerEvent << "/" - << numberOfRuns << G4endl; - } - - if(numSteps[0]<=0 || numSteps[1]<=0 || numSteps[2]<=0) - { - test=false; - G4cerr << "*** ERROR: Invalid Shannon entropy mesh: " - << numSteps[0] << "/" << numSteps[1] << "/" << numSteps[2] - << G4endl; - } - - if(convRuns < 5 || limitSE <= 0) - { - test = false; - G4cerr << "*** ERROR: Invalid Shannon entropy convergence limit/runs: " - << limitSE << "/" << convRuns << G4endl; - } - - if(initEnergy <= 0) - { - test=false; - G4cerr << "*** ERROR: Invalid initial neutron energy: " << initEnergy - << G4endl; - } - - if(saveSources < 0) - { - test=false; - G4cerr << "*** ERROR: Invalid source distribution save interval" - << G4endl; - } - - // Check world properties - for(G4int i=0; i < G4int(initialWorldProps.size()); i++) - { - if(initialWorldProps[i].change <= 0) - { - test = false; - G4cerr << "*** ERROR: Invalid " - << PrintMatPropPair(initialWorldProps[i].GetMatPropPair()) - << " " << initialWorldProps[i].change << G4endl; - } - } - - // Check file names - if(logData && logFile == "") - { - test=false; - G4cerr << "*** ERROR: Empty log file name." << G4endl; - } - - if(saveSources && sourceFile == "") - { - test=false; - G4cerr << "*** ERROR: Empty output source file name." << G4endl; - } - - if(saveFissionData && fissionDataFile == "") - { - test=false; - G4cerr << "*** ERROR: Empty fission data file name." << G4endl; - } - - if(loadSources && initialSourceFile == "") - { - test=false; - G4cerr << "*** ERROR: Empty initial source file name." << G4endl; - } - - if(loadSources) - { - std::ifstream initFile(initialSourceFile); - - if(!initFile.is_open()) - { - test=false; - G4cerr << "*** ERROR: Unable to open initial source file." - << G4endl; - } - else - { - initFile.close(); - } - } - - //Check proper delayed option was provided. - if(theDelayedOption>3 || theDelayedOption<0) - { - test = false; - G4cerr << "*** ERROR: Incorrect option for delayed neutrons, choose options 0 - 4." << G4endl; - } - if(precursorDelayed && !fissionDataFile) - { - test= false; - G4cerr <<"*** ERROR: missing fission data file!" << G4endl; - } - //Check require inputs for thermal model are provided. - if(RunThermalModel && (!htc || !T_infty || !baselineFissionRate || !FissionToEnergy || !reactorPower)) - { - test = false; - G4cerr << "*** ERROR: Missing input for thermal model." << G4endl; - } - - return test; -} diff --git a/G4STORK/src/StorkPeriodicBCStepLimiter.cc b/G4STORK/src/StorkPeriodicBCStepLimiter.cc deleted file mode 100755 index 8a3a1044..00000000 --- a/G4STORK/src/StorkPeriodicBCStepLimiter.cc +++ /dev/null @@ -1,157 +0,0 @@ -/* -StorkPeriodicBCStepLimiter.cc - -Created by: Wesley Ford -Date: 22-06-2012 -Modified: 17-02-2012 - -Source code file for StorkPeriodicBCStepLimiter class. - -*/ - - -// Include header file -#include "StorkPeriodicBCStepLimiter.hh" - - -// Constructor() -// Calls the G4StepLimiter constructor with the proper name -StorkPeriodicBCStepLimiter::StorkPeriodicBCStepLimiter(const G4String &aName, - G4String worldPhysName) -: G4StepLimiter(aName) -{ - worldName=worldPhysName; - nsProcMan = NULL; - pnInfo = NULL; -} - - -// PostStepGetPhysicalInteractionLength() -// Returns a step size of DBL_MIN (very small) if the neutron has entered the -// world (outside) volume. Otherwise returns DBL_MAX (very big). -G4double StorkPeriodicBCStepLimiter::PostStepGetPhysicalInteractionLength( - const G4Track &aTrack, - G4double, - G4ForceCondition *condition) -{ - // Set condition to "Not Forced" - *condition = NotForced; - G4double dp = 0.; - - G4String physVolName = aTrack.GetVolume()->GetName(); - G4VSolid *solidVol = aTrack.GetVolume()->GetLogicalVolume()->GetSolid(); - - // Check that the neutron is in the world volume - if(physVolName!=worldName) - { - return DBL_MAX; - } - // Check that the neutron is ENTERING the world volume (rather than leaving) - else - { - G4ThreeVector p = aTrack.GetPosition(); - G4ThreeVector v = aTrack.GetMomentumDirection(); - G4ThreeVector n = solidVol->SurfaceNormal(p); - - // Compute the dot product of direction and surface normal - dp = v.dot(n); - - if(dp>0.) - { - return DBL_MIN; - } - else - { - return DBL_MAX; - } - } -} - - -// IsApplicable() -// Check that the particle is a neutron, otherwise not applicable. -G4bool -StorkPeriodicBCStepLimiter::IsApplicable(const G4ParticleDefinition &particle) -{ - G4String particleName = particle.GetParticleName(); - if(particleName=="neutron") - { - return true; - } - else - { - return false; - } - -} - - -// PostStepDoIt() -// Result of StorkPeriodicBCStepLimiter acting on a neutron. An exact copy of -// the neutron is produced at the opposite boundary (other side of world volume) -// and the original is killed. -// ASSUMES A SYMMETRIC VOLUME -G4VParticleChange* -StorkPeriodicBCStepLimiter::PostStepDoIt(const G4Track &aTrack, - const G4Step &aStep) -{ - aParticleChange.Initialize(aTrack); - G4VSolid *solidVol = aTrack.GetVolume()->GetLogicalVolume()->GetSolid(); - - G4StepPoint *preStepPoint = aStep.GetPreStepPoint(); - - G4ThreeVector curPos = preStepPoint->GetPosition (); - G4ThreeVector curMom = preStepPoint->GetMomentum (); - G4ThreeVector newPos = curPos; - G4ThreeVector n = solidVol->SurfaceNormal(curPos); - - for(G4int i=0;i<3;i++) - { - if(n[i]==0) - { - newPos[i]*=1; - } - else - { - newPos[i]*=-1; - } - } - - - // Create a new dynamic particle from the parent dynamic particle - G4DynamicParticle *newDynamicParticle = new G4DynamicParticle(); - *newDynamicParticle = *(aTrack.GetDynamicParticle()); - - // Create the primary neutron info for the primary particle - pnInfo = new StorkPrimaryNeutronInfo(); - - // Set the lifetime - pnInfo->SetLifeTime(aTrack.GetLocalTime()); - - //Get the NS process manager and use it to get the n_lambda data - nsProcMan = StorkProcessManager::GetStorkProcessManagerPtr(); - pnInfo->SetEta(nsProcMan->GetNumberOfInteractionLengthsLeft(aStep.GetStepLength())); - - // Create a new track info object and set the primary neutron info - trackInfo = new StorkTrackInfo(); - trackInfo->SetStorkPrimaryNeutronInfo(pnInfo); - - - // Find the time of the hit (time the secondary track starts at) - G4double timeStart = aTrack.GetGlobalTime(); - - // Create a track for the secondary - G4Track *newTrack = new G4Track(newDynamicParticle, timeStart, newPos); - - // Add track info to track - newTrack->SetUserInformation(trackInfo); - - // Add the secondary to the particle change - aParticleChange.AddSecondary(newTrack); - - // Kill the parent particle - aParticleChange.ProposeTrackStatus(fStopAndKill); - - return &aParticleChange; -} - diff --git a/G4STORK/src/StorkPeriodicBCTransform.cc b/G4STORK/src/StorkPeriodicBCTransform.cc deleted file mode 100755 index 40ac5b2e..00000000 --- a/G4STORK/src/StorkPeriodicBCTransform.cc +++ /dev/null @@ -1,93 +0,0 @@ -#include "StorkPeriodicBCTransform.hh" - -StorkPeriodicBCTransform::StorkPeriodicBCTransform() -{ - //ctor -} - -StorkPeriodicBCTransform::~StorkPeriodicBCTransform() -{ - //dtor -} - -StorkPeriodicBCTransform::StorkPeriodicBCTransform(G4ThreeVector n1, G4ThreeVector n2) -{ - InitializeTransform(n1, n2); -} - -void StorkPeriodicBCTransform::InitializeTransform(G4ThreeVector n1, G4ThreeVector n2) -{ - - if(n1==n2) - { - G4cout << "\n Error: Periodic Boundary was linked to itself" << G4endl; - return; - } - - // make n2 point inside the world volume; - n2=-1*n2; - - G4int index=-1; - for(G4int i=0; i<3; i++) - { - if(n2[i]!=0) - { - index=i; - } - } - if(index==-1) - { - G4cout << "\n Error: Periodic Boundary was given a zero vector for n2" << G4endl; - return; - } - - for(G4int i=0; i<3; i++) - { - for(G4int j=0; j<3; j++) - { - if(i==j) - { - TransMom[i][j]=1; - } - else - { - TransMom[i][j]=0; - } - } - } - for(G4int i=0; i<3; i++) - { - for(G4int j=0; j<3; j++) - { - if(n1[j]!=0) - { - TransMom[i][j]=n2[i]/n1[j]; - if(i==j) - { - TransMom[index][index]=TransMom[i][j]; - } - else - { - TransMom[j][i]=-n2[i]/n1[j]; - } - } - } - } - - for(G4int i=0; i<3; i++) - { - for(G4int j=0; j<3; j++) - { - if((n2[i]!=0)&&(n1[j]!=0)) - { - TransPos[i][j]=-1*TransMom[i][j]; - } - else - { - TransPos[i][j]=TransMom[i][j]; - } - } - } - -} - diff --git a/G4STORK/src/StorkPrimaryGeneratorAction.cc b/G4STORK/src/StorkPrimaryGeneratorAction.cc deleted file mode 100755 index 1674677f..00000000 --- a/G4STORK/src/StorkPrimaryGeneratorAction.cc +++ /dev/null @@ -1,570 +0,0 @@ -/* -StorkPrimaryGeneratorAction.cc - -Created by: Liam Russell -Date: 22-06-2011 -Modified: 11-03-2013 - -Source code for StorkPrimaryGeneratorAction class. - -*/ - - -// Include header file - -#include "StorkPrimaryGeneratorAction.hh" - - - -// Constructor -StorkPrimaryGeneratorAction::StorkPrimaryGeneratorAction( - const StorkParseInput* infile, - G4bool master) -{ - // Set default and user input values - runEnd = 0.; - numPrimaries = infile->GetNumberOfPrimariesPerEvent(); - realNumPrimaries = numPrimaries; - initEnergy = infile->GetInitialEnergy(); - uniformDis = infile->GetUniformDistribution(); - shape = infile->GetUniformDistributionShape(); - origin = infile->GetInitialSourcePos(); - initialSource = false; - primaryData = NULL; - normalize = infile->GetRenormalizeAfterRun(); - instantDelayed = infile->GetInstantDelayed(); - precursorDelayed = infile->GetPrecursorDelayed(); - runDuration = infile->GetRunDuration(); - theNav = G4TransportationManager::GetTransportationManager()-> - GetNavigatorForTracking(); - sourcefileDelayed = infile->GetSourceFileDelayed(); - - // Set initial source files (on master only) - if(master) - { - if(infile->LoadInitialSources()) - sourceFile = infile->GetInitialSourceFile(); - if(precursorDelayed){ - delayedSourceFile = infile->GetInitialDelayedFile(); - delayedNeutronGenerator = new StorkDelayedNeutron(delayedSourceFile,runDuration,numPrimaries); - } - } - - // Find neutron definition - G4ParticleTable* pTable = G4ParticleTable::GetParticleTable(); - neutron = pTable->FindParticle("neutron"); - - // Set the particle type for the generator - nGen.SetParticleType(neutron); - - // Set the pointer to the run manager - runMan = dynamic_cast(G4RunManager::GetRunManager()); - - -#ifdef G4TIMEPG - totalGenTime = 0.0; -#endif -} - - -// Destructor -StorkPrimaryGeneratorAction::~StorkPrimaryGeneratorAction() -{ - if(primaryData) delete primaryData; - if(delayedNeutronGenerator) delete delayedNeutronGenerator; -} - - -// GeneratePrimaries() -// The survivors for the current run need to be set and the number of survivors -// is assumed to be renormalized before this function is called. -void StorkPrimaryGeneratorAction::GeneratePrimaries(G4Event *anEvent) -{ -#ifdef G4TIMEPG - genTimer.Start(); -#endif - - nGen.GeneratePrimaryVertices(anEvent,&currPrimaries); - -#ifdef G4TIMEPG - genTimer.Stop(); - totalGenTime += genTimer.GetRealElapsed(); - - G4cout << "Primary Generator Timing: " << G4endl - << "Total primary generator time = " << totalGenTime << "s" - << G4endl; - - totalGenTime = 0.0; -#endif -} - - -// SetPrimaries() -// Set the primaries for the current event (i.e. set on slaves by master) -void StorkPrimaryGeneratorAction::SetPrimaries(StorkPrimaryData *primaryContainer) -{ - // Assign the primaries to the current primaries vector - currPrimaries = *(primaryContainer->primaries); -} - - -// GetPrimaryData() -// Get primary data for the next event -StorkPrimaryData* StorkPrimaryGeneratorAction::GetPrimaryData(G4int /*eventNum*/) -{ - if(primaryIt == survivors.end()) return NULL; - - // Create a new primary data container and delete the old one if it exists - if(primaryData) delete primaryData; - primaryData = new StorkPrimaryData(); - - // Create a new primaries vector - primaryData->primaries->reserve(realNumPrimaries); - - // Insert the appropriate survivors into the primary data container - for(G4int i=0; iprimaries->push_back(*primaryIt); - primaryIt++; - } - - return primaryData; -} - - - -// InitializeRun() -// Add delayed neutrons born in this run to survivors and renormalize survivors -// if necessary. -void StorkPrimaryGeneratorAction::InitializeRun() -{ -#ifdef G4TIMEPG - genTimer.Start(); -#endif - - // Set up initial sources if needed - if(!initialSource) - { - if(sourceFile.empty()) - InitialSource(); - else - LoadSource(sourceFile); - } - - // Get the end time for the run - runEnd = runMan->GetRunEnd(); - - // Check that some survivors exist - if(survivors.size() == 0) - { - G4cerr << "***ERROR: No survivors (neutrons) for this run." << G4endl; - return; - } - - - // Add delayed neutrons born in the current run to survivors - AddCurrentDelayed(); - - // Check to see whether the size of the survivor distribution is correct - G4int missing = numPrimaries*numEvents - G4int(survivors.size()); - - if(normalize && missing != 0) - { - // Renormalize survivors - RenormalizeSurvivors(missing); - - // Check that renormalized survivors have correct number of elements - if(G4int(survivors.size()) != numPrimaries*numEvents) - { - G4cerr << "***Error: Suvivors not properly normalized." << G4endl; - } - - } - - // Calculate the actual number of primaries per event - realNumPrimaries = G4int(std::ceil(G4double(survivors.size()) - /G4double(numEvents))); - -#ifdef G4TIMEPG - genTimer.Stop(); - totalGenTime += genTimer.GetRealElapsed(); -#endif - - primaryIt = survivors.begin(); - - return; -} - - -// RenormalizeSurvivors() -// Delete/duplicate survivors until the total number of survivors equals -// the number of primaries for each run. The process is randomized using the -// modified Fisher-Yates shuffle algorithm -void StorkPrimaryGeneratorAction::RenormalizeSurvivors(G4int numMissing) -{ - // Do nothing if no renormalization is needed. - if(numMissing == 0) return; - - - // Local variables - G4int numSurvivors = G4int(survivors.size()); - - // Copy the unrenormalized survivors to a new vector - NeutronSources originalSurvivors = survivors; - - // Clear original vector and set to proper size - survivors.clear(); - survivors.reserve(numPrimaries*numEvents); - - - // If numMissing is positive duplicate survivors - if(numMissing > 0) - { - // Add original survivors to number of missing - numMissing += numSurvivors; - - // Duplicate all survivors until the number of missing is less than the - // original number of survivors - while(numMissing > numSurvivors) - { - survivors.insert(survivors.end(),originalSurvivors.begin(), - originalSurvivors.end()); - numMissing -= numSurvivors; - } - - // Check that there are still missing survivors - if(numMissing == 0) return; - } - // Otherwise set the number of survivors to add as the total number of - // survivors per run - else - { - numMissing = numPrimaries*numEvents; - } - - - // Extract numMissing survivors from the originals either from the - // shuffled or unshuffled depending on which involves the least shuffling - - // If number of missing is less than half of survivors, add shuffled - if(G4double(numMissing) < 0.5*G4double(numSurvivors)) - { - ShuffleSurvivors(numMissing,&originalSurvivors); - - // Add shuffled to survivors - survivors.insert(survivors.end(),originalSurvivors.begin(), - originalSurvivors.begin()+numMissing); - } - // Otherwise add unshuffled - else - { - ShuffleSurvivors(numSurvivors-numMissing,&originalSurvivors); - - // Add unshuffled to survivors - survivors.insert(survivors.end(),originalSurvivors.end()-numMissing, - originalSurvivors.end()); - } - - - return; - -} - - -// ShuffleSurvivors() -// Shuffle the first 'numShuffle' elements of a neutron source vector. -void StorkPrimaryGeneratorAction::ShuffleSurvivors(G4int numShuffle, - NeutronSources *origSurvivors) -{ - // Local variables - StorkNeutronData tempData; - G4int totalSurvivors = G4int(origSurvivors->size()); - G4int randIndex = totalSurvivors; - - // Make sure numMissing is positive - numShuffle = std::abs(numShuffle); - - // Shuffle numMissing random survivors to the start of the vector - for(G4int i = 0; i < numShuffle ; i++) - { - randIndex = G4int(G4UniformRand()*(totalSurvivors - i)) + i; - tempData = survivors[randIndex]; - survivors[randIndex] = survivors[i]; - survivors[i] = tempData; - } - - return; -} - - -// AddCurrentDelayed() -// Add delayed neutrons in the current run to the survivors. Renormalize the -// delayed neutrons relative to the k_run values of intervening runs. -void StorkPrimaryGeneratorAction::AddCurrentDelayed() -{ - if(sourcefileDelayed){ - NeutronSources delayedToBeAdded = delayedNeutronGenerator->GetDelayedNeutrons(runEnd); - dNeutrons.insert(dNeutrons.end(),delayedToBeAdded.begin(),delayedToBeAdded.end()); - - } - - // Add delayed to survivors - survivors.insert(survivors.end(),dNeutrons.begin(), - dNeutrons.end()); - //Clear the delayed neutrons. - dNeutrons.clear(); - - return; -} - - -// UpdateSourceDistributions() -// Rewrite the survivors distribution with the survivors from the current run -// and add the delayed neutrons to the current list -void StorkPrimaryGeneratorAction::UpdateSourceDistributions( - const NeutronSources *nSource, - const NeutronSources *dnSource) -{ -#ifdef G4TIMEPG - genTimer.Start(); -#endif - - // Assign the new distribution to survivors - survivors.assign(nSource->begin(),nSource->end()); - - // Only add the delayed neutrons after the source has converged - if(runMan->GetSourceConvergence() && !sourcefileDelayed) - { - // Add the delayed neutrons to the end of the delayed neutron list - dNeutrons.insert(dNeutrons.end(),dnSource->begin(),dnSource->end()); - - } - -#ifdef G4TIMEPG - genTimer.Stop(); - totalGenTime += genTimer.GetRealElapsed(); -#endif -} - - -// GetNumPrimaries() -// Returns current size of survivors. If run has started and the survivors -// vector is empty, use the expected number of survivors -G4int StorkPrimaryGeneratorAction::GetNumPrimaries() -{ - if(survivors.empty() && !runMan->GetCurrentRun()->GetRunID()) - return numEvents * numPrimaries; - else - return G4int(survivors.size()); -} - - -// GetNumDNPrimaries() -// This is called AFTER the run occurs -G4int StorkPrimaryGeneratorAction::GetNumDNPrimaries() -{ - return G4int(dNeutrons.size()); -} - - -// LoadSource() -// Loads an initial source distribution from file (csv text file) -// Assume that the input file is properly formatted and the values are correct -// FILE FORMAT: each on a new line(s) -// a) header lines (start with #) -// b) current time of records -// c) number of survivors -// d) survivors ... -// e) number of delayed -// f) delayed ... -void StorkPrimaryGeneratorAction::LoadSource(G4String fname) -{ - if(initialSource){ - return; - } - // Variables - std::ifstream infile; - char buffer[256]; - StorkNeutronData input; - G4double recordTime; - G4int numRecords; - G4String line; - std::stringstream conv; - G4int lineNum = 0; - - infile.open(fname.c_str()); - - // Ignore header lines - while(infile.peek() == '#' || lineNum < 5) - { - infile.getline(buffer,256); - lineNum++; - } - - - infile >> recordTime >> numRecords; - - // Read in each line of file - // Format is: global time, local time, x, y, z, px, py, pz - - // Read in the survivors - for(G4int i=0; i> input.first >> input.second - >> input.third[0] >> input.third[1] >> input.third[2] - >> input.fourth[0] >> input.fourth[1] >> input.fourth[2] - >> input.fifth >> input.sixth >> input.seventh >> input.eigth - >> input.ninth; - - // Correct for the current time of the records - input.first -= recordTime; - - // Write survivor - survivors.push_back(input); - } - - - // Reserve memory for the delayed vector - infile >> numRecords; - - if(sourcefileDelayed){ - // Read in delayed - for(G4int i=0; i> input.first >> input.second - >> input.third[0] >> input.third[1] >> input.third[2] - >> input.fourth[0] >> input.fourth[1] >> input.fourth[2] - >> input.fifth >> input.sixth >> input.seventh >> input.eigth - >> input.ninth; - // Correct for the current time of the records - input.first -= recordTime; - - dNeutrons.push_back(input); - } - } - infile.close(); - - initialSource = true; -} - - -// InitialSource() -// Default initial source if no source file is provided. -// Initial neutron energy is 14 MeV -void StorkPrimaryGeneratorAction::InitialSource() -{ - if(initialSource) return; - - - G4double mass = neutron->GetPDGMass(); - G4double meanEng = initEnergy; - G4double stdEng = 0.25*meanEng; - G4double phi; - G4double theta; - G4double rEng; - G4double rMom; - - // Build neutron data common values (position,time,lifetime,eta(-1.0)) - StorkNeutronData input(0.,0.,origin,G4ThreeVector(0.,0.,0.)); - - for(G4int i=0; iGetWorld(); - - // Determining the shape of the world volume - // By default we want to generate random - // points everywhere inside the world voulme - if(shape == "Cell") - shape = worldPointerCD->GetWorldLogicalVolume() - ->GetDaughter(0)->GetLogicalVolume() - ->GetSolid()->GetEntityType(); - - G4ThreeVector extent = worldPointerCD->GetWorldDimensions(); - - G4double limit[3]; - - if(shape=="G4Orb") - { - // Select a random position - limit[0] = G4UniformRand()*extent[0]; - limit[1] = G4UniformRand()*2.0*CLHEP::pi; - limit[2] = G4UniformRand()*CLHEP::pi; - - // Set position - input->third.setRThetaPhi(limit[0],limit[2],limit[1]); - } - - else if(shape=="G4Tubs") - { - // Select a random position - limit[0] = G4UniformRand()*extent[1]; - limit[1] = G4UniformRand()*2.0*CLHEP::pi; - limit[2] = G4UniformRand()*extent[2]*2-extent[2]; - - // Set position - input->third.setRhoPhiZ(limit[0],limit[1],limit[2]); - } - - else - { - limit[0] = G4UniformRand()*extent[0]*2-extent[0]; - limit[1] = G4UniformRand()*extent[1]*2-extent[1]; - limit[2] = G4UniformRand()*extent[2]*2-extent[2]; - - // Set position - input->third.set(limit[0],limit[2],limit[1]); - } - input->third = input->third + origin*CLHEP::cm; -} - -//Add precursors based on current fissions. -void StorkPrimaryGeneratorAction::AddPrecursors(MSHSiteVector fissionSites, DblVector fissionEnergy){ - - //Reset the fission sites/energies to the most recent run and add precursors. - delayedNeutronGenerator->SetFissionSource(fissionSites,fissionEnergy); - delayedNeutronGenerator->AddPrecursors(); - - return; -} - - -std::vector StorkPrimaryGeneratorAction::GetPrecursors() -{ - return delayedNeutronGenerator->GetPrecursors(); -} - diff --git a/G4STORK/src/StorkPrimaryNeutronGenerator.cc b/G4STORK/src/StorkPrimaryNeutronGenerator.cc deleted file mode 100755 index 679a7a1f..00000000 --- a/G4STORK/src/StorkPrimaryNeutronGenerator.cc +++ /dev/null @@ -1,62 +0,0 @@ -/* -StorkPrimaryNeutronGenerator.cc - -Created by: Liam Russell -Date: 22-06-2011 -Modified: 11-03-2013 - -Source code for StorkPrimaryNeutronGenerator class. - -*/ - - -// Include header file -#include "StorkPrimaryNeutronGenerator.hh" - - -// GeneratePrimaryVertices() -// Create a primary neutron in the event for each of the NeutronSources entries. -void StorkPrimaryNeutronGenerator::GeneratePrimaryVertices(G4Event *evt, - NeutronSources *nSource) -{ - G4PrimaryVertex *vertex; - G4PrimaryParticle *particle; - StorkNeutronData *source; - StorkPrimaryNeutronInfo *pnInfo; - - G4double mass = neutron->GetPDGMass(); - G4ThreeVector pol = G4ThreeVector(0.,0.,0.); - G4int numPrimaries = G4int(nSource->size()); - - // Create a primary neutron for each entry in nSource - for(G4int i=0; ithird, source->first); - - particle = new G4PrimaryParticle(neutron, source->fourth[0], - source->fourth[1], source->fourth[2]); - particle->SetMass(mass); - particle->SetCharge(0.0); - particle->SetPolarization(pol[0],pol[1],pol[2]); - - // Create the primary particle user information - pnInfo = new StorkPrimaryNeutronInfo(); - // Set the lifetime - pnInfo->SetLifeTime(source->second); - // Set the eta values - G4double eta[4] = {source->fifth,source->sixth,source->seventh, - source->eigth}; - pnInfo->SetEta(eta); - // Set the weight and primary neutron info - pnInfo->SetWeight(source->ninth); - particle->SetUserInformation(pnInfo); - - vertex->SetPrimary(particle); - - // Add the primary to the event - evt->AddPrimaryVertex(vertex); - } -} diff --git a/G4STORK/src/StorkProcessManager.cc b/G4STORK/src/StorkProcessManager.cc deleted file mode 100755 index 4ea862b4..00000000 --- a/G4STORK/src/StorkProcessManager.cc +++ /dev/null @@ -1,175 +0,0 @@ -/* -StorkProcessManager.cc - -Created by: Liam Russell -Date: 24-05-2012 -Modified: 11-03-2013 - -Source code file for StorkProcessManager class. - -*/ - -#include "StorkProcessManager.hh" - - -// Initialize static pointer -StorkProcessManager* StorkProcessManager::theManager = NULL; - - -// GetStorkProcessManagerPtr() -// Static function to get pointer to StorkProcessManager singleton. This function -// will create the singleton if it does not already exist. -StorkProcessManager* StorkProcessManager::GetStorkProcessManagerPtr() -{ - if(!theManager) - { - theManager = new StorkProcessManager(); - } - - return theManager; -} - - -// GetStorkProcessManagerPtrIfExists() -// Static function to get pointer to StorkProcessManager singleton. This function -// will NOT create the singleton if it does not exist. -StorkProcessManager* StorkProcessManager::GetStorkProcessManagerPtrIfExists() -{ - return theManager; -} - - -// Constructor -// Initialize pointers and then set them to the appropriate processes. -StorkProcessManager::StorkProcessManager() -{ - // Initialize the pointers - theElasticProcess = NULL; - theInelasticProcess = NULL; - theFissionProcess = NULL; - theCaptureProcess = NULL; - - // Initialize data arrays - numProcesses = 4; - n_lambda = new G4double[numProcesses]; - procOrder = new G4String[numProcesses](); - - // Get pointers to the hadronic processes - G4ProcessManager *procMan = G4Neutron::Neutron()->GetProcessManager(); - G4ProcessVector *procVector = procMan->GetPostStepProcessVector(); - G4String procName; - - for(G4int i=0; ientries(); i++) - { - procName = (*procVector)[i]->GetProcessName(); - - if(procName == "StorkHadronElastic") - { - theElasticProcess = dynamic_cast((*procVector)[i]); - procOrder[0] = procName; - theElasticProcess->SetProcessIndex(0); - } - else if(procName == "StorkNeutronInelastic") - { - theInelasticProcess = dynamic_cast((*procVector)[i]); - procOrder[1] = procName; - theInelasticProcess->SetProcessIndex(1); - } - else if(procName == "StorkHadronFission") - { - theFissionProcess = dynamic_cast((*procVector)[i]); - procOrder[2] = procName; - theFissionProcess->SetProcessIndex(2); - } - else if(procName == "StorkHadronCapture") - { - theCaptureProcess = dynamic_cast((*procVector)[i]); - procOrder[3] = procName; - theCaptureProcess->SetProcessIndex(3); - } - } -} - - -// Destructor -StorkProcessManager::~StorkProcessManager() -{ - // Clear dynamic memory - delete [] procOrder; - delete [] n_lambda; -} - - -// GetNumberOfInteractionLengthsLeft() -// Returns the number of interaction lengths left for each process. Returns -// -1.0 if the process does not exist. -G4double* StorkProcessManager::GetNumberOfInteractionLengthsLeft(const G4double previousStepSize) const -{ - // Initialize the n_lambda array - for(G4int i=0; iGetNumberOfInteractionLengthLeft(previousStepSize); - - if(theInelasticProcess) - n_lambda[1] = theInelasticProcess->GetNumberOfInteractionLengthLeft(previousStepSize); - - if(theFissionProcess) - n_lambda[2] = theFissionProcess->GetNumberOfInteractionLengthLeft(previousStepSize); - - if(theCaptureProcess) - n_lambda[3] = theCaptureProcess->GetNumberOfInteractionLengthLeft(previousStepSize); - - - return n_lambda; -} - - -// GetProcessIndex() -// Find the index for the process by name -G4int StorkProcessManager::GetProcessIndex(const G4String procName) const -{ - // Search the process name array for the index (i) - for(G4int i=0; iGetRunDuration(); - kCalcType = fIn->GetKCalcType(); - RunThermalModel = fIn->GetRunThermalModel(); - worldSize = G4ThreeVector(0.,0.,0.); - survivorsBuffer = NULL; - delayedBuffer = NULL; - rndmInitializer = fIn->GetInitialSourceFile(); - maxShannonEntropy = 1.0; - theMPInterpMan = fIn->GetNSInterpolationManager(); - nameLen = new G4int[theMPInterpMan->GetNumberOfInterpVectors()]; - variableProps = NULL; - saveFissionData = false; - numDelayProd = 0; - numFDCollectionRuns = 0; - numRuns = fIn->GetNumberOfRuns(); - reactorPower = fIn->GetReactorPower(); - updatePrecursors = fIn->GetPrecursorDelayed(); - neutronFluxCalc = fIn->GetNeutronFluxCalc(); - renormalize = fIn->GetRenormalizeAfterRun(); - saveInterval = fIn->SaveSourcesInterval(); - primariesPerRun = fIn->GetNumberOfEvents()*fIn->GetNumberOfPrimariesPerEvent(); - saveRundata = false; - - fn_index = save_index = 0; - Origin = fIn->GetOrigin(); - - //Set up the neutron flux calcution - if(neutronFluxCalc){ - fluxCalcShape = fIn->GetFluxCalcShape(); - - fluxCalcRegion[0] = (fIn->GetFluxRegion())[0]; - fluxCalcRegion[1] = (fIn->GetFluxRegion())[1]; - fluxCalcRegion[2] = (fIn->GetFluxRegion())[2]; - fluxCalcRegion[3] = (fIn->GetFluxRegion())[3]; - - EnergyRange[0]=(fIn->GetEnergyRange())[0]; - EnergyRange[1]=(fIn->GetEnergyRange())[1]; - } - - - // Set the shannon entropy mesh - for(G4int i=0; i<3; i++) - { - numSpatialSteps[i] = (fIn->GetMeshSteps())[i]; - maxShannonEntropy *= numSpatialSteps[i]; - } - - // Calculate maximum Shannon entropy - maxShannonEntropy = -1.0 * std::log(1.0/maxShannonEntropy) / std::log(2); - - // Create the fSites and sSites arrays - fSites = new G4int **[numSpatialSteps[0]]; - sSites = new G4int **[numSpatialSteps[0]]; - - for(G4int i=0; iGetLogOutputStream(); -} - - -// Destructor -StorkRunAction::~StorkRunAction() -{ - // Delete all elements of the fSites and sSites arrays - for(G4int i=0; iGetRunID() == 0 && - !infile->OverrideInitRandomSeed()) - { - // Restore engine from file - CLHEP::HepRandom::restoreEngineStatus(rndmInitializer); - } - - // Get the number of events and initialize the run - numEvents = aRun->GetNumberOfEventToBeProcessed(); - - // Clear the container vectors - survivors.clear(); - delayed.clear(); - - // Delete and recreate the survivors buffer - if(survivorsBuffer) - delete [] survivorsBuffer; - survivorsBuffer = new NeutronSources[numEvents]; - - // Delete and recreate the delayed buffer - if(delayedBuffer) - delete [] delayedBuffer; - delayedBuffer = new NeutronSources[numEvents]; - - // Reset the entries of the fsites array - for(G4int i=0; iGetRunID(); - - - if(runID == 0) - { - // Set up the appropriate unit for output - tUnit = 1.*ns; - G4String unit = "(ns)"; - - if(runDuration >= 1e9) - { - tUnit = 1.*s; - unit = "(s) "; - } - else if(runDuration >= 1e6) - { - tUnit = 1.*ms; - unit = "(ms)"; - } - else if(runDuration >= 1e3) - { - tUnit = 1.*microsecond; - unit = "(us)"; - } - - - // Write header lines - *output << "# Number of Primaries per Run = " - << genAction->GetNumPrimaries() << G4endl - << "# Number of Events per Run = " - << numEvents << G4endl - << "# " << G4endl << "# " << G4endl; - - - *output << "# Run # " - << " Start " << unit << " " - << "Lifetime " << unit - << " Production " - << " Loss " - << " krun " - << " keff " - << "FS Shannon H " - << " S Shannon H " - << "Duration (s) "; - if(neutronFluxCalc){ - *output << "Flux (n cm^-2 s^-1) "; - underline = 150; - - } - else{ - underline = 129; - } - G4String interpName; - - // Output the material properties that are being interpolated - for(G4int i=0; iGetNumberOfInterpVectors(); i++) - { - interpName = (*theMPInterpMan)[i]->first; - - *output << interpName << " "; - - // Set length of each name - nameLen[i] = interpName.size() + 1; - underline += nameLen[i]; - } - - *output << G4endl; - *output << "#"; - - output->width(underline); - output->fill('-'); - *output << "-" << G4endl; - - } - - //Set the saving index for fission site/energies. - if(saveInterval && !(runID%saveInterval)){ - save_index = fnSites.size(); - saveRundata = true; - } - else - saveRundata = false; - -#ifdef G4TIMERA - runCalcTimer.Stop(); - totalRunCalcTime = runCalcTimer.GetRealElapsed(); -#endif -} - - -// UpdateSourceDistributions() -// Update the survivor and delayed neutron distributions of the -// StorkPrimaryGeneratorAction class. -void StorkRunAction::UpdateSourceDistributions() -{ - // Pass suvivors and delayed neutrons to primary generator - genAction->UpdateSourceDistributions(&survivors,&delayed); -} - - -// EndOfRunAction() -// Calculate the results of the run (k_eff, k_run, Shannon entropy, etc). -// Output results to the screen and to the StorkRunManager. -void StorkRunAction::EndOfRunAction(const G4Run *aRun) -{ -#ifdef G4TIMERA - runCalcTimer.Start(); -#endif - - // Collate the survivors and delayed neutrons - CollateNeutronSources(); - - //G4int numPrimaries = genAction->GetNumPrimaries(); - - // Find the Shannon Entropy - shannonEntropy[0] = CalcShannonEntropy(fSites,totalFS); - shannonEntropy[1] = CalcShannonEntropy(sSites,G4int(survivors.size())); - - //Find neutron flux of specified material. - if(neutronFluxCalc) - neutronFlux = CalcNeutronFlux(); - - //Find krun - krun = G4double(survivors.size()/G4double(primariesPerRun)); - - // Find the average neutron lifetime - avgLifetime /= G4double(numNLost); - - // Correct the production total for the delayed primary neutrons - // the delay neutrons are already added on to the total production in StorkNeutronSD - //numNProduced += genAction->GetNumDNPrimaries(); - - // Find keff - - // Dynamic Criticality Method - if(kCalcType == 0) - { - keff = G4double(numNProduced) / G4double(numNLost); - } - // Time Absorption Method - else if(kCalcType == 1) - { - G4double alpha = (std::log(krun))/runDuration; - keff = std::exp(alpha*avgLifetime); - } - // Generational Method - else if(kCalcType == 2) - { - keff = G4double(numNProduced) / G4double(numNLost); - } - else - { - G4cout << "Error: Invalid Keff calculation method selected!" << G4endl; - keff=0.; - } - - //Reset the current fission sites. - ResetCurrentFissionData(); - - //Add precursors if flag is set. - if(updatePrecursors) - { - genAction->AddPrecursors(GetCurrentFissionSites(),GetCurrentFissionEnergy()); - } - - // Find the run time - runTimer.Stop(); - - - // Output data to the output stream (csv format) - output->fill(' '); - *output << std::setw(6) << std::right << aRun->GetRunID()+1 << " " - << std::right << std::resetiosflags(std::ios_base::floatfield) - << std::setw(16) << (aRun->GetRunID()) * runDuration / tUnit << " " - << std::setw(12) << std::setprecision(4) - << avgLifetime / tUnit << " " - << std::setw(12) << numNProduced << " " - << std::setw(12) << numNLost << " " - << std::setw(12) << std::setprecision(4) - << std::fixed << krun << " " - << std::setw(12) << std::fixed << keff << " " - << std::setw(12) << std::setprecision(4) << std::fixed - << shannonEntropy[0] << " " - << std::setw(12) << std::setprecision(4) << std::fixed - << shannonEntropy[1] << " " - << std::resetiosflags(std::ios_base::floatfield) - << std::setw(12) << runTimer.GetRealElapsed(); - if(neutronFluxCalc){ - *output << std::setw(12) << std::setprecision(4) - << neutronFlux; - } - - // Output the current value of the interpolated material properties - for(G4int i=0; iGetNumberOfInterpVectors(); i++) - { - *output << std::setw(nameLen[i]) << variableProps[i]; - } - - *output << G4endl; - - // Assign run results - runResults[0] = avgLifetime / tUnit; - runResults[1] = G4double(numNProduced); - runResults[2] = G4double(numNLost); - runResults[3] = krun; - runResults[4] = keff; - runResults[5] = shannonEntropy[0]; - runResults[6] = shannonEntropy[1]; - runResults[7] = runTimer.GetRealElapsed(); - - // Increment fission data collection counter - if(saveFissionData) - numFDCollectionRuns++; - -#ifdef G4TIMERA - runCalcTimer.Stop(); - totalRunCalcTime += runCalcTimer.GetRealElapsed(); - - - G4cout << "Run Timing:" << G4endl - << "Total run time: " << runTimer << G4endl - << "Total run calculation time = " << totalRunCalcTime << "s" - << G4endl; -#endif -} - - -// CalcShannonEntropy() -// Calculate the Shannon entropy of the given sites. -G4double StorkRunAction::CalcShannonEntropy(G4int ***sites, G4int total) -{ - G4double Pijk; - G4double entropy = 0.0; - - // Find the Shannon entropy - for(G4int i=0; ieventNum] = *(eventData->survivors); - delayedBuffer[eventData->eventNum] = *(eventData->delayed); - - // Add the lifetime to the total (average later) - avgLifetime += eventData->totalLifetime; - - // Add the neutron production and loss - numNProduced += eventData->numNProd; - numNLost += eventData->numNLost; - - // Add the fission sites to the 3D array - numSites = eventData->fSites->size(); - totalFS += numSites; - - // Discretize fission sites - for(G4int i=0; ifSites))[i]).data); - fSites[fInd.first][fInd.second][fInd.third]++; - } - - // Discretize survivor positions - for(G4int i=0; isurvivors->size()); i++) - { - fInd = SpatialIndex(((*(eventData->survivors))[i]).third); - sSites[fInd.first][fInd.second][fInd.third]++; - } - - // Save fission data if necessary - if(saveFissionData || updatePrecursors) - { - if(saveFissionData) numDelayProd += eventData->numDProd; - - fnEnergies.insert(fnEnergies.end(),eventData->fnEnergy->begin(), - eventData->fnEnergy->end()); - fnSites.insert(fnSites.end(),eventData->fSites->begin(), - eventData->fSites->end()); - } - -#ifdef G4TIMERA - // Add the tally event time to the calulation total - runCalcTimer.Stop(); - totalRunCalcTime += runCalcTimer.GetRealElapsed(); -#endif -} - - -// CollateNeutronSources() -// Combine the neutron source buffers into a single list for each buffer -void StorkRunAction::CollateNeutronSources() -{ - // Add the sources in order to their respective containers - for(G4int i=0; i < numEvents; i++) - { - // Add survivors and delayed for ith event - survivors.insert(survivors.end(),(survivorsBuffer[i]).begin(), - (survivorsBuffer[i]).end()); - delayed.insert(delayed.end(),(delayedBuffer[i]).begin(), - (delayedBuffer[i]).end()); - } - -} - - -// SpatialIndex() -// Find the spatial index of a fission site based on the given world -// size and number of steps in the mesh used to divide the world -Index3D StorkRunAction::SpatialIndex(G4ThreeVector position) const -{ - Index3D site; - - site.first = G4int(numSpatialSteps[0] * (position[0]/worldSize[0] + 0.5)); - site.second = G4int(numSpatialSteps[1] * (position[1]/worldSize[1] + 0.5)); - site.third = G4int(numSpatialSteps[2] * (position[2]/worldSize[2] + 0.5)); - - // Check to make sure index is in range - if(site.first < 0 || site.first >= numSpatialSteps[0] || - site.second < 0 || site.second >= numSpatialSteps[1] || - site.third < 0 || site.third >= numSpatialSteps[2]) - { - G4cerr << "*** ERROR: Improper indexing in Shannon entropy mesh." - << G4endl << "World box dimensions = " << worldSize << G4endl - << "\t Current position = " << position << G4endl - << "\t Calculated index = (" << site.first << "," - << site.second << "," << site.third << ") ***" << G4endl; - } - - return site; -} - - -// SetWorldProperty() -// Sets the requested material property in the worldPropMap to the desired value -void StorkRunAction::UpdateWorldProperties(G4double *values) -{ - variableProps = values; -} - - -// SaveSources() -// Saves the survivors and delayed to a text file with the following format -// FILE FORMAT: each on a new line(s) -// a) header lines (start with #) -// b) current time of records -// c) number of survivors -// d) survivors (global time, lifetime, position (x,y,z), momentum (px,py,pz)) -// e) number of delayed -// f) delayed (global time, lifetime, position (x,y,z), momentum (px,py,pz)) -void StorkRunAction::SaveSources(G4String fname, G4int curRunID, G4double runEnd) -{ -#ifdef G4TIMERA - // Set up timer for writing sources to file - G4Timer sourceTimer; - sourceTimer.Start(); -#endif - - runID = curRunID; - // Print the current state of the random engine - CLHEP::HepRandom::saveEngineStatus(fname); - - // User variables - G4int numEntries; - StorkNeutronData *record; - - // Open stream to output file (append) - G4String FDir = fname.substr(0, fname.find_last_of('/')); - if(!(DirectoryExists(FDir.data()))) - { - system( ("mkdir -p -m=666 "+FDir).c_str()); - if(DirectoryExists(FDir.data())) - { - G4cout << "created directory " << FDir << "\n" << G4endl; - } - else - { - G4cout << "\nError: could not create directory " << FDir << "\n" << G4endl; - return; - } - } - std::ofstream outFile(fname.data(),std::ios_base::app); - - if(!outFile.is_open()) - { - *output << G4endl << "Error: Could not write source to file." - << "Improper file name " << fname << G4endl; - return; - } - - // Write header lines - outFile << "# Source file for following input:" << G4endl << "#" << G4endl; - - infile->PrintInput(&outFile); - - outFile << "#" << G4endl; - - // Write time of records and number of runs - outFile << "# Source distribution after " << runID << " runs" << G4endl - << "#" << G4endl << runEnd << G4endl; - - // Write number of survivors then each survivors - numEntries = survivors.size(); - outFile << numEntries << G4endl; - - outFile.fill(' '); - - for(G4int i=0; ifirst << " " - << std::right << std::setprecision(16) << std::scientific - << std::setw(25) << record->second << " " - << std::setw(25) << record->third[0] << " " - << std::setw(25) << record->third[1] << " " - << std::setw(25) << record->third[2] << " " - << std::setw(25) << record->fourth[0] << " " - << std::setw(25) << record->fourth[1] << " " - << std::setw(25) << record->fourth[2] << " " - << std::setw(25) << record->fifth << " " - << std::setw(25) << record->sixth << " " - << std::setw(25) << record->seventh << " " - << std::setw(25) << record->eigth << " " - << std::setw(25) << record->ninth << G4endl; - } - - - // Write the number of delayed and then each delayed neutron record - numEntries = delayed.size(); - outFile << numEntries << G4endl; - - for(G4int i=0; ifirst << " " - << std::right << std::setprecision(16) - << std::setw(25) << record->second << " " - << std::setw(25) << record->third[0] << " " - << std::setw(25) << record->third[1] << " " - << std::setw(25) << record->third[2] << " " - << std::setw(25) << record->fourth[0] << " " - << std::setw(25) << record->fourth[1] << " " - << std::setw(25) << record->fourth[2] << " " - << std::setw(25) << record->fifth << " " - << std::setw(25) << record->sixth << " " - << std::setw(25) << record->seventh << " " - << std::setw(25) << record->eigth << " " - << std::setw(25) << record->ninth << G4endl; - } - - outFile.close(); - -#ifdef G4TIMERA - sourceTimer.Stop(); - G4cout << G4endl << "Source writing time: " << sourceTimer << G4endl; -#endif -} - - -// WriteFissionData() -// Write fission sites and energies to file -G4bool StorkRunAction::WriteFissionData(G4String fname, - G4int start) -{ - // Declare and open file stream - G4String FDir = fname.substr(0, fname.find_last_of('/')); - if(!(DirectoryExists(FDir.data()))) - { - system( ("mkdir -p -m=666 "+FDir).c_str()); - if(DirectoryExists(FDir.data())) - { - G4cout << "created directory " << FDir << "\n" << G4endl; - } - else - { - G4cout << "\nError: could not create directory " << FDir << "\n" << G4endl; - return false; - } - } - std::ofstream outFile(fname.c_str(),std::ifstream::out); - - // Check that stream is ready for use - if(!outFile.good()) - { - G4cerr << G4endl << "ERROR: Could not write source to file. " - << "Improper file name: " << fname << G4endl; - - return false; - } - - // Check if fission data vectors are the same size - if(G4int(fnEnergies.size()) != G4int(fnSites.size())) - { - G4cerr << G4endl << "ERROR: Different numbers of fission sites and " - << "fission energies: " << G4int(fnSites.size()) << "/" - << G4int(fnEnergies.size()) << G4endl; - - return false; - } - - - // Write header lines - outFile << "# Fission data file for following input:" << G4endl - << "#" << G4endl; - - infile->PrintInput(&outFile); - - // Write time of records and number of runs - outFile << "#" << G4endl << "# Fission data collection started at run " - << start << G4endl << "#" << G4endl; - - //Get the collection interval. - G4int collectionInt = numRuns-start; - if(saveInterval) - collectionInt = saveInterval; - - if(updatePrecursors) - { - //Get the precursor numbers - std::vector precursors = genAction->GetPrecursors(); - - //Write the precursor data - outFile << "# Precursor Groups: " << G4endl; - - for(G4int i = 0; i<6; i++){ - outFile << std::setw(12) << precursors[i] << G4endl; - } - } - // Write number of fission data points, the run duration, the current run and primaries simulated per run. - G4int numEntries = G4int(fnEnergies.size()); - outFile << numEntries << G4endl << runDuration << G4endl << collectionInt << G4endl - << primariesPerRun << G4endl; - - outFile.fill(' '); - for(G4int i = save_index; iGetPDGMass(); - - //In units of c (speed of light) - G4double lowVelocity_cutoff = sqrt(2*EnergyRange[0]/Mass); - G4double highVelocity_cutoff = sqrt(2*EnergyRange[1]/Mass); - - //Initialize variables for neutron flux calculation. - G4double volume; - G4double speed; - G4double total = 0.0; - G4int tally; - G4int CalcType; - G4double x, y, z; - G4bool inRegion; - G4double innerR=-1, outerR=-1, minX=-1, maxX=-1, minY=-1, maxY=-1, minZ=-1, maxZ=-1; - - //Get region of interest and volume. This is relative to current set origin (default = 0,0,0). - if(fluxCalcShape == "Cylinder"){ - innerR = fluxCalcRegion[0]; - outerR = fluxCalcRegion[1]; - minZ = fluxCalcRegion[2]; - maxZ = fluxCalcRegion[3]; - - volume = CLHEP::pi*(maxZ-minZ)*( pow(outerR,2) - pow(innerR,2) ); - CalcType = 0; - - - } - else if(fluxCalcShape == "Cube"){ - minX = Origin[0]-fluxCalcRegion[0]/2; - maxX = Origin[0]+fluxCalcRegion[0]/2; - minY = Origin[1]-fluxCalcRegion[1]/2; - maxY = Origin[1]+fluxCalcRegion[1]/2; - minZ = Origin[2]-fluxCalcRegion[2]/2; - maxZ = Origin[2]+fluxCalcRegion[2]/2; - - volume = fluxCalcRegion[0]*fluxCalcRegion[1]*fluxCalcRegion[2]; - CalcType = 1; - } - else if(fluxCalcShape == "Sphere"){ - innerR = fluxCalcRegion[0]; - outerR = fluxCalcRegion[1]; - - volume = (4/3)*CLHEP::pi*(pow(outerR,3) - pow(innerR,3) ); - CalcType = 2; - } - else{ - G4cerr << "*** ERROR: Shape not properly specified for flux calculation." << G4endl; - return 0; - } - - - - - - //Calculate the simulated power in W. - G4double simulatedPower = numSites*198/(6.24150934*pow(10,12)*runDuration*pow(10,-9)); - - //Run through all survivors, check if they are in the material of interest and calculate fluence. - for(G4int i=0; iinnerR && radiusminZ && zminX && xminY && yminZ && zinnerR && radius lowVelocity_cutoff && speed < highVelocity_cutoff && inRegion){ - total += speed; - tally++; - } - } - - G4double simulatedFlux = 299.792458*total/(volume); - G4double currentPower = reactorPower; - - //Calculate actual flux, convert to cm^(-2)s^(-1) from mm^(-2)ns^(-1) - G4double actualFlux = pow(10,11)*simulatedFlux*currentPower/simulatedPower; - - return actualFlux; - -} - -void StorkRunAction::ResetCurrentFissionData(){ - - CurrentfnSites.clear(); - CurrentfnEnergy.clear(); - - CurrentfnSites.insert(CurrentfnSites.end(),fnSites.begin()+fn_index,fnSites.end()); - CurrentfnEnergy.insert(CurrentfnEnergy.end(),fnEnergies.begin()+fn_index,fnEnergies.end()); - - fn_index = fnSites.size(); - - return; -} diff --git a/G4STORK/src/StorkRunManager.cc b/G4STORK/src/StorkRunManager.cc deleted file mode 100755 index 0a2b6f2a..00000000 --- a/G4STORK/src/StorkRunManager.cc +++ /dev/null @@ -1,660 +0,0 @@ -/* -StorkRunManager.cc - -Created by: Liam Russell -Date: 22-06-2011 -Modified: 09-07-2012 - -Source code for StorkRunManager class. - -*/ - - -// Include header file -#include "StorkRunManager.hh" - - -// Static pointer to the event manager -G4EventManager* StorkRunManager::EventMan=0; - - -// Constructor -StorkRunManager::StorkRunManager() -:G4RunManager() -{ - runStart = 0.0; - frac = 25.*perCent; - - // Initialize flags and values - interpStarted = false; - sourceConverged = false; - convergeStop=0; - seSelect = NULL; - nConv = 0; - heatTransfer = NULL; - -} - -// Constructor with input file -StorkRunManager::StorkRunManager(const StorkParseInput* infile) -:G4RunManager() -{ - // maybe able to run default Constructor instead - runStart = 0.0; - frac = 25.*perCent; - - // Initialize flags and values - interpStarted = false; - sourceConverged = false; - convergeStop=0; - seSelect = NULL; - nConv = 0; - - // Set default values - runDuration = infile->GetRunDuration(); - runEnd = runStart + runDuration; - numRuns = infile->GetNumberOfRuns(); - saveInterval = infile->SaveSourcesInterval(); - saveFile = infile->GetSourceFile(); - theMPInterpMan = infile->GetNSInterpolationManager(); - interpStartCond = infile->GetInterpStartCond(); - - // Fission Energy Deposition Flags and files - interp = infile->GetInterp(); - RunThermalModel = infile->GetRunThermalModel(); - reactorPower = infile->GetReactorPower(); - saveMatTemp = infile->SaveTemperature(); - matTempFile = infile->GetTemperatureDataFile(); - - if(RunThermalModel) - { - heatTransfer = new StorkHeatTransfer(infile); - } - - // Initialize flags and values - convergenceLimit = infile->GetConvergenceLimit(); - totalConv = infile->GetNumberOfConvergenceRuns(); - runInterpStarted = numRuns; - propValues = new G4double[theMPInterpMan->GetNumberOfInterpVectors()]; - saveFissionData = infile->SaveFissionData(); - fissionFile = infile->GetFissionDataFile(); - - // Set up the run data array and initialize all values to zero - for(G4int i=0; i < 8; i++) - { - runData[i] = new G4double[numRuns]; - - for(G4int j=0; j < numRuns; j++) - { - runData[i][j] = 0.0; - } - - // Initialize the average run data to 0 - avgRunData[i+1] = 0.; - } - - // Get output stream - output = infile->GetLogOutputStream(); - - // Find the number of characters needed to write maximum run number - numRunOutputWidth = std::ceil(std::log(numRuns)/std::log(10)); -} - - -// Destructor -StorkRunManager::~StorkRunManager() -{ - // Delete the run data arrays - for(G4int i=0; i < 8; i++) - { - delete [] runData[i]; - } - - // Delete Heat Transfer Class - if(heatTransfer) - delete heatTransfer; - - // Delete Shannon entropy array - if(seSelect) delete [] seSelect; - - // Delete variable property values array - if(propValues) delete [] propValues; -} - -// Data Initializer in case no input file was used during construction -void StorkRunManager::InitializeRunData(const StorkParseInput* infile) -{ - // Set default values - runDuration = infile->GetRunDuration(); - runEnd = runStart + runDuration; - numRuns = infile->GetNumberOfRuns(); - saveInterval = infile->SaveSourcesInterval(); - saveFile = infile->GetSourceFile(); - theMPInterpMan = infile->GetNSInterpolationManager(); - interpStartCond = infile->GetInterpStartCond(); - - // Fission Energy Deposition Flags and files - interp = infile->GetInterp(); - RunThermalModel = infile->GetRunThermalModel(); - reactorPower = infile->GetReactorPower(); - saveMatTemp = infile->SaveTemperature(); - matTempFile = infile->GetTemperatureDataFile(); - - // Initialize flags and values - convergenceLimit = infile->GetConvergenceLimit(); - totalConv = infile->GetNumberOfConvergenceRuns(); - runInterpStarted = numRuns; - propValues = new G4double[theMPInterpMan->GetNumberOfInterpVectors()]; - saveFissionData = infile->SaveFissionData(); - fissionFile = infile->GetFissionDataFile(); - - // Set up the run data array and initialize all values to zero - for(G4int i=0; i < 8; i++) - { - runData[i] = new G4double[numRuns]; - - for(G4int j=0; j < numRuns; j++) - { - runData[i][j] = 0.0; - } - - // Initialize the average run data to 0 - avgRunData[i+1] = 0.; - } - - // Get output stream - output = infile->GetLogOutputStream(); - - // Find the number of characters needed to write maximum run number - numRunOutputWidth = std::ceil(std::log(numRuns)/std::log(10)); -} - -void StorkRunManager::InitializeRunData(G4double runDur, G4int numberRuns, G4int numSaveInterval, G4String saveFileName, G4bool interpStartCondition, - const StorkInterpManager* theMPInterpManager, G4double convergenceLim, G4int numConvRuns, G4bool saveFissionDataCond, - G4String fissionDataFile, std::ostream *logOutput, G4bool temperatureTracking,G4double nuclearReactorPower, - G4bool saveTemperature, G4String temperatureDataFile) -{ - // Set default values - runDuration = runDur; - runEnd = runStart + runDuration; - numRuns = numberRuns; - saveInterval = numSaveInterval; - saveFile = saveFileName; - theMPInterpMan = theMPInterpManager; - interpStartCond = interpStartCondition; - - // Fission Energy Deposition Flags and files - RunThermalModel = temperatureTracking; - reactorPower = nuclearReactorPower; - saveMatTemp = saveTemperature; - matTempFile = temperatureDataFile; - - // Initialize flags and values - convergenceLimit = convergenceLim; - totalConv = numConvRuns; - runInterpStarted = numRuns; - propValues = new G4double[theMPInterpMan->GetNumberOfInterpVectors()]; - saveFissionData = saveFissionDataCond; - fissionFile = fissionDataFile; - - // Set up the run data array and initialize all values to zero - for(G4int i=0; i < 8; i++) - { - runData[i] = new G4double[numRuns]; - - for(G4int j=0; j < numRuns; j++) - { - runData[i][j] = 0.0; - } - - // Initialize the average run data to 0 - avgRunData[i+1] = 0.; - } - - // Get output stream - output = logOutput; - - // Find the number of characters needed to write maximum run number - numRunOutputWidth = std::ceil(std::log(numRuns)/std::log(10)); -} - -// BeamOn() -// Start the simulation. Process each run and increment the simulation time. -void StorkRunManager::BeamOn(G4int n_event, const char* macroFile, - G4int n_select) -{ - //G4cout << " made it to the beginning of the StorkRunManager::BeamOn" << G4endl; - G4bool cond = ConfirmBeamOnCondition(); - if(cond) - { - - InitializeVar(n_event); - //G4cout << " made it to the past InitializeVar(n_event) in StorkRunManager::BeamOn" << G4endl; - // Set the number of events in the primary generator action - genAction->SetNumEvents(n_event); - - if(n_event>0) - { - while(runIDCounter < numRuns) - { - // Process the run - RunInitialization(); - DoEventLoop(n_event,macroFile,n_select); - RunTermination(); - - // Record the important results of the run - TallyRunResults(); - if (sourceConverged) - G4cout << G4endl << "#### Souce Has Converged #####" << G4endl; - else - G4cout << G4endl << "#### Souce Has Not Converged #####" << G4endl; - // Update the source distributions of the primary generator - runAction->UpdateSourceDistributions(); - - runStart += runDuration; - runEnd += runDuration; - - - //Run thermal calculation - if(RunThermalModel) - heatTransfer->RunThermalCalculation(runAction->GetCurrentFissionSites()); - - // Save the source distribution if the given interval of runs - // has passed - if(saveInterval && !(runIDCounter%saveInterval)){ - SaveSourceDistribution(saveFile); - if(saveFissionData) SaveFissionDistribution(fissionFile); - - - } - } - - // Save the final source distribution if the save interval is not - // zero and it has not been just saved - if(saveInterval && runIDCounter%saveInterval){ - SaveSourceDistribution(saveFile); - if(saveFissionData) SaveFissionDistribution(fissionFile); - } - } - } -} - - -// DoEventLoop() -// Override G4RunManager::DoEventLoop() -void StorkRunManager::DoEventLoop(G4int n_event, const char* macroFile, - G4int n_select) -{ - timer->Start(); - //if(verboseLevel>0) - //{ timer->Start(); } - - G4String msg; - if(macroFile!=0) - { - if(n_select<0) n_select = n_event; - msg = "/control/execute "; - msg += macroFile; - } - else - { n_select = -1; } - - // Initialize the current run - genAction->InitializeRun(); - - // Event loop - G4int i_event; - for( i_event=0; i_eventSetPrimaries(genAction->GetPrimaryData(i_event)); - - currentEvent = GenerateEvent(i_event); - eventManager->ProcessOneEvent(currentEvent); - AnalyzeEvent(currentEvent); - UpdateScoring(); - - // Update the run action tallies - runAction->TallyEvent(eventAction->GetEventData()); - - if(i_eventApplyCommand(msg); - - StackPreviousEvent(currentEvent); - currentEvent = 0; - - if(runAborted) break; - } - - if(verboseLevel>0) - { - timer->Stop(); - G4cout << "Run terminated." << G4endl; - G4cout << "Run Summary" << G4endl; - - if(runAborted) - { - G4cout << " Run Aborted after " << i_event - << " events processed." << G4endl; - } - else - { - G4cout << " Number of events processed : " << n_event << G4endl; - } - - G4cout << " " << *timer << G4endl; - } - - return; -} - - -// RunInitialization() -// Initialize the current run. Make any necessary changes to the world and -// save the fission data if necessary. -void StorkRunManager::RunInitialization() -{ - // Update properties only if source has converged or interpolation at - // start flag is true - if(sourceConverged || interpStartCond) - { - if(!interpStarted) - { - timeOffset = runStart; - runInterpStarted = runIDCounter; - interpStarted = true; - - /* - // Since interpolation just started create header and record - // pre interpolation temperatures - if(saveMatTemp) - { - worldPointerCD->SaveMaterialTemperatureHeader(matTempFile); - worldPointerCD->SaveMaterialTemperatures(matTempFile, G4int(runStart/runDuration)); - } - */ - } - - /* - // Update the material temperature based on fission sites if - // RunThermalModel is on - if(RunThermalModel) - { - //MapFissionSitesToMaterial(); - heatTransfer->RunThermalCalculation(runAction->GetCurrentFissionSites()); - - // Save the new temperatures only if asked to do so - if(saveMatTemp) - { - worldPointerCD->SaveMaterialTemperatures(matTempFile, G4int(runEnd/runDuration)); - } - }*/ - - - // Update the world properties - UpdateWorld(theMPInterpMan->GetStorkMatPropChanges(runStart -timeOffset)); - - } - - // For each variable property, set it in the run action - for (G4int i=0; i < theMPInterpMan->GetNumberOfInterpVectors(); i++) - { - // Get each property value from the world - propValues[i] = worldPointerCD->GetWorldProperty( - (*theMPInterpMan)[i]->second); - - // Send a pointer to the values to the run action - runAction->UpdateWorldProperties(propValues); - } - - // Start collecting fission data if source has converged - if(saveFissionData && sourceConverged && nConv == runIDCounter) - { - runAction->SaveFissionData(true); - } - - // Do standard Geant4 initialization tasks - G4RunManager::RunInitialization(); - - return; -} - - -// UpdateWorld() -// Rebuild the world with new properties. -void StorkRunManager::UpdateWorld(StorkMatPropChangeVector theChanges) -{ - // Create new world volume - DefineWorldVolume(worldPointerCD->UpdateWorld(theChanges)); - if(worldPointerCD->HasPhysChanged()) - { - // Inform kernel of change - PhysicsHasBeenModified(); - } - -} - - -// SaveSources() -// Calls the run actions save sources function. -// Saves survivors and delayed to the given file. -void StorkRunManager::SaveSourceDistribution(G4String fname) -{ - // Find the end of the output file name minus ".txt" - std::stringstream nameCount; - G4int pos = fname.find(".txt"); - - // Set the fill character to '0' - nameCount.fill('0'); - - nameCount << fname.substr(0,pos) << "-" << std::setw(numRunOutputWidth) - << runIDCounter << ".txt"; - - runAction->SaveSources(nameCount.str(), runIDCounter, runEnd-runDuration); -} - -void StorkRunManager::SaveFissionDistribution(G4String name) -{ - // Find the end of the output file name minus ".txt" - std::stringstream nameCount; - G4int pos = name.find(".txt"); - - // Set the fill character to '0' - nameCount.fill('0'); - - nameCount << name.substr(0,pos) << "-" << std::setw(numRunOutputWidth) - << runIDCounter << ".txt"; - - runAction->WriteFissionData(nameCount.str(), runIDCounter); -} - - -// TallyRunResults() -// Totals the results of each run after the source has converged -void StorkRunManager::TallyRunResults() -{ - // Get run results from run action - G4double *currentRunData = runAction->GetRunResults(); - - // Copy run results to runData arrays - for(G4int i=0; i < 8; i++) - { - runData[i][runIDCounter-1] = currentRunData[i]; - } - - // Check source convergence - sourceConverged = UpdateCheckSourceConvergence(); -} - - -// UpdateCheckSourceConvergence() -// Check convergence of the last "totalConv" runs in terms of Shannon entropy. -// For simplicity, only check at intervals of "totalConv" (25 runs default). -// The default convergence limit is 1%. -G4bool StorkRunManager::UpdateCheckSourceConvergence() -{ - // If the source has already converged, do nothing - if(sourceConverged) return true; - //changed elseif so that it checks convergence when there is no known discontuinity in the shannon entropy instead of every totalConv runs has passed - else if((runIDCounter < totalConv) || (convergeStop > (runIDCounter-totalConv)) ) return false; - - // Local variables - G4int i=0; - G4double seMean=0.; - - // Clear the seSelect array if full - if(seSelect) delete [] seSelect; - - // Create a new array - seSelect = new G4double[totalConv]; - - // Add Shannon entropies to the array - for(i=0; i < totalConv; i++) - { - seSelect[i] = runData[6][runIDCounter - totalConv + i]; - } - - // Find the mean of the selected shannon entropy - for(i=0; i < totalConv; i++) - { - seMean += seSelect[i]; - } - - // Divide mean by total - seMean /= G4double(totalConv); - - // Check whether se values are within the convergence limit of the mean - for(i=0; i < totalConv; i++) - { - if(convergenceLimit < std::abs(seSelect[i] - seMean)) - { - G4cout << "\nRun " << i << " has a Shannon Entropy of " << seSelect[i] << " which differed from the mean of " << seMean << " beyond the limit of " << convergenceLimit << G4endl; - convergeStop = runIDCounter - totalConv + i; - return false; - } - } - - // Convergence has been achieved, set convergence flag - //sourceConverged = true; - nConv = runIDCounter; - return true; -} - - -// OutputConvergence() -// Output the results of the run including convergence to an output stream -void StorkRunManager::OutputResults() -{ - if(sourceConverged) - { - // Find the average run data - AverageRunResults(); - - // Output run results - output->precision(6); - output->fill(' '); - *output << G4endl - << std::right - << "# Avg (last " << std::setw(5) << G4int(avgRunData[0]) - << " runs):" - << std::setw(16) << std::setprecision(4) << std::setw(12) - << avgRunData[1] << " " - << std::setw(12) << G4int(avgRunData[2]) << " " - << std::setw(12) << G4int(avgRunData[3]) << " " - << std::setw(12) << std::setprecision(6) << std::fixed - << avgRunData[4] << " " - << std::setw(12) << std::setprecision(6) << avgRunData[5] << " " - << std::setw(12) << std::setprecision(4) << avgRunData[6] << " " - << std::setw(12) << std::setprecision(4) << avgRunData[7] << " " - << std::setw(12) << std::setprecision(2) - << std::resetiosflags(std::ios_base::floatfield) - << avgRunData[8] - << G4endl; - } - - // Output start of interpolation (if used) - if(interpStarted) - { - *output << "# Interpolation started at run " << runInterpStarted - << G4endl; - } - - // Output the convergence limit in % - *output << G4endl - << "# Source convergence limit = " << convergenceLimit << "%" - << G4endl; - - // Report the results of convergence and the number of runs taken to reach - // this result. - if(!sourceConverged) - { - *output << "# Source convergence not achieved after " << numRuns - << " runs." << G4endl; - } - else - { - *output << "# Source converged after " << nConv << " runs." << G4endl; - } - - /*// Write fission data to file if necessary - if(saveFissionData) - runAction->WriteFissionData(fissionFile, nConv);*/ -} - - -// AverageRunResults() -// Averages a fraction of the total run results. -void StorkRunManager::AverageRunResults() -{ - // Find the number of runs to average over - avgRunData[0] = std::floor(frac * G4double(numRuns-nConv)); - G4int i = numRuns - G4int(avgRunData[0]); - - // Sum the run properties over these runs - for( ; i < numRuns; i++) - { - for(G4int j=0; j < 8; j++) - { - avgRunData[j+1] += runData[j][i]; - } - } - - // Divide by number of runs - for(G4int j=0; j < 8; j++) - { - avgRunData[j+1] /= avgRunData[0]; - } -} - - -//GetWorldProperty() -//returns the material property requested in the input -G4double StorkRunManager::GetWorldProperty(MatPropPair matProp) -{ - G4double val = worldPointerCD->GetWorldProperty(matProp); - - return val; -} - - -// InitializeVar() -// Initializes variables at the start of the beam on function -void StorkRunManager::InitializeVar(G4int n_event) -{ - // Reset the current run counter and run start - runIDCounter = 0; - runStart = 0.; - timeOffset = 0.; - runEnd = runStart + runDuration; - - // Set the pointers to the NS versions of the user action classes - genAction = dynamic_cast - (userPrimaryGeneratorAction); - runAction = dynamic_cast(userRunAction); - eventAction = dynamic_cast(userEventAction); - worldPointerCD = dynamic_cast(userDetector); - - if(RunThermalModel) - heatTransfer->SetWorld(worldPointerCD); - - numberOfEventToBeProcessed = n_event; -} diff --git a/G4STORK/src/StorkSteppingAction.cc b/G4STORK/src/StorkSteppingAction.cc deleted file mode 100755 index 531a51b9..00000000 --- a/G4STORK/src/StorkSteppingAction.cc +++ /dev/null @@ -1,99 +0,0 @@ -// -// StorkSteppingAction.cc -// G4-STORK_AT -// -// Created by Andrew Tan on 2014-07-12. -// Copyright (c) 2014 andrewtan. All rights reserved. -// - -#include "StorkSteppingAction.hh" - -//Constructor -StorkSteppingAction::StorkSteppingAction(StorkEventAction* eventAction): G4UserSteppingAction() -{ - SteppingMan = new G4SteppingManager; - myEventAction = eventAction; -} -//Destructor -StorkSteppingAction::~StorkSteppingAction() -{ - delete SteppingMan; -} - -/*void StorkSteppingAction::UserSteppingAction(const G4Step* theStep) -{ - - G4cout << "Step is limited by " - << theStep->GetPostStepPoint()->GetProcessDefinedStep()->GetProcessName() - << G4endl; - G4cout << "Processes involved to the step" << G4endl; - G4StepStatus stepStatus = fpSteppingManager->GetfStepStatus(); - - if(stepStatus==fAtRestDoItProc) - { - G4ProcessVector* procAtRest = fpSteppingManager->GetfAtRestDoItVector(); - G4SelectedAtRestDoItVector* selProcAtRest - = fpSteppingManager->GetfSelectedAtRestDoItVector(); - size_t MAXofAtRestLoops = fpSteppingManager->GetMAXofAtRestLoops(); - for(size_t i1=0;i1GetProcessName() << " (forced)" << G4endl; } - else if((*selProcAtRest)[MAXofAtRestLoops-i1-1]==1) - { G4cout << " At rest : " << (*procAtRest)[i1]->GetProcessName() << G4endl; } - } - } - - if(stepStatus!=fExclusivelyForcedProc && stepStatus!=fAtRestDoItProc) - { - G4ProcessVector* procAlong = fpSteppingManager->GetfAlongStepDoItVector(); - size_t MAXofAlongStepLoops = fpSteppingManager->GetMAXofAlongStepLoops(); - for(size_t i2=0;i2GetProcessName() << G4endl; - } - } - - if(stepStatus!=fAtRestDoItProc) - { - G4ProcessVector* procPost = fpSteppingManager->GetfPostStepDoItVector(); - G4SelectedPostStepDoItVector* selProcPost - = fpSteppingManager->GetfSelectedPostStepDoItVector(); - size_t MAXofPostStepLoops = fpSteppingManager->GetMAXofPostStepLoops(); - for(size_t i3=0;i3GetProcessName() << " (forced)" << G4endl; } - else if((*selProcPost)[MAXofPostStepLoops-i3-1]==1) - { G4cout << " Post step : " << (*procPost)[i3]->GetProcessName() << G4endl; } - } - } - - G4int nSecAtRest = fpSteppingManager->GetfN2ndariesAtRestDoIt(); - G4int nSecAlong = fpSteppingManager->GetfN2ndariesAlongStepDoIt(); - G4int nSecPost = fpSteppingManager->GetfN2ndariesPostStepDoIt(); - G4int nSecTotal = nSecAtRest+nSecAlong+nSecPost; - G4TrackVector* secVec = fpSteppingManager->GetfSecondary(); - - if(nSecTotal>0) - { - G4cout << " :----- List of 2ndaries - " << std::setw(3) << nSecTotal - << " (Rest=" << std::setw(2) << nSecAtRest - << ",Along=" << std::setw(2) << nSecAlong - << ",Post=" << std::setw(2) << nSecPost << ")" << G4endl; - - for(size_t lp1=(*secVec).size()-nSecTotal; lp1<(*secVec).size(); lp1++) - { - G4cout << " : " - << G4BestUnit((*secVec)[lp1]->GetPosition(), "Length") << " " - << std::setw( 9) << G4BestUnit((*secVec)[lp1]->GetKineticEnergy() , "Energy") << " " - << std::setw(18) << (*secVec)[lp1]->GetDefinition()->GetParticleName() - << " generated by " << (*secVec)[lp1]->GetCreatorProcess()->GetProcessName() << G4endl; - } -} -*/ - - - - diff --git a/G4STORK/src/StorkTallyHit.cc b/G4STORK/src/StorkTallyHit.cc deleted file mode 100755 index ea1ca781..00000000 --- a/G4STORK/src/StorkTallyHit.cc +++ /dev/null @@ -1,37 +0,0 @@ -/* -StorkTallyHit.cc - -Created by: Liam Russell -Date: 18-07-2011 -Modified: 11-03-2013 - -Source code for StorkTallyHit class. - -*/ - - -// Include header file - -#include "StorkTallyHit.hh" - - -// Constructor -StorkTallyHit::StorkTallyHit() -{ - totalLifetime = 0.0; - nLoss = nProd = dProd = 0; -} - - -// Print() -// Outputs all of the tally information to the G4cout. -void StorkTallyHit::Print() -{ - G4cout << "Following quantities are tallied: " << G4endl - << "Neutrons Lost = " << nLoss << G4endl - << "Neutrons Produced = " << nProd << G4endl - << "Total lifetime of lost neutrons = " << totalLifetime << G4endl - << "Number of survivors = " << survivors.size() << G4endl - << "Number of delayed = " << delayed.size() << G4endl - << "Number of fission sites = " << fSites.size() << G4endl; -} diff --git a/G4STORK/src/StorkTimeStepLimiter.cc b/G4STORK/src/StorkTimeStepLimiter.cc deleted file mode 100755 index 3a57c634..00000000 --- a/G4STORK/src/StorkTimeStepLimiter.cc +++ /dev/null @@ -1,46 +0,0 @@ -/* -StorkTimeStepLimiter.cc - -Created by: Liam Russell -Date: 22-06-2011 -Modified: 11-03-2013 - -Source code file for StorkTimeStepLimiter class. - -*/ - - -// Include header file -#include "StorkTimeStepLimiter.hh" - - -// Constructor -// Calls the G4StepLimiter constructor with the proper name -StorkTimeStepLimiter::StorkTimeStepLimiter(const G4String &aName) -: G4StepLimiter(aName) -{ - // Get a pointer to the run manager - runMan = dynamic_cast(G4RunManager::GetRunManager()); -} - - -// PostStepGetPhysicalInteractionLength() -// Returns the total distance the neutron can travel in the time until the -// current run ends at the current momentum of the neutron. -G4double StorkTimeStepLimiter::PostStepGetPhysicalInteractionLength( - const G4Track &aTrack, - G4double, // previousStepSize - G4ForceCondition *condition) -{ - // Set condition to "Not Forced" - *condition = NotForced; - - // Determine the proposed step - G4double proposedStep = aTrack.GetVelocity() * (runMan->GetRunEnd() - - aTrack.GetGlobalTime()); - - // Make sure the step length is not negaitve - if(proposedStep < 0.0) proposedStep = 0.0; - - return proposedStep; -} diff --git a/G4STORK/src/StorkUnion.cc b/G4STORK/src/StorkUnion.cc deleted file mode 100755 index 9b86df54..00000000 --- a/G4STORK/src/StorkUnion.cc +++ /dev/null @@ -1,72 +0,0 @@ -#include "StorkUnion.hh" - -StorkUnion::StorkUnion(solidList* List) -{ - Unions = List; -} - -StorkUnion::~StorkUnion(void) -{ - delete Unions; -} - -solidPos StorkUnion::GetUnionSolid(G4String name) -{ - std::stringstream unionName; - solidList Temp1 = *Unions, ToBeAdded = solidList(); - G4int size = Temp1.size(); - G4bool Add = false; - G4int n = 0; - - while(size > 2) - { - solidList Temp2 = solidList(); - - if(size%2 != 0 && ToBeAdded.size() == 1) - { - size = size - 1; - Add = true; - } - else if(size%2 != 0) - { - size = size - 1; - ToBeAdded.push_back(Temp1[size]); - } - - for(G4int i = 0; i < int(size/2); i++) - { - unionName.str(name); - unionName << n; - Temp2.push_back(std::make_pair(new G4UnionSolid(unionName.str(), Temp1[2*i].first, Temp1[2*i+1].first, 0, Temp1[2*i+1].second-Temp1[2*i].second), Temp1[2*i].second)); - n++; - } - - if(Add) - { - unionName.str(name); - unionName << n; - Temp2.push_back(std::make_pair(new G4UnionSolid(unionName.str(), Temp1[size].first, ToBeAdded[0].first, 0, ToBeAdded[0].second-Temp1[size].second), Temp1[size].second)); - ToBeAdded.pop_back(); - n++; - Add = false; - } - Temp1 = Temp2; - size = Temp1.size(); - } - - if(Temp1.size() == 1) - { - return std::make_pair(new G4UnionSolid(name, Temp1[0].first, ToBeAdded[0].first, 0, ToBeAdded[0].second-Temp1[0].second), Temp1[0].second); - } - else if(ToBeAdded.size() == 0) - { - return std::make_pair(new G4UnionSolid(name, Temp1[0].first, Temp1[1].first, 0, Temp1[1].second-Temp1[0].second), Temp1[0].second); - } - else - { - unionName.str(name); - unionName << n; - solidPos Temp = std::make_pair(new G4UnionSolid(unionName.str(), Temp1[0].first, Temp1[1].first, 0, Temp1[1].second-Temp1[0].second), Temp1[0].second); - return std::make_pair(new G4UnionSolid(name, Temp.first, ToBeAdded[0].first, 0, ToBeAdded[0].second-Temp.second), Temp.second); - } -} diff --git a/G4STORK/src/StorkUnionSolid.cc b/G4STORK/src/StorkUnionSolid.cc deleted file mode 100755 index 1864e311..00000000 --- a/G4STORK/src/StorkUnionSolid.cc +++ /dev/null @@ -1,898 +0,0 @@ -// -// ******************************************************************** -// * License and Disclaimer * -// * * -// * The Geant4 software is copyright of the Copyright Holders of * -// * the Geant4 Collaboration. It is provided under the terms and * -// * conditions of the Geant4 Software License, included in the file * -// * LICENSE and available at http://cern.ch/geant4/license . These * -// * include a list of copyright holders. * -// * * -// * Neither the authors of this software system, nor their employing * -// * institutes,nor the agencies providing financial support for this * -// * work make any representation or warranty, express or implied, * -// * regarding this software system or assume any liability for its * -// * use. Please see the license in the file LICENSE and URL above * -// * for the full disclaimer and the limitation of liability. * -// * * -// * This code implementation is the result of the scientific and * -// * technical work of the GEANT4 collaboration. * -// * By using, copying, modifying or distributing the software (or * -// * any work based on the software) you agree to acknowledge its * -// * use in resulting scientific publications, and indicate your * -// * acceptance of all terms of the Geant4 Software license. * -// ******************************************************************** -// -// -// $Id$ -// -// Implementation of methods for the class G4IntersectionSolid -// -// History: -// -// 12.09.98 V.Grichine: first implementation -// 28.11.98 V.Grichine: fix while loops in DistToIn/Out -// 27.07.99 V.Grichine: modifications in DistToOut(p,v,...), while -> do-while -// 16.03.01 V.Grichine: modifications in CalculateExtent() -// -// -------------------------------------------------------------------- - -#include - -#include "StorkUnionSolid.hh" - -#include "G4SystemOfUnits.hh" -#include "G4VoxelLimits.hh" -#include "G4VPVParameterisation.hh" -#include "G4GeometryTolerance.hh" - -#include "G4VGraphicsScene.hh" -#include "G4Polyhedron.hh" -#include "HepPolyhedronProcessor.h" -//#include "G4NURBS.hh" -// #include "G4NURBSbox.hh" - -/////////////////////////////////////////////////////////////////// -// -// Transfer all data members to G4BooleanSolid which is responsible -// for them. pName will be in turn sent to G4VSolid -//### this function has been checked ### -StorkUnionSolid:: StorkUnionSolid( const G4String& pName, - G4VSolid* pSolidA , - G4VSolid* pSolidB, - ShapeEnum shape, StorkSixVector regionDim, G4ThreeVector offset ) - : G4BooleanSolid(pName,pSolidA,pSolidB) -{ - //sets the shape, dimensions and position of the region that the solids will be contained in - regShape = shape; - regDim=regionDim; - // the offset is the vector from the origin of pSolidA to the origin of the region - regOffSet = offset; -} - -///////////////////////////////////////////////////////////////////// -// -// Constructor -//### this function has been checked ### -StorkUnionSolid::StorkUnionSolid( const G4String& pName, - G4VSolid* pSolidA , - G4VSolid* pSolidB , - G4RotationMatrix* rotMatrix, - const G4ThreeVector& transVector, - ShapeEnum shape, StorkSixVector regionDim, G4ThreeVector offset) - : G4BooleanSolid(pName,pSolidA,pSolidB,rotMatrix,transVector) - -{ - //rotMatrix set the rotation of the referance frame of pSolidB relative to pSolidA - //transVector sets the vector from the origin of pSolidA to the origin of pSolidB before pSolidB is rotated - //sets the shape, dimensions and position of the region that the solids will be contained in - regShape = shape; - regDim=regionDim; - // the offset is the vector from the origin of pSolidA to the origin of the region - regOffSet= offset; -} - -/////////////////////////////////////////////////////////// -// -// Constructor -//### this function has been checked ### -StorkUnionSolid::StorkUnionSolid( const G4String& pName, - G4VSolid* pSolidA , - G4VSolid* pSolidB , - const G4Transform3D& transform, - ShapeEnum shape, StorkSixVector regionDim, G4ThreeVector offset) - : G4BooleanSolid(pName,pSolidA,pSolidB,transform) -{ - //transform sets the vector from the origin of pSolidA to the origin of pSolidB and - //then it sets the rotation of the referance frame of pSolidB relative to pSolidA - //sets the shape, dimensions and position of the region that the solids will be contained in - regShape = shape; - regDim=regionDim; - // the offset is the vector from the origin of pSolidA to the origin of the region - regOffSet= offset; -} - -//StorkUnionSolid::StorkUnionSolid( StorkUnionSolid* solid, G4double addRegion[], ShapeEnum shape, DirEnum dir) -// : G4BooleanSolid(solid->GetEntityType(),,pSolidB,transform) -//{ -// solid->AddRegionToMe(dir, addRegion); -// *this = *solid; -//} - -////////////////////////////////////////////////////////////////// -// -// Fake default constructor - sets only member data and allocates memory -// for usage restricted to object persistency. -//### this function has been checked ### -StorkUnionSolid::StorkUnionSolid( __void__& a ) - : G4BooleanSolid(a) -{ -} - -/////////////////////////////////////////////////////////// -// -// Destructor -//### this function has been checked ### -StorkUnionSolid::~StorkUnionSolid() -{ -} - -/////////////////////////////////////////////////////////////// -// -// Copy constructor -// ### I fixed the copy constructor 2014 Aug 19 -//### this function has been checked ### -StorkUnionSolid::StorkUnionSolid(const StorkUnionSolid& rhs) - : G4BooleanSolid (rhs) -{ - regShape=rhs.GetRegionShape(); - regDim=rhs.GetRegionDim(); - regOffSet=rhs.GetRegionOffSet(); -} - -/////////////////////////////////////////////////////////////// -// -// Assignment operator -// ### I fixed the assignment operator 2014 Aug 19 -//### this function has been checked ### -StorkUnionSolid& StorkUnionSolid::operator = (const StorkUnionSolid& rhs) -{ - // Check assignment to self - // - if (this == &rhs) { return *this; } - - // Copy base class data - // - G4BooleanSolid::operator=(rhs); - - regShape=rhs.GetRegionShape(); - regDim=rhs.GetRegionDim(); - regOffSet=rhs.GetRegionOffSet(); - - return *this; -} - -/////////////////////////////////////////////////////////////// -// -// - - -// taken from G4Unionsolid, this calculates the extent of the volume based off an axis or in other words the distance the particle will travel in the solid based off its current trajectory -//### this function has been checked ### -G4bool -StorkUnionSolid::CalculateExtent( const EAxis pAxis, - const G4VoxelLimits& pVoxelLimit, - const G4AffineTransform& pTransform, - G4double& pMin, - G4double& pMax ) const -{ - G4bool touchesA, touchesB, out ; - G4double minA = kInfinity, minB = kInfinity, - maxA = -kInfinity, maxB = -kInfinity; - - touchesA = fPtrSolidA->CalculateExtent( pAxis, pVoxelLimit, - pTransform, minA, maxA); - touchesB= fPtrSolidB->CalculateExtent( pAxis, pVoxelLimit, - pTransform, minB, maxB); - if( touchesA || touchesB ) - { - pMin = std::min( minA, minB ); - pMax = std::max( maxA, maxB ); - out = true ; - } - else out = false ; - - return out ; // It exists in this slice if either one does. -} - -///////////////////////////////////////////////////// -// -// Important comment: When solids A and B touch together along flat -// surface the surface points will be considered as kSurface, while points -// located around will correspond to kInside - -//### this function has been checked ### -EInside StorkUnionSolid::Inside( const G4ThreeVector& p ) const -{ - EInside positionA = kOutside, positionB = kOutside; - - if(this->InsideRegion(p)) - { - positionA = fPtrSolidA->Inside(p); - positionB = fPtrSolidB->Inside(p); - } - - if( positionA == kInside || positionB == kInside || - ( positionA == kSurface && positionB == kSurface && - ( fPtrSolidA->SurfaceNormal(p) + - fPtrSolidB->SurfaceNormal(p) ).mag2() < - 1000*G4GeometryTolerance::GetInstance()->GetRadialTolerance() ) ) - { - return kInside; - } - else - { - if( ( positionB == kSurface ) || ( positionA == kSurface ) ) - { return kSurface; } - else - { return kOutside; } - } -} - -////////////////////////////////////////////////////////////// -// -// -//### fixed 2014 Aug 19 -//### this function has been checked ### -G4ThreeVector -StorkUnionSolid::SurfaceNormal( const G4ThreeVector& p ) const -{ - G4ThreeVector normal=G4ThreeVector(0.,0.,0.), check = G4ThreeVector(0.,0.,0.); - -#ifdef G4BOOLDEBUG - if( Inside(p) == kOutside ) - { - G4cout << "WARNING - Invalid call in " - << "StorkUnionSolid::SurfaceNormal(p)" << G4endl - << " Point p is outside !" << G4endl; - G4cout << " p = " << p << G4endl; - G4cerr << "WARNING - Invalid call in " - << "StorkUnionSolid::SurfaceNormal(p)" << G4endl - << " Point p is outside !" << G4endl; - G4cerr << " p = " << p << G4endl; - } -#endif - - if(this->InsideRegion(p)) - { - if(fPtrSolidA->Inside(p) == kSurface && fPtrSolidB->Inside(p) != kInside) - { - normal= fPtrSolidA->SurfaceNormal(p) ; - } - else if(fPtrSolidB->Inside(p) == kSurface && - fPtrSolidA->Inside(p) != kInside) - { - normal= fPtrSolidB->SurfaceNormal(p) ; - } - else - { - normal= fPtrSolidA->SurfaceNormal(p) ; - } - } - else - normal= fPtrSolidA->SurfaceNormal( p ); - -#ifdef G4BOOLDEBUG - if(Inside(p)==kInside) - { - G4cout << "WARNING - Invalid call in " - << "StorkUnionSolid::SurfaceNormal(p)" << G4endl - << " Point p is inside !" << G4endl; - G4cout << " p = " << p << G4endl; - G4cerr << "WARNING - Invalid call in " - << "StorkUnionSolid::SurfaceNormal(p)" << G4endl - << " Point p is inside !" << G4endl; - G4cerr << " p = " << p << G4endl; - } -#endif - return normal; -} - -///////////////////////////////////////////////////////////// -// -// The same algorithm as in DistanceToIn(p) - -G4double -StorkUnionSolid::DistanceToIn( const G4ThreeVector& p, - const G4ThreeVector& v ) const -{ -#ifdef G4BOOLDEBUG - if( Inside(p) == kInside ) - { - G4cout << "WARNING - Invalid call in " - << "StorkUnionSolid::DistanceToIn(p,v)" << G4endl - << " Point p is inside !" << G4endl; - G4cout << " p = " << p << G4endl; - G4cout << " v = " << v << G4endl; - G4cerr << "WARNING - Invalid call in " - << "StorkUnionSolid::DistanceToIn(p,v)" << G4endl - << " Point p is inside !" << G4endl; - G4cerr << " p = " << p << G4endl; - G4cerr << " v = " << v << G4endl; - } -#endif - G4double distA = kInfinity, distB = kInfinity; - - if(this->DistInRegion(p, v)) - { - distA = fPtrSolidA->DistanceToIn(p,v); - distB = fPtrSolidB->DistanceToIn(p,v); - } - - return std::min(distA, - distB) ; -} - -//////////////////////////////////////////////////////// -// -// Approximate nearest distance from the point p to the union of -// two solids - -G4double StorkUnionSolid::DistanceToIn( const G4ThreeVector& p) const -{ -#ifdef G4BOOLDEBUG - if( Inside(p) == kInside ) - { - G4cout << "WARNING - Invalid call in " - << "StorkUnionSolid::DistanceToIn(p)" << G4endl - << " Point p is inside !" << G4endl; - G4cout << " p = " << p << G4endl; - G4cerr << "WARNING - Invalid call in " - << "StorkUnionSolid::DistanceToIn(p)" << G4endl - << " Point p is inside !" << G4endl; - G4cerr << " p = " << p << G4endl; - } -#endif -//use functions definced in the various solid classes - G4double minDist= kInfinity, distB=kInfinity, distA=kInfinity; - G4bool check = false, check2 = false; - StorkUnionSolid *tempPointer; - - if(fPtrSolidA->GetEntityType()=="StorkUnionSolid") - { - tempPointer = dynamic_cast(fPtrSolidA); - check = tempPointer->InsideRegion(p); - if(check) - { - distA = tempPointer->DistanceToIn(p, minDist) ; - } - } - else if(fPtrSolidA->Inside(p)!=kOutside) - { - check=true; - distA = 0.0; - } - else - { - distA = fPtrSolidA->DistanceToIn(p); - } - - - if(!check) - { - if(fPtrSolidB->GetEntityType()=="StorkUnionSolid") - { - tempPointer = dynamic_cast(fPtrSolidB); - check2 = tempPointer->InsideRegion(p); - if(check2) - { - distB = tempPointer->DistanceToIn(p, minDist) ; - } - } - else if(fPtrSolidB->Inside(p)!=kOutside) - { - check=true; - distB = 0.0; - } - else - { - distB = fPtrSolidA->DistanceToIn(p); - } - } - - G4double safety = std::min(distA,distB) ; - if(safety < 0.0) safety = 0.0 ; - return safety ; -} - -G4double -StorkUnionSolid::DistanceToIn( const G4ThreeVector& p, G4double minDist) const -{ -#ifdef G4BOOLDEBUG - if( Inside(p) == kInside ) - { - G4cout << "WARNING - Invalid call in " - << "StorkUnionSolid::DistanceToIn(p)" << G4endl - << " Point p is inside !" << G4endl; - G4cout << " p = " << p << G4endl; - G4cerr << "WARNING - Invalid call in " - << "StorkUnionSolid::DistanceToIn(p)" << G4endl - << " Point p is inside !" << G4endl; - G4cerr << " p = " << p << G4endl; - } -#endif -//use functions definced in the various solid classes - G4double regDis = this->DistInRegion(p), distA, distB; - - if(regDis<=minDist) - { - minDist=regDis; - if(fPtrSolidA->GetEntityType()=="StorkUnionSolid") - { - StorkUnionSolid *tempPointer = dynamic_cast(fPtrSolidA); - distA = tempPointer->DistanceToIn(p, minDist) ; - } - else - distA = fPtrSolidA->DistanceToIn(p) ; - - if(fPtrSolidB->GetEntityType()=="StorkUnionSolid") - { - StorkUnionSolid *tempPointer = dynamic_cast(fPtrSolidB); - distB = tempPointer->DistanceToIn(p, minDist) ; - } - else - distB = fPtrSolidB->DistanceToIn(p) ; - - G4double safety = std::min(distA,distB) ; - - if(safety < 0.0) - safety = 0.0 ; - - return safety; - } - return kInfinity; -} - -////////////////////////////////////////////////////////// -// -// The same algorithm as DistanceToOut(p) - -G4double -StorkUnionSolid::DistanceToOut( const G4ThreeVector& p, - const G4ThreeVector& v, - const G4bool calcNorm, - G4bool *validNorm, - G4ThreeVector *n ) const -{ - G4double dist = 0.0; - G4ThreeVector Tmp; - G4ThreeVector* nTmp=&Tmp; - - if (this->InsideRegion(p)) - { - dist = fPtrSolidA->DistanceToOut(p,v,calcNorm, validNorm,nTmp); - - dist += fPtrSolidB->DistanceToOut(p+dist*v,v,calcNorm, validNorm,nTmp); - } - if( calcNorm ) - { - *validNorm = false ; - *n = *nTmp ; - } - - return dist; -} - -////////////////////////////////////////////////////////////// -// -// Inverted algorithm of DistanceToIn(p) - -G4double -StorkUnionSolid::DistanceToOut( const G4ThreeVector& p ) const -{ - G4double distout = 0.0; - - if(this->InsideRegion(p)) - { - distout= std::max(fPtrSolidA->DistanceToOut(p), - fPtrSolidB->DistanceToOut(p) ) ; - } - - return distout; -} - -////////////////////////////////////////////////////////////// -// -// - -G4GeometryType StorkUnionSolid::GetEntityType() const -{ - return G4String("StorkUnionSolid"); -} - -////////////////////////////////////////////////////////////////////////// -// -// Make a clone of the object - -G4VSolid* StorkUnionSolid::Clone() const -{ - return new StorkUnionSolid(*this); -} - -////////////////////////////////////////////////////////////// -// -// -G4bool StorkUnionSolid::InsideRegion( const G4ThreeVector& p ) const -{ - G4ThreeVector q=p-regOffSet; - - static const G4double delta=0.5*kCarTolerance; - static const G4double delta2=0.5*(G4GeometryTolerance::GetInstance()->GetRadialTolerance()); - static const G4double delta3=0.5*(G4GeometryTolerance::GetInstance()->GetAngularTolerance()); - - - if(regShape==0) - { - if((q.rho()>=regDim[0]-delta2)&&(q.rho()<=regDim[1]+delta2)&&(q.phi()>=regDim[2]-delta3)&&(q.phi()<=regDim[3]+delta3)&&(q.z()>=regDim[4]-delta)&&(q.z()<=regDim[5]+delta)) - { - return true; - } - } - else if(regShape==1) - { - if((q.x()>=regDim[0]-delta)&&(q.x()<=regDim[1]+delta)&&(q.y()>=regDim[2]-delta)&&(q.y()<=regDim[3]+delta)&&(q.z()>=regDim[4]-delta)&&(q.z()<=regDim[5]+delta)) - { - return true; - } - } - - else - { - if((q.r()>=regDim[0]-delta2)&&(q.r()<=regDim[1]+delta2)&&(q.phi()>=regDim[2]-delta3)&&(q.phi()<=regDim[3]+delta3)&&(q.theta()>=regDim[4]-delta3)&&(q.theta()<=regDim[5]+delta3)) - { - return true; - } - } - - return false; - -} - -G4bool StorkUnionSolid::DistInRegion( const G4ThreeVector& q, const G4ThreeVector& v ) const -{ - G4double smax, smin, swap3; - G4double swap[6]; - - if (this->InsideRegion(q)) - return true; - - G4ThreeVector p=q-regOffSet; - - //This function finds the intervals over which the given trajectory is within the boundaries of each dimension - //and then it checks to see if the intervals overlap, if they do then the trajectory will pass through the region - //if no then the trajectory will not pass through the region - if(regShape==0) - { - swap[0] = (regDim[4]-p[2])/(v[2]); - swap[1] = (regDim[5]-p[2])/(v[2]); - if(swap[0]>swap[1]) - { - smax=swap[0]; - smin=swap[1]; - } - else - { - smax=swap[1]; - smin=swap[0]; - } - - swap[0] = (-(p[1]*v[1]+p[0]*v[0])+pow(2*p[1]*v[1]*p[0]*v[0]+(pow(regDim[1],2))*(v.perp2()),0.5))/(v.perp2()); - swap[1] = (-(p[1]*v[1]+p[0]*v[0])-pow(2*p[1]*v[1]*p[0]*v[0]+(pow(regDim[1],2))*(v.perp2()),0.5))/(v.perp2()); - swap[2] = (-(p[1]*v[1]+p[0]*v[0])+pow(2*p[1]*v[1]*p[0]*v[0]+(pow(regDim[0],2))*(v.perp2()),0.5))/(v.perp2()); - swap[3] = (-(p[1]*v[1]+p[0]*v[0])-pow(2*p[1]*v[1]*p[0]*v[0]+(pow(regDim[0],2))*(v.perp2()),0.5))/(v.perp2()); - swap[4] = -(p[0]*tan(regDim[2])-p[1])/(v[0]*tan(regDim[2])-v[1]); - swap[5] = -(p[0]*tan(regDim[3])-p[1])/(v[0]*tan(regDim[3])-v[1]); - - if(swap[4]smin) - smin=swap[5]; - - if(!((swap[1]>=swap[4]&&swap[3]>=swap[4])||(swap[1]<=swap[5]&&swap[3]<=swap[5]))) - { - if(swap[1]smin) - smin=swap[3]; - } - else if(!((swap[0]>=swap[4]&&swap[2]>=swap[4])||(swap[0]<=swap[5]&&swap[2]<=swap[5]))) - { - if(swap[0]smin) - smin=swap[2]; - } - else - return false; - - if(smax<=0.) - return false; - - if(sminswap[1]) - { - smax=swap[0]; - smin=swap[1]; - } - else - { - smax=swap[1]; - smin=swap[0]; - } - - for (G4int i=2; i<5; i=i+2) - { - swap[0] = (regDim[i]-p[G4int(i/2)])/(v[G4int(i/2)]); - swap[1] = (regDim[i+1]-p[G4int(i/2)])/(v[G4int(i/2)]); - if(swap[0]smin) - smin=swap[1]; - } - - if(smax<=0.) - return false; - - if(smin0.) ? ((p.z())-regDim[1]) : (-(p.z())+regDim[0]) ; - - if ( safe1 > safe2 ) { safe = safe1; } - else { safe = safe2; } - if ( safe3 > safe ) { safe = safe3; } - - if ( ((regDim[3]-regDim[2])==2*CLHEP::pi) && (rho) ) - { - // Psi=angle from central phi to point - // - cosPsi = (p.x()*cosCPhi + p.y()*sinCPhi)/rho ; - - if ( cosPsi < std::cos((regDim[3]-regDim[2])*0.5) ) - { - // Point lies outside phi range - - if ( (p.y()*cosCPhi - p.x()*sinCPhi) <= 0 ) - { - safePhi = std::fabs(p.x()*sinSPhi - p.y()*cosSPhi) ; - } - else - { - safePhi = std::fabs(p.x()*sinEPhi - p.y()*cosEPhi) ; - } - if ( safePhi > safe ) { safe = safePhi; } - } - } - if ( safe < 0. ) { safe = 0.; } - return safe ; - } - - else if(regShape==1) - { - G4double safex, safey, safez, safe = 0.0 ; - - safex = (p.x()>0) ? ((p.x())-regDim[1]) : (-(p.x())+regDim[0]) ; - safey = (p.y()>0) ? ((p.y())-regDim[3]) : (-(p.y())+regDim[2]) ; - safez = (p.z()>0) ? ((p.z())-regDim[5]) : (-(p.z())+regDim[4]) ; - - if (safex > safe) { safe = safex ; } - if (safey > safe) { safe = safey ; } - if (safez > safe) { safe = safez ; } - - return safe ; - } - - else - { - G4cerr << "This position in a sphere region has not yet been added to the StorkUnionSolid"; - return 0.; - } -} - -void StorkUnionSolid::AddRegionToMe( DirEnum dir, StorkSixVector regionDim ) -{ - if(dir==right) - { - if(regShape==cylUnit) - { - (regDim[2])=(regionDim[2]); - } - else if(regShape==cubicUnit) - { - regDim[1]+=regionDim[1]-regionDim[0]; - } - else - { - regDim[2]=regionDim[2]; - } - } - else if(dir==left) - { - if(regShape==cylUnit) - { - regDim[3]=regionDim[3]; - } - else if(regShape==cubicUnit) - { - regDim[0]+=regionDim[0]-regionDim[1]; - } - else - { - regDim[3]=regionDim[3]; - } - } - else if(dir==up) - { - if(regShape==cylUnit) - { - regDim[1]=regionDim[1]; - } - else if(regShape==cubicUnit) - { - regDim[3]+=regionDim[3]-regionDim[2]; - } - else - { - regDim[1]=regionDim[1]; - } - } - else if(dir==down) - { - if(regShape==cylUnit) - { - regDim[0]=regionDim[0]; - } - else if(regShape==cubicUnit) - { - regDim[2]+=regionDim[2]-regionDim[3]; - } - else - { - regDim[0]=regionDim[0]; - } - } - else if(dir==above) - { - if(regShape==cylUnit) - { - regDim[5]+=regionDim[5]-regionDim[4]; - } - else if(regShape==cubicUnit) - { - regDim[5]+=regionDim[5]-regionDim[4]; - } - else - { - regDim[4]=regionDim[4]; - } - } - else if(dir==below) - { - if(regShape==cylUnit) - { - regDim[4]+=regionDim[4]-regionDim[5]; - } - else if(regShape==cubicUnit) - { - regDim[4]+=regionDim[2]; - } - else - { - regDim[5]=regionDim[5]; - } - } -} - - -void -StorkUnionSolid::ComputeDimensions( G4VPVParameterisation*, - const G4int, - const G4VPhysicalVolume* ) -{ -} - -///////////////////////////////////////////////// -// -// - -void -StorkUnionSolid::DescribeYourselfTo ( G4VGraphicsScene& scene ) const -{ - scene.AddSolid (*this); -} - -//////////////////////////////////////////////////// -// -// - -G4Polyhedron* -StorkUnionSolid::CreatePolyhedron () const -{ - HepPolyhedronProcessor processor; - // Stack components and components of components recursively - // See G4BooleanSolid::StackPolyhedron - G4Polyhedron* top = StackPolyhedron(processor, this); - G4Polyhedron* result = new G4Polyhedron(*top); - if (processor.execute(*result)) { return result; } - else { return 0; } -} - -///////////////////////////////////////////////////////// -// -// -/* -G4NURBS* -StorkUnionSolid::CreateNURBS () const -{ - // Take into account boolean operation - see CreatePolyhedron. - // return new G4NURBSbox (1.0, 1.0, 1.0); - return 0; -} -*/ diff --git a/G4STORK/src/StorkUserBCStepLimiter.cc b/G4STORK/src/StorkUserBCStepLimiter.cc deleted file mode 100755 index 1fab8789..00000000 --- a/G4STORK/src/StorkUserBCStepLimiter.cc +++ /dev/null @@ -1,236 +0,0 @@ -/* -StorkUserBCStepLimiter.cc - -Created by: Wesley Ford -Date: 22-06-2012 -Modified: 17-02-2012 - -Source code file for StorkUserBCStepLimiter class. - -*/ - - -// Include header file -#include "StorkUserBCStepLimiter.hh" - - -// Constructor() -// Calls the G4StepLimiter constructor with the proper name -StorkUserBCStepLimiter::StorkUserBCStepLimiter(std::vector* PeriodicBC, std::vector* ReflectBC, - const G4String &aName, G4String worldPhysName) -: G4StepLimiter(aName) -{ - worldName=worldPhysName; - nsProcMan = NULL; - pnInfo = NULL; - G4int offset[6]={0,0,0,0,0,0}; - G4ThreeVector n1, n2; - - for(G4int i=0; i<6; i++) - { - zeroSides.push_back(i); - BCTransform[i] = NULL; - } - - //BCTransform = new StorkBCTransform *[6]; - - for(G4int i=0; iGetName(); - G4VSolid *solidVol = aTrack.GetVolume()->GetLogicalVolume()->GetSolid(); - - // Check that the neutron is in the world volume - if(physVolName!=worldName) - { - return DBL_MAX; - } - - // Check that the neutron is ENTERING the world volume (rather than leaving) - G4ThreeVector curPos = aTrack.GetPosition (); - G4ThreeVector curMomDir = aTrack.GetMomentumDirection (); - G4ThreeVector n = solidVol->SurfaceNormal(curPos); - - int side = 0; - - for(G4int i=0; i<3; i++) - { - if(n[i]==1) - { - side=2*i; - } - else if(n[i]==-1) - { - side=2*i+1; - } - } - - G4bool check=true; - for(G4int i=0; i=0.)&&(check)) - { - return DBL_MIN; - } - else - { - return DBL_MAX; - } -} - - -// IsApplicable() -// Check that the particle is a neutron, otherwise not applicable. -G4bool -StorkUserBCStepLimiter::IsApplicable(const G4ParticleDefinition &particle) -{ - G4String particleName = particle.GetParticleName(); - if(particleName=="neutron") - { - return true; - } - else - { - return false; - } - -} - - -// PostStepDoIt() -// Result of StorkUserBCStepLimiter acting on a neutron. An exact copy of -// the neutron is produced at the opposite boundary (other side of world volume) -// and the original is killed. -// ASSUMES A SYMMETRIC VOLUME -G4VParticleChange* -StorkUserBCStepLimiter::PostStepDoIt(const G4Track &aTrack, - const G4Step &aStep) -{ - aParticleChange.Initialize(aTrack); - G4VSolid *solidVol = aTrack.GetVolume()->GetLogicalVolume()->GetSolid(); - - G4StepPoint *preStepPoint = aStep.GetPreStepPoint(); - - G4ThreeVector newPos = preStepPoint->GetPosition (); - G4ThreeVector newMomDir = preStepPoint->GetMomentumDirection (); - G4ThreeVector n = solidVol->SurfaceNormal(newPos); - G4int side=-1; - - for(G4int i=0; i<3; i++) - { - if(n[i]==1) - { - side=2*i; - } - else if(n[i]==-1) - { - side=2*i+1; - } - } - - (BCTransform[side])->Transform(newPos, newMomDir); - - if(newMomDir==G4ThreeVector(0.,0.,0.)) - { - G4cout << "Bad Transform" << G4endl; - } - - // Create a new dynamic particle from the parent dynamic particle - G4DynamicParticle *newDynamicParticle = new G4DynamicParticle(); - *newDynamicParticle = *(aTrack.GetDynamicParticle()); - - // Create the primary neutron info for the primary particle - pnInfo = new StorkPrimaryNeutronInfo(); - - // Set the lifetime - pnInfo->SetLifeTime(aTrack.GetLocalTime()); - - //Get the NS process manager and use it to get the n_lambda data - nsProcMan = StorkProcessManager::GetStorkProcessManagerPtr(); - pnInfo->SetEta(nsProcMan->GetNumberOfInteractionLengthsLeft(aStep.GetStepLength())); - - // Create a new track info object and set the primary neutron info - trackInfo = new StorkTrackInfo(); - trackInfo->SetStorkPrimaryNeutronInfo(pnInfo); - - - // Find the time of the hit (time the secondary track starts at) - G4double timeStart = aTrack.GetGlobalTime(); - - // Create a track for the secondary - G4Track *newTrack = new G4Track(newDynamicParticle, timeStart, newPos); - - // Change Momentum Direction - newTrack->SetMomentumDirection(newMomDir); - - // Add track info to track - newTrack->SetUserInformation(trackInfo); - - // Add the secondary to the particle change - aParticleChange.AddSecondary(newTrack); - - // Kill the parent particle - aParticleChange.ProposeTrackStatus(fStopAndKill); - - return &aParticleChange; -} - -G4ThreeVector StorkUserBCStepLimiter::GetNormal(int side) -{ - G4ThreeVector n = G4ThreeVector(0.,0.,0.); - if(floor(double(side)/2)==ceil(double(side)/2)) - { - n[int(side/2)]=1; - } - else - { - n[int(side/2)]=-1; - } - - return n; -} - diff --git a/G4STORK/src/StorkVWorldConstructor.cc b/G4STORK/src/StorkVWorldConstructor.cc deleted file mode 100755 index 7a421ca7..00000000 --- a/G4STORK/src/StorkVWorldConstructor.cc +++ /dev/null @@ -1,282 +0,0 @@ -/* -StorkVWorldConstructor.cc - -Created by: Liam Russell -Date: 23-05-2012 -Modified: 11-03-2013 - -Source file for StorkVWorldConstructor class. - -*/ - -// Include header file -#include "StorkVWorldConstructor.hh" - - -// Constructor -StorkVWorldConstructor::StorkVWorldConstructor() -: worldLogical(0), worldPhysical(0), worldVisAtt(0) -{ - // Initialize member variables - geomChanged = true; - matChanged = true; - Initiation = true; - physChanged = false; - encWorldDim = G4ThreeVector(0.,0.,0.); - reactorDim = encWorldDim; - charPosition = new std::vector; -} - - -// Destructor -StorkVWorldConstructor::~StorkVWorldConstructor() -{ - // Destroy all materials, elements and isotopes - DestroyMaterials(); - - if(worldVisAtt) - delete worldVisAtt; -} - - -// DestroyMaterials() -// Delete all materials, elements, and isotopes -void StorkVWorldConstructor::DestroyMaterials() -{ - // Destroy all allocated materials, elements and isotopes - size_t i; - - G4MaterialTable *matTable = (G4MaterialTable*)G4Material::GetMaterialTable(); - for(i=0; isize(); i++) - { - if((*(matTable))[i]) - delete (*(matTable))[i]; - } - matTable->clear(); - - G4ElementTable *elemTable = (G4ElementTable*)G4Element::GetElementTable(); - for(i=0; isize(); i++) - { - if((*(elemTable))[i]) - delete (*(elemTable))[i]; - } - elemTable->clear(); - - G4IsotopeTable *isoTable = (G4IsotopeTable*)G4Isotope::GetIsotopeTable(); - for(i=0; isize(); i++) - { - if((*(isoTable))[i]) - delete (*(isoTable))[i]; - } - isoTable->clear(); - - return; -} - - -// GetWorldProperty() -// Returns the current world property associated with the given MatPropPair -G4double StorkVWorldConstructor::GetWorldProperty(MatPropPair matProp) -{ - if (IsApplicable(matProp)) - { - return *(variablePropMap[matProp]) / theMPMan->GetUnits(matProp.second); - } - else - { - return -1.0; - } -} - - -// IsApplicable() -// Determines whether the given material and property pair is valid in the -// current world -G4bool StorkVWorldConstructor::IsApplicable(MatPropPair matProp) -{ - if(variablePropMap.find(matProp)==variablePropMap.end()) - return false; - else - return true; -} - - -// ConstructNewWorld() -// Set the initial properties (material-properties), sensitive detector, -// and neutron filter for the sensitive detector. Then construct the world -// using a derived class implementation of ConstructWorld(). -G4VPhysicalVolume* -StorkVWorldConstructor::ConstructNewWorld(const StorkParseInput* infile) -{ - // Get any initial changes (vector may be empty) - initialChanges = infile->GetIntialWorldProperties(); - - // Build sensitive detector - G4SDManager *sDMan = G4SDManager::GetSDMpointer(); - sDReactor = new StorkNeutronSD("Reactor", infile->GetKCalcType(), infile->GetInstantDelayed(), infile->GetPrecursorDelayed()); - sDMan->AddNewDetector(sDReactor); - - // Add filters to the sensitive detectors so that they only track neutrons - G4SDParticleFilter *nFilter = new G4SDParticleFilter("neutronFilter", - "neutron"); - sDReactor->SetFilter(nFilter); - - - // Add any initial changes to the world properties - if(G4int(initialChanges.size()) > 0) - UpdateWorldProperties(initialChanges); - - return ConstructWorld(); -} - - -// UpdateWorld() -// Update the variable material-properties. -G4VPhysicalVolume* -StorkVWorldConstructor::UpdateWorld(StorkMatPropChangeVector changes) -{ - if(UpdateWorldProperties(changes)) - { - return ConstructWorld(); - } - else - { - return worldPhysical; - } -} - - -// UpdateWorldProperties() -// Check whether ALL of the proposed changes are valid. If so, apply the -// changes. -G4bool -StorkVWorldConstructor::UpdateWorldProperties(StorkMatPropChangeVector changes) -{ - // Check whether proposed changes are applicable to the world - for(G4int i=0; iGetPropType(changes[i].GetMatPropPair().second) == "material") - { - physChanged = true; - matChanged = true; - } - // Change the variable properties - *(variablePropMap[changes[i].GetMatPropPair()]) = changes[i].change; - changed = true; - } - } - - return changed; -} - - - -// SaveMaterialTemperatureHeader() -// Outputs the header of the temperature data file -void -StorkVWorldConstructor::SaveMaterialTemperatureHeader(G4String fname) -{ - // Declare and open file stream - std::ofstream outFile(fname.c_str(),std::ofstream::app); - - // Check that stream is ready for use - if(!outFile.good()) - { - G4cerr << G4endl << "ERROR: Could not write material temperatures to file. " << G4endl - << "Improper file name: " << fname << G4endl - << "Continuing program without material temperature data output" << G4endl; - - return; - } - - outFile.fill(' '); - outFile << "All temperatures are given in Kelvin." << G4endl; - outFile << "#########################################################" << G4endl; - outFile << "Run # "; - - // Cycle through all the elements of the map and output the name of each material - for(std::map::iterator it = matMap.begin(); it != matMap.end(); it++) - { - // Need at least 6 space to output the number 5 significant digits and comma - if((*it).first.size() < 6) - { - outFile << std::setw(6) << (*it).first << " "; - charPosition->push_back(6); - } - else - { - outFile << (*it).first << " "; - charPosition->push_back((*it).first.size()); - } - } - outFile << G4endl; - outFile.close(); -} - - -// SaveMaterialTemperatures() -// Outputs temperatures to file specified in StorkParseInput -void -StorkVWorldConstructor::SaveMaterialTemperatures(G4String fname, G4int runNumber) -{ - // Declare and open file stream - std::ofstream outFile(fname.c_str(),std::ofstream::app); - - // Check that stream is ready for use - if(!outFile.good()) - { - G4cerr << G4endl << "ERROR: Could not write material temperatures to file. " << G4endl - << "Improper file name: " << fname << G4endl - << "Continuing program without material temperature data output" << G4endl; - - return; - } - - outFile.fill(' '); - G4int matNum = 0; - - // Print the run number - outFile << std::setw(5) << runNumber << " "; - - // Print the temperature of all the material one after the other - for(std::map::iterator it = matMap.begin(); it != matMap.end(); it++) - { - if(matNum < G4int(charPosition->size())) - { - outFile << std::resetiosflags(std::ios_base::floatfield) << std::right - << std::setprecision(5) - << std::setw((*charPosition)[matNum]) << (*it).second->GetTemperature() << " "; - matNum++; - } - - // This is in case the length of the matMap changed from when the header was created - else - { - outFile << std::resetiosflags(std::ios_base::floatfield) << std::right - << std::setprecision(5) - << std::setw(12) << (*it).second->GetTemperature() << " "; - } - - } - outFile << G4endl; - outFile.close(); -} diff --git a/G4STORK/src/StorkWorld.cc b/G4STORK/src/StorkWorld.cc deleted file mode 100755 index 548f3345..00000000 --- a/G4STORK/src/StorkWorld.cc +++ /dev/null @@ -1,275 +0,0 @@ -/* -StorkWorld.cc - -Created by: Liam Russell -Date: 17-02-2011 -Modified: 11-03-2013 - -Source code for the StorkWorld class. - -*/ - - -// Include header file - -#include "StorkWorld.hh" - -// Include headers here to avoid circular reference with StorkVWorldConstructor -#include "BareSphereConstructor.hh" -#include "C6LatticeConstructor.hh" -#include "InfiniteUniformLatticeConstructor.hh" -#include "ZED2Constructor.hh" -#include "SLOWPOKEConstructor.hh" -#include "SCWRConstructor.hh" -#include "SCWRDopplerConstructor.hh" -#include "SCWRJasonConstructor.hh" -#include "Q_ZED2Constructor.hh" -//#include "DebugConstructor.hh" -#include "TestConstructor.hh" - - -// Overloaded Constructor -StorkWorld::StorkWorld(const StorkParseInput* infile) -: worldPhysical(0), theWorld(0) -{ - // Add the three basic worlds to the world map - AddWorld("C6Lattice", new C6LatticeConstructor()); - AddWorld("Sphere", new BareSphereConstructor()); - AddWorld("Cube", new InfiniteUniformLatticeConstructor()); - AddWorld("ZED2", new ZED2Constructor()); - AddWorld("SLOWPOKE", new SLOWPOKEConstructor()); - AddWorld("SCWR", new SCWRConstructor()); - AddWorld("SCWRJason", new SCWRJasonConstructor()); - AddWorld("SCWRDoppler", new SCWRDopplerConstructor()); - AddWorld("Q_ZED2", new Q_ZED2Constructor()); -// AddWorld("Debug", new DebugConstructor()); - AddWorld("Test", new TestConstructor()); - - // Copy user inputs - inFile = infile; - worldName = infile->GetWorld(); -} - -StorkWorld::StorkWorld() -: worldPhysical(0), theWorld(0) -{ - // Add the three basic worlds to the world map - AddWorld("C6Lattice", new C6LatticeConstructor()); - AddWorld("Sphere", new BareSphereConstructor()); - AddWorld("ZED2", new ZED2Constructor()); - AddWorld("Cube", new InfiniteUniformLatticeConstructor()); - AddWorld("SLOWPOKE", new SLOWPOKEConstructor()); - AddWorld("SCWR", new SCWRConstructor()); - AddWorld("SCWRJason", new SCWRJasonConstructor()); - AddWorld("SCWRDoppler", new SCWRDopplerConstructor()); - AddWorld("Q_ZED2", new Q_ZED2Constructor()); -// AddWorld("Debug", new DebugConstructor()); - AddWorld("Test", new TestConstructor()); -} - -// Destructor -StorkWorld::~StorkWorld() -{ -// // Delete all materials, elements and isotopes -// delete theWorld; - - // Delete the worlds - StorkWorldMap::iterator itr = availableWorlds.begin(); - - while(itr != availableWorlds.end()) - { - delete itr->second; - itr++; - } - - availableWorlds.clear(); -} - - -void StorkWorld::InitializeWorldData(const StorkParseInput* infile) -{ - // Copy user inputs - inFile = infile; - worldName = infile->GetWorld(); -} - -void StorkWorld::InitializeWorldData(G4String worlnam) -{ - // Copy user inputs - - worldName = worlnam; -} - -// Construct() -// Use one of the constructors to build the world. -G4VPhysicalVolume* StorkWorld::Construct() -{ - // Set the world constructor - theWorld = availableWorlds[worldName]; - - if(!theWorld) - { - G4cerr << "***ERROR: " << worldName - << " is not one of the available worlds." << G4endl; - - return NULL; - } - - // Build the world - worldPhysical = theWorld->ConstructNewWorld(inFile); - - return worldPhysical; -} - - -// AddWorld() -// Add world to the available worlds map -void StorkWorld::AddWorld(G4String name, StorkVWorldConstructor *aNewWorld) -{ - availableWorlds[name] = aNewWorld; -} - - -// UpdateWorld() -// Updates the simulation world using a vector of proposed changes -G4VPhysicalVolume* StorkWorld::UpdateWorld(StorkMatPropChangeVector theChanges) -{ - return theWorld->UpdateWorld(theChanges); -} - -// HasMatChanged() -// Returns the value of matChanged in the world class -G4bool StorkWorld::HasMatChanged() -{ - return theWorld->HasMatChanged(); -} - -// HasPhysChanged() -// Returns the calue of physChanged in the world calss -G4bool StorkWorld::HasPhysChanged() -{ - return theWorld->HasPhysChanged(); -} - -// SetPhysChanged() -// Sets the value of physChanged in the world class -void StorkWorld::SetPhysChanged(G4bool value) -{ - theWorld->SetPhysChanged(value); -} - - -// EvaluateHeatCapacities() -// Output material temperature header to specified file in Input file -void StorkWorld::SaveMaterialTemperatureHeader(G4String fname) -{ - theWorld->SaveMaterialTemperatureHeader(fname); -} - -// EvaluateHeatCapacities() -// Output materials temperature to specified file in Input file -void StorkWorld::SaveMaterialTemperatures(G4String fname, G4int runNumber) -{ - theWorld->SaveMaterialTemperatures(fname, runNumber); -} - -// GetWorldBoxDimensions() -// Get dimensions of smallest box enclosing the simulation world -G4ThreeVector StorkWorld::GetWorldBoxDimensions() -{ - return theWorld->GetEncWorldDim(); -} - - -// GetWorldDimensions() -// Get the dimensions of the world -G4ThreeVector StorkWorld::GetWorldDimensions() -{ - return theWorld->GetReactorDim(); -} - - -// GetWorldProperty() -// Get the current value of a material-property in the simulation world -G4double StorkWorld::GetWorldProperty(MatPropPair matProp) -{ - return theWorld->GetWorldProperty(matProp); -} - - -// GetLogicalVolume() -// Get the world logical volume -G4LogicalVolume* StorkWorld::GetWorldLogicalVolume() -{ - return theWorld->GetWorldLogical(); -} - -// GetMaterialMap() -// Get the world material map -StorkMaterialMap* StorkWorld::GetMaterialMap(void) -{ - return theWorld->GetMaterialMap(); -} - -// DumpGeometricalTree() -// Public - prints entire geometry -void StorkWorld::DumpGeometricalTree() -{ - DumpGeometricalTree(worldPhysical); -} - - -// DumpGeometricalTree() -// Private - Print the geometrical tree of the world -void StorkWorld::DumpGeometricalTree(G4VPhysicalVolume *vol, - G4int depth) -{ - for(G4int i=0; iGetName() << "[" << vol->GetCopyNo() << "] " - << vol->GetLogicalVolume()->GetName() << " " - << vol->GetLogicalVolume()->GetNoDaughters() << " " - << vol->GetLogicalVolume()->GetMaterial()->GetName(); - - if(vol->GetLogicalVolume()->GetSensitiveDetector()) - { - G4cout << " " << vol->GetLogicalVolume()->GetSensitiveDetector() - ->GetFullPathName(); - } - - G4cout << G4endl; - for(int i=0;iGetLogicalVolume()->GetNoDaughters();i++) - { - DumpGeometricalTree(vol->GetLogicalVolume()->GetDaughter(i),depth+1); - } - - G4cout << G4endl; -} - -void StorkWorld::SetMatChanged(G4bool value) -{ - theWorld->SetMatChanged(value); -} - -G4ThreeVector StorkWorld::GetFuelDimensions() -{ - return theWorld->GetFuelDimensions(); -} - -G4double* StorkWorld::GetFuelTemperatures() -{ - return theWorld->GetFuelTemperatures(); -} - -G4double* StorkWorld::GetFuelDensities() -{ - return theWorld->GetFuelDensities(); -} - -G4double* StorkWorld::GetFuelRadii() -{ - return theWorld->GetFuelRadii(); -} diff --git a/G4STORK/src/StorkZeroBCStepLimiter.cc b/G4STORK/src/StorkZeroBCStepLimiter.cc deleted file mode 100755 index 047881ac..00000000 --- a/G4STORK/src/StorkZeroBCStepLimiter.cc +++ /dev/null @@ -1,125 +0,0 @@ -#include "StorkZeroBCStepLimiter.hh" - -// Constructor() -// Calls the G4StepLimiter constructor with the proper name -StorkZeroBCStepLimiter::StorkZeroBCStepLimiter(std::vector* PeriodicBC, std::vector* ReflectBC, - const G4String &aName, G4String worldPhysName) -: G4StepLimiter(aName) -{ - worldName=worldPhysName; - nsProcMan = NULL; - pnInfo = NULL; - G4int offset[6]={0,0,0,0,0,0}; - - for(G4int i=0; i<6; i++) - { - zeroSides.push_back(i); - } - - for(G4int i=0; iGetName(); - G4VSolid *solidVol = aTrack.GetVolume()->GetLogicalVolume()->GetSolid(); - - // Check that the neutron is in the world volume - if(physVolName!=worldName) - { - return DBL_MAX; - } - - // Check that the neutron is ENTERING the world volume (rather than leaving) - G4ThreeVector curPos = aTrack.GetPosition (); - G4ThreeVector curMomDir = aTrack.GetMomentumDirection (); - G4ThreeVector n = solidVol->SurfaceNormal(curPos); - - int side = 0; - - for(G4int i=0; i<3; i++) - { - if(n[i]==1) - { - side=2*i; - } - else if(n[i]==-1) - { - side=2*i+1; - } - } - - for(G4int i=0; iOpenGeometry(); - G4PhysicalVolumeStore::GetInstance()->Clean(); - G4LogicalVolumeStore::GetInstance()->Clean(); - - // Set up the solids if necessary - if(geomChanged) - { - // Clean up solids - G4SolidStore::GetInstance()->Clean(); - - // Set static dimensions - //Note the format for cylinder dimensions is (inner radius, outer radius, height) - - // Reactor pool dimensions - G4double buffer = 1.0*cm; - // reactor dimension specifies the dimension of the volume for the uniform distribution - reactorDim = G4ThreeVector(0., 11.049*cm, 22.748*cm); - - G4ThreeVector cellDim = G4ThreeVector(0., 133.0*cm, 564.0*cm); - - // World dimensions - encWorldDim = G4ThreeVector(cellDim[2]+buffer,cellDim[2]+buffer, cellDim[2]+buffer); - - // Lattice cell dimensions - // hole pattern format radius, angle of increment and the offset angle, check radius - G4double sheatheDim[3] = {0., 0.262*cm , 1*cm}; - G4double gridPlateDim[3] = {1.331*cm, 11.049*cm, 0.279*cm}; - //G4double unitRegionDim[6]={0, (gridPlateDim[1]-gridPlateDim[0])/10, 0., CLHEP::pi/(3*10), 0., 0.3*cm}; - //G4double regionDim[6]={gridPlateDim[0], gridPlateDim[1], CLHEP::pi/3, 2*CLHEP::pi/3, -gridPlateDim[2]/2, gridPlateDim[2]/2}; - - - //Geometry positioning data - std::stringstream latticeType1; - G4ThreeVector latCellPos; - G4ThreeVector holePos; - G4ThreeVector holeRPos; - - // Create world solid - new G4Box("worldBox", encWorldDim[0]/2, encWorldDim[1]/2, encWorldDim[2]/2); - - // Create cell solid - new G4Tubs("cellTube", 0., cellDim[1], cellDim[2]/2, 0., 2.0*CLHEP::pi); - - //creates the base zirconium grid slice that the holes will be subtracted from to form the upper and lower grid plate - new G4Tubs("gridPlate", gridPlateDim[0], gridPlateDim[1], gridPlateDim[2]/2, CLHEP::pi/3, CLHEP::pi/3); - - new G4Tubs("sheatheTube", sheatheDim[0], sheatheDim[1], sheatheDim[2]/2, 0., 2.0*CLHEP::pi); - - //test = new G4UnionSolid("TestSolid1",theSolids->GetSolid("sheatheTube"),theSolids->GetSolid("sheatheTube"), 0, G4ThreeVector(1.0*cm,1.0*cm,0.)); - - test = new StorkUnionSolid("TestSolid1",theSolids->GetSolid("sheatheTube"),theSolids->GetSolid("sheatheTube"), 0, G4ThreeVector(1.0*cm,1.0*cm,0.) - ,cylUnit, StorkSixVector(0.,4.*cm,0.,2*CLHEP::pi,-2.0*cm, 2.0*cm),G4ThreeVector(0.*cm,2.0*cm,0.)); - - // test = new StorkUnionSolid("TestSolid2",theSolids->GetSolid("gridPlate"),theSolids->GetSolid("TestSolid1"), 0, G4ThreeVector(0.*cm,2.0*cm,0.) - // ,cylUnit, StorkSixVector(0.,4.*cm,0.,1*CLHEP::pi,-2.0*cm, 2.0*cm),G4ThreeVector(0.,0.,0.)); - -//// new StorkUnionSolid("TestSolid",theSolids->GetSolid("sheatheTube"),theSolids->GetSolid("sheatheTube"), 0, G4ThreeVector(1.0*cm,1.0*cm,0.) -//// ,cylUnit, StorkSixVector(0.,4.*cm,0.,0.5*CLHEP::pi,-2.0*cm, 2.0*cm),G4ThreeVector(0.,0.,0.)); -//// -//// new StorkUnionSolid("TestSolid2",theSolids->GetSolid("TestSolid"),theSolids->GetSolid("sheatheTube"), 0, G4ThreeVector(-1.0*cm,1.0*cm,0.) -//// ,cylUnit, StorkSixVector(0.,4.*cm,0.,CLHEP::pi,-2.0*cm, 2.0*cm),G4ThreeVector(0.,0.,0.)); -//// -//// new StorkUnionSolid("TestSolid3",theSolids->GetSolid("TestSolid2"),theSolids->GetSolid("sheatheTube"), 0, G4ThreeVector(-1.0*cm, -1.0*cm,0.) -//// ,cylUnit, StorkSixVector(0.,4.*cm,0.,1.5*CLHEP::pi,-2.0*cm, 2.0*cm),G4ThreeVector(0.,0.,0.)); -//// -//// test = new StorkUnionSolid("TestSolid4",theSolids->GetSolid("TestSolid3"),theSolids->GetSolid("sheatheTube"), 0, G4ThreeVector(1.0*cm,-1.0*cm,0.) -//// ,cylUnit, StorkSixVector(0.,4.*cm,0.,2*CLHEP::pi,-2.0*cm, 2.0*cm),G4ThreeVector(0.,0.,0.)); -// -//// solidList sheatheTubes; -// -// G4int regionIndices[3]; -// regionIndices[0] = ceil((regionDim[1]-regionDim[0])/(unitRegionDim[1]-unitRegionDim[0])); -// regionIndices[1] = ceil((regionDim[3]-regionDim[2])/(unitRegionDim[3]-unitRegionDim[2])); -// regionIndices[2] = ceil((regionDim[5]-regionDim[4])/(unitRegionDim[5]-unitRegionDim[4])); -// -// unitRegionDim[0] = regionDim[1]-(regionDim[1]-regionDim[0])/(regionIndices[0]); -// unitRegionDim[1] = regionDim[1]; -// unitRegionDim[2] = regionDim[3]-(regionDim[3]-regionDim[2])/(regionIndices[1]); -// unitRegionDim[3] = regionDim[3]; -// unitRegionDim[4] = regionDim[5]-(regionDim[5]-regionDim[4])/(regionIndices[2]); -// unitRegionDim[5] = regionDim[5]; -// -// G4double unitRegDim[6]; -// intVec elemsRow(regionIndices[0], 0); -// G4int count=0; -// -// for(G4int i=0; i unitRegDimTemp(unitRegDim); -// holeRPos={(unitRegDimTemp[1]+unitRegDimTemp[0])/2,(unitRegDimTemp[3]+unitRegDimTemp[2])/2,(unitRegDimTemp[5]+unitRegDimTemp[4])/2}; -// holePos.setRhoPhiZ(holeRPos[0],holeRPos[1],holeRPos[2]); -// latticeType1.str(""); -// latticeType1 << count; -// count++; -// test = new G4UnionSolid("TestSolid"+latticeType1.str(),test, theSolids->GetSolid("sheatheTube"), 0, holePos); -//// ,cylUnit, regionDim, G4ThreeVector(0.,0.,0.)); -//// sheatheTubes.push_back(solidPos(theSolids->GetSolid("sheatheTube"),holePos)); -// -// } -// } -// } -// -//// UnionBinaryTree* sheatheTubeLat = new UnionBinaryTree(&sheatheTubes); -//// -//// sheatheTubeLatPair = sheatheTubeLat->GetUnionSolid("sheatheTubeLat", 0, cylUnit, unitRegionDim, regionDim, 0.0, radCyl, 1.0, NULL, true); -// -// // creates the upGridPlate and the lowGridPlate from the unions of the upGridHolesLat and lowGridHolesLat with the base gridPlate -//// new G4SubtractionSolid("upGridPlate", theSolids->GetSolid("gridPlate"), upGridHolesLatPair.first, 0, upGridHolesLatPair.second); -//// new G4SubtractionSolid("lowGridPlate", theSolids->GetSolid("gridPlate"), lowGridHolesLatPair.first, 0, lowGridHolesLatPair.second); -//// -//// // creates the zirconium grid slice (zircGridPlate) from the union of the upGridPlate and the lowGridPlate -//// new G4UnionSolid("zircGridSliceP1", theSolids->GetSolid("upGridPlate"), theSolids->GetSolid("lowGridPlate"), 0, disUpGridToLowGrid); -//// gridSlice = new G4UnionSolid("zircGridSlice", theSolids->GetSolid("gridPlate"), sheatheTubeLatPair.first, 0, sheatheTubeLatPair.second); - - geomChanged = false; - std::vector *Check = dynamic_cast*>(theSolids); - for(G4int i=0; isize()); i++) - { - G4cout << "\n ###" << ((*Check)[i])->GetName() << " " << ((*Check)[i])->GetEntityType() <<" ### \n"; - } - latticeType1.str(""); - } - - //Initialize stringstream for volume naming purposes - std::stringstream volName; - // Initialize positioning objects - G4ThreeVector volPos; - - // Create world volume - worldLogical = new G4LogicalVolume(theSolids->GetSolid("worldBox"), - matMap["Galactic"],"worldLogical"); - worldPhysical = new G4PVPlacement(0, G4ThreeVector(0,0,0.), worldLogical, - "worldPhysical",0,0,0); - - // Create the lattice cell (moderator) volume - cellLogical = new G4LogicalVolume(theSolids->GetSolid("cellTube"), - matMap["H2O"],"cellLogical"); - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), cellLogical,"cellPhysical", - worldLogical,0,0); - - // //create Zirconium grid plates - zircGridLogical = new G4LogicalVolume(theSolids->GetSolid("TestSolid1"), matMap["Zirconium"], "zircGridLogical"); - - new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), zircGridLogical,"zircGridSlicePhysical", - cellLogical,0,0,0); - - // Add sensitive detector to ALL logical volumes - worldLogical->SetSensitiveDetector( sDReactor ); - cellLogical->SetSensitiveDetector( sDReactor ); - - zircGridLogical->SetSensitiveDetector( sDReactor ); - - // Set visualization attributes - - if(worldVisAtt) - delete worldVisAtt; - if(cellVisAtt) - delete cellVisAtt; - if(zircGridVisAtt) - delete zircGridVisAtt; - - worldVisAtt = new G4VisAttributes(G4Colour(1.,1.,1.)); - worldVisAtt->SetVisibility(false); - worldLogical->SetVisAttributes(worldVisAtt); - -// light blue - cellVisAtt = new G4VisAttributes(G4Colour(47.0/255.0,225.0/255.0,240.0/255.0)); - cellVisAtt->SetVisibility(false); - cellLogical->SetVisAttributes(cellVisAtt); - - - - zircGridVisAtt = new G4VisAttributes(G4Colour(0.,0.,1.)); - zircGridVisAtt->SetVisibility(true); - zircGridLogical->SetVisAttributes(zircGridVisAtt); - - return worldPhysical; -} - - -// ConstructMaterials() -// Define and build the materials in the C6 lattice cell. -void TestConstructor::ConstructMaterials() -{ -// Density Of Defined Materials - G4double ReflectorDensity = 1.85*g/cm3; - G4double LWDensity = 0.998*g/cm3; - G4double FuelDensity = 10.6*g/cm3; - G4double AirDensity = 5.0807e-5*g/cm3; - G4double ZrDensity = 6.49*g/cm3; - G4double AlAlloyDensity = 2.70*g/cm3; - G4double CadmiumDensity = 8.65*g/cm3; - G4double HWDensity = 1.105*g/cm3; - - // Temperature Of Defined Materials - // using data from 20043405 - G4double ReflectorTemp=(22.5+273.15); - G4double LWTemp=(30.6+273.15); - G4double FuelTemp=(57.32+273.15); - G4double AirTemp=(18.0+273.15); - G4double ZrTemp=(52.14+273.15); - G4double AlAlloyTemp1=(20.0+273.15); - G4double AlAlloyTemp2=(21.0+273.15); - G4double AlAlloyTemp3=(22.0+273.15); - G4double AlAlloyTemp4=(48.0+273.15); - G4double CadmiumTemp=(50.0+273.15); - G4double HWTemp=(20.5+273.15); - - // Defining all the pointers - G4Isotope *C12, *C13, *N14, *N15, *O16, *O17, /*O18,*/ *Mg24, - *Mg25, *Mg26, *Al27, *Si28, *Si29, *Si30, *Cr50, - *Cr52, *Cr53, *Cr54, *Mn55, *Fe54, *Fe56, *Fe57, - *Fe58, *Cu63, *Cu65, *Zr90, *Zr91, *Zr92, *Zr94, - *Zr96, *Cd106, *Cd108, *Cd110, *Cd111, *Cd112, - *Cd113, *Cd114, *Cd116, *U235, *U238; - G4Element *H1, *D2, *Be, *Li6, *Li7, *B10, *B11, *C, *N, *Oxygen, - *Mg, *Al, *Si, *Cr, *Mn, *Fe, *Cu, *Zirc, *ECd112, - *ECd113, *Cd, *In115, *Sm148, *Sm149, *Sm150, *Sm152, - *Gd155, *Gd157, *Eu151, *Eu153, *Ir191, *Ir193,*LEU; - G4Material *World, *Air, *Reflector, *LW, *Fuel, *Zr, *AlAlloy1, - *AlAlloy2, *AlAlloy3, *AlAlloy4, *Cadmium, *HW; - -// G4NistManager* manager = G4NistManager::Instance(); - - // Hydrogen And Isotopes - H1 = new G4Element("Hydrogen1", "H1", 1); - H1->AddIsotope(new G4Isotope("H1", 1, 1, 1.0078250321*g/mole), 1); - D2 = new G4Element("Hydrogen2", "H2", 1); - D2->AddIsotope(new G4Isotope("H2", 1, 2, 2.0141017780*g/mole), 1); - - // Lithium Isotopes - Li6 = new G4Element("Lithium6", "Li6", 1); - Li6->AddIsotope(new G4Isotope("Li6", 3, 6, 6.0151223*g/mole), 1); - Li7 = new G4Element("Lithium7", "Li7", 1); - Li7->AddIsotope(new G4Isotope("Li7", 3, 7, 7.0160040*g/mole), 1); - - // Berylium And Isotopes - Be = new G4Element("Berylium", "Be", 1); - Be->AddIsotope(new G4Isotope("Be9", 4, 9, 9.0121822*g/mole), 1); - - // Boron Isotopes - B10 = new G4Element("Boron10", "B10", 1); - B10->AddIsotope(new G4Isotope("B10", 5, 10, 10.012937*g/mole), 1); - B11 = new G4Element("Boron11", "B11", 1); - B11->AddIsotope(new G4Isotope("B11", 5, 11, 11.009305*g/mole), 1); - - // Making Carbon isotopes - C12 = new G4Isotope("C12", 6, 12, 12.000000*g/mole); - C13 = new G4Isotope("C13", 6, 13, 13.003354*g/mole); - - // Naturally occuring Carbon -// C = manager->FindOrBuildElement(6); - C = new G4Element("Carbon", "C", 2); - C->AddIsotope(C12, 98.93*perCent); - C->AddIsotope(C13, 1.07*perCent); - - // Nitrogen Isotopes - N14 = new G4Isotope("N14", 7, 14, 14.0030740052*g/mole); - N15 = new G4Isotope("N15", 7, 15, 15.0001088984*g/mole); - - // Naturally occuring Nitrogen - N = new G4Element("Nitrogen", "N", 2); - N->AddIsotope(N14, 99.632*perCent); - N->AddIsotope(N15, 0.368*perCent); - - // Make oxygen isotope and element - O16 = new G4Isotope("O16", 8, 16, 15.995*g/mole); - O17 = new G4Isotope("O17", 8, 17, 16.999*g/mole); -// O18 = new G4Isotope("O18", 8, 18, 17.999*g/mole); - - // Natural occuring oxygen - Oxygen = new G4Element("Oxygen", "O", 2); - Oxygen->AddIsotope(O16, 99.962*perCent); - Oxygen->AddIsotope(O17, 0.038*perCent); -// Oxygen->AddIsotope(O18, 0.205*perCent); - - // Magnesium Isotopes - Mg24 = new G4Isotope("Mg24", 12, 24, 23.9850423*g/mole); - Mg25 = new G4Isotope("Mg25", 12, 25, 24.9858374*g/mole); - Mg26 = new G4Isotope("Mg26", 12, 26, 25.9825937*g/mole); - - // Naturally Occuring Magnesium - Mg = new G4Element("Magnesium", "Mg", 3); - Mg->AddIsotope(Mg24, 78.99*perCent); - Mg->AddIsotope(Mg25, 10.00*perCent); - Mg->AddIsotope(Mg26, 11.01*perCent); - - // Making Aluminum Isotopes - Al27 = new G4Isotope("Al27", 13, 27, 26.9815386*g/mole); - - // Naturally occuring Aluminum - Al = new G4Element("Aluminum", "Al", 1); - Al->AddIsotope(Al27, 1); - - // Making Silicon Isotopes - Si28 = new G4Isotope("Si28", 14, 28, 27.9769271*g/mole); - Si29 = new G4Isotope("Si29", 14, 29, 28.9764949*g/mole); - Si30 = new G4Isotope("Si30", 14, 30, 29.9737707*g/mole); - - // Naturally occuring Silicon - Si = new G4Element("Silicon", "Si", 3); - Si->AddIsotope(Si28, 92.2297*perCent); - Si->AddIsotope(Si29, 4.6832*perCent); - Si->AddIsotope(Si30, 3.0871*perCent); - - // Chromium Isotopes - Cr50 = new G4Isotope("Cr50", 24, 50, 49.9460464*g/mole); - Cr52 = new G4Isotope("Cr52", 24, 52, 51.9405098*g/mole); - Cr53 = new G4Isotope("Cr53", 24, 53, 52.9406513*g/mole); - Cr54 = new G4Isotope("Cr54", 24, 54, 53.9388825*g/mole); - - // Naturally Occuring Chromium - Cr = new G4Element("Chromium", "Cr", 4); - Cr->AddIsotope(Cr50, 4.345*perCent); - Cr->AddIsotope(Cr52, 83.789*perCent); - Cr->AddIsotope(Cr53, 9.501*perCent); - Cr->AddIsotope(Cr54, 2.365*perCent); - - // Manganese Isotopes - Mn55 = new G4Isotope("Mn55", 25, 55, 54.9380471*g/mole); - - // Naturally occuring Manganese - Mn = new G4Element("Manganese", "Mn", 1); - Mn->AddIsotope(Mn55, 1.); - - // Making Iron Isotopes - Fe54 = new G4Isotope("Fe54", 26, 54, 53.9396127*g/mole); - Fe56 = new G4Isotope("Fe56", 26, 56, 55.9349393*g/mole); - Fe57 = new G4Isotope("Fe57", 26, 57, 56.9353958*g/mole); - Fe58 = new G4Isotope("Fe58", 26, 58, 57.9332773*g/mole); - - // Naturally Occuring Iron - Fe = new G4Element("Iron", "Fe", 4); - Fe->AddIsotope(Fe54, 5.845*perCent); - Fe->AddIsotope(Fe56, 91.754*perCent); - Fe->AddIsotope(Fe57, 2.119*perCent); - Fe->AddIsotope(Fe58, 0.282*perCent); - - // Copper Isotopes - Cu63 = new G4Isotope("Cu63", 29, 63, 62.9295989*g/mole); - Cu65 = new G4Isotope("Cu65", 29, 65, 64.9277929*g/mole); - - // Naturally Occuring Copper - Cu = new G4Element("Copper", "Cu", 2); - Cu->AddIsotope(Cu63, 69.17*perCent); - Cu->AddIsotope(Cu65, 30.83*perCent); - - // Making Zirconium isotopes and elements - Zr90 = new G4Isotope("Zr90", 40, 90, 89.9047044*g/mole); - Zr91 = new G4Isotope("Zr91", 40, 91, 90.9056458*g/mole); - Zr92 = new G4Isotope("Zr92", 40, 92, 91.9050408*g/mole); - Zr94 = new G4Isotope("Zr94", 40, 94, 93.9063152*g/mole); - Zr96 = new G4Isotope("Zr96", 40, 96, 95.9082734*g/mole); - - // Natural Zirconium composition - Zirc = new G4Element("Zirconium", "Zr", 5); - Zirc->AddIsotope(Zr90, 50.706645*perCent); - Zirc->AddIsotope(Zr91, 11.180922*perCent); - Zirc->AddIsotope(Zr92, 17.277879*perCent); - Zirc->AddIsotope(Zr94, 17.890875*perCent); - Zirc->AddIsotope(Zr96, 2.943679*perCent); - - // Cadmium Isotopes - Cd106 = new G4Isotope("Cd106", 48, 106, 105.906461*g/mole); - Cd108 = new G4Isotope("Cd108", 48, 108, 107.904176*g/mole); - Cd110 = new G4Isotope("Cd110", 48, 110, 109.903005*g/mole); - Cd111 = new G4Isotope("Cd111", 48, 111, 110.904182*g/mole); - Cd112 = new G4Isotope("Cd112", 48, 112, 111.902757*g/mole); - Cd113 = new G4Isotope("Cd113", 48, 113, 112.904400*g/mole); - Cd114 = new G4Isotope("Cd114", 48, 114, 113.903357*g/mole); - Cd116 = new G4Isotope("Cd116", 48, 116, 115.904755*g/mole); - - - // Cadmium Isotopes - ECd112 = new G4Element("Cadmium112", "Cd112", 1); - ECd112->AddIsotope(Cd112, 1); - ECd113 = new G4Element("Cadmium113", "Cd113", 1); - ECd113->AddIsotope(Cd113, 1); - - // Naturally Occuring Cadmium - Cd = new G4Element("Cadmium", "Cd", 8); - Cd->AddIsotope(Cd106, 1.25*perCent); - Cd->AddIsotope(Cd108, 0.89*perCent); - Cd->AddIsotope(Cd110, 12.49*perCent); - Cd->AddIsotope(Cd111, 12.80*perCent); - Cd->AddIsotope(Cd112, 24.13*perCent); - Cd->AddIsotope(Cd113, 12.22*perCent); - Cd->AddIsotope(Cd114, 28.73*perCent); - Cd->AddIsotope(Cd116, 7.49*perCent); - - // Indium Isotopes - In115 = new G4Element("Indium115", "In115", 1); - In115->AddIsotope(new G4Isotope("In115", 49, 115, 114.903882*g/mole), 1); - - // Samarium Isotopes (Note: Could not get info on Sm137) - Sm148 = new G4Element("Samatium148", "Am148", 1); - Sm148->AddIsotope(new G4Isotope("Sm148", 62, 148, 147.914819*g/mole), 1); - Sm149 = new G4Element("Samatium149", "Am149", 1); - Sm149->AddIsotope(new G4Isotope("Sm149", 62, 149, 149.917180*g/mole), 1); - Sm150 = new G4Element("Samatium150", "Am150", 1); - Sm150->AddIsotope(new G4Isotope("Sm150", 62, 150, 149.917273*g/mole), 1); - Sm152 = new G4Element("Samatium152", "Am152", 1); - Sm152->AddIsotope(new G4Isotope("Sm152", 62, 152, 151.919728*g/mole), 1); - - // Gadolium Isotopes - Gd155 = new G4Element("Gadolinium155", "Gd155", 1); - Gd155->AddIsotope(new G4Isotope("Gd155", 64, 155, 154.922618*g/mole), 1); - Gd157 = new G4Element("Gadolinium157", "Gd157", 1); - Gd157->AddIsotope(new G4Isotope("Gd157", 64, 157, 156.923956*g/mole), 1); - - // Europium Isotopes - Eu151 = new G4Element("Europium151", "Eu151", 1); - Eu151->AddIsotope(new G4Isotope("Eu151", 63, 151, 150.919702*g/mole), 1); - Eu153 = new G4Element("Europium153", "Eu153", 1); - Eu153->AddIsotope(new G4Isotope("Eu153", 63, 153, 152.921225*g/mole), 1); - - // Iridium Isotopes - Ir191 = new G4Element("Iridium191", "Ir191", 1); - Ir191->AddIsotope(new G4Isotope("Ir191", 77, 191, 190.960584*g/mole), 1); - Ir193 = new G4Element("Iridium193", "Ir193", 1); - Ir193->AddIsotope(new G4Isotope("Ir193", 77, 193, 192.962917*g/mole), 1); - - // Making the Uranium isotopes - U235 = new G4Isotope("U235", 92, 235, 235.0439*g/mole); - U238 = new G4Isotope("U238", 92, 238, 238.0508*g/mole); - - // Low Enriched Uranium (LEU) - LEU = new G4Element("Low Enriched Uranium", "LEU", 2); - LEU->AddIsotope(U235, 19.89*perCent); - LEU->AddIsotope(U238, 80.11*perCent); - - // (Marteial #0) Void Material - World = new G4Material("Galactic", 1, 1, 1.e-25*g/cm3, kStateGas, - 2.73*kelvin, 3.e-18*pascal); - - // (Material #1) Beryllium Sheild with Impurities - Reflector = new G4Material("Reflector", ReflectorDensity, 17, kStateSolid, ReflectorTemp); - Reflector->AddElement(Be, 0.9953863); - Reflector->AddElement(Oxygen, 9.70113e-6); - Reflector->AddElement(Al, 1.010534e-3); - Reflector->AddElement(C, 1.515802e-3); - Reflector->AddElement(Fe, 1.31695e-3); - Reflector->AddElement(Si, 6.063207e-4); - Reflector->AddElement(B10, 4.345298e-7); - Reflector->AddElement(B11, 1.616855e-6); - Reflector->AddElement(Mn, 1.515802e-4); - Reflector->AddElement(Cd, 7.376901e-7); - Reflector->AddElement(Li6, 1.313695e-7); - Reflector->AddElement(Li7, 1.92001e-6); - Reflector->AddElement(Sm149, 6.497736e-7); - Reflector->AddElement(Gd155, 3.53687e-8); - Reflector->AddElement(Gd157, 3.132657e-8); - Reflector->AddElement(Eu151, 2.425283e-7); - Reflector->AddElement(Eu153, 2.627389e-7); - - // (Material #2) Light Water - LW = new G4Material("LightWater", LWDensity, 2, kStateLiquid, LWTemp); - LW->AddElement(Oxygen, 1); - LW->AddElement(H1, 2); - - // (Material #3) Fuel Rods (19.95% Enriched Uranium in (UO2)) - Fuel = new G4Material("Fuel", FuelDensity, 2, kStateSolid, FuelTemp); - Fuel->AddElement(Oxygen, 2); - Fuel->AddElement(LEU, 1); - - // (Material #4) Air - Air = new G4Material("Air", AirDensity, 2, kStateGas, AirTemp); - Air->AddElement(Oxygen, 0.21174); - Air->AddElement(N, 0.78826); - // (Material #5) Zr - Zr = new G4Material("Zirconium", ZrDensity, 1, kStateSolid, ZrTemp); - Zr->AddElement(Zirc, 1); - - // (Material #6) Aluminum with impurities - AlAlloy1 = new G4Material("AlAlloy1", AlAlloyDensity, 5, kStateSolid, AlAlloyTemp1); - AlAlloy1->AddElement(Al, 0.9792); - AlAlloy1->AddElement(Si, 0.0060); - AlAlloy1->AddElement(Cu, 0.0028); - AlAlloy1->AddElement(Mg, 0.0100); - AlAlloy1->AddElement(Cr, 0.0020); - - AlAlloy2 = new G4Material("AlAlloy2", AlAlloyDensity, 5, kStateSolid, AlAlloyTemp2); - AlAlloy2->AddElement(Al, 0.9792); - AlAlloy2->AddElement(Si, 0.0060); - AlAlloy2->AddElement(Cu, 0.0028); - AlAlloy2->AddElement(Mg, 0.0100); - AlAlloy2->AddElement(Cr, 0.0020); - - AlAlloy3 = new G4Material("AlAlloy3", AlAlloyDensity, 5, kStateSolid, AlAlloyTemp3); - AlAlloy3->AddElement(Al, 0.9792); - AlAlloy3->AddElement(Si, 0.0060); - AlAlloy3->AddElement(Cu, 0.0028); - AlAlloy3->AddElement(Mg, 0.0100); - AlAlloy3->AddElement(Cr, 0.0020); - - AlAlloy4 = new G4Material("AlAlloy4", AlAlloyDensity, 5, kStateSolid, AlAlloyTemp4); - AlAlloy4->AddElement(Al, 0.9792); - AlAlloy4->AddElement(Si, 0.0060); - AlAlloy4->AddElement(Cu, 0.0028); - AlAlloy4->AddElement(Mg, 0.0100); - AlAlloy4->AddElement(Cr, 0.0020); - - // (Material #7) Cadmium - Cadmium = new G4Material("Cadmium", CadmiumDensity, 1, kStateSolid, CadmiumTemp); - Cadmium->AddElement(Cd, 1); - - // (Materail #8) Heavy Water - HW = new G4Material("Heavy Water", HWDensity, 2, kStateLiquid, HWTemp); - HW->AddElement(D2, 2); - HW->AddElement(Oxygen, 1); - - - // Add materials to the map indexed by either ZA (format ZZAAA or ZZ) - // For composite materials: world is 0, heavy water is 1, UHW is 2 - matMap["Galactic"] = World; - matMap["H2O"] = LW; - matMap["D2O"] = HW; - matMap["Fuel"] = Fuel; - matMap["Zirconium"] = Zr; - matMap["AlAlloy1"] = AlAlloy1; - matMap["AlAlloy2"] = AlAlloy2; - matMap["AlAlloy3"] = AlAlloy3; - matMap["AlAlloy4"] = AlAlloy4; - matMap["Reflector"] = Reflector; - matMap["Cadmium"] = Cadmium; - matMap["Air"] = Air; - - matChanged = false; - - return; -} diff --git a/G4STORK/src/UnionBinaryTree.cc b/G4STORK/src/UnionBinaryTree.cc deleted file mode 100755 index 0a78dd97..00000000 --- a/G4STORK/src/UnionBinaryTree.cc +++ /dev/null @@ -1,731 +0,0 @@ -#include "UnionBinaryTree.hh" - -UnionBinaryTree::UnionBinaryTree(solidList* List) -{ - Unions = List; -} - -UnionBinaryTree::~UnionBinaryTree(void) -{ - delete Unions; - delete priority; -} - -// creates Union heirarchy -//Note: the order determines the rate of change of the priority with respect to distance along the specified axis and -//the direction of increase and decrease from the centre outwards (a positive order mean decreasing priority away from the centre) -// -solidPos UnionBinaryTree::GetUnionSolid(G4String name, G4int equalP, ShapeEnum regShape, G4double unitRegionDim[], G4double regionDim[], G4double offset, coorEnum axis, G4double order, G4double inPriority[], G4bool delRepeatedEntries) -{ - if(delRepeatedEntries) - RemoveDuplicates(); - - std::stringstream unionName; - solidList Temp1 = *Unions, Temp2, Temp3; - solidPos ToBeAdded; - solidListItr Temp1Itr; - regList regListTemp, regListTemp2; - regionInfo regToBeAdded; - regListItr regionListItr; - numSolids = Temp1.size(); - priority = new G4double[numSolids]; - G4int n=0; - G4bool check=false; - - if(equalP==0) - { - for(G4int i=0; i1) - { - if(regIndicies[j]%2!=0) - { - regIndicies[j]--; - - if(!check) - { - ToBeAdded=Temp2.front(); - regToBeAdded=regListTemp.front(); - Temp2.erase(Temp2.begin()); - regListTemp.erase(regListTemp.begin()); - check=true; - } - else - { - ToBeAdded=Temp2.back(); - regToBeAdded=regListTemp.back(); - Temp2.pop_back(); - regListTemp.pop_back(); - check=false; - } - } - for(G4int i=0; i2) - { - if(Temp1.size()%2!=0) - { - if(!check) - { - ToBeAdded=Temp1.front(); - regToBeAdded=regionList.front(); - Temp1.erase(Temp1.begin()); - regionList.erase(regionList.begin()); - check=true; - } - else - { - ToBeAdded=Temp1.back(); - regToBeAdded=regionList.back(); - Temp1.pop_back(); - regionList.pop_back(); - check=false; - } - } - - for(G4int i=0; i< G4int(Temp1.size()/2) ; i++) - { - unionName.str(""); - unionName << n; - - regListTemp.push_back(regionInfo(AddRegion(regionList[2*i+1].first, regionList[2*i].first, cylUnit, up), regionList[2*i+1].second+regionList[2*i].second)); - - Temp2.push_back(solidPos(new StorkUnionSolid(name+unionName.str(), Temp1[2*i+1].first, Temp1[2*i].first, 0, - Temp1[2*i].second-Temp1[2*i+1].second, cylUnit, regListTemp[i].first, Temp1[2*i+1].second), Temp1[2*i+1].second)); - regIndicies.pop_back(); - n++; - } - if(ToBeAdded.first!=NULL) - { - if(check) - { - Temp2.insert(Temp2.begin(), ToBeAdded); - regListTemp.insert(regListTemp.begin(), regToBeAdded); - ToBeAdded=solidPos(); - regToBeAdded=regionInfo(); - } - else - { - Temp2.insert(Temp2.end(), ToBeAdded); - regListTemp.insert(regListTemp.end(), regToBeAdded); - ToBeAdded=solidPos(); - regToBeAdded=regionInfo(); - } - } - Temp1=Temp2; - regionList=regListTemp; - - Temp2.clear(); - regListTemp.clear(); - } - - G4cout << "\n ### The position of all the Volumes ###\n"; - for(G4int j = 0; jsize()); i++) - { - priority[i]=(((*Unions)[i]).first)->GetCubicVolume()+offset; - } -} - -void UnionBinaryTree::PriorityByPos(coorEnum axis, G4double order, G4double offset) -{ - if(G4int(axis)==0) - { - for(G4int i=0; i< G4int(Unions->size()); i++) - { - priority[i]=pow((0.000001+(((*Unions)[i]).second).mag()),(-0.25*order))+offset; - } - } - else if(G4int(axis)==1) - { - for(G4int i=0; i< G4int(Unions->size()); i++) - { - priority[i]=pow((0.000001+(((*Unions)[i]).second).rho()),(-0.25*order))+offset; - } - } - else if(G4int(axis)==2) - { - for(G4int i=0; i< G4int(Unions->size()); i++) - { - priority[i]=pow((0.000001+(((*Unions)[i]).second).phi()),(-0.5*order))+offset; - } - } - else if(G4int(axis)==3) - { - for(G4int i=0; i< G4int(Unions->size()); i++) - { - priority[i]=pow((0.000001+(((*Unions)[i]).second).x()),(-0.25*order))+offset; - } - } - else if(G4int(axis)==4) - { - for(G4int i=0; i< G4int(Unions->size()); i++) - { - priority[i]=pow((0.000001+(((*Unions)[i]).second).y()),(-0.25*order))+offset; - } - } - else - { - for(G4int i=0; i < G4int(Unions->size()); i++) - { - priority[i]=pow((0.000001+(((*Unions)[i]).second).z()),(-0.25*order))+offset; - } - } -} - -void UnionBinaryTree::RemoveDuplicates() -{ - std::map duplicateMap; - for(solidListItr itr = Unions->begin(); itrend(); itr++) - { - if(duplicateMap.find(*itr)==duplicateMap.end()) - { - duplicateMap[*itr]=1; - } - else - { - Unions->erase(itr); - } - } -} - -intVec UnionBinaryTree::createRegions(solidList* Temp1, ShapeEnum RegShape, G4double unitRegionDim[], G4double regionDim[]) -{ - if(RegShape == cylUnit) - { - G4int regionIndices[3]; - regionIndices[0] = ceil((regionDim[1]-regionDim[0])/(unitRegionDim[1]-unitRegionDim[0])); - regionIndices[1] = ceil((regionDim[3]-regionDim[2])/(unitRegionDim[3]-unitRegionDim[2])); - regionIndices[2] = ceil((regionDim[5]-regionDim[4])/(unitRegionDim[5]-unitRegionDim[4])); - - unitRegionDim[0] = regionDim[1]-(regionDim[1]-regionDim[0])/(regionIndices[0]); - unitRegionDim[1] = regionDim[1]; - unitRegionDim[2] = regionDim[3]-(regionDim[3]-regionDim[2])/(regionIndices[1]); - unitRegionDim[3] = regionDim[3]; - unitRegionDim[4] = regionDim[5]-(regionDim[5]-regionDim[4])/(regionIndices[2]); - unitRegionDim[5] = regionDim[5]; - - G4double unitRegDim[6]; - intVec elemsRow(regionIndices[0], 0); - - for(G4int i=0; i unitRegDimTemp(unitRegDim); - regionList.push_back(regionInfo(unitRegDimTemp, 0.)); - } - } - } -// G4cout<<"\n ### SIZE OF REGION LIST " << regionList.size() << "### \n"; - - solidList Temp2 = *Temp1, Temp3; - Temp1->clear(); - solidPos toBeAdded; - - G4double swap; - solidPos swapP; - // indexs min, second min and max priority - G4int minimum = 0; - - for(G4int i = 0; i < G4int(Temp2.size()-1); i++) - { - minimum=i; - for(G4int j = i; j < G4int(Temp2.size()); j++) - { - if(priority[j]((regionList[j]).first)[5]) - { - polarPos[2]=((regionList[j]).first)[5]; - } - else - { - polarPos[2]=((Temp2[i]).second)[2]; - } - if(((Temp2[i]).second).phi()<((regionList[j]).first)[2]) - { - polarPos[1]=((regionList[j]).first)[2]; - } - else if(((Temp2[i]).second).phi()>((regionList[j]).first)[3]) - { - polarPos[1]=((regionList[j]).first)[3]; - } - else - { - polarPos[1]=((Temp2[i]).second).phi(); - } - if(((Temp2[i]).second).rho()<((regionList[j]).first)[0]) - { - polarPos[0]=((regionList[j]).first)[0]; - } - else if(((Temp2[i]).second).rho()>((regionList[j]).first)[1]) - { - polarPos[0]=((regionList[j]).first)[1]; - } - else - { - polarPos[0]=((Temp2[i]).second).rho(); - } - cartPos.setRhoPhiZ(polarPos[0],polarPos[1], polarPos[2]); - if(((Temp2[i]).first)->Inside(cartPos-Temp2[i].second)==kInside) - { - if(volCopy[i]>0) - { - G4String volShape = (Temp2[i].first)->GetEntityType(); - StorkSixVector newDim; - unionName.str(""); - unionName << volCopy[i]; - - if(volShape=="G4Tubs") - { - G4Tubs *tempTube = dynamic_cast(Temp2[i].first); - newDim.data[0] = (((tempTube)->GetInnerRadius())>0) ? ((tempTube)->GetInnerRadius())*(pow(1.0001,volCopy[i])):0.; - newDim.data[1] = (((tempTube)->GetOuterRadius()))*(pow(0.9999,volCopy[i])); - if(((tempTube)->GetDeltaPhiAngle())!=2*CLHEP::pi) - { - newDim.data[2] = (((tempTube)->GetStartPhiAngle()))*(pow(1.0001,volCopy[i])); - newDim.data[3] = (((tempTube)->GetDeltaPhiAngle()))*(pow(0.9999,volCopy[i])); - } - else - { - newDim.data[2] = 0.; - newDim.data[3] = 2*CLHEP::pi; - } - - newDim.data[4] = (((tempTube)->GetZHalfLength()))*(pow(0.9999,volCopy[i])); - Temp3.push_back(solidPos(new G4Tubs("G4TubsMod"+unionName.str(), newDim[0], newDim[1], newDim[4], newDim[2], newDim[3]),Temp2[i].second)); - } - else if(volShape=="G4Box") - { - G4cerr << "\n Missing code on line 486 of UnionBinaryTree.cc \n"; - } - else if(volShape=="G4Sphere") - { - G4cerr << "\n Missing code on line 486 of UnionBinaryTree.cc \n"; - } - else if(volShape=="G4Sphere") - { - G4cerr << "\n Missing code on line 486 of UnionBinaryTree.cc \n"; - } - - } - else - { - Temp3.push_back(Temp2[i]); - } - regionList[j].second += (priority[i]*0.5); - volCount++; - volCopy[i]++; - - } - } - } - if(toBeAdded.first!=NULL) - { - - Temp3.insert(Temp3.begin(), toBeAdded); - regionList[j] = regionInfo(AddRegion(regionList[j].first, regionList[j-1].first, cylUnit, left), regionList[j-1].second+regionList[j].second); - regionList.erase(regionList.begin()+j-1); - j--; - toBeAdded=solidPos(); - } - if(Temp3.size()>1) - { - if(Temp3.size()>2) - { - unionName.str(""); - unionName << count; - count++; - volume = new G4UnionSolid("volume"+unionName.str(), Temp3[1].first, Temp3[0].first, 0, Temp3[0].second-Temp3[1].second); - - G4int i=2; - for(; ipush_back(solidPos(new StorkUnionSolid("volume"+unionName.str(), Temp3[i].first, volume, 0, Temp3[i-1].second-Temp3[i].second, cylUnit, - regionList[j].first, Temp3[i].second ), Temp3[i].second)); - } - else - { - unionName.str(""); - unionName << count; - count++; - - Temp1->push_back(solidPos(new StorkUnionSolid("volume"+unionName.str(), Temp3[1].first, Temp3[0].first, 0, Temp3[0].second-Temp3[1].second, cylUnit, - regionList[j].first, Temp3[1].second ), Temp3[1].second)); - } - - - } - else if(Temp3.size()==1) - { - if(elemsRow[rowIndex]!=count2) - { - toBeAdded=Temp3[0]; - } - else if(count2>1) - { - unionName.str(""); - unionName << count; - count++; - - (*Temp1)[Temp1->size()-1] = solidPos(new StorkUnionSolid("volume"+unionName.str(), (*Temp1)[Temp1->size()-1].first, Temp3[0].first, 0, Temp3[0].second-(*Temp1)[Temp1->size()-1].second, cylUnit, - AddRegion(regionList[j-1].first, regionList[j].first, cylUnit, right), (*Temp1)[Temp1->size()-1].second), (*Temp1)[Temp1->size()-1].second); - } - else - { - for(G4int i=0; i1) - { - StorkUnionSolid* tempSolid = dynamic_cast((*Temp1)[Temp1->size()-1].first); - tempSolid->AddRegionToMe(right, regionList[j].first); - (*Temp1)[Temp1->size()-1].first = tempSolid; - } - else - { - for(G4int i=0; isize()); j++) - { - G4double temp = ((*Temp1)[j].second)[0]; - G4double temp2 = ((*Temp1)[j].second)[1]; - G4cout << "\n" << temp << ", " << temp2; - } - Temp2.clear(); - return elemsRow; - } - else - { - G4cerr<<"Region Shape has not been added to the UnionBinaryTree code"; - } - return intVec(); -} - -StorkSixVector UnionBinaryTree::AddRegion( StorkSixVector regionDim, StorkSixVector regionDim2, ShapeEnum shape, DirEnum dir ) -{ - StorkSixVector tmpRegDim; - tmpRegDim=regionDim; - if(dir==right) - { - if(shape==cylUnit) - { - (tmpRegDim.data)[2]=(regionDim2.data)[2]; - } - else if(shape==cubicUnit) - { - (tmpRegDim.data)[1]+=(regionDim2.data)[1]-(regionDim2.data)[0]; - } - else - { - (tmpRegDim.data)[2]=(regionDim2.data)[2]; - } - } - else if(dir==left) - { - if(shape==cylUnit) - { - (tmpRegDim.data)[3]=(regionDim2.data)[3]; - } - else if(shape==cubicUnit) - { - (tmpRegDim.data)[0]+=(regionDim2.data)[0]-(regionDim2.data)[1]; - } - else - { - (tmpRegDim.data)[3]=(regionDim2.data)[3]; - } - } - else if(dir==up) - { - if(shape==cylUnit) - { - (tmpRegDim.data)[1]=(regionDim2.data)[1]; - } - else if(shape==cubicUnit) - { - (tmpRegDim.data)[3]+=(regionDim2.data)[3]-(regionDim2.data)[2]; - } - else - { - (tmpRegDim.data)[1]=(regionDim2.data)[1]; - } - } - else if(dir==down) - { - if(shape==cylUnit) - { - (tmpRegDim.data)[0]=(regionDim2.data)[0]; - } - else if(shape==cubicUnit) - { - (tmpRegDim.data)[2]+=(regionDim2.data)[2]-(regionDim2.data)[3]; - } - else - { - (tmpRegDim.data)[0]=(regionDim2.data)[0]; - } - } - else if(dir==above) - { - if(shape==cylUnit) - { - (tmpRegDim.data)[5]+=(regionDim2.data)[5]-(regionDim2.data)[4]; - } - else if(shape==cubicUnit) - { - (tmpRegDim.data)[5]+=(regionDim2.data)[5]-(regionDim2.data)[4]; - } - else - { - (tmpRegDim.data)[4]=(regionDim2.data)[4]; - } - } - else if(dir==below) - { - if(shape==cylUnit) - { - (tmpRegDim.data)[4]+=(regionDim2.data)[4]-(regionDim2.data)[5]; - } - else if(shape==cubicUnit) - { - (tmpRegDim.data)[4]+=(regionDim2.data)[2]; - } - else - { - (tmpRegDim.data)[5]=(regionDim2.data)[5]; - } - } - return tmpRegDim; -} - -G4bool UnionBinaryTree::InsideRegion( const G4ThreeVector& p, ShapeEnum regShape, StorkSixVector regDim ) -{ - G4double kCarTolerance = G4GeometryTolerance::GetInstance()->GetSurfaceTolerance(); - G4double kAngTolerance = G4GeometryTolerance::GetInstance()->GetAngularTolerance(); - static const G4double delta=0.5*kCarTolerance; - static const G4double delta2=0.5*kAngTolerance; - - if(regShape==0) - { - if(p.rho()>regDim[0]-delta&&p.rho()regDim[2]-delta2&&p.phi()regDim[4]-delta&&p.z()regDim[0]-delta&&p.x()regDim[2]-delta&&p.y()regDim[4]-delta&&p.z()regDim[0]-delta&&p.r()regDim[2]-delta2&&p.phi()regDim[4]-delta2&&p.theta()OpenGeometry(); - G4PhysicalVolumeStore::GetInstance()->Clean(); - G4LogicalVolumeStore::GetInstance()->Clean(); - - // Set up the solids if necessary - if(geomChanged) - { - // Clean up solids - G4SolidStore::GetInstance()->Clean(); - - // Create world solid - new G4Box("ZED2World", encWorldDim[1]/2, encWorldDim[1]/2 , encWorldDim[2]/2); - - // Create the reactor tube - //new G4Tubs("RecDimTube", reactorDim[0], reactorDim[1], reactorDim[2], 0., CLHEP::pi/2.0); - //new G4Box("RecDimTube", reactorDim[1]/2, reactorDim[1]/2 , reactorDim[2]); - - // Create the air above the moderator - new G4Tubs("AirTube", TubeAirFuel[0], TubeAirFuel[1], TubeAirFuel[2], 0., CLHEP::pi/2.0); - - - // Create Graphite Reflector solid - new G4Tubs("graphitewall", reactorDim[0], reactorDim[1], Graphitewall[2], 0., CLHEP::pi/2.0); - new G4Tubs("graphitebott", reactorDim[0], reactorDim[1], Graphitebott[2], 0., CLHEP::pi/2.0); - new G4UnionSolid("graphitewall+graphitebott", theSolids->GetSolid("graphitewall"), theSolids->GetSolid("graphitebott"), 0, G4ThreeVector(0.,0.,-Graphitewall[2]-Graphitebott[2])); - - // Create Sheilding walls - //new G4Tubs("sheildingwall", Shieldingwall[0], Shieldingwall[1], Shieldingwall[2], 0., 2.0*CLHEP::pi); - - // Create the Calandria solids 1 - new G4Tubs("calandriashell", CalandriaDim1[0], CalandriaDim1[1], CalandriaDim1[2], 0., CLHEP::pi/2.0); - new G4Tubs("calandriabott", BotReacTankDim[0], BotReacTankDim[1], BotReacTankDim[2], 0., CLHEP::pi/2.0); - new G4UnionSolid("calandriashell+calandriabott", theSolids->GetSolid("calandriashell"), theSolids->GetSolid("calandriabott"), 0, G4ThreeVector(0,0,(-CalandriaDim1[2]-BotReacTankDim[2]))); - - // Create Moderator solid - new G4Tubs("ModSphere", MTankDim[0], MTankDim[1], MTankDim[2]/2., 0., CLHEP::pi/2.0); - - // Create the air above the coolant tube solid - new G4Tubs("AirTube1", Air1Dim[0]/2, Air1Dim[1]/2, Air1Dim[2]/2., 0., 2.0*CLHEP::pi); - - // Create the Calandria tube - new G4Tubs("CalandriaTubedwnCut1", CalendriaT1Dim[0]/2, CalendriaT1Dim[1]/2, (CalendriaT1Dim[2]-topCalandriatoModH)/2., 0., 2.0*CLHEP::pi); - new G4Tubs("CalandriaTubedwnCut2", CalendriaT1Dim[0]/2, CalendriaT1Dim[1]/2, topCalandriatoModH/2., 0., 2.0*CLHEP::pi); - - // Create the GasAnn tube solid - new G4Tubs("GasAnnTube1Cut1", GasAnn1Dim[0]/2, GasAnn1Dim[1]/2, (GasAnn1Dim[2]-topCalandriatoModH)/2., 0., 2.0*CLHEP::pi); - new G4Tubs("GasAnnTube1Cut2", GasAnn1Dim[0]/2, GasAnn1Dim[1]/2, topCalandriatoModH/2., 0., 2.0*CLHEP::pi); - - // Create the pressure tube solid - new G4Tubs("PressureTubedwnCut1", PressureT1Dim[0]/2, PressureT1Dim[1]/2, (GasAnn1Dim[2]-topCalandriatoModH)/2, 0., 2.0*CLHEP::pi); - new G4Tubs("PressureTubedwnCut2", PressureT1Dim[0]/2, PressureT1Dim[1]/2, topCalandriatoModH/2., 0., 2.0*CLHEP::pi); - - // Create the coolant tube solid - new G4Tubs("CoolantTube1Cut1", Coolant1Dim[0]/2, Coolant1Dim[1]/2, FuelinModH/2., 0., 2.0*CLHEP::pi); - new G4Tubs("CoolantTube1Cut2", Coolant1Dim[0]/2, Coolant1Dim[1]/2, topFueltoModH/2., 0., 2.0*CLHEP::pi); - - // Create outer fuel bunndles solid - new G4Tubs("FuelTubeB1", FuelRodBDim1[0]/2, FuelRodBDim1[1]/2, FuelRodBDim1[2], 0., 2.0*CLHEP::pi); - new G4Tubs("FuelTubeB1Cut1", FuelRodBDim1[0]/2, FuelRodBDim1[1]/2, CutFuelBunInMod/2., 0., 2.0*CLHEP::pi); - new G4Tubs("FuelTubeB1Cut2", FuelRodBDim1[0]/2, FuelRodBDim1[1]/2, ModFuelIntersectPos/2., 0., 2.0*CLHEP::pi); - - - // Create inner fuel bunndles solid - new G4Tubs("FuelTubeA1", FuelRodADim1[0]/2, FuelRodADim1[1]/2, FuelRodADim1[2], 0., 2.0*CLHEP::pi); - new G4Tubs("FuelTubeA1Cut1", FuelRodADim1[0]/2, FuelRodADim1[1]/2, CutFuelBunInMod/2., 0., 2.0*CLHEP::pi); - new G4Tubs("FuelTubeA1Cut2", FuelRodADim1[0]/2, FuelRodADim1[1]/2, ModFuelIntersectPos/2., 0., 2.0*CLHEP::pi); - - - // Create outer Zr-4 sheath solid - new G4Tubs("SheathB1", SheathBDim1[0]/2, SheathBDim1[1]/2, SheathBDim1[2], 0., 2.0*CLHEP::pi); - new G4Tubs("SheathB1Cut1", SheathBDim1[0]/2, SheathBDim1[1]/2, CutFuelBunInMod/2., 0., 2.0*CLHEP::pi); - new G4Tubs("SheathB1Cut2", SheathBDim1[0]/2, SheathBDim1[1]/2, ModFuelIntersectPos/2., 0., 2.0*CLHEP::pi); - - // Create inner Zr-4 sheath solid - new G4Tubs("SheathA1", SheathADim1[0]/2, SheathADim1[1]/2, SheathADim1[2], 0., 2.0*CLHEP::pi); - new G4Tubs("SheathA1Cut1", SheathADim1[0]/2, SheathADim1[1]/2, CutFuelBunInMod/2., 0., 2.0*CLHEP::pi); - new G4Tubs("SheathA1Cut2", SheathADim1[0]/2, SheathADim1[1]/2, ModFuelIntersectPos/2., 0., 2.0*CLHEP::pi); - - // Create the end plate - new G4Tubs("EndPlate2", EndPlate2[0], EndPlate2[1], EndPlate2[2], 0., 2.0*CLHEP::pi); - new G4Tubs("EndPlate1", EndPlate2[0], EndPlate2[1], EndPlate2[2], 0., 2.0*CLHEP::pi); - - - - geomChanged = false; - } - - - // Create world volume - worldLogical = new G4LogicalVolume(theSolids->GetSolid("ZED2World"),matMap["World"], "worldLogical",0,0,0); - worldPhysical = new G4PVPlacement(0, G4ThreeVector(0.,0.,0.), worldLogical,"worldPhysical",0,0,0); - - //Create the reactor dimension tube - //reactDimTubeLogical = new G4LogicalVolume(theSolids->GetSolid("RecDimTube"),matMap["World"], "reactDimTubeLogical",0,0,0); - //new G4PVPlacement(0, G4ThreeVector(/*-reactorDim[1]/2,-reactorDim[1]/2*/ 0,0,0.), reactDimTubeLogical, "reactDimTubePhysical", worldLogical,0,0); - - // Create Reflector volume - vesselLogical = new G4LogicalVolume(theSolids->GetSolid("graphitewall+graphitebott"), matMap["Graphite"], "VesselLogical", 0, 0, 0); - new G4PVPlacement(0,G4ThreeVector(-reactorDim[1]/2,-reactorDim[1]/2,-reactorDim[2]+2.*Graphitebott[2]+Graphitewall[2]), vesselLogical, "VesselPhysical",worldLogical , 0, 0); - - // Create Sheilding walls - //ShieldingwalLogical = new G4LogicalVolume(theSolids->GetSolid("sheildingwall"),matMap["TShield"], "ShieldingwalLogical", 0,0,0); - //new G4PVPlacement(0, G4ThreeVector(0.,0.,Graphitewall[2]+Graphitebott[2]+Shieldingwall[2]), ShieldingwalLogical, "ShieldingwallPhysical", airboxLogical,0,0,true); - - - // Create Calandrai volume in mother air volume - tankLogical1 = new G4LogicalVolume(theSolids->GetSolid("calandriashell+calandriabott"), matMap["Al57S"], "VesselLogical1", 0, 0, 0); - new G4PVPlacement(0, G4ThreeVector(0.,0.,BotReacTankDim[2]), tankLogical1,"CalandriaPhysical1", vesselLogical,0,0); - - // Create Moderator volume - ModLogical = new G4LogicalVolume(theSolids->GetSolid("ModSphere"),matMap["Moderator"], "ModLogical",0,0,0); - new G4PVPlacement(0, G4ThreeVector(0.,0.,MTankDim[2]/2-CalandriaDim1[2]), ModLogical, "ModPhysical", tankLogical1, false,0); - - //Create Air above the moderator - airTubeLogical = new G4LogicalVolume(theSolids->GetSolid("AirTube"),matMap["Air"], "airTubeLogical",0,0,0); - new G4PVPlacement(0, G4ThreeVector(0.,0., TubeAirFuel[2]+MTankDim[2]-CalandriaDim1[2]), airTubeLogical, "airTubePhysical", tankLogical1,0,0); - - std::stringstream volName; - - logicCalandria1 = new G4LogicalVolume(theSolids->GetSolid("CalandriaTubedwnCut2"), matMap["AlCalT"], "CalandriaTube1LogicalCut2", 0, 0, 0); - for (G4int i=0; i<13; i++) - { - // Create calandria tubes in mother air volume - volName.str(""); - volName.clear(); - volName << i; - new G4PVPlacement (0, G4ThreeVector(XPos[i],YPos[i],0.), logicCalandria1, "CalandriaTube1PhysicalCut2"+volName.str(), airTubeLogical, false, 0); - } - // Create gas annulus tubes in mother air volume - logicGasAnn1 = new G4LogicalVolume(theSolids->GetSolid("GasAnnTube1Cut2"), matMap["Air"], "GasAnnTube1Logical", 0, 0, 0); - new G4PVPlacement (0, G4ThreeVector(0,0,0), logicGasAnn1, "GasAnnTube1PhysicalCut2", logicCalandria1, false, 0); - - // Create pressure tubes in mother air volume - logicPressure1 = new G4LogicalVolume(theSolids->GetSolid("PressureTubedwnCut2"), matMap["AlPresT"], "PressureTube1Logical", 0, 0, 0); - new G4PVPlacement (0, G4ThreeVector(0,0,0), logicPressure1, "PressureTube1PhysicalCut2", logicGasAnn1, false, 0); - - // Create lower coolant in mother air volume - logicCoolant1 = new G4LogicalVolume(theSolids->GetSolid("CoolantTube1Cut2"), matMap["Coolant"], "Coolant1Logical", 0, 0, 0); - new G4PVPlacement (0, G4ThreeVector(0,0,-topCalandriatoModH/2.+topFueltoModH/2.), logicCoolant1, "Coolant1PhysicalCut2", logicPressure1, false, 0); - - // Create air - logicAir1 = new G4LogicalVolume(theSolids->GetSolid("AirTube1"), matMap["Air"], "Air1Logical", 0, 0, 0); - new G4PVPlacement (0, G4ThreeVector(0,0,-topCalandriatoModH/2.+topFueltoModH+Air1Dim[2]/2.0), logicAir1, "Air1Physical", logicPressure1, false, 0); - - // Create inner/outer FULL fuel bunndles and sheath in air volume - logicRodA1 = new G4LogicalVolume(theSolids->GetSolid("FuelTubeA1"), matMap["LEUMat"], "FuelRodA1Logical", 0, 0, 0); - logicRodB1 = new G4LogicalVolume(theSolids->GetSolid("FuelTubeB1"), matMap["LEUMat"], "FuelRodB1Logical", 0, 0, 0); - logicSheathA1 = new G4LogicalVolume(theSolids->GetSolid("SheathA1"), matMap["Zr4"], "SheathA1Logical", 0, 0, 0); - logicSheathB1 = new G4LogicalVolume(theSolids->GetSolid("SheathB1"), matMap["Zr4"], "SheathB1Logical", 0, 0, 0); - logicEndPlate1 = new G4LogicalVolume(theSolids->GetSolid("EndPlate1"), matMap["Zr4"], "EndPlate1", 0, 0, 0); - logicEndPlate2 = new G4LogicalVolume(theSolids->GetSolid("EndPlate2"), matMap["Zr4"], "EndPlate2", 0, 0, 0); - - for (G4int l=0; lGetSolid("FuelTubeA1Cut2"), matMap["LEUMat"], "FuelRodA1LogicalCut2", 0, 0, 0); - logicRodB1Cut2 = new G4LogicalVolume(theSolids->GetSolid("FuelTubeB1Cut2"), matMap["LEUMat"], "FuelRodB1LogicalCut2", 0, 0, 0); - logicSheathA1Cut2 = new G4LogicalVolume(theSolids->GetSolid("SheathA1Cut2"), matMap["Zr4"], "SheathA1Logicalcut2", 0, 0, 0); - logicSheathB1Cut2 = new G4LogicalVolume(theSolids->GetSolid("SheathB1Cut2"), matMap["Zr4"], "SheathB1LogicalCut2", 0, 0, 0); - logicEndPlate2Cut2 = new G4LogicalVolume(theSolids->GetSolid("EndPlate2"), matMap["Zr4"], "EndPlate2Cut2", 0, 0, 0); - // Rotation and translation of the rod and sheathe - - // Set name for sheathe physical volume - - volName.str(""); - volName << 0; - - // place the center pin in air - new G4PVPlacement(0, G4ThreeVector(0,0,-topFueltoModH/2.+ModFuelIntersectPos/2.), logicSheathA1Cut2,"sheathePhysicalCut2 " + volName.str(), logicCoolant1,0,0); - new G4PVPlacement(0, G4ThreeVector(0,0,0), logicRodA1Cut2,"fuelPhysicalCut2A", logicSheathA1Cut2,0,0); - new G4PVPlacement(0, G4ThreeVector(0,0,0), logicRodB1Cut2,"fuelPhysicalCut2B", logicSheathB1Cut2,0,0); - - - - - for( G4int j = 1; j < rings; j++ ) - { - for( G4int k = 0; k < j*6; k++ ) - { - // Reset string stream - volName.str(""); - - volName << j << "-" << k; - - if(j == 2) - { - G4ThreeVector Tm(ringRad[j-1]*cos(2.0*CLHEP::pi*G4double(k)/G4double(j*6)+secondRingOffset), ringRad[j-1]*sin(2.0*CLHEP::pi*G4double(k)/G4double(j*6)+secondRingOffset),-topFueltoModH/2.+ModFuelIntersectPos/2.); - new G4PVPlacement(0, Tm, logicSheathB1Cut2,"sheathePhysicalCut2 " +volName.str(),logicCoolant1,0,0); - - } - else if (j == 1) - { - G4ThreeVector Tm(ringRad[j-1]*cos(2.0*CLHEP::pi*G4double(k)/G4double(j*6)), ringRad[j-1]*sin(2.0*CLHEP::pi*G4double(k)/G4double(j*6)),-topFueltoModH/2.+ModFuelIntersectPos/2.); - new G4PVPlacement(0, Tm, logicSheathA1Cut2,"sheathePhysicalCut2 " +volName.str(),logicCoolant1,0,0); - } - else - { - G4ThreeVector Tm(ringRad[j-1]*cos(2.0*CLHEP::pi*G4double(k)/G4double(j*6)), ringRad[j-1]*sin(2.0*CLHEP::pi*G4double(k)/G4double(j*6)),-topFueltoModH/2.+ModFuelIntersectPos/2.); - new G4PVPlacement(0, Tm, logicSheathB1Cut2,"sheathePhysicalCut2 " +volName.str(),logicCoolant1,0,0); - } - } - } - - - // Make the end plates 2 - G4ThreeVector EP2(0,0,-topFueltoModH/2.+ModFuelIntersectPos+0.08*cm); - new G4PVPlacement(0, EP2, logicEndPlate2Cut2,"EndPlate2Physical1Cut2",logicCoolant1,0,0); - - - - - - // *********Create Calandrai volume in moderator volume************* - logicCalandria1Mod = new G4LogicalVolume(theSolids->GetSolid("CalandriaTubedwnCut1"), matMap["AlCalT"], "CalandriaTube1ModLogical", 0, 0, 0); - for (G4int i=0; i<13; i++) - { - // Create calandria tubes in moderator volume -reactorDim[2]+2.*Graphitebott[2]+2.*BotReacTankDim[2]+distbtwflrtofuel+(CalendriaT1Dim[2]-topFueltoModH)/2.MTankDim[2] - volName.str(""); - volName.clear(); - volName << i; - new G4PVPlacement (0, G4ThreeVector(XPos[i],YPos[i],distbtwflrtofuel/2.), logicCalandria1Mod, "CalandriaTube1ModPhysicalCut1"+volName.str(), ModLogical, false, 0); - } - // Create gas annulus tubes in moderator volume - logicGasAnn1Mod = new G4LogicalVolume(theSolids->GetSolid("GasAnnTube1Cut1"), matMap["Air"], "GasAnnTube1Logical", 0, 0, 0); - new G4PVPlacement (0, G4ThreeVector(0,0,0), logicGasAnn1Mod, "GasAnnTube1PhysicalCut1", logicCalandria1Mod, false, 0); - - // Create pressure tubes in moderator volume - logicPressure1Mod = new G4LogicalVolume(theSolids->GetSolid("PressureTubedwnCut1"), matMap["AlPresT"], "PressureTube1Logical", 0, 0, 0); - new G4PVPlacement (0, G4ThreeVector(0,0,0), logicPressure1Mod, "PressureTube1PhysicalCut1", logicGasAnn1Mod, false, 0); - - // Create lower coolant in moderator volume - logicCoolant1Mod = new G4LogicalVolume(theSolids->GetSolid("CoolantTube1Cut1"), matMap["Coolant"], "Coolant1Logical", 0, 0, 0); - new G4PVPlacement (0, G4ThreeVector(0,0,0), logicCoolant1Mod, "Coolant1PhysicalCut1", logicPressure1Mod, false, 0); - - // Create inner/outer fuel bunndle and sheath in Moderator volume - logicRodA1Mod = new G4LogicalVolume(theSolids->GetSolid("FuelTubeA1"), matMap["LEUMat"], "FuelRodA1LogicalMod", 0, 0, 0); - logicRodB1Mod = new G4LogicalVolume(theSolids->GetSolid("FuelTubeB1"), matMap["LEUMat"], "FuelRodB1LogicalMod", 0, 0, 0); - logicSheathA1Mod = new G4LogicalVolume(theSolids->GetSolid("SheathA1"), matMap["Zr4"], "SheathA1LogicalMod", 0, 0, 0); - logicSheathB1Mod = new G4LogicalVolume(theSolids->GetSolid("SheathB1"), matMap["Zr4"], "SheathB1LogicalMod", 0, 0, 0); - logicEndPlate1Mod = new G4LogicalVolume(theSolids->GetSolid("EndPlate1"), matMap["Zr4"], "EndPlate1Mod", 0, 0, 0); - logicEndPlate2Mod = new G4LogicalVolume(theSolids->GetSolid("EndPlate2"), matMap["Zr4"], "EndPlate2Mod", 0, 0, 0); - - for (G4int l=0; lGetSolid("FuelTubeA1Cut1"), matMap["LEUMat"], "FuelRodA1LogicalCut1", 0, 0, 0); - logicRodB1Cut1 = new G4LogicalVolume(theSolids->GetSolid("FuelTubeB1Cut1"), matMap["LEUMat"], "FuelRodB1LogicalCut1", 0, 0, 0); - logicSheathA1Cut1 = new G4LogicalVolume(theSolids->GetSolid("SheathA1Cut1"), matMap["Zr4"], "SheathA1LogicalCut1", 0, 0, 0); - logicSheathB1Cut1 = new G4LogicalVolume(theSolids->GetSolid("SheathB1Cut1"), matMap["Zr4"], "SheathB1LogicalCut1", 0, 0, 0); - logicEndPlate2Cut1 = new G4LogicalVolume(theSolids->GetSolid("EndPlate2"), matMap["Zr4"], "EndPlate2Cut1", 0, 0, 0); - - // place the center pin for the cut fuel bundle in the moderator - new G4PVPlacement(0, G4ThreeVector(0,0, (-FuelinModH/2.+(NumOfFuelBunInMod*49.51*cm)+2.*EndPlate2[2]+CutFuelBunInMod/2. )), logicSheathA1Cut1,"sheathePhysicalCut1 " + volName.str(), logicCoolant1Mod,0,0); - new G4PVPlacement(0, G4ThreeVector(0,0,0), logicRodA1Cut1,"fuelPhysicalCut1A ", logicSheathA1Cut1,0,0); - new G4PVPlacement(0, G4ThreeVector(0,0,0), logicRodB1Cut1,"fuelPhysicalCut1B ", logicSheathB1Cut1,0,0); - - - - - // Make the end plates 2 - G4ThreeVector EP(0,0,(-FuelinModH/2.+(NumOfFuelBunInMod*49.51*cm)+0.08*cm)); - new G4PVPlacement(0, EP, logicEndPlate2Cut1,"EndPlate2Physical1Cut1 ",logicCoolant1Mod,0,0); - - for( G4int j = 1; j < rings; j++ ) - { - for( G4int k = 0; k < j*6; k++ ) - { - // Reset string stream - volName.str(""); - - volName << j << "-" << k; - - if(j == 2) - { - G4ThreeVector Tm(ringRad[j-1]*cos(2.0*CLHEP::pi*G4double(k)/G4double(j*6)+secondRingOffset), ringRad[j-1]*sin(2.0*CLHEP::pi*G4double(k)/G4double(j*6)+secondRingOffset),(-FuelinModH/2.+(NumOfFuelBunInMod*49.51*cm)+2.*EndPlate2[2]+CutFuelBunInMod/2. )); - // place the fuel for the cut fuel bundle in the moderator - new G4PVPlacement(0, Tm, logicSheathB1Cut1,"sheathePhysicalCut1 " +volName.str(),logicCoolant1Mod,0,0); - - } - else if (j == 1) - { - G4ThreeVector Tm(ringRad[j-1]*cos(2.0*CLHEP::pi*G4double(k)/G4double(j*6)), ringRad[j-1]*sin(2.0*CLHEP::pi*G4double(k)/G4double(j*6)),(-FuelinModH/2.+(NumOfFuelBunInMod*49.51*cm)+2.*EndPlate2[2]+CutFuelBunInMod/2. )); - new G4PVPlacement(0, Tm, logicSheathA1Cut1,"sheathePhysicalCut1 " +volName.str(),logicCoolant1Mod,0,0); - } - else - { - G4ThreeVector Tm(ringRad[j-1]*cos(2.0*CLHEP::pi*G4double(k)/G4double(j*6)), ringRad[j-1]*sin(2.0*CLHEP::pi*G4double(k)/G4double(j*6)),(-FuelinModH/2.+(NumOfFuelBunInMod*49.51*cm)+2.*EndPlate2[2]+CutFuelBunInMod/2. )); - // place the fuel for the cut fuel bundle in the moderator - new G4PVPlacement(0, Tm, logicSheathB1Cut1,"sheathePhysicalCut1 " +volName.str(),logicCoolant1Mod,0,0); - } - } - } - - - - - - // Set reactor as sensitive detector - worldLogical->SetSensitiveDetector( sDReactor ); - //reactDimTubeLogical->SetSensitiveDetector( sDReactor); - airTubeLogical->SetSensitiveDetector( sDReactor ); - vesselLogical->SetSensitiveDetector( sDReactor ); - tankLogical1->SetSensitiveDetector( sDReactor ); - ModLogical->SetSensitiveDetector( sDReactor ); - logicCalandria1->SetSensitiveDetector( sDReactor ); - logicGasAnn1->SetSensitiveDetector( sDReactor ); - logicPressure1->SetSensitiveDetector( sDReactor ); - logicCoolant1->SetSensitiveDetector( sDReactor ); - logicAir1->SetSensitiveDetector( sDReactor ); - logicRodA1->SetSensitiveDetector( sDReactor ); - logicRodB1->SetSensitiveDetector( sDReactor ); - logicSheathA1->SetSensitiveDetector( sDReactor ); - logicSheathB1->SetSensitiveDetector( sDReactor ); - logicEndPlate2->SetSensitiveDetector( sDReactor ); - logicEndPlate1->SetSensitiveDetector( sDReactor ); - logicCalandria1Mod->SetSensitiveDetector( sDReactor ); - logicGasAnn1Mod->SetSensitiveDetector( sDReactor ); - logicPressure1Mod->SetSensitiveDetector( sDReactor ); - logicCoolant1Mod->SetSensitiveDetector( sDReactor ); - logicRodA1Cut2->SetSensitiveDetector( sDReactor ); - logicRodB1Cut2->SetSensitiveDetector( sDReactor ); - logicSheathA1Cut2->SetSensitiveDetector( sDReactor ); - logicSheathB1Cut2->SetSensitiveDetector( sDReactor ); - logicEndPlate2Cut2->SetSensitiveDetector( sDReactor ); - logicRodA1Mod->SetSensitiveDetector( sDReactor ); - logicRodB1Mod->SetSensitiveDetector( sDReactor ); - logicSheathA1Mod->SetSensitiveDetector( sDReactor ); - logicSheathB1Mod->SetSensitiveDetector( sDReactor ); - logicEndPlate2Mod->SetSensitiveDetector( sDReactor ); - logicEndPlate1Mod->SetSensitiveDetector( sDReactor ); - logicRodA1Cut1->SetSensitiveDetector( sDReactor ); - logicRodB1Cut1->SetSensitiveDetector( sDReactor ); - logicSheathA1Cut1->SetSensitiveDetector( sDReactor ); - logicSheathB1Cut1->SetSensitiveDetector( sDReactor ); - logicEndPlate2Cut1->SetSensitiveDetector( sDReactor ); - - - - // Set visualization attributes - - if(worldVisAtt) - delete worldVisAtt; - if(vesselVisAtt) - delete vesselVisAtt; - if(tank1VisATT) - delete tank1VisATT; - if(ModVisAtt) - delete ModVisAtt; - if(fuelA1VisATT) - delete fuelA1VisATT; - if(fuelB1VisATT) - delete fuelB1VisATT; - if(sheathA1VisATT) - delete sheathA1VisATT; - if(sheathB1VisATT) - delete sheathB1VisATT; - if(Air1VisAtt) - delete Air1VisAtt; - if(Coolant1VisAtt) - delete Coolant1VisAtt; - if(Pressure1VisAtt) - delete Pressure1VisAtt; - if(GasAnn1VisAtt) - delete GasAnn1VisAtt; - if(Calandria1VisAtt) - delete Calandria1VisAtt; - if(EndPlate2VisATT) - delete EndPlate2VisATT; - if(airTubeVisAtt) - delete airTubeVisAtt; - if(DumplineAlVisAtt) - delete DumplineAlVisAtt; - if(DumplineHWVisAtt) - delete DumplineHWVisAtt; - - worldVisAtt = new G4VisAttributes(G4Colour(0.5, 1., 0.5)); - worldVisAtt->SetVisibility(true); - worldLogical->SetVisAttributes(worldVisAtt); - //reactDimTubeLogical->SetVisAttributes(worldVisAtt); - - airTubeVisAtt = new G4VisAttributes(G4Colour(0., 1., 0.5)); - airTubeVisAtt->SetVisibility(true); - airTubeLogical->SetVisAttributes(airTubeVisAtt); - - vesselVisAtt= new G4VisAttributes(G4Colour(1.0,0.0,0.0)); - vesselVisAtt->SetForceSolid(false); - vesselVisAtt->SetVisibility(true); - vesselLogical->SetVisAttributes(vesselVisAtt); - - tank1VisATT= new G4VisAttributes(G4Colour(1.0,1.0,0.0)); - tank1VisATT->SetForceSolid(false); - tank1VisATT->SetVisibility(true); - tankLogical1->SetVisAttributes(tank1VisATT); - - ModVisAtt = new G4VisAttributes(G4Colour(0.,1.,0.)); - ModVisAtt->SetVisibility(true); - ModVisAtt->SetForceSolid(false); - ModLogical->SetVisAttributes(ModVisAtt); - - Calandria1VisAtt = new G4VisAttributes(G4Colour(1., 0., 1.)); - Calandria1VisAtt->SetForceSolid(false); - Calandria1VisAtt->SetVisibility(false); - logicCalandria1->SetVisAttributes(Calandria1VisAtt); - logicCalandria1Mod->SetVisAttributes(Calandria1VisAtt); - - - GasAnn1VisAtt = new G4VisAttributes(G4Colour(1., 0., 0.)); - GasAnn1VisAtt->SetForceSolid(false); - GasAnn1VisAtt->SetVisibility(false); - logicGasAnn1->SetVisAttributes(GasAnn1VisAtt); - logicGasAnn1Mod->SetVisAttributes(GasAnn1VisAtt); - - - - Pressure1VisAtt = new G4VisAttributes(G4Colour(0., 1., 0.)); - Pressure1VisAtt->SetForceSolid(false); - Pressure1VisAtt->SetVisibility(false); - logicPressure1->SetVisAttributes(Pressure1VisAtt); - logicPressure1Mod->SetVisAttributes(Pressure1VisAtt); - - - Coolant1VisAtt = new G4VisAttributes(G4Colour(0.53, 0.81, 0.92)); - Coolant1VisAtt->SetForceSolid(false); - Coolant1VisAtt->SetVisibility(false); - logicCoolant1->SetVisAttributes(Coolant1VisAtt); - logicCoolant1Mod->SetVisAttributes(Coolant1VisAtt); - - Air1VisAtt = new G4VisAttributes(G4Colour(0., 1., 0.5)); - Air1VisAtt->SetForceSolid(false); - Air1VisAtt->SetVisibility(true); - logicAir1->SetVisAttributes(Air1VisAtt); - //logicAir1RU->SetVisAttributes(Air1VisAtt); - - fuelA1VisATT = new G4VisAttributes(G4Colour(0.0, 0.0 ,1.0)); - fuelA1VisATT->SetForceSolid(false); - fuelA1VisATT->SetVisibility(true); - logicRodA1->SetVisAttributes(fuelA1VisATT); - logicRodA1Cut2->SetVisAttributes(fuelA1VisATT); - logicRodA1Mod->SetVisAttributes(fuelA1VisATT); - logicRodA1Cut1->SetVisAttributes(fuelA1VisATT); - - fuelB1VisATT = new G4VisAttributes(G4Colour(0,0.5,0.92)); - fuelB1VisATT->SetForceSolid(false); - fuelB1VisATT->SetVisibility(true); - logicRodB1->SetVisAttributes(fuelB1VisATT); - logicRodB1Cut2->SetVisAttributes(fuelB1VisATT); - logicRodB1Mod->SetVisAttributes(fuelB1VisATT); - logicRodB1Cut1->SetVisAttributes(fuelB1VisATT); - - sheathA1VisATT = new G4VisAttributes(G4Colour(0.5, 0.0 ,1.0)); - sheathA1VisATT->SetForceSolid(false); - sheathA1VisATT->SetVisibility(false); - logicSheathA1->SetVisAttributes(sheathA1VisATT); - logicSheathA1Cut2->SetVisAttributes(sheathA1VisATT); - logicSheathA1Mod->SetVisAttributes(sheathA1VisATT); - logicSheathA1Cut1->SetVisAttributes(sheathA1VisATT); - - sheathB1VisATT = new G4VisAttributes(G4Colour(1.0, 0.5 ,1.0)); - sheathB1VisATT->SetForceSolid(false); - sheathB1VisATT->SetVisibility(false); - logicSheathB1->SetVisAttributes(sheathB1VisATT); - logicSheathB1Cut2->SetVisAttributes(sheathB1VisATT); - logicSheathB1Mod->SetVisAttributes(sheathB1VisATT); - logicSheathB1Cut1->SetVisAttributes(sheathB1VisATT); - - - EndPlate2VisATT = new G4VisAttributes(G4Colour(0.5, 0.5, 0.5)); - EndPlate2VisATT->SetForceSolid(false); - EndPlate2VisATT->SetVisibility(true); - logicEndPlate2->SetVisAttributes(EndPlate2VisATT); - logicEndPlate1->SetVisAttributes(EndPlate2VisATT); - logicEndPlate2Cut2->SetVisAttributes(EndPlate2VisATT); - logicEndPlate2Mod->SetVisAttributes(EndPlate2VisATT); - logicEndPlate1Mod->SetVisAttributes(EndPlate2VisATT); - logicEndPlate2Cut1->SetVisAttributes(EndPlate2VisATT); - - return worldPhysical; -} - - -// ConstructMaterials() -// Construct all the materials needed for the ZED2Constructor. -void ZED2Constructor::ConstructMaterials() -{ - // Elements, isotopes and materials - G4Isotope *U234, *U235, *U238, *U236, *D2, *O16, *O17, - *Fe54, *Fe56, *Fe57, *Fe58, *Cr50, *Cr52, *Cr53, *Cr54, - *Si28, *Si29, *Si30, *Cu63, *Cu65, *Mn55, *Mg24, - *Mg25, *Mg26, *Zn64, *Zn66, *Zn67, *Zn68, *Zn70, - *Al27, *Ti46, *Ti47, *Ti48, *Ti49, *Ti50, *Na23, - *Ga69, *Ga71, *H1, *C12, *C13, *Zr90, *Zr91, - *Zr92, *Zr94, *Zr96, *Sn112, *Sn114, *Sn115, *Sn116, - *Sn117, *Sn118, *Sn119, *Sn120, *Sn122, *Sn124, - *Ca40, *Ca42, *Ca43, *Ca44, *Ca46, *Ca48, *B10, *B11, - *Li6, *Li7, *Gd152,*Gd154, *Gd155, *Gd156, *Gd157, - *Gd158, *Gd160,*V50, *V51; - G4Element *Oxygen, *Deuterium, *LEU, - *Cr, *Fe, *Si, *Cu, *Mn, *Mg, *Zn, *Al, - *Ti, *Na, *Ga, *Hydrogen, *C, *Zr, *Sn, *Ca, /*RU,*/ - *B, *Li, *Gd, *V, /*OxygenMod, *HydrogenMod, *OxygenRU,*/ - *FeAl, *CuAl,*FeZr, *CrZr, *OxygenZr, - *OxygenLEU, /*HydrogenLW,*/ *OxygenLW; - G4Material *World, *LEUMat, /*HeavyWater,*/ - *Aluminum57S, *AlPresT, *AlCalT, *H2O, *D2O, - /*Coolant,*/ *AnnulusGas, *Zr4, *Air, /*RUMat,*/ *Moderator, *Graphite; - - // Create the world environment - World = new G4Material("Galactic", 1, 1, 1.e-25*g/cm3, kStateGas,2.73*kelvin, 3.e-18*pascal); - - - //make Calcium isotopes and element - Ca40 = new G4Isotope("Ca40", 20, 40, 39.9625906*g/mole); - Ca42 = new G4Isotope("Ca42", 20, 42, 41.9586176*g/mole); - Ca43 = new G4Isotope("Ca43", 20, 43, 42.9587662*g/mole); - Ca44 = new G4Isotope("Ca44", 20, 44, 43.9554806*g/mole); - Ca46 = new G4Isotope("Ca46", 20, 46, 45.953689*g/mole); - Ca48 = new G4Isotope("Ca48", 20, 48, 47.952533*g/mole); - - Ca = new G4Element("Calcium", "Ca", 6); - Ca->AddIsotope(Ca40, 96.941*perCent); - Ca->AddIsotope(Ca42, 0.647*perCent); - Ca->AddIsotope(Ca43, 0.135*perCent); - Ca->AddIsotope(Ca44, 2.086*perCent); - Ca->AddIsotope(Ca46, 0.004*perCent); - Ca->AddIsotope(Ca48, 0.187*perCent); - - //make Boron isotopes and element - B10 = new G4Isotope("B10", 5, 10, 10.012937*g/mole); - B11 = new G4Isotope("B11", 5, 11, 11.009305*g/mole); - - B = new G4Element("Boron", "B", 2); - B->AddIsotope(B10, 19.9*perCent); - B->AddIsotope(B11, 80.1*perCent); - - //make Lithium isotopes and element - Li6 = new G4Isotope("Li6", 3, 6, 6.0151223*g/mole); - Li7 = new G4Isotope("Li7", 3, 7, 7.0160040*g/mole); - - Li = new G4Element("Lithium", "Li", 2); - Li->AddIsotope(Li6, 7.59 *perCent); - Li->AddIsotope(Li7, 92.41*perCent); - - //make Vanadium isotopes and element - V50 = new G4Isotope("V50", 23, 50, 49.9471609 *g/mole); - V51 = new G4Isotope("V51", 23, 51, 50.9439617 *g/mole); - - V = new G4Element("Vanadium", "V", 2); - V->AddIsotope(V50, 0.250 *perCent); - V->AddIsotope(V51, 99.750*perCent); - - - - - //make chromium isotopes and element - Cr50 = new G4Isotope("Cr50", 24, 50, 49.9460422*g/mole); - Cr52 = new G4Isotope("Cr52", 24, 52, 51.9405075*g/mole); - Cr53 = new G4Isotope("Cr53", 24, 53, 52.9406494*g/mole); - Cr54 = new G4Isotope("Cr54", 24, 54, 53.9388804*g/mole); - - Cr = new G4Element("Chromium", "Cr", 4); - Cr->AddIsotope(Cr50, 4.1737*perCent); - Cr->AddIsotope(Cr52, 83.7003*perCent); - Cr->AddIsotope(Cr53, 9.6726*perCent); - Cr->AddIsotope(Cr54, 2.4534*perCent); - - CrZr = new G4Element("Chromium", "Cr", 4); - CrZr->AddIsotope(Cr50, 4.10399884*perCent); - CrZr->AddIsotope(Cr52, 82.20818453*perCent); - CrZr->AddIsotope(Cr53, 9.50012786*perCent); - CrZr->AddIsotope(Cr54, 4.18768878*perCent); - - - //make iron isotopes and element - Fe54 = new G4Isotope("Fe54", 26, 54, 53.9396105*g/mole); - Fe56 = new G4Isotope("Fe56", 26, 56, 55.9349375*g/mole); - Fe57 = new G4Isotope("Fe57", 26, 57, 56.9353940*g/mole); - Fe58 = new G4Isotope("Fe58", 26, 58, 57.9332756*g/mole); - - Fe = new G4Element("Iron", "Fe", 4); - Fe->AddIsotope(Fe54, 5.80*perCent); - Fe->AddIsotope(Fe56, 91.72*perCent); - Fe->AddIsotope(Fe57, 2.20*perCent); - Fe->AddIsotope(Fe58, 0.28*perCent); - - //make iron element for Aluminium material in ZED-2 - FeAl = new G4Element("Iron", "Fe", 4); - FeAl->AddIsotope(Fe54, 0.02340*perCent); - FeAl->AddIsotope(Fe56, 0.36700*perCent); - FeAl->AddIsotope(Fe57, 0.00848*perCent); - FeAl->AddIsotope(Fe58, 0.00112*perCent); - - //make iron element for Aluminium material in ZED-2 - FeZr = new G4Element("Iron", "Fe", 4); - FeZr->AddIsotope(Fe54, 5.60198907*perCent); - FeZr->AddIsotope(Fe56, 91.9458541*perCent); - FeZr->AddIsotope(Fe57, 2.14094671*perCent); - FeZr->AddIsotope(Fe58, 0.31121012*perCent); - - //make Silicon isotopes and element - Si28 = new G4Isotope("Si28", 14, 28, 27.9769271*g/mole); - Si29 = new G4Isotope("Si29", 14, 29, 28.9764949*g/mole); - Si30 = new G4Isotope("Si30", 14, 30, 29.9737707*g/mole); - - Si = new G4Element("Silicon", "Si", 3); - Si->AddIsotope(Si28, 92.23*perCent); - Si->AddIsotope(Si29, 4.67*perCent); - Si->AddIsotope(Si30, 3.1*perCent); - - //make Magnesium isotopes and element - Mg24 = new G4Isotope("Mg24", 12, 24, 23.9850423*g/mole); - Mg25 = new G4Isotope("Mg25", 12, 25, 24.9858374*g/mole); - Mg26 = new G4Isotope("Mg26", 12, 26, 25.9825937 *g/mole); - - Mg = new G4Element("Magnesium", "Mg", 3); - Mg->AddIsotope(Mg24, 78.99*perCent); - Mg->AddIsotope(Mg25, 10.00*perCent); - Mg->AddIsotope(Mg26, 11.01*perCent); - - //make Manganese isotopes and element - Mn55 = new G4Isotope("Mn55", 25, 55, 54.9380471*g/mole); - - Mn = new G4Element("Manganese", "Mn", 1); - Mn->AddIsotope(Mn55, 100.00*perCent); - - //make Copper isotopes and element - Cu63 = new G4Isotope("Cu63", 29, 63, 62.9295989*g/mole); - Cu65 = new G4Isotope("Cu65", 29, 65, 64.9277929 *g/mole); - - Cu = new G4Element("Copper", "Cu", 2); - Cu->AddIsotope(Cu63, 69.17*perCent); - Cu->AddIsotope(Cu65, 30.83*perCent); - - //make copper for Al - CuAl = new G4Element("Copper", "Cu", 2); - CuAl->AddIsotope(Cu63, 0.01383*perCent); - CuAl->AddIsotope(Cu65, 0.00617*perCent); - - //make Aluminum isotopes and element - Al27 = new G4Isotope("Al27", 13, 27, 26.9815386 *g/mole); - - Al = new G4Element("Aluminum", "Al", 1); - Al->AddIsotope(Al27, 100.00*perCent); - - //make Zirconium isotopes and element - Zr90 = new G4Isotope("Zr90", 40, 90, 89.9047026*g/mole); - Zr91 = new G4Isotope("Zr91", 40, 91, 90.9056439*g/mole); - Zr92 = new G4Isotope("Zr92", 40, 92, 91.9050386*g/mole); - Zr94 = new G4Isotope("Zr94", 40, 94, 93.9063148*g/mole); - Zr96 = new G4Isotope("Zr96", 40, 96, 95.908275*g/mole); - - - - Zr = new G4Element("Zirconium", "Zr", 5); - Zr->AddIsotope(Zr90, 0.5075558873*perCent); //ATM% - Zr->AddIsotope(Zr91, 0.1116101232*perCent); - Zr->AddIsotope(Zr92, 0.1722780975*perCent); - Zr->AddIsotope(Zr94, 0.1791179604*perCent); - Zr->AddIsotope(Zr96, 0.0294379317*perCent); - - - //make Zinc isotopes and element - Zn64 = new G4Isotope("Zn64", 30, 64, 63.9291448*g/mole); - Zn66 = new G4Isotope("Zn66", 30, 66, 65.9260347*g/mole); - Zn67 = new G4Isotope("Zn67", 30, 67, 66.9271291*g/mole); - Zn68 = new G4Isotope("Zn68", 30, 68, 67.9248459*g/mole); - Zn70 = new G4Isotope("Zn70", 30, 70, 69.925325*g/mole); - - Zn = new G4Element("Zinc", "Zn", 5); - Zn->AddIsotope(Zn64, 48.63*perCent); - Zn->AddIsotope(Zn66, 27.90*perCent); - Zn->AddIsotope(Zn67, 4.10*perCent); - Zn->AddIsotope(Zn68, 18.75*perCent); - Zn->AddIsotope(Zn70, 0.62*perCent); - - //make Tin isotopes and element - Sn112 = new G4Isotope("Sn112", 50, 112, 111.904826*g/mole); - Sn114 = new G4Isotope("Sn114", 50, 114, 113.902784*g/mole); - Sn115 = new G4Isotope("Sn115", 50, 115, 114.903348*g/mole); - Sn116 = new G4Isotope("Sn116", 50, 116, 115.901747*g/mole); - Sn117 = new G4Isotope("Sn117", 50, 117, 116.902956*g/mole); - Sn118 = new G4Isotope("Sn118", 50, 118, 117.901609*g/mole); - Sn119 = new G4Isotope("Sn119", 50, 119, 118.903311*g/mole); - Sn120 = new G4Isotope("Sn120", 50, 120, 119.9021991*g/mole); - Sn122 = new G4Isotope("Sn122", 50, 122, 121.9034404*g/mole); - Sn124 = new G4Isotope("Sn124", 50, 124, 123.9052743*g/mole); - - Sn = new G4Element("Tin", "Sn", 10); - Sn->AddIsotope(Sn112, 0.97*perCent); - Sn->AddIsotope(Sn114, 0.66*perCent); - Sn->AddIsotope(Sn115, 0.34*perCent); - Sn->AddIsotope(Sn116, 14.54*perCent); - Sn->AddIsotope(Sn117, 7.68*perCent); - Sn->AddIsotope(Sn118, 24.22*perCent); - Sn->AddIsotope(Sn119, 8.59*perCent); - Sn->AddIsotope(Sn120, 32.58*perCent); - Sn->AddIsotope(Sn122, 4.63*perCent); - Sn->AddIsotope(Sn124, 0.0*perCent); - - // Soudium Isotopes - Na23 = new G4Isotope("Na23", 11, 23, 22.9897677*g/mole); - - // Naturally occuring Soudiium - Na = new G4Element("Soudium", "Na", 1); - Na->AddIsotope(Na23, 1.); - - // Gallium Isotopes - Ga69 = new G4Isotope("Ga69", 31, 69, 68.9255809*g/mole); - Ga71 = new G4Isotope("Ga71", 31, 71, 70.9247005*g/mole); - - // Naturally Occuring Gallium - Ga = new G4Element("Gallium", "Ga", 2); - Ga->AddIsotope(Ga69, 60.108*perCent); - Ga->AddIsotope(Ga71, 39.892*perCent); - - - //make Gadolinium isotopes and element - Gd152 = new G4Isotope("Gd152", 64, 152, 151.919786*g/mole); - Gd154 = new G4Isotope("Gd154", 64, 154, 153.920861*g/mole); - Gd155 = new G4Isotope("Gd155", 64, 155, 154.922618*g/mole); - Gd156 = new G4Isotope("Gd156", 64, 156, 155.922118*g/mole); - Gd157 = new G4Isotope("Gd157", 64, 157, 156.923956*g/mole); - Gd158 = new G4Isotope("Gd158", 64, 158, 157.924019*g/mole); - Gd160 = new G4Isotope("Gd160", 64, 160, 159.927049*g/mole); - - - Gd = new G4Element("Gadolinium", "Gd", 7); - Gd->AddIsotope(Gd152, 0.20*perCent); - Gd->AddIsotope(Gd154, 2.18*perCent); - Gd->AddIsotope(Gd155, 14.80*perCent); - Gd->AddIsotope(Gd156, 20.47*perCent); - Gd->AddIsotope(Gd157, 15.65*perCent); - Gd->AddIsotope(Gd158, 24.84*perCent); - Gd->AddIsotope(Gd160, 21.86*perCent); - - - //make titanium isotopes and element - Ti46 = new G4Isotope("Ti46", 22, 46, 45.9526294*g/mole); - Ti47 = new G4Isotope("Ti47", 22, 47, 46.9517640*g/mole); - Ti48 = new G4Isotope("Ti48", 22, 48, 47.9479473*g/mole); - Ti49 = new G4Isotope("Ti49", 22, 49, 48.9478711*g/mole); - Ti50 = new G4Isotope("Ti50", 22, 50, 49.9447921*g/mole); - - Ti = new G4Element("Titanium", "Zn", 5); - Ti->AddIsotope(Ti46, 8.25*perCent); - Ti->AddIsotope(Ti47, 7.44*perCent); - Ti->AddIsotope(Ti48, 73.72*perCent); - Ti->AddIsotope(Ti49, 5.41*perCent); - Ti->AddIsotope(Ti50, 5.18*perCent); - - //make Carbon isotopes and element - C12 = new G4Isotope("C12", 6, 12, 12.0*g/mole); - C13 = new G4Isotope("C13", 6, 13, 13.00335*g/mole); - - C = new G4Element("Carbon", "C", 2); - C->AddIsotope(C12, 98.83*perCent); - C->AddIsotope(C13, 1.07*perCent); - - - // Make the uranium isotopes and element - U234 = new G4Isotope("U234", 92, 234, 234.0410*g/mole); - U235 = new G4Isotope("U235", 92, 235, 235.0439*g/mole); - U236 = new G4Isotope("U236", 92, 236, 236.0456*g/mole); - U238 = new G4Isotope("U238", 92, 238, 238.0508*g/mole); - - - - // Make hydrogen isotopes and elements - H1 = new G4Isotope("H1", 1, 1, 1.0078*g/mole); - Hydrogen = new G4Element("Hydrogen", "H", 1); - Hydrogen->AddIsotope(H1, 100*perCent); - - - D2 = new G4Isotope("D2", 1, 2, 2.014*g/mole); - Deuterium = new G4Element("Deuterium", "D", 1); - Deuterium->AddIsotope(D2, 100*perCent); - - // Make Oxygen isotopes and elements - O16 = new G4Isotope("O16", 8, 16, 15.9949146*g/mole); - O17 = new G4Isotope("O17", 8, 17, 16.9991312*g/mole); - // O18 = new G4Isotope("O18", 8, 18, 17.9991603*g/mole); - Oxygen = new G4Element("Oxygen", "O", 2); - Oxygen->AddIsotope(O16, 99.963868927*perCent); - Oxygen->AddIsotope(O17, 0.036131072*perCent); - - OxygenZr = new G4Element("Oxygen", "O", 1); - OxygenZr->AddIsotope(O16, 0.688463*perCent); - - OxygenLEU = new G4Element("Oxygen", "O", 1); - OxygenLEU->AddIsotope(O16, 100.0*perCent); - - // Making Oxygen for the heavy water - /*OxygenMod = new G4Element("OxygenMod", "OM", 2); - OxygenMod->AddIsotope(O16, 33.313111651*perCent); - OxygenMod->AddIsotope(O17, 0.020000116*perCent);*/ - - // Making Oxygen for the light water - OxygenLW = new G4Element("OxygenLW", "OLW", 2); - OxygenLW->AddIsotope(O16, 99.995998592*perCent);; - OxygenLW->AddIsotope(O17, 0.004001407*perCent); - - - // Making hydrogen for the lightwater - Hydrogen = new G4Element("HydrogenLW", "HLW", 1); - Hydrogen->AddIsotope(H1, 100*perCent); - - - LEU = new G4Element("Low Enriched Uranium","LEU",4); - LEU->AddIsotope(U234, 0.007432*perCent); - LEU->AddIsotope(U235, 0.9583*perCent); - LEU->AddIsotope(U236, 0.000239*perCent); - LEU->AddIsotope(U238, 99.0341*perCent); - - - // Make the LEU material - LEUMat = new G4Material("U235 Material", 10.52*g/cm3, 2,kStateSolid, 299.51*kelvin); - LEUMat->AddElement(LEU,88.146875681*perCent); - LEUMat->AddElement(OxygenLEU,11.853119788*perCent); - - - - // Create H20 material - H2O = new G4Material("Light Water", 0.99745642056*g/cm3, 2, kStateLiquid); - H2O->AddElement(OxygenLW, 1); - H2O->AddElement(Hydrogen, 2); - - D2O = new G4Material("Heavy Water", 1.10480511492*g/cm3, 2, kStateLiquid); - D2O->AddElement(Oxygen, 1); - D2O->AddElement(Deuterium, 2); - -// Graphite = new G4Material("Graphite", 6., 12.0107*g/mole, 1.64*g/cm3); - Graphite = new G4Material("Graphite", 1.64*g/cm3, 5, kStateSolid); - Graphite->AddElement(Li, 1.7e-5*perCent); - Graphite->AddElement(B, 3.e-5*perCent); - Graphite->AddElement(C, 99.99697797*perCent); - Graphite->AddElement(V, 0.00300031*perCent); - Graphite->AddElement(Gd, 2.e-5*perCent); - - - - // Make Argon - G4Element* Ar = new G4Element("Argon", "Ar", 18., 39.948*g/mole); - // Make Argon - G4Element* N = new G4Element("Nitrogen", "N", 7., 14.01*g/mole); - - - - - //Create Aluminum57S (Reactor Calandria) - Aluminum57S = new G4Material("Aluminuum 57S", 2.7*g/cm3, 8, kStateSolid); - Aluminum57S->AddElement(Al, 96.7*perCent); - Aluminum57S->AddElement(Si, 0.25*perCent); - Aluminum57S->AddElement(Fe, 0.4*perCent); - Aluminum57S->AddElement(Cu, 0.1*perCent); - Aluminum57S->AddElement(Mn, 0.1*perCent); - Aluminum57S->AddElement(Mg, 2.2*perCent); - Aluminum57S->AddElement(Cr, 0.15*perCent); - Aluminum57S->AddElement(Zn, 0.1*perCent); - - //Create AlPresT (pressure Tube) -// AlPresT = new G4Material("Aluminuum 6061", 2.712631*g/cm3, 8, kStateSolid); - AlPresT = new G4Material("Aluminuum 6061", 2.712631*g/cm3, 8, kStateSolid); - - AlPresT->AddElement(Al, 99.1244424*perCent); - AlPresT->AddElement(Si, 0.5922414*perCent); - AlPresT->AddElement(Fe, 0.1211379*perCent); - AlPresT->AddElement(Cu, 0.0018171*perCent); - AlPresT->AddElement(Mn, 0.0383626*perCent); - //AlPresT->AddElement(Mg, 0.7000*perCent); - AlPresT->AddElement(Cr, 0.1211405*perCent); - AlPresT->AddElement(Li, 0.00075712*perCent); - AlPresT->AddElement(B, 0.00010095*perCent); - //AlPresT->AddElement(Zn, 0.0230*perCent); - //AlPresT->AddElement(Na, 0.0090*perCent); - //AlPresT->AddElement(Ga, 0.0120*perCent); - //AlPresT->AddElement(Ti, 0.0110*perCent); - - //Create AlCalT (calandria Tube) -// AlCalT = new G4Material("Aluminuum 6063", 2.684951*g/cm3, 8, kStateSolid); - AlCalT = new G4Material("Aluminuum 6063", 2.684951*g/cm3, 8, kStateSolid); - AlCalT->AddElement(Al, 99.18675267*perCent); - AlCalT->AddElement(Si, 0.509640251*perCent); - AlCalT->AddElement(Fe, 0.241396625*perCent); - AlCalT->AddElement(Li, 0.00754387*perCent); - AlCalT->AddElement(B, 0.000100586*perCent); - //AlCalT->AddElement(Cu, 0.0590*perCent); - AlCalT->AddElement(Mn, 0.041228175*perCent); - //AlCalT->AddElement(Mg, 0.5400*perCent); - //AlCalT->AddElement(Cr, 0.0100*perCent); - //AlCalT->AddElement(Zn, 0.0340*perCent); - //AlCalT->AddElement(Na, 0.0170*perCent); - AlCalT->AddElement(Gd, 0.000010059*perCent); - AlCalT->AddElement(Ti, 0.041228175*perCent); - - - Moderator = new G4Material("Moderator", 1.102597*g/cm3, 2, kStateLiquid, 299.51*kelvin); - Moderator->AddMaterial(D2O, 98.705*perCent); - Moderator->AddMaterial(H2O, 1.295*perCent); - - //Create Annulus Gas - AnnulusGas = new G4Material("AnnulusGas", 0.0012*g/cm3, 2, kStateGas/*, - 448.72*kelvin*/); - AnnulusGas->AddElement(C,27.11*perCent); - AnnulusGas->AddElement(Oxygen,72.89*perCent); - - - Zr4 = new G4Material("Zircaloy-4", 6.55*g/cm3, 4, kStateSolid); - Zr4->AddElement(Oxygen, 0.12*perCent); - Zr4->AddElement(CrZr, 0.11*perCent); - Zr4->AddElement(FeZr, 0.22*perCent); - Zr4->AddElement(Zr, 99.58*perCent); - - // Make Air - Air = new G4Material("Air", 1.29*mg/cm3, 5, kStateGas); - Air->AddElement(N, 74.74095914*perCent); - Air->AddElement(Oxygen, 23.49454694*perCent); - Air->AddElement(Ar, 1.274547311*perCent); - Air->AddElement(Li, 0.474350981*perCent); - Air->AddElement(C, 0.015595629*perCent); - //Air->AddElement(Hydrogen, 0.009895657); - - - - - - // Add materials to the map indexed by either ZA (format ZZAAA or ZZ) - // For composite materials: world is 0, heavy water is 1, UHW is 2 - matMap["World"] = World; - matMap["LEUMat"] = LEUMat; - matMap["Graphite"] = Graphite; - matMap["Al57S"] = Aluminum57S; - matMap["AlPresT"] = AlPresT; - matMap["AlCalT"] = AlCalT; - matMap["Zr4"] = Zr4; - matMap["Air"] = Air; - //matMap["RUMat"] = RUMat; - matMap["Moderator"] = Moderator; - matMap["Coolant"] = H2O; - /* G4Isotope *U234, *U235, *U238, *U236, *D2, *O16, *O17, - *Fe54, *Fe56, *Fe57, *Fe58, *Cr50, *Cr52, *Cr53, *Cr54, - *Si28, *Si29, *Si30, *Cu63, *Cu65, *Mn55, *Mg24, - *Mg25, *Mg26, *Zn64, *Zn66, *Zn67, *Zn68, *Zn70, - *Al27, *Ti46, *Ti47, *Ti48, *Ti49, *Ti50, *Na23, - *Ga69, *Ga71, *H1, *C12, *C13, *Zr90, *Zr91, - *Zr92, *Zr94, *Zr96, *Sn112, *Sn114, *Sn115, *Sn116, - *Sn117, *Sn118, *Sn119, *Sn120, *Sn122, *Sn124, - *Ca40, *Ca42, *Ca43, *Ca44, *Ca46, *Ca48, *B10, *B11, - *Li6, *Li7, *Gd152,*Gd154, *Gd155, *Gd156, *Gd157, - *Gd158, *Gd160,*V50, *V51; - G4Element *Oxygen, *Deuterium, *LEU, - *Cr, *Fe, *Si, *Cu, *Mn, *Mg, *Zn, *Al, - *Ti, *Na, *Ga, *Hydrogen, *C, *Zr, *Sn, *Ca, *RU, - *B, *Li, *Gd, *V, *OxygenMod, *HydrogenMod, *OxygenRU, - *FeAl, *CuAl,*FeZr, *CrZr, *OxygenZr, - *OxygenLEU, *HydrogenLW, *OxygenLW; - G4Material *World, *LEUMat, *HeavyWater, - *Aluminum57S, *AlPresT, *AlCalT, *H2O, - *Coolant, *AnnulusGas, *Zr4, *Air, *RUMat, *Moderator, *Graphite; - - // Create the world environment - World = new G4Material("Galactic", 1, 1, 1.e-25*g/cm3, kStateGas, - 2.73*kelvin, 3.e-18*pascal); - - //make Calcium isotopes and element - Ca40 = new G4Isotope("Ca40", 20, 40, 39.9625906*g/mole); - Ca42 = new G4Isotope("Ca42", 20, 42, 41.9586176*g/mole); - Ca43 = new G4Isotope("Ca43", 20, 43, 42.9587662*g/mole); - Ca44 = new G4Isotope("Ca44", 20, 44, 43.9554806*g/mole); - Ca46 = new G4Isotope("Ca46", 20, 46, 45.953689*g/mole); - Ca48 = new G4Isotope("Ca48", 20, 48, 47.952533*g/mole); - - Ca = new G4Element("Calcium", "Ca", 6); - Ca->AddIsotope(Ca40, 96.941*perCent); - Ca->AddIsotope(Ca42, 0.647*perCent); - Ca->AddIsotope(Ca43, 0.135*perCent); - Ca->AddIsotope(Ca44, 2.086*perCent); - Ca->AddIsotope(Ca46, 0.004*perCent); - Ca->AddIsotope(Ca48, 0.187*perCent); - - //make Boron isotopes and element - B10 = new G4Isotope("B10", 5, 10, 10.012937*g/mole); - B11 = new G4Isotope("B11", 5, 11, 11.009305*g/mole); - - B = new G4Element("Boron", "B", 2); - B->AddIsotope(B10, 19.9*perCent); - B->AddIsotope(B11, 80.1*perCent); - - //make Lithium isotopes and element - Li6 = new G4Isotope("Li6", 3, 6, 6.0151223*g/mole); - Li7 = new G4Isotope("Li7", 3, 7, 7.0160040*g/mole); - - Li = new G4Element("Lithium", "Li", 2); - Li->AddIsotope(Li6, 7.59 *perCent); - Li->AddIsotope(Li7, 92.41*perCent); - - //make Vanadium isotopes and element - V50 = new G4Isotope("V50", 23, 50, 49.9471609 *g/mole); - V51 = new G4Isotope("V51", 23, 51, 50.9439617 *g/mole); - - V = new G4Element("Vanadium", "V", 2); - V->AddIsotope(V50, 0.250 *perCent); - V->AddIsotope(V51, 99.750*perCent); - - - - - //make chromium isotopes and element - Cr50 = new G4Isotope("Cr50", 24, 50, 49.9460422*g/mole); - Cr52 = new G4Isotope("Cr52", 24, 52, 51.9405075*g/mole); - Cr53 = new G4Isotope("Cr53", 24, 53, 52.9406494*g/mole); - Cr54 = new G4Isotope("Cr54", 24, 54, 53.9388804*g/mole); - - Cr = new G4Element("Chromium", "Cr", 4); - Cr->AddIsotope(Cr50, 4.1737*perCent); - Cr->AddIsotope(Cr52, 83.7003*perCent); - Cr->AddIsotope(Cr53, 9.6726*perCent); - Cr->AddIsotope(Cr54, 2.4534*perCent); - - CrZr = new G4Element("Chromium", "Cr", 4); - CrZr->AddIsotope(Cr50, 7.244845E-3*perCent); - CrZr->AddIsotope(Cr52, 0.145123227*perCent); - CrZr->AddIsotope(Cr53, 0.016770705*perCent); - CrZr->AddIsotope(Cr54, 0.007392584*perCent); - - - //make iron isotopes and element - Fe54 = new G4Isotope("Fe54", 26, 54, 53.9396105*g/mole); - Fe56 = new G4Isotope("Fe56", 26, 56, 55.9349375*g/mole); - Fe57 = new G4Isotope("Fe57", 26, 57, 56.9353940*g/mole); - Fe58 = new G4Isotope("Fe58", 26, 58, 57.9332756*g/mole); - - Fe = new G4Element("Iron", "Fe", 4); - Fe->AddIsotope(Fe54, 5.80*perCent); - Fe->AddIsotope(Fe56, 91.72*perCent); - Fe->AddIsotope(Fe57, 2.20*perCent); - Fe->AddIsotope(Fe58, 0.28*perCent); - - //make iron element for Aluminium material in ZED-2 - FeAl = new G4Element("Iron", "Fe", 4); - FeAl->AddIsotope(Fe54, 0.02340*perCent); - FeAl->AddIsotope(Fe56, 0.36700*perCent); - FeAl->AddIsotope(Fe57, 0.00848*perCent); - FeAl->AddIsotope(Fe58, 0.00112*perCent); - - //make iron element for Aluminium material in ZED-2 - FeZr = new G4Element("Iron", "Fe", 4); - FeZr->AddIsotope(Fe54, 1.84154E-2*perCent); - FeZr->AddIsotope(Fe56, 3.022533E-1*perCent); - FeZr->AddIsotope(Fe57, 7.037927E-3*perCent); - FeZr->AddIsotope(Fe58, 1.02304E-3*perCent); - //make Silicon isotopes and element - Si28 = new G4Isotope("Si28", 14, 28, 27.9769271*g/mole); - Si29 = new G4Isotope("Si29", 14, 29, 28.9764949*g/mole); - Si30 = new G4Isotope("Si30", 14, 30, 29.9737707*g/mole); - - Si = new G4Element("Silicon", "Si", 3); - Si->AddIsotope(Si28, 92.23*perCent); - Si->AddIsotope(Si29, 4.67*perCent); - Si->AddIsotope(Si30, 3.1*perCent); - - //make Magnesium isotopes and element - Mg24 = new G4Isotope("Mg24", 12, 24, 23.9850423*g/mole); - Mg25 = new G4Isotope("Mg25", 12, 25, 24.9858374*g/mole); - Mg26 = new G4Isotope("Mg26", 12, 26, 25.9825937 *g/mole); - - Mg = new G4Element("Magnesium", "Mg", 3); - Mg->AddIsotope(Mg24, 78.99*perCent); - Mg->AddIsotope(Mg25, 10.00*perCent); - Mg->AddIsotope(Mg26, 11.01*perCent); - - //make Manganese isotopes and element - Mn55 = new G4Isotope("Mn55", 25, 55, 54.9380471*g/mole); - - Mn = new G4Element("Manganese", "Mn", 1); - Mn->AddIsotope(Mn55, 100.00*perCent); - - //make Copper isotopes and element - Cu63 = new G4Isotope("Cu63", 29, 63, 62.9295989*g/mole); - Cu65 = new G4Isotope("Cu65", 29, 65, 64.9277929 *g/mole); - - Cu = new G4Element("Copper", "Cu", 2); - Cu->AddIsotope(Cu63, 69.17*perCent); - Cu->AddIsotope(Cu65, 30.83*perCent); - - //make copper for Al - CuAl = new G4Element("Copper", "Cu", 2); - CuAl->AddIsotope(Cu63, 0.01383*perCent); - CuAl->AddIsotope(Cu65, 0.00617*perCent); - - //make Aluminum isotopes and element - Al27 = new G4Isotope("Al27", 13, 27, 26.9815386 *g/mole); - - Al = new G4Element("Aluminum", "Al", 1); - Al->AddIsotope(Al27, 100.00*perCent); - - //make Zirconium isotopes and element - Zr90 = new G4Isotope("Zr90", 40, 90, 89.9047026*g/mole); - Zr91 = new G4Isotope("Zr91", 40, 91, 90.9056439*g/mole); - Zr92 = new G4Isotope("Zr92", 40, 92, 91.9050386*g/mole); - Zr94 = new G4Isotope("Zr94", 40, 94, 93.9063148*g/mole); - Zr96 = new G4Isotope("Zr96", 40, 96, 95.908275*g/mole); - - - - Zr = new G4Element("Zirconium", "Zr", 5); - Zr->AddIsotope(Zr90, 50.1407*perCent); //ATM% - Zr->AddIsotope(Zr91, 11.0258*perCent); - Zr->AddIsotope(Zr92, 17.0191*perCent); - Zr->AddIsotope(Zr94, 17.6948*perCent); - Zr->AddIsotope(Zr96, 2.90813*perCent); - - //make Zinc isotopes and element - Zn64 = new G4Isotope("Zn64", 30, 64, 63.9291448*g/mole); - Zn66 = new G4Isotope("Zn66", 30, 66, 65.9260347*g/mole); - Zn67 = new G4Isotope("Zn67", 30, 67, 66.9271291*g/mole); - Zn68 = new G4Isotope("Zn68", 30, 68, 67.9248459*g/mole); - Zn70 = new G4Isotope("Zn70", 30, 70, 69.925325*g/mole); - - Zn = new G4Element("Zinc", "Zn", 5); - Zn->AddIsotope(Zn64, 48.63*perCent); - Zn->AddIsotope(Zn66, 27.90*perCent); - Zn->AddIsotope(Zn67, 4.10*perCent); - Zn->AddIsotope(Zn68, 18.75*perCent); - Zn->AddIsotope(Zn70, 0.62*perCent); - - //make Tin isotopes and element - Sn112 = new G4Isotope("Sn112", 50, 112, 111.904826*g/mole); - Sn114 = new G4Isotope("Sn114", 50, 114, 113.902784*g/mole); - Sn115 = new G4Isotope("Sn115", 50, 115, 114.903348*g/mole); - Sn116 = new G4Isotope("Sn116", 50, 116, 115.901747*g/mole); - Sn117 = new G4Isotope("Sn117", 50, 117, 116.902956*g/mole); - Sn118 = new G4Isotope("Sn118", 50, 118, 117.901609*g/mole); - Sn119 = new G4Isotope("Sn119", 50, 119, 118.903311*g/mole); - Sn120 = new G4Isotope("Sn120", 50, 120, 119.9021991*g/mole); - Sn122 = new G4Isotope("Sn122", 50, 122, 121.9034404*g/mole); - Sn124 = new G4Isotope("Sn124", 50, 124, 123.9052743*g/mole); - - Sn = new G4Element("Tin", "Sn", 10); - Sn->AddIsotope(Sn112, 0.97*perCent); - Sn->AddIsotope(Sn114, 0.66*perCent); - Sn->AddIsotope(Sn115, 0.34*perCent); - Sn->AddIsotope(Sn116, 14.54*perCent); - Sn->AddIsotope(Sn117, 7.68*perCent); - Sn->AddIsotope(Sn118, 24.22*perCent); - Sn->AddIsotope(Sn119, 8.59*perCent); - Sn->AddIsotope(Sn120, 32.58*perCent); - Sn->AddIsotope(Sn122, 4.63*perCent); - Sn->AddIsotope(Sn124, 0.0*perCent); - - // Soudium Isotopes - Na23 = new G4Isotope("Na23", 11, 23, 22.9897677*g/mole); - - // Naturally occuring Soudiium - Na = new G4Element("Soudium", "Na", 1); - Na->AddIsotope(Na23, 1.); - - // Gallium Isotopes - Ga69 = new G4Isotope("Ga69", 31, 69, 68.9255809*g/mole); - Ga71 = new G4Isotope("Ga71", 31, 71, 70.9247005*g/mole); - - // Naturally Occuring Gallium - Ga = new G4Element("Gallium", "Ga", 2); - Ga->AddIsotope(Ga69, 60.108*perCent); - Ga->AddIsotope(Ga71, 39.892*perCent); - - - //make Gadolinium isotopes and element - Gd152 = new G4Isotope("Gd152", 64, 152, 151.919786*g/mole); - Gd154 = new G4Isotope("Gd154", 64, 154, 153.920861*g/mole); - Gd155 = new G4Isotope("Gd155", 64, 155, 154.922618*g/mole); - Gd156 = new G4Isotope("Gd156", 64, 156, 155.922118*g/mole); - Gd157 = new G4Isotope("Gd157", 64, 157, 156.923956*g/mole); - Gd158 = new G4Isotope("Gd158", 64, 158, 157.924019*g/mole); - Gd160 = new G4Isotope("Gd160", 64, 160, 159.927049*g/mole); - - - Gd = new G4Element("Gadolinium", "Gd", 7); - Gd->AddIsotope(Gd152, 0.20*perCent); - Gd->AddIsotope(Gd154, 2.18*perCent); - Gd->AddIsotope(Gd155, 14.80*perCent); - Gd->AddIsotope(Gd156, 20.47*perCent); - Gd->AddIsotope(Gd157, 15.65*perCent); - Gd->AddIsotope(Gd158, 24.84*perCent); - Gd->AddIsotope(Gd160, 21.86*perCent); - - - //make titanium isotopes and element - Ti46 = new G4Isotope("Ti46", 22, 46, 45.9526294*g/mole); - Ti47 = new G4Isotope("Ti47", 22, 47, 46.9517640*g/mole); - Ti48 = new G4Isotope("Ti48", 22, 48, 47.9479473*g/mole); - Ti49 = new G4Isotope("Ti49", 22, 49, 48.9478711*g/mole); - Ti50 = new G4Isotope("Ti50", 22, 50, 49.9447921*g/mole); - - Ti = new G4Element("Titanium", "Zn", 5); - Ti->AddIsotope(Ti46, 8.25*perCent); - Ti->AddIsotope(Ti47, 7.44*perCent); - Ti->AddIsotope(Ti48, 73.72*perCent); - Ti->AddIsotope(Ti49, 5.41*perCent); - Ti->AddIsotope(Ti50, 5.18*perCent); - - //make Carbon isotopes and element - C12 = new G4Isotope("C12", 6, 12, 12.0*g/mole); - C13 = new G4Isotope("C13", 6, 13, 13.00335*g/mole); - - C = new G4Element("Carbon", "C", 2); - C->AddIsotope(C12, 98.83*perCent); - C->AddIsotope(C13, 1.07*perCent); - - - // Make the uranium isotopes and element - U234 = new G4Isotope("U234", 92, 234, 234.0410*g/mole); - U235 = new G4Isotope("U235", 92, 235, 235.0439*g/mole); - U236 = new G4Isotope("U236", 92, 236, 236.0456*g/mole); - U238 = new G4Isotope("U238", 92, 238, 238.0508*g/mole); - - - - // Make heavy water isotopes and elements - H1 = new G4Isotope("H1", 1, 1, 1.0078*g/mole); - Hydrogen = new G4Element("Hydrogen", "H", 1); - Hydrogen->AddIsotope(H1, 100*perCent); - - - D2 = new G4Isotope("D2", 1, 2, 2.014*g/mole); - Deuterium = new G4Element("Deuterium", "D", 1); - Deuterium->AddIsotope(D2, 100*perCent); - - - O16 = new G4Isotope("O16", 8, 16, 15.9949146*g/mole); - O17 = new G4Isotope("O17", 8, 17, 16.9991312*g/mole); - // O18 = new G4Isotope("O18", 8, 18, 17.9991603*g/mole); - Oxygen = new G4Element("Oxygen", "O", 1); - Oxygen->AddIsotope(O16, 100*perCent); - - OxygenZr = new G4Element("Oxygen", "O", 1); - OxygenZr->AddIsotope(O16, 0.688463*perCent); - - - OxygenRU = new G4Element("OxygenRU", "O", 2); - OxygenRU->AddIsotope(O16, 11.843718*perCent); - OxygenRU->AddIsotope(O17, 0.004502*perCent); - - - // Making Oxygen for the heavy water - OxygenMod = new G4Element("OxygenMod", "OM", 2); - OxygenMod->AddIsotope(O16, 33.313111651*perCent);; - OxygenMod->AddIsotope(O17, 0.020000116*perCent); - - -// Making hydrogen for the hwavy water - HydrogenMod = new G4Element("HydrogenMod", "HM", 2); - HydrogenMod->AddIsotope(H1, 0.958387035*perCent); - HydrogenMod->AddIsotope(D2, 65.708501196*perCent); - - - // Making Oxygen for the light water - OxygenLW = new G4Element("OxygenLW", "OLW", 2); - OxygenLW->AddIsotope(O16, 3.333194E+1*perCent);; - OxygenLW->AddIsotope(O17, 1.3338E-3*perCent); - - -// Making hydrogen for the lightwater - HydrogenLW = new G4Element("HydrogenLW", "HLW", 1); - HydrogenLW->AddIsotope(H1, 6.669057E+1*perCent); - - - LEU = new G4Element("Low Enriched Uranium","LEU",4); - LEU->AddIsotope(U234, 0.007432*perCent); - LEU->AddIsotope(U235, 0.9583*perCent); - LEU->AddIsotope(U236, 0.000239*perCent); - LEU->AddIsotope(U238, 99.0341*perCent); - - - - OxygenLEU = new G4Element("Oxygen", "O", 1); - OxygenLEU->AddIsotope(O16, 100.0*perCent); - - // Make Recovered Uranium - RU = new G4Element("Recovered Uranium","RU",4); - RU->AddIsotope(U234, 0.01308*perCent); - RU->AddIsotope(U235, 0.8476*perCent); - RU->AddIsotope(U236, 0.2011*perCent); - RU->AddIsotope(U238, 87.09*perCent); - - - // Make the LEU material - LEUMat = new G4Material("U235 Material", 10.52*g/cm3, 2,kStateSolid, 299.51*kelvin); - LEUMat->AddElement(LEU,1); - LEUMat->AddElement(OxygenLEU,2); - - - // Make the RUfuel material - RUMat = new G4Material("RU Material", 10.45*g/cm3, 2, kStateSolid, 298.55*kelvin); - - RUMat->AddElement(RU,1); - RUMat->AddElement(OxygenRU,1); - - // Create H20 material - H2O = new G4Material("Light Water", 0.99745642056*g/cm3, 2, kStateLiquid); - H2O->AddElement(OxygenLW, 1); - H2O->AddElement(HydrogenLW, 1); - - - // Make the heavy water material - HeavyWater = new G4Material("Heavy Water", 1.10480511492*g/cm3, 2, kStateLiquid); - HeavyWater->AddElement(HydrogenMod, 1); - HeavyWater->AddElement(OxygenMod, 1); - - - -// Graphite = new G4Material("Graphite", 6., 12.0107*g/mole, 1.64*g/cm3); - Graphite = new G4Material("Graphite", 1.64*g/cm3, 5, kStateSolid); - Graphite->AddElement(Li, 1.7e-5*perCent); - Graphite->AddElement(B, 3.e-5*perCent); - Graphite->AddElement(C, 99.99697797*perCent); - Graphite->AddElement(V, 0.00300031*perCent); - Graphite->AddElement(Gd, 2.e-5*perCent); - - - - // Make Argon - G4Element* Ar = new G4Element("Argon", "Ar", 18., 39.948*g/mole); - // Make Argon - G4Element* N = new G4Element("Nitrogen", "N", 7., 14.01*g/mole); - - - - - //Create Aluminum57S (Reactor Calandria) - Aluminum57S = new G4Material("Aluminuum 57S", 2.7*g/cm3, 8, kStateSolid); - Aluminum57S->AddElement(Al, 96.7*perCent); - Aluminum57S->AddElement(Si, 0.25*perCent); - Aluminum57S->AddElement(Fe, 0.4*perCent); - Aluminum57S->AddElement(Cu, 0.1*perCent); - Aluminum57S->AddElement(Mn, 0.1*perCent); - Aluminum57S->AddElement(Mg, 2.2*perCent); - Aluminum57S->AddElement(Cr, 0.15*perCent); - Aluminum57S->AddElement(Zn, 0.1*perCent); - - //Create AlPresT (pressure Tube) -// AlPresT = new G4Material("Aluminuum 6061", 2.712631*g/cm3, 8, kStateSolid); - AlPresT = new G4Material("Aluminuum 6061", 2.712631*g/cm3, 8, kStateSolid); - - AlPresT->AddElement(Al, 99.1244424*perCent); - AlPresT->AddElement(Si, 0.5922414*perCent); - AlPresT->AddElement(Fe, 0.1211379*perCent); - AlPresT->AddElement(Cu, 0.0018171*perCent); - AlPresT->AddElement(Mn, 0.0383626*perCent); - //AlPresT->AddElement(Mg, 0.7000*perCent); - AlPresT->AddElement(Cr, 0.1211405*perCent); - AlPresT->AddElement(Li, 0.00075712*perCent); - AlPresT->AddElement(B, 0.00010095*perCent); - //AlPresT->AddElement(Zn, 0.0230*perCent); - //AlPresT->AddElement(Na, 0.0090*perCent); - //AlPresT->AddElement(Ga, 0.0120*perCent); - //AlPresT->AddElement(Ti, 0.0110*perCent); - - //Create AlCalT (calandria Tube) -// AlCalT = new G4Material("Aluminuum 6063", 2.684951*g/cm3, 8, kStateSolid); - AlCalT = new G4Material("Aluminuum 6063", 2.684951*g/cm3, 8, kStateSolid); - AlCalT->AddElement(Al, 99.18675267*perCent); - AlCalT->AddElement(Si, 0.509640251*perCent); - AlCalT->AddElement(Fe, 0.241396625*perCent); - AlCalT->AddElement(Li, 0.00754387*perCent); - AlCalT->AddElement(B, 0.000100586*perCent); - //AlCalT->AddElement(Cu, 0.0590*perCent); - AlCalT->AddElement(Mn, 0.041228175*perCent); - //AlCalT->AddElement(Mg, 0.5400*perCent); - //AlCalT->AddElement(Cr, 0.0100*perCent); - //AlCalT->AddElement(Zn, 0.0340*perCent); - //AlCalT->AddElement(Na, 0.0170*perCent); - AlCalT->AddElement(Gd, 0.000010059*perCent); - AlCalT->AddElement(Ti, 0.041228175*perCent); - - - // Create Coolant - Coolant = new G4Material("Coolant", 0.8074*g/cm3, 2, kStateLiquid); - Coolant->AddMaterial(HeavyWater, 99.3777*perCent); - Coolant->AddMaterial(H2O, 0.6223*perCent); - - - Moderator = new G4Material("Moderator", 1.102597*g/cm3, 2, kStateLiquid,299.51*kelvin); - Moderator->AddMaterial(HeavyWater, 98.705*perCent); - Moderator->AddMaterial(H2O, 1.295*perCent); - - //Create Annulus Gas - AnnulusGas = new G4Material("AnnulusGas", 0.0012*g/cm3, 2, kStateGas); - AnnulusGas->AddElement(C,27.11*perCent); - AnnulusGas->AddElement(Oxygen,72.89*perCent); - - - Zr4 = new G4Material("Zircaloy-4", 6.55*g/cm3, 4, kStateSolid); - Zr4->AddElement(Oxygen, 0.12*perCent); - Zr4->AddElement(CrZr, 0.11*perCent); - Zr4->AddElement(FeZr, 0.22*perCent); - Zr4->AddElement(Zr, 99.58*perCent); - - // Make Air - Air = new G4Material("Air", 1.29*mg/cm3, 5, kStateGas); - Air->AddElement(N, 74.74095914*perCent); - Air->AddElement(Oxygen, 23.49454694*perCent); - Air->AddElement(Ar, 1.274547311*perCent); - Air->AddElement(Li, 0.474350981*perCent); - Air->AddElement(C, 0.015595629*perCent); - //Air->AddElement(Hydrogen, 0.009895657); - - - - - - // Add materials to the map indexed by either ZA (format ZZAAA or ZZ) - // For composite materials: world is 0, heavy water is 1, UHW is 2 - matMap["World"] = World; - matMap["LEUMat"] = LEUMat; - matMap["Heavy Water"] = HeavyWater; - matMap["Graphite"] = Graphite; - matMap["Al57S"] = Aluminum57S; - matMap["AlPresT"] = AlPresT; - matMap["AlCalT"] = AlCalT; - matMap["Coolant"] = Coolant; - matMap["AnnulusGas"] = AnnulusGas; - matMap["Zr4"] = Zr4; - matMap["Air"] = Air; - matMap["RUMat"] = RUMat; - matMap["Moderator"] = Moderator;*/ - - - matChanged = false; - - return; -} - diff --git a/README.md b/README.md index a02dc738..ffe6b3b8 100644 --- a/README.md +++ b/README.md @@ -1,15 +1,15 @@ Porting G4-STORK particle simulation software to GPU ========== -GEANT-4 is a widely-used software toolkit used to simulate particle -interactions. Several members of McMaster's Engineering Physics department -have created G4-STORK, a program that uses the GEANT-4 toolkit to simulate +Geant4 is a widely-used software toolkit used to simulate particle +interactions with matter. Several members of McMaster's Engineering Physics department +have created G4-STORK, a program that uses the Geant4 toolkit to simulate particle interactions in McMaster's nuclear reactor. Due to the computation time needed to run these simulations, they cannot simulate particle interactions that take place over the course of minutes (or even seconds), or that have a large numbers of particles. -The goal of this project is to port the calculations done by GEANT-4 to a GPU +The goal of this project is to port some of the calculations done by Geant4 to a GPU architecture using CUDA. This will significantly increase the performance of the simulations, allowing researchers to use more accurate models of the system. @@ -24,131 +24,70 @@ system. Prerequisites ========== -The following operating systems are supported: -- gcc (at least 4.8) -- CUDA requires gcc version less than 4.9 +The following software is required: +- gcc (must be version 4.8 - 4.9) -*Note*: Xcode 7 includes a newer version of the clang compiler that is not yet -supported. - -To run computations on the GPU with CUDA, a relatively new **NVIDIA GPU** is -required. +The following hardware is required: +- NVIDIA GPU with CUDA compute capability of at least 2.0 Installation ========== **Install cmake**
1. Download cmake 2.8.4 from https://cmake.org/files/v2.8/
-2. Follow the instructions in the readme included with the download - -**Install topc-2.5.2**
-1. `cd /path/to/GEANT4-GPU/topc-2.5.2`
-2. `./configure` (installs to `usr/local/include` and `usr/local/src`)
-3. `make install` +2. Follow the instructions in the Readme included with the download -**Install marshalgen-1.0**
-1. (Fedora only) `yum install bison flex`
-2. `cd /path/to/GEANT4-GPU/marshalgen-1.0`
-3. `make`
-4. At this point, make sure that the `usr/local/marshalgen-1.0` folder exists -and contains all the same files as the *marshalgen-1.0* folder in GEANT4-GPU. If -not, simply copy those files into `usr/local/marshalgen-1.0`.
-5. Note: there is a syntax error in marshalgen-1.0/Phase1/mgen.pl line 683 (one -extra `\)` before the `;\n";`. The version in the repo is fixed, but if you -downloaded marshalgen from another source, you need to fix this) - -**Install GEANT-4**
+**Install Geant4**
If installing on McMaster's servers, add `. /opt/rh/devtoolset-3/enable` to your bash_profile to use the newer version of gcc. -1. (Fedora only) `yum install expat-devel`
-2. `mkdir /path/to/GEANT4-GPU/geant4.10.00.p02-build /path/to/GEANT4-GPU/ -geant4.10.00.p02-install`
-3. `cd /path/to/GEANT4-GPU/geant4.10.00.p02-build`
-4. `cmake -DGEANT4_INSTALL_DATA=ON -DGEANT4_ENABLE_CUDA=ON -DGEANT4_USE_SYSTEM_EXPAT=OFF -DCMAKE_INSTALL_PREFIX=/path/to/GEANT4-GPU/geant4.10.00.p02-install /path/to/GEANT4-GPU/geant4.10.00.p02`
+1. `mkdir /path/to/Geant4-GPU/geant4.10.02-build`
+2. `mkdir /path/to/Geant4-GPU/geant4.10.02-install`
+3. `cd /path/to/Geant4-GPU/geant4.10.02-build`
+4. `cmake -DGEANT4_ENABLE_CUDA=ON -DGEANT4_USE_SYSTEM_EXPAT=OFF -DCMAKE_INSTALL_PREFIX=/path/to/Geant4-GPU/geant4.10.02-install ../geant4.10.02`
IF installing on McMaster's server, you must add flag `-DCUDA_HOST_COMPILER=/usr/bin/g++`
-5. `make -jN` where `N` is the number of processors on your computer
-6. `make install` - -**Install G4-STORK**
-1. `mkdir /path/to/GEANT4-GPU/G4STORK/Build`
-2. `cd /path/to/GEANT4-GPU/G4STORK/Build`
-3. `source /path/to/GEANT4-GPU/geant4.10.00.p02-install/bin/geant4.sh`
-4. `rm -rf CMakeCache.txt CMakeFiles/`
-5. `cmake -DTOPC_USE=1 -DGeant4_DIR=/path/to/GEANT4-GPU/geant4.10.01.p02-install/lib/Geant4.10.00.p02/Geant4Config.cmake ../` (note: it may be *lib64* - instead of *lib* on Linux)
-6. `make -f ../MarshalMakefile` (note: if this fails, make sure -`usr/local/marshalgen-1.0` contains the `marshalgen` binary)
-7. `make -jN` where `N` is the number of processors on your computer -8. Open `/path/to/GEANT4-GPU/Build/addFilesG4STORK` and modify the top few -variables with the correct paths for your install. +5. `make install -jN` where `N` is the number of processors on your computer
**Installing Geant4 on McMaster's Server (no root privileges)**
-1. SSH into one of McMaster's servers (i.e. `ssh macid@gpu1.mcmaster.ca`), account is on a shared drive across all department servers so once you install once you can access it from any one.
-2. Set up your .gitconfig file, ssh keys, and clone the repo in your home folder (path is `/u50/yourMacId/`)
-3. You'll need to install cmake, to do this download the latest version onto your regular desktop
+1. Clone the repo
+3. Download the latest version of CMake onto your local desktop
4. Copy the tarred file to McMaster's server via SSH: `scp cmake-3.4.0.tar yourMacId@gpu1.mcmaster.ca:/u50/yourMacId/`
5. Return to your SSH terminal and untar the file (this may take a while): `tar -xvf cmake-3.4.0.tar`
6. Build and install cmake: `cd cmake-3.4.0;./bootstrap;make;make install`
8. Add cmake's bin folder to your path. Open `/u50/yourMacId/.bash_profile` and add the following line right before `export PATH`: `PATH=$PATH:$HOME/cmake-3.4.0/bin`
-9. Follow the instructions above to "Install GEANT-4" (starting from 2), and add the following flag to the cmake command in step 4: `-DGEANT4_USE_SYSTEM_EXPAT=OFF`
+9. Follow the instructions above to "Install Geant4"
**Setting Environment Variables**
It is recommended to add a line to your bash_profile that loads the Geant4 -environment variables, like so: +environment variables when you login, like so: ``` -source /path/to/geant4.10.00.p02-install/bin/geant4.sh +source /path/to/Geant4.10.02-install/bin/Geant4.sh ``` Testing Installation ========== -**Testing GEANT4**
-There are several basic examples included with GEANT4 which can be run to test -the install. To run the example `B1`:
-1. `cd /path/to/GEANT4-GPU/geant4.10.00.p02/examples/basic`
-2. `mkdir B1-build`
-3. `cd B1-build`
-4. `cmake -D CMAKE_CXX_COMPILER=nvcc -DGeant4_DIR=/path/to/GEANT4-GPU/geant4.10.00.p02-install/lib/Geant4-10.0.2 ../B1`
-5. `make -jN` where `N` is the number of cores on your machine
-6. `./exampleB1` - -**Testing G4-STORK**
-To test that everything installed properly, run the following command from -`/path/to/GEANT4-GPU/G4STORK/Build`: -``` -./g4stork ../InputFiles/C6LatticeInput.txt -``` -If it runs with no errors, then you should be all set up! +**Testing Geant4**
Compiling After Changes ========== -Every time you change the source code of G4STORK or GEANT4, you need to -recompile. From `/path/to/GEANT4-GPU/geant4.10.00.p02-build` rerun the cmake command from *Install GEANT-4: Step 4*, run `make`, and then run `make install`. Note that you only need to rerun cmake if you modified any CMake files, but you must always run the two make commands. +Every time you change the source code of Geant4, you need to recompile by running `make install` from `/path/to/Geant4-GPU/geant4.10.02-build` Troubleshooting ========== Potential problems include: - Spaces in pathname to GEANT-GPU - Unsupported OS -- Newer version of Clang (included with Xcode 7), download Xcode 6 and uninstall - Xcode 7 if this is the case FAQ ========== -**What is GEANT-4**
-Many physics researchers use GEANT-4 to learn about how particles interact +**What is Geant4**
+Many physics researchers use Geant4 to learn about how particles interact with a specific environment. It is a toolkit (i.e. library) that uses the Monte Carlo model, meaning each particle's properties are calculated independently according to certain probabilities. It runs all those calculations, and provides output. -**What is G4-STORK**
-McMaster's Engineering Physics department created G4-STORK -- a project that -leverages GEANT-4 to study the McMaster nuclear reactor. G4-STORK includes the -necessary data structures and algorithms specific to the reactor, and also -adds CPU parallelization via the MPI model. - **Why will running the simulations on a GPU improve the performance**
GPU's contain a large amount of cores that can perform calculations much more -quickly than a CPU if the problem is well-suited to parallelization. GEANT-4 +quickly than a CPU if the problem is well-suited to parallelization. Geant4 runs relatively simple calculations on millions of particles, and each particle is completely independent of the others. This is exactly that sort of well-suited problem, and stands to see large performance gains. diff --git a/marshalgen-1.0/MANUAL.txt b/marshalgen-1.0/MANUAL.txt deleted file mode 100644 index 117beba3..00000000 --- a/marshalgen-1.0/MANUAL.txt +++ /dev/null @@ -1,454 +0,0 @@ -Getting Started -====================================== -You can try the example under Examples/LinkedList by typing -./marshalgen Examples/LinkedList/LinkedList.h - -LinkedList.h is the input file. It is the header file containing the -declaration of the target class (LinkedList) with Marshalgen -annotations. - - The output file, MarshaledLinkedList.h, will be generated in the same -directory with the input file. MarshaledLinkedList.h contains the -marshaling/unmarshaling code for the class LinkedList. Another file, -LinkedList.msh, is also generated. However, this is an intermediate -file and is used only for debugging purpose. - -Notes on architecture -====================================== - The current version Marshalgen assumes: the IEEE floating-point -standard; a common byte ordering of integers and pointers; and a -common format of structs or classes on the source and destination -machines. - -A Simple Example -====================================== - Let's have a closer look inside the file LinkedList.h -#include -#ifndef _LINKED_LIST_H -#define _LINKED_LIST_H - -//MSH_BEGIN -class LinkedList{ -public: - int head; //MSH: primitive - LinkedList *next; //MSH: predefined_ptr -public: - LinkedList(int = 0, LinkedList* = NULL); -}; -//MSH_END - -#endif - - - The declaration of each struct or class to be marshaled (here is the -class LinkedList) must be surrounded by "//MSH_BEGIN" and "//MSH_END". -If there are multiple structs or classes in the same file, each should -be surrounded by a seperate pair of "//MSH_BEGIN" and "//MSH_END". - The annotation right after the declaration of each data field -describes how Marshalgen should marshal the data field. All the -annotations are in the format of "//MSH: annotation_type [options]" or -"/* MSH: annotation_type [options] */". - - The annotation "//MSH: primitive" tells Marshalgen to marshal the -data field "int head" as a variable of primitive type. This means that -Marshalgen should perform a shallow copy of this data field to the -buffer. - memcpy(marshalgen_buffer, &this->head, sizeof(this->head)); - - The annotation "//MSH: predefined_ptr" tells Marshalgen that the data -field "LinkedList *next" is a pointer to an object of a predefined -type. "Predefined type" means that the user had already "defined" -(using Marshalgen annotations) how Marshalgen should marshal the type -(here is the class LinkedList). - - -Using the generated marshaling/unmarshaling Code -====================================== - The usage of the marshaling code for class LinkedList is shown in the -file LinkedList.cpp. - -... -#include "MarshaledLinkedList.h" -int main(int argc,char** argv){ - LinkedList* lst = new LinkedList(1,NULL); - // marshaling object "lst" - MarshaledLinkedList m(lst); - - // m.getBuffer() returns the marshaled buffer of "lst" - char* marshalBuffer = m.getBuffer(); - - // now we unmarshal (reconstruct a LinkedList object from the buffer) - MarshaledLinkedList m2(marshalBuffer); - LinkedList* lst2 = m2.unmarshal(); - ... -} - - The marshaling/unmarshaling routines for the class LinkedList are -generated in the class MarshaledLinkedList. The header file -"MarshaledLinkedList.h" is included at the beginning. - - Note that all of the generated marshaling routines require the header -file MarshaledObj.h. So, be sure to include the file MarshaledObj.h -(available in the Marshalgen directory) in the include-path when -compiling. - -To get the marshaled buffer for an object of type LinkedList (here, it is -the object "lst"), one should first call the constructor of -MarshaledLinkedList with the target object as the parameter. - MarshaledLinkedList m(lst); - -Then, the result buffer can be obtained by calling the function -"m.getBuffer()", and the buffer size can be obtained by calling the -function "m.getBufferSize()". - - The unmarshaling process starts by calling the constructor of the -class MarshaledLinkedList with the buffer as the parameter. - MarshaledLinkedList m2(marshalBuffer); - -The re-constructed object is then obtained by calling "m2.unmarshal()". - - -Basic Annotations and Options -====================================== -1/ PRIM_TYPE a; //MSH: primitive - This annotation tells Marshalgen that "a" is of a primitive type. -Primitive type usually means the C primitive type: int, char, long, -float, double, etc. In general, one could use this annotation for any -type PRIM_TYPE whose number of bytes needed to copy can be obtained via -"sizeof(PRIM_TYPE)". - memcpy(marshalgen_buffer, &a, sizeof(PRIM_TYPE)); - -2/ PRIM_TYPE *a; //MSH: primitive_ptr - This annotation tells Marshalgen that "a" is a pointer to a primitive -type, and Marshalgen should copy the whole variable that the pointer -points to, not just the pointer. - memcpy(marshalgen_buffer, a, sizeof(PRIM_TYPE)); - -3/ CLASS_NAME b; //MSH: predefined - Marshalgen will marshal the object "b". Marshalgen assumes that the -user had already specified how to marshal the class "CLASS_NAME". -Marshalgen then look inside the declaration of the class CLASS_NAME -for the necessary annotations. - -4/ CLASS_NAME *b; //MSH: predefined_ptr - Marshalgen will marshal the object that "b" points to. Marshalgen -assumes that the user had already specified how to marshal the class -"CLASS_NAME". Marshalgen then look inside the declaration of the -class CLASS_NAME for the necessary annotations. - -5/ PRIM_TYPE t; //MSH: transient - This annotation tells Marshalgen not to marshal/unmarshal this data -field. This is the same as having no annotation. - -6/ PRIM_TYPE* ptr; //MSH: ptr_shallow_copy - This annotation tells Marshalgen to copy only the pointer, not the -value that the pointer points to. This option is useful only when the -object will be unmarshaled into an identical process with the same -virtual addresses. - -7/ PRIM_TYPE a[N]; //MSH: ptr_to_index - This annotation tells Marshalgen to copy the whole array "a", -including N elements. Currently, this annotation only supports the -case when PRIM_TYPE is a primitive type. - -8/ PRIM_TYPE *a; //MSH: ptr_as_array - This annotation allows the user to marshal an array pointed by "a". -The user can specify the size and the type of each element of the -array using the macros: $ELEMENT; $ELE_INDEX; $ELE_COUNT; $THIS. For -more details, see section "Advanced example A" below. - -9/ -//MSH_include_begin -#define MY_MACRO -#include "myincludefile.h" -//MSH_include_end - - Any C/C++ code between "//MSH_include_begin" and "//MSH_include_end" -will be included in the beginning of each Marshalgen output files. -This option allows the user to include their declarations in the -generated marshaling/unmarshaling code. - -10/ //MSH_constructor: CONSTRUCTOR - When unmarshaling a buffer to reconstruct an object, Marshalgen needs -to call the constructor of the object's class. By default, the default -constructor (without any argument) will be called. If one prefers -a particular constructor to be called when constructing the object, -then one needs to put the constructor with proper number of arguments -in CONSTRUCTOR. - - For example, the following class has two constructors -class Foo { - //MSH_constructor: Foo(1.0) - Foo(int v) {...} - Foo(float v) {...} -} - If the one prefers the constructor "Foo(float v)" to be called, one -should specify "Foo(1.0)" in the annotation "MSH_constructor". Note -that only the number of arguments and the argument type is necessary -to locate the correct constructor. The actual values of the arguments -do not matter because later on the contents of the object will be -overwritten with the information from the marshaling buffer anyway. - - See the file Cat.h under directory Examples/Polymorphism for another example. - -11/ //MSH: manual - This annotation is useful when none of the Marshalgen's provided -annotations fits the user's purpose. The "//MSH:manual" annotation -allows user to directly write customized marshaling and unmarshaling -code for a particular field, using the macros $THIS, $$, and -$SIZE. For more details, see section "Advanced example B". - -Annotations for polymorphism and templates -====================================== -12/ //MSH_superclass : PARENT_CLASS - This annotation tells Marshalgen that the current class (the class -contains this annotation) is a derived class from the class -PARENT_CLASS. When Marshalgen marshals an object of the current class, -Marshalgen also needs to marshal the data fields that the current -class inherits from the class PARENT_CLASS. One must also -annotate the class PARENT_CLASS seperately. - This annotation should not associate with any data field (i.e, it -should be written seperately in one line). - -13/ //MSH_derivedclass : CHILD_CLASS - This annotations tells Marshalgen to also marshal the data fields -from the derived class of the current class. This annotations is -particularly useful when the object declared as the parent type may -actually have different derived types depending on a certain data -field of the base class. - The annotation specifies which derived class needed to be marshaled -together with the current class. This annotation does not associated -with any data field. The syntax is: -/* MSH_derivedclass: PHRASE_1 | PHRASE_2 | .... */ - - where PHRASE_x can be the name of type, or a conditional command of format: -"(C_expression) => CONSTRUCTOR". - -C_expression is any C/C++ expresssion that returns a boolean -value. CONSTRUCTOR is the constructor of the derived class one wants -to marshal when C_expression is true. - At runtime, Marshalgen will evaluate the phrases from left to right, -if the C_expression of a phrase returns boolean true, then Marshalgen will -marshal the current object as the derived class specified in the -corresponding constructor. The evaluation stops after the first phrase -whose C_expression returns boolean true. - - See "Advanced example C" for more details. - - -Conditional command for type specification -=========================================== - In annotations such as "MSH: predefined", "MSH: ptr_as_array", -"MSH_derivedclass" etc., one needs to specify a type. This type -can either be the direct name of the type, or one can add the -conditions under which a certain type is chosen. - The syntax of the conditional command is described in the description -of the annotaion "MSH_derivedclass". The same syntax and usage apply -for all other annotations where a specification of type is needed. - - -Marshalgen macros, variables, and utilitie functions -=========================================== -1) "$THIS" - refers to the current instance of the class that has the -annotations. This macro is often used in the C/C++ embedded code in -the annotations. -2) "$$" - refers to the resulting buffer. Marshalgen will copy marshal the -values to this buffer and send this buffer over the network. One -can modify this buffer directly if needed. -3) "$SIZE" - refers to the size of the "$$" buffer. -4) $ELEMENT, $ELE_INDEX, $ELE_COUNT - See section "Advanced example A" for details. -5) MSH_IsSameClass - This C++ function returns true if T1 and T2 are of the same -type. This function is defined in MarshaledObj.h (is included in every -generated marshaling header files). MSH_IsSameClass is -particularly helpful when annotating templates. - - For an example, see the example under Examples/Template . - - -How to combine annotations from multiple files -======================================= - In the below example, the annotation "Bar b; //MSH: predefined" in -the class Foo (inside the file Foo.h) refers to the class Bar in -another file (Bar.h). - -/** Foo.h **/ -//MSH_include_begin -#include "MarshaledBar.h" -//MSH_include_end - -//MSH_BEGIN -class Foo { -public: - int x; //MSH: primitive - Bar b; //MSH: predefined -}; -//MSH_END - - -/** Bar.h **/ - -//MSH_BEGIN -class Bar { -public: - double *y; //MSH: primitive_ptr -}; -//MSH_END - - Marshalgen does not check for the existence of the referred classes -when generating marshaling routines. However, the marshaling routine -of the class Foo (generated in the file MarshaledFoo.h) will call the -marshaling routine of the class Bar (generated in the file -MarshaledBar.h) when marshaling the data field "Bar b". -Therefore, the header file for marshaling routine of the class Bar -("MarshaledBar.h") should be included at the beginning of the file -Foo.h (using the annotation "//MSH_include_begin and -"//MSH_include_end" as shown). - - -Advanced example A -======================================= -//MSH_BEGIN -class Foo -{ -public: - int count; - double *HC; /* MSH: ptr_as_array - [elementType: double] - [elementCount: { $ELE_COUNT = $THIS->count; }] - [elementGet: { $ELEMENT = $THIS->HC[$ELE_INDEX]; }] - [elementSet: { $THIS->HC[$ELE_INDEX] = $ELEMENT; }] - */ -} -//MSH_END - - In the above example, the annotation "/* MSH: ptr_as_array ... */" -tells Marshalgen that the data field "double *HC" is a pointer to an -array, and the information necessary to marshal the data field is -specified in the following options. - -i) The option "[elementType: double]" tells Marshalgen - that each element of the array has the "double" type. -ii) The option "[elementCount: { $ELE_COUNT = $THIS->count; } ]" -specifies how Marshalgen can obtain the size of the array in the -number of elements (presumably the programmer maintains the correct -size of the array "HC" in the data field "count"). The C++ code -inside {...} is the code to be executed to obtain the array size. The -array size should be assigned to $ELE_COUNT, a variable used by -Marshalgen. The variable $THIS refers to the object to be marshaled. -We would have liked to use "this" instead of "$THIS". However, since -the marshaling/unmarshaling routines are placed in a separate class, -"this" would not refer to the object to be marshaled but to the -instance of the class containing the marshaling/unmarshaling routines. - - Similarly, the C++ code inside {...} of the options - "elementGet" and "elementSet" specify how Marshalgen can get - access to the marshaled object. In the option "elementGet", $ELEMENT - refers to the object to be marshaled. In the option - "elementSet", $ELEMENT refers to the object that has been - reconstructed. $ELEMENT is automatically assigned by Marshalgen. - $ELE_INDEX refers to the index of the object in the array. The variable - $ELE_INDEX is automatically assigned by Marshalgen. - -The options "elementGet" and "elementSet" are needed because sometimes -the data field is not directly accessible from outside the class: the -data field may be declared as "private" or "protected". Since the -annotation approach does not permit us to change the original code of -the class, the marshaling/unmarshaling routines have to reside outside -the class. As a consequence, one has to provide Marshalgen with -necessary code to access the data fields declared as "private" or -"protected". - - -Advanced example B -======================================= - If none of the provided annotations fits the user's purpose, the user -can write customized code to deal with each specific case. Marshalgen -provides this mechanism through the annotation "//MSH: manual". - See the example below: - -//MSH_BEGIN -class MyString{ -public: - int length() { return len;} - int buffer() { return str;} - MyString(char* s){ - int i=0; - //find the length of the string - while(s[i]!=0) i++; - len = i; - buffer = malloc(len); - memcpy(buffer,s,len); - *(buffer+len)='\0'; - } - -protected: - int len; // MSH: primitive - char* str; /* MSH: manual - { - memcpy($$, $THIS->buffer, $THIS->length()); - *($$+$THIS->length()) = '\0'; - } - { - $THIS = new MyString($$); - } - { - $SIZE = $THIS->length(); - } */ -}; -//MSH_END - - The "MSH: manual" annotation requires three fields. The fields are -defined inside "{...}" and are placed in the order: marshaling code, -unmarshaling code, and code to determine buffer size. One will -write the code to handle the actions, which should manipulate the -marshaling buffer $$ directly. - - - -Advanced example C -======================================= - Consider the following class hierachy - -class Animal { - /* if "type" is "cat" then the object is of type Cat, - "type" is "dog" then the object is of type Dog. */ - MyString type; -} - -class Cat : public Animal{ - float sleep_time; -} - -class Dog : public Animal{ - double weight; -} - - Cat and Dog are the derived types of the type Animal. Assume that the -user knows that any object of type Animal would be either of type Cat -or Dog depending on the value of the data field "type" of class -Animal. Then whenever an object of type Animal is marshaled, the -proper data fields from the derived class should also be marshaled. - The annotation for the base class Animal is as follows: - -// MSH_BEGIN -class Animal { -public: - MyString type; /* MSH: predefined */ - - /* MSH_derivedclass: - ($THIS->type.equals("cat")) => Cat(0) - | ($THIS->type.equals("dog")) => Dog(0) - */ -}; -//MSH_END - - - In the above example, an object of type Animal will be marshaled as -an object of type Cat if "($THIS->type.equals("cat"))" return the -boolean true value. The object will be marshaled as an object of type -Dog if "($THIS->type.equals("dog"))" is true. diff --git a/marshalgen-1.0/Makefile b/marshalgen-1.0/Makefile deleted file mode 100644 index 351241c0..00000000 --- a/marshalgen-1.0/Makefile +++ /dev/null @@ -1,13 +0,0 @@ - -compile: - cd Phase2 && make - -dist: distclean - dir=`basename $$PWD`; cd ..; tar cvf $$dir.tar ./$$dir && gzip $$dir.tar - dir=`basename $$PWD`; ls -l ../$$dir.tar.gz - -clean: - cd Phase2 && make clean - -distclean: - cd Phase2 && make distclean diff --git a/marshalgen-1.0/MarshaledObj.h b/marshalgen-1.0/MarshaledObj.h deleted file mode 100644 index a6f6bf9d..00000000 --- a/marshalgen-1.0/MarshaledObj.h +++ /dev/null @@ -1,216 +0,0 @@ - /********************************************************************** - * Include file with Base Class of Marshalgen * - * Copyright (c) 2001 Gene Cooperman * - * * - * This library is free software; you can redistribute it and/or * - * modify it under the terms of the GNU Lesser General Public * - * License as published by the Free Software Foundation; either * - * version 2.1 of the License, or (at your option) any later version. * - * * - * This library is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * - * Lesser General Public License for more details. * - * * - * You should have received a copy of the GNU Lesser General Public * - * License along with this library (see file COPYING); if not, write * - * to the Free Software Foundation, Inc., 59 Temple Place, Suite * - * 330, Boston, MA 02111-1307 USA, or contact Gene Cooperman * - * . * - **********************************************************************/ - -#ifndef MARSHALEDOBJ_H -#define MARSHALEDOBJ_H - -#include -#include -#include -#include - -#define MSH_ASSERT(X) {assert(X);} - -#define MSH_HEADER_SIZE (sizeof(int)*2) -// the first field (first sizeof(int) bytes) contains the $TYPE_CHOICE -// the second field contains the size including the header -#define MSH_TOTALSIZE_OFFSET (sizeof(int)) -#define MSH_TYPECHOICE_OFFSET 0 - -#define MSH_SET_TYPECHOICE(X) { memcpy(msh_buffer+MSH_TYPECHOICE_OFFSET,&(X),sizeof(int));} -#define MSH_SET_TOTALSIZE(X) { memcpy(msh_buffer+MSH_TOTALSIZE_OFFSET,&(X),sizeof(int));} -#define MSH_GET_TYPECHOICE(X,BUF) { memcpy(&(X), ((char*)BUF)+MSH_TYPECHOICE_OFFSET,sizeof(int));} -#define MSH_GET_TOTALSIZE(X,BUF) { memcpy(&(X), ((char*)BUF)+MSH_TOTALSIZE_OFFSET,sizeof(int));} - - -class MarshaledObj { - private: - // Make sure all marshaled objects are word aligned. - static const int WORD_SIZE = sizeof(long); - public: - static int ROUND_UP( int x ){ - return (((x)+(WORD_SIZE-1)) / WORD_SIZE) * WORD_SIZE; - } - - public: - // Constructs an empty MarshaledObj, - MarshaledObj(){ - msh_extent = 128; - msh_size = MSH_HEADER_SIZE; - msh_isUnmarshalDone = false; - - msh_buffer = (char *)malloc(msh_extent); - MSH_ASSERT(msh_buffer); - - msh_cursor = msh_buffer + MSH_HEADER_SIZE; - msh_field_begin = msh_cursor; - - msh_typechoice = 0; - int totalsize = msh_cursor-msh_buffer; - - MSH_SET_TYPECHOICE(msh_typechoice); - MSH_SET_TOTALSIZE(totalsize); - } - - //MarshaledObj(void *buf); - // This constructs a MarshledObj from a buffer (of type char*) for unmarshaling. - // buf is obtain from an already marshaled object. - // The first field of buf must be an int that contains the size of the buf - // NOT including itself. - // isUnmarshaling must be 'u' (for unmarshaling) . - MarshaledObj(void *buf, char isUnmarshaling) { - msh_isUnmarshalDone = false; - - if(isUnmarshaling != 'u') { - printf("MarshaledObj(void*, char): wrong argument\n"); - return; - } - - //msh_extent = ROUND_UP(*(int *)buf + sizeof(int)); - MSH_GET_TYPECHOICE(msh_typechoice,buf); - - MSH_GET_TOTALSIZE(msh_size,buf); - msh_extent = ROUND_UP(msh_size); - - msh_buffer = (char *)malloc(msh_extent); - MSH_ASSERT(msh_buffer); - - memcpy(msh_buffer, (char *)buf, msh_extent); - msh_cursor = msh_buffer + MSH_HEADER_SIZE; - msh_field_begin = msh_cursor; - - //MSH_SET_TYPECHOICE(msh_typechoice); - - } - - ~MarshaledObj() { - if ( ! isUnmarshaling() ) - free(msh_buffer); - } - - inline bool isUnmarshaling() { - return (msh_extent <= 0); - } - - private: - // Dont use copy constructor - const MarshaledObj& operator=(const MarshaledObj& right); - - protected: - int msh_typechoice; // alias of $TYPE_CHOICE - - // points to the buffer (header+body) - char *msh_buffer; - - // msh_field_begin points to the size of the current field being marshaled - char* msh_field_begin; - - // msh_size contains the total size of msh_buffer. i.e., - size_t msh_size; - - // msh_cursor points to the next field to be marshaled. - char *msh_cursor; - - // msh_extent is the total allocated space for msh_buffer. - // msh_extent is always >= msh_size - size_t msh_extent; - - bool msh_isUnmarshalDone; //Is unmarshaling done yet? - - public: - inline void EXTEND_BUFFER(int size){ - msh_size += size; - if(msh_size > msh_extent){ - resizeBuffer(msh_size); - } - } - - void resizeBuffer(size_t new_size ) { - int msh_displacement = msh_cursor - msh_buffer; - int field_displacement = msh_field_begin - msh_buffer; - - while(new_size > msh_extent) - msh_extent *= 2; - - msh_buffer = (char *)realloc( msh_buffer, msh_extent); - MSH_ASSERT(msh_buffer); - - msh_cursor = msh_buffer + msh_displacement; - msh_field_begin = msh_buffer + field_displacement; - } - - public: - // Returns the total size of buffer - inline int getBufferSize() { - return msh_size; - } - - inline char *getBuffer() { - return msh_buffer; - } - - /* p: pointer to the data field, size: size of that primitive data field */ - void marshalPrimitive(void* p, int size) { - int msh_currentSize; - if (isUnmarshaling()) - throw "Tried to marshal in object marked isUnmarshaling = true"; - msh_currentSize = size; - EXTEND_BUFFER(msh_currentSize + sizeof(int)); - - // *(int *)msh_cursor = msh_currentSize; - memcpy(msh_cursor, &msh_currentSize, sizeof(int)); - msh_cursor += sizeof(int); - memcpy(msh_cursor, p, size); - msh_cursor += msh_currentSize; - msh_size = msh_cursor - msh_buffer; - - MSH_SET_TOTALSIZE(msh_size); - } - - void unmarshalPrimitive(void* p, int size) { - int msh_currentSize; - //memcpy(&msh_currentSize, msh_cursor, sizeof(int)); - /* in case *msh_cursor is invalid, use "size" not to crash the memory */ - msh_currentSize = size; - msh_cursor += sizeof(int); - memcpy(p, msh_cursor, msh_currentSize); - msh_cursor += msh_currentSize; - //msh_size = msh_cursor - msh_buffer; - } -}; - -/* Used for distinguish the class types of the template parameter - vietha 2003.05.01 */ -template -class MSH_IsSameClass -{ -public: - enum {Is = 0}; -}; - -template -class MSH_IsSameClass -{ -public: - enum {Is = 1}; -}; - -#endif diff --git a/marshalgen-1.0/Phase1/mgen.pl b/marshalgen-1.0/Phase1/mgen.pl deleted file mode 100755 index 60de5346..00000000 --- a/marshalgen-1.0/Phase1/mgen.pl +++ /dev/null @@ -1,1217 +0,0 @@ -#!/usr/bin/perl -w -use strict; -use 5; -use File::Basename; - -#### Global variables - -my %type_hash = ("" => 1, "primitive" => 1,"primitive_ptr" => 1, - "transient" => 1,"ptr_to_index" =>1 ,"ptr_shallow_copy" => 1, - "manual" => 1,"predefined" => 1, "predefined_ptr" => 1, - "ptr_as_array" => 1); -# "embedded" => 1,"embedded_ptr" => 1,"global" => 1, - -my $shadowedClass_parm = "Shadowed_param"; - -my $line_counter = 0; - -my $constructor_call; - -#### - -if (@ARGV != 1){ - print STDERR "Usage: $0 source_file\n"; - exit -1; -} - -my $in_file = $ARGV[0]; -my $out_file; - -#Construct the output filename: - -if ($in_file =~ /(.*)\..*/){ - $out_file = "$1\.msh"; -} -else { - $out_file = "$in_file\.msh"; -} - -open(SRC, $in_file ) or die "Unable to open input file: $in_file\n<$!>"; -open(DEST, ">$out_file") or die "Unable to open output file: $out_file\n<$!>"; -select((select(DEST), $| = 1)[0]); #autoflush - -my @src; -chomp(@src = ()); -close SRC; - -my $linebuf = ""; -my $line; -my $begin = 0; -foreach $line (@src){ - $line_counter++; - - if ($line =~ /\/\/\s*MSH\_include\_end/){ - $begin or error_die("\\MSH_include_end comes before \\MSH_include_begin!", $line); - $linebuf .= "$line"; - last; - } - if ($line =~ /\/\/\s*MSH\_include\_begin/){ - (!$begin) or error_die("Can't have nested \\MSH_include_begin annotations!", $line); - $begin = 1; - } - if ($begin) {$linebuf .= "$line\n";} -} - -# Output the following: -# %{ -# INCLUDE_MACROS [anything you want to include or defined] -# %} - -my $in_file_basename = basename($in_file); -print DEST "\%\{\n"; -#print DEST "\#include \"$in_file\"\n"; -print DEST "\#include \"$in_file_basename\"\n"; -print DEST "$linebuf\n"; -print DEST "\%\}\n\n"; - -print DEST "// This file is generated automatically from $in_file_basename ."; -print DEST " It is an\n"; -print DEST "// intermediate file useful for debugging,"; -print DEST " but otherwise may be deleted.\n\n"; - -my $ann_begin = 0; -my $marshaledClass_parm; -my $parameter; - -$marshaledClass_parm = $parameter = "param"; -#$marshaledClass_parm = $parameter = "\$THIS"; - -my $i; -for ($i = 0; $i <= $#src; $i++){ - $line_counter = $i+1; - - $linebuf = ""; - $line = $src[$i]; - - if($line =~ /(.*)\/\*\s*MSH(.*)\s*\:(.*)\*\//){ #single-line comment - # convert "/* MSH... */" format to "// MSH..." format - $linebuf = "$1//MSH$2:$3"; - } - elsif ($line =~ /(.*)\/\*\s*MSH(.*)\s*\:(.*)/){ # multiple-line comment - #Putting multi-line comments of /* MSH: ... */ into one line - $linebuf = "$1//MSH$2:$3"; - while($i <= $#src){ - $line = $src[++$i]; - #if ($line =~ /(.*)\*\//) {$linebuf .= $1; last;} - #else {$linebuf .= $line;} - if ($line =~ /(.*)\*\//) {$linebuf .= "\n$1"; last;} #remove the "*/" at the end - else {$linebuf .= "\n$line";} - } - } - else {$linebuf = $line;} - my $lookahead_line; - if ($i <$#src){ $lookahead_line = $src[$i+1];} - - #print "linebuf=$linebuf\n"; - - if (!$ann_begin && $linebuf =~ /\/\/\s*MSH\_BEGIN/){ - $ann_begin = 1; - my $buffer = ""; - my ($type, $className, $parent_classes, $template_declare) = getClassName($lookahead_line); - - #print "className=$className\n"; - - $buffer .= $template_declare; - if ($type == 0){$buffer .= " marshaling class Marshaled";} - else {$buffer .= " marshaling struct Marshaled";} - $buffer .= "$className \($className\* $parameter\) $parent_classes\{\n"; - print DEST $buffer; - - $constructor_call = "\t\$THIS = new $className();\n"; - } - elsif ($ann_begin && $linebuf =~ /\/\/\s*MSH\_END/){ - $ann_begin = 0; - - ## generating the option containing the constructor call - my $constructor_opt = "\tunmarshaling constructor {\n"; - $constructor_opt .= $constructor_call; - $constructor_opt .= "\t}\n"; - print DEST $constructor_opt; - - print DEST "\}\n\n"; - } - elsif ($linebuf =~ /\/\/\s*MSH_constructor\s*\:\s*([\s\S]*)/) { - $constructor_call = "\t\$THIS = new $1;\n"; - } - elsif ($linebuf =~ /\/\/\s*MSH_superclass\s*\:\s*([\s\S]*)/) - # || ($linebuf =~ /\/\*\s*MSH_superclass\:\s*([\s\S]*)\*\//)) - { - my $marsh_buffer = marshal_baseclass($1); - print DEST $marsh_buffer; - } - elsif ($linebuf =~ /\/\/\s*MSH_derivedclass\s*\:\s*([\s\S]*)/) - #|| ($linebuf =~ /\/\*\s*MSH_derivedclass\s*\:\s*([\s\S]*)\*\//)) - { - my $marsh_buffer = marshal_derivedclass($1); - print DEST $marsh_buffer; - } - elsif ($linebuf =~ /\/\/\s*MSH\s*\:.*/) - # || ($linebuf =~ /\/\*\s*MSH\:.*/)) - { - my $marsh_buffer = marshal_annot($linebuf); - print DEST $marsh_buffer; - } -} - -close DEST; -exit 0; - - -#input: "template class G4THitsCollection : public G4HitsCollection \n" -#parent_classes: ": public G4HitsCollection \n" -#template_declare: "template " -#className: "G4THitsCollection" - - - -sub getClassName{ - my $line_buffer = shift; - my $type = -1; - my $parent_classes = ""; - my $className = ""; - my $template_declare = ""; - - #if ($line_buffer =~ /template\s+\\s+class\s+(\S+)(.*)/){ - # extract until encounter '{'} - if ($line_buffer =~ /template\s+\\s+class\s+(\S+)([^{]*)/){ - $className = "$2\<$1\>"; - $parent_classes = $3; - $template_declare = "template \"; - $type = 0; - } - #elsif ($line_buffer =~ /template\s+\\s+struct\s+\S+(.*)/){ - elsif ($line_buffer =~ /template\s+\\s+struct\s+(\S+)([^{]*)/){ - $className = "$2\<$1\>"; - $parent_classes = $3; - $template_declare = "template \"; - $type = 1; - } - #elsif($line_buffer =~ /class\s+(\S+)/){ - elsif($line_buffer =~ /class\s+([a-zA-Z0-9_]+)/){ - $className = $1; - $type = 0; - } - #elsif($line_buffer =~ /struct\s+(\S+)/){ - elsif($line_buffer =~ /struct\s+([a-zA-Z0-9_]+)/){ - $className = $1; - $type = 1; - } - else{ - error_die("Could not find class name", $line_buffer); - } - - #print "className=$className;template_decl=$template_declare\n"; - -return ($type, $className, $parent_classes, $template_declare); -} - - -sub marshal_annot{ - my $linebuf = shift; - my $vartype; - my $varname; - my $anntype; - my $marshalbuf; - my $token; - - - #if ($linebuf =~ /\/\/\s*MSH\_virtual\s*\:([\s\S]*)/){ - # $linebuf = $1; - # } - #elsif ($linebuf =~ /\/\*\s*MSH\_virtual\s*\:([\s\S]*)/){ - # $linebuf = $1; - #} - #print "Linebuf=$linebuf\n"; - - #if ($linebuf =~ /\s+([a-zA-Z0-9_]+)\:\:([a-zA-Z0-9_]+)/){ - if ($linebuf =~ /\s*(\S+\s*\**)\s+([a-zA-Z0-9_]+)\s*;/ || - $linebuf =~ /\s*(\S+\s+\**)\s*([a-zA-Z0-9_]+)\s*;/){ - $vartype = $1; - $varname = $2; - } - else {error_die("Could not extract the name and the type of the data field", $linebuf);} - #print "Vartype=$vartype; varname=$varname\n"; - - if ($linebuf =~ /(.*\;)\s*\/\/\s*MSH\s*:\s*([a-zA-Z0-9_]*)\s*/){ - $anntype = $2; - $token = $1; - } - #print "Token=$token; anntype=$anntype\n"; - - error_die("Invalid annotation: $anntype",$linebuf) unless defined($type_hash{$anntype}); - - unless ($anntype eq "" || $anntype eq "transient"){ - $marshalbuf = "\n$token\n"; - $marshalbuf .= annot_marshalling($linebuf, $anntype, $vartype, $varname); - $marshalbuf .= annot_unmarshaling($linebuf, $anntype, $vartype, $varname); - $marshalbuf .= annot_getSize($linebuf, $anntype, $vartype, $varname); - } - return $marshalbuf; - -} - -sub marshal_baseclass{ - my $baseclass = shift; - #print "Baseclass=$baseclass;\n"; - - my $annot; - my $rand_num; - - $rand_num = int(rand(1000)); - - # generate a dummy field - $annot = " int __dummy$rand_num; // marshaling code for MSH_superclass\n"; - ## marshaling code - $annot .= " //FIELDMARSHAL:\n {\n"; - $annot .= "\t\tMarshaled$baseclass marParent(\$THIS);\n"; - $annot .= "\t\tEXTEND_BUFFER(marParent.getBufferSize());\n"; - $annot .= "\t\tmemcpy(\$\$,marParent.getBuffer(), marParent.getBufferSize());\n"; - $annot .= "\t\t\$SIZE = marParent.getBufferSize();\n"; - $annot .= "\n }\n"; - - ## unmarshaling code - $annot .= " //FIELD UNMARSHAL:\n {\n"; - $annot .= "\t\tMarshaled$baseclass marObj(\$\$);\n"; - $annot .= "\t\tmarObj.unmarshalTo(\$THIS);\n"; - $annot .= "\n }\n"; - - ## size - $annot .= " //FIELD SIZE :\n {\n"; - $annot .= "\t\t//code for size, just dummy code because the size will be set correctly at the end of marshaling code\n"; - #$annot .= "\t\t\$SIZE = 0;\n"; - $annot .= "\n }\n"; - return $annot; -} - -sub marshal_derivedclass{ - my $derivedclass = shift; - #print "Derived class=$derivedclass;\n"; - $constructor_call = ""; # reset the code for constructor call - - my ($numOfTypes, $cref, $rref, $conref) = extractMultipleTypes($derivedclass); - my @arrTypeChoices = @{$cref}; - my @arrTypeResults = @{$rref}; - my @arrConstructorArgs = @{$conref}; - my $isMultipleTypes = ($numOfTypes>=2); - my $strElementType; - - ## generating calls to the correct constructors (constructor of the child class) - if ($isMultipleTypes) { - $constructor_call .= "\tif(0){}\n"; - } - for (my $i=0;$i<$numOfTypes;$i++) { - if (!$isMultipleTypes) { - #$strElementType = $derivedclass; - $strElementType = $arrTypeResults[$i]; - } else { - my $choice = $arrTypeChoices[$i]; - #$constructor_call .= "\telse if\($choice\){\n"; - $constructor_call .= "\telse if(\$TYPE_CHOICE == $i){\n"; - $strElementType = $arrTypeResults[$i]; - } - - my $consArg = $arrConstructorArgs[$i]; - $constructor_call .= "\t\$THIS = new $strElementType($consArg);\n"; - if ($isMultipleTypes) { - $constructor_call .= "\t}\n"; - } - } - - - ## generating the marshaling/unmarshaling/size code - my $annot; - my $rand_num; - - $rand_num = int(rand(1000)); - - # generate a dummy field - $annot = " int __dummy$rand_num; // marshaling code for MSH_derivedclass\n"; - - ## marshaling code - $annot .= " //FIELDMARSHAL:\n {\n"; - if ($isMultipleTypes) { - $annot .= "\tif(0){}\n"; - } - for (my $i=0;$i<$numOfTypes;$i++) { - if (!$isMultipleTypes) { - #$strElementType = $derivedclass; - $strElementType = $arrTypeResults[$i]; - } else { - my $choice = $arrTypeChoices[$i]; - $annot .= "\telse if\($choice\){\n"; - $strElementType = $arrTypeResults[$i]; - } - - $annot .= "\t\t$strElementType *aObj$rand_num = ($strElementType*)\$THIS;\n"; - $annot .= "\t\tMarshaled$strElementType marChild(aObj$rand_num);\n"; - $annot .= "\t\tEXTEND_BUFFER(marChild.getBufferSize());\n"; - $annot .= "\t\tmemcpy(\$\$,marChild.getBuffer(), marChild.getBufferSize());\n"; - $annot .= "\t\t\$SIZE = marChild.getBufferSize();\n"; - $annot .= "\t\t\$TYPE_CHOICE = $i;\n"; - if ($isMultipleTypes) { - $annot .= "\t}\n"; - } - } - - $annot .= "\n }\n"; - - ## unmarshaling code - $annot .= " //FIELD UNMARSHAL:\n {\n"; - if ($isMultipleTypes) { - $annot .= "\tif(0){}\n"; - } - for (my $i=0;$i<$numOfTypes;$i++) { - if (!$isMultipleTypes) { - #$strElementType = $derivedclass; - $strElementType = $arrTypeResults[$i]; - } else { - my $choice = $arrTypeChoices[$i]; - #$annot .= "\telse if\($choice\){\n"; - $annot .= "\telse if(\$TYPE_CHOICE == $i){\n"; - $strElementType = $arrTypeResults[$i]; - } - - $annot .= "\t\tMarshaled$strElementType marObj(\$\$);\n"; - $annot .= "\t\tmarObj.unmarshalTo(($strElementType*)\$THIS);\n"; - if ($isMultipleTypes) { - $annot .= "\t}\n"; - } - } - $annot .= "\n }\n"; - - ## size - $annot .= " //FIELD SIZE :\n {\n"; - $annot .= "\t\t//code for size, just dummy code because the size will be set correctly at the end of marshaling code\n"; - # $annot .= "\t\t\$SIZE = 0;\n"; - $annot .= "\n }\n"; - return $annot; -} - - -sub annot_marshalling{ - my $abuf = shift; - my $atype = shift; - my $vartype = shift; - my $varname = shift; - my $annot = " //FIELDMARSHAL:\n {\n"; - - my $strTypeOption = get_Option_Name( $abuf, "elementType:"); - - if ($atype eq "primitive"){ - if(!$strTypeOption){ #if there is no customized "elementType" - my $strElementGet = get_Option_Code($abuf, "elementGet:"); - if (!$strElementGet){ - $annot .= "\tmemcpy\(\$\$\, \&$shadowedClass_parm\-\>$varname\, sizeof\($vartype\)\);" - } - else { - $annot .= "\t$vartype \$ELEMENT\;\n\t$strElementGet\n"; - $annot .= "\tmemcpy(\$\$, \&\$ELEMENT, sizeof\($vartype\)\)\;" - } - }else { #if there is customized "elementType" option - my ($numOfTypes, $cref, $rref) = extractMultipleTypes($strTypeOption); - my @arrTypeChoices = @{$cref}; - my @arrTypeResults = @{$rref}; - my $isMultipleTypes = ($numOfTypes>=2); - my $strElementType; - - # I know I repeat here the same code as in function "annotate_ptr_as_array" - # Should better unify them in one place, but no time yet. (vietha Aug 23,2004) - if ($isMultipleTypes) { - $annot .= "\tif(0){}\n"; - } - for (my $i=0;$i<$numOfTypes;$i++) { - if (!$isMultipleTypes) { - # single type, strElemenType == strTypeVariable - $strElementType = $strTypeOption; - } else { - my $choice = $arrTypeChoices[$i]; - $annot .= "\telse if\($choice\){\n"; - $strElementType = $arrTypeResults[$i]; - } - - my $strElementGet = get_Option_Code($abuf, "elementGet:"); - if (!$strElementGet){ - $annot .= "\t\tmemcpy\(\$\$\, \&$shadowedClass_parm\-\>$varname\, sizeof\($strElementType\)\);\n"; - } - else { - $annot .= "\t\t$strElementType \$ELEMENT\;\n\t$strElementGet\n"; - $annot .= "\t\tmemcpy(\$\$, \&\$ELEMENT, sizeof\($strElementType\)\)\;\n" - } - if ($isMultipleTypes) { - $annot .= "\t}\n"; - } - } - } - } - elsif ($atype eq "primitive_ptr"){ - - my ($strElementGet) = get_Option_Code($abuf, "elementGet:"); - if (!$strElementGet){ - my $vartypeDeref = chopOneAsterisk($vartype); - $annot .= "\tmemcpy\(\$\$\, $shadowedClass_parm\-\>$varname\, sizeof\($vartypeDeref\)\);" - } - else { - $annot .= "\t$vartype\* \$ELEMENT\;\n\t$strElementGet\n"; - $annot .= "\tmemcpy(\$\$\, \$ELEMENT, sizeof\($vartype\)\)\;" - } - } - elsif ($atype eq "ptr_to_index"){ - my $array_size = get_array_info($abuf); - $annot .= " memcpy\( \$\$\, $marshaledClass_parm\-\>$varname"; - $annot .= ", sizeof\( $vartype \) \* $array_size \)\; "; - } - elsif ($atype eq "ptr_shallow_copy"){ - $annot .= " memcpy\( \$\$\, \&\$varname\, sizeof\( int \)\)\;"; - } - elsif ($atype eq "manual"){ - my ($marshal, $unmarshal, $getSize) = get_functions($abuf); - #if( !$marshal){ - # error_die("Marshaling code expected for \"manual\" annotation",$abuf); - #} - $annot .= $marshal; - } - elsif ($atype eq "predefined"){ - if(!$strTypeOption){ #if there is no customized "elementType" - my ($strElementGet) = get_Option_Code($abuf, "elementGet:"); - if(!$strElementGet) { - $annot.= "\tMarshaled$vartype var\(\&$shadowedClass_parm\-\>$varname\)\;\n"; - }else{ - $annot .= "\t$vartype \$ELEMENT\;\n"; - $annot .= "\t$strElementGet\n"; - $annot .= "\tMarshaled$vartype var\(\&\$ELEMENT\)\;\n"; - } - $annot .= "\tEXTEND_BUFFER(var\.getBufferSize\(\)\)\;\n"; - $annot .= "\t\$SIZE = var\.getBufferSize\(\)\;\n"; - $annot .= "\tmemcpy\(\$\$\, var\.getBuffer\(\)\, var\.getBufferSize\(\)\)\;"; - }else { #if there is customized "elementType" option - my ($numOfTypes, $cref, $rref) = extractMultipleTypes($strTypeOption); - my @arrTypeChoices = @{$cref}; - my @arrTypeResults = @{$rref}; - my $isMultipleTypes = ($numOfTypes>=2); - my $strElementType; - # I know I repeat here the same code as in function "annotate_ptr_as_array" - # Should better unify them in one place, but no time yet. (vietha Aug 23,2004) - if ($isMultipleTypes) { - $annot .= "\tif(0){}\n"; - } - for (my $i=0;$i<$numOfTypes;$i++) { - if (!$isMultipleTypes) { - # single type, strElemenType == strTypeVariable - $strElementType = $strTypeOption; - } else { - my $choice = $arrTypeChoices[$i]; - $annot .= "\telse if\($choice\){\n"; - $strElementType = $arrTypeResults[$i]; - } - - # one of the type of choices might be primitive - my $isPrimitiveType=IsPrimitiveType($strElementType); - - my $strElementGet = get_Option_Code($abuf, "elementGet:"); - if (!$strElementGet){ - if($isPrimitiveType){ - $annot .= "\tEXTEND_BUFFER(sizeof\($strElementType\)\)\;\n"; - $annot .= "\t\$SIZE = sizeof\($strElementType\);\n"; - $annot .= "\t\tmemcpy\(\$\$\, \&$shadowedClass_parm\-\>$varname\, sizeof\($strElementType\)\);\n"; - }else{ - $annot.= "\t\tMarshaled$strElementType var\(\&$shadowedClass_parm\-\>$varname\)\;\n"; - $annot .= "\tEXTEND_BUFFER(var\.getBufferSize\(\)\)\;\n"; - $annot .= "\t\$SIZE = var\.getBufferSize\(\)\;\n"; - $annot .= "\t\tmemcpy\(\$\$\, var\.getBuffer\(\)\, var\.getBufferSize\(\)\)\;\n"; - } - } - else { - if($isPrimitiveType){ - $annot .= "\t\t$strElementType \$ELEMENT\;\n\t$strElementGet\n"; - $annot .= "\tEXTEND_BUFFER(sizeof\($strElementType\)\)\;\n"; - $annot .= "\t\$SIZE = sizeof\($strElementType\);\n"; - $annot .= "\t\tmemcpy(\$\$, \&\$ELEMENT, sizeof\($strElementType\)\)\;\n" - - }else{ - $annot .= "\t\t$strElementType \$ELEMENT\;\n"; - $annot .= "\t\t$strElementGet\n"; - $annot .= "\t\tMarshaled$strElementType var\(\&\$ELEMENT\)\;\n"; - $annot .= "\tEXTEND_BUFFER(var\.getBufferSize\(\)\)\;\n"; - $annot .= "\t\$SIZE = var\.getBufferSize\(\)\;\n"; - $annot .= "\t\tmemcpy\(\$\$\, var\.getBuffer\(\)\, var\.getBufferSize\(\)\)\;\n"; - } - } - - if ($isMultipleTypes) { - $annot .= "\t}\n"; - } - } - } - } - elsif( $atype eq "predefined_ptr"){ - my ($strElementGet) = get_Option_Code($abuf, "elementGet:"); - my $vartypeDeref = chopOneAsterisk($vartype); - if (!$strElementGet) { - $annot .= "\tMarshaled$vartypeDeref var\($shadowedClass_parm\-\>$varname\)\;\n"; - }else{ - $annot .= "\t$vartype\* \$ELEMENT\;\n"; - $annot .= "\t$strElementGet\n"; - $annot .= "\tMarshaled$vartypeDeref var\(\$ELEMENT\)\;\n"; - } - $annot .= "\tEXTEND_BUFFER(var\.getBufferSize\(\)\)\;\n"; - $annot .= "\t\$SIZE = var\.getBufferSize\(\)\;\n"; - $annot .= "\tmemcpy\(\$\$\, var\.getBuffer\(\)\, var\.getBufferSize\(\)\);"; - } - elsif ($atype eq "ptr_as_array"){ - my $outstr = annotate_ptr_as_array($abuf); - if (!$outstr){ - error_die("Failed to parse the annotation",$abuf); - } - else {$annot .= $outstr;} - } - #elsif ($atype eq "embedded" || $atype eq "embedded_ptr" || $atype eq "global"){ - # die "The annotation type $atype does not exist!\n"; - #} - $annot .= "\n }\n"; - #$marshal = $annot; - return $annot; -} - - -sub annotate_ptr_as_array { - my $annot_buf = shift; - my $annot = ""; - my $strTypeOption = get_Option_Name( $annot_buf, "elementType:"); - if ( !$strTypeOption ) { - error_die("Unrecognizable options in ptr_as_array, \"elementType\" expected",$annot_buf); - } - - # accept both keywords "elementCount" and "elementNum" - my $strElementNum = get_Option_Code( $annot_buf, "elementCount:"); - if ( !$strElementNum ) { - my $strElementNum = get_Option_Code( $annot_buf, "elementNum:"); - if ( !$strElementNum ) { - error_die("Unrecognizable options in ptr_as_array, \"elementCount\" expected",$annot_buf); - } - } - - my $strElementGet = get_Option_Code( $annot_buf, "elementGet:"); - if (!$strElementGet ) { - error_die("Unrecognizable options in ptr_as_array, \"elementGet\" expected",$annot_buf); - } - - - $annot .= "\tint copy_off \= 0\;\n"; - $annot .= "\tint \$ELE_COUNT\;\n"; - - $annot .= "\t$strElementNum\n"; #!!! - - $annot .= "\tmemcpy\( \$\$\+copy_off\, \&\$ELE_COUNT\,sizeof\(int\)\)\;\n"; - $annot .= "\tcopy_off \+\= sizeof\(int\)\;\n"; - $annot.= "\tfor\(int \$ELE_INDEX\=0;\$ELE_INDEX\<\$ELE_COUNT\;\$ELE_INDEX\+\+\)\{\n"; - - - my ($numOfTypes, $cref, $rref) = extractMultipleTypes($strTypeOption); - my @arrTypeChoices = @{$cref}; - my @arrTypeResults = @{$rref}; - my $isMultipleTypes = ($numOfTypes>=2); - my $strElementType; - - #print "numOfTypes=$numOfTypes\n"; - - if ($isMultipleTypes) { - $annot .="\t\tif(0){}\n"; - } - my $asterisk; - - for (my $i=0;$i<$numOfTypes;$i++) { - if (!$isMultipleTypes) { - # single type, strElemenType == strTypeVariable - $strElementType = $strTypeOption; - } else { - my $choice = $arrTypeChoices[$i]; - $annot .= "\t\telse if\($choice\){\n"; - $strElementType = $arrTypeResults[$i]; - } - - my $strElementTypeDeref = $strElementType; - # Since the name of type used with "Marshaled..." should not contain "*", we remove it - if ($strElementTypeDeref =~ /\*/) { - #$strElementTypeDeref =~ s/\*.*//; - $strElementTypeDeref = chopOneAsterisk($strElementTypeDeref); - $asterisk = 1; - } - - my $isPrimitiveType=IsPrimitiveType($strElementType); - - - if ($isMultipleTypes) { - if ($asterisk) { - $annot .= "\t\t\tvoid\* \$ELEMENT\;\n"; - } else { - my $result = $arrTypeResults[$i]; - $annot .= "\t\t\t$result \$ELEMENT \;\n"; - } - $annot .= "\t\t\t$strElementGet\n"; - if($isPrimitiveType){ - # nothing - }elsif ($asterisk) { - $annot .= "\t\t\tMarshaled$strElementTypeDeref marEle\(\($strElementType\)\$ELEMENT\)\;\n"; - } else { # if not, add "&" before passing to Marshaled.... - $annot .= "\t\t\tMarshaled$strElementTypeDeref marEle\(\($strElementType\*\)\&\$ELEMENT\)\;\n"; - } - } else { - $annot .= "\t\t\t$strElementType \$ELEMENT;\n\t\t\t$strElementGet\n"; - - if($isPrimitiveType){ - # nothing - }elsif ($asterisk) { # if the element is already a pointer - $annot .= "\t\t\tMarshaled$strElementTypeDeref marEle\(\$ELEMENT\)\;\n"; - } else { #if not, add "&" before passing to Marshaled.... - $annot .= "\t\t\tMarshaled$strElementTypeDeref marEle\(\&\$ELEMENT);\n"; - } - } - - if($isPrimitiveType){ - $annot.= "\t\t\tEXTEND_BUFFER\(sizeof\($strElementType\)\);\n"; - $annot.= "\t\t\tmemcpy\(\$\$\+copy_off\, &\$ELEMENT, sizeof\($strElementType\)\);\n"; - $annot.= "\t\t\tcopy_off \+\= sizeof\($strElementType\);\n"; - }else{ - $annot.= "\t\t\tEXTEND_BUFFER\(marEle\.getBufferSize\(\)\);\n"; - $annot.= "\t\t\tmemcpy\(\$\$\+copy_off\, marEle\.getBuffer\(\)\, marEle\.getBufferSize\(\)\);\n"; - $annot.= "\t\t\tcopy_off \+\= marEle\.getBufferSize\(\);\n"; - } - $annot.= "\t\t\}\n"; - - } - if ($isMultipleTypes) { - $annot .= "\t}\n"; - } - $annot.= "\t\$SIZE \= copy_off;\n"; - - return $annot; -} - - -sub annot_unmarshaling{ - my $annot_buf = shift; - my $annot_type = shift; - my $vartype = shift; - my $varname = shift; - my $annot = " //FIELDUNMARSHAL:\n {\n"; - - my $strTypeOption = get_Option_Name( $annot_buf, "elementType:"); - - if ($annot_type eq "" || $annot_type eq "transient"){} #do nothing - elsif ($annot_type eq "primitive"){ - if(!$strTypeOption){ #if there is no customized "elementType" - my $strElementSet = get_Option_Code( $annot_buf, "elementSet:"); - if(!$strElementSet) { #default - $annot .= "\tmemcpy(\&$shadowedClass_parm\-\>$varname\, \$\$\, sizeof\($vartype\)\);\n";} - else{ - $annot .= "\t$vartype \$ELEMENT;\n"; - $annot .= "\tmemcpy(\&\$ELEMENT, \$\$, sizeof\($vartype\)\);\n"; - $annot .= "\t$strElementSet\n"; - } - }else { #if there is customized "elementType" option - my ($numOfTypes, $cref, $rref) = extractMultipleTypes($strTypeOption); - my @arrTypeChoices = @{$cref}; - my @arrTypeResults = @{$rref}; - my $isMultipleTypes = ($numOfTypes>=2); - my $strElementType; - if ($isMultipleTypes) { - $annot .= "\tif(0){}\n"; - } - for (my $i=0;$i<$numOfTypes;$i++) { - if (!$isMultipleTypes) { - # single type, strElemenType == strTypeVariable - $strElementType = $strTypeOption; - } else { - my $choice = $arrTypeChoices[$i]; - $annot .= "\telse if\($choice\){\n"; - $strElementType = $arrTypeResults[$i]; - } - - my $strElementSet = get_Option_Code($annot_buf, "elementSet:"); - if (!$strElementSet){ - $annot .= "\t\tmemcpy(\&$shadowedClass_parm\-\>$varname\, \$\$\, sizeof\($strElementType\)\);\n"; - } - else { - $annot .= "\t$strElementType \$ELEMENT;\n"; - $annot .= "\tmemcpy(\&\$ELEMENT, \$\$, sizeof\($strElementType\)\);\n"; - $annot .= "\t$strElementSet\n"; - } - if ($isMultipleTypes) { - $annot .= "\t}\n"; - } - } - } - } - elsif ($annot_type eq "primitive_ptr"){ #eg int* i; - my $strElementSet = get_Option_Code($annot_buf, "elementSet:"); - my $vartypeDeref = chopOneAsterisk($vartype); - $annot .= "\t$shadowedClass_parm\-\>$varname \= ($vartype)malloc\(sizeof\($vartypeDeref\)\);\n"; - if(!$strElementSet) { #default - $annot .= "\tmemcpy($shadowedClass_parm\-\>$varname\, \$\$\, sizeof\($vartypeDeref\)\);\n";} - else{ - $annot .= "\t$vartype\* \$ELEMENT;\n"; - $annot .= "\tmemcpy\(\$ELEMENT\, \$\$\, sizeof\($vartype\)\);\n"; - $annot .= "\t$strElementSet\n"; - } - } - elsif ($annot_type eq "ptr_to_index"){ #eg. double d_array[12] - my $array_size = get_array_info($annot_buf); - $annot .= " memcpy\( $marshaledClass_parm\-\>$varname"; - $annot .= ", \$\$, sizeof\( $vartype \) \* $array_size \)\; "; - } - elsif ($annot_type eq "ptr_shallow_copy"){ - $annot .= " memcpy( \&\$varname\, \$\$\, sizeof\( int \)\)\;"; - } - elsif ($annot_type eq "manual"){# manual {marshal()} {unmarshal()} {getSize()} - # get marshaling function from { marshal() } - my ($marshal, $unmarshal, $getSize) = get_functions($annot_buf); - $annot .= $unmarshal; - } - elsif ($annot_type eq "predefined"){ - if(!$strTypeOption){ #if there is no customized "elementType" - my $strElementSet = get_Option_Code($annot_buf, "elementSet:"); - $annot .= "\tMarshaled$vartype var\(\$\$\, \'u\'\)\;\n"; - if(!$strElementSet) { - $annot .="\tvar\.unmarshalTo\(\&$shadowedClass_parm\-\>$varname\)\;\n"; - } - else{ - $annot .= "\t$vartype \$ELEMENT;\n"; - $annot .= "\tvar\.unmarshalTo\(\&\$ELEMENT\)\;\n"; - $annot .= "\t$strElementSet\n"; - } - }else { #if there is customized "elementType" option - my ($numOfTypes, $cref, $rref) = extractMultipleTypes($strTypeOption); - my @arrTypeChoices = @{$cref}; - my @arrTypeResults = @{$rref}; - my $isMultipleTypes = ($numOfTypes>=2); - my $strElementType; - if ($isMultipleTypes) { - $annot .= "\tif(0){}\n"; - } - for (my $i=0;$i<$numOfTypes;$i++) { - if (!$isMultipleTypes) { - # single type, strElemenType == strTypeVariable - $strElementType = $strTypeOption; - } else { - my $choice = $arrTypeChoices[$i]; - $annot .= "\telse if\($choice\){\n"; - $strElementType = $arrTypeResults[$i]; - } - - # one of the type of choices might be primitive - my $isPrimitiveType=IsPrimitiveType($strElementType); - - my $strElementSet = get_Option_Code($annot_buf, "elementSet:"); - if (!$strElementSet){ - if($isPrimitiveType){ - $annot .= "\t\tmemcpy(\&$shadowedClass_parm\-\>$varname\, \$\$\, sizeof\($strElementType\)\);\n"; - } - else{ - $annot .= "\t\tMarshaled$strElementType var\(\$\$\, \'u\'\)\;\n"; - $annot .="\t\tvar\.unmarshalTo\(\&$shadowedClass_parm\-\>$varname\)\;\n"; - } - } - else { - if($isPrimitiveType){ - $annot .= "\t\t$vartype \$ELEMENT;\n"; - $annot .= "\t\tmemcpy(\&\$ELEMENT, \$\$, sizeof\($strElementType\)\);\n"; - $annot .= "\t\t$strElementSet\n"; - }else{ - $annot .= "\t\tMarshaled$strElementType var\(\$\$\, \'u\'\)\;\n"; - $annot .= "\t\t$strElementType \$ELEMENT;\n"; - $annot .= "\t\tvar\.unmarshalTo\(\&\$ELEMENT\)\;\n"; - $annot .= "\t\t$strElementSet\n"; - } - } - if ($isMultipleTypes) { - $annot .= "\t}\n"; - } - } - } - } - elsif ($annot_type eq "predefined_ptr"){#eg: List *ls;//predefined_ptr - my $strElementSet = get_Option_Code( $annot_buf, "elementSet:"); - my $vartypeDeref = chopOneAsterisk($vartype); - $annot .= "\tMarshaled$vartypeDeref var\(\$\$\, \'u\'\);\n"; - if(!$strElementSet) { - $annot .= "\t$shadowedClass_parm\-\>$varname \= var\.unmarshal\(\)\;\n"; - } - else{ - $annot .= "\t$vartype\* \$ELEMENT\;\n"; - $annot .= "\t\$ELEMENT \= var\.unmarshal\(\)\;\n"; - $annot .= "\t$strElementSet\n"; - } - } - elsif ($annot_type eq "ptr_as_array"){ -# int copy_off = 0; -# int $ELE_COUNT; -# memcpy(&$ELE_COUNT, $$+copy_off, sizeof(int)); -# copy_off += sizeof(int); -# for(int $ELE_INDEX=0;$ELE_INDEX<$ELE_COUNT;$ELE_INDEX++){ -# $ELEMENT; -# Marshaled marEle($$+copy_off); -# $ELEMENT = marEle.unmarshal(); -# copy_off += marEle.getBufferSize(); -# - - my ($strTypeOption, $strElementSet, $strElementTypeDeref); - - $strTypeOption = get_Option_Name( $annot_buf, "elementType:"); - if( !$strTypeOption) { - error_die("Unrecognizable options in ptr_as_array, \"elementType\" expected",$annot_buf); - } - $strElementSet = get_Option_Code( $annot_buf, "elementSet:"); - if(!$strElementSet ) { - error_die("Unrecognizable options in ptr_as_array, \"elementSet\" expected",$annot_buf); - } - # numOfTypes = 1: single type case - # numOfTypes>= 2: multiple types, with CASE(...) syntax */ - # int numOfTypes = 0; - # IF strTypeOption == CASE{T:DMXPmtHit,DMXScintHit}{DMXPmtHit*,DMXScintHit*}] - # THEN strTypeVariable = T - # arrTypeChoices = {DMXPmtHit,DMXScintHit} - # arrTypeResults = {DMXPmtHit*,DMXScintHit*} - # return (Number of types); - # ELSE return 1; - - my ($numOfTypes, $cref, $rref) = extractMultipleTypes($strTypeOption); - my @arrTypeChoices = @{$cref}; - my @arrTypeResults = @{$rref}; - my $isMultipleTypes = ($numOfTypes>=2); - - if ($isMultipleTypes) { - $annot .="\tif(0){}\n"; - } - my $asterisk; - - for (my $i=0;$i<$numOfTypes;$i++) { - my ($strElementType, $choice); - if (!$isMultipleTypes) { - # single type, strElemenType == strTypeVariable - $strElementType = $strTypeOption; - } else { - $choice = $arrTypeChoices[$i]; - $annot .= "\telse if\($choice\){\n"; - $strElementType = $arrTypeResults[$i]; - } - - my $strElementTypeDeref = $strElementType; - # Since the name of type used with "Marshaled..." should not contain "*", we remove it - if ($strElementTypeDeref =~ /\*/) { - #$strElementTypeDeref =~ s/\*.*//; - $strElementTypeDeref = chopOneAsterisk($strElementTypeDeref); - $asterisk = 1; - } - - my $isPrimitiveType=IsPrimitiveType($strElementType); - - $annot .= "\t\tint copy_off \= 0\;\n"; - $annot .= "\t\tint \$ELE_COUNT\;\n"; - $annot .= "\t\tmemcpy\(\&\$ELE_COUNT\, \$\$\+copy_off\, sizeof\(int\)\)\;\n"; - $annot .= "\t\tcopy_off \+\= sizeof\(int\)\;\n"; - $annot .= "\t\tfor\(int \$ELE_INDEX\=0;\$ELE_INDEX\<\$ELE_COUNT\;\$ELE_INDEX\+\+\)\{\n"; - if($isPrimitiveType){} - else{ - $annot .= "\t\t\tMarshaled$strElementTypeDeref marEle\(\$\$\+copy_off\)\;\n"; - } - #if ($isMultipleTypes) { - #my $choice = $arrTypeChoices[$i]; - #my $result = $arrTypeResults[$i]; - if($isPrimitiveType){ - $annot .= "\t\t\t$strElementType \$ELEMENT;\n"; - $annot .= "\t\t\tmemcpy\(\&\$ELEMENT,\$\$\+copy_off, sizeof\($strElementType\)\);\n"; - $annot .= "\t\t\tcopy_off \+\= sizeof\($strElementType\);\n"; - }elsif ($asterisk) { - $annot .= "\t\t\t$strElementType \$ELEMENT \= \($strElementType\)marEle\.unmarshal\(\)\;\n"; - $annot .= "\t\t\tcopy_off \+\= marEle\.getBufferSize\(\)\;\n"; - } else { - $annot .= "\t\t\t$strElementType *\$ELEMENT \= \($strElementType *\)marEle\.unmarshal\(\)\;\n"; - $annot .= "\t\t\tcopy_off \+\= marEle\.getBufferSize\(\)\;\n"; - } - #} else { - #$annot .= "\t\t\t$strElementType \$ELEMENT \= \($strElementType\)marEle\.unmarshal\(\)\;\n"; - #} - - $annot .= "\t\t\t$strElementSet\n"; - $annot .= "\t\t\}\n"; - if ($isMultipleTypes) { - $annot .= "\t}\n"; - } - } -} - #elsif ($annot_type eq "embedded" || $annot_type eq "embedded_ptr" || $annot_type eq "global"){} #do nothing - else { - error_die("The annotation type $annot_type does not exist", $annot_buf); - } - $annot .= "\n }\n"; - return $annot; -} - - -sub annot_getSize{ - - my $annot_buf = shift; - my $annot_type = shift; - my $vartype = shift; - my $varname = shift; - my $annot = ""; - my $strMaxSize = ""; - $annot .=" //FIELDSIZE:\n {\n"; - - my $strTypeOption = get_Option_Name( $annot_buf, "elementType:"); - - if ($annot_type eq "" || $annot_type eq "transient"){}#do nothing - elsif ($annot_type eq "primitive"){ - if(!$strTypeOption){ #if there is no customized "elementType" - $annot .="\t\$SIZE = sizeof($vartype);\n"; - }else { #if there is customized "elementType" option - my ($numOfTypes, $cref, $rref) = extractMultipleTypes($strTypeOption); - my @arrTypeChoices = @{$cref}; - my @arrTypeResults = @{$rref}; - my $isMultipleTypes = ($numOfTypes>=2); - my $strElementType; - if ($isMultipleTypes) { - $annot .= "\tif(0){}\n"; - } - for (my $i=0;$i<$numOfTypes;$i++) { - if (!$isMultipleTypes) { - # single type, strElemenType == strTypeVariable - $strElementType = $strTypeOption; - } else { - my $choice = $arrTypeChoices[$i]; - $annot .= "\telse if\($choice\){\n"; - $strElementType = $arrTypeResults[$i]; - } - $annot .="\t\t\$SIZE = sizeof($strElementType);\n"; - if ($isMultipleTypes) { - $annot .= "\t}\n"; - } - } - } - } - elsif ($annot_type eq "primitive_ptr"){ - my $vartypeDeref = chopOneAsterisk($vartype); - $annot .= " \$SIZE = sizeof( $vartypeDeref\)\;"; - } - elsif ($annot_type eq "ptr_shallow_copy"){ - $annot .= " \$SIZE = sizeof( int );"; - } - elsif ($annot_type eq "ptr_to_index"){ - my $size = get_array_info($annot_buf); - $annot .= " \$SIZE = sizeof( $vartype ) * $size\;"; - } - elsif ($annot_type eq "manual"){ - #manual {marshal()} {unmarshal()} {getSize()} - # get marshaling function from { marshal() } - my ($marshal, $unmarshal, $getSize) = get_functions( $annot_buf); - $annot .= $getSize; - #if( !$annot){ die "wrong size function: \n$annot_buf\n";} - } - elsif ($annot_type eq "predefined"){ - $annot .= "\t// no need to declare size since \$SIZE is already assigned in the MARSHAL field\n"; - # option MaxSize is obsolete -# my $strMaxSize = get_Option_Code( $annot_buf, "MaxSize:"); -# if($strMaxSize){ -# $annot .= "\t$strMaxSize\n"; -# }els -# if(!$strTypeOption){ #if there is no customized "elementType" -# my $strElementGet = get_Option_Code($annot_buf, "elementGet:"); -# if (!$strElementGet){ -# $annot .= "\tMarshaled$vartype var(\&$shadowedClass_parm->$varname);\n"; -# }else{ -# $annot .= "\t$vartype \$ELEMENT\;\n\t$strElementGet\n"; -# $annot .= "\tMarshaled$vartype var(\&\$ELEMENT);\n"; -# } -# $annot .= "\t\$SIZE = var.getBufferSize();\n"; -# }else { #if there is customized "elementType" option -# my ($numOfTypes, $cref, $rref) = extractMultipleTypes($strTypeOption); -# my @arrTypeChoices = @{$cref}; -# my @arrTypeResults = @{$rref}; -# my $isMultipleTypes = ($numOfTypes>=2); -# my $strElementType; -# if ($isMultipleTypes) { -# $annot .= "\tif(0){}\n"; -# } -# for (my $i=0;$i<$numOfTypes;$i++) { -# if (!$isMultipleTypes) { -# # single type, strElemenType == strTypeVariable -# $strElementType = $strTypeOption; -# } else { -# my $choice = $arrTypeChoices[$i]; -# $annot .= "\telse if\($choice\){\n"; -# $strElementType = $arrTypeResults[$i]; -# } -# # one of the type of choices might be primitive -# my $isPrimitiveType=IsPrimitiveType($strElementType); -# if($isPrimitiveType){ -# $annot .="\t\t\$SIZE = sizeof($strElementType);\n"; -# }else{ -# $annot .= "\t\tMarshaled$strElementType var(\&$shadowedClass_parm->$varname);\n"; -# $annot .= "\t\t\$SIZE = var.getBufferSize();\n"; -# } -# if ($isMultipleTypes) { -# $annot .= "\t}\n"; -# } -# } -# } - } - elsif ($annot_type eq "predefined_ptr"){ # eg: List *ls;//predefined_ptr - $annot .= "\t// no need to declare size since \$SIZE is already assigned in the MARSHAL field\n"; -# my $vartypeDeref = chopOneAsterisk($vartype); -# my ($strElementGet) = get_Option_Code($annot_buf, "elementGet:"); -# if (!$strElementGet) { -# $annot .= "\t$vartype\* \$ELEMENT\;\n"; -# $annot .= "\t$strElementGet\n"; -# $annot .= "\tMarshaled$vartypeDeref var\(\$ELEMENT);\n"; -# }else{ -# $annot .= "\tMarshaled$vartypeDeref var\($shadowedClass_parm->$varname);\n"; -# } -# $annot .= "\t\$SIZE = var.getBufferSize();"; - } - elsif ($annot_type eq "ptr_as_array"){ - #changed by imltv 10/13/03 ==>remove MAXSize annotation - } - #elsif ($annot_type eq "embedded" || $annot_type eq "embedded_ptr" || $annot_type eq "global"){} #do nothing - else{ - error_die("The annotation type $annot_type does not exist", $annot_buf); - } - $annot .= "\n }\n"; - return $annot; -} - - -#annot_buf is in the form of --- TYPE NAME [num]; //ptr_to_index -sub get_array_info { - my $annot = shift; - if (($annot =~ /\[(\d+)\]/) && $1){ - return $1; - } - else { - error_die("Ill-formed array annotations", $annot); - } -} - -sub get_functions { - # annot_buf is in the form of --- - # TYPE NAME; //manual {marshal()} {unmarshal()} {getSize()} - #replaces get_marshal_func(), get_unmarshal_func(), and get_size_func() - my $buf = shift; - - #if ($buf =~ /\{(.*)\}\s+\{(.*)\}\s+\{(.*)\}/){ - #print "buf=$buf\n"; - if ($buf =~ /\{([\s\S]*)\}\s+\{([\s\S]*)\}\s+\{([\s\S]*)\}/){ - my @rvalue = ($1, $2, $3); - #print "Manual buffer: Marshal field = $1\n Unmarshal field = $2\n Marshal size = $3\n"; - return @rvalue; - } - else{ - error_die("Invalid format for \"manual\" annotation.\nMust be \{MARSHALING CODE\} \{UNMARSHALING CODE\} \{SIZE\}",$buf); - } - -} - - -sub get_Option_Name{ - my $annot_buf = shift; - my $tag = shift; - if ($annot_buf =~ /$tag\s*([^\]]*)/){return $1;} - else {return;} -} - -sub get_Option_Code{ - my $annot_buf = shift; - my $tag = shift; - if ($annot_buf =~ /$tag\s*\{([^\}]*)/){return $1;} - else {return;} -} - -#(MSH_IsSameClass::Is) => DMXPmtHit* | true => DMXScintHit* -#arrTypeChoices = {DMXPmtHit,DMXScintHit} -#arrTypeResults = {DMXPmtHit*,DMXScintHit*} -#return (Number of types); -#ELSE return 1; -#CONDITION_COMMAND -> "(" C_expression ")" "==>" C_type - -sub extractMultipleTypes{ - my $strTypeOption = shift; - - #print "strTypeOption=$strTypeOption\n"; - - my @conds = split(/\|/, $strTypeOption); #assumes the test does not contain the "|" token - my $i = 0; - my @arrTypeChoices = (); - my @arrTypeResults = (); - my @arrConstructorArgs = (); - - - if ($#conds == 0){ #no conditionals, but one result - if ($conds[0] =~ /\s*(.*)\((.*)\)/){ # Foo(1,2) (type with constructor) - $arrTypeResults[0] = $1; - $arrConstructorArgs[0] = $2; - }elsif ($conds[0] =~ /\s*(.*)/){ # Foo (only the type) - $arrTypeResults[0] = $1; - $arrConstructorArgs[0] = ""; - } - else { - error_die("Invalid type expression: $conds[0]",$strTypeOption); - } - - return (1, \@arrTypeChoices, \@arrTypeResults,\@arrConstructorArgs); - } - - for ($i =0; $i<= $#conds; $i++){ - #print "cond=$conds[$i]\n"; - #if ($conds[$i] =~ /(.*)\s*\=\=\>\s*(.*)/){ - - if ($conds[$i] =~ /(.*)\s*\=\>\s*(.*)\((.*)\)/){ # Foo(1,2) (type with constructor) - $arrTypeChoices[$i] = $1; - $arrTypeResults[$i] = $2; - $arrConstructorArgs[$i] = $3; - }elsif ($conds[$i] =~ /(.*)\s*\=\>\s*(.*)/){ # Foo (only the type) - $arrTypeChoices[$i] = $1; - $arrTypeResults[$i] = $2; - $arrConstructorArgs[$i] = ""; - } - else { - error_die("Invalid conditional expression: $conds[$i]",$strTypeOption); - } - } - return ($#arrTypeChoices+1, \@arrTypeChoices, \@arrTypeResults, \@arrConstructorArgs); -} - -sub chopOneAsterisk{ - my $type = shift; - $type =~s/\*//; - return $type; -} - -sub IsPrimitiveType{ - my $type = shift; - # trim the spaces - $type =~ s/^\s+//; - $type =~ s/\s+$//; - #print "primitiveType=\'$type\'\n"; - if(($type eq 'bool')||($type eq 'char')||($type eq 'int')||($type eq 'long') - ||($type eq 'float') || ($type eq 'double')){ - return 1; - } - return 0; -} - -sub error_die { - my $msg = shift; - my $source = shift; - die "Error: $msg\nAt line $line_counter: $source\n"; -} - - diff --git a/marshalgen-1.0/Phase2/Makefile b/marshalgen-1.0/Phase2/Makefile deleted file mode 100644 index 6b8b53d6..00000000 --- a/marshalgen-1.0/Phase2/Makefile +++ /dev/null @@ -1,40 +0,0 @@ -CFLAGS=-g -O0 -CC=gcc ${CFLAGS} - -# test: marshalgen -# @ echo "" -# ./marshal < marshalgen.in - -marshal: marshalgen.tab.o lex.yy.o mast.o - ${CC} -o marshal marshalgen.tab.o lex.yy.o mast.o - -mast.o : mast.c mast.h - ${CC} -c mast.c - -# -d causes marshalgen.tab.h to be generated -marshalgen.tab.c marshalgen.tab.h: marshalgen.y - bison -d -v marshalgen.y - -lex.yy.o: lex.yy.c marshalgen.tab.h - ${CC} -c lex.yy.c - -lex.yy.c: marshalgen.l - flex marshalgen.l - -marshalgen.tab.o: marshalgen.tab.c - ${CC} -o marshalgen.tab.o -c -DYYERROR_VERBOSE marshalgen.tab.c - -clean: - rm -f core marshalgen marshalgen.tab.h *.o *~ marshalgen.output\ - marshalgen.tab.c lex.yy.c marshalgen.output - -distclean: clean - rm -f marshal - -dist: distclean - dir=`basename $$PWD`; cd ..; tar cvf $$dir.tar ./$$dir; \ - gzip $$dir.tar && ( cd $$dir; ls -l ../$$dir.tar.gz ) - -test-debug: marshalgen.tab.c lex.yy.o - rm -f marshalgen.tab.o - make DEBUG=-DYYDEBUG test diff --git a/marshalgen-1.0/Phase2/marshalgen.l b/marshalgen-1.0/Phase2/marshalgen.l deleted file mode 100644 index 8dbb98b7..00000000 --- a/marshalgen-1.0/Phase2/marshalgen.l +++ /dev/null @@ -1,141 +0,0 @@ -/* - * %{ HEADER %} - * marshaling class (...) { body } - * body := decls; | decls; { GSS } { GSS } { GSS } - * GSS means "Get, Set, or Size" (Get field for marshaling, Set field for - * unmarshaling, Size of field) -*/ - -D [0-9] -L [a-zA-Z_] -H [a-fA-F0-9] -E [Ee][+-]?{D}+ -FS (f|F|l|L) -IS (u|U|l|L)* -COLON ":" - -BEGIN_C "%{" -END_C "%}" -BRACKETS "[]" - -%{ -#define YYSTYPE char * - -#include -#include /* for malloc() */ -#include "marshalgen.tab.h" - -static void count(); -static int nested_braces = 0; -static void error(char *str) { printf(str); printf("/n"); abort(); } -extern int yy_line; -%} - -%x HEADER -%x GSS -%x GSS_C_COMMENT -%x C_COMMENT - - -%% -[\n] { yy_line++; count(); } - -"%{" { count(); BEGIN(HEADER); return(BEGIN_C); } -
[^%]* { count(); return(OTHER); } -
"%}" { count(); BEGIN(INITIAL); return(END_C); } - -"{" { count(); if (++nested_braces == 2) BEGIN(GSS); - return('{'); } -"}" { count(); - if (--nested_braces < 0) error("unbalanced braces"); - return('}'); } - -[^*]* { count(); return(OTHER); } -"*"+[^*/]* { count(); return(OTHER); } -"*"+"/" { count(); BEGIN(GSS); return(OTHER); } - -[^*]* { count(); } -"*"+[^*/]* { count(); } -"*"+"/" { count(); BEGIN(INITIAL); } - -\"(\\.|[^\\"])*\" { count(); return(OTHER); /* STRING_LITERAL */ } -"/*" { count(); BEGIN(GSS_C_COMMENT); return(OTHER); } -"$" { count(); return(OTHER); } -"$$" { count(); return(DOLLARS); } -"$SIZE" {count(); return(DOLLARSIZE); } -"$THIS" {count(); return(DOLLAR_THIS); } -"$THIS_SHADOW" {count(); return(DOLLAR_THIS_SHADOW); } -"$ELEMENT" {count(); return(DOLLAR_ELEMENT); } - -"$ELE_NUM" {count(); return(DOLLAR_ELE_NUM); } -"$ELE_COUNT" {count(); return(DOLLAR_ELE_NUM); } - -"$INDEX" {count(); return(DOLLAR_INDEX); } -"$ELE_INDEX" {count(); return(DOLLAR_INDEX); } -"$TYPE_CHOICE" {count(); return(TYPE_CHOICE); } - -[^{}$]* { count(); return(OTHER); } -"{" { count(); ++nested_braces; return(OTHER); } -"}" { count(); - if (--nested_braces < 1) error("internal error"); - if (nested_braces == 1) - { BEGIN(INITIAL); return('}'); } - else return(OTHER); - } - -"//".*\n { yy_line++; count(); /* C++-style comments in .msh */ } - -"(" { count(); return('('); } -")" { count(); return(')'); } -"," { count(); return(','); } -":" { count(); return(':'); } -";" { count(); return(';'); } -("*")+ { count(); return(ASTERISKS); } -"&" { count(); return('&'); } -"[]" { count(); return(BRACKETS); } -"<" { count(); return('<'); } -">" { count(); return('>'); } - -"template" { count(); return(TEMPLATE); } -"class" { count(); return(CLASS); } -"struct" { count(); return(CLASS); } -"marshaling" { count(); return(MARSHALING); } -"unmarshaling" { count(); return(UNMARSHALING); } -"constructor" { count(); return(CONSTRUCTOR); } -{D}+{IS}? { count(); return(CONSTANT); } -{D}+{E}{FS}? { count(); return(CONSTANT); } -{D}*"."{D}+({E})?{FS}? { count(); return(CONSTANT); } -{D}+"."{D}*({E})?{FS}? { count(); return(CONSTANT); } - -{L}({L}|{D}|{COLON})* { count(); return(ID); } -[ \t\v\f] { count(); } -. { count(); return(OTHER); } - -%% - -yywrap() -{ - return(1); -} - - -int column = 0; - -void count() -{ - int i; - - /* This was added to define the semantic value of the current yytext */ - yylval = memcpy( malloc(yyleng + 1), yytext, yyleng ); - yylval[yyleng] = '\0'; - - for (i = 0; yytext[i] != '\0'; i++) - if (yytext[i] == '\n') - column = 0; - else if (yytext[i] == '\t') - column += 8 - (column % 8); - else - column++; - - //ECHO; -} diff --git a/marshalgen-1.0/Phase2/marshalgen.y b/marshalgen-1.0/Phase2/marshalgen.y deleted file mode 100644 index db7571e3..00000000 --- a/marshalgen-1.0/Phase2/marshalgen.y +++ /dev/null @@ -1,200 +0,0 @@ -/* For us, semantic values are strings */ -%{ -#define YYSTYPE char * -#include "mast.h" -struct mast *tree; -%} - -%token BEGIN_C END_C TOBECOPIED STMTS -%token CLASS MARSHALING UNMARSHALING CONSTRUCTOR -%token ID DOLLARS DOLLARSIZE -%token CONSTANT STRINGLITERAL BRACKETS ASTERISKS TEMPLATE -%token DOLLAR_THIS DOLLAR_ELEMENT DOLLAR_ELE_NUM DOLLAR_INDEX -%token DOLLAR_THIS_SHADOW TYPE_CHOICE -%token OTHER - - -%start program -%% - -program - : quotes specs {$$ = (char *)Mast_init($1, (struct specs*)$2); - tree = (struct mast*)$$;} - ; - -quotes - : - | BEGIN_C header END_C {$$ = $2;} - ; - -header - : OTHER {$$ = $1;} - | OTHER stmts {$$ = (char *)strconcat(2, $1, $2);} - ; - -specs - : spec {$$ = (char*)Specs_init((struct spec*)$1, NULL);} - | spec specs - { $$ = (char *)Specs_init((struct spec*)$1, (struct specs*)$2);} - ; - -spec - : template_declare MARSHALING CLASS mtype '(' formals ')' parent_classes '{' fieldspecs UNMARSHALING CONSTRUCTOR constructor_call '}' - {$$ = (char *)Spec_init($1,$4, (struct formals *)$6, $8, - (struct fieldspecs*)$10, $13);} - ; - -template_declare - : TEMPLATE '<' class_option template_name '>' {$$ = (char*)strconcat(7,$1," ",$2,$3," ",$4,$5);} - | {$$ = " ";} - ; - -class_option : CLASS { $$ = $1;} - | { $$ = " ";} - ; - -template_name: ID { $$ = $1;} - ; - -formals - : type ID formalsrest { $$ = (char*)Formals_init($1, $2, - (struct formals *)$3); } - ; - -formalsrest - : { $$ = NULL; } - | ',' type ID formalsrest { $$ = (char*)Formals_init($2, $3, - (struct formals *)$4) } - ; - -parent_classes: ':' ID ID parent_list {$$ = (char*)strconcat(7, $1," ",$2," ",$3," ",$4);} - | { $$ = "";} - ; - -parent_list : - ',' ID ID parent_list { $$ = (char*)strconcat(6, $1," ",$2," ",$3, $4);} - | { $$ = "";} - ; - -fieldspecs - : { $$ = NULL; } - | fieldspec fieldspecs - {$$ = (char*)Fieldspecs_init( - (struct fieldspec*)$1, (struct fieldspecs*)$2);} - ; - -fieldspec - : type ID ';' gss - {$$ = (char *)Fieldspec_init($1, $2, (struct gss*)$4);} - ; - -/* gss - Get, Set, and Size */ -gss - : {$$ = NULL;} - | getspec setspec sizespec {$$ = (char *)Gss_init($1, $2, $3);} - ; - -getspec - : '{' stmts '}' {$$ = (char *)strconcat(3, "{", $2, "}");} - ; - -setspec - : '{' stmts '}' {$$ = (char *)strconcat(3, "{", $2, "}");} - ; - -sizespec - : '{' stmts '}' {$$ = (char *)strconcat(3, "{", $2, "}");} - ; - -constructor_call - : '{' stmts '}' {$$ = (char *)strconcat(3, "{", $2, "}");} - ; - -stmts - : OTHER {$$ = $1;} - | DOLLARS {$$ = "msh_cursor";} - | DOLLARSIZE {$$ = "msh_currentSize"; } - | DOLLAR_THIS {$$ = "param"; } - | DOLLAR_THIS_SHADOW {$$ = "Shadowed_param"; } - | DOLLAR_ELEMENT {$$ = "anElement"; } - | DOLLAR_ELE_NUM {$$ = "elementNum"; } - | DOLLAR_INDEX {$$ = "index"; } - | TYPE_CHOICE {$$ = "msh_typechoice"; } - - | OTHER stmts {$$ = (char *)strconcat(2, $1, $2);} - | DOLLARS stmts {$$ = (char *)strconcat(2, "msh_cursor", $2);} - | DOLLARSIZE stmts {$$ = (char *)strconcat(2, "msh_currentSize", $2);} - | DOLLAR_THIS stmts {$$ = (char *)strconcat(2, "param", $2);} - | DOLLAR_THIS_SHADOW stmts {$$ = (char *)strconcat(2, "Shadowed_param", $2);} - | DOLLAR_ELEMENT stmts {$$ = (char *)strconcat(2, "anElement", $2);} - | DOLLAR_ELE_NUM stmts {$$ = (char *)strconcat(2, "elementNum", $2);} - | DOLLAR_INDEX stmts {$$ = (char *)strconcat(2, "index", $2);} - | TYPE_CHOICE stmts {$$ = (char *)strconcat(2, "msh_typechoice", $2);} - ; - -/* support templated class name */ -mtype - : ID {$$ = $1;} - | ID ASTERISKS {$$ = (char*)strconcat(2, $1, $2);} - | ID '<' mtype '>' {$$ = (char*)strconcat(4, $1,$2,$3,$4);} - | ID '<' mtype '>' ASTERISKS {$$ = (char*)strconcat(5, $1,$2,$3,$4,$5);} - ; - -/* type for declarations */ -type - : mtype {$$ = $1;} - | mtype BRACKETS {$$ = (char*)strconcat(2, $1, $2);} - | mtype '&' {$$ = (char*)strconcat(2, $1, $2);} - - | CLASS mtype {$$ = (char*)strconcat(2, $1, $2);} - | CLASS mtype BRACKETS {$$ = (char*)strconcat(3, $1, $2, $3);} - | CLASS mtype '&' {$$ = (char*)strconcat(3, $1, $2, $3);} - ; - - -%% - -#include -#include - -extern char yytext[]; -extern int column; -int yy_line = 1; - -yyerror(s) -char *s; -{ - fflush(stdout); - printf("%s",yylval); - printf("\n%*s\nLine %d: %*s\n", column, "^", yy_line, column, s); -} - - - -main(int argc, char **argv) -{ - extern FILE *yyin; - FILE *fout; - if(argc < 3){ - printf("Usage: %s \n", argv[0]); - exit(1); - } - yyin = fopen(argv[1],"r"); - - fout = fopen(argv[2], "w+"); - if(fout == NULL) { - printf("Can't create output file %s", argv[2]); - exit(-1); - } - - - yyparse(); - mast_print(tree); - /* printf("num_specs = %d, num_fieldspecs = %d\n", num_specs(tree), - num_fieldspecs(tree->sp->sp->fsp)); */ - generate_files(tree, fout); - - fclose(yyin); - fclose(fout); - exit(0); -} diff --git a/marshalgen-1.0/Phase2/mast.c b/marshalgen-1.0/Phase2/mast.c deleted file mode 100644 index 9a784ebe..00000000 --- a/marshalgen-1.0/Phase2/mast.c +++ /dev/null @@ -1,920 +0,0 @@ -#include -#include -#include - -#include "mast.h" - -//vietha 2003.05.09 -#define SHADOWED_LABEL ("Shadowed") - -int num_specs(struct mast *m) { - int n = 0; - struct specs *cursor; - - for(cursor = m->sp; cursor != NULL; cursor = cursor->next) { - n++; - } - - return n; -} - -int num_fieldspecs(struct fieldspecs *f) { - int n = 0; - struct fieldspecs *cursor; - - for(cursor = f; cursor != NULL; cursor = cursor->next) { - n++; - } - - return n; -} - -int num_formals(struct formals *fmls) { - int n = 0; - struct formals *cursor; - - for(cursor = fmls; cursor != NULL; cursor = cursor->next) { - n++; - } - - return n; -} - -struct mast *Mast_init(char *m, struct specs *s) { - struct mast *ret; - ret = (struct mast*)malloc(sizeof(struct mast)); - - ret->macros = m; - ret->sp = s; - - return ret; -} - -void Mast_free(struct mast *m) { - if(m->sp != NULL) - Specs_free(m->sp); - free(m); - m = NULL; -} - -struct spec *Spec_init(char* template_decl, char *mt, struct formals *fmls, char* parent_classes, struct fieldspecs *f, char* constructor) { - struct spec *ret; - ret = (struct spec*)malloc(sizeof(struct spec)); - - ret->mtype = mt; - ret->fmls = fmls; - ret->fsp = f; - //vietha 2003.4.29 - ret->template_decl = template_decl; - ret->parent_classes = parent_classes; - ret->constructor_call = constructor; - - return ret; -} - -void Spec_free(struct spec *s) { - // fix mtype leak ! - - if(s->fmls != NULL) - Formals_free(s->fmls); - if(s->fsp != NULL) - Fieldspecs_free(s->fsp); - - free(s); - s = NULL; -} - -struct specs *Specs_init(struct spec *sp, struct specs *nt) { - struct specs *ret; - ret = (struct specs*)malloc(sizeof(struct specs)); - - ret->sp = sp; - ret->next= nt; - - return ret; -} - -void Specs_free(struct specs *s) { - if(s->sp != NULL) - Spec_free(s->sp); - if(s->next != NULL) - Specs_free(s->next); - free(s); - s = NULL; -} - -struct formals *Formals_init(char *type, char *name, - struct formals *next) -{ - struct formals *ret; - ret = (struct formals*)malloc(sizeof(struct formals)); - - ret->type = type; - ret->name = name; - ret->next = next; - - return ret; -} - -void Formals_free(struct formals *f) { - //Fix type and name leak!! - - if(f->next != NULL) - Formals_free(f->next); - - free(f); - f = NULL; -} - -struct fieldspec *Fieldspec_init(char *t, char *nm, struct gss *g) { - struct fieldspec *ret; - ret = (struct fieldspec*)malloc(sizeof(struct fieldspec)); - - ret->type = t; - ret->name = nm; - ret->g = g; - - return ret; -} - -void Fieldspec_free(struct fieldspec *fsp) { - // Fix type and name leak! - - if(fsp->g != NULL) - Gss_free(fsp->g); - - free(fsp); - fsp = NULL; -} - -struct gss *Gss_init(char *g, char *s, char *sz) { - struct gss *ret; - ret = (struct gss*)malloc(sizeof(struct gss)); - - ret->getsp = g; - ret->setsp = s; - ret->sizesp = sz; - - return ret; -} - -void Gss_free(struct gss *g) { - // Fix get, set and size big leak!! - - free(g); - g = NULL; -} - - -struct fieldspecs *Fieldspecs_init(struct fieldspec *f, struct fieldspecs *nt) { - struct fieldspecs *ret; - ret = (struct fieldspecs*)malloc(sizeof(struct fieldspecs)); - - ret->fsp = f; - ret->next= nt; - - return ret; -} - -void Fieldspecs_free(struct fieldspecs *fsps) { - if(fsps->next != NULL) - Fieldspecs_free(fsps->next); - if(fsps->fsp != NULL) - Fieldspec_free(fsps->fsp); - - free(fsps); - fsps = NULL; -} - - -void mast_print(struct mast *m) { - //printf("macros: {\n%s\n}\n", m->macros); - specs_print(m->sp); -} - -void specs_print(struct specs *s) { - if(s == NULL) { - return; - } - spec_print(s->sp); - specs_print(s->next); -} - -void spec_print(struct spec *s) { - //printf("mtype: %s\n", s->mtype); - formals_print(s->fmls); - fieldspecs_print(s->fsp); -} - -void formals_print(struct formals *fmls) { - //printf("formals: ( \n"); - //printf("%s %s", fmls->type, fmls->name); - formalsrest_print(fmls->next); -} - -void formalsrest_print(struct formals *fmlsrest) { - if(fmlsrest != NULL) { - //printf(", %s %s", fmlsrest->type, fmlsrest->name); - formalsrest_print(fmlsrest->next); - } else { - //printf(" )\n"); - } -} - -void fieldspecs_print(struct fieldspecs *f) { - if(f == NULL) { - return; - } - fieldspec_print(f->fsp); - fieldspecs_print(f->next); -} - -void fieldspec_print(struct fieldspec *f) { - //printf("fieldspec: {\n"); - //printf("type: %s\n", f->type); - //printf("name: %s\n", f->name); - gss_print(f->g); - //printf("}\n"); -} - -void gss_print(struct gss* g) { - if(g == NULL) return; - - //printf("getspec: %s\n", g->getsp); - //printf("setspec: %s\n", g->setsp); - //printf("sizespec: %s\n", g->sizesp); -} - -//concatenates variable number of strings, the first argument specifies -//the number of string to be concatenated. Returns the string concatenated -//caller should call free to free the storage allocated. -char *strconcat(int n, ...) { - va_list ap; - int i , total_len = 0; - char **s; - char *ret; - - va_start(ap, n); - if(n <= 0) return NULL; - - s = (char **)malloc(n * sizeof(char *)); - - for(i = 0; i < n; i++) { - s[i] = va_arg(ap, char *); - total_len += strlen(s[i]); - } - - ret = (char *)malloc(total_len + 1); - strcpy(ret, s[0]); - for(i = 1; i < n; i++) { - strcat(ret, s[i]); - } - free(s); - va_end(ap); - - return ret; -} - -/* Based on one spec (class ... marshal(..) {...}) - create a "Shadowed" class to access "protected" data fields of the main class - vietha 2003.05.09 */ -void generate_shadowClass(struct spec *s, FILE *fs) { - char file_name[50], instance_var[51]; - char *mtype = s->mtype; - char *type = s->fmls->type; - char *name = s->fmls->name; - int k, i; - int numOffieldspecs = num_fieldspecs(s->fsp); - - struct fieldspec *fsp; - char *ftype; //field type - char *fname; //field name - //vietha 2003.4.29 - char mtype_without_template[50]; - char* type_without_asterisk = strdup(type); - char* ptr; - - // remove the "<...>" from the class type - memset(mtype_without_template, 0, sizeof(mtype_without_template)); - typename_without_template(mtype,mtype_without_template); - - // remove the '*' from the type - ptr = strrchr(type_without_asterisk,'*'); - if(ptr) *ptr='\0'; - - fprintf(fs, "\n%s class %s;\n", s->template_decl, mtype_without_template); - - fprintf(fs, "\n%s class %s%s : public %s{\n", s->template_decl, SHADOWED_LABEL, mtype_without_template, type_without_asterisk); - indent(fs,1); - fprintf(fs, "friend class %s;\n", mtype); - free(type_without_asterisk); - -#if 0 - //class def - fprintf(fs, "\n%s class %s%s %s{\n", s->template_decl, SHADOWED_LABEL, mtype_without_template, s->parent_classes); - - // Data field declarations - //Declare a fields , these should be the same exact types and names - //as the those specified by the user, I am making it public here for - // accessing the private data fields of the main class - fprintf(fs, "public:\n"); - for(k = 1; k <= numOffieldspecs; k++) { - int i = 1; - struct fieldspecs *cursor; - - if(s->fmls != NULL && s->fmls->next != NULL) - isMultipleMarshal = 1; - - //First go to the num fieldspec - for(cursor = s->fsp; cursor != NULL; cursor = cursor->next) { - if(i == k) - break; - i++; - } - fsp = cursor->fsp; - - ftype = fsp->type; //field type - fname = fsp->name; //field name - //gss1 = fsp->g; - - indent(fs,1); - fprintf(fs, "%s %s;\n", ftype, fname); - } -#endif - - //Finish up - fprintf(fs, "};\n\n"); -} - - -//Based on one spec (class ... marshal(..) {...}) -//creates files: one .h file -void generate_hfile(struct spec *s, FILE *fs) { - //char file_name[50], instance_var[51]; - char *mtype = s->mtype; - char *type = s->fmls->type; - char *name = s->fmls->name; - int len = 0, i; - int numOffieldspecs = num_fieldspecs(s->fsp); - - //vietha 2003.4.29 - char mtype_without_template[50]; - memset(mtype_without_template, 0, sizeof(mtype_without_template)); - typename_without_template(mtype,mtype_without_template); - - //class def - //vietha - //fprintf(fs, "class %s : public %s {\n", mtype, "MarshaledObj"); - fprintf(fs, "%s class %s : public %s {\n", s->template_decl, mtype_without_template, "MarshaledObj"); - - /* Data field declarations */ - //Declare a field for Foo *, this should be the same exact type - //as the type specified by the user, I am making it public here only for - //easiness for testing. (Although a friend class would be better) - fprintf(fs, "public:\n"); - indent(fs,1); - fprintf(fs, "%s %s;\n", type, name); - //vietha 2003.05.09 - indent(fs,1); - fprintf(fs, "%s%s* %s_%s;\n", SHADOWED_LABEL, mtype, SHADOWED_LABEL, name); - - fprintf(fs, "public:\n"); -} - -/* generate the implementation of functions of the Marshaled... Class - Before, these were put in a .cpp file, - but now I put them in the end of the .h file , - because the implementation of a class with template should be in the heaher files. - vietha 2003/05/01 - */ -void generate_cfile(struct spec *s, FILE *fs) { - char file_name[50]; - char mtype_without_template[50]; - char *mtype = s->mtype; - char *type = s->fmls->type; - char *name = s->fmls->name; - int len = 0, i; - int numOffieldspecs = num_fieldspecs(s->fsp); - char type_no_star[128]; //type name without the *, used in "new type();" - - strcpy(type_no_star, type); - type_no_star[strlen(type)-1] = '\0'; - - //vietha 2003.4.29 - memset(mtype_without_template, 0, sizeof(mtype_without_template)); - typename_without_template(mtype,mtype_without_template); - - - //Implement constructors - //fprintf(fs, "%s %s::%s(%s %s) : MarshaledObj() {\n", s->template_decl, mtype, mtype_without_template, type, "objptr"); - fprintf(fs, "%s(%s %s) : MarshaledObj() {\n", mtype_without_template, type, "objptr"); - - indent(fs,1); - fprintf(fs, "msh_isUnmarshalDone = false;\n"); - indent(fs,1); - fprintf(fs, "this->%s = objptr;\n", name); - //vietha 2003.05.09 - indent(fs,1); - fprintf(fs, "this->%s_%s = (%s%s*)this->%s;\n", SHADOWED_LABEL, name, SHADOWED_LABEL, mtype, name); - - - //If objptr == NULL, then we stop here. - indent(fs,1); - fprintf(fs, "if (objptr == NULL)\n"); - indent(fs,2); - fprintf(fs, "return;\n\n"); - - for(i = 1; i <= numOffieldspecs; i++) { - // Add shallow copy, vietha - //for(i = 0; i <= numOffieldspecs; i++) { - indent(fs,1); - fprintf(fs, "marshal%d();\n", i); - } - fprintf(fs, "}\n\n"); - - //fprintf(fs, "%s %s::%s(void *buf, char isUnmarshaling)\n", s->template_decl, mtype, mtype_without_template); - fprintf(fs, "%s(void *buf, char isUnmarshaling = 'u')\n", mtype_without_template); - fprintf(fs, ": MarshaledObj(buf, isUnmarshaling) {\n"); - indent(fs,1); - fprintf(fs, "msh_isUnmarshalDone = false;\n"); - fprintf(fs, "}\n\n"); - - //Destructor - //fprintf(fs, "%s %s::~%s() {\n", s->template_decl, mtype, mtype_without_template); - fprintf(fs, "~%s() {\n", mtype_without_template); - indent(fs,1); - fprintf(fs, "//if(msh_isUnmarshalDone && this->%s != NULL) {\n", name); - indent(fs,2); - fprintf(fs, "//delete this->%s;\n", name); - indent(fs,1); - fprintf(fs, "//}\n"); - fprintf(fs, "}\n\n"); - - //unmarshal function unmarshals the whole object - //fprintf(fs, "%s %s %s::unmarshal() {\n", s->template_decl, type, mtype); - fprintf(fs, "%s unmarshal() {\n", type); - indent(fs,1); - fprintf(fs, "//We don't want to unmarshal the buffer is empty.\n"); - indent(fs,1); - //fprintf(fs, "if(*(int *)this->msh_buffer == 0) {\n"); - fprintf(fs, "if(msh_size <= MSH_HEADER_SIZE) {\n"); - indent(fs,2); - fprintf(fs, "//This is buggy, we can't always assume that\n"); - indent(fs,2); - fprintf(fs, "//obj == NULL <==> List is empty.\n"); - indent(fs,2); - fprintf(fs, "return NULL;\n"); - indent(fs,1); - fprintf(fs, "} else {\n"); - indent(fs,2); - - // vietha 2004.08.29 - //fprintf(fs, "this->%s = new %s();\n", name, type_no_star); - fprintf(fs, "%s\n", s->constructor_call); - - //vietha 2003.05.09 - indent(fs,2); - fprintf(fs, "this->%s_%s = (%s%s*)this->%s;\n", SHADOWED_LABEL, name, SHADOWED_LABEL, mtype, name); - - indent(fs,2); - fprintf(fs, "this->msh_isUnmarshalDone = true;\n"); - - for(i = 1; i <= numOffieldspecs; i++) { - // Add shallow copy, vietha - //for(i = 0; i <= numOffieldspecs; i++) { - indent(fs,2); - fprintf(fs, "unmarshal%d();\n", i); - } - indent(fs,2); - fprintf(fs, "return this->%s;\n", name); - indent(fs,1); - fprintf(fs, "}\n"); - fprintf(fs, "}\n\n"); - - - //vietha 2003.04.28 - //unmarshal function that copies to an already-existing object - //fprintf(fs, "%s void %s::unmarshalTo(%s obj) {\n", s->template_decl, mtype, type); - fprintf(fs, "void unmarshalTo(%s obj) {\n", type); - indent(fs,1); - fprintf(fs, "//We don't want to unmarshal the buffer is empty.\n"); - indent(fs,1); - //fprintf(fs, "if(*(int *)this->msh_buffer == 0) {\n"); - fprintf(fs, "if(msh_size <= MSH_HEADER_SIZE) {\n"); - indent(fs,2); - fprintf(fs, "//This is buggy, we can't always assume that\n"); - indent(fs,2); - fprintf(fs, "//obj == NULL <==> List is empty.\n"); - indent(fs,2); - fprintf(fs, "return;\n"); - indent(fs,1); - fprintf(fs, "} else {\n"); - indent(fs,2); - fprintf(fs, "this->%s = obj;\n", name); - - //vietha 2003.05.09 - indent(fs,2); - fprintf(fs, "this->%s_%s = (%s%s*)this->%s;\n", SHADOWED_LABEL, name, SHADOWED_LABEL, mtype, name); - - indent(fs,2); - fprintf(fs, "this->msh_isUnmarshalDone = true;\n"); - - for(i = 1; i <= numOffieldspecs; i++) { - // Add shallow copy, vietha - //for(i = 0; i <= numOffieldspecs; i++) { - indent(fs,2); - fprintf(fs, "unmarshal%d();\n", i); - } - indent(fs,1); - fprintf(fs, "}\n"); - fprintf(fs, "}\n\n"); - - //Now define marshal##n and unmarshal##n for each field of obj - for(i = 1; i <= numOffieldspecs; i++) { - //for(i = 0; i <= numOffieldspecs; i++) { - generate_marshalfunc(s, i, fs); - generate_unmarshalfunc(s, i, fs); - } - - //Done -} - - -//@param: sp is a spec. -//@param: num is the number (index) of the current fieldspec -//@param: fs is the FILE ptr -//This function creates two functions: marshal##n and unmarshal##n -//vietha 2003/04/25 -// num = 0 : marshaling the shallow-copy of the whole object - -void generate_marshalfunc(struct spec *sp, int num, FILE *fs) { - char *mtype = sp->mtype; - struct fieldspec *fsp; - - char *ftype; //field type - char *fname; //field name - struct gss *gss1; - char *getspec, *sizespec; - - char *msh_size = "msh_size"; - char *msh_buffer = "msh_buffer"; - char *msh_extent = "msh_extent"; - char *msh_cursor = "msh_cursor"; - /* vietha 2003.05.05 */ - char *msh_field_begin = "msh_field_begin"; - - char *currentSize = "msh_currentSize"; - - int isMultipleMarshal = 0; // Is this spec for marshaling multiples? - - //vietha 2003/04/25 - char *type = sp->fmls->type; - char *name = sp->fmls->name; - char type_no_star[128]; //type name without the *, used in "new type();" - strcpy(type_no_star, type); - type_no_star[strlen(type)-1] = '\0'; - - - if(num == 0){ /* for the shallow-copy of the whole object*/ - }else{ /* for data fields */ - int i = 1; - struct fieldspecs *cursor; - - if(sp->fmls != NULL && sp->fmls->next != NULL) - isMultipleMarshal = 1; - - //First go to the num fieldspec - for(cursor = sp->fsp; cursor != NULL; cursor = cursor->next) { - if(i == num) - break; - i++; - } - fsp = cursor->fsp; - - ftype = fsp->type; //field type - fname = fsp->name; //field name - gss1 = fsp->g; - } - - //Start definition of marshal##n - //fprintf(fs, "%s void %s::marshal%d() {\n", sp->template_decl, mtype, num); - fprintf(fs, "void marshal%d() {\n", num); - if(gss1 == NULL & (num!=0) ) { //Default case, call library functions - /* vietha 2003.05.05 */ - indent(fs, 1); - fprintf(fs, "//Default case, call library function\n"); - indent(fs, 1); - if(!isMultipleMarshal) { - fprintf(fs, "marshalPrimitive((void*)&(%s->%s), sizeof(%s));\n", - sp->fmls->name, fname, ftype); - } else { - fprintf(fs, "marshalPrimitive((void*)&%s, sizeof(%s));\n",fname, ftype); - } - } else { - if(num!=0){ - sizespec = gss1->sizesp; - getspec = gss1->getsp; - } - indent(fs, 1); - fprintf(fs, "//declare field_size to be the size of this field\n"); - indent(fs, 1); - fprintf(fs, "int %s = 0;\n", currentSize); - - indent(fs, 1); - fprintf(fs, "if (isUnmarshaling())\n"); - indent(fs, 2); - fprintf(fs, "throw \"Tried to marshal in obj marked isUnmarshaling == true\";\n\n"); - - if(num == 0){ //for marshaling shallow-copy - indent(fs, 1); - fprintf(fs, "%s = sizeof(%s); \n", currentSize,type_no_star); - }else{ - indent(fs, 1); - fprintf(fs, "//Copy the sizespec into %s here:\n", currentSize); - indent(fs, 1); - fprintf(fs, "%s\n\n", sizespec); - } - - indent(fs, 1); - fprintf(fs, "//Increase the size of buffer if needed\n"); - indent(fs, 1); - //fprintf(fs, "%s += %s + sizeof(int) + sizeof(int); // 4 bytes for the total size of field, 4 bytes for the number of elements in the array\n", msh_size, currentSize); - //indent(fs, 1); - //fprintf(fs, "EXTEND_BUFFER(%s);\n\n", msh_size); - fprintf(fs, "EXTEND_BUFFER(%s + sizeof(int) + sizeof(int)); // 4 bytes for the total size of field, 4 bytes for the number of elements in the array (in the case of array marshaling)\n", currentSize); - - indent(fs, 1); - //fprintf(fs, "//Put the size of the current field in the first sizeof(int) bytes\n"); - /* vietha 2003.05.05 */ - fprintf(fs, "//Mark the beginning position for this field, will write the total size of this field here later\n"); - indent(fs, 1); - //fprintf(fs, "*(int*)%s = %s;\n\n", msh_cursor, currentSize); - fprintf(fs, "%s = %s;\n\n", msh_field_begin, msh_cursor); - - indent(fs,1); - fprintf(fs, "//Advance cursor of distance = sizeof(int)\n"); - indent(fs, 1); - fprintf(fs, "%s += sizeof(int);\n\n", msh_cursor); - - if (num == 0){ - indent(fs, 1); - fprintf(fs, "memcpy(%s, %s, sizeof(%s));\n", msh_cursor, name, type_no_star); - }else{ - indent(fs, 1); - fprintf(fs, "//Now just copy \"get\" functions here\n"); - //the getspec is a (compound)stmt that copies the value of the current - //field into msh_cursor, which is of type "char *", therefore, user - //has essentially did the "marshaling" work for us, we just need to - //copy it - indent(fs, 1); - fprintf(fs, "%s\n", getspec); - } - - indent(fs,1); - fprintf(fs, "//Now advance the cursor\n"); - indent(fs,1); - fprintf(fs, "%s += %s;\n", msh_cursor, currentSize); - - /* vietha 2003.05.05 */ - indent(fs,1); - fprintf(fs, "//Now set the size of this field\n"); - indent(fs,1); - fprintf(fs,"int tmp; //use memcpy instead of *(int*)... =... to prevent bus error\n"); - indent(fs,1); - fprintf(fs, "tmp = (%s-%s) - sizeof(int);\n", msh_cursor, msh_field_begin); - indent(fs,1); - fprintf(fs, "memcpy(%s, &tmp, sizeof(int));\n\n", msh_field_begin); - - indent(fs,1); - fprintf(fs, "//Now set msh_size\n"); - indent(fs,1); - fprintf(fs, "%s = %s - %s;\n", msh_size, msh_cursor, msh_buffer); - indent(fs,1); - /*fprintf(fs, "tmp = %s - sizeof(int);\n", msh_size); - indent(fs,1); - fprintf(fs, "memcpy(%s, &tmp, sizeof(int));\n\n", msh_buffer);*/ - // vietha 2004.08.29 - fprintf(fs, "MSH_SET_TOTALSIZE(%s);", msh_size); - } - - indent(fs,1); - //fprintf(fs, "*(int*)msh_header = msh_typechoice;\n"); - fprintf(fs, "MSH_SET_TYPECHOICE(msh_typechoice);\n"); - //Finish up - fprintf(fs, "}\n\n"); -} - -//@param: sp is a spec. -//@param: num is the number (index) of the current fieldspec -//@param: fs is the FILE ptr -//This function creates two functions: marshal##n and unmarshal##n -//vietha 2003/04/25 -// num = 0 : unmarshaling the shallow-copy of the whole object - -void generate_unmarshalfunc(struct spec *sp, int num, FILE *fs) { - char *mtype = sp->mtype; - char *var_name = sp->fmls->name; - char *type = sp->fmls->type; - struct fieldspec *fsp; - char *ftype; //field type - char *fname; //field name - struct gss *gss1; - char *setspec, *sizespec; - - char *msh_size = "msh_size"; - char *msh_buffer = "msh_buffer"; - char *msh_extent = "msh_extent"; - char *msh_cursor = "msh_cursor"; - - char *currentSize = "msh_currentSize"; - - int isMultipleMarshal = 0; // Is this spec for marshaling multiples? - //vietha 2003/04/25 - char *name = sp->fmls->name; - char type_no_star[128]; //type name without the *, used in "new type();" - strcpy(type_no_star, type); - type_no_star[strlen(type)-1] = '\0'; - - if(num == 0){ //for the shallow-copy - }else{ - - int i = 1; - struct fieldspecs *cursor; - - if(sp->fmls != NULL && sp->fmls->next != NULL) - isMultipleMarshal = 1; - - //First go to the num fieldspec - for(cursor = sp->fsp; cursor != NULL; cursor = cursor->next) { - if(i == num) - break; - i++; - } - fsp = cursor->fsp; - - ftype = fsp->type; //field type - fname = fsp->name; //field name - gss1 = fsp->g; - } - - //Start definition of unmarshal##n - //fprintf(fs, "%s void %s::unmarshal%d() {\n", sp->template_decl, mtype, num); - fprintf(fs, "void unmarshal%d() {\n", num); - if(gss1 == NULL & (num!=0)) { //Default case, call library functions - // If ftype is one of the "primitive" types, - /*if(!strcmp(ftype, "int") || !strcmp(ftype, "double")) { - indent(fs, 1); - fprintf(fs, "//Default case, call library function\n"); - indent(fs, 1); - if(!isMultipleMarshal) { - fprintf(fs, "%s->%s = %sAs%s();\n", - sp->fmls->name, fname, "unmarshal", ftype); - } else { - fprintf(fs, "%s->%s = %sAs%s();\n", - "this", fname, "unmarshal", ftype); - } - }*/ - /* vietha 2003.05.05 */ - indent(fs, 1); - fprintf(fs, "//Default case, call library function\n"); - indent(fs, 1); - if(!isMultipleMarshal) { - fprintf(fs, "unmarshalPrimitive((void*)&(%s->%s), sizeof(%s));\n", - sp->fmls->name, fname, ftype); - } else { - fprintf(fs, "unmarshalPrimitive((void*)&%s, sizeof(%s));\n",fname, ftype); - } - } else { - if(num!=0){ - sizespec = gss1->sizesp; - setspec = gss1->setsp; - } - indent(fs, 1); - fprintf(fs, "//declare currentSize to be the size of this field\n"); - indent(fs, 1); - fprintf(fs, "int %s = 0;\n", currentSize); - - indent(fs, 1); - fprintf(fs, "//copy the size of the current field into currentSize\n"); - indent(fs, 1); - //fprintf(fs, "%s = *(int*)%s;\n", currentSize, msh_cursor); - fprintf(fs, "memcpy(&%s, %s, sizeof(int));\n", currentSize, msh_cursor); - - indent(fs, 1); - fprintf(fs, "%s += sizeof(int);\n", msh_cursor); - - if(num==0){ //unmarshaling the shallow-copy - indent(fs, 1); - fprintf(fs, "memcpy(%s, %s, sizeof(%s));\n", name, msh_cursor, type_no_star); - }else{ - indent(fs, 1); - fprintf(fs, "//Now copy the setspec here\n"); - indent(fs, 1); - fprintf(fs, "%s\n", setspec); - } - - indent(fs, 1); - fprintf(fs, "%s += %s;\n", - msh_cursor, currentSize); - //indent(fs, 1); - //fprintf(fs, "%s = %s - %s;\n", msh_size, msh_cursor, msh_buffer); - - } - //Finish up - fprintf(fs, "}\n\n"); - -} - -void generate_files(struct mast *m, FILE* fs) { - char *macros = m->macros; - //char file_name[50]; - char *mtype = m->sp->sp->mtype; - struct specs *cur1; - //FILE *fs; - //vietha 2003.4.29 - char mtype_without_template[50]; - memset(mtype_without_template, 0, sizeof(mtype_without_template)); - typename_without_template(mtype,mtype_without_template); - - //Create the .h file name -// strcpy(file_name, mtype_without_template); -// strcat(file_name, ".h"); - -// fs = fopen(file_name, "w+"); -// if(fs == NULL) { -// perror("Can't open file"); -// exit(-1); -// } - - fprintf(fs, "// This file was generated automatically by marshalgen.\n" - "\n"); - - //macros - fprintf(fs, "#ifndef %s_H\n", mtype_without_template); - fprintf(fs, "#define %s_H\n\n", mtype_without_template); - - fprintf(fs, "%s\n", macros); - - //include .h file - fprintf(fs, "#include \n"); - fprintf(fs, "#include \n"); - //include files - fprintf(fs, "#include \"MarshaledObj.h\"\n"); - - /* generate the "Shadowed" class to access private data fields - and write it to the .h file */ - for(cur1 = m->sp; cur1 != NULL; cur1 = cur1->next) { - //For a spec, if it has only one "type ID" pair - if(cur1->sp->fmls != NULL && cur1->sp->fmls->next == NULL) - generate_shadowClass(cur1->sp, fs); - } - - // in case of multiple classes, go through each class - for(cur1 = m->sp; cur1 != NULL; cur1 = cur1->next) { - /* generate class decs for all specs - and write them to the .h file */ - generate_hfile(cur1->sp, fs); - - fprintf(fs, "\n\n// Function implementations\n\n"); - /* generate implemented function decs for all specs - and write them to the .h file, - instead of writing to the ".cpp" file as before */ - generate_cfile(cur1->sp, fs); - - //Finish up - fprintf(fs, "};\n"); - } - - - fprintf(fs, "#endif\n\n"); - //Now free m - Mast_free(m); -} - - -void indent(FILE *f, int n) { - int i = 0; - int tabstop = 4; - - for(i = 0; i < n * tabstop; i++) { - fprintf(f, " "); - } - -} - -//vietha 2003.04.29 -/* remove the "" from the class name "SomeThing" */ -void typename_without_template(char* source, char* output){ - char *template_begin,*template_end; - int len; - - template_begin= strchr(source,'<'); - if(!template_begin) {strcpy(output,source);return;} - template_end = strrchr(template_begin,'>'); - if(!template_end) {strcpy(output,source);return;} - template_end++; //points the part after '' - - len = template_begin - source; //number of chars before '<' - strncpy(output, source, len); - strcat(output, template_end); -} diff --git a/marshalgen-1.0/Phase2/mast.h b/marshalgen-1.0/Phase2/mast.h deleted file mode 100644 index edd6a51c..00000000 --- a/marshalgen-1.0/Phase2/mast.h +++ /dev/null @@ -1,95 +0,0 @@ -#include -#include - -struct mast { - char *macros; - struct specs *sp; -}; - -struct spec { - char *mtype; - struct formals *fmls; - struct fieldspecs *fsp; - //vietha 2003.4.29 - char* template_decl; - char* parent_classes; - //vietha 2004.08.29 - char* constructor_call; -}; - -struct formals { - char *type; - char *name; - struct formals *next; -}; - -struct specs { - struct spec *sp; - struct specs *next; -}; - -struct fieldspec { - char *type; - char *name; - struct gss *g; -}; - -struct gss { - char *getsp; - char *setsp; - char *sizesp; -}; - -struct fieldspecs { - struct fieldspec *fsp; - struct fieldspecs *next; -}; - -int num_specs(struct mast *m); -int num_fieldspecs(struct fieldspecs *f); - -char *strconcat(int n, ...); - -struct mast *Mast_init(char *m, struct specs *s); -//struct spec *Spec_init(char *mt, struct formals *fmls, struct fieldspecs *f); -struct spec *Spec_init(char* template_decl, char *mt, struct formals *fmls, char* parent_classes, struct fieldspecs *f, char *constructor); -struct specs *Specs_init(struct spec *sp, struct specs *nt); -struct fieldspec *Fieldspec_init(char *t, char *nm, struct gss *g); -struct gss *Gss_init(char *g, char *s, char *sz); -struct fieldspecs *Fieldspecs_init(struct fieldspec *f, struct fieldspecs *nt); -struct formals *Formals_init(char *type, char *name, - struct formals *fmlsrest); - -void Mast_free(struct mast *m); -void Spec_free(struct spec *s); -void Specs_free(struct specs *s); -void Fieldspec_free(struct fieldspec *fsp); -void Fieldspecs_free(struct fieldspecs *fsps); -void Gss_free(struct gss *g); -void Formals_free(struct formals *f); - -void mast_print(struct mast *m); -void specs_print(struct specs *s); -void spec_print(struct spec *s); -void formals_print(struct formals *fmls); -void formalsrest_print(struct formals *fmls); -void fieldspecs_print(struct fieldspecs *f); -void fieldspec_print(struct fieldspec *f); -void gss_print(struct gss* g); - -//void generate_hfile_single(struct spec *s, FILE *fs); -//void generate_hfile_multiple(struct spec *s, FILE *fs); -//void generate_cfile_single(struct spec *s, FILE *fs); -//void generate_cfile_multiple(struct spec *s, FILE *fs); - -void generate_hfile(struct spec *s, FILE *fs); -void generate_cfile(struct spec *s, FILE *fs); -void generate_marshalfunc(struct spec *sp, int num, FILE *fs); -void generate_unmarshalfunc(struct spec *sp, int num, FILE *fs); -void generate_files(struct mast *m, FILE *fs); -void indent(FILE *f, int n); - -//vietha 2003.04.29 -void typename_without_template(char* source, char* output); -//vietha 2003.05.09 -void generate_shadowClass(struct spec *s, FILE *fs); diff --git a/marshalgen-1.0/README.txt b/marshalgen-1.0/README.txt deleted file mode 100644 index d08edf16..00000000 --- a/marshalgen-1.0/README.txt +++ /dev/null @@ -1,36 +0,0 @@ -General Information -=================== - -This is version 1.0 of Marshalgen, last updated in November, 2005. -Marshalgen stands for MARSHALing code GENerator. It is a package that -allows one to generate marshaling code for C++ structs or classes -based on annotations of the existing source code. - - - -Installation -============ -The installation can be done by typing the command - make - -The executable, ./marshalgen, is then available in the current directory. -Usage: ./marshalgen FILE.h - where FILE.h is an include file with Marshalgen annotation. - FILE.h can be in any directory. - -This creates MarshaledFILE.h in the same directory as FILE.h, and it -does: #include - - - -Manual -============ - -See the file 'MANUAL.txt' - - -Contact -============ - For any bug report, suggestion, or question, feel free to contact us. -Viet Ha Nguyen (vietha@ccs.neu.edu) -Gene Cooperman (gene@ccs.neu.edu) diff --git a/marshalgen-1.0/marshalgen b/marshalgen-1.0/marshalgen deleted file mode 100755 index 14178ae4..00000000 --- a/marshalgen-1.0/marshalgen +++ /dev/null @@ -1,70 +0,0 @@ -#!/bin/bash - -if [ $# -lt 1 ]; -then -echo "Usage: $0 ..." -exit 1 -fi - -while [ $# -ge 1 ]; do - - ANN_FILE=$1 - #echo "Annotated input file=$ANN_FILE" - - if [ ! -e $ANN_FILE ]; then - echo "Could not find file $ANN_FILE." - exit 1 - fi - - MARSHALGEN_DIR=`dirname $0` - TARGET_DIR=`dirname $ANN_FILE` - - # get the prefix of the input file - NAME_PREFIX=`basename $ANN_FILE | sed "s/\..*//"` - - # and append ".msh" to it - MSH_FILE="$TARGET_DIR/$NAME_PREFIX.msh" - - - ########### Phase 2 ############### - - echo "" - echo "Phase 1: Reading $ANN_FILE, generating temporary $MSH_FILE file ..." - echo "" - echo "$MARSHALGEN_DIR/Phase1/mgen.pl $ANN_FILE" - $MARSHALGEN_DIR/Phase1/mgen.pl $ANN_FILE - - if [ $? -ne "0" ]; then - echo "" - echo "Phase 1 failed. Stopped." - exit 1 - fi - - - ########### Phase 2 ############### - - OUTPUT_FILE="$TARGET_DIR/Marshaled$NAME_PREFIX.h" - echo "" - echo "Phase 2: Reading $MSH_FILE, generating marshaling code" \ - " to $OUTPUT_FILE" - echo "" - - if [ ! -e $MSH_FILE ]; then - echo "Could not find file $MSH_FILE." - exit 1 - fi - - echo "$MARSHALGEN_DIR/Phase2/marshal $MSH_FILE $OUTPUT_FILE" - $MARSHALGEN_DIR/Phase2/marshal $MSH_FILE $OUTPUT_FILE - - if [ $? -ne "0" ]; then - echo "" - echo "Phase 2 failed. Stopped." - exit 1 - else - echo "" - echo "Marshalgen executed successfully." - fi - - shift -done diff --git a/topc-2.5.2/CHANGES b/topc-2.5.2/CHANGES deleted file mode 100644 index 00ed151f..00000000 --- a/topc-2.5.2/CHANGES +++ /dev/null @@ -1,54 +0,0 @@ -Version 2.5: - -Fixing various bugs -- especially some that affect the use of TOP-C - with around 100 slaves or more; or the use with other MPIs besides - the built-in MPI subsect, mpinu. - -In TOP-C 2.5, a major change was to now handle dead sockets, and ensure -that the current task on that slave was sent to a new slave. - -TOP-C 2.5 has some bug fixes that could affect distributed memory -operation on clusters with on the order of 100 or more slave processes. - -The environment variable TOPC_OPTS and the initialization file ~/.topcrc -are also now available (format: --TOPC-xxx ...). - -TOP-C 2.4 and earlier used rsh by default (instead of ssh) to create -the remote slaves. ssh is now the default. TOP-C 2.4 tested the -environment variable RSH, and if it was set, TOP-C would use the -value of RSH instead of "rsh". -Version 2.5 now tests the environment variable SSH, and if it is set, -TOP-C uses the value of SSH instead of "ssh". -If a site continues to use "rsh", one can: setenv SSH "rsh" - or for sh/bash: SSH=rsh; export SSH - -All of the example programs (examples subdirectory) now work both -as C and C++ programs. They can be compiled with either topcc or topc++ . - -TOP-C now handles aggregated task inputs. This is important for -finer grain parallelism with shorter messages, when the latency -of sending a network message is comparable or greater than the task execution -time. To aggregate 5 tasks at a time, try it with: --TOPC-task-aggregation=5 -This feature is currently -restricted to trivial parallelism (no TOP-C action except NO_ACTION). - -See the utils directory for code that will be polished and documented - in a later version of TOP-C: - a broadcast utility inside TOP-C: - ssh-killall: EXAMPLE: ssh-killall a.out (Use procgroup of current dir - to kill all a.out processes on slave processors) - a C++ interface for TOP-C: ---TOPC-stats command line option added to display statistics (run time, - CPU information, etc.) at beginning and end of run. ---TOPC-verbose no longer displays stats at end, but --TOPC-verbose - is now enabled by default. - -=== -COMING (not yet done): - See utils directory for features that are planned for integration -into TOP-C. - -Should guarantee continuation of TOP-C even in unlikely event -that a slave dies at the end, while waiting for TOP-C to complete. - -Should provide simple checkpointing. diff --git a/topc-2.5.2/COPYING b/topc-2.5.2/COPYING deleted file mode 100644 index 2bb5b6e5..00000000 --- a/topc-2.5.2/COPYING +++ /dev/null @@ -1,502 +0,0 @@ - GNU LESSER GENERAL PUBLIC LICENSE - Version 2.1, February 1999 - - Copyright (C) 1991, 1999 Free Software Foundation, Inc. - 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - -[This is the first released version of the Lesser GPL. It also counts - as the successor of the GNU Library Public License, version 2, hence - the version number 2.1.] - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -Licenses are intended to guarantee your freedom to share and change -free software--to make sure the software is free for all its users. - - This license, the Lesser General Public License, applies to some -specially designated software packages--typically libraries--of the -Free Software Foundation and other authors who decide to use it. You -can use it too, but we suggest you first think carefully about whether -this license or the ordinary General Public License is the better -strategy to use in any particular case, based on the explanations below. - - When we speak of free software, we are referring to freedom of use, -not price. Our General Public Licenses are designed to make sure that -you have the freedom to distribute copies of free software (and charge -for this service if you wish); that you receive source code or can get -it if you want it; that you can change the software and use pieces of -it in new free programs; and that you are informed that you can do -these things. - - To protect your rights, we need to make restrictions that forbid -distributors to deny you these rights or to ask you to surrender these -rights. These restrictions translate to certain responsibilities for -you if you distribute copies of the library or if you modify it. - - For example, if you distribute copies of the library, whether gratis -or for a fee, you must give the recipients all the rights that we gave -you. You must make sure that they, too, receive or can get the source -code. If you link other code with the library, you must provide -complete object files to the recipients, so that they can relink them -with the library after making changes to the library and recompiling -it. And you must show them these terms so they know their rights. - - We protect your rights with a two-step method: (1) we copyright the -library, and (2) we offer you this license, which gives you legal -permission to copy, distribute and/or modify the library. - - To protect each distributor, we want to make it very clear that -there is no warranty for the free library. Also, if the library is -modified by someone else and passed on, the recipients should know -that what they have is not the original version, so that the original -author's reputation will not be affected by problems that might be -introduced by others. - - Finally, software patents pose a constant threat to the existence of -any free program. We wish to make sure that a company cannot -effectively restrict the users of a free program by obtaining a -restrictive license from a patent holder. Therefore, we insist that -any patent license obtained for a version of the library must be -consistent with the full freedom of use specified in this license. - - Most GNU software, including some libraries, is covered by the -ordinary GNU General Public License. This license, the GNU Lesser -General Public License, applies to certain designated libraries, and -is quite different from the ordinary General Public License. We use -this license for certain libraries in order to permit linking those -libraries into non-free programs. - - When a program is linked with a library, whether statically or using -a shared library, the combination of the two is legally speaking a -combined work, a derivative of the original library. The ordinary -General Public License therefore permits such linking only if the -entire combination fits its criteria of freedom. The Lesser General -Public License permits more lax criteria for linking other code with -the library. - - We call this license the "Lesser" General Public License because it -does Less to protect the user's freedom than the ordinary General -Public License. It also provides other free software developers Less -of an advantage over competing non-free programs. These disadvantages -are the reason we use the ordinary General Public License for many -libraries. However, the Lesser license provides advantages in certain -special circumstances. - - For example, on rare occasions, there may be a special need to -encourage the widest possible use of a certain library, so that it becomes -a de-facto standard. To achieve this, non-free programs must be -allowed to use the library. A more frequent case is that a free -library does the same job as widely used non-free libraries. In this -case, there is little to gain by limiting the free library to free -software only, so we use the Lesser General Public License. - - In other cases, permission to use a particular library in non-free -programs enables a greater number of people to use a large body of -free software. For example, permission to use the GNU C Library in -non-free programs enables many more people to use the whole GNU -operating system, as well as its variant, the GNU/Linux operating -system. - - Although the Lesser General Public License is Less protective of the -users' freedom, it does ensure that the user of a program that is -linked with the Library has the freedom and the wherewithal to run -that program using a modified version of the Library. - - The precise terms and conditions for copying, distribution and -modification follow. Pay close attention to the difference between a -"work based on the library" and a "work that uses the library". The -former contains code derived from the library, whereas the latter must -be combined with the library in order to run. - - GNU LESSER GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License Agreement applies to any software library or other -program which contains a notice placed by the copyright holder or -other authorized party saying it may be distributed under the terms of -this Lesser General Public License (also called "this License"). -Each licensee is addressed as "you". - - A "library" means a collection of software functions and/or data -prepared so as to be conveniently linked with application programs -(which use some of those functions and data) to form executables. - - The "Library", below, refers to any such software library or work -which has been distributed under these terms. A "work based on the -Library" means either the Library or any derivative work under -copyright law: that is to say, a work containing the Library or a -portion of it, either verbatim or with modifications and/or translated -straightforwardly into another language. (Hereinafter, translation is -included without limitation in the term "modification".) - - "Source code" for a work means the preferred form of the work for -making modifications to it. For a library, complete source code means -all the source code for all modules it contains, plus any associated -interface definition files, plus the scripts used to control compilation -and installation of the library. - - Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running a program using the Library is not restricted, and output from -such a program is covered only if its contents constitute a work based -on the Library (independent of the use of the Library in a tool for -writing it). Whether that is true depends on what the Library does -and what the program that uses the Library does. - - 1. You may copy and distribute verbatim copies of the Library's -complete source code as you receive it, in any medium, provided that -you conspicuously and appropriately publish on each copy an -appropriate copyright notice and disclaimer of warranty; keep intact -all the notices that refer to this License and to the absence of any -warranty; and distribute a copy of this License along with the -Library. - - You may charge a fee for the physical act of transferring a copy, -and you may at your option offer warranty protection in exchange for a -fee. - - 2. You may modify your copy or copies of the Library or any portion -of it, thus forming a work based on the Library, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) The modified work must itself be a software library. - - b) You must cause the files modified to carry prominent notices - stating that you changed the files and the date of any change. - - c) You must cause the whole of the work to be licensed at no - charge to all third parties under the terms of this License. - - d) If a facility in the modified Library refers to a function or a - table of data to be supplied by an application program that uses - the facility, other than as an argument passed when the facility - is invoked, then you must make a good faith effort to ensure that, - in the event an application does not supply such function or - table, the facility still operates, and performs whatever part of - its purpose remains meaningful. - - (For example, a function in a library to compute square roots has - a purpose that is entirely well-defined independent of the - application. Therefore, Subsection 2d requires that any - application-supplied function or table used by this function must - be optional: if the application does not supply it, the square - root function must still compute square roots.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Library, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Library, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote -it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Library. - -In addition, mere aggregation of another work not based on the Library -with the Library (or with a work based on the Library) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may opt to apply the terms of the ordinary GNU General Public -License instead of this License to a given copy of the Library. To do -this, you must alter all the notices that refer to this License, so -that they refer to the ordinary GNU General Public License, version 2, -instead of to this License. (If a newer version than version 2 of the -ordinary GNU General Public License has appeared, then you can specify -that version instead if you wish.) Do not make any other change in -these notices. - - Once this change is made in a given copy, it is irreversible for -that copy, so the ordinary GNU General Public License applies to all -subsequent copies and derivative works made from that copy. - - This option is useful when you wish to copy part of the code of -the Library into a program that is not a library. - - 4. You may copy and distribute the Library (or a portion or -derivative of it, under Section 2) in object code or executable form -under the terms of Sections 1 and 2 above provided that you accompany -it with the complete corresponding machine-readable source code, which -must be distributed under the terms of Sections 1 and 2 above on a -medium customarily used for software interchange. - - If distribution of object code is made by offering access to copy -from a designated place, then offering equivalent access to copy the -source code from the same place satisfies the requirement to -distribute the source code, even though third parties are not -compelled to copy the source along with the object code. - - 5. A program that contains no derivative of any portion of the -Library, but is designed to work with the Library by being compiled or -linked with it, is called a "work that uses the Library". Such a -work, in isolation, is not a derivative work of the Library, and -therefore falls outside the scope of this License. - - However, linking a "work that uses the Library" with the Library -creates an executable that is a derivative of the Library (because it -contains portions of the Library), rather than a "work that uses the -library". The executable is therefore covered by this License. -Section 6 states terms for distribution of such executables. - - When a "work that uses the Library" uses material from a header file -that is part of the Library, the object code for the work may be a -derivative work of the Library even though the source code is not. -Whether this is true is especially significant if the work can be -linked without the Library, or if the work is itself a library. The -threshold for this to be true is not precisely defined by law. - - If such an object file uses only numerical parameters, data -structure layouts and accessors, and small macros and small inline -functions (ten lines or less in length), then the use of the object -file is unrestricted, regardless of whether it is legally a derivative -work. (Executables containing this object code plus portions of the -Library will still fall under Section 6.) - - Otherwise, if the work is a derivative of the Library, you may -distribute the object code for the work under the terms of Section 6. -Any executables containing that work also fall under Section 6, -whether or not they are linked directly with the Library itself. - - 6. As an exception to the Sections above, you may also combine or -link a "work that uses the Library" with the Library to produce a -work containing portions of the Library, and distribute that work -under terms of your choice, provided that the terms permit -modification of the work for the customer's own use and reverse -engineering for debugging such modifications. - - You must give prominent notice with each copy of the work that the -Library is used in it and that the Library and its use are covered by -this License. You must supply a copy of this License. If the work -during execution displays copyright notices, you must include the -copyright notice for the Library among them, as well as a reference -directing the user to the copy of this License. Also, you must do one -of these things: - - a) Accompany the work with the complete corresponding - machine-readable source code for the Library including whatever - changes were used in the work (which must be distributed under - Sections 1 and 2 above); and, if the work is an executable linked - with the Library, with the complete machine-readable "work that - uses the Library", as object code and/or source code, so that the - user can modify the Library and then relink to produce a modified - executable containing the modified Library. (It is understood - that the user who changes the contents of definitions files in the - Library will not necessarily be able to recompile the application - to use the modified definitions.) - - b) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (1) uses at run time a - copy of the library already present on the user's computer system, - rather than copying library functions into the executable, and (2) - will operate properly with a modified version of the library, if - the user installs one, as long as the modified version is - interface-compatible with the version that the work was made with. - - c) Accompany the work with a written offer, valid for at - least three years, to give the same user the materials - specified in Subsection 6a, above, for a charge no more - than the cost of performing this distribution. - - d) If distribution of the work is made by offering access to copy - from a designated place, offer equivalent access to copy the above - specified materials from the same place. - - e) Verify that the user has already received a copy of these - materials or that you have already sent this user a copy. - - For an executable, the required form of the "work that uses the -Library" must include any data and utility programs needed for -reproducing the executable from it. However, as a special exception, -the materials to be distributed need not include anything that is -normally distributed (in either source or binary form) with the major -components (compiler, kernel, and so on) of the operating system on -which the executable runs, unless that component itself accompanies -the executable. - - It may happen that this requirement contradicts the license -restrictions of other proprietary libraries that do not normally -accompany the operating system. Such a contradiction means you cannot -use both them and the Library together in an executable that you -distribute. - - 7. You may place library facilities that are a work based on the -Library side-by-side in a single library together with other library -facilities not covered by this License, and distribute such a combined -library, provided that the separate distribution of the work based on -the Library and of the other library facilities is otherwise -permitted, and provided that you do these two things: - - a) Accompany the combined library with a copy of the same work - based on the Library, uncombined with any other library - facilities. This must be distributed under the terms of the - Sections above. - - b) Give prominent notice with the combined library of the fact - that part of it is a work based on the Library, and explaining - where to find the accompanying uncombined form of the same work. - - 8. You may not copy, modify, sublicense, link with, or distribute -the Library except as expressly provided under this License. Any -attempt otherwise to copy, modify, sublicense, link with, or -distribute the Library is void, and will automatically terminate your -rights under this License. However, parties who have received copies, -or rights, from you under this License will not have their licenses -terminated so long as such parties remain in full compliance. - - 9. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Library or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Library (or any work based on the -Library), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Library or works based on it. - - 10. Each time you redistribute the Library (or any work based on the -Library), the recipient automatically receives a license from the -original licensor to copy, distribute, link with or modify the Library -subject to these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties with -this License. - - 11. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Library at all. For example, if a patent -license would not permit royalty-free redistribution of the Library by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Library. - -If any portion of this section is held invalid or unenforceable under any -particular circumstance, the balance of the section is intended to apply, -and the section as a whole is intended to apply in other circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 12. If the distribution and/or use of the Library is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Library under this License may add -an explicit geographical distribution limitation excluding those countries, -so that distribution is permitted only in or among countries not thus -excluded. In such case, this License incorporates the limitation as if -written in the body of this License. - - 13. The Free Software Foundation may publish revised and/or new -versions of the Lesser General Public License from time to time. -Such new versions will be similar in spirit to the present version, -but may differ in detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Library -specifies a version number of this License which applies to it and -"any later version", you have the option of following the terms and -conditions either of that version or of any later version published by -the Free Software Foundation. If the Library does not specify a -license version number, you may choose any version ever published by -the Free Software Foundation. - - 14. If you wish to incorporate parts of the Library into other free -programs whose distribution conditions are incompatible with these, -write to the author to ask for permission. For software which is -copyrighted by the Free Software Foundation, write to the Free -Software Foundation; we sometimes make exceptions for this. Our -decision will be guided by the two goals of preserving the free status -of all derivatives of our free software and of promoting the sharing -and reuse of software generally. - - NO WARRANTY - - 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO -WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. -EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR -OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY -KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE -LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME -THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN -WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY -AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU -FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR -CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE -LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING -RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A -FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF -SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH -DAMAGES. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Libraries - - If you develop a new library, and you want it to be of the greatest -possible use to the public, we recommend making it free software that -everyone can redistribute and change. You can do so by permitting -redistribution under these terms (or, alternatively, under the terms of the -ordinary General Public License). - - To apply these terms, attach the following notices to the library. It is -safest to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least the -"copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - -Also add information on how to contact you by electronic and paper mail. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the library, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the - library `Frob' (a library for tweaking knobs) written by James Random Hacker. - - , 1 April 1990 - Ty Coon, President of Vice - -That's all there is to it! diff --git a/topc-2.5.2/FEATURES b/topc-2.5.2/FEATURES deleted file mode 100644 index 2e5106a2..00000000 --- a/topc-2.5.2/FEATURES +++ /dev/null @@ -1,29 +0,0 @@ -THIS IS STILL A DOCUMENT IN PROGRESS. - -Emulation of parallel computation in a sequential process for ease of - debugging: by a single command line switch (`topcc --seq'). - -Common API (and ABI) for distributed memory (sockets), shared memory (posix - threads) and sequential computation. - -TOP-C continues and resubmits task to another slave if a slave dies. -This does not kill the computation. - -A subset of MPI (mpinu) is provided for use of TOP-C with sockets, and - TOP-C retains the ability to use other MPI implementations. - -Extensibility: ease of writing new communication layer based on - existing models: src/comm-*.c - -Ease of checkpointing, since the latest version of all state (including - shared data) is always up to date on master process. - -Receive thread on slave in mpi mode (to allow overlap of computation -and communication). This currently is used only on the slave. -This overlap occurs during UPDATE. - (Some dialects of MPI already do this, but not MPINU (built into TOP-C).) - -Many usability features: command line option, topcc (wrapper for native - compiler), topc-config, ... - -... diff --git a/topc-2.5.2/INSTALL b/topc-2.5.2/INSTALL deleted file mode 100644 index 6e55276e..00000000 --- a/topc-2.5.2/INSTALL +++ /dev/null @@ -1,76 +0,0 @@ -The installation instructions follow the common model: - ./configure - make - make install -The rest of the instructions are modified from those for the GTK+ package. - -Simple install procedure -======================== - - % gzip -cd topc.tar.gz | tar xvf - # unpack the sources - % cd topc # change to the toplevel directory - % ./configure # run the `configure' script - % make # build TOP-C - [ Become root if necessary ] - % make install # install TOP-C - -The Nitty-Gritty -================ - -The 'configure' script can be given a number of options to enable -and disable various features. For a complete list, type: - - ./configure --help - few of the more important ones: - -* --prefix=PREFIX install architecture-independent files in PREFIX - [ Defaults to /usr/local ] - -* --exec-prefix=EPREFIX install architecture-dependent files in EPREFIX - [ Defaults to the value given to --prefix ] - - -Options can be given to the compiler and linker by setting -environment variables before running configure. A few of the more -important ones: - - CC : The C compiler to use - CXX : The C++ compiler to use (needed only if application uses C++) - CFLAGS : C compiler flags - -The most important use of this is to set the -optimization/debugging flags. For instance, to compile with no -debugging information at all, run configure as: - - CFLAGS=-O2 ./configure # Bourne compatible shells (sh/bash/zsh) - -or, - - setenv CFLAGS -O2 ; ./configure # csh and variants - -Installation directories -======================== - -The location of the installed files is determined by the --prefix -and --exec-prefix options given to configure. There are also more -detailed flags to control individual directories. However, the -use of these flags is not tested. - -Two shell scripts, topcc and topc++, are created during the configure -process, and installed in the bin/ directory ($exec_prefix/bin). -These can be used as replacements for the configured values of CC and CXX -(where the values were set by ./configure) in compiling and linking -TOP-C applications. - -Additionally, a shell script topc-config is created during the configure -process, and installed in the bin/ directory ($exec_prefix/bin). This -provides an alternate way for to determine the location of TOP-C libraries, -include files, and definitions that are needed when building TOP-C -applications. - -If you move TOP-C after installation, it will be necessary to edit -topc, topc++ and topc-config. The three scripts also contain -a --help command line parameter, which provides a brief synopsis -of their usage. - -For complete details, see the file docs/gtk-config.txt diff --git a/topc-2.5.2/Makefile.in b/topc-2.5.2/Makefile.in deleted file mode 100644 index 4afa8c49..00000000 --- a/topc-2.5.2/Makefile.in +++ /dev/null @@ -1,92 +0,0 @@ -# @configure_input@ -# cd ROOT_DIR; autoscan; mv autoconf.scan configure.in; autoconf; ./configure - -# For debugging with gcc/gdb, re-make after: env CFLAGS="-g3 -O0" ./configure -# (defines macros for gdb) -# For testing portability, re-make after: env "CFLAGS=-Wall -W" ./configure -# For alternate C compiler, re-make after: -# env CC=cc ./configure --cache-file=/dev/null - -prefix=@prefix@ -exec_prefix=@exec_prefix@ - -@SET_MAKE@ - -default: source - -source: - ( cd src; ${MAKE} ) - -examples: source - ( cd bin; ${MAKE} all ) - -check: source - @ echo "*** WARNING: Some of these tests may take a little while" - ( cd bin; ${MAKE} checkall | grep TEST ) - -install: source - @test -d @bindir@ || mkdir -p @bindir@ - cp bin/topc-config @bindir@/ - cp bin/topcc @bindir@/ - cp bin/topc++ @bindir@/ - @test -d @includedir@ || mkdir -p @includedir@ - cp include/*.h @includedir@/ - @test -d @libdir@ || mkdir -p @libdir@ - cp lib/lib*.a @libdir@ - @test -d @mandir@ || mkdir -p @mandir@ - @test -d @mandir@/man1 || mkdir -p @mandir@/man1 - cp doc/topcc.1 @mandir@/man1/ - cp doc/topc++.1 @mandir@/man1/ - @test -d @infodir@ || mkdir -p @infodir@ - cp doc/topc.info* @infodir@/ - test @infodir@ = /usr/local/info && \ - install-info --section Development Development @infodir@/topc.info - -uninstall: - rm -f @bindir@/topc-config - rm -f @bindir@/topcc - rm -f @bindir@/topc++ - rm -f @includedir@/topc.h - rm -f @includedir@/mpinu.h - rm -f @libdir@/libtopc*.a - rm -f @libdir@/libmpinu.a - rm -f @mandir@/man1/topcc.1 - rm -f @mandir@/man1/topc++.1 - rm -f @infodir@/topc.info* - install-info --remove topc - -clean: - ( cd src; ${MAKE} clean ) - ( cd bin; ${MAKE} clean ) - ( cd doc; ${MAKE} clean ) - ( cd lib; rm -f lib* ) - ( cd include; rm -f *.h ) - -distclean: clean - ( cd src; ${MAKE} distclean ) - ( cd bin; ${MAKE} distclean ) - ( cd doc; ${MAKE} distclean ) - rm config.* - rm -f README Makefile \ - bin/Makefile bin/topcc bin/topc++ bin/topc-config \ - doc/Makefile doc/topcc.1 doc/topc-version.texi \ - src/Makefile src/mpinu/Makefile src/mpinu/procgroup \ - utils/ssh-procgroup utils/ssh-killall - rm -rf autom4te.cache - -maintainer-clean: - ( cd doc; ${MAKE} maintainer-clean ) - ${MAKE} distclean - -# If not in ./topc, do "mv ...; tar ...; mv ..." -dist: distclean - name=`basename $$PWD`; \ - version=@TOPC_VERSION@; \ - if [ "$$name" != "topc-$$version" ] ; then \ - echo "main dir, $$name, not same as topc-$$version" ; \ - exit 1; \ - fi; \ - ( cd @PWD@/..; \ - tar cvf topc-$$version.tar ./topc-$$version; \ - gzip topc-$$version.tar; ); \ - ls -l ../topc-$$version.tar.gz diff --git a/topc-2.5.2/QUICK-START b/topc-2.5.2/QUICK-START deleted file mode 100644 index 15de979b..00000000 --- a/topc-2.5.2/QUICK-START +++ /dev/null @@ -1,134 +0,0 @@ - Quick Start: Installation and Test Run - - "Difficulty?" exclaimed Ford. "Difficulty? What - do you mean difficulty? [The wheel is] the single - simplest machine in the universe!" ... - "All right, Mr. Wiseguy," she said, "you're so - clever, you tell us what color it should be." - from "The Restaurant at the End of the Universe" - by Douglas Adams - - - This is version 2.5.2 of Task Oriented Parallel C/C++ (`TOP-C'). - See http://www.ccs.neu.edu/home/gene/topc.html for general - information on obtaining source, overview slides of `TOP-C', - previous `TOP-C' applications, etc. - Gene Cooperman - gene@ccs.neu.edu - - It has been tested and works on several workstation - architectures. It provides task-oriented parallelism to the end user. - The same application source code (or object code) can be executed (or - linked) with any of the following communication libraries using the - topcc command (a substitute for cc or gcc): - 1. a distributed memory library using MPI (MPI subset, mpinu, - included in distribution); or - 2. a shared memory library using threads; or - 3. a single-process sequential library (useful for development and - debugging). - - The `TOP-C' model has been successfully used for some very large - computations. - (See http://www.ccs.neu.edu/home/gene/par-tools.html - and http://www.ccs.neu.edu/home/gene/pargeant4.html) - - To unpack: - - - gunzip topc.tar.gz - tar xvf topc.tar - cd topc - ./configure - make - - If you are impatient, you can immediately do: - - - cd bin - make parfactor - > FACTORING 123456789 - > ./a.out 123456789 - > master -> 1: 2 - > master -> 2: 1002 - > 1 -> master: TRUE - > UPDATE: TRUE - > ... - > 3 3 3607 3803 - and see a demonstration for factoring numbers by a Euclidean sieve. - Then try: ./a.out YOUR_NUMBER - Read bin/Makefile for an example of compiling a `TOP-C' program. - - If you want to use more or different slave processes, modify - `bin/procgroup'. Then, again: - - - cd bin - ./a.out YOUR_NUMBER - - And compare with your results using a single slave process: - - - ./a.out --TOPC-num-slaves=1 YOUR_NUMBER - - Or investigate what other command-line TOP-C options are available for - a.out. - - - ./a.out --TOPC-help - - Other TOP-C applications besides parfactor are in the directory - `../examples'. For example, if you would like to try `parquicksort.c', - then from the `bin' directory, try: - - - make check TEST_FILE=parquicksort - - When you write your own `TOP-C' application, `app.c', make sure that - it contains #include at the top, and that you have a - procgroup file in the current directory, and then: - - - bin/topcc --mpi -o app app.c - # or else: bin/topc++ --mpi -o app app.cc - ./app - - `topcc' is a wrapper for your standard C compiler. It accepts all the - standard compiler command line options, plus a few more. `topc++' - also exists. [NOTE: bin/topcc --help and bin/topc++ --help both work - and `doc/topcc.1' exists ] - - This might be a good point to download and print at least the first - half of the manual, or else make it from the doc directory: - (cd doc; make pdf; make ps) - Note that the table of contents may appear at the - end of the documentation after the index. See Appendix A. Summary of - `TOP-C' Commands, for a list of the `TOP-C' commands. See B. Example - `TOP-C' Application, for a simple `TOP-C' example application - involving only trivial parallelism. The `examples' subdirectory - provides more detailed examples. A tutorial is available from the web - page, http://www.ccs.neu.edu/home/gene/topc.html. - - Finally, if you want to install `TOP-C' permanently, type - - ./configure # Install in /usr/local - ./configure --prefix=$HOME # Install in home directory - make install - - This adds a man page, an info file (try info topc), etc. HTML - documentation is available in the `doc' subdirectory of the `TOP-C' - distribution. By default, `TOP-C' will install in `/usr/local', - requiring root privilege. If you configured --prefix=$HOME, - TOP-C' will create files in `$HOME/bin', `$HOME/lib', - `$HOME/include', `$HOME/man' and `$HOME/info'. If you want to make - `TOP-C' with cc instead of gcc, type: - - - env CC=cc ./configure --cache-file=/dev/null - - CFLAGS, CXX (for topc++ and CXXFLAGS can also be set. For other - configuration options, type: - - ./configure --help - - Please write the author, Gene Cooperman (gene@ccs.neu.edu), if - there are any questions. diff --git a/topc-2.5.2/README.in b/topc-2.5.2/README.in deleted file mode 100644 index f8076119..00000000 --- a/topc-2.5.2/README.in +++ /dev/null @@ -1,25 +0,0 @@ -General Information -=================== - -This is version @TOPC_VERSION@ of TOP-C, last updated in @TOPC_UPDATED@. -TOP-C stands for Task Oriented Parallel C/C++. It is a package that -allows one to easily write parallel C/C++ applications that tolerate -high latency, while running in a distributed memory (message passing) or -shared memory (POSIX threads-based) mode. - -TOP-C hides the details of parallel programming, and presents the -application programmer with a simple task-oriented interface, for which -the application programmer need only define four callback functions. -Yet, TOP-C has been shown to readily adapt to a wide variety of algorithmic -requirements. - -TOP-C has been tested and ran on recent versions of Linux/Intel, SUN/Sparc, -IRIX/SGI, AIX/IBM, and OSF/Compaq Alpha. - -The TOP-C home page is: - http://www.ccs.neu.edu/home/gene/topc.html - -Installation -============ - -See the file 'INSTALL' diff --git a/topc-2.5.2/TODO b/topc-2.5.2/TODO deleted file mode 100644 index c832137f..00000000 --- a/topc-2.5.2/TODO +++ /dev/null @@ -1,175 +0,0 @@ -Check out C++ standard: rules for compatibility of void * with other pointers. - ---TOPC-verbose with --mpi: - TOPC_init() -- printout mixed w/ app printout. Fix it? - ALSO: "... `hostname` connected." messages coming in late. - MAYBE ADD: Connecting to `hostname` ... (so it displays earlier??) - -Note: no security in MPINU, open to man-in-the-middle attacks. -If this is a problem for you, do _not_ use MPINU. Use a different -implementation of MPI. - -ADD doc/topc.texi: - Using an MPI other than the built-in TOP-C libmpinu -SEE: ~/projects/topc-2/topc.texi-extra -dnl topc-config.in: --mpi) -dnl Note that with_mpi_cc != no means libmpi="". -dnl This is the right thing if using ${MPICC} -dnl Maybe we should have undocumented --mpi-internal returning this, -dnl which is called from topcc.in and topc++.in, -dnl while --mpi should indicate problem and: exit 1 -dnl # Do all of this for MPICXX also - -Compare with: ~/projects/topc-2/SSH-SETUP about using without passwords. - -Create DEBIAN file. - -Should we use in mpinu? -execvp is nicer and is POSIX.1: -: if (-1 == execvp("mpirun %s...", argv...)) { - perror("execvp"); exit(1); - } -Probably ought to revisit mpinu with these issues. -Finish setting up use of alternative MPI w/ C++ (to be done as with C) - -One page summary of all TOP-C commands, mirroring Appendix (chapter org.) - -Don't call malloc() or free() for messages of size <= 2 * sizeof_msg_hdr -Instead, keep free list (w/ mem_hdr_free_head) of buffers of that size: -memory.c: -//============================================================= -// push/pop onto free list: better cache performance than FIFO -struct short_msg { - ... struct msg_hdr fields ... - data; -} -static struct short_msg initial_free_list[NUM_INITIAL_FREE_LIST], - *free_list = NULL; -static int initial_free_list_used = 0; -static struct short_msg *pop_free_list() { - struct short_msg *tmp; - if (free_list == NULL) { - if (! initial_free_list_used) { - struct short_msg *tail = initial_free_list+NUM_INITIAL_FREE_LIST-1; - free_list = initial_free_list; - for (tmp = free_list; tmp < tail; tmp++) - tmp->next = tmp + 1; - initial_free_list_used = 1; - } else { - free_list = malloc(sizeof(struct short_msg)); - free_list->next = NULL; - } - } - tmp = free_list; - free_list = free_list->next; - return tmp; -} -static void push_free_list(struct short_msg *tmp) { - tmp->next = free_list; - free_list = tmp; -} -//============================================================= -and initialize next and prev pointers of following buffer and update -mem_uninit_msg upon doing so. - -Add TOPC_task_tmp_data() or else app-declared destructor callback function -so that TOP-C can free/delete buffer no longer used. -Note: C++ has two destructors, free/delete, and application - may want to declare third. -DISCUSS further best interface. -TOPC_task_tmp_data(void *) -void *TOPC_task_tmp_data(void *) would cause TOP-C to free the argument - at the end of a task. Common usage: -TOPC_MSG(TOPC_task_tmp_data(data),size); -On the master, this means to free(data) after GenerateTaskInput() is done. -On the slave, this means to free(data) after there are no more - REDO's or CONTINUATION()'s for this task (i.e.: when we see new task). -Initially, could insist that this be called at most once per - task, although that restriction could be lifted later. -TOPC_task_tmp_data(void *) will be especially important in - conjunction with TOPC_MSG_PTR() and aggregation, since there - may be several send messages pending in queue. - -src/comm-mpi.c:msg_info code can probably just use code from src/memory.c - -Can we test for memory overcommit by application? -(We sort of do it now by trial malloc when TOPC_init() gains control. -It affects example/simple.c - -comm-mpi.c: Better name for cache_thread, cache_thread_msg, etc. - (receive thread, receive buffer) -Explain in manual, when debugging with gdb, turn off receive thread - for easier debugging. - -Create a reference sheet for TOP-C commands (maybe two pages per side). - Base it partly on Summary section of manual. - -MANUAL: Add the comments at the beginning of the manual into - the manual. - -Absorb some of .future/doc/manual.dvi and .future/doc/topc.tex - into topc.texi and into a future topc-tutorial.texi - -Consider providing guarantee that TOP-C never calls malloc() if -TOPC_MSG_PTR() is used instead of TOPC_MSG(). - -> TOPC_malloc_tmp() probably is not worth the extra complication, but -> it can be considered. -TOP_malloc_tmp(size) -- Equivalent of malloc(), except that the buffer - would be freed at the end of a task (After REDO's and - CONTINUATION). What would be the equivalent for C++? - Also add --TOPC_safety level that plays tricks with mmap - to detect if the user has tried to access a buffer that was freed. - -sendahead messages -- GenerateTaskInput() is called n times for each slave, - even while that slave is busy. This maintains a queue of n - tasks for the slave that can be sent and stored on the - slave processor even while the slave is finishing its current - task. Even for n = 1, this can be significant, since it - provides overlapped communication and computation. On the - downside, it means that the application generates the next - task for a slave before seeing the result of a previous - task, and the result may be that the new task generated - is less useful. - When this is implemented, the logic for the receive thread - in comm-mpi.c could also be separated out, and joined - with a new file for management of TOP-C buffers and queues. - -marshalling -- add something, perhaps like MPI_Pack/Unpack, but with - extra arg for field name/type for error checking. Perhaps - have TOPC_pack_first(char *name, buf, size), - TOPC_pack_next(char *name, buf, size). - -implement slave stats - -Extend examples to simple examples of simulated annealing and neural nets? -simple work-stealing example for search (a la CILK)?? - -========================================================================== -MUCH FURTHER IN THE FUTURE: -Add pages for shared memory model (and so eliminate current ralse sharing, - where all of shared data acts as a single large page). As with the - rest of the TOP-C philosophy, a page will not be declared to TOP-C, - and so it will be more like a lock used by an application to lock - access to a region of memory. Such locks do not need to have - the region of memory declared to them. -In distributed memory, add greater robustness for dead or slow slaves. - Have backoff algorithm that re-allocates a slave task if a slave - doesn't reply in a certain time. If the new slave computes the task - before the old slave can reply, declare the old slave to be dead - and stop using it. Do _not_ use socket of that - dead slave unless a handler is in place, since that could crash the - master process. For now, I prefer to do without signal handlers, - to avoid conflicts with the application signal handlers. -Revive previous experiment with ability to start new slaves dynamically - during an ongoing TOP-C computation. -Add mixed distributed/shared memory model for clusters of - multiprocessor computers. - It becomes a tree with master node, communicating with distributed - slaves, who then have shared memory slaves below them. -Add a general model for a tree of masters to handle cases - when master might become overloaded. (Although I haven't - seen this case arise yet.) -Add support for large amounts of data in distributed memory model - that don't fit all on one node. This gets closer to the realm - of DSM. diff --git a/topc-2.5.2/bin/Makefile.in b/topc-2.5.2/bin/Makefile.in deleted file mode 100644 index d94a3413..00000000 --- a/topc-2.5.2/bin/Makefile.in +++ /dev/null @@ -1,188 +0,0 @@ -# @configure_input@ -exec_prefix=@PWD@ - -EXAMPLEDIR=@PWD@/examples -INCLUDEDIR=@PWD@/include -LIBDIR=@PWD@/lib -SRCDIR=@PWD@/src -SOURCE=${SRCDIR}/topc.c ${SRCDIR}/options.c ${SRCDIR}/procgroup.c - -CC=@CC@ -CFLAGS=@CFLAGS@ -TOPCC=./topcc - -@SET_MAKE@ - -BINARIES=parfactor parfactor-raw gauss-elim gauss-elim-fine-grain \ - par8queens-raw par8queens-abort \ - parquicksort parquicksort-raw - -parfactor: parfactor.o ${LIBDIR}/libtopc-mpi.a ${LIBDIR}/libmpinu.a - ${TOPCC} ${CFLAGS} parfactor.o - @ echo FACTORING 123456789 - ./a.out 123456789 -parfactor-seq: parfactor.o ${LIBDIR}/libtopc-seq.a - ${TOPCC} --seq ${CFLAGS} parfactor.o - @ echo FACTORING 123456789 - ./a.out 123456789 -parfactor-pthread: parfactor.o ${LIBDIR}/libtopc-pthread.a - ${TOPCC} --pthread ${CFLAGS} parfactor.o - @ echo FACTORING 123456789 - ./a.out 123456789 -parfactor-pthread-long: parfactor.o ${LIBDIR}/libtopc-pthread.a - ${TOPCC} --pthread ${CFLAGS} parfactor.o - @ echo FACTORING 123456761 \(prime\) - ./a.out 123456761 -parfactor.o: ${EXAMPLEDIR}/parfactor.c ${INCLUDEDIR}/topc.h - ${TOPCC} -c ${CFLAGS} ${EXAMPLEDIR}/parfactor.c - -# TEST raw interface to TOP-C with different communication layers -parfactor-raw: parfactor-raw.o ${LIBDIR}/libtopc-mpi.a ${LIBDIR}/libmpinu.a - ${TOPCC} ${CFLAGS} parfactor-raw.o - @ echo FACTORING 123456789 - ./a.out 123456789 -parfactor-raw-seq: parfactor-raw.o ${LIBDIR}/libtopc-seq.a - ${TOPCC} --seq ${CFLAGS} parfactor-raw.o - @ echo FACTORING 123456789 - ./a.out 123456789 -parfactor-raw-pthread: parfactor-raw.o ${LIBDIR}/libtopc-pthread.a - ${TOPCC} --pthread ${CFLAGS} parfactor-raw.o - @ echo FACTORING 123456789 - ./a.out 123456789 -parfactor-raw.o: ${EXAMPLEDIR}/parfactor-raw.c ${INCLUDEDIR}/topc.h - ${TOPCC} -c ${CFLAGS} ${EXAMPLEDIR}/parfactor-raw.c - -gauss-elim: gauss-elim.o ${LIBDIR}/libtopc-mpi.a ${LIBDIR}/libmpinu.a - ${TOPCC} ${CFLAGS} gauss-elim.o - @ echo DOING GAUSSIAN ELIMINATION OF MATRIX IN PROGRAM - ./a.out -gauss-elim-seq: gauss-elim.o ${LIBDIR}/libtopc-seq.a - ${TOPCC} --seq ${CFLAGS} gauss-elim.o - @ echo DOING GAUSSIAN ELIMINATION OF MATRIX IN PROGRAM - @ echo NOTICE THERE ARE FEWER TASK INPUTS DUE TO SEQUENTIALIZED STEPS - ./a.out -gauss-elim-pthread: gauss-elim.o ${LIBDIR}/libtopc-pthread.a - ${TOPCC} --pthread ${CFLAGS} gauss-elim.o - @ echo FACTORING 123456789 - ./a.out -gauss-elim.o: ${EXAMPLEDIR}/gauss-elim.c ${INCLUDEDIR}/topc.h - ${TOPCC} -c ${CFLAGS} ${EXAMPLEDIR}/gauss-elim.c - -parquicksort: parquicksort.o ${LIBDIR}/libtopc-mpi.a ${LIBDIR}/libmpinu.a - ${TOPCC} ${CFLAGS} parquicksort.o - @ echo DOING parallel quicksort - ./a.out -parquicksort-seq: parquicksort.o ${LIBDIR}/libtopc-seq.a - ${TOPCC} --seq ${CFLAGS} parquicksort.o - @ echo DOING parallel quicksort - ./a.out -parquicksort-pthread: parquicksort.o ${LIBDIR}/libtopc-pthread.a - ${TOPCC} --pthread ${CFLAGS} parquicksort.o - @ echo DOING parallel quicksort - ./a.out -parquicksort.o: ${EXAMPLEDIR}/parquicksort.c ${INCLUDEDIR}/topc.h - ${TOPCC} -c ${CFLAGS} ${EXAMPLEDIR}/parquicksort.c - -par8queens-raw: par8queens-raw.o ${LIBDIR}/libtopc-mpi.a ${LIBDIR}/libmpinu.a - ${TOPCC} ${CFLAGS} par8queens-raw.o - @ echo DOING parallel 8queens-raw - ./a.out -par8queens-raw-seq: par8queens-raw.o ${LIBDIR}/libtopc-seq.a - ${TOPCC} --seq ${CFLAGS} par8queens-raw.o - @ echo DOING parallel 8queens-raw - ./a.out -par8queens-raw-pthread: par8queens-raw.o ${LIBDIR}/libtopc-pthread.a - ${TOPCC} --pthread ${CFLAGS} par8queens-raw.o - @ echo DOING parallel 8queens-raw - ./a.out -par8queens-raw.o: ${EXAMPLEDIR}/par8queens-raw.c ${INCLUDEDIR}/topc.h - ${TOPCC} -c ${CFLAGS} ${EXAMPLEDIR}/par8queens-raw.c - -parsimple: parsimple.o ${LIBDIR}/libtopc-mpi.a ${LIBDIR}/libmpinu.a - ${TOPCC} ${CFLAGS} parsimple.o - @ echo DOING parallel simple - ./a.out -parsimple-seq: parsimple.o ${LIBDIR}/libtopc-seq.a - ${TOPCC} --seq ${CFLAGS} parsimple.o - @ echo DOING parallel simple - ./a.out -parsimple-pthread: parsimple.o ${LIBDIR}/libtopc-pthread.a - ${TOPCC} --pthread ${CFLAGS} parsimple.o - @ echo DOING parallel simple - ./a.out -parsimple.o: ${EXAMPLEDIR}/parsimple.c ${INCLUDEDIR}/topc.h - ${TOPCC} -c ${CFLAGS} ${EXAMPLEDIR}/parsimple.c - -all: ${INCLUDEDIR}/topc.h ${TOPCC} - for file in ${BINARIES}; do \ - ${TOPCC} -c ${CFLAGS} ${EXAMPLEDIR}/$$file.c ; \ - done - -${INCLUDEDIR}/topc.h: ${SRCDIR}/topc.h - ( cd ${SRCDIR}; ${MAKE} ${INCLUDEDIR}/topc.h ) -${LIBDIR}/libtopc-mpi.a: ${SOURCE} ${SRCDIR}/comm-mpi.c - ( cd ${SRCDIR}; ${MAKE} ${LIBDIR}/libtopc-mpi.a ) -${LIBDIR}/libtopc-seq.a: ${SOURCE} ${SRCDIR}/comm-seq.c - ( cd ${SRCDIR}; ${MAKE} ${LIBDIR}/libtopc-seq.a ) -${LIBDIR}/libtopc-pthread.a: ${SOURCE} ${SRCDIR}/comm-pthread.c - ( cd ${SRCDIR}; ${MAKE} ${LIBDIR}/libtopc-pthread.a ) -${LIBDIR}/libmpinu.a: ${SRCDIR}/mpinu/libmpi.a - cp ${SRCDIR}/mpinu/libmpi.a ${LIBDIR}/libmpinu.a -${SRCDIR}/mpinu/libmpi.a: - ( cd ${SRCDIR}; ${MAKE} ${LIBDIR}/libmpinu.a ) - -checkall: ${LIBDIR}/libtopc.a ${LIBDIR}/libtopc-seq.a \ - ${LIBDIR}/libtopc-pthread.a ${LIBDIR}/libmpinu.a - echo "*** WARNING: Some of these tests may take a little while" - ${MAKE} check TEST_FILE=parfactor - ${MAKE} check TEST_FILE=parfactor-raw - ${MAKE} check TEST_FILE=gauss-elim - ${MAKE} check TEST_FILE=gauss-elim-redo - ${MAKE} check TEST_FILE=gauss-elim-fine-grain - ${MAKE} check TEST_FILE=par8queens-raw - ${MAKE} check TEST_FILE=par8queens-abort - ${MAKE} check TEST_FILE=parquicksort - ${MAKE} check TEST_FILE=parquicksort-raw - ${MAKE} check TEST_FILE=parsimple - -# Should add code to check that correct answer was returned in ../tests . -# Could simply compare sequential output with others, to see if same -# autom4te (part of autoconf package) provides support for that. -check: - @ if test "${TEST_FILE}" = ""; then \ - echo ""; \ - echo '***' TOP-C: bin/Makefile: invalid call to "'make check'"; \ - echo "Syntax: make check TEST_FILE=EXAMPLE_FILE"; \ - echo " where examples/EXAMPLE_FILE.c is a file in TOP-C distrib"; \ - exit 1; \ - fi; - ${MAKE} checkit TEST_FILE='${TEST_FILE}' -checkit: ${EXAMPLEDIR}/${TEST_FILE}.c ${INCLUDEDIR}/topc.h - ${TOPCC} -c ${CFLAGS} ${EXAMPLEDIR}/${TEST_FILE}.c - @ echo "" - @ echo DOING --seq version of ${TEST_FILE} ${TEST_ARGS} && \ - ${TOPCC} --seq ${CFLAGS} ${TEST_FILE}.o && \ - ./a.out ${TEST_ARGS} && echo TESTED: ${TEST_FILE}-seq ${TEST_ARGS} \ - || ( echo ""; echo ======TEST ${TEST_FILE}-seq FAILED======; echo "" ) - @if test "x@HAVE_PTHREAD@" = "xyes"; then \ - echo "" \ - echo DOING --pthread version of ${TEST_FILE} ${TEST_ARGS} && \ - ${TOPCC} --pthread ${CFLAGS} ${TEST_FILE}.o && \ - ./a.out ${TEST_ARGS} && echo TESTED: ${TEST_FILE}-pthread ${TEST_ARGS}\ - || ( echo ""; echo ======TEST ${TEST_FILE}-pthread FAILED======; \ - echo "" ) \ - fi - @ echo "" - @ echo DOING --mpi version of ${TEST_FILE} ${TEST_ARGS} && \ - ${TOPCC} --mpi ${CFLAGS} ${TEST_FILE}.o && \ - ./a.out ${TEST_ARGS} && echo TESTED: ${TEST_FILE}-mpi ${TEST_ARGS} \ - || ( echo ""; echo ======TEST ${TEST_FILE}-mpi FAILED======; echo "" ) - -src: - ( cd ${SRCDIR}; ${MAKE} ) - -clean: - rm -f *.o a.out core .gdbinit - -distclean: clean - rm -f *~ slave?.out diff --git a/topc-2.5.2/bin/README b/topc-2.5.2/bin/README deleted file mode 100644 index f86b7e89..00000000 --- a/topc-2.5.2/bin/README +++ /dev/null @@ -1,25 +0,0 @@ -General Information -=================== - -This is version 2.5.2 of TOP-C, last updated in April, 2011. -TOP-C stands for Task Oriented Parallel C/C++. It is a package that -allows one to easily write parallel C/C++ applications that tolerate -high latency, while running in a distributed memory (message passing) or -shared memory (POSIX threads-based) mode. - -TOP-C hides the details of parallel programming, and presents the -application programmer with a simple task-oriented interface, for which -the application programmer need only define four callback functions. -Yet, TOP-C has been shown to readily adapt to a wide variety of algorithmic -requirements. - -TOP-C has been tested and ran on recent versions of Linux/Intel, SUN/Sparc, -IRIX/SGI, AIX/IBM, and OSF/Compaq Alpha. - -The TOP-C home page is: - http://www.ccs.neu.edu/home/gene/topc.html - -Installation -============ - -See the file 'INSTALL' diff --git a/topc-2.5.2/bin/gdbinit-example b/topc-2.5.2/bin/gdbinit-example deleted file mode 100644 index 0a80ed13..00000000 --- a/topc-2.5.2/bin/gdbinit-example +++ /dev/null @@ -1,13 +0,0 @@ -break main -break exit -break MPINU_set_and_exec_cmds -break MPINU_mpi_master -break TOPC_master_slave -break COMM_receive_msg -break COMM_send_msg -# slave routines: -break slave_loop -break cache_messages_init -# break MPINU_mpi_master -run --TOPC-slave-timeout=500 --TOPC-slave-wait=50 -# run --TOPC-slave-timeout=180 diff --git a/topc-2.5.2/bin/procgroup b/topc-2.5.2/bin/procgroup deleted file mode 100644 index 165e117e..00000000 --- a/topc-2.5.2/bin/procgroup +++ /dev/null @@ -1,74 +0,0 @@ -# NOTE: '#' in column 0 is a comment. - -local 0 -localhost 1 - > slave1.out -localhost 1 - > slave2.out -localhost 1 - > slave3.out -localhost 1 - > slave4.out -localhost 1 - > slave5.out - -#altair.ccs.neu.edu 1 - >slave1.out -#tyl.ccs.neu.edu 1 - >slave2.out -#thabit.ccs.neu.edu 1 - >slave3.out -#turais.ccs.neu.edu 1 - >slave4.out -#wasat.ccs.neu.edu 1 - >slave5.out - - - -# This causes: -# a. two slave processes to run on localhost -# b. with the same arguments as the master (`-') -# c. VARIATION: localhost 1 - >slave1.out -# This variation redirects output of this slave to slave1.out - -# The general format is that "local 0" (required) implies creation of a master. -# Otherwise there is one line per slave. -# The first field is the hostname or localhost (in a form valid for "rsh") -# If you prefer ssh over rsh, then (e.g. in csh): setenv RSH ssh -# The second field, 1, is obligatory. -# The third field is an absolute or relative pathname (e.g.: ./XXX or ../XXX) -# of the binary. A relative pathname is appended to path of the binary -# on master. The slave process will execute in the same directory -# as the current working directory of the master, if possible. -# Otherwise, the slave will execute in the home directory. -# If the third field is `-', then the command line (including arguments) -# for that slave will be the same as on the master. -# Any additional fields (fourth and beyond) are appended to the -# command line for that slave only. -# Note that '>slave1.out' works, redirecting standard output. -# Currently, `localhost' implies the Bourne shell, and any other -# name implies the default user shell for that machine. -# By default, standard output and error are sent to user tty (a la rsh). -# -# The format is inherited from MPICH, which grew from P4. - -#========================================================================= -#EXAMPLE: -# # Master process -# local 0 -# # One slave process on local computer, using same binary and same arguments -# localhost 1 - -# # One remote slave process, with absolute path to binary and no arguments -# regulus.ccs.neu.edu 1 /ccs/tmp/gene/a.out -# # One slave using alpha architecture, -# # with path of alpha binary relative to binary of this master process. -# # Output placed in slave-alpha-1.out in user's home directory. -# alpha.ccs.neu.edu 1 ../alpha/a.out > slave-alpha-1.out - -#========================================================================= -#IF YOU HAVE PROBLEMS: -# MPINU uses "rsh" to start a slave process. Diagnose it via: -# rsh REMOTE_SLAVE_HOST hostname -# If it doesn't work or if it asks you for a password, try: -# 1. Add a .rhosts file on the remote host and specify your local host. -# 2. Sometimes adding .localhost to your .rhosts helps. -# 3. Specify an alternative to "rsh" in your shell. For example: -# RSH=ssh; export RSH # in Bourne shell, bash, etc. -# setenv RSH ssh # in csh, tcsh, etc. -# 4. If you use "ssh", you may also need to copy keys to allow -# login to the remote host without a password. -# It's also possible that mpinu guessed badly the hostname of your local host. -# If you suspect this, on the master try (in csh, tcsh): -# setenv CALLBACK_HOST LOCAL_MASTER_HOST -# where LOCAL_MASTER_HOST is the correct hostname of the local master. - diff --git a/topc-2.5.2/bin/topc++.in b/topc-2.5.2/bin/topc++.in deleted file mode 100644 index 360f42bd..00000000 --- a/topc-2.5.2/bin/topc++.in +++ /dev/null @@ -1,98 +0,0 @@ -#! /bin/sh -# @configure_input@ - -CXX='@CXX@' -MPICXX="@MPICXX@" -# Add -g for symbolic debugging -CXXFLAGS= -LIBMALLOC=@LIBEFENCE@ - -prefix=@prefix@ -exec_prefix=@exec_prefix@ -TOPC_CONFIG_DIR=@bindir@ - -if test -x $TOPC_CONFIG_DIR/topc-config; then - TOPC_CONFIG=$TOPC_CONFIG_DIR/topc-config -else - TOPC_CONFIG=@PWD@/bin/topc-config -fi - -if [ $# -eq 0 -o "$1" = "-h" -o "$1" = "--help" ]; then - cat < - If --mpi is used, the current directory must contain procgroup - or else: ./topc++ --mpi myapp.c - ./a.out --TOPC_procgroup=MYDIR/procgroup -Example: topc++ --mpi -o myapp myapp.cc - ./myapp -EOF - exit 1 -fi; - -# Also accept -seq|-mpi|-pthread, but only if it's first argument. -case $1 in - -seq | -mpi | -pthread) - flags="-$@" - ;; - *) - flags="$@" - ;; -esac - -# if: cc -c ..., don't need libs for linking. -for flag in $flags; do - case $flag in - --seq) - cflags="`$TOPC_CONFIG --seq --cflags`" - libs="`$TOPC_CONFIG --seq --libs`" - ;; - --mpi) - cflags="`$TOPC_CONFIG --mpi --cflags`" - libs="`$TOPC_CONFIG --mpi --libs`" - CXX="$MPICXX" - ;; - --pthread) - if test "@HAVE_PTHREAD@" != "yes"; then - echo "*** No --pthread; This was configured with --enable-pthread=no" - echo "*** or else libpthread was not found during configure." - exit 1 - fi - cflags="`$TOPC_CONFIG --pthread --cflags`" - libs="`$TOPC_CONFIG --pthread --libs`" - ;; - --version) - echo "( TOP-C/C++ version `$TOPC_CONFIG --version`, using $CXX $CXXFLAGS)" - echo $CXX version: - args="$args $flag" - ;; - --efence) - efence=$LIBMALLOC - ;; - -c) - echo_libs=no - efence= - args="$args $flag" - ;; - *) - args="$args $flag" - ;; - esac -done - -if test "x$libs" = "x"; then - cflags="`$TOPC_CONFIG --mpi --cflags`" - libs="`$TOPC_CONFIG --mpi --libs`" - CXX="$MPICXX" -fi - -if test x$echo_libs = xno; then - libs= -fi - -$CXX $CXXFLAGS $cflags $args $libs $efence diff --git a/topc-2.5.2/bin/topc-config.in b/topc-2.5.2/bin/topc-config.in deleted file mode 100644 index f31c13e8..00000000 --- a/topc-2.5.2/bin/topc-config.in +++ /dev/null @@ -1,160 +0,0 @@ -#!/bin/sh -# @configure_input@ -# Based on example of gtk-config - -prefix=@prefix@ -exec_prefix=@exec_prefix@ -exec_prefix_set=no -libdir=-L@libdir@ -includedir=-I@includedir@ - -TOPC_CONFIG_DIR=@bindir@ - -usage() -{ - cat <&2 -fi - -while test $# -gt 0; do - case "$1" in - -*=*) optarg=`echo "$1" | sed 's/[-_a-zA-Z0-9]*=//'` ;; - *) optarg= ;; - esac - - case $1 in - --prefix=*) - prefix=$optarg - if test $exec_prefix_set = no ; then - exec_prefix=$optarg - fi - ;; - --prefix) - echo_prefix=yes - ;; - --exec-prefix=*) - exec_prefix=$optarg - exec_prefix_set=yes - ;; - --exec-prefix) - echo_exec_prefix=yes - ;; - --with-build-prefix) - use_uninstalled - ;; - --version) - echo '@TOPC_VERSION@ (@TOPC_UPDATED@)' - exit 0 - ;; - --cflags) - echo_cflags=yes - ;; - --libs) - echo_libs=yes - ;; - --seq | -seq) - mem_model=yes - topc_cflags= - topc_libs="-ltopc-seq @LIBSFORSEQ@" - ;; - --mpi | -mpi) - mem_model=yes - topc_cflags= - topc_libs="-ltopc-mpi @LIBSFORMPI@" - if test "@HAVE_PTHREAD@" = "yes"; then - topc_cflags="@CFLAGS_FOR_POSIX_1C@" - topc_libs="$topc_libs @LIBSFORPTHREAD@" - fi - ;; - --pthread | -pthread) - mem_model=yes - if test "@HAVE_PTHREAD@" = "yes"; then - topc_cflags="@CFLAGS_FOR_POSIX_1C@" - topc_libs="-ltopc-pthread @LIBSFORPTHREAD@" - else - echo "*** No --pthread; This was configured with --enable-pthread=no" - echo "*** or else libpthread was not found during configure." - exit 1 - fi - ;; - *) - usage 1 1>&2 - ;; - esac - shift -done - -if test "x$mem_model" = "x"; then - if test "$echo_cflags" = "yes"; then - echo "" - echo "*** One of --seq, --mpi, --pthread must be specified with --cflags" - usage 1 - fi -fi - -if test "x$mem_model" = "x"; then - if test "$echo_libs" = "yes"; then - echo "" - echo "*** One of --seq, --mpi, --pthread must be specified with --libs" - usage 1 - fi -fi - -if test "x$echo_cflags$echo_libs$echo_prefix$echo_exec_prefix" = "x"; then - echo "*** Nothing requested" 1>&2 - usage 1 1>&2 -fi - -if test "$echo_prefix" = "yes"; then - echo $prefix -fi - -if test "$echo_exec_prefix" = "yes"; then - echo $exec_prefix -fi - -if test "$echo_cflags" = "yes"; then - if test @includedir@ != /usr/include ; then - includes=-I@includedir@ - for i in $topc_cflags ; do - if test $i = $includedir ; then - includes="" - fi - done - fi - echo $includes $topc_cflags -fi - -if test "$echo_libs" = "yes"; then - if test @libdir@ != /usr/lib ; then - libs=-L@libdir@ - for i in $topc_libs ; do - if test $i = @libdir@ ; then - libs="" - fi - done - fi - echo $libs $topc_libs -fi diff --git a/topc-2.5.2/bin/topcc.in b/topc-2.5.2/bin/topcc.in deleted file mode 100644 index d51c5208..00000000 --- a/topc-2.5.2/bin/topcc.in +++ /dev/null @@ -1,99 +0,0 @@ -#! /bin/sh -# @configure_input@ - -CC='@CC@' -MPICC="@MPICC@" -# Add -g for symbolic debugging -CFLAGS= -LIBMALLOC=@LIBEFENCE@ - -prefix=@prefix@ -exec_prefix=@exec_prefix@ -TOPC_CONFIG_DIR=@bindir@ - -if test -x $TOPC_CONFIG_DIR/topc-config; then - TOPC_CONFIG=$TOPC_CONFIG_DIR/topc-config -else - TOPC_CONFIG=@PWD@/bin/topc-config -fi - -if [ $# -eq 0 -o "$1" = "-h" -o "$1" = "--help" ]; then - cat < - If --mpi is used, the current directory must contain procgroup - or else: ./topcc --mpi myapp.c - ./a.out --TOPC_procgroup=MYDIR/procgroup -Example: topcc --mpi -o myapp myapp.c - ./myapp -EOF - exit 1 -fi; - -# Also accept -seq|-mpi|-pthread, but only if it's first argument. -case $1 in - -seq | -mpi | -pthread) - flags="-$@" - ;; - *) - flags="$@" - ;; -esac - -# if: cc -c ..., don't need libs for linking. -for flag in $flags; do - case $flag in - --seq) - cflags="`$TOPC_CONFIG --seq --cflags`" - libs="`$TOPC_CONFIG --seq --libs`" - ;; - --mpi) - cflags="`$TOPC_CONFIG --mpi --cflags`" - libs="`$TOPC_CONFIG --mpi --libs`" - CC="$MPICC" - ;; - --pthread) - if test "@HAVE_PTHREAD@" != "yes"; then - echo "*** No --pthread; This was configured with --enable-pthread=no" - echo "*** or else libpthread was not found during configure." - exit 1 - fi - cflags="`$TOPC_CONFIG --pthread --cflags`" - libs="`$TOPC_CONFIG --pthread --libs`" - ;; - --version) - echo "( TOP-C/C++ version `$TOPC_CONFIG --version`, using $CC $CFLAGS)" - echo $CC version: - args="$args $flag" - ;; - --efence) - efence=$LIBMALLOC - ;; - -c) - echo_libs=no - efence= - args="$args $flag" - ;; - *) - args="$args $flag" - ;; - esac -done - -if test "x$libs" = "x"; then - cflags="`$TOPC_CONFIG --mpi --cflags`" - libs="`$TOPC_CONFIG --mpi --libs`" - CC="$MPICC" -fi - -if test x$echo_libs = xno; then - libs= -fi - -$CC $CFLAGS $cflags $args $libs $efence diff --git a/topc-2.5.2/configure b/topc-2.5.2/configure deleted file mode 100755 index 4f52e832..00000000 --- a/topc-2.5.2/configure +++ /dev/null @@ -1,5987 +0,0 @@ -#! /bin/sh -# Guess values for system-dependent variables and create Makefiles. -# Generated by GNU Autoconf 2.64 for TOP-C 0.0.0. -# -# Report bugs to . -# -# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001, -# 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 Free Software -# Foundation, Inc. -# -# This configure script is free software; the Free Software Foundation -# gives unlimited permission to copy, distribute and modify it. -## -------------------- ## -## M4sh Initialization. ## -## -------------------- ## - -# Be more Bourne compatible -DUALCASE=1; export DUALCASE # for MKS sh -if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then : - emulate sh - NULLCMD=: - # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which - # is contrary to our usage. Disable this feature. - alias -g '${1+"$@"}'='"$@"' - setopt NO_GLOB_SUBST -else - case `(set -o) 2>/dev/null` in #( - *posix*) : - set -o posix ;; #( - *) : - ;; -esac -fi - - -as_nl=' -' -export as_nl -# Printing a long string crashes Solaris 7 /usr/bin/printf. -as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' -as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo -as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo -# Prefer a ksh shell builtin over an external printf program on Solaris, -# but without wasting forks for bash or zsh. -if test -z "$BASH_VERSION$ZSH_VERSION" \ - && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then - as_echo='print -r --' - as_echo_n='print -rn --' -elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then - as_echo='printf %s\n' - as_echo_n='printf %s' -else - if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then - as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"' - as_echo_n='/usr/ucb/echo -n' - else - as_echo_body='eval expr "X$1" : "X\\(.*\\)"' - as_echo_n_body='eval - arg=$1; - case $arg in #( - *"$as_nl"*) - expr "X$arg" : "X\\(.*\\)$as_nl"; - arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; - esac; - expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl" - ' - export as_echo_n_body - as_echo_n='sh -c $as_echo_n_body as_echo' - fi - export as_echo_body - as_echo='sh -c $as_echo_body as_echo' -fi - -# The user is always right. -if test "${PATH_SEPARATOR+set}" != set; then - PATH_SEPARATOR=: - (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { - (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || - PATH_SEPARATOR=';' - } -fi - - -# IFS -# We need space, tab and new line, in precisely that order. Quoting is -# there to prevent editors from complaining about space-tab. -# (If _AS_PATH_WALK were called with IFS unset, it would disable word -# splitting by setting IFS to empty value.) -IFS=" "" $as_nl" - -# Find who we are. Look in the path if we contain no directory separator. -case $0 in #(( - *[\\/]* ) as_myself=$0 ;; - *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break - done -IFS=$as_save_IFS - - ;; -esac -# We did not find ourselves, most probably we were run as `sh COMMAND' -# in which case we are not to be found in the path. -if test "x$as_myself" = x; then - as_myself=$0 -fi -if test ! -f "$as_myself"; then - $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 - exit 1 -fi - -# Unset variables that we do not need and which cause bugs (e.g. in -# pre-3.0 UWIN ksh). But do not cause bugs in bash 2.01; the "|| exit 1" -# suppresses any "Segmentation fault" message there. '((' could -# trigger a bug in pdksh 5.2.14. -for as_var in BASH_ENV ENV MAIL MAILPATH -do eval test x\${$as_var+set} = xset \ - && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || : -done -PS1='$ ' -PS2='> ' -PS4='+ ' - -# NLS nuisances. -LC_ALL=C -export LC_ALL -LANGUAGE=C -export LANGUAGE - -# CDPATH. -(unset CDPATH) >/dev/null 2>&1 && unset CDPATH - -if test "x$CONFIG_SHELL" = x; then - as_bourne_compatible="if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then : - emulate sh - NULLCMD=: - # Pre-4.2 versions of Zsh do word splitting on \${1+\"\$@\"}, which - # is contrary to our usage. Disable this feature. - alias -g '\${1+\"\$@\"}'='\"\$@\"' - setopt NO_GLOB_SUBST -else - case \`(set -o) 2>/dev/null\` in #( - *posix*) : - set -o posix ;; #( - *) : - ;; -esac -fi -" - as_required="as_fn_return () { (exit \$1); } -as_fn_success () { as_fn_return 0; } -as_fn_failure () { as_fn_return 1; } -as_fn_ret_success () { return 0; } -as_fn_ret_failure () { return 1; } - -exitcode=0 -as_fn_success || { exitcode=1; echo as_fn_success failed.; } -as_fn_failure && { exitcode=1; echo as_fn_failure succeeded.; } -as_fn_ret_success || { exitcode=1; echo as_fn_ret_success failed.; } -as_fn_ret_failure && { exitcode=1; echo as_fn_ret_failure succeeded.; } -if ( set x; as_fn_ret_success y && test x = \"\$1\" ); then : - -else - exitcode=1; echo positional parameters were not saved. -fi -test x\$exitcode = x0 || exit 1" - as_suggested=" as_lineno_1=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_1a=\$LINENO - as_lineno_2=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_2a=\$LINENO - eval 'test \"x\$as_lineno_1'\$as_run'\" != \"x\$as_lineno_2'\$as_run'\" && - test \"x\`expr \$as_lineno_1'\$as_run' + 1\`\" = \"x\$as_lineno_2'\$as_run'\"' || exit 1 -test \$(( 1 + 1 )) = 2 || exit 1" - if (eval "$as_required") 2>/dev/null; then : - as_have_required=yes -else - as_have_required=no -fi - if test x$as_have_required = xyes && (eval "$as_suggested") 2>/dev/null; then : - -else - as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -as_found=false -for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - as_found=: - case $as_dir in #( - /*) - for as_base in sh bash ksh sh5; do - # Try only shells that exist, to save several forks. - as_shell=$as_dir/$as_base - if { test -f "$as_shell" || test -f "$as_shell.exe"; } && - { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$as_shell"; } 2>/dev/null; then : - CONFIG_SHELL=$as_shell as_have_required=yes - if { $as_echo "$as_bourne_compatible""$as_suggested" | as_run=a "$as_shell"; } 2>/dev/null; then : - break 2 -fi -fi - done;; - esac - as_found=false -done -$as_found || { if { test -f "$SHELL" || test -f "$SHELL.exe"; } && - { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$SHELL"; } 2>/dev/null; then : - CONFIG_SHELL=$SHELL as_have_required=yes -fi; } -IFS=$as_save_IFS - - - if test "x$CONFIG_SHELL" != x; then : - # We cannot yet assume a decent shell, so we have to provide a - # neutralization value for shells without unset; and this also - # works around shells that cannot unset nonexistent variables. - BASH_ENV=/dev/null - ENV=/dev/null - (unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV - export CONFIG_SHELL - exec "$CONFIG_SHELL" "$as_myself" ${1+"$@"} -fi - - if test x$as_have_required = xno; then : - $as_echo "$0: This script requires a shell more modern than all" - $as_echo "$0: the shells that I found on your system." - if test x${ZSH_VERSION+set} = xset ; then - $as_echo "$0: In particular, zsh $ZSH_VERSION has bugs and should" - $as_echo "$0: be upgraded to zsh 4.3.4 or later." - else - $as_echo "$0: Please tell bug-autoconf@gnu.org and gene@ccs.neu.edu -$0: about your system, including any error possibly output -$0: before this message. Then install a modern shell, or -$0: manually run the script under such a shell if you do -$0: have one." - fi - exit 1 -fi -fi -fi -SHELL=${CONFIG_SHELL-/bin/sh} -export SHELL -# Unset more variables known to interfere with behavior of common tools. -CLICOLOR_FORCE= GREP_OPTIONS= -unset CLICOLOR_FORCE GREP_OPTIONS - -## --------------------- ## -## M4sh Shell Functions. ## -## --------------------- ## -# as_fn_unset VAR -# --------------- -# Portably unset VAR. -as_fn_unset () -{ - { eval $1=; unset $1;} -} -as_unset=as_fn_unset - -# as_fn_set_status STATUS -# ----------------------- -# Set $? to STATUS, without forking. -as_fn_set_status () -{ - return $1 -} # as_fn_set_status - -# as_fn_exit STATUS -# ----------------- -# Exit the shell with STATUS, even in a "trap 0" or "set -e" context. -as_fn_exit () -{ - set +e - as_fn_set_status $1 - exit $1 -} # as_fn_exit - -# as_fn_mkdir_p -# ------------- -# Create "$as_dir" as a directory, including parents if necessary. -as_fn_mkdir_p () -{ - - case $as_dir in #( - -*) as_dir=./$as_dir;; - esac - test -d "$as_dir" || eval $as_mkdir_p || { - as_dirs= - while :; do - case $as_dir in #( - *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( - *) as_qdir=$as_dir;; - esac - as_dirs="'$as_qdir' $as_dirs" - as_dir=`$as_dirname -- "$as_dir" || -$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ - X"$as_dir" : 'X\(//\)[^/]' \| \ - X"$as_dir" : 'X\(//\)$' \| \ - X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || -$as_echo X"$as_dir" | - sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ - s//\1/ - q - } - /^X\(\/\/\)[^/].*/{ - s//\1/ - q - } - /^X\(\/\/\)$/{ - s//\1/ - q - } - /^X\(\/\).*/{ - s//\1/ - q - } - s/.*/./; q'` - test -d "$as_dir" && break - done - test -z "$as_dirs" || eval "mkdir $as_dirs" - } || test -d "$as_dir" || as_fn_error "cannot create directory $as_dir" - - -} # as_fn_mkdir_p -# as_fn_append VAR VALUE -# ---------------------- -# Append the text in VALUE to the end of the definition contained in VAR. Take -# advantage of any shell optimizations that allow amortized linear growth over -# repeated appends, instead of the typical quadratic growth present in naive -# implementations. -if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then : - eval 'as_fn_append () - { - eval $1+=\$2 - }' -else - as_fn_append () - { - eval $1=\$$1\$2 - } -fi # as_fn_append - -# as_fn_arith ARG... -# ------------------ -# Perform arithmetic evaluation on the ARGs, and store the result in the -# global $as_val. Take advantage of shells that can avoid forks. The arguments -# must be portable across $(()) and expr. -if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then : - eval 'as_fn_arith () - { - as_val=$(( $* )) - }' -else - as_fn_arith () - { - as_val=`expr "$@" || test $? -eq 1` - } -fi # as_fn_arith - - -# as_fn_error ERROR [LINENO LOG_FD] -# --------------------------------- -# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are -# provided, also output the error to LOG_FD, referencing LINENO. Then exit the -# script with status $?, using 1 if that was 0. -as_fn_error () -{ - as_status=$?; test $as_status -eq 0 && as_status=1 - if test "$3"; then - as_lineno=${as_lineno-"$2"} as_lineno_stack=as_lineno_stack=$as_lineno_stack - $as_echo "$as_me:${as_lineno-$LINENO}: error: $1" >&$3 - fi - $as_echo "$as_me: error: $1" >&2 - as_fn_exit $as_status -} # as_fn_error - -if expr a : '\(a\)' >/dev/null 2>&1 && - test "X`expr 00001 : '.*\(...\)'`" = X001; then - as_expr=expr -else - as_expr=false -fi - -if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then - as_basename=basename -else - as_basename=false -fi - -if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then - as_dirname=dirname -else - as_dirname=false -fi - -as_me=`$as_basename -- "$0" || -$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ - X"$0" : 'X\(//\)$' \| \ - X"$0" : 'X\(/\)' \| . 2>/dev/null || -$as_echo X/"$0" | - sed '/^.*\/\([^/][^/]*\)\/*$/{ - s//\1/ - q - } - /^X\/\(\/\/\)$/{ - s//\1/ - q - } - /^X\/\(\/\).*/{ - s//\1/ - q - } - s/.*/./; q'` - -# Avoid depending upon Character Ranges. -as_cr_letters='abcdefghijklmnopqrstuvwxyz' -as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' -as_cr_Letters=$as_cr_letters$as_cr_LETTERS -as_cr_digits='0123456789' -as_cr_alnum=$as_cr_Letters$as_cr_digits - - - as_lineno_1=$LINENO as_lineno_1a=$LINENO - as_lineno_2=$LINENO as_lineno_2a=$LINENO - eval 'test "x$as_lineno_1'$as_run'" != "x$as_lineno_2'$as_run'" && - test "x`expr $as_lineno_1'$as_run' + 1`" = "x$as_lineno_2'$as_run'"' || { - # Blame Lee E. McMahon (1931-1989) for sed's syntax. :-) - sed -n ' - p - /[$]LINENO/= - ' <$as_myself | - sed ' - s/[$]LINENO.*/&-/ - t lineno - b - :lineno - N - :loop - s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/ - t loop - s/-\n.*// - ' >$as_me.lineno && - chmod +x "$as_me.lineno" || - { $as_echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2; as_fn_exit 1; } - - # Don't try to exec as it changes $[0], causing all sort of problems - # (the dirname of $[0] is not the place where we might find the - # original and so on. Autoconf is especially sensitive to this). - . "./$as_me.lineno" - # Exit status is that of the last command. - exit -} - -ECHO_C= ECHO_N= ECHO_T= -case `echo -n x` in #((((( --n*) - case `echo 'xy\c'` in - *c*) ECHO_T=' ';; # ECHO_T is single tab character. - xy) ECHO_C='\c';; - *) echo `echo ksh88 bug on AIX 6.1` > /dev/null - ECHO_T=' ';; - esac;; -*) - ECHO_N='-n';; -esac - -rm -f conf$$ conf$$.exe conf$$.file -if test -d conf$$.dir; then - rm -f conf$$.dir/conf$$.file -else - rm -f conf$$.dir - mkdir conf$$.dir 2>/dev/null -fi -if (echo >conf$$.file) 2>/dev/null; then - if ln -s conf$$.file conf$$ 2>/dev/null; then - as_ln_s='ln -s' - # ... but there are two gotchas: - # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. - # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. - # In both cases, we have to default to `cp -p'. - ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || - as_ln_s='cp -p' - elif ln conf$$.file conf$$ 2>/dev/null; then - as_ln_s=ln - else - as_ln_s='cp -p' - fi -else - as_ln_s='cp -p' -fi -rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file -rmdir conf$$.dir 2>/dev/null - -if mkdir -p . 2>/dev/null; then - as_mkdir_p='mkdir -p "$as_dir"' -else - test -d ./-p && rmdir ./-p - as_mkdir_p=false -fi - -if test -x / >/dev/null 2>&1; then - as_test_x='test -x' -else - if ls -dL / >/dev/null 2>&1; then - as_ls_L_option=L - else - as_ls_L_option= - fi - as_test_x=' - eval sh -c '\'' - if test -d "$1"; then - test -d "$1/."; - else - case $1 in #( - -*)set "./$1";; - esac; - case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in #(( - ???[sx]*):;;*)false;;esac;fi - '\'' sh - ' -fi -as_executable_p=$as_test_x - -# Sed expression to map a string onto a valid CPP name. -as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" - -# Sed expression to map a string onto a valid variable name. -as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" - - -exec 7<&0 &1 - -# Name of the host. -# hostname on some systems (SVR3.2, Linux) returns a bogus exit status, -# so uname gets run too. -ac_hostname=`(hostname || uname -n) 2>/dev/null | sed 1q` - -# -# Initializations. -# -ac_default_prefix=/usr/local -ac_clean_files= -ac_config_libobj_dir=. -LIBOBJS= -cross_compiling=no -subdirs= -MFLAGS= -MAKEFLAGS= - -# Identity of this package. -PACKAGE_NAME='TOP-C' -PACKAGE_TARNAME='top-c' -PACKAGE_VERSION='0.0.0' -PACKAGE_STRING='TOP-C 0.0.0' -PACKAGE_BUGREPORT='gene@ccs.neu.edu' -PACKAGE_URL='' - -ac_unique_file="src/topc.c" -# Factoring default headers for most tests. -ac_includes_default="\ -#include -#ifdef HAVE_SYS_TYPES_H -# include -#endif -#ifdef HAVE_SYS_STAT_H -# include -#endif -#ifdef STDC_HEADERS -# include -# include -#else -# ifdef HAVE_STDLIB_H -# include -# endif -#endif -#ifdef HAVE_STRING_H -# if !defined STDC_HEADERS && defined HAVE_MEMORY_H -# include -# endif -# include -#endif -#ifdef HAVE_STRINGS_H -# include -#endif -#ifdef HAVE_INTTYPES_H -# include -#endif -#ifdef HAVE_STDINT_H -# include -#endif -#ifdef HAVE_UNISTD_H -# include -#endif" - -ac_subst_vars='LTLIBOBJS -MPICXX -MPICC -STRIP -STRIP_LIBS -LIBEFENCE -CFLAGS_FOR_POSIX_1C -LIBSFORSEQ -LIBSFORPTHREAD -HAVE_PTHREAD -LIBPTHREAD -LIBSFORMPI -LIBSFORSLEEP -LIBSFORSOCKETS -HOSTNAME -PWD -TOPC_UPDATED -TOPC_VERSION -LIBOBJS -EGREP -GREP -CPP -ac_ct_CXX -CXXFLAGS -CXX -RANLIB -SET_MAKE -LN_S -OBJEXT -EXEEXT -ac_ct_CC -CPPFLAGS -LDFLAGS -CFLAGS -CC -target_alias -host_alias -build_alias -LIBS -ECHO_T -ECHO_N -ECHO_C -DEFS -mandir -localedir -libdir -psdir -pdfdir -dvidir -htmldir -infodir -docdir -oldincludedir -includedir -localstatedir -sharedstatedir -sysconfdir -datadir -datarootdir -libexecdir -sbindir -bindir -program_transform_name -prefix -exec_prefix -PACKAGE_URL -PACKAGE_BUGREPORT -PACKAGE_STRING -PACKAGE_VERSION -PACKAGE_TARNAME -PACKAGE_NAME -PATH_SEPARATOR -SHELL' -ac_subst_files='' -ac_user_opts=' -enable_option_checking -enable_cxx -enable_posix_1c_threads -enable_pthread -enable_strip_libs -with_mpi_cc -with_mpi_cxx -' - ac_precious_vars='build_alias -host_alias -target_alias -CC -CFLAGS -LDFLAGS -LIBS -CPPFLAGS -CXX -CXXFLAGS -CCC -CPP' - - -# Initialize some variables set by options. -ac_init_help= -ac_init_version=false -ac_unrecognized_opts= -ac_unrecognized_sep= -# The variables have the same names as the options, with -# dashes changed to underlines. -cache_file=/dev/null -exec_prefix=NONE -no_create= -no_recursion= -prefix=NONE -program_prefix=NONE -program_suffix=NONE -program_transform_name=s,x,x, -silent= -site= -srcdir= -verbose= -x_includes=NONE -x_libraries=NONE - -# Installation directory options. -# These are left unexpanded so users can "make install exec_prefix=/foo" -# and all the variables that are supposed to be based on exec_prefix -# by default will actually change. -# Use braces instead of parens because sh, perl, etc. also accept them. -# (The list follows the same order as the GNU Coding Standards.) -bindir='${exec_prefix}/bin' -sbindir='${exec_prefix}/sbin' -libexecdir='${exec_prefix}/libexec' -datarootdir='${prefix}/share' -datadir='${datarootdir}' -sysconfdir='${prefix}/etc' -sharedstatedir='${prefix}/com' -localstatedir='${prefix}/var' -includedir='${prefix}/include' -oldincludedir='/usr/include' -docdir='${datarootdir}/doc/${PACKAGE_TARNAME}' -infodir='${datarootdir}/info' -htmldir='${docdir}' -dvidir='${docdir}' -pdfdir='${docdir}' -psdir='${docdir}' -libdir='${exec_prefix}/lib' -localedir='${datarootdir}/locale' -mandir='${datarootdir}/man' - -ac_prev= -ac_dashdash= -for ac_option -do - # If the previous option needs an argument, assign it. - if test -n "$ac_prev"; then - eval $ac_prev=\$ac_option - ac_prev= - continue - fi - - case $ac_option in - *=*) ac_optarg=`expr "X$ac_option" : '[^=]*=\(.*\)'` ;; - *) ac_optarg=yes ;; - esac - - # Accept the important Cygnus configure options, so we can diagnose typos. - - case $ac_dashdash$ac_option in - --) - ac_dashdash=yes ;; - - -bindir | --bindir | --bindi | --bind | --bin | --bi) - ac_prev=bindir ;; - -bindir=* | --bindir=* | --bindi=* | --bind=* | --bin=* | --bi=*) - bindir=$ac_optarg ;; - - -build | --build | --buil | --bui | --bu) - ac_prev=build_alias ;; - -build=* | --build=* | --buil=* | --bui=* | --bu=*) - build_alias=$ac_optarg ;; - - -cache-file | --cache-file | --cache-fil | --cache-fi \ - | --cache-f | --cache- | --cache | --cach | --cac | --ca | --c) - ac_prev=cache_file ;; - -cache-file=* | --cache-file=* | --cache-fil=* | --cache-fi=* \ - | --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* | --c=*) - cache_file=$ac_optarg ;; - - --config-cache | -C) - cache_file=config.cache ;; - - -datadir | --datadir | --datadi | --datad) - ac_prev=datadir ;; - -datadir=* | --datadir=* | --datadi=* | --datad=*) - datadir=$ac_optarg ;; - - -datarootdir | --datarootdir | --datarootdi | --datarootd | --dataroot \ - | --dataroo | --dataro | --datar) - ac_prev=datarootdir ;; - -datarootdir=* | --datarootdir=* | --datarootdi=* | --datarootd=* \ - | --dataroot=* | --dataroo=* | --dataro=* | --datar=*) - datarootdir=$ac_optarg ;; - - -disable-* | --disable-*) - ac_useropt=`expr "x$ac_option" : 'x-*disable-\(.*\)'` - # Reject names that are not valid shell variable names. - expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && - as_fn_error "invalid feature name: $ac_useropt" - ac_useropt_orig=$ac_useropt - ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` - case $ac_user_opts in - *" -"enable_$ac_useropt" -"*) ;; - *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--disable-$ac_useropt_orig" - ac_unrecognized_sep=', ';; - esac - eval enable_$ac_useropt=no ;; - - -docdir | --docdir | --docdi | --doc | --do) - ac_prev=docdir ;; - -docdir=* | --docdir=* | --docdi=* | --doc=* | --do=*) - docdir=$ac_optarg ;; - - -dvidir | --dvidir | --dvidi | --dvid | --dvi | --dv) - ac_prev=dvidir ;; - -dvidir=* | --dvidir=* | --dvidi=* | --dvid=* | --dvi=* | --dv=*) - dvidir=$ac_optarg ;; - - -enable-* | --enable-*) - ac_useropt=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'` - # Reject names that are not valid shell variable names. - expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && - as_fn_error "invalid feature name: $ac_useropt" - ac_useropt_orig=$ac_useropt - ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` - case $ac_user_opts in - *" -"enable_$ac_useropt" -"*) ;; - *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--enable-$ac_useropt_orig" - ac_unrecognized_sep=', ';; - esac - eval enable_$ac_useropt=\$ac_optarg ;; - - -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \ - | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \ - | --exec | --exe | --ex) - ac_prev=exec_prefix ;; - -exec-prefix=* | --exec_prefix=* | --exec-prefix=* | --exec-prefi=* \ - | --exec-pref=* | --exec-pre=* | --exec-pr=* | --exec-p=* | --exec-=* \ - | --exec=* | --exe=* | --ex=*) - exec_prefix=$ac_optarg ;; - - -gas | --gas | --ga | --g) - # Obsolete; use --with-gas. - with_gas=yes ;; - - -help | --help | --hel | --he | -h) - ac_init_help=long ;; - -help=r* | --help=r* | --hel=r* | --he=r* | -hr*) - ac_init_help=recursive ;; - -help=s* | --help=s* | --hel=s* | --he=s* | -hs*) - ac_init_help=short ;; - - -host | --host | --hos | --ho) - ac_prev=host_alias ;; - -host=* | --host=* | --hos=* | --ho=*) - host_alias=$ac_optarg ;; - - -htmldir | --htmldir | --htmldi | --htmld | --html | --htm | --ht) - ac_prev=htmldir ;; - -htmldir=* | --htmldir=* | --htmldi=* | --htmld=* | --html=* | --htm=* \ - | --ht=*) - htmldir=$ac_optarg ;; - - -includedir | --includedir | --includedi | --included | --include \ - | --includ | --inclu | --incl | --inc) - ac_prev=includedir ;; - -includedir=* | --includedir=* | --includedi=* | --included=* | --include=* \ - | --includ=* | --inclu=* | --incl=* | --inc=*) - includedir=$ac_optarg ;; - - -infodir | --infodir | --infodi | --infod | --info | --inf) - ac_prev=infodir ;; - -infodir=* | --infodir=* | --infodi=* | --infod=* | --info=* | --inf=*) - infodir=$ac_optarg ;; - - -libdir | --libdir | --libdi | --libd) - ac_prev=libdir ;; - -libdir=* | --libdir=* | --libdi=* | --libd=*) - libdir=$ac_optarg ;; - - -libexecdir | --libexecdir | --libexecdi | --libexecd | --libexec \ - | --libexe | --libex | --libe) - ac_prev=libexecdir ;; - -libexecdir=* | --libexecdir=* | --libexecdi=* | --libexecd=* | --libexec=* \ - | --libexe=* | --libex=* | --libe=*) - libexecdir=$ac_optarg ;; - - -localedir | --localedir | --localedi | --localed | --locale) - ac_prev=localedir ;; - -localedir=* | --localedir=* | --localedi=* | --localed=* | --locale=*) - localedir=$ac_optarg ;; - - -localstatedir | --localstatedir | --localstatedi | --localstated \ - | --localstate | --localstat | --localsta | --localst | --locals) - ac_prev=localstatedir ;; - -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \ - | --localstate=* | --localstat=* | --localsta=* | --localst=* | --locals=*) - localstatedir=$ac_optarg ;; - - -mandir | --mandir | --mandi | --mand | --man | --ma | --m) - ac_prev=mandir ;; - -mandir=* | --mandir=* | --mandi=* | --mand=* | --man=* | --ma=* | --m=*) - mandir=$ac_optarg ;; - - -nfp | --nfp | --nf) - # Obsolete; use --without-fp. - with_fp=no ;; - - -no-create | --no-create | --no-creat | --no-crea | --no-cre \ - | --no-cr | --no-c | -n) - no_create=yes ;; - - -no-recursion | --no-recursion | --no-recursio | --no-recursi \ - | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r) - no_recursion=yes ;; - - -oldincludedir | --oldincludedir | --oldincludedi | --oldincluded \ - | --oldinclude | --oldinclud | --oldinclu | --oldincl | --oldinc \ - | --oldin | --oldi | --old | --ol | --o) - ac_prev=oldincludedir ;; - -oldincludedir=* | --oldincludedir=* | --oldincludedi=* | --oldincluded=* \ - | --oldinclude=* | --oldinclud=* | --oldinclu=* | --oldincl=* | --oldinc=* \ - | --oldin=* | --oldi=* | --old=* | --ol=* | --o=*) - oldincludedir=$ac_optarg ;; - - -prefix | --prefix | --prefi | --pref | --pre | --pr | --p) - ac_prev=prefix ;; - -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*) - prefix=$ac_optarg ;; - - -program-prefix | --program-prefix | --program-prefi | --program-pref \ - | --program-pre | --program-pr | --program-p) - ac_prev=program_prefix ;; - -program-prefix=* | --program-prefix=* | --program-prefi=* \ - | --program-pref=* | --program-pre=* | --program-pr=* | --program-p=*) - program_prefix=$ac_optarg ;; - - -program-suffix | --program-suffix | --program-suffi | --program-suff \ - | --program-suf | --program-su | --program-s) - ac_prev=program_suffix ;; - -program-suffix=* | --program-suffix=* | --program-suffi=* \ - | --program-suff=* | --program-suf=* | --program-su=* | --program-s=*) - program_suffix=$ac_optarg ;; - - -program-transform-name | --program-transform-name \ - | --program-transform-nam | --program-transform-na \ - | --program-transform-n | --program-transform- \ - | --program-transform | --program-transfor \ - | --program-transfo | --program-transf \ - | --program-trans | --program-tran \ - | --progr-tra | --program-tr | --program-t) - ac_prev=program_transform_name ;; - -program-transform-name=* | --program-transform-name=* \ - | --program-transform-nam=* | --program-transform-na=* \ - | --program-transform-n=* | --program-transform-=* \ - | --program-transform=* | --program-transfor=* \ - | --program-transfo=* | --program-transf=* \ - | --program-trans=* | --program-tran=* \ - | --progr-tra=* | --program-tr=* | --program-t=*) - program_transform_name=$ac_optarg ;; - - -pdfdir | --pdfdir | --pdfdi | --pdfd | --pdf | --pd) - ac_prev=pdfdir ;; - -pdfdir=* | --pdfdir=* | --pdfdi=* | --pdfd=* | --pdf=* | --pd=*) - pdfdir=$ac_optarg ;; - - -psdir | --psdir | --psdi | --psd | --ps) - ac_prev=psdir ;; - -psdir=* | --psdir=* | --psdi=* | --psd=* | --ps=*) - psdir=$ac_optarg ;; - - -q | -quiet | --quiet | --quie | --qui | --qu | --q \ - | -silent | --silent | --silen | --sile | --sil) - silent=yes ;; - - -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb) - ac_prev=sbindir ;; - -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \ - | --sbi=* | --sb=*) - sbindir=$ac_optarg ;; - - -sharedstatedir | --sharedstatedir | --sharedstatedi \ - | --sharedstated | --sharedstate | --sharedstat | --sharedsta \ - | --sharedst | --shareds | --shared | --share | --shar \ - | --sha | --sh) - ac_prev=sharedstatedir ;; - -sharedstatedir=* | --sharedstatedir=* | --sharedstatedi=* \ - | --sharedstated=* | --sharedstate=* | --sharedstat=* | --sharedsta=* \ - | --sharedst=* | --shareds=* | --shared=* | --share=* | --shar=* \ - | --sha=* | --sh=*) - sharedstatedir=$ac_optarg ;; - - -site | --site | --sit) - ac_prev=site ;; - -site=* | --site=* | --sit=*) - site=$ac_optarg ;; - - -srcdir | --srcdir | --srcdi | --srcd | --src | --sr) - ac_prev=srcdir ;; - -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*) - srcdir=$ac_optarg ;; - - -sysconfdir | --sysconfdir | --sysconfdi | --sysconfd | --sysconf \ - | --syscon | --sysco | --sysc | --sys | --sy) - ac_prev=sysconfdir ;; - -sysconfdir=* | --sysconfdir=* | --sysconfdi=* | --sysconfd=* | --sysconf=* \ - | --syscon=* | --sysco=* | --sysc=* | --sys=* | --sy=*) - sysconfdir=$ac_optarg ;; - - -target | --target | --targe | --targ | --tar | --ta | --t) - ac_prev=target_alias ;; - -target=* | --target=* | --targe=* | --targ=* | --tar=* | --ta=* | --t=*) - target_alias=$ac_optarg ;; - - -v | -verbose | --verbose | --verbos | --verbo | --verb) - verbose=yes ;; - - -version | --version | --versio | --versi | --vers | -V) - ac_init_version=: ;; - - -with-* | --with-*) - ac_useropt=`expr "x$ac_option" : 'x-*with-\([^=]*\)'` - # Reject names that are not valid shell variable names. - expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && - as_fn_error "invalid package name: $ac_useropt" - ac_useropt_orig=$ac_useropt - ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` - case $ac_user_opts in - *" -"with_$ac_useropt" -"*) ;; - *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--with-$ac_useropt_orig" - ac_unrecognized_sep=', ';; - esac - eval with_$ac_useropt=\$ac_optarg ;; - - -without-* | --without-*) - ac_useropt=`expr "x$ac_option" : 'x-*without-\(.*\)'` - # Reject names that are not valid shell variable names. - expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && - as_fn_error "invalid package name: $ac_useropt" - ac_useropt_orig=$ac_useropt - ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` - case $ac_user_opts in - *" -"with_$ac_useropt" -"*) ;; - *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--without-$ac_useropt_orig" - ac_unrecognized_sep=', ';; - esac - eval with_$ac_useropt=no ;; - - --x) - # Obsolete; use --with-x. - with_x=yes ;; - - -x-includes | --x-includes | --x-include | --x-includ | --x-inclu \ - | --x-incl | --x-inc | --x-in | --x-i) - ac_prev=x_includes ;; - -x-includes=* | --x-includes=* | --x-include=* | --x-includ=* | --x-inclu=* \ - | --x-incl=* | --x-inc=* | --x-in=* | --x-i=*) - x_includes=$ac_optarg ;; - - -x-libraries | --x-libraries | --x-librarie | --x-librari \ - | --x-librar | --x-libra | --x-libr | --x-lib | --x-li | --x-l) - ac_prev=x_libraries ;; - -x-libraries=* | --x-libraries=* | --x-librarie=* | --x-librari=* \ - | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*) - x_libraries=$ac_optarg ;; - - -*) as_fn_error "unrecognized option: \`$ac_option' -Try \`$0 --help' for more information." - ;; - - *=*) - ac_envvar=`expr "x$ac_option" : 'x\([^=]*\)='` - # Reject names that are not valid shell variable names. - case $ac_envvar in #( - '' | [0-9]* | *[!_$as_cr_alnum]* ) - as_fn_error "invalid variable name: \`$ac_envvar'" ;; - esac - eval $ac_envvar=\$ac_optarg - export $ac_envvar ;; - - *) - # FIXME: should be removed in autoconf 3.0. - $as_echo "$as_me: WARNING: you should use --build, --host, --target" >&2 - expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null && - $as_echo "$as_me: WARNING: invalid host type: $ac_option" >&2 - : ${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option} - ;; - - esac -done - -if test -n "$ac_prev"; then - ac_option=--`echo $ac_prev | sed 's/_/-/g'` - as_fn_error "missing argument to $ac_option" -fi - -if test -n "$ac_unrecognized_opts"; then - case $enable_option_checking in - no) ;; - fatal) as_fn_error "unrecognized options: $ac_unrecognized_opts" ;; - *) $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2 ;; - esac -fi - -# Check all directory arguments for consistency. -for ac_var in exec_prefix prefix bindir sbindir libexecdir datarootdir \ - datadir sysconfdir sharedstatedir localstatedir includedir \ - oldincludedir docdir infodir htmldir dvidir pdfdir psdir \ - libdir localedir mandir -do - eval ac_val=\$$ac_var - # Remove trailing slashes. - case $ac_val in - */ ) - ac_val=`expr "X$ac_val" : 'X\(.*[^/]\)' \| "X$ac_val" : 'X\(.*\)'` - eval $ac_var=\$ac_val;; - esac - # Be sure to have absolute directory names. - case $ac_val in - [\\/$]* | ?:[\\/]* ) continue;; - NONE | '' ) case $ac_var in *prefix ) continue;; esac;; - esac - as_fn_error "expected an absolute directory name for --$ac_var: $ac_val" -done - -# There might be people who depend on the old broken behavior: `$host' -# used to hold the argument of --host etc. -# FIXME: To remove some day. -build=$build_alias -host=$host_alias -target=$target_alias - -# FIXME: To remove some day. -if test "x$host_alias" != x; then - if test "x$build_alias" = x; then - cross_compiling=maybe - $as_echo "$as_me: WARNING: If you wanted to set the --build type, don't use --host. - If a cross compiler is detected then cross compile mode will be used." >&2 - elif test "x$build_alias" != "x$host_alias"; then - cross_compiling=yes - fi -fi - -ac_tool_prefix= -test -n "$host_alias" && ac_tool_prefix=$host_alias- - -test "$silent" = yes && exec 6>/dev/null - - -ac_pwd=`pwd` && test -n "$ac_pwd" && -ac_ls_di=`ls -di .` && -ac_pwd_ls_di=`cd "$ac_pwd" && ls -di .` || - as_fn_error "working directory cannot be determined" -test "X$ac_ls_di" = "X$ac_pwd_ls_di" || - as_fn_error "pwd does not report name of working directory" - - -# Find the source files, if location was not specified. -if test -z "$srcdir"; then - ac_srcdir_defaulted=yes - # Try the directory containing this script, then the parent directory. - ac_confdir=`$as_dirname -- "$as_myself" || -$as_expr X"$as_myself" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ - X"$as_myself" : 'X\(//\)[^/]' \| \ - X"$as_myself" : 'X\(//\)$' \| \ - X"$as_myself" : 'X\(/\)' \| . 2>/dev/null || -$as_echo X"$as_myself" | - sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ - s//\1/ - q - } - /^X\(\/\/\)[^/].*/{ - s//\1/ - q - } - /^X\(\/\/\)$/{ - s//\1/ - q - } - /^X\(\/\).*/{ - s//\1/ - q - } - s/.*/./; q'` - srcdir=$ac_confdir - if test ! -r "$srcdir/$ac_unique_file"; then - srcdir=.. - fi -else - ac_srcdir_defaulted=no -fi -if test ! -r "$srcdir/$ac_unique_file"; then - test "$ac_srcdir_defaulted" = yes && srcdir="$ac_confdir or .." - as_fn_error "cannot find sources ($ac_unique_file) in $srcdir" -fi -ac_msg="sources are in $srcdir, but \`cd $srcdir' does not work" -ac_abs_confdir=`( - cd "$srcdir" && test -r "./$ac_unique_file" || as_fn_error "$ac_msg" - pwd)` -# When building in place, set srcdir=. -if test "$ac_abs_confdir" = "$ac_pwd"; then - srcdir=. -fi -# Remove unnecessary trailing slashes from srcdir. -# Double slashes in file names in object file debugging info -# mess up M-x gdb in Emacs. -case $srcdir in -*/) srcdir=`expr "X$srcdir" : 'X\(.*[^/]\)' \| "X$srcdir" : 'X\(.*\)'`;; -esac -for ac_var in $ac_precious_vars; do - eval ac_env_${ac_var}_set=\${${ac_var}+set} - eval ac_env_${ac_var}_value=\$${ac_var} - eval ac_cv_env_${ac_var}_set=\${${ac_var}+set} - eval ac_cv_env_${ac_var}_value=\$${ac_var} -done - -# -# Report the --help message. -# -if test "$ac_init_help" = "long"; then - # Omit some internal or obsolete options to make the list less imposing. - # This message is too long to be a string in the A/UX 3.1 sh. - cat <<_ACEOF -\`configure' configures TOP-C 0.0.0 to adapt to many kinds of systems. - -Usage: $0 [OPTION]... [VAR=VALUE]... - -To assign environment variables (e.g., CC, CFLAGS...), specify them as -VAR=VALUE. See below for descriptions of some of the useful variables. - -Defaults for the options are specified in brackets. - -Configuration: - -h, --help display this help and exit - --help=short display options specific to this package - --help=recursive display the short help of all the included packages - -V, --version display version information and exit - -q, --quiet, --silent do not print \`checking...' messages - --cache-file=FILE cache test results in FILE [disabled] - -C, --config-cache alias for \`--cache-file=config.cache' - -n, --no-create do not create output files - --srcdir=DIR find the sources in DIR [configure dir or \`..'] - -Installation directories: - --prefix=PREFIX install architecture-independent files in PREFIX - [$ac_default_prefix] - --exec-prefix=EPREFIX install architecture-dependent files in EPREFIX - [PREFIX] - -By default, \`make install' will install all the files in -\`$ac_default_prefix/bin', \`$ac_default_prefix/lib' etc. You can specify -an installation prefix other than \`$ac_default_prefix' using \`--prefix', -for instance \`--prefix=\$HOME'. - -For better control, use the options below. - -Fine tuning of the installation directories: - --bindir=DIR user executables [EPREFIX/bin] - --sbindir=DIR system admin executables [EPREFIX/sbin] - --libexecdir=DIR program executables [EPREFIX/libexec] - --sysconfdir=DIR read-only single-machine data [PREFIX/etc] - --sharedstatedir=DIR modifiable architecture-independent data [PREFIX/com] - --localstatedir=DIR modifiable single-machine data [PREFIX/var] - --libdir=DIR object code libraries [EPREFIX/lib] - --includedir=DIR C header files [PREFIX/include] - --oldincludedir=DIR C header files for non-gcc [/usr/include] - --datarootdir=DIR read-only arch.-independent data root [PREFIX/share] - --datadir=DIR read-only architecture-independent data [DATAROOTDIR] - --infodir=DIR info documentation [DATAROOTDIR/info] - --localedir=DIR locale-dependent data [DATAROOTDIR/locale] - --mandir=DIR man documentation [DATAROOTDIR/man] - --docdir=DIR documentation root [DATAROOTDIR/doc/top-c] - --htmldir=DIR html documentation [DOCDIR] - --dvidir=DIR dvi documentation [DOCDIR] - --pdfdir=DIR pdf documentation [DOCDIR] - --psdir=DIR ps documentation [DOCDIR] -_ACEOF - - cat <<\_ACEOF -_ACEOF -fi - -if test -n "$ac_init_help"; then - case $ac_init_help in - short | recursive ) echo "Configuration of TOP-C 0.0.0:";; - esac - cat <<\_ACEOF - -Optional Features: - --disable-option-checking ignore unrecognized --enable/--with options - --disable-FEATURE do not include FEATURE (same as --enable-FEATURE=no) - --enable-FEATURE[=ARG] include FEATURE [ARG=yes] - --enable-cxx provide topc++ for C++ default=yes - --enable-posix-1c-threads - turn on strict POSIX 1C default=no - --enable-pthread POSIX threads for shared memory default=yes - --enable-strip-libs Smaller image, but no symbolic debugging default=no - -Optional Packages: - --with-PACKAGE[=ARG] use PACKAGE [ARG=yes] - --without-PACKAGE do not use PACKAGE (same as --with-PACKAGE=no) - --with-mpi-cc=PROG Use PROG to compile mpi files default=built-in MPI - (Also consider: env CC=cc ./configure (use vendor cc); - see appendix of manual for more on non-default MPI) - --with-mpi-cxx=PROG Use PROG to compile mpi files default=built-in MPI - (Also consider: env CXX=c++ ./configure (vendor C++)) - -Some influential environment variables: - CC C compiler command - CFLAGS C compiler flags - LDFLAGS linker flags, e.g. -L if you have libraries in a - nonstandard directory - LIBS libraries to pass to the linker, e.g. -l - CPPFLAGS C/C++/Objective C preprocessor flags, e.g. -I if - you have headers in a nonstandard directory - CXX C++ compiler command - CXXFLAGS C++ compiler flags - CPP C preprocessor - -Use these variables to override the choices made by `configure' or to help -it to find libraries and programs with nonstandard names/locations. - -Report bugs to . -_ACEOF -ac_status=$? -fi - -if test "$ac_init_help" = "recursive"; then - # If there are subdirs, report their specific --help. - for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue - test -d "$ac_dir" || - { cd "$srcdir" && ac_pwd=`pwd` && srcdir=. && test -d "$ac_dir"; } || - continue - ac_builddir=. - -case "$ac_dir" in -.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; -*) - ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` - # A ".." for each directory in $ac_dir_suffix. - ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` - case $ac_top_builddir_sub in - "") ac_top_builddir_sub=. ac_top_build_prefix= ;; - *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; - esac ;; -esac -ac_abs_top_builddir=$ac_pwd -ac_abs_builddir=$ac_pwd$ac_dir_suffix -# for backward compatibility: -ac_top_builddir=$ac_top_build_prefix - -case $srcdir in - .) # We are building in place. - ac_srcdir=. - ac_top_srcdir=$ac_top_builddir_sub - ac_abs_top_srcdir=$ac_pwd ;; - [\\/]* | ?:[\\/]* ) # Absolute name. - ac_srcdir=$srcdir$ac_dir_suffix; - ac_top_srcdir=$srcdir - ac_abs_top_srcdir=$srcdir ;; - *) # Relative name. - ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix - ac_top_srcdir=$ac_top_build_prefix$srcdir - ac_abs_top_srcdir=$ac_pwd/$srcdir ;; -esac -ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix - - cd "$ac_dir" || { ac_status=$?; continue; } - # Check for guested configure. - if test -f "$ac_srcdir/configure.gnu"; then - echo && - $SHELL "$ac_srcdir/configure.gnu" --help=recursive - elif test -f "$ac_srcdir/configure"; then - echo && - $SHELL "$ac_srcdir/configure" --help=recursive - else - $as_echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2 - fi || ac_status=$? - cd "$ac_pwd" || { ac_status=$?; break; } - done -fi - -test -n "$ac_init_help" && exit $ac_status -if $ac_init_version; then - cat <<\_ACEOF -TOP-C configure 0.0.0 -generated by GNU Autoconf 2.64 - -Copyright (C) 2009 Free Software Foundation, Inc. -This configure script is free software; the Free Software Foundation -gives unlimited permission to copy, distribute and modify it. -_ACEOF - exit -fi - -## ------------------------ ## -## Autoconf initialization. ## -## ------------------------ ## - -# ac_fn_c_try_compile LINENO -# -------------------------- -# Try to compile conftest.$ac_ext, and return whether this succeeded. -ac_fn_c_try_compile () -{ - as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack - rm -f conftest.$ac_objext - if { { ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" -$as_echo "$ac_try_echo"; } >&5 - (eval "$ac_compile") 2>conftest.err - ac_status=$? - if test -s conftest.err; then - grep -v '^ *+' conftest.err >conftest.er1 - cat conftest.er1 >&5 - mv -f conftest.er1 conftest.err - fi - $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 - test $ac_status = 0; } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then : - ac_retval=0 -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_retval=1 -fi - eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} - return $ac_retval - -} # ac_fn_c_try_compile - -# ac_fn_c_check_func LINENO FUNC VAR -# ---------------------------------- -# Tests whether FUNC exists, setting the cache variable VAR accordingly -ac_fn_c_check_func () -{ - as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 -$as_echo_n "checking for $2... " >&6; } -if { as_var=$3; eval "test \"\${$as_var+set}\" = set"; }; then : - $as_echo_n "(cached) " >&6 -else - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -/* Define $2 to an innocuous variant, in case declares $2. - For example, HP-UX 11i declares gettimeofday. */ -#define $2 innocuous_$2 - -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char $2 (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ - -#ifdef __STDC__ -# include -#else -# include -#endif - -#undef $2 - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char $2 (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_$2 || defined __stub___$2 -choke me -#endif - -int -main () -{ -return $2 (); - ; - return 0; -} -_ACEOF -if ac_fn_c_try_link "$LINENO"; then : - eval "$3=yes" -else - eval "$3=no" -fi -rm -f core conftest.err conftest.$ac_objext \ - conftest$ac_exeext conftest.$ac_ext -fi -eval ac_res=\$$3 - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 -$as_echo "$ac_res" >&6; } - eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} - -} # ac_fn_c_check_func - -# ac_fn_cxx_try_compile LINENO -# ---------------------------- -# Try to compile conftest.$ac_ext, and return whether this succeeded. -ac_fn_cxx_try_compile () -{ - as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack - rm -f conftest.$ac_objext - if { { ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" -$as_echo "$ac_try_echo"; } >&5 - (eval "$ac_compile") 2>conftest.err - ac_status=$? - if test -s conftest.err; then - grep -v '^ *+' conftest.err >conftest.er1 - cat conftest.er1 >&5 - mv -f conftest.er1 conftest.err - fi - $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 - test $ac_status = 0; } && { - test -z "$ac_cxx_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then : - ac_retval=0 -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_retval=1 -fi - eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} - return $ac_retval - -} # ac_fn_cxx_try_compile - -# ac_fn_c_try_run LINENO -# ---------------------- -# Try to link conftest.$ac_ext, and return whether this succeeded. Assumes -# that executables *can* be run. -ac_fn_c_try_run () -{ - as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack - if { { ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" -$as_echo "$ac_try_echo"; } >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 - test $ac_status = 0; } && { ac_try='./conftest$ac_exeext' - { { case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" -$as_echo "$ac_try_echo"; } >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 - test $ac_status = 0; }; }; then : - ac_retval=0 -else - $as_echo "$as_me: program exited with status $ac_status" >&5 - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_retval=$ac_status -fi - rm -rf conftest.dSYM conftest_ipa8_conftest.oo - eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} - return $ac_retval - -} # ac_fn_c_try_run - -# ac_fn_c_try_cpp LINENO -# ---------------------- -# Try to preprocess conftest.$ac_ext, and return whether this succeeded. -ac_fn_c_try_cpp () -{ - as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack - if { { ac_try="$ac_cpp conftest.$ac_ext" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" -$as_echo "$ac_try_echo"; } >&5 - (eval "$ac_cpp conftest.$ac_ext") 2>conftest.err - ac_status=$? - if test -s conftest.err; then - grep -v '^ *+' conftest.err >conftest.er1 - cat conftest.er1 >&5 - mv -f conftest.er1 conftest.err - fi - $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 - test $ac_status = 0; } >/dev/null && { - test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || - test ! -s conftest.err - }; then : - ac_retval=0 -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_retval=1 -fi - eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} - return $ac_retval - -} # ac_fn_c_try_cpp - -# ac_fn_c_check_header_mongrel LINENO HEADER VAR INCLUDES -# ------------------------------------------------------- -# Tests whether HEADER exists, giving a warning if it cannot be compiled using -# the include files in INCLUDES and setting the cache variable VAR -# accordingly. -ac_fn_c_check_header_mongrel () -{ - as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack - if { as_var=$3; eval "test \"\${$as_var+set}\" = set"; }; then : - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 -$as_echo_n "checking for $2... " >&6; } -if { as_var=$3; eval "test \"\${$as_var+set}\" = set"; }; then : - $as_echo_n "(cached) " >&6 -fi -eval ac_res=\$$3 - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 -$as_echo "$ac_res" >&6; } -else - # Is the header compilable? -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 usability" >&5 -$as_echo_n "checking $2 usability... " >&6; } -cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -$4 -#include <$2> -_ACEOF -if ac_fn_c_try_compile "$LINENO"; then : - ac_header_compiler=yes -else - ac_header_compiler=no -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_compiler" >&5 -$as_echo "$ac_header_compiler" >&6; } - -# Is the header present? -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 presence" >&5 -$as_echo_n "checking $2 presence... " >&6; } -cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -#include <$2> -_ACEOF -if ac_fn_c_try_cpp "$LINENO"; then : - ac_header_preproc=yes -else - ac_header_preproc=no -fi -rm -f conftest.err conftest.$ac_ext -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_preproc" >&5 -$as_echo "$ac_header_preproc" >&6; } - -# So? What about this header? -case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in #(( - yes:no: ) - { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&5 -$as_echo "$as_me: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&2;} - { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5 -$as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;} - ;; - no:yes:* ) - { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: present but cannot be compiled" >&5 -$as_echo "$as_me: WARNING: $2: present but cannot be compiled" >&2;} - { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: check for missing prerequisite headers?" >&5 -$as_echo "$as_me: WARNING: $2: check for missing prerequisite headers?" >&2;} - { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: see the Autoconf documentation" >&5 -$as_echo "$as_me: WARNING: $2: see the Autoconf documentation" >&2;} - { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: section \"Present But Cannot Be Compiled\"" >&5 -$as_echo "$as_me: WARNING: $2: section \"Present But Cannot Be Compiled\"" >&2;} - { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5 -$as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;} -( cat <<\_ASBOX -## ------------------------------- ## -## Report this to gene@ccs.neu.edu ## -## ------------------------------- ## -_ASBOX - ) | sed "s/^/$as_me: WARNING: /" >&2 - ;; -esac - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 -$as_echo_n "checking for $2... " >&6; } -if { as_var=$3; eval "test \"\${$as_var+set}\" = set"; }; then : - $as_echo_n "(cached) " >&6 -else - eval "$3=\$ac_header_compiler" -fi -eval ac_res=\$$3 - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 -$as_echo "$ac_res" >&6; } -fi - eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} - -} # ac_fn_c_check_header_mongrel - -# ac_fn_c_check_header_compile LINENO HEADER VAR INCLUDES -# ------------------------------------------------------- -# Tests whether HEADER exists and can be compiled using the include files in -# INCLUDES, setting the cache variable VAR accordingly. -ac_fn_c_check_header_compile () -{ - as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 -$as_echo_n "checking for $2... " >&6; } -if { as_var=$3; eval "test \"\${$as_var+set}\" = set"; }; then : - $as_echo_n "(cached) " >&6 -else - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -$4 -#include <$2> -_ACEOF -if ac_fn_c_try_compile "$LINENO"; then : - eval "$3=yes" -else - eval "$3=no" -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -eval ac_res=\$$3 - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 -$as_echo "$ac_res" >&6; } - eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} - -} # ac_fn_c_check_header_compile - -# ac_fn_c_check_type LINENO TYPE VAR INCLUDES -# ------------------------------------------- -# Tests whether TYPE exists after having included INCLUDES, setting cache -# variable VAR accordingly. -ac_fn_c_check_type () -{ - as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 -$as_echo_n "checking for $2... " >&6; } -if { as_var=$3; eval "test \"\${$as_var+set}\" = set"; }; then : - $as_echo_n "(cached) " >&6 -else - eval "$3=no" - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -$4 -int -main () -{ -if (sizeof ($2)) - return 0; - ; - return 0; -} -_ACEOF -if ac_fn_c_try_compile "$LINENO"; then : - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -$4 -int -main () -{ -if (sizeof (($2))) - return 0; - ; - return 0; -} -_ACEOF -if ac_fn_c_try_compile "$LINENO"; then : - -else - eval "$3=yes" -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -eval ac_res=\$$3 - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 -$as_echo "$ac_res" >&6; } - eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} - -} # ac_fn_c_check_type -cat >config.log <<_ACEOF -This file contains any messages produced by compilers while -running configure, to aid debugging if configure makes a mistake. - -It was created by TOP-C $as_me 0.0.0, which was -generated by GNU Autoconf 2.64. Invocation command line was - - $ $0 $@ - -_ACEOF -exec 5>>config.log -{ -cat <<_ASUNAME -## --------- ## -## Platform. ## -## --------- ## - -hostname = `(hostname || uname -n) 2>/dev/null | sed 1q` -uname -m = `(uname -m) 2>/dev/null || echo unknown` -uname -r = `(uname -r) 2>/dev/null || echo unknown` -uname -s = `(uname -s) 2>/dev/null || echo unknown` -uname -v = `(uname -v) 2>/dev/null || echo unknown` - -/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null || echo unknown` -/bin/uname -X = `(/bin/uname -X) 2>/dev/null || echo unknown` - -/bin/arch = `(/bin/arch) 2>/dev/null || echo unknown` -/usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null || echo unknown` -/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown` -/usr/bin/hostinfo = `(/usr/bin/hostinfo) 2>/dev/null || echo unknown` -/bin/machine = `(/bin/machine) 2>/dev/null || echo unknown` -/usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null || echo unknown` -/bin/universe = `(/bin/universe) 2>/dev/null || echo unknown` - -_ASUNAME - -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - $as_echo "PATH: $as_dir" - done -IFS=$as_save_IFS - -} >&5 - -cat >&5 <<_ACEOF - - -## ----------- ## -## Core tests. ## -## ----------- ## - -_ACEOF - - -# Keep a trace of the command line. -# Strip out --no-create and --no-recursion so they do not pile up. -# Strip out --silent because we don't want to record it for future runs. -# Also quote any args containing shell meta-characters. -# Make two passes to allow for proper duplicate-argument suppression. -ac_configure_args= -ac_configure_args0= -ac_configure_args1= -ac_must_keep_next=false -for ac_pass in 1 2 -do - for ac_arg - do - case $ac_arg in - -no-create | --no-c* | -n | -no-recursion | --no-r*) continue ;; - -q | -quiet | --quiet | --quie | --qui | --qu | --q \ - | -silent | --silent | --silen | --sile | --sil) - continue ;; - *\'*) - ac_arg=`$as_echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;; - esac - case $ac_pass in - 1) as_fn_append ac_configure_args0 " '$ac_arg'" ;; - 2) - as_fn_append ac_configure_args1 " '$ac_arg'" - if test $ac_must_keep_next = true; then - ac_must_keep_next=false # Got value, back to normal. - else - case $ac_arg in - *=* | --config-cache | -C | -disable-* | --disable-* \ - | -enable-* | --enable-* | -gas | --g* | -nfp | --nf* \ - | -q | -quiet | --q* | -silent | --sil* | -v | -verb* \ - | -with-* | --with-* | -without-* | --without-* | --x) - case "$ac_configure_args0 " in - "$ac_configure_args1"*" '$ac_arg' "* ) continue ;; - esac - ;; - -* ) ac_must_keep_next=true ;; - esac - fi - as_fn_append ac_configure_args " '$ac_arg'" - ;; - esac - done -done -{ ac_configure_args0=; unset ac_configure_args0;} -{ ac_configure_args1=; unset ac_configure_args1;} - -# When interrupted or exit'd, cleanup temporary files, and complete -# config.log. We remove comments because anyway the quotes in there -# would cause problems or look ugly. -# WARNING: Use '\'' to represent an apostrophe within the trap. -# WARNING: Do not start the trap code with a newline, due to a FreeBSD 4.0 bug. -trap 'exit_status=$? - # Save into config.log some information that might help in debugging. - { - echo - - cat <<\_ASBOX -## ---------------- ## -## Cache variables. ## -## ---------------- ## -_ASBOX - echo - # The following way of writing the cache mishandles newlines in values, -( - for ac_var in `(set) 2>&1 | sed -n '\''s/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'\''`; do - eval ac_val=\$$ac_var - case $ac_val in #( - *${as_nl}*) - case $ac_var in #( - *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5 -$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; - esac - case $ac_var in #( - _ | IFS | as_nl) ;; #( - BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( - *) { eval $ac_var=; unset $ac_var;} ;; - esac ;; - esac - done - (set) 2>&1 | - case $as_nl`(ac_space='\'' '\''; set) 2>&1` in #( - *${as_nl}ac_space=\ *) - sed -n \ - "s/'\''/'\''\\\\'\'''\''/g; - s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\''\\2'\''/p" - ;; #( - *) - sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" - ;; - esac | - sort -) - echo - - cat <<\_ASBOX -## ----------------- ## -## Output variables. ## -## ----------------- ## -_ASBOX - echo - for ac_var in $ac_subst_vars - do - eval ac_val=\$$ac_var - case $ac_val in - *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; - esac - $as_echo "$ac_var='\''$ac_val'\''" - done | sort - echo - - if test -n "$ac_subst_files"; then - cat <<\_ASBOX -## ------------------- ## -## File substitutions. ## -## ------------------- ## -_ASBOX - echo - for ac_var in $ac_subst_files - do - eval ac_val=\$$ac_var - case $ac_val in - *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; - esac - $as_echo "$ac_var='\''$ac_val'\''" - done | sort - echo - fi - - if test -s confdefs.h; then - cat <<\_ASBOX -## ----------- ## -## confdefs.h. ## -## ----------- ## -_ASBOX - echo - cat confdefs.h - echo - fi - test "$ac_signal" != 0 && - $as_echo "$as_me: caught signal $ac_signal" - $as_echo "$as_me: exit $exit_status" - } >&5 - rm -f core *.core core.conftest.* && - rm -f -r conftest* confdefs* conf$$* $ac_clean_files && - exit $exit_status -' 0 -for ac_signal in 1 2 13 15; do - trap 'ac_signal='$ac_signal'; as_fn_exit 1' $ac_signal -done -ac_signal=0 - -# confdefs.h avoids OS command line length limits that DEFS can exceed. -rm -f -r conftest* confdefs.h - -$as_echo "/* confdefs.h */" > confdefs.h - -# Predefined preprocessor variables. - -cat >>confdefs.h <<_ACEOF -#define PACKAGE_NAME "$PACKAGE_NAME" -_ACEOF - -cat >>confdefs.h <<_ACEOF -#define PACKAGE_TARNAME "$PACKAGE_TARNAME" -_ACEOF - -cat >>confdefs.h <<_ACEOF -#define PACKAGE_VERSION "$PACKAGE_VERSION" -_ACEOF - -cat >>confdefs.h <<_ACEOF -#define PACKAGE_STRING "$PACKAGE_STRING" -_ACEOF - -cat >>confdefs.h <<_ACEOF -#define PACKAGE_BUGREPORT "$PACKAGE_BUGREPORT" -_ACEOF - -cat >>confdefs.h <<_ACEOF -#define PACKAGE_URL "$PACKAGE_URL" -_ACEOF - - -# Let the site file select an alternate cache file if it wants to. -# Prefer an explicitly selected file to automatically selected ones. -ac_site_file1=NONE -ac_site_file2=NONE -if test -n "$CONFIG_SITE"; then - ac_site_file1=$CONFIG_SITE -elif test "x$prefix" != xNONE; then - ac_site_file1=$prefix/share/config.site - ac_site_file2=$prefix/etc/config.site -else - ac_site_file1=$ac_default_prefix/share/config.site - ac_site_file2=$ac_default_prefix/etc/config.site -fi -for ac_site_file in "$ac_site_file1" "$ac_site_file2" -do - test "x$ac_site_file" = xNONE && continue - if test -r "$ac_site_file"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: loading site script $ac_site_file" >&5 -$as_echo "$as_me: loading site script $ac_site_file" >&6;} - sed 's/^/| /' "$ac_site_file" >&5 - . "$ac_site_file" - fi -done - -if test -r "$cache_file"; then - # Some versions of bash will fail to source /dev/null (special - # files actually), so we avoid doing that. - if test -f "$cache_file"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: loading cache $cache_file" >&5 -$as_echo "$as_me: loading cache $cache_file" >&6;} - case $cache_file in - [\\/]* | ?:[\\/]* ) . "$cache_file";; - *) . "./$cache_file";; - esac - fi -else - { $as_echo "$as_me:${as_lineno-$LINENO}: creating cache $cache_file" >&5 -$as_echo "$as_me: creating cache $cache_file" >&6;} - >$cache_file -fi - -# Check that the precious variables saved in the cache have kept the same -# value. -ac_cache_corrupted=false -for ac_var in $ac_precious_vars; do - eval ac_old_set=\$ac_cv_env_${ac_var}_set - eval ac_new_set=\$ac_env_${ac_var}_set - eval ac_old_val=\$ac_cv_env_${ac_var}_value - eval ac_new_val=\$ac_env_${ac_var}_value - case $ac_old_set,$ac_new_set in - set,) - { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5 -$as_echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;} - ac_cache_corrupted=: ;; - ,set) - { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was not set in the previous run" >&5 -$as_echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;} - ac_cache_corrupted=: ;; - ,);; - *) - if test "x$ac_old_val" != "x$ac_new_val"; then - # differences in whitespace do not lead to failure. - ac_old_val_w=`echo x $ac_old_val` - ac_new_val_w=`echo x $ac_new_val` - if test "$ac_old_val_w" != "$ac_new_val_w"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' has changed since the previous run:" >&5 -$as_echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;} - ac_cache_corrupted=: - else - { $as_echo "$as_me:${as_lineno-$LINENO}: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&5 -$as_echo "$as_me: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&2;} - eval $ac_var=\$ac_old_val - fi - { $as_echo "$as_me:${as_lineno-$LINENO}: former value: \`$ac_old_val'" >&5 -$as_echo "$as_me: former value: \`$ac_old_val'" >&2;} - { $as_echo "$as_me:${as_lineno-$LINENO}: current value: \`$ac_new_val'" >&5 -$as_echo "$as_me: current value: \`$ac_new_val'" >&2;} - fi;; - esac - # Pass precious variables to config.status. - if test "$ac_new_set" = set; then - case $ac_new_val in - *\'*) ac_arg=$ac_var=`$as_echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;; - *) ac_arg=$ac_var=$ac_new_val ;; - esac - case " $ac_configure_args " in - *" '$ac_arg' "*) ;; # Avoid dups. Use of quotes ensures accuracy. - *) as_fn_append ac_configure_args " '$ac_arg'" ;; - esac - fi -done -if $ac_cache_corrupted; then - { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 -$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} - { $as_echo "$as_me:${as_lineno-$LINENO}: error: changes in the environment can compromise the build" >&5 -$as_echo "$as_me: error: changes in the environment can compromise the build" >&2;} - as_fn_error "run \`make distclean' and/or \`rm $cache_file' and start over" "$LINENO" 5 -fi -## -------------------- ## -## Main body of script. ## -## -------------------- ## - -ac_ext=c -ac_cpp='$CPP $CPPFLAGS' -ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' -ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' -ac_compiler_gnu=$ac_cv_c_compiler_gnu - - - - -# Set version number -TOPC_VERSION=2.5.2 -TOPC_UPDATED="April, 2011" - -# Checks for programs. -ac_ext=c -ac_cpp='$CPP $CPPFLAGS' -ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' -ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' -ac_compiler_gnu=$ac_cv_c_compiler_gnu -if test -n "$ac_tool_prefix"; then - # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args. -set dummy ${ac_tool_prefix}gcc; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_CC+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -n "$CC"; then - ac_cv_prog_CC="$CC" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_CC="${ac_tool_prefix}gcc" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - -fi -fi -CC=$ac_cv_prog_CC -if test -n "$CC"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 -$as_echo "$CC" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - -fi -if test -z "$ac_cv_prog_CC"; then - ac_ct_CC=$CC - # Extract the first word of "gcc", so it can be a program name with args. -set dummy gcc; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_ac_ct_CC+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -n "$ac_ct_CC"; then - ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_ac_ct_CC="gcc" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - -fi -fi -ac_ct_CC=$ac_cv_prog_ac_ct_CC -if test -n "$ac_ct_CC"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 -$as_echo "$ac_ct_CC" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - if test "x$ac_ct_CC" = x; then - CC="" - else - case $cross_compiling:$ac_tool_warned in -yes:) -{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 -$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} -ac_tool_warned=yes ;; -esac - CC=$ac_ct_CC - fi -else - CC="$ac_cv_prog_CC" -fi - -if test -z "$CC"; then - if test -n "$ac_tool_prefix"; then - # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args. -set dummy ${ac_tool_prefix}cc; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_CC+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -n "$CC"; then - ac_cv_prog_CC="$CC" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_CC="${ac_tool_prefix}cc" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - -fi -fi -CC=$ac_cv_prog_CC -if test -n "$CC"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 -$as_echo "$CC" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - - fi -fi -if test -z "$CC"; then - # Extract the first word of "cc", so it can be a program name with args. -set dummy cc; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_CC+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -n "$CC"; then - ac_cv_prog_CC="$CC" # Let the user override the test. -else - ac_prog_rejected=no -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then - ac_prog_rejected=yes - continue - fi - ac_cv_prog_CC="cc" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - -if test $ac_prog_rejected = yes; then - # We found a bogon in the path, so make sure we never use it. - set dummy $ac_cv_prog_CC - shift - if test $# != 0; then - # We chose a different compiler from the bogus one. - # However, it has the same basename, so the bogon will be chosen - # first if we set CC to just the basename; use the full file name. - shift - ac_cv_prog_CC="$as_dir/$ac_word${1+' '}$@" - fi -fi -fi -fi -CC=$ac_cv_prog_CC -if test -n "$CC"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 -$as_echo "$CC" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - -fi -if test -z "$CC"; then - if test -n "$ac_tool_prefix"; then - for ac_prog in cl.exe - do - # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. -set dummy $ac_tool_prefix$ac_prog; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_CC+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -n "$CC"; then - ac_cv_prog_CC="$CC" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_CC="$ac_tool_prefix$ac_prog" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - -fi -fi -CC=$ac_cv_prog_CC -if test -n "$CC"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 -$as_echo "$CC" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - - test -n "$CC" && break - done -fi -if test -z "$CC"; then - ac_ct_CC=$CC - for ac_prog in cl.exe -do - # Extract the first word of "$ac_prog", so it can be a program name with args. -set dummy $ac_prog; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_ac_ct_CC+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -n "$ac_ct_CC"; then - ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_ac_ct_CC="$ac_prog" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - -fi -fi -ac_ct_CC=$ac_cv_prog_ac_ct_CC -if test -n "$ac_ct_CC"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 -$as_echo "$ac_ct_CC" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - - test -n "$ac_ct_CC" && break -done - - if test "x$ac_ct_CC" = x; then - CC="" - else - case $cross_compiling:$ac_tool_warned in -yes:) -{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 -$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} -ac_tool_warned=yes ;; -esac - CC=$ac_ct_CC - fi -fi - -fi - - -test -z "$CC" && { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 -$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -as_fn_error "no acceptable C compiler found in \$PATH -See \`config.log' for more details." "$LINENO" 5; } - -# Provide some information about the compiler. -$as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler version" >&5 -set X $ac_compile -ac_compiler=$2 -for ac_option in --version -v -V -qversion; do - { { ac_try="$ac_compiler $ac_option >&5" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" -$as_echo "$ac_try_echo"; } >&5 - (eval "$ac_compiler $ac_option >&5") 2>conftest.err - ac_status=$? - if test -s conftest.err; then - sed '10a\ -... rest of stderr output deleted ... - 10q' conftest.err >conftest.er1 - cat conftest.er1 >&5 - rm -f conftest.er1 conftest.err - fi - $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 - test $ac_status = 0; } -done - -cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -#include -int -main () -{ -FILE *f = fopen ("conftest.out", "w"); - return ferror (f) || fclose (f) != 0; - - ; - return 0; -} -_ACEOF -ac_clean_files_save=$ac_clean_files -ac_clean_files="$ac_clean_files a.out a.out.dSYM a.exe b.out conftest.out" -# Try to create an executable without -o first, disregard a.out. -# It will help us diagnose broken compilers, and finding out an intuition -# of exeext. -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler default output file name" >&5 -$as_echo_n "checking for C compiler default output file name... " >&6; } -ac_link_default=`$as_echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'` - -# The possible output files: -ac_files="a.out conftest.exe conftest a.exe a_out.exe b.out conftest.*" - -ac_rmfiles= -for ac_file in $ac_files -do - case $ac_file in - *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; - * ) ac_rmfiles="$ac_rmfiles $ac_file";; - esac -done -rm -f $ac_rmfiles - -if { { ac_try="$ac_link_default" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" -$as_echo "$ac_try_echo"; } >&5 - (eval "$ac_link_default") 2>&5 - ac_status=$? - $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 - test $ac_status = 0; }; then : - # Autoconf-2.13 could set the ac_cv_exeext variable to `no'. -# So ignore a value of `no', otherwise this would lead to `EXEEXT = no' -# in a Makefile. We should not override ac_cv_exeext if it was cached, -# so that the user can short-circuit this test for compilers unknown to -# Autoconf. -for ac_file in $ac_files '' -do - test -f "$ac_file" || continue - case $ac_file in - *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) - ;; - [ab].out ) - # We found the default executable, but exeext='' is most - # certainly right. - break;; - *.* ) - if test "${ac_cv_exeext+set}" = set && test "$ac_cv_exeext" != no; - then :; else - ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` - fi - # We set ac_cv_exeext here because the later test for it is not - # safe: cross compilers may not add the suffix if given an `-o' - # argument, so we may need to know it at that point already. - # Even if this section looks crufty: it has the advantage of - # actually working. - break;; - * ) - break;; - esac -done -test "$ac_cv_exeext" = no && ac_cv_exeext= - -else - ac_file='' -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_file" >&5 -$as_echo "$ac_file" >&6; } -if test -z "$ac_file"; then : - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 -$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -{ as_fn_set_status 77 -as_fn_error "C compiler cannot create executables -See \`config.log' for more details." "$LINENO" 5; }; } -fi -ac_exeext=$ac_cv_exeext - -# Check that the compiler produces executables we can run. If not, either -# the compiler is broken, or we cross compile. -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the C compiler works" >&5 -$as_echo_n "checking whether the C compiler works... " >&6; } -# If not cross compiling, check that we can run a simple program. -if test "$cross_compiling" != yes; then - if { ac_try='./$ac_file' - { { case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" -$as_echo "$ac_try_echo"; } >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 - test $ac_status = 0; }; }; then - cross_compiling=no - else - if test "$cross_compiling" = maybe; then - cross_compiling=yes - else - { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 -$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -as_fn_error "cannot run C compiled programs. -If you meant to cross compile, use \`--host'. -See \`config.log' for more details." "$LINENO" 5; } - fi - fi -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 -$as_echo "yes" >&6; } - -rm -f -r a.out a.out.dSYM a.exe conftest$ac_cv_exeext b.out conftest.out -ac_clean_files=$ac_clean_files_save -# Check that the compiler produces executables we can run. If not, either -# the compiler is broken, or we cross compile. -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are cross compiling" >&5 -$as_echo_n "checking whether we are cross compiling... " >&6; } -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $cross_compiling" >&5 -$as_echo "$cross_compiling" >&6; } - -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of executables" >&5 -$as_echo_n "checking for suffix of executables... " >&6; } -if { { ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" -$as_echo "$ac_try_echo"; } >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 - test $ac_status = 0; }; then : - # If both `conftest.exe' and `conftest' are `present' (well, observable) -# catch `conftest.exe'. For instance with Cygwin, `ls conftest' will -# work properly (i.e., refer to `conftest.exe'), while it won't with -# `rm'. -for ac_file in conftest.exe conftest conftest.*; do - test -f "$ac_file" || continue - case $ac_file in - *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; - *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` - break;; - * ) break;; - esac -done -else - { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 -$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -as_fn_error "cannot compute suffix of executables: cannot compile and link -See \`config.log' for more details." "$LINENO" 5; } -fi -rm -f conftest$ac_cv_exeext -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_exeext" >&5 -$as_echo "$ac_cv_exeext" >&6; } - -rm -f conftest.$ac_ext -EXEEXT=$ac_cv_exeext -ac_exeext=$EXEEXT -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of object files" >&5 -$as_echo_n "checking for suffix of object files... " >&6; } -if test "${ac_cv_objext+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -int -main () -{ - - ; - return 0; -} -_ACEOF -rm -f conftest.o conftest.obj -if { { ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" -$as_echo "$ac_try_echo"; } >&5 - (eval "$ac_compile") 2>&5 - ac_status=$? - $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 - test $ac_status = 0; }; then : - for ac_file in conftest.o conftest.obj conftest.*; do - test -f "$ac_file" || continue; - case $ac_file in - *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM ) ;; - *) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'` - break;; - esac -done -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 -$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -as_fn_error "cannot compute suffix of object files: cannot compile -See \`config.log' for more details." "$LINENO" 5; } -fi -rm -f conftest.$ac_cv_objext conftest.$ac_ext -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_objext" >&5 -$as_echo "$ac_cv_objext" >&6; } -OBJEXT=$ac_cv_objext -ac_objext=$OBJEXT -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C compiler" >&5 -$as_echo_n "checking whether we are using the GNU C compiler... " >&6; } -if test "${ac_cv_c_compiler_gnu+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -int -main () -{ -#ifndef __GNUC__ - choke me -#endif - - ; - return 0; -} -_ACEOF -if ac_fn_c_try_compile "$LINENO"; then : - ac_compiler_gnu=yes -else - ac_compiler_gnu=no -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -ac_cv_c_compiler_gnu=$ac_compiler_gnu - -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_compiler_gnu" >&5 -$as_echo "$ac_cv_c_compiler_gnu" >&6; } -if test $ac_compiler_gnu = yes; then - GCC=yes -else - GCC= -fi -ac_test_CFLAGS=${CFLAGS+set} -ac_save_CFLAGS=$CFLAGS -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -g" >&5 -$as_echo_n "checking whether $CC accepts -g... " >&6; } -if test "${ac_cv_prog_cc_g+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - ac_save_c_werror_flag=$ac_c_werror_flag - ac_c_werror_flag=yes - ac_cv_prog_cc_g=no - CFLAGS="-g" - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -int -main () -{ - - ; - return 0; -} -_ACEOF -if ac_fn_c_try_compile "$LINENO"; then : - ac_cv_prog_cc_g=yes -else - CFLAGS="" - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -int -main () -{ - - ; - return 0; -} -_ACEOF -if ac_fn_c_try_compile "$LINENO"; then : - -else - ac_c_werror_flag=$ac_save_c_werror_flag - CFLAGS="-g" - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -int -main () -{ - - ; - return 0; -} -_ACEOF -if ac_fn_c_try_compile "$LINENO"; then : - ac_cv_prog_cc_g=yes -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - ac_c_werror_flag=$ac_save_c_werror_flag -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_g" >&5 -$as_echo "$ac_cv_prog_cc_g" >&6; } -if test "$ac_test_CFLAGS" = set; then - CFLAGS=$ac_save_CFLAGS -elif test $ac_cv_prog_cc_g = yes; then - if test "$GCC" = yes; then - CFLAGS="-g -O2" - else - CFLAGS="-g" - fi -else - if test "$GCC" = yes; then - CFLAGS="-O2" - else - CFLAGS= - fi -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $CC option to accept ISO C89" >&5 -$as_echo_n "checking for $CC option to accept ISO C89... " >&6; } -if test "${ac_cv_prog_cc_c89+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - ac_cv_prog_cc_c89=no -ac_save_CC=$CC -cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -#include -#include -#include -#include -/* Most of the following tests are stolen from RCS 5.7's src/conf.sh. */ -struct buf { int x; }; -FILE * (*rcsopen) (struct buf *, struct stat *, int); -static char *e (p, i) - char **p; - int i; -{ - return p[i]; -} -static char *f (char * (*g) (char **, int), char **p, ...) -{ - char *s; - va_list v; - va_start (v,p); - s = g (p, va_arg (v,int)); - va_end (v); - return s; -} - -/* OSF 4.0 Compaq cc is some sort of almost-ANSI by default. It has - function prototypes and stuff, but not '\xHH' hex character constants. - These don't provoke an error unfortunately, instead are silently treated - as 'x'. The following induces an error, until -std is added to get - proper ANSI mode. Curiously '\x00'!='x' always comes out true, for an - array size at least. It's necessary to write '\x00'==0 to get something - that's true only with -std. */ -int osf4_cc_array ['\x00' == 0 ? 1 : -1]; - -/* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters - inside strings and character constants. */ -#define FOO(x) 'x' -int xlc6_cc_array[FOO(a) == 'x' ? 1 : -1]; - -int test (int i, double x); -struct s1 {int (*f) (int a);}; -struct s2 {int (*f) (double a);}; -int pairnames (int, char **, FILE *(*)(struct buf *, struct stat *, int), int, int); -int argc; -char **argv; -int -main () -{ -return f (e, argv, 0) != argv[0] || f (e, argv, 1) != argv[1]; - ; - return 0; -} -_ACEOF -for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std \ - -Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__" -do - CC="$ac_save_CC $ac_arg" - if ac_fn_c_try_compile "$LINENO"; then : - ac_cv_prog_cc_c89=$ac_arg -fi -rm -f core conftest.err conftest.$ac_objext - test "x$ac_cv_prog_cc_c89" != "xno" && break -done -rm -f conftest.$ac_ext -CC=$ac_save_CC - -fi -# AC_CACHE_VAL -case "x$ac_cv_prog_cc_c89" in - x) - { $as_echo "$as_me:${as_lineno-$LINENO}: result: none needed" >&5 -$as_echo "none needed" >&6; } ;; - xno) - { $as_echo "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5 -$as_echo "unsupported" >&6; } ;; - *) - CC="$CC $ac_cv_prog_cc_c89" - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c89" >&5 -$as_echo "$ac_cv_prog_cc_c89" >&6; } ;; -esac -if test "x$ac_cv_prog_cc_c89" != xno; then : - -fi - -ac_ext=c -ac_cpp='$CPP $CPPFLAGS' -ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' -ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' -ac_compiler_gnu=$ac_cv_c_compiler_gnu - -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether ln -s works" >&5 -$as_echo_n "checking whether ln -s works... " >&6; } -LN_S=$as_ln_s -if test "$LN_S" = "ln -s"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 -$as_echo "yes" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no, using $LN_S" >&5 -$as_echo "no, using $LN_S" >&6; } -fi - -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether ${MAKE-make} sets \$(MAKE)" >&5 -$as_echo_n "checking whether ${MAKE-make} sets \$(MAKE)... " >&6; } -set x ${MAKE-make} -ac_make=`$as_echo "$2" | sed 's/+/p/g; s/[^a-zA-Z0-9_]/_/g'` -if { as_var=ac_cv_prog_make_${ac_make}_set; eval "test \"\${$as_var+set}\" = set"; }; then : - $as_echo_n "(cached) " >&6 -else - cat >conftest.make <<\_ACEOF -SHELL = /bin/sh -all: - @echo '@@@%%%=$(MAKE)=@@@%%%' -_ACEOF -# GNU make sometimes prints "make[1]: Entering...", which would confuse us. -case `${MAKE-make} -f conftest.make 2>/dev/null` in - *@@@%%%=?*=@@@%%%*) - eval ac_cv_prog_make_${ac_make}_set=yes;; - *) - eval ac_cv_prog_make_${ac_make}_set=no;; -esac -rm -f conftest.make -fi -if eval test \$ac_cv_prog_make_${ac_make}_set = yes; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 -$as_echo "yes" >&6; } - SET_MAKE= -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } - SET_MAKE="MAKE=${MAKE-make}" -fi - -if test -n "$ac_tool_prefix"; then - # Extract the first word of "${ac_tool_prefix}ranlib", so it can be a program name with args. -set dummy ${ac_tool_prefix}ranlib; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_RANLIB+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -n "$RANLIB"; then - ac_cv_prog_RANLIB="$RANLIB" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_RANLIB="${ac_tool_prefix}ranlib" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - -fi -fi -RANLIB=$ac_cv_prog_RANLIB -if test -n "$RANLIB"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $RANLIB" >&5 -$as_echo "$RANLIB" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - -fi -if test -z "$ac_cv_prog_RANLIB"; then - ac_ct_RANLIB=$RANLIB - # Extract the first word of "ranlib", so it can be a program name with args. -set dummy ranlib; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_ac_ct_RANLIB+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -n "$ac_ct_RANLIB"; then - ac_cv_prog_ac_ct_RANLIB="$ac_ct_RANLIB" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_ac_ct_RANLIB="ranlib" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - -fi -fi -ac_ct_RANLIB=$ac_cv_prog_ac_ct_RANLIB -if test -n "$ac_ct_RANLIB"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_RANLIB" >&5 -$as_echo "$ac_ct_RANLIB" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - if test "x$ac_ct_RANLIB" = x; then - RANLIB=":" - else - case $cross_compiling:$ac_tool_warned in -yes:) -{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 -$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} -ac_tool_warned=yes ;; -esac - RANLIB=$ac_ct_RANLIB - fi -else - RANLIB="$ac_cv_prog_RANLIB" -fi - - -# Mostly for Solaris: -# libxnet is a small subset. If functions still missing, add other libs. -# Note that last libraries added to $LIBS appears as first one. -ac_fn_c_check_func "$LINENO" "connect" "ac_cv_func_connect" -if test "x$ac_cv_func_connect" = x""yes; then : - -else - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for connect in -lxnet" >&5 -$as_echo_n "checking for connect in -lxnet... " >&6; } -if test "${ac_cv_lib_xnet_connect+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lxnet $LIBS" - - -# ac_fn_c_try_link LINENO -# ----------------------- -# Try to link conftest.$ac_ext, and return whether this succeeded. -ac_fn_c_try_link () -{ - as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack - rm -f conftest.$ac_objext conftest$ac_exeext - if { { ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" -$as_echo "$ac_try_echo"; } >&5 - (eval "$ac_link") 2>conftest.err - ac_status=$? - if test -s conftest.err; then - grep -v '^ *+' conftest.err >conftest.er1 - cat conftest.er1 >&5 - mv -f conftest.er1 conftest.err - fi - $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 - test $ac_status = 0; } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then : - ac_retval=0 -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_retval=1 -fi - # Delete the IPA/IPO (Inter Procedural Analysis/Optimization) information - # created by the PGI compiler (conftest_ipa8_conftest.oo), as it would - # interfere with the next link command; also delete a directory that is - # left behind by Apple's compiler. We do this before executing the actions. - rm -rf conftest.dSYM conftest_ipa8_conftest.oo - eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} - return $ac_retval - -} # ac_fn_c_try_link -cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char connect (); -int -main () -{ -return connect (); - ; - return 0; -} -_ACEOF -if ac_fn_c_try_link "$LINENO"; then : - ac_cv_lib_xnet_connect=yes -else - ac_cv_lib_xnet_connect=no -fi -rm -f core conftest.err conftest.$ac_objext \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_xnet_connect" >&5 -$as_echo "$ac_cv_lib_xnet_connect" >&6; } -if test "x$ac_cv_lib_xnet_connect" = x""yes; then : - cat >>confdefs.h <<_ACEOF -#define HAVE_LIBXNET 1 -_ACEOF - - LIBS="-lxnet $LIBS" - -fi - -fi - -ac_fn_c_check_func "$LINENO" "socket" "ac_cv_func_socket" -if test "x$ac_cv_func_socket" = x""yes; then : - -else - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for socket in -lsocket" >&5 -$as_echo_n "checking for socket in -lsocket... " >&6; } -if test "${ac_cv_lib_socket_socket+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lsocket $LIBS" -cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char socket (); -int -main () -{ -return socket (); - ; - return 0; -} -_ACEOF -if ac_fn_c_try_link "$LINENO"; then : - ac_cv_lib_socket_socket=yes -else - ac_cv_lib_socket_socket=no -fi -rm -f core conftest.err conftest.$ac_objext \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_socket_socket" >&5 -$as_echo "$ac_cv_lib_socket_socket" >&6; } -if test "x$ac_cv_lib_socket_socket" = x""yes; then : - cat >>confdefs.h <<_ACEOF -#define HAVE_LIBSOCKET 1 -_ACEOF - - LIBS="-lsocket $LIBS" - -fi - -fi - -ac_fn_c_check_func "$LINENO" "gethostbyname" "ac_cv_func_gethostbyname" -if test "x$ac_cv_func_gethostbyname" = x""yes; then : - -else - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for gethostbyname in -lnsl" >&5 -$as_echo_n "checking for gethostbyname in -lnsl... " >&6; } -if test "${ac_cv_lib_nsl_gethostbyname+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lnsl $LIBS" -cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char gethostbyname (); -int -main () -{ -return gethostbyname (); - ; - return 0; -} -_ACEOF -if ac_fn_c_try_link "$LINENO"; then : - ac_cv_lib_nsl_gethostbyname=yes -else - ac_cv_lib_nsl_gethostbyname=no -fi -rm -f core conftest.err conftest.$ac_objext \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_nsl_gethostbyname" >&5 -$as_echo "$ac_cv_lib_nsl_gethostbyname" >&6; } -if test "x$ac_cv_lib_nsl_gethostbyname" = x""yes; then : - cat >>confdefs.h <<_ACEOF -#define HAVE_LIBNSL 1 -_ACEOF - - LIBS="-lnsl $LIBS" - -fi - -fi - -LIBSFORSOCKETS="$LIBS" -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for malloc in -lefence" >&5 -$as_echo_n "checking for malloc in -lefence... " >&6; } -if test "${ac_cv_lib_efence_malloc+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lefence $LIBS" -cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char malloc (); -int -main () -{ -return malloc (); - ; - return 0; -} -_ACEOF -if ac_fn_c_try_link "$LINENO"; then : - ac_cv_lib_efence_malloc=yes -else - ac_cv_lib_efence_malloc=no -fi -rm -f core conftest.err conftest.$ac_objext \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_efence_malloc" >&5 -$as_echo "$ac_cv_lib_efence_malloc" >&6; } -if test "x$ac_cv_lib_efence_malloc" = x""yes; then : - LIBEFENCE=-lefence -else - LIBEFENCE= -fi - -LIBS= -ac_fn_c_check_func "$LINENO" "nanosleep" "ac_cv_func_nanosleep" -if test "x$ac_cv_func_nanosleep" = x""yes; then : - -else - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for nanosleep in -lrt" >&5 -$as_echo_n "checking for nanosleep in -lrt... " >&6; } -if test "${ac_cv_lib_rt_nanosleep+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lrt $LIBS" -cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char nanosleep (); -int -main () -{ -return nanosleep (); - ; - return 0; -} -_ACEOF -if ac_fn_c_try_link "$LINENO"; then : - ac_cv_lib_rt_nanosleep=yes -else - ac_cv_lib_rt_nanosleep=no -fi -rm -f core conftest.err conftest.$ac_objext \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_rt_nanosleep" >&5 -$as_echo "$ac_cv_lib_rt_nanosleep" >&6; } -if test "x$ac_cv_lib_rt_nanosleep" = x""yes; then : - cat >>confdefs.h <<_ACEOF -#define HAVE_LIBRT 1 -_ACEOF - - LIBS="-lrt $LIBS" - -fi - -fi - -LIBSFORSLEEP="$LIBS" -LIBS= - -LIBSFORMPI="$LIBSFORSLEEP" -LIBSFORPTHREAD="$LIBSFORSLEEP" -LIBSFORSEQ="$LIBSFORSLEEP" - -# Check whether --enable-cxx was given. -if test "${enable_cxx+set}" = set; then : - enableval=$enable_cxx; -else - enable_cxx=yes -fi - -if test "x$enable_cxx" = "xyes"; then - ac_ext=cpp -ac_cpp='$CXXCPP $CPPFLAGS' -ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5' -ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' -ac_compiler_gnu=$ac_cv_cxx_compiler_gnu -if test -z "$CXX"; then - if test -n "$CCC"; then - CXX=$CCC - else - if test -n "$ac_tool_prefix"; then - for ac_prog in g++ c++ gpp aCC CC cxx cc++ cl.exe FCC KCC RCC xlC_r xlC - do - # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. -set dummy $ac_tool_prefix$ac_prog; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_CXX+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -n "$CXX"; then - ac_cv_prog_CXX="$CXX" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_CXX="$ac_tool_prefix$ac_prog" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - -fi -fi -CXX=$ac_cv_prog_CXX -if test -n "$CXX"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CXX" >&5 -$as_echo "$CXX" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - - test -n "$CXX" && break - done -fi -if test -z "$CXX"; then - ac_ct_CXX=$CXX - for ac_prog in g++ c++ gpp aCC CC cxx cc++ cl.exe FCC KCC RCC xlC_r xlC -do - # Extract the first word of "$ac_prog", so it can be a program name with args. -set dummy $ac_prog; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_ac_ct_CXX+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -n "$ac_ct_CXX"; then - ac_cv_prog_ac_ct_CXX="$ac_ct_CXX" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_ac_ct_CXX="$ac_prog" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - -fi -fi -ac_ct_CXX=$ac_cv_prog_ac_ct_CXX -if test -n "$ac_ct_CXX"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CXX" >&5 -$as_echo "$ac_ct_CXX" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - - test -n "$ac_ct_CXX" && break -done - - if test "x$ac_ct_CXX" = x; then - CXX="g++" - else - case $cross_compiling:$ac_tool_warned in -yes:) -{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 -$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} -ac_tool_warned=yes ;; -esac - CXX=$ac_ct_CXX - fi -fi - - fi -fi -# Provide some information about the compiler. -$as_echo "$as_me:${as_lineno-$LINENO}: checking for C++ compiler version" >&5 -set X $ac_compile -ac_compiler=$2 -for ac_option in --version -v -V -qversion; do - { { ac_try="$ac_compiler $ac_option >&5" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" -$as_echo "$ac_try_echo"; } >&5 - (eval "$ac_compiler $ac_option >&5") 2>conftest.err - ac_status=$? - if test -s conftest.err; then - sed '10a\ -... rest of stderr output deleted ... - 10q' conftest.err >conftest.er1 - cat conftest.er1 >&5 - rm -f conftest.er1 conftest.err - fi - $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 - test $ac_status = 0; } -done - -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C++ compiler" >&5 -$as_echo_n "checking whether we are using the GNU C++ compiler... " >&6; } -if test "${ac_cv_cxx_compiler_gnu+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -int -main () -{ -#ifndef __GNUC__ - choke me -#endif - - ; - return 0; -} -_ACEOF -if ac_fn_cxx_try_compile "$LINENO"; then : - ac_compiler_gnu=yes -else - ac_compiler_gnu=no -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -ac_cv_cxx_compiler_gnu=$ac_compiler_gnu - -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_cxx_compiler_gnu" >&5 -$as_echo "$ac_cv_cxx_compiler_gnu" >&6; } -if test $ac_compiler_gnu = yes; then - GXX=yes -else - GXX= -fi -ac_test_CXXFLAGS=${CXXFLAGS+set} -ac_save_CXXFLAGS=$CXXFLAGS -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CXX accepts -g" >&5 -$as_echo_n "checking whether $CXX accepts -g... " >&6; } -if test "${ac_cv_prog_cxx_g+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - ac_save_cxx_werror_flag=$ac_cxx_werror_flag - ac_cxx_werror_flag=yes - ac_cv_prog_cxx_g=no - CXXFLAGS="-g" - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -int -main () -{ - - ; - return 0; -} -_ACEOF -if ac_fn_cxx_try_compile "$LINENO"; then : - ac_cv_prog_cxx_g=yes -else - CXXFLAGS="" - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -int -main () -{ - - ; - return 0; -} -_ACEOF -if ac_fn_cxx_try_compile "$LINENO"; then : - -else - ac_cxx_werror_flag=$ac_save_cxx_werror_flag - CXXFLAGS="-g" - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -int -main () -{ - - ; - return 0; -} -_ACEOF -if ac_fn_cxx_try_compile "$LINENO"; then : - ac_cv_prog_cxx_g=yes -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - ac_cxx_werror_flag=$ac_save_cxx_werror_flag -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cxx_g" >&5 -$as_echo "$ac_cv_prog_cxx_g" >&6; } -if test "$ac_test_CXXFLAGS" = set; then - CXXFLAGS=$ac_save_CXXFLAGS -elif test $ac_cv_prog_cxx_g = yes; then - if test "$GXX" = yes; then - CXXFLAGS="-g -O2" - else - CXXFLAGS="-g" - fi -else - if test "$GXX" = yes; then - CXXFLAGS="-O2" - else - CXXFLAGS= - fi -fi -ac_ext=c -ac_cpp='$CPP $CPPFLAGS' -ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' -ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' -ac_compiler_gnu=$ac_cv_c_compiler_gnu - -fi - -# Check whether --enable-posix-1c-threads was given. -if test "${enable_posix_1c_threads+set}" = set; then : - enableval=$enable_posix_1c_threads; -else - enable_posix_1c_threads=no -fi - -if test "x$enable_posix_1c_threads" = "xyes"; then - CFLAGS_FOR_POSIX_1C="-D_POSIX_C_SOURCE=199506L" -fi - -# Check whether --enable-pthread was given. -if test "${enable_pthread+set}" = set; then : - enableval=$enable_pthread; -else - enable_pthread=yes -fi - - -if test "x$enable_pthread" = "xyes"; then - # AC_CHECK_HEADER(pthread.h) - # This call adds -lpthread to LIBS - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for pthread_create in -lpthread" >&5 -$as_echo_n "checking for pthread_create in -lpthread... " >&6; } -if test "${ac_cv_lib_pthread_pthread_create+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lpthread $LIBS" -cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char pthread_create (); -int -main () -{ -return pthread_create (); - ; - return 0; -} -_ACEOF -if ac_fn_c_try_link "$LINENO"; then : - ac_cv_lib_pthread_pthread_create=yes -else - ac_cv_lib_pthread_pthread_create=no -fi -rm -f core conftest.err conftest.$ac_objext \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_pthread_pthread_create" >&5 -$as_echo "$ac_cv_lib_pthread_pthread_create" >&6; } -if test "x$ac_cv_lib_pthread_pthread_create" = x""yes; then : - cat >>confdefs.h <<_ACEOF -#define HAVE_LIBPTHREAD 1 -_ACEOF - - LIBS="-lpthread $LIBS" - -fi - - # We temporarily add "-lpthread" because AC_CHECK_LIB fails to find it - # on Alpha: OSF1-4.0 fails to find it. - # __pthread_create in: /usr/shlib/libpthread.so - # and pthread.h redefines pthread_create to __pthread_create - # and declare return type as int. This conflicts with char return - # type declared in AC_CHECK_LIB. - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for working pthread library" >&5 -$as_echo_n "checking for working pthread library... " >&6; } - ac_save_LIBS="$LIBS" - LIBS="-lpthread $LIBS" - if test "$cross_compiling" = yes; then : - HAVE_PTHREAD=no -else - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -#include - int main() { - pthread_mutex_t mutex; if(0 != pthread_mutex_init(&mutex, NULL)) exit(1); - return(0); } - -_ACEOF -if ac_fn_c_try_run "$LINENO"; then : - HAVE_PTHREAD=yes -else - HAVE_PTHREAD=no -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ - conftest.$ac_objext conftest.beam conftest.$ac_ext -fi - - - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $HAVE_PTHREAD" >&5 -$as_echo "$HAVE_PTHREAD" >&6; } - LIBS="$ac_save_LIBS" - LIBPTHREAD="$LIBS" - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for sem_init in -lposix4" >&5 -$as_echo_n "checking for sem_init in -lposix4... " >&6; } -if test "${ac_cv_lib_posix4_sem_init+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lposix4 $LIBS" -cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char sem_init (); -int -main () -{ -return sem_init (); - ; - return 0; -} -_ACEOF -if ac_fn_c_try_link "$LINENO"; then : - ac_cv_lib_posix4_sem_init=yes -else - ac_cv_lib_posix4_sem_init=no -fi -rm -f core conftest.err conftest.$ac_objext \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_posix4_sem_init" >&5 -$as_echo "$ac_cv_lib_posix4_sem_init" >&6; } -if test "x$ac_cv_lib_posix4_sem_init" = x""yes; then : - cat >>confdefs.h <<_ACEOF -#define HAVE_LIBPOSIX4 1 -_ACEOF - - LIBS="-lposix4 $LIBS" - -fi - - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for working semaphore library" >&5 -$as_echo_n "checking for working semaphore library... " >&6; } - if test "$cross_compiling" = yes; then : - HAVE_SEMAPHORE=no -else - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -#include - int main() { sem_t sem; if(0 != sem_init(&sem, 0, 0)) exit(1); - return(0); } - -_ACEOF -if ac_fn_c_try_run "$LINENO"; then : - HAVE_SEMAPHORE=yes -else - HAVE_SEMAPHORE=no -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ - conftest.$ac_objext conftest.beam conftest.$ac_ext -fi - - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $HAVE_SEMAPHORE" >&5 -$as_echo "$HAVE_SEMAPHORE" >&6; } - LIBSFORPTHREAD="$LIBS $LIBSFORPTHREAD" -else - HAVE_PTHREAD=no -fi - -# LIBS="$LIBSFORSOCKETS $LIBSFORPTHREAD" - -# Check whether --enable-strip-libs was given. -if test "${enable_strip_libs+set}" = set; then : - enableval=$enable_strip_libs; -else - enable_strip_libs=no -fi - - -if test "x$enable_strip_libs" = "xyes"; then - STRIP_LIBS=yes - STRIP=strip -else - STRIP=: -fi - - -# Check whether --with-mpi-cc was given. -if test "${with_mpi_cc+set}" = set; then : - withval=$with_mpi_cc; -else - with_mpi_cc=no -fi - - -# Check whether --with-mpi-cxx was given. -if test "${with_mpi_cxx+set}" = set; then : - withval=$with_mpi_cxx; -else - with_mpi_cxx=no -fi - -if test "x$with_mpi_cxx" = "xno"; then - MPICXX='$'{CXX} -else - MPICXX="$with_mpi_cxx" -fi -if test "x$with_mpi_cc" = "xno"; then - libmpi="-lmpinu" - MPICC='$'{CC} -else - HAVE_MPI_H=1 -# AC_DEFINE(HAVE_MPI_H) [Do it below, after resetting DEFS) - MPICC="$with_mpi_cc" -fi -LIBSFORMPI="$libmpi $LIBSFORSOCKETS $LIBSFORMPI" -# topc-config.in: --mpi) -# Note that with_mpi_cc != no means libmpi="". -# This is the right thing if using ${MPICC} -# Maybe we should have undocumented --mpi-internal returning this, -# which is called from topcc.in and topc++.in, -# while --mpi should indicate problem and: exit 1 -# # Do all of this for MPICXX also - -# Checks for header files. -ac_ext=c -ac_cpp='$CPP $CPPFLAGS' -ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' -ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' -ac_compiler_gnu=$ac_cv_c_compiler_gnu -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to run the C preprocessor" >&5 -$as_echo_n "checking how to run the C preprocessor... " >&6; } -# On Suns, sometimes $CPP names a directory. -if test -n "$CPP" && test -d "$CPP"; then - CPP= -fi -if test -z "$CPP"; then - if test "${ac_cv_prog_CPP+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - # Double quotes because CPP needs to be expanded - for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp" - do - ac_preproc_ok=false -for ac_c_preproc_warn_flag in '' yes -do - # Use a header file that comes with gcc, so configuring glibc - # with a fresh cross-compiler works. - # Prefer to if __STDC__ is defined, since - # exists even on freestanding compilers. - # On the NeXT, cc -E runs the code through the compiler's parser, - # not just through cpp. "Syntax error" is here to catch this case. - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -#ifdef __STDC__ -# include -#else -# include -#endif - Syntax error -_ACEOF -if ac_fn_c_try_cpp "$LINENO"; then : - -else - # Broken: fails on valid input. -continue -fi -rm -f conftest.err conftest.$ac_ext - - # OK, works on sane cases. Now check whether nonexistent headers - # can be detected and how. - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -#include -_ACEOF -if ac_fn_c_try_cpp "$LINENO"; then : - # Broken: success on invalid input. -continue -else - # Passes both tests. -ac_preproc_ok=: -break -fi -rm -f conftest.err conftest.$ac_ext - -done -# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. -rm -f conftest.err conftest.$ac_ext -if $ac_preproc_ok; then : - break -fi - - done - ac_cv_prog_CPP=$CPP - -fi - CPP=$ac_cv_prog_CPP -else - ac_cv_prog_CPP=$CPP -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $CPP" >&5 -$as_echo "$CPP" >&6; } -ac_preproc_ok=false -for ac_c_preproc_warn_flag in '' yes -do - # Use a header file that comes with gcc, so configuring glibc - # with a fresh cross-compiler works. - # Prefer to if __STDC__ is defined, since - # exists even on freestanding compilers. - # On the NeXT, cc -E runs the code through the compiler's parser, - # not just through cpp. "Syntax error" is here to catch this case. - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -#ifdef __STDC__ -# include -#else -# include -#endif - Syntax error -_ACEOF -if ac_fn_c_try_cpp "$LINENO"; then : - -else - # Broken: fails on valid input. -continue -fi -rm -f conftest.err conftest.$ac_ext - - # OK, works on sane cases. Now check whether nonexistent headers - # can be detected and how. - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -#include -_ACEOF -if ac_fn_c_try_cpp "$LINENO"; then : - # Broken: success on invalid input. -continue -else - # Passes both tests. -ac_preproc_ok=: -break -fi -rm -f conftest.err conftest.$ac_ext - -done -# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. -rm -f conftest.err conftest.$ac_ext -if $ac_preproc_ok; then : - -else - { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 -$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -as_fn_error "C preprocessor \"$CPP\" fails sanity check -See \`config.log' for more details." "$LINENO" 5; } -fi - -ac_ext=c -ac_cpp='$CPP $CPPFLAGS' -ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' -ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' -ac_compiler_gnu=$ac_cv_c_compiler_gnu - - -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for grep that handles long lines and -e" >&5 -$as_echo_n "checking for grep that handles long lines and -e... " >&6; } -if test "${ac_cv_path_GREP+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -z "$GREP"; then - ac_path_GREP_found=false - # Loop through the user's path and test for each of PROGNAME-LIST - as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_prog in grep ggrep; do - for ac_exec_ext in '' $ac_executable_extensions; do - ac_path_GREP="$as_dir/$ac_prog$ac_exec_ext" - { test -f "$ac_path_GREP" && $as_test_x "$ac_path_GREP"; } || continue -# Check for GNU ac_path_GREP and select it if it is found. - # Check for GNU $ac_path_GREP -case `"$ac_path_GREP" --version 2>&1` in -*GNU*) - ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_found=:;; -*) - ac_count=0 - $as_echo_n 0123456789 >"conftest.in" - while : - do - cat "conftest.in" "conftest.in" >"conftest.tmp" - mv "conftest.tmp" "conftest.in" - cp "conftest.in" "conftest.nl" - $as_echo 'GREP' >> "conftest.nl" - "$ac_path_GREP" -e 'GREP$' -e '-(cannot match)-' < "conftest.nl" >"conftest.out" 2>/dev/null || break - diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break - as_fn_arith $ac_count + 1 && ac_count=$as_val - if test $ac_count -gt ${ac_path_GREP_max-0}; then - # Best one so far, save it but keep looking for a better one - ac_cv_path_GREP="$ac_path_GREP" - ac_path_GREP_max=$ac_count - fi - # 10*(2^10) chars as input seems more than enough - test $ac_count -gt 10 && break - done - rm -f conftest.in conftest.tmp conftest.nl conftest.out;; -esac - - $ac_path_GREP_found && break 3 - done - done - done -IFS=$as_save_IFS - if test -z "$ac_cv_path_GREP"; then - as_fn_error "no acceptable grep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 - fi -else - ac_cv_path_GREP=$GREP -fi - -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_GREP" >&5 -$as_echo "$ac_cv_path_GREP" >&6; } - GREP="$ac_cv_path_GREP" - - -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for egrep" >&5 -$as_echo_n "checking for egrep... " >&6; } -if test "${ac_cv_path_EGREP+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if echo a | $GREP -E '(a|b)' >/dev/null 2>&1 - then ac_cv_path_EGREP="$GREP -E" - else - if test -z "$EGREP"; then - ac_path_EGREP_found=false - # Loop through the user's path and test for each of PROGNAME-LIST - as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_prog in egrep; do - for ac_exec_ext in '' $ac_executable_extensions; do - ac_path_EGREP="$as_dir/$ac_prog$ac_exec_ext" - { test -f "$ac_path_EGREP" && $as_test_x "$ac_path_EGREP"; } || continue -# Check for GNU ac_path_EGREP and select it if it is found. - # Check for GNU $ac_path_EGREP -case `"$ac_path_EGREP" --version 2>&1` in -*GNU*) - ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_found=:;; -*) - ac_count=0 - $as_echo_n 0123456789 >"conftest.in" - while : - do - cat "conftest.in" "conftest.in" >"conftest.tmp" - mv "conftest.tmp" "conftest.in" - cp "conftest.in" "conftest.nl" - $as_echo 'EGREP' >> "conftest.nl" - "$ac_path_EGREP" 'EGREP$' < "conftest.nl" >"conftest.out" 2>/dev/null || break - diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break - as_fn_arith $ac_count + 1 && ac_count=$as_val - if test $ac_count -gt ${ac_path_EGREP_max-0}; then - # Best one so far, save it but keep looking for a better one - ac_cv_path_EGREP="$ac_path_EGREP" - ac_path_EGREP_max=$ac_count - fi - # 10*(2^10) chars as input seems more than enough - test $ac_count -gt 10 && break - done - rm -f conftest.in conftest.tmp conftest.nl conftest.out;; -esac - - $ac_path_EGREP_found && break 3 - done - done - done -IFS=$as_save_IFS - if test -z "$ac_cv_path_EGREP"; then - as_fn_error "no acceptable egrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 - fi -else - ac_cv_path_EGREP=$EGREP -fi - - fi -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_EGREP" >&5 -$as_echo "$ac_cv_path_EGREP" >&6; } - EGREP="$ac_cv_path_EGREP" - - -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5 -$as_echo_n "checking for ANSI C header files... " >&6; } -if test "${ac_cv_header_stdc+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -#include -#include -#include -#include - -int -main () -{ - - ; - return 0; -} -_ACEOF -if ac_fn_c_try_compile "$LINENO"; then : - ac_cv_header_stdc=yes -else - ac_cv_header_stdc=no -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - -if test $ac_cv_header_stdc = yes; then - # SunOS 4.x string.h does not declare mem*, contrary to ANSI. - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -#include - -_ACEOF -if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "memchr" >/dev/null 2>&1; then : - -else - ac_cv_header_stdc=no -fi -rm -f conftest* - -fi - -if test $ac_cv_header_stdc = yes; then - # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI. - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -#include - -_ACEOF -if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "free" >/dev/null 2>&1; then : - -else - ac_cv_header_stdc=no -fi -rm -f conftest* - -fi - -if test $ac_cv_header_stdc = yes; then - # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi. - if test "$cross_compiling" = yes; then : - : -else - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -#include -#include -#if ((' ' & 0x0FF) == 0x020) -# define ISLOWER(c) ('a' <= (c) && (c) <= 'z') -# define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c)) -#else -# define ISLOWER(c) \ - (('a' <= (c) && (c) <= 'i') \ - || ('j' <= (c) && (c) <= 'r') \ - || ('s' <= (c) && (c) <= 'z')) -# define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c)) -#endif - -#define XOR(e, f) (((e) && !(f)) || (!(e) && (f))) -int -main () -{ - int i; - for (i = 0; i < 256; i++) - if (XOR (islower (i), ISLOWER (i)) - || toupper (i) != TOUPPER (i)) - return 2; - return 0; -} -_ACEOF -if ac_fn_c_try_run "$LINENO"; then : - -else - ac_cv_header_stdc=no -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ - conftest.$ac_objext conftest.beam conftest.$ac_ext -fi - -fi -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_stdc" >&5 -$as_echo "$ac_cv_header_stdc" >&6; } -if test $ac_cv_header_stdc = yes; then - -$as_echo "#define STDC_HEADERS 1" >>confdefs.h - -fi - -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for sys/wait.h that is POSIX.1 compatible" >&5 -$as_echo_n "checking for sys/wait.h that is POSIX.1 compatible... " >&6; } -if test "${ac_cv_header_sys_wait_h+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -#include -#include -#ifndef WEXITSTATUS -# define WEXITSTATUS(stat_val) ((unsigned int) (stat_val) >> 8) -#endif -#ifndef WIFEXITED -# define WIFEXITED(stat_val) (((stat_val) & 255) == 0) -#endif - -int -main () -{ - int s; - wait (&s); - s = WIFEXITED (s) ? WEXITSTATUS (s) : 1; - ; - return 0; -} -_ACEOF -if ac_fn_c_try_compile "$LINENO"; then : - ac_cv_header_sys_wait_h=yes -else - ac_cv_header_sys_wait_h=no -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_sys_wait_h" >&5 -$as_echo "$ac_cv_header_sys_wait_h" >&6; } -if test $ac_cv_header_sys_wait_h = yes; then - -$as_echo "#define HAVE_SYS_WAIT_H 1" >>confdefs.h - -fi - -# On IRIX 5.3, sys/types and inttypes.h are conflicting. -for ac_header in sys/types.h sys/stat.h stdlib.h string.h memory.h strings.h \ - inttypes.h stdint.h unistd.h -do : - as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` -ac_fn_c_check_header_compile "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default -" -eval as_val=\$$as_ac_Header - if test "x$as_val" = x""yes; then : - cat >>confdefs.h <<_ACEOF -#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 -_ACEOF - -fi - -done - - -for ac_header in fcntl.h limits.h netdb.h netinet/in.h stdlib.h string.h sys/socket.h sys/time.h unistd.h -do : - as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` -ac_fn_c_check_header_mongrel "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default" -eval as_val=\$$as_ac_Header - if test "x$as_val" = x""yes; then : - cat >>confdefs.h <<_ACEOF -#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 -_ACEOF - -fi - -done - -for ac_header in pthread.h semaphore.h -do : - as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` -ac_fn_c_check_header_mongrel "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default" -eval as_val=\$$as_ac_Header - if test "x$as_val" = x""yes; then : - cat >>confdefs.h <<_ACEOF -#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 -_ACEOF - -fi - -done - - -# Checks for typedefs, structures, and compiler characteristics. -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for an ANSI C-conforming const" >&5 -$as_echo_n "checking for an ANSI C-conforming const... " >&6; } -if test "${ac_cv_c_const+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -int -main () -{ -/* FIXME: Include the comments suggested by Paul. */ -#ifndef __cplusplus - /* Ultrix mips cc rejects this. */ - typedef int charset[2]; - const charset cs; - /* SunOS 4.1.1 cc rejects this. */ - char const *const *pcpcc; - char **ppc; - /* NEC SVR4.0.2 mips cc rejects this. */ - struct point {int x, y;}; - static struct point const zero = {0,0}; - /* AIX XL C 1.02.0.0 rejects this. - It does not let you subtract one const X* pointer from another in - an arm of an if-expression whose if-part is not a constant - expression */ - const char *g = "string"; - pcpcc = &g + (g ? g-g : 0); - /* HPUX 7.0 cc rejects these. */ - ++pcpcc; - ppc = (char**) pcpcc; - pcpcc = (char const *const *) ppc; - { /* SCO 3.2v4 cc rejects this. */ - char *t; - char const *s = 0 ? (char *) 0 : (char const *) 0; - - *t++ = 0; - if (s) return 0; - } - { /* Someone thinks the Sun supposedly-ANSI compiler will reject this. */ - int x[] = {25, 17}; - const int *foo = &x[0]; - ++foo; - } - { /* Sun SC1.0 ANSI compiler rejects this -- but not the above. */ - typedef const int *iptr; - iptr p = 0; - ++p; - } - { /* AIX XL C 1.02.0.0 rejects this saying - "k.c", line 2.27: 1506-025 (S) Operand must be a modifiable lvalue. */ - struct s { int j; const int *ap[3]; }; - struct s *b; b->j = 5; - } - { /* ULTRIX-32 V3.1 (Rev 9) vcc rejects this */ - const int foo = 10; - if (!foo) return 0; - } - return !cs[0] && !zero.x; -#endif - - ; - return 0; -} -_ACEOF -if ac_fn_c_try_compile "$LINENO"; then : - ac_cv_c_const=yes -else - ac_cv_c_const=no -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_const" >&5 -$as_echo "$ac_cv_c_const" >&6; } -if test $ac_cv_c_const = no; then - -$as_echo "#define const /**/" >>confdefs.h - -fi - -ac_fn_c_check_type "$LINENO" "pid_t" "ac_cv_type_pid_t" "$ac_includes_default" -if test "x$ac_cv_type_pid_t" = x""yes; then : - -else - -cat >>confdefs.h <<_ACEOF -#define pid_t int -_ACEOF - -fi - -ac_fn_c_check_type "$LINENO" "size_t" "ac_cv_type_size_t" "$ac_includes_default" -if test "x$ac_cv_type_size_t" = x""yes; then : - -else - -cat >>confdefs.h <<_ACEOF -#define size_t unsigned int -_ACEOF - -fi - -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether time.h and sys/time.h may both be included" >&5 -$as_echo_n "checking whether time.h and sys/time.h may both be included... " >&6; } -if test "${ac_cv_header_time+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -#include -#include -#include - -int -main () -{ -if ((struct tm *) 0) -return 0; - ; - return 0; -} -_ACEOF -if ac_fn_c_try_compile "$LINENO"; then : - ac_cv_header_time=yes -else - ac_cv_header_time=no -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_time" >&5 -$as_echo "$ac_cv_header_time" >&6; } -if test $ac_cv_header_time = yes; then - -$as_echo "#define TIME_WITH_SYS_TIME 1" >>confdefs.h - -fi - - -# Checks for library functions. -# This defines HAVE_MALLOC if malloc(0) returns valid ptr instead of NULL. -for ac_header in stdlib.h -do : - ac_fn_c_check_header_mongrel "$LINENO" "stdlib.h" "ac_cv_header_stdlib_h" "$ac_includes_default" -if test "x$ac_cv_header_stdlib_h" = x""yes; then : - cat >>confdefs.h <<_ACEOF -#define HAVE_STDLIB_H 1 -_ACEOF - -fi - -done - -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for GNU libc compatible malloc" >&5 -$as_echo_n "checking for GNU libc compatible malloc... " >&6; } -if test "${ac_cv_func_malloc_0_nonnull+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test "$cross_compiling" = yes; then : - ac_cv_func_malloc_0_nonnull=no -else - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -#if defined STDC_HEADERS || defined HAVE_STDLIB_H -# include -#else -char *malloc (); -#endif - -int -main () -{ -return ! malloc (0); - ; - return 0; -} -_ACEOF -if ac_fn_c_try_run "$LINENO"; then : - ac_cv_func_malloc_0_nonnull=yes -else - ac_cv_func_malloc_0_nonnull=no -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ - conftest.$ac_objext conftest.beam conftest.$ac_ext -fi - -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_malloc_0_nonnull" >&5 -$as_echo "$ac_cv_func_malloc_0_nonnull" >&6; } -if test $ac_cv_func_malloc_0_nonnull = yes; then : - -$as_echo "#define HAVE_MALLOC 1" >>confdefs.h - -else - $as_echo "#define HAVE_MALLOC 0" >>confdefs.h - - case " $LIBOBJS " in - *" malloc.$ac_objext "* ) ;; - *) LIBOBJS="$LIBOBJS malloc.$ac_objext" - ;; -esac - - -$as_echo "#define malloc rpl_malloc" >>confdefs.h - -fi - - -# AC_FUNC_MMAP -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking return type of signal handlers" >&5 -$as_echo_n "checking return type of signal handlers... " >&6; } -if test "${ac_cv_type_signal+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -#include -#include - -int -main () -{ -return *(signal (0, 0)) (0) == 1; - ; - return 0; -} -_ACEOF -if ac_fn_c_try_compile "$LINENO"; then : - ac_cv_type_signal=int -else - ac_cv_type_signal=void -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_type_signal" >&5 -$as_echo "$ac_cv_type_signal" >&6; } - -cat >>confdefs.h <<_ACEOF -#define RETSIGTYPE $ac_cv_type_signal -_ACEOF - - -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether lstat dereferences a symlink specified with a trailing slash" >&5 -$as_echo_n "checking whether lstat dereferences a symlink specified with a trailing slash... " >&6; } -if test "${ac_cv_func_lstat_dereferences_slashed_symlink+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - rm -f conftest.sym conftest.file -echo >conftest.file -if test "$as_ln_s" = "ln -s" && ln -s conftest.file conftest.sym; then - if test "$cross_compiling" = yes; then : - ac_cv_func_lstat_dereferences_slashed_symlink=no -else - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -struct stat sbuf; - /* Linux will dereference the symlink and fail. - That is better in the sense that it means we will not - have to compile and use the lstat wrapper. */ - return lstat ("conftest.sym/", &sbuf) == 0; - ; - return 0; -} -_ACEOF -if ac_fn_c_try_run "$LINENO"; then : - ac_cv_func_lstat_dereferences_slashed_symlink=yes -else - ac_cv_func_lstat_dereferences_slashed_symlink=no -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ - conftest.$ac_objext conftest.beam conftest.$ac_ext -fi - -else - # If the `ln -s' command failed, then we probably don't even - # have an lstat function. - ac_cv_func_lstat_dereferences_slashed_symlink=no -fi -rm -f conftest.sym conftest.file - -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_lstat_dereferences_slashed_symlink" >&5 -$as_echo "$ac_cv_func_lstat_dereferences_slashed_symlink" >&6; } - -test $ac_cv_func_lstat_dereferences_slashed_symlink = yes && - -cat >>confdefs.h <<_ACEOF -#define LSTAT_FOLLOWS_SLASHED_SYMLINK 1 -_ACEOF - - -if test $ac_cv_func_lstat_dereferences_slashed_symlink = no; then - case " $LIBOBJS " in - *" lstat.$ac_objext "* ) ;; - *) LIBOBJS="$LIBOBJS lstat.$ac_objext" - ;; -esac - -fi - -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether stat accepts an empty string" >&5 -$as_echo_n "checking whether stat accepts an empty string... " >&6; } -if test "${ac_cv_func_stat_empty_string_bug+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test "$cross_compiling" = yes; then : - ac_cv_func_stat_empty_string_bug=yes -else - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -struct stat sbuf; - return stat ("", &sbuf) == 0; - ; - return 0; -} -_ACEOF -if ac_fn_c_try_run "$LINENO"; then : - ac_cv_func_stat_empty_string_bug=no -else - ac_cv_func_stat_empty_string_bug=yes -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ - conftest.$ac_objext conftest.beam conftest.$ac_ext -fi - -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_stat_empty_string_bug" >&5 -$as_echo "$ac_cv_func_stat_empty_string_bug" >&6; } -if test $ac_cv_func_stat_empty_string_bug = yes; then - case " $LIBOBJS " in - *" stat.$ac_objext "* ) ;; - *) LIBOBJS="$LIBOBJS stat.$ac_objext" - ;; -esac - - -cat >>confdefs.h <<_ACEOF -#define HAVE_STAT_EMPTY_STRING_BUG 1 -_ACEOF - -fi - -for ac_func in vprintf -do : - ac_fn_c_check_func "$LINENO" "vprintf" "ac_cv_func_vprintf" -if test "x$ac_cv_func_vprintf" = x""yes; then : - cat >>confdefs.h <<_ACEOF -#define HAVE_VPRINTF 1 -_ACEOF - -ac_fn_c_check_func "$LINENO" "_doprnt" "ac_cv_func__doprnt" -if test "x$ac_cv_func__doprnt" = x""yes; then : - -$as_echo "#define HAVE_DOPRNT 1" >>confdefs.h - -fi - -fi -done - - -for ac_func in alarm getcwd gethostbyname gethostname memset select socket strchr strerror strtol -do : - as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` -ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var" -eval as_val=\$$as_ac_var - if test "x$as_val" = x""yes; then : - cat >>confdefs.h <<_ACEOF -#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 -_ACEOF - -fi -done - - -# Erase old @DEFS@ and add to it -rm -rf conftest* confdefs.h -# AIX cpp loses on an empty file, so make sure it contains at least a newline. -echo > confdefs.h -if test "$HAVE_MPI_H" != ""; then - $as_echo "#define HAVE_MPI_H 1" >>confdefs.h - -fi; - -# AIX-cc doesn't allow "// ..." style commenting by default. -# AIX-xlc is IBM ANSI C, while cc is IBM extended C and xlC is C++/C -# OSF1: libpthread in weird place, not found by this script -# In linuxthreads-2.0.6 and also in some later versions using "old semaphore", -# make parfactor-pthread occasionally fails. -# Enable ASSERT in linuxthreads:queue.h for the 'smoking gun' -# We disable all of linuxthreads semaphores until we can test linuxthreads-2.0.7 -target=`uname -s` -case $target-$CC in - IRIX64-*) $as_echo "#define HAVE_PROCESS_SCOPE_BOUND_NP 1" >>confdefs.h - ;; - AIX-xlc) CFLAGS="$CFLAGS -qcpluscmt" ;; - AIX-xlC) CFLAGS="$CFLAGS -qcpluscmt" ;; - AIX-cc) CFLAGS="$CFLAGS -qcpluscmt" ;; - Linux-*) linux_pthread_sem_bug=yes ;; - OSF1-*) if test x$HAVE_PTHREAD = xyes; then - LIBSFORPTHREAD="-lpthread $LIBSFORPTHREAD" - fi - ;; -esac - -# Substitute shell variables - - - - - - - - - - - - - - - - - - -if test "x$HAVE_PTHREAD" = "xyes"; then - # Older Solaris has only thr_setconcurrency() - # AC_CHECK_FUNCS(FUNC)/AC_CHECK_HEADERS(file.h) (plural forms only) - # do AC_DEFINE(HAVE_FUNC), AC_DEFINE(HAVE_FILE_H) - for ac_func in pthread_setconcurrency thr_setconcurrency -do : - as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` -ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var" -eval as_val=\$$as_ac_var - if test "x$as_val" = x""yes; then : - cat >>confdefs.h <<_ACEOF -#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 -_ACEOF - -fi -done - - - # Alternative, but would also need in conf.h.in: #include - # if test "$ac_cv_func_pthread_setconcurrency" != yes; then - # AC_CHECK_FUNC(thr_setconcurrency, - # , AC_DEFINE(pthread_setconcurrency, thr_setconcurrency) - # AC_DEFINE(HAVE_PTHREAD_SETCONCURRENCY) - # ) - # fi - if test "x$HAVE_SEMAPHORE" != "xyes"; then - $as_echo "#define HAVE_SEMAPHORE 0" >>confdefs.h - - elif test "x$linux_pthread_sem_bug" = "xyes"; then - $as_echo "#define HAVE_SEMAPHORE 0" >>confdefs.h - - fi -else - $as_echo "#define HAVE_PTHREAD 0" >>confdefs.h - -fi - -# if test "x$with_static_cache_size" = "xno"; then -# AC_DEFINE(STATIC_CACHE_SIZE, 0) -# elif test "x$with_static_cache_size" != "xyes"; then -# AC_DEFINE_UNQUOTED(STATIC_CACHE_SIZE, $with_static_cache_size) -# fi - -ac_config_files="$ac_config_files src/Makefile src/mpinu/Makefile src/mpinu/procgroup bin/Makefile bin/topcc bin/topc++ bin/topc-config doc/Makefile doc/topcc.1 doc/topc-version.texi utils/ssh-killall Makefile README" - -cat >confcache <<\_ACEOF -# This file is a shell script that caches the results of configure -# tests run on this system so they can be shared between configure -# scripts and configure runs, see configure's option --config-cache. -# It is not useful on other systems. If it contains results you don't -# want to keep, you may remove or edit it. -# -# config.status only pays attention to the cache file if you give it -# the --recheck option to rerun configure. -# -# `ac_cv_env_foo' variables (set or unset) will be overridden when -# loading this file, other *unset* `ac_cv_foo' will be assigned the -# following values. - -_ACEOF - -# The following way of writing the cache mishandles newlines in values, -# but we know of no workaround that is simple, portable, and efficient. -# So, we kill variables containing newlines. -# Ultrix sh set writes to stderr and can't be redirected directly, -# and sets the high bit in the cache file unless we assign to the vars. -( - for ac_var in `(set) 2>&1 | sed -n 's/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'`; do - eval ac_val=\$$ac_var - case $ac_val in #( - *${as_nl}*) - case $ac_var in #( - *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5 -$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; - esac - case $ac_var in #( - _ | IFS | as_nl) ;; #( - BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( - *) { eval $ac_var=; unset $ac_var;} ;; - esac ;; - esac - done - - (set) 2>&1 | - case $as_nl`(ac_space=' '; set) 2>&1` in #( - *${as_nl}ac_space=\ *) - # `set' does not quote correctly, so add quotes: double-quote - # substitution turns \\\\ into \\, and sed turns \\ into \. - sed -n \ - "s/'/'\\\\''/g; - s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\\2'/p" - ;; #( - *) - # `set' quotes correctly as required by POSIX, so do not add quotes. - sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" - ;; - esac | - sort -) | - sed ' - /^ac_cv_env_/b end - t clear - :clear - s/^\([^=]*\)=\(.*[{}].*\)$/test "${\1+set}" = set || &/ - t end - s/^\([^=]*\)=\(.*\)$/\1=${\1=\2}/ - :end' >>confcache -if diff "$cache_file" confcache >/dev/null 2>&1; then :; else - if test -w "$cache_file"; then - test "x$cache_file" != "x/dev/null" && - { $as_echo "$as_me:${as_lineno-$LINENO}: updating cache $cache_file" >&5 -$as_echo "$as_me: updating cache $cache_file" >&6;} - cat confcache >$cache_file - else - { $as_echo "$as_me:${as_lineno-$LINENO}: not updating unwritable cache $cache_file" >&5 -$as_echo "$as_me: not updating unwritable cache $cache_file" >&6;} - fi -fi -rm -f confcache - -test "x$prefix" = xNONE && prefix=$ac_default_prefix -# Let make expand exec_prefix. -test "x$exec_prefix" = xNONE && exec_prefix='${prefix}' - -# Transform confdefs.h into DEFS. -# Protect against shell expansion while executing Makefile rules. -# Protect against Makefile macro expansion. -# -# If the first sed substitution is executed (which looks for macros that -# take arguments), then branch to the quote section. Otherwise, -# look for a macro that doesn't take arguments. -ac_script=' -:mline -/\\$/{ - N - s,\\\n,, - b mline -} -t clear -:clear -s/^[ ]*#[ ]*define[ ][ ]*\([^ (][^ (]*([^)]*)\)[ ]*\(.*\)/-D\1=\2/g -t quote -s/^[ ]*#[ ]*define[ ][ ]*\([^ ][^ ]*\)[ ]*\(.*\)/-D\1=\2/g -t quote -b any -:quote -s/[ `~#$^&*(){}\\|;'\''"<>?]/\\&/g -s/\[/\\&/g -s/\]/\\&/g -s/\$/$$/g -H -:any -${ - g - s/^\n// - s/\n/ /g - p -} -' -DEFS=`sed -n "$ac_script" confdefs.h` - - -ac_libobjs= -ac_ltlibobjs= -for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue - # 1. Remove the extension, and $U if already installed. - ac_script='s/\$U\././;s/\.o$//;s/\.obj$//' - ac_i=`$as_echo "$ac_i" | sed "$ac_script"` - # 2. Prepend LIBOBJDIR. When used with automake>=1.10 LIBOBJDIR - # will be set to the directory where LIBOBJS objects are built. - as_fn_append ac_libobjs " \${LIBOBJDIR}$ac_i\$U.$ac_objext" - as_fn_append ac_ltlibobjs " \${LIBOBJDIR}$ac_i"'$U.lo' -done -LIBOBJS=$ac_libobjs - -LTLIBOBJS=$ac_ltlibobjs - - - -: ${CONFIG_STATUS=./config.status} -ac_write_fail=0 -ac_clean_files_save=$ac_clean_files -ac_clean_files="$ac_clean_files $CONFIG_STATUS" -{ $as_echo "$as_me:${as_lineno-$LINENO}: creating $CONFIG_STATUS" >&5 -$as_echo "$as_me: creating $CONFIG_STATUS" >&6;} -as_write_fail=0 -cat >$CONFIG_STATUS <<_ASEOF || as_write_fail=1 -#! $SHELL -# Generated by $as_me. -# Run this file to recreate the current configuration. -# Compiler output produced by configure, useful for debugging -# configure, is in config.log if it exists. - -debug=false -ac_cs_recheck=false -ac_cs_silent=false - -SHELL=\${CONFIG_SHELL-$SHELL} -export SHELL -_ASEOF -cat >>$CONFIG_STATUS <<\_ASEOF || as_write_fail=1 -## -------------------- ## -## M4sh Initialization. ## -## -------------------- ## - -# Be more Bourne compatible -DUALCASE=1; export DUALCASE # for MKS sh -if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then : - emulate sh - NULLCMD=: - # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which - # is contrary to our usage. Disable this feature. - alias -g '${1+"$@"}'='"$@"' - setopt NO_GLOB_SUBST -else - case `(set -o) 2>/dev/null` in #( - *posix*) : - set -o posix ;; #( - *) : - ;; -esac -fi - - -as_nl=' -' -export as_nl -# Printing a long string crashes Solaris 7 /usr/bin/printf. -as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' -as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo -as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo -# Prefer a ksh shell builtin over an external printf program on Solaris, -# but without wasting forks for bash or zsh. -if test -z "$BASH_VERSION$ZSH_VERSION" \ - && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then - as_echo='print -r --' - as_echo_n='print -rn --' -elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then - as_echo='printf %s\n' - as_echo_n='printf %s' -else - if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then - as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"' - as_echo_n='/usr/ucb/echo -n' - else - as_echo_body='eval expr "X$1" : "X\\(.*\\)"' - as_echo_n_body='eval - arg=$1; - case $arg in #( - *"$as_nl"*) - expr "X$arg" : "X\\(.*\\)$as_nl"; - arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; - esac; - expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl" - ' - export as_echo_n_body - as_echo_n='sh -c $as_echo_n_body as_echo' - fi - export as_echo_body - as_echo='sh -c $as_echo_body as_echo' -fi - -# The user is always right. -if test "${PATH_SEPARATOR+set}" != set; then - PATH_SEPARATOR=: - (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { - (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || - PATH_SEPARATOR=';' - } -fi - - -# IFS -# We need space, tab and new line, in precisely that order. Quoting is -# there to prevent editors from complaining about space-tab. -# (If _AS_PATH_WALK were called with IFS unset, it would disable word -# splitting by setting IFS to empty value.) -IFS=" "" $as_nl" - -# Find who we are. Look in the path if we contain no directory separator. -case $0 in #(( - *[\\/]* ) as_myself=$0 ;; - *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break - done -IFS=$as_save_IFS - - ;; -esac -# We did not find ourselves, most probably we were run as `sh COMMAND' -# in which case we are not to be found in the path. -if test "x$as_myself" = x; then - as_myself=$0 -fi -if test ! -f "$as_myself"; then - $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 - exit 1 -fi - -# Unset variables that we do not need and which cause bugs (e.g. in -# pre-3.0 UWIN ksh). But do not cause bugs in bash 2.01; the "|| exit 1" -# suppresses any "Segmentation fault" message there. '((' could -# trigger a bug in pdksh 5.2.14. -for as_var in BASH_ENV ENV MAIL MAILPATH -do eval test x\${$as_var+set} = xset \ - && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || : -done -PS1='$ ' -PS2='> ' -PS4='+ ' - -# NLS nuisances. -LC_ALL=C -export LC_ALL -LANGUAGE=C -export LANGUAGE - -# CDPATH. -(unset CDPATH) >/dev/null 2>&1 && unset CDPATH - - -# as_fn_error ERROR [LINENO LOG_FD] -# --------------------------------- -# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are -# provided, also output the error to LOG_FD, referencing LINENO. Then exit the -# script with status $?, using 1 if that was 0. -as_fn_error () -{ - as_status=$?; test $as_status -eq 0 && as_status=1 - if test "$3"; then - as_lineno=${as_lineno-"$2"} as_lineno_stack=as_lineno_stack=$as_lineno_stack - $as_echo "$as_me:${as_lineno-$LINENO}: error: $1" >&$3 - fi - $as_echo "$as_me: error: $1" >&2 - as_fn_exit $as_status -} # as_fn_error - - -# as_fn_set_status STATUS -# ----------------------- -# Set $? to STATUS, without forking. -as_fn_set_status () -{ - return $1 -} # as_fn_set_status - -# as_fn_exit STATUS -# ----------------- -# Exit the shell with STATUS, even in a "trap 0" or "set -e" context. -as_fn_exit () -{ - set +e - as_fn_set_status $1 - exit $1 -} # as_fn_exit - -# as_fn_unset VAR -# --------------- -# Portably unset VAR. -as_fn_unset () -{ - { eval $1=; unset $1;} -} -as_unset=as_fn_unset -# as_fn_append VAR VALUE -# ---------------------- -# Append the text in VALUE to the end of the definition contained in VAR. Take -# advantage of any shell optimizations that allow amortized linear growth over -# repeated appends, instead of the typical quadratic growth present in naive -# implementations. -if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then : - eval 'as_fn_append () - { - eval $1+=\$2 - }' -else - as_fn_append () - { - eval $1=\$$1\$2 - } -fi # as_fn_append - -# as_fn_arith ARG... -# ------------------ -# Perform arithmetic evaluation on the ARGs, and store the result in the -# global $as_val. Take advantage of shells that can avoid forks. The arguments -# must be portable across $(()) and expr. -if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then : - eval 'as_fn_arith () - { - as_val=$(( $* )) - }' -else - as_fn_arith () - { - as_val=`expr "$@" || test $? -eq 1` - } -fi # as_fn_arith - - -if expr a : '\(a\)' >/dev/null 2>&1 && - test "X`expr 00001 : '.*\(...\)'`" = X001; then - as_expr=expr -else - as_expr=false -fi - -if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then - as_basename=basename -else - as_basename=false -fi - -if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then - as_dirname=dirname -else - as_dirname=false -fi - -as_me=`$as_basename -- "$0" || -$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ - X"$0" : 'X\(//\)$' \| \ - X"$0" : 'X\(/\)' \| . 2>/dev/null || -$as_echo X/"$0" | - sed '/^.*\/\([^/][^/]*\)\/*$/{ - s//\1/ - q - } - /^X\/\(\/\/\)$/{ - s//\1/ - q - } - /^X\/\(\/\).*/{ - s//\1/ - q - } - s/.*/./; q'` - -# Avoid depending upon Character Ranges. -as_cr_letters='abcdefghijklmnopqrstuvwxyz' -as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' -as_cr_Letters=$as_cr_letters$as_cr_LETTERS -as_cr_digits='0123456789' -as_cr_alnum=$as_cr_Letters$as_cr_digits - -ECHO_C= ECHO_N= ECHO_T= -case `echo -n x` in #((((( --n*) - case `echo 'xy\c'` in - *c*) ECHO_T=' ';; # ECHO_T is single tab character. - xy) ECHO_C='\c';; - *) echo `echo ksh88 bug on AIX 6.1` > /dev/null - ECHO_T=' ';; - esac;; -*) - ECHO_N='-n';; -esac - -rm -f conf$$ conf$$.exe conf$$.file -if test -d conf$$.dir; then - rm -f conf$$.dir/conf$$.file -else - rm -f conf$$.dir - mkdir conf$$.dir 2>/dev/null -fi -if (echo >conf$$.file) 2>/dev/null; then - if ln -s conf$$.file conf$$ 2>/dev/null; then - as_ln_s='ln -s' - # ... but there are two gotchas: - # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. - # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. - # In both cases, we have to default to `cp -p'. - ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || - as_ln_s='cp -p' - elif ln conf$$.file conf$$ 2>/dev/null; then - as_ln_s=ln - else - as_ln_s='cp -p' - fi -else - as_ln_s='cp -p' -fi -rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file -rmdir conf$$.dir 2>/dev/null - - -# as_fn_mkdir_p -# ------------- -# Create "$as_dir" as a directory, including parents if necessary. -as_fn_mkdir_p () -{ - - case $as_dir in #( - -*) as_dir=./$as_dir;; - esac - test -d "$as_dir" || eval $as_mkdir_p || { - as_dirs= - while :; do - case $as_dir in #( - *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( - *) as_qdir=$as_dir;; - esac - as_dirs="'$as_qdir' $as_dirs" - as_dir=`$as_dirname -- "$as_dir" || -$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ - X"$as_dir" : 'X\(//\)[^/]' \| \ - X"$as_dir" : 'X\(//\)$' \| \ - X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || -$as_echo X"$as_dir" | - sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ - s//\1/ - q - } - /^X\(\/\/\)[^/].*/{ - s//\1/ - q - } - /^X\(\/\/\)$/{ - s//\1/ - q - } - /^X\(\/\).*/{ - s//\1/ - q - } - s/.*/./; q'` - test -d "$as_dir" && break - done - test -z "$as_dirs" || eval "mkdir $as_dirs" - } || test -d "$as_dir" || as_fn_error "cannot create directory $as_dir" - - -} # as_fn_mkdir_p -if mkdir -p . 2>/dev/null; then - as_mkdir_p='mkdir -p "$as_dir"' -else - test -d ./-p && rmdir ./-p - as_mkdir_p=false -fi - -if test -x / >/dev/null 2>&1; then - as_test_x='test -x' -else - if ls -dL / >/dev/null 2>&1; then - as_ls_L_option=L - else - as_ls_L_option= - fi - as_test_x=' - eval sh -c '\'' - if test -d "$1"; then - test -d "$1/."; - else - case $1 in #( - -*)set "./$1";; - esac; - case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in #(( - ???[sx]*):;;*)false;;esac;fi - '\'' sh - ' -fi -as_executable_p=$as_test_x - -# Sed expression to map a string onto a valid CPP name. -as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" - -# Sed expression to map a string onto a valid variable name. -as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" - - -exec 6>&1 -## ----------------------------------- ## -## Main body of $CONFIG_STATUS script. ## -## ----------------------------------- ## -_ASEOF -test $as_write_fail = 0 && chmod +x $CONFIG_STATUS || ac_write_fail=1 - -cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 -# Save the log message, to keep $0 and so on meaningful, and to -# report actual input values of CONFIG_FILES etc. instead of their -# values after options handling. -ac_log=" -This file was extended by TOP-C $as_me 0.0.0, which was -generated by GNU Autoconf 2.64. Invocation command line was - - CONFIG_FILES = $CONFIG_FILES - CONFIG_HEADERS = $CONFIG_HEADERS - CONFIG_LINKS = $CONFIG_LINKS - CONFIG_COMMANDS = $CONFIG_COMMANDS - $ $0 $@ - -on `(hostname || uname -n) 2>/dev/null | sed 1q` -" - -_ACEOF - -case $ac_config_files in *" -"*) set x $ac_config_files; shift; ac_config_files=$*;; -esac - - - -cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 -# Files that config.status was made for. -config_files="$ac_config_files" - -_ACEOF - -cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 -ac_cs_usage="\ -\`$as_me' instantiates files and other configuration actions -from templates according to the current configuration. Unless the files -and actions are specified as TAGs, all are instantiated by default. - -Usage: $0 [OPTION]... [TAG]... - - -h, --help print this help, then exit - -V, --version print version number and configuration settings, then exit - -q, --quiet, --silent - do not print progress messages - -d, --debug don't remove temporary files - --recheck update $as_me by reconfiguring in the same conditions - --file=FILE[:TEMPLATE] - instantiate the configuration file FILE - -Configuration files: -$config_files - -Report bugs to ." - -_ACEOF -cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 -ac_cs_version="\\ -TOP-C config.status 0.0.0 -configured by $0, generated by GNU Autoconf 2.64, - with options \\"`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`\\" - -Copyright (C) 2009 Free Software Foundation, Inc. -This config.status script is free software; the Free Software Foundation -gives unlimited permission to copy, distribute and modify it." - -ac_pwd='$ac_pwd' -srcdir='$srcdir' -test -n "\$AWK" || AWK=awk -_ACEOF - -cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 -# The default lists apply if the user does not specify any file. -ac_need_defaults=: -while test $# != 0 -do - case $1 in - --*=*) - ac_option=`expr "X$1" : 'X\([^=]*\)='` - ac_optarg=`expr "X$1" : 'X[^=]*=\(.*\)'` - ac_shift=: - ;; - *) - ac_option=$1 - ac_optarg=$2 - ac_shift=shift - ;; - esac - - case $ac_option in - # Handling of the options. - -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r) - ac_cs_recheck=: ;; - --version | --versio | --versi | --vers | --ver | --ve | --v | -V ) - $as_echo "$ac_cs_version"; exit ;; - --debug | --debu | --deb | --de | --d | -d ) - debug=: ;; - --file | --fil | --fi | --f ) - $ac_shift - case $ac_optarg in - *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; - esac - as_fn_append CONFIG_FILES " '$ac_optarg'" - ac_need_defaults=false;; - --he | --h | --help | --hel | -h ) - $as_echo "$ac_cs_usage"; exit ;; - -q | -quiet | --quiet | --quie | --qui | --qu | --q \ - | -silent | --silent | --silen | --sile | --sil | --si | --s) - ac_cs_silent=: ;; - - # This is an error. - -*) as_fn_error "unrecognized option: \`$1' -Try \`$0 --help' for more information." ;; - - *) as_fn_append ac_config_targets " $1" - ac_need_defaults=false ;; - - esac - shift -done - -ac_configure_extra_args= - -if $ac_cs_silent; then - exec 6>/dev/null - ac_configure_extra_args="$ac_configure_extra_args --silent" -fi - -_ACEOF -cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 -if \$ac_cs_recheck; then - set X '$SHELL' '$0' $ac_configure_args \$ac_configure_extra_args --no-create --no-recursion - shift - \$as_echo "running CONFIG_SHELL=$SHELL \$*" >&6 - CONFIG_SHELL='$SHELL' - export CONFIG_SHELL - exec "\$@" -fi - -_ACEOF -cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 -exec 5>>config.log -{ - echo - sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX -## Running $as_me. ## -_ASBOX - $as_echo "$ac_log" -} >&5 - -_ACEOF -cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 -_ACEOF - -cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 - -# Handling of arguments. -for ac_config_target in $ac_config_targets -do - case $ac_config_target in - "src/Makefile") CONFIG_FILES="$CONFIG_FILES src/Makefile" ;; - "src/mpinu/Makefile") CONFIG_FILES="$CONFIG_FILES src/mpinu/Makefile" ;; - "src/mpinu/procgroup") CONFIG_FILES="$CONFIG_FILES src/mpinu/procgroup" ;; - "bin/Makefile") CONFIG_FILES="$CONFIG_FILES bin/Makefile" ;; - "bin/topcc") CONFIG_FILES="$CONFIG_FILES bin/topcc" ;; - "bin/topc++") CONFIG_FILES="$CONFIG_FILES bin/topc++" ;; - "bin/topc-config") CONFIG_FILES="$CONFIG_FILES bin/topc-config" ;; - "doc/Makefile") CONFIG_FILES="$CONFIG_FILES doc/Makefile" ;; - "doc/topcc.1") CONFIG_FILES="$CONFIG_FILES doc/topcc.1" ;; - "doc/topc-version.texi") CONFIG_FILES="$CONFIG_FILES doc/topc-version.texi" ;; - "utils/ssh-killall") CONFIG_FILES="$CONFIG_FILES utils/ssh-killall" ;; - "Makefile") CONFIG_FILES="$CONFIG_FILES Makefile" ;; - "README") CONFIG_FILES="$CONFIG_FILES README" ;; - - *) as_fn_error "invalid argument: \`$ac_config_target'" "$LINENO" 5;; - esac -done - - -# If the user did not use the arguments to specify the items to instantiate, -# then the envvar interface is used. Set only those that are not. -# We use the long form for the default assignment because of an extremely -# bizarre bug on SunOS 4.1.3. -if $ac_need_defaults; then - test "${CONFIG_FILES+set}" = set || CONFIG_FILES=$config_files -fi - -# Have a temporary directory for convenience. Make it in the build tree -# simply because there is no reason against having it here, and in addition, -# creating and moving files from /tmp can sometimes cause problems. -# Hook for its removal unless debugging. -# Note that there is a small window in which the directory will not be cleaned: -# after its creation but before its name has been assigned to `$tmp'. -$debug || -{ - tmp= - trap 'exit_status=$? - { test -z "$tmp" || test ! -d "$tmp" || rm -fr "$tmp"; } && exit $exit_status -' 0 - trap 'as_fn_exit 1' 1 2 13 15 -} -# Create a (secure) tmp directory for tmp files. - -{ - tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` && - test -n "$tmp" && test -d "$tmp" -} || -{ - tmp=./conf$$-$RANDOM - (umask 077 && mkdir "$tmp") -} || as_fn_error "cannot create a temporary directory in ." "$LINENO" 5 - -# Set up the scripts for CONFIG_FILES section. -# No need to generate them if there are no CONFIG_FILES. -# This happens for instance with `./config.status config.h'. -if test -n "$CONFIG_FILES"; then - - -ac_cr=`echo X | tr X '\015'` -# On cygwin, bash can eat \r inside `` if the user requested igncr. -# But we know of no other shell where ac_cr would be empty at this -# point, so we can use a bashism as a fallback. -if test "x$ac_cr" = x; then - eval ac_cr=\$\'\\r\' -fi -ac_cs_awk_cr=`$AWK 'BEGIN { print "a\rb" }' /dev/null` -if test "$ac_cs_awk_cr" = "a${ac_cr}b"; then - ac_cs_awk_cr='\r' -else - ac_cs_awk_cr=$ac_cr -fi - -echo 'BEGIN {' >"$tmp/subs1.awk" && -_ACEOF - - -{ - echo "cat >conf$$subs.awk <<_ACEOF" && - echo "$ac_subst_vars" | sed 's/.*/&!$&$ac_delim/' && - echo "_ACEOF" -} >conf$$subs.sh || - as_fn_error "could not make $CONFIG_STATUS" "$LINENO" 5 -ac_delim_num=`echo "$ac_subst_vars" | grep -c '$'` -ac_delim='%!_!# ' -for ac_last_try in false false false false false :; do - . ./conf$$subs.sh || - as_fn_error "could not make $CONFIG_STATUS" "$LINENO" 5 - - ac_delim_n=`sed -n "s/.*$ac_delim\$/X/p" conf$$subs.awk | grep -c X` - if test $ac_delim_n = $ac_delim_num; then - break - elif $ac_last_try; then - as_fn_error "could not make $CONFIG_STATUS" "$LINENO" 5 - else - ac_delim="$ac_delim!$ac_delim _$ac_delim!! " - fi -done -rm -f conf$$subs.sh - -cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 -cat >>"\$tmp/subs1.awk" <<\\_ACAWK && -_ACEOF -sed -n ' -h -s/^/S["/; s/!.*/"]=/ -p -g -s/^[^!]*!// -:repl -t repl -s/'"$ac_delim"'$// -t delim -:nl -h -s/\(.\{148\}\).*/\1/ -t more1 -s/["\\]/\\&/g; s/^/"/; s/$/\\n"\\/ -p -n -b repl -:more1 -s/["\\]/\\&/g; s/^/"/; s/$/"\\/ -p -g -s/.\{148\}// -t nl -:delim -h -s/\(.\{148\}\).*/\1/ -t more2 -s/["\\]/\\&/g; s/^/"/; s/$/"/ -p -b -:more2 -s/["\\]/\\&/g; s/^/"/; s/$/"\\/ -p -g -s/.\{148\}// -t delim -' >$CONFIG_STATUS || ac_write_fail=1 -rm -f conf$$subs.awk -cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 -_ACAWK -cat >>"\$tmp/subs1.awk" <<_ACAWK && - for (key in S) S_is_set[key] = 1 - FS = "" - -} -{ - line = $ 0 - nfields = split(line, field, "@") - substed = 0 - len = length(field[1]) - for (i = 2; i < nfields; i++) { - key = field[i] - keylen = length(key) - if (S_is_set[key]) { - value = S[key] - line = substr(line, 1, len) "" value "" substr(line, len + keylen + 3) - len += length(value) + length(field[++i]) - substed = 1 - } else - len += 1 + keylen - } - - print line -} - -_ACAWK -_ACEOF -cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 -if sed "s/$ac_cr//" < /dev/null > /dev/null 2>&1; then - sed "s/$ac_cr\$//; s/$ac_cr/$ac_cs_awk_cr/g" -else - cat -fi < "$tmp/subs1.awk" > "$tmp/subs.awk" \ - || as_fn_error "could not setup config files machinery" "$LINENO" 5 -_ACEOF - -# VPATH may cause trouble with some makes, so we remove $(srcdir), -# ${srcdir} and @srcdir@ from VPATH if srcdir is ".", strip leading and -# trailing colons and then remove the whole line if VPATH becomes empty -# (actually we leave an empty line to preserve line numbers). -if test "x$srcdir" = x.; then - ac_vpsub='/^[ ]*VPATH[ ]*=/{ -s/:*\$(srcdir):*/:/ -s/:*\${srcdir}:*/:/ -s/:*@srcdir@:*/:/ -s/^\([^=]*=[ ]*\):*/\1/ -s/:*$// -s/^[^=]*=[ ]*$// -}' -fi - -cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 -fi # test -n "$CONFIG_FILES" - - -eval set X " :F $CONFIG_FILES " -shift -for ac_tag -do - case $ac_tag in - :[FHLC]) ac_mode=$ac_tag; continue;; - esac - case $ac_mode$ac_tag in - :[FHL]*:*);; - :L* | :C*:*) as_fn_error "invalid tag \`$ac_tag'" "$LINENO" 5;; - :[FH]-) ac_tag=-:-;; - :[FH]*) ac_tag=$ac_tag:$ac_tag.in;; - esac - ac_save_IFS=$IFS - IFS=: - set x $ac_tag - IFS=$ac_save_IFS - shift - ac_file=$1 - shift - - case $ac_mode in - :L) ac_source=$1;; - :[FH]) - ac_file_inputs= - for ac_f - do - case $ac_f in - -) ac_f="$tmp/stdin";; - *) # Look for the file first in the build tree, then in the source tree - # (if the path is not absolute). The absolute path cannot be DOS-style, - # because $ac_f cannot contain `:'. - test -f "$ac_f" || - case $ac_f in - [\\/$]*) false;; - *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";; - esac || - as_fn_error "cannot find input file: \`$ac_f'" "$LINENO" 5;; - esac - case $ac_f in *\'*) ac_f=`$as_echo "$ac_f" | sed "s/'/'\\\\\\\\''/g"`;; esac - as_fn_append ac_file_inputs " '$ac_f'" - done - - # Let's still pretend it is `configure' which instantiates (i.e., don't - # use $as_me), people would be surprised to read: - # /* config.h. Generated by config.status. */ - configure_input='Generated from '` - $as_echo "$*" | sed 's|^[^:]*/||;s|:[^:]*/|, |g' - `' by configure.' - if test x"$ac_file" != x-; then - configure_input="$ac_file. $configure_input" - { $as_echo "$as_me:${as_lineno-$LINENO}: creating $ac_file" >&5 -$as_echo "$as_me: creating $ac_file" >&6;} - fi - # Neutralize special characters interpreted by sed in replacement strings. - case $configure_input in #( - *\&* | *\|* | *\\* ) - ac_sed_conf_input=`$as_echo "$configure_input" | - sed 's/[\\\\&|]/\\\\&/g'`;; #( - *) ac_sed_conf_input=$configure_input;; - esac - - case $ac_tag in - *:-:* | *:-) cat >"$tmp/stdin" \ - || as_fn_error "could not create $ac_file" "$LINENO" 5 ;; - esac - ;; - esac - - ac_dir=`$as_dirname -- "$ac_file" || -$as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ - X"$ac_file" : 'X\(//\)[^/]' \| \ - X"$ac_file" : 'X\(//\)$' \| \ - X"$ac_file" : 'X\(/\)' \| . 2>/dev/null || -$as_echo X"$ac_file" | - sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ - s//\1/ - q - } - /^X\(\/\/\)[^/].*/{ - s//\1/ - q - } - /^X\(\/\/\)$/{ - s//\1/ - q - } - /^X\(\/\).*/{ - s//\1/ - q - } - s/.*/./; q'` - as_dir="$ac_dir"; as_fn_mkdir_p - ac_builddir=. - -case "$ac_dir" in -.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; -*) - ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` - # A ".." for each directory in $ac_dir_suffix. - ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` - case $ac_top_builddir_sub in - "") ac_top_builddir_sub=. ac_top_build_prefix= ;; - *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; - esac ;; -esac -ac_abs_top_builddir=$ac_pwd -ac_abs_builddir=$ac_pwd$ac_dir_suffix -# for backward compatibility: -ac_top_builddir=$ac_top_build_prefix - -case $srcdir in - .) # We are building in place. - ac_srcdir=. - ac_top_srcdir=$ac_top_builddir_sub - ac_abs_top_srcdir=$ac_pwd ;; - [\\/]* | ?:[\\/]* ) # Absolute name. - ac_srcdir=$srcdir$ac_dir_suffix; - ac_top_srcdir=$srcdir - ac_abs_top_srcdir=$srcdir ;; - *) # Relative name. - ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix - ac_top_srcdir=$ac_top_build_prefix$srcdir - ac_abs_top_srcdir=$ac_pwd/$srcdir ;; -esac -ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix - - - case $ac_mode in - :F) - # - # CONFIG_FILE - # - -_ACEOF - -cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 -# If the template does not know about datarootdir, expand it. -# FIXME: This hack should be removed a few years after 2.60. -ac_datarootdir_hack=; ac_datarootdir_seen= -ac_sed_dataroot=' -/datarootdir/ { - p - q -} -/@datadir@/p -/@docdir@/p -/@infodir@/p -/@localedir@/p -/@mandir@/p' -case `eval "sed -n \"\$ac_sed_dataroot\" $ac_file_inputs"` in -*datarootdir*) ac_datarootdir_seen=yes;; -*@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*) - { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5 -$as_echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;} -_ACEOF -cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 - ac_datarootdir_hack=' - s&@datadir@&$datadir&g - s&@docdir@&$docdir&g - s&@infodir@&$infodir&g - s&@localedir@&$localedir&g - s&@mandir@&$mandir&g - s&\\\${datarootdir}&$datarootdir&g' ;; -esac -_ACEOF - -# Neutralize VPATH when `$srcdir' = `.'. -# Shell code in configure.ac might set extrasub. -# FIXME: do we really want to maintain this feature? -cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 -ac_sed_extra="$ac_vpsub -$extrasub -_ACEOF -cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 -:t -/@[a-zA-Z_][a-zA-Z_0-9]*@/!b -s|@configure_input@|$ac_sed_conf_input|;t t -s&@top_builddir@&$ac_top_builddir_sub&;t t -s&@top_build_prefix@&$ac_top_build_prefix&;t t -s&@srcdir@&$ac_srcdir&;t t -s&@abs_srcdir@&$ac_abs_srcdir&;t t -s&@top_srcdir@&$ac_top_srcdir&;t t -s&@abs_top_srcdir@&$ac_abs_top_srcdir&;t t -s&@builddir@&$ac_builddir&;t t -s&@abs_builddir@&$ac_abs_builddir&;t t -s&@abs_top_builddir@&$ac_abs_top_builddir&;t t -$ac_datarootdir_hack -" -eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$tmp/subs.awk" >$tmp/out \ - || as_fn_error "could not create $ac_file" "$LINENO" 5 - -test -z "$ac_datarootdir_hack$ac_datarootdir_seen" && - { ac_out=`sed -n '/\${datarootdir}/p' "$tmp/out"`; test -n "$ac_out"; } && - { ac_out=`sed -n '/^[ ]*datarootdir[ ]*:*=/p' "$tmp/out"`; test -z "$ac_out"; } && - { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file contains a reference to the variable \`datarootdir' -which seems to be undefined. Please make sure it is defined." >&5 -$as_echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir' -which seems to be undefined. Please make sure it is defined." >&2;} - - rm -f "$tmp/stdin" - case $ac_file in - -) cat "$tmp/out" && rm -f "$tmp/out";; - *) rm -f "$ac_file" && mv "$tmp/out" "$ac_file";; - esac \ - || as_fn_error "could not create $ac_file" "$LINENO" 5 - ;; - - - - esac - -done # for ac_tag - - -as_fn_exit 0 -_ACEOF -ac_clean_files=$ac_clean_files_save - -test $ac_write_fail = 0 || - as_fn_error "write failure creating $CONFIG_STATUS" "$LINENO" 5 - - -# configure is writing to config.log, and then calls config.status. -# config.status does its own redirection, appending to config.log. -# Unfortunately, on DOS this fails, as config.log is still kept open -# by configure, so config.status won't be able to write to it; its -# output is simply discarded. So we exec the FD to /dev/null, -# effectively closing config.log, so it can be properly (re)opened and -# appended to by config.status. When coming back to configure, we -# need to make the FD available again. -if test "$no_create" != yes; then - ac_cs_success=: - ac_config_status_args= - test "$silent" = yes && - ac_config_status_args="$ac_config_status_args --quiet" - exec 5>/dev/null - $SHELL $CONFIG_STATUS $ac_config_status_args || ac_cs_success=false - exec 5>>config.log - # Use ||, not &&, to avoid exiting from the if with $? = 1, which - # would make configure fail if this is the last instruction. - $ac_cs_success || as_fn_exit $? -fi -if test -n "$ac_unrecognized_opts" && test "$enable_option_checking" != no; then - { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: unrecognized options: $ac_unrecognized_opts" >&5 -$as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2;} -fi - -chmod a+x utils/ssh-killall - -if test "x$HAVE_PTHREAD" != xyes; then - echo "" - { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: *** Will not use pthreads in this configure" >&5 -$as_echo "$as_me: WARNING: *** Will not use pthreads in this configure" >&2;} -elif test "x$HAVE_SEMAPHORE" != xyes; then - echo "" - { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: *** O/S semaphores not found. Using TOP-C semaphores" >&5 -$as_echo "$as_me: WARNING: *** O/S semaphores not found. Using TOP-C semaphores" >&2;} -elif test "x$linux_pthread_sem_bug" = "xyes"; then - echo "" - { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: *** Using TOP-C semaphore due to possible bug in O/S sem" >&5 -$as_echo "$as_me: WARNING: *** Using TOP-C semaphore due to possible bug in O/S sem" >&2;} - { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: *See http://www.ccs.neu.edu/home/gene/linuxthreads-bug.html" >&5 -$as_echo "$as_me: WARNING: *See http://www.ccs.neu.edu/home/gene/linuxthreads-bug.html" >&2;} - { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: * if you are curious about a bug in earlier Linux threads" >&5 -$as_echo "$as_me: WARNING: * if you are curious about a bug in earlier Linux threads" >&2;} -fi - -chmod a+x bin/topcc bin/topc++ bin/topc-config - -# --enable-batch not currently among our configure options -if test "x$enable_batch" != xyes; then - echo "" - echo "Now please type \`${TB}make${TN}' to compile. Good luck." - echo "" -else - make -fi diff --git a/topc-2.5.2/configure.ac b/topc-2.5.2/configure.ac deleted file mode 100644 index 87a4218f..00000000 --- a/topc-2.5.2/configure.ac +++ /dev/null @@ -1,264 +0,0 @@ -# This file is used for TOP-C development, only -- not for making TOP-C -# Process this file with autoconf to produce a configure script. -# For debugging, invoke as: env CFLAGS=-g ./configure -# For testing portability, invoke as: env "CFLAGS=-Wall -W" ./configure -# For alternate C compiler, invoke as: -# env CC=cc ./configure --cache-file=/dev/null - -AC_INIT(TOP-C,0.0.0,[gene@ccs.neu.edu]) -AC_CONFIG_SRCDIR([src/topc.c]) - -# Set version number -TOPC_VERSION=2.5.2 -TOPC_UPDATED="April, 2011" - -# Checks for programs. -AC_PROG_CC -AC_PROG_LN_S -AC_PROG_MAKE_SET -AC_PROG_RANLIB - -# Mostly for Solaris: -# libxnet is a small subset. If functions still missing, add other libs. -# Note that last libraries added to $LIBS appears as first one. -AC_CHECK_FUNC(connect, , AC_CHECK_LIB(xnet, connect)) -AC_CHECK_FUNC(socket, , AC_CHECK_LIB(socket, socket)) -AC_CHECK_FUNC(gethostbyname, , AC_CHECK_LIB(nsl, gethostbyname)) -LIBSFORSOCKETS="$LIBS" -AC_CHECK_LIB(efence, malloc, LIBEFENCE=-lefence, LIBEFENCE= ) -LIBS= -AC_CHECK_FUNC(nanosleep, , AC_CHECK_LIB(rt, nanosleep)) -LIBSFORSLEEP="$LIBS" -LIBS= - -LIBSFORMPI="$LIBSFORSLEEP" -LIBSFORPTHREAD="$LIBSFORSLEEP" -LIBSFORSEQ="$LIBSFORSLEEP" - -AC_ARG_ENABLE(cxx, - [ --enable-cxx provide topc++ for C++ [default=yes]], - , enable_cxx=yes) -if test "x$enable_cxx" = "xyes"; then - AC_PROG_CXX -fi - -AC_ARG_ENABLE(posix-1c-threads, - [ --enable-posix-1c-threads - turn on strict POSIX 1C [default=no]], - , enable_posix_1c_threads=no) -if test "x$enable_posix_1c_threads" = "xyes"; then - CFLAGS_FOR_POSIX_1C="-D_POSIX_C_SOURCE=199506L" -fi - -AC_ARG_ENABLE(pthread, - [ --enable-pthread POSIX threads for shared memory [default=yes]], - , enable_pthread=yes) - -if test "x$enable_pthread" = "xyes"; then - # AC_CHECK_HEADER(pthread.h) - # This call adds -lpthread to LIBS - AC_CHECK_LIB(pthread, pthread_create) - # We temporarily add "-lpthread" because AC_CHECK_LIB fails to find it - # on Alpha: OSF1-4.0 fails to find it. - # __pthread_create in: /usr/shlib/libpthread.so - # and pthread.h redefines pthread_create to __pthread_create - # and declare return type as int. This conflicts with char return - # type declared in AC_CHECK_LIB. - AC_MSG_CHECKING(for working pthread library) - ac_save_LIBS="$LIBS" - LIBS="-lpthread $LIBS" - AC_TRY_RUN(#include - int main() { - pthread_mutex_t mutex; if(0 != pthread_mutex_init(&mutex, NULL)) exit(1); - return(0); } - , - HAVE_PTHREAD=yes, HAVE_PTHREAD=no, HAVE_PTHREAD=no) - - AC_MSG_RESULT($HAVE_PTHREAD) - LIBS="$ac_save_LIBS" - LIBPTHREAD="$LIBS" - AC_CHECK_LIB(posix4, sem_init) - AC_MSG_CHECKING(for working semaphore library) - AC_TRY_RUN(#include - int main() { sem_t sem; if(0 != sem_init(&sem, 0, 0)) exit(1); - return(0); } - , - HAVE_SEMAPHORE=yes, HAVE_SEMAPHORE=no, HAVE_SEMAPHORE=no) - AC_MSG_RESULT($HAVE_SEMAPHORE) - LIBSFORPTHREAD="$LIBS $LIBSFORPTHREAD" -else - HAVE_PTHREAD=no -fi - -# LIBS="$LIBSFORSOCKETS $LIBSFORPTHREAD" - -AC_ARG_ENABLE(strip-libs, - [ --enable-strip-libs Smaller image, but no symbolic debugging [default=no]], - , enable_strip_libs=no) - -if test "x$enable_strip_libs" = "xyes"; then - STRIP_LIBS=yes - STRIP=strip -else - STRIP=: -fi - -AC_ARG_WITH(mpi-cc, -[ --with-mpi-cc=PROG Use PROG to compile mpi files [default=built-in MPI] - (Also consider: env CC=cc ./configure (use vendor cc); - see appendix of manual for more on non-default MPI)], -, with_mpi_cc=no) -AC_ARG_WITH(mpi-cxx, -[ --with-mpi-cxx=PROG Use PROG to compile mpi files [default=built-in MPI] - (Also consider: env CXX=c++ ./configure (vendor C++))], -, with_mpi_cxx=no) -if test "x$with_mpi_cxx" = "xno"; then - MPICXX='$'{CXX} -else - MPICXX="$with_mpi_cxx" -fi -if test "x$with_mpi_cc" = "xno"; then - libmpi="-lmpinu" - MPICC='$'{CC} -else - HAVE_MPI_H=1 -# AC_DEFINE(HAVE_MPI_H) [Do it below, after resetting DEFS) - MPICC="$with_mpi_cc" -fi -LIBSFORMPI="$libmpi $LIBSFORSOCKETS $LIBSFORMPI" -# topc-config.in: --mpi) -# Note that with_mpi_cc != no means libmpi="". -# This is the right thing if using ${MPICC} -# Maybe we should have undocumented --mpi-internal returning this, -# which is called from topcc.in and topc++.in, -# while --mpi should indicate problem and: exit 1 -# # Do all of this for MPICXX also - -# Checks for header files. -AC_HEADER_STDC -AC_HEADER_SYS_WAIT -AC_CHECK_HEADERS([fcntl.h limits.h netdb.h netinet/in.h stdlib.h string.h sys/socket.h sys/time.h unistd.h]) -AC_CHECK_HEADERS(pthread.h semaphore.h) - -# Checks for typedefs, structures, and compiler characteristics. -AC_C_CONST -AC_TYPE_PID_T -AC_TYPE_SIZE_T -AC_HEADER_TIME - -# Checks for library functions. -# This defines HAVE_MALLOC if malloc(0) returns valid ptr instead of NULL. -AC_FUNC_MALLOC -# AC_FUNC_MMAP -AC_TYPE_SIGNAL -AC_FUNC_STAT -AC_FUNC_VPRINTF -AC_CHECK_FUNCS([alarm getcwd gethostbyname gethostname memset select socket strchr strerror strtol]) - -# Erase old @DEFS@ and add to it -rm -rf conftest* confdefs.h -# AIX cpp loses on an empty file, so make sure it contains at least a newline. -echo > confdefs.h -if test "$HAVE_MPI_H" != ""; then - AC_DEFINE(HAVE_MPI_H) -fi; - -# AIX-cc doesn't allow "// ..." style commenting by default. -# AIX-xlc is IBM ANSI C, while cc is IBM extended C and xlC is C++/C -# OSF1: libpthread in weird place, not found by this script -# In linuxthreads-2.0.6 and also in some later versions using "old semaphore", -# make parfactor-pthread occasionally fails. -# Enable ASSERT in linuxthreads:queue.h for the 'smoking gun' -# We disable all of linuxthreads semaphores until we can test linuxthreads-2.0.7 -target=`uname -s` -case $target-$CC in - IRIX64-*) AC_DEFINE(HAVE_PROCESS_SCOPE_BOUND_NP) ;; - AIX-xlc) CFLAGS="$CFLAGS -qcpluscmt" ;; - AIX-xlC) CFLAGS="$CFLAGS -qcpluscmt" ;; - AIX-cc) CFLAGS="$CFLAGS -qcpluscmt" ;; - Linux-*) linux_pthread_sem_bug=yes ;; - OSF1-*) if test x$HAVE_PTHREAD = xyes; then - LIBSFORPTHREAD="-lpthread $LIBSFORPTHREAD" - fi - ;; -esac - -# Substitute shell variables -AC_SUBST(TOPC_VERSION) -AC_SUBST(TOPC_UPDATED) -AC_SUBST(PWD) -AC_SUBST(HOSTNAME) -AC_SUBST(LIBSFORSOCKETS) -AC_SUBST(LIBSFORSLEEP) -AC_SUBST(LIBSFORMPI) -AC_SUBST(LIBPTHREAD) -AC_SUBST(HAVE_PTHREAD) -AC_SUBST(LIBSFORPTHREAD) -AC_SUBST(LIBSFORSEQ) -AC_SUBST(CFLAGS_FOR_POSIX_1C) -AC_SUBST(LIBEFENCE) -AC_SUBST(STRIP_LIBS) -AC_SUBST(STRIP) -AC_SUBST(MPICC) -AC_SUBST(MPICXX) - -if test "x$HAVE_PTHREAD" = "xyes"; then - # Older Solaris has only thr_setconcurrency() - # AC_CHECK_FUNCS(FUNC)/AC_CHECK_HEADERS(file.h) (plural forms only) - # do AC_DEFINE(HAVE_FUNC), AC_DEFINE(HAVE_FILE_H) - AC_CHECK_FUNCS(pthread_setconcurrency thr_setconcurrency) - - # Alternative, but would also need in conf.h.in: #include - # if test "$ac_cv_func_pthread_setconcurrency" != yes; then - # AC_CHECK_FUNC(thr_setconcurrency, - # , AC_DEFINE(pthread_setconcurrency, thr_setconcurrency) - # AC_DEFINE(HAVE_PTHREAD_SETCONCURRENCY) - # ) - # fi - if test "x$HAVE_SEMAPHORE" != "xyes"; then - AC_DEFINE(HAVE_SEMAPHORE, 0) - elif test "x$linux_pthread_sem_bug" = "xyes"; then - AC_DEFINE(HAVE_SEMAPHORE,0) - fi -else - AC_DEFINE(HAVE_PTHREAD, 0) -fi - -# if test "x$with_static_cache_size" = "xno"; then -# AC_DEFINE(STATIC_CACHE_SIZE, 0) -# elif test "x$with_static_cache_size" != "xyes"; then -# AC_DEFINE_UNQUOTED(STATIC_CACHE_SIZE, $with_static_cache_size) -# fi - -AC_CONFIG_FILES([src/Makefile - src/mpinu/Makefile src/mpinu/procgroup - bin/Makefile bin/topcc bin/topc++ bin/topc-config - doc/Makefile doc/topcc.1 doc/topc-version.texi - utils/ssh-killall Makefile README - ]) -AC_OUTPUT -chmod a+x utils/ssh-killall - -if test "x$HAVE_PTHREAD" != xyes; then - echo "" - AC_MSG_WARN(*** Will not use pthreads in this configure) -elif test "x$HAVE_SEMAPHORE" != xyes; then - echo "" - AC_MSG_WARN(*** O/S semaphores not found. Using TOP-C semaphores) -elif test "x$linux_pthread_sem_bug" = "xyes"; then - echo "" - AC_MSG_WARN(*** Using TOP-C semaphore due to possible bug in O/S sem) - AC_MSG_WARN(*See http://www.ccs.neu.edu/home/gene/linuxthreads-bug.html,) - AC_MSG_WARN(* if you are curious about a bug in earlier Linux threads) -fi - -chmod a+x bin/topcc bin/topc++ bin/topc-config - -# --enable-batch not currently among our configure options -if test "x$enable_batch" != xyes; then - echo "" - echo "Now please type \`${TB}make${TN}' to compile. Good luck." - echo "" -else - make -fi diff --git a/topc-2.5.2/doc/Makefile b/topc-2.5.2/doc/Makefile deleted file mode 100644 index a01c2b3d..00000000 --- a/topc-2.5.2/doc/Makefile +++ /dev/null @@ -1,87 +0,0 @@ -# doc/Makefile. Generated from Makefile.in by configure. - -# You should be able to type: make topc.xxx -# for the format documentation that you prefer. -# If this doesn't work on your system, you can download -# the TOP-C documentation in all formats from XXX? - -default: topc.info topc.dvi topc.pdf topc.html - -all: txt info dvi ps pdf html -info: topc.info -html: topc.html -dvi: topc.dvi -txt: topc.txt -ps: topc.ps -pdf: topc.pdf - -topc.info: topc.texi - @ makeinfo topc.texi || \ - ( echo "*** Can't make topc.info; missing makeinfo ??"; \ - echo "*** Download topc-docs.tar.gz for a copy" ) - -# Apparently texindex topc.fn and texindex topc.vr not needed. -topc.dvi: topc.texi - texi2dvi topc.texi - -topc.html: html/topc_toc.html - -# Not needed: Newer tex12html automatically makes background color white. -# ( cd html; for file in *.html; do \ -# patch -s -N $$file < color.patch; \ -# done ) -html/topc_toc.html: topc.texi - ( cd html; texi2html -split_chapter ../topc.texi ) - ( cd html; patch -s -N topc_toc.html < img.patch ) - ( cd html; rm -f *.orig ) - -topc.ps: topc.dvi - dvips -Ppdf -G0 topc.dvi - -topc.pdf: topc.ps - ps2pdf topc.ps - -topc.txt: topc.texi - texi2html -monolithic topc.texi - lynx -dump -nolist topc.html > topc.txt - rm -f topc.html - -clean: - rm -f topc.?? topc.??s *.aux *.log *~ - -# distribution of docs, only -dist: html dvi ps pdf - dir=`dirname $$PWD`; \ - name=`basename $$dir`; \ - version=2.5.2; \ - if [ "$$name" != "topc-$$version" ] ; then \ - echo "main dir, $$name, not same as topc-$$version" ; \ - exit 1; \ - fi; \ - mkdir topc-$$version; \ - cp html/* topc-$$version/; \ - cp topc.dvi topc-$$version/; \ - cp topc.ps topc-$$version/; \ - cp topc.pdf topc-$$version/; \ - ( cd topc-$$version; gzip topc.dvi; gzip topc.ps ); \ - cp topc.dvi topc-$$version/; \ - ( tar cvf ../../topc-$$version-html.tar ./topc-$$version; \ - gzip ../../topc-$$version-html.tar; ); \ - rm -rf topc-$$version; \ - ls -l ../../topc-$$version-html.tar.gz - -distclean: clean - rm -f topc.ps topc.pdf topc.txt - rm -rf topc-$$version - -maintainer-clean: distclean - rm -f topc.dvi topc.info* html/*.html - -install: topc.info - cp topc.info ${prefix}/share/info || \ - ( echo "*** Insufficient permission to copy to ${prefix}/share/info"; \ - echo "*** Can't intall topc.info" ) - sh -c 'install-info --version' 2&> /dev/null && \ - install-info topc.info ${prefix}/share/info || \ - ( echo "*** Couldn't find 'install-info' or insuff. permission"; \ - echo "*** Can't intall topc.info" ) diff --git a/topc-2.5.2/doc/Makefile.in b/topc-2.5.2/doc/Makefile.in deleted file mode 100644 index 99b94aef..00000000 --- a/topc-2.5.2/doc/Makefile.in +++ /dev/null @@ -1,87 +0,0 @@ -# @configure_input@ - -# You should be able to type: make topc.xxx -# for the format documentation that you prefer. -# If this doesn't work on your system, you can download -# the TOP-C documentation in all formats from XXX? - -default: topc.info topc.dvi topc.pdf topc.html - -all: txt info dvi ps pdf html -info: topc.info -html: topc.html -dvi: topc.dvi -txt: topc.txt -ps: topc.ps -pdf: topc.pdf - -topc.info: topc.texi - @ makeinfo topc.texi || \ - ( echo "*** Can't make topc.info; missing makeinfo ??"; \ - echo "*** Download topc-docs.tar.gz for a copy" ) - -# Apparently texindex topc.fn and texindex topc.vr not needed. -topc.dvi: topc.texi - texi2dvi topc.texi - -topc.html: html/topc_toc.html - -# Not needed: Newer tex12html automatically makes background color white. -# ( cd html; for file in *.html; do \ -# patch -s -N $$file < color.patch; \ -# done ) -html/topc_toc.html: topc.texi - ( cd html; texi2html -split_chapter ../topc.texi ) - ( cd html; patch -s -N topc_toc.html < img.patch ) - ( cd html; rm -f *.orig ) - -topc.ps: topc.dvi - dvips -Ppdf -G0 topc.dvi - -topc.pdf: topc.ps - ps2pdf topc.ps - -topc.txt: topc.texi - texi2html -monolithic topc.texi - lynx -dump -nolist topc.html > topc.txt - rm -f topc.html - -clean: - rm -f topc.?? topc.??s *.aux *.log *~ - -# distribution of docs, only -dist: html dvi ps pdf - dir=`dirname $$PWD`; \ - name=`basename $$dir`; \ - version=@TOPC_VERSION@; \ - if [ "$$name" != "topc-$$version" ] ; then \ - echo "main dir, $$name, not same as topc-$$version" ; \ - exit 1; \ - fi; \ - mkdir topc-$$version; \ - cp html/* topc-$$version/; \ - cp topc.dvi topc-$$version/; \ - cp topc.ps topc-$$version/; \ - cp topc.pdf topc-$$version/; \ - ( cd topc-$$version; gzip topc.dvi; gzip topc.ps ); \ - cp topc.dvi topc-$$version/; \ - ( tar cvf ../../topc-$$version-html.tar ./topc-$$version; \ - gzip ../../topc-$$version-html.tar; ); \ - rm -rf topc-$$version; \ - ls -l ../../topc-$$version-html.tar.gz - -distclean: clean - rm -f topc.ps topc.pdf topc.txt - rm -rf topc-$$version - -maintainer-clean: distclean - rm -f topc.dvi topc.info* html/*.html - -install: topc.info - cp topc.info @infodir@ || \ - ( echo "*** Insufficient permission to copy to @infodir@"; \ - echo "*** Can't intall topc.info" ) - sh -c 'install-info --version' 2&> /dev/null && \ - install-info topc.info @infodir@ || \ - ( echo "*** Couldn't find 'install-info' or insuff. permission"; \ - echo "*** Can't intall topc.info" ) diff --git a/topc-2.5.2/doc/NOTES/dead_socket_behavior.txt b/topc-2.5.2/doc/NOTES/dead_socket_behavior.txt deleted file mode 100644 index 184383af..00000000 --- a/topc-2.5.2/doc/NOTES/dead_socket_behavior.txt +++ /dev/null @@ -1,168 +0,0 @@ -THESE ARE OLD DESIGN NOTES FOR HANDLING ISSUE OF DEAD SLAVES. -THE FIRST PART ABOUT THE UNIUX/Linux HANDLING OF DEAD SOCKECTS - IS STILL PERTINENT. - -document: - -When a socket is dead, it will send a FIN to its partner. -An RST is TCP's response to some packets that it doesn't expect and has no other way of -dealing with. A common case is when the peer closes the connection (sending you a FIN) -but you ignore it because you're writing and not reading. So you write to a -connection that has been closed by the other end and the other end's TCP responds -with an RST. - -The following is what we observed on Sun Solaris and isn't documented . -1. Reading a FIN, the read() call will return 0 and no error is set. -The following read() calls will return 0 and no error is set. - -2. Having not read the FIN and writing to a dead socket, it will recieve an RST from the partner. -The following write() call will generate a sigpipe signal, return -1 with error = EPIPE. - -3. The first read() call, on a socket that has recieved an RST, will return -1 with error = ECONNRESET. -The following read() calls will return 0 and errno is not reset. - -4. If there is a FIN received by the socket, the select() call will indicate -that the socket is both readable and writable. - -EPIPE(32): -Broken pipe. A write on a pipe or FIFO for which there is no process to read the data. - -ECONNRESET(131): -Connection reset by peer. A connection was forcibly closed by a peer. -This normally results from a peer executing a shutdown(2) call. - - - -logic of TOP-C when slaves dies - comm-recv() : call MPI_Recv - comm-send() : call MPI_Send - -MPINU uses SO_KEEPALIVE. Therefore it ignores SIGPIPE signals. Otherwise, whenever SO_KEEPALIVE - ceates a new probe on the socket, if the socket is dead, the TOPC process will die. -If socket dies, SO_KEEPALIVE continues to probe, causing -extra SIGPIPE's. But when we discover dead slave, we'll close socket. - -in MPI: -slave[]; -initialization: slave[i] = ALIVE; -if slave[i] == DEAD , meaning ith slave dead. - - - -comm-recv(){ - - tryagain: - - MPI_Probe(,, &status, ); //MPI_Probe calls select() and MPI_read_hdr() - //In MPI_read_hdr, if read returns 0, we know the socket is dead and we should - //clear this socket in the fd_set, so in the future we will not check this socket any more - //slave[i] = DEAD; - MPI_Probe computes msg size and decides MPI_SOURCE according to status. - - - MPI_Recv() is called by comm-recv() with msg size and source parameters filled in by MPI_Probe(); - - -SUPPOSE: socket dies after MPI_Probe() call and before or during MPI_Recv() call returns, -SOLUTION: delete the dead socket and call MPI_Probe() again, this is done transparently to TOP-C. - - if(MPI_FAIL == MPI_Recv(, status.MPI_SOURCE, size, , ) - goto tryAgain; - //in MPI_Recv, if recv() call also returns 0 or -1 with ECONNRESET, - //we should clear the socket in the fd_set. - //MPI_Recv return MPI_FAIL; - //slave[i] = DEAD; -} - - - -comm-send(){ - - if(MPI_FAIL == MPI_Send()) - //If MPI_Send() returns fail, we ignore the failure and detect it later - //when task's ID is out of some scope. - //Also we make some changes in MPI_Send(), if MPI_Send() finds out a socket is dead, - //MPI_Send() will deletes that socket from the fd_set. - - //MPI_Send call send(), if send() call return -1 and errno = EPIPE, - //we should clear the socket in the fd_set - //MPI_Send return MPI_FAIL; - //revise comm-send() return TOPC_BOOL and - //need to fix other comm-send() functions in other senarios, such as TOPC-seq - //the logic of TOPC is: - //ignore the return value of comm_send() - //consider every task is sent out and put it in task queue - //using the task ID values as the time expire label - //resend task if the ID indicates that task need to be resend -} - -When a task times out in src/topc.c: -Maintain a task queue for tasks that have been sent out and have not been done by slaves and are ordered -according to ID assigned . -If the deduction of the ID of the current done task is larger than the sum of the ID of the first task -on the task queue compared and a threshold value, -send this task to another alive idle slave, remove it from the head of the task queue, -put it at the tail of the task queue, and change the its ID to the new generated ID. - - -Another Issues: -1. Maybe one slave is dead and TOP-C is waiting for time out. If slave is working on the last task, timeout never arrives. - -Solution: -In topc.c, if master discovers only one task remaining, master sends a PING to -check if socket alive. If not alive, declare slave dead ans reassign that task. - -2. Add one status to slave, slow_slave(). -So a slave could be busy, slow or dead. -Logic in topc.c: - -//=========================== -// Anaylyze slow slave to see if it should be dead. -static struct ... *slow_slave = NULL; // initially : task_id: 0; - -// call this instead of slave[rank].dead = 1 -void slow_slave(rank) { - if (slow_slave == NULL) { - slow_slave = malloc (num_slaves* sizeof(struct ...)); - for i = 0 .. num_slaves-1 - slow_slave[rank].task_id = -1; - } - - if slave[rank].task_id is equal to slow_slave[rank].task_id (original task_id) - // then check if we waited at least one minute - if time() - slow_slave[rank].current_elapsed_time > 1 minute - declare slave dead: slave[rank].dead = 1 - else - just return, and master will check again on next cycle - else - // slave was slow on previous task, but not on current taks - Reset slow slave[rank] ={slave[rank].task_id: latest current_elapse_time using time() } - -} - - - -//=========================== -//For the slave that does the last task, it may not read the END_MASTER_SLAVE_TAG. -The scenario is: -Master: -1. send out the last task -2. find the slave that is doing the last task timeout, then - send a ping tag to it to make sure it is still alive. -3. recieve the last task output. -4. send out END_MASTER_SLAVE_TAG to all slaves. -5. call TOPC_finalize, MPI_finalize: MPI_finalize will colse all sockets. -6. Wait for all zombie processes. - -Slave: -1. receive the task input -2. send out the task result -3. read the PING_TAG. -4. reply with PING_TAG. - -The problem: if slave replies after master has done step 5, slave -observe the dead socket and will not read/write to this socket any more. -So, slave may not read the END_MASTER_SLAVE_TAG and hang there. - -Solution: -For slave it just ignores the PING_TAG and continue as usual. diff --git a/topc-2.5.2/doc/NOTES/topc-architecture b/topc-2.5.2/doc/NOTES/topc-architecture deleted file mode 100644 index 9ca01dd6..00000000 --- a/topc-2.5.2/doc/NOTES/topc-architecture +++ /dev/null @@ -1,119 +0,0 @@ -topc.c contains the main algorithm. - topc.c, options.c, memory.c and procgroup.c form a layer on top of - the `comm' layer: - options.c introduces the global, non-static symbols TOPC_OPT_* - and the constants SAFETY_* - in comm.h and topc.h - memory.c exports MEM_malloc, MEM_register_buf, MEM_free, - TOPC_MSG, TOPC_MSG_PTR - The comm layer includes: comm-mpi.c, comm-pthread.c and comm-seq.c - The interface to the comm layer is through symbols: COMM_* - that are declared in comm.h - The comm-mpi.c module sits on top of MPINU (an MPI layer). - -MAIN PROCEDURES: - The primary routines are: - TOPC_master_slave: contains `heart' of the algorithm - TOPC_raw_submit_task_input (especially) - and TOPC_raw_begin_master_slave, TOPC_raw_end_master_slave - together have the equivalent functionality of TOPC_master_slave - Some global variables are: - num_slaves - num_idle_slave (# for which slave[i].busy == FALSE) - num_dead_slaves (# for which slave[i].dead == TRUE) - - TOPC_master_slave calls: - wait_until_an_idle_slave - COMM_generate_task_input - MEM_registger_buf (see memory module) - submit_task_input (if new input available) - receive_task_output (if no new input available, blocks until output avail.) - wait_until_an_idle_slave calls: - If num_idle_slaves > 0, just return immediately. - receive_task_output (if no slaves are idle, this will create an idle slave) - new_dead_slave (Now there is one idle slave; check if it is dead) - submit_task_input (if it was dead, resubmit its task to a new slave) -QUESTION: suppose no new idle slave is available? - If num_idle_save == 0 still, go back to receive_task_output - submit_task_input calls: - PRECONDITION: num_idle_slaves > 0 - find_available_slave (Precodition is that num_idle_slaves > 0) - trace_input - add_to_aggregate_buffer (If application using aggregated tasks) - send_task_input - send_task_input calls: - update_slave - COMM_send_msg - receive_task_output calls: - COMM_receive_msg - trace_result - COMM_free_receive_buf (tell COMM layer to free the receive buffer that - it created in COMM_receive_msg) - free_input_data (MEM_free) - -initialization: - -aggregated tasks: - Code for aggregated tasks limited to: if (TOPC_OPT_aggregated_tasks > 1) - and it occurs only in src/topc.c . - If next task input is NOTASK, send out pending task (don't wait). - Note that if pending message too large, submit_task_input calls - itself again with argument NOTASK as signal to send out. - At beginning of TOPC_master_slave, on master, each slave_array element - (for each slave) is given buffer - for aggreg_inputs of default size AGGREG_TASKS_SIZE . - The buffer is freed at end of TOPC_master_slave. - For any "large message" (pending message whose size goes over - AGGREG_TASKS_SIZE), we call realloc() to resize the buffer. - The new size may be larger or smaller than previously. The - cost of realloc() will be small compared to sending a large message. - "Small messages" don't require realloc. - The pending message is always kept in the buffer of aggreg_tasks, - which is static in submit_task_input. When the buffer is sent - out, the buffer of aggreg_tasks is exchanged with that of - the slave_array element for the right slave. - -updates: - Updates must be broadcast to all slaves. Since some slaves are - typically busy, we implement an update_queue to hold pending updates. - The primary procedures are: - - update_slave: - - -dead slaves: - COMM_send_msg: - Check for dead slave whenever COMM_send_msg. If dead slave - found, record dead and increment nm_dead_slaves - broadcast_update: broadcast to slave only if it's not dead - find_available_slave: satisfying ! slave[i].dead - receive_task_output: ignore output from dead slaves - wait_until_an_idle_slave: - If idle slave is dead, resubmit its input and try again for idle slave -QUESTION: Suppose it's a CONTINUATION? (input is not original input) - master_slave_chdir: Don't do it for dead slaves - TOPC_master_slave: We receive_task_output only if - num_idle_slaves + num_dead_slaves < num_slaves - -memory: - We want to check if an application calls TOPC_MSG() twice, since this - can cause memory leaks. An application calls TOPC_MSG(), which uses - MEM_malloc to allocate new memory. MEM_register_buf is called - from within the heart of TOP-C, and it records that the MEM_malloc - buffer was passed to TOP-C. If also checks that there are no - outstanding earlier MEM_malloc buffers that have not yet been registerd. - Finally, MEM_free is used by the heart of TOP-C to free any - MEM_malloc buffers that TOP-C no longer uses. Since TOP-C's own - TOPC_MSG had internally called MEM_malloc, the application code should - have no pointers to this internal buffer that is freed by MEM_free. - - In fact, topc.c uses free_input_data to free any buffers on the master - side. This directly calls MEM_free. On the slave side, - MEM_free is called directly from inside slave_loop. - -receive threads: - - - -============================================== -memory module (MEM_*): diff --git a/topc-2.5.2/doc/NOTES/topc_further_adjustment.txt b/topc-2.5.2/doc/NOTES/topc_further_adjustment.txt deleted file mode 100644 index adb00424..00000000 --- a/topc-2.5.2/doc/NOTES/topc_further_adjustment.txt +++ /dev/null @@ -1,37 +0,0 @@ -I THINK THESE ARE OLD COMMENTS, NO LONGER APPLICABLE. CHECK AND DELETE. - -1. for MPI_Send() : - in MPINU: don't declare slave_q[] - in comm-send: if MPI_Send() returns fail, comm-send() return -1, - in topc.c we can update the slave_q[] according to the return value of - comm-send(); -2. for MPI_Recv(): -It will not update slave_[q] , just return fail. -Although TOPC at this moment doesn't know the slave is dead, but later -when TOPC tries to send a message to this slave, the dead slave will be -detected. Otherwise, when a task times out, master also can detect the dead -slaves. - -3. MPINU will get rid of the slave_q[] array. -IN topc.c: we can use slave_array[] instead of slave_q[]; -slave_array[] is an array of slave records. -In slave recordd, there is a field, dead, indicating the slave is dead of alive. -If dead == true, then slave is dead , otherwise slave is alive. - - -4. look at maxID and last_task_id if they are equal. -If equal then use last_task_id instead of maxID. - -5. don't need to maintain a task queue. -Let n be the number of slaves. -The idea is: -After every n tasks are done, go over slave_array[] and check every slave is busy -or idle. If the slave is busy and the task id of that slave is bigger than some -kind of threshold, then resend the task. -When compute the difference of two ids, we need to consider the wrap arround values. -the difference of two ids: dif1 = |id1 - id2| -dif2 = (id2 + maxid - id1) -if min(dif1, dif2) < threshold, then resend task with id1. - - -6. diff --git a/topc-2.5.2/doc/html/action.gif b/topc-2.5.2/doc/html/action.gif deleted file mode 100644 index b7273412..00000000 Binary files a/topc-2.5.2/doc/html/action.gif and /dev/null differ diff --git a/topc-2.5.2/doc/html/color.patch b/topc-2.5.2/doc/html/color.patch deleted file mode 100644 index 9efcaead..00000000 --- a/topc-2.5.2/doc/html/color.patch +++ /dev/null @@ -1,4 +0,0 @@ -8c8 -< ---- -> diff --git a/topc-2.5.2/doc/html/img.patch b/topc-2.5.2/doc/html/img.patch deleted file mode 100644 index 9bd4f407..00000000 --- a/topc-2.5.2/doc/html/img.patch +++ /dev/null @@ -1,2 +0,0 @@ -9a10 -> [TOP-C logo] diff --git a/topc-2.5.2/doc/html/logo.gif b/topc-2.5.2/doc/html/logo.gif deleted file mode 100644 index f57fd2d0..00000000 Binary files a/topc-2.5.2/doc/html/logo.gif and /dev/null differ diff --git a/topc-2.5.2/doc/html/task.gif b/topc-2.5.2/doc/html/task.gif deleted file mode 100644 index 5a45ce46..00000000 Binary files a/topc-2.5.2/doc/html/task.gif and /dev/null differ diff --git a/topc-2.5.2/doc/html/topc.html b/topc-2.5.2/doc/html/topc.html deleted file mode 100644 index 47c4fec4..00000000 --- a/topc-2.5.2/doc/html/topc.html +++ /dev/null @@ -1,216 +0,0 @@ - - - - - -TOP-C (Task Oriented Parallel C/C++): TOP-C (Task Oriented Parallel C/C++) - - - - - - - - - - - - - - - - - -
[Top][Contents][Index][ ? ]
-

TOP-C (Task Oriented Parallel C/C++)

- -This documents version 2.5.0 of
-`TOP-C' (Task Oriented Parallel C/C++),
-last updated September, 2004. -

- -

- - - - - - - - - - - - - - - - -
1. `TOP-C' Copying Conditions  
2. Quick Start: Installation and Test Run  
3. Overview of `TOP-C/C++'  
4. Writing `TOP-C' Applications  
5. Compiling and Invoking `TOP-C' Applications  
6. Debugging and Tracing  
7. Performance and Long Jobs  
8. Advanced Features of `TOP-C'  
9. `TOP-C' Raw Interface for Parallelizing Sequential Code  
10. Acknowledgements  
A. Summary of `TOP-C' Commands  
B. Example `TOP-C' Application  
C. Using a Different `MPI' with TOP-C  
Function Index  
Variable Index  
Concept Index  
- -
- -- The Detailed Node Listing --- -
- -
-Overview of `TOP-C/C++' -
- -
- - - - -
3.1 Programmer's Model  
3.2 Three Key Concepts for TOP-C  
3.3 Distributed and Shared Memory Models  
- -
-Programmer's Model -
- -
- - - - - -
3.1.1 Structure of a TOP-C Program  
3.1.2 Four Callback Functions  
3.1.3 Task Input and Task Output Buffers  
3.1.4 The `TOP-C' Algorithm  
- -
-Task Input and Task Output Buffers -
- -
- - - -
Defining Application Task Buffers  
Marshaling (Serialization) and Heterogeneous Architectures  
- -
-Writing `TOP-C' Applications -
- -
- - - - - -
4.1 The Main TOP-C Library Calls  
4.2 Callback Functions for TOPC_master_slave()  
4.3 Actions Returned by CheckTaskResult()  
4.4 TOP-C Utilities  
- -
-Compiling and Invoking `TOP-C' Applications -
- -
- - - - - - -
5.1 Compiling TOP-C Applications  
5.2 Command Line Options in TOP-C Applications  
5.3 Invoking a TOP-C Application in Sequential Memory  
5.4 Invoking a TOP-C Application in Distributed Memory  
5.5 Invoking a TOP-C Application in Shared Memory  
- -
-Invoking a TOP-C Application in Distributed Memory -
- -
- - - -
5.4.1 Writing Procgroup Files for `MPINU'  
5.4.2 If Slaves Fail to Start  
- -
-Debugging and Tracing -
- -
- - - - - - - -
6.1 Debugging by Limiting the Parallelism  
6.2 Debugging with `--TOPC-safety'  
6.3 TOP-C and POSIX signals  
6.4 Tracing Messages  
6.5 Stepping Through a Slave Process with `gdb'  
6.6 Segmentation faults and other memory problems  
- -
-Performance and Long Jobs -
- -
- - - - -
7.2 Strategies for Greater Concurrency  
7.3 Improving Performance  
7.4 Long Jobs and Courtesy to Others  
- -
-Advanced Features of `TOP-C' -
- -
- - - - - - - -
8.1 Testing for Task Continuations and Redos  
8.2 Aborting Tasks  
8.3 Memory Allocation for Task Buffers  
8.4 Optimizing TOP-C Code for the Shared Memory Model  
8.5 Modifying TOP-C Code for the Sequential Memory Model  
8.6 Caveats  
- -
-Memory Allocation for Task Buffers -
- -
- - - - - -
8.3.1 Avoiding malloc and new with Task Buffers  
8.3.2 Using TOPC_MSG_PTR() to Avoid Copying Large Buffers  
8.3.3 Allocation and Freeing of Task Buffers for TOPC_MSG_PTR()  
8.3.4 Marshaling Complex Data Structures into `TOP-C' Task Buffers  
- -
-Optimizing TOP-C Code for the Shared Memory Model -
- -
- - - - - -
8.4.1 Reader-Writer Synchronization  
8.4.2 Thread-Private Global Variables  
8.4.3 Sharing Variables between Master and Slave and Volatile Variables  
8.4.4 SMP Performance  
- -
-`TOP-C' Raw Interface for Parallelizing Sequential Code -
- -
- - - - -
9.1 `TOP-C' raw functions  
9.2 Parallelizing `for' Loops  
9.3 Parallelizing `while' Loops  
-

- -


-
- -This document was generated -by Gene Cooperman on October, 6 2004 -using texi2html - - - - diff --git a/topc-2.5.2/doc/html/topc/topc.html b/topc-2.5.2/doc/html/topc/topc.html deleted file mode 100644 index 1da0fe0b..00000000 --- a/topc-2.5.2/doc/html/topc/topc.html +++ /dev/null @@ -1,235 +0,0 @@ - - - - - -TOP-C (Task Oriented Parallel C/C++): Top - - - - - - - - - - - - - - - - - - - - -
[Top][Contents][Index][ ? ]
-

TOP-C (Task Oriented Parallel C/C++) -

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - - - -
[Top][Contents][Index][ ? ]
-

- - This document was generated by Gene Cooperman on April, 15 2011 using texi2html 1.78. - -
- -

- - diff --git a/topc-2.5.2/doc/html/topc/topc_1.html b/topc-2.5.2/doc/html/topc/topc_1.html deleted file mode 100644 index 7a13037a..00000000 --- a/topc-2.5.2/doc/html/topc/topc_1.html +++ /dev/null @@ -1,115 +0,0 @@ - - - - - -TOP-C (Task Oriented Parallel C/C++): 1. TOP-C Copying Conditions - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

1. ‘TOP-C’ Copying Conditions

- -

All of the copyright notices of this package are designed to encourage -free copying and usage. This manual is copyright by Gene Cooperman. -Most of the source code files of the ‘TOP-C’ software package contain -a copyright notice similar to that below. At the current time, Some of -the source files are copyright by Gene Cooperman alone and some by both -Gene Cooperman and Victor Grinberg, but all files are distributed under -the GNU LGPL license referred to below. -

-
 
  **********************************************************************
-  * Copyright (c) 2000 - 2004 Gene Cooperman <gene@ccs.neu.edu>        *
-  *                                                                    *
-  * This library is free software; you can redistribute it and/or      *
-  * modify it under the terms of the GNU Lesser General Public         *
-  * License as published by the Free Software Foundation; either       *
-  * version 2.1 of the License, or (at your option) any later version. *
-  *                                                                    *
-  * This library is distributed in the hope that it will be useful,    *
-  * but WITHOUT ANY WARRANTY; without even the implied warranty of     *
-  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU   *
-  * Lesser General Public License for more details.                    *
-  *                                                                    *
-  * You should have received a copy of the GNU Lesser General Public   *
-  * License along with this library (see file COPYING); if not, write  *
-  * to the Free Software Foundation, Inc., 59 Temple Place, Suite      *
-  * 330, Boston, MA 02111-1307 USA, or contact Gene Cooperman          *
-  * <gene@ccs.neu.edu>.                                                *
-  **********************************************************************
-
- -
- - - - - - - - - - - - -
[ << ][ >> ]           [Top][Contents][Index][ ? ]
-

- - This document was generated by Gene Cooperman on April, 15 2011 using texi2html 1.78. - -
- -

- - diff --git a/topc-2.5.2/doc/html/topc/topc_10.html b/topc-2.5.2/doc/html/topc/topc_10.html deleted file mode 100644 index ce9e6617..00000000 --- a/topc-2.5.2/doc/html/topc/topc_10.html +++ /dev/null @@ -1,116 +0,0 @@ - - - - - -TOP-C (Task Oriented Parallel C/C++): 10. Acknowledgements - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

10. Acknowledgements

- -

A project of this scope cannot be achieved alone. While Gene Cooperman -was the primary author, the project has benefited from contributions -by several various individuals and institutions at different times. -

-

The author wishes to thank the National Science Foundation for -support under which much of this work was developed. -The author wishes to thank the Mariner Project at Boston University -for the use of the Origin 2000 and other facilities which helped in the -development of this software. An earlier, experimental version of mpinu -(MPI subset) was written by Markos Kyzas and partially revised by Gene -Cooperman. Michael Weller provided ideas for improving some of the C -code, and provided valuable feedback when he adapted the ‘TOP-C’ ideas -to a large application on an IBM SP-2. The loader module is joint -with Victor Grinberg. Further experience and feedback was gained -from the GAP community when the ‘TOP-C’ model was ported to ParGAP, a -refereed share package. (GAP – Groups, Algorithms and Programming) -is a language similar to Maple, specialized for symbolic computations -in computational algebra and especially computational group theory.) -‘TOP-C’, version 2, was exported by Victor Grinberg from ParGAP, with -enhancements by Gene Cooperman. Some important feedback was gained -in the TOP-C parallelization of Geant4. -(Geant4 is a toolkit for the Monte Carlo simulation of particle-matter -interaction. The package has close to a million lines of C++ code. -The TOP-C parallelization is included with the Geant4 distribution.) -Xiaoqin Ma analyzed mechanisms for -detecting and recovering from dead slaves, broken sockets, etc., -and wrote the first version of code to handle that. -

- - -
- - - - - - - - - - - - -
[ << ][ >> ]           [Top][Contents][Index][ ? ]
-

- - This document was generated by Gene Cooperman on April, 15 2011 using texi2html 1.78. - -
- -

- - diff --git a/topc-2.5.2/doc/html/topc/topc_11.html b/topc-2.5.2/doc/html/topc/topc_11.html deleted file mode 100644 index 1b1b97c6..00000000 --- a/topc-2.5.2/doc/html/topc/topc_11.html +++ /dev/null @@ -1,265 +0,0 @@ - - - - - -TOP-C (Task Oriented Parallel C/C++): A. Summary of TOP-C Commands - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

A. Summary of ‘TOP-C’ Commands

- -

From The Main TOP-C Library Calls. -

-
void TOPC_init ( int *argc, char ***argv )
-
void TOPC_finalize ( void )
-

Function -

-
void TOPC_master_slave
-

( TOPC_BUF (*generate_task_input)(),
   TOPC_BUF (*do_task)(void *input),
   TOPC_ACTION (*check_task_result)(void *input, void *output),
   void (*update_shared_data)(void *input, void *output) -
) -

Function -

-
TOPC_BUF TOPC_MSG ( void *buf, int buf_size )
-

Function -

-
- -
-

From Callback Functions for TOPC_master_slave(). -

-
TOPC_BUF GenerateTaskInput ( void )
-

Function -

-
TOPC_BUF DoTask ( void *input )
-

Function -

-
TOPC_ACTION CheckTaskResult ( void *input, void *output)
-

Function -

-
void UpdateSharedData ( void *input, void *output )
-

Function -

-
- -
-

From Actions Returned by CheckTaskResult(). -

-
Action TOPC_ACTION NO_ACTION
-

Action -

-
Action TOPC_ACTION UPDATE
-

Action -

-
Action TOPC_ACTION REDO
-

Action -

-
Action TOPC_ACTION CONTINUATION ( void *next_input )
-

Action -

-
- -
-

From TOP-C Utilities. -

-
TOPC_BOOL TOPC_is_up_to_date ( void )
-

Function -

-
int TOPC_rank ( void )
-

Function -

-
TOPC_BOOL TOPC_is_master ( void )
-

Function -

-
int TOPC_num_slaves ( void )
-

Function -

-
int TOPC_num_idle_slaves ( void )
-

Function -

-
int TOPC_node_count ( void )
-

Function -

-
- -
-

From Optimizing TOP-C Code for the Shared Memory Model. -

-
TOPC_thread_private
-

Variable -

-
TOPC_thread_private_t
-

Type -

-
void TOPC_ATOMIC_READ ( 0 ) { ... C code ... }
-
void TOPC_ATOMIC_WRITE ( 0 ) { ... C code ... }
-

Function -

-
void TOPC_BEGIN_ATOMIC_READ ( 0 )
-
void TOPC_END_ATOMIC_READ ( 0 )
-
void TOPC_BEGIN_ATOMIC_WRITE ( 0 )
-
void TOPC_END_ATOMIC_WRITE ( 0 )
-

Function -

-
- -
-

From Raw ‘TOP-C’ interface: raw_master_slave. -

-
void TOPC_raw_begin_master_slave
-

(do_task, check_task_result, update_shared_data) -

-
void TOPC_raw_end_master_slave ()
-

Function -

-
void TOPC_raw_submit_task_input ( TOPC_BUF input )
-

Function -

-
TOPC_BOOL TOPC_raw_wait_for_task_result ()
-

Function -

-
- -
-

From Aborting Tasks. -

-
void TOPC_abort_tasks ( void )
-
TOPC_BOOL TOPC_is_abort_pending ( void )
-

Function -

-
- -
-

From Testing for Task Continuations and Redos. -

-
TOPC_BOOL TOPC_is_REDO ( void )
-
TOPC_BOOL TOPC_is_CONTINUATION ( void )
-

Function -

-
- -
-

From Using TOPC_MSG_PTR() to Avoid Copying Large Buffers. -

-
TOPC_BUF TOPC_MSG_PTR ( void *buf, int buf_size )
-

Function -

-
- -
-

From Command Line Options in TOP-C Applications. -

-
--TOPC-help‘[=<0/1>]
-

[boolean, default: false] -

-
--TOPC-verbose‘[=<0/1>]
-

[boolean, default: false] -

-
--TOPC-stats‘[=<0/1>]
-

[boolean, default: false] -

-
--TOPC-num-slaves‘=<int>
-

[default: -1 (system-defined)] -

-
--TOPC-slave-wait‘=<int>
-

[default: 0] -

-
--TOPC-slave-timeout‘=<int>
-

[default: 1800 s] -

-
--TOPC-trace‘=<int: 0/1/2>
-

[trace (0: notrace, 1: trace, 2: user trace fncs, default: 2)] -

-
--TOPC-procgroup‘=<string>
-

[default: "./procgroup"] -

-
--TOPC-safety‘=<int: 0..20>
-

[default: 0] -

-
- -
-

From Tracing Messages. -

-
int TOPC_OPT_trace
-
void (*)(void *input) TOPC_OPT_trace_input
-
void (*)(void *input, void *output) TOPC_OPT_trace_result
-
- - - -
- - - - - - - - - - - - -
[ << ][ >> ]           [Top][Contents][Index][ ? ]
-

- - This document was generated by Gene Cooperman on April, 15 2011 using texi2html 1.78. - -
- -

- - diff --git a/topc-2.5.2/doc/html/topc/topc_12.html b/topc-2.5.2/doc/html/topc/topc_12.html deleted file mode 100644 index 41817aaa..00000000 --- a/topc-2.5.2/doc/html/topc/topc_12.html +++ /dev/null @@ -1,176 +0,0 @@ - - - - - -TOP-C (Task Oriented Parallel C/C++): B. Example TOP-C Application - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

B. Example ‘TOP-C’ Application

- - -

There are several example ‘TOP-C’ programs in the -‘topc/examples’ subdirectory. We include one example in this -manual. It does not contain any UPDATE actions, and therefore -illustrates only a trivial form of parallelism (with no interaction -among the slaves). The ‘topc/examples’ subdirectory should be -inspected for more sophisticated examples. -After understanding this example, you may also want to look at -Advanced Features of ‘TOP-C, or if you are parallelizing a sequential -program, then you may want to look at TOP-C’ Raw Interface for Parallelizing Sequential Code. -

-

This program produces an array of 10,000,000 random integers in one pass, -and then finds the maximum value in a second pass. It would be compiled -by: topcc MODEfile.out, where MODE is one of ---seq, --mpi, or --pthread. One can control the -number of slaves by executing: ./a.out --TOPC-num-slaves=num. -

-
 
#include <stdlib.h>
-#include <string.h>
-#include <stdio.h>
-#include <topc.h>
-
-#define MAX 2000000
-#define INCR MAX/10 /* We assume INCR divides MAX exactly */
-
-int array[MAX];
-int idx;
-int max_int;
-
-TOPC_BUF GenerateTaskInput() {
-  int input_task;
-  if (idx >= MAX) return NOTASK;
-  input_task = idx;
-  idx = idx + INCR;
-  return TOPC_MSG( &input_task, sizeof(input_task) );
-}
-TOPC_BUF DoTaskRandom( int *ignore ) {
-  int rand_int[INCR];
-  int i;
-  for ( i = 0; i < INCR; i++)
-    rand_int[i] = rand();
-  return TOPC_MSG( rand_int, INCR * sizeof(int) );
-}
-TOPC_ACTION CheckTaskRandom( int *input, int rand_vals[] ) {
-  int curr_idx = *input;
-  memcpy( array+curr_idx, rand_vals, INCR * sizeof(int) );
-  return NO_ACTION;
-}
-
-TOPC_BUF GenerateTaskInMax() {
-  int *input_task;
-  if (idx >= MAX) return NOTASK;
-  input_task = array + idx;
-  idx = idx + INCR;
-  return TOPC_MSG( input_task, INCR * sizeof(int) );
-}
-TOPC_BUF DoTaskMax( int subarray[] ) {
-  int i;
-  int max=0;
-  for ( i = 0; i < INCR; i++)
-    if ( subarray[i] > max )
-      max = subarray[i];
-  return TOPC_MSG( &max, sizeof(max) );
-}
-TOPC_ACTION CheckTaskMax( int ignore[], int *output ) {
-  int curr_max = *output;
-  if ( curr_max > max_int )
-    max_int = curr_max;
-  return NO_ACTION;
-}
-
-int main( int argc, char **argv ) {
-  /* Set default to no trace; Override with:  ./a.out --TOPC-trace=1 */
-  TOPC_OPT_trace = 0;
-  TOPC_init( &argc, &argv );
-  idx = 0; /* Initialize idx, and randomize values of array[] */
-  TOPC_master_slave(GenerateTaskInput, DoTaskRandom, CheckTaskRandom,
-                    NULL);
-  if (TOPC_is_master())
-    printf("Finished randomizing integers.\n");
-  idx = 0; /* Re-initialize idx to 0, and find max. value in array[] */
-  TOPC_master_slave( GenerateTaskInMax, DoTaskMax, CheckTaskMax, NULL );
-  TOPC_finalize();
-  printf("The maximum integer is:  %d\n", max_int);
-  exit(0);
-}
-
- - - -
- - - - - - - - - - - - -
[ << ][ >> ]           [Top][Contents][Index][ ? ]
-

- - This document was generated by Gene Cooperman on April, 15 2011 using texi2html 1.78. - -
- -

- - diff --git a/topc-2.5.2/doc/html/topc/topc_13.html b/topc-2.5.2/doc/html/topc/topc_13.html deleted file mode 100644 index 65806057..00000000 --- a/topc-2.5.2/doc/html/topc/topc_13.html +++ /dev/null @@ -1,152 +0,0 @@ - - - - - -TOP-C (Task Oriented Parallel C/C++): C. Using a Different MPI with TOP-C - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

C. Using a Different ‘MPI’ with TOP-C

- -

TOP-C’ provides a built-in subset of MPI sufficient to run -distributed applications. If you prefer to use a different implementation -of ‘MPI’ with ‘TOP-C’, this note describes how to do so. -Examples for ‘MPICH’, ‘LAM’ and ‘IBM POE’ are at the -end of this section. You should re-configure and re-build ‘TOP-C’ -using the same C/C++ compiler as that of your chosen MPI. -

-

First test a ‘hello_world’ MPI program -for your chosen MPI implementation to make sure that the -startup mechanism is well understood. -

-

Many dialects of ‘MPI’ provide their own wrapper around -the C and C++ compiler. For example, ‘LAM MPI’ provides mpicc. -If your dialect provides such a wrapper mpicc, then -do ./configure --with-mpi-cc=mpicc and make. There is a similar -configure flag, --with-mpi-cxx, for ‘C++’. -

-

If you do use such a wrapper, you should use the same C compiler for -the rest of ‘TOP-C’. Hence, if mpicc uses cc, -then configure with env CC=cc ./configure --with-mpi-cc=mpicc ---cache-file=/dev/null. -In general, you can always specify a non-default C and C++ compiler by -specifying CC=... and CXX=..., respectively. -

-

If your dialect does not provide such a wrapper, it is easy to create -one by modifying the shell script below for your site. -

 
#!/bin/sh
-gcc -I/usr/local/include $* -L/usr/local/lib -lmpi
-
- -

These wrappers will enable topcc and topc++ to work, -but not topc-config. If you also need topc-config, -then you must modify topc-config. -Determine the libraries used by your dialect of MPI. -Then search for a string with -ltopc-mpi in -‘.../topc/bin/topc-config’, -and append to it your ‘libmpi’. For example, -append to -ltopc-mpi with -L/usr/local/lib -lmpi. -

-

Finally, for many dialects of MPI, after compiling the MPI application, -they may also require a special command at runtime to execute, -such as mpirun a.out. -In such cases, your ‘TOP-C’ application must be treated similarly. -

-

The following examples illustrate the configuration and use of -MPI for other MPI implementations using 2 slaves and 1 master. -

 
# IBM POE/AIX:
-  env CC=xlc CXX=xlC ./configure --with-mpi-cc=mpcc --with-mpi-cxx=mpCC
-  make; cd bin; ./topcc --mpi -qcpluscmt ../examples/parfactor.c
-  poe ./a.out 1234 --TOPC-stats -procs 3 -pgmmodel spmd
-
- -
 
# MPICH/Linux:
-  ./configure --with-mpi-cc=mpicc
-  make; cd bin; ./topcc --mpi ../examples/parfactor.c
-  mpirun -np 3 ./a.out --TOPC-stats 1234
-
- -
 
# LAM/Linux:
-  ./configure --with-mpi-cc=mpicc
-  make; cd bin; ./topcc --mpi ../examples/parfactor.c
-  mpirun -c 3 ./a.out -- --TOPC-stats 1234
-
- - - -
- - - - - - - - - - - - -
[ << ][ >> ]           [Top][Contents][Index][ ? ]
-

- - This document was generated by Gene Cooperman on April, 15 2011 using texi2html 1.78. - -
- -

- - diff --git a/topc-2.5.2/doc/html/topc/topc_14.html b/topc-2.5.2/doc/html/topc/topc_14.html deleted file mode 100644 index 465b3b33..00000000 --- a/topc-2.5.2/doc/html/topc/topc_14.html +++ /dev/null @@ -1,155 +0,0 @@ - - - - - -TOP-C (Task Oriented Parallel C/C++): Function Index - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

Function Index

-
Jump to:   C -   -D -   -G -   -T -   -U -   -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Index Entry Section

C
CheckTaskResult4.2 Callback Functions for TOPC_master_slave()

D
DoTask4.2 Callback Functions for TOPC_master_slave()

G
GenerateTaskInput4.2 Callback Functions for TOPC_master_slave()

T
TOPC_abort_tasks4.4 TOP-C Utilities
TOPC_abort_tasks8.2 Aborting Tasks
TOPC_ATOMIC_READ8.4.1 Reader-Writer Synchronization
TOPC_ATOMIC_WRITE8.4.1 Reader-Writer Synchronization
TOPC_BEGIN_ATOMIC_READ8.4.1 Reader-Writer Synchronization
TOPC_BEGIN_ATOMIC_WRITE8.4.1 Reader-Writer Synchronization
TOPC_END_ATOMIC_READ8.4.1 Reader-Writer Synchronization
TOPC_END_ATOMIC_WRITE8.4.1 Reader-Writer Synchronization
TOPC_finalize4.1 The Main TOP-C Library Calls
TOPC_init4.1 The Main TOP-C Library Calls
TOPC_is_abort_pending4.4 TOP-C Utilities
TOPC_is_abort_pending8.2 Aborting Tasks
TOPC_is_CONTINUATION4.4 TOP-C Utilities
TOPC_is_CONTINUATION8.1 Testing for Task Continuations and Redos
TOPC_is_master4.4 TOP-C Utilities
TOPC_is_REDO4.4 TOP-C Utilities
TOPC_is_REDO8.1 Testing for Task Continuations and Redos
TOPC_is_up_to_date4.4 TOP-C Utilities
TOPC_master_slave4.1 The Main TOP-C Library Calls
TOPC_MSG4.1 The Main TOP-C Library Calls
TOPC_MSG_PTR8.3.2 Using TOPC_MSG_PTR() to Avoid Copying Large Buffers
TOPC_node_count4.4 TOP-C Utilities
TOPC_num_idle_slaves4.4 TOP-C Utilities
TOPC_num_slaves4.4 TOP-C Utilities
TOPC_rank4.4 TOP-C Utilities
TOPC_raw_begin_master_slave9.1 ‘TOP-C’ raw functions
TOPC_raw_end_master_slave9.1 ‘TOP-C’ raw functions
TOPC_raw_submit_task_input9.1 ‘TOP-C’ raw functions
TOPC_raw_wait_for_task_result9.1 ‘TOP-C’ raw functions

U
UpdateSharedData4.2 Callback Functions for TOPC_master_slave()

-
Jump to:   C -   -D -   -G -   -T -   -U -   -
- -
- - - - - - - - - - - - -
[ << ][ >> ]           [Top][Contents][Index][ ? ]
-

- - This document was generated by Gene Cooperman on April, 15 2011 using texi2html 1.78. - -
- -

- - diff --git a/topc-2.5.2/doc/html/topc/topc_15.html b/topc-2.5.2/doc/html/topc/topc_15.html deleted file mode 100644 index e82274f1..00000000 --- a/topc-2.5.2/doc/html/topc/topc_15.html +++ /dev/null @@ -1,149 +0,0 @@ - - - - - -TOP-C (Task Oriented Parallel C/C++): Variable Index - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

Variable Index

-
Jump to:   / -   -
-C -   -N -   -R -   -S -   -T -   -U -   -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Index Entry Section

/
/tmp/mpinu-ssh5.4.2 If Slaves Fail to Start

C
CONTINUATION4.3 Actions Returned by CheckTaskResult()

N
NO_ACTION4.3 Actions Returned by CheckTaskResult()

R
REDO4.3 Actions Returned by CheckTaskResult()

S
SSH5.4.1 Writing Procgroup Files for ‘MPINU

T
TOPC_OPT_trace_input6.4 Tracing Messages
TOPC_OPT_trace_result6.4 Tracing Messages
TOPC_OPTS5.2 Command Line Options in TOP-C Applications
TOPC_thread_private8.4.2 Thread-Private Global Variables
TOPC_thread_private_t8.4.2 Thread-Private Global Variables

U
UPDATE4.3 Actions Returned by CheckTaskResult()

-
Jump to:   / -   -
-C -   -N -   -R -   -S -   -T -   -U -   -
- - - -
- - - - - - - - - - - - -
[ << ][ >> ]           [Top][Contents][Index][ ? ]
-

- - This document was generated by Gene Cooperman on April, 15 2011 using texi2html 1.78. - -
- -

- - diff --git a/topc-2.5.2/doc/html/topc/topc_16.html b/topc-2.5.2/doc/html/topc/topc_16.html deleted file mode 100644 index e22b4fa6..00000000 --- a/topc-2.5.2/doc/html/topc/topc_16.html +++ /dev/null @@ -1,306 +0,0 @@ - - - - - -TOP-C (Task Oriented Parallel C/C++): Concept Index - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

Concept Index

-
Jump to:   - -   -. -   -
-A -   -C -   -D -   -E -   -F -   -G -   -H -   -I -   -L -   -M -   -N -   -O -   -P -   -R -   -S -   -T -   -V -   -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Index Entry Section

-
–mpi argument to topcc/topc++5.4 Invoking a TOP-C Application in Distributed Memory
–pthread argument to topcc/topc++5.5 Invoking a TOP-C Application in Shared Memory
–seq argument to topcc/topc++5.3 Invoking a TOP-C Application in Sequential Memory
–TOPC-aggregated-tasks5.2 Command Line Options in TOP-C Applications
–TOPC-aggregated-tasks, usage7.3 Improving Performance
–TOPC-help5.2 Command Line Options in TOP-C Applications
–TOPC-num-slaves5.2 Command Line Options in TOP-C Applications
–TOPC-num-slaves, example6.1 Debugging by Limiting the Parallelism
–TOPC-num-slaves, selection of slave hosts using procgroup file5.4.1 Writing Procgroup Files for ‘MPINU
–TOPC-procgroup5.2 Command Line Options in TOP-C Applications
–TOPC-procgroup, usage of procgroup file5.4.1 Writing Procgroup Files for ‘MPINU
–TOPC-safety5.2 Command Line Options in TOP-C Applications
–TOPC-safety for debugging6.2 Debugging with ‘--TOPC-safety
–TOPC-slave-timeout5.2 Command Line Options in TOP-C Applications
–TOPC-slave-timeout, for long jobs and runaway jobs7.4 Long Jobs and Courtesy to Others
–TOPC-slave-wait5.2 Command Line Options in TOP-C Applications
–TOPC-slave-wait, debugging a slave process with ‘gdb6.5 Stepping Through a Slave Process with ‘gdb
–TOPC-stats5.2 Command Line Options in TOP-C Applications
–TOPC-trace5.2 Command Line Options in TOP-C Applications
–TOPC-verbose5.2 Command Line Options in TOP-C Applications

.
.topcrc5.2 Command Line Options in TOP-C Applications

A
aborting tasks8.2 Aborting Tasks
action3.2 Three Key Concepts for TOP-C
actions returned by CheckTaskResult()4.3 Actions Returned by CheckTaskResult()
aggregation of tasks7.3 Improving Performance

C
command line options, TOP-C5.2 Command Line Options in TOP-C Applications
compiling the distributed memory model5.4 Invoking a TOP-C Application in Distributed Memory
compiling the sequential memory model5.3 Invoking a TOP-C Application in Sequential Memory
compiling the shared memory model5.5 Invoking a TOP-C Application in Shared Memory
CONTINUATION, testing for8.1 Testing for Task Continuations and Redos

D
debugging6. Debugging and Tracing
debugging memory management with efence6.6 Segmentation faults and other memory problems
debugging ‘TOP-C’ ‘--mpi’ applications that fail to start5.4.2 If Slaves Fail to Start
debugging, –TOPC-safety6.2 Debugging with ‘--TOPC-safety
distributed memory model3.3 Distributed and Shared Memory Models
distributed memory, fails to start5.4.2 If Slaves Fail to Start

E
efence, debugging memory management6.6 Segmentation faults and other memory problems
example TOP-C applicationB. Example ‘TOP-C’ Application

F
fine grain thread parallelism8.4.1 Reader-Writer Synchronization
finer grain parallelism7.3 Improving Performance

G
global shared data3.2 Three Key Concepts for TOP-C
global thread-private variable8.4.2 Thread-Private Global Variables

H
heterogeneous architecturesMarshaling (Serialization) and Heterogeneous Architectures

I
initializing ‘TOP-C4.1 The Main TOP-C Library Calls

L
large message buffers8.3.2 Using TOPC_MSG_PTR() to Avoid Copying Large Buffers

M
Marshalgen, a package for marshalingMarshalgen, a Package for Marshaling
marshalingMarshaling (Serialization) and Heterogeneous Architectures
master-slave mode, invoking4.1 The Main TOP-C Library Calls
memory model, distributed3.3 Distributed and Shared Memory Models
memory model, distributed, compiling5.4 Invoking a TOP-C Application in Distributed Memory
memory model, sequential8.5 Modifying TOP-C Code for the Sequential Memory Model
memory model, sequential, compiling5.3 Invoking a TOP-C Application in Sequential Memory
memory model, shared8.4 Optimizing TOP-C Code for the Shared Memory Model
memory model, shared, compiling5.5 Invoking a TOP-C Application in Shared Memory
message format, TOPC_MSG()4.1 The Main TOP-C Library Calls
MPINU5.4.1 Writing Procgroup Files for ‘MPINU
mpinu-ssh for debugging slave startup5.4.2 If Slaves Fail to Start

N
network latency, overcoming it7.3 Improving Performance

O
options, TOP-C5.2 Command Line Options in TOP-C Applications

P
procgroup file5.4.1 Writing Procgroup Files for ‘MPINU

R
reader-writer synchronization8.4.1 Reader-Writer Synchronization
REDO, testing for8.1 Testing for Task Continuations and Redos

S
segmentation fault, debugging with efence6.6 Segmentation faults and other memory problems
sequential memory model8.5 Modifying TOP-C Code for the Sequential Memory Model
serializationMarshaling (Serialization) and Heterogeneous Architectures
shared data3.2 Three Key Concepts for TOP-C
shared memory model8.4 Optimizing TOP-C Code for the Shared Memory Model
SIGALRM6.3 TOP-C and POSIX signals
SIGALRM, raised by ‘TOP-C7.4 Long Jobs and Courtesy to Others
signals and TOP-C6.3 TOP-C and POSIX signals
SIGPINT6.3 TOP-C and POSIX signals
SIGPIPE6.3 TOP-C and POSIX signals
SIGPIPE signal handler not recognized6. Debugging and Tracing
SIGSEGV, debugging with efence6.6 Segmentation faults and other memory problems
slave startup in distributed memory, difficulties5.4.2 If Slaves Fail to Start
SMP3.3 Distributed and Shared Memory Models
SSH environment variable for starting remote slaves5.4.1 Writing Procgroup Files for ‘MPINU
static local variables and threads8.4.2 Thread-Private Global Variables
synchronization of threads, shared memory model8.4.1 Reader-Writer Synchronization

T
task3.2 Three Key Concepts for TOP-C
task continuation, testing8.1 Testing for Task Continuations and Redos
task input3.1.3 Task Input and Task Output Buffers
task input4.1 The Main TOP-C Library Calls
task input/output buffers, variable size8.3.1 Avoiding malloc and new with Task Buffers
task output3.1.3 Task Input and Task Output Buffers
task output4.1 The Main TOP-C Library Calls
thread-private variable8.4.2 Thread-Private Global Variables
THREAD_PRIVATE8.4.2 Thread-Private Global Variables
threads, synchronization in shared memory model8.4.1 Reader-Writer Synchronization
TOP-C action3.2 Three Key Concepts for TOP-C
TOP-C command line options5.2 Command Line Options in TOP-C Applications
TOP-C options5.2 Command Line Options in TOP-C Applications
topc++5.1 Compiling TOP-C Applications
topc-config5.1 Compiling TOP-C Applications
TOPC_MSG_PTR()8.3.2 Using TOPC_MSG_PTR() to Avoid Copying Large Buffers
TOPC_OPT_trace, usage for dynamically debugging messages6.4 Tracing Messages
TOPC_OPT_trace_input6.4 Tracing Messages
TOPC_OPT_trace_result6.4 Tracing Messages
TOPC_OPTS environment variable for initialization5.2 Command Line Options in TOP-C Applications
topcc5.1 Compiling TOP-C Applications
topcrc5.2 Command Line Options in TOP-C Applications

-
Jump to:   - -   -. -   -
-A -   -C -   -D -   -E -   -F -   -G -   -H -   -I -   -L -   -M -   -N -   -O -   -P -   -R -   -S -   -T -   -V -   -
-
- - - - - - - - - - - - -
[ << ][ >> ]           [Top][Contents][Index][ ? ]
-

- - This document was generated by Gene Cooperman on April, 15 2011 using texi2html 1.78. - -
- -

- - diff --git a/topc-2.5.2/doc/html/topc/topc_17.html b/topc-2.5.2/doc/html/topc/topc_17.html deleted file mode 100644 index a8fd45e2..00000000 --- a/topc-2.5.2/doc/html/topc/topc_17.html +++ /dev/null @@ -1,173 +0,0 @@ - - - - - -TOP-C (Task Oriented Parallel C/C++): Concept Index: V - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

Concept Index: V

-
Jump to:   - -   -. -   -
-A -   -C -   -D -   -E -   -F -   -G -   -H -   -I -   -L -   -M -   -N -   -O -   -P -   -R -   -S -   -T -   -V -   -
- - - - - - - -
Index Entry Section

V
variable size task buffers8.3.1 Avoiding malloc and new with Task Buffers
volatile C/C++ variables8.4.3 Sharing Variables between Master and Slave and Volatile Variables

-
Jump to:   - -   -. -   -
-A -   -C -   -D -   -E -   -F -   -G -   -H -   -I -   -L -   -M -   -N -   -O -   -P -   -R -   -S -   -T -   -V -   -
- -
- - - - - - - - - - - - -
[ << ][ >> ]           [Top][Contents][Index][ ? ]
-

- - This document was generated by Gene Cooperman on April, 15 2011 using texi2html 1.78. - -
- -

- - diff --git a/topc-2.5.2/doc/html/topc/topc_2.html b/topc-2.5.2/doc/html/topc/topc_2.html deleted file mode 100644 index c7ff7f67..00000000 --- a/topc-2.5.2/doc/html/topc/topc_2.html +++ /dev/null @@ -1,192 +0,0 @@ - - - - - -TOP-C (Task Oriented Parallel C/C++): 2. Quick Start: Installation and Test Run - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

2. Quick Start: Installation and Test Run

- -
 
   This is version 2.5.2 of Task Oriented Parallel C/C++ (‘TOP-C’).
-   See http://www.ccs.neu.edu/home/gene/topc.html for general
-   information on obtaining source, overview slides of ‘TOP-C’,
-   previous ‘TOP-C’ applications, etc.
-                                                      Gene Cooperman
-                                                      gene@ccs.neu.edu
-
- -

It has been tested and works on several workstation -architectures. It provides task-oriented parallelism to the end user. -The same application source code (or object code) can be executed -(or linked) with any of the following communication libraries -using the topcc command (a substitute for cc or gcc): -

    -
  1. a distributed memory library using MPI - (MPI subset, mpinu, included in distribution); or -
  2. a shared memory library using threads; or -
  3. a single-process sequential library - (useful for development and debugging). -
-

The ‘TOP-C’ model has been successfully used for some very large -computations. -

-

To unpack: -

 
  gunzip topc.tar.gz
-  tar xvf topc.tar
-  cd topc
-  ./configure
-  make
-
- -

If you are impatient, you can immediately do: -

 
  cd bin
-  make parfactor
-
-

and see a demonstration for factoring numbers by a Euclidean sieve. -Then try: ./a.out YOUR_NUMBER
-Read bin/Makefile for an example of compiling a ‘TOP-C’ program. -

-

If you want to use more or different slave processes, modify -‘bin/procgroup’. -Then, again: -

 
  cd bin
-  ./a.out YOUR_NUMBER
-
- -

And compare with your results using a single slave process: -

 
  ./a.out --TOPC-num-slaves=1 YOUR_NUMBER
-
-

Or investigate what other command-line TOP-C options are available for a.out. -

 
  ./a.out --TOPC-help
-
- -

Other TOP-C applications besides parfactor are in the directory -‘../examples’. For example, if you would like to try -‘parquicksort.c’, then from the ‘bin’ directory, try: -

 
  make check TEST_FILE=parquicksort
-
- -

When you write your own ‘TOP-C’ application, ‘app.c’, make -sure that it contains #include <topc.h> at the top, and that you -have a procgroup file in the current directory, and then: -

 
  bin/topcc --mpi -o app app.c
-  # or else:  bin/topc++ --mpi -o app app.cc
-  ./app
-
-

topcc’ is a wrapper for your standard C compiler. It accepts all -the standard compiler command line options, plus a few more. -‘topc++’ also exists. [NOTE: bin/topcc --help and -bin/topc++ --help both work and ‘doc/topcc.1’ exists ] -

-

This might be a good point to download and print at least the first half -of the manual, or else make it from the doc directory (cd doc; -make pdf; make ps). Note that the table of contents may appear at the -end of the documentation after the index. See Summary of ‘TOP-C’ Commands, for a list of the -‘TOP-C’ commands. See Example ‘TOP-C’ Application, for a simple ‘TOP-C’ -example application involving only trivial parallelism. The -‘examples’ subdirectory provides more detailed examples. -A tutorial is available from the web page, -http://www.ccs.neu.edu/home/gene/topc.html. -

-

Finally, if you want to install ‘TOP-C’ permanently, type -

 
  ./configure                 # Install in /usr/local
-  ./configure --prefix=$HOME  # Install in home directory
-  make install
-
- -

This adds a man page, an info file (try info topc), etc. HTML -documentation is available in the ‘doc’ subdirectory of the -‘TOP-C’ distribution. By default, ‘TOP-C’ will install in -‘/usr/local’, requiring root privilege. If you configure ---prefix=$HOME, -‘TOP-C’ will create files in ‘$HOME/bin’, ‘$HOME/lib’, -‘$HOME/include’, ‘$HOME/man’ and ‘$HOME/info’. -If you want to make ‘TOP-C’ with cc instead of gcc, type: -

 
  env CC=cc ./configure --cache-file=/dev/null
-
-

CFLAGS, CXX (for topc++ and -CXXFLAGS can also be set. -For other configuration options, type: -

 
  ./configure --help
-
- -

Please write the author, Gene Cooperman (gene@ccs.neu.edu), if -there are any questions. -

-
- - - - - - - - - - - - -
[ << ][ >> ]           [Top][Contents][Index][ ? ]
-

- - This document was generated by Gene Cooperman on April, 15 2011 using texi2html 1.78. - -
- -

- - diff --git a/topc-2.5.2/doc/html/topc/topc_3.html b/topc-2.5.2/doc/html/topc/topc_3.html deleted file mode 100644 index f82c50bf..00000000 --- a/topc-2.5.2/doc/html/topc/topc_3.html +++ /dev/null @@ -1,552 +0,0 @@ - - - - - -TOP-C (Task Oriented Parallel C/C++): 3. Overview of TOP-C/C++ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

3. Overview of ‘TOP-C/C++

- -
 
-
                       "Difficulty?" exclaimed Ford. "Difficulty?  What
-                   do you mean difficulty?  [The wheel is] the single
-                   simplest machine in the universe!"  ...
-                       "All right, Mr. Wiseguy,"  she said,  "you're so
-                   clever, you tell us what color it should be."
-                       from "The Restaurant at the End of the Universe"
-                       by Douglas Adams
-
-
- -

TOP-C’ has been designed especially to make it easy to parallelize -existing sequential applications. Toward this goal, -‘TOP-C’ emphasizes: -

    -
  1. ease of use (high level task-oriented abstraction); -
  2. latency tolerance; and -
  3. architecture independence (same application code for - shared and distributed memory). -
- -

A ‘TOP-C’ application is compiled and run using topcc -(similarly to gcc) or topc++ (similarly to g++). -For example, assuming a ‘procgroup’ file in the current -directory to specify the remote hosts for the slave processes, -one executes: -

 
  topcc --mpi parfactor.c
-  # or else:  topc++ --mpi parfactor.cc
-  ./a.out
-
- -

If a ‘TOP-C’ application fails to link, check for a clash of -symbol names. All TOP-C symbols are of the form -TOPC_*, COMM_*, MEM_*, MPI_*, MPINU_*, NO_ACTION, UPDATE, REDO, CONTINUATION, -or NOTASK. -

-

For purposes of documentation, we will standardize on an explanation of -topcc. Wherever topcc is mentioned, the description is -equally valid for topc++. -

- - - - - - -
- - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

3.1 Programmer's Model

- - - - - - - - -
- - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

3.1.1 Structure of a TOP-C Program

- -

A typical TOP-C application has the following structure: -

 
#include <topc.h>
-... define four callback functions for TOPC_master_slave() ...
-int main( int argc, char **argv ) {
-  TOPC_init( &argc, &argv );
-  ...
-  TOPC_master_slave( GenerateTaskInput, DoTask, CheckTaskResult,
-                     UpdateSharedData )
-  ...
-  TOPC_finalize();
-}
-
- -

The program above is run with a master process and several slave processes -operating with identical command line arguments and identical initial -data (SPSD, or Single Program, Single Data). Communication among processes -occurs only within the routine TOPC_master_slave(), during which -execution can be called SPMD (Single Program, Multiple Data). At the end -of TOPC_master_slave(), execution returns to SPSD, although the -master process may contain some additional process-private data. -

-

TOP-C’ Raw Interface for Parallelizing Sequential Code describes an alternative interface that is -often useful for parallelizing existing sequential code. However, for -new applications, the standard interface will usually be cleaner. -

-
- - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

3.1.2 Four Callback Functions

- -

In a ‘TOP-C’ application, the programmer defines four callback -functions and passes control to the ‘TOP-C’ library through the -following command. -

 
  TOPC_master_slave(GenerateTaskInput, DoTask, CheckTaskResult,
-                    UpdateSharedData);
-
- -

Pictorially, TOP-C arranges for the flow of control among the four callback -functions as follows: -

 
      (ON MASTER)      task input
-   GenerateTaskInput() ---------->
-
-
-  task input   (ON A SLAVE)  task output
-  -----------> DoTask(input) ----------->
-
-
-  task output     (ON MASTER)                    action
-  -----------> CheckTaskResult(input, output) ----------->
-
-
-if (action == UPDATE):
-  task input, task output      (ON ALL PROCESSES)
-  -----------------------> UpdateSharedData(input, output)
-
- -
- - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

3.1.3 Task Input and Task Output Buffers

- - -

A task input or task output is an arbitrary buffer of bytes -of type (void *) in ‘TOP-C’. The task buffers are arbitrary -application-defined data structures, which are opaque to ‘TOP-C’. -Note that in ANSI C, a void pointer is compatible with any other pointer type -(such as (struct task_input *) and (struct task_output *) -in the example below). -

- - - - - - - - -

Defining Application Task Buffers

- -

An application callback function returning a task input or task output -must encapsulate it in a function, TOPC_MSG( void *buf, int -buf_size ), which is then returned by the callback functions -GenerateTaskInput() and DoTask(). TOPC_MSG() -internally allocates a copy of buf, and TOP-C later frees the copy -automatically. So, buf may be reused by the application program. -

-
 
TOPC_BUF DoTask( struct task_input * inp ) {
-  struct task_output outp;
-  ...
-  outp = ...;
-  return TOPC_MSG( &outp, sizeof(outp) );
-}
-
- -

The principle of memory allocation in ‘TOP-C’ is that if an -application allocates memory, then it is the responsibility of the -application to free that memory. TOPC_MSG() has the further -property of copying its buffer argument to a separate ‘TOP-C’ space -(using a shallow copy), after which the application can free any memory it -allocated. This happens automatically in the above example, -since outp is allocated on the stack. -

- - -

Marshaling (Serialization) and Heterogeneous Architectures

- - -

If a heterogeneous -architecture is used, there is an issue of converting data formats -or marshaling. -This is the application's responsibility. For simple data formats -(integers, floats or characters), such conversion can easily be done -in an ad hoc manner. Most C compilers use the IEEE binary -floating point standard, and characters are almost always encoded -in eight bit ASCII representation (or possibly in a standard Unicode -format). Although the byte ordering of integers is not standardized, -the system calls htonl() and ntohl() are available -to convert integers into 32 bit network integers that are -portable across heterogeneous systems. -

-

For more complicated conversions, one can consider writing one's own -marshaling routines or else using a standard package for marshaling -such as the ‘XDR’ library (RFC 1832, eXternal Data Representation), -‘IDL’ (‘Corba’), or ‘SOAP’ (‘XML’). -

- - -

Marshalgen, a Package for Marshaling

- -

For complex C++ applications, we recommend tat you try out -‘Marshalgen’ package. A pointer to it is available from the TOP-C -home page. Since the C++ classes to be marshaled are already defined in -‘.h’ files, Marshalgen asks th user simply to annotate those files -with comments (for example, deep copying vs. shallow copying fo -pointers). ‘Marshalgen’ also has support for such real world -issues as marshalingsubclasses and templates, handling of polymorphism, -etc. The ‘Marshalgen’ preprocessor then generates methods for a -new marshaling class that know how to marshal and unmarshal the original -class. -

- - -
- - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

3.1.4 The ‘TOP-C’ Algorithm

- -

When there is only one slave, -The ‘TOP-C’ algorithm can be summarized by the -following C code. -

 
{ void *input, *output;
-  TOPC_ACTION action;
-  while ( (input = GenerateTaskInput()) != NOTASK ) {
-     do {
-       output = DoTask(input);
-       action = CheckTaskResult(input, output);
-     } while (action == REDO);  /* REDO not useful for only one slave */
-     if (action == UPDATE) then UpdateSharedData(input, output);
-  }
-}
-
- -

On a first reading, it is recommended to skip the rest of this -section until having read through Section Actions Returned by CheckTaskResult(). -

-

For a better understanding of the case of multiple -slaves, this simplified excerpt from the ‘TOP-C’ source code describes -the ‘TOP-C’ algorithm. -

 
TOPC_BUF input, output;
-int num_idle_slaves = num_slaves;
-TOPC_ACTION action;
-
-while (TRUE) {
-  wait_until_an_idle_slave();
-  input = COMM_generate_task_input();
-  if (input.data != NOTASK.data) {
-    SUBMIT_TO_SLAVE:  output = DoTask(input.data);
-    num_idle_slaves--;
-  }
-  else if (num_idle_slaves < num_slaves) // else insure progress condition
-    receive_task_output();               // by blocking until a slave replies
-  else break;
-} // termination condition:  _after_ all slaves idle, next input was NOTASK
-
- -

The code for wait_until_an_idle_slave() can be expanded as follows. -

 
void wait_until_an_idle_slave() {
-  do {
-    while ( result_is_available(&input, &output) ) {
-      action = CheckTaskResult(input.data, output.data);
-      if (action == UPDATE)
-        UpdateSharedData(input.data, output.data);
-      if (action == REDO) /* Use updated shared data, when redoing */
-        SUBMIT_TO_SLAVE:  output = DoTask(input.data);
-      num_idle_slaves++;
-    } while (num_idle_slaves == 0);
-  }
-
- -

Note that the term result refers to an ‘(input,output)’ pair. -The routine CheckTaskResult() returns an action, which -determines the -control structure for a parallel algorithm. A common definition is: -

-
 
TOPC_ACTION CheckTaskResult( void *input, void *output ) {
-  if (output == NULL) return NO_ACTION;
-  else if ( TOPC_is_up_to_date() ) return UPDATE;
-  else return return REDO; }
-
- -

TOPC_is_up_to_date() returns true if and only if during the interval -between when the task input was originally generated and when the task -output was returned by the most recent slave, no other slave process had -returned a task output during the interim that had caused the shared data -to be modified through an UPDATE action. An UPDATE action causes -UpdateSharedData() to be invoked on each process. Further -discussion can be found in TOP-C Utilities. -

-
- - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

3.2 Three Key Concepts for TOP-C

- - -

The ‘TOP-C’ programmer's model is based on three key concepts: -

    -
  1. - tasks in the context of a master/slave architecture; -
  2. - global shared data with lazy updates; and -
  3. - actions to be taken after each task. -
- -

Task descriptions (task inputs) are generated on the master, and assigned to -a slave. The slave executes the task and returns the result to the master. -The master may update its own private data based on the result, or it may -update data on all processes. Such global updates take place on each slave -after the slave completes its current task. Updates are lazy in -that they occur only after a task completes, although it is possible to -issue a non-binding request to ‘TOP-C’ to abort the current tasks -(Aborting Tasks). -A SPMD (Single Program Multiple -Data) style of programming is encouraged. -

-

In both shared and distributed memory architectures, one must worry -about the order of reads and writes as multiple slaves autonomously -update data. The utilities below are meant to ease that chore, by -supporting the ease of the SPMD programming style, while still -maintaining good efficiency and generality for a broad range of -applications. The software can easily be ported to a variety of -architectures. -

-
- - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

3.3 Distributed and Shared Memory Models

- - -

TOP-C’ provides a single API to support three primary memory -models: distributed memory, shared memory and -sequential memory. (The last model, sequential memory, refers to -a single sequential, non-parallel process.) On a first reading, one -should think primarily of the distributed memory model (distributed -nodes, each with its own private memory). Most programs written for -distributed memory will compile without change for sequential memory. -‘TOP-C’ is designed so that the same application source code may -operate efficiently both under distributed and under shared memory. In -order to also compile for shared memory hardware (such as SMP), -additional hints to ‘TOP-C’ may be necessary. -

-

In shared memory architectures, all data outside of the four -callback functions is shared, by default. Hence, an UPDATE -action under shared memory causes only the master process to invoke -UpdateSharedData(). To avoid inconsistencies in the data, by -default ‘TOP-C’ arranges that no slave process may run -DoTask() while UpdateSharedData() is running. -‘TOP-C’ also provides support for finer levels of granularity -through application-defined private variables and critical sections. -Further discussion can be found in Optimizing TOP-C Code for the Shared Memory Model. -

-
- - - - - - - - - - - - -
[ << ][ >> ]           [Top][Contents][Index][ ? ]
-

- - This document was generated by Gene Cooperman on April, 15 2011 using texi2html 1.78. - -
- -

- - diff --git a/topc-2.5.2/doc/html/topc/topc_4.html b/topc-2.5.2/doc/html/topc/topc_4.html deleted file mode 100644 index 1bb4477b..00000000 --- a/topc-2.5.2/doc/html/topc/topc_4.html +++ /dev/null @@ -1,448 +0,0 @@ - - - - - -TOP-C (Task Oriented Parallel C/C++): 4. Writing TOP-C Applications - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

4. Writing ‘TOP-C’ Applications

- -

This chapter assumes a knowledge of the basic concepts in -Overview of ‘TOP-C/C++. In particular, recall Structure of a TOP-C Program. -

- - - - - - - -
- - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

4.1 The Main TOP-C Library Calls

- - -

Every ‘TOP-C’ application must include a ‘topc.h’ header, open -with TOPC_init(), call TOPC_master_slave() one or more -times, and then close with TOPC_finalize(). -

-
 
#include <topc.h>
-      Required at head of any file using TOPC library calls.
-
-
-
Function: void TOPC_init ( int *argc, char ***argv ) - -
-

Required before first occurrence of TOPC_master_slave(); - Recommended to place this as first executable statement in - main(). It will strip off extra ‘TOP-C’ and - communication layer arguments such as ‘--TOPC-stats’, - which are added by ‘TOP-C’. -

-
-
Function: void TOPC_finalize ( void ) - -
-

Placed after last ‘TOP-C’ command. -

-
-
Function: void TOPC_master_slave - -
-

( TOPC_BUF (*generate_task_input)(),
   TOPC_BUF (*do_task)(void *input),
   TOPC_ACTION (*check_task_result)(void *input, void *output),
   void (*update_shared_data)(void *input, void *output) -
) -
Primary call, passed four application callbacks to ‘TOP-C’. - One can have multiple calls to - TOPC_master_slave(), each invoking different callback functions, - between TOPC_init() - and TOPC_finalize(). -

- -
-

A task input or task output is simply a buffer of bytes, specified by -TOPC_MSG(). -

-
-
Function: TOPC_BUF TOPC_MSG ( void *buf, int buf_size ) - -
-

Must be returned by GenerateTaskInput() and DoTask(). - Specifies arbitrary user data structure. - ‘TOP-C’ will make a copy of buf in ‘TOP-C’ space. - It remains the responsibility of the application to free or - reuse the space of the original buffer buf. If - TOPC_MSG(NULL, 0) is called, a NULL pointer will be - received at the destination. - (See section Using TOPC_MSG_PTR() to Avoid Copying Large Buffers, for TOPC_MSG_PTR, - to avoid copying very large buffers, where the overhead is - unacceptable.) -

- -

EXAMPLE: -

 
    TOPC_BUF convert_string_to_msg( char *mystring ) {
-        if (mystring == NULL) return TOPC_MSG(NULL,0);
-        else return TOPC_MSG(mystring, strlen(mystring)+1);
-    }
-
- -
- - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

4.2 Callback Functions for TOPC_master_slave()

- -

The application writer must define the following four callback functions -(although the last can be NULL). The callback terminology -is based on C concepts. In a more object-oriented style, one would -view user callbacks as instantiation of abstract methods in a -user-defined subclass. The first two functions return a -TOPC_BUF, which is produced by TOPC_MSG(). -

-
Function: TOPC_BUF GenerateTaskInput ( void ) - -
-

executes on master; returns a data structure specified by - TOPC_MSG(buf, buf_size). - It should return NOTASK, when there are no more tasks, and it - should be prepared to return NOTASK again if invoked again. -

-
-
Function: TOPC_BUF DoTask ( void *input ) - -
-

executes on slave; operates on the result of GenerateTaskInput(); - returns a data structure specified by - TOPC_MSG(buf, buf_size). - buf must be a static or global user buffer. -

-
-
Function: TOPC_ACTION CheckTaskResult ( void *input, void *output) - -
-

executes on master; operates on the result of DoTask(); - returns an ACTION that determines what happens to the task next. - The terminology result refers to an ‘(input, output)’ pair. - An easy way to write CheckTaskResult() appears in the - example for the utility TOPC_is_up_to_date(). - When returning the action UPDATE, it works to first modify - the input and output buffers. UpdateSharedData() will - then be invoked with the modified buffers. - See TOP-C Utilities, for more details. -

-
-
Function: void UpdateSharedData ( void *input, void *output ) - -
-

executes on master and all slaves; operates on the result of - DoTask(), and the original task returned by - GenerateTaskInput(); - called only if CheckTaskResult() returned UPDATE; - useful for updating global variables in all processes; - The pointer argument, update_shared_data, of - TOPC_master_slave() may be NULL if - an application never requests an UPDATE action. - In a shared memory environment, only the master calls - UpdateSharedData(). See Optimizing TOP-C Code for the Shared Memory Model, for more details. -

- -

Note that in defining the above callback functions, C allows one to -replace the (void *) declaration of the arguments by specific -pointer types. Note that the buffers of any message parameters -(input and output) of DoTask() or -CheckTaskResult() are part of TOP-C space. Such buffers may be -freed by TOP-C on exit from the callback function. An application -wishing to use the buffer after the callback exits must explicitly save -a copy into the application's own space. -

-
- - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

4.3 Actions Returned by CheckTaskResult()

- - -

A TOP-C result is an (input, output) pair corresponding -to an invocation of DoTask(). ‘TOP-C’ passes the result to -CheckTaskResult(). The return value allows the application to -tell ‘TOP-C’ what further actions to take. -The actions returned by CheckTaskResult() are: -

-
Action: TOPC_ACTION NO_ACTION - -
-

C constant, causing no further action for task -

-
-
Action: TOPC_ACTION UPDATE - -
-

C constant, invoking UpdateSharedData( void *input, - void *output) (see below) - also updates bookkeeping for sake of TOPC_is_up_to_date() - (see section TOP-C Utilities) -

-
-
Action: TOPC_ACTION REDO - -
-

Invoke DoTask() on original task input again, and on - the same slave that previously executed the task; useful if - shared data has changed since original - invocation of DoTask() (see TOPC_is_up_to_date(), - below). See Strategies for Greater Concurrency, - for slave strategies to efficiently process a REDO action. -

-
-
Action: TOPC_ACTION CONTINUATION ( void *next_input ) - -
-

CONTINUATION(next_input) is a parametrized action that - may be returned by CheckTaskResult(), after which - DoTask( next_input ) is called on the original slave. - This is useful if only the master can decide whether task is complete, - or if the master wishes to supply additional input messages - needed for the task. - Note that REDO is essentially equivalent to - CONTINUATION( original_task_input ). - Note that any pending calls to UpdateSharedData() will have - occurred on the slave before the new call to DoTask(). - Hence, this allows an extended conversation between master and - slave, in which the slave continues to receive updates of the - shared data before each new input from the master. - Note also that even though a CONTINUATION action returns - to the original slave, any previous pointers to input buffers - on that slave - (and pointers to output buffers from intervening UPDATE - actions) will no longer be valid. Useful data from previous buffers - should have been copied into global variables on the slave. - In the case of the shared memory model, those global variables must be - thread-private. (see section Thread-Private Global Variables) -

- -

It is possible for CheckTaskResult(input, output) to -modify the buffer data in its two arguments, input and output, -in which case the modifications will be visible to any further -callback functions processing the current task. This practice makes -the code more difficult to maintain, and is not recommended when other -solutions are available. -

-
- - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

4.4 TOP-C Utilities

- -

TOP-C’ also defines some utilities. -

-
Function: TOPC_BOOL TOPC_is_up_to_date ( void ) - -
-

returns TRUE or FALSE (1 or 0); returns TRUE if and only if - CheckTaskResult() - has not returned the result UPDATE (invoking - UpdateSharedData()) - between the time when GenerateTaskInput() was originally - called on the - current task, and the time when the corresponding - CheckTaskResult() - was called. - Typical usage: -

 
          TOPC_ACTION CheckTaskResult( void *input, void *output )
-          { if (input == NULL) return NO_ACTION;
-            else if (TOPC_is_up_to_date()) return UPDATE;
-            else return REDO;
-          } 
-
-
-
Function: int TOPC_rank ( void ) - -
-

Unique ID of process or thread. Master always has rank 0. - Slaves have contiguous ranks, beginning at 1. -

-
-
Function: TOPC_BOOL TOPC_is_master ( void ) - -
-

Returns boolean, 0 or 1, depending on if this is master. - Equivalent to TOPC_rank() == 0. -

-
-
Function: int TOPC_num_slaves ( void ) - -
-

Total number of slaves. -

-
-
Function: int TOPC_num_idle_slaves ( void ) - -
-

Total number of idle slaves (not doing task, update or other action). -

-
-
Function: int TOPC_node_count ( void ) - -
-

Total number of processes or threads. Equivalent to - TOPC_num_slaves() + 1. -

- -
-
Function: TOPC_BOOL TOPC_is_REDO ( void ) - -
-
Function: TOPC_BOOL TOPC_is_CONTINUATION ( void ) - -
-
Function: void TOPC_abort_tasks ( void ) - -
-
Function: TOPC_BOOL TOPC_is_abort_pending ( void ) - -
-

See Advanced Features of ‘TOP-C for descriptions. -

- -
- - - - - - - - - - - - -
[ << ][ >> ]           [Top][Contents][Index][ ? ]
-

- - This document was generated by Gene Cooperman on April, 15 2011 using texi2html 1.78. - -
- -

- - diff --git a/topc-2.5.2/doc/html/topc/topc_5.html b/topc-2.5.2/doc/html/topc/topc_5.html deleted file mode 100644 index 59ba5284..00000000 --- a/topc-2.5.2/doc/html/topc/topc_5.html +++ /dev/null @@ -1,600 +0,0 @@ - - - - - -TOP-C (Task Oriented Parallel C/C++): 5. Compiling and Invoking TOP-C Applications - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

5. Compiling and Invoking ‘TOP-C’ Applications

- -

A ‘TOP-C’ application can be compiled once, and then linked to your -choice of a run-time library for either a sequential, distributed memory -or shared memory architecture. The two shell scripts ‘bin/topcc’ -and ‘bin/topc++’ are used instead of ‘gcc’ and ‘g++’ (or -other C/C++ compilers). -

- - - - - - - - -
- - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

5.1 Compiling TOP-C Applications

- - -

The TOP-C application file must contain -

 
    #include <topc.h>
-
-

It must make calls to -

 
    TOPC_init(...);
-    TOPC_master_slave(...);
-    TOPC_finalize();
-
-

as describe in Structure of a TOP-C Program. The -application file is compiled by one of: -

 
    topcc --seq myfile.c
-    topcc --mpi myfile.c
-    topcc --pthread myfile.c
-
-

according to whether the target computer architecture will be sequential -(‘--seq’: single processor), distributed memory (‘--mpi’: -networked CPU's), or shared memory (‘--pthread’: SMP or other -shared memory architecture with a POSIX threads interface). -topcc is a substitute for cc or gcc, -and creates an ‘a.out’ file. -(Similarly, topc++ exists as a substitute for c++ or -g++.) -There are man files, -

 
doc/topcc.1’,   ‘doc,topc++.1’
-
-

with further information on topcc and topc++. -If installed, man topcc and man topc++ exist. -

-

The same object file may be relinked to use different ‘TOP-C’ memory -models without recompiling the object file. -

 
    topcc -c myapp.c
-    topcc --seq -o myapp-seq myapp.o
-    topcc --mpi -o myapp-mpi myapp.o
-
- -

For large applications, it may be preferable to directly invoke -the ‘TOP-C’ libraries and include files. For such -situations, topc-config exists. The following -is exactly equivalent to topcc --mpi myfile.c -(assuming you configured ‘TOP-C’ using gcc). -

 
    gcc `topc-config --cflags` --mpi myfile.c `topc-config --libs`
-
-

Type topc-config with no arguments for a full set of -command line options. -

-

For the rest of this chapter, we standardize our description for -topcc. However, topc++ is equally valid wherever -topcc is mentioned. -

-
- - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

5.2 Command Line Options in TOP-C Applications

- - -

TOP-C searches for TOP-C parameters in the following locations, in order: -

    -
  1. values of variables TOPC_OPT_xxx in the application code - before TOPC_init() -
  2. the file ‘.topcrc’ in the home directory -
  3. the environment variable TOPC_OPTS -
  4. arguments on the command line in the form --TOPC-xxx -
-

The file ‘.topcrc’ and the environment variable TOPC_OPTS -specify parameters -in the same format as on the command line. Later assignments of an -option override earlier assignments. -

-

For a brief synopsis of application command line options, type: -

 
    topcc myapp.c
-    ./a.out --TOPC-help
-    [ OR FOR MORE INFORMATION:  ./a.out --TOPC-help --TOPC-verbose  ]
-
- -

Currently, this will display the following. -

 
Usage:  ./a.out [TOPC_OPTION ...] [OTHER_OPTIONS ...]
-
-  where TOPC_OPTION is one of:
---TOPC-help[=<0/1>]        display this message   [default: false]
---TOPC-stats[=<0/1>]       print stats before & after [default: false]
---TOPC-verbose[=<0/1>]     set verbose mode       [default: false]
---TOPC-num-slaves=<int>    number of slaves (sys-defined default) 
-                                                   [default: -1]
---TOPC-aggregated-tasks=<int> number of tasks to aggregate 
-                                                   [default: 1]
---TOPC-slave-wait=<int>    secs before slave starts (use w/ gdb attach)
-                                                   [default: 0]
---TOPC-slave-timeout=<int> dist mem: secs to die if no msgs, 0=never
-                                                   [default: 1800]
---TOPC-trace=<int>         trace (0: notrace, 1: trace, 2: user trace fncs.) 
-                                                   [default: 2]
---TOPC-procgroup=<string>  procgroup file (--mpi)
-                                                   [default: "./procgroup"]
---TOPC-topc-log=<string>   NOT IMPL: log file for TOPC output ("-" = stdout) 
-                                                   [default: "-"]
---TOPC-safety=<int>        [0..20]: higher turns off optimizations,
-                         (try with --TOPC-verbose) [default: 0]
-
- -

For each option, ‘--TOPC-PARAM’, there is a corresponding -C/C++ variable, TOPC_OPT_PARAM. This variable is of type -int or (char *). If the application program sets the value -before a call to TOPC_init(), these variables will act as -defaults. For example, to turn off tracing by default, write: -

 
int main( int argc, char *argv[] ) {
-  TOPC_OPT_trace = 0;
-  TOPC_init( &argc, &argv );
-  ...
-}
-
- -

The option ‘--TOPC-trace’ causes the task input and task output -to be traced and printed as they are passed across the network. The action of -a task is also printed. If an application is called with -‘--TOPC-trace=2’ (default) and if the variables -TOPC_OPT_trace_input and TOPC_OPT_trace_result are set -to pointers to -functions then those functions are called, and they may print additional -information. -TOPC_OPT_trace_input must be set to a function of one -variable: void * input. -TOPC_OPT_trace_result must be set to a function of two -variables: void * input, void * output. -When using C++, the function pointers must be cast to -TOPC_trace_input_ptr or TOPC_trace_result_ptr -before being assigned to TOPC_OPT_trace_input or -TOPC_OPT_trace_result, respectively. -For an example, see ‘examples/parfactor.c’ in the TOP-C distribution. -

-

The option ‘--TOPC-stats’ prints statistics (running times, -etc.) and -information about the conditions of an invocation of a TOP-C application -before and after a run. -The option ‘--TOPC-verbose’ (set by default) displays TOP-C -warnings. With –TOPC-help, it provides additional information. -

-

For the usage of ‘--TOPC-procgroup’, -see Invoking a TOP-C Application in Distributed Memory. -That section also explains on what hosts the slaves run -when ‘--TOPC-num-slaves’ indicates a different number of -slaves than the ‘procgroup’ file. -

-

For the usage of ‘--TOPC-aggregated-tasks’, -see Improving Performance. -For the usage of ‘--TOPC-slave-wait’, see -Stepping Through a Slave Process with ‘gdb. -For the usage of ‘--TOPC-safety’, see -Command Line Options in TOP-C Applications. -For the usage of the other options, see the Concept Index. -

-

TOP-C’ recognizes -- as terminating all option processing, -according to standard UNIX conventions. -

-
- - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

5.3 Invoking a TOP-C Application in Sequential Memory

- - -

For example, -

 
    topcc --seq -g -O0 myfile.c
-
-

compiles a sequential version for debugging using gdb -(see (gdb)Top section `Summary' in The GNU debugger), for example. -This is usually a first step in debugging a TOP-C application, since -sequential debugging is easier than parallel debugging. -

-
- - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

5.4 Invoking a TOP-C Application in Distributed Memory

- - -

Linking using the ‘--mpi’ option (default) allows an application to -execute using a distributed memory model of networked processors. The -‘TOP-C’ distribution includes a subset MPI(1) -implementation ‘MPINU’, sufficient to run ‘TOP-C’ -applications. -

 
  topcc --mpi myapp.c
-  ./a.out
-
-

The application must then create the remote slave processes at runtime. -If you use ‘MPINU’ (the default configuration of ‘TOP-C’, -then the remote slave processes are specified by a ‘procgroup’ file. -Otherwise, the startup mechanism depends on your ‘MPI’ implementation. -

- - - - - -
- - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

5.4.1 Writing Procgroup Files for ‘MPINU

- - -

MPINU’ is built into the default configuration of the -‘TOP-C’ library and uses the ‘procgroup’ mechanism to specify -slave processes. (If you prefer to use a different ‘MPI’ dialect, -‘TOP-C’ will work, but ‘src/Makefile.in’ must be modified, -and that ‘MPI’ dialect may use a different mechanism for -introducing slave processes.) -

-

When the application binary is executed under the default, it looks at -the current directory for a file, -

 
procgroup’
-
-

The procgroup file determines the number and location of the slave -processes. The procgroup file need only be visible from the -master process. If one prefers, one can specify an alternate -procgroup file via the syntax as in the following example: -

 
    ./a.out --TOPC-procgroup=../myprocgroup.big
-
- -

The ‘TOP-C’ distribution includes a file ‘bin/procgroup’ as an -example of the procgroup format. -The file must contain a line: -

 
    local 0
-
-

for the master process. It must also contain a line for each slave -process in one of the following forms: -

 
    hostname 1 full_pathname
-    hostname 1 -
-    hostname 1 ./relative_pathname
-    hostname 1 ../relative_pathname
-
-

where hostname is the remote host. -The pathname - means to use the same pathname for the slave -on the remote host as for the master on the current host. -A relative pathname, such as ./a.out or ../new_arch/a.out, -specifies a pathname relative to the pathname of the binary of -the master on the current host. -

-

Most of the time, it is simplest to just include a full pathname -or else - in the ‘procgroup’ file. The relative pathnames are -useful for a shared filesystem with binaries compiled for -different architectures. For example, the procgroup file might include -relative paths ‘../sparc/a.out’, ‘../alpha/a.out’ and -‘../linux/a.out’. -If you invoke ‘full_path/sparc/a.out’, this will yield a master -running ‘full_path/sparc/a.out’ and three slaves running -each of the three architectures. -

-

The full principles are as follows. -Let SLAVE_PATH be the path of the slave as given in the procgroup file, -and let MASTER_DIR be the directory of the master process as invoked on -on the command line. -

 
SLAVE_PATH absolute:
-  slave binary image is SLAVE_PATH
-SLAVE_PATH relative and MASTER_DIR absolute:
-  slave binary image is MASTER_DIR/SLAVE_PATH
-SLAVE_PATH relative and MASTER_DIR relative:
-  slave binary image is $PWD/MASTER_DIR/SLAVE_PATH
-SLAVE_PATH is - and master process invoked on command line as MASTER_BIN:
-  slave binary image is MASTER_BIN  (if MASTER_BIN is absolute path)
-  or $PWD/MASTER_BIN (if MASTER_BIN is relative path)
-If the procgroup line contains command line arguments,
-  those command line arguments are passed to the slave application
-  as its first arguments, and any arguments on the master command
-  line are appended to the list of arguments.
-
-

TOP-C assumes that your -application does not change the working directory before -calling TOPC_init(). -

-

By default, ‘TOP-C’ uses the procgroup file in the current directory. -You can choose an explicit procgroup file via a program -variable, TOPC_OPT_procgroup="/project/myprocgroup";, or via a -command-line option, -/project/sparc/app --TOPC-procgroup=/project/myprocgroup. -See section Command Line Options in TOP-C Applications. -

-

If the command line option ‘--TOPC-num-slaves=int’ -is given, and if int is less than the number of -slaves in the ‘procgroup’ file, then ‘TOP-C’ will -use the first int slaves from the file. If int -is more than the number of slaves in the ‘procgroup’ file, -then ‘TOP-C’ will use all of the given slaves, and then -create additional processes on the remote hosts, by -returning to the beginning of the ‘procgroup’ file and -re-reading the list of slave host/binaries until int -slaves have been created in all. -

-

It is recommended to use only localhost during initial -development. -

- - -

The environment variable, SSH (default value ssh) is used to -invoke the remote host. If, for example, your site uses rsh -instead of ssh, the following code, when executed -before TOPC_init() will produce this effect. -

 
  putenv("SSH=rsh");
-
-

Alternatively, type SSH=rsh (sh/bash, etc.) or -setenv SSH rsh -(csh/tcsh, etc.) in the UNIX shell before invoking the TOP-C application. -

-
- - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

5.4.2 If Slaves Fail to Start

- - -

If some slave processes start, but not others, then try executing -the following simple program. -

 
#include "topc.h"
-int main(int argc, char *argv) {
-  char host[100];
-  printf("%s connecting ...\n", gethostname(host, 99));
-  TOPC_init(&argc, &argv);
-  printf("... %s connected.\n", gethostname(host, 99));
-  TOPC_finalize();
-}
-
- -

If the slave processes fail to start up or fail to respond to the master -and if you are using ‘MPINU’ (default configuration of ‘TOP-C’, - one other debugging resource is available. -If an application fails to start up, then ‘TOP-C’ leaves in -the ‘/tmp’ directory a file -

 
/tmp/mpinu-ssh.$$’
-
-

where $$ is the process id. The file shows the commands that -‘TOP-C/mpinu’ tried to use to start up the slave process. By -examining and even manually executing those commands from the terminal, -one can often deduce the difficulty in creating the slave processes. -

-

Test the ability of your computer facility to execute remote processes -without passwords by typing: ssh REMOTE_HOST pwd. -If the problem is that ssh is not working, try setting -the environment variable SSH to ssh or other site-specific -setting. -See section Writing Procgroup Files for ‘MPINU. -

-

If you are using ssh (default if the environment variable -SSH is not set), and if it requires a password then the following -commands within UNIX may allow ssh to operate on your local cluster -without passwords. -

 
ssh-keygen -t dsa       [accept default values]
-ssh-keygen -t rsa       [accept default values]
-cat ~/.ssh/id*.pub >> ~/.ssh/authorized_keys
-
-

For security, be sure that ~/.ssh has no read permission for other users. -

-
- - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

5.5 Invoking a TOP-C Application in Shared Memory

- - -

Linking using the ‘--pthread’ option allows an -application to execute using POSIX threads. -Note that the ‘TOP-C’ memory model for shared memory has some small -variations from the distributed memory model. -The largest potential -source of incompatibility is if your DoTask() routine modifies -any global or static variables. If so, such variables will -need to be declared thread private. -Check your source code to see if this -affects you. -

-

Second, if you encounter insufficient performance, you may consider -experimenting with fine grain thread parallelism. The default -‘TOP-C’ algorithm for shared memory allows UpdateSharedData() -to begin executing only after each current invocation of DoTask() -completes. This can be modified by an application for -finer grain parallelism. See section Optimizing TOP-C Code for the Shared Memory Model, for details in either of the above cases. -

-

Note also that while a ‘TOP-C’ application object file can usually be -linked using an arbitrary ‘TOP-C’ memory model without recompiling, -there are some circumstances where you may first need to recompile the -application source using topcc --pthread. -

-
- - - - - - - - - - - - -
[ << ][ >> ]           [Top][Contents][Index][ ? ]
-

- - This document was generated by Gene Cooperman on April, 15 2011 using texi2html 1.78. - -
- -

- - diff --git a/topc-2.5.2/doc/html/topc/topc_6.html b/topc-2.5.2/doc/html/topc/topc_6.html deleted file mode 100644 index 90a58a63..00000000 --- a/topc-2.5.2/doc/html/topc/topc_6.html +++ /dev/null @@ -1,441 +0,0 @@ - - - - - -TOP-C (Task Oriented Parallel C/C++): 6. Debugging and Tracing - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

6. Debugging and Tracing

- - -

If the difficulty is that the application fails to start in the distributed -memory model (using topcc --mpi), then read -If Slaves Fail to Start, for some -debugging techniques. Note also that TOP-C ignores SIGPIPE. This is -because TOP-C employs the SO_KEEPALIVE option, and the master process -would otherwise die if a slave process were to die. SO_KEEPALIVE -is needed for robustness when slave processes execute long tasks without -communicating with the master process. -The rest of this section assumes that the -application starts up correctly. -

- - - - - - - - - -
- - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

6.1 Debugging by Limiting the Parallelism

- -

First, compile and link your code -using topcc --seq --TOPC-safety=20 -g -O0, -and make sure that your application works correctly sequentially. Only after -you have confidence in the correctness of the sequential code, should you -begin to debug the parallel version. -

-

If the application works correctly in sequential mode, one should debug -in the context of a single slave. It is convenient to declare the -remote slave to be localhost in the ‘procgroup’ file, in order -to minimize network delays and so as not to disturb users of -other machines. In this case, the code is “almost” -sequential. An easy way to do this is: -

 
  topcc --mpi --TOPC-num-slaves=1 -g -O0
-
- -

Next, one should test on two slaves, and finally all possible slaves. -

-
- - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

6.2 Debugging with ‘--TOPC-safety

- - -

The command-line option ‘--TOPC-safety=val’ provides assistance -for debugging parallel programs. At higher values of val, -optimizations that do not change the correctness of the program are -converted to safer equivalents. A good strategy is to -test if ‘--TOPC-safety=20’ causes the bug to go away, and if so, -progressively lower val toward zero, until the bug reappears. -The value at which the bug reappears indicates what ‘TOP-C’ -optimization feature is not being used correctly. If the bug still -exists at ‘--TOPC-safety=20’, one should next try compiling -with the ‘--seq’ flag and use a debugger to debug the sequential code. -

-

The effects due to different safety levels are subject to change. -To see the current effects, invoke any TOP-C application as follows -

 
  ./a.out --TOPC-help --TOPC-verbose
-
-

and you will see something like: -

 
  safety: >=0: all; >=2: no TOP-C memory mgr (uses malloc/free);
-  >=4: no TOPC_MSG_PTR; >=8: no aggreg.;
-  >=12: no TOPC_abort_tasks; >=14: no receive thread on slave;
-  >=16: default atomic read/write for DoTask, UpdateSharedData;
-   =19: only 2 slaves; >=20: only 1 slave
-  (AGGREGATION NOT YET IMPLEMENTED)
-
- -

Values higher than 4 cause TOPC_MSG_PTR() to act as -if TOPC_MSG() was called instead. -Values higher than 12 cause TOPC_abort_tasks() to have no effect. -Values higher than 14 imply that a single thread in the slave process -must receive messages and execute DoTask(). Normally, -‘TOP-C’ arranges to overlap communication and computation on the -slave by setting up a separate thread to receive and store messages from -the master. -Values higher than 15 imply that ‘TOP-C’ will use malloc instead -of trying to do its -own memory allocation (which is optimized for ‘TOP-C’ memory -patterns). -Values higher than 16 imply that all of DoTask acts as -if a read lock was placed around it, and all of UpdateSharedData -has a write lock placed aound it. (This has an effect only -in the shared memory model where calls to TOPC_ATOMIC_READ/WRITE -are ignored.) -At values of 19 and 20, the number of slaves is reduced to -2 and to 1, regardless of the setting of ‘--TOPC-num-slaves’ -and the specification in a ‘procgroup’ file. -

-
- - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

6.3 TOP-C and POSIX signals

- -

If an application handles its own signals, this can create a clash -with the TOP-C. -In the distributed memory model (–mpi), ‘TOP-C’ will create its own -signal handlers for SIGALRM. This is used in conjunction with -alarm() to eventually kill runaway -slave processes. In addition, if using ‘MPINU’, -the built-in MPI subset, ‘TOP-C’ will create its own handler -for SIGPIPE. This is in order to allow the master -process to detect dead sockets, indicating dead slaves. -Finally, for short periods, ‘MPINU’ -will disable the use of SIGINT around calls to select(). -Nevertheless, if a SIGINT is sent during this period, TOP-C will pass the -signal on to the original SIGINT handler of the application. -

-

TOP-C’ does not modify signal handlers in the sequential (–seq) -or shared memory (–pthread) models. Furthermore, if a different -MPI (other than MPINU) is used with TOP-C, TOP-C will only handle -SIGALRM. However, the other MPI may handle signals itself. -See section Using a Different ‘MPI’ with TOP-C. -

-
- - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

6.4 Tracing Messages

- - -

If a bug appears as one moves to greater parallelism, one should trace -messages between master and slaves (for any number of slaves). -This is the default, and it can be enabled on the command line with: -

 
  ./a.out --TOPC-trace=2 args
-
-

The variable TOPC_OPT_trace can be set in the code to -dynamically turn tracing on (1 or 2) and off (0) during a single run. -A trace value of 2 causes ‘TOP-C’ to invoke the application-defined -trace functions pointed to by -TOPC_OPT_trace_input/result. If the application has not -defined trace functions, or if TOPC_OPT_trace is 1, then -the ‘TOP-C’ default trace functions are invoked. -All message traces -are displayed by the master at the time that the master sends or -receives the corresponding message. -

-
-
Variable: void (*)(void *input) TOPC_OPT_trace_input - -
-
Variable: void (*)(void *input, void *output) TOPC_OPT_trace_result - -
-

Global pointer (default is NULL) to function returning - void. User can - set it to his or her own trace function to print out - data-specific tracing information in addition to generic - message tracing of TOPC_trace. -

-
 
EXAMPLE:  if you pass integers via TOPC_MSG(), define
-  TOPC_trace_input() as:
-         void mytrace_input( int *input ) {
-           printf("%d",*input);
-         }
-         TOPC_OPT_trace_input = mytrace_input;
-
- -

Note that the term ‘result’ in TOPC_OPT_trace_result -refers to an ‘(input, output)’ pair. -

-
- - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

6.5 Stepping Through a Slave Process with ‘gdb

- - -

If you find the master hanging, waiting for a slave message, then the -probable cause is that DoTask() is doing something bad (hanging, -infinite loop, bus/segmentation error, etc.). First try to isolate the -bug using a symbolic debugger (e.g. ‘gdb’) and the sequential memory -model. If your intended application is the shared memory model, you can also -use ‘gdb’ to set a breakpoint in your ‘DoTask’ routine -or at the ‘TOP-C’ invocation, do_task_wrapper. -

-

If the bug only appears in the distributed memory model, you can still -symbolically debug DoTask() using ‘gdb’ (the GNU C debugger) -and its attach command -(see (gdb)Running section `Attach' in The GNU debugger), -which allows you to attach and debug a separate running process. This -lets you debug a running slave, if it is running o the same processor. -For this strategy, you will want the slave to delay executing to give -you time to execute gdb and attach on the remote host or remote thread. -The command line option ‘--TOPC-slave-wait=30’ will force -the slave to wait 30 seconds before processing. -

-

In applying this debugging strategy to an application ‘./a.out’, -one might see: -

 
  [ Execute ./a.out in one window for master process ]
-  gdb ./a.out
-  (gdb) run --TOPC-trace=1 --TOPC-safety=19 --TOPC-slave-wait=30 args
-
-  [ In a second window for a slave process on a different host, now type: ]
-  ps
-    ...
-    1492  p4 S    0:00 a.out args localhost 6262 -p4amslave
-  gdb a.out
-  ...
-  (gdb) break do_task_wrapper
-    Breakpoint 1 at 0x80492ab: file ...
-    [ `break slave_loop' is also useful.  This calls do_task_wrapper ]
-  (gdb) attach 1492
-    Attaching to program `a.out', process 1492
-    0x40075d88 in sigsuspend ()
-  [ After 30 sec's, traced messages in master window appear, ]
-  [ for slave, type: ]
-  (gdb) continue
-    Continuing.
-    Breakpoint 1, DoTask (input=0x805dc50) at ...
-
-  [ Continue stepping through master and slave processes in 2 windows ]
-
- -

If you try to attach to a second slave process after attaching -to a first slave process, ‘gdb’ will offer to kill your first -slave process. To avoid this situation, remember to execute detach -before attaching a second slave process. -

-
- - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

6.6 Segmentation faults and other memory problems

- - -

Memory bugs are among the most difficult to debug. -If you suspect such a bug (perhaps because you are using TOPC_MSG_PTR), -and you fail to free previously malloc'ed memory, that is a memory leak. -If you access a buffer after freeing it, this may cause -a segmentation error at a later stage in the program. -

-

If you suspect such a bug (and maybe you should if nothing else -worked), it is helpful to use a malloc or memory debugger. -An excellent recent memory debugger is -‘valgrind(2). -‘valgrind’ can be directly applied to an application binary, -without recompilation or relinking. -

-

An older debugger is ‘efence’,(3) -topcc -provides direct support for ‘efence’. -‘TOP-C’ will link with the efence library if --efence -is passed to topcc or topc++. -

 
  topcc --efence ...
-
-

This causes all calls to malloc and free to -be intercepted by the ‘efence’ version. -Modify the line LIBMALLOC= in topcc or topc++ -if you use a different library. -

-
- - - - - - - - - - - - -
[ << ][ >> ]           [Top][Contents][Index][ ? ]
-

- - This document was generated by Gene Cooperman on April, 15 2011 using texi2html 1.78. - -
- -

- - diff --git a/topc-2.5.2/doc/html/topc/topc_7.html b/topc-2.5.2/doc/html/topc/topc_7.html deleted file mode 100644 index 16c422bc..00000000 --- a/topc-2.5.2/doc/html/topc/topc_7.html +++ /dev/null @@ -1,342 +0,0 @@ - - - - - -TOP-C (Task Oriented Parallel C/C++): 7. Performance and Long Jobs - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

7. Performance and Long Jobs

- - - - - - - - -
- - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

7.1 Dropping Slow or Dead Slaves

- -

When TOP-C recognizes a dead slave the master terminates communication with -that slave, and resubmits the task of that slave to a different slave. -(Currently, as of TOP-C 2.5.2, if a slave dies near the end of a computation -and after all tasks have been generated, TOP-C may fail to recognize -that slave.) -

-

It is sometimes unclear whether a slave process is dead or slower than -others. Even a slow slave process may hurt overall performance by -causing delays for other processes. -TOP-C internally declares a slave process to be "slow" if there are N -slaves, and if 3*N other tasks return after the given slave task is "due". -If a slow slave has not returned by slave-timeout seconds -(see Command Line Options in TOP-C Applications), then -the slave is considered dead. The master process sends no further tasks -to that slave, and sends a replicate of the original task to a new -slave. -

-
- - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

7.2 Strategies for Greater Concurrency

- -
-
Strategy 1: SEMI-INDEPENDENT TASKS:
-

Define tasks so that most task outputs do not require any update. - This is always the case for trivial parallelism (when tasks are - independent of each other). It is also often the case for many - examples of search and enumeration problems. -

-
- -
-
Strategy 2: CACHE PARTIAL RESULTS:
-

Inside DoTask() and UpdateSharedData(), save partial - computations in global private variables. Then, in the event of a - REDO action, ‘TOP-C’ guarantees to invoke - DoTask() again on the - original slave process or slave thread. That slave may then use - previously computed partial results in order to shorten the required - computation. Note that pointers on the slave to input and output - buffers from previous UPDATE actions and from the original task - input will no longer be valid. The slave process must copy - any data it wishes to cache to global variables. - In the case of the shared memory model, those global variables must be - thread-private. (see section Thread-Private Global Variables) - Note the existence of TOPC_is_REDO() for testing for a REDO - action. -

-
- -
-
Strategy 3: MERGE TASK OUTPUTS:
-

Inside CheckTaskResult(), the master may merge two or more task - outputs in an application independent way. This may avoid the - need for a REDO action, or it may reduce the number of required - UPDATE actions. -

-
- -
- - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

7.3 Improving Performance

- - -

If your application runs too slowly due to excessive time for communication, -consider running multiple slave processes on a single processor. This -allows one process to continue computing while another is communicating -or idle waiting for a new task to be generated by the master. -

-

If communication overhead or idle time is still too high, consider if it is -possible to increase the granularity of your task. TOP-C can -aggregating several consecutive tasks as a single larger -task to be performed by a single process. This amortizes the network -latency of a single network message over several tasks. -For example, you can do combine 5 tasks -by invoking ‘--TOPC-aggregated-tasks=5’ on -the command line of the application. Alternatively, execute the statement: -

 
  TOPC_OPT_aggregated_tasks=5;
-
-

before TOPC_master_slave(). -In this situation, the five task outputs will also be bundled -as a single network message. Currently (TOP-C 2.5.2), this -works only if all tasks return NO_ACTION. TOP-C will signal -an error if TOPC_OPT_aggregated_tasks > 1 and any action -other than NO_ACTION is returned. -

-

Other useful techniques that may improve performance of certain -applications are: -

    -
  1. - set up multiple slaves on each processor (if slave processors - are sometimes idle) -
  2. - re-write the code to bundle a set of tasks as a single task - (to improve the granularity of your parallelism) -
- -
-
PERFORMANCE ISSUE FOR MPI:
-

If you have a more efficient version of ‘MPI’ (perhaps a vendor version -tuned to your hardware), consider replacing LIBMPI in -‘.../top-c/Makefile’ by your vendor's ‘limbpi.a’ or -‘libmpi.so’, and delete or modify the the LIBMPI target in the -‘Makefile’. -Alternatively, see the appendix, -Using a Different ‘MPI’ with TOP-C, -for a more general way to use a different MPI dialect. -

-
-
-
PERFORMANCE ISSUE FOR SMP (POSIX threads):
-

Finally under ‘SMP’, there is an important performance issue -concerning the interaction of ‘TOP-C’ with the operating system. -First, the vendor-supplied compiler, cc, is recommended over -gcc for ‘SMP’, due to specialized vendor-specific -architectural issues. Second, if a thread completes its work before -using its full scheduling quantum, the operating system may yield the -CPU of that thread to another thread — potentially including a thread -belonging to a different process. There are several ways to defend -against this. One defense is to insure that the time for a single task -is significantly longer than one quantum. Another defense is to ask the -operating system to give you at least as many "run slots" as you have -threads (slaves plus master). Some operating systems use -pthread_setconcurrency() to allow an application to declare this -information, and ‘TOP-C’ invokes pthread_setconcurrency() -where it is available. However, other operating systems may have -alternative ways of tuning the scheduling of threads, and it is -worthwhile to read the relevant manuals of your operating system. -

-
- -
- - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

7.4 Long Jobs and Courtesy to Others

- - -

In the distributed memory model, infinite loops and broken socket -connections tend to leave orphaned processes running. -In the ‘TOP-C’ distributed memory model, -a slave times out if a task lasts longer than -a half hour or if the master does not reply -in a half hour. -This is implemented with the UNIX system call, alarm(). -

-

A half hour (1800 seconds) is the default timeout period. -The command line option --TOPC-slave-timeout=num -allows one to change this default. If num is 0, -then there is no timeout and ‘TOP-C’ makes no calls -to SIGALRM. -

-

The application writer may also find some of the following UNIX system calls -useful for allowing large jobs to coexist with other applications. -

-
setpriority(PRIO_PROCESS,getpid(),prio)
-

#include <unistd.h>
-#include <sys/resource.h>

-— prio = 10 still - gives you some CPU time. prio = 19 means that any job of - higher priority always runs before you. Place in main(). -

-
setrlimit(RLIMIT_RSS, &rlp)
-

#include <sys/resource.h>
-struct rlimit rlp;
-rlp.rlim_max = rlp.rlim_cur = SIZE;

-— SIZE is RAM limit (bytes). If your system has - significant paging, the system will prefer to keep your process - from growing beyond SIZE bytes of resident RAM. Even if you set - nice to priority 20, this is still important. Otherwise you may - cause someone to page out much of his or her job in your favor during - one of your infrequent quantum slices of CPU time. Place in - main(). (Not all operating systems enforce this request.) -

-
- -
- - - - - - - - - - - - -
[ << ][ >> ]           [Top][Contents][Index][ ? ]
-

- - This document was generated by Gene Cooperman on April, 15 2011 using texi2html 1.78. - -
- -

- - diff --git a/topc-2.5.2/doc/html/topc/topc_8.html b/topc-2.5.2/doc/html/topc/topc_8.html deleted file mode 100644 index 12ee9381..00000000 --- a/topc-2.5.2/doc/html/topc/topc_8.html +++ /dev/null @@ -1,898 +0,0 @@ - - - - - -TOP-C (Task Oriented Parallel C/C++): 8. Advanced Features of TOP-C - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

8. Advanced Features of ‘TOP-C

- -

It is best to postpone reading this section until the basic features -discussed in the previous chapters are clear. -

- - - - - - - - - -
- - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

8.1 Testing for Task Continuations and Redos

- - -
-
Function: TOPC_BOOL TOPC_is_REDO ( void ) - -
-
Function: TOPC_BOOL TOPC_is_CONTINUATION ( void ) - -
-

These return 0 (false) or 1 (true), according to whether the current - call to DoTask() was a result of a REDO - or CONTINUATION() action, respectively. The result is - is not meaningful if called outside of DoTask(). -

- -
- - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

8.2 Aborting Tasks

- - -
-
Function: void TOPC_abort_tasks ( void ) - -
-
Function: TOPC_BOOL TOPC_is_abort_pending ( void ) - -
-

TOPC_abort_tasks() should be called in CheckTaskResult(). - ‘TOP-C’ then makes a best effort (no guarantee) to notify each - slave. TOP-C does not directly abort tasks. However, - TOPC_is_abort_pending() returns 1 (true) - when invoked in DoTask() on a slave. A typical - DoTask() callback uses this to poll for an abort request - from the master, upon which it returns early with a special - task output. At the beginning of the next new task, REDO - or CONTINUATION, ‘TOP-C’ resets the pending abort - to 0 (false). See ‘examples/README’ of the ‘TOP-C’ - distribution for example code. -

- -
- - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

8.3 Memory Allocation for Task Buffers

- -

The principle of memory allocation in ‘TOP-C’ is that if an -application allocates memory, then it is the responsibility of the -application to free that memory. This issue typically arises around the -issue of task buffers (see section Task Input and Task Output Buffers) and calls -to TOPC_MSG(buf,buf_size). An application -often calls buf = malloc(...); or -buf = new ...; (in C++) -and copies data into that buffer before the call to TOPC_MSG. -Since the last action of GenerateTaskInput() or DoTask() -is typically to return TOPC_MSG(buf,buf_size), -there remains the question of how to free buf. -

- - - - - - - -
- - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

8.3.1 Avoiding malloc and new with Task Buffers

- -

The best memory allocation solution for task buffers is to implement the -buffers as local variables, and therefore on the stack. This avoids the -need for malloc and new, and the question of how to later -free that memory. -If you use TOPC_MSG (as opposed to TOPC_MSG_PTR, -see section Using TOPC_MSG_PTR() to Avoid Copying Large Buffers), then recall that TOPC_MSG -copies its buffer to a separate TOP-C space. For example, -

 
{ int x;
-   ...
-  return TOPC_MSG(&x, size_of(x));
-}
-
- - - - -

If your task buffer is of fixed size, one can allocate it as a character -array on the stack: char buf[BUF_SIZE];. -If your buffer contains variable size data, consider using -alloca in place of malloc to allocate on the -stack. -

 
{ ...
-  buf = alloca(buf_size);
-  return TOPC_MSG(buf, buf_size);
-}
-
- -

In all of the above cases, there is no need to free the buffer, since -TOPC_MSG will make a ‘TOP-C’-private copy and the -stack-allocated buffer will disappear when the current routine exits. -Note that alloca may be unavailable on your system. -Alternatively, the use of alloca may be undesirable due to very -large buffers and O/S limits on stack size. In such cases, consider the -following alternative. -

 
{ TOPC_BUF tmp;
-  ...
-  buf = malloc(buf_size);
-  tmp = TOPC_MSG(buf, buf_size);
-  free(buf);
-  return tmp;
-}
-
- -
- - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

8.3.2 Using TOPC_MSG_PTR() to Avoid Copying Large Buffers

- - -

If the cost of copying a large buffer is a concern, ‘TOP-C’ provides -an alternative function, which avoids copying into ‘TOP-C’ space. -

-
-
Function: TOPC_BUF TOPC_MSG_PTR ( void *buf, int buf_size ) - -
-

Same as TOPC_MSG(), except that it does not copy - buf into ‘TOP-C’ space. It is the responsibility - of the application not to free or modify buf as long - as ‘TOP-C’ might potentially pass it to an - application callback function. -

- -

TOPC_MSG_PTR() is inherently dangerous, if the application -modifies or frees a buffer and ‘TOP-C’ later passes that buffer -to a callback function. It may be useful when the cost of copying -large buffers is an issue, or if one is concerned about ‘TOP-C’ -making a call to malloc(). Note that the invocation -

 
  ./a.out --TOPC-safety=4
-
-

automatically converts all calls to TOPC_MSG_PTR() into -calls to TOPC_MSG(). This is useful in deciding -if a bug is related to the use of TOPC_MSG_PTR(). -

-

An application should not pass a buffer on the stack to TOPC_MSG_PTR(). -This can be avoided either by declaring a local variable to be -‘static’, or else using a global variable (or a class member -in the case of C++). In such cases, it is the responsibility of the -application to dynamically create and free buffers. -An example of how this can be done follows in the next section. -

-

Note that if the application code must also be compatible with the -shared memory model, then the static local variable or global variable -must also be thread-private -(Thread-Private Global Variables). -

-

For examples of coding with TOPC_MSG_PTR() that are compatible -with all memory models, including the shared memory model, -see ‘examples/README’ and the corresponding examples -in the ‘TOP-C’ distribution. -

-
- - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

8.3.3 Allocation and Freeing of Task Buffers for TOPC_MSG_PTR()

- -

Recall the syntax for creating a message buffer of type TOPC_BUF -using -TOPC_MSG_PTR(buf, buf_size). The two callback functions -GenerateTaskInput() and DoTask() both return such a -message buffer. In the case of -GenerateTaskInput(), ‘TOP-C’ saves a copy of the buffer, -which becomes an input argument to CheckTaskResult() -and to UpdateSharedData on the master. -Hence, if buf points to a temporarily allocated buffer, -it is the responsibility of the ‘TOP-C’ callback function to free the -buffer only after the callback function has returned. -This seeming contradiction can be easily handled by the following code. -
-

 
    TOPC_BUF GenerateTaskInput() {
-      static void *buf = NULL;
-      if ( buf == NULL ) { malloc(buf_size); }
-      ... [ Add new message data to buf ] ...
-      return TOPC_MSG_PTR(buf, buf_size);
-    }
-
-
-

If buf_size might vary dynamically between calls, the following -fragment solves the same problem. -

 
    TOPC_BUF GenerateTaskInput() {
-      static void *buf = NULL;
-      if ( buf != NULL ) { free(buf); }
-      ... [ Compute buf_size for new message ] ...
-      buf = malloc( buf_size );
-      ... [ Add new message data to buf ] ...
-      return TOPC_MSG_PTR(buf, buf_size);
-    }
-
- -

Note that buf is allocated as a static local -variable. ‘TOP-C’ restricts the buf of -TOPC_MSG_PTR(buf, buf_size) to point to a buffer that is in -the heap (not on the stack). Hence, buf must not point to -non-static local data. -

- -
- - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

8.3.4 Marshaling Complex Data Structures into ‘TOP-C’ Task Buffers

- -

If you use a distributed memory model and the buffer pointed to by -input includes fields with their own pointers, the application -must first follow all pointers and copy into a new buffer all data -referenced directly or indirectly by input. The new buffer can -then be passed to TOPC_MSG(). This copying process is called -marshaling. See section Marshaling and Heterogeneous Architectures. -

-

If following all pointers is a burden, then one can -load the application on the master and slaves at a common absolute -address, and insure that all pointer references have been initialized -before the first call to TOPC_master_slave(). In ‘gcc’, -one specifies an absolute load address with code such as: -

 
  gcc -Wl,-Tdata -Wl,-Thex_addr ...
-
-

These flags are for the data segment. If the pointers indirectly -reference -data on the stack, you may have to similarly specify stack absolute addresses. -Choosing a good hex_addr for all machines may be a matter of trial -and error. In a test run, print out the absolute addresses of some -pointer variables near the beginning of your data memory. -

-

Specifying an absolute load address has many risks, such as if -the master and slaves use different versions of the operating system, -the compiler, other software, or different hardware configurations. -Hence, this technique is recommended only as a last resort. -

- -
- - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

8.4 Optimizing TOP-C Code for the Shared Memory Model

- - -

The ‘TOP-C’ programmer's model changes slightly for shared -memory. With careful design, one can use the same application source -code both for distributed memory and shared memory architectures. -Processes are replaced by threads. UpdateSharedData() is -executed only by the master thread, and not by any slave thread. As -with distributed memory, TOPC_MSG() buffers are copied to -‘TOP-C’ space (shallow copy). As usual, the application is responsible -for freeing any application buffers outside of ‘TOP-C’ space. -Furthermore, since the master and slaves share memory, ‘TOP-C’ -creates the slaves only during the first call to master_slave. If a -slave needs to initialize any private data (see -TOPC_thread_private, below), then this can be done by the slave -the first time that it gains control through DoTask(). -

-

Two issues arise in porting a distributed memory -‘TOP-C’ application to shared memory. -

    -
  1. - reader-write synchronization: DoTask() must not read - shared data while UpdateSharedData() (on the master) - simultaneously writes to the shared data. -
  2. - creating thread-private (unshared) global variables: -
- -

Most ‘TOP-C’ applications for the distributed memory model will run -unchanged in the shared memory model. In some cases, one must add -additional ‘TOP-C’ code to handle these additional issues. In all -cases, one can easily retain compatibility with the distributed memory model. -

- - - - - - - -
- - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

8.4.1 Reader-Writer Synchronization

- - -

In shared memory, ‘TOP-C’ uses a classical single-writer, -multiple-reader strategy with writer-preferred for lock requests. -By default, DoTask() acts as the critical section of the -readers (the slave threads) and UpdateSharedData() acts as the -critical section of the writer (the master thread). -‘TOP-C’ sets a read lock around all of DoTask() and a write -lock around all of UpdateSharedData(). -

-

As always in the ‘TOP-C’ model, -it is an error if an application writes to shared data outside -of UpdateSharedData(). Note that GenerateTaskInput() -and CheckTaskResult() can safely read the shared data without -a lock in this case, since these routines and UpdateSharedData() -are all invoked only by the master thread. -

-

The default behavior implies that DoTask() and -UpdateSharedData() never run simultaneously. Optionally, one -can achieve greater concurrency through a finer level of granularity -by declaring to ‘TOP-C’ which sections of code read or write -shared data. If ‘TOP-C’ detects any call to TOPC_ATOMIC_READ(0), -‘TOP-C’ will follow the critical sections declared by the -application inside of DoTask() and UpdateSharedData(). -

-
-
Function: void TOPC_ATOMIC_READ ( 0 ) { ... C code ... } - -
-
Function: void TOPC_ATOMIC_WRITE ( 0 ) { ... C code ... } - -
-

This sets a global read or write lock in effect during the time - that C code is being executed. If a thread holds a write lock, - no thread may hold a read lock. If no thread holds a write lock, - arbitrarily many threads hold a read lock. If a thread requests - a write lock, no additional read locks will be granted until after the - write lock has been granted. See ‘examples/README’ of the - ‘TOP-C’ distribution for example code. -

- -

It is not useful to use TOPC_ATOMIC_READ() outside of DoTask() -not to use TOPC_ATOMIC_WRITE() outside of UpdateSharedData(). -

-

The number 0 refers to page 0 of shared data. ‘TOP-C’ currently -supports only a single common page of shared data, but future versions -will support multiple pages. In the future, two threads will be able to -simultaneously hold write locks if they are for different pages. -

-

The following alternatives to TOPC_ATOMIC_READ() -and TOPC_ATOMIC_WRITE() are provided for greater flexibility. -

-
-
Function: void TOPC_BEGIN_ATOMIC_READ ( 0 ) - -
-
Function: void TOPC_END_ATOMIC_READ ( 0 ) - -
-
Function: void TOPC_BEGIN_ATOMIC_WRITE ( 0 ) - -
-
Function: void TOPC_END_ATOMIC_WRITE ( 0 ) - -
-

The usage is the same as for TOPC_ATOMIC_READ -and TOPC_ATOMIC_WRITE. -

- -

In the distributed memory model of ‘TOP-C’, all of the -above invocations for atomic reading and writing are ignored, -thus retaining full compatibility between the shared and -distributed memory models. -

-
- - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

8.4.2 Thread-Private Global Variables

- - -

A thread-private variable is a variable whose data is not -shared among threads: i.e., each thread has a private copy of -the variable. -The only variables that are thread-private by default in -shared memory are those on the stack (non-static, local variables). All -other variables exist as a single copy, shared by all threads. -This is inherent in the POSIX standard for threads in C/C++. -If DoTask() accesses any global variables or local static variables, -then those variables must be made thread-private. -

-

Ideally, if C allowed it, we would just write something like: -

 
  THREAD_PRIVATE int myvar = 0;  /* NOT SUPPORTED */
-
-

Instead, ‘TOP-C’ achieves the same effect ‘as if’ it had -declared -

 
  TOPC_thread_private_t TOPC_thread_private;
-
-

This allows the application writer to include in his or her code: -

 
  typedef int TOPC_thread_private_t;
-  #define myvar TOPC_thread_private;
-  int myvar_debug() {return myvar;} /* needed to access myvar in gdb */
-
- -

TOP-C’ provides primitives to declare a single thread-private -global variable. ‘TOP-C’ allows -the application programmer to declare the type of that variable. -

-
Variable: TOPC_thread_private - -
-

A pre-defined thread-private variable of type, - TOPC_thread_private_t. It may be - used like any C variable, and each thread has its own private - copy that will not be shared. -

-
-
Type: TOPC_thread_private_t - -
-

Initially, undefined. User must define this type using typedef - if TOPC_thread_private is used. -

- -

If more than one thread-private variable is desired, define -TOPC_thread_private_t as a struct, and use each -field as a separate thread-private variable. -

-

EXAMPLE: -

-
 
/* Ideally, if C allowed it, we would just write:
- *      THREAD_PRIVATE struct {int my_rank; int rnd;} mystruct;
- * We emulate this using TOP-C's implicitly declared thread-private var:
- *      TOPC_thread_private_t TOPC_thread_private;
- */
-typedef struct {int my_rank; int rnd;} TOPC_thread_private_t;
-#define mystruct TOPC_thread_private
-void set_info() {
-  mystruct.my_rank = TOPC_rank();
-  mystruct.rnd = rand();
-}
-void get_info() {
-foo();
-  if (mystruct.my_rank != TOPC_rank()) printf("ERROR\n");
-  printf("Slave %d random num:  %d\n", mystruct.my_rank, mystruct.rnd);
-}
-TOPC_BUF do_Task() {
-  set_info(); /* info in mystruct is NOT shared among threads */
-  get_info();
-  ...;
-}
-
- -

Additional examples can be found by reading -‘examples/README’ in the ‘TOP-C’ distribution. -

-
- - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

8.4.3 Sharing Variables between Master and Slave and Volatile Variables

- - -

The shared memory model, like any ‘SMP’ code, -allows the master and slaves to -communicate through global variables, which are shared by default. -It is recommended not to use this feature, and instead to maintain -communication through TOPC_MSG(), for ease of code maintenance, -and to maintain portability with the other ‘TOP-C’ models -(distributed memory and sequential). If you do use your own global shared -variables between master and slaves, be sure to declare them volatile. -

 
  volatile int myvar;
-
-

ANSI C requires this qualifier if a variable -may be accessed or modified by more than one thread. -Without this qualifier, your program may not run correctly. -

-

To be more precise, if a non-local variable is accessed more than once -in a procedure, the compiler is allowed to keep the first access value -in a thread register and reuse it at later occurrences, without consulting -the shared memory. A volatile declaration tells the compiler to re-read -the value from shared memory at each occurrence. Similarly, a write to -a volatile variable causes the corresponding transfer of its value from -a register to shared memory to occur at a time not much later than the -execution of the write instruction. -

-

If you suspect a missing volatile declaration, note that ‘gcc’ -support the following command-line options. -

 
  gcc -fvolatile -fvolatile-global ...
-  # If topcc uses gcc:
-  topcc --pthread -fvolatile -fvolatile-global myfile.c
-
-

The option -fvolatile tells ‘gcc’ to compile all memory -references through pointers as volatile, and the option --fvolatile-global tells ‘gcc’ to compile all memory -references to extern and global data as volatile. -However, note that this implies a performance penalty -since the compiler will issue -a load/store instruction for each volatile access, and -will not keep volatile values in registers. -

- -
- - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

8.4.4 SMP Performance

- -

Note that ‘SMP’ involves certain performance issues that do not arise -in other modes. If you find a lack of performance, please read -Improving Performance. Also, note that the vendor-supplied -compiler, cc, is often recommended over gcc for -‘SMP’, due to specialized vendor-specific architectural issues. -

-
- - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

8.5 Modifying TOP-C Code for the Sequential Memory Model

- - -

TOP-C’ also provides a sequential memory model. That model is -useful for first debugging an application in a sequential context, and -then re-compiling it with one of the parallel ‘TOP-C’ libraries for -production use. The application code for the sequential library is -usually both source and object compatible with the application code for -a parallel library. The sequential library emulates an application with -a single ‘TOP-C’ library. -

-

The sequential memory model emulates an application in which -‘DoTask()’ is executed in the context of the single slave -process/thread, and all other code is executed in the context of the -master process/thread. This affects the values returned by -TOPC_is_master() and TOPC_rank(). In particular, -conditional code for execution on the master will work -correctly in the sequential memory model, but the following conditional -code for execution on the slave will probably not work correctly. -

 
int main( int argc, char *argv[] ) {
-  TOPC_init( &argc, &argv );
-  if ( TOPC_is_master() )
-    ...;  /* is executed in sequential model */
-  else
-    ...;  /* is never executed in sequential model */
-  TOPC_master_slave( ..., ..., ..., ...);
-  TOPC_finalize();
-}
-
- -
- - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

8.6 Caveats

-

IMPORTANT: -‘TOP-C’ sets alarm() before waiting to receive - message from master. By default, if the master does not reply in a - half hour (1800 seconds), then the slave receives - SIGALRM and dies. - This is to prevent runaway processes in dist. memory version when master dies - without killing all slaves. Long Jobs and Courtesy to Others, - in order to change this default. - If your applications also uses SIGALRM, then run your - application with --TOPC-slave-timeout=0 and ‘TOP-C’ - will not use SIGALRM. -

-

GenerateTaskInput() and DoTask() - This memory is managed by ‘TOP-C’. -

-

The slave process attempts to set current directory to the same as the master - inside TOPC_init() and produces a warning if unsuccessful. -

-

When a task buffer is copied into ‘TOP-C’ space, -it becomes word-aligned. If the buffer was originally not -word-aligned, but some field in the buffer was word-aligned, -the internal field will no longer be word-aligned. On some -architectures, casting a non-word-aligned field to ‘int’ -or certain other types will cause a bus error. -

-
- - - - - - - - - - - - -
[ << ][ >> ]           [Top][Contents][Index][ ? ]
-

- - This document was generated by Gene Cooperman on April, 15 2011 using texi2html 1.78. - -
- -

- - diff --git a/topc-2.5.2/doc/html/topc/topc_9.html b/topc-2.5.2/doc/html/topc/topc_9.html deleted file mode 100644 index 2fe342ec..00000000 --- a/topc-2.5.2/doc/html/topc/topc_9.html +++ /dev/null @@ -1,298 +0,0 @@ - - - - - -TOP-C (Task Oriented Parallel C/C++): 9. TOP-C Raw Interface for Parallelizing Sequential Code - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

9. ‘TOP-C’ Raw Interface for Parallelizing Sequential Code

- -

There are instances when tasks are most naturally generated deep -inside nested loops. Often, this occurs in parallelizing existing -sequential applications. -In such circumstances, it may be difficult to -re-write the code to create a function GenerateTaskInput(), since -that would require turning the loops inside out. (If you don't know what this -refers to, then you probably don't need the raw interface.) -

-

On a first reading, you may wish to first look at the example for -either a ‘for’ loop or ‘while’ loop, depending on the type of -loop that you are parallelizing. Then return to the formal -descriptions of the ‘TOP-C’ raw functions. This chapter assumes -familiarity with the basic concepts of Overview of ‘TOP-C/C++ and Writing ‘TOP-C’ Applications. -

- - - - - - -
- - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

9.1 ‘TOP-C’ raw functions

- -
-
Function: void TOPC_raw_begin_master_slave - -
-

(do_task, check_task_result, update_shared_data) -

Function: void TOPC_raw_end_master_slave () - -
-

This behaves like master_slave, with - TOPC_raw_submit_task_input(input) serving - the role of GenerateTaskInput(). The slave blocks inside - TOPC_raw_begin_master_slave() and executes ‘do_task()’ and - ‘update_shared_data()’ until the master executes - TOPC_raw_end_master_slave(). At that time, the slave - unblocks. The slave does nothing inside - TOPC_raw_end_master_slave(). -

- -
-
Function: void TOPC_raw_submit_task_input ( TOPC_BUF input ) - -
-

Invoked by master between TOPC_raw_begin_master_slave() - and TOPC_raw_end_master_slave(); Typical usage is: -

 
     TOPC_raw_submit_task_input(TOPC_MSG(&input_data,
-                                         sizeof(input_data)) );
-
-

The argument, input, corresponds to what would be returned by - GenerateTaskInput() in the routine TOPC_master_slave(). - input will be processed by DoTask() and its siblings, - just as in TOPC_master_slave()). - There can be multiple occurrences of - TOPC_raw_submit_task_input(). -

- -
-
Function: TOPC_BOOL TOPC_raw_wait_for_task_result () - -
-

Invoked by master between TOPC_raw_begin_master_slave() and - TOPC_raw_end_master_slave(); - If no tasks are outstanding, returns false immediately. Otherwise, it - blocks until a task does return. It calls application - callback, CheckTaskResult(), and then returns true. -

- -
- - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

9.2 Parallelizing ‘for’ Loops

- -

Assume that we are parallelizing a code fragment of the following form. -The variables i and j will be the input to -DoTask(), and any data structures indexed by i and -j (for example array in array[i][j]) will be -part of the shared data. -

 
  float array[ROWS][COLS];
-  ...
-    for ( i = 0; i < 10; i++ ) {
-      for ( j = 0; j < 10; j++ ) {
-        /* do_task: */ ...
-        /* update:  */ array[i][j] = ...;
-      }
-    }
-
- -

Assume that the labels do_task and update above -correspond to the callback functions DoTask() and -UpdateSharedData(). Then the code is parallelized below. -

-
 
  float array[ROWS][COLS];
-  typedef struct {int i_val; int j_val;} input_t;
-  void *DoTask(input_t *buf) {
-    int i = (*buf).i_val, j = (*buf).j_val;
-    /* do_task: */ ...
-  }
-  void *CheckTaskResult(input_t *buf, output_t *buf2) {
-    /* update:  */ array[i][j] = ...;
-    return NO_ACTION;
-  }
-  main(int argc, char **argv) {
-    TOPC_init( &argc, &argv );
-    TOPC_raw_begin_master_slave(DoTask, CheckTaskResult,
-                                UpdateSharedData);
-    if (TOPC_is_master()) {
-      for ( i = 0; i < 10; i++ ) {
-        for ( j = 0; j < 10; j++ ) {
-          input_t input;
-          input.i_val = i; input.j_val = j;
-          TOPC_raw_submit_task_input( TOPC_MSG(&input, sizeof(input)) );
-        }
-      }
-    } TOPC_raw_end_master_slave();
-    TOPC_finalize();
-  }
-
- -
- - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

9.3 Parallelizing ‘while’ Loops

- -

Assume that we are parallelizing a code fragment of the following form -and input is a pointer. -

 
  while ( (input = next_input()) != NULL ) {
-    /* do_task: */ ...
-    /* update:  */ ...
-  }
-
- -

Assume that the labels do_task and update above -correspond to the callback functions DoTask() and -UpdateSharedData(). Then the code is parallelized below, -where input_size must be specified by the application before it -is used. -

-
 
  TOPC_init( &argc, &argv );
-  TOPC_raw_begin_master_slave(DoTask, CheckTaskResult,
-                              UpdateSharedData);
-  if (TOPC_is_master()) {
-    while ( (input = next_input()) != NULL
-            || TOPC_raw_wait_for_task_result() ) {
-      TOPC_raw_submit_task_input( TOPC_MSG(input, input_size) );
-    }
-  } TOPC_raw_end_master_slave();
-  TOPC_finalize();
-
- -

Note that the code inside the raw begin/end block is executed -only by the master in the code above. -

- -

If the buffer, input, contains pointers to other data, then you -will need to marshal the data before calling TOPC_MSG(). -See section Marshaling and Heterogeneous Architectures. -

-
- - - - - - - - - - - - -
[ << ][ >> ]           [Top][Contents][Index][ ? ]
-

- - This document was generated by Gene Cooperman on April, 15 2011 using texi2html 1.78. - -
- -

- - diff --git a/topc-2.5.2/doc/html/topc/topc_abt.html b/topc-2.5.2/doc/html/topc/topc_abt.html deleted file mode 100644 index b599e05c..00000000 --- a/topc-2.5.2/doc/html/topc/topc_abt.html +++ /dev/null @@ -1,167 +0,0 @@ - - - - - -TOP-C (Task Oriented Parallel C/C++): About This Document - - - - - - - - - - - - - - - - - - - - -
[Top][Contents][Index][ ? ]
-

About This Document

-

- This document was generated by Gene Cooperman on April, 15 2011 using texi2html 1.78. -

-

- The buttons in the navigation panels have the following meaning: -

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Button Name Go to From 1.2.3 go to
[ < ] BackPrevious section in reading order1.2.2
[ > ] ForwardNext section in reading order1.2.4
[ << ] FastBackBeginning of this chapter or previous chapter1
[ Up ] UpUp section1.2
[ >> ] FastForwardNext chapter2
[Top] TopCover (top) of document  
[Contents] ContentsTable of contents  
[Index] IndexIndex  
[ ? ] AboutAbout (help)  
- -

- where the Example assumes that the current position is at Subsubsection One-Two-Three of a document of the following structure: -

- -
    -
  • 1. Section One -
      -
    • 1.1 Subsection One-One -
        -
      • ...
      • -
      -
    • -
    • 1.2 Subsection One-Two -
        -
      • 1.2.1 Subsubsection One-Two-One
      • -
      • 1.2.2 Subsubsection One-Two-Two
      • -
      • 1.2.3 Subsubsection One-Two-Three     - <== Current Position
      • -
      • 1.2.4 Subsubsection One-Two-Four
      • -
      -
    • -
    • 1.3 Subsection One-Three -
        -
      • ...
      • -
      -
    • -
    • 1.4 Subsection One-Four
    • -
    -
  • -
- -
- - - - - -
[Top][Contents][Index][ ? ]
-

- - This document was generated by Gene Cooperman on April, 15 2011 using texi2html 1.78. - -
- -

- - diff --git a/topc-2.5.2/doc/html/topc/topc_fot.html b/topc-2.5.2/doc/html/topc/topc_fot.html deleted file mode 100644 index a8aa09b5..00000000 --- a/topc-2.5.2/doc/html/topc/topc_fot.html +++ /dev/null @@ -1,76 +0,0 @@ - - - - - -TOP-C (Task Oriented Parallel C/C++): Footnotes - - - - - - - - - - - - - - - - - - - - -
[Top][Contents][Index][ ? ]
-

Footnotes

-

(1)

-

MPI is -Message Passing Interface, see http://www.mpi-forum.org/ -

(2)

-

valgrind is available at -http://www.valgrind.kde.org. -

(3)

-

efence is available at -http://sources.isc.org/devel/memleak/efence. -


- - - - - -
[Top][Contents][Index][ ? ]
-

- - This document was generated by Gene Cooperman on April, 15 2011 using texi2html 1.78. - -
- -

- - diff --git a/topc-2.5.2/doc/html/topc/topc_ovr.html b/topc-2.5.2/doc/html/topc/topc_ovr.html deleted file mode 100644 index 8ceaa700..00000000 --- a/topc-2.5.2/doc/html/topc/topc_ovr.html +++ /dev/null @@ -1,87 +0,0 @@ - - - - - -TOP-C (Task Oriented Parallel C/C++): Short Table of Contents - - - - - - - - - - - - - - - - - - - - -
[Top][Contents][Index][ ? ]
-

Short Table of Contents

- -
- - - - - -
[Top][Contents][Index][ ? ]
-

- - This document was generated by Gene Cooperman on April, 15 2011 using texi2html 1.78. - -
- -

- - diff --git a/topc-2.5.2/doc/html/topc/topc_toc.html b/topc-2.5.2/doc/html/topc/topc_toc.html deleted file mode 100644 index 4380ca7e..00000000 --- a/topc-2.5.2/doc/html/topc/topc_toc.html +++ /dev/null @@ -1,155 +0,0 @@ - - - - - -TOP-C (Task Oriented Parallel C/C++): Table of Contents - - - - - - - - - - - - - - - - - - - - -
[Top][Contents][Index][ ? ]
-

Table of Contents

-
- - -
-
- - - - - -
[Top][Contents][Index][ ? ]
-

- - This document was generated by Gene Cooperman on April, 15 2011 using texi2html 1.78. - -
- -

- - diff --git a/topc-2.5.2/doc/html/topc_1.html b/topc-2.5.2/doc/html/topc_1.html deleted file mode 100644 index 00ec972d..00000000 --- a/topc-2.5.2/doc/html/topc_1.html +++ /dev/null @@ -1,92 +0,0 @@ - - - - - -TOP-C (Task Oriented Parallel C/C++): Copying - - - - - - - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
- -

1. `TOP-C' Copying Conditions

- -

- -All of the copyright notices of this package are designed to encourage -free copying and usage. This manual is copyright by Gene Cooperman. -Most of the source code files of the `TOP-C' software package contain -a copyright notice similar to that below. At the current time, Some of -the source files are copyright by Gene Cooperman alone and some by both -Gene Cooperman and Victor Grinberg, but all files are distributed under -the GNU LGPL license referred to below. -

- -
 
  **********************************************************************
-  * Copyright (c) 2000 - 2004 Gene Cooperman <gene@ccs.neu.edu>        *
-  *                                                                    *
-  * This library is free software; you can redistribute it and/or      *
-  * modify it under the terms of the GNU Lesser General Public         *
-  * License as published by the Free Software Foundation; either       *
-  * version 2.1 of the License, or (at your option) any later version. *
-  *                                                                    *
-  * This library is distributed in the hope that it will be useful,    *
-  * but WITHOUT ANY WARRANTY; without even the implied warranty of     *
-  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU   *
-  * Lesser General Public License for more details.                    *
-  *                                                                    *
-  * You should have received a copy of the GNU Lesser General Public   *
-  * License along with this library (see file COPYING); if not, write  *
-  * to the Free Software Foundation, Inc., 59 Temple Place, Suite      *
-  * 330, Boston, MA 02111-1307 USA, or contact Gene Cooperman          *
-  * <gene@ccs.neu.edu>.                                                *
-  **********************************************************************
-

- - -


- - - - - - - -
[ << ][ >> ]           [Top][Contents][Index][ ? ]
-
- -This document was generated -by Gene Cooperman on October, 6 2004 -using texi2html - - - - diff --git a/topc-2.5.2/doc/html/topc_10.html b/topc-2.5.2/doc/html/topc_10.html deleted file mode 100644 index d3e11705..00000000 --- a/topc-2.5.2/doc/html/topc_10.html +++ /dev/null @@ -1,91 +0,0 @@ - - - - - -TOP-C (Task Oriented Parallel C/C++): Acknowledgements - - - - - - - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

10. Acknowledgements

- -

- -A project of this scope cannot be achieved alone. While Gene Cooperman -was the primary author, the project has benefited from contributions -by several various individuals and institutions at different times. -

- -The author wishes to thank the National Science Foundation for -support under which much of this work was developed. -The author wishes to thank the Mariner Project at Boston University -for the use of the Origin 2000 and other facilities which helped in the -development of this software. An earlier, experimental version of mpinu -(MPI subset) was written by Markos Kyzas and partially revised by Gene -Cooperman. Michael Weller provided ideas for improving some of the C -code, and provided valuable feedback when he adapted the `TOP-C' ideas -to a large application on an IBM SP-2. The loader module is joint -with Victor Grinberg. Further experience and feedback was gained -from the GAP community when the `TOP-C' model was ported to ParGAP, a -refereed share package. (GAP -- Groups, Algorithms and Programming) -is a language similar to Maple, specialized for symbolic computations -in computational algebra and especially computational group theory.) -`TOP-C', version 2, was exported by Victor Grinberg from ParGAP, with -enhancements by Gene Cooperman. Some important feedback was gained -in the TOP-C parallelization of Geant4. -(Geant4 is a toolkit for the Monte Carlo simulation of particle-matter -interaction. The package has close to a million lines of C++ code. -The TOP-C parallelization is included with the Geant4 distribution.) -Xiaoqin Ma analyzed mechanisms for -detecting and recovering from dead slaves, broken sockets, etc., -and wrote the first version of code to handle that. -

- - -


- - - - - - - -
[ << ][ >> ]           [Top][Contents][Index][ ? ]
-
- -This document was generated -by Gene Cooperman on October, 6 2004 -using texi2html - - - - diff --git a/topc-2.5.2/doc/html/topc_11.html b/topc-2.5.2/doc/html/topc_11.html deleted file mode 100644 index 3eee5e3c..00000000 --- a/topc-2.5.2/doc/html/topc_11.html +++ /dev/null @@ -1,238 +0,0 @@ - - - - - -TOP-C (Task Oriented Parallel C/C++): Summary - - - - - - - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

A. Summary of `TOP-C' Commands

- -

- -From 4.1 The Main TOP-C Library Calls. -

-
void TOPC_init ( int *argc, char ***argv ) -
void TOPC_finalize ( void ) -
  Function
-
-
void TOPC_master_slave -
( TOPC_BUF (*generate_task_input)(),
   TOPC_BUF (*do_task)(void *input),
   TOPC_ACTION (*check_task_result)(void *input, void *output),
   void (*update_shared_data)(void *input, void *output) -
) -
  Function
-
-
TOPC_BUF TOPC_MSG ( void *buf, int buf_size ) -
  Function
-
-
-

- -From Callback Functions for TOPC_master_slave() . -

-
TOPC_BUF GenerateTaskInput ( void ) -
  Function
-
-
TOPC_BUF DoTask ( void *input ) -
  Function
-
-
TOPC_ACTION CheckTaskResult ( void *input, void *output) -
  Function
-
-
void UpdateSharedData ( void *input, void *output ) -
  Function
-
-
-

- -From Actions Returned by CheckTaskResult() . -

-
Action TOPC_ACTION NO_ACTION -
  Action
-
-
Action TOPC_ACTION UPDATE -
  Action
-
-
Action TOPC_ACTION REDO -
  Action
-
-
Action TOPC_ACTION CONTINUATION ( void *next_input ) -
  Action
-
-
-

- -From 4.4 TOP-C Utilities. -

-
TOPC_BOOL TOPC_is_up_to_date ( void ) -
  Function
-
-
int TOPC_rank ( void ) -
  Function
-
-
TOPC_BOOL TOPC_is_master ( void ) -
  Function
-
-
int TOPC_num_slaves ( void ) -
  Function
-
-
int TOPC_num_idle_slaves ( void ) -
  Function
-
-
int TOPC_node_count ( void ) -
  Function
-
-
-

- -From Optimizing TOP-C Code for the Shared Memory Model . -

-
TOPC_thread_private -
  Variable
-
-
TOPC_thread_private_t -
  Type
-
-
void TOPC_ATOMIC_READ ( 0 ) { ... C code ... } -
void TOPC_ATOMIC_WRITE ( 0 ) { ... C code ... } -
  Function
-
-
void TOPC_BEGIN_ATOMIC_READ ( 0 ) -
void TOPC_END_ATOMIC_READ ( 0 ) -
void TOPC_BEGIN_ATOMIC_WRITE ( 0 ) -
void TOPC_END_ATOMIC_WRITE ( 0 ) -
  Function
-
-
-

- -From Raw `TOP-C' interface: raw_master_slave . -

-
void TOPC_raw_begin_master_slave -
(do_task, check_task_result, update_shared_data) -
void TOPC_raw_end_master_slave () -
  Function
-
-
void TOPC_raw_submit_task_input ( TOPC_BUF input ) -
  Function
-
-
TOPC_BOOL TOPC_raw_wait_for_task_result () -
  Function
-
-
-

- -From 8.2 Aborting Tasks. -

-
void TOPC_abort_tasks ( void ) -
TOPC_BOOL TOPC_is_abort_pending ( void ) -
  Function
-
-
-

- -From 8.1 Testing for Task Continuations and Redos. -

-
TOPC_BOOL TOPC_is_REDO ( void ) -
TOPC_BOOL TOPC_is_CONTINUATION ( void ) -
  Function
-
-
-

- -From 8.3.2 Using TOPC_MSG_PTR() to Avoid Copying Large Buffers. -

-
TOPC_BUF TOPC_MSG_PTR ( void *buf, int buf_size ) -
  Function
-
-
-

- -From Command Line Options in TOP-C Applications . -

-
--TOPC-help`[=<0/1>]' -
  [boolean, default: false]
-
-
--TOPC-verbose`[=<0/1>]' -
  [boolean, default: false]
-
-
--TOPC-stats`[=<0/1>]' -
  [boolean, default: false]
-
-
--TOPC-num-slaves`=<int>' -
  [default: -1 (system-defined)]
-
-
--TOPC-slave-wait`=<int>' -
  [default: 0]
-
-
--TOPC-slave-timeout`=<int>' -
  [default: 1800 s]
-
-
--TOPC-trace`=<int: 0/1/2>' -
  [trace (0: notrace, 1: trace, 2: user trace fncs, default: 2)]
-
-
--TOPC-procgroup`=<string>' -
  [default: "./procgroup"]
-
-
--TOPC-safety`=<int: 0..20>' -
  [default: 0]
-
-
-

- -From 6.4 Tracing Messages. -

-
int TOPC_OPT_trace -
void (*)(void *input) TOPC_OPT_trace_input -
void (*)(void *input, void *output) TOPC_OPT_trace_result -
-

- - -


- - - - - - - -
[ << ][ >> ]           [Top][Contents][Index][ ? ]
-
- -This document was generated -by Gene Cooperman on October, 6 2004 -using texi2html - - - - diff --git a/topc-2.5.2/doc/html/topc_12.html b/topc-2.5.2/doc/html/topc_12.html deleted file mode 100644 index b858799c..00000000 --- a/topc-2.5.2/doc/html/topc_12.html +++ /dev/null @@ -1,153 +0,0 @@ - - - - - -TOP-C (Task Oriented Parallel C/C++): Example - - - - - - - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

B. Example `TOP-C' Application

- -

- - -

- -There are several example `TOP-C' programs in the -`topc/examples' subdirectory. We include one example in this -manual. It does not contain any UPDATE actions, and therefore -illustrates only a trivial form of parallelism (with no interaction -among the slaves). The `topc/examples' subdirectory should be -inspected for more sophisticated examples. -After understanding this example, you may also want to look at -8. Advanced Features of `TOP-C', or if you are parallelizing a sequential -program, then you may want to look at 9. `TOP-C' Raw Interface for Parallelizing Sequential Code. -

- -This program produces an array of 10,000,000 random integers in one pass, -and then finds the maximum value in a second pass. It would be compiled -by: topcc MODE `file.out', where MODE is one of ---seq, --mpi, or --pthread. One can control the -number of slaves by executing: ./a.out --TOPC-num-slaves=num. -

- -
 
#include <stdlib.h>
-#include <string.h>
-#include <stdio.h>
-#include <topc.h>
-
-#define MAX 2000000
-#define INCR MAX/10 /* We assume INCR divides MAX exactly */
-
-int array[MAX];
-int idx;
-int max_int;
-
-TOPC_BUF GenerateTaskInput() {
-  int input_task;
-  if (idx >= MAX) return NOTASK;
-  input_task = idx;
-  idx = idx + INCR;
-  return TOPC_MSG( &input_task, sizeof(input_task) );
-}
-TOPC_BUF DoTaskRandom( int *ignore ) {
-  int rand_int[INCR];
-  int i;
-  for ( i = 0; i < INCR; i++)
-    rand_int[i] = rand();
-  return TOPC_MSG( rand_int, INCR * sizeof(int) );
-}
-TOPC_ACTION CheckTaskRandom( int *input, int rand_vals[] ) {
-  int curr_idx = *input;
-  memcpy( array+curr_idx, rand_vals, INCR * sizeof(int) );
-  return NO_ACTION;
-}
-
-TOPC_BUF GenerateTaskInMax() {
-  int *input_task;
-  if (idx >= MAX) return NOTASK;
-  input_task = array + idx;
-  idx = idx + INCR;
-  return TOPC_MSG( input_task, INCR * sizeof(int) );
-}
-TOPC_BUF DoTaskMax( int subarray[] ) {
-  int i;
-  int max=0;
-  for ( i = 0; i < INCR; i++)
-    if ( subarray[i] > max )
-      max = subarray[i];
-  return TOPC_MSG( &max, sizeof(max) );
-}
-TOPC_ACTION CheckTaskMax( int ignore[], int *output ) {
-  int curr_max = *output;
-  if ( curr_max > max_int )
-    max_int = curr_max;
-  return NO_ACTION;
-}
-
-int main( int argc, char **argv ) {
-  /* Set default to no trace; Override with:  ./a.out --TOPC-trace=1 */
-  TOPC_OPT_trace = 0;
-  TOPC_init( &argc, &argv );
-  idx = 0; /* Initialize idx, and randomize values of array[] */
-  TOPC_master_slave(GenerateTaskInput, DoTaskRandom, CheckTaskRandom,
-                    NULL);
-  if (TOPC_is_master())
-    printf("Finished randomizing integers.\n");
-  idx = 0; /* Re-initialize idx to 0, and find max. value in array[] */
-  TOPC_master_slave( GenerateTaskInMax, DoTaskMax, CheckTaskMax, NULL );
-  TOPC_finalize();
-  printf("The maximum integer is:  %d\n", max_int);
-  exit(0);
-}
-

- - -


- - - - - - - -
[ << ][ >> ]           [Top][Contents][Index][ ? ]
-
- -This document was generated -by Gene Cooperman on October, 6 2004 -using texi2html - - - - diff --git a/topc-2.5.2/doc/html/topc_13.html b/topc-2.5.2/doc/html/topc_13.html deleted file mode 100644 index 97869b91..00000000 --- a/topc-2.5.2/doc/html/topc_13.html +++ /dev/null @@ -1,131 +0,0 @@ - - - - - -TOP-C (Task Oriented Parallel C/C++): Using a Different MPI with TOP-C - - - - - - - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

C. Using a Different `MPI' with TOP-C

- -

- -`TOP-C' provides a built-in subset of MPI sufficient to run -distributed applications. If you prefer to use a different implementation -of `MPI' with `TOP-C', this note describes how to do so. -Examples for `MPICH', `LAM' and `IBM POE' are at the -end of this section. You should re-configure and re-build `TOP-C' -using the same C/C++ compiler as that of your chosen MPI. -

- -First test a `hello_world' MPI program -for your chosen MPI implementation to make sure that the -startup mechanism is well understood. -

- -Many dialects of `MPI' provide their own wrapper around -the C and C++ compiler. For example, `LAM MPI' provides mpicc. -If your dialect provides such a wrapper mpicc, then -do ./configure --with-mpi-cc=mpicc and make. There is a similar -configure flag, --with-mpi-cxx, for `C++'. -

- -If you do use such a wrapper, you should use the same C compiler for -the rest of `TOP-C'. Hence, if mpicc uses cc, -then configure with env CC=cc ./configure --with-mpi-cc=mpicc ---cache-file=/dev/null. -In general, you can always specify a non-default C and C++ compiler by -specifying CC=... and CXX=..., respectively. -

- -If your dialect does not provide such a wrapper, it is easy to create -one by modifying the shell script below for your site. -
 
#!/bin/sh
-gcc -I/usr/local/include $* -L/usr/local/lib -lmpi
-

- -These wrappers will enable topcc and topc++ to work, -but not topc-config. If you also need topc-config, -then you must modify topc-config. -Determine the libraries used by your dialect of MPI. -Then search for a string with -ltopc-mpi in -`.../topc/bin/topc-config', -and append to it your `libmpi'. For example, -append to -ltopc-mpi with -L/usr/local/lib -lmpi. -

- -Finally, for many dialects of MPI, after compiling the MPI application, -they may also require a special command at runtime to execute, -such as mpirun a.out. -In such cases, your `TOP-C' application must be treated similarly. -

- -The following examples illustrate the configuration and use of -MPI for other MPI implementations using 2 slaves and 1 master. -
 
# IBM POE/AIX:
-  env CC=xlc CXX=xlC ./configure --with-mpi-cc=mpcc --with-mpi-cxx=mpCC
-  make; cd bin; ./topcc --mpi -qcpluscmt ../examples/parfactor.c
-  poe ./a.out 1234 --TOPC-stats -procs 3 -pgmmodel spmd
-

- -
 
# MPICH/Linux:
-  ./configure --with-mpi-cc=mpicc
-  make; cd bin; ./topcc --mpi ../examples/parfactor.c
-  mpirun -np 3 ./a.out --TOPC-stats 1234
-

- -
 
# LAM/Linux:
-  ./configure --with-mpi-cc=mpicc
-  make; cd bin; ./topcc --mpi ../examples/parfactor.c
-  mpirun -c 3 ./a.out -- --TOPC-stats 1234
-

- - -


- - - - - - - -
[ << ][ >> ]           [Top][Contents][Index][ ? ]
-
- -This document was generated -by Gene Cooperman on October, 6 2004 -using texi2html - - - - diff --git a/topc-2.5.2/doc/html/topc_14.html b/topc-2.5.2/doc/html/topc_14.html deleted file mode 100644 index 941d6601..00000000 --- a/topc-2.5.2/doc/html/topc_14.html +++ /dev/null @@ -1,128 +0,0 @@ - - - - - -TOP-C (Task Oriented Parallel C/C++): Function Index - - - - - - - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

Function Index

- -
Jump to:   C -   -D -   -G -   -T -   -U -   -

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Index Entry Section

C
CheckTaskResult4.2 Callback Functions for TOPC_master_slave()

D
DoTask4.2 Callback Functions for TOPC_master_slave()

G
GenerateTaskInput4.2 Callback Functions for TOPC_master_slave()

T
TOPC_abort_tasks4.4 TOP-C Utilities
TOPC_abort_tasks8.2 Aborting Tasks
TOPC_ATOMIC_READ8.4.1 Reader-Writer Synchronization
TOPC_ATOMIC_WRITE8.4.1 Reader-Writer Synchronization
TOPC_BEGIN_ATOMIC_READ8.4.1 Reader-Writer Synchronization
TOPC_BEGIN_ATOMIC_WRITE8.4.1 Reader-Writer Synchronization
TOPC_END_ATOMIC_READ8.4.1 Reader-Writer Synchronization
TOPC_END_ATOMIC_WRITE8.4.1 Reader-Writer Synchronization
TOPC_finalize4.1 The Main TOP-C Library Calls
TOPC_init4.1 The Main TOP-C Library Calls
TOPC_is_abort_pending4.4 TOP-C Utilities
TOPC_is_abort_pending8.2 Aborting Tasks
TOPC_is_CONTINUATION4.4 TOP-C Utilities
TOPC_is_CONTINUATION8.1 Testing for Task Continuations and Redos
TOPC_is_master4.4 TOP-C Utilities
TOPC_is_REDO4.4 TOP-C Utilities
TOPC_is_REDO8.1 Testing for Task Continuations and Redos
TOPC_is_up_to_date4.4 TOP-C Utilities
TOPC_master_slave4.1 The Main TOP-C Library Calls
TOPC_MSG4.1 The Main TOP-C Library Calls
TOPC_MSG_PTR8.3.2 Using TOPC_MSG_PTR() to Avoid Copying Large Buffers
TOPC_node_count4.4 TOP-C Utilities
TOPC_num_idle_slaves4.4 TOP-C Utilities
TOPC_num_slaves4.4 TOP-C Utilities
TOPC_rank4.4 TOP-C Utilities
TOPC_raw_begin_master_slave9.1 `TOP-C' raw functions
TOPC_raw_end_master_slave9.1 `TOP-C' raw functions
TOPC_raw_submit_task_input9.1 `TOP-C' raw functions
TOPC_raw_wait_for_task_result9.1 `TOP-C' raw functions

U
UpdateSharedData4.2 Callback Functions for TOPC_master_slave()

Jump to:   C -   -D -   -G -   -T -   -U -   -

- - -


- - - - - - - -
[ << ][ >> ]           [Top][Contents][Index][ ? ]
-
- -This document was generated -by Gene Cooperman on October, 6 2004 -using texi2html - - - - diff --git a/topc-2.5.2/doc/html/topc_15.html b/topc-2.5.2/doc/html/topc_15.html deleted file mode 100644 index 73da15d7..00000000 --- a/topc-2.5.2/doc/html/topc_15.html +++ /dev/null @@ -1,120 +0,0 @@ - - - - - -TOP-C (Task Oriented Parallel C/C++): Variable Index - - - - - - - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

Variable Index

- -
Jump to:   / -   -
-C -   -N -   -R -   -S -   -T -   -U -   -

- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Index Entry Section

/
/tmp/mpinu-ssh5.4.2 If Slaves Fail to Start

C
CONTINUATION4.3 Actions Returned by CheckTaskResult()

N
NO_ACTION4.3 Actions Returned by CheckTaskResult()

R
REDO4.3 Actions Returned by CheckTaskResult()

S
SSH5.4.1 Writing Procgroup Files for `MPINU'

T
TOPC_OPT_trace_input6.4 Tracing Messages
TOPC_OPT_trace_result6.4 Tracing Messages
TOPC_OPTS5.2 Command Line Options in TOP-C Applications
TOPC_thread_private8.4.2 Thread-Private Global Variables
TOPC_thread_private_t8.4.2 Thread-Private Global Variables

U
UPDATE4.3 Actions Returned by CheckTaskResult()

Jump to:   / -   -
-C -   -N -   -R -   -S -   -T -   -U -   -

- - -


- - - - - - - -
[ << ][ >> ]           [Top][Contents][Index][ ? ]
-
- -This document was generated -by Gene Cooperman on October, 6 2004 -using texi2html - - - - diff --git a/topc-2.5.2/doc/html/topc_16.html b/topc-2.5.2/doc/html/topc_16.html deleted file mode 100644 index 47f7fd39..00000000 --- a/topc-2.5.2/doc/html/topc_16.html +++ /dev/null @@ -1,277 +0,0 @@ - - - - - -TOP-C (Task Oriented Parallel C/C++): Concept Index - - - - - - - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

Concept Index

- -
Jump to:   - -   -. -   -
-A -   -C -   -D -   -E -   -F -   -G -   -H -   -I -   -L -   -M -   -N -   -O -   -P -   -R -   -S -   -T -   -V -   -

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Index Entry Section

-
--mpi argument to topcc/topc++5.4 Invoking a TOP-C Application in Distributed Memory
--pthread argument to topcc/topc++5.5 Invoking a TOP-C Application in Shared Memory
--seq argument to topcc/topc++5.3 Invoking a TOP-C Application in Sequential Memory
--TOPC-aggregated-tasks5.2 Command Line Options in TOP-C Applications
--TOPC-aggregated-tasks, usage7.3 Improving Performance
--TOPC-help5.2 Command Line Options in TOP-C Applications
--TOPC-num-slaves5.2 Command Line Options in TOP-C Applications
--TOPC-num-slaves, example6.1 Debugging by Limiting the Parallelism
--TOPC-num-slaves, selection of slave hosts using procgroup file5.4.1 Writing Procgroup Files for `MPINU'
--TOPC-procgroup5.2 Command Line Options in TOP-C Applications
--TOPC-procgroup, usage of procgroup file5.4.1 Writing Procgroup Files for `MPINU'
--TOPC-safety5.2 Command Line Options in TOP-C Applications
--TOPC-safety for debugging6.2 Debugging with `--TOPC-safety'
--TOPC-slave-timeout5.2 Command Line Options in TOP-C Applications
--TOPC-slave-timeout, for long jobs and runaway jobs7.4 Long Jobs and Courtesy to Others
--TOPC-slave-wait5.2 Command Line Options in TOP-C Applications
--TOPC-slave-wait, debugging a slave process with `gdb'6.5 Stepping Through a Slave Process with `gdb'
--TOPC-stats5.2 Command Line Options in TOP-C Applications
--TOPC-trace5.2 Command Line Options in TOP-C Applications
--TOPC-verbose5.2 Command Line Options in TOP-C Applications

.
.topcrc5.2 Command Line Options in TOP-C Applications

A
aborting tasks8.2 Aborting Tasks
action3.2 Three Key Concepts for TOP-C
actions returned by CheckTaskResult()4.3 Actions Returned by CheckTaskResult()
aggregation of tasks7.3 Improving Performance

C
command line options, TOP-C5.2 Command Line Options in TOP-C Applications
compiling the distributed memory model5.4 Invoking a TOP-C Application in Distributed Memory
compiling the sequential memory model5.3 Invoking a TOP-C Application in Sequential Memory
compiling the shared memory model5.5 Invoking a TOP-C Application in Shared Memory
CONTINUATION, testing for8.1 Testing for Task Continuations and Redos

D
debugging6. Debugging and Tracing
debugging memory management with efence6.6 Segmentation faults and other memory problems
debugging `TOP-C' `--mpi' applications that fail to start5.4.2 If Slaves Fail to Start
debugging, --TOPC-safety6.2 Debugging with `--TOPC-safety'
distributed memory model3.3 Distributed and Shared Memory Models
distributed memory, fails to start5.4.2 If Slaves Fail to Start

E
efence, debugging memory management6.6 Segmentation faults and other memory problems
example TOP-C applicationB. Example `TOP-C' Application

F
fine grain thread parallelism8.4.1 Reader-Writer Synchronization
finer grain parallelism7.3 Improving Performance

G
global shared data3.2 Three Key Concepts for TOP-C
global thread-private variable8.4.2 Thread-Private Global Variables

H
heterogeneous architecturesMarshaling (Serialization) and Heterogeneous Architectures

I
initializing `TOP-C'4.1 The Main TOP-C Library Calls

L
large message buffers8.3.2 Using TOPC_MSG_PTR() to Avoid Copying Large Buffers

M
Marshalgen, a package for marshalingMarshalgen, a Package for Marshaling
marshalingMarshaling (Serialization) and Heterogeneous Architectures
master-slave mode, invoking4.1 The Main TOP-C Library Calls
memory model, distributed3.3 Distributed and Shared Memory Models
memory model, distributed, compiling5.4 Invoking a TOP-C Application in Distributed Memory
memory model, sequential8.5 Modifying TOP-C Code for the Sequential Memory Model
memory model, sequential, compiling5.3 Invoking a TOP-C Application in Sequential Memory
memory model, shared8.4 Optimizing TOP-C Code for the Shared Memory Model
memory model, shared, compiling5.5 Invoking a TOP-C Application in Shared Memory
message format, TOPC_MSG()4.1 The Main TOP-C Library Calls
MPINU5.4.1 Writing Procgroup Files for `MPINU'
mpinu-ssh for debugging slave startup5.4.2 If Slaves Fail to Start

N
network latency, overcoming it7.3 Improving Performance

O
options, TOP-C5.2 Command Line Options in TOP-C Applications

P
procgroup file5.4.1 Writing Procgroup Files for `MPINU'

R
reader-writer synchronization8.4.1 Reader-Writer Synchronization
REDO, testing for8.1 Testing for Task Continuations and Redos

S
segmentation fault, debugging with efence6.6 Segmentation faults and other memory problems
sequential memory model8.5 Modifying TOP-C Code for the Sequential Memory Model
serializationMarshaling (Serialization) and Heterogeneous Architectures
shared data3.2 Three Key Concepts for TOP-C
shared memory model8.4 Optimizing TOP-C Code for the Shared Memory Model
SIGALRM6.3 TOP-C and POSIX signals
SIGALRM, raised by `TOP-C'7.4 Long Jobs and Courtesy to Others
signals and TOP-C6.3 TOP-C and POSIX signals
SIGPINT6.3 TOP-C and POSIX signals
SIGPIPE6.3 TOP-C and POSIX signals
SIGPIPE signal handler not recognized6. Debugging and Tracing
SIGSEGV, debugging with efence6.6 Segmentation faults and other memory problems
slave startup in distributed memory, difficulties5.4.2 If Slaves Fail to Start
SMP3.3 Distributed and Shared Memory Models
SSH environment variable for starting remote slaves5.4.1 Writing Procgroup Files for `MPINU'
static local variables and threads8.4.2 Thread-Private Global Variables
synchronization of threads, shared memory model8.4.1 Reader-Writer Synchronization

T
task3.2 Three Key Concepts for TOP-C
task continuation, testing8.1 Testing for Task Continuations and Redos
task input3.1.3 Task Input and Task Output Buffers
task input4.1 The Main TOP-C Library Calls
task input/output buffers, variable size8.3.1 Avoiding malloc and new with Task Buffers
task output3.1.3 Task Input and Task Output Buffers
task output4.1 The Main TOP-C Library Calls
thread-private variable8.4.2 Thread-Private Global Variables
`THREAD_PRIVATE'8.4.2 Thread-Private Global Variables
threads, synchronization in shared memory model8.4.1 Reader-Writer Synchronization
TOP-C action3.2 Three Key Concepts for TOP-C
TOP-C command line options5.2 Command Line Options in TOP-C Applications
TOP-C options5.2 Command Line Options in TOP-C Applications
topc++5.1 Compiling TOP-C Applications
topc-config5.1 Compiling TOP-C Applications
TOPC_MSG_PTR()8.3.2 Using TOPC_MSG_PTR() to Avoid Copying Large Buffers
TOPC_OPT_trace, usage for dynamically debugging messages6.4 Tracing Messages
TOPC_OPT_trace_input6.4 Tracing Messages
TOPC_OPT_trace_result6.4 Tracing Messages
TOPC_OPTS environment variable for initialization5.2 Command Line Options in TOP-C Applications
topcc5.1 Compiling TOP-C Applications
topcrc5.2 Command Line Options in TOP-C Applications

Jump to:   - -   -. -   -
-A -   -C -   -D -   -E -   -F -   -G -   -H -   -I -   -L -   -M -   -N -   -O -   -P -   -R -   -S -   -T -   -V -   -


- - - - - - - -
[ << ][ >> ]           [Top][Contents][Index][ ? ]
-
- -This document was generated -by Gene Cooperman on October, 6 2004 -using texi2html - - - - diff --git a/topc-2.5.2/doc/html/topc_17.html b/topc-2.5.2/doc/html/topc_17.html deleted file mode 100644 index e44a1838..00000000 --- a/topc-2.5.2/doc/html/topc_17.html +++ /dev/null @@ -1,145 +0,0 @@ - - - - - -TOP-C (Task Oriented Parallel C/C++): Concept Index: V - - - - - - - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

Concept Index: V

-
Jump to:   - -   -. -   -
-A -   -C -   -D -   -E -   -F -   -G -   -H -   -I -   -L -   -M -   -N -   -O -   -P -   -R -   -S -   -T -   -V -   -

- - - - - - - -
Index Entry Section

V
variable size task buffers8.3.1 Avoiding malloc and new with Task Buffers
volatile C/C++ variables8.4.3 Sharing Variables between Master and Slave and Volatile Variables

Jump to:   - -   -. -   -
-A -   -C -   -D -   -E -   -F -   -G -   -H -   -I -   -L -   -M -   -N -   -O -   -P -   -R -   -S -   -T -   -V -   -

- -


- - - - - - - -
[ << ][ >> ]           [Top][Contents][Index][ ? ]
-
- -This document was generated -by Gene Cooperman on October, 6 2004 -using texi2html - - - - diff --git a/topc-2.5.2/doc/html/topc_2.html b/topc-2.5.2/doc/html/topc_2.html deleted file mode 100644 index ee7b5bb4..00000000 --- a/topc-2.5.2/doc/html/topc_2.html +++ /dev/null @@ -1,168 +0,0 @@ - - - - - -TOP-C (Task Oriented Parallel C/C++): Quick Start - - - - - - - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

2. Quick Start: Installation and Test Run

- -

- -
 
   This is version 2.5.0 of Task Oriented Parallel C/C++ (`TOP-C').
-   See http://www.ccs.neu.edu/home/gene/topc.html for general
-   information on obtaining source, overview slides of `TOP-C',
-   previous `TOP-C' applications, etc.
-                                                      Gene Cooperman
-                                                      gene@ccs.neu.edu
-

- -It has been tested and works on several workstation -architectures. It provides task-oriented parallelism to the end user. -The same application source code (or object code) can be executed -(or linked) with any of the following communication libraries -using the topcc command (a substitute for cc or gcc): -

    -
  1. a distributed memory library using MPI - (MPI subset, mpinu, included in distribution); or -
  2. a shared memory library using threads; or -
  3. a single-process sequential library - (useful for development and debugging). -
-The `TOP-C' model has been successfully used for some very large -computations. -

- -To unpack: -
 
  gunzip topc.tar.gz
-  tar xvf topc.tar
-  cd topc
-  ./configure
-  make
-

- -If you are impatient, you can immediately do: -
 
  cd bin
-  make parfactor
-
and see a demonstration for factoring numbers by a Euclidean sieve. -Then try: ./a.out YOUR_NUMBER
-Read bin/Makefile for an example of compiling a `TOP-C' program. -

- -If you want to use more or different slave processes, modify -`bin/procgroup'. -Then, again: -
 
  cd bin
-  ./a.out YOUR_NUMBER
-

- -And compare with your results using a single slave process: -
 
  ./a.out --TOPC-num-slaves=1 YOUR_NUMBER
-
Or investigate what other command-line TOP-C options are available for a.out. -
 
  ./a.out --TOPC-help
-

- -Other TOP-C applications besides parfactor are in the directory -`../examples'. For example, if you would like to try -`parquicksort.c', then from the `bin' directory, try: -
 
  make check TEST_FILE=parquicksort
-

- -When you write your own `TOP-C' application, `app.c', make -sure that it contains #include <topc.h> at the top, and that you -have a procgroup file in the current directory, and then: -
 
  bin/topcc --mpi -o app app.c
-  # or else:  bin/topc++ --mpi -o app app.cc
-  ./app
-
`topcc' is a wrapper for your standard C compiler. It accepts all -the standard compiler command line options, plus a few more. -`topc++' also exists. [NOTE: bin/topcc --help and -bin/topc++ --help both work and `doc/topcc.1' exists ] -

- -This might be a good point to download and print at least the first half -of the manual, or else make it from the doc directory (cd doc; -make pdf; make ps). Note that the table of contents may appear at the -end of the documentation after the index. See A. Summary of `TOP-C' Commands, for a list of the -`TOP-C' commands. See B. Example `TOP-C' Application, for a simple `TOP-C' -example application involving only trivial parallelism. The -`examples' subdirectory provides more detailed examples. -A tutorial is available from the web page, -http://www.ccs.neu.edu/home/gene/topc.html. -

- -Finally, if you want to install `TOP-C' permanently, type -
 
  ./configure                 # Install in /usr/local
-  ./configure --prefix=$HOME  # Install in home directory
-  make install
-

- -This adds a man page, an info file (try info topc), etc. HTML -documentation is available in the `doc' subdirectory of the -`TOP-C' distribution. By default, `TOP-C' will install in -`/usr/local', requiring root privilege. If you configure ---prefix=$HOME, -`TOP-C' will create files in `$HOME/bin', `$HOME/lib', -`$HOME/include', `$HOME/man' and `$HOME/info'. -If you want to make `TOP-C' with cc instead of gcc, type: -
 
  env CC=cc ./configure --cache-file=/dev/null
-
CFLAGS, CXX (for topc++ and -CXXFLAGS can also be set. -For other configuration options, type: -
 
  ./configure --help
-

- -Please write the author, Gene Cooperman (gene@ccs.neu.edu), if -there are any questions. -

- - -


- - - - - - - -
[ << ][ >> ]           [Top][Contents][Index][ ? ]
-
- -This document was generated -by Gene Cooperman on October, 6 2004 -using texi2html - - - - diff --git a/topc-2.5.2/doc/html/topc_3.html b/topc-2.5.2/doc/html/topc_3.html deleted file mode 100644 index 81d934a3..00000000 --- a/topc-2.5.2/doc/html/topc_3.html +++ /dev/null @@ -1,540 +0,0 @@ - - - - - -TOP-C (Task Oriented Parallel C/C++): Overview - - - - - - - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

3. Overview of `TOP-C/C++'

- -

- -
 
                       "Difficulty?" exclaimed Ford. "Difficulty?  What
-                   do you mean difficulty?  [The wheel is] the single
-                   simplest machine in the universe!"  ...
-                       "All right, Mr. Wiseguy,"  she said,  "you're so
-                   clever, you tell us what color it should be."
-                       from "The Restaurant at the End of the Universe"
-                       by Douglas Adams
-

- -`TOP-C' has been designed especially to make it easy to parallelize -existing sequential applications. Toward this goal, -`TOP-C' emphasizes: -

    -
  1. ease of use (high level task-oriented abstraction); -
  2. latency tolerance; and -
  3. architecture independence (same application code for - shared and distributed memory). -
-

- -A `TOP-C' application is compiled and run using topcc -(similarly to gcc) or topc++ (similarly to g++). -For example, assuming a `procgroup' file in the current -directory to specify the remote hosts for the slave processes, -one executes: -
 
  topcc --mpi parfactor.c
-  # or else:  topc++ --mpi parfactor.cc
-  ./a.out
-

- -If a `TOP-C' application fails to link, check for a clash of -symbol names. All TOP-C symbols are of the form -TOPC_*, COMM_*, MEM_*, MPI_*, MPINU_*, NO_ACTION, UPDATE, REDO, CONTINUATION, -or NOTASK. -

- -For purposes of documentation, we will standardize on an explanation of -topcc. Wherever topcc is mentioned, the description is -equally valid for topc++. -

- -

- - - -
3.1 Programmer's Model  
3.2 Three Key Concepts for TOP-C  
3.3 Distributed and Shared Memory Models  
-

- - -


- - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

3.1 Programmer's Model

- -

- -

- - - - -
3.1.1 Structure of a TOP-C Program  
3.1.2 Four Callback Functions  
3.1.3 Task Input and Task Output Buffers  
3.1.4 The `TOP-C' Algorithm  
-

- - -


- - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

3.1.1 Structure of a TOP-C Program

- -

- -A typical TOP-C application has the following structure: -
 
#include <topc.h>
-... define four callback functions for TOPC_master_slave() ...
-int main( int argc, char **argv ) {
-  TOPC_init( &argc, &argv );
-  ...
-  TOPC_master_slave( GenerateTaskInput, DoTask, CheckTaskResult,
-                     UpdateSharedData )
-  ...
-  TOPC_finalize();
-}
-

- -The program above is run with a master process and several slave processes -operating with identical command line arguments and identical initial -data (SPSD, or Single Program, Single Data). Communication among processes -occurs only within the routine TOPC_master_slave(), during which -execution can be called SPMD (Single Program, Multiple Data). At the end -of TOPC_master_slave(), execution returns to SPSD, although the -master process may contain some additional process-private data. -

- -9. `TOP-C' Raw Interface for Parallelizing Sequential Code describes an alternative interface that is -often useful for parallelizing existing sequential code. However, for -new applications, the standard interface will usually be cleaner. -

- - -


- - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

3.1.2 Four Callback Functions

- -

- -In a `TOP-C' application, the programmer defines four callback -functions and passes control to the `TOP-C' library through the -following command. -
 
  TOPC_master_slave(GenerateTaskInput, DoTask, CheckTaskResult,
-                    UpdateSharedData);
-

- -Pictorially, TOP-C arranges for the flow of control among the four callback -functions as follows: -
 
      (ON MASTER)      task input
-   GenerateTaskInput() ---------->
-
-
-  task input   (ON A SLAVE)  task output
-  -----------> DoTask(input) ----------->
-
-
-  task output     (ON MASTER)                    action
-  -----------> CheckTaskResult(input, output) ----------->
-
-
-if (action == UPDATE):
-  task input, task output      (ON ALL PROCESSES)
-  -----------------------> UpdateSharedData(input, output)
-

- - -


- - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

3.1.3 Task Input and Task Output Buffers

- -

- - - -

- -A task input or task output is an arbitrary buffer of bytes -of type (void *) in `TOP-C'. The task buffers are arbitrary -application-defined data structures, which are opaque to `TOP-C'. -Note that in ANSI C, a void pointer is compatible with any other pointer type -(such as (struct task_input *) and (struct task_output *) -in the example below). -

- -

- - - -
Defining Application Task Buffers  
Marshaling (Serialization) and Heterogeneous Architectures  
Marshalgen, a Package for Marshaling  
-

- - - -

Defining Application Task Buffers

- -

- -An application callback function returning a task input or task output -must encapsulate it in a function, TOPC_MSG( void *buf, int -buf_size ), which is then returned by the callback functions -GenerateTaskInput() and DoTask(). TOPC_MSG() -internally allocates a copy of buf, and TOP-C later frees the copy -automatically. So, buf may be reused by the application program. -

- -
 
TOPC_BUF DoTask( struct task_input * inp ) {
-  struct task_output outp;
-  ...
-  outp = ...;
-  return TOPC_MSG( &outp, sizeof(outp) );
-}
-

- -The principle of memory allocation in `TOP-C' is that if an -application allocates memory, then it is the responsibility of the -application to free that memory. TOPC_MSG() has the further -property of copying its buffer argument to a separate `TOP-C' space -(using a shallow copy), after which the application can free any memory it -allocated. This happens automatically in the above example, -since outp is allocated on the stack. -

- - - -

Marshaling (Serialization) and Heterogeneous Architectures

- -

- - - - -

- -If a heterogeneous -architecture is used, there is an issue of converting data formats -or marshaling. -This is the application's responsibility. For simple data formats -(integers, floats or characters), such conversion can easily be done -in an ad hoc manner. Most C compilers use the IEEE binary -floating point standard, and characters are almost always encoded -in eight bit ASCII representation (or possibly in a standard Unicode -format). Although the byte ordering of integers is not standardized, -the system calls htonl() and ntohl() are available -to convert integers into 32 bit network integers that are -portable across heterogeneous systems. -

- -For more complicated conversions, one can consider writing one's own -marshaling routines or else using a standard package for marshaling -such as the `XDR' library (RFC 1832, eXternal Data Representation), -`IDL' (`Corba'), or `SOAP' (`XML'). -

- - - -

Marshalgen, a Package for Marshaling

- -

- -For complex C++ applications, we recommend tat you try out -`Marshalgen' package. A pointer to it is available from the TOP-C -home page. Since the C++ classes to be marshaled are already defined in -`.h' files, Marshalgen asks th user simply to annotate those files -with comments (for example, deep copying vs. shallow copying fo -pointers). `Marshalgen' also has support for such real world -issues as marshalingsubclasses and templates, handling of polymorphism, -etc. The `Marshalgen' preprocessor then generates methods for a -new marshaling class that know how to marshal and unmarshal the original -class. -

- - -

- - -


- - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

3.1.4 The `TOP-C' Algorithm

- -

- -When there is only one slave, -The `TOP-C' algorithm can be summarized by the -following C code. -
 
{ void *input, *output;
-  TOPC_ACTION action;
-  while ( (input = GenerateTaskInput()) != NOTASK ) {
-     do {
-       output = DoTask(input);
-       action = CheckTaskResult(input, output);
-     } while (action == REDO);  /* REDO not useful for only one slave */
-     if (action == UPDATE) then UpdateSharedData(input, output);
-  }
-}
-

- -On a first reading, it is recommended to skip the rest of this -section until having read through Section 4.3 Actions Returned by CheckTaskResult(). -

- -For a better understanding of the case of multiple -slaves, this simplified excerpt from the `TOP-C' source code describes -the `TOP-C' algorithm. -
 
TOPC_BUF input, output;
-int num_idle_slaves = num_slaves;
-TOPC_ACTION action;
-
-while (TRUE) {
-  wait_until_an_idle_slave();
-  input = COMM_generate_task_input();
-  if (input.data != NOTASK.data) {
-    SUBMIT_TO_SLAVE:  output = DoTask(input.data);
-    num_idle_slaves--;
-  }
-  else if (num_idle_slaves < num_slaves) // else insure progress condition
-    receive_task_output();               // by blocking until a slave replies
-  else break;
-} // termination condition:  _after_ all slaves idle, next input was NOTASK
-

- -The code for wait_until_an_idle_slave() can be expanded as follows. -
 
void wait_until_an_idle_slave() {
-  do {
-    while ( result_is_available(&input, &output) ) {
-      action = CheckTaskResult(input.data, output.data);
-      if (action == UPDATE)
-        UpdateSharedData(input.data, output.data);
-      if (action == REDO) /* Use updated shared data, when redoing */
-        SUBMIT_TO_SLAVE:  output = DoTask(input.data);
-      num_idle_slaves++;
-    } while (num_idle_slaves == 0);
-  }
-

- -Note that the term result refers to an `(input,output)' pair. -The routine CheckTaskResult() returns an action, which -determines the -control structure for a parallel algorithm. A common definition is: -

- -
 
TOPC_ACTION CheckTaskResult( void *input, void *output ) {
-  if (output == NULL) return NO_ACTION;
-  else if ( TOPC_is_up_to_date() ) return UPDATE;
-  else return return REDO; }
-

- -TOPC_is_up_to_date() returns true if and only if during the interval -between when the task input was originally generated and when the task -output was returned by the most recent slave, no other slave process had -returned a task output during the interim that had caused the shared data -to be modified through an UPDATE action. An UPDATE action causes -UpdateSharedData() to be invoked on each process. Further -discussion can be found in 4.4 TOP-C Utilities. -

- - -


- - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

3.2 Three Key Concepts for TOP-C

- -

- - - - - - -

- - The `TOP-C' programmer's model is based on three key concepts: -

    -
  1. - tasks in the context of a master/slave architecture; -
  2. - global shared data with lazy updates; and -
  3. - actions to be taken after each task. -
-

- -Task descriptions (task inputs) are generated on the master, and assigned to -a slave. The slave executes the task and returns the result to the master. -The master may update its own private data based on the result, or it may -update data on all processes. Such global updates take place on each slave -after the slave completes its current task. Updates are lazy in -that they occur only after a task completes, although it is possible to -issue a non-binding request to `TOP-C' to abort the current tasks -(8.2 Aborting Tasks). -A SPMD (Single Program Multiple -Data) style of programming is encouraged. -

- -In both shared and distributed memory architectures, one must worry -about the order of reads and writes as multiple slaves autonomously -update data. The utilities below are meant to ease that chore, by -supporting the ease of the SPMD programming style, while still -maintaining good efficiency and generality for a broad range of -applications. The software can easily be ported to a variety of -architectures. -

- - -


- - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

3.3 Distributed and Shared Memory Models

- -

- - - - -

- -`TOP-C' provides a single API to support three primary memory -models: distributed memory, shared memory and -sequential memory. (The last model, sequential memory, refers to -a single sequential, non-parallel process.) On a first reading, one -should think primarily of the distributed memory model (distributed -nodes, each with its own private memory). Most programs written for -distributed memory will compile without change for sequential memory. -`TOP-C' is designed so that the same application source code may -operate efficiently both under distributed and under shared memory. In -order to also compile for shared memory hardware (such as SMP), -additional hints to `TOP-C' may be necessary. -

- -In shared memory architectures, all data outside of the four -callback functions is shared, by default. Hence, an UPDATE -action under shared memory causes only the master process to invoke -UpdateSharedData(). To avoid inconsistencies in the data, by -default `TOP-C' arranges that no slave process may run -DoTask() while UpdateSharedData() is running. -`TOP-C' also provides support for finer levels of granularity -through application-defined private variables and critical sections. -Further discussion can be found in 8.4 Optimizing TOP-C Code for the Shared Memory Model. -

- - -


- - - - - - - -
[ << ][ >> ]           [Top][Contents][Index][ ? ]
-
- -This document was generated -by Gene Cooperman on October, 6 2004 -using texi2html - - - - diff --git a/topc-2.5.2/doc/html/topc_4.html b/topc-2.5.2/doc/html/topc_4.html deleted file mode 100644 index fbd4130b..00000000 --- a/topc-2.5.2/doc/html/topc_4.html +++ /dev/null @@ -1,402 +0,0 @@ - - - - - -TOP-C (Task Oriented Parallel C/C++): Writing TOP-C Applications - - - - - - - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

4. Writing `TOP-C' Applications

- -

- -This chapter assumes a knowledge of the basic concepts in -3. Overview of `TOP-C/C++'. In particular, recall 3.1.1 Structure of a TOP-C Program. -

- -

- - - - -
4.1 The Main TOP-C Library Calls  
4.2 Callback Functions for TOPC_master_slave()  
4.3 Actions Returned by CheckTaskResult()  
4.4 TOP-C Utilities  
-

- - -


- - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

4.1 The Main TOP-C Library Calls

- -

- - - - - - -

- -Every `TOP-C' application must include a `topc.h' header, open -with TOPC_init(), call TOPC_master_slave() one or more -times, and then close with TOPC_finalize(). -

- -
 
#include <topc.h>
-      Required at head of any file using TOPC library calls.
-
-

-
Function: void TOPC_init ( int *argc, char ***argv ) -
Required before first occurrence of TOPC_master_slave(); - Recommended to place this as first executable statement in - main(). It will strip off extra `TOP-C' and - communication layer arguments such as `--TOPC-stats', - which are added by `TOP-C'. -
- -
-
Function: void TOPC_finalize ( void ) -
Placed after last `TOP-C' command. -
- -
-
Function: void TOPC_master_slave -
( TOPC_BUF (*generate_task_input)(),
   TOPC_BUF (*do_task)(void *input),
   TOPC_ACTION (*check_task_result)(void *input, void *output),
   void (*update_shared_data)(void *input, void *output) -
) -
Primary call, passed four application callbacks to `TOP-C'. - One can have multiple calls to - TOPC_master_slave(), each invoking different callback functions, - between TOPC_init() - and TOPC_finalize(). -
-

- -A task input or task output is simply a buffer of bytes, specified by -TOPC_MSG(). -

- - -

-
Function: TOPC_BUF TOPC_MSG ( void *buf, int buf_size ) -
Must be returned by GenerateTaskInput() and DoTask(). - Specifies arbitrary user data structure. - `TOP-C' will make a copy of buf in `TOP-C' space. - It remains the responsibility of the application to free or - reuse the space of the original buffer buf. If - TOPC_MSG(NULL, 0) is called, a NULL pointer will be - received at the destination. - (See section 8.3.2 Using TOPC_MSG_PTR() to Avoid Copying Large Buffers, for TOPC_MSG_PTR, - to avoid copying very large buffers, where the overhead is - unacceptable.) -
-

- -EXAMPLE: -
 
    TOPC_BUF convert_string_to_msg( char *mystring ) {
-        if (mystring == NULL) return TOPC_MSG(NULL,0);
-        else return TOPC_MSG(mystring, strlen(mystring)+1);
-    }
-

- - -


- - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

4.2 Callback Functions for TOPC_master_slave()

- -

- -The application writer must define the following four callback functions -(although the last can be NULL). The callback terminology -is based on C concepts. In a more object-oriented style, one would -view user callbacks as instantiation of abstract methods in a -user-defined subclass. The first two functions return a -TOPC_BUF, which is produced by TOPC_MSG(). - -

-
Function: TOPC_BUF GenerateTaskInput ( void ) -
executes on master; returns a data structure specified by - TOPC_MSG(buf, buf_size). - It should return NOTASK, when there are no more tasks, and it - should be prepared to return NOTASK again if invoked again. -
- -
-
Function: TOPC_BUF DoTask ( void *input ) -
executes on slave; operates on the result of GenerateTaskInput(); - returns a data structure specified by - TOPC_MSG(buf, buf_size). - buf must be a static or global user buffer. -
- -
-
Function: TOPC_ACTION CheckTaskResult ( void *input, void *output) -
executes on master; operates on the result of DoTask(); - returns an ACTION that determines what happens to the task next. - The terminology result refers to an `(input, output)' pair. - An easy way to write CheckTaskResult() appears in the - example for the utility TOPC_is_up_to_date(). - When returning the action UPDATE, it works to first modify - the input and output buffers. UpdateSharedData() will - then be invoked with the modified buffers. - See 4.4 TOP-C Utilities, for more details. -
- -
-
Function: void UpdateSharedData ( void *input, void *output ) -
executes on master and all slaves; operates on the result of - DoTask(), and the original task returned by - GenerateTaskInput(); - called only if CheckTaskResult() returned UPDATE; - useful for updating global variables in all processes; - The pointer argument, update_shared_data, of - TOPC_master_slave() may be NULL if - an application never requests an UPDATE action. - In a shared memory environment, only the master calls - UpdateSharedData(). See 8.4 Optimizing TOP-C Code for the Shared Memory Model, for more details. -
-

- -Note that in defining the above callback functions, C allows one to -replace the (void *) declaration of the arguments by specific -pointer types. Note that the buffers of any message parameters -(input and output) of DoTask() or -CheckTaskResult() are part of TOP-C space. Such buffers may be -freed by TOP-C on exit from the callback function. An application -wishing to use the buffer after the callback exits must explicitly save -a copy into the application's own space. -

- - -


- - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

4.3 Actions Returned by CheckTaskResult()

- -

- - -

- -A TOP-C result is an (input, output) pair corresponding -to an invocation of DoTask(). `TOP-C' passes the result to -CheckTaskResult(). The return value allows the application to -tell `TOP-C' what further actions to take. -The actions returned by CheckTaskResult() are: - -

-
Action: TOPC_ACTION NO_ACTION -
C constant, causing no further action for task -
- -
-
Action: TOPC_ACTION UPDATE -
C constant, invoking UpdateSharedData( void *input, - void *output) (see below) - also updates bookkeeping for sake of TOPC_is_up_to_date() - (see section 4.4 TOP-C Utilities) -
- -
-
Action: TOPC_ACTION REDO -
Invoke DoTask() on original task input again, and on - the same slave that previously executed the task; useful if - shared data has changed since original - invocation of DoTask() (see TOPC_is_up_to_date(), - below). See 7.2 Strategies for Greater Concurrency, - for slave strategies to efficiently process a REDO action. -
- -
-
Action: TOPC_ACTION CONTINUATION ( void *next_input ) -
CONTINUATION(next_input) is a parametrized action that - may be returned by CheckTaskResult(), after which - DoTask( next_input ) is called on the original slave. - This is useful if only the master can decide whether task is complete, - or if the master wishes to supply additional input messages - needed for the task. - Note that REDO is essentially equivalent to - CONTINUATION( original_task_input ). - Note that any pending calls to UpdateSharedData() will have - occurred on the slave before the new call to DoTask(). - Hence, this allows an extended conversation between master and - slave, in which the slave continues to receive updates of the - shared data before each new input from the master. - Note also that even though a CONTINUATION action returns - to the original slave, any previous pointers to input buffers - on that slave - (and pointers to output buffers from intervening UPDATE - actions) will no longer be valid. Useful data from previous buffers - should have been copied into global variables on the slave. - In the case of the shared memory model, those global variables must be - thread-private. (see section 8.4.2 Thread-Private Global Variables) -
-

- -It is possible for CheckTaskResult(input, output) to -modify the buffer data in its two arguments, input and output, -in which case the modifications will be visible to any further -callback functions processing the current task. This practice makes -the code more difficult to maintain, and is not recommended when other -solutions are available. -

- - -


- - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

4.4 TOP-C Utilities

- -

- -`TOP-C' also defines some utilities. - -

-
Function: TOPC_BOOL TOPC_is_up_to_date ( void ) -
returns TRUE or FALSE (1 or 0); returns TRUE if and only if - CheckTaskResult() - has not returned the result UPDATE (invoking - UpdateSharedData()) - between the time when GenerateTaskInput() was originally - called on the - current task, and the time when the corresponding - CheckTaskResult() - was called. - Typical usage: -
 
          TOPC_ACTION CheckTaskResult( void *input, void *output )
-          { if (input == NULL) return NO_ACTION;
-            else if (TOPC_is_up_to_date()) return UPDATE;
-            else return REDO;
-          } 
- -
-
Function: int TOPC_rank ( void ) -
Unique ID of process or thread. Master always has rank 0. - Slaves have contiguous ranks, beginning at 1. -
- -
-
Function: TOPC_BOOL TOPC_is_master ( void ) -
Returns boolean, 0 or 1, depending on if this is master. - Equivalent to TOPC_rank() == 0. -
- -
-
Function: int TOPC_num_slaves ( void ) -
Total number of slaves. -
- -
-
Function: int TOPC_num_idle_slaves ( void ) -
Total number of idle slaves (not doing task, update or other action). -
- -
-
Function: int TOPC_node_count ( void ) -
Total number of processes or threads. Equivalent to - TOPC_num_slaves() + 1. -
-

- - -

-
Function: TOPC_BOOL TOPC_is_REDO ( void ) -
-
Function: TOPC_BOOL TOPC_is_CONTINUATION ( void ) -
-
Function: void TOPC_abort_tasks ( void ) -
-
Function: TOPC_BOOL TOPC_is_abort_pending ( void ) -
See 8. Advanced Features of `TOP-C' for descriptions. -
-

- - -


- - - - - - - -
[ << ][ >> ]           [Top][Contents][Index][ ? ]
-
- -This document was generated -by Gene Cooperman on October, 6 2004 -using texi2html - - - - diff --git a/topc-2.5.2/doc/html/topc_5.html b/topc-2.5.2/doc/html/topc_5.html deleted file mode 100644 index f5dd3559..00000000 --- a/topc-2.5.2/doc/html/topc_5.html +++ /dev/null @@ -1,609 +0,0 @@ - - - - - -TOP-C (Task Oriented Parallel C/C++): Compiling and Invoking TOP-C Applications - - - - - - - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

5. Compiling and Invoking `TOP-C' Applications

- -

- -A `TOP-C' application can be compiled once, and then linked to your -choice of a run-time library for either a sequential, distributed memory -or shared memory architecture. The two shell scripts `bin/topcc' -and `bin/topc++' are used instead of `gcc' and `g++' (or -other C/C++ compilers). -

- -

- - - - - -
5.1 Compiling TOP-C Applications  
5.2 Command Line Options in TOP-C Applications  
5.3 Invoking a TOP-C Application in Sequential Memory  
5.4 Invoking a TOP-C Application in Distributed Memory  
5.5 Invoking a TOP-C Application in Shared Memory  
-

- - -


- - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

5.1 Compiling TOP-C Applications

- -

- - - - -

- -The TOP-C application file must contain -
 
    #include <topc.h>
-
It must make calls to -
 
    TOPC_init(...);
-    TOPC_master_slave(...);
-    TOPC_finalize();
-
as describe in 3.1.1 Structure of a TOP-C Program. The -application file is compiled by one of: -
 
    topcc --seq myfile.c
-    topcc --mpi myfile.c
-    topcc --pthread myfile.c
-
according to whether the target computer architecture will be sequential -(`--seq': single processor), distributed memory (`--mpi': -networked CPU's), or shared memory (`--pthread': SMP or other -shared memory architecture with a POSIX threads interface). -topcc is a substitute for cc or gcc, -and creates an `a.out' file. -(Similarly, topc++ exists as a substitute for c++ or -g++.) -There are man files, -
 
    `doc/topcc.1',   `doc,topc++.1'
-
with further information on topcc and topc++. -If installed, man topcc and man topc++ exist. -

- -The same object file may be relinked to use different `TOP-C' memory -models without recompiling the object file. -
 
    topcc -c myapp.c
-    topcc --seq -o myapp-seq myapp.o
-    topcc --mpi -o myapp-mpi myapp.o
-

- -For large applications, it may be preferable to directly invoke -the `TOP-C' libraries and include files. For such -situations, topc-config exists. The following -is exactly equivalent to topcc --mpi myfile.c -(assuming you configured `TOP-C' using gcc). -
 
    gcc `topc-config --cflags` --mpi myfile.c `topc-config --libs`
-
Type topc-config with no arguments for a full set of -command line options. -

- -For the rest of this chapter, we standardize our description for -topcc. However, topc++ is equally valid wherever -topcc is mentioned. -

- - -


- - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

5.2 Command Line Options in TOP-C Applications

- -

- - - - - - - - - - - - - - - - - - - -

- -TOP-C searches for TOP-C parameters in the following locations, in order: -

    -
  1. values of variables TOPC_OPT_xxx in the application code - before TOPC_init() -
  2. the file `.topcrc' in the home directory -
  3. the environment variable TOPC_OPTS -
  4. arguments on the command line in the form --TOPC-xxx -
-The file `.topcrc' and the environment variable TOPC_OPTS -specify parameters -in the same format as on the command line. Later assignments of an -option override earlier assignments. -

- -For a brief synopsis of application command line options, type: -
 
    topcc myapp.c
-    ./a.out --TOPC-help
-    [ OR FOR MORE INFORMATION:  ./a.out --TOPC-help --TOPC-verbose  ]
-

- -Currently, this will display the following. -
 
Usage:  ./a.out [TOPC_OPTION ...] [OTHER_OPTIONS ...]
-
-  where TOPC_OPTION is one of:
---TOPC-help[=<0/1>]        display this message   [default: false]
---TOPC-stats[=<0/1>]       print stats before & after [default: false]
---TOPC-verbose[=<0/1>]     set verbose mode       [default: false]
---TOPC-num-slaves=<int>    number of slaves (sys-defined default) 
-                                                   [default: -1]
---TOPC-aggregated-tasks=<int> number of tasks to aggregate 
-                                                   [default: 1]
---TOPC-slave-wait=<int>    secs before slave starts (use w/ gdb attach)
-                                                   [default: 0]
---TOPC-slave-timeout=<int> dist mem: secs to die if no msgs, 0=never
-                                                   [default: 1800]
---TOPC-trace=<int>         trace (0: notrace, 1: trace, 2: user trace fncs.) 
-                                                   [default: 2]
---TOPC-procgroup=<string>  procgroup file (--mpi)
-                                                   [default: "./procgroup"]
---TOPC-topc-log=<string>   NOT IMPL: log file for TOPC output ("-" = stdout) 
-                                                   [default: "-"]
---TOPC-safety=<int>        [0..20]: higher turns off optimizations,
-                         (try with --TOPC-verbose) [default: 0]
-

- -For each option, `--TOPC-PARAM', there is a corresponding -C/C++ variable, TOPC_OPT_PARAM. This variable is of type -int or (char *). If the application program sets the value -before a call to TOPC_init(), these variables will act as -defaults. For example, to turn off tracing by default, write: -
 
int main( int argc, char *argv[] ) {
-  TOPC_OPT_trace = 0;
-  TOPC_init( &argc, &argv );
-  ...
-}
-

- -The option `--TOPC-trace' causes the task input and task output -to be traced and printed as they are passed across the network. The action of -a task is also printed. If an application is called with -`--TOPC-trace=2' (default) and if the variables -TOPC_OPT_trace_input and TOPC_OPT_trace_result are set -to pointers to -functions then those functions are called, and they may print additional -information. -TOPC_OPT_trace_input must be set to a function of one -variable: void * input. -TOPC_OPT_trace_result must be set to a function of two -variables: void * input, void * output. -When using C++, the function pointers must be cast to -TOPC_trace_input_ptr or TOPC_trace_result_ptr -before being assigned to TOPC_OPT_trace_input or -TOPC_OPT_trace_result, respectively. -For an example, see `examples/parfactor.c' in the TOP-C distribution. -

- -The option `--TOPC-stats' prints statistics (running times, -etc.) and -information about the conditions of an invocation of a TOP-C application -before and after a run. -The option `--TOPC-verbose' (set by default) displays TOP-C -warnings. With --TOPC-help, it provides additional information. -

- -For the usage of `--TOPC-procgroup', -see 5.4 Invoking a TOP-C Application in Distributed Memory. -That section also explains on what hosts the slaves run -when `--TOPC-num-slaves' indicates a different number of -slaves than the `procgroup' file. -

- -For the usage of `--TOPC-aggregated-tasks', -see 7.3 Improving Performance. -For the usage of `--TOPC-slave-wait', see -6.5 Stepping Through a Slave Process with `gdb'. -For the usage of `--TOPC-safety', see -5.2 Command Line Options in TOP-C Applications. -For the usage of the other options, see the Concept Index. -

- -`TOP-C' recognizes -- as terminating all option processing, -according to standard UNIX conventions. -

- - -


- - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

5.3 Invoking a TOP-C Application in Sequential Memory

- -

- - - - -

- -For example, -
 
    topcc --seq -g -O0 myfile.c
-
compiles a sequential version for debugging using gdb -(see section `Summary' in The GNU debugger), for example. -This is usually a first step in debugging a TOP-C application, since -sequential debugging is easier than parallel debugging. -

- - -


- - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

5.4 Invoking a TOP-C Application in Distributed Memory

- -

- - - - -

- -Linking using the `--mpi' option (default) allows an application to -execute using a distributed memory model of networked processors. The -`TOP-C' distribution includes a subset MPI(1) -implementation `MPINU', sufficient to run `TOP-C' -applications. -
 
  topcc --mpi myapp.c
-  ./a.out
-
The application must then create the remote slave processes at runtime. -If you use `MPINU' (the default configuration of `TOP-C', -then the remote slave processes are specified by a `procgroup' file. -Otherwise, the startup mechanism depends on your `MPI' implementation. -

- -

- - -
5.4.1 Writing Procgroup Files for `MPINU'  
5.4.2 If Slaves Fail to Start  
-

- - -


- - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

5.4.1 Writing Procgroup Files for `MPINU'

- -

- - - - - - -

- -`MPINU' is built into the default configuration of the -`TOP-C' library and uses the `procgroup' mechanism to specify -slave processes. (If you prefer to use a different `MPI' dialect, -`TOP-C' will work, but `src/Makefile.in' must be modified, -and that `MPI' dialect may use a different mechanism for -introducing slave processes.) -

- -When the application binary is executed under the default, it looks at -the current directory for a file, -
 
    `procgroup'
-
The procgroup file determines the number and location of the slave -processes. The procgroup file need only be visible from the -master process. If one prefers, one can specify an alternate -procgroup file via the syntax as in the following example: -
 
    ./a.out --TOPC-procgroup=../myprocgroup.big
-

- -The `TOP-C' distribution includes a file `bin/procgroup' as an -example of the procgroup format. -The file must contain a line: -
 
    local 0
-
for the master process. It must also contain a line for each slave -process in one of the following forms: -
 
    hostname 1 full_pathname
-    hostname 1 -
-    hostname 1 ./relative_pathname
-    hostname 1 ../relative_pathname
-
where hostname is the remote host. -The pathname - means to use the same pathname for the slave -on the remote host as for the master on the current host. -A relative pathname, such as ./a.out or ../new_arch/a.out, -specifies a pathname relative to the pathname of the binary of -the master on the current host. -

- -Most of the time, it is simplest to just include a full pathname -or else - in the `procgroup' file. The relative pathnames are -useful for a shared filesystem with binaries compiled for -different architectures. For example, the procgroup file might include -relative paths `../sparc/a.out', `../alpha/a.out' and -`../linux/a.out'. -If you invoke `full_path/sparc/a.out', this will yield a master -running `full_path/sparc/a.out' and three slaves running -each of the three architectures. -

- -The full principles are as follows. -Let SLAVE_PATH be the path of the slave as given in the procgroup file, -and let MASTER_DIR be the directory of the master process as invoked on -on the command line. -
 
SLAVE_PATH absolute:
-  slave binary image is SLAVE_PATH
-SLAVE_PATH relative and MASTER_DIR absolute:
-  slave binary image is MASTER_DIR/SLAVE_PATH
-SLAVE_PATH relative and MASTER_DIR relative:
-  slave binary image is $PWD/MASTER_DIR/SLAVE_PATH
-SLAVE_PATH is - and master process invoked on command line as MASTER_BIN:
-  slave binary image is MASTER_BIN  (if MASTER_BIN is absolute path)
-  or $PWD/MASTER_BIN (if MASTER_BIN is relative path)
-If the procgroup line contains command line arguments,
-  those command line arguments are passed to the slave application
-  as its first arguments, and any arguments on the master command
-  line are appended to the list of arguments.
-
TOP-C assumes that your -application does not change the working directory before -calling TOPC_init(). -

- -By default, `TOP-C' uses the procgroup file in the current directory. -You can choose an explicit procgroup file via a program -variable, TOPC_OPT_procgroup="/project/myprocgroup";, or via a -command-line option, -/project/sparc/app --TOPC-procgroup=/project/myprocgroup. -See section 5.2 Command Line Options in TOP-C Applications. -

- -If the command line option `--TOPC-num-slaves=int' -is given, and if int is less than the number of -slaves in the `procgroup' file, then `TOP-C' will -use the first int slaves from the file. If int -is more than the number of slaves in the `procgroup' file, -then `TOP-C' will use all of the given slaves, and then -create additional processes on the remote hosts, by -returning to the beginning of the `procgroup' file and -re-reading the list of slave host/binaries until int -slaves have been created in all. -

- -It is recommended to use only localhost during initial -development. -

- - -

- -The environment variable, SSH (default value ssh) is used to -invoke the remote host. If, for example, your site uses rsh -instead of ssh, the following code, when executed -before TOPC_init() will produce this effect. -
 
  putenv("SSH=rsh");
-
Alternatively, type SSH=rsh (sh/bash, etc.) or -setenv SSH rsh -(csh/tcsh, etc.) in the UNIX shell before invoking the TOP-C application. -

- - -


- - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

5.4.2 If Slaves Fail to Start

- -

- - - - - - -

- -If some slave processes start, but not others, then try executing -the following simple program. -
 
#include "topc.h"
-int main(int argc, char *argv) {
-  char host[100];
-  printf("%s connecting ...\n", gethostname(host, 99));
-  TOPC_init(&argc, &argv);
-  printf("... %s connected.\n", gethostname(host, 99));
-  TOPC_finalize();
-}
-

- -If the slave processes fail to start up or fail to respond to the master -and if you are using `MPINU' (default configuration of `TOP-C', - one other debugging resource is available. -If an application fails to start up, then `TOP-C' leaves in -the `/tmp' directory a file -
 
    `/tmp/mpinu-ssh.$$'
-
where $$ is the process id. The file shows the commands that -`TOP-C/mpinu' tried to use to start up the slave process. By -examining and even manually executing those commands from the terminal, -one can often deduce the difficulty in creating the slave processes. -

- -Test the ability of your computer facility to execute remote processes -without passwords by typing: ssh REMOTE_HOST pwd. -If the problem is that ssh is not working, try setting -the environment variable SSH to ssh or other site-specific -setting. -See section 5.4.1 Writing Procgroup Files for `MPINU'. -

- -If you are using ssh (default if the environment variable -SSH is not set), and if it requires a password then the following -commands within UNIX may allow ssh to operate on your local cluster -without passwords. -
 
ssh-keygen -t dsa       [accept default values]
-ssh-keygen -t rsa       [accept default values]
-cat ~/.ssh/id*.pub >> ~/.ssh/authorized_keys
-
For security, be sure that ~/.ssh has no read permission for other users. -

- - -


- - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

5.5 Invoking a TOP-C Application in Shared Memory

- -

- - - - -

- -Linking using the `--pthread' option allows an -application to execute using POSIX threads. -Note that the `TOP-C' memory model for shared memory has some small -variations from the distributed memory model. -The largest potential -source of incompatibility is if your DoTask() routine modifies -any global or static variables. If so, such variables will -need to be declared thread private. -Check your source code to see if this -affects you. -

- -Second, if you encounter insufficient performance, you may consider -experimenting with fine grain thread parallelism. The default -`TOP-C' algorithm for shared memory allows UpdateSharedData() -to begin executing only after each current invocation of DoTask() -completes. This can be modified by an application for -finer grain parallelism. See section Optimizing TOP-C Code for the Shared Memory Model, for details in either of the above cases. -

- -Note also that while a `TOP-C' application object file can usually be -linked using an arbitrary `TOP-C' memory model without recompiling, -there are some circumstances where you may first need to recompile the -application source using topcc --pthread. -

- - -


- - - - - - - -
[ << ][ >> ]           [Top][Contents][Index][ ? ]
-
- -This document was generated -by Gene Cooperman on October, 6 2004 -using texi2html - - - - diff --git a/topc-2.5.2/doc/html/topc_6.html b/topc-2.5.2/doc/html/topc_6.html deleted file mode 100644 index c5d7bd2c..00000000 --- a/topc-2.5.2/doc/html/topc_6.html +++ /dev/null @@ -1,420 +0,0 @@ - - - - - -TOP-C (Task Oriented Parallel C/C++): Debugging and Tracing - - - - - - - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

6. Debugging and Tracing

- -

- - - -

- -If the difficulty is that the application fails to start in the distributed -memory model (using topcc --mpi), then read -5.4.2 If Slaves Fail to Start, for some -debugging techniques. Note also that TOP-C ignores SIGPIPE. This is -because TOP-C employs the SO_KEEPALIVE option, and the master process -would otherwise die if a slave process were to die. SO_KEEPALIVE -is needed for robustness when slave processes execute long tasks without -communicating with the master process. -The rest of this section assumes that the -application starts up correctly. -

- -

- - - - - - -
6.1 Debugging by Limiting the Parallelism  
6.2 Debugging with `--TOPC-safety'  
6.3 TOP-C and POSIX signals  
6.4 Tracing Messages  
6.5 Stepping Through a Slave Process with `gdb'  
6.6 Segmentation faults and other memory problems  
-

- - -


- - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

6.1 Debugging by Limiting the Parallelism

- -

- -First, compile and link your code -using topcc --seq --TOPC-safety=20 -g -O0, -and make sure that your application works correctly sequentially. Only after -you have confidence in the correctness of the sequential code, should you -begin to debug the parallel version. -

- -If the application works correctly in sequential mode, one should debug -in the context of a single slave. It is convenient to declare the -remote slave to be localhost in the `procgroup' file, in order -to minimize network delays and so as not to disturb users of -other machines. In this case, the code is "almost" -sequential. An easy way to do this is: -
 
  topcc --mpi --TOPC-num-slaves=1 -g -O0
-

- -Next, one should test on two slaves, and finally all possible slaves. -

- - -


- - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

6.2 Debugging with `--TOPC-safety'

- -

- - - -

- -The command-line option `--TOPC-safety=val' provides assistance -for debugging parallel programs. At higher values of val, -optimizations that do not change the correctness of the program are -converted to safer equivalents. A good strategy is to -test if `--TOPC-safety=20' causes the bug to go away, and if so, -progressively lower val toward zero, until the bug reappears. -The value at which the bug reappears indicates what `TOP-C' -optimization feature is not being used correctly. If the bug still -exists at `--TOPC-safety=20', one should next try compiling -with the `--seq' flag and use a debugger to debug the sequential code. -

- -The effects due to different safety levels are subject to change. -To see the current effects, invoke any TOP-C application as follows -
 
  ./a.out --TOPC-help --TOPC-verbose
-
and you will see something like: -
 
  safety: >=0: all; >=2: no TOP-C memory mgr (uses malloc/free);
-  >=4: no TOPC_MSG_PTR; >=8: no aggreg.;
-  >=12: no TOPC_abort_tasks; >=14: no receive thread on slave;
-  >=16: default atomic read/write for DoTask, UpdateSharedData;
-   =19: only 2 slaves; >=20: only 1 slave
-  (AGGREGATION NOT YET IMPLEMENTED)
-

- -Values higher than 4 cause TOPC_MSG_PTR() to act as -if TOPC_MSG() was called instead. -Values higher than 12 cause TOPC_abort_tasks() to have no effect. -Values higher than 14 imply that a single thread in the slave process -must receive messages and execute DoTask(). Normally, -`TOP-C' arranges to overlap communication and computation on the -slave by setting up a separate thread to receive and store messages from -the master. -Values higher than 15 imply that `TOP-C' will use malloc instead -of trying to do its -own memory allocation (which is optimized for `TOP-C' memory -patterns). -Values higher than 16 imply that all of DoTask acts as -if a read lock was placed around it, and all of UpdateSharedData -has a write lock placed aound it. (This has an effect only -in the shared memory model where calls to TOPC_ATOMIC_READ/WRITE -are ignored.) -At values of 19 and 20, the number of slaves is reduced to -2 and to 1, regardless of the setting of `--TOPC-num-slaves' -and the specification in a `procgroup' file. -

- - -


- - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

6.3 TOP-C and POSIX signals

- -

- -If an application handles its own signals, this can create a clash -with the TOP-C. -In the distributed memory model (--mpi), `TOP-C' will create its own -signal handlers for SIGALRM. This is used in conjunction with -alarm() to eventually kill runaway -slave processes. In addition, if using `MPINU', -the built-in MPI subset, `TOP-C' will create its own handler -for SIGPIPE. This is in order to allow the master -process to detect dead sockets, indicating dead slaves. -Finally, for short periods, `MPINU' -will disable the use of SIGINT around calls to select(). -Nevertheless, if a SIGINT is sent during this period, TOP-C will pass the -signal on to the original SIGINT handler of the application. -

- -`TOP-C' does not modify signal handlers in the sequential (--seq) -or shared memory (--pthread) models. Furthermore, if a different -MPI (other than MPINU) is used with TOP-C, TOP-C will only handle -SIGALRM. However, the other MPI may handle signals itself. -See section C. Using a Different `MPI' with TOP-C. -

- - -


- - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

6.4 Tracing Messages

- -

- - - - -

- -If a bug appears as one moves to greater parallelism, one should trace -messages between master and slaves (for any number of slaves). -This is the default, and it can be enabled on the command line with: -
 
  ./a.out --TOPC-trace=2 args
-
The variable TOPC_OPT_trace can be set in the code to -dynamically turn tracing on (1 or 2) and off (0) during a single run. -A trace value of 2 causes `TOP-C' to invoke the application-defined -trace functions pointed to by -TOPC_OPT_trace_input/result. If the application has not -defined trace functions, or if TOPC_OPT_trace is 1, then -the `TOP-C' default trace functions are invoked. -All message traces -are displayed by the master at the time that the master sends or -receives the corresponding message. -

- - -

-
Variable: void (*)(void *input) TOPC_OPT_trace_input -
-
Variable: void (*)(void *input, void *output) TOPC_OPT_trace_result -
Global pointer (default is NULL) to function returning - void. User can - set it to his or her own trace function to print out - data-specific tracing information in addition to generic - message tracing of TOPC_trace. -
-
 
EXAMPLE:  if you pass integers via TOPC_MSG(), define
-  TOPC_trace_input() as:
-         void mytrace_input( int *input ) {
-           printf("%d",*input);
-         }
-         TOPC_OPT_trace_input = mytrace_input;
-

- -Note that the term `result' in TOPC_OPT_trace_result -refers to an `(input, output)' pair. -

- - -


- - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

6.5 Stepping Through a Slave Process with `gdb'

- -

- - -

- -If you find the master hanging, waiting for a slave message, then the -probable cause is that DoTask() is doing something bad (hanging, -infinite loop, bus/segmentation error, etc.). First try to isolate the -bug using a symbolic debugger (e.g. `gdb') and the sequential memory -model. If your intended application is the shared memory model, you can also -use `gdb' to set a breakpoint in your `DoTask' routine -or at the `TOP-C' invocation, do_task_wrapper. -

- -If the bug only appears in the distributed memory model, you can still -symbolically debug DoTask() using `gdb' (the GNU C debugger) -and its attach command -(see section `Attach' in The GNU debugger), -which allows you to attach and debug a separate running process. This -lets you debug a running slave, if it is running o the same processor. -For this strategy, you will want the slave to delay executing to give -you time to execute gdb and attach on the remote host or remote thread. -The command line option `--TOPC-slave-wait=30' will force -the slave to wait 30 seconds before processing. -

- -In applying this debugging strategy to an application `./a.out', -one might see: -
 
  [ Execute ./a.out in one window for master process ]
-  gdb ./a.out
-  (gdb) run --TOPC-trace=1 --TOPC-safety=19 --TOPC-slave-wait=30 args
-
-  [ In a second window for a slave process on a different host, now type: ]
-  ps
-    ...
-    1492  p4 S    0:00 a.out args localhost 6262 -p4amslave
-  gdb a.out
-  ...
-  (gdb) break do_task_wrapper
-    Breakpoint 1 at 0x80492ab: file ...
-    [ `break slave_loop' is also useful.  This calls do_task_wrapper ]
-  (gdb) attach 1492
-    Attaching to program `a.out', process 1492
-    0x40075d88 in sigsuspend ()
-  [ After 30 sec's, traced messages in master window appear, ]
-  [ for slave, type: ]
-  (gdb) continue
-    Continuing.
-    Breakpoint 1, DoTask (input=0x805dc50) at ...
-
-  [ Continue stepping through master and slave processes in 2 windows ]
-

- -If you try to attach to a second slave process after attaching -to a first slave process, `gdb' will offer to kill your first -slave process. To avoid this situation, remember to execute detach -before attaching a second slave process. -

- - -


- - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

6.6 Segmentation faults and other memory problems

- -

- - - - - -

- -Memory bugs are among the most difficult to debug. -If you suspect such a bug (perhaps because you are using TOPC_MSG_PTR), -and you fail to free previously malloc'ed memory, that is a memory leak. -If you access a buffer after freeing it, this may cause -a segmentation error at a later stage in the program. -

- -If you suspect such a bug (and maybe you should if nothing else -worked), it is helpful to use a malloc or memory debugger. -An excellent recent memory debugger is -`valgrind'(2). -`valgrind' can be directly applied to an application binary, -without recompilation or relinking. -

- -An older debugger is `efence',(3) -topcc -provides direct support for `efence'. -`TOP-C' will link with the efence library if --efence -is passed to topcc or topc++. -
 
  topcc --efence ...
-
This causes all calls to malloc and free to -be intercepted by the `efence' version. -Modify the line LIBMALLOC= in topcc or topc++ -if you use a different library. -

- - -


- - - - - - - -
[ << ][ >> ]           [Top][Contents][Index][ ? ]
-
- -This document was generated -by Gene Cooperman on October, 6 2004 -using texi2html - - - - diff --git a/topc-2.5.2/doc/html/topc_7.html b/topc-2.5.2/doc/html/topc_7.html deleted file mode 100644 index c4f47b28..00000000 --- a/topc-2.5.2/doc/html/topc_7.html +++ /dev/null @@ -1,314 +0,0 @@ - - - - - -TOP-C (Task Oriented Parallel C/C++): Performance and Long Jobs - - - - - - - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

7. Performance and Long Jobs

- -

- -

- - - - -
7.1 Dropping Slow or Dead Slaves  
7.2 Strategies for Greater Concurrency  
7.3 Improving Performance  
7.4 Long Jobs and Courtesy to Others  
-

- - -


- - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

7.1 Dropping Slow or Dead Slaves

- -

- -When TOP-C recognizes a dead slave the master terminates communication with -that slave, and resubmits the task of that slave to a different slave. -(Currently, as of TOP-C 2.5.0, if a slave dies near the end of a computation -and after all tasks have been generated, TOP-C may fail to recognize -that slave.) -

- -It is sometimes unclear whether a slave process is dead or slower than -others. Even a slow slave process may hurt overall performance by -causing delays for other processes. -TOP-C internally declares a slave process to be "slow" if there are N -slaves, and if 3*N other tasks return after the given slave task is "due". -If a slow slave has not returned by slave-timeout seconds -(see 5.2 Command Line Options in TOP-C Applications), then -the slave is considered dead. The master process sends no further tasks -to that slave, and sends a replicate of the original task to a new -slave. -

- - -


- - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

7.2 Strategies for Greater Concurrency

- -

- -

-
Strategy 1: SEMI-INDEPENDENT TASKS: -
Define tasks so that most task outputs do not require any update. - This is always the case for trivial parallelism (when tasks are - independent of each other). It is also often the case for many - examples of search and enumeration problems. -
-

- -

-
Strategy 2: CACHE PARTIAL RESULTS: -
Inside DoTask() and UpdateSharedData(), save partial - computations in global private variables. Then, in the event of a - REDO action, `TOP-C' guarantees to invoke - DoTask() again on the - original slave process or slave thread. That slave may then use - previously computed partial results in order to shorten the required - computation. Note that pointers on the slave to input and output - buffers from previous UPDATE actions and from the original task - input will no longer be valid. The slave process must copy - any data it wishes to cache to global variables. - In the case of the shared memory model, those global variables must be - thread-private. (see section 8.4.2 Thread-Private Global Variables) - Note the existence of TOPC_is_REDO() for testing for a REDO - action. -
-

- -

-
Strategy 3: MERGE TASK OUTPUTS: -
Inside CheckTaskResult(), the master may merge two or more task - outputs in an application independent way. This may avoid the - need for a REDO action, or it may reduce the number of required - UPDATE actions. -
-

- - -


- - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

7.3 Improving Performance

- -

- - - - - -

- -If your application runs too slowly due to excessive time for communication, -consider running multiple slave processes on a single processor. This -allows one process to continue computing while another is communicating -or idle waiting for a new task to be generated by the master. -

- -If communication overhead or idle time is still too high, consider if it is -possible to increase the granularity of your task. TOP-C can -aggregating several consecutive tasks as a single larger -task to be performed by a single process. This amortizes the network -latency of a single network message over several tasks. -For example, you can do combine 5 tasks -by invoking `--TOPC-aggregated-tasks=5' on -the command line of the application. Alternatively, execute the statement: -
 
  TOPC_OPT_aggregated_tasks=5;
-
before TOPC_master_slave(). -In this situation, the five task outputs will also be bundled -as a single network message. Currently (TOP-C 2.5.0), this -works only if all tasks return NO_ACTION. TOP-C will signal -an error if TOPC_OPT_aggregated_tasks > 1 and any action -other than NO_ACTION is returned. -

- -Other useful techniques that may improve performance of certain -applications are: -

    -
  1. - set up multiple slaves on each processor (if slave processors - are sometimes idle) -
  2. - re-write the code to bundle a set of tasks as a single task - (to improve the granularity of your parallelism) -
-

- -

-
PERFORMANCE ISSUE FOR MPI: -
If you have a more efficient version of `MPI' (perhaps a vendor version -tuned to your hardware), consider replacing LIBMPI in -`.../top-c/Makefile' by your vendor's `limbpi.a' or -`libmpi.so', and delete or modify the the LIBMPI target in the -`Makefile'. -Alternatively, see the appendix, -C. Using a Different `MPI' with TOP-C, -for a more general way to use a different MPI dialect. -
-
-
PERFORMANCE ISSUE FOR SMP (POSIX threads): -
Finally under `SMP', there is an important performance issue -concerning the interaction of `TOP-C' with the operating system. -First, the vendor-supplied compiler, cc, is recommended over -gcc for `SMP', due to specialized vendor-specific -architectural issues. Second, if a thread completes its work before -using its full scheduling quantum, the operating system may yield the -CPU of that thread to another thread -- potentially including a thread -belonging to a different process. There are several ways to defend -against this. One defense is to insure that the time for a single task -is significantly longer than one quantum. Another defense is to ask the -operating system to give you at least as many "run slots" as you have -threads (slaves plus master). Some operating systems use -pthread_setconcurrency() to allow an application to declare this -information, and `TOP-C' invokes pthread_setconcurrency() -where it is available. However, other operating systems may have -alternative ways of tuning the scheduling of threads, and it is -worthwhile to read the relevant manuals of your operating system. -
-

- - -


- - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

7.4 Long Jobs and Courtesy to Others

- -

- - - -

- -In the distributed memory model, infinite loops and broken socket -connections tend to leave orphaned processes running. -In the `TOP-C' distributed memory model, -a slave times out if a task lasts longer than -a half hour or if the master does not reply -in a half hour. -This is implemented with the UNIX system call, alarm(). -

- -A half hour (1800 seconds) is the default timeout period. -The command line option --TOPC-slave-timeout=num -allows one to change this default. If num is 0, -then there is no timeout and `TOP-C' makes no calls -to SIGALRM. -

- -The application writer may also find some of the following UNIX system calls -useful for allowing large jobs to coexist with other applications. -

-
setpriority(PRIO_PROCESS,getpid(),prio) -
#include <unistd.h>
-#include <sys/resource.h>

---- prio = 10 still - gives you some CPU time. prio = 19 means that any job of - higher priority always runs before you. Place in main(). -
setrlimit(RLIMIT_RSS, &rlp) -
#include <sys/resource.h>
-struct rlimit rlp;
-rlp.rlim_max = rlp.rlim_cur = SIZE;

---- SIZE is RAM limit (bytes). If your system has - significant paging, the system will prefer to keep your process - from growing beyond SIZE bytes of resident RAM. Even if you set - nice to priority 20, this is still important. Otherwise you may - cause someone to page out much of his or her job in your favor during - one of your infrequent quantum slices of CPU time. Place in - main(). (Not all operating systems enforce this request.) -
-

- - -


- - - - - - - -
[ << ][ >> ]           [Top][Contents][Index][ ? ]
-
- -This document was generated -by Gene Cooperman on October, 6 2004 -using texi2html - - - - diff --git a/topc-2.5.2/doc/html/topc_8.html b/topc-2.5.2/doc/html/topc_8.html deleted file mode 100644 index 29d96884..00000000 --- a/topc-2.5.2/doc/html/topc_8.html +++ /dev/null @@ -1,862 +0,0 @@ - - - - - -TOP-C (Task Oriented Parallel C/C++): Advanced Features - - - - - - - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

8. Advanced Features of `TOP-C'

- -

- -It is best to postpone reading this section until the basic features -discussed in the previous chapters are clear. -

- -

- - - - - - -
8.1 Testing for Task Continuations and Redos  
8.2 Aborting Tasks  
8.3 Memory Allocation for Task Buffers  
8.4 Optimizing TOP-C Code for the Shared Memory Model  
8.5 Modifying TOP-C Code for the Sequential Memory Model  
8.6 Caveats  
-

- - -


- - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

8.1 Testing for Task Continuations and Redos

- -

- - - - -

- - -

-
Function: TOPC_BOOL TOPC_is_REDO ( void ) -
-
Function: TOPC_BOOL TOPC_is_CONTINUATION ( void ) -
These return 0 (false) or 1 (true), according to whether the current - call to DoTask() was a result of a REDO - or CONTINUATION() action, respectively. The result is - is not meaningful if called outside of DoTask(). -
-

- - -


- - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

8.2 Aborting Tasks

- -

- - -

- - -

-
Function: void TOPC_abort_tasks ( void ) -
-
Function: TOPC_BOOL TOPC_is_abort_pending ( void ) -
TOPC_abort_tasks() should be called in CheckTaskResult(). - `TOP-C' then makes a best effort (no guarantee) to notify each - slave. TOP-C does not directly abort tasks. However, - TOPC_is_abort_pending() returns 1 (true) - when invoked in DoTask() on a slave. A typical - DoTask() callback uses this to poll for an abort request - from the master, upon which it returns early with a special - task output. At the beginning of the next new task, REDO - or CONTINUATION, `TOP-C' resets the pending abort - to 0 (false). See `examples/README' of the `TOP-C' - distribution for example code. -
-

- - -


- - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

8.3 Memory Allocation for Task Buffers

- -

- -The principle of memory allocation in `TOP-C' is that if an -application allocates memory, then it is the responsibility of the -application to free that memory. This issue typically arises around the -issue of task buffers (see section 3.1.3 Task Input and Task Output Buffers) and calls -to TOPC_MSG(buf,buf_size). An application -often calls buf = malloc(...); or -buf = new ...; (in C++) -and copies data into that buffer before the call to TOPC_MSG. -Since the last action of GenerateTaskInput() or DoTask() -is typically to return TOPC_MSG(buf,buf_size), -there remains the question of how to free buf. -

- -

- - - - -
8.3.1 Avoiding malloc and new with Task Buffers  
8.3.2 Using TOPC_MSG_PTR() to Avoid Copying Large Buffers  
8.3.3 Allocation and Freeing of Task Buffers for TOPC_MSG_PTR()  
8.3.4 Marshaling Complex Data Structures into `TOP-C' Task Buffers  
-

- - -


- - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

8.3.1 Avoiding malloc and new with Task Buffers

- -

- -The best memory allocation solution for task buffers is to implement the -buffers as local variables, and therefore on the stack. This avoids the -need for malloc and new, and the question of how to later -free that memory. -If you use TOPC_MSG (as opposed to TOPC_MSG_PTR, -see section 8.3.2 Using TOPC_MSG_PTR() to Avoid Copying Large Buffers), then recall that TOPC_MSG -copies its buffer to a separate TOP-C space. For example, -
 
{ int x;
-   ...
-  return TOPC_MSG(&x, size_of(x));
-}
-

- - - -

- -If your task buffer is of fixed size, one can allocate it as a character -array on the stack: char buf[BUF_SIZE];. -If your buffer contains variable size data, consider using -alloca in place of malloc to allocate on the -stack. -
 
{ ...
-  buf = alloca(buf_size);
-  return TOPC_MSG(buf, buf_size);
-}
-

- -In all of the above cases, there is no need to free the buffer, since -TOPC_MSG will make a `TOP-C'-private copy and the -stack-allocated buffer will disappear when the current routine exits. -Note that alloca may be unavailable on your system. -Alternatively, the use of alloca may be undesirable due to very -large buffers and O/S limits on stack size. In such cases, consider the -following alternative. -
 
{ TOPC_BUF tmp;
-  ...
-  buf = malloc(buf_size);
-  tmp = TOPC_MSG(buf, buf_size);
-  free(buf);
-  return tmp;
-}
-

- - -


- - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

8.3.2 Using TOPC_MSG_PTR() to Avoid Copying Large Buffers

- -

- - - -

- -If the cost of copying a large buffer is a concern, `TOP-C' provides -an alternative function, which avoids copying into `TOP-C' space. -

- - -

-
Function: TOPC_BUF TOPC_MSG_PTR ( void *buf, int buf_size ) -
Same as TOPC_MSG(), except that it does not copy - buf into `TOP-C' space. It is the responsibility - of the application not to free or modify buf as long - as `TOP-C' might potentially pass it to an - application callback function. -
-

- -TOPC_MSG_PTR() is inherently dangerous, if the application -modifies or frees a buffer and `TOP-C' later passes that buffer -to a callback function. It may be useful when the cost of copying -large buffers is an issue, or if one is concerned about `TOP-C' -making a call to malloc(). Note that the invocation -
 
  ./a.out --TOPC-safety=4
-
automatically converts all calls to TOPC_MSG_PTR() into -calls to TOPC_MSG(). This is useful in deciding -if a bug is related to the use of TOPC_MSG_PTR(). -

- -An application should not pass a buffer on the stack to TOPC_MSG_PTR(). -This can be avoided either by declaring a local variable to be -`static', or else using a global variable (or a class member -in the case of C++). In such cases, it is the responsibility of the -application to dynamically create and free buffers. -An example of how this can be done follows in the next section. -

- -Note that if the application code must also be compatible with the -shared memory model, then the static local variable or global variable -must also be thread-private -(8.4.2 Thread-Private Global Variables). -

- -For examples of coding with TOPC_MSG_PTR() that are compatible -with all memory models, including the shared memory model, -see `examples/README' and the corresponding examples -in the `TOP-C' distribution. -

- - -


- - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

8.3.3 Allocation and Freeing of Task Buffers for TOPC_MSG_PTR()

- -

- -Recall the syntax for creating a message buffer of type TOPC_BUF -using -TOPC_MSG_PTR(buf, buf_size). The two callback functions -GenerateTaskInput() and DoTask() both return such a -message buffer. In the case of -GenerateTaskInput(), `TOP-C' saves a copy of the buffer, -which becomes an input argument to CheckTaskResult() -and to UpdateSharedData on the master. -Hence, if buf points to a temporarily allocated buffer, -it is the responsibility of the `TOP-C' callback function to free the -buffer only after the callback function has returned. -This seeming contradiction can be easily handled by the following code. -
 
    TOPC_BUF GenerateTaskInput() {
-      static void *buf = NULL;
-      if ( buf == NULL ) { malloc(buf_size); }
-      ... [ Add new message data to buf ] ...
-      return TOPC_MSG_PTR(buf, buf_size);
-    }
-
If buf_size might vary dynamically between calls, the following -fragment solves the same problem. -
 
    TOPC_BUF GenerateTaskInput() {
-      static void *buf = NULL;
-      if ( buf != NULL ) { free(buf); }
-      ... [ Compute buf_size for new message ] ...
-      buf = malloc( buf_size );
-      ... [ Add new message data to buf ] ...
-      return TOPC_MSG_PTR(buf, buf_size);
-    }
-

- -Note that buf is allocated as a static local -variable. `TOP-C' restricts the buf of -TOPC_MSG_PTR(buf, buf_size) to point to a buffer that is in -the heap (not on the stack). Hence, buf must not point to -non-static local data. -

- - -


- - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

8.3.4 Marshaling Complex Data Structures into `TOP-C' Task Buffers

- -

- -If you use a distributed memory model and the buffer pointed to by -input includes fields with their own pointers, the application -must first follow all pointers and copy into a new buffer all data -referenced directly or indirectly by input. The new buffer can -then be passed to TOPC_MSG(). This copying process is called -marshaling. See section Marshaling and Heterogeneous Architectures. -

- -If following all pointers is a burden, then one can -load the application on the master and slaves at a common absolute -address, and insure that all pointer references have been initialized -before the first call to TOPC_master_slave(). In `gcc', -one specifies an absolute load address with code such as: -
 
  gcc -Wl,-Tdata -Wl,-Thex_addr ...
-
These flags are for the data segment. If the pointers indirectly -reference -data on the stack, you may have to similarly specify stack absolute addresses. -Choosing a good hex_addr for all machines may be a matter of trial -and error. In a test run, print out the absolute addresses of some -pointer variables near the beginning of your data memory. -

- -Specifying an absolute load address has many risks, such as if -the master and slaves use different versions of the operating system, -the compiler, other software, or different hardware configurations. -Hence, this technique is recommended only as a last resort. -

- - -


- - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

8.4 Optimizing TOP-C Code for the Shared Memory Model

- -

- - - -

- - The `TOP-C' programmer's model changes slightly for shared -memory. With careful design, one can use the same application source -code both for distributed memory and shared memory architectures. -Processes are replaced by threads. UpdateSharedData() is -executed only by the master thread, and not by any slave thread. As -with distributed memory, TOPC_MSG() buffers are copied to -`TOP-C' space (shallow copy). As usual, the application is responsible -for freeing any application buffers outside of `TOP-C' space. -Furthermore, since the master and slaves share memory, `TOP-C' -creates the slaves only during the first call to master_slave. If a -slave needs to initialize any private data (see -TOPC_thread_private, below), then this can be done by the slave -the first time that it gains control through DoTask(). -

- -Two issues arise in porting a distributed memory -`TOP-C' application to shared memory. -

    -
  1. - reader-write synchronization: DoTask() must not read - shared data while UpdateSharedData() (on the master) - simultaneously writes to the shared data. -
  2. - creating thread-private (unshared) global variables: -
-

- -Most `TOP-C' applications for the distributed memory model will run -unchanged in the shared memory model. In some cases, one must add -additional `TOP-C' code to handle these additional issues. In all -cases, one can easily retain compatibility with the distributed memory model. -

- -

- - - - -
8.4.1 Reader-Writer Synchronization  
8.4.2 Thread-Private Global Variables  
8.4.3 Sharing Variables between Master and Slave and Volatile Variables  
8.4.4 SMP Performance  
-

- - -


- - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

8.4.1 Reader-Writer Synchronization

- -

- - - - - -

- -In shared memory, `TOP-C' uses a classical single-writer, -multiple-reader strategy with writer-preferred for lock requests. -By default, DoTask() acts as the critical section of the -readers (the slave threads) and UpdateSharedData() acts as the -critical section of the writer (the master thread). -`TOP-C' sets a read lock around all of DoTask() and a write -lock around all of UpdateSharedData(). -

- -As always in the `TOP-C' model, -it is an error if an application writes to shared data outside -of UpdateSharedData(). Note that GenerateTaskInput() -and CheckTaskResult() can safely read the shared data without -a lock in this case, since these routines and UpdateSharedData() -are all invoked only by the master thread. -

- -The default behavior implies that DoTask() and -UpdateSharedData() never run simultaneously. Optionally, one -can achieve greater concurrency through a finer level of granularity -by declaring to `TOP-C' which sections of code read or write -shared data. If `TOP-C' detects any call to TOPC_ATOMIC_READ(0), -`TOP-C' will follow the critical sections declared by the -application inside of DoTask() and UpdateSharedData(). -

- - -

-
Function: void TOPC_ATOMIC_READ ( 0 ) { ... C code ... } -
-
Function: void TOPC_ATOMIC_WRITE ( 0 ) { ... C code ... } -
This sets a global read or write lock in effect during the time - that C code is being executed. If a thread holds a write lock, - no thread may hold a read lock. If no thread holds a write lock, - arbitrarily many threads hold a read lock. If a thread requests - a write lock, no additional read locks will be granted until after the - write lock has been granted. See `examples/README' of the - `TOP-C' distribution for example code. -
-

- -It is not useful to use TOPC_ATOMIC_READ() outside of DoTask() -not to use TOPC_ATOMIC_WRITE() outside of UpdateSharedData(). -

- -The number 0 refers to page 0 of shared data. `TOP-C' currently -supports only a single common page of shared data, but future versions -will support multiple pages. In the future, two threads will be able to -simultaneously hold write locks if they are for different pages. -

- -The following alternatives to TOPC_ATOMIC_READ() -and TOPC_ATOMIC_WRITE() are provided for greater flexibility. -

- - -

-
Function: void TOPC_BEGIN_ATOMIC_READ ( 0 ) -
-
Function: void TOPC_END_ATOMIC_READ ( 0 ) -
-
Function: void TOPC_BEGIN_ATOMIC_WRITE ( 0 ) -
-
Function: void TOPC_END_ATOMIC_WRITE ( 0 ) -
The usage is the same as for TOPC_ATOMIC_READ -and TOPC_ATOMIC_WRITE. -
-

- -In the distributed memory model of `TOP-C', all of the -above invocations for atomic reading and writing are ignored, -thus retaining full compatibility between the shared and -distributed memory models. -

- - -


- - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

8.4.2 Thread-Private Global Variables

- -

- - - - - -

- -A thread-private variable is a variable whose data is not -shared among threads: i.e., each thread has a private copy of -the variable. -The only variables that are thread-private by default in -shared memory are those on the stack (non-static, local variables). All -other variables exist as a single copy, shared by all threads. -This is inherent in the POSIX standard for threads in C/C++. -If DoTask() accesses any global variables or local static variables, -then those variables must be made thread-private. -

- -Ideally, if C allowed it, we would just write something like: -
 
  THREAD_PRIVATE int myvar = 0;  /* NOT SUPPORTED */
-
Instead, `TOP-C' achieves the same effect `as if' it had -declared -
 
  TOPC_thread_private_t TOPC_thread_private;
-
This allows the application writer to include in his or her code: -
 
  typedef int TOPC_thread_private_t;
-  #define myvar TOPC_thread_private;
-  int myvar_debug() {return myvar;} /* needed to access myvar in gdb */
-

- -`TOP-C' provides primitives to declare a single thread-private -global variable. `TOP-C' allows -the application programmer to declare the type of that variable. - -

-
Variable: TOPC_thread_private -
A pre-defined thread-private variable of type, - TOPC_thread_private_t. It may be - used like any C variable, and each thread has its own private - copy that will not be shared. -
- -
-
Type: TOPC_thread_private_t -
Initially, undefined. User must define this type using typedef - if TOPC_thread_private is used. -
-

- -If more than one thread-private variable is desired, define -TOPC_thread_private_t as a struct, and use each -field as a separate thread-private variable. -

- -EXAMPLE: -

- -
 
/* Ideally, if C allowed it, we would just write:
- *      THREAD_PRIVATE struct {int my_rank; int rnd;} mystruct;
- * We emulate this using TOP-C's implicitly declared thread-private var:
- *      TOPC_thread_private_t TOPC_thread_private;
- */
-typedef struct {int my_rank; int rnd;} TOPC_thread_private_t;
-#define mystruct TOPC_thread_private
-void set_info() {
-  mystruct.my_rank = TOPC_rank();
-  mystruct.rnd = rand();
-}
-void get_info() {
-foo();
-  if (mystruct.my_rank != TOPC_rank()) printf("ERROR\n");
-  printf("Slave %d random num:  %d\n", mystruct.my_rank, mystruct.rnd);
-}
-TOPC_BUF do_Task() {
-  set_info(); /* info in mystruct is NOT shared among threads */
-  get_info();
-  ...;
-}
-

- -Additional examples can be found by reading -`examples/README' in the `TOP-C' distribution. -

- - -


- - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

8.4.3 Sharing Variables between Master and Slave and Volatile Variables

- -

- - -

- -The shared memory model, like any `SMP' code, -allows the master and slaves to -communicate through global variables, which are shared by default. -It is recommended not to use this feature, and instead to maintain -communication through TOPC_MSG(), for ease of code maintenance, -and to maintain portability with the other `TOP-C' models -(distributed memory and sequential). If you do use your own global shared -variables between master and slaves, be sure to declare them volatile. -
 
  volatile int myvar;
-
ANSI C requires this qualifier if a variable -may be accessed or modified by more than one thread. -Without this qualifier, your program may not run correctly. -

- -To be more precise, if a non-local variable is accessed more than once -in a procedure, the compiler is allowed to keep the first access value -in a thread register and reuse it at later occurrences, without consulting -the shared memory. A volatile declaration tells the compiler to re-read -the value from shared memory at each occurrence. Similarly, a write to -a volatile variable causes the corresponding transfer of its value from -a register to shared memory to occur at a time not much later than the -execution of the write instruction. -

- -If you suspect a missing volatile declaration, note that `gcc' -support the following command-line options. -
 
  gcc -fvolatile -fvolatile-global ...
-  # If topcc uses gcc:
-  topcc --pthread -fvolatile -fvolatile-global myfile.c
-
The option -fvolatile tells `gcc' to compile all memory -references through pointers as volatile, and the option --fvolatile-global tells `gcc' to compile all memory -references to extern and global data as volatile. -However, note that this implies a performance penalty -since the compiler will issue -a load/store instruction for each volatile access, and -will not keep volatile values in registers. -

- - -


- - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

8.4.4 SMP Performance

- -

- -Note that `SMP' involves certain performance issues that do not arise -in other modes. If you find a lack of performance, please read -7.3 Improving Performance. Also, note that the vendor-supplied -compiler, cc, is often recommended over gcc for -`SMP', due to specialized vendor-specific architectural issues. -

- - -


- - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

8.5 Modifying TOP-C Code for the Sequential Memory Model

- -

- - - -

- -`TOP-C' also provides a sequential memory model. That model is -useful for first debugging an application in a sequential context, and -then re-compiling it with one of the parallel `TOP-C' libraries for -production use. The application code for the sequential library is -usually both source and object compatible with the application code for -a parallel library. The sequential library emulates an application with -a single `TOP-C' library. -

- -The sequential memory model emulates an application in which -`DoTask()' is executed in the context of the single slave -process/thread, and all other code is executed in the context of the -master process/thread. This affects the values returned by -TOPC_is_master() and TOPC_rank(). In particular, -conditional code for execution on the master will work -correctly in the sequential memory model, but the following conditional -code for execution on the slave will probably not work correctly. -
 
int main( int argc, char *argv[] ) {
-  TOPC_init( &argc, &argv );
-  if ( TOPC_is_master() )
-    ...;  /* is executed in sequential model */
-  else
-    ...;  /* is never executed in sequential model */
-  TOPC_master_slave( ..., ..., ..., ...);
-  TOPC_finalize();
-}
-

- - -


- - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

8.6 Caveats

- -IMPORTANT: -`TOP-C' sets alarm() before waiting to receive - message from master. By default, if the master does not reply in a - half hour (1800 seconds), then the slave receives - SIGALRM and dies. - This is to prevent runaway processes in dist. memory version when master dies - without killing all slaves. 7.4 Long Jobs and Courtesy to Others, - in order to change this default. - If your applications also uses SIGALRM, then run your - application with --TOPC-slave-timeout=0 and `TOP-C' - will not use SIGALRM. -

- -GenerateTaskInput() and DoTask() - This memory is managed by `TOP-C'. -

- -The slave process attempts to set current directory to the same as the master - inside TOPC_init() and produces a warning if unsuccessful. -

- -When a task buffer is copied into `TOP-C' space, -it becomes word-aligned. If the buffer was originally not -word-aligned, but some field in the buffer was word-aligned, -the internal field will no longer be word-aligned. On some -architectures, casting a non-word-aligned field to `int' -or certain other types will cause a bus error. -

- - -


- - - - - - - -
[ << ][ >> ]           [Top][Contents][Index][ ? ]
-
- -This document was generated -by Gene Cooperman on October, 6 2004 -using texi2html - - - - diff --git a/topc-2.5.2/doc/html/topc_9.html b/topc-2.5.2/doc/html/topc_9.html deleted file mode 100644 index 18cd1b51..00000000 --- a/topc-2.5.2/doc/html/topc_9.html +++ /dev/null @@ -1,265 +0,0 @@ - - - - - -TOP-C (Task Oriented Parallel C/C++): TOP-C Raw Interface - - - - - - - - - - - - - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

9. `TOP-C' Raw Interface for Parallelizing Sequential Code

- -

- -There are instances when tasks are most naturally generated deep -inside nested loops. Often, this occurs in parallelizing existing -sequential applications. -In such circumstances, it may be difficult to -re-write the code to create a function GenerateTaskInput(), since -that would require turning the loops inside out. (If you don't know what this -refers to, then you probably don't need the raw interface.) -

- -On a first reading, you may wish to first look at the example for -either a `for' loop or `while' loop, depending on the type of -loop that you are parallelizing. Then return to the formal -descriptions of the `TOP-C' raw functions. This chapter assumes -familiarity with the basic concepts of 3. Overview of `TOP-C/C++' and 4. Writing `TOP-C' Applications. -

- -

- - - -
9.1 `TOP-C' raw functions  
9.2 Parallelizing `for' Loops  
9.3 Parallelizing `while' Loops  
-

- - -


- - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

9.1 `TOP-C' raw functions

- -

- - -

-
Function: void TOPC_raw_begin_master_slave -
(do_task, check_task_result, update_shared_data) - -
Function: void TOPC_raw_end_master_slave () -
This behaves like master_slave, with - TOPC_raw_submit_task_input(input) serving - the role of GenerateTaskInput(). The slave blocks inside - TOPC_raw_begin_master_slave() and executes `do_task()' and - `update_shared_data()' until the master executes - TOPC_raw_end_master_slave(). At that time, the slave - unblocks. The slave does nothing inside - TOPC_raw_end_master_slave(). -
-

- - -

-
Function: void TOPC_raw_submit_task_input ( TOPC_BUF input ) -
Invoked by master between TOPC_raw_begin_master_slave() - and TOPC_raw_end_master_slave(); Typical usage is: -
 
     TOPC_raw_submit_task_input(TOPC_MSG(&input_data,
-                                         sizeof(input_data)) );
-
The argument, input, corresponds to what would be returned by - GenerateTaskInput() in the routine TOPC_master_slave(). - input will be processed by DoTask() and its siblings, - just as in TOPC_master_slave()). - There can be multiple occurrences of - TOPC_raw_submit_task_input(). -
-

- - -

-
Function: TOPC_BOOL TOPC_raw_wait_for_task_result () -
Invoked by master between TOPC_raw_begin_master_slave() and - TOPC_raw_end_master_slave(); - If no tasks are outstanding, returns false immediately. Otherwise, it - blocks until a task does return. It calls application - callback, CheckTaskResult(), and then returns true. -
-

- - -


- - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

9.2 Parallelizing `for' Loops

- -

- -Assume that we are parallelizing a code fragment of the following form. -The variables i and j will be the input to -DoTask(), and any data structures indexed by i and -j (for example array in array[i][j]) will be -part of the shared data. -
 
  float array[ROWS][COLS];
-  ...
-    for ( i = 0; i < 10; i++ ) {
-      for ( j = 0; j < 10; j++ ) {
-        /* do_task: */ ...
-        /* update:  */ array[i][j] = ...;
-      }
-    }
-

- -Assume that the labels do_task and update above -correspond to the callback functions DoTask() and -UpdateSharedData(). Then the code is parallelized below. -

- -
 
  float array[ROWS][COLS];
-  typedef struct {int i_val; int j_val;} input_t;
-  void *DoTask(input_t *buf) {
-    int i = (*buf).i_val, j = (*buf).j_val;
-    /* do_task: */ ...
-  }
-  void *CheckTaskResult(input_t *buf, output_t *buf2) {
-    /* update:  */ array[i][j] = ...;
-    return NO_ACTION;
-  }
-  main(int argc, char **argv) {
-    TOPC_init( &argc, &argv );
-    TOPC_raw_begin_master_slave(DoTask, CheckTaskResult,
-                                UpdateSharedData);
-    if (TOPC_is_master()) {
-      for ( i = 0; i < 10; i++ ) {
-        for ( j = 0; j < 10; j++ ) {
-          input_t input;
-          input.i_val = i; input.j_val = j;
-          TOPC_raw_submit_task_input( TOPC_MSG(&input, sizeof(input)) );
-        }
-      }
-    } TOPC_raw_end_master_slave();
-    TOPC_finalize();
-  }
-

- - -


- - - - - - - - - - - -
[ < ][ > ]   [ << ][ Up ][ >> ]         [Top][Contents][Index][ ? ]
-

9.3 Parallelizing `while' Loops

- -

- -Assume that we are parallelizing a code fragment of the following form -and input is a pointer. -
 
  while ( (input = next_input()) != NULL ) {
-    /* do_task: */ ...
-    /* update:  */ ...
-  }
-

- -Assume that the labels do_task and update above -correspond to the callback functions DoTask() and -UpdateSharedData(). Then the code is parallelized below, -where input_size must be specified by the application before it -is used. -

- -
 
  TOPC_init( &argc, &argv );
-  TOPC_raw_begin_master_slave(DoTask, CheckTaskResult,
-                              UpdateSharedData);
-  if (TOPC_is_master()) {
-    while ( (input = next_input()) != NULL
-            || TOPC_raw_wait_for_task_result() ) {
-      TOPC_raw_submit_task_input( TOPC_MSG(input, input_size) );
-    }
-  } TOPC_raw_end_master_slave();
-  TOPC_finalize();
-

- -Note that the code inside the raw begin/end block is executed -only by the master in the code above. -

- -If the buffer, input, contains pointers to other data, then you -will need to marshal the data before calling TOPC_MSG(). -See section Marshaling and Heterogeneous Architectures. -

- - -


- - - - - - - -
[ << ][ >> ]           [Top][Contents][Index][ ? ]
-
- -This document was generated -by Gene Cooperman on October, 6 2004 -using texi2html - - - - diff --git a/topc-2.5.2/doc/html/topc_abt.html b/topc-2.5.2/doc/html/topc_abt.html deleted file mode 100644 index 162aee45..00000000 --- a/topc-2.5.2/doc/html/topc_abt.html +++ /dev/null @@ -1,202 +0,0 @@ - - - - - -TOP-C (Task Oriented Parallel C/C++): About this document - - - - - - - - - - - - - - - - - -
[Top][Contents][Index][ ? ]
-

About this document

-This document was generated -using texi2html -

-The buttons in the navigation panels have the following meaning: -

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Button Name Go to From 1.2.3 go to
- [ < ] -Back - -previous section in reading order - -1.2.2 -
- [ > ] -Forward - -next section in reading order - -1.2.4 -
- [ << ] -FastBack - -previous or up-and-previous section - -1.1 -
- [ Up ] -Up - -up section - -1.2 -
- [ >> ] -FastForward - -next or up-and-next section - -1.3 -
- [Top] -Top - -cover (top) of document - -   -
- [Contents] -Contents - -table of contents - -   -
- [Index] -Index - -concept index - -   -
- [ ? ] -About - -this page - -   -
-

-where the Example assumes that the current position -is at Subsubsection One-Two-Three of a document of -the following structure: -
    -
  • 1. Section One
  • -
      -
    • 1.1 Subsection One-One
    • -
        -
      • ...
      • -
      -
    • 1.2 Subsection One-Two
    • -
        -
      • 1.2.1 Subsubsection One-Two-One -
      • 1.2.2 Subsubsection One-Two-Two -
      • 1.2.3 Subsubsection One-Two-Three     -<== Current Position -
      • 1.2.4 Subsubsection One-Two-Four -
      -
    • 1.3 Subsection One-Three
    • -
        -
      • ...
      • -
      -
    • 1.4 Subsection One-Four
    • -
    -
- -
-
- -This document was generated -by Gene Cooperman on October, 6 2004 -using texi2html - - - - diff --git a/topc-2.5.2/doc/html/topc_foot.html b/topc-2.5.2/doc/html/topc_foot.html deleted file mode 100644 index b88f196a..00000000 --- a/topc-2.5.2/doc/html/topc_foot.html +++ /dev/null @@ -1,24 +0,0 @@ - - - - -TOP-C (Task Oriented Parallel C/C++) - Footnotes - - -

TOP-C (Task Oriented Parallel C/C++)

-

A Package for Easily Writing Parallel Applications

-

for both Distributed and Shared Memory Architectures

-

Version 2.4.0, October, 2001

-
Gene Cooperman
-

-


-

(1)

-

MPI is -Message Passing Interface, see @url{http://www.mpi-forum.org/ -


-This document was generated on 13 October 2001 using the -texi2html -translator version 1.51.

- - diff --git a/topc-2.5.2/doc/html/topc_fot.html b/topc-2.5.2/doc/html/topc_fot.html deleted file mode 100644 index 6b63cf8f..00000000 --- a/topc-2.5.2/doc/html/topc_fot.html +++ /dev/null @@ -1,53 +0,0 @@ - - - - - -TOP-C (Task Oriented Parallel C/C++): Footnotes - - - - - - - - - - - - - - - - - -
[Top][Contents][Index][ ? ]
-

Footnotes

-

(1)

-

MPI is -Message Passing Interface, see http://www.mpi-forum.org/ -

(2)

-

valgrind is available at -http://www.valgrind.kde.org. -

(3)

-

efence is available at -http://sources.isc.org/devel/memleak/efence. -


-
- -This document was generated -by Gene Cooperman on October, 6 2004 -using texi2html - - - - diff --git a/topc-2.5.2/doc/html/topc_ovr.html b/topc-2.5.2/doc/html/topc_ovr.html deleted file mode 100644 index 7adc111f..00000000 --- a/topc-2.5.2/doc/html/topc_ovr.html +++ /dev/null @@ -1,79 +0,0 @@ - - - - - -TOP-C (Task Oriented Parallel C/C++): Short Table of Contents - - - - - - - - - - - - - - - - - -
[Top][Contents][Index][ ? ]
-

Short Table of Contents

-
-1. `TOP-C' Copying Conditions -
-2. Quick Start: Installation and Test Run -
-3. Overview of `TOP-C/C++' -
-4. Writing `TOP-C' Applications -
-5. Compiling and Invoking `TOP-C' Applications -
-6. Debugging and Tracing -
-7. Performance and Long Jobs -
-8. Advanced Features of `TOP-C' -
-9. `TOP-C' Raw Interface for Parallelizing Sequential Code -
-10. Acknowledgements -
-A. Summary of `TOP-C' Commands -
-B. Example `TOP-C' Application -
-C. Using a Different `MPI' with TOP-C -
-Function Index -
-Variable Index -
-Concept Index -
- -
-
-
- -This document was generated -by Gene Cooperman on October, 6 2004 -using texi2html - - - - diff --git a/topc-2.5.2/doc/html/topc_toc.html b/topc-2.5.2/doc/html/topc_toc.html deleted file mode 100644 index 7f97df38..00000000 --- a/topc-2.5.2/doc/html/topc_toc.html +++ /dev/null @@ -1,193 +0,0 @@ - - - - - -TOP-C (Task Oriented Parallel C/C++): Table of Contents - - - - - - - - - - - - - - - - - -
[Top][Contents][Index][ ? ]
-

Table of Contents

-
-1. `TOP-C' Copying Conditions -
-2. Quick Start: Installation and Test Run -
-3. Overview of `TOP-C/C++' -
-
-3.1 Programmer's Model -
-
-3.1.1 Structure of a TOP-C Program -
-3.1.2 Four Callback Functions -
-3.1.3 Task Input and Task Output Buffers -
-3.1.4 The `TOP-C' Algorithm -
-
-3.2 Three Key Concepts for TOP-C -
-3.3 Distributed and Shared Memory Models -
-
-4. Writing `TOP-C' Applications -
-
-4.1 The Main TOP-C Library Calls -
-4.2 Callback Functions for TOPC_master_slave() -
-4.3 Actions Returned by CheckTaskResult() -
-4.4 TOP-C Utilities -
-
-5. Compiling and Invoking `TOP-C' Applications -
-
-5.1 Compiling TOP-C Applications -
-5.2 Command Line Options in TOP-C Applications -
-5.3 Invoking a TOP-C Application in Sequential Memory -
-5.4 Invoking a TOP-C Application in Distributed Memory -
-
-5.4.1 Writing Procgroup Files for `MPINU' -
-5.4.2 If Slaves Fail to Start -
-
-5.5 Invoking a TOP-C Application in Shared Memory -
-
-6. Debugging and Tracing -
-
-6.1 Debugging by Limiting the Parallelism -
-6.2 Debugging with `--TOPC-safety' -
-6.3 TOP-C and POSIX signals -
-6.4 Tracing Messages -
-6.5 Stepping Through a Slave Process with `gdb' -
-6.6 Segmentation faults and other memory problems -
-
-7. Performance and Long Jobs -
-
-7.1 Dropping Slow or Dead Slaves -
-7.2 Strategies for Greater Concurrency -
-7.3 Improving Performance -
-7.4 Long Jobs and Courtesy to Others -
-
-8. Advanced Features of `TOP-C' -
-
-8.1 Testing for Task Continuations and Redos -
-8.2 Aborting Tasks -
-8.3 Memory Allocation for Task Buffers -
-
-8.3.1 Avoiding malloc and new with Task Buffers -
-8.3.2 Using TOPC_MSG_PTR() to Avoid Copying Large Buffers -
-8.3.3 Allocation and Freeing of Task Buffers for TOPC_MSG_PTR() -
-8.3.4 Marshaling Complex Data Structures into `TOP-C' Task Buffers -
-
-8.4 Optimizing TOP-C Code for the Shared Memory Model -
-
-8.4.1 Reader-Writer Synchronization -
-8.4.2 Thread-Private Global Variables -
-8.4.3 Sharing Variables between Master and Slave and Volatile Variables -
-8.4.4 SMP Performance -
-
-8.5 Modifying TOP-C Code for the Sequential Memory Model -
-8.6 Caveats -
-
-9. `TOP-C' Raw Interface for Parallelizing Sequential Code -
-
-9.1 `TOP-C' raw functions -
-9.2 Parallelizing `for' Loops -
-9.3 Parallelizing `while' Loops -
-
-10. Acknowledgements -
-A. Summary of `TOP-C' Commands -
-B. Example `TOP-C' Application -
-C. Using a Different `MPI' with TOP-C -
-Function Index -
-Variable Index -
-Concept Index -
-
-
-
- -This document was generated -by Gene Cooperman on October, 6 2004 -using texi2html - - - - diff --git a/topc-2.5.2/doc/logo.fig b/topc-2.5.2/doc/logo.fig deleted file mode 100644 index 7d0ee731..00000000 --- a/topc-2.5.2/doc/logo.fig +++ /dev/null @@ -1,106 +0,0 @@ -#FIG 3.1 -Landscape -Center -Inches -1200 2 -6 3450 2625 4350 3525 -2 1 0 1 -1 7 0 0 -1 0.000 0 0 -1 0 0 3 - 3498 3123 3604 2805 3922 2698 -2 1 0 1 -1 7 0 0 -1 0.000 0 0 -1 0 0 2 - 4081 3494 3551 2964 -2 1 0 1 -1 7 0 0 -1 0.000 0 0 -1 0 0 2 - 4293 3282 3763 2751 --6 -6 7875 2550 8775 3450 -2 1 0 1 -1 7 0 0 -1 0.000 0 0 -1 0 0 3 - 8727 3048 8621 2730 8303 2623 -2 1 0 1 -1 7 0 0 -1 0.000 0 0 -1 0 0 2 - 8144 3419 8674 2889 -2 1 0 1 -1 7 0 0 -1 0.000 0 0 -1 0 0 2 - 7932 3207 8462 2676 --6 -6 6675 2550 7425 3300 -2 1 0 1 -1 7 0 0 -1 0.000 0 0 -1 0 0 2 - 7425 2850 7125 2550 -2 1 0 1 -1 7 0 0 -1 0.000 0 0 -1 0 0 2 - 6825 3225 6975 2625 -2 1 0 1 -1 7 0 0 -1 0.000 0 0 -1 0 0 2 - 7125 2550 6675 2700 -2 1 0 1 -1 7 0 0 -1 0.000 0 0 -1 0 0 2 - 7125 3300 7275 2700 --6 -6 4425 1650 5325 2550 -1 3 0 1 -1 7 0 0 -1 0.000 1 0.0000 4875 2100 450 450 4875 2100 5325 2100 -4 0 -1 0 0 0 24 0.0000 4 255 195 4811 2229 S\001 --6 -6 6975 1650 7875 2550 -1 3 0 1 -1 7 0 0 -1 0.000 1 0.0000 7425 2100 450 450 7425 2100 7875 2100 -4 0 -1 0 0 0 24 0.0000 4 255 195 7361 2229 S\001 --6 -6 8550 1950 9450 2850 -1 3 0 1 -1 7 0 0 -1 0.000 1 0.0000 9000 2400 450 450 9000 2400 9450 2400 -4 0 -1 0 0 0 24 0.0000 4 255 195 8935 2529 S\001 --6 -6 4800 600 7350 1500 -6 5925 900 6300 1200 -4 0 -1 0 0 0 24 0.0000 4 255 330 5925 1200 M\001 --6 -1 1 0 1 -1 7 0 0 -1 0.000 1 0.0000 6075 1050 1275 450 6075 1050 7350 600 --6 -6 2850 1950 3750 2850 -1 3 0 1 -1 7 0 0 -1 0.000 1 0.0000 3300 2400 450 450 3300 2400 3750 2400 -4 0 -1 0 0 0 24 0.0000 4 255 195 3235 2529 S\001 --6 -6 4800 2550 5550 3300 -2 1 0 1 -1 7 0 0 -1 0.000 0 0 -1 0 0 2 - 4800 2850 5100 2550 -2 1 0 1 -1 7 0 0 -1 0.000 0 0 -1 0 0 2 - 5400 3225 5250 2625 -2 1 0 1 -1 7 0 0 -1 0.000 0 0 -1 0 0 2 - 5100 2550 5550 2700 -2 1 0 1 -1 7 0 0 -1 0.000 0 0 -1 0 0 2 - 5100 3300 4950 2700 --6 -6 3600 3375 8700 5175 -6 3600 3375 8700 5175 -5 1 0 1 -1 7 0 0 -1 0.000 0 0 0 0 4007.812 4275.000 4275 4575 3675 4050 4275 3975 -5 1 0 1 -1 7 0 0 -1 0.000 0 1 0 0 8292.188 4275.000 8025 4575 8625 4050 8025 3975 -6 4275 3375 8025 3975 -5 1 0 1 -1 7 0 0 -1 0.000 0 0 0 0 5651.786 4012.500 5100 3900 5625 3450 6150 3750 -5 1 0 1 -1 7 0 0 -1 0.000 0 0 0 0 4693.382 4002.206 4275 3975 4575 3600 5100 3900 -5 1 0 1 -1 7 0 0 -1 0.000 0 1 0 0 6648.214 4012.500 7200 3900 6675 3450 6150 3750 -5 1 0 1 -1 7 0 0 -1 0.000 0 1 0 0 7606.618 4002.206 8025 3975 7725 3600 7200 3900 --6 -6 4275 4575 8025 5175 -5 1 0 1 -1 7 0 0 -1 0.000 0 1 0 0 5651.786 4537.500 5100 4650 5625 5100 6150 4800 -5 1 0 1 -1 7 0 0 -1 0.000 0 1 0 0 4693.382 4547.794 4275 4575 4575 4950 5100 4650 -5 1 0 1 -1 7 0 0 -1 0.000 0 0 0 0 6648.214 4537.500 7200 4650 6675 5100 6150 4800 -5 1 0 1 -1 7 0 0 -1 0.000 0 0 0 0 7606.618 4547.794 8025 4575 7725 4950 7200 4650 --6 --6 -4 0 -1 0 0 0 36 0.0000 4 375 1005 5775 4275 Data\001 --6 -2 1 0 1 -1 7 0 0 -1 0.000 0 0 -1 0 0 2 - 6300 3225 6300 1725 -2 1 0 1 -1 7 0 0 -1 0.000 0 0 -1 0 0 2 - 6000 3225 6000 1725 -2 1 0 1 -1 7 0 0 -1 0.000 0 0 -1 0 0 3 - 5850 1800 6150 1650 6450 1800 -2 1 0 1 -1 7 0 0 -1 0.000 0 0 -1 0 0 3 - 5850 3150 6150 3300 6450 3150 -2 1 0 1 -1 7 0 0 -1 0.000 0 0 -1 1 1 2 - 0 0 1.00 60.00 120.00 - 0 0 1.00 60.00 120.00 - 7425 1200 7725 1650 -2 1 0 1 -1 7 0 0 -1 0.000 0 0 -1 1 1 2 - 0 0 1.00 60.00 120.00 - 0 0 1.00 60.00 120.00 - 7425 1050 8775 1950 -2 1 0 1 -1 7 0 0 -1 0.000 0 0 -1 1 1 2 - 0 0 1.00 60.00 120.00 - 0 0 1.00 60.00 120.00 - 4800 1050 3450 1950 -2 1 0 1 -1 7 0 0 -1 0.000 0 0 -1 1 1 2 - 0 0 1.00 60.00 120.00 - 0 0 1.00 60.00 120.00 - 4875 1200 4575 1650 diff --git a/topc-2.5.2/doc/texinfo.tex b/topc-2.5.2/doc/texinfo.tex deleted file mode 100644 index 99113dd7..00000000 --- a/topc-2.5.2/doc/texinfo.tex +++ /dev/null @@ -1,6325 +0,0 @@ -% texinfo.tex -- TeX macros to handle Texinfo files. -% -% Load plain if necessary, i.e., if running under initex. -\expandafter\ifx\csname fmtname\endcsname\relax\input plain\fi -% -\def\texinfoversion{2002-03-01.06} -% -% Copyright (C) 1985, 86, 88, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, -% 2000, 01, 02 Free Software Foundation, Inc. -% -% This texinfo.tex file is free software; you can redistribute it and/or -% modify it under the terms of the GNU General Public License as -% published by the Free Software Foundation; either version 2, or (at -% your option) any later version. -% -% This texinfo.tex file is distributed in the hope that it will be -% useful, but WITHOUT ANY WARRANTY; without even the implied warranty -% of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -% General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with this texinfo.tex file; see the file COPYING. If not, write -% to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, -% Boston, MA 02111-1307, USA. -% -% In other words, you are welcome to use, share and improve this program. -% You are forbidden to forbid anyone else to use, share and improve -% what you give them. Help stamp out software-hoarding! -% -% Please try the latest version of texinfo.tex before submitting bug -% reports; you can get the latest version from: -% ftp://ftp.gnu.org/gnu/texinfo.tex -% (and all GNU mirrors, see http://www.gnu.org/order/ftp.html) -% ftp://texinfo.org/texinfo/texinfo.tex -% ftp://tug.org/tex/texinfo.tex -% (and all CTAN mirrors, see http://www.ctan.org), -% and /home/gd/gnu/doc/texinfo.tex on the GNU machines. -% -% The texinfo.tex in any given Texinfo distribution could well be out -% of date, so if that's what you're using, please check. -% -% Texinfo has a small home page at http://texinfo.org/ and also -% http://www.gnu.org/software/texinfo. -% -% Send bug reports to bug-texinfo@gnu.org. Please include including a -% complete document in each bug report with which we can reproduce the -% problem. Patches are, of course, greatly appreciated. -% -% To process a Texinfo manual with TeX, it's most reliable to use the -% texi2dvi shell script that comes with the distribution. For a simple -% manual foo.texi, however, you can get away with this: -% tex foo.texi -% texindex foo.?? -% tex foo.texi -% tex foo.texi -% dvips foo.dvi -o # or whatever, to process the dvi file; this makes foo.ps. -% The extra TeX runs get the cross-reference information correct. -% Sometimes one run after texindex suffices, and sometimes you need more -% than two; texi2dvi does it as many times as necessary. -% -% It is possible to adapt texinfo.tex for other languages. You can get -% the existing language-specific files from the full Texinfo distribution. - -\message{Loading texinfo [version \texinfoversion]:} - -% If in a .fmt file, print the version number -% and turn on active characters that we couldn't do earlier because -% they might have appeared in the input file name. -\everyjob{\message{[Texinfo version \texinfoversion]}% - \catcode`+=\active \catcode`\_=\active} - -% Save some parts of plain tex whose names we will redefine. -\let\ptexb=\b -\let\ptexbullet=\bullet -\let\ptexc=\c -\let\ptexcomma=\, -\let\ptexdot=\. -\let\ptexdots=\dots -\let\ptexend=\end -\let\ptexequiv=\equiv -\let\ptexexclam=\! -\let\ptexi=\i -\let\ptexlbrace=\{ -\let\ptexrbrace=\} -\let\ptexstar=\* -\let\ptext=\t - -% We never want plain's outer \+ definition in Texinfo. -% For @tex, we can use \tabalign. -\let\+ = \relax - -\message{Basics,} -\chardef\other=12 - -% If this character appears in an error message or help string, it -% starts a new line in the output. -\newlinechar = `^^J - -% Set up fixed words for English if not already set. -\ifx\putwordAppendix\undefined \gdef\putwordAppendix{Appendix}\fi -\ifx\putwordChapter\undefined \gdef\putwordChapter{Chapter}\fi -\ifx\putwordfile\undefined \gdef\putwordfile{file}\fi -\ifx\putwordin\undefined \gdef\putwordin{in}\fi -\ifx\putwordIndexIsEmpty\undefined \gdef\putwordIndexIsEmpty{(Index is empty)}\fi -\ifx\putwordIndexNonexistent\undefined \gdef\putwordIndexNonexistent{(Index is nonexistent)}\fi -\ifx\putwordInfo\undefined \gdef\putwordInfo{Info}\fi -\ifx\putwordInstanceVariableof\undefined \gdef\putwordInstanceVariableof{Instance Variable of}\fi -\ifx\putwordMethodon\undefined \gdef\putwordMethodon{Method on}\fi -\ifx\putwordNoTitle\undefined \gdef\putwordNoTitle{No Title}\fi -\ifx\putwordof\undefined \gdef\putwordof{of}\fi -\ifx\putwordon\undefined \gdef\putwordon{on}\fi -\ifx\putwordpage\undefined \gdef\putwordpage{page}\fi -\ifx\putwordsection\undefined \gdef\putwordsection{section}\fi -\ifx\putwordSection\undefined \gdef\putwordSection{Section}\fi -\ifx\putwordsee\undefined \gdef\putwordsee{see}\fi -\ifx\putwordSee\undefined \gdef\putwordSee{See}\fi -\ifx\putwordShortTOC\undefined \gdef\putwordShortTOC{Short Contents}\fi -\ifx\putwordTOC\undefined \gdef\putwordTOC{Table of Contents}\fi -% -\ifx\putwordMJan\undefined \gdef\putwordMJan{January}\fi -\ifx\putwordMFeb\undefined \gdef\putwordMFeb{February}\fi -\ifx\putwordMMar\undefined \gdef\putwordMMar{March}\fi -\ifx\putwordMApr\undefined \gdef\putwordMApr{April}\fi -\ifx\putwordMMay\undefined \gdef\putwordMMay{May}\fi -\ifx\putwordMJun\undefined \gdef\putwordMJun{June}\fi -\ifx\putwordMJul\undefined \gdef\putwordMJul{July}\fi -\ifx\putwordMAug\undefined \gdef\putwordMAug{August}\fi -\ifx\putwordMSep\undefined \gdef\putwordMSep{September}\fi -\ifx\putwordMOct\undefined \gdef\putwordMOct{October}\fi -\ifx\putwordMNov\undefined \gdef\putwordMNov{November}\fi -\ifx\putwordMDec\undefined \gdef\putwordMDec{December}\fi -% -\ifx\putwordDefmac\undefined \gdef\putwordDefmac{Macro}\fi -\ifx\putwordDefspec\undefined \gdef\putwordDefspec{Special Form}\fi -\ifx\putwordDefvar\undefined \gdef\putwordDefvar{Variable}\fi -\ifx\putwordDefopt\undefined \gdef\putwordDefopt{User Option}\fi -\ifx\putwordDeftypevar\undefined\gdef\putwordDeftypevar{Variable}\fi -\ifx\putwordDeffunc\undefined \gdef\putwordDeffunc{Function}\fi -\ifx\putwordDeftypefun\undefined\gdef\putwordDeftypefun{Function}\fi - -% Ignore a token. -% -\def\gobble#1{} - -\hyphenation{ap-pen-dix} -\hyphenation{mini-buf-fer mini-buf-fers} -\hyphenation{eshell} -\hyphenation{white-space} - -% Margin to add to right of even pages, to left of odd pages. -\newdimen \bindingoffset -\newdimen \normaloffset -\newdimen\pagewidth \newdimen\pageheight - -% Sometimes it is convenient to have everything in the transcript file -% and nothing on the terminal. We don't just call \tracingall here, -% since that produces some useless output on the terminal. -% -\def\gloggingall{\begingroup \globaldefs = 1 \loggingall \endgroup}% -\ifx\eTeXversion\undefined -\def\loggingall{\tracingcommands2 \tracingstats2 - \tracingpages1 \tracingoutput1 \tracinglostchars1 - \tracingmacros2 \tracingparagraphs1 \tracingrestores1 - \showboxbreadth\maxdimen\showboxdepth\maxdimen -}% -\else -\def\loggingall{\tracingcommands3 \tracingstats2 - \tracingpages1 \tracingoutput1 \tracinglostchars1 - \tracingmacros2 \tracingparagraphs1 \tracingrestores1 - \tracingscantokens1 \tracingassigns1 \tracingifs1 - \tracinggroups1 \tracingnesting2 - \showboxbreadth\maxdimen\showboxdepth\maxdimen -}% -\fi - -% add check for \lastpenalty to plain's definitions. If the last thing -% we did was a \nobreak, we don't want to insert more space. -% -\def\smallbreak{\ifnum\lastpenalty<10000\par\ifdim\lastskip<\smallskipamount - \removelastskip\penalty-50\smallskip\fi\fi} -\def\medbreak{\ifnum\lastpenalty<10000\par\ifdim\lastskip<\medskipamount - \removelastskip\penalty-100\medskip\fi\fi} -\def\bigbreak{\ifnum\lastpenalty<10000\par\ifdim\lastskip<\bigskipamount - \removelastskip\penalty-200\bigskip\fi\fi} - -% For @cropmarks command. -% Do @cropmarks to get crop marks. -% -\newif\ifcropmarks -\let\cropmarks = \cropmarkstrue -% -% Dimensions to add cropmarks at corners. -% Added by P. A. MacKay, 12 Nov. 1986 -% -\newdimen\outerhsize \newdimen\outervsize % set by the paper size routines -\newdimen\cornerlong \cornerlong=1pc -\newdimen\cornerthick \cornerthick=.3pt -\newdimen\topandbottommargin \topandbottommargin=.75in - -% Main output routine. -\chardef\PAGE = 255 -\output = {\onepageout{\pagecontents\PAGE}} - -\newbox\headlinebox -\newbox\footlinebox - -% \onepageout takes a vbox as an argument. Note that \pagecontents -% does insertions, but you have to call it yourself. -\def\onepageout#1{% - \ifcropmarks \hoffset=0pt \else \hoffset=\normaloffset \fi - % - \ifodd\pageno \advance\hoffset by \bindingoffset - \else \advance\hoffset by -\bindingoffset\fi - % - % Do this outside of the \shipout so @code etc. will be expanded in - % the headline as they should be, not taken literally (outputting ''code). - \setbox\headlinebox = \vbox{\let\hsize=\pagewidth \makeheadline}% - \setbox\footlinebox = \vbox{\let\hsize=\pagewidth \makefootline}% - % - {% - % Have to do this stuff outside the \shipout because we want it to - % take effect in \write's, yet the group defined by the \vbox ends - % before the \shipout runs. - % - \escapechar = `\\ % use backslash in output files. - \indexdummies % don't expand commands in the output. - \normalturnoffactive % \ in index entries must not stay \, e.g., if - % the page break happens to be in the middle of an example. - \shipout\vbox{% - % Do this early so pdf references go to the beginning of the page. - \ifpdfmakepagedest \pdfmkdest{\the\pageno} \fi - % - \ifcropmarks \vbox to \outervsize\bgroup - \hsize = \outerhsize - \vskip-\topandbottommargin - \vtop to0pt{% - \line{\ewtop\hfil\ewtop}% - \nointerlineskip - \line{% - \vbox{\moveleft\cornerthick\nstop}% - \hfill - \vbox{\moveright\cornerthick\nstop}% - }% - \vss}% - \vskip\topandbottommargin - \line\bgroup - \hfil % center the page within the outer (page) hsize. - \ifodd\pageno\hskip\bindingoffset\fi - \vbox\bgroup - \fi - % - \unvbox\headlinebox - \pagebody{#1}% - \ifdim\ht\footlinebox > 0pt - % Only leave this space if the footline is nonempty. - % (We lessened \vsize for it in \oddfootingxxx.) - % The \baselineskip=24pt in plain's \makefootline has no effect. - \vskip 2\baselineskip - \unvbox\footlinebox - \fi - % - \ifcropmarks - \egroup % end of \vbox\bgroup - \hfil\egroup % end of (centering) \line\bgroup - \vskip\topandbottommargin plus1fill minus1fill - \boxmaxdepth = \cornerthick - \vbox to0pt{\vss - \line{% - \vbox{\moveleft\cornerthick\nsbot}% - \hfill - \vbox{\moveright\cornerthick\nsbot}% - }% - \nointerlineskip - \line{\ewbot\hfil\ewbot}% - }% - \egroup % \vbox from first cropmarks clause - \fi - }% end of \shipout\vbox - }% end of group with \turnoffactive - \advancepageno - \ifnum\outputpenalty>-20000 \else\dosupereject\fi -} - -\newinsert\margin \dimen\margin=\maxdimen - -\def\pagebody#1{\vbox to\pageheight{\boxmaxdepth=\maxdepth #1}} -{\catcode`\@ =11 -\gdef\pagecontents#1{\ifvoid\topins\else\unvbox\topins\fi -% marginal hacks, juha@viisa.uucp (Juha Takala) -\ifvoid\margin\else % marginal info is present - \rlap{\kern\hsize\vbox to\z@{\kern1pt\box\margin \vss}}\fi -\dimen@=\dp#1 \unvbox#1 -\ifvoid\footins\else\vskip\skip\footins\footnoterule \unvbox\footins\fi -\ifr@ggedbottom \kern-\dimen@ \vfil \fi} -} - -% Here are the rules for the cropmarks. Note that they are -% offset so that the space between them is truly \outerhsize or \outervsize -% (P. A. MacKay, 12 November, 1986) -% -\def\ewtop{\vrule height\cornerthick depth0pt width\cornerlong} -\def\nstop{\vbox - {\hrule height\cornerthick depth\cornerlong width\cornerthick}} -\def\ewbot{\vrule height0pt depth\cornerthick width\cornerlong} -\def\nsbot{\vbox - {\hrule height\cornerlong depth\cornerthick width\cornerthick}} - -% Parse an argument, then pass it to #1. The argument is the rest of -% the input line (except we remove a trailing comment). #1 should be a -% macro which expects an ordinary undelimited TeX argument. -% -\def\parsearg#1{% - \let\next = #1% - \begingroup - \obeylines - \futurelet\temp\parseargx -} - -% If the next token is an obeyed space (from an @example environment or -% the like), remove it and recurse. Otherwise, we're done. -\def\parseargx{% - % \obeyedspace is defined far below, after the definition of \sepspaces. - \ifx\obeyedspace\temp - \expandafter\parseargdiscardspace - \else - \expandafter\parseargline - \fi -} - -% Remove a single space (as the delimiter token to the macro call). -{\obeyspaces % - \gdef\parseargdiscardspace {\futurelet\temp\parseargx}} - -{\obeylines % - \gdef\parseargline#1^^M{% - \endgroup % End of the group started in \parsearg. - % - % First remove any @c comment, then any @comment. - % Result of each macro is put in \toks0. - \argremovec #1\c\relax % - \expandafter\argremovecomment \the\toks0 \comment\relax % - % - % Call the caller's macro, saved as \next in \parsearg. - \expandafter\next\expandafter{\the\toks0}% - }% -} - -% Since all \c{,omment} does is throw away the argument, we can let TeX -% do that for us. The \relax here is matched by the \relax in the call -% in \parseargline; it could be more or less anything, its purpose is -% just to delimit the argument to the \c. -\def\argremovec#1\c#2\relax{\toks0 = {#1}} -\def\argremovecomment#1\comment#2\relax{\toks0 = {#1}} - -% \argremovec{,omment} might leave us with trailing spaces, though; e.g., -% @end itemize @c foo -% will have two active spaces as part of the argument with the -% `itemize'. Here we remove all active spaces from #1, and assign the -% result to \toks0. -% -% This loses if there are any *other* active characters besides spaces -% in the argument -- _ ^ +, for example -- since they get expanded. -% Fortunately, Texinfo does not define any such commands. (If it ever -% does, the catcode of the characters in questionwill have to be changed -% here.) But this means we cannot call \removeactivespaces as part of -% \argremovec{,omment}, since @c uses \parsearg, and thus the argument -% that \parsearg gets might well have any character at all in it. -% -\def\removeactivespaces#1{% - \begingroup - \ignoreactivespaces - \edef\temp{#1}% - \global\toks0 = \expandafter{\temp}% - \endgroup -} - -% Change the active space to expand to nothing. -% -\begingroup - \obeyspaces - \gdef\ignoreactivespaces{\obeyspaces\let =\empty} -\endgroup - - -\def\flushcr{\ifx\par\lisppar \def\next##1{}\else \let\next=\relax \fi \next} - -%% These are used to keep @begin/@end levels from running away -%% Call \inENV within environments (after a \begingroup) -\newif\ifENV \ENVfalse \def\inENV{\ifENV\relax\else\ENVtrue\fi} -\def\ENVcheck{% -\ifENV\errmessage{Still within an environment; press RETURN to continue} -\endgroup\fi} % This is not perfect, but it should reduce lossage - -% @begin foo is the same as @foo, for now. -\newhelp\EMsimple{Press RETURN to continue.} - -\outer\def\begin{\parsearg\beginxxx} - -\def\beginxxx #1{% -\expandafter\ifx\csname #1\endcsname\relax -{\errhelp=\EMsimple \errmessage{Undefined command @begin #1}}\else -\csname #1\endcsname\fi} - -% @end foo executes the definition of \Efoo. -% -\def\end{\parsearg\endxxx} -\def\endxxx #1{% - \removeactivespaces{#1}% - \edef\endthing{\the\toks0}% - % - \expandafter\ifx\csname E\endthing\endcsname\relax - \expandafter\ifx\csname \endthing\endcsname\relax - % There's no \foo, i.e., no ``environment'' foo. - \errhelp = \EMsimple - \errmessage{Undefined command `@end \endthing'}% - \else - \unmatchedenderror\endthing - \fi - \else - % Everything's ok; the right environment has been started. - \csname E\endthing\endcsname - \fi -} - -% There is an environment #1, but it hasn't been started. Give an error. -% -\def\unmatchedenderror#1{% - \errhelp = \EMsimple - \errmessage{This `@end #1' doesn't have a matching `@#1'}% -} - -% Define the control sequence \E#1 to give an unmatched @end error. -% -\def\defineunmatchedend#1{% - \expandafter\def\csname E#1\endcsname{\unmatchedenderror{#1}}% -} - - -% Single-spacing is done by various environments (specifically, in -% \nonfillstart and \quotations). -\newskip\singlespaceskip \singlespaceskip = 12.5pt -\def\singlespace{% - % Why was this kern here? It messes up equalizing space above and below - % environments. --karl, 6may93 - %{\advance \baselineskip by -\singlespaceskip - %\kern \baselineskip}% - \setleading\singlespaceskip -} - -%% Simple single-character @ commands - -% @@ prints an @ -% Kludge this until the fonts are right (grr). -\def\@{{\tt\char64}} - -% This is turned off because it was never documented -% and you can use @w{...} around a quote to suppress ligatures. -%% Define @` and @' to be the same as ` and ' -%% but suppressing ligatures. -%\def\`{{`}} -%\def\'{{'}} - -% Used to generate quoted braces. -\def\mylbrace {{\tt\char123}} -\def\myrbrace {{\tt\char125}} -\let\{=\mylbrace -\let\}=\myrbrace -\begingroup - % Definitions to produce actual \{ & \} command in an index. - \catcode`\{ = 12 \catcode`\} = 12 - \catcode`\[ = 1 \catcode`\] = 2 - \catcode`\@ = 0 \catcode`\\ = 12 - @gdef@lbracecmd[\{]% - @gdef@rbracecmd[\}]% -@endgroup - -% Accents: @, @dotaccent @ringaccent @ubaraccent @udotaccent -% Others are defined by plain TeX: @` @' @" @^ @~ @= @v @H. -\let\, = \c -\let\dotaccent = \. -\def\ringaccent#1{{\accent23 #1}} -\let\tieaccent = \t -\let\ubaraccent = \b -\let\udotaccent = \d - -% Other special characters: @questiondown @exclamdown -% Plain TeX defines: @AA @AE @O @OE @L (and lowercase versions) @ss. -\def\questiondown{?`} -\def\exclamdown{!`} - -% Dotless i and dotless j, used for accents. -\def\imacro{i} -\def\jmacro{j} -\def\dotless#1{% - \def\temp{#1}% - \ifx\temp\imacro \ptexi - \else\ifx\temp\jmacro \j - \else \errmessage{@dotless can be used only with i or j}% - \fi\fi -} - -% Be sure we're in horizontal mode when doing a tie, since we make space -% equivalent to this in @example-like environments. Otherwise, a space -% at the beginning of a line will start with \penalty -- and -% since \penalty is valid in vertical mode, we'd end up putting the -% penalty on the vertical list instead of in the new paragraph. -{\catcode`@ = 11 - % Avoid using \@M directly, because that causes trouble - % if the definition is written into an index file. - \global\let\tiepenalty = \@M - \gdef\tie{\leavevmode\penalty\tiepenalty\ } -} - -% @: forces normal size whitespace following. -\def\:{\spacefactor=1000 } - -% @* forces a line break. -\def\*{\hfil\break\hbox{}\ignorespaces} - -% @. is an end-of-sentence period. -\def\.{.\spacefactor=3000 } - -% @! is an end-of-sentence bang. -\def\!{!\spacefactor=3000 } - -% @? is an end-of-sentence query. -\def\?{?\spacefactor=3000 } - -% @w prevents a word break. Without the \leavevmode, @w at the -% beginning of a paragraph, when TeX is still in vertical mode, would -% produce a whole line of output instead of starting the paragraph. -\def\w#1{\leavevmode\hbox{#1}} - -% @group ... @end group forces ... to be all on one page, by enclosing -% it in a TeX vbox. We use \vtop instead of \vbox to construct the box -% to keep its height that of a normal line. According to the rules for -% \topskip (p.114 of the TeXbook), the glue inserted is -% max (\topskip - \ht (first item), 0). If that height is large, -% therefore, no glue is inserted, and the space between the headline and -% the text is small, which looks bad. -% -\def\group{\begingroup - \ifnum\catcode13=\active \else - \errhelp = \groupinvalidhelp - \errmessage{@group invalid in context where filling is enabled}% - \fi - % - % The \vtop we start below produces a box with normal height and large - % depth; thus, TeX puts \baselineskip glue before it, and (when the - % next line of text is done) \lineskip glue after it. (See p.82 of - % the TeXbook.) Thus, space below is not quite equal to space - % above. But it's pretty close. - \def\Egroup{% - \egroup % End the \vtop. - \endgroup % End the \group. - }% - % - \vtop\bgroup - % We have to put a strut on the last line in case the @group is in - % the midst of an example, rather than completely enclosing it. - % Otherwise, the interline space between the last line of the group - % and the first line afterwards is too small. But we can't put the - % strut in \Egroup, since there it would be on a line by itself. - % Hence this just inserts a strut at the beginning of each line. - \everypar = {\strut}% - % - % Since we have a strut on every line, we don't need any of TeX's - % normal interline spacing. - \offinterlineskip - % - % OK, but now we have to do something about blank - % lines in the input in @example-like environments, which normally - % just turn into \lisppar, which will insert no space now that we've - % turned off the interline space. Simplest is to make them be an - % empty paragraph. - \ifx\par\lisppar - \edef\par{\leavevmode \par}% - % - % Reset ^^M's definition to new definition of \par. - \obeylines - \fi - % - % Do @comment since we are called inside an environment such as - % @example, where each end-of-line in the input causes an - % end-of-line in the output. We don't want the end-of-line after - % the `@group' to put extra space in the output. Since @group - % should appear on a line by itself (according to the Texinfo - % manual), we don't worry about eating any user text. - \comment -} -% -% TeX puts in an \escapechar (i.e., `@') at the beginning of the help -% message, so this ends up printing `@group can only ...'. -% -\newhelp\groupinvalidhelp{% -group can only be used in environments such as @example,^^J% -where each line of input produces a line of output.} - -% @need space-in-mils -% forces a page break if there is not space-in-mils remaining. - -\newdimen\mil \mil=0.001in - -\def\need{\parsearg\needx} - -% Old definition--didn't work. -%\def\needx #1{\par % -%% This method tries to make TeX break the page naturally -%% if the depth of the box does not fit. -%{\baselineskip=0pt% -%\vtop to #1\mil{\vfil}\kern -#1\mil\nobreak -%\prevdepth=-1000pt -%}} - -\def\needx#1{% - % Ensure vertical mode, so we don't make a big box in the middle of a - % paragraph. - \par - % - % If the @need value is less than one line space, it's useless. - \dimen0 = #1\mil - \dimen2 = \ht\strutbox - \advance\dimen2 by \dp\strutbox - \ifdim\dimen0 > \dimen2 - % - % Do a \strut just to make the height of this box be normal, so the - % normal leading is inserted relative to the preceding line. - % And a page break here is fine. - \vtop to #1\mil{\strut\vfil}% - % - % TeX does not even consider page breaks if a penalty added to the - % main vertical list is 10000 or more. But in order to see if the - % empty box we just added fits on the page, we must make it consider - % page breaks. On the other hand, we don't want to actually break the - % page after the empty box. So we use a penalty of 9999. - % - % There is an extremely small chance that TeX will actually break the - % page at this \penalty, if there are no other feasible breakpoints in - % sight. (If the user is using lots of big @group commands, which - % almost-but-not-quite fill up a page, TeX will have a hard time doing - % good page breaking, for example.) However, I could not construct an - % example where a page broke at this \penalty; if it happens in a real - % document, then we can reconsider our strategy. - \penalty9999 - % - % Back up by the size of the box, whether we did a page break or not. - \kern -#1\mil - % - % Do not allow a page break right after this kern. - \nobreak - \fi -} - -% @br forces paragraph break - -\let\br = \par - -% @dots{} output an ellipsis using the current font. -% We do .5em per period so that it has the same spacing in a typewriter -% font as three actual period characters. -% -\def\dots{% - \leavevmode - \hbox to 1.5em{% - \hskip 0pt plus 0.25fil minus 0.25fil - .\hss.\hss.% - \hskip 0pt plus 0.5fil minus 0.5fil - }% -} - -% @enddots{} is an end-of-sentence ellipsis. -% -\def\enddots{% - \leavevmode - \hbox to 2em{% - \hskip 0pt plus 0.25fil minus 0.25fil - .\hss.\hss.\hss.% - \hskip 0pt plus 0.5fil minus 0.5fil - }% - \spacefactor=3000 -} - - -% @page forces the start of a new page -% -\def\page{\par\vfill\supereject} - -% @exdent text.... -% outputs text on separate line in roman font, starting at standard page margin - -% This records the amount of indent in the innermost environment. -% That's how much \exdent should take out. -\newskip\exdentamount - -% This defn is used inside fill environments such as @defun. -\def\exdent{\parsearg\exdentyyy} -\def\exdentyyy #1{{\hfil\break\hbox{\kern -\exdentamount{\rm#1}}\hfil\break}} - -% This defn is used inside nofill environments such as @example. -\def\nofillexdent{\parsearg\nofillexdentyyy} -\def\nofillexdentyyy #1{{\advance \leftskip by -\exdentamount -\leftline{\hskip\leftskip{\rm#1}}}} - -% @inmargin{WHICH}{TEXT} puts TEXT in the WHICH margin next to the current -% paragraph. For more general purposes, use the \margin insertion -% class. WHICH is `l' or `r'. -% -\newskip\inmarginspacing \inmarginspacing=1cm -\def\strutdepth{\dp\strutbox} -% -\def\doinmargin#1#2{\strut\vadjust{% - \nobreak - \kern-\strutdepth - \vtop to \strutdepth{% - \baselineskip=\strutdepth - \vss - % if you have multiple lines of stuff to put here, you'll need to - % make the vbox yourself of the appropriate size. - \ifx#1l% - \llap{\ignorespaces #2\hskip\inmarginspacing}% - \else - \rlap{\hskip\hsize \hskip\inmarginspacing \ignorespaces #2}% - \fi - \null - }% -}} -\def\inleftmargin{\doinmargin l} -\def\inrightmargin{\doinmargin r} -% -% @inmargin{TEXT [, RIGHT-TEXT]} -% (if RIGHT-TEXT is given, use TEXT for left page, RIGHT-TEXT for right; -% else use TEXT for both). -% -\def\inmargin#1{\parseinmargin #1,,\finish} -\def\parseinmargin#1,#2,#3\finish{% not perfect, but better than nothing. - \setbox0 = \hbox{\ignorespaces #2}% - \ifdim\wd0 > 0pt - \def\lefttext{#1}% have both texts - \def\righttext{#2}% - \else - \def\lefttext{#1}% have only one text - \def\righttext{#1}% - \fi - % - \ifodd\pageno - \def\temp{\inrightmargin\righttext}% odd page -> outside is right margin - \else - \def\temp{\inleftmargin\lefttext}% - \fi - \temp -} - -% @include file insert text of that file as input. -% Allow normal characters that we make active in the argument (a file name). -\def\include{\begingroup - \catcode`\\=12 - \catcode`~=12 - \catcode`^=12 - \catcode`_=12 - \catcode`|=12 - \catcode`<=12 - \catcode`>=12 - \catcode`+=12 - \parsearg\includezzz} -% Restore active chars for included file. -\def\includezzz#1{\endgroup\begingroup - % Read the included file in a group so nested @include's work. - \def\thisfile{#1}% - \input\thisfile -\endgroup} - -\def\thisfile{} - -% @center line outputs that line, centered - -\def\center{\parsearg\centerzzz} -\def\centerzzz #1{{\advance\hsize by -\leftskip -\advance\hsize by -\rightskip -\centerline{#1}}} - -% @sp n outputs n lines of vertical space - -\def\sp{\parsearg\spxxx} -\def\spxxx #1{\vskip #1\baselineskip} - -% @comment ...line which is ignored... -% @c is the same as @comment -% @ignore ... @end ignore is another way to write a comment - -\def\comment{\begingroup \catcode`\^^M=\other% -\catcode`\@=\other \catcode`\{=\other \catcode`\}=\other% -\commentxxx} -{\catcode`\^^M=\other \gdef\commentxxx#1^^M{\endgroup}} - -\let\c=\comment - -% @paragraphindent NCHARS -% We'll use ems for NCHARS, close enough. -% We cannot implement @paragraphindent asis, though. -% -\def\asisword{asis} % no translation, these are keywords -\def\noneword{none} -% -\def\paragraphindent{\parsearg\doparagraphindent} -\def\doparagraphindent#1{% - \def\temp{#1}% - \ifx\temp\asisword - \else - \ifx\temp\noneword - \defaultparindent = 0pt - \else - \defaultparindent = #1em - \fi - \fi - \parindent = \defaultparindent -} - -% @exampleindent NCHARS -% We'll use ems for NCHARS like @paragraphindent. -% It seems @exampleindent asis isn't necessary, but -% I preserve it to make it similar to @paragraphindent. -\def\exampleindent{\parsearg\doexampleindent} -\def\doexampleindent#1{% - \def\temp{#1}% - \ifx\temp\asisword - \else - \ifx\temp\noneword - \lispnarrowing = 0pt - \else - \lispnarrowing = #1em - \fi - \fi -} - -% @asis just yields its argument. Used with @table, for example. -% -\def\asis#1{#1} - -% @math outputs its argument in math mode. -% We don't use $'s directly in the definition of \math because we need -% to set catcodes according to plain TeX first, to allow for subscripts, -% superscripts, special math chars, etc. -% -% @math does not do math typesetting in section titles, index -% entries, and other such contexts where the catcodes are set before -% @math gets a chance to work. This could perhaps be fixed, but for now -% at least we can have real math in the main text, where it's needed most. -% -% -\let\implicitmath = $%$ font-lock fix -% -% One complication: _ usually means subscripts, but it could also mean -% an actual _ character, as in @math{@var{some_variable} + 1}. So make -% _ within @math be active (mathcode "8000), and distinguish by seeing -% if the current family is \slfam, which is what @var uses. -% -{\catcode95 = \active % 95 = _ -\gdef\mathunderscore{% - \catcode95=\active - \def_{\ifnum\fam=\slfam\_\else\sb\fi}% -}} -% -\def\math{\tex\mathcode`\_="8000\mathunderscore \implicitmath\finishmath} -\def\finishmath#1{#1\implicitmath\Etex} - -% @bullet and @minus need the same treatment as @math, just above. -\def\bullet{\implicitmath\ptexbullet\implicitmath} -\def\minus{\implicitmath-\implicitmath} - -% @refill is a no-op. -\let\refill=\relax - -% If working on a large document in chapters, it is convenient to -% be able to disable indexing, cross-referencing, and contents, for test runs. -% This is done with @novalidate (before @setfilename). -% -\newif\iflinks \linkstrue % by default we want the aux files. -\let\novalidate = \linksfalse - -% @setfilename is done at the beginning of every texinfo file. -% So open here the files we need to have open while reading the input. -% This makes it possible to make a .fmt file for texinfo. -\def\setfilename{% - \iflinks - \readauxfile - \fi % \openindices needs to do some work in any case. - \openindices - \fixbackslash % Turn off hack to swallow `\input texinfo'. - \global\let\setfilename=\comment % Ignore extra @setfilename cmds. - % - % If texinfo.cnf is present on the system, read it. - % Useful for site-wide @afourpaper, etc. - % Just to be on the safe side, close the input stream before the \input. - \openin 1 texinfo.cnf - \ifeof1 \let\temp=\relax \else \def\temp{\input texinfo.cnf }\fi - \closein1 - \temp - % - \comment % Ignore the actual filename. -} - -% Called from \setfilename. -% -\def\openindices{% - \newindex{cp}% - \newcodeindex{fn}% - \newcodeindex{vr}% - \newcodeindex{tp}% - \newcodeindex{ky}% - \newcodeindex{pg}% -} - -% @bye. -\outer\def\bye{\pagealignmacro\tracingstats=1\ptexend} - - -\message{pdf,} -% adobe `portable' document format -\newcount\tempnum -\newcount\lnkcount -\newtoks\filename -\newcount\filenamelength -\newcount\pgn -\newtoks\toksA -\newtoks\toksB -\newtoks\toksC -\newtoks\toksD -\newbox\boxA -\newcount\countA -\newif\ifpdf -\newif\ifpdfmakepagedest - -\ifx\pdfoutput\undefined - \pdffalse - \let\pdfmkdest = \gobble - \let\pdfurl = \gobble - \let\endlink = \relax - \let\linkcolor = \relax - \let\pdfmakeoutlines = \relax -\else - \pdftrue - \pdfoutput = 1 - \input pdfcolor - \def\dopdfimage#1#2#3{% - \def\imagewidth{#2}% - \def\imageheight{#3}% - % without \immediate, pdftex seg faults when the same image is - % included twice. (Version 3.14159-pre-1.0-unofficial-20010704.) - \ifnum\pdftexversion < 14 - \immediate\pdfimage - \else - \immediate\pdfximage - \fi - \ifx\empty\imagewidth\else width \imagewidth \fi - \ifx\empty\imageheight\else height \imageheight \fi - \ifnum\pdftexversion<13 - #1.pdf% - \else - {#1.pdf}% - \fi - \ifnum\pdftexversion < 14 \else - \pdfrefximage \pdflastximage - \fi} - \def\pdfmkdest#1{{\normalturnoffactive \pdfdest name{#1} xyz}} - \def\pdfmkpgn#1{#1} - \let\linkcolor = \Blue % was Cyan, but that seems light? - \def\endlink{\Black\pdfendlink} - % Adding outlines to PDF; macros for calculating structure of outlines - % come from Petr Olsak - \def\expnumber#1{\expandafter\ifx\csname#1\endcsname\relax 0% - \else \csname#1\endcsname \fi} - \def\advancenumber#1{\tempnum=\expnumber{#1}\relax - \advance\tempnum by1 - \expandafter\xdef\csname#1\endcsname{\the\tempnum}} - \def\pdfmakeoutlines{{% - \openin 1 \jobname.toc - \ifeof 1\else\begingroup - \closein 1 - \indexnofonts - \def\tt{} - \let\_ = \normalunderscore - % Thanh's hack / proper braces in bookmarks - \edef\mylbrace{\iftrue \string{\else}\fi}\let\{=\mylbrace - \edef\myrbrace{\iffalse{\else\string}\fi}\let\}=\myrbrace - % - \def\chapentry ##1##2##3{} - \let\appendixentry = \chapentry - \def\unnumbchapentry ##1##2{} - \def\secentry ##1##2##3##4{\advancenumber{chap##2}} - \def\unnumbsecentry ##1##2{} - \def\subsecentry ##1##2##3##4##5{\advancenumber{sec##2.##3}} - \def\unnumbsubsecentry ##1##2{} - \def\subsubsecentry ##1##2##3##4##5##6{\advancenumber{subsec##2.##3.##4}} - \def\unnumbsubsubsecentry ##1##2{} - \input \jobname.toc - \def\chapentry ##1##2##3{% - \pdfoutline goto name{\pdfmkpgn{##3}}count-\expnumber{chap##2}{##1}} - \let\appendixentry = \chapentry - \def\unnumbchapentry ##1##2{% - \pdfoutline goto name{\pdfmkpgn{##2}}{##1}} - \def\secentry ##1##2##3##4{% - \pdfoutline goto name{\pdfmkpgn{##4}}count-\expnumber{sec##2.##3}{##1}} - \def\unnumbsecentry ##1##2{% - \pdfoutline goto name{\pdfmkpgn{##2}}{##1}} - \def\subsecentry ##1##2##3##4##5{% - \pdfoutline goto name{\pdfmkpgn{##5}}count-\expnumber{subsec##2.##3.##4}{##1}} - \def\unnumbsubsecentry ##1##2{% - \pdfoutline goto name{\pdfmkpgn{##2}}{##1}} - \def\subsubsecentry ##1##2##3##4##5##6{% - \pdfoutline goto name{\pdfmkpgn{##6}}{##1}} - \def\unnumbsubsubsecentry ##1##2{% - \pdfoutline goto name{\pdfmkpgn{##2}}{##1}} - \input \jobname.toc - \endgroup\fi - }} - \def\makelinks #1,{% - \def\params{#1}\def\E{END}% - \ifx\params\E - \let\nextmakelinks=\relax - \else - \let\nextmakelinks=\makelinks - \ifnum\lnkcount>0,\fi - \picknum{#1}% - \startlink attr{/Border [0 0 0]} - goto name{\pdfmkpgn{\the\pgn}}% - \linkcolor #1% - \advance\lnkcount by 1% - \endlink - \fi - \nextmakelinks - } - \def\picknum#1{\expandafter\pn#1} - \def\pn#1{% - \def\p{#1}% - \ifx\p\lbrace - \let\nextpn=\ppn - \else - \let\nextpn=\ppnn - \def\first{#1} - \fi - \nextpn - } - \def\ppn#1{\pgn=#1\gobble} - \def\ppnn{\pgn=\first} - \def\pdfmklnk#1{\lnkcount=0\makelinks #1,END,} - \def\addtokens#1#2{\edef\addtoks{\noexpand#1={\the#1#2}}\addtoks} - \def\skipspaces#1{\def\PP{#1}\def\D{|}% - \ifx\PP\D\let\nextsp\relax - \else\let\nextsp\skipspaces - \ifx\p\space\else\addtokens{\filename}{\PP}% - \advance\filenamelength by 1 - \fi - \fi - \nextsp} - \def\getfilename#1{\filenamelength=0\expandafter\skipspaces#1|\relax} - \ifnum\pdftexversion < 14 - \let \startlink \pdfannotlink - \else - \let \startlink \pdfstartlink - \fi - \def\pdfurl#1{% - \begingroup - \normalturnoffactive\def\@{@}% - \let\value=\expandablevalue - \leavevmode\Red - \startlink attr{/Border [0 0 0]}% - user{/Subtype /Link /A << /S /URI /URI (#1) >>}% - % #1 - \endgroup} - \def\pdfgettoks#1.{\setbox\boxA=\hbox{\toksA={#1.}\toksB={}\maketoks}} - \def\addtokens#1#2{\edef\addtoks{\noexpand#1={\the#1#2}}\addtoks} - \def\adn#1{\addtokens{\toksC}{#1}\global\countA=1\let\next=\maketoks} - \def\poptoks#1#2|ENDTOKS|{\let\first=#1\toksD={#1}\toksA={#2}} - \def\maketoks{% - \expandafter\poptoks\the\toksA|ENDTOKS| - \ifx\first0\adn0 - \else\ifx\first1\adn1 \else\ifx\first2\adn2 \else\ifx\first3\adn3 - \else\ifx\first4\adn4 \else\ifx\first5\adn5 \else\ifx\first6\adn6 - \else\ifx\first7\adn7 \else\ifx\first8\adn8 \else\ifx\first9\adn9 - \else - \ifnum0=\countA\else\makelink\fi - \ifx\first.\let\next=\done\else - \let\next=\maketoks - \addtokens{\toksB}{\the\toksD} - \ifx\first,\addtokens{\toksB}{\space}\fi - \fi - \fi\fi\fi\fi\fi\fi\fi\fi\fi\fi - \next} - \def\makelink{\addtokens{\toksB}% - {\noexpand\pdflink{\the\toksC}}\toksC={}\global\countA=0} - \def\pdflink#1{% - \startlink attr{/Border [0 0 0]} goto name{\pdfmkpgn{#1}} - \linkcolor #1\endlink} - \def\done{\edef\st{\global\noexpand\toksA={\the\toksB}}\st} -\fi % \ifx\pdfoutput - - -\message{fonts,} -% Font-change commands. - -% Texinfo sort of supports the sans serif font style, which plain TeX does not. -% So we set up a \sf analogous to plain's \rm, etc. -\newfam\sffam -\def\sf{\fam=\sffam \tensf} -\let\li = \sf % Sometimes we call it \li, not \sf. - -% We don't need math for this one. -\def\ttsl{\tenttsl} - -% Default leading. -\newdimen\textleading \textleading = 13.2pt - -% Set the baselineskip to #1, and the lineskip and strut size -% correspondingly. There is no deep meaning behind these magic numbers -% used as factors; they just match (closely enough) what Knuth defined. -% -\def\lineskipfactor{.08333} -\def\strutheightpercent{.70833} -\def\strutdepthpercent {.29167} -% -\def\setleading#1{% - \normalbaselineskip = #1\relax - \normallineskip = \lineskipfactor\normalbaselineskip - \normalbaselines - \setbox\strutbox =\hbox{% - \vrule width0pt height\strutheightpercent\baselineskip - depth \strutdepthpercent \baselineskip - }% -} - -% Set the font macro #1 to the font named #2, adding on the -% specified font prefix (normally `cm'). -% #3 is the font's design size, #4 is a scale factor -\def\setfont#1#2#3#4{\font#1=\fontprefix#2#3 scaled #4} - -% Use cm as the default font prefix. -% To specify the font prefix, you must define \fontprefix -% before you read in texinfo.tex. -\ifx\fontprefix\undefined -\def\fontprefix{cm} -\fi -% Support font families that don't use the same naming scheme as CM. -\def\rmshape{r} -\def\rmbshape{bx} %where the normal face is bold -\def\bfshape{b} -\def\bxshape{bx} -\def\ttshape{tt} -\def\ttbshape{tt} -\def\ttslshape{sltt} -\def\itshape{ti} -\def\itbshape{bxti} -\def\slshape{sl} -\def\slbshape{bxsl} -\def\sfshape{ss} -\def\sfbshape{ss} -\def\scshape{csc} -\def\scbshape{csc} - -\newcount\mainmagstep -\ifx\bigger\relax - % not really supported. - \let\mainmagstep=\magstep1 - \setfont\textrm\rmshape{12}{1000} - \setfont\texttt\ttshape{12}{1000} -\else - \mainmagstep=\magstephalf - \setfont\textrm\rmshape{10}{\mainmagstep} - \setfont\texttt\ttshape{10}{\mainmagstep} -\fi -% Instead of cmb10, you many want to use cmbx10. -% cmbx10 is a prettier font on its own, but cmb10 -% looks better when embedded in a line with cmr10. -\setfont\textbf\bfshape{10}{\mainmagstep} -\setfont\textit\itshape{10}{\mainmagstep} -\setfont\textsl\slshape{10}{\mainmagstep} -\setfont\textsf\sfshape{10}{\mainmagstep} -\setfont\textsc\scshape{10}{\mainmagstep} -\setfont\textttsl\ttslshape{10}{\mainmagstep} -\font\texti=cmmi10 scaled \mainmagstep -\font\textsy=cmsy10 scaled \mainmagstep - -% A few fonts for @defun, etc. -\setfont\defbf\bxshape{10}{\magstep1} %was 1314 -\setfont\deftt\ttshape{10}{\magstep1} -\def\df{\let\tentt=\deftt \let\tenbf = \defbf \bf} - -% Fonts for indices, footnotes, small examples (9pt). -\setfont\smallrm\rmshape{9}{1000} -\setfont\smalltt\ttshape{9}{1000} -\setfont\smallbf\bfshape{10}{900} -\setfont\smallit\itshape{9}{1000} -\setfont\smallsl\slshape{9}{1000} -\setfont\smallsf\sfshape{9}{1000} -\setfont\smallsc\scshape{10}{900} -\setfont\smallttsl\ttslshape{10}{900} -\font\smalli=cmmi9 -\font\smallsy=cmsy9 - -% Fonts for small examples (8pt). -\setfont\smallerrm\rmshape{8}{1000} -\setfont\smallertt\ttshape{8}{1000} -\setfont\smallerbf\bfshape{10}{800} -\setfont\smallerit\itshape{8}{1000} -\setfont\smallersl\slshape{8}{1000} -\setfont\smallersf\sfshape{8}{1000} -\setfont\smallersc\scshape{10}{800} -\setfont\smallerttsl\ttslshape{10}{800} -\font\smalleri=cmmi8 -\font\smallersy=cmsy8 - -% Fonts for title page: -\setfont\titlerm\rmbshape{12}{\magstep3} -\setfont\titleit\itbshape{10}{\magstep4} -\setfont\titlesl\slbshape{10}{\magstep4} -\setfont\titlett\ttbshape{12}{\magstep3} -\setfont\titlettsl\ttslshape{10}{\magstep4} -\setfont\titlesf\sfbshape{17}{\magstep1} -\let\titlebf=\titlerm -\setfont\titlesc\scbshape{10}{\magstep4} -\font\titlei=cmmi12 scaled \magstep3 -\font\titlesy=cmsy10 scaled \magstep4 -\def\authorrm{\secrm} - -% Chapter (and unnumbered) fonts (17.28pt). -\setfont\chaprm\rmbshape{12}{\magstep2} -\setfont\chapit\itbshape{10}{\magstep3} -\setfont\chapsl\slbshape{10}{\magstep3} -\setfont\chaptt\ttbshape{12}{\magstep2} -\setfont\chapttsl\ttslshape{10}{\magstep3} -\setfont\chapsf\sfbshape{17}{1000} -\let\chapbf=\chaprm -\setfont\chapsc\scbshape{10}{\magstep3} -\font\chapi=cmmi12 scaled \magstep2 -\font\chapsy=cmsy10 scaled \magstep3 - -% Section fonts (14.4pt). -\setfont\secrm\rmbshape{12}{\magstep1} -\setfont\secit\itbshape{10}{\magstep2} -\setfont\secsl\slbshape{10}{\magstep2} -\setfont\sectt\ttbshape{12}{\magstep1} -\setfont\secttsl\ttslshape{10}{\magstep2} -\setfont\secsf\sfbshape{12}{\magstep1} -\let\secbf\secrm -\setfont\secsc\scbshape{10}{\magstep2} -\font\seci=cmmi12 scaled \magstep1 -\font\secsy=cmsy10 scaled \magstep2 - -% Subsection fonts (13.15pt). -\setfont\ssecrm\rmbshape{12}{\magstephalf} -\setfont\ssecit\itbshape{10}{1315} -\setfont\ssecsl\slbshape{10}{1315} -\setfont\ssectt\ttbshape{12}{\magstephalf} -\setfont\ssecttsl\ttslshape{10}{1315} -\setfont\ssecsf\sfbshape{12}{\magstephalf} -\let\ssecbf\ssecrm -\setfont\ssecsc\scbshape{10}{\magstep1} -\font\sseci=cmmi12 scaled \magstephalf -\font\ssecsy=cmsy10 scaled 1315 -% The smallcaps and symbol fonts should actually be scaled \magstep1.5, -% but that is not a standard magnification. - -% In order for the font changes to affect most math symbols and letters, -% we have to define the \textfont of the standard families. Since -% texinfo doesn't allow for producing subscripts and superscripts except -% in the main text, we don't bother to reset \scriptfont and -% \scriptscriptfont (which would also require loading a lot more fonts). -% -\def\resetmathfonts{% - \textfont0=\tenrm \textfont1=\teni \textfont2=\tensy - \textfont\itfam=\tenit \textfont\slfam=\tensl \textfont\bffam=\tenbf - \textfont\ttfam=\tentt \textfont\sffam=\tensf -} - -% The font-changing commands redefine the meanings of \tenSTYLE, instead -% of just \STYLE. We do this so that font changes will continue to work -% in math mode, where it is the current \fam that is relevant in most -% cases, not the current font. Plain TeX does \def\bf{\fam=\bffam -% \tenbf}, for example. By redefining \tenbf, we obviate the need to -% redefine \bf itself. -\def\textfonts{% - \let\tenrm=\textrm \let\tenit=\textit \let\tensl=\textsl - \let\tenbf=\textbf \let\tentt=\texttt \let\smallcaps=\textsc - \let\tensf=\textsf \let\teni=\texti \let\tensy=\textsy \let\tenttsl=\textttsl - \resetmathfonts \setleading{\textleading}} -\def\titlefonts{% - \let\tenrm=\titlerm \let\tenit=\titleit \let\tensl=\titlesl - \let\tenbf=\titlebf \let\tentt=\titlett \let\smallcaps=\titlesc - \let\tensf=\titlesf \let\teni=\titlei \let\tensy=\titlesy - \let\tenttsl=\titlettsl - \resetmathfonts \setleading{25pt}} -\def\titlefont#1{{\titlefonts\rm #1}} -\def\chapfonts{% - \let\tenrm=\chaprm \let\tenit=\chapit \let\tensl=\chapsl - \let\tenbf=\chapbf \let\tentt=\chaptt \let\smallcaps=\chapsc - \let\tensf=\chapsf \let\teni=\chapi \let\tensy=\chapsy \let\tenttsl=\chapttsl - \resetmathfonts \setleading{19pt}} -\def\secfonts{% - \let\tenrm=\secrm \let\tenit=\secit \let\tensl=\secsl - \let\tenbf=\secbf \let\tentt=\sectt \let\smallcaps=\secsc - \let\tensf=\secsf \let\teni=\seci \let\tensy=\secsy \let\tenttsl=\secttsl - \resetmathfonts \setleading{16pt}} -\def\subsecfonts{% - \let\tenrm=\ssecrm \let\tenit=\ssecit \let\tensl=\ssecsl - \let\tenbf=\ssecbf \let\tentt=\ssectt \let\smallcaps=\ssecsc - \let\tensf=\ssecsf \let\teni=\sseci \let\tensy=\ssecsy \let\tenttsl=\ssecttsl - \resetmathfonts \setleading{15pt}} -\let\subsubsecfonts = \subsecfonts % Maybe make sssec fonts scaled magstephalf? -\def\smallfonts{% - \let\tenrm=\smallrm \let\tenit=\smallit \let\tensl=\smallsl - \let\tenbf=\smallbf \let\tentt=\smalltt \let\smallcaps=\smallsc - \let\tensf=\smallsf \let\teni=\smalli \let\tensy=\smallsy - \let\tenttsl=\smallttsl - \resetmathfonts \setleading{10.5pt}} -\def\smallerfonts{% - \let\tenrm=\smallerrm \let\tenit=\smallerit \let\tensl=\smallersl - \let\tenbf=\smallerbf \let\tentt=\smallertt \let\smallcaps=\smallersc - \let\tensf=\smallersf \let\teni=\smalleri \let\tensy=\smallersy - \let\tenttsl=\smallerttsl - \resetmathfonts \setleading{9.5pt}} -\let\smallexamplefonts = \smallerfonts - -% Set up the default fonts, so we can use them for creating boxes. -% -\textfonts - -% Define these so they can be easily changed for other fonts. -\def\angleleft{$\langle$} -\def\angleright{$\rangle$} - -% Count depth in font-changes, for error checks -\newcount\fontdepth \fontdepth=0 - -% Fonts for short table of contents. -\setfont\shortcontrm\rmshape{12}{1000} -\setfont\shortcontbf\bxshape{12}{1000} -\setfont\shortcontsl\slshape{12}{1000} - -%% Add scribe-like font environments, plus @l for inline lisp (usually sans -%% serif) and @ii for TeX italic - -% \smartitalic{ARG} outputs arg in italics, followed by an italic correction -% unless the following character is such as not to need one. -\def\smartitalicx{\ifx\next,\else\ifx\next-\else\ifx\next.\else\/\fi\fi\fi} -\def\smartslanted#1{{\sl #1}\futurelet\next\smartitalicx} -\def\smartitalic#1{{\it #1}\futurelet\next\smartitalicx} - -\let\i=\smartitalic -\let\var=\smartslanted -\let\dfn=\smartslanted -\let\emph=\smartitalic -\let\cite=\smartslanted - -\def\b#1{{\bf #1}} -\let\strong=\b - -% We can't just use \exhyphenpenalty, because that only has effect at -% the end of a paragraph. Restore normal hyphenation at the end of the -% group within which \nohyphenation is presumably called. -% -\def\nohyphenation{\hyphenchar\font = -1 \aftergroup\restorehyphenation} -\def\restorehyphenation{\hyphenchar\font = `- } - -\def\t#1{% - {\tt \rawbackslash \frenchspacing #1}% - \null -} -\let\ttfont=\t -\def\samp#1{`\tclose{#1}'\null} -\setfont\keyrm\rmshape{8}{1000} -\font\keysy=cmsy9 -\def\key#1{{\keyrm\textfont2=\keysy \leavevmode\hbox{% - \raise0.4pt\hbox{\angleleft}\kern-.08em\vtop{% - \vbox{\hrule\kern-0.4pt - \hbox{\raise0.4pt\hbox{\vphantom{\angleleft}}#1}}% - \kern-0.4pt\hrule}% - \kern-.06em\raise0.4pt\hbox{\angleright}}}} -% The old definition, with no lozenge: -%\def\key #1{{\ttsl \nohyphenation \uppercase{#1}}\null} -\def\ctrl #1{{\tt \rawbackslash \hat}#1} - -% @file, @option are the same as @samp. -\let\file=\samp -\let\option=\samp - -% @code is a modification of @t, -% which makes spaces the same size as normal in the surrounding text. -\def\tclose#1{% - {% - % Change normal interword space to be same as for the current font. - \spaceskip = \fontdimen2\font - % - % Switch to typewriter. - \tt - % - % But `\ ' produces the large typewriter interword space. - \def\ {{\spaceskip = 0pt{} }}% - % - % Turn off hyphenation. - \nohyphenation - % - \rawbackslash - \frenchspacing - #1% - }% - \null -} - -% We *must* turn on hyphenation at `-' and `_' in \code. -% Otherwise, it is too hard to avoid overfull hboxes -% in the Emacs manual, the Library manual, etc. - -% Unfortunately, TeX uses one parameter (\hyphenchar) to control -% both hyphenation at - and hyphenation within words. -% We must therefore turn them both off (\tclose does that) -% and arrange explicitly to hyphenate at a dash. -% -- rms. -{ - \catcode`\-=\active - \catcode`\_=\active - % - \global\def\code{\begingroup - \catcode`\-=\active \let-\codedash - \catcode`\_=\active \let_\codeunder - \codex - } - % - % If we end up with any active - characters when handling the index, - % just treat them as a normal -. - \global\def\indexbreaks{\catcode`\-=\active \let-\realdash} -} - -\def\realdash{-} -\def\codedash{-\discretionary{}{}{}} -\def\codeunder{\ifusingtt{\normalunderscore\discretionary{}{}{}}{\_}} -\def\codex #1{\tclose{#1}\endgroup} - -%\let\exp=\tclose %Was temporary - -% @kbd is like @code, except that if the argument is just one @key command, -% then @kbd has no effect. - -% @kbdinputstyle -- arg is `distinct' (@kbd uses slanted tty font always), -% `example' (@kbd uses ttsl only inside of @example and friends), -% or `code' (@kbd uses normal tty font always). -\def\kbdinputstyle{\parsearg\kbdinputstylexxx} -\def\kbdinputstylexxx#1{% - \def\arg{#1}% - \ifx\arg\worddistinct - \gdef\kbdexamplefont{\ttsl}\gdef\kbdfont{\ttsl}% - \else\ifx\arg\wordexample - \gdef\kbdexamplefont{\ttsl}\gdef\kbdfont{\tt}% - \else\ifx\arg\wordcode - \gdef\kbdexamplefont{\tt}\gdef\kbdfont{\tt}% - \fi\fi\fi -} -\def\worddistinct{distinct} -\def\wordexample{example} -\def\wordcode{code} - -% Default is kbdinputdistinct. (Too much of a hassle to call the macro, -% the catcodes are wrong for parsearg to work.) -\gdef\kbdexamplefont{\ttsl}\gdef\kbdfont{\ttsl} - -\def\xkey{\key} -\def\kbdfoo#1#2#3\par{\def\one{#1}\def\three{#3}\def\threex{??}% -\ifx\one\xkey\ifx\threex\three \key{#2}% -\else{\tclose{\kbdfont\look}}\fi -\else{\tclose{\kbdfont\look}}\fi} - -% For @url, @env, @command quotes seem unnecessary, so use \code. -\let\url=\code -\let\env=\code -\let\command=\code - -% @uref (abbreviation for `urlref') takes an optional (comma-separated) -% second argument specifying the text to display and an optional third -% arg as text to display instead of (rather than in addition to) the url -% itself. First (mandatory) arg is the url. Perhaps eventually put in -% a hypertex \special here. -% -\def\uref#1{\douref #1,,,\finish} -\def\douref#1,#2,#3,#4\finish{\begingroup - \unsepspaces - \pdfurl{#1}% - \setbox0 = \hbox{\ignorespaces #3}% - \ifdim\wd0 > 0pt - \unhbox0 % third arg given, show only that - \else - \setbox0 = \hbox{\ignorespaces #2}% - \ifdim\wd0 > 0pt - \ifpdf - \unhbox0 % PDF: 2nd arg given, show only it - \else - \unhbox0\ (\code{#1})% DVI: 2nd arg given, show both it and url - \fi - \else - \code{#1}% only url given, so show it - \fi - \fi - \endlink -\endgroup} - -% rms does not like angle brackets --karl, 17may97. -% So now @email is just like @uref, unless we are pdf. -% -%\def\email#1{\angleleft{\tt #1}\angleright} -\ifpdf - \def\email#1{\doemail#1,,\finish} - \def\doemail#1,#2,#3\finish{\begingroup - \unsepspaces - \pdfurl{mailto:#1}% - \setbox0 = \hbox{\ignorespaces #2}% - \ifdim\wd0>0pt\unhbox0\else\code{#1}\fi - \endlink - \endgroup} -\else - \let\email=\uref -\fi - -% Check if we are currently using a typewriter font. Since all the -% Computer Modern typewriter fonts have zero interword stretch (and -% shrink), and it is reasonable to expect all typewriter fonts to have -% this property, we can check that font parameter. -% -\def\ifmonospace{\ifdim\fontdimen3\font=0pt } - -% Typeset a dimension, e.g., `in' or `pt'. The only reason for the -% argument is to make the input look right: @dmn{pt} instead of @dmn{}pt. -% -\def\dmn#1{\thinspace #1} - -\def\kbd#1{\def\look{#1}\expandafter\kbdfoo\look??\par} - -% @l was never documented to mean ``switch to the Lisp font'', -% and it is not used as such in any manual I can find. We need it for -% Polish suppressed-l. --karl, 22sep96. -%\def\l#1{{\li #1}\null} - -% Explicit font changes: @r, @sc, undocumented @ii. -\def\r#1{{\rm #1}} % roman font -\def\sc#1{{\smallcaps#1}} % smallcaps font -\def\ii#1{{\it #1}} % italic font - -% @acronym downcases the argument and prints in smallcaps. -\def\acronym#1{{\smallcaps \lowercase{#1}}} - -% @pounds{} is a sterling sign. -\def\pounds{{\it\$}} - - -\message{page headings,} - -\newskip\titlepagetopglue \titlepagetopglue = 1.5in -\newskip\titlepagebottomglue \titlepagebottomglue = 2pc - -% First the title page. Must do @settitle before @titlepage. -\newif\ifseenauthor -\newif\iffinishedtitlepage - -% Do an implicit @contents or @shortcontents after @end titlepage if the -% user says @setcontentsaftertitlepage or @setshortcontentsaftertitlepage. -% -\newif\ifsetcontentsaftertitlepage - \let\setcontentsaftertitlepage = \setcontentsaftertitlepagetrue -\newif\ifsetshortcontentsaftertitlepage - \let\setshortcontentsaftertitlepage = \setshortcontentsaftertitlepagetrue - -\def\shorttitlepage{\parsearg\shorttitlepagezzz} -\def\shorttitlepagezzz #1{\begingroup\hbox{}\vskip 1.5in \chaprm \centerline{#1}% - \endgroup\page\hbox{}\page} - -\def\titlepage{\begingroup \parindent=0pt \textfonts - \let\subtitlerm=\tenrm - \def\subtitlefont{\subtitlerm \normalbaselineskip = 13pt \normalbaselines}% - % - \def\authorfont{\authorrm \normalbaselineskip = 16pt \normalbaselines}% - % - % Leave some space at the very top of the page. - \vglue\titlepagetopglue - % - % Now you can print the title using @title. - \def\title{\parsearg\titlezzz}% - \def\titlezzz##1{\leftline{\titlefonts\rm ##1} - % print a rule at the page bottom also. - \finishedtitlepagefalse - \vskip4pt \hrule height 4pt width \hsize \vskip4pt}% - % No rule at page bottom unless we print one at the top with @title. - \finishedtitlepagetrue - % - % Now you can put text using @subtitle. - \def\subtitle{\parsearg\subtitlezzz}% - \def\subtitlezzz##1{{\subtitlefont \rightline{##1}}}% - % - % @author should come last, but may come many times. - \def\author{\parsearg\authorzzz}% - \def\authorzzz##1{\ifseenauthor\else\vskip 0pt plus 1filll\seenauthortrue\fi - {\authorfont \leftline{##1}}}% - % - % Most title ``pages'' are actually two pages long, with space - % at the top of the second. We don't want the ragged left on the second. - \let\oldpage = \page - \def\page{% - \iffinishedtitlepage\else - \finishtitlepage - \fi - \oldpage - \let\page = \oldpage - \hbox{}}% -% \def\page{\oldpage \hbox{}} -} - -\def\Etitlepage{% - \iffinishedtitlepage\else - \finishtitlepage - \fi - % It is important to do the page break before ending the group, - % because the headline and footline are only empty inside the group. - % If we use the new definition of \page, we always get a blank page - % after the title page, which we certainly don't want. - \oldpage - \endgroup - % - % Need this before the \...aftertitlepage checks so that if they are - % in effect the toc pages will come out with page numbers. - \HEADINGSon - % - % If they want short, they certainly want long too. - \ifsetshortcontentsaftertitlepage - \shortcontents - \contents - \global\let\shortcontents = \relax - \global\let\contents = \relax - \fi - % - \ifsetcontentsaftertitlepage - \contents - \global\let\contents = \relax - \global\let\shortcontents = \relax - \fi - % - \ifpdf \pdfmakepagedesttrue \fi -} - -\def\finishtitlepage{% - \vskip4pt \hrule height 2pt width \hsize - \vskip\titlepagebottomglue - \finishedtitlepagetrue -} - -%%% Set up page headings and footings. - -\let\thispage=\folio - -\newtoks\evenheadline % headline on even pages -\newtoks\oddheadline % headline on odd pages -\newtoks\evenfootline % footline on even pages -\newtoks\oddfootline % footline on odd pages - -% Now make Tex use those variables -\headline={{\textfonts\rm \ifodd\pageno \the\oddheadline - \else \the\evenheadline \fi}} -\footline={{\textfonts\rm \ifodd\pageno \the\oddfootline - \else \the\evenfootline \fi}\HEADINGShook} -\let\HEADINGShook=\relax - -% Commands to set those variables. -% For example, this is what @headings on does -% @evenheading @thistitle|@thispage|@thischapter -% @oddheading @thischapter|@thispage|@thistitle -% @evenfooting @thisfile|| -% @oddfooting ||@thisfile - -\def\evenheading{\parsearg\evenheadingxxx} -\def\oddheading{\parsearg\oddheadingxxx} -\def\everyheading{\parsearg\everyheadingxxx} - -\def\evenfooting{\parsearg\evenfootingxxx} -\def\oddfooting{\parsearg\oddfootingxxx} -\def\everyfooting{\parsearg\everyfootingxxx} - -{\catcode`\@=0 % - -\gdef\evenheadingxxx #1{\evenheadingyyy #1@|@|@|@|\finish} -\gdef\evenheadingyyy #1@|#2@|#3@|#4\finish{% -\global\evenheadline={\rlap{\centerline{#2}}\line{#1\hfil#3}}} - -\gdef\oddheadingxxx #1{\oddheadingyyy #1@|@|@|@|\finish} -\gdef\oddheadingyyy #1@|#2@|#3@|#4\finish{% -\global\oddheadline={\rlap{\centerline{#2}}\line{#1\hfil#3}}} - -\gdef\everyheadingxxx#1{\oddheadingxxx{#1}\evenheadingxxx{#1}}% - -\gdef\evenfootingxxx #1{\evenfootingyyy #1@|@|@|@|\finish} -\gdef\evenfootingyyy #1@|#2@|#3@|#4\finish{% -\global\evenfootline={\rlap{\centerline{#2}}\line{#1\hfil#3}}} - -\gdef\oddfootingxxx #1{\oddfootingyyy #1@|@|@|@|\finish} -\gdef\oddfootingyyy #1@|#2@|#3@|#4\finish{% - \global\oddfootline = {\rlap{\centerline{#2}}\line{#1\hfil#3}}% - % - % Leave some space for the footline. Hopefully ok to assume - % @evenfooting will not be used by itself. - \global\advance\pageheight by -\baselineskip - \global\advance\vsize by -\baselineskip -} - -\gdef\everyfootingxxx#1{\oddfootingxxx{#1}\evenfootingxxx{#1}} -% -}% unbind the catcode of @. - -% @headings double turns headings on for double-sided printing. -% @headings single turns headings on for single-sided printing. -% @headings off turns them off. -% @headings on same as @headings double, retained for compatibility. -% @headings after turns on double-sided headings after this page. -% @headings doubleafter turns on double-sided headings after this page. -% @headings singleafter turns on single-sided headings after this page. -% By default, they are off at the start of a document, -% and turned `on' after @end titlepage. - -\def\headings #1 {\csname HEADINGS#1\endcsname} - -\def\HEADINGSoff{ -\global\evenheadline={\hfil} \global\evenfootline={\hfil} -\global\oddheadline={\hfil} \global\oddfootline={\hfil}} -\HEADINGSoff -% When we turn headings on, set the page number to 1. -% For double-sided printing, put current file name in lower left corner, -% chapter name on inside top of right hand pages, document -% title on inside top of left hand pages, and page numbers on outside top -% edge of all pages. -\def\HEADINGSdouble{ -\global\pageno=1 -\global\evenfootline={\hfil} -\global\oddfootline={\hfil} -\global\evenheadline={\line{\folio\hfil\thistitle}} -\global\oddheadline={\line{\thischapter\hfil\folio}} -\global\let\contentsalignmacro = \chapoddpage -} -\let\contentsalignmacro = \chappager - -% For single-sided printing, chapter title goes across top left of page, -% page number on top right. -\def\HEADINGSsingle{ -\global\pageno=1 -\global\evenfootline={\hfil} -\global\oddfootline={\hfil} -\global\evenheadline={\line{\thischapter\hfil\folio}} -\global\oddheadline={\line{\thischapter\hfil\folio}} -\global\let\contentsalignmacro = \chappager -} -\def\HEADINGSon{\HEADINGSdouble} - -\def\HEADINGSafter{\let\HEADINGShook=\HEADINGSdoublex} -\let\HEADINGSdoubleafter=\HEADINGSafter -\def\HEADINGSdoublex{% -\global\evenfootline={\hfil} -\global\oddfootline={\hfil} -\global\evenheadline={\line{\folio\hfil\thistitle}} -\global\oddheadline={\line{\thischapter\hfil\folio}} -\global\let\contentsalignmacro = \chapoddpage -} - -\def\HEADINGSsingleafter{\let\HEADINGShook=\HEADINGSsinglex} -\def\HEADINGSsinglex{% -\global\evenfootline={\hfil} -\global\oddfootline={\hfil} -\global\evenheadline={\line{\thischapter\hfil\folio}} -\global\oddheadline={\line{\thischapter\hfil\folio}} -\global\let\contentsalignmacro = \chappager -} - -% Subroutines used in generating headings -% This produces Day Month Year style of output. -% Only define if not already defined, in case a txi-??.tex file has set -% up a different format (e.g., txi-cs.tex does this). -\ifx\today\undefined -\def\today{% - \number\day\space - \ifcase\month - \or\putwordMJan\or\putwordMFeb\or\putwordMMar\or\putwordMApr - \or\putwordMMay\or\putwordMJun\or\putwordMJul\or\putwordMAug - \or\putwordMSep\or\putwordMOct\or\putwordMNov\or\putwordMDec - \fi - \space\number\year} -\fi - -% @settitle line... specifies the title of the document, for headings. -% It generates no output of its own. -\def\thistitle{\putwordNoTitle} -\def\settitle{\parsearg\settitlezzz} -\def\settitlezzz #1{\gdef\thistitle{#1}} - - -\message{tables,} -% Tables -- @table, @ftable, @vtable, @item(x), @kitem(x), @xitem(x). - -% default indentation of table text -\newdimen\tableindent \tableindent=.8in -% default indentation of @itemize and @enumerate text -\newdimen\itemindent \itemindent=.3in -% margin between end of table item and start of table text. -\newdimen\itemmargin \itemmargin=.1in - -% used internally for \itemindent minus \itemmargin -\newdimen\itemmax - -% Note @table, @vtable, and @vtable define @item, @itemx, etc., with -% these defs. -% They also define \itemindex -% to index the item name in whatever manner is desired (perhaps none). - -\newif\ifitemxneedsnegativevskip - -\def\itemxpar{\par\ifitemxneedsnegativevskip\nobreak\vskip-\parskip\nobreak\fi} - -\def\internalBitem{\smallbreak \parsearg\itemzzz} -\def\internalBitemx{\itemxpar \parsearg\itemzzz} - -\def\internalBxitem "#1"{\def\xitemsubtopix{#1} \smallbreak \parsearg\xitemzzz} -\def\internalBxitemx "#1"{\def\xitemsubtopix{#1} \itemxpar \parsearg\xitemzzz} - -\def\internalBkitem{\smallbreak \parsearg\kitemzzz} -\def\internalBkitemx{\itemxpar \parsearg\kitemzzz} - -\def\kitemzzz #1{\dosubind {kw}{\code{#1}}{for {\bf \lastfunction}}% - \itemzzz {#1}} - -\def\xitemzzz #1{\dosubind {kw}{\code{#1}}{for {\bf \xitemsubtopic}}% - \itemzzz {#1}} - -\def\itemzzz #1{\begingroup % - \advance\hsize by -\rightskip - \advance\hsize by -\tableindent - \setbox0=\hbox{\itemfont{#1}}% - \itemindex{#1}% - \nobreak % This prevents a break before @itemx. - % - % If the item text does not fit in the space we have, put it on a line - % by itself, and do not allow a page break either before or after that - % line. We do not start a paragraph here because then if the next - % command is, e.g., @kindex, the whatsit would get put into the - % horizontal list on a line by itself, resulting in extra blank space. - \ifdim \wd0>\itemmax - % - % Make this a paragraph so we get the \parskip glue and wrapping, - % but leave it ragged-right. - \begingroup - \advance\leftskip by-\tableindent - \advance\hsize by\tableindent - \advance\rightskip by0pt plus1fil - \leavevmode\unhbox0\par - \endgroup - % - % We're going to be starting a paragraph, but we don't want the - % \parskip glue -- logically it's part of the @item we just started. - \nobreak \vskip-\parskip - % - % Stop a page break at the \parskip glue coming up. Unfortunately - % we can't prevent a possible page break at the following - % \baselineskip glue. - \nobreak - \endgroup - \itemxneedsnegativevskipfalse - \else - % The item text fits into the space. Start a paragraph, so that the - % following text (if any) will end up on the same line. - \noindent - % Do this with kerns and \unhbox so that if there is a footnote in - % the item text, it can migrate to the main vertical list and - % eventually be printed. - \nobreak\kern-\tableindent - \dimen0 = \itemmax \advance\dimen0 by \itemmargin \advance\dimen0 by -\wd0 - \unhbox0 - \nobreak\kern\dimen0 - \endgroup - \itemxneedsnegativevskiptrue - \fi -} - -\def\item{\errmessage{@item while not in a table}} -\def\itemx{\errmessage{@itemx while not in a table}} -\def\kitem{\errmessage{@kitem while not in a table}} -\def\kitemx{\errmessage{@kitemx while not in a table}} -\def\xitem{\errmessage{@xitem while not in a table}} -\def\xitemx{\errmessage{@xitemx while not in a table}} - -% Contains a kludge to get @end[description] to work. -\def\description{\tablez{\dontindex}{1}{}{}{}{}} - -% @table, @ftable, @vtable. -\def\table{\begingroup\inENV\obeylines\obeyspaces\tablex} -{\obeylines\obeyspaces% -\gdef\tablex #1^^M{% -\tabley\dontindex#1 \endtabley}} - -\def\ftable{\begingroup\inENV\obeylines\obeyspaces\ftablex} -{\obeylines\obeyspaces% -\gdef\ftablex #1^^M{% -\tabley\fnitemindex#1 \endtabley -\def\Eftable{\endgraf\afterenvbreak\endgroup}% -\let\Etable=\relax}} - -\def\vtable{\begingroup\inENV\obeylines\obeyspaces\vtablex} -{\obeylines\obeyspaces% -\gdef\vtablex #1^^M{% -\tabley\vritemindex#1 \endtabley -\def\Evtable{\endgraf\afterenvbreak\endgroup}% -\let\Etable=\relax}} - -\def\dontindex #1{} -\def\fnitemindex #1{\doind {fn}{\code{#1}}}% -\def\vritemindex #1{\doind {vr}{\code{#1}}}% - -{\obeyspaces % -\gdef\tabley#1#2 #3 #4 #5 #6 #7\endtabley{\endgroup% -\tablez{#1}{#2}{#3}{#4}{#5}{#6}}} - -\def\tablez #1#2#3#4#5#6{% -\aboveenvbreak % -\begingroup % -\def\Edescription{\Etable}% Necessary kludge. -\let\itemindex=#1% -\ifnum 0#3>0 \advance \leftskip by #3\mil \fi % -\ifnum 0#4>0 \tableindent=#4\mil \fi % -\ifnum 0#5>0 \advance \rightskip by #5\mil \fi % -\def\itemfont{#2}% -\itemmax=\tableindent % -\advance \itemmax by -\itemmargin % -\advance \leftskip by \tableindent % -\exdentamount=\tableindent -\parindent = 0pt -\parskip = \smallskipamount -\ifdim \parskip=0pt \parskip=2pt \fi% -\def\Etable{\endgraf\afterenvbreak\endgroup}% -\let\item = \internalBitem % -\let\itemx = \internalBitemx % -\let\kitem = \internalBkitem % -\let\kitemx = \internalBkitemx % -\let\xitem = \internalBxitem % -\let\xitemx = \internalBxitemx % -} - -% This is the counter used by @enumerate, which is really @itemize - -\newcount \itemno - -\def\itemize{\parsearg\itemizezzz} - -\def\itemizezzz #1{% - \begingroup % ended by the @end itemize - \itemizey {#1}{\Eitemize} -} - -\def\itemizey #1#2{% -\aboveenvbreak % -\itemmax=\itemindent % -\advance \itemmax by -\itemmargin % -\advance \leftskip by \itemindent % -\exdentamount=\itemindent -\parindent = 0pt % -\parskip = \smallskipamount % -\ifdim \parskip=0pt \parskip=2pt \fi% -\def#2{\endgraf\afterenvbreak\endgroup}% -\def\itemcontents{#1}% -\let\item=\itemizeitem} - -% Set sfcode to normal for the chars that usually have another value. -% These are `.?!:;,' -\def\frenchspacing{\sfcode46=1000 \sfcode63=1000 \sfcode33=1000 - \sfcode58=1000 \sfcode59=1000 \sfcode44=1000 } - -% \splitoff TOKENS\endmark defines \first to be the first token in -% TOKENS, and \rest to be the remainder. -% -\def\splitoff#1#2\endmark{\def\first{#1}\def\rest{#2}}% - -% Allow an optional argument of an uppercase letter, lowercase letter, -% or number, to specify the first label in the enumerated list. No -% argument is the same as `1'. -% -\def\enumerate{\parsearg\enumeratezzz} -\def\enumeratezzz #1{\enumeratey #1 \endenumeratey} -\def\enumeratey #1 #2\endenumeratey{% - \begingroup % ended by the @end enumerate - % - % If we were given no argument, pretend we were given `1'. - \def\thearg{#1}% - \ifx\thearg\empty \def\thearg{1}\fi - % - % Detect if the argument is a single token. If so, it might be a - % letter. Otherwise, the only valid thing it can be is a number. - % (We will always have one token, because of the test we just made. - % This is a good thing, since \splitoff doesn't work given nothing at - % all -- the first parameter is undelimited.) - \expandafter\splitoff\thearg\endmark - \ifx\rest\empty - % Only one token in the argument. It could still be anything. - % A ``lowercase letter'' is one whose \lccode is nonzero. - % An ``uppercase letter'' is one whose \lccode is both nonzero, and - % not equal to itself. - % Otherwise, we assume it's a number. - % - % We need the \relax at the end of the \ifnum lines to stop TeX from - % continuing to look for a . - % - \ifnum\lccode\expandafter`\thearg=0\relax - \numericenumerate % a number (we hope) - \else - % It's a letter. - \ifnum\lccode\expandafter`\thearg=\expandafter`\thearg\relax - \lowercaseenumerate % lowercase letter - \else - \uppercaseenumerate % uppercase letter - \fi - \fi - \else - % Multiple tokens in the argument. We hope it's a number. - \numericenumerate - \fi -} - -% An @enumerate whose labels are integers. The starting integer is -% given in \thearg. -% -\def\numericenumerate{% - \itemno = \thearg - \startenumeration{\the\itemno}% -} - -% The starting (lowercase) letter is in \thearg. -\def\lowercaseenumerate{% - \itemno = \expandafter`\thearg - \startenumeration{% - % Be sure we're not beyond the end of the alphabet. - \ifnum\itemno=0 - \errmessage{No more lowercase letters in @enumerate; get a bigger - alphabet}% - \fi - \char\lccode\itemno - }% -} - -% The starting (uppercase) letter is in \thearg. -\def\uppercaseenumerate{% - \itemno = \expandafter`\thearg - \startenumeration{% - % Be sure we're not beyond the end of the alphabet. - \ifnum\itemno=0 - \errmessage{No more uppercase letters in @enumerate; get a bigger - alphabet} - \fi - \char\uccode\itemno - }% -} - -% Call itemizey, adding a period to the first argument and supplying the -% common last two arguments. Also subtract one from the initial value in -% \itemno, since @item increments \itemno. -% -\def\startenumeration#1{% - \advance\itemno by -1 - \itemizey{#1.}\Eenumerate\flushcr -} - -% @alphaenumerate and @capsenumerate are abbreviations for giving an arg -% to @enumerate. -% -\def\alphaenumerate{\enumerate{a}} -\def\capsenumerate{\enumerate{A}} -\def\Ealphaenumerate{\Eenumerate} -\def\Ecapsenumerate{\Eenumerate} - -% Definition of @item while inside @itemize. - -\def\itemizeitem{% -\advance\itemno by 1 -{\let\par=\endgraf \smallbreak}% -\ifhmode \errmessage{In hmode at itemizeitem}\fi -{\parskip=0in \hskip 0pt -\hbox to 0pt{\hss \itemcontents\hskip \itemmargin}% -\vadjust{\penalty 1200}}% -\flushcr} - -% @multitable macros -% Amy Hendrickson, 8/18/94, 3/6/96 -% -% @multitable ... @end multitable will make as many columns as desired. -% Contents of each column will wrap at width given in preamble. Width -% can be specified either with sample text given in a template line, -% or in percent of \hsize, the current width of text on page. - -% Table can continue over pages but will only break between lines. - -% To make preamble: -% -% Either define widths of columns in terms of percent of \hsize: -% @multitable @columnfractions .25 .3 .45 -% @item ... -% -% Numbers following @columnfractions are the percent of the total -% current hsize to be used for each column. You may use as many -% columns as desired. - - -% Or use a template: -% @multitable {Column 1 template} {Column 2 template} {Column 3 template} -% @item ... -% using the widest term desired in each column. -% -% For those who want to use more than one line's worth of words in -% the preamble, break the line within one argument and it -% will parse correctly, i.e., -% -% @multitable {Column 1 template} {Column 2 template} {Column 3 -% template} -% Not: -% @multitable {Column 1 template} {Column 2 template} -% {Column 3 template} - -% Each new table line starts with @item, each subsequent new column -% starts with @tab. Empty columns may be produced by supplying @tab's -% with nothing between them for as many times as empty columns are needed, -% ie, @tab@tab@tab will produce two empty columns. - -% @item, @tab, @multitable or @end multitable do not need to be on their -% own lines, but it will not hurt if they are. - -% Sample multitable: - -% @multitable {Column 1 template} {Column 2 template} {Column 3 template} -% @item first col stuff @tab second col stuff @tab third col -% @item -% first col stuff -% @tab -% second col stuff -% @tab -% third col -% @item first col stuff @tab second col stuff -% @tab Many paragraphs of text may be used in any column. -% -% They will wrap at the width determined by the template. -% @item@tab@tab This will be in third column. -% @end multitable - -% Default dimensions may be reset by user. -% @multitableparskip is vertical space between paragraphs in table. -% @multitableparindent is paragraph indent in table. -% @multitablecolmargin is horizontal space to be left between columns. -% @multitablelinespace is space to leave between table items, baseline -% to baseline. -% 0pt means it depends on current normal line spacing. -% -\newskip\multitableparskip -\newskip\multitableparindent -\newdimen\multitablecolspace -\newskip\multitablelinespace -\multitableparskip=0pt -\multitableparindent=6pt -\multitablecolspace=12pt -\multitablelinespace=0pt - -% Macros used to set up halign preamble: -% -\let\endsetuptable\relax -\def\xendsetuptable{\endsetuptable} -\let\columnfractions\relax -\def\xcolumnfractions{\columnfractions} -\newif\ifsetpercent - -% #1 is the part of the @columnfraction before the decimal point, which -% is presumably either 0 or the empty string (but we don't check, we -% just throw it away). #2 is the decimal part, which we use as the -% percent of \hsize for this column. -\def\pickupwholefraction#1.#2 {% - \global\advance\colcount by 1 - \expandafter\xdef\csname col\the\colcount\endcsname{.#2\hsize}% - \setuptable -} - -\newcount\colcount -\def\setuptable#1{% - \def\firstarg{#1}% - \ifx\firstarg\xendsetuptable - \let\go = \relax - \else - \ifx\firstarg\xcolumnfractions - \global\setpercenttrue - \else - \ifsetpercent - \let\go\pickupwholefraction - \else - \global\advance\colcount by 1 - \setbox0=\hbox{#1\unskip }% Add a normal word space as a separator; - % typically that is always in the input, anyway. - \expandafter\xdef\csname col\the\colcount\endcsname{\the\wd0}% - \fi - \fi - \ifx\go\pickupwholefraction - % Put the argument back for the \pickupwholefraction call, so - % we'll always have a period there to be parsed. - \def\go{\pickupwholefraction#1}% - \else - \let\go = \setuptable - \fi% - \fi - \go -} - -% This used to have \hskip1sp. But then the space in a template line is -% not enough. That is bad. So let's go back to just & until we -% encounter the problem it was intended to solve again. -% --karl, nathan@acm.org, 20apr99. -\def\tab{&} - -% @multitable ... @end multitable definitions: -% -\def\multitable{\parsearg\dotable} -\def\dotable#1{\bgroup - \vskip\parskip - \let\item\crcr - \tolerance=9500 - \hbadness=9500 - \setmultitablespacing - \parskip=\multitableparskip - \parindent=\multitableparindent - \overfullrule=0pt - \global\colcount=0 - \def\Emultitable{\global\setpercentfalse\cr\egroup\egroup}% - % - % To parse everything between @multitable and @item: - \setuptable#1 \endsetuptable - % - % \everycr will reset column counter, \colcount, at the end of - % each line. Every column entry will cause \colcount to advance by one. - % The table preamble - % looks at the current \colcount to find the correct column width. - \everycr{\noalign{% - % - % \filbreak%% keeps underfull box messages off when table breaks over pages. - % Maybe so, but it also creates really weird page breaks when the table - % breaks over pages. Wouldn't \vfil be better? Wait until the problem - % manifests itself, so it can be fixed for real --karl. - \global\colcount=0\relax}}% - % - % This preamble sets up a generic column definition, which will - % be used as many times as user calls for columns. - % \vtop will set a single line and will also let text wrap and - % continue for many paragraphs if desired. - \halign\bgroup&\global\advance\colcount by 1\relax - \multistrut\vtop{\hsize=\expandafter\csname col\the\colcount\endcsname - % - % In order to keep entries from bumping into each other - % we will add a \leftskip of \multitablecolspace to all columns after - % the first one. - % - % If a template has been used, we will add \multitablecolspace - % to the width of each template entry. - % - % If the user has set preamble in terms of percent of \hsize we will - % use that dimension as the width of the column, and the \leftskip - % will keep entries from bumping into each other. Table will start at - % left margin and final column will justify at right margin. - % - % Make sure we don't inherit \rightskip from the outer environment. - \rightskip=0pt - \ifnum\colcount=1 - % The first column will be indented with the surrounding text. - \advance\hsize by\leftskip - \else - \ifsetpercent \else - % If user has not set preamble in terms of percent of \hsize - % we will advance \hsize by \multitablecolspace. - \advance\hsize by \multitablecolspace - \fi - % In either case we will make \leftskip=\multitablecolspace: - \leftskip=\multitablecolspace - \fi - % Ignoring space at the beginning and end avoids an occasional spurious - % blank line, when TeX decides to break the line at the space before the - % box from the multistrut, so the strut ends up on a line by itself. - % For example: - % @multitable @columnfractions .11 .89 - % @item @code{#} - % @tab Legal holiday which is valid in major parts of the whole country. - % Is automatically provided with highlighting sequences respectively marking - % characters. - \noindent\ignorespaces##\unskip\multistrut}\cr -} - -\def\setmultitablespacing{% test to see if user has set \multitablelinespace. -% If so, do nothing. If not, give it an appropriate dimension based on -% current baselineskip. -\ifdim\multitablelinespace=0pt -\setbox0=\vbox{X}\global\multitablelinespace=\the\baselineskip -\global\advance\multitablelinespace by-\ht0 -%% strut to put in table in case some entry doesn't have descenders, -%% to keep lines equally spaced -\let\multistrut = \strut -\else -%% FIXME: what is \box0 supposed to be? -\gdef\multistrut{\vrule height\multitablelinespace depth\dp0 -width0pt\relax} \fi -%% Test to see if parskip is larger than space between lines of -%% table. If not, do nothing. -%% If so, set to same dimension as multitablelinespace. -\ifdim\multitableparskip>\multitablelinespace -\global\multitableparskip=\multitablelinespace -\global\advance\multitableparskip-7pt %% to keep parskip somewhat smaller - %% than skip between lines in the table. -\fi% -\ifdim\multitableparskip=0pt -\global\multitableparskip=\multitablelinespace -\global\advance\multitableparskip-7pt %% to keep parskip somewhat smaller - %% than skip between lines in the table. -\fi} - - -\message{conditionals,} -% Prevent errors for section commands. -% Used in @ignore and in failing conditionals. -\def\ignoresections{% - \let\chapter=\relax - \let\unnumbered=\relax - \let\top=\relax - \let\unnumberedsec=\relax - \let\unnumberedsection=\relax - \let\unnumberedsubsec=\relax - \let\unnumberedsubsection=\relax - \let\unnumberedsubsubsec=\relax - \let\unnumberedsubsubsection=\relax - \let\section=\relax - \let\subsec=\relax - \let\subsubsec=\relax - \let\subsection=\relax - \let\subsubsection=\relax - \let\appendix=\relax - \let\appendixsec=\relax - \let\appendixsection=\relax - \let\appendixsubsec=\relax - \let\appendixsubsection=\relax - \let\appendixsubsubsec=\relax - \let\appendixsubsubsection=\relax - \let\contents=\relax - \let\smallbook=\relax - \let\titlepage=\relax -} - -% Used in nested conditionals, where we have to parse the Texinfo source -% and so want to turn off most commands, in case they are used -% incorrectly. -% -\def\ignoremorecommands{% - \let\defcodeindex = \relax - \let\defcv = \relax - \let\deffn = \relax - \let\deffnx = \relax - \let\defindex = \relax - \let\defivar = \relax - \let\defmac = \relax - \let\defmethod = \relax - \let\defop = \relax - \let\defopt = \relax - \let\defspec = \relax - \let\deftp = \relax - \let\deftypefn = \relax - \let\deftypefun = \relax - \let\deftypeivar = \relax - \let\deftypeop = \relax - \let\deftypevar = \relax - \let\deftypevr = \relax - \let\defun = \relax - \let\defvar = \relax - \let\defvr = \relax - \let\ref = \relax - \let\xref = \relax - \let\printindex = \relax - \let\pxref = \relax - \let\settitle = \relax - \let\setchapternewpage = \relax - \let\setchapterstyle = \relax - \let\everyheading = \relax - \let\evenheading = \relax - \let\oddheading = \relax - \let\everyfooting = \relax - \let\evenfooting = \relax - \let\oddfooting = \relax - \let\headings = \relax - \let\include = \relax - \let\lowersections = \relax - \let\down = \relax - \let\raisesections = \relax - \let\up = \relax - \let\set = \relax - \let\clear = \relax - \let\item = \relax -} - -% Ignore @ignore ... @end ignore. -% -\def\ignore{\doignore{ignore}} - -% Also ignore @ifinfo, @ifhtml, @ifnottex, @html, @menu, -% @documentdescription, and @direntry text. -% -\def\ifinfo{\doignore{ifinfo}} -\def\ifhtml{\doignore{ifhtml}} -\def\ifnottex{\doignore{ifnottex}} -\def\html{\doignore{html}} -\def\menu{\doignore{menu}} -\def\documentdescription{\doignore{documentdescription}} -\def\direntry{\doignore{direntry}} - -% @dircategory CATEGORY -- specify a category of the dir file -% which this file should belong to. Ignore this in TeX. -\let\dircategory = \comment - -% Ignore text until a line `@end #1'. -% -\def\doignore#1{\begingroup - % Don't complain about control sequences we have declared \outer. - \ignoresections - % - % Define a command to swallow text until we reach `@end #1'. - % This @ is a catcode 12 token (that is the normal catcode of @ in - % this texinfo.tex file). We change the catcode of @ below to match. - \long\def\doignoretext##1@end #1{\enddoignore}% - % - % Make sure that spaces turn into tokens that match what \doignoretext wants. - \catcode32 = 10 - % - % Ignore braces, too, so mismatched braces don't cause trouble. - \catcode`\{ = 9 - \catcode`\} = 9 - % - % We must not have @c interpreted as a control sequence. - \catcode`\@ = 12 - % - % Make the letter c a comment character so that the rest of the line - % will be ignored. This way, the document can have (for example) - % @c @end ifinfo - % and the @end ifinfo will be properly ignored. - % (We've just changed @ to catcode 12.) - \catcode`\c = 14 - % - % And now expand that command. - \doignoretext -} - -% What we do to finish off ignored text. -% -\def\enddoignore{\endgroup\ignorespaces}% - -\newif\ifwarnedobs\warnedobsfalse -\def\obstexwarn{% - \ifwarnedobs\relax\else - % We need to warn folks that they may have trouble with TeX 3.0. - % This uses \immediate\write16 rather than \message to get newlines. - \immediate\write16{} - \immediate\write16{WARNING: for users of Unix TeX 3.0!} - \immediate\write16{This manual trips a bug in TeX version 3.0 (tex hangs).} - \immediate\write16{If you are running another version of TeX, relax.} - \immediate\write16{If you are running Unix TeX 3.0, kill this TeX process.} - \immediate\write16{ Then upgrade your TeX installation if you can.} - \immediate\write16{ (See ftp://ftp.gnu.org/pub/gnu/TeX.README.)} - \immediate\write16{If you are stuck with version 3.0, run the} - \immediate\write16{ script ``tex3patch'' from the Texinfo distribution} - \immediate\write16{ to use a workaround.} - \immediate\write16{} - \global\warnedobstrue - \fi -} - -% **In TeX 3.0, setting text in \nullfont hangs tex. For a -% workaround (which requires the file ``dummy.tfm'' to be installed), -% uncomment the following line: -%%%%%\font\nullfont=dummy\let\obstexwarn=\relax - -% Ignore text, except that we keep track of conditional commands for -% purposes of nesting, up to an `@end #1' command. -% -\def\nestedignore#1{% - \obstexwarn - % We must actually expand the ignored text to look for the @end - % command, so that nested ignore constructs work. Thus, we put the - % text into a \vbox and then do nothing with the result. To minimize - % the change of memory overflow, we follow the approach outlined on - % page 401 of the TeXbook: make the current font be a dummy font. - % - \setbox0 = \vbox\bgroup - % Don't complain about control sequences we have declared \outer. - \ignoresections - % - % Define `@end #1' to end the box, which will in turn undefine the - % @end command again. - \expandafter\def\csname E#1\endcsname{\egroup\ignorespaces}% - % - % We are going to be parsing Texinfo commands. Most cause no - % trouble when they are used incorrectly, but some commands do - % complicated argument parsing or otherwise get confused, so we - % undefine them. - % - % We can't do anything about stray @-signs, unfortunately; - % they'll produce `undefined control sequence' errors. - \ignoremorecommands - % - % Set the current font to be \nullfont, a TeX primitive, and define - % all the font commands to also use \nullfont. We don't use - % dummy.tfm, as suggested in the TeXbook, because not all sites - % might have that installed. Therefore, math mode will still - % produce output, but that should be an extremely small amount of - % stuff compared to the main input. - % - \nullfont - \let\tenrm=\nullfont \let\tenit=\nullfont \let\tensl=\nullfont - \let\tenbf=\nullfont \let\tentt=\nullfont \let\smallcaps=\nullfont - \let\tensf=\nullfont - % Similarly for index fonts. - \let\smallrm=\nullfont \let\smallit=\nullfont \let\smallsl=\nullfont - \let\smallbf=\nullfont \let\smalltt=\nullfont \let\smallsc=\nullfont - \let\smallsf=\nullfont - % Similarly for smallexample fonts. - \let\smallerrm=\nullfont \let\smallerit=\nullfont \let\smallersl=\nullfont - \let\smallerbf=\nullfont \let\smallertt=\nullfont \let\smallersc=\nullfont - \let\smallersf=\nullfont - % - % Don't complain when characters are missing from the fonts. - \tracinglostchars = 0 - % - % Don't bother to do space factor calculations. - \frenchspacing - % - % Don't report underfull hboxes. - \hbadness = 10000 - % - % Do minimal line-breaking. - \pretolerance = 10000 - % - % Do not execute instructions in @tex - \def\tex{\doignore{tex}}% - % Do not execute macro definitions. - % `c' is a comment character, so the word `macro' will get cut off. - \def\macro{\doignore{ma}}% -} - -% @set VAR sets the variable VAR to an empty value. -% @set VAR REST-OF-LINE sets VAR to the value REST-OF-LINE. -% -% Since we want to separate VAR from REST-OF-LINE (which might be -% empty), we can't just use \parsearg; we have to insert a space of our -% own to delimit the rest of the line, and then take it out again if we -% didn't need it. Make sure the catcode of space is correct to avoid -% losing inside @example, for instance. -% -\def\set{\begingroup\catcode` =10 - \catcode`\-=12 \catcode`\_=12 % Allow - and _ in VAR. - \parsearg\setxxx} -\def\setxxx#1{\setyyy#1 \endsetyyy} -\def\setyyy#1 #2\endsetyyy{% - \def\temp{#2}% - \ifx\temp\empty \global\expandafter\let\csname SET#1\endcsname = \empty - \else \setzzz{#1}#2\endsetzzz % Remove the trailing space \setxxx inserted. - \fi - \endgroup -} -% Can't use \xdef to pre-expand #2 and save some time, since \temp or -% \next or other control sequences that we've defined might get us into -% an infinite loop. Consider `@set foo @cite{bar}'. -\def\setzzz#1#2 \endsetzzz{\expandafter\gdef\csname SET#1\endcsname{#2}} - -% @clear VAR clears (i.e., unsets) the variable VAR. -% -\def\clear{\parsearg\clearxxx} -\def\clearxxx#1{\global\expandafter\let\csname SET#1\endcsname=\relax} - -% @value{foo} gets the text saved in variable foo. -{ - \catcode`\_ = \active - % - % We might end up with active _ or - characters in the argument if - % we're called from @code, as @code{@value{foo-bar_}}. So \let any - % such active characters to their normal equivalents. - \gdef\value{\begingroup - \catcode`\-=12 \catcode`\_=12 - \indexbreaks \let_\normalunderscore - \valuexxx} -} -\def\valuexxx#1{\expandablevalue{#1}\endgroup} - -% We have this subroutine so that we can handle at least some @value's -% properly in indexes (we \let\value to this in \indexdummies). Ones -% whose names contain - or _ still won't work, but we can't do anything -% about that. The command has to be fully expandable, since the result -% winds up in the index file. This means that if the variable's value -% contains other Texinfo commands, it's almost certain it will fail -% (although perhaps we could fix that with sufficient work to do a -% one-level expansion on the result, instead of complete). -% -\def\expandablevalue#1{% - \expandafter\ifx\csname SET#1\endcsname\relax - {[No value for ``#1'']}% - \else - \csname SET#1\endcsname - \fi -} - -% @ifset VAR ... @end ifset reads the `...' iff VAR has been defined -% with @set. -% -\def\ifset{\parsearg\ifsetxxx} -\def\ifsetxxx #1{% - \expandafter\ifx\csname SET#1\endcsname\relax - \expandafter\ifsetfail - \else - \expandafter\ifsetsucceed - \fi -} -\def\ifsetsucceed{\conditionalsucceed{ifset}} -\def\ifsetfail{\nestedignore{ifset}} -\defineunmatchedend{ifset} - -% @ifclear VAR ... @end ifclear reads the `...' iff VAR has never been -% defined with @set, or has been undefined with @clear. -% -\def\ifclear{\parsearg\ifclearxxx} -\def\ifclearxxx #1{% - \expandafter\ifx\csname SET#1\endcsname\relax - \expandafter\ifclearsucceed - \else - \expandafter\ifclearfail - \fi -} -\def\ifclearsucceed{\conditionalsucceed{ifclear}} -\def\ifclearfail{\nestedignore{ifclear}} -\defineunmatchedend{ifclear} - -% @iftex, @ifnothtml, @ifnotinfo always succeed; we read the text -% following, through the first @end iftex (etc.). Make `@end iftex' -% (etc.) valid only after an @iftex. -% -\def\iftex{\conditionalsucceed{iftex}} -\def\ifnothtml{\conditionalsucceed{ifnothtml}} -\def\ifnotinfo{\conditionalsucceed{ifnotinfo}} -\defineunmatchedend{iftex} -\defineunmatchedend{ifnothtml} -\defineunmatchedend{ifnotinfo} - -% We can't just want to start a group at @iftex (for example) and end it -% at @end iftex, since then @set commands inside the conditional have no -% effect (they'd get reverted at the end of the group). So we must -% define \Eiftex to redefine itself to be its previous value. (We can't -% just define it to fail again with an ``unmatched end'' error, since -% the @ifset might be nested.) -% -\def\conditionalsucceed#1{% - \edef\temp{% - % Remember the current value of \E#1. - \let\nece{prevE#1} = \nece{E#1}% - % - % At the `@end #1', redefine \E#1 to be its previous value. - \def\nece{E#1}{\let\nece{E#1} = \nece{prevE#1}}% - }% - \temp -} - -% We need to expand lots of \csname's, but we don't want to expand the -% control sequences after we've constructed them. -% -\def\nece#1{\expandafter\noexpand\csname#1\endcsname} - -% @defininfoenclose. -\let\definfoenclose=\comment - - -\message{indexing,} -% Index generation facilities - -% Define \newwrite to be identical to plain tex's \newwrite -% except not \outer, so it can be used within \newindex. -{\catcode`\@=11 -\gdef\newwrite{\alloc@7\write\chardef\sixt@@n}} - -% \newindex {foo} defines an index named foo. -% It automatically defines \fooindex such that -% \fooindex ...rest of line... puts an entry in the index foo. -% It also defines \fooindfile to be the number of the output channel for -% the file that accumulates this index. The file's extension is foo. -% The name of an index should be no more than 2 characters long -% for the sake of vms. -% -\def\newindex#1{% - \iflinks - \expandafter\newwrite \csname#1indfile\endcsname - \openout \csname#1indfile\endcsname \jobname.#1 % Open the file - \fi - \expandafter\xdef\csname#1index\endcsname{% % Define @#1index - \noexpand\doindex{#1}} -} - -% @defindex foo == \newindex{foo} -% -\def\defindex{\parsearg\newindex} - -% Define @defcodeindex, like @defindex except put all entries in @code. -% -\def\defcodeindex{\parsearg\newcodeindex} -% -\def\newcodeindex#1{% - \iflinks - \expandafter\newwrite \csname#1indfile\endcsname - \openout \csname#1indfile\endcsname \jobname.#1 - \fi - \expandafter\xdef\csname#1index\endcsname{% - \noexpand\docodeindex{#1}}% -} - - -% @synindex foo bar makes index foo feed into index bar. -% Do this instead of @defindex foo if you don't want it as a separate index. -% -% @syncodeindex foo bar similar, but put all entries made for index foo -% inside @code. -% -\def\synindex#1 #2 {\dosynindex\doindex{#1}{#2}} -\def\syncodeindex#1 #2 {\dosynindex\docodeindex{#1}{#2}} - -% #1 is \doindex or \docodeindex, #2 the index getting redefined (foo), -% #3 the target index (bar). -\def\dosynindex#1#2#3{% - % Only do \closeout if we haven't already done it, else we'll end up - % closing the target index. - \expandafter \ifx\csname donesynindex#2\endcsname \undefined - % The \closeout helps reduce unnecessary open files; the limit on the - % Acorn RISC OS is a mere 16 files. - \expandafter\closeout\csname#2indfile\endcsname - \expandafter\let\csname\donesynindex#2\endcsname = 1 - \fi - % redefine \fooindfile: - \expandafter\let\expandafter\temp\expandafter=\csname#3indfile\endcsname - \expandafter\let\csname#2indfile\endcsname=\temp - % redefine \fooindex: - \expandafter\xdef\csname#2index\endcsname{\noexpand#1{#3}}% -} - -% Define \doindex, the driver for all \fooindex macros. -% Argument #1 is generated by the calling \fooindex macro, -% and it is "foo", the name of the index. - -% \doindex just uses \parsearg; it calls \doind for the actual work. -% This is because \doind is more useful to call from other macros. - -% There is also \dosubind {index}{topic}{subtopic} -% which makes an entry in a two-level index such as the operation index. - -\def\doindex#1{\edef\indexname{#1}\parsearg\singleindexer} -\def\singleindexer #1{\doind{\indexname}{#1}} - -% like the previous two, but they put @code around the argument. -\def\docodeindex#1{\edef\indexname{#1}\parsearg\singlecodeindexer} -\def\singlecodeindexer #1{\doind{\indexname}{\code{#1}}} - -% Take care of texinfo commands likely to appear in an index entry. -% (Must be a way to avoid doing expansion at all, and thus not have to -% laboriously list every single command here.) -% -\def\indexdummies{% -\def\ { }% -\def\@{@}% change to @@ when we switch to @ as escape char in aux files. -% Need these in case \tex is in effect and \{ is a \delimiter again. -% But can't use \lbracecmd and \rbracecmd because texindex assumes -% braces and backslashes are used only as delimiters. -\let\{ = \mylbrace -\let\} = \myrbrace -\def\_{{\realbackslash _}}% -\normalturnoffactive -% -% Take care of the plain tex accent commands. -\def\,##1{\realbackslash ,{##1}}% -\def\"{\realbackslash "}% -\def\`{\realbackslash `}% -\def\'{\realbackslash '}% -\def\^{\realbackslash ^}% -\def\~{\realbackslash ~}% -\def\={\realbackslash =}% -\def\b{\realbackslash b}% -\def\c{\realbackslash c}% -\def\d{\realbackslash d}% -\def\u{\realbackslash u}% -\def\v{\realbackslash v}% -\def\H{\realbackslash H}% -\def\dotless##1{\realbackslash dotless {##1}}% -% Take care of the plain tex special European modified letters. -\def\AA{\realbackslash AA}% -\def\AE{\realbackslash AE}% -\def\L{\realbackslash L}% -\def\OE{\realbackslash OE}% -\def\O{\realbackslash O}% -\def\aa{\realbackslash aa}% -\def\ae{\realbackslash ae}% -\def\l{\realbackslash l}% -\def\oe{\realbackslash oe}% -\def\o{\realbackslash o}% -\def\ss{\realbackslash ss}% -% -% Although these internals commands shouldn't show up, sometimes they do. -\def\bf{\realbackslash bf }% -\def\gtr{\realbackslash gtr}% -\def\hat{\realbackslash hat}% -\def\less{\realbackslash less}% -%\def\rm{\realbackslash rm }% -\def\sf{\realbackslash sf}% -\def\sl{\realbackslash sl }% -\def\tclose##1{\realbackslash tclose {##1}}% -\def\tt{\realbackslash tt}% -% -\def\b##1{\realbackslash b {##1}}% -\def\i##1{\realbackslash i {##1}}% -\def\sc##1{\realbackslash sc {##1}}% -\def\t##1{\realbackslash t {##1}}% -\def\r##1{\realbackslash r {##1}}% -% -\def\TeX{\realbackslash TeX}% -\def\acronym##1{\realbackslash acronym {##1}}% -\def\cite##1{\realbackslash cite {##1}}% -\def\code##1{\realbackslash code {##1}}% -\def\command##1{\realbackslash command {##1}}% -\def\dfn##1{\realbackslash dfn {##1}}% -\def\dots{\realbackslash dots }% -\def\emph##1{\realbackslash emph {##1}}% -\def\env##1{\realbackslash env {##1}}% -\def\file##1{\realbackslash file {##1}}% -\def\kbd##1{\realbackslash kbd {##1}}% -\def\key##1{\realbackslash key {##1}}% -\def\math##1{\realbackslash math {##1}}% -\def\option##1{\realbackslash option {##1}}% -\def\samp##1{\realbackslash samp {##1}}% -\def\strong##1{\realbackslash strong {##1}}% -\def\uref##1{\realbackslash uref {##1}}% -\def\url##1{\realbackslash url {##1}}% -\def\var##1{\realbackslash var {##1}}% -\def\w{\realbackslash w }% -% -% These math commands don't seem likely to be used in index entries. -\def\copyright{\realbackslash copyright}% -\def\equiv{\realbackslash equiv}% -\def\error{\realbackslash error}% -\def\expansion{\realbackslash expansion}% -\def\point{\realbackslash point}% -\def\print{\realbackslash print}% -\def\result{\realbackslash result}% -% -% Handle some cases of @value -- where the variable name does not -% contain - or _, and the value does not contain any -% (non-fully-expandable) commands. -\let\value = \expandablevalue -% -\unsepspaces -% Turn off macro expansion -\turnoffmacros -} - -% If an index command is used in an @example environment, any spaces -% therein should become regular spaces in the raw index file, not the -% expansion of \tie (\\leavevmode \penalty \@M \ ). -{\obeyspaces - \gdef\unsepspaces{\obeyspaces\let =\space}} - -% \indexnofonts no-ops all font-change commands. -% This is used when outputting the strings to sort the index by. -\def\indexdummyfont#1{#1} -\def\indexdummytex{TeX} -\def\indexdummydots{...} - -\def\indexnofonts{% -\def\@{@}% -% how to handle braces? -\def\_{\normalunderscore}% -% -\let\,=\indexdummyfont -\let\"=\indexdummyfont -\let\`=\indexdummyfont -\let\'=\indexdummyfont -\let\^=\indexdummyfont -\let\~=\indexdummyfont -\let\==\indexdummyfont -\let\b=\indexdummyfont -\let\c=\indexdummyfont -\let\d=\indexdummyfont -\let\u=\indexdummyfont -\let\v=\indexdummyfont -\let\H=\indexdummyfont -\let\dotless=\indexdummyfont -% Take care of the plain tex special European modified letters. -\def\AA{AA}% -\def\AE{AE}% -\def\L{L}% -\def\OE{OE}% -\def\O{O}% -\def\aa{aa}% -\def\ae{ae}% -\def\l{l}% -\def\oe{oe}% -\def\o{o}% -\def\ss{ss}% -% -% Don't no-op \tt, since it isn't a user-level command -% and is used in the definitions of the active chars like <, >, |, etc. -% Likewise with the other plain tex font commands. -%\let\tt=\indexdummyfont -% -\let\b=\indexdummyfont -\let\i=\indexdummyfont -\let\r=\indexdummyfont -\let\sc=\indexdummyfont -\let\t=\indexdummyfont -% -\let\TeX=\indexdummytex -\let\acronym=\indexdummyfont -\let\cite=\indexdummyfont -\let\code=\indexdummyfont -\let\command=\indexdummyfont -\let\dfn=\indexdummyfont -\let\dots=\indexdummydots -\let\emph=\indexdummyfont -\let\env=\indexdummyfont -\let\file=\indexdummyfont -\let\kbd=\indexdummyfont -\let\key=\indexdummyfont -\let\math=\indexdummyfont -\let\option=\indexdummyfont -\let\samp=\indexdummyfont -\let\strong=\indexdummyfont -\let\uref=\indexdummyfont -\let\url=\indexdummyfont -\let\var=\indexdummyfont -\let\w=\indexdummyfont -} - -% To define \realbackslash, we must make \ not be an escape. -% We must first make another character (@) an escape -% so we do not become unable to do a definition. - -{\catcode`\@=0 \catcode`\\=\other - @gdef@realbackslash{\}} - -\let\indexbackslash=0 %overridden during \printindex. -\let\SETmarginindex=\relax % put index entries in margin (undocumented)? - -% For \ifx comparisons. -\def\emptymacro{\empty} - -% Most index entries go through here, but \dosubind is the general case. -% -\def\doind#1#2{\dosubind{#1}{#2}\empty} - -% Workhorse for all \fooindexes. -% #1 is name of index, #2 is stuff to put there, #3 is subentry -- -% \empty if called from \doind, as we usually are. The main exception -% is with defuns, which call us directly. -% -\def\dosubind#1#2#3{% - % Put the index entry in the margin if desired. - \ifx\SETmarginindex\relax\else - \insert\margin{\hbox{\vrule height8pt depth3pt width0pt #2}}% - \fi - {% - \count255=\lastpenalty - {% - \indexdummies % Must do this here, since \bf, etc expand at this stage - \escapechar=`\\ - {% - \let\folio = 0% We will expand all macros now EXCEPT \folio. - \def\rawbackslashxx{\indexbackslash}% \indexbackslash isn't defined now - % so it will be output as is; and it will print as backslash. - % - \def\thirdarg{#3}% - % - % If third arg is present, precede it with space in sort key. - \ifx\thirdarg\emptymacro - \let\subentry = \empty - \else - \def\subentry{ #3}% - \fi - % - % First process the index entry with all font commands turned - % off to get the string to sort by. - {\indexnofonts \xdef\indexsorttmp{#2\subentry}}% - % - % Now the real index entry with the fonts. - \toks0 = {#2}% - % - % If the third (subentry) arg is present, add it to the index - % line to write. - \ifx\thirdarg\emptymacro \else - \toks0 = \expandafter{\the\toks0{#3}}% - \fi - % - % Set up the complete index entry, with both the sort key and - % the original text, including any font commands. We write - % three arguments to \entry to the .?? file (four in the - % subentry case), texindex reduces to two when writing the .??s - % sorted result. - \edef\temp{% - \write\csname#1indfile\endcsname{% - \realbackslash entry{\indexsorttmp}{\folio}{\the\toks0}}% - }% - % - % If a skip is the last thing on the list now, preserve it - % by backing up by \lastskip, doing the \write, then inserting - % the skip again. Otherwise, the whatsit generated by the - % \write will make \lastskip zero. The result is that sequences - % like this: - % @end defun - % @tindex whatever - % @defun ... - % will have extra space inserted, because the \medbreak in the - % start of the @defun won't see the skip inserted by the @end of - % the previous defun. - % - % But don't do any of this if we're not in vertical mode. We - % don't want to do a \vskip and prematurely end a paragraph. - % - % Avoid page breaks due to these extra skips, too. - % - \iflinks - \ifvmode - \skip0 = \lastskip - \ifdim\lastskip = 0pt \else \nobreak\vskip-\lastskip \fi - \fi - % - \temp % do the write - % - % - \ifvmode \ifdim\skip0 = 0pt \else \nobreak\vskip\skip0 \fi \fi - \fi - }% - }% - \penalty\count255 - }% -} - -% The index entry written in the file actually looks like -% \entry {sortstring}{page}{topic} -% or -% \entry {sortstring}{page}{topic}{subtopic} -% The texindex program reads in these files and writes files -% containing these kinds of lines: -% \initial {c} -% before the first topic whose initial is c -% \entry {topic}{pagelist} -% for a topic that is used without subtopics -% \primary {topic} -% for the beginning of a topic that is used with subtopics -% \secondary {subtopic}{pagelist} -% for each subtopic. - -% Define the user-accessible indexing commands -% @findex, @vindex, @kindex, @cindex. - -\def\findex {\fnindex} -\def\kindex {\kyindex} -\def\cindex {\cpindex} -\def\vindex {\vrindex} -\def\tindex {\tpindex} -\def\pindex {\pgindex} - -\def\cindexsub {\begingroup\obeylines\cindexsub} -{\obeylines % -\gdef\cindexsub "#1" #2^^M{\endgroup % -\dosubind{cp}{#2}{#1}}} - -% Define the macros used in formatting output of the sorted index material. - -% @printindex causes a particular index (the ??s file) to get printed. -% It does not print any chapter heading (usually an @unnumbered). -% -\def\printindex{\parsearg\doprintindex} -\def\doprintindex#1{\begingroup - \dobreak \chapheadingskip{10000}% - % - \smallfonts \rm - \tolerance = 9500 - \indexbreaks - % - % See if the index file exists and is nonempty. - % Change catcode of @ here so that if the index file contains - % \initial {@} - % as its first line, TeX doesn't complain about mismatched braces - % (because it thinks @} is a control sequence). - \catcode`\@ = 11 - \openin 1 \jobname.#1s - \ifeof 1 - % \enddoublecolumns gets confused if there is no text in the index, - % and it loses the chapter title and the aux file entries for the - % index. The easiest way to prevent this problem is to make sure - % there is some text. - \putwordIndexNonexistent - \else - % - % If the index file exists but is empty, then \openin leaves \ifeof - % false. We have to make TeX try to read something from the file, so - % it can discover if there is anything in it. - \read 1 to \temp - \ifeof 1 - \putwordIndexIsEmpty - \else - % Index files are almost Texinfo source, but we use \ as the escape - % character. It would be better to use @, but that's too big a change - % to make right now. - \def\indexbackslash{\rawbackslashxx}% - \catcode`\\ = 0 - \escapechar = `\\ - \begindoublecolumns - \input \jobname.#1s - \enddoublecolumns - \fi - \fi - \closein 1 -\endgroup} - -% These macros are used by the sorted index file itself. -% Change them to control the appearance of the index. - -\def\initial#1{{% - % Some minor font changes for the special characters. - \let\tentt=\sectt \let\tt=\sectt \let\sf=\sectt - % - % Remove any glue we may have, we'll be inserting our own. - \removelastskip - % - % We like breaks before the index initials, so insert a bonus. - \penalty -300 - % - % Typeset the initial. Making this add up to a whole number of - % baselineskips increases the chance of the dots lining up from column - % to column. It still won't often be perfect, because of the stretch - % we need before each entry, but it's better. - % - % No shrink because it confuses \balancecolumns. - \vskip 1.67\baselineskip plus .5\baselineskip - \leftline{\secbf #1}% - \vskip .33\baselineskip plus .1\baselineskip - % - % Do our best not to break after the initial. - \nobreak -}} - -% This typesets a paragraph consisting of #1, dot leaders, and then #2 -% flush to the right margin. It is used for index and table of contents -% entries. The paragraph is indented by \leftskip. -% -\def\entry#1#2{\begingroup - % - % Start a new paragraph if necessary, so our assignments below can't - % affect previous text. - \par - % - % Do not fill out the last line with white space. - \parfillskip = 0in - % - % No extra space above this paragraph. - \parskip = 0in - % - % Do not prefer a separate line ending with a hyphen to fewer lines. - \finalhyphendemerits = 0 - % - % \hangindent is only relevant when the entry text and page number - % don't both fit on one line. In that case, bob suggests starting the - % dots pretty far over on the line. Unfortunately, a large - % indentation looks wrong when the entry text itself is broken across - % lines. So we use a small indentation and put up with long leaders. - % - % \hangafter is reset to 1 (which is the value we want) at the start - % of each paragraph, so we need not do anything with that. - \hangindent = 2em - % - % When the entry text needs to be broken, just fill out the first line - % with blank space. - \rightskip = 0pt plus1fil - % - % A bit of stretch before each entry for the benefit of balancing columns. - \vskip 0pt plus1pt - % - % Start a ``paragraph'' for the index entry so the line breaking - % parameters we've set above will have an effect. - \noindent - % - % Insert the text of the index entry. TeX will do line-breaking on it. - #1% - % The following is kludged to not output a line of dots in the index if - % there are no page numbers. The next person who breaks this will be - % cursed by a Unix daemon. - \def\tempa{{\rm }}% - \def\tempb{#2}% - \edef\tempc{\tempa}% - \edef\tempd{\tempb}% - \ifx\tempc\tempd\ \else% - % - % If we must, put the page number on a line of its own, and fill out - % this line with blank space. (The \hfil is overwhelmed with the - % fill leaders glue in \indexdotfill if the page number does fit.) - \hfil\penalty50 - \null\nobreak\indexdotfill % Have leaders before the page number. - % - % The `\ ' here is removed by the implicit \unskip that TeX does as - % part of (the primitive) \par. Without it, a spurious underfull - % \hbox ensues. - \ifpdf - \pdfgettoks#2.\ \the\toksA % The page number ends the paragraph. - \else - \ #2% The page number ends the paragraph. - \fi - \fi% - \par -\endgroup} - -% Like \dotfill except takes at least 1 em. -\def\indexdotfill{\cleaders - \hbox{$\mathsurround=0pt \mkern1.5mu ${\it .}$ \mkern1.5mu$}\hskip 1em plus 1fill} - -\def\primary #1{\line{#1\hfil}} - -\newskip\secondaryindent \secondaryindent=0.5cm -\def\secondary#1#2{{% - \parfillskip=0in - \parskip=0in - \hangindent=1in - \hangafter=1 - \noindent\hskip\secondaryindent\hbox{#1}\indexdotfill - \ifpdf - \pdfgettoks#2.\ \the\toksA % The page number ends the paragraph. - \else - #2 - \fi - \par -}} - -% Define two-column mode, which we use to typeset indexes. -% Adapted from the TeXbook, page 416, which is to say, -% the manmac.tex format used to print the TeXbook itself. -\catcode`\@=11 - -\newbox\partialpage -\newdimen\doublecolumnhsize - -\def\begindoublecolumns{\begingroup % ended by \enddoublecolumns - % Grab any single-column material above us. - \output = {% - % - % Here is a possibility not foreseen in manmac: if we accumulate a - % whole lot of material, we might end up calling this \output - % routine twice in a row (see the doublecol-lose test, which is - % essentially a couple of indexes with @setchapternewpage off). In - % that case we just ship out what is in \partialpage with the normal - % output routine. Generally, \partialpage will be empty when this - % runs and this will be a no-op. See the indexspread.tex test case. - \ifvoid\partialpage \else - \onepageout{\pagecontents\partialpage}% - \fi - % - \global\setbox\partialpage = \vbox{% - % Unvbox the main output page. - \unvbox\PAGE - \kern-\topskip \kern\baselineskip - }% - }% - \eject % run that output routine to set \partialpage - % - % Use the double-column output routine for subsequent pages. - \output = {\doublecolumnout}% - % - % Change the page size parameters. We could do this once outside this - % routine, in each of @smallbook, @afourpaper, and the default 8.5x11 - % format, but then we repeat the same computation. Repeating a couple - % of assignments once per index is clearly meaningless for the - % execution time, so we may as well do it in one place. - % - % First we halve the line length, less a little for the gutter between - % the columns. We compute the gutter based on the line length, so it - % changes automatically with the paper format. The magic constant - % below is chosen so that the gutter has the same value (well, +-<1pt) - % as it did when we hard-coded it. - % - % We put the result in a separate register, \doublecolumhsize, so we - % can restore it in \pagesofar, after \hsize itself has (potentially) - % been clobbered. - % - \doublecolumnhsize = \hsize - \advance\doublecolumnhsize by -.04154\hsize - \divide\doublecolumnhsize by 2 - \hsize = \doublecolumnhsize - % - % Double the \vsize as well. (We don't need a separate register here, - % since nobody clobbers \vsize.) - \vsize = 2\vsize -} - -% The double-column output routine for all double-column pages except -% the last. -% -\def\doublecolumnout{% - \splittopskip=\topskip \splitmaxdepth=\maxdepth - % Get the available space for the double columns -- the normal - % (undoubled) page height minus any material left over from the - % previous page. - \dimen@ = \vsize - \divide\dimen@ by 2 - \advance\dimen@ by -\ht\partialpage - % - % box0 will be the left-hand column, box2 the right. - \setbox0=\vsplit255 to\dimen@ \setbox2=\vsplit255 to\dimen@ - \onepageout\pagesofar - \unvbox255 - \penalty\outputpenalty -} -% -% Re-output the contents of the output page -- any previous material, -% followed by the two boxes we just split, in box0 and box2. -\def\pagesofar{% - \unvbox\partialpage - % - \hsize = \doublecolumnhsize - \wd0=\hsize \wd2=\hsize - \hbox to\pagewidth{\box0\hfil\box2}% -} -% -% All done with double columns. -\def\enddoublecolumns{% - \output = {% - % Split the last of the double-column material. Leave it on the - % current page, no automatic page break. - \balancecolumns - % - % If we end up splitting too much material for the current page, - % though, there will be another page break right after this \output - % invocation ends. Having called \balancecolumns once, we do not - % want to call it again. Therefore, reset \output to its normal - % definition right away. (We hope \balancecolumns will never be - % called on to balance too much material, but if it is, this makes - % the output somewhat more palatable.) - \global\output = {\onepageout{\pagecontents\PAGE}}% - }% - \eject - \endgroup % started in \begindoublecolumns - % - % \pagegoal was set to the doubled \vsize above, since we restarted - % the current page. We're now back to normal single-column - % typesetting, so reset \pagegoal to the normal \vsize (after the - % \endgroup where \vsize got restored). - \pagegoal = \vsize -} -% -% Called at the end of the double column material. -\def\balancecolumns{% - \setbox0 = \vbox{\unvbox255}% like \box255 but more efficient, see p.120. - \dimen@ = \ht0 - \advance\dimen@ by \topskip - \advance\dimen@ by-\baselineskip - \divide\dimen@ by 2 % target to split to - %debug\message{final 2-column material height=\the\ht0, target=\the\dimen@.}% - \splittopskip = \topskip - % Loop until we get a decent breakpoint. - {% - \vbadness = 10000 - \loop - \global\setbox3 = \copy0 - \global\setbox1 = \vsplit3 to \dimen@ - \ifdim\ht3>\dimen@ - \global\advance\dimen@ by 1pt - \repeat - }% - %debug\message{split to \the\dimen@, column heights: \the\ht1, \the\ht3.}% - \setbox0=\vbox to\dimen@{\unvbox1}% - \setbox2=\vbox to\dimen@{\unvbox3}% - % - \pagesofar -} -\catcode`\@ = \other - - -\message{sectioning,} -% Chapters, sections, etc. - -\newcount\chapno -\newcount\secno \secno=0 -\newcount\subsecno \subsecno=0 -\newcount\subsubsecno \subsubsecno=0 - -% This counter is funny since it counts through charcodes of letters A, B, ... -\newcount\appendixno \appendixno = `\@ -% \def\appendixletter{\char\the\appendixno} -% We do the following for the sake of pdftex, which needs the actual -% letter in the expansion, not just typeset. -\def\appendixletter{% - \ifnum\appendixno=`A A% - \else\ifnum\appendixno=`B B% - \else\ifnum\appendixno=`C C% - \else\ifnum\appendixno=`D D% - \else\ifnum\appendixno=`E E% - \else\ifnum\appendixno=`F F% - \else\ifnum\appendixno=`G G% - \else\ifnum\appendixno=`H H% - \else\ifnum\appendixno=`I I% - \else\ifnum\appendixno=`J J% - \else\ifnum\appendixno=`K K% - \else\ifnum\appendixno=`L L% - \else\ifnum\appendixno=`M M% - \else\ifnum\appendixno=`N N% - \else\ifnum\appendixno=`O O% - \else\ifnum\appendixno=`P P% - \else\ifnum\appendixno=`Q Q% - \else\ifnum\appendixno=`R R% - \else\ifnum\appendixno=`S S% - \else\ifnum\appendixno=`T T% - \else\ifnum\appendixno=`U U% - \else\ifnum\appendixno=`V V% - \else\ifnum\appendixno=`W W% - \else\ifnum\appendixno=`X X% - \else\ifnum\appendixno=`Y Y% - \else\ifnum\appendixno=`Z Z% - % The \the is necessary, despite appearances, because \appendixletter is - % expanded while writing the .toc file. \char\appendixno is not - % expandable, thus it is written literally, thus all appendixes come out - % with the same letter (or @) in the toc without it. - \else\char\the\appendixno - \fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi - \fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi} - -% Each @chapter defines this as the name of the chapter. -% page headings and footings can use it. @section does likewise. -\def\thischapter{} -\def\thissection{} - -\newcount\absseclevel % used to calculate proper heading level -\newcount\secbase\secbase=0 % @raise/lowersections modify this count - -% @raisesections: treat @section as chapter, @subsection as section, etc. -\def\raisesections{\global\advance\secbase by -1} -\let\up=\raisesections % original BFox name - -% @lowersections: treat @chapter as section, @section as subsection, etc. -\def\lowersections{\global\advance\secbase by 1} -\let\down=\lowersections % original BFox name - -% Choose a numbered-heading macro -% #1 is heading level if unmodified by @raisesections or @lowersections -% #2 is text for heading -\def\numhead#1#2{\absseclevel=\secbase\advance\absseclevel by #1 -\ifcase\absseclevel - \chapterzzz{#2} -\or - \seczzz{#2} -\or - \numberedsubseczzz{#2} -\or - \numberedsubsubseczzz{#2} -\else - \ifnum \absseclevel<0 - \chapterzzz{#2} - \else - \numberedsubsubseczzz{#2} - \fi -\fi -} - -% like \numhead, but chooses appendix heading levels -\def\apphead#1#2{\absseclevel=\secbase\advance\absseclevel by #1 -\ifcase\absseclevel - \appendixzzz{#2} -\or - \appendixsectionzzz{#2} -\or - \appendixsubseczzz{#2} -\or - \appendixsubsubseczzz{#2} -\else - \ifnum \absseclevel<0 - \appendixzzz{#2} - \else - \appendixsubsubseczzz{#2} - \fi -\fi -} - -% like \numhead, but chooses numberless heading levels -\def\unnmhead#1#2{\absseclevel=\secbase\advance\absseclevel by #1 -\ifcase\absseclevel - \unnumberedzzz{#2} -\or - \unnumberedseczzz{#2} -\or - \unnumberedsubseczzz{#2} -\or - \unnumberedsubsubseczzz{#2} -\else - \ifnum \absseclevel<0 - \unnumberedzzz{#2} - \else - \unnumberedsubsubseczzz{#2} - \fi -\fi -} - -% @chapter, @appendix, @unnumbered. -\def\thischaptername{No Chapter Title} -\outer\def\chapter{\parsearg\chapteryyy} -\def\chapteryyy #1{\numhead0{#1}} % normally numhead0 calls chapterzzz -\def\chapterzzz #1{% -\secno=0 \subsecno=0 \subsubsecno=0 -\global\advance \chapno by 1 \message{\putwordChapter\space \the\chapno}% -\chapmacro {#1}{\the\chapno}% -\gdef\thissection{#1}% -\gdef\thischaptername{#1}% -% We don't substitute the actual chapter name into \thischapter -% because we don't want its macros evaluated now. -\xdef\thischapter{\putwordChapter{} \the\chapno: \noexpand\thischaptername}% -\toks0 = {#1}% -\edef\temp{\noexpand\writetocentry{\realbackslash chapentry{\the\toks0}% - {\the\chapno}}}% -\temp -\donoderef -\global\let\section = \numberedsec -\global\let\subsection = \numberedsubsec -\global\let\subsubsection = \numberedsubsubsec -} - -\outer\def\appendix{\parsearg\appendixyyy} -\def\appendixyyy #1{\apphead0{#1}} % normally apphead0 calls appendixzzz -\def\appendixzzz #1{% -\secno=0 \subsecno=0 \subsubsecno=0 -\global\advance \appendixno by 1 -\message{\putwordAppendix\space \appendixletter}% -\chapmacro {#1}{\putwordAppendix{} \appendixletter}% -\gdef\thissection{#1}% -\gdef\thischaptername{#1}% -\xdef\thischapter{\putwordAppendix{} \appendixletter: \noexpand\thischaptername}% -\toks0 = {#1}% -\edef\temp{\noexpand\writetocentry{\realbackslash appendixentry{\the\toks0}% - {\appendixletter}}}% -\temp -\appendixnoderef -\global\let\section = \appendixsec -\global\let\subsection = \appendixsubsec -\global\let\subsubsection = \appendixsubsubsec -} - -% @centerchap is like @unnumbered, but the heading is centered. -\outer\def\centerchap{\parsearg\centerchapyyy} -\def\centerchapyyy #1{{\let\unnumbchapmacro=\centerchapmacro \unnumberedyyy{#1}}} - -% @top is like @unnumbered. -\outer\def\top{\parsearg\unnumberedyyy} - -\outer\def\unnumbered{\parsearg\unnumberedyyy} -\def\unnumberedyyy #1{\unnmhead0{#1}} % normally unnmhead0 calls unnumberedzzz -\def\unnumberedzzz #1{% -\secno=0 \subsecno=0 \subsubsecno=0 -% -% This used to be simply \message{#1}, but TeX fully expands the -% argument to \message. Therefore, if #1 contained @-commands, TeX -% expanded them. For example, in `@unnumbered The @cite{Book}', TeX -% expanded @cite (which turns out to cause errors because \cite is meant -% to be executed, not expanded). -% -% Anyway, we don't want the fully-expanded definition of @cite to appear -% as a result of the \message, we just want `@cite' itself. We use -% \the to achieve this: TeX expands \the only once, -% simply yielding the contents of . (We also do this for -% the toc entries.) -\toks0 = {#1}\message{(\the\toks0)}% -% -\unnumbchapmacro {#1}% -\gdef\thischapter{#1}\gdef\thissection{#1}% -\toks0 = {#1}% -\edef\temp{\noexpand\writetocentry{\realbackslash unnumbchapentry{\the\toks0}}}% -\temp -\unnumbnoderef -\global\let\section = \unnumberedsec -\global\let\subsection = \unnumberedsubsec -\global\let\subsubsection = \unnumberedsubsubsec -} - -% Sections. -\outer\def\numberedsec{\parsearg\secyyy} -\def\secyyy #1{\numhead1{#1}} % normally calls seczzz -\def\seczzz #1{% -\subsecno=0 \subsubsecno=0 \global\advance \secno by 1 % -\gdef\thissection{#1}\secheading {#1}{\the\chapno}{\the\secno}% -\toks0 = {#1}% -\edef\temp{\noexpand\writetocentry{\realbackslash secentry{\the\toks0}% - {\the\chapno}{\the\secno}}}% -\temp -\donoderef -\nobreak -} - -\outer\def\appendixsection{\parsearg\appendixsecyyy} -\outer\def\appendixsec{\parsearg\appendixsecyyy} -\def\appendixsecyyy #1{\apphead1{#1}} % normally calls appendixsectionzzz -\def\appendixsectionzzz #1{% -\subsecno=0 \subsubsecno=0 \global\advance \secno by 1 % -\gdef\thissection{#1}\secheading {#1}{\appendixletter}{\the\secno}% -\toks0 = {#1}% -\edef\temp{\noexpand\writetocentry{\realbackslash secentry{\the\toks0}% - {\appendixletter}{\the\secno}}}% -\temp -\appendixnoderef -\nobreak -} - -\outer\def\unnumberedsec{\parsearg\unnumberedsecyyy} -\def\unnumberedsecyyy #1{\unnmhead1{#1}} % normally calls unnumberedseczzz -\def\unnumberedseczzz #1{% -\plainsecheading {#1}\gdef\thissection{#1}% -\toks0 = {#1}% -\edef\temp{\noexpand\writetocentry{\realbackslash unnumbsecentry{\the\toks0}}}% -\temp -\unnumbnoderef -\nobreak -} - -% Subsections. -\outer\def\numberedsubsec{\parsearg\numberedsubsecyyy} -\def\numberedsubsecyyy #1{\numhead2{#1}} % normally calls numberedsubseczzz -\def\numberedsubseczzz #1{% -\gdef\thissection{#1}\subsubsecno=0 \global\advance \subsecno by 1 % -\subsecheading {#1}{\the\chapno}{\the\secno}{\the\subsecno}% -\toks0 = {#1}% -\edef\temp{\noexpand\writetocentry{\realbackslash subsecentry{\the\toks0}% - {\the\chapno}{\the\secno}{\the\subsecno}}}% -\temp -\donoderef -\nobreak -} - -\outer\def\appendixsubsec{\parsearg\appendixsubsecyyy} -\def\appendixsubsecyyy #1{\apphead2{#1}} % normally calls appendixsubseczzz -\def\appendixsubseczzz #1{% -\gdef\thissection{#1}\subsubsecno=0 \global\advance \subsecno by 1 % -\subsecheading {#1}{\appendixletter}{\the\secno}{\the\subsecno}% -\toks0 = {#1}% -\edef\temp{\noexpand\writetocentry{\realbackslash subsecentry{\the\toks0}% - {\appendixletter}{\the\secno}{\the\subsecno}}}% -\temp -\appendixnoderef -\nobreak -} - -\outer\def\unnumberedsubsec{\parsearg\unnumberedsubsecyyy} -\def\unnumberedsubsecyyy #1{\unnmhead2{#1}} %normally calls unnumberedsubseczzz -\def\unnumberedsubseczzz #1{% -\plainsubsecheading {#1}\gdef\thissection{#1}% -\toks0 = {#1}% -\edef\temp{\noexpand\writetocentry{\realbackslash unnumbsubsecentry% - {\the\toks0}}}% -\temp -\unnumbnoderef -\nobreak -} - -% Subsubsections. -\outer\def\numberedsubsubsec{\parsearg\numberedsubsubsecyyy} -\def\numberedsubsubsecyyy #1{\numhead3{#1}} % normally numberedsubsubseczzz -\def\numberedsubsubseczzz #1{% -\gdef\thissection{#1}\global\advance \subsubsecno by 1 % -\subsubsecheading {#1} - {\the\chapno}{\the\secno}{\the\subsecno}{\the\subsubsecno}% -\toks0 = {#1}% -\edef\temp{\noexpand\writetocentry{\realbackslash subsubsecentry{\the\toks0}% - {\the\chapno}{\the\secno}{\the\subsecno}{\the\subsubsecno}}}% -\temp -\donoderef -\nobreak -} - -\outer\def\appendixsubsubsec{\parsearg\appendixsubsubsecyyy} -\def\appendixsubsubsecyyy #1{\apphead3{#1}} % normally appendixsubsubseczzz -\def\appendixsubsubseczzz #1{% -\gdef\thissection{#1}\global\advance \subsubsecno by 1 % -\subsubsecheading {#1} - {\appendixletter}{\the\secno}{\the\subsecno}{\the\subsubsecno}% -\toks0 = {#1}% -\edef\temp{\noexpand\writetocentry{\realbackslash subsubsecentry{\the\toks0}% - {\appendixletter}{\the\secno}{\the\subsecno}{\the\subsubsecno}}}% -\temp -\appendixnoderef -\nobreak -} - -\outer\def\unnumberedsubsubsec{\parsearg\unnumberedsubsubsecyyy} -\def\unnumberedsubsubsecyyy #1{\unnmhead3{#1}} %normally unnumberedsubsubseczzz -\def\unnumberedsubsubseczzz #1{% -\plainsubsubsecheading {#1}\gdef\thissection{#1}% -\toks0 = {#1}% -\edef\temp{\noexpand\writetocentry{\realbackslash unnumbsubsubsecentry% - {\the\toks0}}}% -\temp -\unnumbnoderef -\nobreak -} - -% These are variants which are not "outer", so they can appear in @ifinfo. -% Actually, they should now be obsolete; ordinary section commands should work. -\def\infotop{\parsearg\unnumberedzzz} -\def\infounnumbered{\parsearg\unnumberedzzz} -\def\infounnumberedsec{\parsearg\unnumberedseczzz} -\def\infounnumberedsubsec{\parsearg\unnumberedsubseczzz} -\def\infounnumberedsubsubsec{\parsearg\unnumberedsubsubseczzz} - -\def\infoappendix{\parsearg\appendixzzz} -\def\infoappendixsec{\parsearg\appendixseczzz} -\def\infoappendixsubsec{\parsearg\appendixsubseczzz} -\def\infoappendixsubsubsec{\parsearg\appendixsubsubseczzz} - -\def\infochapter{\parsearg\chapterzzz} -\def\infosection{\parsearg\sectionzzz} -\def\infosubsection{\parsearg\subsectionzzz} -\def\infosubsubsection{\parsearg\subsubsectionzzz} - -% These macros control what the section commands do, according -% to what kind of chapter we are in (ordinary, appendix, or unnumbered). -% Define them by default for a numbered chapter. -\global\let\section = \numberedsec -\global\let\subsection = \numberedsubsec -\global\let\subsubsection = \numberedsubsubsec - -% Define @majorheading, @heading and @subheading - -% NOTE on use of \vbox for chapter headings, section headings, and such: -% 1) We use \vbox rather than the earlier \line to permit -% overlong headings to fold. -% 2) \hyphenpenalty is set to 10000 because hyphenation in a -% heading is obnoxious; this forbids it. -% 3) Likewise, headings look best if no \parindent is used, and -% if justification is not attempted. Hence \raggedright. - - -\def\majorheading{\parsearg\majorheadingzzz} -\def\majorheadingzzz #1{% -{\advance\chapheadingskip by 10pt \chapbreak }% -{\chapfonts \vbox{\hyphenpenalty=10000\tolerance=5000 - \parindent=0pt\raggedright - \rm #1\hfill}}\bigskip \par\penalty 200} - -\def\chapheading{\parsearg\chapheadingzzz} -\def\chapheadingzzz #1{\chapbreak % -{\chapfonts \vbox{\hyphenpenalty=10000\tolerance=5000 - \parindent=0pt\raggedright - \rm #1\hfill}}\bigskip \par\penalty 200} - -% @heading, @subheading, @subsubheading. -\def\heading{\parsearg\plainsecheading} -\def\subheading{\parsearg\plainsubsecheading} -\def\subsubheading{\parsearg\plainsubsubsecheading} - -% These macros generate a chapter, section, etc. heading only -% (including whitespace, linebreaking, etc. around it), -% given all the information in convenient, parsed form. - -%%% Args are the skip and penalty (usually negative) -\def\dobreak#1#2{\par\ifdim\lastskip<#1\removelastskip\penalty#2\vskip#1\fi} - -\def\setchapterstyle #1 {\csname CHAPF#1\endcsname} - -%%% Define plain chapter starts, and page on/off switching for it -% Parameter controlling skip before chapter headings (if needed) - -\newskip\chapheadingskip - -\def\chapbreak{\dobreak \chapheadingskip {-4000}} -\def\chappager{\par\vfill\supereject} -\def\chapoddpage{\chappager \ifodd\pageno \else \hbox to 0pt{} \chappager\fi} - -\def\setchapternewpage #1 {\csname CHAPPAG#1\endcsname} - -\def\CHAPPAGoff{% -\global\let\contentsalignmacro = \chappager -\global\let\pchapsepmacro=\chapbreak -\global\let\pagealignmacro=\chappager} - -\def\CHAPPAGon{% -\global\let\contentsalignmacro = \chappager -\global\let\pchapsepmacro=\chappager -\global\let\pagealignmacro=\chappager -\global\def\HEADINGSon{\HEADINGSsingle}} - -\def\CHAPPAGodd{ -\global\let\contentsalignmacro = \chapoddpage -\global\let\pchapsepmacro=\chapoddpage -\global\let\pagealignmacro=\chapoddpage -\global\def\HEADINGSon{\HEADINGSdouble}} - -\CHAPPAGon - -\def\CHAPFplain{ -\global\let\chapmacro=\chfplain -\global\let\unnumbchapmacro=\unnchfplain -\global\let\centerchapmacro=\centerchfplain} - -% Plain chapter opening. -% #1 is the text, #2 the chapter number or empty if unnumbered. -\def\chfplain#1#2{% - \pchapsepmacro - {% - \chapfonts \rm - \def\chapnum{#2}% - \setbox0 = \hbox{#2\ifx\chapnum\empty\else\enspace\fi}% - \vbox{\hyphenpenalty=10000 \tolerance=5000 \parindent=0pt \raggedright - \hangindent = \wd0 \centerparametersmaybe - \unhbox0 #1\par}% - }% - \nobreak\bigskip % no page break after a chapter title - \nobreak -} - -% Plain opening for unnumbered. -\def\unnchfplain#1{\chfplain{#1}{}} - -% @centerchap -- centered and unnumbered. -\let\centerparametersmaybe = \relax -\def\centerchfplain#1{{% - \def\centerparametersmaybe{% - \advance\rightskip by 3\rightskip - \leftskip = \rightskip - \parfillskip = 0pt - }% - \chfplain{#1}{}% -}} - -\CHAPFplain % The default - -\def\unnchfopen #1{% -\chapoddpage {\chapfonts \vbox{\hyphenpenalty=10000\tolerance=5000 - \parindent=0pt\raggedright - \rm #1\hfill}}\bigskip \par\nobreak -} - -\def\chfopen #1#2{\chapoddpage {\chapfonts -\vbox to 3in{\vfil \hbox to\hsize{\hfil #2} \hbox to\hsize{\hfil #1} \vfil}}% -\par\penalty 5000 % -} - -\def\centerchfopen #1{% -\chapoddpage {\chapfonts \vbox{\hyphenpenalty=10000\tolerance=5000 - \parindent=0pt - \hfill {\rm #1}\hfill}}\bigskip \par\nobreak -} - -\def\CHAPFopen{ -\global\let\chapmacro=\chfopen -\global\let\unnumbchapmacro=\unnchfopen -\global\let\centerchapmacro=\centerchfopen} - - -% Section titles. -\newskip\secheadingskip -\def\secheadingbreak{\dobreak \secheadingskip {-1000}} -\def\secheading#1#2#3{\sectionheading{sec}{#2.#3}{#1}} -\def\plainsecheading#1{\sectionheading{sec}{}{#1}} - -% Subsection titles. -\newskip \subsecheadingskip -\def\subsecheadingbreak{\dobreak \subsecheadingskip {-500}} -\def\subsecheading#1#2#3#4{\sectionheading{subsec}{#2.#3.#4}{#1}} -\def\plainsubsecheading#1{\sectionheading{subsec}{}{#1}} - -% Subsubsection titles. -\let\subsubsecheadingskip = \subsecheadingskip -\let\subsubsecheadingbreak = \subsecheadingbreak -\def\subsubsecheading#1#2#3#4#5{\sectionheading{subsubsec}{#2.#3.#4.#5}{#1}} -\def\plainsubsubsecheading#1{\sectionheading{subsubsec}{}{#1}} - - -% Print any size section title. -% -% #1 is the section type (sec/subsec/subsubsec), #2 is the section -% number (maybe empty), #3 the text. -\def\sectionheading#1#2#3{% - {% - \expandafter\advance\csname #1headingskip\endcsname by \parskip - \csname #1headingbreak\endcsname - }% - {% - % Switch to the right set of fonts. - \csname #1fonts\endcsname \rm - % - % Only insert the separating space if we have a section number. - \def\secnum{#2}% - \setbox0 = \hbox{#2\ifx\secnum\empty\else\enspace\fi}% - % - \vbox{\hyphenpenalty=10000 \tolerance=5000 \parindent=0pt \raggedright - \hangindent = \wd0 % zero if no section number - \unhbox0 #3}% - }% - \ifdim\parskip<10pt \nobreak\kern10pt\nobreak\kern-\parskip\fi \nobreak -} - - -\message{toc,} -% Table of contents. -\newwrite\tocfile - -% Write an entry to the toc file, opening it if necessary. -% Called from @chapter, etc. We supply {\folio} at the end of the -% argument, which will end up as the last argument to the \...entry macro. -% -% We open the .toc file here instead of at @setfilename or any other -% given time so that @contents can be put in the document anywhere. -% -\newif\iftocfileopened -\def\writetocentry#1{% - \iftocfileopened\else - \immediate\openout\tocfile = \jobname.toc - \global\tocfileopenedtrue - \fi - \iflinks \write\tocfile{#1{\folio}}\fi -} - -\newskip\contentsrightmargin \contentsrightmargin=1in -\newcount\savepageno -\newcount\lastnegativepageno \lastnegativepageno = -1 - -% Finish up the main text and prepare to read what we've written -% to \tocfile. -% -\def\startcontents#1{% - % If @setchapternewpage on, and @headings double, the contents should - % start on an odd page, unlike chapters. Thus, we maintain - % \contentsalignmacro in parallel with \pagealignmacro. - % From: Torbjorn Granlund - \contentsalignmacro - \immediate\closeout\tocfile - % - % Don't need to put `Contents' or `Short Contents' in the headline. - % It is abundantly clear what they are. - \unnumbchapmacro{#1}\def\thischapter{}% - \savepageno = \pageno - \begingroup % Set up to handle contents files properly. - \catcode`\\=0 \catcode`\{=1 \catcode`\}=2 \catcode`\@=11 - % We can't do this, because then an actual ^ in a section - % title fails, e.g., @chapter ^ -- exponentiation. --karl, 9jul97. - %\catcode`\^=7 % to see ^^e4 as \"a etc. juha@piuha.ydi.vtt.fi - \raggedbottom % Worry more about breakpoints than the bottom. - \advance\hsize by -\contentsrightmargin % Don't use the full line length. - % - % Roman numerals for page numbers. - \ifnum \pageno>0 \pageno = \lastnegativepageno \fi -} - - -% Normal (long) toc. -\def\contents{% - \startcontents{\putwordTOC}% - \openin 1 \jobname.toc - \ifeof 1 \else - \closein 1 - \input \jobname.toc - \fi - \vfill \eject - \contentsalignmacro % in case @setchapternewpage odd is in effect - \pdfmakeoutlines - \endgroup - \lastnegativepageno = \pageno - \pageno = \savepageno -} - -% And just the chapters. -\def\summarycontents{% - \startcontents{\putwordShortTOC}% - % - \let\chapentry = \shortchapentry - \let\appendixentry = \shortappendixentry - \let\unnumbchapentry = \shortunnumberedentry - % We want a true roman here for the page numbers. - \secfonts - \let\rm=\shortcontrm \let\bf=\shortcontbf \let\sl=\shortcontsl - \rm - \hyphenpenalty = 10000 - \advance\baselineskip by 1pt % Open it up a little. - \def\secentry ##1##2##3##4{} - \def\unnumbsecentry ##1##2{} - \def\subsecentry ##1##2##3##4##5{} - \def\unnumbsubsecentry ##1##2{} - \def\subsubsecentry ##1##2##3##4##5##6{} - \def\unnumbsubsubsecentry ##1##2{} - \openin 1 \jobname.toc - \ifeof 1 \else - \closein 1 - \input \jobname.toc - \fi - \vfill \eject - \contentsalignmacro % in case @setchapternewpage odd is in effect - \endgroup - \lastnegativepageno = \pageno - \pageno = \savepageno -} -\let\shortcontents = \summarycontents - -\ifpdf - \pdfcatalog{/PageMode /UseOutlines}% -\fi - -% These macros generate individual entries in the table of contents. -% The first argument is the chapter or section name. -% The last argument is the page number. -% The arguments in between are the chapter number, section number, ... - -% Chapters, in the main contents. -\def\chapentry#1#2#3{\dochapentry{#2\labelspace#1}{#3}} -% -% Chapters, in the short toc. -% See comments in \dochapentry re vbox and related settings. -\def\shortchapentry#1#2#3{% - \tocentry{\shortchaplabel{#2}\labelspace #1}{\doshortpageno\bgroup#3\egroup}% -} - -% Appendices, in the main contents. -\def\appendixentry#1#2#3{\dochapentry{\putwordAppendix{} #2\labelspace#1}{#3}} -% -% Appendices, in the short toc. -\let\shortappendixentry = \shortchapentry - -% Typeset the label for a chapter or appendix for the short contents. -% The arg is, e.g., `Appendix A' for an appendix, or `3' for a chapter. -% We could simplify the code here by writing out an \appendixentry -% command in the toc file for appendices, instead of using \chapentry -% for both, but it doesn't seem worth it. -% -\newdimen\shortappendixwidth -% -\def\shortchaplabel#1{% - % This space should be enough, since a single number is .5em, and the - % widest letter (M) is 1em, at least in the Computer Modern fonts. - % But use \hss just in case. - % (This space doesn't include the extra space that gets added after - % the label; that gets put in by \shortchapentry above.) - \dimen0 = 1em - \hbox to \dimen0{#1\hss}% -} - -% Unnumbered chapters. -\def\unnumbchapentry#1#2{\dochapentry{#1}{#2}} -\def\shortunnumberedentry#1#2{\tocentry{#1}{\doshortpageno\bgroup#2\egroup}} - -% Sections. -\def\secentry#1#2#3#4{\dosecentry{#2.#3\labelspace#1}{#4}} -\def\unnumbsecentry#1#2{\dosecentry{#1}{#2}} - -% Subsections. -\def\subsecentry#1#2#3#4#5{\dosubsecentry{#2.#3.#4\labelspace#1}{#5}} -\def\unnumbsubsecentry#1#2{\dosubsecentry{#1}{#2}} - -% And subsubsections. -\def\subsubsecentry#1#2#3#4#5#6{% - \dosubsubsecentry{#2.#3.#4.#5\labelspace#1}{#6}} -\def\unnumbsubsubsecentry#1#2{\dosubsubsecentry{#1}{#2}} - -% This parameter controls the indentation of the various levels. -\newdimen\tocindent \tocindent = 3pc - -% Now for the actual typesetting. In all these, #1 is the text and #2 is the -% page number. -% -% If the toc has to be broken over pages, we want it to be at chapters -% if at all possible; hence the \penalty. -\def\dochapentry#1#2{% - \penalty-300 \vskip1\baselineskip plus.33\baselineskip minus.25\baselineskip - \begingroup - \chapentryfonts - \tocentry{#1}{\dopageno\bgroup#2\egroup}% - \endgroup - \nobreak\vskip .25\baselineskip plus.1\baselineskip -} - -\def\dosecentry#1#2{\begingroup - \secentryfonts \leftskip=\tocindent - \tocentry{#1}{\dopageno\bgroup#2\egroup}% -\endgroup} - -\def\dosubsecentry#1#2{\begingroup - \subsecentryfonts \leftskip=2\tocindent - \tocentry{#1}{\dopageno\bgroup#2\egroup}% -\endgroup} - -\def\dosubsubsecentry#1#2{\begingroup - \subsubsecentryfonts \leftskip=3\tocindent - \tocentry{#1}{\dopageno\bgroup#2\egroup}% -\endgroup} - -% Final typesetting of a toc entry; we use the same \entry macro as for -% the index entries, but we want to suppress hyphenation here. (We -% can't do that in the \entry macro, since index entries might consist -% of hyphenated-identifiers-that-do-not-fit-on-a-line-and-nothing-else.) -\def\tocentry#1#2{\begingroup - \vskip 0pt plus1pt % allow a little stretch for the sake of nice page breaks - % Do not use \turnoffactive in these arguments. Since the toc is - % typeset in cmr, characters such as _ would come out wrong; we - % have to do the usual translation tricks. - \entry{#1}{#2}% -\endgroup} - -% Space between chapter (or whatever) number and the title. -\def\labelspace{\hskip1em \relax} - -\def\dopageno#1{{\rm #1}} -\def\doshortpageno#1{{\rm #1}} - -\def\chapentryfonts{\secfonts \rm} -\def\secentryfonts{\textfonts} -\let\subsecentryfonts = \textfonts -\let\subsubsecentryfonts = \textfonts - - -\message{environments,} -% @foo ... @end foo. - -% Since these characters are used in examples, it should be an even number of -% \tt widths. Each \tt character is 1en, so two makes it 1em. -% Furthermore, these definitions must come after we define our fonts. -\newbox\dblarrowbox \newbox\longdblarrowbox -\newbox\pushcharbox \newbox\bullbox -\newbox\equivbox \newbox\errorbox - -%{\tentt -%\global\setbox\dblarrowbox = \hbox to 1em{\hfil$\Rightarrow$\hfil} -%\global\setbox\longdblarrowbox = \hbox to 1em{\hfil$\mapsto$\hfil} -%\global\setbox\pushcharbox = \hbox to 1em{\hfil$\dashv$\hfil} -%\global\setbox\equivbox = \hbox to 1em{\hfil$\ptexequiv$\hfil} -% Adapted from the manmac format (p.420 of TeXbook) -%\global\setbox\bullbox = \hbox to 1em{\kern.15em\vrule height .75ex width .85ex -% depth .1ex\hfil} -%} - -% @point{}, @result{}, @expansion{}, @print{}, @equiv{}. -\def\point{$\star$} -\def\result{\leavevmode\raise.15ex\hbox to 1em{\hfil$\Rightarrow$\hfil}} -\def\expansion{\leavevmode\raise.1ex\hbox to 1em{\hfil$\mapsto$\hfil}} -\def\print{\leavevmode\lower.1ex\hbox to 1em{\hfil$\dashv$\hfil}} -\def\equiv{\leavevmode\lower.1ex\hbox to 1em{\hfil$\ptexequiv$\hfil}} - -% Adapted from the TeXbook's \boxit. -{\tentt \global\dimen0 = 3em}% Width of the box. -\dimen2 = .55pt % Thickness of rules -% The text. (`r' is open on the right, `e' somewhat less so on the left.) -\setbox0 = \hbox{\kern-.75pt \tensf error\kern-1.5pt} - -\global\setbox\errorbox=\hbox to \dimen0{\hfil - \hsize = \dimen0 \advance\hsize by -5.8pt % Space to left+right. - \advance\hsize by -2\dimen2 % Rules. - \vbox{ - \hrule height\dimen2 - \hbox{\vrule width\dimen2 \kern3pt % Space to left of text. - \vtop{\kern2.4pt \box0 \kern2.4pt}% Space above/below. - \kern3pt\vrule width\dimen2}% Space to right. - \hrule height\dimen2} - \hfil} - -% The @error{} command. -\def\error{\leavevmode\lower.7ex\copy\errorbox} - -% @tex ... @end tex escapes into raw Tex temporarily. -% One exception: @ is still an escape character, so that @end tex works. -% But \@ or @@ will get a plain tex @ character. - -\def\tex{\begingroup - \catcode `\\=0 \catcode `\{=1 \catcode `\}=2 - \catcode `\$=3 \catcode `\&=4 \catcode `\#=6 - \catcode `\^=7 \catcode `\_=8 \catcode `\~=13 \let~=\tie - \catcode `\%=14 - \catcode 43=12 % plus - \catcode`\"=12 - \catcode`\==12 - \catcode`\|=12 - \catcode`\<=12 - \catcode`\>=12 - \escapechar=`\\ - % - \let\b=\ptexb - \let\bullet=\ptexbullet - \let\c=\ptexc - \let\,=\ptexcomma - \let\.=\ptexdot - \let\dots=\ptexdots - \let\equiv=\ptexequiv - \let\!=\ptexexclam - \let\i=\ptexi - \let\{=\ptexlbrace - \let\+=\tabalign - \let\}=\ptexrbrace - \let\*=\ptexstar - \let\t=\ptext - % - \def\endldots{\mathinner{\ldots\ldots\ldots\ldots}}% - \def\enddots{\relax\ifmmode\endldots\else$\mathsurround=0pt \endldots\,$\fi}% - \def\@{@}% -\let\Etex=\endgroup} - -% Define @lisp ... @endlisp. -% @lisp does a \begingroup so it can rebind things, -% including the definition of @endlisp (which normally is erroneous). - -% Amount to narrow the margins by for @lisp. -\newskip\lispnarrowing \lispnarrowing=0.4in - -% This is the definition that ^^M gets inside @lisp, @example, and other -% such environments. \null is better than a space, since it doesn't -% have any width. -\def\lisppar{\null\endgraf} - -% Make each space character in the input produce a normal interword -% space in the output. Don't allow a line break at this space, as this -% is used only in environments like @example, where each line of input -% should produce a line of output anyway. -% -{\obeyspaces % -\gdef\sepspaces{\obeyspaces\let =\tie}} - -% Define \obeyedspace to be our active space, whatever it is. This is -% for use in \parsearg. -{\sepspaces% -\global\let\obeyedspace= } - -% This space is always present above and below environments. -\newskip\envskipamount \envskipamount = 0pt - -% Make spacing and below environment symmetrical. We use \parskip here -% to help in doing that, since in @example-like environments \parskip -% is reset to zero; thus the \afterenvbreak inserts no space -- but the -% start of the next paragraph will insert \parskip -% -\def\aboveenvbreak{{% - \ifnum\lastpenalty < 10000 - \advance\envskipamount by \parskip - \endgraf - \ifdim\lastskip<\envskipamount - \removelastskip - \penalty-50 - \vskip\envskipamount - \fi - \fi -}} - -\let\afterenvbreak = \aboveenvbreak - -% \nonarrowing is a flag. If "set", @lisp etc don't narrow margins. -\let\nonarrowing=\relax - -% @cartouche ... @end cartouche: draw rectangle w/rounded corners around -% environment contents. -\font\circle=lcircle10 -\newdimen\circthick -\newdimen\cartouter\newdimen\cartinner -\newskip\normbskip\newskip\normpskip\newskip\normlskip -\circthick=\fontdimen8\circle -% -\def\ctl{{\circle\char'013\hskip -6pt}}% 6pt from pl file: 1/2charwidth -\def\ctr{{\hskip 6pt\circle\char'010}} -\def\cbl{{\circle\char'012\hskip -6pt}} -\def\cbr{{\hskip 6pt\circle\char'011}} -\def\carttop{\hbox to \cartouter{\hskip\lskip - \ctl\leaders\hrule height\circthick\hfil\ctr - \hskip\rskip}} -\def\cartbot{\hbox to \cartouter{\hskip\lskip - \cbl\leaders\hrule height\circthick\hfil\cbr - \hskip\rskip}} -% -\newskip\lskip\newskip\rskip - -\long\def\cartouche{% -\begingroup - \lskip=\leftskip \rskip=\rightskip - \leftskip=0pt\rightskip=0pt %we want these *outside*. - \cartinner=\hsize \advance\cartinner by-\lskip - \advance\cartinner by-\rskip - \cartouter=\hsize - \advance\cartouter by 18.4pt % allow for 3pt kerns on either -% side, and for 6pt waste from -% each corner char, and rule thickness - \normbskip=\baselineskip \normpskip=\parskip \normlskip=\lineskip - % Flag to tell @lisp, etc., not to narrow margin. - \let\nonarrowing=\comment - \vbox\bgroup - \baselineskip=0pt\parskip=0pt\lineskip=0pt - \carttop - \hbox\bgroup - \hskip\lskip - \vrule\kern3pt - \vbox\bgroup - \hsize=\cartinner - \kern3pt - \begingroup - \baselineskip=\normbskip - \lineskip=\normlskip - \parskip=\normpskip - \vskip -\parskip -\def\Ecartouche{% - \endgroup - \kern3pt - \egroup - \kern3pt\vrule - \hskip\rskip - \egroup - \cartbot - \egroup -\endgroup -}} - - -% This macro is called at the beginning of all the @example variants, -% inside a group. -\def\nonfillstart{% - \aboveenvbreak - \inENV % This group ends at the end of the body - \hfuzz = 12pt % Don't be fussy - \sepspaces % Make spaces be word-separators rather than space tokens. - \singlespace - \let\par = \lisppar % don't ignore blank lines - \obeylines % each line of input is a line of output - \parskip = 0pt - \parindent = 0pt - \emergencystretch = 0pt % don't try to avoid overfull boxes - % @cartouche defines \nonarrowing to inhibit narrowing - % at next level down. - \ifx\nonarrowing\relax - \advance \leftskip by \lispnarrowing - \exdentamount=\lispnarrowing - \let\exdent=\nofillexdent - \let\nonarrowing=\relax - \fi -} - -% Define the \E... control sequence only if we are inside the particular -% environment, so the error checking in \end will work. -% -% To end an @example-like environment, we first end the paragraph (via -% \afterenvbreak's vertical glue), and then the group. That way we keep -% the zero \parskip that the environments set -- \parskip glue will be -% inserted at the beginning of the next paragraph in the document, after -% the environment. -% -\def\nonfillfinish{\afterenvbreak\endgroup} - -% @lisp: indented, narrowed, typewriter font. -\def\lisp{\begingroup - \nonfillstart - \let\Elisp = \nonfillfinish - \tt - \let\kbdfont = \kbdexamplefont % Allow @kbd to do something special. - \gobble % eat return -} - -% @example: Same as @lisp. -\def\example{\begingroup \def\Eexample{\nonfillfinish\endgroup}\lisp} - -% @small... is usually equivalent to the non-small (@smallbook -% redefines). We must call \example (or whatever) last in the -% definition, since it reads the return following the @example (or -% whatever) command. -% -% This actually allows (for example) @end display inside an -% @smalldisplay. Too bad, but makeinfo will catch the error anyway. -% -\def\smalldisplay{\begingroup\def\Esmalldisplay{\nonfillfinish\endgroup}\display} -\def\smallexample{\begingroup\def\Esmallexample{\nonfillfinish\endgroup}\lisp} -\def\smallformat{\begingroup\def\Esmallformat{\nonfillfinish\endgroup}\format} -\def\smalllisp{\begingroup\def\Esmalllisp{\nonfillfinish\endgroup}\lisp} - -% Real @smallexample and @smalllisp (when @smallbook): use smaller fonts. -% Originally contributed by Pavel@xerox. -\def\smalllispx{\begingroup - \def\Esmalllisp{\nonfillfinish\endgroup}% - \def\Esmallexample{\nonfillfinish\endgroup}% - \smallexamplefonts - \lisp -} - -% @display: same as @lisp except keep current font. -% -\def\display{\begingroup - \nonfillstart - \let\Edisplay = \nonfillfinish - \gobble -} -% -% @smalldisplay (when @smallbook): @display plus smaller fonts. -% -\def\smalldisplayx{\begingroup - \def\Esmalldisplay{\nonfillfinish\endgroup}% - \smallexamplefonts \rm - \display -} - -% @format: same as @display except don't narrow margins. -% -\def\format{\begingroup - \let\nonarrowing = t - \nonfillstart - \let\Eformat = \nonfillfinish - \gobble -} -% -% @smallformat (when @smallbook): @format plus smaller fonts. -% -\def\smallformatx{\begingroup - \def\Esmallformat{\nonfillfinish\endgroup}% - \smallexamplefonts \rm - \format -} - -% @flushleft (same as @format). -% -\def\flushleft{\begingroup \def\Eflushleft{\nonfillfinish\endgroup}\format} - -% @flushright. -% -\def\flushright{\begingroup - \let\nonarrowing = t - \nonfillstart - \let\Eflushright = \nonfillfinish - \advance\leftskip by 0pt plus 1fill - \gobble -} - - -% @quotation does normal linebreaking (hence we can't use \nonfillstart) -% and narrows the margins. -% -\def\quotation{% - \begingroup\inENV %This group ends at the end of the @quotation body - {\parskip=0pt \aboveenvbreak}% because \aboveenvbreak inserts \parskip - \singlespace - \parindent=0pt - % We have retained a nonzero parskip for the environment, since we're - % doing normal filling. So to avoid extra space below the environment... - \def\Equotation{\parskip = 0pt \nonfillfinish}% - % - % @cartouche defines \nonarrowing to inhibit narrowing at next level down. - \ifx\nonarrowing\relax - \advance\leftskip by \lispnarrowing - \advance\rightskip by \lispnarrowing - \exdentamount = \lispnarrowing - \let\nonarrowing = \relax - \fi -} - - -% LaTeX-like @verbatim...@end verbatim and @verb{...} -% If we want to allow any as delimiter, -% we need the curly braces so that makeinfo sees the @verb command, eg: -% `@verbx...x' would look like the '@verbx' command. --janneke@gnu.org -% -% [Knuth]: Donald Ervin Knuth, 1996. The TeXbook. -% -% [Knuth] p. 344; only we need to do '@' too -\def\dospecials{% - \do\ \do\\\do\@\do\{\do\}\do\$\do\&% - \do\#\do\^\do\^^K\do\_\do\^^A\do\%\do\~} -% -% [Knuth] p. 380 -\def\uncatcodespecials{% - \def\do##1{\catcode`##1=12}\dospecials} -% -% [Knuth] pp. 380,381,391 -% Disable Spanish ligatures ?` and !` of \tt font -\begingroup - \catcode`\`=\active\gdef`{\relax\lq} -\endgroup -% -% Setup for the @verb command. -% -% Eight spaces for a tab -\begingroup - \catcode`\^^I=\active - \gdef\tabeightspaces{\catcode`\^^I=\active\def^^I{\ \ \ \ \ \ \ \ }} -\endgroup -% -\def\setupverb{% - \tt % easiest (and conventionally used) font for verbatim - \def\par{\leavevmode\endgraf}% - \catcode`\`=\active - \tabeightspaces - % Respect line breaks, - % print special symbols as themselves, and - % make each space count - % must do in this order: - \obeylines \uncatcodespecials \sepspaces -} - -% Setup for the @verbatim environment -% -% Real tab expansion -\newdimen\tabw \setbox0=\hbox{\tt\space} \tabw=8\wd0 % tab amount -% -\def\starttabbox{\setbox0=\hbox\bgroup} -\begingroup - \catcode`\^^I=\active - \gdef\tabexpand{% - \catcode`\^^I=\active - \def^^I{\leavevmode\egroup - \dimen0=\wd0 % the width so far, or since the previous tab - \divide\dimen0 by\tabw - \multiply\dimen0 by\tabw % compute previous multiple of \tabw - \advance\dimen0 by\tabw % advance to next multiple of \tabw - \wd0=\dimen0 \box0 \starttabbox - }% - } -\endgroup -\def\setupverbatim{% - % Easiest (and conventionally used) font for verbatim - \tt - \def\par{\leavevmode\egroup\box0\endgraf}% - \catcode`\`=\active - \tabexpand - % Respect line breaks, - % print special symbols as themselves, and - % make each space count - % must do in this order: - \obeylines \uncatcodespecials \sepspaces - \everypar{\starttabbox}% -} - -% Do the @verb magic: verbatim text is quoted by unique -% delimiter characters. Before first delimiter expect a -% right brace, after last delimiter expect closing brace: -% -% \def\doverb'{'#1'}'{#1} -% -% [Knuth] p. 382; only eat outer {} -\begingroup - \catcode`[=1\catcode`]=2\catcode`\{=12\catcode`\}=12 - \gdef\doverb{#1[\def\next##1#1}[##1\endgroup]\next] -\endgroup -% -\def\verb{\begingroup\setupverb\doverb} -% -% -% Do the @verbatim magic: define the macro \doverbatim so that -% the (first) argument ends when '@end verbatim' is reached, ie: -% -% \def\doverbatim#1@end verbatim{#1} -% -% For Texinfo it's a lot easier than for LaTeX, -% because texinfo's \verbatim doesn't stop at '\end{verbatim}': -% we need not redefine '\', '{' and '}' -% -% Inspired by LaTeX's verbatim command set [latex.ltx] -%% Include LaTeX hack for completeness -- never know -%% \begingroup -%% \catcode`|=0 \catcode`[=1 -%% \catcode`]=2\catcode`\{=12\catcode`\}=12\catcode`\ =\active -%% \catcode`\\=12|gdef|doverbatim#1@end verbatim[ -%% #1|endgroup|def|Everbatim[]|end[verbatim]] -%% |endgroup -\begingroup - \catcode`\ =\active - \gdef\doverbatim#1@end verbatim{#1\end{verbatim}} -\endgroup -% -\def\verbatim{% - \def\Everbatim{\nonfillfinish\endgroup}% - \begingroup - \nonfillstart - \advance\leftskip by -\defbodyindent - \begingroup\setupverbatim\doverbatim -} - -% @verbatiminclude FILE - insert text of file in verbatim environment. -% -% Allow normal characters that we make active in the argument (a file name). -\def\verbatiminclude{% - \begingroup - \catcode`\\=12 - \catcode`~=12 - \catcode`^=12 - \catcode`_=12 - \catcode`|=12 - \catcode`<=12 - \catcode`>=12 - \catcode`+=12 - \parsearg\doverbatiminclude -} -\def\setupverbatiminclude{% - \begingroup - \nonfillstart - \advance\leftskip by -\defbodyindent - \begingroup\setupverbatim -} -% -\def\doverbatiminclude#1{% - % Restore active chars for included file. - \endgroup - \begingroup - \def\thisfile{#1}% - \expandafter\expandafter\setupverbatiminclude\input\thisfile - \endgroup\nonfillfinish\endgroup -} - - -\message{defuns,} -% @defun etc. - -% Allow user to change definition object font (\df) internally -\def\setdeffont #1 {\csname DEF#1\endcsname} - -\newskip\defbodyindent \defbodyindent=.4in -\newskip\defargsindent \defargsindent=50pt -\newskip\deftypemargin \deftypemargin=12pt -\newskip\deflastargmargin \deflastargmargin=18pt - -\newcount\parencount -% define \functionparens, which makes ( and ) and & do special things. -% \functionparens affects the group it is contained in. -\def\activeparens{% -\catcode`\(=\active \catcode`\)=\active \catcode`\&=\active -\catcode`\[=\active \catcode`\]=\active} - -% Make control sequences which act like normal parenthesis chars. -\let\lparen = ( \let\rparen = ) - -{\activeparens % Now, smart parens don't turn on until &foo (see \amprm) - -% Be sure that we always have a definition for `(', etc. For example, -% if the fn name has parens in it, \boldbrax will not be in effect yet, -% so TeX would otherwise complain about undefined control sequence. -\global\let(=\lparen \global\let)=\rparen -\global\let[=\lbrack \global\let]=\rbrack - -\gdef\functionparens{\boldbrax\let&=\amprm\parencount=0 } -\gdef\boldbrax{\let(=\opnr\let)=\clnr\let[=\lbrb\let]=\rbrb} -% This is used to turn on special parens -% but make & act ordinary (given that it's active). -\gdef\boldbraxnoamp{\let(=\opnr\let)=\clnr\let[=\lbrb\let]=\rbrb\let&=\ampnr} - -% Definitions of (, ) and & used in args for functions. -% This is the definition of ( outside of all parentheses. -\gdef\oprm#1 {{\rm\char`\(}#1 \bf \let(=\opnested - \global\advance\parencount by 1 -} -% -% This is the definition of ( when already inside a level of parens. -\gdef\opnested{\char`\(\global\advance\parencount by 1 } -% -\gdef\clrm{% Print a paren in roman if it is taking us back to depth of 0. - % also in that case restore the outer-level definition of (. - \ifnum \parencount=1 {\rm \char `\)}\sl \let(=\oprm \else \char `\) \fi - \global\advance \parencount by -1 } -% If we encounter &foo, then turn on ()-hacking afterwards -\gdef\amprm#1 {{\rm\}\let(=\oprm \let)=\clrm\ } -% -\gdef\normalparens{\boldbrax\let&=\ampnr} -} % End of definition inside \activeparens -%% These parens (in \boldbrax) actually are a little bolder than the -%% contained text. This is especially needed for [ and ] -\def\opnr{{\sf\char`\(}\global\advance\parencount by 1 } -\def\clnr{{\sf\char`\)}\global\advance\parencount by -1 } -\let\ampnr = \& -\def\lbrb{{\bf\char`\[}} -\def\rbrb{{\bf\char`\]}} - -% Active &'s sneak into the index arguments, so make sure it's defined. -{ - \catcode`& = 13 - \global\let& = \ampnr -} - -% First, defname, which formats the header line itself. -% #1 should be the function name. -% #2 should be the type of definition, such as "Function". - -\def\defname #1#2{% -% Get the values of \leftskip and \rightskip as they were -% outside the @def... -\dimen2=\leftskip -\advance\dimen2 by -\defbodyindent -\noindent -\setbox0=\hbox{\hskip \deflastargmargin{\rm #2}\hskip \deftypemargin}% -\dimen0=\hsize \advance \dimen0 by -\wd0 % compute size for first line -\dimen1=\hsize \advance \dimen1 by -\defargsindent %size for continuations -\parshape 2 0in \dimen0 \defargsindent \dimen1 -% Now output arg 2 ("Function" or some such) -% ending at \deftypemargin from the right margin, -% but stuck inside a box of width 0 so it does not interfere with linebreaking -{% Adjust \hsize to exclude the ambient margins, -% so that \rightline will obey them. -\advance \hsize by -\dimen2 -\rlap{\rightline{{\rm #2}\hskip -1.25pc }}}% -% Make all lines underfull and no complaints: -\tolerance=10000 \hbadness=10000 -\advance\leftskip by -\defbodyindent -\exdentamount=\defbodyindent -{\df #1}\enskip % Generate function name -} - -% Actually process the body of a definition -% #1 should be the terminating control sequence, such as \Edefun. -% #2 should be the "another name" control sequence, such as \defunx. -% #3 should be the control sequence that actually processes the header, -% such as \defunheader. - -\def\defparsebody #1#2#3{\begingroup\inENV% Environment for definitionbody -\medbreak % -% Define the end token that this defining construct specifies -% so that it will exit this group. -\def#1{\endgraf\endgroup\medbreak}% -\def#2{\begingroup\obeylines\activeparens\spacesplit#3}% -\parindent=0in -\advance\leftskip by \defbodyindent -\exdentamount=\defbodyindent -\begingroup % -\catcode 61=\active % 61 is `=' -\obeylines\activeparens\spacesplit#3} - -% #1 is the \E... control sequence to end the definition (which we define). -% #2 is the \...x control sequence for consecutive fns (which we define). -% #3 is the control sequence to call to resume processing. -% #4, delimited by the space, is the class name. -% -\def\defmethparsebody#1#2#3#4 {\begingroup\inENV % -\medbreak % -% Define the end token that this defining construct specifies -% so that it will exit this group. -\def#1{\endgraf\endgroup\medbreak}% -\def#2##1 {\begingroup\obeylines\activeparens\spacesplit{#3{##1}}}% -\parindent=0in -\advance\leftskip by \defbodyindent -\exdentamount=\defbodyindent -\begingroup\obeylines\activeparens\spacesplit{#3{#4}}} - -% Used for @deftypemethod and @deftypeivar. -% #1 is the \E... control sequence to end the definition (which we define). -% #2 is the \...x control sequence for consecutive fns (which we define). -% #3 is the control sequence to call to resume processing. -% #4, delimited by a space, is the class name. -% #5 is the method's return type. -% -\def\deftypemethparsebody#1#2#3#4 #5 {\begingroup\inENV - \medbreak - \def#1{\endgraf\endgroup\medbreak}% - \def#2##1 ##2 {\begingroup\obeylines\activeparens\spacesplit{#3{##1}{##2}}}% - \parindent=0in - \advance\leftskip by \defbodyindent - \exdentamount=\defbodyindent - \begingroup\obeylines\activeparens\spacesplit{#3{#4}{#5}}} - -% Used for @deftypeop. The change from \deftypemethparsebody is an -% extra argument at the beginning which is the `category', instead of it -% being the hardwired string `Method' or `Instance Variable'. We have -% to account for this both in the \...x definition and in parsing the -% input at hand. Thus also need a control sequence (passed as #5) for -% the \E... definition to assign the category name to. -% -\def\deftypeopparsebody#1#2#3#4#5 #6 {\begingroup\inENV - \medbreak - \def#1{\endgraf\endgroup\medbreak}% - \def#2##1 ##2 ##3 {% - \def#4{##1}% - \begingroup\obeylines\activeparens\spacesplit{#3{##2}{##3}}}% - \parindent=0in - \advance\leftskip by \defbodyindent - \exdentamount=\defbodyindent - \begingroup\obeylines\activeparens\spacesplit{#3{#5}{#6}}} - -\def\defopparsebody #1#2#3#4#5 {\begingroup\inENV % -\medbreak % -% Define the end token that this defining construct specifies -% so that it will exit this group. -\def#1{\endgraf\endgroup\medbreak}% -\def#2##1 ##2 {\def#4{##1}% -\begingroup\obeylines\activeparens\spacesplit{#3{##2}}}% -\parindent=0in -\advance\leftskip by \defbodyindent -\exdentamount=\defbodyindent -\begingroup\obeylines\activeparens\spacesplit{#3{#5}}} - -% These parsing functions are similar to the preceding ones -% except that they do not make parens into active characters. -% These are used for "variables" since they have no arguments. - -\def\defvarparsebody #1#2#3{\begingroup\inENV% Environment for definitionbody -\medbreak % -% Define the end token that this defining construct specifies -% so that it will exit this group. -\def#1{\endgraf\endgroup\medbreak}% -\def#2{\begingroup\obeylines\spacesplit#3}% -\parindent=0in -\advance\leftskip by \defbodyindent -\exdentamount=\defbodyindent -\begingroup % -\catcode 61=\active % -\obeylines\spacesplit#3} - -% This is used for \def{tp,vr}parsebody. It could probably be used for -% some of the others, too, with some judicious conditionals. -% -\def\parsebodycommon#1#2#3{% - \begingroup\inENV % - \medbreak % - % Define the end token that this defining construct specifies - % so that it will exit this group. - \def#1{\endgraf\endgroup\medbreak}% - \def#2##1 {\begingroup\obeylines\spacesplit{#3{##1}}}% - \parindent=0in - \advance\leftskip by \defbodyindent - \exdentamount=\defbodyindent - \begingroup\obeylines -} - -\def\defvrparsebody#1#2#3#4 {% - \parsebodycommon{#1}{#2}{#3}% - \spacesplit{#3{#4}}% -} - -% This loses on `@deftp {Data Type} {struct termios}' -- it thinks the -% type is just `struct', because we lose the braces in `{struct -% termios}' when \spacesplit reads its undelimited argument. Sigh. -% \let\deftpparsebody=\defvrparsebody -% -% So, to get around this, we put \empty in with the type name. That -% way, TeX won't find exactly `{...}' as an undelimited argument, and -% won't strip off the braces. -% -\def\deftpparsebody #1#2#3#4 {% - \parsebodycommon{#1}{#2}{#3}% - \spacesplit{\parsetpheaderline{#3{#4}}}\empty -} - -% Fine, but then we have to eventually remove the \empty *and* the -% braces (if any). That's what this does. -% -\def\removeemptybraces\empty#1\relax{#1} - -% After \spacesplit has done its work, this is called -- #1 is the final -% thing to call, #2 the type name (which starts with \empty), and #3 -% (which might be empty) the arguments. -% -\def\parsetpheaderline#1#2#3{% - #1{\removeemptybraces#2\relax}{#3}% -}% - -\def\defopvarparsebody #1#2#3#4#5 {\begingroup\inENV % -\medbreak % -% Define the end token that this defining construct specifies -% so that it will exit this group. -\def#1{\endgraf\endgroup\medbreak}% -\def#2##1 ##2 {\def#4{##1}% -\begingroup\obeylines\spacesplit{#3{##2}}}% -\parindent=0in -\advance\leftskip by \defbodyindent -\exdentamount=\defbodyindent -\begingroup\obeylines\spacesplit{#3{#5}}} - -% Split up #2 at the first space token. -% call #1 with two arguments: -% the first is all of #2 before the space token, -% the second is all of #2 after that space token. -% If #2 contains no space token, all of it is passed as the first arg -% and the second is passed as empty. - -{\obeylines -\gdef\spacesplit#1#2^^M{\endgroup\spacesplitfoo{#1}#2 \relax\spacesplitfoo}% -\long\gdef\spacesplitfoo#1#2 #3#4\spacesplitfoo{% -\ifx\relax #3% -#1{#2}{}\else #1{#2}{#3#4}\fi}} - -% So much for the things common to all kinds of definitions. - -% Define @defun. - -% First, define the processing that is wanted for arguments of \defun -% Use this to expand the args and terminate the paragraph they make up - -\def\defunargs#1{\functionparens \sl -% Expand, preventing hyphenation at `-' chars. -% Note that groups don't affect changes in \hyphenchar. -% Set the font temporarily and use \font in case \setfont made \tensl a macro. -{\tensl\hyphenchar\font=0}% -#1% -{\tensl\hyphenchar\font=45}% -\ifnum\parencount=0 \else \errmessage{Unbalanced parentheses in @def}\fi% -\interlinepenalty=10000 -\advance\rightskip by 0pt plus 1fil -\endgraf\nobreak\vskip -\parskip\nobreak -} - -\def\deftypefunargs #1{% -% Expand, preventing hyphenation at `-' chars. -% Note that groups don't affect changes in \hyphenchar. -% Use \boldbraxnoamp, not \functionparens, so that & is not special. -\boldbraxnoamp -\tclose{#1}% avoid \code because of side effects on active chars -\interlinepenalty=10000 -\advance\rightskip by 0pt plus 1fil -\endgraf\nobreak\vskip -\parskip\nobreak -} - -% Do complete processing of one @defun or @defunx line already parsed. - -% @deffn Command forward-char nchars - -\def\deffn{\defmethparsebody\Edeffn\deffnx\deffnheader} - -\def\deffnheader #1#2#3{\doind {fn}{\code{#2}}% -\begingroup\defname {#2}{#1}\defunargs{#3}\endgroup % -\catcode 61=\other % Turn off change made in \defparsebody -} - -% @defun == @deffn Function - -\def\defun{\defparsebody\Edefun\defunx\defunheader} - -\def\defunheader #1#2{\doind {fn}{\code{#1}}% Make entry in function index -\begingroup\defname {#1}{\putwordDeffunc}% -\defunargs {#2}\endgroup % -\catcode 61=\other % Turn off change made in \defparsebody -} - -% @deftypefun int foobar (int @var{foo}, float @var{bar}) - -\def\deftypefun{\defparsebody\Edeftypefun\deftypefunx\deftypefunheader} - -% #1 is the data type. #2 is the name and args. -\def\deftypefunheader #1#2{\deftypefunheaderx{#1}#2 \relax} -% #1 is the data type, #2 the name, #3 the args. -\def\deftypefunheaderx #1#2 #3\relax{% -\doind {fn}{\code{#2}}% Make entry in function index -\begingroup\defname {\defheaderxcond#1\relax$.$#2}{\putwordDeftypefun}% -\deftypefunargs {#3}\endgroup % -\catcode 61=\other % Turn off change made in \defparsebody -} - -% @deftypefn {Library Function} int foobar (int @var{foo}, float @var{bar}) - -\def\deftypefn{\defmethparsebody\Edeftypefn\deftypefnx\deftypefnheader} - -% \defheaderxcond#1\relax$.$ -% puts #1 in @code, followed by a space, but does nothing if #1 is null. -\def\defheaderxcond#1#2$.${\ifx#1\relax\else\code{#1#2} \fi} - -% #1 is the classification. #2 is the data type. #3 is the name and args. -\def\deftypefnheader #1#2#3{\deftypefnheaderx{#1}{#2}#3 \relax} -% #1 is the classification, #2 the data type, #3 the name, #4 the args. -\def\deftypefnheaderx #1#2#3 #4\relax{% -\doind {fn}{\code{#3}}% Make entry in function index -\begingroup -\normalparens % notably, turn off `&' magic, which prevents -% at least some C++ text from working -\defname {\defheaderxcond#2\relax$.$#3}{#1}% -\deftypefunargs {#4}\endgroup % -\catcode 61=\other % Turn off change made in \defparsebody -} - -% @defmac == @deffn Macro - -\def\defmac{\defparsebody\Edefmac\defmacx\defmacheader} - -\def\defmacheader #1#2{\doind {fn}{\code{#1}}% Make entry in function index -\begingroup\defname {#1}{\putwordDefmac}% -\defunargs {#2}\endgroup % -\catcode 61=\other % Turn off change made in \defparsebody -} - -% @defspec == @deffn Special Form - -\def\defspec{\defparsebody\Edefspec\defspecx\defspecheader} - -\def\defspecheader #1#2{\doind {fn}{\code{#1}}% Make entry in function index -\begingroup\defname {#1}{\putwordDefspec}% -\defunargs {#2}\endgroup % -\catcode 61=\other % Turn off change made in \defparsebody -} - -% @defop CATEGORY CLASS OPERATION ARG... -% -\def\defop #1 {\def\defoptype{#1}% -\defopparsebody\Edefop\defopx\defopheader\defoptype} -% -\def\defopheader#1#2#3{% -\dosubind {fn}{\code{#2}}{\putwordon\ #1}% Make entry in function index -\begingroup\defname {#2}{\defoptype\ \putwordon\ #1}% -\defunargs {#3}\endgroup % -} - -% @deftypeop CATEGORY CLASS TYPE OPERATION ARG... -% -\def\deftypeop #1 {\def\deftypeopcategory{#1}% - \deftypeopparsebody\Edeftypeop\deftypeopx\deftypeopheader - \deftypeopcategory} -% -% #1 is the class name, #2 the data type, #3 the operation name, #4 the args. -\def\deftypeopheader#1#2#3#4{% - \dosubind{fn}{\code{#3}}{\putwordon\ \code{#1}}% entry in function index - \begingroup - \defname{\defheaderxcond#2\relax$.$#3} - {\deftypeopcategory\ \putwordon\ \code{#1}}% - \deftypefunargs{#4}% - \endgroup -} - -% @deftypemethod CLASS TYPE METHOD ARG... -% -\def\deftypemethod{% - \deftypemethparsebody\Edeftypemethod\deftypemethodx\deftypemethodheader} -% -% #1 is the class name, #2 the data type, #3 the method name, #4 the args. -\def\deftypemethodheader#1#2#3#4{% - \dosubind{fn}{\code{#3}}{\putwordon\ \code{#1}}% entry in function index - \begingroup - \defname{\defheaderxcond#2\relax$.$#3}{\putwordMethodon\ \code{#1}}% - \deftypefunargs{#4}% - \endgroup -} - -% @deftypeivar CLASS TYPE VARNAME -% -\def\deftypeivar{% - \deftypemethparsebody\Edeftypeivar\deftypeivarx\deftypeivarheader} -% -% #1 is the class name, #2 the data type, #3 the variable name. -\def\deftypeivarheader#1#2#3{% - \dosubind{vr}{\code{#3}}{\putwordof\ \code{#1}}% entry in variable index - \begingroup - \defname{\defheaderxcond#2\relax$.$#3} - {\putwordInstanceVariableof\ \code{#1}}% - \defvarargs{#3}% - \endgroup -} - -% @defmethod == @defop Method -% -\def\defmethod{\defmethparsebody\Edefmethod\defmethodx\defmethodheader} -% -% #1 is the class name, #2 the method name, #3 the args. -\def\defmethodheader#1#2#3{% - \dosubind{fn}{\code{#2}}{\putwordon\ \code{#1}}% entry in function index - \begingroup - \defname{#2}{\putwordMethodon\ \code{#1}}% - \defunargs{#3}% - \endgroup -} - -% @defcv {Class Option} foo-class foo-flag - -\def\defcv #1 {\def\defcvtype{#1}% -\defopvarparsebody\Edefcv\defcvx\defcvarheader\defcvtype} - -\def\defcvarheader #1#2#3{% -\dosubind {vr}{\code{#2}}{\putwordof\ #1}% Make entry in var index -\begingroup\defname {#2}{\defcvtype\ \putwordof\ #1}% -\defvarargs {#3}\endgroup % -} - -% @defivar CLASS VARNAME == @defcv {Instance Variable} CLASS VARNAME -% -\def\defivar{\defvrparsebody\Edefivar\defivarx\defivarheader} -% -\def\defivarheader#1#2#3{% - \dosubind {vr}{\code{#2}}{\putwordof\ #1}% entry in var index - \begingroup - \defname{#2}{\putwordInstanceVariableof\ #1}% - \defvarargs{#3}% - \endgroup -} - -% @defvar -% First, define the processing that is wanted for arguments of @defvar. -% This is actually simple: just print them in roman. -% This must expand the args and terminate the paragraph they make up -\def\defvarargs #1{\normalparens #1% -\interlinepenalty=10000 -\endgraf\nobreak\vskip -\parskip\nobreak} - -% @defvr Counter foo-count - -\def\defvr{\defvrparsebody\Edefvr\defvrx\defvrheader} - -\def\defvrheader #1#2#3{\doind {vr}{\code{#2}}% -\begingroup\defname {#2}{#1}\defvarargs{#3}\endgroup} - -% @defvar == @defvr Variable - -\def\defvar{\defvarparsebody\Edefvar\defvarx\defvarheader} - -\def\defvarheader #1#2{\doind {vr}{\code{#1}}% Make entry in var index -\begingroup\defname {#1}{\putwordDefvar}% -\defvarargs {#2}\endgroup % -} - -% @defopt == @defvr {User Option} - -\def\defopt{\defvarparsebody\Edefopt\defoptx\defoptheader} - -\def\defoptheader #1#2{\doind {vr}{\code{#1}}% Make entry in var index -\begingroup\defname {#1}{\putwordDefopt}% -\defvarargs {#2}\endgroup % -} - -% @deftypevar int foobar - -\def\deftypevar{\defvarparsebody\Edeftypevar\deftypevarx\deftypevarheader} - -% #1 is the data type. #2 is the name, perhaps followed by text that -% is actually part of the data type, which should not be put into the index. -\def\deftypevarheader #1#2{% -\dovarind#2 \relax% Make entry in variables index -\begingroup\defname {\defheaderxcond#1\relax$.$#2}{\putwordDeftypevar}% -\interlinepenalty=10000 -\endgraf\nobreak\vskip -\parskip\nobreak -\endgroup} -\def\dovarind#1 #2\relax{\doind{vr}{\code{#1}}} - -% @deftypevr {Global Flag} int enable - -\def\deftypevr{\defvrparsebody\Edeftypevr\deftypevrx\deftypevrheader} - -\def\deftypevrheader #1#2#3{\dovarind#3 \relax% -\begingroup\defname {\defheaderxcond#2\relax$.$#3}{#1} -\interlinepenalty=10000 -\endgraf\nobreak\vskip -\parskip\nobreak -\endgroup} - -% Now define @deftp -% Args are printed in bold, a slight difference from @defvar. - -\def\deftpargs #1{\bf \defvarargs{#1}} - -% @deftp Class window height width ... - -\def\deftp{\deftpparsebody\Edeftp\deftpx\deftpheader} - -\def\deftpheader #1#2#3{\doind {tp}{\code{#2}}% -\begingroup\defname {#2}{#1}\deftpargs{#3}\endgroup} - -% These definitions are used if you use @defunx (etc.) -% anywhere other than immediately after a @defun or @defunx. -% -\def\defcvx#1 {\errmessage{@defcvx in invalid context}} -\def\deffnx#1 {\errmessage{@deffnx in invalid context}} -\def\defivarx#1 {\errmessage{@defivarx in invalid context}} -\def\defmacx#1 {\errmessage{@defmacx in invalid context}} -\def\defmethodx#1 {\errmessage{@defmethodx in invalid context}} -\def\defoptx #1 {\errmessage{@defoptx in invalid context}} -\def\defopx#1 {\errmessage{@defopx in invalid context}} -\def\defspecx#1 {\errmessage{@defspecx in invalid context}} -\def\deftpx#1 {\errmessage{@deftpx in invalid context}} -\def\deftypefnx#1 {\errmessage{@deftypefnx in invalid context}} -\def\deftypefunx#1 {\errmessage{@deftypefunx in invalid context}} -\def\deftypeivarx#1 {\errmessage{@deftypeivarx in invalid context}} -\def\deftypemethodx#1 {\errmessage{@deftypemethodx in invalid context}} -\def\deftypeopx#1 {\errmessage{@deftypeopx in invalid context}} -\def\deftypevarx#1 {\errmessage{@deftypevarx in invalid context}} -\def\deftypevrx#1 {\errmessage{@deftypevrx in invalid context}} -\def\defunx#1 {\errmessage{@defunx in invalid context}} -\def\defvarx#1 {\errmessage{@defvarx in invalid context}} -\def\defvrx#1 {\errmessage{@defvrx in invalid context}} - - -\message{macros,} -% @macro. - -% To do this right we need a feature of e-TeX, \scantokens, -% which we arrange to emulate with a temporary file in ordinary TeX. -\ifx\eTeXversion\undefined - \newwrite\macscribble - \def\scanmacro#1{% - \begingroup \newlinechar`\^^M - % Undo catcode changes of \startcontents and \doprintindex - \catcode`\@=0 \catcode`\\=12 \escapechar=`\@ - % Append \endinput to make sure that TeX does not see the ending newline. - \toks0={#1\endinput}% - \immediate\openout\macscribble=\jobname.tmp - \immediate\write\macscribble{\the\toks0}% - \immediate\closeout\macscribble - \let\xeatspaces\eatspaces - \input \jobname.tmp - \endgroup -} -\else -\def\scanmacro#1{% -\begingroup \newlinechar`\^^M -% Undo catcode changes of \startcontents and \doprintindex -\catcode`\@=0 \catcode`\\=12 \escapechar=`\@ -\let\xeatspaces\eatspaces\scantokens{#1\endinput}\endgroup} -\fi - -\newcount\paramno % Count of parameters -\newtoks\macname % Macro name -\newif\ifrecursive % Is it recursive? -\def\macrolist{} % List of all defined macros in the form - % \do\macro1\do\macro2... - -% Utility routines. -% Thisdoes \let #1 = #2, except with \csnames. -\def\cslet#1#2{% -\expandafter\expandafter -\expandafter\let -\expandafter\expandafter -\csname#1\endcsname -\csname#2\endcsname} - -% Trim leading and trailing spaces off a string. -% Concepts from aro-bend problem 15 (see CTAN). -{\catcode`\@=11 -\gdef\eatspaces #1{\expandafter\trim@\expandafter{#1 }} -\gdef\trim@ #1{\trim@@ @#1 @ #1 @ @@} -\gdef\trim@@ #1@ #2@ #3@@{\trim@@@\empty #2 @} -\def\unbrace#1{#1} -\unbrace{\gdef\trim@@@ #1 } #2@{#1} -} - -% Trim a single trailing ^^M off a string. -{\catcode`\^^M=12\catcode`\Q=3% -\gdef\eatcr #1{\eatcra #1Q^^MQ}% -\gdef\eatcra#1^^MQ{\eatcrb#1Q}% -\gdef\eatcrb#1Q#2Q{#1}% -} - -% Macro bodies are absorbed as an argument in a context where -% all characters are catcode 10, 11 or 12, except \ which is active -% (as in normal texinfo). It is necessary to change the definition of \. - -% It's necessary to have hard CRs when the macro is executed. This is -% done by making ^^M (\endlinechar) catcode 12 when reading the macro -% body, and then making it the \newlinechar in \scanmacro. - -\def\macrobodyctxt{% - \catcode`\~=12 - \catcode`\^=12 - \catcode`\_=12 - \catcode`\|=12 - \catcode`\<=12 - \catcode`\>=12 - \catcode`\+=12 - \catcode`\{=12 - \catcode`\}=12 - \catcode`\@=12 - \catcode`\^^M=12 - \usembodybackslash} - -\def\macroargctxt{% - \catcode`\~=12 - \catcode`\^=12 - \catcode`\_=12 - \catcode`\|=12 - \catcode`\<=12 - \catcode`\>=12 - \catcode`\+=12 - \catcode`\@=12 - \catcode`\\=12} - -% \mbodybackslash is the definition of \ in @macro bodies. -% It maps \foo\ => \csname macarg.foo\endcsname => #N -% where N is the macro parameter number. -% We define \csname macarg.\endcsname to be \realbackslash, so -% \\ in macro replacement text gets you a backslash. - -{\catcode`@=0 @catcode`@\=@active - @gdef@usembodybackslash{@let\=@mbodybackslash} - @gdef@mbodybackslash#1\{@csname macarg.#1@endcsname} -} -\expandafter\def\csname macarg.\endcsname{\realbackslash} - -\def\macro{\recursivefalse\parsearg\macroxxx} -\def\rmacro{\recursivetrue\parsearg\macroxxx} - -\def\macroxxx#1{% - \getargs{#1}% now \macname is the macname and \argl the arglist - \ifx\argl\empty % no arguments - \paramno=0% - \else - \expandafter\parsemargdef \argl;% - \fi - \if1\csname ismacro.\the\macname\endcsname - \message{Warning: redefining \the\macname}% - \else - \expandafter\ifx\csname \the\macname\endcsname \relax - \else \errmessage{The name \the\macname\space is reserved}\fi - \global\cslet{macsave.\the\macname}{\the\macname}% - \global\expandafter\let\csname ismacro.\the\macname\endcsname=1% - % Add the macroname to \macrolist - \toks0 = \expandafter{\macrolist\do}% - \xdef\macrolist{\the\toks0 - \expandafter\noexpand\csname\the\macname\endcsname}% - \fi - \begingroup \macrobodyctxt - \ifrecursive \expandafter\parsermacbody - \else \expandafter\parsemacbody - \fi} - -\def\unmacro{\parsearg\unmacroxxx} -\def\unmacroxxx#1{% - \if1\csname ismacro.#1\endcsname - \global\cslet{#1}{macsave.#1}% - \global\expandafter\let \csname ismacro.#1\endcsname=0% - % Remove the macro name from \macrolist - \begingroup - \edef\tempa{\expandafter\noexpand\csname#1\endcsname}% - \def\do##1{% - \def\tempb{##1}% - \ifx\tempa\tempb - % remove this - \else - \toks0 = \expandafter{\newmacrolist\do}% - \edef\newmacrolist{\the\toks0\expandafter\noexpand\tempa}% - \fi}% - \def\newmacrolist{}% - % Execute macro list to define \newmacrolist - \macrolist - \global\let\macrolist\newmacrolist - \endgroup - \else - \errmessage{Macro #1 not defined}% - \fi -} - -% This makes use of the obscure feature that if the last token of a -% is #, then the preceding argument is delimited by -% an opening brace, and that opening brace is not consumed. -\def\getargs#1{\getargsxxx#1{}} -\def\getargsxxx#1#{\getmacname #1 \relax\getmacargs} -\def\getmacname #1 #2\relax{\macname={#1}} -\def\getmacargs#1{\def\argl{#1}} - -% Parse the optional {params} list. Set up \paramno and \paramlist -% so \defmacro knows what to do. Define \macarg.blah for each blah -% in the params list, to be ##N where N is the position in that list. -% That gets used by \mbodybackslash (above). - -% We need to get `macro parameter char #' into several definitions. -% The technique used is stolen from LaTeX: let \hash be something -% unexpandable, insert that wherever you need a #, and then redefine -% it to # just before using the token list produced. -% -% The same technique is used to protect \eatspaces till just before -% the macro is used. - -\def\parsemargdef#1;{\paramno=0\def\paramlist{}% - \let\hash\relax\let\xeatspaces\relax\parsemargdefxxx#1,;,} -\def\parsemargdefxxx#1,{% - \if#1;\let\next=\relax - \else \let\next=\parsemargdefxxx - \advance\paramno by 1% - \expandafter\edef\csname macarg.\eatspaces{#1}\endcsname - {\xeatspaces{\hash\the\paramno}}% - \edef\paramlist{\paramlist\hash\the\paramno,}% - \fi\next} - -% These two commands read recursive and nonrecursive macro bodies. -% (They're different since rec and nonrec macros end differently.) - -\long\def\parsemacbody#1@end macro% -{\xdef\temp{\eatcr{#1}}\endgroup\defmacro}% -\long\def\parsermacbody#1@end rmacro% -{\xdef\temp{\eatcr{#1}}\endgroup\defmacro}% - -% This defines the macro itself. There are six cases: recursive and -% nonrecursive macros of zero, one, and many arguments. -% Much magic with \expandafter here. -% \xdef is used so that macro definitions will survive the file -% they're defined in; @include reads the file inside a group. -\def\defmacro{% - \let\hash=##% convert placeholders to macro parameter chars - \ifrecursive - \ifcase\paramno - % 0 - \expandafter\xdef\csname\the\macname\endcsname{% - \noexpand\scanmacro{\temp}}% - \or % 1 - \expandafter\xdef\csname\the\macname\endcsname{% - \bgroup\noexpand\macroargctxt - \noexpand\braceorline - \expandafter\noexpand\csname\the\macname xxx\endcsname}% - \expandafter\xdef\csname\the\macname xxx\endcsname##1{% - \egroup\noexpand\scanmacro{\temp}}% - \else % many - \expandafter\xdef\csname\the\macname\endcsname{% - \bgroup\noexpand\macroargctxt - \noexpand\csname\the\macname xx\endcsname}% - \expandafter\xdef\csname\the\macname xx\endcsname##1{% - \expandafter\noexpand\csname\the\macname xxx\endcsname ##1,}% - \expandafter\expandafter - \expandafter\xdef - \expandafter\expandafter - \csname\the\macname xxx\endcsname - \paramlist{\egroup\noexpand\scanmacro{\temp}}% - \fi - \else - \ifcase\paramno - % 0 - \expandafter\xdef\csname\the\macname\endcsname{% - \noexpand\norecurse{\the\macname}% - \noexpand\scanmacro{\temp}\egroup}% - \or % 1 - \expandafter\xdef\csname\the\macname\endcsname{% - \bgroup\noexpand\macroargctxt - \noexpand\braceorline - \expandafter\noexpand\csname\the\macname xxx\endcsname}% - \expandafter\xdef\csname\the\macname xxx\endcsname##1{% - \egroup - \noexpand\norecurse{\the\macname}% - \noexpand\scanmacro{\temp}\egroup}% - \else % many - \expandafter\xdef\csname\the\macname\endcsname{% - \bgroup\noexpand\macroargctxt - \expandafter\noexpand\csname\the\macname xx\endcsname}% - \expandafter\xdef\csname\the\macname xx\endcsname##1{% - \expandafter\noexpand\csname\the\macname xxx\endcsname ##1,}% - \expandafter\expandafter - \expandafter\xdef - \expandafter\expandafter - \csname\the\macname xxx\endcsname - \paramlist{% - \egroup - \noexpand\norecurse{\the\macname}% - \noexpand\scanmacro{\temp}\egroup}% - \fi - \fi} - -\def\norecurse#1{\bgroup\cslet{#1}{macsave.#1}} - -% \braceorline decides whether the next nonwhitespace character is a -% {. If so it reads up to the closing }, if not, it reads the whole -% line. Whatever was read is then fed to the next control sequence -% as an argument (by \parsebrace or \parsearg) -\def\braceorline#1{\let\next=#1\futurelet\nchar\braceorlinexxx} -\def\braceorlinexxx{% - \ifx\nchar\bgroup\else - \expandafter\parsearg - \fi \next} - -% We mant to disable all macros during \shipout so that they are not -% expanded by \write. -\def\turnoffmacros{\begingroup \def\do##1{\let\noexpand##1=\relax}% - \edef\next{\macrolist}\expandafter\endgroup\next} - - -% @alias. -% We need some trickery to remove the optional spaces around the equal -% sign. Just make them active and then expand them all to nothing. -\def\alias{\begingroup\obeyspaces\parsearg\aliasxxx} -\def\aliasxxx #1{\aliasyyy#1\relax} -\def\aliasyyy #1=#2\relax{\ignoreactivespaces -\edef\next{\global\let\expandafter\noexpand\csname#1\endcsname=% - \expandafter\noexpand\csname#2\endcsname}% -\expandafter\endgroup\next} - - -\message{cross references,} -% @xref etc. - -\newwrite\auxfile - -\newif\ifhavexrefs % True if xref values are known. -\newif\ifwarnedxrefs % True if we warned once that they aren't known. - -% @inforef is relatively simple. -\def\inforef #1{\inforefzzz #1,,,,**} -\def\inforefzzz #1,#2,#3,#4**{\putwordSee{} \putwordInfo{} \putwordfile{} \file{\ignorespaces #3{}}, - node \samp{\ignorespaces#1{}}} - -% @node's job is to define \lastnode. -\def\node{\ENVcheck\parsearg\nodezzz} -\def\nodezzz#1{\nodexxx [#1,]} -\def\nodexxx[#1,#2]{\gdef\lastnode{#1}} -\let\nwnode=\node -\let\lastnode=\relax - -% The sectioning commands (@chapter, etc.) call these. -\def\donoderef{% - \ifx\lastnode\relax\else - \expandafter\expandafter\expandafter\setref{\lastnode}% - {Ysectionnumberandtype}% - \global\let\lastnode=\relax - \fi -} -\def\unnumbnoderef{% - \ifx\lastnode\relax\else - \expandafter\expandafter\expandafter\setref{\lastnode}{Ynothing}% - \global\let\lastnode=\relax - \fi -} -\def\appendixnoderef{% - \ifx\lastnode\relax\else - \expandafter\expandafter\expandafter\setref{\lastnode}% - {Yappendixletterandtype}% - \global\let\lastnode=\relax - \fi -} - - -% @anchor{NAME} -- define xref target at arbitrary point. -% -\newcount\savesfregister -\gdef\savesf{\relax \ifhmode \savesfregister=\spacefactor \fi} -\gdef\restoresf{\relax \ifhmode \spacefactor=\savesfregister \fi} -\gdef\anchor#1{\savesf \setref{#1}{Ynothing}\restoresf \ignorespaces} - -% \setref{NAME}{SNT} defines a cross-reference point NAME, namely -% NAME-title, NAME-pg, and NAME-SNT. Called from \foonoderef. We have -% to set \indexdummies so commands such as @code in a section title -% aren't expanded. It would be nicer not to expand the titles in the -% first place, but there's so many layers that that is hard to do. -% -\def\setref#1#2{{% - \indexdummies - \pdfmkdest{#1}% - \dosetq{#1-title}{Ytitle}% - \dosetq{#1-pg}{Ypagenumber}% - \dosetq{#1-snt}{#2}% -}} - -% @xref, @pxref, and @ref generate cross-references. For \xrefX, #1 is -% the node name, #2 the name of the Info cross-reference, #3 the printed -% node name, #4 the name of the Info file, #5 the name of the printed -% manual. All but the node name can be omitted. -% -\def\pxref#1{\putwordsee{} \xrefX[#1,,,,,,,]} -\def\xref#1{\putwordSee{} \xrefX[#1,,,,,,,]} -\def\ref#1{\xrefX[#1,,,,,,,]} -\def\xrefX[#1,#2,#3,#4,#5,#6]{\begingroup - \unsepspaces - \def\printedmanual{\ignorespaces #5}% - \def\printednodename{\ignorespaces #3}% - \setbox1=\hbox{\printedmanual}% - \setbox0=\hbox{\printednodename}% - \ifdim \wd0 = 0pt - % No printed node name was explicitly given. - \expandafter\ifx\csname SETxref-automatic-section-title\endcsname\relax - % Use the node name inside the square brackets. - \def\printednodename{\ignorespaces #1}% - \else - % Use the actual chapter/section title appear inside - % the square brackets. Use the real section title if we have it. - \ifdim \wd1 > 0pt - % It is in another manual, so we don't have it. - \def\printednodename{\ignorespaces #1}% - \else - \ifhavexrefs - % We know the real title if we have the xref values. - \def\printednodename{\refx{#1-title}{}}% - \else - % Otherwise just copy the Info node name. - \def\printednodename{\ignorespaces #1}% - \fi% - \fi - \fi - \fi - % - % If we use \unhbox0 and \unhbox1 to print the node names, TeX does not - % insert empty discretionaries after hyphens, which means that it will - % not find a line break at a hyphen in a node names. Since some manuals - % are best written with fairly long node names, containing hyphens, this - % is a loss. Therefore, we give the text of the node name again, so it - % is as if TeX is seeing it for the first time. - \ifpdf - \leavevmode - \getfilename{#4}% - {\normalturnoffactive - \ifnum\filenamelength>0 - \startlink attr{/Border [0 0 0]}% - goto file{\the\filename.pdf} name{#1}% - \else - \startlink attr{/Border [0 0 0]}% - goto name{#1}% - \fi - }% - \linkcolor - \fi - % - \ifdim \wd1 > 0pt - \putwordsection{} ``\printednodename'' \putwordin{} \cite{\printedmanual}% - \else - % _ (for example) has to be the character _ for the purposes of the - % control sequence corresponding to the node, but it has to expand - % into the usual \leavevmode...\vrule stuff for purposes of - % printing. So we \turnoffactive for the \refx-snt, back on for the - % printing, back off for the \refx-pg. - {\normalturnoffactive - % Only output a following space if the -snt ref is nonempty; for - % @unnumbered and @anchor, it won't be. - \setbox2 = \hbox{\ignorespaces \refx{#1-snt}{}}% - \ifdim \wd2 > 0pt \refx{#1-snt}\space\fi - }% - % [mynode], - [\printednodename],\space - % page 3 - \turnoffactive \putwordpage\tie\refx{#1-pg}{}% - \fi - \endlink -\endgroup} - -% \dosetq is the interface for calls from other macros - -% Use \normalturnoffactive so that punctuation chars such as underscore -% and backslash work in node names. (\turnoffactive doesn't do \.) -\def\dosetq#1#2{% - {\let\folio=0% - \normalturnoffactive - \edef\next{\write\auxfile{\internalsetq{#1}{#2}}}% - \iflinks - \next - \fi - }% -} - -% \internalsetq {foo}{page} expands into -% CHARACTERS 'xrdef {foo}{...expansion of \Ypage...} -% When the aux file is read, ' is the escape character - -\def\internalsetq #1#2{'xrdef {#1}{\csname #2\endcsname}} - -% Things to be expanded by \internalsetq - -\def\Ypagenumber{\folio} - -\def\Ytitle{\thissection} - -\def\Ynothing{} - -\def\Ysectionnumberandtype{% -\ifnum\secno=0 \putwordChapter\xreftie\the\chapno % -\else \ifnum \subsecno=0 \putwordSection\xreftie\the\chapno.\the\secno % -\else \ifnum \subsubsecno=0 % -\putwordSection\xreftie\the\chapno.\the\secno.\the\subsecno % -\else % -\putwordSection\xreftie\the\chapno.\the\secno.\the\subsecno.\the\subsubsecno % -\fi \fi \fi } - -\def\Yappendixletterandtype{% -\ifnum\secno=0 \putwordAppendix\xreftie'char\the\appendixno{}% -\else \ifnum \subsecno=0 \putwordSection\xreftie'char\the\appendixno.\the\secno % -\else \ifnum \subsubsecno=0 % -\putwordSection\xreftie'char\the\appendixno.\the\secno.\the\subsecno % -\else % -\putwordSection\xreftie'char\the\appendixno.\the\secno.\the\subsecno.\the\subsubsecno % -\fi \fi \fi } - -\gdef\xreftie{'tie} - -% Use TeX 3.0's \inputlineno to get the line number, for better error -% messages, but if we're using an old version of TeX, don't do anything. -% -\ifx\inputlineno\thisisundefined - \let\linenumber = \empty % Non-3.0. -\else - \def\linenumber{\the\inputlineno:\space} -\fi - -% Define \refx{NAME}{SUFFIX} to reference a cross-reference string named NAME. -% If its value is nonempty, SUFFIX is output afterward. - -\def\refx#1#2{% - \expandafter\ifx\csname X#1\endcsname\relax - % If not defined, say something at least. - \angleleft un\-de\-fined\angleright - \iflinks - \ifhavexrefs - \message{\linenumber Undefined cross reference `#1'.}% - \else - \ifwarnedxrefs\else - \global\warnedxrefstrue - \message{Cross reference values unknown; you must run TeX again.}% - \fi - \fi - \fi - \else - % It's defined, so just use it. - \csname X#1\endcsname - \fi - #2% Output the suffix in any case. -} - -% This is the macro invoked by entries in the aux file. -% -\def\xrdef#1{\begingroup - % Reenable \ as an escape while reading the second argument. - \catcode`\\ = 0 - \afterassignment\endgroup - \expandafter\gdef\csname X#1\endcsname -} - -% Read the last existing aux file, if any. No error if none exists. -\def\readauxfile{\begingroup - \catcode`\^^@=\other - \catcode`\^^A=\other - \catcode`\^^B=\other - \catcode`\^^C=\other - \catcode`\^^D=\other - \catcode`\^^E=\other - \catcode`\^^F=\other - \catcode`\^^G=\other - \catcode`\^^H=\other - \catcode`\^^K=\other - \catcode`\^^L=\other - \catcode`\^^N=\other - \catcode`\^^P=\other - \catcode`\^^Q=\other - \catcode`\^^R=\other - \catcode`\^^S=\other - \catcode`\^^T=\other - \catcode`\^^U=\other - \catcode`\^^V=\other - \catcode`\^^W=\other - \catcode`\^^X=\other - \catcode`\^^Z=\other - \catcode`\^^[=\other - \catcode`\^^\=\other - \catcode`\^^]=\other - \catcode`\^^^=\other - \catcode`\^^_=\other - \catcode`\@=\other - \catcode`\^=\other - % It was suggested to define this as 7, which would allow ^^e4 etc. - % in xref tags, i.e., node names. But since ^^e4 notation isn't - % supported in the main text, it doesn't seem desirable. Furthermore, - % that is not enough: for node names that actually contain a ^ - % character, we would end up writing a line like this: 'xrdef {'hat - % b-title}{'hat b} and \xrdef does a \csname...\endcsname on the first - % argument, and \hat is not an expandable control sequence. It could - % all be worked out, but why? Either we support ^^ or we don't. - % - % The other change necessary for this was to define \auxhat: - % \def\auxhat{\def^{'hat }}% extra space so ok if followed by letter - % and then to call \auxhat in \setq. - % - \catcode`\~=\other - \catcode`\[=\other - \catcode`\]=\other - \catcode`\"=\other - \catcode`\_=\other - \catcode`\|=\other - \catcode`\<=\other - \catcode`\>=\other - \catcode`\$=\other - \catcode`\#=\other - \catcode`\&=\other - \catcode`+=\other % avoid \+ for paranoia even though we've turned it off - % Make the characters 128-255 be printing characters - {% - \count 1=128 - \def\loop{% - \catcode\count 1=\other - \advance\count 1 by 1 - \ifnum \count 1<256 \loop \fi - }% - }% - % The aux file uses ' as the escape (for now). - % Turn off \ as an escape so we do not lose on - % entries which were dumped with control sequences in their names. - % For example, 'xrdef {$\leq $-fun}{page ...} made by @defun ^^ - % Reference to such entries still does not work the way one would wish, - % but at least they do not bomb out when the aux file is read in. - \catcode`\{=1 - \catcode`\}=2 - \catcode`\%=\other - \catcode`\'=0 - \catcode`\\=\other - % - \openin 1 \jobname.aux - \ifeof 1 \else - \closein 1 - \input \jobname.aux - \global\havexrefstrue - \global\warnedobstrue - \fi - % Open the new aux file. TeX will close it automatically at exit. - \openout\auxfile=\jobname.aux -\endgroup} - - -% Footnotes. - -\newcount \footnoteno - -% The trailing space in the following definition for supereject is -% vital for proper filling; pages come out unaligned when you do a -% pagealignmacro call if that space before the closing brace is -% removed. (Generally, numeric constants should always be followed by a -% space to prevent strange expansion errors.) -\def\supereject{\par\penalty -20000\footnoteno =0 } - -% @footnotestyle is meaningful for info output only. -\let\footnotestyle=\comment - -\let\ptexfootnote=\footnote - -{\catcode `\@=11 -% -% Auto-number footnotes. Otherwise like plain. -\gdef\footnote{% - \global\advance\footnoteno by \@ne - \edef\thisfootno{$^{\the\footnoteno}$}% - % - % In case the footnote comes at the end of a sentence, preserve the - % extra spacing after we do the footnote number. - \let\@sf\empty - \ifhmode\edef\@sf{\spacefactor\the\spacefactor}\/\fi - % - % Remove inadvertent blank space before typesetting the footnote number. - \unskip - \thisfootno\@sf - \footnotezzz -}% - -% Don't bother with the trickery in plain.tex to not require the -% footnote text as a parameter. Our footnotes don't need to be so general. -% -% Oh yes, they do; otherwise, @ifset and anything else that uses -% \parseargline fail inside footnotes because the tokens are fixed when -% the footnote is read. --karl, 16nov96. -% -\long\gdef\footnotezzz{\insert\footins\bgroup - % We want to typeset this text as a normal paragraph, even if the - % footnote reference occurs in (for example) a display environment. - % So reset some parameters. - \interlinepenalty\interfootnotelinepenalty - \splittopskip\ht\strutbox % top baseline for broken footnotes - \splitmaxdepth\dp\strutbox - \floatingpenalty\@MM - \leftskip\z@skip - \rightskip\z@skip - \spaceskip\z@skip - \xspaceskip\z@skip - \parindent\defaultparindent - % - \smallfonts \rm - % - % Because we use hanging indentation in footnotes, a @noindent appears - % to exdent this text, so make it be a no-op. makeinfo does not use - % hanging indentation so @noindent can still be needed within footnote - % text after an @example or the like (not that this is good style). - \let\noindent = \relax - % - % Hang the footnote text off the number. Use \everypar in case the - % footnote extends for more than one paragraph. - \everypar = {\hang}% - \textindent{\thisfootno}% - % - % Don't crash into the line above the footnote text. Since this - % expands into a box, it must come within the paragraph, lest it - % provide a place where TeX can split the footnote. - \footstrut - \futurelet\next\fo@t -} -\def\fo@t{\ifcat\bgroup\noexpand\next \let\next\f@@t - \else\let\next\f@t\fi \next} -\def\f@@t{\bgroup\aftergroup\@foot\let\next} -\def\f@t#1{#1\@foot} -\def\@foot{\strut\par\egroup} - -}%end \catcode `\@=11 - -% @| inserts a changebar to the left of the current line. It should -% surround any changed text. This approach does *not* work if the -% change spans more than two lines of output. To handle that, we would -% have adopt a much more difficult approach (putting marks into the main -% vertical list for the beginning and end of each change). -% -\def\|{% - % \vadjust can only be used in horizontal mode. - \leavevmode - % - % Append this vertical mode material after the current line in the output. - \vadjust{% - % We want to insert a rule with the height and depth of the current - % leading; that is exactly what \strutbox is supposed to record. - \vskip-\baselineskip - % - % \vadjust-items are inserted at the left edge of the type. So - % the \llap here moves out into the left-hand margin. - \llap{% - % - % For a thicker or thinner bar, change the `1pt'. - \vrule height\baselineskip width1pt - % - % This is the space between the bar and the text. - \hskip 12pt - }% - }% -} - -% For a final copy, take out the rectangles -% that mark overfull boxes (in case you have decided -% that the text looks ok even though it passes the margin). -% -\def\finalout{\overfullrule=0pt} - -% @image. We use the macros from epsf.tex to support this. -% If epsf.tex is not installed and @image is used, we complain. -% -% Check for and read epsf.tex up front. If we read it only at @image -% time, we might be inside a group, and then its definitions would get -% undone and the next image would fail. -\openin 1 = epsf.tex -\ifeof 1 \else - \closein 1 - % Do not bother showing banner with post-v2.7 epsf.tex (available in - % doc/epsf.tex until it shows up on ctan). - \def\epsfannounce{\toks0 = }% - \input epsf.tex -\fi -% -% We will only complain once about lack of epsf.tex. -\newif\ifwarnednoepsf -\newhelp\noepsfhelp{epsf.tex must be installed for images to - work. It is also included in the Texinfo distribution, or you can get - it from ftp://tug.org/tex/epsf.tex.} -% -\def\image#1{% - \ifx\epsfbox\undefined - \ifwarnednoepsf \else - \errhelp = \noepsfhelp - \errmessage{epsf.tex not found, images will be ignored}% - \global\warnednoepsftrue - \fi - \else - \imagexxx #1,,,,,\finish - \fi -} -% -% Arguments to @image: -% #1 is (mandatory) image filename; we tack on .eps extension. -% #2 is (optional) width, #3 is (optional) height. -% #4 is (ignored optional) html alt text. -% #5 is (ignored optional) extension. -% #6 is just the usual extra ignored arg for parsing this stuff. -\newif\ifimagevmode -\def\imagexxx#1,#2,#3,#4,#5,#6\finish{\begingroup - \catcode`\^^M = 5 % in case we're inside an example - \normalturnoffactive % allow _ et al. in names - % If the image is by itself, center it. - \ifvmode - \imagevmodetrue - \nobreak\bigskip - % Usually we'll have text after the image which will insert - % \parskip glue, so insert it here too to equalize the space - % above and below. - \nobreak\vskip\parskip - \nobreak - \line\bgroup\hss - \fi - % - % Output the image. - \ifpdf - \dopdfimage{#1}{#2}{#3}% - \else - % \epsfbox itself resets \epsf?size at each figure. - \setbox0 = \hbox{\ignorespaces #2}\ifdim\wd0 > 0pt \epsfxsize=#2\relax \fi - \setbox0 = \hbox{\ignorespaces #3}\ifdim\wd0 > 0pt \epsfysize=#3\relax \fi - \epsfbox{#1.eps}% - \fi - % - \ifimagevmode \hss \egroup \bigbreak \fi % space after the image -\endgroup} - - -\message{localization,} -% and i18n. - -% @documentlanguage is usually given very early, just after -% @setfilename. If done too late, it may not override everything -% properly. Single argument is the language abbreviation. -% It would be nice if we could set up a hyphenation file here. -% -\def\documentlanguage{\parsearg\dodocumentlanguage} -\def\dodocumentlanguage#1{% - \tex % read txi-??.tex file in plain TeX. - % Read the file if it exists. - \openin 1 txi-#1.tex - \ifeof1 - \errhelp = \nolanghelp - \errmessage{Cannot read language file txi-#1.tex}% - \let\temp = \relax - \else - \def\temp{\input txi-#1.tex }% - \fi - \temp - \endgroup -} -\newhelp\nolanghelp{The given language definition file cannot be found or -is empty. Maybe you need to install it? In the current directory -should work if nowhere else does.} - - -% @documentencoding should change something in TeX eventually, most -% likely, but for now just recognize it. -\let\documentencoding = \comment - - -% Page size parameters. -% -\newdimen\defaultparindent \defaultparindent = 15pt - -\chapheadingskip = 15pt plus 4pt minus 2pt -\secheadingskip = 12pt plus 3pt minus 2pt -\subsecheadingskip = 9pt plus 2pt minus 2pt - -% Prevent underfull vbox error messages. -\vbadness = 10000 - -% Don't be so finicky about underfull hboxes, either. -\hbadness = 2000 - -% Following George Bush, just get rid of widows and orphans. -\widowpenalty=10000 -\clubpenalty=10000 - -% Use TeX 3.0's \emergencystretch to help line breaking, but if we're -% using an old version of TeX, don't do anything. We want the amount of -% stretch added to depend on the line length, hence the dependence on -% \hsize. We call this whenever the paper size is set. -% -\def\setemergencystretch{% - \ifx\emergencystretch\thisisundefined - % Allow us to assign to \emergencystretch anyway. - \def\emergencystretch{\dimen0}% - \else - \emergencystretch = .15\hsize - \fi -} - -% Parameters in order: 1) textheight; 2) textwidth; 3) voffset; -% 4) hoffset; 5) binding offset; 6) topskip. We also call -% \setleading{\textleading}, so the caller should define \textleading. -% The caller should also set \parskip. -% -\def\internalpagesizes#1#2#3#4#5#6{% - \voffset = #3\relax - \topskip = #6\relax - \splittopskip = \topskip - % - \vsize = #1\relax - \advance\vsize by \topskip - \outervsize = \vsize - \advance\outervsize by 2\topandbottommargin - \pageheight = \vsize - % - \hsize = #2\relax - \outerhsize = \hsize - \advance\outerhsize by 0.5in - \pagewidth = \hsize - % - \normaloffset = #4\relax - \bindingoffset = #5\relax - % - \setleading{\textleading} - % - \parindent = \defaultparindent - \setemergencystretch -} - -% Use `small' versions. -% -\def\smallenvironments{% - \let\smalldisplay = \smalldisplayx - \let\smallexample = \smalllispx - \let\smallformat = \smallformatx - \let\smalllisp = \smalllispx -} - -% @letterpaper (the default). -\def\letterpaper{{\globaldefs = 1 - \parskip = 3pt plus 2pt minus 1pt - \textleading = 13.2pt - % - % If page is nothing but text, make it come out even. - \internalpagesizes{46\baselineskip}{6in}{\voffset}{.25in}{\bindingoffset}{36pt}% -}} - -% Use @smallbook to reset parameters for 7x9.5 (or so) format. -\def\smallbook{{\globaldefs = 1 - \parskip = 2pt plus 1pt - \textleading = 12pt - % - \internalpagesizes{7.5in}{5.in}{\voffset}{.25in}{\bindingoffset}{16pt}% - % - \lispnarrowing = 0.3in - \tolerance = 700 - \hfuzz = 1pt - \contentsrightmargin = 0pt - \deftypemargin = 0pt - \defbodyindent = .5cm - \smallenvironments -}} - -% Use @afourpaper to print on European A4 paper. -\def\afourpaper{{\globaldefs = 1 - \parskip = 3pt plus 2pt minus 1pt - \textleading = 12pt - % - \internalpagesizes{53\baselineskip}{160mm}{\voffset}{4mm}{\bindingoffset}{44pt}% - % - \tolerance = 700 - \hfuzz = 1pt -}} - -% Use @afivepaper to print on European A5 paper. -% From romildo@urano.iceb.ufop.br, 2 July 2000. -% He also recommends making @example and @lisp be small. -\def\afivepaper{{\globaldefs = 1 - \parskip = 2pt plus 1pt minus 0.1pt - \textleading = 12.5pt - % - \internalpagesizes{166mm}{120mm}{\voffset}{-8mm}{\bindingoffset}{8pt}% - % - \lispnarrowing = 0.2in - \tolerance = 800 - \hfuzz = 1.2pt - \contentsrightmargin = 0mm - \deftypemargin = 0pt - \defbodyindent = 2mm - \tableindent = 12mm - % - \smallenvironments -}} - -% A specific text layout, 24x15cm overall, intended for A4 paper. Top margin -% 29mm, hence bottom margin 28mm, nominal side margin 3cm. -\def\afourlatex{{\globaldefs = 1 - \textleading = 13.6pt - % - \afourpaper - \internalpagesizes{237mm}{150mm}{3.6mm}{3.6mm}{3mm}{7mm}% - % - % Must explicitly reset to 0 because we call \afourpaper, apparently, - % although this does not entirely make sense. - \globaldefs = 0 -}} - -% Use @afourwide to print on European A4 paper in wide format. -\def\afourwide{% - \afourpaper - \internalpagesizes{6.5in}{9.5in}{\hoffset}{\normaloffset}{\bindingoffset}{7mm}% -} - -% @pagesizes TEXTHEIGHT[,TEXTWIDTH] -% Perhaps we should allow setting the margins, \topskip, \parskip, -% and/or leading, also. Or perhaps we should compute them somehow. -% -\def\pagesizes{\parsearg\pagesizesxxx} -\def\pagesizesxxx#1{\pagesizesyyy #1,,\finish} -\def\pagesizesyyy#1,#2,#3\finish{{% - \setbox0 = \hbox{\ignorespaces #2}\ifdim\wd0 > 0pt \hsize=#2\relax \fi - \globaldefs = 1 - % - \parskip = 3pt plus 2pt minus 1pt - \setleading{\textleading}% - % - \internalpagesizes{#1}{\hsize}{\voffset}{\normaloffset}{\bindingoffset}{44pt}% -}} - -% Set default to letter. -% -\letterpaper - - -\message{and turning on texinfo input format.} - -% Define macros to output various characters with catcode for normal text. -\catcode`\"=\other -\catcode`\~=\other -\catcode`\^=\other -\catcode`\_=\other -\catcode`\|=\other -\catcode`\<=\other -\catcode`\>=\other -\catcode`\+=\other -\catcode`\$=\other -\def\normaldoublequote{"} -\def\normaltilde{~} -\def\normalcaret{^} -\def\normalunderscore{_} -\def\normalverticalbar{|} -\def\normalless{<} -\def\normalgreater{>} -\def\normalplus{+} -\def\normaldollar{$}%$ font-lock fix - -% This macro is used to make a character print one way in ttfont -% where it can probably just be output, and another way in other fonts, -% where something hairier probably needs to be done. -% -% #1 is what to print if we are indeed using \tt; #2 is what to print -% otherwise. Since all the Computer Modern typewriter fonts have zero -% interword stretch (and shrink), and it is reasonable to expect all -% typewriter fonts to have this, we can check that font parameter. -% -\def\ifusingtt#1#2{\ifdim \fontdimen3\font=0pt #1\else #2\fi} - -% Same as above, but check for italic font. Actually this also catches -% non-italic slanted fonts since it is impossible to distinguish them from -% italic fonts. But since this is only used by $ and it uses \sl anyway -% this is not a problem. -\def\ifusingit#1#2{\ifdim \fontdimen1\font>0pt #1\else #2\fi} - -% Turn off all special characters except @ -% (and those which the user can use as if they were ordinary). -% Most of these we simply print from the \tt font, but for some, we can -% use math or other variants that look better in normal text. - -\catcode`\"=\active -\def\activedoublequote{{\tt\char34}} -\let"=\activedoublequote -\catcode`\~=\active -\def~{{\tt\char126}} -\chardef\hat=`\^ -\catcode`\^=\active -\def^{{\tt \hat}} - -\catcode`\_=\active -\def_{\ifusingtt\normalunderscore\_} -% Subroutine for the previous macro. -\def\_{\leavevmode \kern.06em \vbox{\hrule width.3em height.1ex}} - -\catcode`\|=\active -\def|{{\tt\char124}} -\chardef \less=`\< -\catcode`\<=\active -\def<{{\tt \less}} -\chardef \gtr=`\> -\catcode`\>=\active -\def>{{\tt \gtr}} -\catcode`\+=\active -\def+{{\tt \char 43}} -\catcode`\$=\active -\def${\ifusingit{{\sl\$}}\normaldollar}%$ font-lock fix -%\catcode 27=\active -%\def^^[{$\diamondsuit$} - -% Set up an active definition for =, but don't enable it most of the time. -{\catcode`\==\active -\global\def={{\tt \char 61}}} - -\catcode`+=\active -\catcode`\_=\active - -% If a .fmt file is being used, characters that might appear in a file -% name cannot be active until we have parsed the command line. -% So turn them off again, and have \everyjob (or @setfilename) turn them on. -% \otherifyactive is called near the end of this file. -\def\otherifyactive{\catcode`+=\other \catcode`\_=\other} - -\catcode`\@=0 - -% \rawbackslashxx output one backslash character in current font -\global\chardef\rawbackslashxx=`\\ -%{\catcode`\\=\other -%@gdef@rawbackslashxx{\}} - -% \rawbackslash redefines \ as input to do \rawbackslashxx. -{\catcode`\\=\active -@gdef@rawbackslash{@let\=@rawbackslashxx }} - -% \normalbackslash outputs one backslash in fixed width font. -\def\normalbackslash{{\tt\rawbackslashxx}} - -% \catcode 17=0 % Define control-q -\catcode`\\=\active - -% Used sometimes to turn off (effectively) the active characters -% even after parsing them. -@def@turnoffactive{@let"=@normaldoublequote -@let\=@realbackslash -@let~=@normaltilde -@let^=@normalcaret -@let_=@normalunderscore -@let|=@normalverticalbar -@let<=@normalless -@let>=@normalgreater -@let+=@normalplus -@let$=@normaldollar}%$ font-lock fix - -@def@normalturnoffactive{@let"=@normaldoublequote -@let\=@normalbackslash -@let~=@normaltilde -@let^=@normalcaret -@let_=@normalunderscore -@let|=@normalverticalbar -@let<=@normalless -@let>=@normalgreater -@let+=@normalplus -@let$=@normaldollar}%$ font-lock fix - -% Make _ and + \other characters, temporarily. -% This is canceled by @fixbackslash. -@otherifyactive - -% If a .fmt file is being used, we don't want the `\input texinfo' to show up. -% That is what \eatinput is for; after that, the `\' should revert to printing -% a backslash. -% -@gdef@eatinput input texinfo{@fixbackslash} -@global@let\ = @eatinput - -% On the other hand, perhaps the file did not have a `\input texinfo'. Then -% the first `\{ in the file would cause an error. This macro tries to fix -% that, assuming it is called before the first `\' could plausibly occur. -% Also back turn on active characters that might appear in the input -% file name, in case not using a pre-dumped format. -% -@gdef@fixbackslash{% - @ifx\@eatinput @let\ = @normalbackslash @fi - @catcode`+=@active - @catcode`@_=@active -} - -% Say @foo, not \foo, in error messages. -@escapechar = `@@ - -% These look ok in all fonts, so just make them not special. -@catcode`@& = @other -@catcode`@# = @other -@catcode`@% = @other - -@c Set initial fonts. -@textfonts -@rm - - -@c Local variables: -@c eval: (add-hook 'write-file-hooks 'time-stamp) -@c page-delimiter: "^\\\\message" -@c time-stamp-start: "def\\\\texinfoversion{" -@c time-stamp-format: "%:y-%02m-%02d.%02H" -@c time-stamp-end: "}" -@c End: diff --git a/topc-2.5.2/doc/topc++.1 b/topc-2.5.2/doc/topc++.1 deleted file mode 100644 index 49c6c9af..00000000 --- a/topc-2.5.2/doc/topc++.1 +++ /dev/null @@ -1 +0,0 @@ -.so man1/topcc.1 diff --git a/topc-2.5.2/doc/topc-version.texi b/topc-2.5.2/doc/topc-version.texi deleted file mode 100644 index c5e12250..00000000 --- a/topc-2.5.2/doc/topc-version.texi +++ /dev/null @@ -1,5 +0,0 @@ -@comment doc/topc-version.texi. Generated from topc-version.texi.in by configure. - -@set VERSION 2.5.2 -@set UPDATED April, 2011 -@set PWD /home/kason/school/4zp6/repo/GEANT4-GPU/topc-2.5.2 diff --git a/topc-2.5.2/doc/topc-version.texi.in b/topc-2.5.2/doc/topc-version.texi.in deleted file mode 100644 index 90e0cd01..00000000 --- a/topc-2.5.2/doc/topc-version.texi.in +++ /dev/null @@ -1,5 +0,0 @@ -@comment @configure_input@ - -@set VERSION @TOPC_VERSION@ -@set UPDATED @TOPC_UPDATED@ -@set PWD @PWD@ diff --git a/topc-2.5.2/doc/topc.dvi b/topc-2.5.2/doc/topc.dvi deleted file mode 100644 index 8f8adf1c..00000000 Binary files a/topc-2.5.2/doc/topc.dvi and /dev/null differ diff --git a/topc-2.5.2/doc/topc.info b/topc-2.5.2/doc/topc.info deleted file mode 100644 index b21be2a9..00000000 --- a/topc-2.5.2/doc/topc.info +++ /dev/null @@ -1,2928 +0,0 @@ -This is topc.info, produced by makeinfo version 4.13 from topc.texi. - -This file documents version 2.5.2 of `TOP-C' (Task Oriented Parallel C/C++) - (last updated April, 2011) - Copyright (c) 2000 - 2004 Gene Cooperman - Permission is granted to make and distribute verbatim copies of this -manual provided the copyright notice and this permission notice are -preserved on all copies. - - Permission is granted to copy and distribute modified versions of -this manual under the conditions for verbatim copying, provided also -that the sections entitled "Copying" and "GNU Lesser General Public -License" are included exactly as in the original, and provided that the -entire resulting derived work is distributed under the terms of a -permission notice identical to this one. - - Permission is granted to copy and distribute translations of this -manual into another language, under the above conditions for modified -versions, except that this permission notice may be stated in a -translation approved by the Free Software Foundation. - -INFO-DIR-SECTION Programming -START-INFO-DIR-ENTRY -* TOP-C: (topc). TOP-C (Task Oriented Parallel C/C++) -END-INFO-DIR-ENTRY - - -File: topc.info, Node: Top, Next: Copying, Prev: (dir), Up: (dir) - - This documents version 2.5.2 of -`TOP-C' (Task Oriented Parallel C/C++), -last updated April, 2011. - -* Menu: - -* Copying:: -* Quick Start:: -* Overview:: -* Writing TOP-C Applications:: -* Compiling and Invoking TOP-C Applications:: -* Debugging and Tracing:: -* Performance and Long Jobs:: -* Advanced Features:: -* TOP-C Raw Interface:: -* Acknowledgements:: -* Summary:: -* Example:: -* Using a Different MPI with TOP-C:: -* Function Index:: -* Variable Index:: -* Concept Index:: - - --- The Detailed Node Listing --- - -Overview of `TOP-C/C++' - -* Programmer Model:: -* Three Key Concepts for TOP-C:: -* Memory Models:: - -Programmer's Model - -* Structure of a TOP-C Program:: -* Four Callback Functions:: -* Task Buffers:: -* The TOP-C Algorithm:: - -Task Input and Task Output Buffers - -* Defining Task Buffers:: -* Marshaling:: - -Writing `TOP-C' Applications - -* The Main TOP-C Library Calls:: -* Callback Functions:: -* Actions:: -* TOP-C Utilities:: - -Compiling and Invoking `TOP-C' Applications - -* Compiling TOP-C Applications:: -* Command Line Options:: -* Invoking a TOP-C Application in Sequential Memory:: -* Invoking a TOP-C Application in Distributed Memory:: -* Invoking a TOP-C Application in Shared Memory:: - -Invoking a TOP-C Application in Distributed Memory - -* Procgroup Files:: -* Slaves Fail to Start:: - -Debugging and Tracing - -* Debugging by Limiting Parallelism:: -* Debugging with --TOPC-safety:: -* TOP-C and POSIX signals:: -* Tracing Messages:: -* Stepping Through a Slave:: -* Segmentation faults:: - -Performance and Long Jobs - -* Strategies for Greater Concurrency:: -* Improving Performance:: -* Long Jobs:: - -Advanced Features of `TOP-C' - -* Testing for Task Continuations:: -* Aborting Tasks:: -* Allocation of Task Buffers:: -* Shared Memory Model:: -* Sequential Memory Model:: -* Caveats:: - -Memory Allocation for Task Buffers - -* Avoiding malloc:: -* Large Buffers and TOPC_MSG_PTR:: -* Allocation for TOPC_MSG_PTR:: -* Marshaling Complex Data Structures:: - -Optimizing TOP-C Code for the Shared Memory Model - -* Reader-Writer Synchronization:: -* Thread-Private Global Variables:: -* Volatile Variables:: -* SMP Performance:: - -`TOP-C' Raw Interface for Parallelizing Sequential Code - -* TOPC-C raw functions:: -* Parallelizing For Loops:: -* Parallelizing While Loops:: - - -File: topc.info, Node: Copying, Next: Quick Start, Prev: Top, Up: Top - -1 `TOP-C' Copying Conditions -**************************** - -All of the copyright notices of this package are designed to encourage -free copying and usage. This manual is copyright by Gene Cooperman. -Most of the source code files of the `TOP-C' software package contain a -copyright notice similar to that below. At the current time, Some of -the source files are copyright by Gene Cooperman alone and some by both -Gene Cooperman and Victor Grinberg, but all files are distributed under -the GNU LGPL license referred to below. - - ********************************************************************** - * Copyright (c) 2000 - 2004 Gene Cooperman * - * * - * This library is free software; you can redistribute it and/or * - * modify it under the terms of the GNU Lesser General Public * - * License as published by the Free Software Foundation; either * - * version 2.1 of the License, or (at your option) any later version. * - * * - * This library is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * - * Lesser General Public License for more details. * - * * - * You should have received a copy of the GNU Lesser General Public * - * License along with this library (see file COPYING); if not, write * - * to the Free Software Foundation, Inc., 59 Temple Place, Suite * - * 330, Boston, MA 02111-1307 USA, or contact Gene Cooperman * - * . * - ********************************************************************** - - -File: topc.info, Node: Quick Start, Next: Overview, Prev: Copying, Up: Top - -2 Quick Start: Installation and Test Run -***************************************** - - This is version 2.5.2 of Task Oriented Parallel C/C++ (`TOP-C'). - See `http://www.ccs.neu.edu/home/gene/topc.html' for general - information on obtaining source, overview slides of `TOP-C', - previous `TOP-C' applications, etc. - Gene Cooperman - - - It has been tested and works on several workstation architectures. -It provides task-oriented parallelism to the end user. The same -application source code (or object code) can be executed (or linked) -with any of the following communication libraries using the topcc -command (a substitute for cc or gcc): - 1. a distributed memory library using MPI (MPI subset, mpinu, - included in distribution); or - - 2. a shared memory library using threads; or - - 3. a single-process sequential library (useful for development - and debugging). - The `TOP-C' model has been successfully used for some very large -computations. - - To unpack: - gunzip topc.tar.gz - tar xvf topc.tar - cd topc - ./configure - make - - If you are impatient, you can immediately do: - cd bin - make parfactor -and see a demonstration for factoring numbers by a Euclidean sieve. -Then try: `./a.out YOUR_NUMBER' -Read bin/Makefile for an example of compiling a `TOP-C' program. - - If you want to use more or different slave processes, modify -`bin/procgroup'. Then, again: - cd bin - ./a.out YOUR_NUMBER - - And compare with your results using a single slave process: - ./a.out --TOPC-num-slaves=1 YOUR_NUMBER - Or investigate what other command-line TOP-C options are available -for a.out. - ./a.out --TOPC-help - - Other TOP-C applications besides parfactor are in the directory -`../examples'. For example, if you would like to try `parquicksort.c', -then from the `bin' directory, try: - make check TEST_FILE=parquicksort - - When you write your own `TOP-C' application, `app.c', make sure that -it contains `#include ' at the top, and that you have a -procgroup file in the current directory, and then: - bin/topcc --mpi -o app app.c - # or else: bin/topc++ --mpi -o app app.cc - ./app -`topcc' is a wrapper for your standard C compiler. It accepts all the -standard compiler command line options, plus a few more. `topc++' also -exists. [NOTE: `bin/topcc --help' and `bin/topc++ --help' both work -and `doc/topcc.1' exists ] - - This might be a good point to download and print at least the first -half of the manual, or else make it from the doc directory (`cd doc; -make pdf; make ps'). Note that the table of contents may appear at the -end of the documentation after the index. See *note Summary::, for a -list of the `TOP-C' commands. See *note Example::, for a simple `TOP-C' -example application involving only trivial parallelism. The `examples' -subdirectory provides more detailed examples. A tutorial is available -from the web page, `http://www.ccs.neu.edu/home/gene/topc.html'. - - Finally, if you want to install `TOP-C' permanently, type - ./configure # Install in /usr/local - ./configure --prefix=$HOME # Install in home directory - make install - - This adds a man page, an info file (try `info topc'), etc. HTML -documentation is available in the `doc' subdirectory of the `TOP-C' -distribution. By default, `TOP-C' will install in `/usr/local', -requiring root privilege. If you configure `--prefix=$HOME', `TOP-C' -will create files in `$HOME/bin', `$HOME/lib', `$HOME/include', -`$HOME/man' and `$HOME/info'. If you want to make `TOP-C' with `cc' -instead of `gcc', type: - env CC=cc ./configure --cache-file=/dev/null - `CFLAGS', `CXX' (for `topc++' and `CXXFLAGS' can also be set. For -other configuration options, type: - ./configure --help - - Please write the author, Gene Cooperman (), if -there are any questions. - - -File: topc.info, Node: Overview, Next: Writing TOP-C Applications, Prev: Quick Start, Up: Top - -3 Overview of `TOP-C/C++' -************************* - - "Difficulty?" exclaimed Ford. "Difficulty? What - do you mean difficulty? [The wheel is] the single - simplest machine in the universe!" ... - "All right, Mr. Wiseguy," she said, "you're so - clever, you tell us what color it should be." - from "The Restaurant at the End of the Universe" - by Douglas Adams - -`TOP-C' has been designed especially to make it easy to parallelize -_existing_ sequential applications. Toward this goal, `TOP-C' -emphasizes: - 1. ease of use (high level task-oriented abstraction); - - 2. latency tolerance; and - - 3. architecture independence (same application code for shared - and distributed memory). - - A `TOP-C' application is compiled and run using `topcc' (similarly -to `gcc') or `topc++' (similarly to `g++'). For example, assuming a -`procgroup' file in the current directory to specify the remote hosts -for the slave processes, one executes: - topcc --mpi parfactor.c - # or else: topc++ --mpi parfactor.cc - ./a.out - - If a `TOP-C' application fails to link, check for a clash of symbol -names. All TOP-C symbols are of the form TOPC_*, COMM_*, MEM_*, MPI_*, -MPINU_*, NO_ACTION, UPDATE, REDO, CONTINUATION, or NOTASK. - - For purposes of documentation, we will standardize on an explanation -of `topcc'. Wherever `topcc' is mentioned, the description is equally -valid for `topc++'. - -* Menu: - -* Programmer Model:: -* Three Key Concepts for TOP-C:: -* Memory Models:: - - -File: topc.info, Node: Programmer Model, Next: Three Key Concepts for TOP-C, Prev: Overview, Up: Overview - -3.1 Programmer's Model -====================== - -* Menu: - -* Structure of a TOP-C Program:: -* Four Callback Functions:: -* Task Buffers:: -* The TOP-C Algorithm:: - - -File: topc.info, Node: Structure of a TOP-C Program, Next: Four Callback Functions, Prev: Programmer Model, Up: Programmer Model - -3.1.1 Structure of a TOP-C Program ----------------------------------- - -A typical TOP-C application has the following structure: - #include - ... define four callback functions for TOPC_master_slave() ... - int main( int argc, char **argv ) { - TOPC_init( &argc, &argv ); - ... - TOPC_master_slave( GenerateTaskInput, DoTask, CheckTaskResult, - UpdateSharedData ) - ... - TOPC_finalize(); - } - - The program above is run with a master process and several slave -processes operating with identical command line arguments and identical -initial data (SPSD, or Single Program, Single Data). Communication -among processes occurs only within the routine `TOPC_master_slave()', -during which execution can be called SPMD (Single Program, Multiple -Data). At the end of `TOPC_master_slave()', execution returns to SPSD, -although the master process may contain some additional process-private -data. - - *note TOP-C Raw Interface:: describes an alternative interface that -is often useful for parallelizing existing sequential code. However, -for new applications, the standard interface will usually be cleaner. - - -File: topc.info, Node: Four Callback Functions, Next: Task Buffers, Prev: Structure of a TOP-C Program, Up: Programmer Model - -3.1.2 Four Callback Functions ------------------------------ - -In a `TOP-C' application, the programmer defines four callback -functions and passes control to the `TOP-C' library through the -following command. - TOPC_master_slave(GenerateTaskInput, DoTask, CheckTaskResult, - UpdateSharedData); - - Pictorially, TOP-C arranges for the flow of control among the four -callback functions as follows: - - (ON MASTER) task input - GenerateTaskInput() ----------> - - - task input (ON A SLAVE) task output - -----------> DoTask(input) -----------> - - - task output (ON MASTER) action - -----------> CheckTaskResult(input, output) -----------> - - - if (action == UPDATE): - task input, task output (ON ALL PROCESSES) - -----------------------> UpdateSharedData(input, output) - - -File: topc.info, Node: Task Buffers, Next: The TOP-C Algorithm, Prev: Four Callback Functions, Up: Programmer Model - -3.1.3 Task Input and Task Output Buffers ----------------------------------------- - -A "task input" or "task output" is an arbitrary buffer of bytes of type -`(void *)' in `TOP-C'. The task buffers are arbitrary -application-defined data structures, which are opaque to `TOP-C'. Note -that in ANSI C, a void pointer is compatible with any other pointer type -(such as `(struct task_input *)' and `(struct task_output *)' in the -example below). - -* Menu: - -* Defining Task Buffers:: -* Marshaling:: -* Marshalgen:: - - -File: topc.info, Node: Defining Task Buffers, Next: Marshaling, Prev: Task Buffers, Up: Task Buffers - -Defining Application Task Buffers -................................. - -An application callback function returning a task input or task output -must encapsulate it in a function, `TOPC_MSG( void *BUF, int BUF_SIZE -)', which is then returned by the callback functions -`GenerateTaskInput()' and `DoTask()'. `TOPC_MSG()' internally -allocates a copy of BUF, and TOP-C later frees the copy automatically. -So, BUF may be reused by the application program. - - TOPC_BUF DoTask( struct task_input * inp ) { - struct task_output outp; - ... - outp = ...; - return TOPC_MSG( &outp, sizeof(outp) ); - } - - The principle of memory allocation in `TOP-C' is that if an -application allocates memory, then it is the responsibility of the -application to free that memory. `TOPC_MSG()' has the further property -of copying its buffer argument to a separate `TOP-C' space (using a -shallow copy), after which the application can free any memory it -allocated. This happens automatically in the above example, since -`outp' is allocated on the stack. - - -File: topc.info, Node: Marshaling, Next: Marshalgen, Prev: Defining Task Buffers, Up: Task Buffers - -Marshaling (Serialization) and Heterogeneous Architectures -.......................................................... - -If a heterogeneous architecture is used, there is an issue of -converting data formats or "marshaling". This is the application's -responsibility. For simple data formats (integers, floats or -characters), such conversion can easily be done in an ad hoc manner. -Most C compilers use the IEEE binary floating point standard, and -characters are almost always encoded in eight bit ASCII representation -(or possibly in a standard Unicode format). Although the byte ordering -of integers is not standardized, the system calls `htonl()' and -`ntohl()' are available to convert integers into 32 bit _network -integers_ that are portable across heterogeneous systems. - - For more complicated conversions, one can consider writing one's own -marshaling routines or else using a standard package for marshaling -such as the `XDR' library (RFC 1832, eXternal Data Representation), -`IDL' (`Corba'), or `SOAP' (`XML'). - - -File: topc.info, Node: Marshalgen, Prev: Marshaling, Up: Task Buffers - -Marshalgen, a Package for Marshaling -.................................... - -For complex C++ applications, we recommend tat you try out `Marshalgen' -package. A pointer to it is available from the TOP-C home page. Since -the C++ classes to be marshaled are already defined in `.h' files, -Marshalgen asks th user simply to annotate those files with comments -(for example, deep copying vs. shallow copying fo pointers). -`Marshalgen' also has support for such real world issues as -marshalingsubclasses and templates, handling of polymorphism, etc. The -`Marshalgen' preprocessor then generates methods for a new marshaling -class that know how to marshal and unmarshal the original class. - - -File: topc.info, Node: The TOP-C Algorithm, Prev: Task Buffers, Up: Programmer Model - -3.1.4 The `TOP-C' Algorithm ---------------------------- - -When there is only one slave, The `TOP-C' algorithm can be summarized -by the following C code. - { void *input, *output; - TOPC_ACTION action; - while ( (input = GenerateTaskInput()) != NOTASK ) { - do { - output = DoTask(input); - action = CheckTaskResult(input, output); - } while (action == REDO); /* REDO not useful for only one slave */ - if (action == UPDATE) then UpdateSharedData(input, output); - } - } - - On a first reading, it is recommended to skip the rest of this -section until having read through Section *note Actions::. - - For a better understanding of the case of multiple slaves, this -simplified excerpt from the `TOP-C' source code describes the `TOP-C' -algorithm. - TOPC_BUF input, output; - int num_idle_slaves = num_slaves; - TOPC_ACTION action; - - while (TRUE) { - wait_until_an_idle_slave(); - input = COMM_generate_task_input(); - if (input.data != NOTASK.data) { - SUBMIT_TO_SLAVE: output = DoTask(input.data); - num_idle_slaves--; - } - else if (num_idle_slaves < num_slaves) // else insure progress condition - receive_task_output(); // by blocking until a slave replies - else break; - } // termination condition: _after_ all slaves idle, next input was NOTASK - - The code for `wait_until_an_idle_slave()' can be expanded as follows. - void wait_until_an_idle_slave() { - do { - while ( result_is_available(&input, &output) ) { - action = CheckTaskResult(input.data, output.data); - if (action == UPDATE) - UpdateSharedData(input.data, output.data); - if (action == REDO) /* Use updated shared data, when redoing */ - SUBMIT_TO_SLAVE: output = DoTask(input.data); - num_idle_slaves++; - } while (num_idle_slaves == 0); - } - - Note that the term "result" refers to an `(input,output)' pair. The -routine `CheckTaskResult()' returns an "action", which determines the -control structure for a parallel algorithm. A common definition is: - - TOPC_ACTION CheckTaskResult( void *input, void *output ) { - if (output == NULL) return NO_ACTION; - else if ( TOPC_is_up_to_date() ) return UPDATE; - else return return REDO; } - - `TOPC_is_up_to_date()' returns true if and only if during the -interval between when the task input was originally generated and when -the task output was returned by the most recent slave, no other slave -process had returned a task output during the interim that had caused -the shared data to be modified through an `UPDATE' action. An `UPDATE' -action causes `UpdateSharedData()' to be invoked on each process. -Further discussion can be found in *note TOP-C Utilities::. - - -File: topc.info, Node: Three Key Concepts for TOP-C, Next: Memory Models, Prev: Programmer Model, Up: Overview - -3.2 Three Key Concepts for TOP-C -================================ - -The `TOP-C' programmer's model is based on three key concepts: - 1. "tasks" in the context of a master/slave architecture; - - 2. global "shared data" with lazy updates; and - - 3. "ACTIONS" to be taken after each task. - - Task descriptions (task inputs) are generated on the master, and -assigned to a slave. The slave executes the task and returns the -result to the master. The master may update its own private data based -on the result, or it may update data on all processes. Such global -updates take place on each slave after the slave completes its current -task. Updates are "lazy" in that they occur only after a task -completes, although it is possible to issue a non-binding request to -`TOP-C' to abort the current tasks (*note Aborting Tasks::). A SPMD -(Single Program Multiple Data) style of programming is encouraged. - - In both shared and distributed memory architectures, one must worry -about the order of reads and writes as multiple slaves autonomously -update data. The utilities below are meant to ease that chore, by -supporting the ease of the SPMD programming style, while still -maintaining good efficiency and generality for a broad range of -applications. The software can easily be ported to a variety of -architectures. - - -File: topc.info, Node: Memory Models, Prev: Three Key Concepts for TOP-C, Up: Overview - -3.3 Distributed and Shared Memory Models -======================================== - -`TOP-C' provides a single API to support three primary memory models: -"distributed memory", "shared memory" and "sequential memory". (The -last model, sequential memory, refers to a single sequential, -non-parallel process.) On a first reading, one should think primarily -of the distributed memory model (distributed nodes, each with its own -private memory). Most programs written for distributed memory will -compile without change for sequential memory. `TOP-C' is designed so -that the same application source code may operate efficiently both -under distributed and under shared memory. In order to also compile -for shared memory hardware (such as SMP), additional hints to `TOP-C' -may be necessary. - - In shared memory architectures, _all_ data outside of the four -callback functions is shared, by default. Hence, an `UPDATE' action -under shared memory causes only the master process to invoke -`UpdateSharedData()'. To avoid inconsistencies in the data, by default -`TOP-C' arranges that no slave process may run `DoTask()' while -`UpdateSharedData()' is running. `TOP-C' also provides support for -finer levels of granularity through application-defined private -variables and critical sections. Further discussion can be found in -*note Shared Memory Model::. - - -File: topc.info, Node: Writing TOP-C Applications, Next: Compiling and Invoking TOP-C Applications, Prev: Overview, Up: Top - -4 Writing `TOP-C' Applications -****************************** - -This chapter assumes a knowledge of the basic concepts in *note -Overview::. In particular, recall *note Structure of a TOP-C Program::. - -* Menu: - -* The Main TOP-C Library Calls:: -* Callback Functions:: -* Actions:: -* TOP-C Utilities:: - - -File: topc.info, Node: The Main TOP-C Library Calls, Next: Callback Functions, Prev: Writing TOP-C Applications, Up: Writing TOP-C Applications - -4.1 The Main TOP-C Library Calls -================================ - -Every `TOP-C' application must include a `topc.h' header, open with -`TOPC_init()', call `TOPC_master_slave()' one or more times, and then -close with `TOPC_finalize()'. - - `#include ' - Required at head of any file using TOPC library calls. - - -- Function: void TOPC_init ( int *ARGC, char ***ARGV ) - Required before first occurrence of `TOPC_master_slave()'; - Recommended to place this as first executable statement in - `main()'. It will strip off extra `TOP-C' and - communication layer arguments such as `--TOPC-stats', - which are added by `TOP-C'. - - -- Function: void TOPC_finalize ( void ) - Placed after last `TOP-C' command. - - -- Function: void TOPC_master_slave - ( TOPC_BUF (*GENERATE_TASK_INPUT)(), - TOPC_BUF (*DO_TASK)(void *input), - TOPC_ACTION (*CHECK_TASK_RESULT)(void *input, void *output), - void (*UPDATE_SHARED_DATA)(void *input, void *output) - ) - Primary call, passed four application callbacks to `TOP-C'. - One can have multiple calls to `TOPC_master_slave()', - each invoking different callback functions, between - `TOPC_init()' and `TOPC_finalize()'. - - - A task input or task output is simply a buffer of bytes, specified by -`TOPC_MSG()'. - - -- Function: TOPC_BUF TOPC_MSG ( void *BUF, int BUF_SIZE ) - Must be returned by `GenerateTaskInput()' and `DoTask()'. - Specifies arbitrary user data structure. `TOP-C' will - make a copy of BUF in `TOP-C' space. It remains the - responsibility of the application to free or reuse the space - of the original buffer BUF. If `TOPC_MSG(NULL, 0)' is called, - a `NULL' pointer will be received at the destination. (*Note - Large Buffers and TOPC_MSG_PTR::, for `TOPC_MSG_PTR', to - avoid copying very large buffers, where the overhead is - unacceptable.) - -EXAMPLE: - TOPC_BUF convert_string_to_msg( char *mystring ) { - if (mystring == NULL) return TOPC_MSG(NULL,0); - else return TOPC_MSG(mystring, strlen(mystring)+1); - } - - -File: topc.info, Node: Callback Functions, Next: Actions, Prev: The Main TOP-C Library Calls, Up: Writing TOP-C Applications - -4.2 Callback Functions for `TOPC_master_slave()' -================================================ - -The application writer must define the following four callback functions -(although the last can be `NULL'). The CALLBACK terminology is based -on C concepts. In a more object-oriented style, one would view user -callbacks as instantiation of abstract methods in a user-defined -subclass. The first two functions return a `TOPC_BUF', which is -produced by `TOPC_MSG()'. - - -- Function: TOPC_BUF GenerateTaskInput ( void ) - executes on master; returns a data structure specified by - `TOPC_MSG(BUF, BUF_SIZE)'. It should return `NOTASK', - when there are no more tasks, and it should be prepared to - return `NOTASK' again if invoked again. - - -- Function: TOPC_BUF DoTask ( void *INPUT ) - executes on slave; operates on the result of `GenerateTaskInput()'; - returns a data structure specified by - `TOPC_MSG(BUF, BUF_SIZE)'. BUF must be a static or global - user buffer. - - -- Function: TOPC_ACTION CheckTaskResult ( void *INPUT, void *OUTPUT) - executes on master; operates on the result of `DoTask()'; - returns an ACTION that determines what happens to the task next. - The terminology "result" refers to an `(input, output)' pair. - An easy way to write `CheckTaskResult()' appears in the - example for the utility `TOPC_is_up_to_date()'. When - returning the action `UPDATE', it works to first modify - the input and output buffers. `UpdateSharedData()' will - then be invoked with the modified buffers. See *note - TOP-C Utilities::, for more details. - - -- Function: void UpdateSharedData ( void *INPUT, void *OUTPUT ) - executes on master and all slaves; operates on the result of - `DoTask()', and the original task returned by - `GenerateTaskInput()'; called only if `CheckTaskResult()' - returned `UPDATE'; useful for updating global variables in - all processes; The pointer argument, UPDATE_SHARED_DATA, of - `TOPC_master_slave()' may be `NULL' if an - application never requests an `UPDATE' action. In a - shared memory environment, only the master calls - `UpdateSharedData()'. See *note Shared Memory Model::, for more - details. - - Note that in defining the above callback functions, C allows one to -replace the `(void *)' declaration of the arguments by specific pointer -types. Note that the buffers of any message parameters (INPUT and -OUTPUT) of `DoTask()' or `CheckTaskResult()' are part of TOP-C space. -Such buffers may be freed by TOP-C on exit from the callback function. -An application wishing to use the buffer after the callback exits must -explicitly save a copy into the application's own space. - - -File: topc.info, Node: Actions, Next: TOP-C Utilities, Prev: Callback Functions, Up: Writing TOP-C Applications - -4.3 Actions Returned by `CheckTaskResult()' -=========================================== - -A "TOP-C result" is an (INPUT, OUTPUT) pair corresponding to an -invocation of `DoTask()'. `TOP-C' passes the result to -`CheckTaskResult()'. The return value allows the application to tell -`TOP-C' what further actions to take. The actions returned by -`CheckTaskResult()' are: - - -- Action: TOPC_ACTION NO_ACTION - C constant, causing no further action for task - - -- Action: TOPC_ACTION UPDATE - C constant, invoking `UpdateSharedData( void *INPUT, void - *OUTPUT)' (see below) also updates bookkeeping for sake of - `TOPC_is_up_to_date()' (*note TOP-C Utilities::) - - -- Action: TOPC_ACTION REDO - Invoke `DoTask()' on original task input again, and on - the same slave that previously executed the task; useful if - shared data has changed since original invocation of - `DoTask()' (see `TOPC_is_up_to_date()', below). See - *note Strategies for Greater Concurrency::, for slave - strategies to efficiently process a `REDO' action. - - -- Action: TOPC_ACTION CONTINUATION ( void *NEXT_INPUT ) - `CONTINUATION(NEXT_INPUT)' is a parametrized action that may be - returned by `CheckTaskResult()', after which `DoTask( - NEXT_INPUT )' is called on the original slave. This is - useful if only the master can decide whether task is complete, - or if the master wishes to supply additional input messages - needed for the task. Note that `REDO' is essentially - equivalent to `CONTINUATION( ORIGINAL_TASK_INPUT )'. - Note that any pending calls to `UpdateSharedData()' will have - occurred on the slave before the new call to `DoTask()'. - Hence, this allows an extended conversation between master and - slave, in which the slave continues to receive updates of the - shared data before each new input from the master. - Note also that even though a `CONTINUATION' action returns - to the original slave, any previous pointers to input buffers - on that slave (and pointers to output buffers from - intervening `UPDATE' actions) will no longer be valid. - Useful data from previous buffers should have been copied - into global variables on the slave. In the case of the - shared memory model, those global variables must be - thread-private. (*note Thread-Private Global Variables::) - - It is possible for `CheckTaskResult(INPUT, OUTPUT)' to modify the -buffer data in its two arguments, INPUT and OUTPUT, in which case the -modifications will be visible to any further callback functions -processing the current task. This practice makes the code more -difficult to maintain, and is not recommended when other solutions are -available. - - -File: topc.info, Node: TOP-C Utilities, Prev: Actions, Up: Writing TOP-C Applications - -4.4 TOP-C Utilities -=================== - -`TOP-C' also defines some utilities. - - -- Function: TOPC_BOOL TOPC_is_up_to_date ( void ) - returns TRUE or FALSE (1 or 0); returns TRUE if and only if - `CheckTaskResult()' has not returned the result `UPDATE' - (invoking `UpdateSharedData()') between the time - when `GenerateTaskInput()' was originally called on the - current task, and the time when the corresponding - `CheckTaskResult()' was called. Typical usage: - TOPC_ACTION CheckTaskResult( void *input, void *output ) - { if (input == NULL) return NO_ACTION; - else if (TOPC_is_up_to_date()) return UPDATE; - else return REDO; - } - - -- Function: int TOPC_rank ( void ) - Unique ID of process or thread. Master always has rank 0. - Slaves have contiguous ranks, beginning at 1. - - -- Function: TOPC_BOOL TOPC_is_master ( void ) - Returns boolean, 0 or 1, depending on if this is master. - Equivalent to `TOPC_rank() == 0'. - - -- Function: int TOPC_num_slaves ( void ) - Total number of slaves. - - -- Function: int TOPC_num_idle_slaves ( void ) - Total number of idle slaves (not doing task, update or other - action). - - -- Function: int TOPC_node_count ( void ) - Total number of processes or threads. Equivalent to - `TOPC_num_slaves() + 1'. - - -- Function: TOPC_BOOL TOPC_is_REDO ( void ) - -- Function: TOPC_BOOL TOPC_is_CONTINUATION ( void ) - -- Function: void TOPC_abort_tasks ( void ) - -- Function: TOPC_BOOL TOPC_is_abort_pending ( void ) - See *note Advanced Features:: for descriptions. - - -File: topc.info, Node: Compiling and Invoking TOP-C Applications, Next: Debugging and Tracing, Prev: Writing TOP-C Applications, Up: Top - -5 Compiling and Invoking `TOP-C' Applications -********************************************* - -A `TOP-C' application can be compiled once, and then linked to your -choice of a run-time library for either a sequential, distributed memory -or shared memory architecture. The two shell scripts `bin/topcc' and -`bin/topc++' are used instead of `gcc' and `g++' (or other C/C++ -compilers). - -* Menu: - -* Compiling TOP-C Applications:: -* Command Line Options:: -* Invoking a TOP-C Application in Sequential Memory:: -* Invoking a TOP-C Application in Distributed Memory:: -* Invoking a TOP-C Application in Shared Memory:: - - -File: topc.info, Node: Compiling TOP-C Applications, Next: Command Line Options, Prev: Compiling and Invoking TOP-C Applications, Up: Compiling and Invoking TOP-C Applications - -5.1 Compiling TOP-C Applications -================================ - -The TOP-C application file must contain - #include - It must make calls to - TOPC_init(...); - TOPC_master_slave(...); - TOPC_finalize(); -as describe in *note Structure of a TOP-C Program::. The application -file is compiled by one of: - topcc --seq MYFILE.C - topcc --mpi MYFILE.C - topcc --pthread MYFILE.C -according to whether the target computer architecture will be sequential -(`--seq': single processor), distributed memory (`--mpi': networked -CPU's), or shared memory (`--pthread': SMP or other shared memory -architecture with a POSIX threads interface). `topcc' is a substitute -for `cc' or `gcc', and creates an `a.out' file. (Similarly, `topc++' -exists as a substitute for `c++' or `g++'.) There are man files, - `doc/topcc.1', `doc,topc++.1' - with further information on `topcc' and `topc++'. If installed, -`man topcc' and `man topc++' exist. - - The same object file may be relinked to use different `TOP-C' memory -models without recompiling the object file. - topcc -c MYAPP.C - topcc --seq -o MYAPP-SEQ MYAPP.O - topcc --mpi -o MYAPP-MPI MYAPP.O - - For large applications, it may be preferable to directly invoke the -`TOP-C' libraries and include files. For such situations, -`topc-config' exists. The following is exactly equivalent to `topcc ---mpi myfile.c' (assuming you configured `TOP-C' using `gcc'). - gcc `topc-config --cflags` --mpi myfile.c `topc-config --libs` - Type `topc-config' with no arguments for a full set of command line -options. - - For the rest of this chapter, we standardize our description for -`topcc'. However, `topc++' is equally valid wherever `topcc' is -mentioned. - - -File: topc.info, Node: Command Line Options, Next: Invoking a TOP-C Application in Sequential Memory, Prev: Compiling TOP-C Applications, Up: Compiling and Invoking TOP-C Applications - -5.2 Command Line Options in TOP-C Applications -============================================== - -TOP-C searches for TOP-C parameters in the following locations, in -order: - 1. values of variables `TOPC_OPT_xxx' in the application code - before `TOPC_init()' - - 2. the file `.topcrc' in the home directory - - 3. the environment variable `TOPC_OPTS' - - 4. arguments on the command line in the form `--TOPC-xxx' - The file `.topcrc' and the environment variable `TOPC_OPTS' -specify parameters in the same format as on the command line. Later -assignments of an option override earlier assignments. - - For a brief synopsis of application command line options, type: - topcc MYAPP.C - ./a.out --TOPC-help - [ OR FOR MORE INFORMATION: ./a.out --TOPC-help --TOPC-verbose ] - - Currently, this will display the following. - Usage: ./a.out [TOPC_OPTION ...] [OTHER_OPTIONS ...] - - where TOPC_OPTION is one of: - --TOPC-help`[=<0/1>]' display this message [default: false] - --TOPC-stats`[=<0/1>]' print stats before & after [default: false] - --TOPC-verbose`[=<0/1>]' set verbose mode [default: false] - --TOPC-num-slaves`=' number of slaves (sys-defined default) - [default: -1] - --TOPC-aggregated-tasks`=' number of tasks to aggregate - [default: 1] - --TOPC-slave-wait=`' secs before slave starts (use w/ gdb attach) - [default: 0] - --TOPC-slave-timeout=`' dist mem: secs to die if no msgs, 0=never - [default: 1800] - --TOPC-trace`=' trace (0: notrace, 1: trace, 2: user trace fncs.) - [default: 2] - --TOPC-procgroup`=' procgroup file (--mpi) - [default: "./procgroup"] - --TOPC-topc-log`=' NOT IMPL: log file for TOPC output ("-" = stdout) - [default: "-"] - --TOPC-safety=`' [0..20]: higher turns off optimizations, - (try with --TOPC-verbose) [default: 0] - - For each option, `--TOPC-PARAM', there is a corresponding C/C++ -variable, `TOPC_OPT_PARAM'. This variable is of type `int' or `(char -*)'. If the application program sets the value before a call to -`TOPC_init()', these variables will act as defaults. For example, to -turn off tracing by default, write: - int main( int argc, char *argv[] ) { - TOPC_OPT_trace = 0; - TOPC_init( &argc, &argv ); - ... - } - - The option `--TOPC-trace' causes the task input and task output to -be traced and printed as they are passed across the network. The -action of a task is also printed. If an application is called with -`--TOPC-trace=2' (default) and if the variables `TOPC_OPT_trace_input' -and `TOPC_OPT_trace_result' are set to pointers to functions then those -functions are called, and they may print additional information. -`TOPC_OPT_trace_input' must be set to a function of one variable: -`void * INPUT'. `TOPC_OPT_trace_result' must be set to a function of -two variables: `void * INPUT, void * OUTPUT'. When using C++, the -function pointers must be cast to `TOPC_trace_input_ptr' or -`TOPC_trace_result_ptr' before being assigned to `TOPC_OPT_trace_input' -or `TOPC_OPT_trace_result', respectively. For an example, see -`examples/parfactor.c' in the TOP-C distribution. - - The option `--TOPC-stats' prints statistics (running times, etc.) and -information about the conditions of an invocation of a TOP-C application -before and after a run. The option `--TOPC-verbose' (set by default) -displays TOP-C warnings. With -TOPC-help, it provides additional -information. - - For the usage of `--TOPC-procgroup', see *note Invoking a TOP-C -Application in Distributed Memory::. That section also explains on -what hosts the slaves run when `--TOPC-num-slaves' indicates a -different number of slaves than the `procgroup' file. - - For the usage of `--TOPC-aggregated-tasks', see *note Improving -Performance::. For the usage of `--TOPC-slave-wait', see *note -Stepping Through a Slave::. For the usage of `--TOPC-safety', see -*note Command Line Options::. For the usage of the other options, see -the *note Concept Index::. - - `TOP-C' recognizes `--' as terminating all option processing, -according to standard UNIX conventions. - - -File: topc.info, Node: Invoking a TOP-C Application in Sequential Memory, Next: Invoking a TOP-C Application in Distributed Memory, Prev: Command Line Options, Up: Compiling and Invoking TOP-C Applications - -5.3 Invoking a TOP-C Application in Sequential Memory -===================================================== - -For example, - topcc --seq -g -O0 MYFILE.C - compiles a sequential version for debugging using `gdb' (*note -Summary: (gdb)Top.), for example. This is usually a first step in -debugging a TOP-C application, since sequential debugging is easier -than parallel debugging. - - -File: topc.info, Node: Invoking a TOP-C Application in Distributed Memory, Next: Invoking a TOP-C Application in Shared Memory, Prev: Invoking a TOP-C Application in Sequential Memory, Up: Compiling and Invoking TOP-C Applications - -5.4 Invoking a TOP-C Application in Distributed Memory -====================================================== - -Linking using the `--mpi' option (default) allows an application to -execute using a distributed memory model of networked processors. The -`TOP-C' distribution includes a subset MPI(1) implementation `MPINU', -sufficient to run `TOP-C' applications. - topcc --mpi MYAPP.C - ./a.out -The application must then create the remote slave processes at runtime. -If you use `MPINU' (the default configuration of `TOP-C', then the -remote slave processes are specified by a `procgroup' file. Otherwise, -the startup mechanism depends on your `MPI' implementation. - -* Menu: - -* Procgroup Files:: -* Slaves Fail to Start:: - - ---------- Footnotes ---------- - - (1) MPI is _Message Passing Interface_, see -`http://www.mpi-forum.org/' - - -File: topc.info, Node: Procgroup Files, Next: Slaves Fail to Start, Prev: Invoking a TOP-C Application in Distributed Memory, Up: Invoking a TOP-C Application in Distributed Memory - -5.4.1 Writing Procgroup Files for `MPINU' ------------------------------------------ - -`MPINU' is built into the default configuration of the `TOP-C' library -and uses the `procgroup' mechanism to specify slave processes. (If you -prefer to use a different `MPI' dialect, `TOP-C' will work, but -`src/Makefile.in' must be modified, and that `MPI' dialect may use a -different mechanism for introducing slave processes.) - - When the application binary is executed under the default, it looks -at the current directory for a file, - `procgroup' - The PROCGROUP FILE determines the number and location of the slave -processes. The PROCGROUP FILE need only be visible from the master -process. If one prefers, one can specify an alternate PROCGROUP FILE -via the syntax as in the following example: - ./a.out --TOPC-procgroup=../myprocgroup.big - - The `TOP-C' distribution includes a file `bin/procgroup' as an -example of the procgroup format. The file must contain a line: - local 0 - for the master process. It must also contain a line for each slave -process in one of the following forms: - hostname 1 FULL_PATHNAME - hostname 1 - - hostname 1 ./RELATIVE_PATHNAME - hostname 1 ../RELATIVE_PATHNAME - where `hostname' is the remote host. The pathname `-' means to use -the same pathname for the slave on the remote host as for the master on -the current host. A relative pathname, such as `./a.out' or -`../new_arch/a.out', specifies a pathname relative to the pathname of -the binary of the master on the current host. - - Most of the time, it is simplest to just include a full pathname or -else `-' in the `procgroup' file. The relative pathnames are useful -for a shared filesystem with binaries compiled for different -architectures. For example, the procgroup file might include relative -paths `../sparc/a.out', `../alpha/a.out' and `../linux/a.out'. If you -invoke `full_path/sparc/a.out', this will yield a master running -`full_path/sparc/a.out' and three slaves running each of the three -architectures. - - The full principles are as follows. Let SLAVE_PATH be the path of -the slave as given in the procgroup file, and let MASTER_DIR be the -directory of the master process as invoked on on the command line. - SLAVE_PATH absolute: - slave binary image is SLAVE_PATH - SLAVE_PATH relative and MASTER_DIR absolute: - slave binary image is MASTER_DIR/SLAVE_PATH - SLAVE_PATH relative and MASTER_DIR relative: - slave binary image is $PWD/MASTER_DIR/SLAVE_PATH - SLAVE_PATH is - and master process invoked on command line as MASTER_BIN: - slave binary image is MASTER_BIN (if MASTER_BIN is absolute path) - or $PWD/MASTER_BIN (if MASTER_BIN is relative path) - If the procgroup line contains command line arguments, - those command line arguments are passed to the slave application - as its first arguments, and any arguments on the master command - line are appended to the list of arguments. - TOP-C assumes that your application does not change the working -directory before calling `TOPC_init()'. - - By default, `TOP-C' uses the procgroup file in the current directory. -You can choose an explicit procgroup file via a program variable, -`TOPC_OPT_procgroup="/project/myprocgroup";', or via a command-line -option, `/project/sparc/app --TOPC-procgroup=/project/myprocgroup'. -*Note Command Line Options::. - - If the command line option `--TOPC-num-slaves=INT' is given, and if -INT is less than the number of slaves in the `procgroup' file, then -`TOP-C' will use the first INT slaves from the file. If INT is more -than the number of slaves in the `procgroup' file, then `TOP-C' will -use all of the given slaves, and then create additional processes on -the remote hosts, by returning to the beginning of the `procgroup' file -and re-reading the list of slave host/binaries until INT slaves have -been created in all. - - It is recommended to use only `localhost' during initial development. - - The environment variable, `SSH' (default value `ssh') is used to -invoke the remote host. If, for example, your site uses `rsh' instead -of `ssh', the following code, when executed before `TOPC_init()' will -produce this effect. - putenv("SSH=rsh"); - Alternatively, type `SSH=rsh' (sh/bash, etc.) or `setenv SSH rsh' -(csh/tcsh, etc.) in the UNIX shell before invoking the TOP-C -application. - - -File: topc.info, Node: Slaves Fail to Start, Prev: Procgroup Files, Up: Invoking a TOP-C Application in Distributed Memory - -5.4.2 If Slaves Fail to Start ------------------------------ - -If some slave processes start, but not others, then try executing the -following simple program. - #include "topc.h" - int main(int argc, char *argv) { - char host[100]; - printf("%s connecting ...\n", gethostname(host, 99)); - TOPC_init(&argc, &argv); - printf("... %s connected.\n", gethostname(host, 99)); - TOPC_finalize(); - } - - If the slave processes fail to start up or fail to respond to the -master and if you are using `MPINU' (default configuration of `TOP-C', -one other debugging resource is available. If an application fails to -start up, then `TOP-C' leaves in the `/tmp' directory a file - `/tmp/mpinu-ssh.$$' - where `$$' is the process id. The file shows the commands that -`TOP-C/mpinu' tried to use to start up the slave process. By examining -and even manually executing those commands from the terminal, one can -often deduce the difficulty in creating the slave processes. - - Test the ability of your computer facility to execute remote -processes _without passwords_ by typing: `ssh REMOTE_HOST pwd'. If -the problem is that `ssh' is not working, try setting the environment -variable `SSH' to `ssh' or other site-specific setting. *Note -Procgroup Files::. - - If you are using `ssh' (default if the environment variable `SSH' is -not set), and if it requires a password then the following commands -within UNIX may allow ssh to operate on your local cluster without -passwords. - ssh-keygen -t dsa [accept default values] - ssh-keygen -t rsa [accept default values] - cat ~/.ssh/id*.pub >> ~/.ssh/authorized_keys - For security, be sure that ~/.ssh has no read permission for other -users. - - -File: topc.info, Node: Invoking a TOP-C Application in Shared Memory, Prev: Invoking a TOP-C Application in Distributed Memory, Up: Compiling and Invoking TOP-C Applications - -5.5 Invoking a TOP-C Application in Shared Memory -================================================= - -Linking using the `--pthread' option allows an application to execute -using POSIX threads. Note that the `TOP-C' memory model for shared -memory has some small variations from the distributed memory model. -The largest potential source of incompatibility is if your `DoTask()' -routine modifies any global or static variables. If so, such variables -will need to be declared "thread private". Check your source code to -see if this affects you. - - Second, if you encounter insufficient performance, you may consider -experimenting with _fine grain thread parallelism_. The default -`TOP-C' algorithm for shared memory allows `UpdateSharedData()' to -begin executing only after each current invocation of `DoTask()' -completes. This can be modified by an application for finer grain -parallelism. *Note `TOP-C' Shared Memory Model: Shared Memory Model, -for details in either of the above cases. - - Note also that while a `TOP-C' application object file can usually be -linked using an arbitrary `TOP-C' memory model without recompiling, -there are some circumstances where you may first need to recompile the -application source using `topcc --pthread'. - - -File: topc.info, Node: Debugging and Tracing, Next: Performance and Long Jobs, Prev: Compiling and Invoking TOP-C Applications, Up: Top - -6 Debugging and Tracing -*********************** - -If the difficulty is that the application fails to start in the -distributed memory model (using `topcc --mpi'), then read *note Slaves -Fail to Start::, for some debugging techniques. Note also that TOP-C -ignores SIGPIPE. This is because TOP-C employs the SO_KEEPALIVE -option, and the master process would otherwise die if a slave process -were to die. SO_KEEPALIVE is needed for robustness when slave -processes execute long tasks without communicating with the master -process. The rest of this section assumes that the application starts -up correctly. - -* Menu: - -* Debugging by Limiting Parallelism:: -* Debugging with --TOPC-safety:: -* TOP-C and POSIX signals:: -* Tracing Messages:: -* Stepping Through a Slave:: -* Segmentation faults:: - - -File: topc.info, Node: Debugging by Limiting Parallelism, Next: Debugging with --TOPC-safety, Prev: Debugging and Tracing, Up: Debugging and Tracing - -6.1 Debugging by Limiting the Parallelism -========================================= - -First, compile and link your code using `topcc --seq --TOPC-safety=20 --g -O0', and make sure that your application works correctly -sequentially. Only after you have confidence in the correctness of the -sequential code, should you begin to debug the parallel version. - - If the application works correctly in sequential mode, one should -debug in the context of a single slave. It is convenient to declare the -remote slave to be `localhost' in the `procgroup' file, in order to -minimize network delays and so as not to disturb users of other -machines. In this case, the code is "almost" sequential. An easy way -to do this is: - topcc --mpi --TOPC-num-slaves=1 -g -O0 - - Next, one should test on two slaves, and finally all possible slaves. - - -File: topc.info, Node: Debugging with --TOPC-safety, Next: TOP-C and POSIX signals, Prev: Debugging by Limiting Parallelism, Up: Debugging and Tracing - -6.2 Debugging with `--TOPC-safety' -================================== - -The command-line option `--TOPC-safety=VAL' provides assistance for -debugging parallel programs. At higher values of VAL, optimizations -that do not change the correctness of the program are converted to -safer equivalents. A good strategy is to test if `--TOPC-safety=20' -causes the bug to go away, and if so, progressively lower VAL toward -zero, until the bug reappears. The value at which the bug reappears -indicates what `TOP-C' optimization feature is not being used -correctly. If the bug still exists at `--TOPC-safety=20', one should -next try compiling with the `--seq' flag and use a debugger to debug -the sequential code. - - The effects due to different safety levels are subject to change. -To see the current effects, invoke any TOP-C application as follows - ./a.out --TOPC-help --TOPC-verbose - and you will see something like: - safety: >=0: all; >=2: no TOP-C memory mgr (uses malloc/free); - >=4: no TOPC_MSG_PTR; >=8: no aggreg.; - >=12: no TOPC_abort_tasks; >=14: no receive thread on slave; - >=16: default atomic read/write for DoTask, UpdateSharedData; - =19: only 2 slaves; >=20: only 1 slave - (AGGREGATION NOT YET IMPLEMENTED) - - Values higher than 4 cause `TOPC_MSG_PTR()' to act as if -`TOPC_MSG()' was called instead. Values higher than 12 cause -`TOPC_abort_tasks()' to have no effect. Values higher than 14 imply -that a single thread in the slave process must receive messages and -execute `DoTask()'. Normally, `TOP-C' arranges to overlap -communication and computation on the slave by setting up a separate -thread to receive and store messages from the master. Values higher -than 15 imply that `TOP-C' will use malloc instead of trying to do its -own memory allocation (which is optimized for `TOP-C' memory patterns). -Values higher than 16 imply that all of `DoTask' acts as if a read lock -was placed around it, and all of `UpdateSharedData' has a write lock -placed aound it. (This has an effect only in the shared memory model -where calls to `TOPC_ATOMIC_READ/WRITE' are ignored.) At values of 19 -and 20, the number of slaves is reduced to 2 and to 1, regardless of -the setting of `--TOPC-num-slaves' and the specification in a -`procgroup' file. - - -File: topc.info, Node: TOP-C and POSIX signals, Next: Tracing Messages, Prev: Debugging with --TOPC-safety, Up: Debugging and Tracing - -6.3 TOP-C and POSIX signals -=========================== - -If an application handles its own signals, this can create a clash with -the TOP-C. In the distributed memory model (-mpi), `TOP-C' will create -its own signal handlers for `SIGALRM'. This is used in conjunction with -`alarm()' to eventually kill runaway slave processes. In addition, if -using `MPINU', the built-in MPI subset, `TOP-C' will create its own -handler for `SIGPIPE'. This is in order to allow the master process to -detect dead sockets, indicating dead slaves. Finally, for short -periods, `MPINU' will disable the use of `SIGINT' around calls to -`select()'. Nevertheless, if a SIGINT is sent during this period, -TOP-C will pass the signal on to the original SIGINT handler of the -application. - - `TOP-C' does not modify signal handlers in the sequential (-seq) or -shared memory (-pthread) models. Furthermore, if a different MPI -(other than MPINU) is used with TOP-C, TOP-C will only handle -`SIGALRM'. However, the other MPI may handle signals itself. *Note -Using a Different MPI with TOP-C::. - - -File: topc.info, Node: Tracing Messages, Next: Stepping Through a Slave, Prev: TOP-C and POSIX signals, Up: Debugging and Tracing - -6.4 Tracing Messages -==================== - -If a bug appears as one moves to greater parallelism, one should trace -messages between master and slaves (for any number of slaves). This is -the default, and it can be enabled on the command line with: - ./a.out --TOPC-trace=2 ARGS - The variable `TOPC_OPT_trace' can be set in the code to dynamically -turn tracing on (1 or 2) and off (0) during a single run. A trace -value of 2 causes `TOP-C' to invoke the application-defined trace -functions pointed to by `TOPC_OPT_trace_input/result'. If the -application has not defined trace functions, or if `TOPC_OPT_trace' is -1, then the `TOP-C' default trace functions are invoked. All message -traces are displayed by the master at the time that the master sends or -receives the corresponding message. - - -- Variable: void (*)(void *input) TOPC_OPT_trace_input - -- Variable: void (*)(void *input, void *output) TOPC_OPT_trace_result - Global pointer (default is `NULL') to function returning - `void'. User can set it to his or her own trace function - to print out data-specific tracing information in - addition to generic message tracing of `TOPC_trace'. - - EXAMPLE: if you pass integers via `TOPC_MSG()', define - `TOPC_trace_input()' as: - void mytrace_input( int *input ) { - printf("%d",*input); - } - TOPC_OPT_trace_input = mytrace_input; - - Note that the term `result' in `TOPC_OPT_trace_result' refers to an -`(input, output)' pair. - - -File: topc.info, Node: Stepping Through a Slave, Next: Segmentation faults, Prev: Tracing Messages, Up: Debugging and Tracing - -6.5 Stepping Through a Slave Process with `gdb' -=============================================== - -If you find the master hanging, waiting for a slave message, then the -probable cause is that `DoTask()' is doing something bad (hanging, -infinite loop, bus/segmentation error, etc.). First try to isolate the -bug using a symbolic debugger (e.g. `gdb') and the sequential memory -model. If your intended application is the shared memory model, you -can also use `gdb' to set a breakpoint in your `DoTask' routine or at -the `TOP-C' invocation, `do_task_wrapper'. - - If the bug only appears in the distributed memory model, you can -still symbolically debug `DoTask()' using `gdb' (the GNU C debugger) -and its `attach' command (*note Attach: (gdb)Running.), which allows -you to attach and debug a separate running process. This lets you -debug a running slave, if it is running o the same processor. For this -strategy, you will want the slave to delay executing to give you time -to execute gdb and attach on the remote host or remote thread. The -command line option `--TOPC-slave-wait=30' will force the slave to wait -30 seconds before processing. - - In applying this debugging strategy to an application `./a.out', one -might see: - [ Execute ./a.out in one window for master process ] - gdb ./a.out - (gdb) run --TOPC-trace=1 --TOPC-safety=19 --TOPC-slave-wait=30 ARGS - - [ In a second window for a slave process on a different host, now type: ] - ps - ... - 1492 p4 S 0:00 a.out ARGS localhost 6262 -p4amslave - gdb a.out - ... - (gdb) break do_task_wrapper - Breakpoint 1 at 0x80492ab: file ... - [ `break slave_loop' is also useful. This calls do_task_wrapper ] - (gdb) attach 1492 - Attaching to program `a.out', process 1492 - 0x40075d88 in sigsuspend () - [ After 30 sec's, traced messages in master window appear, ] - [ for slave, type: ] - (gdb) continue - Continuing. - Breakpoint 1, DoTask (input=0x805dc50) at ... - - [ Continue stepping through master and slave processes in 2 windows ] - - If you try to "attach" to a second slave process after attaching to -a first slave process, `gdb' will offer to kill your first slave -process. To avoid this situation, remember to execute `detach' before -attaching a second slave process. - - -File: topc.info, Node: Segmentation faults, Prev: Stepping Through a Slave, Up: Debugging and Tracing - -6.6 Segmentation faults and other memory problems -================================================= - -Memory bugs are among the most difficult to debug. If you suspect such -a bug (perhaps because you are using `TOPC_MSG_PTR'), and you fail to -free previously malloc'ed memory, that is a memory leak. If you access -a buffer after freeing it, this may cause a segmentation error at a -later stage in the program. - - If you suspect such a bug (and maybe you should if nothing else -worked), it is helpful to use a _malloc or memory debugger_. An -excellent recent memory debugger is `valgrind'(1). `valgrind' can be -directly applied to an application binary, without recompilation or -relinking. - - An older debugger is `efence',(2) `topcc' provides direct support -for `efence'. `TOP-C' will link with the efence library if `--efence' -is passed to `topcc' or `topc++'. - topcc --efence ... - This causes all calls to `malloc' and `free' to be intercepted by -the `efence' version. Modify the line `LIBMALLOC=' in `topcc' or -`topc++' if you use a different library. - - ---------- Footnotes ---------- - - (1) VALGRIND is available at `http://www.valgrind.kde.org'. - - (2) EFENCE is available at -`http://sources.isc.org/devel/memleak/efence'. - - -File: topc.info, Node: Performance and Long Jobs, Next: Advanced Features, Prev: Debugging and Tracing, Up: Top - -7 Performance and Long Jobs -*************************** - -* Menu: - -* Dropping Slow or Dead Slaves:: -* Strategies for Greater Concurrency:: -* Improving Performance:: -* Long Jobs:: - - -File: topc.info, Node: Dropping Slow or Dead Slaves, Next: Strategies for Greater Concurrency, Prev: Performance and Long Jobs, Up: Performance and Long Jobs - -7.1 Dropping Slow or Dead Slaves -================================ - -When TOP-C recognizes a dead slave the master terminates communication -with that slave, and resubmits the task of that slave to a different -slave. (Currently, as of TOP-C 2.5.2, if a slave dies near the end of -a computation and after all tasks have been generated, TOP-C may fail -to recognize that slave.) - - It is sometimes unclear whether a slave process is dead or slower -than others. Even a slow slave process may hurt overall performance by -causing delays for other processes. TOP-C internally declares a slave -process to be "slow" if there are N slaves, and if 3*N other tasks -return after the given slave task is "due". If a slow slave has not -returned by SLAVE-TIMEOUT seconds (see *note Command Line Options::), -then the slave is considered dead. The master process sends no further -tasks to that slave, and sends a replicate of the original task to a new -slave. - - -File: topc.info, Node: Strategies for Greater Concurrency, Next: Improving Performance, Prev: Dropping Slow or Dead Slaves, Up: Performance and Long Jobs - -7.2 Strategies for Greater Concurrency -====================================== - -Strategy 1: SEMI-INDEPENDENT TASKS: - Define tasks so that most task outputs do not require any update. - This is always the case for trivial parallelism (when tasks are - independent of each other). It is also often the case for many - examples of search and enumeration problems. - -Strategy 2: CACHE PARTIAL RESULTS: - Inside `DoTask()' and `UpdateSharedData()', save partial - computations in global private variables. Then, in the event of a - `REDO' action, `TOP-C' guarantees to invoke `DoTask()' - again on the original slave process or slave thread. That - slave may then use previously computed partial results in - order to shorten the required computation. Note that pointers - on the slave to input and output buffers from previous - `UPDATE' actions and from the original task input will no - longer be valid. The slave process must copy any data it - wishes to cache to global variables. In the case of the - shared memory model, those global variables must be - thread-private. (*note Thread-Private Global Variables::) - Note the existence of `TOPC_is_REDO()' for testing for a `REDO' - action. - -Strategy 3: MERGE TASK OUTPUTS: - Inside `CheckTaskResult()', the master may merge two or more task - outputs in an application independent way. This may avoid the - need for a `REDO' action, or it may reduce the number of required - `UPDATE' actions. - - -File: topc.info, Node: Improving Performance, Next: Long Jobs, Prev: Strategies for Greater Concurrency, Up: Performance and Long Jobs - -7.3 Improving Performance -========================= - -If your application runs too slowly due to excessive time for -communication, consider running multiple slave processes on a single -processor. This allows one process to continue computing while another -is communicating or idle waiting for a new task to be generated by the -master. - - If communication overhead or idle time is still too high, consider -if it is possible to increase the granularity of your task. TOP-C can -aggregating several consecutive tasks as a single larger task to be -performed by a single process. This amortizes the network latency of a -single network message over several tasks. For example, you can do -combine 5 tasks by invoking `--TOPC-aggregated-tasks=5' on the command -line of the application. Alternatively, execute the statement: - TOPC_OPT_aggregated_tasks=5; - before `TOPC_master_slave()'. In this situation, the five task -outputs will also be bundled as a single network message. Currently -(TOP-C 2.5.2), this works only if all tasks return `NO_ACTION'. TOP-C -will signal an error if `TOPC_OPT_aggregated_tasks' > 1 and any action -other than `NO_ACTION' is returned. - - Other useful techniques that may improve performance of certain -applications are: - 1. set up multiple slaves on each processor (if slave processors - are sometimes idle) - - 2. re-write the code to bundle a set of tasks as a single task - (to improve the granularity of your parallelism) - -PERFORMANCE ISSUE FOR MPI: - If you have a more efficient version of `MPI' (perhaps a vendor - version tuned to your hardware), consider replacing `LIBMPI' in - `.../top-c/Makefile' by your vendor's `limbpi.a' or `libmpi.so', - and delete or modify the the `LIBMPI' target in the `Makefile'. - Alternatively, see the appendix, *note Using a Different MPI with - TOP-C::, for a more general way to use a different MPI dialect. - -PERFORMANCE ISSUE FOR SMP (POSIX threads): - Finally under `SMP', there is an important performance issue - concerning the interaction of `TOP-C' with the operating system. - First, the vendor-supplied compiler, `cc', is recommended over - `gcc' for `SMP', due to specialized vendor-specific architectural - issues. Second, if a thread completes its work before using its - full scheduling quantum, the operating system may yield the CPU of - that thread to another thread -- potentially including a thread - belonging to a different process. There are several ways to defend - against this. One defense is to insure that the time for a single - task is significantly longer than one quantum. Another defense is - to ask the operating system to give you at least as many "run - slots" as you have threads (slaves plus master). Some operating - systems use `pthread_setconcurrency()' to allow an application to - declare this information, and `TOP-C' invokes - `pthread_setconcurrency()' where it is available. However, other - operating systems may have alternative ways of tuning the - scheduling of threads, and it is worthwhile to read the relevant - manuals of your operating system. - - -File: topc.info, Node: Long Jobs, Prev: Improving Performance, Up: Performance and Long Jobs - -7.4 Long Jobs and Courtesy to Others -==================================== - -In the distributed memory model, infinite loops and broken socket -connections tend to leave orphaned processes running. In the `TOP-C' -distributed memory model, a slave times out if a task lasts longer than -a half hour or if the master does not reply in a half hour. This is -implemented with the UNIX system call, `alarm()'. - - A half hour (1800 seconds) is the default timeout period. The -command line option `--TOPC-slave-timeout=NUM' allows one to change -this default. If NUM is 0, then there is no timeout and `TOP-C' makes -no calls to `SIGALRM'. - - The application writer may also find some of the following UNIX -system calls useful for allowing large jobs to coexist with other -applications. -` setpriority(PRIO_PROCESS,getpid(),PRIO) ' - `#include - #include ' - -- PRIO = 10 still gives you some CPU time. PRIO = 19 - means that any job of higher priority always runs before - you. Place in `main()'. - -` setrlimit(RLIMIT_RSS, &RLP) ' - `#include - struct rlimit rlp; - rlp.rlim_max = rlp.rlim_cur = SIZE;' - -- SIZE is RAM limit (bytes). If your system has - significant paging, the system will prefer to keep your process - from growing beyond SIZE bytes of resident RAM. Even if you - set nice to priority 20, this is still important. - Otherwise you may cause someone to page out much of his or - her job in your favor during one of your infrequent - quantum slices of CPU time. Place in `main()'. (Not all - operating systems enforce this request.) - - -File: topc.info, Node: Advanced Features, Next: TOP-C Raw Interface, Prev: Performance and Long Jobs, Up: Top - -8 Advanced Features of `TOP-C' -****************************** - -It is best to postpone reading this section until the basic features -discussed in the previous chapters are clear. - -* Menu: - -* Testing for Task Continuations:: -* Aborting Tasks:: -* Allocation of Task Buffers:: -* Shared Memory Model:: -* Sequential Memory Model:: -* Caveats:: - - -File: topc.info, Node: Testing for Task Continuations, Next: Aborting Tasks, Prev: Advanced Features, Up: Advanced Features - -8.1 Testing for Task Continuations and Redos -============================================ - - -- Function: TOPC_BOOL TOPC_is_REDO ( void ) - -- Function: TOPC_BOOL TOPC_is_CONTINUATION ( void ) - These return 0 (false) or 1 (true), according to whether the - current call to `DoTask()' was a result of a `REDO' or - `CONTINUATION()' action, respectively. The result is is not - meaningful if called outside of `DoTask()'. - - -File: topc.info, Node: Aborting Tasks, Next: Allocation of Task Buffers, Prev: Testing for Task Continuations, Up: Advanced Features - -8.2 Aborting Tasks -================== - - -- Function: void TOPC_abort_tasks ( void ) - -- Function: TOPC_BOOL TOPC_is_abort_pending ( void ) - `TOPC_abort_tasks()' should be called in `CheckTaskResult()'. - `TOP-C' then makes a best effort (no guarantee) to notify each - slave. TOP-C does not directly abort tasks. However, - `TOPC_is_abort_pending()' returns 1 (true) when invoked in - `DoTask()' on a slave. A typical `DoTask()' callback uses - this to poll for an abort request from the master, upon which - it returns early with a special task output. At the beginning - of the next new task, `REDO' or `CONTINUATION', `TOP-C' resets - the pending abort to 0 (false). See `examples/README' of the - `TOP-C' distribution for example code. - - -File: topc.info, Node: Allocation of Task Buffers, Next: Shared Memory Model, Prev: Aborting Tasks, Up: Advanced Features - -8.3 Memory Allocation for Task Buffers -====================================== - -The principle of memory allocation in `TOP-C' is that if an application -allocates memory, then it is the responsibility of the application to -free that memory. This issue typically arises around the issue of task -buffers (*note Task Buffers::) and calls to `TOPC_MSG(BUF,BUF_SIZE)'. -An application often calls `BUF = malloc(...);' or `BUF = new ...;' (in -C++) and copies data into that buffer before the call to `TOPC_MSG'. -Since the last action of `GenerateTaskInput()' or `DoTask()' is -typically to return `TOPC_MSG(BUF,BUF_SIZE)', there remains the -question of how to free BUF. - -* Menu: - -* Avoiding malloc:: -* Large Buffers and TOPC_MSG_PTR:: -* Allocation for TOPC_MSG_PTR:: -* Marshaling Complex Data Structures:: - - -File: topc.info, Node: Avoiding malloc, Next: Large Buffers and TOPC_MSG_PTR, Prev: Allocation of Task Buffers, Up: Allocation of Task Buffers - -8.3.1 Avoiding `malloc' and `new' with Task Buffers ---------------------------------------------------- - -The best memory allocation solution for task buffers is to implement the -buffers as local variables, and therefore on the stack. This avoids the -need for `malloc' and `new', and the question of how to later free that -memory. If you use `TOPC_MSG' (as opposed to `TOPC_MSG_PTR', *note -Large Buffers and TOPC_MSG_PTR::), then recall that `TOPC_MSG' copies -its buffer to a separate `TOP-C' space. For example, - { int x; - ... - return TOPC_MSG(&x, size_of(x)); - } - - If your task buffer is of fixed size, one can allocate it as a -character array on the stack: `char buf[BUF_SIZE];'. If your buffer -contains variable size data, consider using `alloca' in place of -`malloc' to allocate on the stack. - { ... - buf = alloca(buf_size); - return TOPC_MSG(buf, buf_size); - } - - In all of the above cases, there is no need to free the buffer, since -`TOPC_MSG' will make a `TOP-C'-private copy and the stack-allocated -buffer will disappear when the current routine exits. Note that -`alloca' may be unavailable on your system. Alternatively, the use of -`alloca' may be undesirable due to very large buffers and O/S limits on -stack size. In such cases, consider the following alternative. - { TOPC_BUF tmp; - ... - buf = malloc(buf_size); - tmp = TOPC_MSG(buf, buf_size); - free(buf); - return tmp; - } - - -File: topc.info, Node: Large Buffers and TOPC_MSG_PTR, Next: Allocation for TOPC_MSG_PTR, Prev: Avoiding malloc, Up: Allocation of Task Buffers - -8.3.2 Using `TOPC_MSG_PTR()' to Avoid Copying Large Buffers ------------------------------------------------------------ - -If the cost of copying a large buffer is a concern, `TOP-C' provides an -alternative function, which avoids copying into `TOP-C' space. - - -- Function: TOPC_BUF TOPC_MSG_PTR ( void *BUF, int BUF_SIZE ) - Same as `TOPC_MSG()', except that it does not copy BUF - into `TOP-C' space. It is the responsibility of the - application not to free or modify BUF as long as `TOP-C' - might potentially pass it to an application callback function. - - `TOPC_MSG_PTR()' is inherently dangerous, if the application -modifies or frees a buffer and `TOP-C' later passes that buffer to a -callback function. It may be useful when the cost of copying large -buffers is an issue, or if one is concerned about `TOP-C' making a call -to `malloc()'. Note that the invocation - ./a.out --TOPC-safety=4 - automatically converts all calls to `TOPC_MSG_PTR()' into calls to -`TOPC_MSG()'. This is useful in deciding if a bug is related to the -use of `TOPC_MSG_PTR()'. - - An application should not pass a buffer on the stack to -`TOPC_MSG_PTR()'. This can be avoided either by declaring a local -variable to be `static', or else using a global variable (or a class -member in the case of C++). In such cases, it is the responsibility of -the application to dynamically create and free buffers. An example of -how this can be done follows in the next section. - - Note that if the application code must also be compatible with the -shared memory model, then the static local variable or global variable -must also be "thread-private" (*note Thread-Private Global Variables::). - - For examples of coding with `TOPC_MSG_PTR()' that are compatible -with all memory models, including the shared memory model, see -`examples/README' and the corresponding examples in the `TOP-C' -distribution. - - -File: topc.info, Node: Allocation for TOPC_MSG_PTR, Next: Marshaling Complex Data Structures, Prev: Large Buffers and TOPC_MSG_PTR, Up: Allocation of Task Buffers - -8.3.3 Allocation and Freeing of Task Buffers for `TOPC_MSG_PTR()' ------------------------------------------------------------------ - -Recall the syntax for creating a message buffer of type `TOPC_BUF' using -`TOPC_MSG_PTR(BUF, BUF_SIZE)'. The two callback functions -`GenerateTaskInput()' and `DoTask()' both return such a message buffer. -In the case of `GenerateTaskInput()', `TOP-C' saves a copy of the -buffer, which becomes an input argument to `CheckTaskResult()' and to -`UpdateSharedData' on the master. Hence, if BUF points to a -temporarily allocated buffer, it is the responsibility of the `TOP-C' -callback function to free the buffer only _after_ the callback function -has returned. This seeming contradiction can be easily handled by the -following code. - - TOPC_BUF GenerateTaskInput() { - static void *buf = NULL; - if ( buf == NULL ) { malloc(buf_size); } - ... [ Add new message data to buf ] ... - return TOPC_MSG_PTR(buf, buf_size); - } - - - If `buf_size' might vary dynamically between calls, the following -fragment solves the same problem. - TOPC_BUF GenerateTaskInput() { - static void *buf = NULL; - if ( buf != NULL ) { free(buf); } - ... [ Compute buf_size for new message ] ... - buf = malloc( buf_size ); - ... [ Add new message data to buf ] ... - return TOPC_MSG_PTR(buf, buf_size); - } - - Note that `buf' is allocated as a _static_ local variable. `TOP-C' -restricts the BUF of `TOPC_MSG_PTR(BUF, BUF_SIZE)' to point to a buffer -that is in the heap (not on the stack). Hence, BUF must _not_ point to -non-static local data. - - -File: topc.info, Node: Marshaling Complex Data Structures, Prev: Allocation for TOPC_MSG_PTR, Up: Allocation of Task Buffers - -8.3.4 Marshaling Complex Data Structures into `TOP-C' Task Buffers ------------------------------------------------------------------- - -If you use a distributed memory model and the buffer pointed to by -`input' includes fields with their own pointers, the application must -first follow all pointers and copy into a new buffer all data -referenced directly or indirectly by `input'. The new buffer can then -be passed to `TOPC_MSG()'. This copying process is called -"marshaling". *Note Marshaling and Heterogeneous Architectures: Task -Buffers. - - If following all pointers is a burden, then one can load the -application on the master and slaves at a common absolute address, and -insure that all pointer references have been initialized before the -first call to `TOPC_master_slave()'. In `gcc', one specifies an -absolute load address with code such as: - gcc -Wl,-Tdata -Wl,-THEX_ADDR ... - These flags are for the data segment. If the pointers indirectly -reference data on the stack, you may have to similarly specify stack -absolute addresses. Choosing a good HEX_ADDR for all machines may be a -matter of trial and error. In a test run, print out the absolute -addresses of some pointer variables near the beginning of your data -memory. - - Specifying an absolute load address has many risks, such as if the -master and slaves use different versions of the operating system, the -compiler, other software, or different hardware configurations. Hence, -this technique is recommended only as a last resort. - - -File: topc.info, Node: Shared Memory Model, Next: Sequential Memory Model, Prev: Allocation of Task Buffers, Up: Advanced Features - -8.4 Optimizing TOP-C Code for the Shared Memory Model -===================================================== - -The `TOP-C' programmer's model changes slightly for shared memory. -With careful design, one can use the same application source code both -for distributed memory and shared memory architectures. Processes are -replaced by threads. `UpdateSharedData()' is executed only by the -master thread, and not by any slave thread. As with distributed -memory, `TOPC_MSG()' buffers are copied to `TOP-C' space (shallow -copy). As usual, the application is responsible for freeing any -application buffers outside of `TOP-C' space. Furthermore, since the -master and slaves share memory, `TOP-C' creates the slaves only during -the first call to master_slave. If a slave needs to initialize any -private data (see `TOPC_thread_private', below), then this can be done -by the slave the first time that it gains control through `DoTask()'. - - Two issues arise in porting a distributed memory `TOP-C' application -to shared memory. - 1. reader-write synchronization: `DoTask()' must not read shared - data while `UpdateSharedData()' (on the master) simultaneously - writes to the shared data. - - 2. creating thread-private (unshared) global variables: - - Most `TOP-C' applications for the distributed memory model will run -unchanged in the shared memory model. In some cases, one must add -additional `TOP-C' code to handle these additional issues. In all -cases, one can easily retain compatibility with the distributed memory -model. - -* Menu: - -* Reader-Writer Synchronization:: -* Thread-Private Global Variables:: -* Volatile Variables:: -* SMP Performance:: - - -File: topc.info, Node: Reader-Writer Synchronization, Next: Thread-Private Global Variables, Prev: Shared Memory Model, Up: Shared Memory Model - -8.4.1 Reader-Writer Synchronization ------------------------------------ - -In shared memory, `TOP-C' uses a classical single-writer, -multiple-reader strategy with writer-preferred for lock requests. By -default, `DoTask()' acts as the critical section of the readers (the -slave threads) and `UpdateSharedData()' acts as the critical section of -the writer (the master thread). `TOP-C' sets a read lock around all of -DoTask() and a write lock around all of UpdateSharedData(). - - As always in the `TOP-C' model, it is an error if an application -writes to shared data outside of `UpdateSharedData()'. Note that -`GenerateTaskInput()' and `CheckTaskResult()' can safely read the -shared data without a lock in this case, since these routines and -`UpdateSharedData()' are all invoked only by the master thread. - - The default behavior implies that `DoTask()' and -`UpdateSharedData()' never run simultaneously. Optionally, one can -achieve greater concurrency through a finer level of granularity by -declaring to `TOP-C' which sections of code read or write shared data. -If `TOP-C' detects any call to `TOPC_ATOMIC_READ(0)', `TOP-C' will -follow the critical sections declared by the application inside of -`DoTask()' and `UpdateSharedData()'. - - -- Function: void TOPC_ATOMIC_READ ( 0 ) { ... C CODE ... } - -- Function: void TOPC_ATOMIC_WRITE ( 0 ) { ... C CODE ... } - This sets a global read or write lock in effect during the time - that C CODE is being executed. If a thread holds a write lock, - no thread may hold a read lock. If no thread holds a write lock, - arbitrarily many threads hold a read lock. If a thread requests - a write lock, no additional read locks will be granted until after - the write lock has been granted. See `examples/README' of the - `TOP-C' distribution for example code. - - It is not useful to use `TOPC_ATOMIC_READ()' outside of `DoTask()' -not to use `TOPC_ATOMIC_WRITE()' outside of `UpdateSharedData()'. - - The number 0 refers to page 0 of shared data. `TOP-C' currently -supports only a single common page of shared data, but future versions -will support multiple pages. In the future, two threads will be able to -simultaneously hold write locks if they are for different pages. - - The following alternatives to `TOPC_ATOMIC_READ()' and -`TOPC_ATOMIC_WRITE()' are provided for greater flexibility. - - -- Function: void TOPC_BEGIN_ATOMIC_READ ( 0 ) - -- Function: void TOPC_END_ATOMIC_READ ( 0 ) - -- Function: void TOPC_BEGIN_ATOMIC_WRITE ( 0 ) - -- Function: void TOPC_END_ATOMIC_WRITE ( 0 ) - The usage is the same as for `TOPC_ATOMIC_READ' and - `TOPC_ATOMIC_WRITE'. - - In the distributed memory model of `TOP-C', all of the above -invocations for atomic reading and writing are ignored, thus retaining -full compatibility between the shared and distributed memory models. - - -File: topc.info, Node: Thread-Private Global Variables, Next: Volatile Variables, Prev: Reader-Writer Synchronization, Up: Shared Memory Model - -8.4.2 Thread-Private Global Variables -------------------------------------- - -A "thread-private" variable is a variable whose data is not shared -among threads: i.e., each thread has a private copy of the variable. -The only variables that are thread-private by default in shared memory -are those on the stack (non-static, local variables). All other -variables exist as a single copy, shared by all threads. This is -inherent in the POSIX standard for threads in C/C++. If `DoTask()' -accesses any global variables or local static variables, then those -variables must be made thread-private. - - Ideally, if C allowed it, we would just write something like: - THREAD_PRIVATE int myvar = 0; /* NOT SUPPORTED */ - Instead, `TOP-C' achieves the same effect `as if' it had declared - TOPC_thread_private_t TOPC_thread_private; - This allows the application writer to include in his or her code: - typedef int TOPC_thread_private_t; - #define myvar TOPC_thread_private; - int myvar_debug() {return myvar;} /* needed to access myvar in gdb */ - - `TOP-C' provides primitives to declare a single thread-private -global variable. `TOP-C' allows the application programmer to declare -the type of that variable. - - -- Variable: TOPC_thread_private - A pre-defined thread-private variable of type, - `TOPC_thread_private_t'. It may be used like any C - variable, and each thread has its own private copy that - will _not_ be shared. - - -- Type: TOPC_thread_private_t - Initially, undefined. User must define this type using `typedef' - if `TOPC_thread_private' is used. - - If more than one thread-private variable is desired, define -`TOPC_thread_private_t' as a STRUCT, and use each field as a separate -thread-private variable. - -EXAMPLE: - - /* Ideally, if C allowed it, we would just write: - * THREAD_PRIVATE struct {int my_rank; int rnd;} mystruct; - * We emulate this using TOP-C's implicitly declared thread-private var: - * TOPC_thread_private_t TOPC_thread_private; - */ - typedef struct {int my_rank; int rnd;} TOPC_thread_private_t; - #define mystruct TOPC_thread_private - void set_info() { - mystruct.my_rank = TOPC_rank(); - mystruct.rnd = rand(); - } - void get_info() { - foo(); - if (mystruct.my_rank != TOPC_rank()) printf("ERROR\n"); - printf("Slave %d random num: %d\n", mystruct.my_rank, mystruct.rnd); - } - TOPC_BUF do_Task() { - set_info(); /* info in mystruct is NOT shared among threads */ - get_info(); - ...; - } - - Additional examples can be found by reading `examples/README' in the -`TOP-C' distribution. - - -File: topc.info, Node: Volatile Variables, Next: SMP Performance, Prev: Thread-Private Global Variables, Up: Shared Memory Model - -8.4.3 Sharing Variables between Master and Slave and Volatile Variables ------------------------------------------------------------------------ - -The shared memory model, like any `SMP' code, allows the master and -slaves to communicate through global variables, which are shared by -default. It is recommended not to use this feature, and instead to -maintain communication through `TOPC_MSG()', for ease of code -maintenance, and to maintain portability with the other `TOP-C' models -(distributed memory and sequential). If you do use your own global -shared variables between master and slaves, be sure to declare them -`volatile'. - volatile int myvar; - ANSI C requires this qualifier if a variable may be accessed or -modified by more than one thread. Without this qualifier, your program -may not run correctly. - - To be more precise, if a non-local variable is accessed more than -once in a procedure, the compiler is allowed to keep the first access -value in a thread register and reuse it at later occurrences, without -consulting the shared memory. A volatile declaration tells the -compiler to re-read the value from shared memory at each occurrence. -Similarly, a write to a volatile variable causes the corresponding -transfer of its value from a register to shared memory to occur at a -time not much later than the execution of the write instruction. - - If you suspect a missing volatile declaration, note that `gcc' -support the following command-line options. - gcc -fvolatile -fvolatile-global ... - # If topcc uses gcc: - topcc --pthread -fvolatile -fvolatile-global myfile.c -The option `-fvolatile' tells `gcc' to compile all memory references -through pointers as volatile, and the option `-fvolatile-global' tells -`gcc' to compile all memory references to extern and global data as -volatile. However, note that this implies a performance penalty since -the compiler will issue a load/store instruction for each volatile -access, and will _not_ keep volatile values in registers. - - -File: topc.info, Node: SMP Performance, Prev: Volatile Variables, Up: Shared Memory Model - -8.4.4 SMP Performance ---------------------- - -Note that `SMP' involves certain performance issues that do not arise -in other modes. If you find a lack of performance, please read *note -Improving Performance::. Also, note that the vendor-supplied compiler, -`cc', is often recommended over `gcc' for `SMP', due to specialized -vendor-specific architectural issues. - - -File: topc.info, Node: Sequential Memory Model, Next: Caveats, Prev: Shared Memory Model, Up: Advanced Features - -8.5 Modifying TOP-C Code for the Sequential Memory Model -======================================================== - -`TOP-C' also provides a sequential memory model. That model is useful -for first debugging an application in a sequential context, and then -re-compiling it with one of the parallel `TOP-C' libraries for -production use. The application code for the sequential library is -usually both source and object compatible with the application code for -a parallel library. The sequential library emulates an application with -a single `TOP-C' library. - - The sequential memory model emulates an application in which -`DoTask()' is executed in the context of the single slave -process/thread, and all other code is executed in the context of the -master process/thread. This affects the values returned by -`TOPC_is_master()' and `TOPC_rank()'. In particular, conditional code -for execution on the master will work correctly in the sequential -memory model, but the following conditional code for execution on the -slave will probably _not_ work correctly. - int main( int argc, char *argv[] ) { - TOPC_init( &argc, &argv ); - if ( TOPC_is_master() ) - ...; /* is executed in sequential model */ - else - ...; /* is _never_ executed in sequential model */ - TOPC_master_slave( ..., ..., ..., ...); - TOPC_finalize(); - } - - -File: topc.info, Node: Caveats, Prev: Sequential Memory Model, Up: Advanced Features - -8.6 Caveats -=========== - -IMPORTANT: `TOP-C' sets `alarm()' before waiting to receive message -from master. By default, if the master does not reply in a half hour -(1800 seconds), then the slave receives `SIGALRM' and dies. This -is to prevent runaway processes in dist. memory version when master dies - without killing all slaves. *note Long Jobs::, in order to change -this default. If your applications also uses `SIGALRM', then run your - application with `--TOPC-slave-timeout=0' and `TOP-C' will not use -`SIGALRM'. - - `GenerateTaskInput()' and `DoTask()' This memory is managed by -`TOP-C'. - - The slave process attempts to set current directory to the same as -the master inside `TOPC_init()' and produces a warning if -unsuccessful. - - When a task buffer is copied into `TOP-C' space, it becomes -word-aligned. If the buffer was originally not word-aligned, but some -field in the buffer was word-aligned, the internal field will no longer -be word-aligned. On some architectures, casting a non-word-aligned -field to `int' or certain other types will cause a bus error. - - -File: topc.info, Node: TOP-C Raw Interface, Next: Acknowledgements, Prev: Advanced Features, Up: Top - -9 `TOP-C' Raw Interface for Parallelizing Sequential Code -********************************************************* - -There are instances when tasks are most naturally generated deep inside -nested loops. Often, this occurs in parallelizing existing sequential -applications. In such circumstances, it may be difficult to re-write -the code to create a function `GenerateTaskInput()', since that would -require turning the loops inside out. (If you don't know what this -refers to, then you probably don't need the raw interface.) - - On a first reading, you may wish to first look at the example for -either a `for' loop or `while' loop, depending on the type of loop that -you are parallelizing. Then return to the formal descriptions of the -`TOP-C' raw functions. This chapter assumes familiarity with the basic -concepts of *note Overview:: and *note Writing TOP-C Applications::. - -* Menu: - -* TOPC-C raw functions:: -* Parallelizing For Loops:: -* Parallelizing While Loops:: - - -File: topc.info, Node: TOPC-C raw functions, Next: Parallelizing For Loops, Prev: TOP-C Raw Interface, Up: TOP-C Raw Interface - -9.1 `TOP-C' raw functions -========================= - - -- Function: void TOPC_raw_begin_master_slave - (DO_TASK, CHECK_TASK_RESULT, UPDATE_SHARED_DATA) - - -- Function: void TOPC_raw_end_master_slave () - This behaves like master_slave, with - `TOPC_raw_submit_task_input(INPUT)' serving the role of - `GenerateTaskInput()'. The slave blocks inside - `TOPC_raw_begin_master_slave()' and executes `do_task()' and - `update_shared_data()' until the master executes - `TOPC_raw_end_master_slave()'. At that time, the slave - unblocks. The slave does nothing inside - `TOPC_raw_end_master_slave()'. - - -- Function: void TOPC_raw_submit_task_input ( TOPC_BUF INPUT ) - Invoked by master between `TOPC_raw_begin_master_slave()' - and `TOPC_raw_end_master_slave()'; Typical usage is: - `TOPC_raw_submit_task_input(TOPC_MSG(&INPUT_DATA, - sizeof(INPUT_DATA)) );' - The argument, INPUT, corresponds to what would be returned - by `GenerateTaskInput()' in the routine - `TOPC_master_slave()'. INPUT will be processed by - `DoTask()' and its siblings, just as in - `TOPC_master_slave()'). There can be multiple occurrences - of `TOPC_raw_submit_task_input()'. - - -- Function: TOPC_BOOL TOPC_raw_wait_for_task_result () - Invoked by master between `TOPC_raw_begin_master_slave()' and - `TOPC_raw_end_master_slave()'; If no tasks are - outstanding, returns false immediately. Otherwise, it - blocks until a task does return. It calls application - callback, `CheckTaskResult()', and then returns true. - - -File: topc.info, Node: Parallelizing For Loops, Next: Parallelizing While Loops, Prev: TOPC-C raw functions, Up: TOP-C Raw Interface - -9.2 Parallelizing `for' Loops -============================= - -Assume that we are parallelizing a code fragment of the following form. -The variables `i' and `j' will be the input to `DoTask()', and any data -structures indexed by `i' and `j' (for example `array' in -`array[i][j]') will be part of the shared data. - float array[ROWS][COLS]; - ... - for ( i = 0; i < 10; i++ ) { - for ( j = 0; j < 10; j++ ) { - /* do_task: */ ... - /* update: */ array[i][j] = ...; - } - } - - Assume that the labels `do_task' and `update' above correspond to -the callback functions `DoTask()' and `UpdateSharedData()'. Then the -code is parallelized below. - - float array[ROWS][COLS]; - typedef struct {int i_val; int j_val;} input_t; - void *DoTask(input_t *buf) { - int i = (*buf).i_val, j = (*buf).j_val; - /* do_task: */ ... - } - void *CheckTaskResult(input_t *buf, output_t *buf2) { - /* update: */ array[i][j] = ...; - return NO_ACTION; - } - main(int argc, char **argv) { - TOPC_init( &argc, &argv ); - TOPC_raw_begin_master_slave(DoTask, CheckTaskResult, - UpdateSharedData); - if (TOPC_is_master()) { - for ( i = 0; i < 10; i++ ) { - for ( j = 0; j < 10; j++ ) { - input_t input; - input.i_val = i; input.j_val = j; - TOPC_raw_submit_task_input( TOPC_MSG(&input, sizeof(input)) ); - } - } - } TOPC_raw_end_master_slave(); - TOPC_finalize(); - } - - -File: topc.info, Node: Parallelizing While Loops, Prev: Parallelizing For Loops, Up: TOP-C Raw Interface - -9.3 Parallelizing `while' Loops -=============================== - -Assume that we are parallelizing a code fragment of the following form -and `input' is a pointer. - while ( (input = next_input()) != NULL ) { - /* do_task: */ ... - /* update: */ ... - } - - Assume that the labels `do_task' and `update' above correspond to -the callback functions `DoTask()' and `UpdateSharedData()'. Then the -code is parallelized below, where `input_size' must be specified by the -application before it is used. - - TOPC_init( &argc, &argv ); - TOPC_raw_begin_master_slave(DoTask, CheckTaskResult, - UpdateSharedData); - if (TOPC_is_master()) { - while ( (input = next_input()) != NULL - || TOPC_raw_wait_for_task_result() ) { - TOPC_raw_submit_task_input( TOPC_MSG(input, input_size) ); - } - } TOPC_raw_end_master_slave(); - TOPC_finalize(); - - Note that the code inside the "raw begin/end block" is executed only -by the master in the code above. - - If the buffer, `input', contains pointers to other data, then you -will need to "marshal" the data before calling `TOPC_MSG()'. *Note -Marshaling and Heterogeneous Architectures: Task Buffers. - - -File: topc.info, Node: Acknowledgements, Next: Summary, Prev: TOP-C Raw Interface, Up: Top - -10 Acknowledgements -******************* - -A project of this scope cannot be achieved alone. While Gene Cooperman -was the primary author, the project has benefited from contributions by -several various individuals and institutions at different times. - - The author wishes to thank the National Science Foundation for -support under which much of this work was developed. The author wishes -to thank the Mariner Project at Boston University for the use of the -Origin 2000 and other facilities which helped in the development of -this software. An earlier, experimental version of mpinu (MPI subset) -was written by Markos Kyzas and partially revised by Gene Cooperman. -Michael Weller provided ideas for improving some of the C code, and -provided valuable feedback when he adapted the `TOP-C' ideas to a large -application on an IBM SP-2. The loader module is joint with Victor -Grinberg. Further experience and feedback was gained from the GAP -community when the `TOP-C' model was ported to ParGAP, a refereed share -package. (GAP - Groups, Algorithms and Programming) is a language -similar to Maple, specialized for symbolic computations in -computational algebra and especially computational group theory.) -`TOP-C', version 2, was exported by Victor Grinberg from ParGAP, with -enhancements by Gene Cooperman. Some important feedback was gained in -the TOP-C parallelization of Geant4. (Geant4 is a toolkit for the -Monte Carlo simulation of particle-matter interaction. The package has -close to a million lines of C++ code. The TOP-C parallelization is -included with the Geant4 distribution.) Xiaoqin Ma analyzed mechanisms -for detecting and recovering from dead slaves, broken sockets, etc., -and wrote the first version of code to handle that. - - -File: topc.info, Node: Summary, Next: Example, Prev: Acknowledgements, Up: Top - -Appendix A Summary of `TOP-C' Commands -************************************** - -_From *note The Main TOP-C Library Calls::._ -`void TOPC_init ( int *ARGC, char ***ARGV )' -`void TOPC_finalize ( void )' - Function - -`void TOPC_master_slave' - ( TOPC_BUF (*GENERATE_TASK_INPUT)(), - TOPC_BUF (*DO_TASK)(void *input), - TOPC_ACTION (*CHECK_TASK_RESULT)(void *input, void *output), - void (*UPDATE_SHARED_DATA)(void *input, void *output) - ) - Function - -`TOPC_BUF TOPC_MSG ( void *BUF, int BUF_SIZE )' - Function - - -_From *note Callback Functions for `TOPC_master_slave()': Callback -Functions._ -`TOPC_BUF GenerateTaskInput ( void )' - Function - -`TOPC_BUF DoTask ( void *INPUT )' - Function - -`TOPC_ACTION CheckTaskResult ( void *INPUT, void *OUTPUT)' - Function - -`void UpdateSharedData ( void *INPUT, void *OUTPUT )' - Function - - -_From *note Actions Returned by `CheckTaskResult()': Actions._ -`Action TOPC_ACTION NO_ACTION' - Action - -`Action TOPC_ACTION UPDATE' - Action - -`Action TOPC_ACTION REDO' - Action - -`Action TOPC_ACTION CONTINUATION ( void *NEXT_INPUT )' - Action - - -_From *note TOP-C Utilities::._ -`TOPC_BOOL TOPC_is_up_to_date ( void )' - Function - -`int TOPC_rank ( void )' - Function - -`TOPC_BOOL TOPC_is_master ( void )' - Function - -`int TOPC_num_slaves ( void )' - Function - -`int TOPC_num_idle_slaves ( void )' - Function - -`int TOPC_node_count ( void )' - Function - - -_From *note Optimizing TOP-C Code for the Shared Memory Model: Shared -Memory Model._ -`TOPC_thread_private' - Variable - -`TOPC_thread_private_t' - Type - -`void TOPC_ATOMIC_READ ( 0 ) { ... C CODE ... }' -`void TOPC_ATOMIC_WRITE ( 0 ) { ... C CODE ... }' - Function - -`void TOPC_BEGIN_ATOMIC_READ ( 0 )' -`void TOPC_END_ATOMIC_READ ( 0 )' -`void TOPC_BEGIN_ATOMIC_WRITE ( 0 )' -`void TOPC_END_ATOMIC_WRITE ( 0 )' - Function - - -_From *note Raw `TOP-C' interface: `raw_master_slave': TOP-C Raw -Interface._ -`void TOPC_raw_begin_master_slave' - (DO_TASK, CHECK_TASK_RESULT, UPDATE_SHARED_DATA) - -`void TOPC_raw_end_master_slave ()' - Function - -`void TOPC_raw_submit_task_input ( TOPC_BUF INPUT )' - Function - -`TOPC_BOOL TOPC_raw_wait_for_task_result ()' - Function - - -_From *note Aborting Tasks::._ -`void TOPC_abort_tasks ( void )' -`TOPC_BOOL TOPC_is_abort_pending ( void )' - Function - - -_From *note Testing for Task Continuations::._ -`TOPC_BOOL TOPC_is_REDO ( void )' -`TOPC_BOOL TOPC_is_CONTINUATION ( void )' - Function - - -_From *note Large Buffers and TOPC_MSG_PTR::._ -`TOPC_BUF TOPC_MSG_PTR ( void *BUF, int BUF_SIZE )' - Function - - -_From *note Command Line Options in TOP-C Applications: Command Line -Options._ -`--TOPC-help`[=<0/1>]'' - [boolean, default: false] - -`--TOPC-verbose`[=<0/1>]'' - [boolean, default: false] - -`--TOPC-stats`[=<0/1>]'' - [boolean, default: false] - -`--TOPC-num-slaves`='' - [default: -1 (system-defined)] - -`--TOPC-slave-wait`='' - [default: 0] - -`--TOPC-slave-timeout`='' - [default: 1800 s] - -`--TOPC-trace`='' - [trace (0: notrace, 1: trace, 2: user trace fncs, default: 2)] - -`--TOPC-procgroup`='' - [default: "./procgroup"] - -`--TOPC-safety`='' - [default: 0] - - -_From *note Tracing Messages::._ -`int TOPC_OPT_trace' -`void (*)(void *input) TOPC_OPT_trace_input' -`void (*)(void *input, void *output) TOPC_OPT_trace_result' - - -File: topc.info, Node: Example, Next: Using a Different MPI with TOP-C, Prev: Summary, Up: Top - -Appendix B Example `TOP-C' Application -************************************** - -There are several example `TOP-C' programs in the `topc/examples' -subdirectory. We include one example in this manual. It does not -contain any `UPDATE' actions, and therefore illustrates only a trivial -form of parallelism (with no interaction among the slaves). The -`topc/examples' subdirectory should be inspected for more sophisticated -examples. After understanding this example, you may also want to look -at *note Advanced Features::, or if you are parallelizing a sequential -program, then you may want to look at *note TOP-C Raw Interface::. - - This program produces an array of 10,000,000 random integers in one -pass, and then finds the maximum value in a second pass. It would be -compiled by: `topcc MODE `file.out'', where MODE is one of `--seq', -`--mpi', or `--pthread'. One can control the number of slaves by -executing: `./a.out --TOPC-num-slaves=NUM'. - - #include - #include - #include - #include - - #define MAX 2000000 - #define INCR MAX/10 /* We assume INCR divides MAX exactly */ - - int array[MAX]; - int idx; - int max_int; - - TOPC_BUF GenerateTaskInput() { - int input_task; - if (idx >= MAX) return NOTASK; - input_task = idx; - idx = idx + INCR; - return TOPC_MSG( &input_task, sizeof(input_task) ); - } - TOPC_BUF DoTaskRandom( int *ignore ) { - int rand_int[INCR]; - int i; - for ( i = 0; i < INCR; i++) - rand_int[i] = rand(); - return TOPC_MSG( rand_int, INCR * sizeof(int) ); - } - TOPC_ACTION CheckTaskRandom( int *input, int rand_vals[] ) { - int curr_idx = *input; - memcpy( array+curr_idx, rand_vals, INCR * sizeof(int) ); - return NO_ACTION; - } - - TOPC_BUF GenerateTaskInMax() { - int *input_task; - if (idx >= MAX) return NOTASK; - input_task = array + idx; - idx = idx + INCR; - return TOPC_MSG( input_task, INCR * sizeof(int) ); - } - TOPC_BUF DoTaskMax( int subarray[] ) { - int i; - int max=0; - for ( i = 0; i < INCR; i++) - if ( subarray[i] > max ) - max = subarray[i]; - return TOPC_MSG( &max, sizeof(max) ); - } - TOPC_ACTION CheckTaskMax( int ignore[], int *output ) { - int curr_max = *output; - if ( curr_max > max_int ) - max_int = curr_max; - return NO_ACTION; - } - - int main( int argc, char **argv ) { - /* Set default to no trace; Override with: ./a.out --TOPC-trace=1 */ - TOPC_OPT_trace = 0; - TOPC_init( &argc, &argv ); - idx = 0; /* Initialize idx, and randomize values of array[] */ - TOPC_master_slave(GenerateTaskInput, DoTaskRandom, CheckTaskRandom, - NULL); - if (TOPC_is_master()) - printf("Finished randomizing integers.\n"); - idx = 0; /* Re-initialize idx to 0, and find max. value in array[] */ - TOPC_master_slave( GenerateTaskInMax, DoTaskMax, CheckTaskMax, NULL ); - TOPC_finalize(); - printf("The maximum integer is: %d\n", max_int); - exit(0); - } - - -File: topc.info, Node: Using a Different MPI with TOP-C, Next: Function Index, Prev: Example, Up: Top - -Appendix C Using a Different `MPI' with TOP-C -********************************************* - -`TOP-C' provides a built-in subset of MPI sufficient to run distributed -applications. If you prefer to use a different implementation of `MPI' -with `TOP-C', this note describes how to do so. Examples for `MPICH', -`LAM' and `IBM POE' are at the end of this section. You should -re-configure and re-build `TOP-C' using the same C/C++ compiler as that -of your chosen MPI. - - First test a `hello_world' MPI program for your chosen MPI -implementation to make sure that the startup mechanism is well -understood. - - Many dialects of `MPI' provide their own wrapper around the C and -C++ compiler. For example, `LAM MPI' provides `mpicc'. If your -dialect provides such a wrapper `mpicc', then do `./configure ---with-mpi-cc=mpicc' and `make'. There is a similar configure flag, -`--with-mpi-cxx', for `C++'. - - If you do use such a wrapper, you should use the same C compiler for -the rest of `TOP-C'. Hence, if `mpicc' uses `cc', then configure with -`env CC=cc ./configure --with-mpi-cc=mpicc --cache-file=/dev/null'. In -general, you can always specify a non-default C and C++ compiler by -specifying `CC=...' and `CXX=...', respectively. - - If your dialect does not provide such a wrapper, it is easy to create -one by modifying the shell script below for your site. - #!/bin/sh - gcc -I/usr/local/include $* -L/usr/local/lib -lmpi - - These wrappers will enable `topcc' and `topc++' to work, but not -`topc-config'. If you also need `topc-config', then you must modify -`topc-config'. Determine the libraries used by your dialect of MPI. -Then search for a string with `-ltopc-mpi' in -`.../topc/bin/topc-config', and append to it your `libmpi'. For -example, append to `-ltopc-mpi' with `-L/usr/local/lib -lmpi'. - - Finally, for many dialects of MPI, after compiling the MPI -application, they may also require a special command at runtime to -execute, such as `mpirun a.out'. In such cases, your `TOP-C' -application must be treated similarly. - - The following examples illustrate the configuration and use of MPI -for other MPI implementations using 2 slaves and 1 master. - # IBM POE/AIX: - env CC=xlc CXX=xlC ./configure --with-mpi-cc=mpcc --with-mpi-cxx=mpCC - make; cd bin; ./topcc --mpi -qcpluscmt ../examples/parfactor.c - poe ./a.out 1234 --TOPC-stats -procs 3 -pgmmodel spmd - - # MPICH/Linux: - ./configure --with-mpi-cc=mpicc - make; cd bin; ./topcc --mpi ../examples/parfactor.c - mpirun -np 3 ./a.out --TOPC-stats 1234 - - # LAM/Linux: - ./configure --with-mpi-cc=mpicc - make; cd bin; ./topcc --mpi ../examples/parfactor.c - mpirun -c 3 ./a.out -- --TOPC-stats 1234 - - -File: topc.info, Node: Function Index, Next: Variable Index, Prev: Using a Different MPI with TOP-C, Up: Top - -Function Index -************** - -[index] -* Menu: - -* CheckTaskResult: Callback Functions. (line 26) -* DoTask: Callback Functions. (line 20) -* GenerateTaskInput: Callback Functions. (line 14) -* TOPC_abort_tasks <1>: Aborting Tasks. (line 7) -* TOPC_abort_tasks: TOP-C Utilities. (line 43) -* TOPC_ATOMIC_READ: Reader-Writer Synchronization. - (line 28) -* TOPC_ATOMIC_WRITE: Reader-Writer Synchronization. - (line 29) -* TOPC_BEGIN_ATOMIC_READ: Reader-Writer Synchronization. - (line 49) -* TOPC_BEGIN_ATOMIC_WRITE: Reader-Writer Synchronization. - (line 51) -* TOPC_END_ATOMIC_READ: Reader-Writer Synchronization. - (line 50) -* TOPC_END_ATOMIC_WRITE: Reader-Writer Synchronization. - (line 52) -* TOPC_finalize: The Main TOP-C Library Calls. - (line 21) -* TOPC_init: The Main TOP-C Library Calls. - (line 14) -* TOPC_is_abort_pending <1>: Aborting Tasks. (line 8) -* TOPC_is_abort_pending: TOP-C Utilities. (line 44) -* TOPC_is_CONTINUATION <1>: Testing for Task Continuations. - (line 8) -* TOPC_is_CONTINUATION: TOP-C Utilities. (line 42) -* TOPC_is_master: TOP-C Utilities. (line 26) -* TOPC_is_REDO <1>: Testing for Task Continuations. - (line 7) -* TOPC_is_REDO: TOP-C Utilities. (line 41) -* TOPC_is_up_to_date: TOP-C Utilities. (line 9) -* TOPC_master_slave: The Main TOP-C Library Calls. - (line 24) -* TOPC_MSG: The Main TOP-C Library Calls. - (line 39) -* TOPC_MSG_PTR: Large Buffers and TOPC_MSG_PTR. - (line 10) -* TOPC_node_count: TOP-C Utilities. (line 37) -* TOPC_num_idle_slaves: TOP-C Utilities. (line 33) -* TOPC_num_slaves: TOP-C Utilities. (line 30) -* TOPC_rank: TOP-C Utilities. (line 22) -* TOPC_raw_begin_master_slave: TOPC-C raw functions. (line 7) -* TOPC_raw_end_master_slave: TOPC-C raw functions. (line 10) -* TOPC_raw_submit_task_input: TOPC-C raw functions. (line 20) -* TOPC_raw_wait_for_task_result: TOPC-C raw functions. (line 32) -* UpdateSharedData: Callback Functions. (line 37) - - -File: topc.info, Node: Variable Index, Next: Concept Index, Prev: Function Index, Up: Top - -Variable Index -************** - -[index] -* Menu: - -* /tmp/mpinu-ssh: Slaves Fail to Start. (line 6) -* CONTINUATION: Actions. (line 29) -* NO_ACTION: Actions. (line 13) -* REDO: Actions. (line 21) -* SSH: Procgroup Files. (line 81) -* TOPC_OPT_trace_input: Tracing Messages. (line 20) -* TOPC_OPT_trace_result: Tracing Messages. (line 21) -* TOPC_OPTS: Command Line Options. (line 6) -* TOPC_thread_private: Thread-Private Global Variables. - (line 29) -* TOPC_thread_private_t: Thread-Private Global Variables. - (line 35) -* UPDATE: Actions. (line 16) - - -File: topc.info, Node: Concept Index, Prev: Variable Index, Up: Top - -Concept Index -************* - -[index] -* Menu: - -* -mpi argument to topcc/topc++: Invoking a TOP-C Application in Distributed Memory. - (line 6) -* -pthread argument to topcc/topc++: Invoking a TOP-C Application in Shared Memory. - (line 6) -* -seq argument to topcc/topc++: Invoking a TOP-C Application in Sequential Memory. - (line 6) -* -TOPC-aggregated-tasks: Command Line Options. (line 6) -* -TOPC-aggregated-tasks, usage: Improving Performance. - (line 6) -* -TOPC-help: Command Line Options. (line 6) -* -TOPC-num-slaves: Command Line Options. (line 6) -* -TOPC-num-slaves, example: Debugging by Limiting Parallelism. - (line 6) -* -TOPC-num-slaves, selection of slave hosts using procgroup file: Procgroup Files. - (line 6) -* -TOPC-procgroup: Command Line Options. (line 6) -* -TOPC-procgroup, usage of procgroup file: Procgroup Files. (line 6) -* -TOPC-safety: Command Line Options. (line 6) -* -TOPC-safety for debugging: Debugging with --TOPC-safety. - (line 6) -* -TOPC-slave-timeout: Command Line Options. (line 6) -* -TOPC-slave-timeout, for long jobs and runaway jobs: Long Jobs. - (line 6) -* -TOPC-slave-wait: Command Line Options. (line 6) -* -TOPC-slave-wait, debugging a slave process with gdb: Stepping Through a Slave. - (line 6) -* -TOPC-stats: Command Line Options. (line 6) -* -TOPC-trace: Command Line Options. (line 6) -* -TOPC-verbose: Command Line Options. (line 6) -* .topcrc: Command Line Options. (line 6) -* aborting tasks: Aborting Tasks. (line 6) -* action: Three Key Concepts for TOP-C. - (line 6) -* actions returned by CheckTaskResult(): Actions. (line 6) -* aggregation of tasks: Improving Performance. - (line 6) -* command line options, TOP-C: Command Line Options. (line 6) -* compiling the distributed memory model: Invoking a TOP-C Application in Distributed Memory. - (line 6) -* compiling the sequential memory model: Invoking a TOP-C Application in Sequential Memory. - (line 6) -* compiling the shared memory model: Invoking a TOP-C Application in Shared Memory. - (line 6) -* CONTINUATION, testing for: Testing for Task Continuations. - (line 6) -* debugging: Debugging and Tracing. - (line 6) -* debugging memory management with efence: Segmentation faults. - (line 6) -* debugging TOP-C --mpi applications that fail to start: Slaves Fail to Start. - (line 6) -* debugging, -TOPC-safety: Debugging with --TOPC-safety. - (line 6) -* distributed memory model: Memory Models. (line 6) -* distributed memory, fails to start: Slaves Fail to Start. (line 6) -* efence, debugging memory management: Segmentation faults. (line 6) -* example TOP-C application: Example. (line 6) -* fine grain thread parallelism: Reader-Writer Synchronization. - (line 6) -* finer grain parallelism: Improving Performance. - (line 6) -* global shared data: Three Key Concepts for TOP-C. - (line 6) -* global thread-private variable: Thread-Private Global Variables. - (line 6) -* heterogeneous architectures: Marshaling. (line 6) -* initializing TOP-C: The Main TOP-C Library Calls. - (line 6) -* large message buffers: Large Buffers and TOPC_MSG_PTR. - (line 6) -* Marshalgen, a package for marshaling: Marshalgen. (line 16) -* marshaling: Marshaling. (line 6) -* master-slave mode, invoking: The Main TOP-C Library Calls. - (line 6) -* memory model, distributed: Memory Models. (line 6) -* memory model, distributed, compiling: Invoking a TOP-C Application in Distributed Memory. - (line 6) -* memory model, sequential: Sequential Memory Model. - (line 6) -* memory model, sequential, compiling: Invoking a TOP-C Application in Sequential Memory. - (line 6) -* memory model, shared: Shared Memory Model. (line 6) -* memory model, shared, compiling: Invoking a TOP-C Application in Shared Memory. - (line 6) -* message format, TOPC_MSG(): The Main TOP-C Library Calls. - (line 6) -* MPINU: Procgroup Files. (line 6) -* mpinu-ssh for debugging slave startup: Slaves Fail to Start. (line 6) -* network latency, overcoming it: Improving Performance. - (line 6) -* options, TOP-C: Command Line Options. (line 6) -* procgroup file: Procgroup Files. (line 6) -* reader-writer synchronization: Reader-Writer Synchronization. - (line 6) -* REDO, testing for: Testing for Task Continuations. - (line 6) -* segmentation fault, debugging with efence: Segmentation faults. - (line 6) -* sequential memory model: Sequential Memory Model. - (line 6) -* serialization: Marshaling. (line 6) -* shared data: Three Key Concepts for TOP-C. - (line 6) -* shared memory model: Shared Memory Model. (line 6) -* SIGALRM: TOP-C and POSIX signals. - (line 6) -* SIGALRM, raised by TOP-C: Long Jobs. (line 6) -* signals and TOP-C: TOP-C and POSIX signals. - (line 6) -* SIGPINT: TOP-C and POSIX signals. - (line 6) -* SIGPIPE: TOP-C and POSIX signals. - (line 6) -* SIGPIPE signal handler not recognized: Debugging and Tracing. - (line 6) -* SIGSEGV, debugging with efence: Segmentation faults. (line 6) -* slave startup in distributed memory, difficulties: Slaves Fail to Start. - (line 6) -* SMP: Memory Models. (line 6) -* SSH environment variable for starting remote slaves: Procgroup Files. - (line 6) -* static local variables and threads: Thread-Private Global Variables. - (line 6) -* synchronization of threads, shared memory model: Reader-Writer Synchronization. - (line 6) -* task: Three Key Concepts for TOP-C. - (line 6) -* task continuation, testing: Testing for Task Continuations. - (line 6) -* task input <1>: The Main TOP-C Library Calls. - (line 6) -* task input: Task Buffers. (line 6) -* task input/output buffers, variable size: Avoiding malloc. (line 17) -* task output <1>: The Main TOP-C Library Calls. - (line 6) -* task output: Task Buffers. (line 6) -* thread-private variable: Thread-Private Global Variables. - (line 6) -* THREAD_PRIVATE: Thread-Private Global Variables. - (line 6) -* threads, synchronization in shared memory model: Reader-Writer Synchronization. - (line 6) -* TOP-C action: Three Key Concepts for TOP-C. - (line 6) -* TOP-C command line options: Command Line Options. (line 6) -* TOP-C options: Command Line Options. (line 6) -* topc++: Compiling TOP-C Applications. - (line 6) -* topc-config: Compiling TOP-C Applications. - (line 6) -* TOPC_MSG_PTR(): Large Buffers and TOPC_MSG_PTR. - (line 6) -* TOPC_OPT_trace, usage for dynamically debugging messages: Tracing Messages. - (line 6) -* TOPC_OPT_trace_input: Tracing Messages. (line 6) -* TOPC_OPT_trace_result: Tracing Messages. (line 6) -* TOPC_OPTS environment variable for initialization: Command Line Options. - (line 6) -* topcc: Compiling TOP-C Applications. - (line 6) -* topcrc: Command Line Options. (line 6) -* variable size task buffers: Avoiding malloc. (line 17) -* volatile C/C++ variables: Volatile Variables. (line 6) - - - -Tag Table: -Node: Top1208 -Node: Copying3519 -Node: Quick Start5605 -Node: Overview9753 -Node: Programmer Model11486 -Node: Structure of a TOP-C Program11758 -Node: Four Callback Functions13066 -Node: Task Buffers14072 -Node: Defining Task Buffers14702 -Node: Marshaling15863 -Node: Marshalgen16991 -Node: The TOP-C Algorithm17751 -Node: Three Key Concepts for TOP-C20676 -Node: Memory Models22111 -Node: Writing TOP-C Applications23555 -Node: The Main TOP-C Library Calls23985 -Node: Callback Functions26278 -Node: Actions29232 -Node: TOP-C Utilities32158 -Node: Compiling and Invoking TOP-C Applications33942 -Node: Compiling TOP-C Applications34695 -Node: Command Line Options36662 -Node: Invoking a TOP-C Application in Sequential Memory41429 -Node: Invoking a TOP-C Application in Distributed Memory42028 -Ref: Invoking a TOP-C Application in Distributed Memory-Footnote-143031 -Node: Procgroup Files43107 -Node: Slaves Fail to Start47694 -Node: Invoking a TOP-C Application in Shared Memory49560 -Node: Debugging and Tracing50990 -Node: Debugging by Limiting Parallelism51921 -Node: Debugging with --TOPC-safety52912 -Node: TOP-C and POSIX signals55362 -Node: Tracing Messages56573 -Node: Stepping Through a Slave58248 -Node: Segmentation faults60745 -Ref: Segmentation faults-Footnote-161960 -Ref: Segmentation faults-Footnote-262024 -Node: Performance and Long Jobs62102 -Node: Dropping Slow or Dead Slaves62400 -Node: Strategies for Greater Concurrency63511 -Node: Improving Performance65242 -Node: Long Jobs68557 -Node: Advanced Features70349 -Node: Testing for Task Continuations70804 -Node: Aborting Tasks71380 -Node: Allocation of Task Buffers72325 -Node: Avoiding malloc73252 -Node: Large Buffers and TOPC_MSG_PTR74875 -Node: Allocation for TOPC_MSG_PTR76925 -Node: Marshaling Complex Data Structures78764 -Node: Shared Memory Model80408 -Node: Reader-Writer Synchronization82211 -Node: Thread-Private Global Variables85201 -Node: Volatile Variables88033 -Node: SMP Performance90181 -Node: Sequential Memory Model90641 -Node: Caveats92130 -Node: TOP-C Raw Interface93316 -Node: TOPC-C raw functions94399 -Node: Parallelizing For Loops96221 -Node: Parallelizing While Loops97981 -Node: Acknowledgements99342 -Node: Summary101187 -Node: Example106589 -Node: Using a Different MPI with TOP-C109839 -Node: Function Index112679 -Node: Variable Index116192 -Node: Concept Index117293 - -End Tag Table diff --git a/topc-2.5.2/doc/topc.texi b/topc-2.5.2/doc/topc.texi deleted file mode 100644 index 6a442d79..00000000 --- a/topc-2.5.2/doc/topc.texi +++ /dev/null @@ -1,3329 +0,0 @@ -\input texinfo.tex @c -*-texinfo-*- -@c %**start of header -@setfilename topc.info -@settitle TOP-C (Task Oriented Parallel C/C++) -@comment @setchapternewpage odd for larger documents and double-sided -@setchapternewpage off -@footnotestyle end -@include topc-version.texi -@comment omit overfull boxes -@finalout -@comment Make a chapter into a section, etc. -@comment @lowersections -@c %**end of header - -@iftex -@hbadness=40000 -@pretolerance=100000 -@tolerance=100000 -@end iftex - -@comment Decide if actual code, "heart of the TOP-C algorithm" -@comment makes a better description than current version -@comment [ or combine two by adding comments to C code ] -@ignore -@{ TOPC_BUF input, output; - int number_of_idle_slaves = number_of_slaves; - TOPC_ACTION action; - do @{ - if ( (input = GenerateTaskInput()) != NOTASK ) @{ - SUBMIT_TO_SLAVE: output = DoTask(input.data); - number_of_idle_slaves--; - @} - if ( result_is_available(input, output) ) @{ - number_of_idle_slaves++; - action = CheckTaskResult(input.data, output.data); - if (action == UPDATE_ACTION) - UpdateSharedData(input.data, output.data); - @} - @} while ( input != NOTASK || number_of_idle_slaves < number_of_slaves ); -@} -This simplified excerpt from the @samp{TOP-C} source code describes -the @samp{TOP-C} algorithm.. - TOPC_BUF input, output; - int num_idle_slaves = num_slaves; - TOPC_ACTION action; - - while (1) @{ - wait_until_an_idle_slave(); - while ( result_is_available(&input, &output) ) @{ - action = CheckTaskResult(input.data, output.data); - if (action == UPDATE_ACTION) - UpdateSharedData(input.data, output.data); - num_idle_slaves++; - @} - input = COMM_generate_task_input(); - if (input.data != NOTASK.data) @{ - SUBMIT_TO_SLAVE: output = DoTask(input.data); - num_idle_slaves--; - @} - else if (num_idle_slaves < num_slaves) // else insure progress condition - receive_task_output(); // by blocking until slave reply - else break; - @} // termination condition: last input _after_ all slaves idle was NOTASK - -@end ignore -@comment Document ./configure --strip-libs -@comment Explain that any pointer type is acceptable for arguments of callbacks -@comment From .future/manual.dvi, take problems with starting as --mpi -@comment and add it as appendix (and move existing stuff there). -@comment Add --TOPC-sendahead=0 by default -@comment and allow it to create at least 1 in advance. -@comment 0 in advance means send out while processing curr. result? -@comment Note that previous task can still generate REDO, -@comment CONTINUATION() guaranteed to go to same slave, but possibly -@comment with an intervening task before the action. -@comment For setpriority(), setrlimit(), etc., re-format for .texi -@comment and consider making them TOP-C options, or at least --TOPC_nice -@comment Make MSG_CACHE_SIZE a dynamic option based on messages seen, -@comment and do setsockopt(SO_RCVBUF/SO_SNDBUF) for it. -@comment Use this in tutorial to gradually expand examples. -@comment 1. no UpdateSharedData, trivial parallelism -@comment 2. no UpdateSharedData (with SOFT_ABORT for search) -@comment 3. no CheckTaskResult, automatic re-check and re-do -@comment ON --mpi, HAVE TO COMPARE INODE/VNODE OF MASTER AND SLAVE -@comment BINARY, AND WARN IF NOT SAME. -@comment ADD TOPC_master_slave_once( GenerateTaskInput, DoTask, Check... ) -@comment AND DEFINE master_slave_chdir(), getstats(), vnode of slave(), -@comment find getsockopt(SO_RCVBUF) of slave, etc., -@comment USING THIS MODE within topc.c -@comment CREATE NOMSG, synonymous with NOTASK?? -@comment SHOULD HAVE marshaling functions: -@comment SetMsgFld("field1",ptr,size); GetMsgFld("field1); -@comment and require marshaling/unmarshaling in identical order. -@comment Check that same size fields are unpacked as packed. -@comment LATER, COULD INCLUDE SEPARATE TUTORIAL -@comment (then add recursion example) -@comment DOCUMENT sendahead when ready (still experimental version only) -@comment ADD FAQ (common questions): -@comment Why must generate_task_input() be prepared to return -@comment more than once when there is no more work to do? -@comment After passing TOP-C an application buffer using TOPC_MSG, -@comment do I need to free the application buffer, or will TOP-C do that? - -@ifinfo -This file documents version @value{VERSION} of -@center @samp{TOP-C} (Task Oriented Parallel C/C++) -@center (last updated @value{UPDATED}) - -@center Copyright (c) 2000 - 2004 Gene Cooperman - -Permission is granted to make and distribute verbatim -copies of this manual provided the copyright notice and -this permission notice are preserved on all copies. - -@ignore -Permission is granted to process this file through TeX -and print the results, provided the printed document -carries a copying permission notice identical to this -one except for the removal of this paragraph (this -paragraph not being relevant to the printed manual). - -@end ignore -Permission is granted to copy and distribute modified -versions of this manual under the conditions for -verbatim copying, provided also that the sections -entitled ``Copying'' and ``GNU Lesser General Public License'' -are included exactly as in the original, and provided -that the entire resulting derived work is distributed -under the terms of a permission notice identical to this -one. - -Permission is granted to copy and distribute -translations of this manual into another language, -under the above conditions for modified versions, -except that this permission notice may be stated in a -translation approved by the Free Software Foundation. -@end ifinfo - -@ignore -@shorttitlepage TOP-C (Task Oriented Parallel C/C++) -@end ignore - -@titlepage - -@title TOP-C (Task Oriented Parallel C/C++) -@ifhtml -TOP-C logo -@end ifhtml -@subtitle A Package for Easily Writing Parallel Applications -@subtitle for both Distributed and Shared Memory Architectures -@subtitle Version @value{VERSION}, @value{UPDATED} -@author Gene Cooperman - - Copyright (c) 2000-2004, Gene Cooperman - - Permission is granted to make and distribute verbatim - copies of this manual provided the copyright notice and - this permission notice are preserved on all copies. - - Permission is granted to copy and distribute modified - versions of this manual under the conditions for - verbatim copying, provided also that the sections - entitled ``Copying'' and ``GNU General Public License'' - are included exactly as in the original, and provided - that the entire resulting derived work is distributed - under the terms of a permission notice identical to this - one. - - Permission is granted to copy and distribute - translations of this manual into another language, - under the above conditions for modified versions, - except that this permission notice may be stated in a - translation approved by the Free Software Foundation. - - @page - @vskip 0pt plus 1filll -@end titlepage - -@comment makefile should run install-info after copying info file to dir. -@dircategory Programming -@direntry -* TOP-C: (topc). TOP-C (Task Oriented Parallel C/C++) -@end direntry - -@node Top, Copying, (dir), (dir) -@comment node-name, next, previous, up - -@ifinfo -This documents version @value{VERSION} of@* -@samp{TOP-C} (Task Oriented Parallel C/C++),@* -last updated @value{UPDATED}. -@end ifinfo - -@menu -* Copying:: -* Quick Start:: -* Overview:: -* Writing TOP-C Applications:: -* Compiling and Invoking TOP-C Applications:: -* Debugging and Tracing:: -* Performance and Long Jobs:: -* Advanced Features:: -* TOP-C Raw Interface:: -* Acknowledgements:: -* Summary:: -* Example:: -* Using a Different MPI with TOP-C:: -* Function Index:: -* Variable Index:: -* Concept Index:: - - --- The Detailed Node Listing --- - -Overview of @samp{TOP-C/C++} - -* Programmer Model:: -* Three Key Concepts for TOP-C:: -* Memory Models:: - -Programmer's Model - -* Structure of a TOP-C Program:: -* Four Callback Functions:: -* Task Buffers:: -* The TOP-C Algorithm:: - -Task Input and Task Output Buffers - -* Defining Task Buffers:: -* Marshaling:: - -Writing @samp{TOP-C} Applications - -* The Main TOP-C Library Calls:: -* Callback Functions:: -* Actions:: -* TOP-C Utilities:: - -Compiling and Invoking @samp{TOP-C} Applications - -* Compiling TOP-C Applications:: -* Command Line Options:: -* Invoking a TOP-C Application in Sequential Memory:: -* Invoking a TOP-C Application in Distributed Memory:: -* Invoking a TOP-C Application in Shared Memory:: - -Invoking a TOP-C Application in Distributed Memory - -* Procgroup Files:: -* Slaves Fail to Start:: - -Debugging and Tracing - -* Debugging by Limiting Parallelism:: -* Debugging with --TOPC-safety:: -* TOP-C and POSIX signals:: -* Tracing Messages:: -* Stepping Through a Slave:: -* Segmentation faults:: - -Performance and Long Jobs - -* Strategies for Greater Concurrency:: -* Improving Performance:: -* Long Jobs:: - -Advanced Features of @samp{TOP-C} - -* Testing for Task Continuations:: -* Aborting Tasks:: -* Allocation of Task Buffers:: -* Shared Memory Model:: -* Sequential Memory Model:: -* Caveats:: - -Memory Allocation for Task Buffers - -* Avoiding malloc:: -* Large Buffers and TOPC_MSG_PTR:: -* Allocation for TOPC_MSG_PTR:: -* Marshaling Complex Data Structures:: - -Optimizing TOP-C Code for the Shared Memory Model - -* Reader-Writer Synchronization:: -* Thread-Private Global Variables:: -* Volatile Variables:: -* SMP Performance:: - -@samp{TOP-C} Raw Interface for Parallelizing Sequential Code - -* TOPC-C raw functions:: -* Parallelizing For Loops:: -* Parallelizing While Loops:: -@end menu - -@node Copying, Quick Start, Top, Top -@chapter @samp{TOP-C} Copying Conditions - -All of the copyright notices of this package are designed to encourage -free copying and usage. This manual is copyright by Gene Cooperman. -Most of the source code files of the @samp{TOP-C} software package contain -a copyright notice similar to that below. At the current time, Some of -the source files are copyright by Gene Cooperman alone and some by both -Gene Cooperman and Victor Grinberg, but all files are distributed under -the GNU LGPL license referred to below. - -@example - ********************************************************************** - * Copyright (c) 2000 - 2004 Gene Cooperman * - * * - * This library is free software; you can redistribute it and/or * - * modify it under the terms of the GNU Lesser General Public * - * License as published by the Free Software Foundation; either * - * version 2.1 of the License, or (at your option) any later version. * - * * - * This library is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * - * Lesser General Public License for more details. * - * * - * You should have received a copy of the GNU Lesser General Public * - * License along with this library (see file COPYING); if not, write * - * to the Free Software Foundation, Inc., 59 Temple Place, Suite * - * 330, Boston, MA 02111-1307 USA, or contact Gene Cooperman * - * . * - ********************************************************************** -@end example - -@node Quick Start, Overview, Copying, Top -@chapter Quick Start: Installation and Test Run - -@display - This is version @value{VERSION} of Task Oriented Parallel C/C++ (@samp{TOP-C}). - See @url{http://www.ccs.neu.edu/home/gene/topc.html} for general - information on obtaining source, overview slides of @samp{TOP-C}, - previous @samp{TOP-C} applications, etc. - Gene Cooperman - @email{gene@@ccs.neu.edu} -@end display - -It has been tested and works on several workstation -architectures. It provides task-oriented parallelism to the end user. -The same application source code (or object code) can be executed -(or linked) with any of the following communication libraries -using the topcc command (a substitute for cc or gcc): -@enumerate -@item a distributed memory library using MPI - (MPI subset, mpinu, included in distribution); or -@item a shared memory library using threads; or -@item a single-process sequential library - (useful for development and debugging). -@end enumerate -The @samp{TOP-C} model has been successfully used for some very large -computations. -@comment (See http://www.ccs.neu.edu/home/gene/par-tools.html) - -To unpack: -@example - gunzip topc.tar.gz - tar xvf topc.tar - cd topc - ./configure - make -@end example - -If you are impatient, you can immediately do: -@example -@group - cd bin - make parfactor -@end group -@end example -@noindent -and see a demonstration for factoring numbers by a Euclidean sieve. -Then try: @code{./a.out @var{YOUR_NUMBER}}@* -Read bin/Makefile for an example of compiling a @samp{TOP-C} program. - -If you want to use more or different slave processes, modify -@file{bin/procgroup}. -Then, again: -@example -@group - cd bin - ./a.out @var{YOUR_NUMBER} -@end group -@end example - -And compare with your results using a single slave process: -@example - ./a.out --TOPC-num-slaves=1 YOUR_NUMBER -@end example -Or investigate what other command-line TOP-C options are available for a.out. -@example - ./a.out --TOPC-help -@end example - -Other TOP-C applications besides parfactor are in the directory -@file{../examples}. For example, if you would like to try -@file{parquicksort.c}, then from the @file{bin} directory, try: -@example - make check TEST_FILE=parquicksort -@end example - -When you write your own @samp{TOP-C} application, @file{app.c}, make -sure that it contains @code{#include } at the top, and that you -have a procgroup file in the current directory, and then: -@example -@group - bin/topcc --mpi -o app app.c - # or else: bin/topc++ --mpi -o app app.cc - ./app -@end group -@end example -@noindent -@file{topcc} is a wrapper for your standard C compiler. It accepts all -the standard compiler command line options, plus a few more. -@file{topc++} also exists. [NOTE: @code{bin/topcc --help} and -@code{bin/topc++ --help} both work and @file{doc/topcc.1} exists ] - -This might be a good point to download and print at least the first half -of the manual, or else make it from the doc directory (@command{cd doc; -make pdf; make ps}). Note that the table of contents may appear at the -end of the documentation after the index. See @ref{Summary}, for a list of the -@samp{TOP-C} commands. See @ref{Example}, for a simple @samp{TOP-C} -example application involving only trivial parallelism. The -@file{examples} subdirectory provides more detailed examples. -A tutorial is available from the web page, -@url{http://www.ccs.neu.edu/home/gene/topc.html}. - -Finally, if you want to install @samp{TOP-C} permanently, type -@example -@group - ./configure # Install in /usr/local - ./configure --prefix=$HOME # Install in home directory - make install -@end group -@end example - -This adds a man page, an info file (try @code{info topc}), etc. HTML -documentation is available in the @file{doc} subdirectory of the -@samp{TOP-C} distribution. By default, @samp{TOP-C} will install in -@file{/usr/local}, requiring root privilege. If you configure -@code{--prefix=$HOME}, -@samp{TOP-C} will create files in @file{$HOME/bin}, @file{$HOME/lib}, -@file{$HOME/include}, @file{$HOME/man} and @file{$HOME/info}. -If you want to make @samp{TOP-C} with @code{cc} instead of @code{gcc}, type: -@example - env CC=cc ./configure --cache-file=/dev/null -@end example -@code{CFLAGS}, @code{CXX} (for @command{topc++} and -@code{CXXFLAGS} can also be set. -For other configuration options, type: -@example - ./configure --help -@end example - -Please write the author, Gene Cooperman (@email{gene@@ccs.neu.edu}), if -there are any questions. - -@node Overview, Writing TOP-C Applications, Quick Start, Top -@chapter Overview of @samp{TOP-C/C++} - -@comment @flushleft -@display -@cartouche -@noindent - "Difficulty?" exclaimed Ford. "Difficulty? What - do you mean difficulty? [The wheel is] the single - simplest machine in the universe!" ... - "All right, Mr. Wiseguy," she said, "you're so - clever, you tell us what color it should be." - from "The Restaurant at the End of the Universe" - by Douglas Adams -@end cartouche -@end display -@comment @end flushleft - -@noindent -@samp{TOP-C} has been designed especially to make it easy to parallelize -@emph{existing} sequential applications. Toward this goal, -@samp{TOP-C} emphasizes: -@enumerate -@item ease of use (high level task-oriented abstraction); -@item latency tolerance; and -@item architecture independence (same application code for - shared and distributed memory). -@end enumerate - -A @samp{TOP-C} application is compiled and run using @command{topcc} -(similarly to @command{gcc}) or @command{topc++} (similarly to @command{g++}). -For example, assuming a @file{procgroup} file in the current -directory to specify the remote hosts for the slave processes, -one executes: -@example - topcc --mpi parfactor.c - # or else: topc++ --mpi parfactor.cc - ./a.out -@end example - -If a @samp{TOP-C} application fails to link, check for a clash of -symbol names. All TOP-C symbols are of the form -TOPC_*, COMM_*, MEM_*, MPI_*, MPINU_*, NO_ACTION, UPDATE, REDO, CONTINUATION, -or NOTASK. - -For purposes of documentation, we will standardize on an explanation of -@command{topcc}. Wherever @command{topcc} is mentioned, the description is -equally valid for @command{topc++}. - -@menu -* Programmer Model:: -* Three Key Concepts for TOP-C:: -* Memory Models:: -@end menu - -@node Programmer Model, Three Key Concepts for TOP-C, Overview, Overview -@section Programmer's Model - -@menu -* Structure of a TOP-C Program:: -* Four Callback Functions:: -* Task Buffers:: -* The TOP-C Algorithm:: -@end menu - -@node Structure of a TOP-C Program, Four Callback Functions, Programmer Model, Programmer Model -@subsection Structure of a TOP-C Program - -A typical TOP-C application has the following structure: -@example -#include -... define four callback functions for TOPC_master_slave() ... -int main( int argc, char **argv ) @{ - TOPC_init( &argc, &argv ); - ... - TOPC_master_slave( GenerateTaskInput, DoTask, CheckTaskResult, - UpdateSharedData ) - ... - TOPC_finalize(); -@} -@end example - -The program above is run with a master process and several slave processes -operating with identical command line arguments and identical initial -data (SPSD, or Single Program, Single Data). Communication among processes -occurs only within the routine @code{TOPC_master_slave()}, during which -execution can be called SPMD (Single Program, Multiple Data). At the end -of @code{TOPC_master_slave()}, execution returns to SPSD, although the -master process may contain some additional process-private data. - -@ref{TOP-C Raw Interface} describes an alternative interface that is -often useful for parallelizing existing sequential code. However, for -new applications, the standard interface will usually be cleaner. - -@node Four Callback Functions, Task Buffers, Structure of a TOP-C Program, Programmer Model -@subsection Four Callback Functions - -In a @samp{TOP-C} application, the programmer defines four callback -functions and passes control to the @samp{TOP-C} library through the -following command. -@example -@group - TOPC_master_slave(GenerateTaskInput, DoTask, CheckTaskResult, - UpdateSharedData); -@end group -@end example - -Pictorially, TOP-C arranges for the flow of control among the four callback -functions as follows: -@clear for-tex -@iftex -@set for-tex -@end iftex -@comment Have latex version of this, but how to pass it through? -@example - (ON MASTER) task input - GenerateTaskInput() ----------> - - - task input (ON A SLAVE) task output - -----------> DoTask(input) -----------> - - - task output (ON MASTER) action - -----------> CheckTaskResult(input, output) -----------> - - -if (action == UPDATE): - task input, task output (ON ALL PROCESSES) - -----------------------> UpdateSharedData(input, output) -@end example -@ignore -@tex -{\footnotesize -\begin{figure}[htb]\label{topc-fig} -\begin{center}\label{diagram} -\setlength{\unitlength}{3.0pt} -% \setlength{\unitlength}{2pt} % for 2-column mode -\begin{picture}(100,95) -\put(25,90){\makebox(0,0)[b]{\bf MASTER}} -\put(75,90){\makebox(0,0)[b]{\bf SLAVE}} -\put(50,00){\line(0,1){4}} -\multiput(50,15)(0,5){16}{\line(0,1){4}} % 20 times, delta = (0,5) -\thicklines -\put(5,88){\line(1,0){95}} -\put(25,75){\oval(20,10)} % corner is (35,70) -\put(25,75){\makebox(0,0){\verb|get\_task()|}} -\put(75,55){\oval(25,10)} % corner is (62,5, 50) -\put(75,55){\makebox(0,0){\verb|do\_task(input)|}} -\put(25,32){\oval(45,10)} % corner is (47.5, 26) -\put(25,32){\makebox(0,0){\parbox[t]{90pt}{\verb|get\_task\_result| \hbox{\ \ }\ -verb|(output, input)|}}} -\put(50,10){\oval(75,10)} -\put(50,10){\makebox(0,0){\verb|update\_environment(output, input)|}} -\thinlines -% text is near beginning of vector -% ref. point is one corner of oval -\thicklines -\put(34,69){\vector(3,-1){27}} % base is length 20 -\put(36,69){\makebox(0,0)[bl]{\verb|input|}} -\put(62,51){\vector(-3,-2){18}} % base is length 20 -\put(60,51){\makebox(0,0)[br]{\verb|output|}} -\thinlines -\put(48,37){\vector(3,2){15}} % base is length 20 -\put(48,37){\makebox(0,0)[tl]{(if action == {\tt REDO})}} -\put(25,25){\vector(3,-1){25}} % base is length 20 -\put(36,22){\makebox(0,0)[bl]{(if action == {\tt UPDATE})}} -\end{picture}\break - \hbox{\large TOP-C Programmer's Model} -\end{center} -\end{figure} -} -@end tex -@end ignore - -@node Task Buffers, The TOP-C Algorithm, Four Callback Functions, Programmer Model -@subsection Task Input and Task Output Buffers - -@cindex task input -@cindex task output - -A @dfn{task input} or @dfn{task output} is an arbitrary buffer of bytes -of type @code{(void *)} in @samp{TOP-C}. The task buffers are arbitrary -application-defined data structures, which are opaque to @samp{TOP-C}. -Note that in ANSI C, a void pointer is compatible with any other pointer type -(such as @code{(struct task_input *)} and @code{(struct task_output *)} -in the example below). - -@menu -* Defining Task Buffers:: -* Marshaling:: -* Marshalgen:: -@end menu - -@node Defining Task Buffers, Marshaling, Task Buffers, Task Buffers -@subsubheading Defining Application Task Buffers - -An application callback function returning a task input or task output -must encapsulate it in a function, @code{TOPC_MSG( void *@var{buf}, int -@var{buf_size} )}, which is then returned by the callback functions -@code{GenerateTaskInput()} and @code{DoTask()}. @code{TOPC_MSG()} -internally allocates a copy of @var{buf}, and TOP-C later frees the copy -automatically. So, @var{buf} may be reused by the application program. - -@example -TOPC_BUF DoTask( struct task_input * inp ) @{ - struct task_output outp; - ... - outp = ...; - return TOPC_MSG( &outp, sizeof(outp) ); -@} -@end example - -The principle of memory allocation in @samp{TOP-C} is that if an -application allocates memory, then it is the responsibility of the -application to free that memory. @code{TOPC_MSG()} has the further -property of copying its buffer argument to a separate @samp{TOP-C} space -(using a shallow copy), after which the application can free any memory it -allocated. This happens automatically in the above example, -since @code{outp} is allocated on the stack. - -@node Marshaling, Marshalgen, Defining Task Buffers, Task Buffers -@subsubheading Marshaling (Serialization) and Heterogeneous Architectures - -@cindex marshaling -@cindex serialization -@cindex heterogeneous architectures - -If a heterogeneous -architecture is used, there is an issue of converting data formats -or @dfn{marshaling}. -This is the application's responsibility. For simple data formats -(integers, floats or characters), such conversion can easily be done -in an ad hoc manner. Most C compilers use the IEEE binary -floating point standard, and characters are almost always encoded -in eight bit ASCII representation (or possibly in a standard Unicode -format). Although the byte ordering of integers is not standardized, -the system calls @code{htonl()} and @code{ntohl()} are available -to convert integers into 32 bit @emph{network integers} that are -portable across heterogeneous systems. - -For more complicated conversions, one can consider writing one's own -marshaling routines or else using a standard package for marshaling -such as the @samp{XDR} library (RFC 1832, eXternal Data Representation), -@samp{IDL} (@samp{Corba}), or @samp{SOAP} (@samp{XML}). - -@node Marshalgen, , Marshaling, Task Buffers -@subsubheading Marshalgen, a Package for Marshaling - -For complex C++ applications, we recommend tat you try out -@samp{Marshalgen} package. A pointer to it is available from the TOP-C -home page. Since the C++ classes to be marshaled are already defined in -@file{.h} files, Marshalgen asks th user simply to annotate those files -with comments (for example, deep copying vs. shallow copying fo -pointers). @samp{Marshalgen} also has support for such real world -issues as marshalingsubclasses and templates, handling of polymorphism, -etc. The @samp{Marshalgen} preprocessor then generates methods for a -new marshaling class that know how to marshal and unmarshal the original -class. - -@cindex Marshalgen, a package for marshaling - -@node The TOP-C Algorithm, , Task Buffers, Programmer Model -@subsection The @samp{TOP-C} Algorithm - -When there is only one slave, -The @samp{TOP-C} algorithm can be summarized by the -following C code. -@example -@{ void *input, *output; - TOPC_ACTION action; - while ( (input = GenerateTaskInput()) != NOTASK ) @{ - do @{ - output = DoTask(input); - action = CheckTaskResult(input, output); - @} while (action == REDO); /* REDO not useful for only one slave */ - if (action == UPDATE) then UpdateSharedData(input, output); - @} -@} -@end example - -On a first reading, it is recommended to skip the rest of this -section until having read through Section @ref{Actions}. - -For a better understanding of the case of multiple -slaves, this simplified excerpt from the @samp{TOP-C} source code describes -the @samp{TOP-C} algorithm. -@example -TOPC_BUF input, output; -int num_idle_slaves = num_slaves; -TOPC_ACTION action; - -while (TRUE) @{ - wait_until_an_idle_slave(); - input = COMM_generate_task_input(); - if (input.data != NOTASK.data) @{ - SUBMIT_TO_SLAVE: output = DoTask(input.data); - num_idle_slaves--; - @} - else if (num_idle_slaves < num_slaves) // else insure progress condition - receive_task_output(); // by blocking until a slave replies - else break; -@} // termination condition: _after_ all slaves idle, next input was NOTASK -@end example - -The code for @code{wait_until_an_idle_slave()} can be expanded as follows. -@example -void wait_until_an_idle_slave() @{ - do @{ - while ( result_is_available(&input, &output) ) @{ - action = CheckTaskResult(input.data, output.data); - if (action == UPDATE) - UpdateSharedData(input.data, output.data); - if (action == REDO) /* Use updated shared data, when redoing */ - SUBMIT_TO_SLAVE: output = DoTask(input.data); - num_idle_slaves++; - @} while (num_idle_slaves == 0); - @} -@end example - -Note that the term @dfn{result} refers to an @samp{(input,output)} pair. -The routine @code{CheckTaskResult()} returns an @dfn{action}, which -determines the -control structure for a parallel algorithm. A common definition is: - -@example -@group -TOPC_ACTION CheckTaskResult( void *input, void *output ) @{ - if (output == NULL) return NO_ACTION; - else if ( TOPC_is_up_to_date() ) return UPDATE; - else return return REDO; @} -@end group -@end example - -@code{TOPC_is_up_to_date()} returns true if and only if during the interval -between when the task input was originally generated and when the task -output was returned by the most recent slave, no other slave process had -returned a task output during the interim that had caused the shared data -to be modified through an @code{UPDATE} action. An @code{UPDATE} action causes -@code{UpdateSharedData()} to be invoked on each process. Further -discussion can be found in @ref{TOP-C Utilities}. - -@node Three Key Concepts for TOP-C, Memory Models, Programmer Model, Overview -@section Three Key Concepts for TOP-C - -@cindex task -@cindex shared data -@cindex global shared data -@cindex action -@cindex TOP-C action - - The @samp{TOP-C} programmer's model is based on three key concepts: -@enumerate -@item - @dfn{tasks} in the context of a master/slave architecture; -@item - global @dfn{shared data} with lazy updates; and -@item - @dfn{@var{actions}} to be taken after each task. -@end enumerate - -Task descriptions (task inputs) are generated on the master, and assigned to -a slave. The slave executes the task and returns the result to the master. -The master may update its own private data based on the result, or it may -update data on all processes. Such global updates take place on each slave -after the slave completes its current task. Updates are @dfn{lazy} in -that they occur only after a task completes, although it is possible to -issue a non-binding request to @samp{TOP-C} to abort the current tasks -(@ref{Aborting Tasks}). -A SPMD (Single Program Multiple -Data) style of programming is encouraged. - -In both shared and distributed memory architectures, one must worry -about the order of reads and writes as multiple slaves autonomously -update data. The utilities below are meant to ease that chore, by -supporting the ease of the SPMD programming style, while still -maintaining good efficiency and generality for a broad range of -applications. The software can easily be ported to a variety of -architectures. - -@node Memory Models, , Three Key Concepts for TOP-C, Overview -@section Distributed and Shared Memory Models - -@cindex memory model, distributed -@cindex distributed memory model -@cindex SMP - -@samp{TOP-C} provides a single API to support three primary memory -models: @dfn{distributed memory}, @dfn{shared memory} and -@dfn{sequential memory}. (The last model, sequential memory, refers to -a single sequential, non-parallel process.) On a first reading, one -should think primarily of the distributed memory model (distributed -nodes, each with its own private memory). Most programs written for -distributed memory will compile without change for sequential memory. -@samp{TOP-C} is designed so that the same application source code may -operate efficiently both under distributed and under shared memory. In -order to also compile for shared memory hardware (such as SMP), -additional hints to @samp{TOP-C} may be necessary. - -In shared memory architectures, @emph{all} data outside of the four -callback functions is shared, by default. Hence, an @code{UPDATE} -action under shared memory causes only the master process to invoke -@code{UpdateSharedData()}. To avoid inconsistencies in the data, by -default @samp{TOP-C} arranges that no slave process may run -@code{DoTask()} while @code{UpdateSharedData()} is running. -@samp{TOP-C} also provides support for finer levels of granularity -through application-defined private variables and critical sections. -Further discussion can be found in @ref{Shared Memory Model}. - -@node Writing TOP-C Applications, Compiling and Invoking TOP-C Applications, Overview, Top -@chapter Writing @samp{TOP-C} Applications - -This chapter assumes a knowledge of the basic concepts in -@ref{Overview}. In particular, recall @ref{Structure of a TOP-C Program}. - -@menu -* The Main TOP-C Library Calls:: -* Callback Functions:: -* Actions:: -* TOP-C Utilities:: -@end menu - -@node The Main TOP-C Library Calls, Callback Functions, Writing TOP-C Applications, Writing TOP-C Applications -@section The Main TOP-C Library Calls - -@cindex initializing @samp{TOP-C} -@cindex master-slave mode, invoking -@cindex task input -@cindex task output -@cindex message format, TOPC_MSG() - -Every @samp{TOP-C} application must include a @file{topc.h} header, open -with @code{TOPC_init()}, call @code{TOPC_master_slave()} one or more -times, and then close with @code{TOPC_finalize()}. - -@display -@code{#include } - Required at head of any file using TOPC library calls. -@end display -@deftypefun void TOPC_init ( int *@var{argc}, char ***@var{argv} ) - Required before first occurrence of @code{TOPC_master_slave()}; - Recommended to place this as first executable statement in - @code{main()}. It will strip off extra @samp{TOP-C} and - communication layer arguments such as @option{--TOPC-stats}, - which are added by @samp{TOP-C}. -@end deftypefun -@deftypefun void TOPC_finalize ( void ) - Placed after last @samp{TOP-C} command. -@end deftypefun -@deftypefun void TOPC_master_slave - ( TOPC_BUF (*@var{generate_task_input})(),@*@ @ - TOPC_BUF (*@var{do_task})(void *input),@*@ @ - TOPC_ACTION (*@var{check_task_result})(void *input, void *output),@*@ @ - void (*@var{update_shared_data})(void *input, void *output) - @*) - @*Primary call, passed four application callbacks to @samp{TOP-C}. - One can have multiple calls to - @code{TOPC_master_slave()}, each invoking different callback functions, - between @code{TOPC_init()} - and @code{TOPC_finalize()}. -@end deftypefun - -@sp 1 -A task input or task output is simply a buffer of bytes, specified by -@code{TOPC_MSG()}. - -@deftypefun TOPC_BUF TOPC_MSG ( void *@var{buf}, int @var{buf_size} ) - Must be returned by @code{GenerateTaskInput()} and @code{DoTask()}. - Specifies arbitrary user data structure. - @samp{TOP-C} will make a copy of @var{buf} in @samp{TOP-C} space. - It remains the responsibility of the application to free or - reuse the space of the original buffer @var{buf}. If - @code{TOPC_MSG(NULL, 0)} is called, a @code{NULL} pointer will be - received at the destination. - (@xref{Large Buffers and TOPC_MSG_PTR}, for @code{TOPC_MSG_PTR}, - to avoid copying very large buffers, where the overhead is - unacceptable.) -@end deftypefun - -@noindent -EXAMPLE: -@example -@group - TOPC_BUF convert_string_to_msg( char *mystring ) @{ - if (mystring == NULL) return TOPC_MSG(NULL,0); - else return TOPC_MSG(mystring, strlen(mystring)+1); - @} -@end group -@end example - -@node Callback Functions, Actions, The Main TOP-C Library Calls, Writing TOP-C Applications -@section Callback Functions for @code{TOPC_master_slave()} - -The application writer must define the following four callback functions -(although the last can be @code{NULL}). The @var{callback} terminology -is based on C@w{ }concepts. In a more object-oriented style, one would -view user callbacks as instantiation of abstract methods in a -user-defined subclass. The first two functions return a -@code{TOPC_BUF}, which is produced by @code{TOPC_MSG()}. -@deftypefun TOPC_BUF GenerateTaskInput ( void ) - executes on master; returns a data structure specified by - @code{TOPC_MSG(@var{buf}, @var{buf_size})}. - It should return @code{NOTASK}, when there are no more tasks, and it - should be prepared to return @code{NOTASK} again if invoked again. -@end deftypefun -@deftypefun TOPC_BUF DoTask ( void *@var{input} ) - executes on slave; operates on the result of @code{GenerateTaskInput()}; - returns a data structure specified by - @code{TOPC_MSG(@var{buf}, @var{buf_size})}. - @var{buf} must be a static or global user buffer. -@end deftypefun -@deftypefun TOPC_ACTION CheckTaskResult ( void *@var{input}, void *@var{output}) - executes on master; operates on the result of @code{DoTask()}; - returns an @var{ACTION} that determines what happens to the task next. - The terminology @dfn{result} refers to an @samp{(input, output)} pair. - An easy way to write @code{CheckTaskResult()} appears in the - example for the utility @code{TOPC_is_up_to_date()}. - When returning the action @code{UPDATE}, it works to first modify - the input and output buffers. @code{UpdateSharedData()} will - then be invoked with the modified buffers. - See @ref{TOP-C Utilities}, for more details. -@end deftypefun -@deftypefun void UpdateSharedData ( void *@var{input}, void *@var{output} ) - executes on master and all slaves; operates on the result of - @code{DoTask()}, and the original task returned by - @code{GenerateTaskInput()}; - called only if @code{CheckTaskResult()} returned @code{UPDATE}; - useful for updating global variables in all processes; - The pointer argument, @var{update_shared_data}, of - @code{TOPC_master_slave()} may be @code{NULL} if - an application never requests an @code{UPDATE} action. - In a shared memory environment, only the master calls - @code{UpdateSharedData()}. See @ref{Shared Memory - Model}, for more details. -@end deftypefun - -Note that in defining the above callback functions, C allows one to -replace the @code{(void *)} declaration of the arguments by specific -pointer types. Note that the buffers of any message parameters -(@var{input} and @var{output}) of @code{DoTask()} or -@code{CheckTaskResult()} are part of TOP-C space. Such buffers may be -freed by TOP-C on exit from the callback function. An application -wishing to use the buffer after the callback exits must explicitly save -a copy into the application's own space. - -@node Actions, TOP-C Utilities, Callback Functions, Writing TOP-C Applications -@section Actions Returned by @code{CheckTaskResult()} - -@cindex actions returned by @code{CheckTaskResult()} - -A @dfn{TOP-C result} is an (@var{input}, @var{output}) pair corresponding -to an invocation of @code{DoTask()}. @samp{TOP-C} passes the result to -@code{CheckTaskResult()}. The return value allows the application to -tell @samp{TOP-C} what further actions to take. -The actions returned by @code{CheckTaskResult()} are: -@deftypevr Action TOPC_ACTION NO_ACTION - C constant, causing no further action for task -@end deftypevr -@deftypevr Action TOPC_ACTION UPDATE - C constant, invoking @code{UpdateSharedData( void *@var{input}, - void *@var{output})} (see below) - also updates bookkeeping for sake of @code{TOPC_is_up_to_date()} - (@pxref{TOP-C Utilities}) -@end deftypevr -@deftypevr Action TOPC_ACTION REDO - Invoke @code{DoTask()} on original task input again, and on - the same slave that previously executed the task; useful if - shared data has changed since original - invocation of @code{DoTask()} (see @code{TOPC_is_up_to_date()}, - below). See @ref{Strategies for Greater Concurrency}, - for slave strategies to efficiently process a @code{REDO} action. -@end deftypevr -@comment Small lie that this is a variable, but we don't want it w/ fnc's -@deftypevr Action TOPC_ACTION CONTINUATION ( void *@var{next_input} ) - @code{CONTINUATION(@var{next_input})} is a parametrized action that - may be returned by @code{CheckTaskResult()}, after which - @code{DoTask( @var{next_input} )} is called on the original slave. - This is useful if only the master can decide whether task is complete, - or if the master wishes to supply additional input messages - needed for the task. - Note that @code{REDO} is essentially equivalent to - @code{CONTINUATION( @var{original_task_input} )}. - Note that any pending calls to @code{UpdateSharedData()} will have - occurred on the slave before the new call to @code{DoTask()}. - Hence, this allows an extended conversation between master and - slave, in which the slave continues to receive updates of the - shared data before each new input from the master. - Note also that even though a @code{CONTINUATION} action returns - to the original slave, any previous pointers to input buffers - on that slave - (and pointers to output buffers from intervening @code{UPDATE} - actions) will no longer be valid. Useful data from previous buffers - should have been copied into global variables on the slave. - In the case of the shared memory model, those global variables must be - thread-private. (@pxref{Thread-Private Global Variables}) -@end deftypevr - -It is possible for @code{CheckTaskResult(@var{input}, @var{output})} to -modify the buffer data in its two arguments, @var{input} and @var{output}, -in which case the modifications will be visible to any further -callback functions processing the current task. This practice makes -the code more difficult to maintain, and is not recommended when other -solutions are available. - -@node TOP-C Utilities, , Actions, Writing TOP-C Applications -@section TOP-C Utilities - -@samp{TOP-C} also defines some utilities. -@deftypefun TOPC_BOOL TOPC_is_up_to_date ( void ) - returns TRUE or FALSE (1 or 0); returns TRUE if and only if - @code{CheckTaskResult()} - has not returned the result @code{UPDATE} (invoking - @code{UpdateSharedData()}) - between the time when @code{GenerateTaskInput()} was originally - called on the - current task, and the time when the corresponding - @code{CheckTaskResult()} - was called. - Typical usage: -@example - TOPC_ACTION CheckTaskResult( void *input, void *output ) - @{ if (input == NULL) return NO_ACTION; - else if (TOPC_is_up_to_date()) return UPDATE; - else return REDO; - @}@ -@end example -@end deftypefun -@deftypefun int TOPC_rank ( void ) - Unique ID of process or thread. Master always has rank 0. - Slaves have contiguous ranks, beginning at 1. -@end deftypefun -@deftypefun TOPC_BOOL TOPC_is_master ( void ) - Returns boolean, 0 or 1, depending on if this is master. - Equivalent to @code{TOPC_rank() == 0}. -@end deftypefun -@deftypefun int TOPC_num_slaves ( void ) - Total number of slaves. -@end deftypefun -@deftypefun int TOPC_num_idle_slaves ( void ) - Total number of idle slaves (not doing task, update or other action). -@end deftypefun -@deftypefun int TOPC_node_count ( void ) - Total number of processes or threads. Equivalent to - @code{TOPC_num_slaves() + 1}. -@end deftypefun - -@deftypefun TOPC_BOOL TOPC_is_REDO ( void ) -@deftypefunx TOPC_BOOL TOPC_is_CONTINUATION ( void ) -@deftypefunx void TOPC_abort_tasks ( void ) -@deftypefunx TOPC_BOOL TOPC_is_abort_pending ( void ) - See @ref{Advanced Features} for descriptions. -@end deftypefun - -@node Compiling and Invoking TOP-C Applications, Debugging and Tracing, Writing TOP-C Applications, Top -@chapter Compiling and Invoking @samp{TOP-C} Applications - -A @samp{TOP-C} application can be compiled once, and then linked to your -choice of a run-time library for either a sequential, distributed memory -or shared memory architecture. The two shell scripts @file{bin/topcc} -and @file{bin/topc++} are used instead of @samp{gcc} and @samp{g++} (or -other C/C++ compilers). - -@menu -* Compiling TOP-C Applications:: -* Command Line Options:: -* Invoking a TOP-C Application in Sequential Memory:: -* Invoking a TOP-C Application in Distributed Memory:: -* Invoking a TOP-C Application in Shared Memory:: -@end menu - -@node Compiling TOP-C Applications, Command Line Options, Compiling and Invoking TOP-C Applications, Compiling and Invoking TOP-C Applications -@section Compiling TOP-C Applications - -@cindex topcc -@cindex topc++ -@cindex topc-config - -The TOP-C application file must contain -@example - #include -@end example -@noindent -It must make calls to -@example -@group - TOPC_init(...); - TOPC_master_slave(...); - TOPC_finalize(); -@end group -@end example -@noindent -as describe in @ref{Structure of a TOP-C Program}. The -application file is compiled by one of: -@example -@group - topcc --seq @var{myfile.c} - topcc --mpi @var{myfile.c} - topcc --pthread @var{myfile.c} -@end group -@end example -@noindent -according to whether the target computer architecture will be sequential -(@option{--seq}: single processor), distributed memory (@option{--mpi}: -networked CPU's), or shared memory (@option{--pthread}: SMP or other -shared memory architecture with a POSIX threads interface). -@command{topcc} is a substitute for @command{cc} or @command{gcc}, -and creates an @samp{a.out} file. -(Similarly, @command{topc++} exists as a substitute for @command{c++} or -@command{g++}.) -There are man files, -@display - @file{doc/topcc.1}, @file{doc,topc++.1} -@end display -@noindent -with further information on @command{topcc} and @command{topc++}. -If installed, @command{man topcc} and @command{man topc++} exist. - -The same object file may be relinked to use different @samp{TOP-C} memory -models without recompiling the object file. -@example -@group - topcc -c @var{myapp.c} - topcc --seq -o @var{myapp-seq} @var{myapp.o} - topcc --mpi -o @var{myapp-mpi} @var{myapp.o} -@end group -@end example - -For large applications, it may be preferable to directly invoke -the @samp{TOP-C} libraries and include files. For such -situations, @command{topc-config} exists. The following -is exactly equivalent to @command{topcc --mpi myfile.c} -(assuming you configured @samp{TOP-C} using @command{gcc}). -@example - gcc `topc-config --cflags` --mpi myfile.c `topc-config --libs` -@end example -Type @command{topc-config} with no arguments for a full set of -command line options. - -For the rest of this chapter, we standardize our description for -@command{topcc}. However, @command{topc++} is equally valid wherever -@command{topcc} is mentioned. - -@node Command Line Options, Invoking a TOP-C Application in Sequential Memory, Compiling TOP-C Applications, Compiling and Invoking TOP-C Applications -@section Command Line Options in TOP-C Applications - -@cindex TOP-C options -@cindex TOP-C command line options -@vindex TOPC_OPTS -@cindex TOPC_OPTS environment variable for initialization -@cindex .topcrc -@cindex topcrc -@cindex options, TOP-C -@cindex command line options, TOP-C -@cindex --TOPC-help -@cindex --TOPC-verbose -@cindex --TOPC-stats -@cindex --TOPC-num-slaves -@cindex --TOPC-aggregated-tasks -@cindex --TOPC-slave-wait -@cindex --TOPC-slave-timeout -@cindex --TOPC-trace -@cindex --TOPC-procgroup -@cindex --TOPC-safety - -TOP-C searches for TOP-C parameters in the following locations, in order: -@enumerate -@item values of variables @code{TOPC_OPT_xxx} in the application code - before @code{TOPC_init()} -@item the file @file{.topcrc} in the home directory -@item the environment variable @env{TOPC_OPTS} -@item arguments on the command line in the form @code{--TOPC-xxx} -@end enumerate -The file @file{.topcrc} and the environment variable @env{TOPC_OPTS} -specify parameters -in the same format as on the command line. Later assignments of an -option override earlier assignments. - -For a brief synopsis of application command line options, type: -@example -@group - topcc @var{myapp.c} - ./a.out --TOPC-help - [ OR FOR MORE INFORMATION: ./a.out --TOPC-help --TOPC-verbose ] -@end group -@end example - -Currently, this will display the following. -@example -Usage: ./a.out [TOPC_OPTION ...] [OTHER_OPTIONS ...] - - where TOPC_OPTION is one of: ---TOPC-help@code{[=<0/1>]} display this message [default: false] ---TOPC-stats@code{[=<0/1>]} print stats before & after [default: false] ---TOPC-verbose@code{[=<0/1>]} set verbose mode [default: false] ---TOPC-num-slaves@code{=} number of slaves (sys-defined default) - [default: -1] ---TOPC-aggregated-tasks@code{=} number of tasks to aggregate - [default: 1] ---TOPC-slave-wait=@code{} secs before slave starts (use w/ gdb attach) - [default: 0] ---TOPC-slave-timeout=@code{} dist mem: secs to die if no msgs, 0=never - [default: 1800] ---TOPC-trace@code{=} trace (0: notrace, 1: trace, 2: user trace fncs.) - [default: 2] ---TOPC-procgroup@code{=} procgroup file (--mpi) - [default: "./procgroup"] ---TOPC-topc-log@code{=} NOT IMPL: log file for TOPC output ("-" = stdout) - [default: "-"] ---TOPC-safety=@code{} [0..20]: higher turns off optimizations, - (try with --TOPC-verbose) [default: 0] -@end example - -For each option, @option{--TOPC-@var{PARAM}}, there is a corresponding -C/C++ variable, @code{TOPC_OPT_@var{PARAM}}. This variable is of type -@code{int} or @code{(char *)}. If the application program sets the value -before a call to @code{TOPC_init()}, these variables will act as -defaults. For example, to turn off tracing by default, write: -@example -@group -int main( int argc, char *argv[] ) @{ - TOPC_OPT_trace = 0; - TOPC_init( &argc, &argv ); - ... -@end group -@} -@end example - -The option @option{--TOPC-trace} causes the task input and task output -to be traced and printed as they are passed across the network. The action of -a task is also printed. If an application is called with -@option{--TOPC-trace=2} (default) and if the variables -@code{TOPC_OPT_trace_input} and @code{TOPC_OPT_trace_result} are set -to pointers to -functions then those functions are called, and they may print additional -information. -@code{TOPC_OPT_trace_input} must be set to a function of one -variable: @code{void * @var{input}}. -@code{TOPC_OPT_trace_result} must be set to a function of two -variables: @code{void * @var{input}, void * @var{output}}. -When using C++, the function pointers must be cast to -@code{TOPC_trace_input_ptr} or @code{TOPC_trace_result_ptr} -before being assigned to @code{TOPC_OPT_trace_input} or -@code{TOPC_OPT_trace_result}, respectively. -For an example, see @file{examples/parfactor.c} in the TOP-C distribution. - -The option @option{--TOPC-stats} prints statistics (running times, -etc.) and -information about the conditions of an invocation of a TOP-C application -before and after a run. -The option @option{--TOPC-verbose} (set by default) displays TOP-C -warnings. With --TOPC-help, it provides additional information. - -For the usage of @option{--TOPC-procgroup}, -see @ref{Invoking a TOP-C Application in Distributed Memory}. -That section also explains on what hosts the slaves run -when @option{--TOPC-num-slaves} indicates a different number of -slaves than the @file{procgroup} file. - -For the usage of @option{--TOPC-aggregated-tasks}, -see @ref{Improving Performance}. -For the usage of @option{--TOPC-slave-wait}, see -@ref{Stepping Through a Slave}. -For the usage of @option{--TOPC-safety}, see -@ref{Command Line Options}. -For the usage of the other options, see the @ref{Concept Index}. - -@samp{TOP-C} recognizes @code{--} as terminating all option processing, -according to standard UNIX conventions. - -@node Invoking a TOP-C Application in Sequential Memory, Invoking a TOP-C Application in Distributed Memory, Command Line Options, Compiling and Invoking TOP-C Applications -@section Invoking a TOP-C Application in Sequential Memory - -@cindex memory model, sequential, compiling -@cindex compiling the sequential memory model -@cindex --seq argument to @code{topcc/topc++} - -For example, -@example - topcc --seq -g -O0 @var{myfile.c} -@end example -@noindent -compiles a sequential version for debugging using @command{gdb} -(@pxref{Top, , Summary, gdb, The GNU debugger}), for example. -This is usually a first step in debugging a TOP-C application, since -sequential debugging is easier than parallel debugging. - -@node Invoking a TOP-C Application in Distributed Memory, Invoking a TOP-C Application in Shared Memory, Invoking a TOP-C Application in Sequential Memory, Compiling and Invoking TOP-C Applications -@section Invoking a TOP-C Application in Distributed Memory - -@cindex memory model, distributed, compiling -@cindex compiling the distributed memory model -@cindex --mpi argument to @code{topcc/topc++} - -Linking using the @option{--mpi} option (default) allows an application to -execute using a distributed memory model of networked processors. The -@samp{TOP-C} distribution includes a subset MPI@footnote{MPI is -@emph{Message Passing Interface}, see @url{http://www.mpi-forum.org/}} -implementation @samp{MPINU}, sufficient to run @samp{TOP-C} -applications. -@example -@group - topcc --mpi @var{myapp.c} - ./a.out -@end group -@end example -The application must then create the remote slave processes at runtime. -If you use @samp{MPINU} (the default configuration of @samp{TOP-C}, -then the remote slave processes are specified by a @file{procgroup} file. -Otherwise, the startup mechanism depends on your @samp{MPI} implementation. - -@menu -* Procgroup Files:: -* Slaves Fail to Start:: -@end menu - -@node Procgroup Files, Slaves Fail to Start, Invoking a TOP-C Application in Distributed Memory, Invoking a TOP-C Application in Distributed Memory -@subsection Writing Procgroup Files for @samp{MPINU} - -@cindex MPINU -@cindex SSH environment variable for starting remote slaves -@cindex procgroup file -@cindex --TOPC-procgroup, usage of procgroup file -@cindex --TOPC-num-slaves, selection of slave hosts using procgroup file - -@samp{MPINU} is built into the default configuration of the -@samp{TOP-C} library and uses the @samp{procgroup} mechanism to specify -slave processes. (If you prefer to use a different @samp{MPI} dialect, -@samp{TOP-C} will work, but @file{src/Makefile.in} must be modified, -and that @samp{MPI} dialect may use a different mechanism for -introducing slave processes.) - -When the application binary is executed under the default, it looks at -the current directory for a file, -@display - @file{procgroup} -@end display -The @var{procgroup file} determines the number and location of the slave -processes. The @var{procgroup file} need only be visible from the -master process. If one prefers, one can specify an alternate -@var{procgroup file} via the syntax as in the following example: -@example - ./a.out --TOPC-procgroup=../myprocgroup.big -@end example - -The @samp{TOP-C} distribution includes a file @file{bin/procgroup} as an -example of the procgroup format. -The file must contain a line: -@example - local 0 -@end example -@noindent -for the master process. It must also contain a line for each slave -process in one of the following forms: -@example - hostname 1 @var{full_pathname} - hostname 1 - - hostname 1 ./@var{relative_pathname} - hostname 1 ../@var{relative_pathname} -@end example -@noindent -where @code{hostname} is the remote host. -The pathname @code{-} means to use the same pathname for the slave -on the remote host as for the master on the current host. -A relative pathname, such as @code{./a.out} or @code{../new_arch/a.out}, -specifies a pathname relative to the pathname of the binary of -the master on the current host. - -Most of the time, it is simplest to just include a full pathname -or else @code{-} in the @file{procgroup} file. The relative pathnames are -useful for a shared filesystem with binaries compiled for -different architectures. For example, the procgroup file might include -relative paths @file{../sparc/a.out}, @file{../alpha/a.out} and -@file{../linux/a.out}. -If you invoke @file{full_path/sparc/a.out}, this will yield a master -running @file{full_path/sparc/a.out} and three slaves running -each of the three architectures. - -The full principles are as follows. -Let SLAVE_PATH be the path of the slave as given in the procgroup file, -and let MASTER_DIR be the directory of the master process as invoked on -on the command line. -@example -SLAVE_PATH absolute: - slave binary image is SLAVE_PATH -SLAVE_PATH relative and MASTER_DIR absolute: - slave binary image is MASTER_DIR/SLAVE_PATH -SLAVE_PATH relative and MASTER_DIR relative: - slave binary image is $PWD/MASTER_DIR/SLAVE_PATH -SLAVE_PATH is - and master process invoked on command line as MASTER_BIN: - slave binary image is MASTER_BIN (if MASTER_BIN is absolute path) - or $PWD/MASTER_BIN (if MASTER_BIN is relative path) -If the procgroup line contains command line arguments, - those command line arguments are passed to the slave application - as its first arguments, and any arguments on the master command - line are appended to the list of arguments. -@end example -TOP-C assumes that your -application does not change the working directory before -calling @code{TOPC_init()}. - -By default, @samp{TOP-C} uses the procgroup file in the current directory. -You can choose an explicit procgroup file via a program -variable, @code{TOPC_OPT_procgroup="/project/myprocgroup";}, or via a -command-line option, -@code{/project/sparc/app --TOPC-procgroup=/project/myprocgroup}. -@xref{Command Line Options}. - -If the command line option @option{--TOPC-num-slaves=@var{int}} -is given, and if @var{int} is less than the number of -slaves in the @file{procgroup} file, then @samp{TOP-C} will -use the first @var{int} slaves from the file. If @var{int} -is more than the number of slaves in the @file{procgroup} file, -then @samp{TOP-C} will use all of the given slaves, and then -create additional processes on the remote hosts, by -returning to the beginning of the @file{procgroup} file and -re-reading the list of slave host/binaries until @var{int} -slaves have been created in all. - -It is recommended to use only @code{localhost} during initial -development. - -@vindex SSH - -The environment variable, @env{SSH} (default value @code{ssh}) is used to -invoke the remote host. If, for example, your site uses @code{rsh} -instead of @code{ssh}, the following code, when executed -before @code{TOPC_init()} will produce this effect. -@example - putenv("SSH=rsh"); -@end example -Alternatively, type @command{SSH=rsh} (sh/bash, etc.) or -@command{setenv SSH rsh} -(csh/tcsh, etc.) in the UNIX shell before invoking the TOP-C application. - -@node Slaves Fail to Start, , Procgroup Files, Invoking a TOP-C Application in Distributed Memory -@subsection If Slaves Fail to Start - -@vindex /tmp/mpinu-ssh -@cindex debugging @samp{TOP-C} @option{--mpi} applications that fail to start -@cindex distributed memory, fails to start -@cindex mpinu-ssh for debugging slave startup -@cindex slave startup in distributed memory, difficulties - -If some slave processes start, but not others, then try executing -the following simple program. -@example -#include "topc.h" -int main(int argc, char *argv) @{ - char host[100]; - printf("%s connecting ...\n", gethostname(host, 99)); - TOPC_init(&argc, &argv); - printf("... %s connected.\n", gethostname(host, 99)); - TOPC_finalize(); -@} -@end example - -If the slave processes fail to start up or fail to respond to the master -and if you are using @samp{MPINU} (default configuration of @samp{TOP-C}, - one other debugging resource is available. -If an application fails to start up, then @samp{TOP-C} leaves in -the @file{/tmp} directory a file -@display - @file{/tmp/mpinu-ssh.$$} -@end display -where @code{$$} is the process id. The file shows the commands that -@samp{TOP-C/mpinu} tried to use to start up the slave process. By -examining and even manually executing those commands from the terminal, -one can often deduce the difficulty in creating the slave processes. - -Test the ability of your computer facility to execute remote processes -@emph{without passwords} by typing: @code{ssh REMOTE_HOST pwd}. -If the problem is that @code{ssh} is not working, try setting -the environment variable @env{SSH} to @code{ssh} or other site-specific -setting. -@xref{Procgroup Files}. - -If you are using @code{ssh} (default if the environment variable -@env{SSH} is not set), and if it requires a password then the following -commands within UNIX may allow ssh to operate on your local cluster -without passwords. -@example -ssh-keygen -t dsa [accept default values] -ssh-keygen -t rsa [accept default values] -cat ~/.ssh/id*.pub >> ~/.ssh/authorized_keys -@end example -For security, be sure that ~/.ssh has no read permission for other users. - -@node Invoking a TOP-C Application in Shared Memory, , Invoking a TOP-C Application in Distributed Memory, Compiling and Invoking TOP-C Applications -@section Invoking a TOP-C Application in Shared Memory - -@cindex memory model, shared, compiling -@cindex compiling the shared memory model -@cindex --pthread argument to @code{topcc/topc++} - -Linking using the @option{--pthread} option allows an -application to execute using POSIX threads. -Note that the @samp{TOP-C} memory model for shared memory has some small -variations from the distributed memory model. -The largest potential -source of incompatibility is if your @code{DoTask()} routine modifies -any global or static variables. If so, such variables will -need to be declared @dfn{thread private}. -Check your source code to see if this -affects you. - -Second, if you encounter insufficient performance, you may consider -experimenting with @emph{fine grain thread parallelism}. The default -@samp{TOP-C} algorithm for shared memory allows @code{UpdateSharedData()} -to begin executing only after each current invocation of @code{DoTask()} -completes. This can be modified by an application for -finer grain parallelism. @xref{Shared Memory -Model, @samp{TOP-C} Shared Memory Model, Optimizing TOP-C Code for -the Shared Memory Model}, for details in either of the above cases. - -Note also that while a @samp{TOP-C} application object file can usually be -linked using an arbitrary @samp{TOP-C} memory model without recompiling, -there are some circumstances where you may first need to recompile the -application source using @command{topcc --pthread}. - -@node Debugging and Tracing, Performance and Long Jobs, Compiling and Invoking TOP-C Applications, Top -@chapter Debugging and Tracing - -@cindex debugging -@cindex SIGPIPE signal handler not recognized - -If the difficulty is that the application fails to start in the distributed -memory model (using @command{topcc --mpi}), then read -@ref{Slaves Fail to Start}, for some -debugging techniques. Note also that TOP-C ignores SIGPIPE. This is -because TOP-C employs the SO_KEEPALIVE option, and the master process -would otherwise die if a slave process were to die. SO_KEEPALIVE -is needed for robustness when slave processes execute long tasks without -communicating with the master process. -The rest of this section assumes that the -application starts up correctly. - -@menu -* Debugging by Limiting Parallelism:: -* Debugging with --TOPC-safety:: -* TOP-C and POSIX signals:: -* Tracing Messages:: -* Stepping Through a Slave:: -* Segmentation faults:: -@end menu - -@node Debugging by Limiting Parallelism, Debugging with --TOPC-safety, Debugging and Tracing, Debugging and Tracing -@section Debugging by Limiting the Parallelism -@cindex --TOPC-num-slaves, example - -First, compile and link your code -using @command{topcc --seq --TOPC-safety=20 -g -O0}, -and make sure that your application works correctly sequentially. Only after -you have confidence in the correctness of the sequential code, should you -begin to debug the parallel version. - -If the application works correctly in sequential mode, one should debug -in the context of a single slave. It is convenient to declare the -remote slave to be @code{localhost} in the @file{procgroup} file, in order -to minimize network delays and so as not to disturb users of -other machines. In this case, the code is ``almost'' -sequential. An easy way to do this is: -@example - topcc --mpi --TOPC-num-slaves=1 -g -O0 -@end example - -Next, one should test on two slaves, and finally all possible slaves. - -@node Debugging with --TOPC-safety, TOP-C and POSIX signals, Debugging by Limiting Parallelism, Debugging and Tracing -@section Debugging with @option{--TOPC-safety} - -@cindex --TOPC-safety for debugging -@cindex debugging, --TOPC-safety - -The command-line option @option{--TOPC-safety=@var{val}} provides assistance -for debugging parallel programs. At higher values of @var{val}, -optimizations that do not change the correctness of the program are -converted to safer equivalents. A good strategy is to -test if @option{--TOPC-safety=20} causes the bug to go away, and if so, -progressively lower @var{val} toward zero, until the bug reappears. -The value at which the bug reappears indicates what @samp{TOP-C} -optimization feature is not being used correctly. If the bug still -exists at @option{--TOPC-safety=20}, one should next try compiling -with the @option{--seq} flag and use a debugger to debug the sequential code. - -The effects due to different safety levels are subject to change. -To see the current effects, invoke any TOP-C application as follows -@example - ./a.out --TOPC-help --TOPC-verbose -@end example -and you will see something like: -@example - safety: >=0: all; >=2: no TOP-C memory mgr (uses malloc/free); - >=4: no TOPC_MSG_PTR; >=8: no aggreg.; - >=12: no TOPC_abort_tasks; >=14: no receive thread on slave; - >=16: default atomic read/write for DoTask, UpdateSharedData; - =19: only 2 slaves; >=20: only 1 slave - (AGGREGATION NOT YET IMPLEMENTED) -@end example - -Values higher than 4 cause @code{TOPC_MSG_PTR()} to act as -if @code{TOPC_MSG()} was called instead. -Values higher than 12 cause @code{TOPC_abort_tasks()} to have no effect. -Values higher than 14 imply that a single thread in the slave process -must receive messages and execute @code{DoTask()}. Normally, -@samp{TOP-C} arranges to overlap communication and computation on the -slave by setting up a separate thread to receive and store messages from -the master. -Values higher than 15 imply that @samp{TOP-C} will use malloc instead -of trying to do its -own memory allocation (which is optimized for @samp{TOP-C} memory -patterns). -Values higher than 16 imply that all of @code{DoTask} acts as -if a read lock was placed around it, and all of @code{UpdateSharedData} -has a write lock placed aound it. (This has an effect only -in the shared memory model where calls to @code{TOPC_ATOMIC_READ/WRITE} -are ignored.) -At values of 19 and 20, the number of slaves is reduced to -2 and to 1, regardless of the setting of @option{--TOPC-num-slaves} -and the specification in a @file{procgroup} file. - -@node TOP-C and POSIX signals, Tracing Messages, Debugging with --TOPC-safety, Debugging and Tracing -@section TOP-C and POSIX signals -@cindex signals and TOP-C -@cindex SIGPIPE -@cindex SIGPINT -@cindex SIGALRM - -If an application handles its own signals, this can create a clash -with the TOP-C. -In the distributed memory model (--mpi), @samp{TOP-C} will create its own -signal handlers for @code{SIGALRM}. This is used in conjunction with -@code{alarm()} to eventually kill runaway -slave processes. In addition, if using @samp{MPINU}, -the built-in MPI subset, @samp{TOP-C} will create its own handler -for @code{SIGPIPE}. This is in order to allow the master -process to detect dead sockets, indicating dead slaves. -Finally, for short periods, @samp{MPINU} -will disable the use of @code{SIGINT} around calls to @code{select()}. -Nevertheless, if a SIGINT is sent during this period, TOP-C will pass the -signal on to the original SIGINT handler of the application. - -@samp{TOP-C} does not modify signal handlers in the sequential (--seq) -or shared memory (--pthread) models. Furthermore, if a different -MPI (other than MPINU) is used with TOP-C, TOP-C will only handle -@code{SIGALRM}. However, the other MPI may handle signals itself. -@xref{Using a Different MPI with TOP-C}. - -@node Tracing Messages, Stepping Through a Slave, TOP-C and POSIX signals, Debugging and Tracing -@section Tracing Messages - -@cindex TOPC_OPT_trace, usage for dynamically debugging messages -@cindex TOPC_OPT_trace_input -@cindex TOPC_OPT_trace_result - -If a bug appears as one moves to greater parallelism, one should trace -messages between master and slaves (for any number of slaves). -This is the default, and it can be enabled on the command line with: -@example - ./a.out --TOPC-trace=2 @var{args} -@end example -The variable @code{TOPC_OPT_trace} can be set in the code to -dynamically turn tracing on (1 or 2) and off (0) during a single run. -A trace value of 2 causes @samp{TOP-C} to invoke the application-defined -trace functions pointed to by -@code{TOPC_OPT_trace_input/result}. If the application has not -defined trace functions, or if @code{TOPC_OPT_trace} is 1, then -the @samp{TOP-C} default trace functions are invoked. -All message traces -are displayed by the master at the time that the master sends or -receives the corresponding message. - -@deftypevar {void (*)(void *input)} TOPC_OPT_trace_input -@deftypevarx {void (*)(void *input, void *output)} TOPC_OPT_trace_result -@comment void (*TOPC_OPT_trace_action)(TOPC_ACTION action); - Global pointer (default is @code{NULL}) to function returning - @code{void}. User can - set it to his or her own trace function to print out - data-specific tracing information in addition to generic - message tracing of @code{TOPC_trace}. -@end deftypevar -@example -EXAMPLE: if you pass integers via @code{TOPC_MSG()}, define - @code{TOPC_trace_input()} as: -@group - void mytrace_input( int *input ) @{ - printf("%d",*input); - @} - TOPC_OPT_trace_input = mytrace_input; -@end group -@end example - -Note that the term @samp{result} in @code{TOPC_OPT_trace_result} -refers to an @samp{(input, output)} pair. - -@node Stepping Through a Slave, Segmentation faults, Tracing Messages, Debugging and Tracing -@section Stepping Through a Slave Process with @samp{gdb} - -@cindex --TOPC-slave-wait, debugging a slave process with @samp{gdb} - -If you find the master hanging, waiting for a slave message, then the -probable cause is that @code{DoTask()} is doing something bad (hanging, -infinite loop, bus/segmentation error, etc.). First try to isolate the -bug using a symbolic debugger (e.g. @samp{gdb}) and the sequential memory -model. If your intended application is the shared memory model, you can also -use @samp{gdb} to set a breakpoint in your @samp{DoTask} routine -or at the @samp{TOP-C} invocation, @code{do_task_wrapper}. - -If the bug only appears in the distributed memory model, you can still -symbolically debug @code{DoTask()} using @samp{gdb} (the GNU C debugger) -and its @code{attach} command -(@pxref{Running, , Attach, gdb, The GNU debugger}), -which allows you to attach and debug a separate running process. This -lets you debug a running slave, if it is running o the same processor. -For this strategy, you will want the slave to delay executing to give -you time to execute gdb and attach on the remote host or remote thread. -The command line option @option{--TOPC-slave-wait=30} will force -the slave to wait 30 seconds before processing. - -In applying this debugging strategy to an application @samp{./a.out}, -one might see: -@example - [ Execute ./a.out in one window for master process ] - gdb ./a.out - (gdb) run --TOPC-trace=1 --TOPC-safety=19 --TOPC-slave-wait=30 @var{args} - - [ In a second window for a slave process on a different host, now type: ] - ps - ... - 1492 p4 S 0:00 a.out @var{args} localhost 6262 -p4amslave - gdb a.out - ... - (gdb) break do_task_wrapper - Breakpoint 1 at 0x80492ab: file ... - [ `break slave_loop' is also useful. This calls do_task_wrapper ] - (gdb) attach 1492 - Attaching to program `a.out', process 1492 - 0x40075d88 in sigsuspend () - [ After 30 sec's, traced messages in master window appear, ] - [ for slave, type: ] - (gdb) continue - Continuing. - Breakpoint 1, DoTask (input=0x805dc50) at ... - - [ Continue stepping through master and slave processes in 2 windows ] -@end example - -If you try to @dfn{attach} to a second slave process after attaching -to a first slave process, @samp{gdb} will offer to kill your first -slave process. To avoid this situation, remember to execute @code{detach} -before attaching a second slave process. - -@node Segmentation faults, , Stepping Through a Slave, Debugging and Tracing -@section Segmentation faults and other memory problems - -@cindex efence, debugging memory management -@cindex debugging memory management with efence -@cindex SIGSEGV, debugging with efence -@cindex segmentation fault, debugging with efence - -Memory bugs are among the most difficult to debug. -If you suspect such a bug (perhaps because you are using @code{TOPC_MSG_PTR}), -and you fail to free previously malloc'ed memory, that is a memory leak. -If you access a buffer after freeing it, this may cause -a segmentation error at a later stage in the program. - -If you suspect such a bug (and maybe you should if nothing else -worked), it is helpful to use a @emph{malloc or memory debugger}. -An excellent recent memory debugger is -@samp{valgrind}@footnote{@var{valgrind} is available at -@url{http://www.valgrind.kde.org}.}. -@samp{valgrind} can be directly applied to an application binary, -without recompilation or relinking. - -An older debugger is @samp{efence},@footnote{@var{efence} is available at -@url{http://sources.isc.org/devel/memleak/efence}.} -@command{topcc} -provides direct support for @samp{efence}. -@samp{TOP-C} will link with the efence library if @code{--efence} -is passed to @command{topcc} or @command{topc++}. -@example - topcc --efence ... -@end example -This causes all calls to @code{malloc} and @code{free} to -be intercepted by the @samp{efence} version. -Modify the line @code{LIBMALLOC=} in @command{topcc} or @command{topc++} -if you use a different library. - -@node Performance and Long Jobs, Advanced Features, Debugging and Tracing, Top -@chapter Performance and Long Jobs - -@menu -* Dropping Slow or Dead Slaves:: -* Strategies for Greater Concurrency:: -* Improving Performance:: -* Long Jobs:: -@end menu - -@node Dropping Slow or Dead Slaves, Strategies for Greater Concurrency, Performance and Long Jobs, Performance and Long Jobs -@section Dropping Slow or Dead Slaves - -When TOP-C recognizes a dead slave the master terminates communication with -that slave, and resubmits the task of that slave to a different slave. -(Currently, as of TOP-C 2.5.2, if a slave dies near the end of a computation -and after all tasks have been generated, TOP-C may fail to recognize -that slave.) - -It is sometimes unclear whether a slave process is dead or slower than -others. Even a slow slave process may hurt overall performance by -causing delays for other processes. -TOP-C internally declares a slave process to be "slow" if there are N -slaves, and if 3*N other tasks return after the given slave task is "due". -If a slow slave has not returned by @var{slave-timeout} seconds -(see @ref{Command Line Options}), then -the slave is considered dead. The master process sends no further tasks -to that slave, and sends a replicate of the original task to a new -slave. - -@node Strategies for Greater Concurrency, Improving Performance, Dropping Slow or Dead Slaves, Performance and Long Jobs -@section Strategies for Greater Concurrency - -@table @asis -@item Strategy 1: SEMI-INDEPENDENT TASKS: - Define tasks so that most task outputs do not require any update. - This is always the case for trivial parallelism (when tasks are - independent of each other). It is also often the case for many - examples of search and enumeration problems. -@end table - -@table @asis -@item Strategy 2: CACHE PARTIAL RESULTS: - Inside @code{DoTask()} and @code{UpdateSharedData()}, save partial - computations in global private variables. Then, in the event of a - @code{REDO} action, @samp{TOP-C} guarantees to invoke - @code{DoTask()} again on the - original slave process or slave thread. That slave may then use - previously computed partial results in order to shorten the required - computation. Note that pointers on the slave to input and output - buffers from previous @code{UPDATE} actions and from the original task - input will no longer be valid. The slave process must copy - any data it wishes to cache to global variables. - In the case of the shared memory model, those global variables must be - thread-private. (@pxref{Thread-Private Global Variables}) - Note the existence of @code{TOPC_is_REDO()} for testing for a @code{REDO} - action. -@end table - -@table @asis -@item Strategy 3: MERGE TASK OUTPUTS: - Inside @code{CheckTaskResult()}, the master may merge two or more task - outputs in an application independent way. This may avoid the - need for a @code{REDO} action, or it may reduce the number of required - @code{UPDATE} actions. -@end table - -@node Improving Performance, Long Jobs, Strategies for Greater Concurrency, Performance and Long Jobs -@section Improving Performance - -@cindex --TOPC-aggregated-tasks, usage -@cindex aggregation of tasks -@cindex network latency, overcoming it -@cindex finer grain parallelism - -If your application runs too slowly due to excessive time for communication, -consider running multiple slave processes on a single processor. This -allows one process to continue computing while another is communicating -or idle waiting for a new task to be generated by the master. - -If communication overhead or idle time is still too high, consider if it is -possible to increase the granularity of your task. TOP-C can -aggregating several consecutive tasks as a single larger -task to be performed by a single process. This amortizes the network -latency of a single network message over several tasks. -For example, you can do combine 5 tasks -by invoking @option{--TOPC-aggregated-tasks=5} on -the command line of the application. Alternatively, execute the statement: -@example - TOPC_OPT_aggregated_tasks=5; -@end example -before @code{TOPC_master_slave()}. -In this situation, the five task outputs will also be bundled -as a single network message. Currently (TOP-C 2.5.2), this -works only if all tasks return @code{NO_ACTION}. TOP-C will signal -an error if @code{TOPC_OPT_aggregated_tasks} > 1 and any action -other than @code{NO_ACTION} is returned. - -Other useful techniques that may improve performance of certain -applications are: -@enumerate -@item - set up multiple slaves on each processor (if slave processors - are sometimes idle) -@item - re-write the code to bundle a set of tasks as a single task - (to improve the granularity of your parallelism) -@end enumerate - -@table @asis -@item PERFORMANCE ISSUE FOR MPI: -If you have a more efficient version of @samp{MPI} (perhaps a vendor version -tuned to your hardware), consider replacing @code{LIBMPI} in -@file{.../top-c/Makefile} by your vendor's @file{limbpi.a} or -@file{libmpi.so}, and delete or modify the the @code{LIBMPI} target in the -@file{Makefile}. -Alternatively, see the appendix, -@ref{Using a Different MPI with TOP-C}, -for a more general way to use a different MPI dialect. -@end table -@table @asis -@item PERFORMANCE ISSUE FOR SMP (POSIX threads): -Finally under @samp{SMP}, there is an important performance issue -concerning the interaction of @samp{TOP-C} with the operating system. -First, the vendor-supplied compiler, @code{cc}, is recommended over -@code{gcc} for @samp{SMP}, due to specialized vendor-specific -architectural issues. Second, if a thread completes its work before -using its full scheduling quantum, the operating system may yield the -CPU of that thread to another thread --- potentially including a thread -belonging to a different process. There are several ways to defend -against this. One defense is to insure that the time for a single task -is significantly longer than one quantum. Another defense is to ask the -operating system to give you at least as many "run slots" as you have -threads (slaves plus master). Some operating systems use -@code{pthread_setconcurrency()} to allow an application to declare this -information, and @samp{TOP-C} invokes @code{pthread_setconcurrency()} -where it is available. However, other operating systems may have -alternative ways of tuning the scheduling of threads, and it is -worthwhile to read the relevant manuals of your operating system. -@end table - -@node Long Jobs, , Improving Performance, Performance and Long Jobs -@section Long Jobs and Courtesy to Others - -@cindex --TOPC-slave-timeout, for long jobs and runaway jobs -@cindex SIGALRM, raised by @samp{TOP-C} - -In the distributed memory model, infinite loops and broken socket -connections tend to leave orphaned processes running. -In the @samp{TOP-C} distributed memory model, -a slave times out if a task lasts longer than -a half hour or if the master does not reply -in a half hour. -This is implemented with the UNIX system call, @code{alarm()}. - -A half hour (1800 seconds) is the default timeout period. -The command line option @code{--TOPC-slave-timeout=@var{num}} -allows one to change this default. If @var{num} is 0, -then there is no timeout and @samp{TOP-C} makes no calls -to @code{SIGALRM}. - -The application writer may also find some of the following UNIX system calls -useful for allowing large jobs to coexist with other applications. -@table @asis -@item @code{ setpriority(PRIO_PROCESS,getpid(),@var{prio}) } -@code{#include @* -#include }@* ---- @var{prio} = 10 still - gives you some CPU time. @var{prio} = 19 means that any job of - higher priority always runs before you. Place in @code{main()}. -@item @code{ setrlimit(RLIMIT_RSS, &@var{rlp}) } -@code{#include @* -struct rlimit rlp;@* -rlp.rlim_max = rlp.rlim_cur = @var{SIZE};}@* ---- @var{SIZE} is RAM limit (bytes). If your system has - significant paging, the system will prefer to keep your process - from growing beyond SIZE bytes of resident RAM. Even if you set - nice to priority 20, this is still important. Otherwise you may - cause someone to page out much of his or her job in your favor during - one of your infrequent quantum slices of CPU time. Place in - @code{main()}. (Not all operating systems enforce this request.) -@end table - -@node Advanced Features, TOP-C Raw Interface, Performance and Long Jobs, Top -@chapter Advanced Features of @samp{TOP-C} - -It is best to postpone reading this section until the basic features -discussed in the previous chapters are clear. - -@menu -* Testing for Task Continuations:: -* Aborting Tasks:: -* Allocation of Task Buffers:: -* Shared Memory Model:: -* Sequential Memory Model:: -* Caveats:: -@end menu - -@node Testing for Task Continuations, Aborting Tasks, Advanced Features, Advanced Features -@section Testing for Task Continuations and Redos - -@cindex task continuation, testing -@cindex CONTINUATION, testing for -@cindex REDO, testing for - -@deftypefun TOPC_BOOL TOPC_is_REDO ( void ) -@deftypefunx TOPC_BOOL TOPC_is_CONTINUATION ( void ) - These return 0 (false) or 1 (true), according to whether the current - call to @code{DoTask()} was a result of a @code{REDO} - or @code{CONTINUATION()} action, respectively. The result is - is not meaningful if called outside of @code{DoTask()}. -@end deftypefun - -@node Aborting Tasks, Allocation of Task Buffers, Testing for Task Continuations, Advanced Features -@section Aborting Tasks - -@cindex aborting tasks - -@deftypefun void TOPC_abort_tasks ( void ) -@deftypefunx TOPC_BOOL TOPC_is_abort_pending ( void ) - @code{TOPC_abort_tasks()} should be called in @code{CheckTaskResult()}. - @samp{TOP-C} then makes a best effort (no guarantee) to notify each - slave. TOP-C does not directly abort tasks. However, - @code{TOPC_is_abort_pending()} returns 1 (true) - when invoked in @code{DoTask()} on a slave. A typical - @code{DoTask()} callback uses this to poll for an abort request - from the master, upon which it returns early with a special - task output. At the beginning of the next new task, @code{REDO} - or @code{CONTINUATION}, @samp{TOP-C} resets the pending abort - to 0 (false). See @file{examples/README} of the @samp{TOP-C} - distribution for example code. -@end deftypefun - -@node Allocation of Task Buffers, Shared Memory Model, Aborting Tasks, Advanced Features -@section Memory Allocation for Task Buffers - -The principle of memory allocation in @samp{TOP-C} is that if an -application allocates memory, then it is the responsibility of the -application to free that memory. This issue typically arises around the -issue of task buffers (@pxref{Task Buffers}) and calls -to @code{TOPC_MSG(@var{buf},@var{buf_size})}. An application -often calls @code{@var{buf} = malloc(...);} or -@code{@var{buf} = new ...;} (in C++) -and copies data into that buffer before the call to @code{TOPC_MSG}. -Since the last action of @code{GenerateTaskInput()} or @code{DoTask()} -is typically to return @code{TOPC_MSG(@var{buf},@var{buf_size})}, -there remains the question of how to free @var{buf}. - -@menu -* Avoiding malloc:: -* Large Buffers and TOPC_MSG_PTR:: -* Allocation for TOPC_MSG_PTR:: -* Marshaling Complex Data Structures:: -@end menu - -@node Avoiding malloc, Large Buffers and TOPC_MSG_PTR, Allocation of Task Buffers, Allocation of Task Buffers -@subsection Avoiding @code{malloc} and @code{new} with Task Buffers - -The best memory allocation solution for task buffers is to implement the -buffers as local variables, and therefore on the stack. This avoids the -need for @code{malloc} and @code{new}, and the question of how to later -free that memory. -If you use @code{TOPC_MSG} (as opposed to @code{TOPC_MSG_PTR}, -@pxref{Large Buffers and TOPC_MSG_PTR}), then recall that @code{TOPC_MSG} -copies its buffer to a separate @code{TOP-C} space. For example, -@example -@{ int x; - ... - return TOPC_MSG(&x, size_of(x)); -@} -@end example - -@cindex variable size task buffers -@cindex task input/output buffers, variable size - -If your task buffer is of fixed size, one can allocate it as a character -array on the stack: @code{char buf[BUF_SIZE];}. -If your buffer contains variable size data, consider using -@code{alloca} in place of @code{malloc} to allocate on the -stack. -@example -@{ ... - buf = alloca(buf_size); - return TOPC_MSG(buf, buf_size); -@} -@end example - -In all of the above cases, there is no need to free the buffer, since -@code{TOPC_MSG} will make a @samp{TOP-C}-private copy and the -stack-allocated buffer will disappear when the current routine exits. -Note that @code{alloca} may be unavailable on your system. -Alternatively, the use of @code{alloca} may be undesirable due to very -large buffers and O/S limits on stack size. In such cases, consider the -following alternative. -@example -@{ TOPC_BUF tmp; - ... - buf = malloc(buf_size); - tmp = TOPC_MSG(buf, buf_size); - free(buf); - return tmp; -@} -@end example - -@node Large Buffers and TOPC_MSG_PTR, Allocation for TOPC_MSG_PTR, Avoiding malloc, Allocation of Task Buffers -@subsection Using @code{TOPC_MSG_PTR()} to Avoid Copying Large Buffers - -@cindex TOPC_MSG_PTR() -@cindex large message buffers - -If the cost of copying a large buffer is a concern, @samp{TOP-C} provides -an alternative function, which avoids copying into @samp{TOP-C} space. - -@deftypefun TOPC_BUF TOPC_MSG_PTR ( void *@var{buf}, int @var{buf_size} ) - Same as @code{TOPC_MSG()}, except that it does not copy - @var{buf} into @samp{TOP-C} space. It is the responsibility - of the application not to free or modify @var{buf} as long - as @samp{TOP-C} might potentially pass it to an - application callback function. -@end deftypefun - -@code{TOPC_MSG_PTR()} is inherently dangerous, if the application -modifies or frees a buffer and @samp{TOP-C} later passes that buffer -to a callback function. It may be useful when the cost of copying -large buffers is an issue, or if one is concerned about @samp{TOP-C} -making a call to @code{malloc()}. Note that the invocation -@example - ./a.out --TOPC-safety=4 -@end example -@noindent -automatically converts all calls to @code{TOPC_MSG_PTR()} into -calls to @code{TOPC_MSG()}. This is useful in deciding -if a bug is related to the use of @code{TOPC_MSG_PTR()}. - -An application should not pass a buffer on the stack to @code{TOPC_MSG_PTR()}. -This can be avoided either by declaring a local variable to be -@samp{static}, or else using a global variable (or a class member -in the case of C++). In such cases, it is the responsibility of the -application to dynamically create and free buffers. -An example of how this can be done follows in the next section. - -Note that if the application code must also be compatible with the -shared memory model, then the static local variable or global variable -must also be @dfn{thread-private} -(@ref{Thread-Private Global Variables}). - -For examples of coding with @code{TOPC_MSG_PTR()} that are compatible -with all memory models, including the shared memory model, -see @file{examples/README} and the corresponding examples -in the @samp{TOP-C} distribution. - -@node Allocation for TOPC_MSG_PTR, Marshaling Complex Data Structures, Large Buffers and TOPC_MSG_PTR, Allocation of Task Buffers -@subsection Allocation and Freeing of Task Buffers for @code{TOPC_MSG_PTR()} - -Recall the syntax for creating a message buffer of type @code{TOPC_BUF} -using -@code{TOPC_MSG_PTR(@var{buf}, @var{buf_size})}. The two callback functions -@code{GenerateTaskInput()} and @code{DoTask()} both return such a -message buffer. In the case of -@code{GenerateTaskInput()}, @samp{TOP-C} saves a copy of the buffer, -which becomes an input argument to @code{CheckTaskResult()} -and to @code{UpdateSharedData} on the master. -Hence, if @var{buf} points to a temporarily allocated buffer, -it is the responsibility of the @samp{TOP-C} callback function to free the -buffer only @emph{after} the callback function has returned. -This seeming contradiction can be easily handled by the following code. -@sp 1 -@example - TOPC_BUF GenerateTaskInput() @{ - static void *buf = NULL; - if ( buf == NULL ) @{ malloc(buf_size); @} - ... [ Add new message data to buf ] ... - return TOPC_MSG_PTR(buf, buf_size); - @} -@end example -@sp 1 -If @code{buf_size} might vary dynamically between calls, the following -fragment solves the same problem. -@example - TOPC_BUF GenerateTaskInput() @{ - static void *buf = NULL; - if ( buf != NULL ) @{ free(buf); @} - ... [ Compute buf_size for new message ] ... - buf = malloc( buf_size ); - ... [ Add new message data to buf ] ... - return TOPC_MSG_PTR(buf, buf_size); - @} -@end example - -Note that @code{buf}@ is allocated as a @emph{static} local -variable. @samp{TOP-C} restricts the @var{buf} of -@code{TOPC_MSG_PTR(@var{buf}, @var{buf_size})} to point to a buffer that is in -the heap (not on the stack). Hence, @var{buf} must @emph{not} point to -non-static local data. - -@comment TEXT FOR REUSE HERE OR ELSEWHERE: -@ignore - -@comment @node Modifying Task Buffers, Local Shared Data, Allocation for TOPC_MSG_PTR, Allocation of Task Buffers -@comment @subsection Modifying Task Buffers in @code{CheckTaskResult()} - -When a @samp{TOP-C} callback function is passed a -@dfn{task input} or @dfn{task output}, that buffer is a pointer -into @samp{TOP-C} space. (As an exception, if the shared memory model -is used with @code{TOPC_MSG_PTR()}, then the buffer will point into -the application memory space.) The callback function may freely -use or even modify the data in the buffer, but the buffer -pointer will no longer be valid after the callback function returns. -If a later invocation of a callback function wishes to use the data -in the buffer, the @samp{TOP-C} application must cache a private -copy and point to it with a global variable (or with a @dfn{thread-private -global variable} (@pxref{Thread-Private Global Variables}) if the application -is also to work with the shared memory model). - -@comment @node Local Shared Data, Marshaling Complex Data Structures, Allocation for TOPC_MSG_PTR, Allocation of Task Buffers -@comment @subsection Local Shared Data - -Sometimes your shared data may be on the stack, instead of in a global -variable. -In order to make this local data accessible to a @samp{TOP-C} callback -function, such as @code{UpdateSharedData()}, you will need to create a global -variable pointing to your local shared data. The example below makes -the local shared data in the array @code{data[]} in the function -@code{foo()} available to the callback function -@code{UpdateSharedData()}. - -@example - int *global_copy_of_data; - void UpdateSharedData( int *input, void *output) @{ - global_copy_of_data[*input] = output; - @} - int foo() @{ - int data[SIZE]; - global_copy_of_data = data; - TOPC_master_slave(...); - @} -@end example - -Of course, @samp{C++} provides a more natural way to handle this by -placing @code{global_copy_of_data}, @code{foo} and -@code{UpdateSharedData} in a single class. - -@end ignore - -@node Marshaling Complex Data Structures, , Allocation for TOPC_MSG_PTR, Allocation of Task Buffers -@subsection Marshaling Complex Data Structures into @samp{TOP-C} Task Buffers - -If you use a distributed memory model and the buffer pointed to by -@code{input} includes fields with their own pointers, the application -must first follow all pointers and copy into a new buffer all data -referenced directly or indirectly by @code{input}. The new buffer can -then be passed to @code{TOPC_MSG()}. This copying process is called -@dfn{marshaling}. @xref{Task Buffers, , -Marshaling and Heterogeneous Architectures}. - -If following all pointers is a burden, then one can -load the application on the master and slaves at a common absolute -address, and insure that all pointer references have been initialized -before the first call to @code{TOPC_master_slave()}. In @samp{gcc}, -one specifies an absolute load address with code such as: -@example - gcc -Wl,-Tdata -Wl,-T@var{hex_addr} ... -@end example -These flags are for the data segment. If the pointers indirectly -reference -data on the stack, you may have to similarly specify stack absolute addresses. -Choosing a good @var{hex_addr} for all machines may be a matter of trial -and error. In a test run, print out the absolute addresses of some -pointer variables near the beginning of your data memory. - -Specifying an absolute load address has many risks, such as if -the master and slaves use different versions of the operating system, -the compiler, other software, or different hardware configurations. -Hence, this technique is recommended only as a last resort. - -@ignore -@comment @node Experimental Version, , Caveats, Miscellaneous Issues -@comment @subsection Notes on Experimental Version -@example - -/* EXPERIMENTAL: not currently supported */ -request_recv_buf(int buf_size) - useful only for distributed memory. - Ask @samp{TOP-C} and socket interface for larger buffer for large messages. -@end example - -There are also situations in which one wishes to add new slaves during -a currently running session (for advanced users, only). This is made -possible for homogeneous architectures by invoking the loader. -This was written jointly by Gene Cooperman and Victor Grinberg. - -The @file{.../top-c/loader/config.h} file should be modified with the network -address of the running job: @var{MASTERNAME} and @var{MASTERPORT} -(and currently change them in C files or use command line args) -Other options can be left as default. One then recompiles: -@example - (cd .../top-c/loader; make; cd .../top-c; make @var{APPLICATION}) -@end example -For an example @var{APPLICATION} type: @code{make parfactor-loader} - -Finally, one runs the application: -@example - ./a.out -masterport @var{PORTNUMBER} -@end example -and on a remote processor of the same architecture, one can -download the binary, @file{.../top-c/loader}, and execute: -@example - ./loader -p @var{PORTNUMBER} -@end example -The loader application will continue to run until killed, so that the -machine will continue to act as a CPU server for further jobs. - -@var{PORTNUMBER} will default to @var{MASTERPORT}. The provision for -adding @var{PORTNUMBER} to the command line is provided only in case the -default port is in use. - -@end ignore - -@node Shared Memory Model, Sequential Memory Model, Allocation of Task Buffers, Advanced Features -@section Optimizing TOP-C Code for the Shared Memory Model - -@cindex memory model, shared -@cindex shared memory model - - The @samp{TOP-C} programmer's model changes slightly for shared -memory. With careful design, one can use the same application source -code both for distributed memory and shared memory architectures. -Processes are replaced by threads. @code{UpdateSharedData()} is -executed only by the master thread, and not by any slave thread. As -with distributed memory, @code{TOPC_MSG()} buffers are copied to -@samp{TOP-C} space (shallow copy). As usual, the application is responsible -for freeing any application buffers outside of @samp{TOP-C} space. -Furthermore, since the master and slaves share memory, @samp{TOP-C} -creates the slaves only during the first call to master_slave. If a -slave needs to initialize any private data (see -@code{TOPC_thread_private}, below), then this can be done by the slave -the first time that it gains control through @code{DoTask()}. - -Two issues arise in porting a distributed memory -@samp{TOP-C} application to shared memory. -@enumerate -@item - reader-write synchronization: @code{DoTask()} must not read - shared data while @code{UpdateSharedData()} (on the master) - simultaneously writes to the shared data. -@item - creating thread-private (unshared) global variables: -@end enumerate - -Most @samp{TOP-C} applications for the distributed memory model will run -unchanged in the shared memory model. In some cases, one must add -additional @samp{TOP-C} code to handle these additional issues. In all -cases, one can easily retain compatibility with the distributed memory model. - -@menu -* Reader-Writer Synchronization:: -* Thread-Private Global Variables:: -* Volatile Variables:: -* SMP Performance:: -@end menu - -@node Reader-Writer Synchronization, Thread-Private Global Variables, Shared Memory Model, Shared Memory Model -@subsection Reader-Writer Synchronization - -@cindex synchronization of threads, shared memory model -@cindex threads, synchronization in shared memory model -@cindex reader-writer synchronization -@cindex fine grain thread parallelism - -In shared memory, @samp{TOP-C} uses a classical single-writer, -multiple-reader strategy with writer-preferred for lock requests. -By default, @code{DoTask()} acts as the critical section of the -readers (the slave threads) and @code{UpdateSharedData()} acts as the -critical section of the writer (the master thread). -@samp{TOP-C} sets a read lock around all of DoTask() and a write -lock around all of UpdateSharedData(). - -As always in the @samp{TOP-C} model, -it is an error if an application writes to shared data outside -of @code{UpdateSharedData()}. Note that @code{GenerateTaskInput()} -and @code{CheckTaskResult()} can safely read the shared data without -a lock in this case, since these routines and @code{UpdateSharedData()} -are all invoked only by the master thread. - -The default behavior implies that @code{DoTask()} and -@code{UpdateSharedData()} never run simultaneously. Optionally, one -can achieve greater concurrency through a finer level of granularity -by declaring to @samp{TOP-C} which sections of code read or write -shared data. If @samp{TOP-C} detects any call to @code{TOPC_ATOMIC_READ(0)}, -@samp{TOP-C} will follow the critical sections declared by the -application inside of @code{DoTask()} and @code{UpdateSharedData()}. - -@deftypefun void TOPC_ATOMIC_READ ( 0 ) @{ @var{... C code ...} @} -@deftypefunx void TOPC_ATOMIC_WRITE ( 0 ) @{ @var{... C code ...} @} - This sets a global read or write lock in effect during the time - that @var{C code} is being executed. If a thread holds a write lock, - no thread may hold a read lock. If no thread holds a write lock, - arbitrarily many threads hold a read lock. If a thread requests - a write lock, no additional read locks will be granted until after the - write lock has been granted. See @file{examples/README} of the - @samp{TOP-C} distribution for example code. -@end deftypefun - -It is not useful to use @code{TOPC_ATOMIC_READ()} outside of @code{DoTask()} -not to use @code{TOPC_ATOMIC_WRITE()} outside of @code{UpdateSharedData()}. - -The number 0 refers to page 0 of shared data. @samp{TOP-C} currently -supports only a single common page of shared data, but future versions -will support multiple pages. In the future, two threads will be able to -simultaneously hold write locks if they are for different pages. - -The following alternatives to @code{TOPC_ATOMIC_READ()} -and @code{TOPC_ATOMIC_WRITE()} are provided for greater flexibility. - -@deftypefun void TOPC_BEGIN_ATOMIC_READ ( 0 ) -@deftypefunx void TOPC_END_ATOMIC_READ ( 0 ) -@deftypefunx void TOPC_BEGIN_ATOMIC_WRITE ( 0 ) -@deftypefunx void TOPC_END_ATOMIC_WRITE ( 0 ) - The usage is the same as for @code{TOPC_ATOMIC_READ} -and @code{TOPC_ATOMIC_WRITE}. -@end deftypefun - -In the distributed memory model of @samp{TOP-C}, all of the -above invocations for atomic reading and writing are ignored, -thus retaining full compatibility between the shared and -distributed memory models. - -@node Thread-Private Global Variables, Volatile Variables, Reader-Writer Synchronization, Shared Memory Model -@subsection Thread-Private Global Variables - -@cindex thread-private variable -@cindex global thread-private variable -@cindex static local variables and threads -@cindex @samp{THREAD_PRIVATE} - -A @dfn{thread-private} variable is a variable whose data is not -shared among threads: i.e., each thread has a private copy of -the variable. -The only variables that are thread-private by default in -shared memory are those on the stack (non-static, local variables). All -other variables exist as a single copy, shared by all threads. -This is inherent in the POSIX standard for threads in C/C++. -If @code{DoTask()} accesses any global variables or local static variables, -then those variables must be made thread-private. - -Ideally, if C allowed it, we would just write something like: -@example - THREAD_PRIVATE int myvar = 0; /* NOT SUPPORTED */ -@end example -Instead, @samp{TOP-C} achieves the same effect @samp{as if} it had -declared -@example - TOPC_thread_private_t TOPC_thread_private; -@end example -This allows the application writer to include in his or her code: -@example - typedef int TOPC_thread_private_t; - #define myvar TOPC_thread_private; - int myvar_debug() @{return myvar;@} /* needed to access myvar in gdb */ -@end example - -@samp{TOP-C} provides primitives to declare a single thread-private -global variable. @samp{TOP-C} allows -the application programmer to declare the type of that variable. -@defvar TOPC_thread_private - A pre-defined thread-private variable of type, - @code{TOPC_thread_private_t}. It may be - used like any C variable, and each thread has its own private - copy that will @emph{not} be shared. -@end defvar -@defvr Type TOPC_thread_private_t - Initially, undefined. User must define this type using @code{typedef} - if @code{TOPC_thread_private} is used. -@end defvr - -If more than one thread-private variable is desired, define -@code{TOPC_thread_private_t} as a @var{struct}, and use each -field as a separate thread-private variable. - -@noindent -EXAMPLE: - -@example -/* Ideally, if C allowed it, we would just write: - * THREAD_PRIVATE struct @{int my_rank; int rnd;@} mystruct; - * We emulate this using TOP-C's implicitly declared thread-private var: - * TOPC_thread_private_t TOPC_thread_private; - */ -typedef struct @{int my_rank; int rnd;@} TOPC_thread_private_t; -#define mystruct TOPC_thread_private -void set_info() @{ - mystruct.my_rank = TOPC_rank(); - mystruct.rnd = rand(); -@} -void get_info() @{ -foo(); - if (mystruct.my_rank != TOPC_rank()) printf("ERROR\n"); - printf("Slave %d random num: %d\n", mystruct.my_rank, mystruct.rnd); -@} -TOPC_BUF do_Task() @{ - set_info(); /* info in mystruct is NOT shared among threads */ - get_info(); - ...; -@} -@end example - -Additional examples can be found by reading -@file{examples/README} in the @samp{TOP-C} distribution. - -@node Volatile Variables, SMP Performance, Thread-Private Global Variables, Shared Memory Model -@subsection Sharing Variables between Master and Slave and Volatile Variables - -@cindex volatile C/C++ variables - -The shared memory model, like any @samp{SMP} code, -allows the master and slaves to -communicate through global variables, which are shared by default. -It is recommended not to use this feature, and instead to maintain -communication through @code{TOPC_MSG()}, for ease of code maintenance, -and to maintain portability with the other @samp{TOP-C} models -(distributed memory and sequential). If you do use your own global shared -variables between master and slaves, be sure to declare them @code{volatile}. -@example - volatile int myvar; -@end example -ANSI C requires this qualifier if a variable -may be accessed or modified by more than one thread. -Without this qualifier, your program may not run correctly. - -To be more precise, if a non-local variable is accessed more than once -in a procedure, the compiler is allowed to keep the first access value -in a thread register and reuse it at later occurrences, without consulting -the shared memory. A volatile declaration tells the compiler to re-read -the value from shared memory at each occurrence. Similarly, a write to -a volatile variable causes the corresponding transfer of its value from -a register to shared memory to occur at a time not much later than the -execution of the write instruction. - -If you suspect a missing volatile declaration, note that @samp{gcc} -support the following command-line options. -@example -@group - gcc -fvolatile -fvolatile-global ... - # If topcc uses gcc: - topcc --pthread -fvolatile -fvolatile-global myfile.c -@end group -@end example -The option @code{-fvolatile} tells @samp{gcc} to compile all memory -references through pointers as volatile, and the option -@code{-fvolatile-global} tells @samp{gcc} to compile all memory -references to extern and global data as volatile. -However, note that this implies a performance penalty -since the compiler will issue -a load/store instruction for each volatile access, and -will @emph{not} keep volatile values in registers. - - -@node SMP Performance, , Volatile Variables, Shared Memory Model -@subsection SMP Performance - -Note that @samp{SMP} involves certain performance issues that do not arise -in other modes. If you find a lack of performance, please read -@ref{Improving Performance}. Also, note that the vendor-supplied -compiler, @code{cc}, is often recommended over @code{gcc} for -@samp{SMP}, due to specialized vendor-specific architectural issues. - -@node Sequential Memory Model, Caveats, Shared Memory Model, Advanced Features -@section Modifying TOP-C Code for the Sequential Memory Model - -@cindex memory model, sequential -@cindex sequential memory model - -@samp{TOP-C} also provides a sequential memory model. That model is -useful for first debugging an application in a sequential context, and -then re-compiling it with one of the parallel @samp{TOP-C} libraries for -production use. The application code for the sequential library is -usually both source and object compatible with the application code for -a parallel library. The sequential library emulates an application with -a single @samp{TOP-C} library. - -The sequential memory model emulates an application in which -@samp{DoTask()} is executed in the context of the single slave -process/thread, and all other code is executed in the context of the -master process/thread. This affects the values returned by -@code{TOPC_is_master()} and @code{TOPC_rank()}. In particular, -conditional code for execution on the master will work -correctly in the sequential memory model, but the following conditional -code for execution on the slave will probably @emph{not} work correctly. -@example -int main( int argc, char *argv[] ) @{ - TOPC_init( &argc, &argv ); - if ( TOPC_is_master() ) - ...; /* is executed in sequential model */ - else - ...; /* is @emph{never} executed in sequential model */ - TOPC_master_slave( ..., ..., ..., ...); - TOPC_finalize(); -@} -@end example - -@node Caveats, , Sequential Memory Model, Advanced Features -@section Caveats -IMPORTANT: -@samp{TOP-C} sets @code{alarm()} before waiting to receive - message from master. By default, if the master does not reply in a - half hour (1800 seconds), then the slave receives - @code{SIGALRM} and dies. - This is to prevent runaway processes in dist. memory version when master dies - without killing all slaves. @ref{Long Jobs}, - in order to change this default. - If your applications also uses @code{SIGALRM}, then run your - application with @code{--TOPC-slave-timeout=0} and @samp{TOP-C} - will not use @code{SIGALRM}. - -@code{GenerateTaskInput()} and @code{DoTask()} - This memory is managed by @samp{TOP-C}. - -The slave process attempts to set current directory to the same as the master - inside @code{TOPC_init()} and produces a warning if unsuccessful. - -When a task buffer is copied into @samp{TOP-C} space, -it becomes word-aligned. If the buffer was originally not -word-aligned, but some field in the buffer was word-aligned, -the internal field will no longer be word-aligned. On some -architectures, casting a non-word-aligned field to @samp{int} -or certain other types will cause a bus error. - -@node TOP-C Raw Interface, Acknowledgements, Advanced Features, Top -@chapter @samp{TOP-C} Raw Interface for Parallelizing Sequential Code - -There are instances when tasks are most naturally generated deep -inside nested loops. Often, this occurs in parallelizing existing -sequential applications. -In such circumstances, it may be difficult to -re-write the code to create a function @code{GenerateTaskInput()}, since -that would require turning the loops inside out. (If you don't know what this -refers to, then you probably don't need the raw interface.) - -On a first reading, you may wish to first look at the example for -either a @samp{for} loop or @samp{while} loop, depending on the type of -loop that you are parallelizing. Then return to the formal -descriptions of the @samp{TOP-C} raw functions. This chapter assumes -familiarity with the basic concepts of @ref{Overview} and @ref{Writing -TOP-C Applications}. - -@menu -* TOPC-C raw functions:: -* Parallelizing For Loops:: -* Parallelizing While Loops:: -@end menu - -@node TOPC-C raw functions, Parallelizing For Loops, TOP-C Raw Interface, TOP-C Raw Interface -@section @samp{TOP-C} raw functions - -@deftypefun void TOPC_raw_begin_master_slave - (@var{do_task}, @var{check_task_result}, @var{update_shared_data}) -@deftypefunx void TOPC_raw_end_master_slave () - This behaves like master_slave, with - @code{TOPC_raw_submit_task_input(@var{input})} serving - the role of @code{GenerateTaskInput()}. The slave blocks inside - @code{TOPC_raw_begin_master_slave()} and executes @samp{do_task()} and - @samp{update_shared_data()} until the master executes - @code{TOPC_raw_end_master_slave()}. At that time, the slave - unblocks. The slave does nothing inside - @code{TOPC_raw_end_master_slave()}. -@end deftypefun - -@deftypefun void TOPC_raw_submit_task_input ( TOPC_BUF @var{input} ) - Invoked by master between @code{TOPC_raw_begin_master_slave()} - and @code{TOPC_raw_end_master_slave()}; Typical usage is: -@example -@group - @code{TOPC_raw_submit_task_input(TOPC_MSG(&@var{input_data}, - sizeof(@var{input_data})) );} -@end group -@end example - The argument, @var{input}, corresponds to what would be returned by - @code{GenerateTaskInput()} in the routine @code{TOPC_master_slave()}. - @var{input} will be processed by @code{DoTask()} and its siblings, - just as in @code{TOPC_master_slave()}). - There can be multiple occurrences of - @code{TOPC_raw_submit_task_input()}. -@end deftypefun - -@deftypefun TOPC_BOOL TOPC_raw_wait_for_task_result () - Invoked by master between @code{TOPC_raw_begin_master_slave()} and - @code{TOPC_raw_end_master_slave()}; - If no tasks are outstanding, returns false immediately. Otherwise, it - blocks until a task does return. It calls application - callback, @code{CheckTaskResult()}, and then returns true. -@end deftypefun - -@node Parallelizing For Loops, Parallelizing While Loops, TOPC-C raw functions, TOP-C Raw Interface -@section Parallelizing @samp{for} Loops - -Assume that we are parallelizing a code fragment of the following form. -The variables @code{i} and @code{j} will be the input to -@code{DoTask()}, and any data structures indexed by @code{i} and -@code{j} (for example @code{array} in @code{array[i][j]}) will be -part of the shared data. -@example - float array[ROWS][COLS]; - ... - for ( i = 0; i < 10; i++ ) @{ - for ( j = 0; j < 10; j++ ) @{ - /* do_task: */ ... - /* update: */ array[i][j] = ...; - @} - @} -@end example - -Assume that the labels @code{do_task} and @code{update} above -correspond to the callback functions @code{DoTask()} and -@code{UpdateSharedData()}. Then the code is parallelized below. - -@example - float array[ROWS][COLS]; - typedef struct @{int i_val; int j_val;@} input_t; - void *DoTask(input_t *buf) @{ - int i = (*buf).i_val, j = (*buf).j_val; - /* do_task: */ ... - @} - void *CheckTaskResult(input_t *buf, output_t *buf2) @{ - /* update: */ array[i][j] = ...; - return NO_ACTION; - @} - main(int argc, char **argv) @{ - TOPC_init( &argc, &argv ); - TOPC_raw_begin_master_slave(DoTask, CheckTaskResult, - UpdateSharedData); - if (TOPC_is_master()) @{ - for ( i = 0; i < 10; i++ ) @{ - for ( j = 0; j < 10; j++ ) @{ - input_t input; - input.i_val = i; input.j_val = j; - TOPC_raw_submit_task_input( TOPC_MSG(&input, sizeof(input)) ); - @} - @} - @} TOPC_raw_end_master_slave(); - TOPC_finalize(); - @} -@end example - -@node Parallelizing While Loops, , Parallelizing For Loops, TOP-C Raw Interface -@section Parallelizing @samp{while} Loops - -Assume that we are parallelizing a code fragment of the following form -and @code{input} is a pointer. -@example - while ( (input = next_input()) != NULL ) @{ - /* do_task: */ ... - /* update: */ ... - @} -@end example - -Assume that the labels @code{do_task} and @code{update} above -correspond to the callback functions @code{DoTask()} and -@code{UpdateSharedData()}. Then the code is parallelized below, -where @code{input_size} must be specified by the application before it -is used. - -@example - TOPC_init( &argc, &argv ); - TOPC_raw_begin_master_slave(DoTask, CheckTaskResult, - UpdateSharedData); - if (TOPC_is_master()) @{ - while ( (input = next_input()) != NULL - || TOPC_raw_wait_for_task_result() ) @{ - TOPC_raw_submit_task_input( TOPC_MSG(input, input_size) ); - @} - @} TOPC_raw_end_master_slave(); - TOPC_finalize(); -@end example - -Note that the code inside the @dfn{raw begin/end block} is executed -only by the master in the code above. - -@comment THIS COMMENT SHOULD PROBABLY BE REMOVED. -@comment Hence, any shared data between master and slave -@comment must be declared outside of the @dfn{raw begin/end block}. -@comment @xref{Local Shared Data}, for a relevant example. - -If the buffer, @code{input}, contains pointers to other data, then you -will need to @dfn{marshal} the data before calling @code{TOPC_MSG()}. -@xref{Task Buffers, , Marshaling and Heterogeneous Architectures}. - -@node Acknowledgements, Summary, TOP-C Raw Interface, Top -@chapter Acknowledgements - -A project of this scope cannot be achieved alone. While Gene Cooperman -was the primary author, the project has benefited from contributions -by several various individuals and institutions at different times. - -The author wishes to thank the National Science Foundation for -support under which much of this work was developed. -The author wishes to thank the Mariner Project at Boston University -for the use of the Origin 2000 and other facilities which helped in the -development of this software. An earlier, experimental version of mpinu -(MPI subset) was written by Markos Kyzas and partially revised by Gene -Cooperman. Michael Weller provided ideas for improving some of the C -code, and provided valuable feedback when he adapted the @samp{TOP-C} ideas -to a large application on an IBM SP-2. The loader module is joint -with Victor Grinberg. Further experience and feedback was gained -from the GAP community when the @samp{TOP-C} model was ported to ParGAP, a -refereed share package. (GAP -- Groups, Algorithms and Programming) -is a language similar to Maple, specialized for symbolic computations -in computational algebra and especially computational group theory.) -@samp{TOP-C}, version 2, was exported by Victor Grinberg from ParGAP, with -enhancements by Gene Cooperman. Some important feedback was gained -in the TOP-C parallelization of Geant4. -(Geant4 is a toolkit for the Monte Carlo simulation of particle-matter -interaction. The package has close to a million lines of C++ code. -The TOP-C parallelization is included with the Geant4 distribution.) -Xiaoqin Ma analyzed mechanisms for -detecting and recovering from dead slaves, broken sockets, etc., -and wrote the first version of code to handle that. - -@page - -@node Summary, Example, Acknowledgements, Top -@appendix Summary of @samp{TOP-C} Commands -@comment To generate this appendix, do: grep '@def\|@end def' topc.texi -@comment and then re-format. - -@noindent -@emph{From @ref{The Main TOP-C Library Calls}.} -@table @code -@need 400 -@item void TOPC_init ( int *@var{argc}, char ***@var{argv} ) -@itemx void TOPC_finalize ( void ) -@flushright - Function -@end flushright -@need 1800 -@item void TOPC_master_slave - ( TOPC_BUF (*@var{generate_task_input})(),@*@ @ - TOPC_BUF (*@var{do_task})(void *input),@*@ @ - TOPC_ACTION (*@var{check_task_result})(void *input, void *output),@*@ @ - void (*@var{update_shared_data})(void *input, void *output) - @*) -@flushright - Function -@end flushright -@need 400 -@item TOPC_BUF TOPC_MSG ( void *@var{buf}, int @var{buf_size} ) -@flushright - Function -@end flushright -@end table - -@sp 1 -@noindent -@emph{From @ref{Callback Functions, - Callback Functions for @code{TOPC_master_slave()}, - Callback Functions for @code{TOPC_master_slave()} }.} -@table @code -@need 400 -@item TOPC_BUF GenerateTaskInput ( void ) -@flushright - Function -@end flushright -@need 400 -@item TOPC_BUF DoTask ( void *@var{input} ) -@flushright - Function -@end flushright -@need 400 -@item TOPC_ACTION CheckTaskResult ( void *@var{input}, void *@var{output}) -@flushright - Function -@end flushright -@need 400 -@item void UpdateSharedData ( void *@var{input}, void *@var{output} ) -@flushright - Function -@end flushright -@end table - -@sp 1 -@noindent -@emph{From @ref{Actions, - Actions Returned by @code{CheckTaskResult()}, - Actions Returned by @code{CheckTaskResult()} }.} -@table @code -@need 400 -@item Action TOPC_ACTION NO_ACTION -@flushright - Action -@end flushright -@need 400 -@item Action TOPC_ACTION UPDATE -@flushright - Action -@end flushright -@need 400 -@item Action TOPC_ACTION REDO -@flushright - Action -@end flushright -@need 400 -@item Action TOPC_ACTION CONTINUATION ( void *@var{next_input} ) -@flushright - Action -@end flushright -@end table - -@sp 1 -@noindent -@emph{From @ref{TOP-C Utilities}.} -@table @code -@need 400 -@item TOPC_BOOL TOPC_is_up_to_date ( void ) -@flushright - Function -@end flushright -@need 400 -@item int TOPC_rank ( void ) -@flushright - Function -@end flushright -@need 400 -@item TOPC_BOOL TOPC_is_master ( void ) -@flushright - Function -@end flushright -@need 400 -@item int TOPC_num_slaves ( void ) -@flushright - Function -@end flushright -@need 400 -@item int TOPC_num_idle_slaves ( void ) -@flushright - Function -@end flushright -@need 400 -@item int TOPC_node_count ( void ) -@flushright - Function -@end flushright -@end table - -@sp 1 -@noindent -@emph{From @ref{Shared Memory Model, - Optimizing TOP-C Code for the Shared Memory Model, - Optimizing TOP-C Code for the Shared Memory Model }.} -@table @code -@need 400 -@item TOPC_thread_private -@flushright - Variable -@end flushright -@need 400 -@item TOPC_thread_private_t -@flushright - Type -@end flushright -@need 400 -@item void TOPC_ATOMIC_READ ( 0 ) @{ @var{... C code ...} @} -@itemx void TOPC_ATOMIC_WRITE ( 0 ) @{ @var{... C code ...} @} -@flushright - Function -@end flushright -@need 400 -@item void TOPC_BEGIN_ATOMIC_READ ( 0 ) -@itemx void TOPC_END_ATOMIC_READ ( 0 ) -@itemx void TOPC_BEGIN_ATOMIC_WRITE ( 0 ) -@itemx void TOPC_END_ATOMIC_WRITE ( 0 ) -@flushright - Function -@end flushright -@end table - -@sp 1 -@noindent -@emph{From @ref{TOP-C Raw Interface, - Raw @samp{TOP-C} interface: @code{raw_master_slave}, - Raw @samp{TOP-C} interface: @code{raw_master_slave} }.} -@table @code -@need 800 -@item void TOPC_raw_begin_master_slave - (@var{do_task}, @var{check_task_result}, @var{update_shared_data}) -@itemx void TOPC_raw_end_master_slave () -@flushright - Function -@end flushright -@need 400 -@item void TOPC_raw_submit_task_input ( TOPC_BUF @var{input} ) -@flushright - Function -@end flushright -@need 400 -@item TOPC_BOOL TOPC_raw_wait_for_task_result () -@flushright - Function -@end flushright -@end table - -@sp 1 -@noindent -@emph{From @ref{Aborting Tasks}.} -@table @code -@item void TOPC_abort_tasks ( void ) -@itemx TOPC_BOOL TOPC_is_abort_pending ( void ) -@flushright - Function -@end flushright -@end table - -@sp 1 -@noindent -@emph{From @ref{Testing for Task Continuations}.} -@table @code -@item TOPC_BOOL TOPC_is_REDO ( void ) -@itemx TOPC_BOOL TOPC_is_CONTINUATION ( void ) -@flushright - Function -@end flushright -@end table - -@sp 1 -@noindent -@emph{From @ref{Large Buffers and TOPC_MSG_PTR}.} -@table @code -@item TOPC_BUF TOPC_MSG_PTR ( void *@var{buf}, int @var{buf_size} ) -@flushright - Function -@end flushright -@end table - -@sp 1 -@noindent -@emph{From @ref{Command Line Options, - Command Line Options in TOP-C Applications, - Command Line Options in TOP-C Applications }.} -@table @code -@item --TOPC-help@samp{[=<0/1>]} -@flushright - [boolean, default: false] -@end flushright -@item --TOPC-verbose@samp{[=<0/1>]} -@flushright - [boolean, default: false] -@end flushright -@item --TOPC-stats@samp{[=<0/1>]} -@flushright - [boolean, default: false] -@end flushright -@item --TOPC-num-slaves@samp{=} -@flushright - [default: -1 (system-defined)] -@end flushright -@item --TOPC-slave-wait@samp{=} -@flushright - [default: 0] -@end flushright -@item --TOPC-slave-timeout@samp{=} -@flushright - [default: 1800 s] -@end flushright -@item --TOPC-trace@samp{=} -@flushright - [trace (0: notrace, 1: trace, 2: user trace fncs, default: 2)] -@end flushright -@item --TOPC-procgroup@samp{=} -@flushright - [default: "./procgroup"] -@end flushright -@item --TOPC-safety@samp{=} -@flushright - [default: 0] -@end flushright -@end table - -@sp 1 -@noindent -@emph{From @ref{Tracing Messages}.} -@table @code -@need 400 -@item int TOPC_OPT_trace -@itemx void (*)(void *input) TOPC_OPT_trace_input -@itemx void (*)(void *input, void *output) TOPC_OPT_trace_result -@end table - -@page - -@node Example, Using a Different MPI with TOP-C, Summary, Top -@appendix Example @samp{TOP-C} Application - -@cindex example TOP-C application - -There are several example @samp{TOP-C} programs in the -@file{topc/examples} subdirectory. We include one example in this -manual. It does not contain any @code{UPDATE} actions, and therefore -illustrates only a trivial form of parallelism (with no interaction -among the slaves). The @file{topc/examples} subdirectory should be -inspected for more sophisticated examples. -After understanding this example, you may also want to look at -@ref{Advanced Features}, or if you are parallelizing a sequential -program, then you may want to look at @ref{TOP-C Raw Interface}. - -This program produces an array of 10,000,000 random integers in one pass, -and then finds the maximum value in a second pass. It would be compiled -by: @command{topcc @var{MODE} @file{file.out}}, where @var{MODE} is one of -@code{--seq}, @code{--mpi}, or @code{--pthread}. One can control the -number of slaves by executing: @code{./a.out --TOPC-num-slaves=@var{num}}. - -@example -#include -#include -#include -#include - -#define MAX 2000000 -#define INCR MAX/10 /* We assume INCR divides MAX exactly */ - -int array[MAX]; -int idx; -int max_int; - -TOPC_BUF GenerateTaskInput() @{ - int input_task; - if (idx >= MAX) return NOTASK; - input_task = idx; - idx = idx + INCR; - return TOPC_MSG( &input_task, sizeof(input_task) ); -@} -TOPC_BUF DoTaskRandom( int *ignore ) @{ - int rand_int[INCR]; - int i; - for ( i = 0; i < INCR; i++) - rand_int[i] = rand(); - return TOPC_MSG( rand_int, INCR * sizeof(int) ); -@} -TOPC_ACTION CheckTaskRandom( int *input, int rand_vals[] ) @{ - int curr_idx = *input; - memcpy( array+curr_idx, rand_vals, INCR * sizeof(int) ); - return NO_ACTION; -@} - -TOPC_BUF GenerateTaskInMax() @{ - int *input_task; - if (idx >= MAX) return NOTASK; - input_task = array + idx; - idx = idx + INCR; - return TOPC_MSG( input_task, INCR * sizeof(int) ); -@} -TOPC_BUF DoTaskMax( int subarray[] ) @{ - int i; - int max=0; - for ( i = 0; i < INCR; i++) - if ( subarray[i] > max ) - max = subarray[i]; - return TOPC_MSG( &max, sizeof(max) ); -@} -TOPC_ACTION CheckTaskMax( int ignore[], int *output ) @{ - int curr_max = *output; - if ( curr_max > max_int ) - max_int = curr_max; - return NO_ACTION; -@} - -int main( int argc, char **argv ) @{ - /* Set default to no trace; Override with: ./a.out --TOPC-trace=1 */ - TOPC_OPT_trace = 0; - TOPC_init( &argc, &argv ); - idx = 0; /* Initialize idx, and randomize values of array[] */ - TOPC_master_slave(GenerateTaskInput, DoTaskRandom, CheckTaskRandom, - NULL); - if (TOPC_is_master()) - printf("Finished randomizing integers.\n"); - idx = 0; /* Re-initialize idx to 0, and find max. value in array[] */ - TOPC_master_slave( GenerateTaskInMax, DoTaskMax, CheckTaskMax, NULL ); - TOPC_finalize(); - printf("The maximum integer is: %d\n", max_int); - exit(0); -@} -@end example - -@page - -@node Using a Different MPI with TOP-C, Function Index, Example, Top -@appendix Using a Different @samp{MPI} with TOP-C - -@samp{TOP-C} provides a built-in subset of MPI sufficient to run -distributed applications. If you prefer to use a different implementation -of @samp{MPI} with @samp{TOP-C}, this note describes how to do so. -Examples for @samp{MPICH}, @samp{LAM} and @samp{IBM POE} are at the -end of this section. You should re-configure and re-build @samp{TOP-C} -using the same C/C++ compiler as that of your chosen MPI. - -First test a @samp{hello_world} MPI program -for your chosen MPI implementation to make sure that the -startup mechanism is well understood. - -Many dialects of @samp{MPI} provide their own wrapper around -the C and C++ compiler. For example, @samp{LAM MPI} provides @code{mpicc}. -If your dialect provides such a wrapper @code{mpicc}, then -do @code{./configure --with-mpi-cc=mpicc} and @code{make}. There is a similar -configure flag, @code{--with-mpi-cxx}, for @samp{C++}. - -If you do use such a wrapper, you should use the same C compiler for -the rest of @samp{TOP-C}. Hence, if @code{mpicc} uses @code{cc}, -then configure with @code{env CC=cc ./configure --with-mpi-cc=mpicc ---cache-file=/dev/null}. -In general, you can always specify a non-default C and C++ compiler by -specifying @code{CC=...} and @code{CXX=...}, respectively. - -If your dialect does not provide such a wrapper, it is easy to create -one by modifying the shell script below for your site. -@example -#!/bin/sh -gcc -I/usr/local/include $* -L/usr/local/lib -lmpi -@end example - -These wrappers will enable @command{topcc} and @command{topc++} to work, -but not @command{topc-config}. If you also need @command{topc-config}, -then you must modify @command{topc-config}. -Determine the libraries used by your dialect of MPI. -Then search for a string with @code{-ltopc-mpi} in -@file{.../topc/bin/topc-config}, -and append to it your @samp{libmpi}. For example, -append to @code{-ltopc-mpi} with @code{-L/usr/local/lib -lmpi}. - -Finally, for many dialects of MPI, after compiling the MPI application, -they may also require a special command at runtime to execute, -such as @code{mpirun a.out}. -In such cases, your @samp{TOP-C} application must be treated similarly. - -The following examples illustrate the configuration and use of -MPI for other MPI implementations using 2 slaves and 1 master. -@example -@group -# IBM POE/AIX: - env CC=xlc CXX=xlC ./configure --with-mpi-cc=mpcc --with-mpi-cxx=mpCC - make; cd bin; ./topcc --mpi -qcpluscmt ../examples/parfactor.c - poe ./a.out 1234 --TOPC-stats -procs 3 -pgmmodel spmd -@end group -@end example - -@example -@group -# MPICH/Linux: - ./configure --with-mpi-cc=mpicc - make; cd bin; ./topcc --mpi ../examples/parfactor.c - mpirun -np 3 ./a.out --TOPC-stats 1234 -@end group -@end example - -@example -@group -# LAM/Linux: - ./configure --with-mpi-cc=mpicc - make; cd bin; ./topcc --mpi ../examples/parfactor.c - mpirun -c 3 ./a.out -- --TOPC-stats 1234 -@end group -@end example - -@page - -@node Function Index, Variable Index, Using a Different MPI with TOP-C, Top -@comment node-name, next, previous, up -@unnumbered Function Index -@comment Run texindex for printed manual -@printindex fn - -@node Variable Index, Concept Index, Function Index, Top -@comment node-name, next, previous, up -@unnumbered Variable Index -@comment Run texindex for printed manual -@printindex vr - -@page - -@node Concept Index, , Variable Index, Top -@comment node-name, next, previous, up -@unnumbered Concept Index -@printindex cp - -@shortcontents -@contents -@bye diff --git a/topc-2.5.2/doc/topcc.1 b/topc-2.5.2/doc/topcc.1 deleted file mode 100644 index 2f3cc88c..00000000 --- a/topc-2.5.2/doc/topcc.1 +++ /dev/null @@ -1,196 +0,0 @@ -.\" doc/topcc.1. Generated from topcc.1.in by configure. -.TH TOPCC 1 -.SH NAME -topcc \- Task Oriented Parallel C (TOP-C) compiler -topc++ \- Task Oriented Parallel C (TOP-C) compiler for C++ -.SH SYNOPSIS -.B topcc -.RB [ \-\-mpi\ \| | \|\ \-\-seq\ \| | \|\ \-\-pthread "\|] \ -[\|" \-\-efence "\|]" -.I CPARAMS -\&... -.br -.B topcc -.RB "[\|" \-\-help\ \| | \|\ \-\-version "\|] -.sp -.B topc++ -\&... -.I (as for topcc) -.sp -.br -.B topc\-config -.RB [\-\-prefix[=DIR]] -.RB [\-\-exec-prefix[=DIR]] -.RB [\-\-with-uninstalled-topc] -.RB [\-\-libs] -.RB [\-\-cflags] -.RB [\-\-help] -.RB [\-\-version] -.sp -.B #include -.SH DESCRIPTION -TOP-C is a programming model for -.I easily -writing parallel applications. -The -.I topcc -shell script is is used to invoke gcc with the correct include files -and libraries for TOP-C. -The -.I topc++ -shell script is is used to invoke g++ with the correct include files -and libraries for TOP-C. -.I CPARAMS -are the same parameters that would be passed to gcc or g++. -.I topc\-config -determines the compiler and linker flags, and can be used when -.I topcc -is inconvenient. For example, -.br -.B topcc --mpi myfile.c -.br -is more or less equivalent to -.br -.B gcc `topc-config --mpi --cflags` myfile.c -.br -.B \ \ `topc-config --mpi --libs` -.br -.I topcc -produces an executable from a source or object file, or an object file -from a source file. The source file must contain "#include ". -Documentation of the TOP-C programmer's model for writing parallel -programs is contained in the directory /home/kason/school/4zp6/repo/GEANT4-GPU/topc-2.5.2/doc/. -Depending on what was installed, the documentation exists in some -or all of .info, .dvi, .ps, .html and .txt format. -.SH OPTIONS -.TP -.B \-\-mpi -Link object file using -.I libtopc-mpi.a -library. This produces a distributed memory application running -on top of an implementation of MPI (Message Passing Interface) included -with the distribution. The application reads a -.I procgroup -file from the current directory to determine the remote host and the -path of the remote application. See the section below for -the format of the procgroup file. -Alternatively the command line used to invoke the application can include -.B \-\-TOPC_procgroup -.I file -where -.I file -is a full path for the desired procgroup file. -If the remote host has a different -architecture, the application programmer may need to use htonl, -nltoh, xdr (eXternal Data Representation), or other techniques -to maintain data independence for heterogeneous architectures. -.TP -.B \-\-pthread -.TP -Link object file using -.I libtopc-pthread.a -library. This produces an SMP application (Symmetric MultiProcessing -shared memory application) running on top of pthreads (POSIX threads). -.B \-\-seq -Link object file using -.I libtopc-seq.a -library. This produces a sequential (non-parallel) application running -in a single process. It is recommended to use this library in the -early stages of application development, so that a symbolic debugger -(gdb or alternative) can be used easily. -.TP -.B \-\-efence -Link executable using -.I \-lefence -for memory management debugging (malloc, free, new, etc.). -If your system doesn't have -.I \-lefence -or you prefer a different library, edit the line -.I LIBMALLOC= -in the -.I topcc -or -.I topc++ -script. -.TP -.B \-\-help -List command line options. -.B \-\-version -List version of topcc. -.SH PROCGROUP -The -.I -procgroup -.:P -file is useful only with the command line option -.I \-\-mpi -. This is the same format that was used by P4, one predecessor of MPI. -The file must contain a line: -.LP -local 0 -.LP -for the master process. It must also contain a line for each slave -process of the form: -.LP -hostname 1 full_pathname -.LP -where -.I hostname -is the remote host. The value 'localhost' is recommended for debugging. -The -.I full_pathname -is the pathname of a binary on the remote host. In a shared file -system, this will typically be the same as the pathname of the -local binary, but it can be a different binary, allowing for -heterogeneous computing. The environment variable -.I RSH -(default 'rsh') is used to invoke the remote host. It is sometimes -useful to modify this environment variable to get around firewalls. -.SH EXAMPLES -See /home/kason/school/4zp6/repo/GEANT4-GPU/topc-2.5.2/examples/. -.SH AUTHOR -Gene Cooperman -.br -See the manual and README for others who ported and helped develop -various parts. -.SH ENVIRONMENT -.TP -.B RSH -Used with \-\-mpi. By default, -.I rsh -is used to invoke application on remote host. If this is set, its value -determines a substitute command, such as -.I ssh. -.TE -.LP -See gcc and g++ for more environment variables. -.SH FILES -''' .B /home/kason/school/4zp6/repo/GEANT4-GPU/topc-2.5.2/doc/ -.B /home/kason/school/4zp6/repo/GEANT4-GPU/topc-2.5.2/doc/topc.dvi -.br -.B /home/kason/school/4zp6/repo/GEANT4-GPU/topc-2.5.2/doc/topc.info -.TP -.B /home/kason/school/4zp6/repo/GEANT4-GPU/topc-2.5.2/doc/html/topc_toc.html -Manual for the TOP-C programming model. -''' .TP -''' .B /home/kason/school/4zp6/repo/GEANT4-GPU/topc-2.5.2/doc/topc.dvi -''' .B /home/kason/school/4zp6/repo/GEANT4-GPU/topc-2.5.2/doc/topc.info -''' .B /home/kason/school/4zp6/repo/GEANT4-GPU/topc-2.5.2/doc/html/topc_toc.html -''' Description of TOP-C programming model. -.TP -.B /home/kason/school/4zp6/repo/GEANT4-GPU/topc-2.5.2/examples/ -Example TOP-C programs. -.TP -.B procgroup -Used with \-\-mpi to determine remote hosts and path of remote application. -.TP -.B /tmp/mpinu-rsh.* -Used with \-\-mpi. If application fails to invoke remote hosts, this -file is left for debugging. -.B /tmp/procgroup.* -Used with \-\-mpi. If application fails to invoke remote hosts, this -file may be left for debugging. -.SH SEE ALSO -.TP -gcc(1), htonl(3), nltoh(3), rsh(1), ssh(1), topc-config(1), xdr(3), -and ANSI/IEEE Std 754-1985 floating point standard. diff --git a/topc-2.5.2/doc/topcc.1.in b/topc-2.5.2/doc/topcc.1.in deleted file mode 100644 index c6524304..00000000 --- a/topc-2.5.2/doc/topcc.1.in +++ /dev/null @@ -1,196 +0,0 @@ -.\" @configure_input@ -.TH TOPCC 1 -.SH NAME -topcc \- Task Oriented Parallel C (TOP-C) compiler -topc++ \- Task Oriented Parallel C (TOP-C) compiler for C++ -.SH SYNOPSIS -.B topcc -.RB [ \-\-mpi\ \| | \|\ \-\-seq\ \| | \|\ \-\-pthread "\|] \ -[\|" \-\-efence "\|]" -.I CPARAMS -\&... -.br -.B topcc -.RB "[\|" \-\-help\ \| | \|\ \-\-version "\|] -.sp -.B topc++ -\&... -.I (as for topcc) -.sp -.br -.B topc\-config -.RB [\-\-prefix[=DIR]] -.RB [\-\-exec-prefix[=DIR]] -.RB [\-\-with-uninstalled-topc] -.RB [\-\-libs] -.RB [\-\-cflags] -.RB [\-\-help] -.RB [\-\-version] -.sp -.B #include -.SH DESCRIPTION -TOP-C is a programming model for -.I easily -writing parallel applications. -The -.I topcc -shell script is is used to invoke @CC@ with the correct include files -and libraries for TOP-C. -The -.I topc++ -shell script is is used to invoke @CXX@ with the correct include files -and libraries for TOP-C. -.I CPARAMS -are the same parameters that would be passed to @CC@ or @CXX@. -.I topc\-config -determines the compiler and linker flags, and can be used when -.I topcc -is inconvenient. For example, -.br -.B topcc --mpi myfile.c -.br -is more or less equivalent to -.br -.B gcc `topc-config --mpi --cflags` myfile.c -.br -.B \ \ `topc-config --mpi --libs` -.br -.I topcc -produces an executable from a source or object file, or an object file -from a source file. The source file must contain "#include ". -Documentation of the TOP-C programmer's model for writing parallel -programs is contained in the directory @PWD@/doc/. -Depending on what was installed, the documentation exists in some -or all of .info, .dvi, .ps, .html and .txt format. -.SH OPTIONS -.TP -.B \-\-mpi -Link object file using -.I libtopc-mpi.a -library. This produces a distributed memory application running -on top of an implementation of MPI (Message Passing Interface) included -with the distribution. The application reads a -.I procgroup -file from the current directory to determine the remote host and the -path of the remote application. See the section below for -the format of the procgroup file. -Alternatively the command line used to invoke the application can include -.B \-\-TOPC_procgroup -.I file -where -.I file -is a full path for the desired procgroup file. -If the remote host has a different -architecture, the application programmer may need to use htonl, -nltoh, xdr (eXternal Data Representation), or other techniques -to maintain data independence for heterogeneous architectures. -.TP -.B \-\-pthread -.TP -Link object file using -.I libtopc-pthread.a -library. This produces an SMP application (Symmetric MultiProcessing -shared memory application) running on top of pthreads (POSIX threads). -.B \-\-seq -Link object file using -.I libtopc-seq.a -library. This produces a sequential (non-parallel) application running -in a single process. It is recommended to use this library in the -early stages of application development, so that a symbolic debugger -(gdb or alternative) can be used easily. -.TP -.B \-\-efence -Link executable using -.I \-lefence -for memory management debugging (malloc, free, new, etc.). -If your system doesn't have -.I \-lefence -or you prefer a different library, edit the line -.I LIBMALLOC= -in the -.I topcc -or -.I topc++ -script. -.TP -.B \-\-help -List command line options. -.B \-\-version -List version of topcc. -.SH PROCGROUP -The -.I -procgroup -.:P -file is useful only with the command line option -.I \-\-mpi -. This is the same format that was used by P4, one predecessor of MPI. -The file must contain a line: -.LP -local 0 -.LP -for the master process. It must also contain a line for each slave -process of the form: -.LP -hostname 1 full_pathname -.LP -where -.I hostname -is the remote host. The value 'localhost' is recommended for debugging. -The -.I full_pathname -is the pathname of a binary on the remote host. In a shared file -system, this will typically be the same as the pathname of the -local binary, but it can be a different binary, allowing for -heterogeneous computing. The environment variable -.I RSH -(default 'rsh') is used to invoke the remote host. It is sometimes -useful to modify this environment variable to get around firewalls. -.SH EXAMPLES -See @PWD@/examples/. -.SH AUTHOR -Gene Cooperman -.br -See the manual and README for others who ported and helped develop -various parts. -.SH ENVIRONMENT -.TP -.B RSH -Used with \-\-mpi. By default, -.I rsh -is used to invoke application on remote host. If this is set, its value -determines a substitute command, such as -.I ssh. -.TE -.LP -See @CC@ and @CXX@ for more environment variables. -.SH FILES -''' .B @PWD@/doc/ -.B @PWD@/doc/topc.dvi -.br -.B @PWD@/doc/topc.info -.TP -.B @PWD@/doc/html/topc_toc.html -Manual for the TOP-C programming model. -''' .TP -''' .B @PWD@/doc/topc.dvi -''' .B @PWD@/doc/topc.info -''' .B @PWD@/doc/html/topc_toc.html -''' Description of TOP-C programming model. -.TP -.B @PWD@/examples/ -Example TOP-C programs. -.TP -.B procgroup -Used with \-\-mpi to determine remote hosts and path of remote application. -.TP -.B /tmp/mpinu-rsh.* -Used with \-\-mpi. If application fails to invoke remote hosts, this -file is left for debugging. -.B /tmp/procgroup.* -Used with \-\-mpi. If application fails to invoke remote hosts, this -file may be left for debugging. -.SH SEE ALSO -.TP -@CC@(1), htonl(3), nltoh(3), rsh(1), ssh(1), topc-config(1), xdr(3), -and ANSI/IEEE Std 754-1985 floating point standard. diff --git a/topc-2.5.2/examples/README b/topc-2.5.2/examples/README deleted file mode 100644 index fc673d93..00000000 --- a/topc-2.5.2/examples/README +++ /dev/null @@ -1,61 +0,0 @@ -To run these examples, do: - cd ../bin -Look at the Makefile, for examples of how to compile and run them. -All of the TOP-C examples (not beginning with "seq") can be run -with any of the TOP-C memory models (distributed, shared memory, sequential). - -All of these examples also compile as C++ programs using topc++ . -To test it, do: ( cd ../bin; make TOPCC=./topc++ checkall ) - -Where there is a large buffer to be returned by TOPC_MSG(), the -code illustrates techniques for using TOPC_MSG_PTR() instead of -TOPC_MSG(), in order to save the cost of copying the buffer if -invoked by TOPC_MSG(). This is purely for efficiency. In such cases, -it is always valid (and simpler) to replace TOPC_MSG_PTR() by TOPC_MSG(), -and allocate its buffer argument as a local variable on the stack. - -In general, you can use ./topcc (in the ../bin dir) as a substitute for cc -Try: ./topcc --help -for a synopsis. To demo a specific program in all three memory models, -Try: make test TEST_FILE=gauss-elim [or other file] - -The files here include: -gauss-elim.c - Gaussian elimination, example of use of TOP-C model - for typical data parallel number crunching. - Illustrates TOPC_MSG_PTR(). -gauss-elim-fine-grain.c - Version using TOPC_ATOMIC_READ/WRITE() for - fine grain SMP parallelism. Also uses TOPC_MSG_PTR(). -gauss-elim-redo.c - Version using REDO to minimize communication at potential - expense of more slave idle time. - Also uses TOPC_MSG_PTR(). - -par8queens-abort.c - 8 queens problem, finds a single solution, - example of use of TOP-C model for search, - using TOPC_abort_tasks() and TOPC_is_abort_pending() - to abort tasks of unsuccessful slaves. - Illustrates TOPC_MSG_PTR(). -par8queens-raw.c - 8 queens problem, finds all solutions, - example of TOP-C raw interface, Useful in parallelizing - software with nested loops - Illustrates TOPC_MSG_PTR(). -seq8queens.c - 8 queens problem. This is the sequential (not TOP-C) code - on which the TOP-C code is based - -parfactor.c - Naive sieve factorization (Illustrates REDO) -parfactor-raw.c - Naive sieve factorization, example of TOP-C raw interface - (Illustrates REDO) - -parquicksort-raw.c - Quicksort, example of parallelizing recursive algorithms - example of TOP-C raw interface - Illustrates TOPC_MSG_PTR(). -parquicksort.c - Quicksort, example of parallelizing recursive algori5thms - without using raw interface - Illustrates TOPC_MSG_PTR(). -seqquicksort.c - Quicksort. This is the sequential (not TOP-C) code - on which the TOP-C code is based - -parsimple.c - Simple example from the manual, - Generates many random numbers in first phase - and finds maximum integer in second phase, - example of multiple calls to TOPC_master_slave() - in one session and large messages (> 1 MB) diff --git a/topc-2.5.2/examples/gauss-elim-fine-grain.c b/topc-2.5.2/examples/gauss-elim-fine-grain.c deleted file mode 100644 index 7d50386b..00000000 --- a/topc-2.5.2/examples/gauss-elim-fine-grain.c +++ /dev/null @@ -1,315 +0,0 @@ -/******************************************************************** - ******************************************************************** - ** USAGE: topcc [ --seq | --mpi | --pthread ] THIS_FILE - ** ./a.out [ using default input data, or] - ** ./a.out dimension number_of_bands [ using random data ] - ** ALGORITHM: Group adjacent rows of matrix into bands (sets of rows) - ** TASK: Do Gaussian elimination on input band and then - ** use other bands to further reduce input band. - ** MODIFICATIONS FOR FINE-GRAINED SMP PARALLELISM: - ** first_unred_band declared volatile, do_task places atomic read - ** around it, and update_shared_data places atomic write around it. - ** shared data: rows of matrix grouped into bands: - ** matrix, first_unred_band, first_unred_col[] (read/write) - ** n (dimension), b (number of bands), band_size (read-only) - ** task input: band number - ** task output: struct band_info: first_unred_band, first_unred_col, - ** rows of band after all possible eliminations done - ** update: copy band to shared data of all slaves - ******************************************************************** - ********************************************************************/ - -/* #define DEBUG */ -#include -#include -#include -#include // strcmp() -#include // strcmp() -#include "topc.h" - -#define MAX_DIM 100 -/* DIM is default, if no args given */ -#define DIM 4 -#define BANDS 2 -#define BAND_SIZE ((DIM+BANDS-1)/BANDS) /* For b | n, this is just n/b */ -int band_size = BAND_SIZE; -float matrix_vals[DIM*DIM] = { 20.0, 2.0, 3.0, 4.0, - 5.0, 20.0, 7.0, 8.0, - 9.0, 10.0, 20.0, 12.0, - 13.0, 14.0, 15.0, 20.0 -}; -float *matrix = matrix_vals; -/* Columns 0 up to first_unred_col[b] of band b are 0 */ -int *first_unred_col; /* BANDS elements, malloc in main() */ -volatile int first_unred_band = 0; /* Done when first_unred_band = b */ -int *band_is_busy; /* BANDS elements, malloc in main() */ - -#define max(x,y) ( (x) < (y) ? y : x ) -struct band_info { - int band_no; - int first_unred_band; - int first_unred_col; - /* float band[BAND_SIZE * DIM]; */ - /* task_out will use dynamically allocated space to extend band: - * malloc( sizeof(struct band_info_info)+BAND_SIZE * DIM*sizeof(float) ) - */ - float band[1]; -}; - -void mytrace_input ( int *in_msg ) -{ printf("band %d", *in_msg); -} -void mytrace_result ( int *ignore, struct band_info *out_msg ) -{ printf("row vector: %5.1f %5.1f ...", - (out_msg->band)[0], out_msg->band[1] ); -} - -/* These will be set to DIM and BANDS inside main() */ -int n, b; /* n = matrix dimension; b = number of bands */ - -void reduce_row(float *matrix_rows[], int row_to_red, int row, int pivot) -{ float scalar = matrix_rows[row_to_red][pivot] / matrix_rows[row][pivot]; - float *row1 = matrix_rows[row_to_red]; - float *row2 = matrix_rows[row]; - int j; - -#ifdef DEBUG - printf("reducing row %d, using row %d and pivot %d\n", row_to_red,row,pivot); -#endif - row1[pivot] = 0; - for (j = pivot+1; j < n; j++) - row1[j] = row1[j] - scalar * row2[j]; -} - -TOPC_BUF generate_task_input() { - static int i; - - for (i = first_unred_band; i < b ; i++) - if (first_unred_col[i] <= first_unred_col[max(first_unred_band-1,0)] - && band_is_busy[i] == 0) { - band_is_busy[i] = 1; - return TOPC_MSG(&i, sizeof(i)); } - return NOTASK; } - -/* FOR EFFICIENCY ONLY: (avoid copying task_out, as done by TOPC_MSG()) - * TOPC_thread_private illustrates how to make TOPC_MSG_PTR() in do_task() - * compatible with shared memory model. - * Most programs would use TOPC_MSG(), allocate task_out locally on stack, - * and TOPC_MSG() would copy it to the TOP-C address space. - * task_out is a persistent thread-private variable, pointing to a - * a malloc buffer that persists. Ideally, if C allowed it, we would write: - * THREAD_PRIVATE struct band_info *task_out = NULL; - * and the first call to do_task would malloc the memory. - */ -typedef struct band_info *TOPC_thread_private_t; -#define task_out TOPC_thread_private -TOPC_thread_private_t task_out_debug() { /* needed for debugging in gdb */ - return task_out; -} - -#define sizeof_task_out (sizeof(struct band_info) + n*band_size*sizeof(*matrix)) - -TOPC_BUF do_task(int *band_ptr) /* 0 <= band_no <= b - 1 */ -{ int band_no = *band_ptr; - int row_start = band_no * band_size; - int row_end = (band_no + 1) * band_size; - int row, i, j, k; - int pivot = max(first_unred_col[max(first_unred_band-1,0)], 0); - /* Added for use with fine-grain parallelism (atomic read/write) */ - int local_first_unred_band; - /* Not all compilers support variable size arrays on stack */ - /* float *matrix_rows[DIM]; */ - float *matrix_rows[MAX_DIM]; - - if ((void *)task_out == NULL) -# ifdef __cplusplus - task_out = (struct band_info *)malloc( sizeof_task_out ); -# else - task_out = malloc( sizeof_task_out ); -# endif - /* Create array of matrix rows */ - for (row = 0; row < n; row++) - matrix_rows[row] = &matrix[row*n]; - /* Copy over the band to be modified */ - for (i = 0, k = 0; i < band_size; i++) /* copy band */ - for (j = 0; j < n; j++, k++) - task_out->band[k] = matrix_rows[band_no*band_size+i][j]; - /* Set matrix_rows to use the band to be modified */ - for (i = 0; i < band_size; i++) - matrix_rows[band_no*band_size+i] = &task_out->band[i*n]; - - /* On some SMP architectures, read of int is always atomic */ - TOPC_ATOMIC_READ(0) { - local_first_unred_band = first_unred_band; - } - - /* Will always be true: generate_task_input() satisfied this condition */ - if (first_unred_col[band_no] <= first_unred_col[max(first_unred_band-1,0)]) { - /* reduce the band, band_no, by all rows above that band */ - for (row = max(first_unred_col[band_no], 0); - /* row is fully reduced */ - row < local_first_unred_band * band_size; row++) {/*row fully reduced*/ - /* reduce band [row_start..row_end-1] by row */ - for (i = row_start; i < row_end; i++) - reduce_row(matrix_rows, i, row, row); /* pivot == row */ - TOPC_ATOMIC_READ(0) { - local_first_unred_band = first_unred_band; - } - } - /* This is non-zero block at or below first unreduced, diagonal block; - Diagonalize the band, band_no, in place */ - for (row = row_start; row < row_end; row++, pivot++) - for (i = row + 1; i < row_end; i++) - reduce_row(matrix_rows, i, row, pivot); - } - - /* task_out->band is now correct; Fill in other new information */ - task_out->band_no = band_no; - task_out->first_unred_band = - ( band_no == local_first_unred_band ? local_first_unred_band+1 - : local_first_unred_band ); - task_out->first_unred_col = task_out->first_unred_band * band_size; - return TOPC_MSG_PTR(task_out, sizeof_task_out); -} - -TOPC_ACTION check_task_result(int *band_ptr, struct band_info *output_ptr) -{ return UPDATE; -} - -void update_shared_data(int *band_ptr, struct band_info *output_ptr) -{ float *mat_ptr = output_ptr->band; - int i, band_no = *band_ptr; - - first_unred_col[output_ptr->band_no] - = output_ptr->first_unred_col; - for (i = band_no*band_size*n; i < (band_no+1)*band_size*n; i++) - matrix[i] = *(mat_ptr++); - if (output_ptr->first_unred_band > first_unred_band) { - /* Notify slaves of new fully reduced band now */ - TOPC_ATOMIC_WRITE(0) { - first_unred_band = output_ptr->first_unred_band; - } - } - band_is_busy[band_no] = 0; /* (Only master needs this) */ -#ifdef DEBUG -if ( TOPC_is_master() ) - { int i, j; - printf("updating band %d\n", band_no); - for (i = 0; i < n; i++, printf("\n")) - for (j = 0; j < n; j++) - printf("%5.1f ", matrix[i*n+j]); - } -#endif -} - -/* The next four callbacks set a common seed on all processes */ -unsigned int seed; -TOPC_BUF gen_seed() { - static int done = 0; - if (!done) { - seed = (unsigned int)time(NULL) >> 6; /* Use same seed for 64 seconds */ - done = 1; - return TOPC_MSG( &seed, sizeof(seed) ); - } else { - return NOTASK; - } -} -TOPC_BUF do_seed( unsigned int *ignore ) { - return TOPC_MSG( NULL, 0 ); -} -TOPC_ACTION check_seed( unsigned int *ignore, void *ignore2 ) { - return UPDATE; -} -void update_seed( unsigned int *new_seed, void *ignore ) { - seed = *new_seed; -} - -int main(int argc, char *argv[]) -{ int i, j; - TOPC_init(&argc, &argv); - - if (argc > 2 && strcmp("-p4pg", argv[argc-2])) { - // This occurs in MPICH 1.2.4 - printf("MPI bug: MPI changed value of argc;" - " Don't use argc with this MPI\n"); - exit(1); - } - if ( argc == 1) { - n = DIM; /* set dimension */ - b = BANDS; /* number of bands */ - } else { - if ( argc != 3 ) { - if (TOPC_is_master()) - printf("Usage: ./a.out DIM NUM_BANDS [ or no args to default ]\n"); - exit(1); - } - n = atoi(argv[1]); - b = atoi(argv[2]); - if (n > MAX_DIM) { - printf("dim > %d; Re-compile with larger MAX_DIM.\n", MAX_DIM); exit(1); - } - matrix = (float *)malloc(n*n*sizeof(*matrix)); - TOPC_master_slave( gen_seed, do_seed, check_seed, update_seed ); - srandom(seed); - for ( i = 0; i < n*n; i++ ) - matrix[i] = 10.0*rand()/(RAND_MAX+1.0); - } -#ifdef __cplusplus - first_unred_col = (int *)malloc(b*sizeof(*first_unred_col)); - band_is_busy = (int *)malloc(b*sizeof(*band_is_busy)); -#else - first_unred_col = malloc(b*sizeof(*first_unred_col)); - band_is_busy = malloc(b*sizeof(*band_is_busy)); -#endif - band_size = (n+b-1)/b; /* For b | n, this is just n/b */ - for (i = 0; i < b; i++) { - /* Columns 0 until first_unred_col[i] of band i are 0 cols and - next block is diagonalized; -1 means nothing diagonalized */ - first_unred_col[i] = -1; - band_is_busy[i] = 0; - } - if ( TOPC_is_master() ) { - printf("Random Matrix:\n"); - for (i = 0; i < n; i++, printf("\n")) - for (j = 0; j < n; j++) - printf("%5.1f ", matrix[i*n+j]); - } -#ifdef __cplusplus - TOPC_OPT_trace_input = (TOPC_trace_input_ptr)mytrace_input; - TOPC_OPT_trace_result = (TOPC_trace_result_ptr)mytrace_result; -#else - TOPC_OPT_trace_input = mytrace_input; - TOPC_OPT_trace_result = mytrace_result; -#endif - TOPC_OPT_trace = 2; /* 2 is default; Set to 0 for no tracing */ - TOPC_master_slave(generate_task_input, do_task, check_task_result, - update_shared_data); - if ( TOPC_is_master() ) { - printf("Result Matrix:\n"); - for (i = 0; i < n; i++, printf("\n")) - for (j = 0; j < n; j++) - printf("%5.1f ", matrix[i*n+j]); - } - TOPC_finalize(); - return 0; - } - -#if 0 -/* THIS VERSION CAN BE USED TO DRIVE A SEQUENTIAL VERSION */ -/* In this case, the parallel version required a new, more - complicated algorithm than the sequential version */ -float matrix[DIM*DIM] = {20.0, 2.0, 3.0, 4.0, 5.0, 20.0, 7.0, 8.0, - 9.0, 10.0, 20.0, 12.0, 13.0, 14.0, 15.0, 20.0}; -int main() -{ int row, i, j; - n = DIM; /* Used by reduce_row */ - void reduce_row(float *, int, int, int); - for (row = 0; row < n; row++) - for (i = row + 1; i < n; i++) - reduce_row(matrix, i, row, row); /* row already reduced */ - for (i = 0; i < n; i++, printf("\n")) - for (j = 0; j < n; j++) - printf("%5.1f ", matrix[i*n+j]); - return 0; -} -#endif diff --git a/topc-2.5.2/examples/gauss-elim-redo.c b/topc-2.5.2/examples/gauss-elim-redo.c deleted file mode 100644 index 1fadcc92..00000000 --- a/topc-2.5.2/examples/gauss-elim-redo.c +++ /dev/null @@ -1,315 +0,0 @@ -/******************************************************************** - ******************************************************************** - ** USAGE: topcc [ --seq | --mpi | --pthread ] THIS_FILE - ** ./a.out [ using default input data, or] - ** ./a.out dimension number_of_bands [ using random data ] - ** ALGORITHM: Group adjacent rows of matrix into bands (sets of rows) - ** TASK: Do Gaussian elimination on input band and then - ** use other bands to further reduce input band. - ** In this version, continue task until band is fully reduced - ** or until there was no more work to do in REDO - ** shared data: rows of matrix grouped into bands: - ** matrix, first_unred_band, first_unred_col[] (read/write) - ** n (dimension), b (number of bands), band_size (read-only) - ** task input: band number - ** task output: struct band_info: first_unred_band, first_unred_col, - ** rows of band after all possible eliminations done - ** update: copy band to shared data of all slaves - ******************************************************************** - ********************************************************************/ - -/* #define DEBUG */ -#include -#include -#include -#include // strcmp() -#include // strcmp() -#include "topc.h" - -#define MAX_DIM 100 -/* DIM is default, if no args given */ -#define DIM 4 -#define BANDS 2 -#define BAND_SIZE ((DIM+BANDS-1)/BANDS) /* For b | n, this is just n/b */ -int band_size = BAND_SIZE; -float matrix_vals[DIM*DIM] = { 20.0, 2.0, 3.0, 4.0, - 5.0, 20.0, 7.0, 8.0, - 9.0, 10.0, 20.0, 12.0, - 13.0, 14.0, 15.0, 20.0 -}; -float *matrix = matrix_vals; -/* Columns 0 up to first_unred_col[b] of band b are 0 */ -int *first_unred_col; /* BANDS elements, malloc in main() */ -int first_unred_band = 0; /* Done when first_unred_band = b */ -int *band_is_busy; /* BANDS elements, malloc in main() */ - -#define max(x,y) ( (x) < (y) ? y : x ) -struct band_info { - int band_no; - int first_unred_band; - int first_unred_col; - /* Next two fields support decisions whether to REDO */ - int do_update; - int prev_unred_col; - /* float band[BAND_SIZE * DIM]; */ - /* task_out will use dynamically allocated space to extend band: - * malloc( sizeof(struct band_info_info)+BAND_SIZE * DIM*sizeof(float) ) - */ - float band[1]; -}; - -void mytrace_input ( int *in_msg ) -{ printf("band %d", *in_msg); -} -void mytrace_result ( int *ignore, struct band_info *out_msg ) -{ printf("row vector: %5.1f %5.1f ...", - (out_msg->band)[0], out_msg->band[1] ); -} - -/* These will be set to DIM and BANDS inside main() */ -int n, b; /* n = matrix dimension; b = number of bands */ - -void reduce_row(float *matrix_rows[], int row_to_red, int row, int pivot) -{ float scalar = matrix_rows[row_to_red][pivot] / matrix_rows[row][pivot]; - float *row1 = matrix_rows[row_to_red]; - float *row2 = matrix_rows[row]; - int j; - -#ifdef DEBUG - printf("reducing row %d, using row %d and pivot %d\n", row_to_red,row,pivot); -#endif - row1[pivot] = 0; - for (j = pivot+1; j < n; j++) - row1[j] = row1[j] - scalar * row2[j]; -} - -TOPC_BUF generate_task_input() { - static int i; - - for (i = first_unred_band; i < b ; i++) - /* First condition checks that last reduced band can be used to reduce - band number i; Otherwise, delay starting this task */ - if (first_unred_col[i] <= first_unred_col[max(first_unred_band-1,0)] - && band_is_busy[i] == 0) { - band_is_busy[i] = 1; - return TOPC_MSG(&i, sizeof(i)); } - return NOTASK; } - -/* FOR EFFICIENCY ONLY: (avoid copying task_out, as done by TOPC_MSG()) - * TOPC_thread_private illustrates how to make TOPC_MSG_PTR() in do_task() - * compatible with shared memory model. - * Most programs would use TOPC_MSG(), allocate task_out locally on stack, - * and TOPC_MSG() would copy it to the TOP-C address space. - * Ideally, if C allowed it, we would just write: - * THREAD_PRIVATE struct band_info *global_output = NULL; - * and the first call to do_task() would malloc the memory. - * Instead, we write this extra code for full generality, to run in the - * shared memory model or any other memory model. - */ -typedef struct band_info *TOPC_thread_private_t; -#define task_out TOPC_thread_private -TOPC_thread_private_t task_out_debug() { /* needed for debugging in gdb */ - return task_out; -} - -#define sizeof_task_out (sizeof(struct band_info) + n*band_size*sizeof(*matrix)) - -TOPC_BUF do_task(int *band_ptr) /* 0 <= band_no <= b - 1 */ -{ int band_no = *band_ptr; - int row_start = band_no * band_size; - int row_end = (band_no + 1) * band_size; - int row, i, j, k; - int pivot = max(first_unred_col[max(first_unred_band-1,0)], 0); - /* float *matrix_rows[DIM]; */ - float *matrix_rows[MAX_DIM]; - - /* Create array of matrix rows */ - for (row = 0; row < n; row++) - matrix_rows[row] = &matrix[row*n]; - - /* If REDO, intervening UPDATE changed matrix[] but not for our band_no */ - if (!TOPC_is_REDO()) { - if ((void *)task_out == NULL) -# ifdef __cplusplus - task_out = (struct band_info *)malloc( sizeof_task_out ); -# else - task_out = malloc( sizeof_task_out ); -# endif - /* Copy over the band to be modified */ - for (i = 0, k = 0; i < band_size; i++) /* copy band */ - for (j = 0; j < n; j++, k++) - task_out->band[k] = matrix_rows[band_no*band_size+i][j]; - } /* end if (!TOPC_is_REDO()) ... */ - - /* Set matrix_rows to use the band to be modified */ - for (i = 0; i < band_size; i++) - matrix_rows[band_no*band_size+i] = &task_out->band[i*n]; - - /* Will always be true: generate_task_input() satisfied this condition */ - if (first_unred_col[band_no] <= first_unred_col[max(first_unred_band-1,0)]) { - /* reduce the band, band_no, by all rows above that band */ - for (row = max(first_unred_col[band_no], 0); - row < first_unred_band * band_size; row++) /* row is fully reduced */ - /* reduce band [row_start..row_end-1] by row */ - for (i = row_start; i < row_end; i++) - reduce_row(matrix_rows, i, row, row); /* pivot == row */ - /* This is non-zero block at or below first unreduced, diagonal block; - Diagonalize the band, band_no, in place */ - for (row = row_start; row < row_end; row++, pivot++) - for (i = row + 1; i < row_end; i++) - reduce_row(matrix_rows, i, row, pivot); - } - - /* task_out->band is now correct; Fill in other new information */ - task_out->band_no = band_no; - task_out->first_unred_band = - ( band_no == first_unred_band ? first_unred_band+1 : first_unred_band ); - task_out->first_unred_col = task_out->first_unred_band * band_size; - - task_out->do_update = (task_out->first_unred_band > band_no); - if (TOPC_is_REDO() - && task_out->prev_unred_col == first_unred_col[max(first_unred_band-1,0)]) - task_out->do_update = 0; - task_out->prev_unred_col = first_unred_col[max(first_unred_band-1,0)]; - return TOPC_MSG_PTR(task_out, sizeof_task_out); -} - -TOPC_ACTION check_task_result(int *band_ptr, struct band_info *output_ptr) -{ - if (output_ptr->do_update) return UPDATE; - else return REDO; -} - -void update_shared_data(int *band_ptr, struct band_info *output_ptr) -{ float *mat_ptr = output_ptr->band; - int i, band_no = *band_ptr; - - if (output_ptr->first_unred_band > first_unred_band) - first_unred_band = output_ptr->first_unred_band; - first_unred_col[output_ptr->band_no] - = output_ptr->first_unred_col; - for (i = band_no*band_size*n; i < (band_no+1)*band_size*n; i++) - matrix[i] = *(mat_ptr++); - band_is_busy[band_no] = 0; /* (Only master needs this) */ -#ifdef DEBUG -if ( TOPC_is_master() ) - { int i, j; - printf("updating band %d\n", band_no); - for (i = 0; i < n; i++, printf("\n")) - for (j = 0; j < n; j++) - printf("%5.1f ", matrix[i*n+j]); - } -#endif -} - -/* The next four callbacks set a common seed on all processes */ -unsigned int seed; -TOPC_BUF gen_seed() { - static int done = 0; - if (!done) { - seed = (unsigned int)time(NULL) >> 6; /* Use same seed for 64 seconds */ - done = 1; - return TOPC_MSG( &seed, sizeof(seed) ); - } else { - return NOTASK; - } -} -TOPC_BUF do_seed( unsigned int *ignore ) { - return TOPC_MSG( NULL, 0 ); -} -TOPC_ACTION check_seed( unsigned int *ignore, void *ignore2 ) { - return UPDATE; -} -void update_seed( unsigned int *new_seed, void *ignore ) { - seed = *new_seed; -} - -int main(int argc, char *argv[]) -{ int i, j; - TOPC_init(&argc, &argv); - - if (argc > 2 && strcmp("-p4pg", argv[argc-2])) { - // This occurs in MPICH 1.2.4 - printf("MPI bug: MPI changed value of argc;" - " Don't use argc with this MPI\n"); - exit(1); - } - if ( argc == 1) { - n = DIM; /* set dimension */ - b = BANDS; /* number of bands */ - } else { - if ( argc != 3 ) { - if (TOPC_is_master()) - printf("Usage: ./a.out DIM NUM_BANDS [ or no args to default ]\n"); - exit(1); - } - n = atoi(argv[1]); - b = atoi(argv[2]); - if (n > MAX_DIM) { - printf("dim > %d; Re-compile with larger MAX_DIM.\n", MAX_DIM); exit(1); - } - matrix = (float *)malloc(n*n*sizeof(*matrix)); - TOPC_master_slave( gen_seed, do_seed, check_seed, update_seed ); - srandom(seed); - for ( i = 0; i < n*n; i++ ) - matrix[i] = 10.0*rand()/(RAND_MAX+1.0); - } -#ifdef __cplusplus - first_unred_col = (int *)malloc(b*sizeof(*first_unred_col)); - band_is_busy = (int *)malloc(b*sizeof(*band_is_busy)); -#else - first_unred_col = malloc(b*sizeof(*first_unred_col)); - band_is_busy = malloc(b*sizeof(*band_is_busy)); -#endif - band_size = (n+b-1)/b; /* For b | n, this is just n/b */ - for (i = 0; i < b; i++) { - /* Columns 0 until first_unred_col[i] of band i are 0 cols and - next block is diagonalized; -1 means nothing diagonalized */ - first_unred_col[i] = -1; - band_is_busy[i] = 0; - } - if ( TOPC_is_master() ) { - printf("Random Matrix:\n"); - for (i = 0; i < n; i++, printf("\n")) - for (j = 0; j < n; j++) - printf("%5.1f ", matrix[i*n+j]); - } -#ifdef __cplusplus - TOPC_OPT_trace_input = (TOPC_trace_input_ptr)mytrace_input; - TOPC_OPT_trace_result = (TOPC_trace_result_ptr)mytrace_result; -#else - TOPC_OPT_trace_input = mytrace_input; - TOPC_OPT_trace_result = mytrace_result; -#endif - TOPC_OPT_trace = 2; /* 2 is default; Set to 0 for no tracing */ - TOPC_master_slave(generate_task_input, do_task, check_task_result, - update_shared_data); - if ( TOPC_is_master() ) { - printf("Result Matrix:\n"); - for (i = 0; i < n; i++, printf("\n")) - for (j = 0; j < n; j++) - printf("%5.1f ", matrix[i*n+j]); - } - TOPC_finalize(); - return 0; - } - -#if 0 -/* THIS VERSION CAN BE USED TO DRIVE A SEQUENTIAL VERSION */ -/* In this case, the parallel version required a new, more - complicated algorithm than the sequential version */ -float matrix[DIM*DIM] = {20.0, 2.0, 3.0, 4.0, 5.0, 20.0, 7.0, 8.0, - 9.0, 10.0, 20.0, 12.0, 13.0, 14.0, 15.0, 20.0}; -int main() -{ int row, i, j; - n = DIM; /* Used by reduce_row */ - void reduce_row(float *, int, int, int); - for (row = 0; row < n; row++) - for (i = row + 1; i < n; i++) - reduce_row(matrix, i, row, row); /* row already reduced */ - for (i = 0; i < n; i++, printf("\n")) - for (j = 0; j < n; j++) - printf("%5.1f ", matrix[i*n+j]); - return 0; -} -#endif diff --git a/topc-2.5.2/examples/gauss-elim.c b/topc-2.5.2/examples/gauss-elim.c deleted file mode 100644 index e2ae14a0..00000000 --- a/topc-2.5.2/examples/gauss-elim.c +++ /dev/null @@ -1,296 +0,0 @@ -/******************************************************************** - ******************************************************************** - ** USAGE: topcc [ --seq | --mpi | --pthread ] THIS_FILE - ** ./a.out [ using default input data, or] - ** ./a.out dimension number_of_bands [ using random data ] - ** ALGORITHM: Group adjacent rows of matrix into bands (sets of rows) - ** TASK: Do Gaussian elimination on input band and then - ** use other bands to further reduce input band. - ** shared data: rows of matrix grouped into bands: - ** matrix, first_unred_band, first_unred_col[] (read/write) - ** n (dimension), b (number of bands), band_size (read-only) - ** task input: band number - ** task output: struct band_info: first_unred_band, first_unred_col, - ** rows of band after all possible eliminations done - ** update: copy band to shared data of all slaves - ** FOR A LARGER RUN, INVOKE BINARY AS: ./a.out 120 30 - ******************************************************************** - ********************************************************************/ - -/* #define DEBUG */ -#include -#include -#include -#include // strcmp() -#include // strcmp() -#include "topc.h" - -#define MAX_DIM 1000 -/* DIM is default, if no args given */ -#define DIM 4 -#define BANDS 2 -#define BAND_SIZE ((DIM+BANDS-1)/BANDS) /* For b | n, this is just n/b */ -int band_size = BAND_SIZE; -float matrix_vals[DIM*DIM] = { 20.0, 2.0, 3.0, 4.0, - 5.0, 20.0, 7.0, 8.0, - 9.0, 10.0, 20.0, 12.0, - 13.0, 14.0, 15.0, 20.0 -}; -float *matrix = matrix_vals; -/* Columns 0 up to first_unred_col[b] of band b are 0 */ -int *first_unred_col; /* BANDS elements, malloc in main() */ -int first_unred_band = 0; /* Done when first_unred_band = b */ -int *band_is_busy; /* BANDS elements, malloc in main() */ - -#define max(x,y) ( (x) < (y) ? y : x ) -struct band_info { - int band_no; - int first_unred_band; - int first_unred_col; - /* float band[BAND_SIZE * DIM]; */ - /* task_out will use dynamically allocated space to extend band: - * malloc( sizeof(struct band_info)+BAND_SIZE * DIM*sizeof(float) ) - */ - float band[1]; -}; - -void mytrace_input ( int *in_msg ) -{ printf("band %d", *in_msg); -} -void mytrace_result ( int *ignore, struct band_info *out_msg ) -{ printf("row vector: %5.1f %5.1f ...", - (out_msg->band)[0], out_msg->band[1] ); -} - -/* These will be set to DIM and BANDS inside main() */ -int n, b; /* n = matrix dimension; b = number of bands */ - -void reduce_row(float *matrix_rows[], int row_to_red, int row, int pivot) -{ float scalar = matrix_rows[row_to_red][pivot] / matrix_rows[row][pivot]; - float *row1 = matrix_rows[row_to_red]; - float *row2 = matrix_rows[row]; - int j; - -#ifdef DEBUG - printf("reducing row %d, using row %d and pivot %d\n", row_to_red,row,pivot); -#endif - row1[pivot] = 0; - for (j = pivot+1; j < n; j++) - row1[j] = row1[j] - scalar * row2[j]; -} - -TOPC_BUF generate_task_input() { - static int i; - - for (i = first_unred_band; i < b ; i++) - if (first_unred_col[i] <= first_unred_col[max(first_unred_band-1,0)] - && band_is_busy[i] == 0) { - band_is_busy[i] = 1; - return TOPC_MSG(&i, sizeof(i)); } - return NOTASK; } - -/* FOR EFFICIENCY ONLY: (avoid copying task_out, as done by TOPC_MSG()) - * TOPC_thread_private illustrates how to make TOPC_MSG_PTR() in do_task() - * compatible with shared memory model. - * Most programs would use TOPC_MSG(), allocate task_out locally on stack, - * and TOPC_MSG() would copy it to the TOP-C address space. - * Ideally, if C allowed it, we would just write: - * THREAD_PRIVATE struct band_info *global_output = NULL; - * and the first call to do_task() would malloc the memory. - * Instead, we write this extra code for full generality, to run in the - * shared memory model or any other memory model. - */ -typedef struct band_info *TOPC_thread_private_t; -#define task_out TOPC_thread_private -TOPC_thread_private_t task_out_debug() { /* needed for debugging in gdb */ - return task_out; -} - -#define sizeof_task_out (sizeof(struct band_info) + n*band_size*sizeof(*matrix)) - -TOPC_BUF do_task(int *band_ptr) /* 0 <= band_no <= b - 1 */ -{ int band_no = *band_ptr; - int row_start = band_no * band_size; - int row_end = (band_no + 1) * band_size; - int row, i, j, k; - int pivot = max(first_unred_col[max(first_unred_band-1,0)], 0); - /* float *matrix_rows[DIM]; */ - float *matrix_rows[MAX_DIM]; - - if ((void *)task_out == NULL) -# ifdef __cplusplus - task_out = (struct band_info *)malloc( sizeof_task_out ); -# else - task_out = malloc( sizeof_task_out ); -# endif - /* Create array of matrix rows */ - for (row = 0; row < n; row++) - matrix_rows[row] = &matrix[row*n]; - /* Copy over the band to be modified */ - for (i = 0, k = 0; i < band_size; i++) /* copy band */ - for (j = 0; j < n; j++, k++) - task_out->band[k] = matrix_rows[band_no*band_size+i][j]; - /* Set matrix_rows to use the band to be modified */ - for (i = 0; i < band_size; i++) - matrix_rows[band_no*band_size+i] = &task_out->band[i*n]; - - /* Will always be true: generate_task_input() satisfied this condition */ - if (first_unred_col[band_no] <= first_unred_col[max(first_unred_band-1,0)]) { - /* reduce the band, band_no, by all rows above that band */ - for (row = max(first_unred_col[band_no], 0); - row < first_unred_band * band_size; row++) /* row is fully reduced */ - /* reduce band [row_start..row_end-1] by row */ - for (i = row_start; i < row_end; i++) - reduce_row(matrix_rows, i, row, row); /* pivot == row */ - /* This is non-zero block at or below first unreduced, diagonal block; - Diagonalize the band, band_no, in place */ - for (row = row_start; row < row_end; row++, pivot++) - for (i = row + 1; i < row_end; i++) - reduce_row(matrix_rows, i, row, pivot); - } - - /* task_out->band is now correct; Fill in other new information */ - task_out->band_no = band_no; - task_out->first_unred_band = - ( band_no == first_unred_band ? first_unred_band+1 : first_unred_band ); - task_out->first_unred_col = task_out->first_unred_band * band_size; - return TOPC_MSG_PTR(task_out, sizeof_task_out); -} - -TOPC_ACTION check_task_result(int *band_ptr, struct band_info *output_ptr) -{ return UPDATE; -} - -void update_shared_data(int *band_ptr, struct band_info *output_ptr) -{ float *mat_ptr = output_ptr->band; - int i, band_no = *band_ptr; - - if (output_ptr->first_unred_band > first_unred_band) - first_unred_band = output_ptr->first_unred_band; - first_unred_col[output_ptr->band_no] - = output_ptr->first_unred_col; - for (i = band_no*band_size*n; i < (band_no+1)*band_size*n; i++) - matrix[i] = *(mat_ptr++); - band_is_busy[band_no] = 0; /* (Only master needs this) */ -#ifdef DEBUG -if ( TOPC_is_master() ) - { int i, j; - printf("updating band %d\n", band_no); - for (i = 0; i < n; i++, printf("\n")) - for (j = 0; j < n; j++) - printf("%5.1f ", matrix[i*n+j]); - } -#endif -} - -/* The next four callbacks set a common seed on all processes */ -unsigned int seed; -TOPC_BUF gen_seed() { - static int done = 0; - if (!done) { - seed = (unsigned int)time(NULL) >> 6; /* Use same seed for 64 seconds */ - done = 1; - return TOPC_MSG( &seed, sizeof(seed) ); - } else { - return NOTASK; - } -} -TOPC_BUF do_seed( unsigned int *ignore ) { - return TOPC_MSG( NULL, 0 ); -} -TOPC_ACTION check_seed( unsigned int *ignore, void *ignore2 ) { - return UPDATE; -} -void update_seed( unsigned int *new_seed, void *ignore ) { - seed = *new_seed; -} - -int main(int argc, char *argv[]) -{ int i, j; - TOPC_init(&argc, &argv); - - if (argc > 2 && strcmp("-p4pg", argv[argc-2])) { - // This occurs in MPICH 1.2.4 - printf("MPI bug: MPI changed value of argc;" - " Don't use argc with this MPI\n"); - exit(1); - } - if ( argc == 1) { - n = DIM; /* set dimension */ - b = BANDS; /* number of bands */ - } else { - if ( argc != 3 ) { - if (TOPC_is_master()) - printf("Usage: ./a.out DIM NUM_BANDS [ or no args to default ]\n"); - exit(1); - } - n = atoi(argv[1]); - b = atoi(argv[2]); - if (n > MAX_DIM) { - printf("dim > %d; Re-compile with larger MAX_DIM.\n", MAX_DIM); exit(1); - } - matrix = (float *)malloc(n*n*sizeof(*matrix)); - TOPC_master_slave( gen_seed, do_seed, check_seed, update_seed ); - srandom(seed); - for ( i = 0; i < n*n; i++ ) - matrix[i] = 10.0*rand()/(RAND_MAX+1.0); - } -#ifdef __cplusplus - first_unred_col = (int *)malloc(b*sizeof(*first_unred_col)); - band_is_busy = (int *)malloc(b*sizeof(*band_is_busy)); -#else - first_unred_col = malloc(b*sizeof(*first_unred_col)); - band_is_busy = malloc(b*sizeof(*band_is_busy)); -#endif - band_size = (n+b-1)/b; /* For b | n, this is just n/b */ - for (i = 0; i < b; i++) { - /* Columns 0 until first_unred_col[i] of band i are 0 cols and - next block is diagonalized; -1 means nothing diagonalized */ - first_unred_col[i] = -1; - band_is_busy[i] = 0; - } - if ( TOPC_is_master() ) { - printf("Random Matrix:\n"); - for (i = 0; i < n; i++, printf("\n")) - for (j = 0; j < n; j++) - printf("%5.1f ", matrix[i*n+j]); - } -#ifdef __cplusplus - TOPC_OPT_trace_input = (TOPC_trace_input_ptr)mytrace_input; - TOPC_OPT_trace_result = (TOPC_trace_result_ptr)mytrace_result; -#else - TOPC_OPT_trace_input = mytrace_input; - TOPC_OPT_trace_result = mytrace_result; -#endif - TOPC_OPT_trace = 2; /* 2 is default; Set to 0 for no tracing */ - TOPC_master_slave(generate_task_input, do_task, check_task_result, - update_shared_data); - if ( TOPC_is_master() ) { - printf("Result Matrix:\n"); - for (i = 0; i < n; i++, printf("\n")) - for (j = 0; j < n; j++) - printf("%5.1f ", matrix[i*n+j]); - } - TOPC_finalize(); - return 0; - } - -#if 0 -/* THIS VERSION CAN BE USED TO DRIVE A SEQUENTIAL VERSION */ -/* In this case, the parallel version required a new, more - complicated algorithm than the sequential version */ -float matrix[DIM*DIM] = {20.0, 2.0, 3.0, 4.0, 5.0, 20.0, 7.0, 8.0, - 9.0, 10.0, 20.0, 12.0, 13.0, 14.0, 15.0, 20.0}; -int main() -{ int row, i, j; - n = DIM; /* Used by reduce_row */ - void reduce_row(float *, int, int, int); - for (row = 0; row < n; row++) - for (i = row + 1; i < n; i++) - reduce_row(matrix, i, row, row); /* row already reduced */ - for (i = 0; i < n; i++, printf("\n")) - for (j = 0; j < n; j++) - printf("%5.1f ", matrix[i*n+j]); - return 0; -} -#endif diff --git a/topc-2.5.2/examples/par8queens-abort.c b/topc-2.5.2/examples/par8queens-abort.c deleted file mode 100644 index f2e8a9a9..00000000 --- a/topc-2.5.2/examples/par8queens-abort.c +++ /dev/null @@ -1,144 +0,0 @@ -/******************************************************************** - ******************************************************************** - ** USAGE: topcc [ --seq | --mpi | --pthread ] THIS_FILE - ** ALGORITHM: 8 queens, recursive solution (abort slaves after first sol.) - ** shared data: none - ** task input: column to place queen from first row - ** task output: positions of 8 queens - ** update: none - ** NOTE: Redefine NQUEENS to other than 8 for other size boards - ******************************************************************** - ********************************************************************/ - -#include -#include -#include -#include -#include "topc.h" - -#define NQUEENS 8 -#define SIZEOF_SOL (NQUEENS*sizeof(int)) -#define MAX_SOLS 10000 - -static int done = 0; - -int check( int cols[], int new_row, int new_col ) { - int row; - for ( row = 0; row < new_row; row++ ) { - if ( (new_col == cols[row]) - || (new_col-cols[row] == new_row-row) - || (new_col-cols[row] == row-new_row) ) - return 0; - } - cols[new_row] = new_col; - return 1; -} - -TOPC_BUF generate_task_input() { - static int col0 = -1; - col0++; - if (col0 >= NQUEENS || done) return NOTASK; - else return TOPC_MSG( &col0, sizeof(col0) ); -} - -/* FOR EFFICIENCY ONLY: (avoid copying cols, as done by TOPC_MSG()) - * TOPC_thread_private illustrates how to make TOPC_MSG_PTR() in do_task() - * compatible with shared memory model. - * Most programs would use TOPC_MSG(), allocate task_out locally on stack, - * and TOPC_MSG() would copy it to the TOP-C address space. - * Ideally, if C allowed it, we would just write: - * THREAD_PRIVATE int *cols = NULL; - * and the first call to do_task() would malloc the memory. - */ -typedef int *TOPC_thread_private_t; -#define cols TOPC_thread_private -TOPC_thread_private_t cols_debug() { /* needed for debugging in gdb */ - return cols; -} - -TOPC_BUF do_task( int *input ) { - int col0 = *input, col1, col2, col3, col4, col5, col6, col7; - - if (cols == NULL) -# ifdef __cplusplus - /* initialize to all zero: */ - cols = (int *)calloc(NQUEENS, sizeof(*cols)); -# else - cols = calloc(NQUEENS, sizeof(*cols)); /* initialize to all zero */ -# endif - cols[0] = col0; - - for ( col1 = 0; col1 < NQUEENS; col1++ ) { - if ( ! check( cols, 1, col1 ) ) continue; /* try next column */ - for ( col2 = 0; col2 < NQUEENS; col2++ ) { - if ( ! check( cols, 2, col2 ) ) continue; /* try next column */ - for ( col3 = 0; col3 < NQUEENS; col3++ ) { - if ( ! check( cols, 3, col3 ) ) continue; /* try next column */ - for ( col4 = 0; col4 < NQUEENS; col4++ ) { - if ( ! check( cols, 4, col4 ) ) continue; /* try next column */ - for ( col5 = 0; col5 < NQUEENS; col5++ ) { - if ( ! check( cols, 5, col5 ) ) continue; /* try next column */ - for ( col6 = 0; col6 < NQUEENS; col6++ ) { - if (TOPC_is_abort_pending()) { - fprintf(stderr, "Slave %d aborting.\n", TOPC_rank()); - fprintf(stderr, "Checked so far: [%d, %d, %d, %d, %d, %d, %d, -]\n", - col0, col1, col2, col3, col4, col5, col6); - } /* It works to call TOPC_is_abort_pending() several times in a task */ - if (TOPC_is_abort_pending()) - return TOPC_MSG(NULL,0); - if ( ! check( cols, 6, col6 ) ) continue; /* try next column */ - for ( col7 = 0; col7 < NQUEENS; col7++ ) { - if ( check( cols, 7, col7 ) ) - return TOPC_MSG_PTR(cols, SIZEOF_SOL); - } } } } } } } - return TOPC_MSG(NULL,0); -} - -int global_output[NQUEENS]; - -TOPC_ACTION check_task_result( int *input, int *output ) { - if (done) - return NO_ACTION; - if (output) { - printf("Found solution for col0 = %d; aborting tasks.\n", *input); - TOPC_abort_tasks(); - } - memcpy( global_output, output, NQUEENS*sizeof(*output) ); - done = 1; - /* If output == NULL (no solution), leave slave idle */ - return NO_ACTION; -} - -void trace_input(int *col0) { - printf("col0: %d", *col0); -} -int main( int argc, char **argv ) { - TOPC_OPT_trace=2; -#ifdef __cplusplus - TOPC_OPT_trace_input = (TOPC_trace_input_ptr)trace_input; -#else - TOPC_OPT_trace_input = trace_input; -#endif - TOPC_init( &argc, &argv ); - TOPC_master_slave( generate_task_input, do_task, check_task_result, NULL ); - TOPC_finalize(); - - if (TOPC_is_master()) { - int *x; - - x = global_output; - printf("first solution: %d %d %d %d %d %d %d %d\n", - x[0], x[1], x[2], x[3], x[4], x[5], x[6], x[7]); - /* - for (col0=0; col0 -#include -#include -#include -#include "topc.h" - -#define NQUEENS 8 -#define SIZEOF_SOL (NQUEENS*sizeof(int)) -#define MAX_SOLS 10000 - -int check( int cols[], int new_row, int new_col ) { - int row; - for ( row = 0; row < new_row; row++ ) { - if ( (new_col == cols[row]) - || (new_col-cols[row] == new_row-row) - || (new_col-cols[row] == row-new_row) ) - return 0; - } - cols[new_row] = new_col; - return 1; -} - -void record_sols( int sols[][NQUEENS], int sol[NQUEENS], int *num_sols ) { - memcpy( &sols[*num_sols][0], sol, SIZEOF_SOL); - (*num_sols)++; - assert(*num_sols <= MAX_SOLS); -} - -/* FOR EFFICIENCY ONLY: (avoid copying global_output, as done by TOPC_MSG()) - * TOPC_thread_private illustrates how to make TOPC_MSG_PTR() in do_task() - * compatible with shared memory model. - * Most programs would use TOPC_MSG(), allocate task_out locally on stack, - * and TOPC_MSG() would copy it to the TOP-C address space. - * Ideally, if C allowed it, we would just write: - * THREAD_PRIVATE struct band *global_output = NULL; - * and the first call to do_task() would malloc the memory. - */ -typedef struct out { int num_sols; int sols[MAX_SOLS][NQUEENS]; } - TOPC_thread_private_t; -#define global_output TOPC_thread_private -TOPC_thread_private_t global_output_debug() { /* needed for debugging in gdb */ - return global_output; -} - -void trace_result(int cols[], struct out *output) -{ printf(" cols: %d %d %d %d %d\n", - cols[0], cols[1], cols[2], cols[3], cols[4]), - printf(" output->num_sols, global_output.num_sols: %d\n", - output->num_sols, global_output.num_sols); -} - -TOPC_BUF do_task( int *cols ) { - int *sols, num_sols = 0; - int col4, col5, col6, col7; - - sols = (int *)(global_output.sols); - - for ( col4 = 0; col4 < NQUEENS; col4++ ) { - if ( ! check( cols, 4, col4 ) ) continue; /* try next column */ - for ( col5 = 0; col5 < NQUEENS; col5++ ) { - if ( ! check( cols, 5, col5 ) ) continue; /* try next column */ - for ( col6 = 0; col6 < NQUEENS; col6++ ) { - if ( ! check( cols, 6, col6 ) ) continue; /* try next column */ - for ( col7 = 0; col7 < NQUEENS; col7++ ) { - if ( check( cols, 7, col7 ) ) - record_sols( (int (*)[NQUEENS])sols, cols, &num_sols ); - } } } } - - global_output.num_sols = num_sols; - return TOPC_MSG_PTR( &global_output, - (char *)(global_output.sols[num_sols]) - - (char *)&global_output ); -} -TOPC_ACTION check_task_result( int *dummy, struct out *output ) { - if (output->num_sols > 0) { - memcpy( (global_output.sols[global_output.num_sols]), - output->sols, - (output->num_sols)*SIZEOF_SOL ); - global_output.num_sols += output->num_sols; - } - return NO_ACTION; -} - -int main( int argc, char **argv ) { - int cols[NQUEENS], (*sols)[NQUEENS]; - int col0, col1, col2, col3; - - global_output.num_sols = 0; - - TOPC_OPT_trace=0; -#ifdef __cplusplus - TOPC_OPT_trace_result = (TOPC_trace_result_ptr)trace_result; -#else - TOPC_OPT_trace_result = trace_result; -#endif - TOPC_init( &argc, &argv ); - TOPC_raw_begin_master_slave( do_task, check_task_result, NULL ); - if (TOPC_is_master()) { - for ( col0 = 0; col0 < NQUEENS; col0++ ) { - check( cols, 0, col0 ); /* This sets cols[0]=col0; */ - for ( col1 = 0; col1 < NQUEENS; col1++ ) { - if ( ! check( cols, 1, col1 ) ) continue; /* try next column */ - for ( col2 = 0; col2 < NQUEENS; col2++ ) { - if ( ! check( cols, 2, col2 ) ) continue; /* try next column */ - for ( col3 = 0; col3 < NQUEENS; col3++ ) { - if ( ! check( cols, 3, col3 ) ) continue; /* try next column */ - else TOPC_raw_submit_task_input( TOPC_MSG(cols, SIZEOF_SOL) ); - } } } } } - TOPC_raw_end_master_slave(); - TOPC_finalize(); - - if (TOPC_is_master()) { - printf("number of solutions: %d\n", global_output.num_sols); - if (global_output.num_sols != 92) { - printf("INTERNAL ERROR: It should have been 82.\n"); - exit(1); - } - /* slave tasks can return in different order than originated */ - sols = (int (*)[NQUEENS])(global_output.sols); - printf("middle solution (approx %d-th solution): %d %d %d %d %d %d %d %d\n", - global_output.num_sols/2+1, - sols[global_output.num_sols/2][0], sols[global_output.num_sols/2][1], - sols[global_output.num_sols/2][2], sols[global_output.num_sols/2][3], - sols[global_output.num_sols/2][4], sols[global_output.num_sols/2][5], - sols[global_output.num_sols/2][6], sols[global_output.num_sols/2][7] - ); - /* - for (col0=0; col0 // atoi() -#include // strcmp() -#include // strcmp() -#include "topc.h" - -#ifndef TASK_INTERVAL -#define TASK_INTERVAL 1000 -#endif - -#ifndef FALSE -enum {FALSE, TRUE}; -#endif - -// Used if TOPC_OPT_trace == 2, or: ./a.out --TOPC-trace=2 -void trace_input( long *input ) { printf("%ld", *input); } -void trace_result( long *input, long *output ) { - if (*output == 1) printf("TRUE"); - if (*output == 0) printf("FALSE"); -} - -long factors[1000], max_factor=1, num_to_factor; -void MasSlaveFactor( long ); - -int main(int argc, char *argv[]) -{ - int i; - char *arg = argv[1]; - -#ifdef __cplusplus - TOPC_OPT_trace_input = (TOPC_trace_input_ptr)trace_input; - TOPC_OPT_trace_result = (TOPC_trace_result_ptr)trace_result; -#else - TOPC_OPT_trace_input = trace_input; - TOPC_OPT_trace_result = trace_result; -#endif - TOPC_OPT_trace = 2; - TOPC_init(&argc, &argv); - if (argc > 2 && strcmp("-p4pg", argv[argc-2])) { - // This occurs in MPICH 1.2.4 - printf("MPI bug: MPI changed value of argc;" - " Don't use argc with this MPI\n"); - exit(1); - } - // Important: Inspect command line only after TOPC_init() - if (argc == 1 ) { - if (TOPC_is_master()) - printf("WARNING: Missing number arg on command line. Using 123456789\n"); - arg = "123456789"; - } - - MasSlaveFactor( strtol(arg, NULL, 10) );/* No error checking in this vers. */ - if ( TOPC_is_master() ) { - for (i = 1; i <= factors[ 0 ]; i++) printf("%ld ", factors[i]); - printf("\n"); } - TOPC_finalize(); - // printf("%d: Exiting\n", TOPC_rank()); fflush(stdout); - return 0; -} - -TOPC_BUF DoTask( long *input ) -{ - long limit; - long num = *input; - long task_out; - - // printf("DoTask(%d)\n", num); fflush(stdout); - limit = num + TASK_INTERVAL; - for ( ; num < limit; num++ ) - if (num_to_factor % num == 0) { - // printf("%d: DoTask returning 1\n", TOPC_rank()); fflush(stdout); - task_out = 1; - return TOPC_MSG(&task_out, sizeof(long)); - } - // printf("%d: DoTask returning 0\n", TOPC_rank()); fflush(stdout); - task_out = 0; - return TOPC_MSG(&task_out, sizeof(long)); -} - -TOPC_ACTION CheckTaskResult( long *input, long *output ) -{ - // printf("CheckTaskResult()\n"); fflush(stdout); - if ( *output == 0 ) return NO_ACTION; - // NOTE: Suppose we factor 12, 2 is outstanding, and 4 is reported to factor - if ( *input < max_factor ) return UPDATE; - if ( TOPC_is_up_to_date() ) return UPDATE; - return REDO; -} - -void UpdateSharedMemory( long *input, long *output ) -{ - long limit, num = *input; - int i; - // printf("%d: UpdateSharedMemory()\n", TOPC_rank()); fflush(stdout); - limit = num + TASK_INTERVAL; - // NOTE: Suppose we factor 12, 4 is reported as factor before 2 is reported - for ( ; num < limit; num++ ) { - if ( num_to_factor % num == 0 ) { - if ( num < max_factor ) { - max_factor = 1; // re-compute max_factor - for( i = 1; i <= factors[0]; i++ ) { - if (factors[i] > max_factor) max_factor = factors[i]; - while (factors[i] % num == 0) { - factors[i] = factors[i] / num; - num_to_factor = num_to_factor * num; - } - } - } - while (num_to_factor % num == 0) { - factors[ ++factors[0] ] = num; - num_to_factor = num_to_factor / num; - if (num_to_factor == 1) return; - } - } - } -} - -void MasSlaveFactor( long num ) -{ long last_num; - - factors[0]=0; - num_to_factor = num; - //printf("Entering master_slave()\n"); fflush(stdout); - TOPC_raw_begin_master_slave(DoTask, CheckTaskResult, - UpdateSharedMemory); - for ( last_num = 2; last_num <= num_to_factor; last_num += TASK_INTERVAL ) - TOPC_raw_submit_task_input(TOPC_MSG(&last_num, sizeof(last_num))); - TOPC_raw_end_master_slave(); -} diff --git a/topc-2.5.2/examples/parfactor.c b/topc-2.5.2/examples/parfactor.c deleted file mode 100644 index 152e4cda..00000000 --- a/topc-2.5.2/examples/parfactor.c +++ /dev/null @@ -1,154 +0,0 @@ -/******************************************************************** - ******************************************************************** - ** USAGE: topcc [ --seq | --mpi | --pthread ] THIS_FILE - ** ALGORITHM: Euclidean sieve for factorization - ** shared data: num_to_factor (divided by each factor found) - ** task input: input (test factor for num_to_factor) - ** task output: 1 or 0 (true or false) - ** update: Divide num_to_factor by num - ******************************************************************** - ********************************************************************/ - -#include // for atol() [ Note long is only 32 bits on many mach's] -#include // for LONG_MAX -#include -#include // for strcmp -#include // for strcmp -#include "topc.h" - -#ifndef TASK_INTERVAL -#define TASK_INTERVAL 1000 -#endif - -// Used if TOPC_OPT_trace == 2, or: ./a.out --TOPC-trace=2 -void trace_input( long *input ) { printf("%ld", *input); } -void trace_result( long *input, long *output ) { - if (*output == 1) printf("TRUE"); - if (*output == 0) printf("FALSE"); -} - -long factors[1000], orig_num, max_factor=1, num_to_factor, next_num; -// TOP-C callback functions: -TOPC_BUF GenerateTaskInput(void); -TOPC_BUF DoTask( long *input ); -TOPC_ACTION CheckTaskResult( long *input, long *output ); -void UpdateSharedData( long *input, long *output ); -long get_argument( int argc, char **argv ); - -int main(int argc, char *argv[]) -{ - int i; - - // Set up defaults. Can be overridden, e.g.: ./a.out --TOPC-trace=0 -#ifdef __cplusplus - TOPC_OPT_trace_input = (TOPC_trace_input_ptr)trace_input; - TOPC_OPT_trace_result = (TOPC_trace_result_ptr)trace_result; -#else - TOPC_OPT_trace_input = trace_input; - TOPC_OPT_trace_result = trace_result; -#endif - TOPC_OPT_trace = 2; - TOPC_init(&argc, &argv); - // This occurs in MPICH 1.2.4: - if (argc > 2 && strcmp("-p4pg", argv[argc-2])) { - printf("MPI bug: MPI changed value of argc;" - " Don't use argc with this MPI\n"); - exit(1); - } - // Important: Inspect command line only after TOPC_init() - orig_num = num_to_factor = get_argument(argc, argv); - - factors[0]=0; // factors[0] is number of factors found so far - next_num = 2 - TASK_INTERVAL; // last number factored - TOPC_master_slave(GenerateTaskInput, DoTask, CheckTaskResult, - UpdateSharedData); - - if ( TOPC_is_master() ) { - for (i = 1; i <= factors[ 0 ]; i++) - { printf("%ld ", factors[i]); fflush(stdout); } - printf("\n"); - } - TOPC_finalize(); - // printf("%d: Exiting\n", TOPC_rank()); fflush(stdout); - return 0; -} - -TOPC_BUF GenerateTaskInput() { - next_num = next_num + TASK_INTERVAL; - if ( next_num > num_to_factor ) return NOTASK; - else return TOPC_MSG(&next_num, sizeof(next_num)); -} - -TOPC_BUF DoTask( long *input ) -{ - long limit; - long num = *input; - long task_out; - - limit = num + TASK_INTERVAL; - for ( ; num < limit; num++ ) - if (num_to_factor % num == 0) { - task_out = 1; - return TOPC_MSG(&task_out, sizeof(long)); - } - task_out = 0; - return TOPC_MSG(&task_out, sizeof(long)); -} - -TOPC_ACTION CheckTaskResult( long *input, long *output ) -{ - if ( *output == 0 ) return NO_ACTION; - if ( TOPC_is_up_to_date() ) return UPDATE; - // Suppose we factor 1006 and a slave reports 1006 before 2 is reported - if ( *input < max_factor ) return UPDATE; - else return REDO; -} - -void UpdateSharedData( long *input, long *output ) -{ - long limit, num = *input; - int i; - limit = num + TASK_INTERVAL; - // Suppose we factor 1006 and a slave reports 1006 before 2 is reported - for ( ; num < limit; num++ ) { - if ( orig_num % num == 0 ) { - if ( num < max_factor ) { - max_factor = 1; // re-compute max_factor - for( i = 1; i <= factors[0]; i++ ) { - if (factors[i] > max_factor) max_factor = factors[i]; - while (factors[i] % num == 0 && factors[i] != num) { - factors[i] = factors[i] / num; - num_to_factor = num_to_factor * num; - } - } - } - while (num_to_factor % num == 0) { - factors[ ++factors[0] ] = num; - if (num > max_factor) max_factor = num; - num_to_factor = num_to_factor / num; - if (num_to_factor == 1) return; - } - } - } -} - -long get_argument(int argc, char **argv) { - long num_to_factor = 123456789; - if (argc == 1) { // If command line doesn't have num_to_factor - if (TOPC_is_master()) - printf("WARNING: Missing number arg on command line. Using 123456789\n"); - } else { - errno = 0; - /* Replace strtol by atol(argv[1]) if your UNIX doesn't have strtol */ - num_to_factor = strtol(argv[1], NULL, 10); - if (num_to_factor > 0 && errno == ERANGE) { - if (TOPC_is_master()) - printf("Argument out of range. Max. integer is: %ld\n", LONG_MAX); - exit(1); - } - } - if (num_to_factor < 2) { - fprintf(stderr, "Can't factor number less than 2\n"); exit(1); - } - return num_to_factor; -} diff --git a/topc-2.5.2/examples/parquicksort-raw.c b/topc-2.5.2/examples/parquicksort-raw.c deleted file mode 100644 index e8e8d69e..00000000 --- a/topc-2.5.2/examples/parquicksort-raw.c +++ /dev/null @@ -1,159 +0,0 @@ -/******************************************************************** - ******************************************************************** - ** USAGE: topcc [ --seq | --mpi | --pthread ] THIS_FILE - ** ALGORITHM: Quicksort - ** shared data: array_global - ** task input: start and end indices - ** struct qs_task {int start; int end; unsigned int random_seed;} *indices; - ** task output: subarray: array_global[indices->start .. indices->end - 1] - ** update: None, result saved on master - ******************************************************************** - ********************************************************************/ - -// The strategy is to use TOPC_raw_begin/end_master_slave(). -// Each slave precomputes quicksort() recursively down to PAR_LEVEL. -// The master then calls quicksort(). When it reaches PAR_LEVEL, -// TOPC_raw_submit_task_input(_input_) is called within quicksort() by the -// master, where _input_ is TOPC_MSG() containing indices: {start,end} -// The slave then calls qs_do_task(), which calls: -// quicksort(array,start,end,PAR_LEVEL); -// Another alternative would be for TOPC_MSG() to include the -// entire subarray: array[start..end] -// which would avoid the need for the slave to precompute down to PAR_LEVEL, -// but it would involve higher communication costs. - -#ifndef PAR_LEVEL -#define PAR_LEVEL 3 /* Level at which master dispatches sorting to slave */ -#endif - -#ifndef ARRAY_LEN -#define ARRAY_LEN 100 -#endif - -#include "topc.h" - -#include -#include -#include -#include -#include -#include - -struct qs_task { - int start; - int end; -}; - -/*==================== MODIFICATION OF SEQUENTIAL CODE =================*/ - -/* Either master will call this with level == 0 and it will sort through - * the recursive level PAR_LEVEL, or else a slave will call it with - * with level == PAR_LEVEL and sort the given subarray entirely. - */ -void quicksort( int array[], int start, int end, int level ) { - int i = start, j = end, pivot = array[start]; - int tmp; - static struct qs_task indices; - - level = level + 1; - if ( start >= end ) return; - - if ( level == PAR_LEVEL ) { - if ( TOPC_is_master() ) { - indices.start = start; - indices.end = end; - TOPC_raw_submit_task_input( TOPC_MSG(&indices, sizeof(indices)) ); - } - return; - } - - /* interchange so nums <= pivot come first, and nums > pivot come later */ - while (1) { - while( (array[i] <= pivot) && (i <= end) ) i++; - while( array[j] > pivot ) j--; /* j>0 always, since pivot is an array val */ - if ( i < j ) { - tmp = array[i]; - array[i] = array[j]; - array[j] = tmp; - } - else { - i--; - j++; - array[start] = array[i]; - array[i] = pivot; - break; - } - } - - assert( i == j-1 ); - quicksort( array, start, i - 1, level ); /* pivot==array[i] is in order */ - quicksort( array, j, end, level ); -} - -void print_array( char const *string, int array[], int len ) { - int i; - printf("%s", string); - for ( i=0; i < len; i++ ) - printf("%d ", array[i]); - printf("\n"); -} - -/*==================== DEFINITION OF TOP-C CALLBACKS =================*/ - -int *array_global = NULL; -TOPC_BUF qs_do_task( struct qs_task *indices ) { - quicksort( array_global, indices->start, indices->end, PAR_LEVEL ); - return TOPC_MSG_PTR( array_global + indices->start, - (indices->end - indices->start + 1) * sizeof(int) ); -} -TOPC_ACTION qs_check_task_result( struct qs_task *indices, int array[] ) { - // In shared memory (--pthread or --seq), array modified in place. - if ( array_global + indices->start != array ) - memcpy( array_global + indices->start, array, - (indices->end - indices->start + 1) * sizeof(int) ); - return NO_ACTION; -} -void qs_trace_input(struct qs_task *indices) { - printf("[%d, %d]", indices->start, indices->end ); -} -void qs_trace_result(struct qs_task *indices, int array[]) { - int len = indices->end - indices->start + 1; - if (len>8) printf("[END OF ARRAY OMMITTED] "); - print_array( "", array, (len>8 ? 8 : len) ); -} - -/*==================== MAIN ROUTINE WITH INITIALIZATION ===================*/ - -int main( int argc, char **argv ) { int array[ARRAY_LEN]; - int i; - - // Set up defaults. Can be overridden, e.g.: ./a.out --TOPC_trace=0 -#ifdef __cplusplus - TOPC_OPT_trace_input = (TOPC_trace_input_ptr)qs_trace_input; - TOPC_OPT_trace_result = (TOPC_trace_result_ptr)qs_trace_result; -#else - TOPC_OPT_trace_input = qs_trace_input; - TOPC_OPT_trace_result = qs_trace_result; -#endif - TOPC_OPT_trace = 2; /* 2 is default */ - TOPC_init(&argc, &argv); - - // PROBLEM: HOW TO ELEGANTLY DISTRIBUTE COMMON SEED? - srandom( (unsigned int)time(NULL) ); - for ( i=0; i < ARRAY_LEN; i++ ) array[i] = ( random() & ((1<<10)-1) ); - array_global = array; /* pass array to qs_do_task & qs_check_task_result */ - - /* Tell slaves to each do quicksort sequentially until PAR_LEVEL */ - if (!TOPC_is_master()) quicksort( array, 0, ARRAY_LEN - 1, 0 ); - - /* The parallel stuff happens here */ - if (TOPC_is_master()) print_array("BEFORE: ", array, ARRAY_LEN - 1); - TOPC_raw_begin_master_slave( qs_do_task, qs_check_task_result, - NULL ); /* update_shared_memory not called */ - if (TOPC_is_master()) quicksort( array, 0, ARRAY_LEN - 1, 0 ); - TOPC_raw_end_master_slave(); - if (TOPC_is_master()) print_array("AFTER: ", array, ARRAY_LEN - 1); - - TOPC_finalize(); - return 0; -} diff --git a/topc-2.5.2/examples/parquicksort.c b/topc-2.5.2/examples/parquicksort.c deleted file mode 100644 index 54ff91f9..00000000 --- a/topc-2.5.2/examples/parquicksort.c +++ /dev/null @@ -1,218 +0,0 @@ -/******************************************************************** - ******************************************************************** - ** USAGE: topcc [ --seq | --mpi | --pthread ] THIS_FILE - ** ALGORITHM: Quicksort - ** shared data: array_global - ** task input: start and end indices - ** struct qs_task {int start; int end; unsigned int random_seed;} *indices; - ** task output: subarray: array_global[indices->start .. indices->end - 1] - ** update: None, result saved on master - ** FOR A LARGER RUN, COMPILE WITH: -DARRAY_LEN=10000 -DPAR_LEVEL=12 - ******************************************************************** - ********************************************************************/ - -// The strategy is to use TOPC_master_slave(); -// Each slave precomputes quicksort() recursively down to -// the recursive level, PAR_LEVEL. -// The master also precomputes quicksort() recursively down to PAR_LEVEL, -// but the master also records what index pair: {start,end} -// would have been invoked at the next call to quicksort() -// This index pair is saved in array_of_tasks, and used by -// qs_generate_task_input() to generate tasks for the slaves. -// The master then calls TOPC_master_slave() -// The slave then calls qs_do_task(), which calls: -// quicksort(array,start,end,PAR_LEVEL); -// Another alternative would be for TOPC_MSG() to include the -// entire subarray: array[start..end] -// which would avoid the need for the slave to precompute down to PAR_LEVEL, -// but it would involve higher communication costs. - -#ifndef PAR_LEVEL -#define PAR_LEVEL 3 /* Level at which master dispatches sorting to slave */ -#endif - -#ifndef ARRAY_LEN -#define ARRAY_LEN 100 -#endif - -#include "topc.h" - -#include -#include -#include -#include -#include -#include - -struct qs_task { - int start; - int end; - unsigned int random_seed; -}; -int *array_of_tasks = NULL; -int length_of_array_of_tasks = 0; -int length_of_array_of_tasks_filled = 0; -#define max(x,y) ( (x)<(y) ? (y) : (x) ) - -/*==================== MODIFICATION OF SEQUENTIAL CODE =================*/ - -/* Either master will call this with level == 0 and it will sort through - * the recursive level PAR_LEVEL, or else a slave will call it with - * with level == PAR_LEVEL and sort the given subarray entirely. - */ -void quicksort( int array[], int start, int end, int level ) { - int i = start, j = end, pivot = array[start]; - int tmp; - - level = level + 1; - if ( start >= end ) return; - - if ( level == PAR_LEVEL ) { - if ( TOPC_is_master() ) { - /* record [start,end] indices for qs_generate_task_input() */ - if ( length_of_array_of_tasks_filled >= length_of_array_of_tasks - 1 ) { - length_of_array_of_tasks = max(100,2*length_of_array_of_tasks); -# ifdef __cplusplus - array_of_tasks = (int *)realloc( array_of_tasks, - sizeof(int)*length_of_array_of_tasks ); -# else - array_of_tasks = realloc( array_of_tasks, - sizeof(int)*length_of_array_of_tasks ); -# endif - } - array_of_tasks[ length_of_array_of_tasks_filled++ ] = start; - array_of_tasks[ length_of_array_of_tasks_filled++ ] = end; - } - return; - } - - /* interchange so nums <= pivot come first, and nums > pivot come later */ - while (1) { - while( (array[i] <= pivot) && (i <= end) ) i++; - while( array[j] > pivot ) j--; /* j>0 always, since pivot is an array val */ - if ( i < j ) { - tmp = array[i]; - array[i] = array[j]; - array[j] = tmp; - } - else { - i--; - j++; - array[start] = array[i]; - array[i] = pivot; - break; - } - } - - assert( i == j-1 ); - quicksort( array, start, i - 1, level ); /* pivot==array[i] is in order */ - quicksort( array, j, end, level ); -} - -void print_array( char const *string, int array[], int len ) { - int i; - printf("%s", string); - for ( i=0; i < len; i++ ) - printf("%d ", array[i]); - printf("\n"); -} - -/*==================== DEFINITION OF TOP-C CALLBACKS =================*/ - -int *array_global = NULL; -TOPC_BUF qs_generate_task_input() { - static struct qs_task indices; - static int random_numbers_initialized = 0; - /* indices.random_seed == 0 means sort array[start..end]; - else initialize random array using seed */ - if ( ! random_numbers_initialized ) { - while ( ! (indices.random_seed = (unsigned int)time(NULL)) ) ; - random_numbers_initialized = 1; - } - else if (length_of_array_of_tasks_filled >= length_of_array_of_tasks) - return NOTASK; - else { - indices.start = array_of_tasks[length_of_array_of_tasks_filled++]; - indices.end = array_of_tasks[length_of_array_of_tasks_filled++]; - indices.random_seed = 0; /* no random seed */ - } - return TOPC_MSG( &indices, sizeof(indices) ); -} -TOPC_BUF qs_do_task( struct qs_task *indices ) { - /* if indices.random_seed != 0, UPDATE: init random array */ - if ( indices->random_seed ) return TOPC_MSG(NULL,0); - quicksort( array_global, indices->start, indices->end, PAR_LEVEL ); - return TOPC_MSG_PTR( array_global + indices->start, - (indices->end - indices->start + 1) * sizeof(int) ); -} -TOPC_ACTION qs_check_task_result( struct qs_task *indices, int array[] ) { - if ( indices->random_seed ) return UPDATE; /* init random array */ - // In shared memory (--pthread or --seq), array modified in place. - if ( array_global + indices->start != array ) - memcpy( array_global + indices->start, array, - (indices->end - indices->start + 1) * sizeof(int) ); - return NO_ACTION; -} -void qs_update_shared_data( struct qs_task *indices, int array[] ) { - int i; - srandom( indices->random_seed ); - for ( i=0; i < ARRAY_LEN; i++ ) array_global[i] = ( random() & ((1<<10)-1) ); -} - -void qs_trace_input(struct qs_task *indices) { - if ( indices->random_seed ) - printf("initializing: random seed: %d", indices->random_seed ); - else - printf("[%d, %d]", indices->start, indices->end ); -} -void qs_trace_result(struct qs_task *indices, int array[]) { - int len = indices->end - indices->start + 1; - if ( indices->random_seed ) printf("Initializing ..."); - else { - if (len>8) printf("[END OF ARRAY OMMITTED] "); - print_array( "", array, (len>8 ? 8 : len) ); - } -} - -/*==================== MAIN ROUTINE WITH INITIALIZATION ===================*/ - -int main( int argc, char **argv ) { - int array[ARRAY_LEN]; - - // Set up defaults. Can be overridden, e.g.: ./a.out --TOPC-trace=0 -#ifdef __cplusplus - TOPC_OPT_trace_input = (TOPC_trace_input_ptr)qs_trace_input; - TOPC_OPT_trace_result = (TOPC_trace_result_ptr)qs_trace_result; -#else - TOPC_OPT_trace_input = qs_trace_input; - TOPC_OPT_trace_result = qs_trace_result; -#endif - TOPC_OPT_trace = 2; /* 2 is default */ - TOPC_init(&argc, &argv); - - /* pass array to qs_do_task, qs_check_task_result, qs_update_shared_data */ - array_global = array; - /* random_numbers_initialized == 0: initialize array, and return NOTASK */ - TOPC_master_slave( qs_generate_task_input, qs_do_task, qs_check_task_result, - qs_update_shared_data ); - - /* Do quicksort sequentially until PAR_LEVEL; if master, record tasks */ - /* This will set array_of_tasks (array of [start..end] pairs for - slaves to sort) */ - quicksort( array, 0, ARRAY_LEN - 1, 0 ); - - /* The parallel stuff happens here */ - if (TOPC_is_master()) print_array("BEFORE: ", array, ARRAY_LEN - 1); - length_of_array_of_tasks = length_of_array_of_tasks_filled; - length_of_array_of_tasks_filled = 0; /* count up again */ - /* random_numbers_initialized == 1 && - * length_of_array_of_tasks > length_of_array_of_tasks_filled: start sorting - */ - TOPC_master_slave( qs_generate_task_input, qs_do_task, qs_check_task_result, - NULL ); - if (TOPC_is_master()) print_array("AFTER: ", array, ARRAY_LEN - 1); - if (TOPC_is_master()) free(array_of_tasks); - - TOPC_finalize(); - return 0; -} diff --git a/topc-2.5.2/examples/parsimple.c b/topc-2.5.2/examples/parsimple.c deleted file mode 100644 index 663cffd9..00000000 --- a/topc-2.5.2/examples/parsimple.c +++ /dev/null @@ -1,73 +0,0 @@ -/* This is the simple example from the manual meant to illustrate - * the basics of the TOP-C model. - */ - -#include -#include -#include -#include - -#define MAX 3000000 -#define INCR MAX/10 /* We assume INCR divides MAX exactly */ - -int array[MAX]; -int idx; -int max_int; - -TOPC_BUF GenerateTaskInput() { - int input_task; - if (idx >= MAX) return NOTASK; - input_task = idx; - idx = idx + INCR; - return TOPC_MSG( &input_task, sizeof(input_task) ); -} -TOPC_BUF DoTaskRandom( int *ignore ) { - int rand_int[INCR]; - int i; - for (i = 0; i < INCR; i++) - rand_int[i] = rand(); - return TOPC_MSG( rand_int, INCR * sizeof(int) ); -} -TOPC_ACTION CheckTaskRandom( int *input, int rand_vals[] ) { - int curr_idx = *input; - memcpy( array+curr_idx, rand_vals, INCR * sizeof(int) ); - return NO_ACTION; -} - -TOPC_BUF GenerateTaskInMax() { - int *input_task; - if (idx >= MAX) return NOTASK; - input_task = array + idx; - idx = idx + INCR; - return TOPC_MSG( input_task, INCR * sizeof(int) ); -} -TOPC_BUF DoTaskMax( int subarray[] ) { - int i; - int max=0; - for (i = 0; i < INCR; i++) - if ( subarray[i] > max ) - max = subarray[i]; - return TOPC_MSG( &max, sizeof(max) ); -} -TOPC_ACTION CheckTaskMax( int ignore[], int *output ) { - int curr_max = *output; - if ( curr_max > max_int ) - max_int = curr_max; - return NO_ACTION; -} - -int main( int argc, char **argv ) { - printf("simple.c uses large static data. This can fail in some config's\n"); - /* Change default to no trace; Can override with: ./a.out --TOPC-trace=1 */ - TOPC_OPT_trace = 0; - TOPC_init( &argc, &argv ); - idx = 0; /* Initialize idx, and randomize values of array[] */ - TOPC_master_slave( GenerateTaskInput, DoTaskRandom, CheckTaskRandom, NULL ); - if (TOPC_is_master()) - printf("Finished randomizing integers.\n"); - idx = 0; /* Re-initialize idx to 0, and find max. value in array[] */ - TOPC_master_slave( GenerateTaskInMax, DoTaskMax, CheckTaskMax, NULL ); - TOPC_finalize(); - printf("The maximum integer is: %d\n", max_int); - return 0; -} diff --git a/topc-2.5.2/examples/seq8queens.c b/topc-2.5.2/examples/seq8queens.c deleted file mode 100644 index e483b435..00000000 --- a/topc-2.5.2/examples/seq8queens.c +++ /dev/null @@ -1,70 +0,0 @@ -/* This is the model sequential code, on which the parallel code is based. */ - -#include -#include -#include -#include - -#define NQUEENS 8 -#define SIZEOF_SOL (NQUEENS*sizeof(int)) -#define MAX_SOLS 10000 - -int check( int cols[], int new_row, int new_col ) { - int row; - for ( row = 0; row < new_row; row++ ) { - if ( (new_col == cols[row]) - || (new_col-cols[row] == new_row-row) - || (new_col-cols[row] == row-new_row) ) - return 0; - } - cols[new_row] = new_col; - return 1; -} - -void record_sols( int sols[][NQUEENS], int sol[NQUEENS], int *num_sols ) { - memcpy( &sols[*num_sols][0], sol, SIZEOF_SOL); - (*num_sols)++; - assert(*num_sols <= MAX_SOLS); -} - -int main( int argc, char **argv ) { - int cols[NQUEENS], sols[MAX_SOLS][NQUEENS], num_sols = 0; - int col0, col1, col2, col3, col4, col5, col6, col7; - for ( col0 = 0; col0 < NQUEENS; col0++ ) { - check( cols, 0, col0 ); /* This sets cols[0]=col0; */ - for ( col1 = 0; col1 < NQUEENS; col1++ ) { - if ( ! check( cols, 1, col1 ) ) continue; /* try next column */ - for ( col2 = 0; col2 < NQUEENS; col2++ ) { - if ( ! check( cols, 2, col2 ) ) continue; /* try next column */ - for ( col3 = 0; col3 < NQUEENS; col3++ ) { - if ( ! check( cols, 3, col3 ) ) continue; /* try next column */ - for ( col4 = 0; col4 < NQUEENS; col4++ ) { - if ( ! check( cols, 4, col4 ) ) continue; /* try next column */ - for ( col5 = 0; col5 < NQUEENS; col5++ ) { - if ( ! check( cols, 5, col5 ) ) continue; /* try next column */ - for ( col6 = 0; col6 < NQUEENS; col6++ ) { - if ( ! check( cols, 6, col6 ) ) continue; /* try next column */ - for ( col7 = 0; col7 < NQUEENS; col7++ ) { - if ( check( cols, 7, col7 ) ) - record_sols( sols, cols, &num_sols ); - } } } } } } } } - printf("number of solutions: %d\n", num_sols); - printf("middle solution (%d-th solution): %d %d %d %d %d %d %d %d\n", - num_sols/2+1, - sols[num_sols/2][0], sols[num_sols/2][1], - sols[num_sols/2][2], sols[num_sols/2][3], - sols[num_sols/2][4], sols[num_sols/2][5], - sols[num_sols/2][6], sols[num_sols/2][7] - ); - /* - for (col0=0; col0 -#include -#include -#include -#include - -void quicksort( int array[], int start, int end, int level ) { - int i = start, j = end, pivot = array[start]; - int tmp; - - level = level + 1; - if ( start >= end ) return; - - /* interchange so nums <= pivot come first, and nums > pivot come later */ - while (1) { - while( (array[i] <= pivot) && (i <= end) ) i++; - while( array[j] > pivot ) j--; /* j>0 always, since pivot is an array val */ - if ( i < j ) { - tmp = array[i]; - array[i] = array[j]; - array[j] = tmp; - } - else { - i--; - j++; - array[start] = array[i]; - array[i] = pivot; - break; - } - } - - assert( i == j-1 ); - quicksort( array, start, i - 1, level ); /* pivot==array[i] is in order */ - quicksort( array, j, end, level ); -} - -void print_array( char *string, int array[], int len ) { - int i; - printf("%s", string); - for ( i=0; i < len; i++ ) - printf("%d ", array[i]); - printf("\n"); -} - -int main( int argc, char **argv ) { - int array[ARRAY_LEN]; - int i; - - srandom( (unsigned int)time(NULL) ); - for ( i=0; i < ARRAY_LEN; i++ ) array[i] = ( random() & ((1<<10)-1) ); - - print_array("BEFORE: ", array, ARRAY_LEN); - quicksort( array, 0, ARRAY_LEN - 1, 0 ); - print_array("AFTER: ", array, ARRAY_LEN); - return 0; -} diff --git a/topc-2.5.2/src/Makefile.in b/topc-2.5.2/src/Makefile.in deleted file mode 100644 index 4885241c..00000000 --- a/topc-2.5.2/src/Makefile.in +++ /dev/null @@ -1,107 +0,0 @@ -# @configure_input@ - -exec_prefix=@PWD@ - -CC=@CC@ -MPICC=@MPICC@ -CFLAGS=@CFLAGS@ -I@PWD@/include -DEFS=@DEFS@ - -LIBDIR=@PWD@/lib -INCLUDEDIR=@PWD@/include - -# Set to "strip" or to "strip -f" (check your man page) for smaller binaries -STRIP=@STRIP@ - -@SET_MAKE@ - -OBJS_SEQ=topc.o memory-no-pthread.o options-no-pthread.o procgroup.o -OBJS_MPI=topc.o memory.o options-no-pthread.o procgroup.o -OBJS_PTHREAD=topc.o memory.o options.o procgroup.o - -all: ${LIBDIR}/libtopc.a ${LIBDIR}/libtopc-seq.a ${LIBDIR}/libmpinu.a \ - ${LIBDIR}/libtopc-pthread.a - -${LIBDIR}/libtopc.a: ${LIBDIR}/libtopc-mpi.a - ( cd ${LIBDIR}; rm -f libtopc.a; ln -s libtopc-mpi.a libtopc.a ) - -${LIBDIR}/libtopc-mpi.a: ${OBJS_MPI} comm-mpi.o ${LIBDIR}/libmpinu.a - rm -f ${LIBDIR}/libtopc-mpi.a - ar qc ${LIBDIR}/libtopc-mpi.a ${OBJS_MPI} comm-mpi.o - ${STRIP} ${LIBDIR}/libtopc-mpi.a; - -${LIBDIR}/libtopc-seq.a: ${OBJS_SEQ} comm-seq.o - rm -f ${LIBDIR}/libtopc-seq.a - ar qc ${LIBDIR}/libtopc-seq.a ${OBJS_SEQ} comm-seq.o - ${STRIP} ${LIBDIR}/libtopc-seq.a; - -${LIBDIR}/libtopc-pthread.a: ${OBJS_PTHREAD} comm-pthread.o - rm -f ${LIBDIR}/libtopc-pthread.a - - ar qc ${LIBDIR}/libtopc-pthread.a ${OBJS_PTHREAD} comm-pthread.o - ${STRIP} ${LIBDIR}/libtopc-pthread.a; - -${INCLUDEDIR}/mpinu.h: mpinu/mpi.h - cp mpinu/mpi.h ${INCLUDEDIR}/mpinu.h - -${LIBDIR}/libmpinu.a: mpinu/libmpi.a - cp mpinu/libmpi.a ${LIBDIR}/libmpinu.a - ${STRIP} ${LIBDIR}/libmpinu.a; - -mpinu/libmpi.a: - ( cd mpinu; ${MAKE} libmpi.a ) - -${INCLUDEDIR}/topc.h: @PWD@/src/topc.h - cp @PWD@/src/topc.h ${INCLUDEDIR}/topc.h - -topc.o: topc.c topc.h comm.h - ${CC} -c ${CFLAGS} topc.c - cp topc.h ${INCLUDEDIR}/topc.h - -memory.o: memory.c topc.h comm.h sem-pthread.h - ${CC} -c ${CFLAGS} ${DEFS} memory.c -options.o: options.c topc.h comm.h - ${CC} -c ${CFLAGS} ${DEFS} \ - -DVER_STR='"@TOPC_VERSION@"' -DUPDATE_STR='"@TOPC_UPDATED@"' options.c -procgroup.o: procgroup.c comm.h - ${CC} -c ${CFLAGS} ${DEFS} procgroup.c - -memory-no-pthread.o: memory.c topc.h comm.h - ${CC} -c -o memory-no-pthread.o ${CFLAGS} ${DEFS} \ - -DHAVE_PTHREAD=0 memory.c -options-no-pthread.o: options.c topc.h comm.h - ${CC} -c -o options-no-pthread.o ${CFLAGS} ${DEFS} -DHAVE_PTHREAD=0 \ - -DVER_STR='"@TOPC_VERSION@"' -DUPDATE_STR='"@TOPC_UPDATED@"' options.c - -comm-mpi.o: comm-mpi.c comm.h ${INCLUDEDIR}/mpinu.h - ${MPICC} -c ${CFLAGS} ${DEFS} comm-mpi.c - -comm-seq.o: comm-seq.c comm.h ${INCLUDEDIR}/mpinu.h - ${CC} -c ${CFLAGS} ${DEFS} comm-seq.c - -comm-pthread.o: comm-pthread.c comm.h sem-pthread.h - @if test "x@HAVE_PTHREAD@" != "xyes"; then \ - echo ""; \ - echo "WARNING: I couldn't find pthread.h; comm-pthread.o may fail"; \ - echo " If pthread is desired, and pthread.h is not"; \ - echo " in a standard location, try copying it to:"; \ - echo " @PWD@/{include}/"; \ - echo " If libpthread.{a,so} is needed, then modify"; \ - echo " LIBSFORPTHREAD everywhere in bin/topc-config.in"; \ - echo "Alternatively, if you do not use shared memory, ignore this."; \ - echo ""; \ - fi - - ${CC} -c ${CFLAGS} ${DEFS} comm-pthread.c - -#Targets of convenience -libmpinu.a: ${LIBDIR}/libmpinu.a -libtopc.a: ${LIBDIR}/libtopc.a -libtopc-mpi.a: ${LIBDIR}/libtopc-mpi.a -libtopc-seq.a: ${LIBDIR}/libtopc-seq.a -libtopc-pthread.a: ${LIBDIR}/libtopc-pthread.a - -clean: - ( cd mpinu; ${MAKE} clean ) - rm -f *.o a.out core - -distclean: clean - rm -f *~ diff --git a/topc-2.5.2/src/comm-mpi.c b/topc-2.5.2/src/comm-mpi.c deleted file mode 100644 index e8880138..00000000 --- a/topc-2.5.2/src/comm-mpi.c +++ /dev/null @@ -1,442 +0,0 @@ - /********************************************************************** - * TOP-C (Task Oriented Parallel C) * - * Copyright (c) 2000 Gene Cooperman * - * and Victor Grinberg * - * * - * This library is free software; you can redistribute it and/or * - * modify it under the terms of the GNU Lesser General Public * - * License as published by the Free Software Foundation; either * - * version 2.1 of the License, or (at your option) any later version. * - * * - * This library is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * - * Lesser General Public License for more details. * - * * - * You should have received a copy of the GNU Lesser General Public * - * License along with this library (see file COPYING); if not, write * - * to the Free Software Foundation, Inc., 59 Temple Place, Suite * - * 330, Boston, MA 02111-1307 USA, or contact Gene Cooperman * - * . * - **********************************************************************/ - -/********************************************************************** - * See ./configure --with-mpi-cc=, etc. (./configure --help) - * for using another MPI with a program, PROG, to compile MPI files. - * See the manual for further details of using another MPI - **********************************************************************/ - -#include -#include // malloc(), rand() -#include // alarm() -#include // signal(), pthread_kill() -#include // strerror() -#include -#ifdef HAVE_MPI_H -# include -#else -# include // MPINU implementation of MPI -#endif -#include "comm.h" // comm.h also defines HAVE_PTHREAD, etc., by default - -#ifdef HAVE_PTHREAD -# include -# ifdef HAVE_SEMAPHORE -# include // Solaris: needs -lposix4 -# else -# include "sem-pthread.h" -# endif -static pthread_t cache_thread; -#endif - -//Compile-time parameters (set in comm.h) -// #define NUM_MSG_CACHE_PTR 1000 // Number of pending msg's that can be cached - -// NOTE: MPI returns MPI_SUCCESS or application-dependent indication -// of failure. We may MPI_SUCCESS to TRUE and others to FALSE. -#ifndef FALSE -enum {FALSE, TRUE}; -#endif - -char *COMM_mem_model = "distributed (mpi)"; - - -/*********************************************************************** - *********************************************************************** - ** Communications functions, implemented over MPI - *********************************************************************** - ***********************************************************************/ - -/*********************************************************************** - * Initialize underlying communications library - */ -static void alarm_handler(int dummy_sig) { - ERROR("%d seconds elapsed without reply by master: slave exiting\n" - " Use `./a.out --TOPC-slave-timeout=XXX' to change interval\n", - TOPC_OPT_slave_timeout); -} -static int use_alarm = 1; -void COMM_init(int *argc, char ***argv) { - int flag; - if (MPI_SUCCESS != MPI_Initialized(&flag)) - ERROR("COMM_init: MPI_Initialized() failed"); - if (!flag) { - if (TOPC_OPT_safety >= SAFETY_NO_TIMEOUT || TOPC_OPT_slave_timeout == 0) - use_alarm = 0; -// SLAVES_DIE should be set to max number of seconds before they die. -#ifdef SLAVES_DIE - // Kill slaves with odd-numbered rank after a while; for testing - use_alarm = 0; -#endif - if (use_alarm) { - signal( SIGALRM, alarm_handler ); - alarm(TOPC_OPT_slave_timeout); - } - if (MPI_SUCCESS != MPI_Init(argc, argv)) - ERROR("TOPC_init: Couldn't initialize. (missing procgroup file?)" - "\n\t Try: ./a.out --TOPC-procgroup=PROCGROUP_FILE"); - if (use_alarm) { /* Again, in case MPI_Init() called alarm() */ - signal( SIGALRM, alarm_handler ); - alarm(TOPC_OPT_slave_timeout); - } - COMM_rank(); // pre-compute rank as static local var. - if (use_alarm && COMM_rank() == 0) { // no alarm on master - alarm(0); - use_alarm = 0; - } -#ifdef HAVE_PTHREAD - if (TOPC_OPT_safety < SAFETY_NO_RCV_THREAD) - cache_thread = pthread_self(); -#endif - -#ifdef SLAVES_DIE - if ( COMM_rank() % 2 == 1 ) - alarm( (int)(rand()/(float)RAND_MAX * SLAVES_DIE) ); -#endif - } -} - -/*********************************************************************** - * Shutdown underlying communications library - */ -void COMM_finalize() { - int flag; - MPI_Initialized(&flag); - if (flag) { - int rank = COMM_rank(); -#ifdef HAVE_PTHREAD - if (TOPC_OPT_safety < SAFETY_NO_RCV_THREAD) - // cache_thread is still self if COMM_receive() never called - if (rank != 0 && ! pthread_equal(pthread_self(), cache_thread) ) { - // MPI_Finalize() will close sockets while cache_thread could - // try to read from them, kill cache_thread now - pthread_kill( cache_thread, SIGKILL ); - pthread_join( cache_thread, NULL ); - } -#endif - if (MPI_SUCCESS != MPI_Finalize()) - WARNING("COMM_finalize: MPI_Finalize() failed"); - if (rank != 0) exit(0); /* If slave, exit */ - } -} - -/*********************************************************************** - * Test if underlying communications library is running - */ -TOPC_BOOL COMM_initialized() { - int flag; - MPI_Initialized(&flag); - // flag is true (1) if initialized. This agrees with TOPC_BOOL of TRUE - return flag; -} - -/*********************************************************************** - * Get number of nodes - */ -int COMM_node_count() { - int count; - MPI_Comm_size(MPI_COMM_WORLD, &count); - return count; -} - -/*********************************************************************** - * Get rank of this node - */ -int COMM_rank() { - static int rank = -1; // -1 means don't know; static so we remember rank - if (rank == -1 && COMM_initialized()) - MPI_Comm_rank(MPI_COMM_WORLD, &rank); - // Else in mpinu, absence of "-p4amslave" in argv[] indicates it's master - // In our case, we can't be sure - if ( rank == -1 ) - ERROR("TOPC_rank()/TOPC_is_master() called" - " before TOPC_init() in dist. memory model\n" - " Can't determine if this is master or slave in this version of MPI.\n" - "Try placing TOPC_init() earlier" - " ( before call to TOPC_rank()/TOPC_is_master() )\n"); - return rank; -} - -/*********************************************************************** - * Return boolean, true if master and slave share memory - */ -TOPC_BOOL COMM_is_shared_memory() { - return FALSE; -} - -/*********************************************************************** - * Return boolean, true if master and slave share memory - */ -void *COMM_stack_bottom = NULL; // set in topc.c - -TOPC_BOOL COMM_is_on_stack(void *buf, size_t dummy_size) { - int stack_top[8]; /* This won't be put in register */ - /* alt: stack_top = alloca(8); autoconf:AC_FUNC_ALLOCA */ - - if ( (buf >= (void *)stack_top && buf <= COMM_stack_bottom) - || (buf <= (void *)stack_top && buf >= COMM_stack_bottom) ) - return TRUE; - else - return FALSE; -} - -/*********************************************************************** - * Set via SOFT_ABORT_TAG - */ -// read on slave by TOPC_is_abort_pending() -volatile int COMM_is_abort_pending = 0; -// called on master by TOPC_abort() -void COMM_soft_abort() { - int slave, num_slaves = COMM_node_count()-1; -#ifdef HAVE_PTHREAD - int have_pthread = 1; -#else - int have_pthread = 0; -#endif - if ( ! have_pthread ) - WARNING("TOP-C compiled without threads; abort message will be delayed"); - else if ( TOPC_OPT_safety >= SAFETY_NO_RCV_THREAD ) - WARNING("--TOPC-safety >= %d (no receive threads); abort msg delayed", - SAFETY_NO_RCV_THREAD); - for (slave = 1; slave <= num_slaves; ++slave) - COMM_send_msg(NULL, 0, slave, SOFT_ABORT_TAG); - } - -/*********************************************************************** - * Check if a message from a slave is instantly available (non-blocking) - */ -TOPC_BOOL COMM_probe_msg() { - MPI_Status status; - int flag; - - if (MPI_SUCCESS != - MPI_Iprobe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &flag, &status)) - ERROR("COMM_probe_msg"); - flag = ( flag == MPI_SUCCESS ? TRUE : FALSE ); - return flag; -} - -/*********************************************************************** - * Check for a message from a slave (blocking) - */ -TOPC_BOOL COMM_probe_msg_blocking(int rank) { - MPI_Status status; - - // Allow half hour (default) for master to reply and for our task, or we die. - if (use_alarm) alarm(TOPC_OPT_slave_timeout); - if (MPI_SUCCESS != - MPI_Probe(rank, MPI_ANY_TAG, MPI_COMM_WORLD, &status)) - ERROR("COMM_probe_msg_blocking"); - return TRUE; -} - -/*********************************************************************** - * Send message - */ -TOPC_BOOL COMM_send_msg(void *msg, size_t msg_size, int dst, enum TAG tag) { - if(MPI_SUCCESS != MPI_Send(msg, (int)msg_size, MPI_BYTE, dst, tag, MPI_COMM_WORLD)) - return FALSE; - else return TRUE; -} - -/*********************************************************************** - * Receive message into malloc'ed memory (blocking call) - * receive from anybody, and set each of four param's if non-NULL - */ -//The fields of struct msg_ptr correspond to the args of COMM_receive_msg() -struct msg_ptr { - void *msg; - size_t msg_size; - int src; - enum TAG tag; - int inuse; -} msg_cache_ptr[NUM_MSG_CACHE_PTR]; -static volatile struct msg_ptr *cache_ptr_head = msg_cache_ptr, - *cache_ptr_tail = msg_cache_ptr; -#ifdef HAVE_PTHREAD -static sem_t cache_semaphore; -static int sem_val = 0; // used by DEBUG -#endif - -static TOPC_BOOL cache_msg() { - struct msg_ptr msg_info; - MPI_Status status; - int size; - - TRYAGAIN: ; - do { - if (MPI_SUCCESS != - MPI_Probe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status)){ - if(COMM_rank() != 0) - exit(1); - else return FALSE; - } - MPI_Get_count(&status, MPI_BYTE, &size); - //if size_t 64 bits, cast 32 bit int back to size_t - msg_info.msg_size = size; - - if (status.MPI_TAG == SOFT_ABORT_TAG) { - COMM_is_abort_pending = 1; - assert(size == 0); - if (MPI_SUCCESS != - MPI_Recv( NULL, 0, MPI_BYTE, - status.MPI_SOURCE, SOFT_ABORT_TAG, MPI_COMM_WORLD, &status)) - ERROR("cache_msg (receiving SOFT_ABORT_TAG)"); - } - } while (status.MPI_TAG == SOFT_ABORT_TAG); - - // Add hook here if want options for caller to pass in buffer - msg_info.msg= MEM_malloc(size, status.MPI_SOURCE, status.MPI_TAG, IS_PRE_MSG); - MEM_register_buf(msg_info.msg); - if (MPI_SUCCESS != - MPI_Recv( msg_info.msg, size, MPI_BYTE, - status.MPI_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status )){ - goto TRYAGAIN; - } - msg_info.src = status.MPI_SOURCE; - msg_info.tag = (enum TAG)status.MPI_TAG; - assert( (msg_info.inuse = 1) > 0 ); - -#ifndef HAVE_PTHREAD - assert(cache_ptr_tail == cache_ptr_head); -#endif - *(cache_ptr_tail++) = msg_info; - if (cache_ptr_tail == msg_cache_ptr + NUM_MSG_CACHE_PTR) - cache_ptr_tail = msg_cache_ptr; -#ifdef HAVE_PTHREAD - if (TOPC_OPT_safety < SAFETY_NO_RCV_THREAD) - if (COMM_rank() != 0) { -# ifdef DEBUG - printf("rank: %d, thread: %d posting (tag: %d); in queue: %d\n", - COMM_rank(), pthread_self(), msg_info.tag, ++sem_val); -# endif - if (cache_ptr_tail == cache_ptr_head) - ERROR("TOP-C: Overflow: More than %d pending messages cached.\n" - " Re-compile src/comm-mpi.c with larger value" - " for NUM_MSG_CACHE_PTR in src/comm.h\n", - NUM_MSG_CACHE_PTR); - sem_post(&cache_semaphore); - } -#endif - return TRUE; -} - -#ifdef HAVE_PTHREAD -static void *cache_messages(void *dummy) { - while (1) - cache_msg(); - /* NOTREACHED */ - return NULL; -} -static void cache_messages_init() { - static pthread_attr_t slave_attr; - int val; - - val = sem_init( &cache_semaphore, 0, 0 ); - if (val == -1) PERROR("sem_init"); - pthread_attr_init(&slave_attr); - pthread_attr_setdetachstate(&slave_attr, PTHREAD_CREATE_JOINABLE); -#ifdef DEBUG - printf("rank: %d, thread created\n", COMM_rank()); -#endif - val = pthread_create( &cache_thread, &slave_attr, cache_messages, NULL ); - if (val != 0) ERROR("%s\n", strerror(val) ); -} -#endif - -TOPC_BOOL COMM_receive_msg(void **msg, size_t *msg_size, int *src, enum TAG *tag) { - struct msg_ptr msg_info; - static int cache_messages_inited = 0; - - // On slave, allow half hour (default) for master to reply, or we die. - if (use_alarm) alarm(TOPC_OPT_slave_timeout); -#ifdef HAVE_PTHREAD - if (TOPC_OPT_safety < SAFETY_NO_RCV_THREAD && COMM_rank() != 0) { - /* The actual receive is done asynchronously by a separate thread */ - if (! cache_messages_inited) { - cache_messages_init(); - cache_messages_inited = 1; - } -# ifdef DEBUG - printf("rank: %d, thread: %d waiting\n", COMM_rank(), pthread_self()); -# endif - sem_wait(&cache_semaphore); -# ifdef DEBUG - printf("rank: %d, thread: %d done waiting\n", COMM_rank(), pthread_self()); -# endif - } - else - // Get and cache a message ourselves, if no thread - if(cache_msg() == FALSE) return FALSE ; -#else - /* The actual receive is done by cache_msg() */ - // Get and cache a message ourselves, if no thread - if(cache_msg() == FALSE) return FALSE ; -#endif - - msg_info = *(cache_ptr_head++); - if (cache_ptr_head == msg_cache_ptr + NUM_MSG_CACHE_PTR) - cache_ptr_head = msg_cache_ptr; - - if (msg) *msg = msg_info.msg; - if (msg_size) *msg_size = msg_info.msg_size; - if (src) *src = msg_info.src; - if (tag) *tag = msg_info.tag; -#ifdef HAVE_PTHREAD -# ifdef DEBUG - printf("rank: %d, thread: %d received tag: %d; in queue: %d\n", - COMM_rank(), pthread_self(), msg_info.tag, --sem_val); -# endif -#endif - assert( --(msg_info.inuse) == 0 ); - return TRUE; -} - -// balances MEM_malloc(), etc. in receive thread for COMM_receive_msg() -void COMM_free_receive_buf(void *msg) { - MEM_free(msg); -} - -/*********************************************************************** - *********************************************************************** - * SMP-related functions (e.g.: private (non-shared) variables) - *********************************************************************** - ***********************************************************************/ - -void *COMM_thread_private(size_t size) { // trivial for non-shared memory - static void *thread_private = NULL; - if ( thread_private == NULL ) { - thread_private = malloc(size); - if (size >= sizeof(void *)) - *(void **)thread_private = NULL; - } - return thread_private; -} -void COMM_begin_atomic_read() {} -void COMM_end_atomic_read() {} -void COMM_begin_atomic_write() {} -void COMM_end_atomic_write() {} -TOPC_BOOL COMM_is_in_atomic_section() { - static int is_in = 0; - return (is_in = 1 - is_in); -} diff --git a/topc-2.5.2/src/comm-pthread.c b/topc-2.5.2/src/comm-pthread.c deleted file mode 100644 index 465c3329..00000000 --- a/topc-2.5.2/src/comm-pthread.c +++ /dev/null @@ -1,690 +0,0 @@ - /********************************************************************** - * TOP-C (Task Oriented Parallel C) * - * Copyright (c) 2000, 2004 Gene Cooperman * - * * - * This library is free software; you can redistribute it and/or * - * modify it under the terms of the GNU Lesser General Public * - * License as published by the Free Software Foundation; either * - * version 2.1 of the License, or (at your option) any later version. * - * * - * This library is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * - * Lesser General Public License for more details. * - * * - * You should have received a copy of the GNU Lesser General Public * - * License along with this library (see file COPYING); if not, write * - * to the Free Software Foundation, Inc., 59 Temple Place, Suite * - * 330, Boston, MA 02111-1307 USA, or contact Gene Cooperman * - * . * - **********************************************************************/ - -#include -#include -#include // malloc()/free(), abs() -#include // strncmp() -#include "comm.h" // comm.h also defines HAVE_PTHREAD, etc., by default - -#ifdef HAVE_PTHREAD_SETCONCURRENCY -// Define __USE_UNIX98 this for sake of pthread_setconcurrency() -// Consider no longer using old pthread_setconcurrency() -# define __USE_UNIX98 -#endif -#include -#ifdef HAVE_SEMAPHORE -# include // Solaris: needs -lposix4 -#else -# include "sem-pthread.h" -#endif - -//Compile-time parameters (see comm.h and topc.c for more params) -#define PTHREAD_STACKSIZE (1 << 22) /* Request 4 MB stack */ - -// volatile: -// NOTE: In waiting on condition var (as below), test_var must be volatile -// or compiler may keep previous value of test_var in register. -// while(test_var) pthread_cond_wait(&cond_var, &mutex); - -//Error checking, assuming return value of x == 0 means no error: -#define ERROR_CHECK(x) { if (x) PERROR(#x); } - -//Alternative implementation to explore: -// Use semaphore instead of msg_cond for master waiting for slave message. -// Semaphore represents number of messages waiting via message[].next_msg - -char *COMM_mem_model = "shared (pthread)"; - -/*********************************************************************** - *********************************************************************** - ** Communications and MPI functions for pthread SMP layer - *********************************************************************** - ***********************************************************************/ - -#ifndef _POSIX_C_SOURCE -#define _POSIX_C_SOURCE 199506L -#endif - -static sem_t master_semaphore; // master blocks until slave thread ready. -static pthread_key_t thread_private_key; - -static size_t stacksize = 0; - -/*********************************************************************** - *********************************************************************** - * Synchronization for queue of messages from slaves to master, - * for synchronization of slave waiting for msg from master - * (implemented by message[slave].sem), - * and for single writer/multiple readers to synchronize - * do_task() (readers) and update_shared_data() (writers) - *********************************************************************** - ***********************************************************************/ - -/*********************************************************************** - *********************************************************************** - * STILL NEED TO THINK OUT free_receive_buffer(), lock(), semaphore() - * Also, has slave released all locks, semaphores before exiting? - *********************************************************************** - ***********************************************************************/ - -/*********************************************************************** - * Optional tracing of all synchronization (define DEBUG_SYNC to enable) - */ -/* #define DEBUG_SYNC */ -#ifdef DEBUG_SYNC -#define DEBUG_SYNC_MAX 1000000 -#define BAR 'a' /* begin atomic read */ -#define EAR 'b' /* end atomic read */ -#define BAW 'c' /* begin atomic write */ -#define EAW 'd' /* end atomic write */ -#define SSM 'e' /* slave sending message */ -#define MRM 'f' /* master receiving message */ -#define MSM 'g' /* master sending message */ -#define SRM 'h' /* slave receiving message */ -#define DEBUG_SYNC_TRACE(type) \ - if (sync_trace_idx 1, now -} -// called by master -static int pop_first_msg() { - int first_rank; - ERROR_CHECK(pthread_mutex_lock(&msg_queue)); - wake_for_msg = 1; - while (!is_pending_msg()) pthread_cond_wait(&msg_cond, &msg_queue); - wake_for_msg = 0; - first_rank = rank_of_first_msg; - // next_msg might be NO_MSG - rank_of_first_msg = message[rank_of_first_msg].next_msg; - // CAN THIS EVER HAPPEN? ABOVE WE WAITED UNTIL is_pending_msg() - if (!is_pending_msg()) rank_of_last_msg = NO_MSG; -#ifdef DEBUG_SYNC - DEBUG_SYNC_TRACE(MRM); - DEBUG_SYNC_TRACE('0'+first_rank); -#endif - ERROR_CHECK(pthread_mutex_unlock(&msg_queue)); - return first_rank; -} - -/*********************************************************************** - * Synchronization among do_task() (readers) and update_shared_data() (writer) - * Implements reader-writer synchronization with writer priority. - */ -// One writer: COMM_update_shared_data() -// Multiple readers: COMM_do_task() -// Code also works for multiple writers and readers if user wants to use it so. -static pthread_mutex_t global_lock1 = PTHREAD_MUTEX_INITIALIZER; -static pthread_mutex_t global_lock2 = PTHREAD_MUTEX_INITIALIZER; -static pthread_cond_t global_cond = PTHREAD_COND_INITIALIZER; -static volatile int readers = 0; -static int wake_writer = 0; - -static TOPC_BUF (*orig_do_task)(void *input) = NULL; -static void (*orig_update_shared_data)(void *input, void *output) = NULL; - -void COMM_begin_atomic_read() { - (*(int *)pthread_getspecific(is_atomic_section_key))++; - ERROR_CHECK(pthread_mutex_lock( &global_lock1 )); - ERROR_CHECK(pthread_mutex_lock( &global_lock2 )); - readers++; -#ifdef DEBUG_SYNC - DEBUG_SYNC_TRACE(BAR); - DEBUG_SYNC_TRACE('0'+readers); -#endif - ERROR_CHECK(pthread_mutex_unlock( &global_lock2 )); - ERROR_CHECK(pthread_mutex_unlock( &global_lock1 )); -} -void COMM_end_atomic_read() { - int is_last_reader, val; - ERROR_CHECK(pthread_mutex_lock( &global_lock2 )); - readers--; -#ifdef DEBUG_SYNC - DEBUG_SYNC_TRACE(EAR); - DEBUG_SYNC_TRACE('0'+readers); -#endif - is_last_reader = (readers == 0); - ERROR_CHECK(pthread_mutex_unlock( &global_lock2 )); - val = (*(int *)pthread_getspecific(is_atomic_section_key))--; - if (wake_writer && is_last_reader) pthread_cond_signal(&global_cond); - if ( val < 0 ) - ERROR("more TOPC_END_ATOMIC_READ() than TOPC_BEGIN_ATOMIC_READ/WRITE()"); -} - -void COMM_begin_atomic_write() { - (*(int *)pthread_getspecific(is_atomic_section_key))++; - // Block new readers from starting - ERROR_CHECK(pthread_mutex_lock( &global_lock1 )); - ERROR_CHECK(pthread_mutex_lock( &global_lock2 )); - wake_writer = 1; // Tell reader to wake me when he finishes reading - // While writer is in cond_wait(), global_lock2 is unlocked (released). - // When reader executes pthread_cond_signal(), writer wakes up - while (readers>0) pthread_cond_wait(&global_cond, &global_lock2); - wake_writer = 0; // No more readers; cancel wakeup call -#ifdef DEBUG_SYNC - DEBUG_SYNC_TRACE(BAW); -#endif - ERROR_CHECK(pthread_mutex_unlock( &global_lock2 )); -} -void COMM_end_atomic_write() { - int val; -#ifdef DEBUG_SYNC - DEBUG_SYNC_TRACE(EAW); -#endif - // Allow new readers to enter - ERROR_CHECK(pthread_mutex_unlock( &global_lock1 )); - val = (*(int *)pthread_getspecific(is_atomic_section_key))--; - if ( val < 0 ) - ERROR("more TOPC_END_ATOMIC_WRITE() than TOPC_BEGIN_ATOMIC_READ/WRITE()"); -} -#if 0 -/* BUG: If application nests TOPC_ATOMIC_READ/WRITE{} inside - * TOPC_ATOMIC_BEGIN/END_ATOMIC_READ/WRITE, - * this code gets mixed up about whether it's in atomic section. - */ -TOPC_BOOL COMM_is_in_atomic_section() { - /* The int value is initialized to 0, and toggles between 1 and 0 */ - return *(int *)pthread_getspecific(is_atomic_section_key) = - 1 - *(int *)pthread_getspecific(is_atomic_section_key); -} -#endif -TOPC_BOOL COMM_is_in_atomic_section() { - int val; - val = *(int *)pthread_getspecific(is_atomic_section_key); - if ( val < 0 ) { - printf("TOP-C: more TOPC_END_ATOMIC_xxx() than TOPC_BEGIN_ATOMIC_xxx()"); - exit(1); - /* NOTREACHED */ - } - else return ( val > 0 ? 1 : 0 ); -} - -/*********************************************************************** - *********************************************************************** - * GET RID OF CODE IN THIS SECTION WHEN SURE IT'S NOT NEEDED - *********************************************************************** - ***********************************************************************/ -// set by topc.c -extern TOPC_BUF (*COMM_do_task)(void *input); -extern void (*COMM_update_shared_data)(void *input, void *output); - - -static TOPC_BUF COMM_do_task_wrapper(void *input) { - TOPC_BUF buf; - buf = orig_do_task(input); - return buf; -} -// Note COMM_generate_task_input() also runs on master thread, -// and so it cannot run while COMM_update_shared_data() runs. -static void COMM_update_shared_data_wrapper(void *input, void *output) { - orig_update_shared_data(input, output); -} -// add wrapper if is_wrap != 0, and remove wrapper if is_wrap == 0 -// Not used currently -static void add_wrapper_to_callbacks(int is_wrap) { - if (is_wrap && orig_do_task == NULL) { - // Make TOPC_master_slave() call our new wrapper functions - orig_do_task = COMM_do_task; - orig_update_shared_data = COMM_update_shared_data; - COMM_do_task = COMM_do_task_wrapper; - COMM_update_shared_data = COMM_update_shared_data_wrapper; - } else if (!is_wrap && orig_do_task != NULL) { - COMM_do_task = orig_do_task; - COMM_update_shared_data = orig_update_shared_data; - orig_do_task = NULL; - orig_update_shared_data = NULL; - } -} - -/*********************************************************************** - *********************************************************************** - * MPI-style Communications library on top of synchronization constructs - *********************************************************************** - ***********************************************************************/ - -/*********************************************************************** - * Initialize underlying communications library - */ -void COMM_init(int *dummy_argc, char ***dummy_argv) { - static int slave_attr_initialized = 0; - static int main_rank = 0; - static int main_is_atomic_section = 0; - int i; - - if ( TOPC_OPT_num_slaves != UNINITIALIZED ) - node_count = TOPC_OPT_num_slaves + 1; - if ( TOPC_OPT_num_slaves == UNINITIALIZED ) { -#ifdef _SC_NPROCESSORS_ONLN - node_count = sysconf( _SC_NPROCESSORS_ONLN ); // num processors online -#else - node_count = sysconf( 15 ); // On Solaris, _SC_NPROCESSORS_ONLN == 15 -#endif - if (node_count < 3) node_count = 3; // sysconf error => -1 - } - if ( node_count > TOPC_MAX_SLAVES ) - ERROR("Configured for at most %d threads, %d requested.\n", - TOPC_MAX_SLAVES, node_count ); - // This is "hint" to operating system -- not binding; not all O/S have it. -#ifdef HAVE_PTHREAD_SETCONCURRENCY - /* threads: slaves + 1 (no thread should need to context switch) */ - pthread_setconcurrency( node_count ); -#endif - last_rank = 0; - - if ( ! slave_attr_initialized ) { - pthread_attr_init(&slave_attr); -// bound = permanently attach thread to execution vehicle -// (if not bound, can have fewer execution vehicles in kernel, -// which attach to different threads at different times, based -// on also doing user space scheduling) -// scheduling in system scope (bound threads, scheduled in kernel) often -// needs privilegs -#ifdef HAVE_PTHREAD_SCOPE_BOUND_NP - pthread_attr_setscope(&slave_attr, PTHREAD_SCOPE_BOUND_NP); -#else - pthread_attr_setscope(&slave_attr, PTHREAD_SCOPE_PROCESS); -#endif - // pthread_attr_setscope(&slave_attr, PTHREAD_SCOPE_SYSTEM); - pthread_attr_setdetachstate(&slave_attr, PTHREAD_CREATE_DETACHED); - - pthread_key_create( &thread_private_key, free_key_value ); - pthread_key_create( &is_atomic_section_key, NULL ); - pthread_setspecific( is_atomic_section_key, &main_is_atomic_section ); - *(int *)pthread_getspecific( is_atomic_section_key ) = 0; - pthread_key_create( &stack_bottom_key, NULL ); // for COMM_is_on_stack() - pthread_key_create( &rank_key, NULL ); - pthread_setspecific( rank_key, &main_rank ); // set value of main() thread - } - slave_attr_initialized = 1; - i = sem_init( &master_semaphore, 0, 0 ); - if (i == -1) PERROR("sem_init"); - is_initialized = 1; -} -//called by new slave -//slave_thread_create() calls pthread_create() which calls this as init routine -static void *slave_thread_init(void *rank_ptr) { - int rank; // Is on stack for life of thread - int is_atomic_section = 0; // Is on stack for life of thread - int tid = pthread_self(); // Used only for debugging, e.g. gdb - rank = *(int *)rank_ptr; - pthread_setspecific( stack_bottom_key, &rank ); // for COMM_is_on_stack() - pthread_setspecific( rank_key, &rank ); - pthread_setspecific( is_atomic_section_key, &is_atomic_section ); - sem_post( &master_semaphore ); // tell master last_rank now copied by slave - // Is there a POSIX way for a slave thread (not process) to sleep? - // if (TOPC_OPT_slave_wait>0) - // sleep(TOPC_OPT_slave_wait); - // master:COMM_finalize() will set COMM_do_task = pthread_exit() - // and next TASK_INPUT_TAG message for slave will "poison it". - while (1) - (*COMM_slave_loop)(); - return NULL; -} -//called by master -static void slave_thread_create() { - pthread_t tid; - int val; - - last_rank++; // pass last_rank to new slave - pthread_mutex_init(&message[last_rank].mutex, NULL); - val = sem_init( &(message[last_rank].sem), 0, 0 ); - if (val == -1) PERROR("sem_init"); - // Initialize to 1 (resource = 1 msg buf; master can put it in use once) - sem_init( &(message[last_rank].sem_inuse), 0, 1 ); - if (val == -1) PERROR("sem_init"); - message[last_rank].in_use = 0; -#ifdef _POSIX_THREAD_ATTR_STACKSIZE - pthread_attr_setstacksize(&slave_attr, PTHREAD_STACKSIZE); -#endif - val = pthread_create( &tid, &slave_attr, slave_thread_init, &last_rank ); - if (val != 0) ERROR("%s\n", strerror(val) ); -#ifdef _POSIX_THREAD_ATTR_STACKSIZE - { int val = pthread_attr_getstacksize(&slave_attr, &stacksize); - if (val) ERROR("%s\n", strerror(val) ); - } -#endif - sem_wait( &master_semaphore ); // wait until slave copies last_rank - if (val == -1) PERROR("sem_wait"); -} - -/*********************************************************************** - * Shutdown underlying communications library - */ -static TOPC_BUF do_task_exit(void *dummy_input) { - extern TOPC_BUF NOTASK; - pthread_exit(NULL); - /* NOTREACHED */ - return NOTASK; -} -void COMM_finalize() { - int i; - - // Slave shouldn't be arriving here, but just in case: - if (COMM_rank() != 0) // if we're a slave, then exit - pthread_exit(NULL); - COMM_do_task = do_task_exit; // next task executed by slave will poison it - if ( last_rank > 0 ) { // If TOPC_master_slave was called, and slaves exist - for (i=1; i < node_count; i++) // num_slaves == node_count - 1 - COMM_send_msg(NULL, 0, i, TASK_INPUT_TAG); - is_initialized = 0; - last_rank = 0; - } -#ifdef DEBUG_SYNC - print_sync_trace(); -#endif -} - -/*********************************************************************** - * Test if underlying communications library is running - */ -TOPC_BOOL COMM_initialized() { - return is_initialized; -} - -/*********************************************************************** - * Get number of nodes - */ -int COMM_node_count() { - return node_count; -} - -/*********************************************************************** - * Get rank of this node - */ -int COMM_rank() { - if ( is_initialized ) - return *(int *)pthread_getspecific( rank_key ); - else return 0; -} - -/*********************************************************************** - * Return boolean, true if master and slave share memory - */ -int COMM_is_shared_memory() { - return 1; // true -} - -/*********************************************************************** - * Return boolean, true if master and slave share memory - */ -void *COMM_stack_bottom = NULL; // set in topc.c - -TOPC_BOOL COMM_is_on_stack(void *buf, size_t size) { - /* argument size not currently used, but available for future */ - int stack_top[8]; /* This won't be put in register */ - void *stack_bottom; - - stack_bottom = pthread_getspecific( stack_bottom_key ); - if (! stack_bottom) // then this must be master thread - stack_bottom = COMM_stack_bottom; -#ifdef _POSIX_THREAD_ATTR_STACKSIZE - else - if ( (size_t)abs((char *)stack_bottom-(char *)stack_top) - > stacksize - (1 << 10)) - ERROR("TOPC_MSG() buffer (%d bytes) too large for\n" - " slave thread stack (size %d bytes)\n" - " Either re-compile %s with larger STACKSIZE value\n" - " or allocate buffer outside of stack.\n", - size, stacksize, __FILE__); -#endif - if ( (buf >= (void *)stack_top && buf <= stack_bottom) - || (buf <= (void *)stack_top && buf >= stack_bottom) ) - return 1; // true - else - return 0; // false -} - -/*********************************************************************** - * Set via SOFT_ABORT_TAG - */ -// read on slave by TOPC_is_abort_pending() -volatile int COMM_is_abort_pending = 0; -// called on master by TOPC_abort() -void COMM_soft_abort() { - COMM_is_abort_pending = 0; - } - -/*********************************************************************** - * Check if a message from a slave is instantly available (non-blocking) - */ -TOPC_BOOL COMM_probe_msg() { - - return is_pending_msg(); - - //Blocking version that works if called on slave: - // struct MSG *msg_ptr; - // msg_ptr = &message[COMM_rank()]; - // sem_wait( &msg_ptr->sem ); - // sem_post( &msg_ptr->sem ); // since available message was not consumed - // return 1; -} - -/*********************************************************************** - * Check for a message from a slave (blocking) - */ -TOPC_BOOL COMM_probe_msg_blocking(int rank) { - // master calls, waits for message from slave - if ( ! message[rank].in_use ) { - ERROR_CHECK(pthread_mutex_lock(&msg_queue)); - wake_for_msg = 1; - while ( ! message[rank].in_use ) pthread_cond_wait(&msg_cond, &msg_queue); - wake_for_msg = 0; - ERROR_CHECK(pthread_mutex_unlock(&msg_queue)); - } - return 1; -} - -/*********************************************************************** - * Send message - */ -TOPC_BOOL COMM_send_msg(void *msg, size_t dummy_msg_size, int dst, - enum TAG tag) { - struct MSG *msg_ptr; - int myrank, i; - - if ( dst != 0 ) { // if we're master (guaranteed not busy) - if ( last_rank == 0 ) { // Only main() thread exists so far - for (i=1; i < node_count; i++) // num_slaves == node_count - 1 - slave_thread_create(); - } - msg_ptr = &message[dst]; - sem_wait( &msg_ptr->sem_inuse ); // Wait if slave didn't yet read last msg - msg_ptr->tag = tag; - msg_ptr->buf = msg; - msg_ptr->in_use = 1; -#ifdef DEBUG_SYNC - DEBUG_SYNC_TRACE(MSM); - DEBUG_SYNC_TRACE('0'+dst); -#endif - sem_post( &msg_ptr->sem ); - } - else { // else we're slave - myrank = COMM_rank(); - msg_ptr = &message[myrank]; - if ( msg_ptr->in_use ) - ERROR("Internal error: slave found msg buf already in use"); - msg_ptr->tag = tag; - msg_ptr->buf = msg; - msg_ptr->in_use = 1; - add_next_msg(myrank); - // pthread_mutex_unlock( &(msg_ptr->mutex) ); // IS NEEDED? write barr.? - } - return 1; -} - -/*********************************************************************** - * Receive message into previously malloc'ed memory (blocking call) - * Receive from anybody, and set each of four param's if non-NULL - * (msg_size not set by current code) - */ -TOPC_BOOL COMM_receive_msg(void **msg, size_t *dummy_msg_size, int *src, - enum TAG *tag) { - struct MSG *msg_ptr; - int myrank, actual_src; - - myrank = COMM_rank(); - - if ( myrank == 0 ) { // if we're master - actual_src = pop_first_msg(); // master blocks here if no msg - msg_ptr = &message[actual_src]; - if ( ! msg_ptr->in_use ) - ERROR("Internal error: master waiting on single slave"); - if (src) *src = actual_src; - if (tag) *tag = msg_ptr->tag; - if (msg) *msg = msg_ptr->buf; - msg_ptr->in_use = 0; - } - else { // else we're slave - msg_ptr = &message[myrank]; - sem_wait( &msg_ptr->sem ); - if ( ! msg_ptr->in_use ) - ERROR("Internal error: slave found msg buf with no message"); - // pthread_mutex_lock( &(msg_ptr->mutex) ); // IS THIS NEEDED? write barr.? - // slave call to pthread_mutex_unlock() served as write barrier - if (src) *src = 0; - if (tag) *tag = msg_ptr->tag; - if (msg) *msg = msg_ptr->buf; -#ifdef DEBUG_SYNC - DEBUG_SYNC_TRACE(SRM); - DEBUG_SYNC_TRACE('0'+myrank); -#endif - msg_ptr->in_use = 0; - sem_post( &msg_ptr->sem_inuse ); // Let master use msg_ptr again - } - return 1; -} - -// balances MEM_malloc() in COMM_receive_msg(), no malloc() for pthread -void COMM_free_receive_buf(void *dummy_msg) { - return; -} - - -/*********************************************************************** - *********************************************************************** - * SMP-related functions (e.g.: private (non-shared) variables) - *********************************************************************** - ***********************************************************************/ -static pthread_mutex_t key_mutex = PTHREAD_MUTEX_INITIALIZER; - -void *COMM_thread_private(size_t size) { - void *thread_private_val; - static int thread_private_initialized = 0; - static size_t old_size = 0; - - /* Occurs if application called us before TOPC_init() */ - if (! thread_private_initialized) { - pthread_mutex_lock(&key_mutex); /* Try again in critical section */ - if (! thread_private_initialized) { - pthread_key_create( &thread_private_key, free_key_value ); - old_size = size; - thread_private_initialized = 1; - } - pthread_mutex_unlock(&key_mutex); - } - if (size != old_size) - ERROR("TOPC_thread_private_t redeclared as a type of a different size."); - thread_private_val = pthread_getspecific(thread_private_key); - if (thread_private_val) return thread_private_val; - // else it was never initialized - thread_private_val = malloc(size); - //In case it's a pointer, initialize to NULL pointer for user - if (size >= sizeof(void *)) - *(void **)thread_private_val = NULL; - pthread_setspecific(thread_private_key, thread_private_val); - - return thread_private_val; -} - diff --git a/topc-2.5.2/src/comm-seq.c b/topc-2.5.2/src/comm-seq.c deleted file mode 100644 index a7bb2479..00000000 --- a/topc-2.5.2/src/comm-seq.c +++ /dev/null @@ -1,220 +0,0 @@ -/********************************************************************** - * TOP-C (Task Oriented Parallel C) * - * Copyright (c) 2000 Gene Cooperman * - * * - * This library is free software; you can redistribute it and/or * - * modify it under the terms of the GNU Lesser General Public * - * License as published by the Free Software Foundation; either * - * version 2.1 of the License, or (at your option) any later version. * - * * - * This library is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * - * Lesser General Public License for more details. * - * * - * You should have received a copy of the GNU Lesser General Public * - * License along with this library (see file COPYING); if not, write * - * to the Free Software Foundation, Inc., 59 Temple Place, Suite * - * 330, Boston, MA 02111-1307 USA, or contact Gene Cooperman * - * . * - **********************************************************************/ - -#include -#include // malloc() -#include "comm.h" // comm.h also defines HAVE_PTHREAD, etc., by default - -// NOTE: MPI returns MPI_SUCCESS or application-dependent indication -// of failure. We may MPI_SUCCESS to TRUE and others to FALSE. -#ifndef FALSE -enum {FALSE, TRUE}; -#endif - -char *COMM_mem_model = "sequential"; - - -/*********************************************************************** - *********************************************************************** - ** Communications and MPI functions for sequential layer - ** (it assumes 1 slave, and we're always excuting on master) - *********************************************************************** - ***********************************************************************/ - - -/*********************************************************************** - * private COMM variables to emulate MPI, messages - * (could emulate several slaves by using arrays here) - */ -static int is_initialized = 0; -static int is_output_msg_available = 0; -static void *output_msg = NULL; -static size_t output_msg_size = 999999; - -/*********************************************************************** - * Initialize underlying communications library - */ -void COMM_init(int *adummy_rgc, char ***dummy_argv) { - is_initialized = 1; -} - -/*********************************************************************** - * Shutdown underlying communications library - */ -void COMM_finalize() { - is_initialized = 0; -} - -/*********************************************************************** - * Test if underlying communications library is running - */ -TOPC_BOOL COMM_initialized() { - return is_initialized; -} - -/*********************************************************************** - * Get number of nodes - */ -int COMM_node_count() { - return 2; // master and slave -} - -/*********************************************************************** - * Get rank of this node - */ -static int is_in_do_task = 0; - -int COMM_rank() { - if (is_in_do_task) - return 1; - else - return 0; -} - -/*********************************************************************** - * Return boolean, true if master and slave share memory - */ -int COMM_is_shared_memory() { - return 0; // false -} - -/*********************************************************************** - * Return boolean, true if master and slave share memory - */ -void *COMM_stack_bottom = NULL; // set in topc.c - -TOPC_BOOL COMM_is_on_stack(void *buf, size_t dummy_size) { - int stack_top[8]; /* This won't be put in register */ - - if ( (buf >= (void *)stack_top && buf <= COMM_stack_bottom) - || (buf <= (void *)stack_top && buf >= COMM_stack_bottom) ) - return 1; // true - else - return 0; // false -} - -/*********************************************************************** - * Set via SOFT_ABORT_TAG - */ -//read on slave by TOPC_is_abort_pending() -volatile int COMM_is_abort_pending = 0; -// called on master by TOPC_abort() -void COMM_soft_abort() { - COMM_is_abort_pending = 0; - } - -/*********************************************************************** - * Check if a message from a slave is instantly available (non-blocking) - */ -TOPC_BOOL COMM_probe_msg() { - return is_output_msg_available; -} - -/*********************************************************************** - * Check for a message from a slave (blocking) - */ -TOPC_BOOL COMM_probe_msg_blocking(int dummy_rank) { - if ( ! is_output_msg_available ) - ERROR("COMM_probe_msg_blocking: Deadlock." - " Blocking and no msg available from slave.\n"); - return 1; -} - -/*********************************************************************** - * Send message - */ -TOPC_BOOL COMM_send_msg(void *msg, size_t dummy_msg_size, int dummy_dst, - enum TAG tag) { - TOPC_BUF buf; - - // always on master; always to slave - switch( tag ) { - case TASK_INPUT_TAG: - case REDO_INPUT_TAG: - case CONTINUATION_INPUT_TAG: - is_in_do_task = 1; - buf = (*COMM_do_task)(msg); - if (TOPC_OPT_aggregated_tasks <= 1) - MEM_register_buf(buf.data); - is_in_do_task = 0; - is_output_msg_available = 1; - // flow through to next case - case PING_TAG: - output_msg = buf.data; - output_msg_size = buf.data_size; // Shouldn't be used by master_slave() - default: // for other cases, ignore the message - ; - } - return 1; -} - -/*********************************************************************** - * Receive message into malloc'ed memory (blocking call) - * receive from anybody, and set each of four param's if non-NULL - */ -TOPC_BOOL COMM_receive_msg(void **msg, size_t *msg_size, int *src, - enum TAG *tag) { - if ( ! is_output_msg_available ) - ERROR("COMM_receive_msg: Deadlock." - " Blocking and no msg available from slave.\n"); - // always on master; always from slave - if (msg) *msg = output_msg; - if (msg_size) *msg_size = output_msg_size; - if (src) *src = 1; - if (tag) *tag = SLAVE_REPLY_TAG; - is_output_msg_available = 0; - return TRUE; -} - -// balances MEM_malloc() in COMM_receive_msg(), no malloc() for seq -void COMM_free_receive_buf(void *dummy_msg) { - return; -} - -/*********************************************************************** - *********************************************************************** - * SMP-related functions (e.g.: private (non-shared) variables) - *********************************************************************** - ***********************************************************************/ - -void *COMM_thread_private(size_t size) { // trivial for non-shared memory - static void *master_thr_priv = NULL, *slave_thr_priv = NULL; - if ( slave_thr_priv == NULL ) { - master_thr_priv = malloc(size); - slave_thr_priv = malloc(size); - if (size >= sizeof(void *)) { - *(void **)master_thr_priv = NULL; - *(void **)slave_thr_priv = NULL; - } - } - if (is_in_do_task) - return slave_thr_priv; - else - return master_thr_priv; -} -void COMM_begin_atomic_read() {} -void COMM_end_atomic_read() {} -void COMM_begin_atomic_write() {} -void COMM_end_atomic_write() {} -TOPC_BOOL COMM_is_in_atomic_section() { - static int is_in = 0; - return (is_in = 1 - is_in); -} diff --git a/topc-2.5.2/src/comm.h b/topc-2.5.2/src/comm.h deleted file mode 100644 index 45e32ac9..00000000 --- a/topc-2.5.2/src/comm.h +++ /dev/null @@ -1,239 +0,0 @@ - /********************************************************************** - * TOP-C (Task Oriented Parallel C) * - * Copyright (c) 2000 Gene Cooperman * - * and Victor Grinberg * - * * - * This library is free software; you can redistribute it and/or * - * modify it under the terms of the GNU Lesser General Public * - * License as published by the Free Software Foundation; either * - * version 2.1 of the License, or (at your option) any later version. * - * * - * This library is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * - * Lesser General Public License for more details. * - * * - * You should have received a copy of the GNU Lesser General Public * - * License along with this library (see file COPYING); if not, write * - * to the Free Software Foundation, Inc., 59 Temple Place, Suite * - * 330, Boston, MA 02111-1307 USA, or contact Gene Cooperman * - * . * - **********************************************************************/ - -#include -#include -#include - -/*********************************************************************** - * This is included in topc.c and comm-xxx.c and page.c . It defines the - * interface between the two. - */ - -#ifndef _COMM_H -#define _COMM_H - -/* #define HAVE_PTHREAD as default, but not if HAVE_PTHREAD == 0 */ -#ifdef HAVE_PTHREAD -# if HAVE_PTHREAD == 0 -# undef HAVE_PTHREAD -# endif -#else -# define HAVE_PTHREAD -#endif - -/* #define HAVE_SEMAPHORE as default, but not if HAVE_SEMAPHORE == 0 */ -#ifdef HAVE_SEMAPHORE -# if HAVE_SEMAPHORE == 0 -# undef HAVE_SEMAPHORE -# endif -#else -# define HAVE_SEMAPHORE -#endif - -/* If HAVE_THR_SETCONCURRENCY, undefine it and patch pthread_setconcurrency */ -#ifdef HAVE_THR_SETCONCURRENCY -# ifndef HAVE_PTHREAD_SETCONCURRENCY -# include -# define pthread_getconcurrency thr_getconcurrency -# define pthread_setconcurrency thr_setconcurrency -# define HAVE_PTHREAD_SETCONCURRENCY -# endif -# undef HAVE_THR_SETCONCURRENCY -#endif - -#include // Needed to define size_t - -//Compile-time parameters (complete set in topc.c) -#define TOPC_MAX_SLAVES 1000 /* Max. number of slaves */ -#define NUM_MSG_CACHE_PTR 100 /* Num pending msg's that can be cached */ - -extern char *COMM_mem_model; - -/*********************************************************************** - * Interface to command line options (options.c) - */ -void TOPC_OPT_pre_init( int *argc, char ***argv ); -void TOPC_OPT_post_init( int *argc, char ***argv ); -void TOPC_OPT_finalize( int num_tasks, int num_redos, int num_updates ); -char *TOPC_OPT_getpwd( char *buf, size_t size ); -#define UNINITIALIZED -1 - -/*********************************************************************** - * TOP-C command line options for application (see options.c for defs) - */ -// These are also in topc.h -extern int TOPC_OPT_num_slaves; -extern int TOPC_OPT_aggregated_tasks; -extern int TOPC_OPT_slave_wait; -extern int TOPC_OPT_slave_timeout; -extern int TOPC_OPT_trace; -extern int TOPC_OPT_help; -extern int TOPC_OPT_verbose; -extern int TOPC_OPT_stats; -extern char * TOPC_OPT_procgroup; -extern char * TOPC_OPT_topc_log; -extern int TOPC_OPT_safety; - -/*********************************************************************** - * Levels for TOPC_OPT_safety - * These values are subject to change as more safety levels are added. - */ -#define SAFETY_NONE 0 -#define SAFETY_NO_MSG_PTR 4 -// Still not sure if memory manager has bug in shared memory in unusual case -#define SAFETY_NO_MEM_MGR 6 -#define SAFETY_NO_AGGREG 8 -#define SAFETY_NO_ABORT_TASKS 12 -#define SAFETY_NO_RCV_THREAD 14 -#define SAFETY_DFLT_ATOMIC_READ_WRITE 16 -#define SAFETY_TWO_SLAVES 19 -#define SAFETY_ONE_SLAVE 20 -#define SAFETY_NO_TIMEOUT 21 - -/*********************************************************************** - * TOP-C data types (shared with topc.h) - */ -#ifndef TOPC_TYPES -#define TOPC_TYPES -typedef int TOPC_BOOL; -typedef struct { - void *data; - size_t data_size; -} TOPC_BUF; -typedef void TOPC_FUNCTION(); -struct TOPC_OPT { - char *name; - union { int integer; TOPC_FUNCTION *fnc; } value; -}; -#endif - -/*********************************************************************** - * TOP-C data types (not in topc.h) - */ -enum TAG { - NO_TAG, - TASK_INPUT_TAG, - REDO_INPUT_TAG, /* Currently, TASK_INPUT_TAG used insted during REDO */ - CONTINUATION_INPUT_TAG, - UPDATE_INPUT_TAG, - UPDATE_OUTPUT_TAG, - SLAVE_REPLY_TAG, - END_MASTER_SLAVE_TAG, - PING_TAG, - CHDIR_TAG, - SLAVE_WAIT_TAG, - SOFT_ABORT_TAG, - MEM_TAG, /* placeholder by MEM system; replaced by other tag later */ - PAGE_ACCESS_TAG, - MAX_TAG /* not used, marks last valid tag */ -}; - -extern TOPC_BUF (*COMM_do_task)(void *input); // for comm-seq.c -extern TOPC_BUF TOPC_MSG(void *input, size_t input_size); // for comm-seq.c -extern void (*COMM_slave_loop)(void); // for comm-pthreads.c - -/*********************************************************************** - * COMM layer functions (interface between comm-xxx.c and topc.c) - */ -void COMM_init(int *argc, char ***argv); -void COMM_finalize(void); -TOPC_BOOL COMM_initialized(void); -int COMM_is_shared_memory(void); -int COMM_node_count(void); -int COMM_rank(void); -TOPC_BOOL COMM_probe_msg(void); -TOPC_BOOL COMM_probe_msg_blocking(int); -TOPC_BOOL COMM_send_msg(void *msg, size_t msg_size, int dst, enum TAG tag); -TOPC_BOOL COMM_receive_msg(void **msg, size_t *msg_size, int *src, enum TAG *tag); -void COMM_free_receive_buf(void *msg); -TOPC_BOOL COMM_is_on_stack(void *buf, size_t size); -extern void *COMM_stack_bottom; -void COMM_soft_abort(void); // called by master -extern volatile int COMM_is_abort_pending; // read on slave - -/*********************************************************************** - * SMP functions - */ -void COMM_begin_atomic_read(void); -void COMM_end_atomic_read(void); -void COMM_begin_atomic_write(void); -void COMM_end_atomic_write(void); -TOPC_BOOL COMM_is_in_atomic_section(void); - -// end TOPC_H -#endif - -/*********************************************************************** - * Functions from memory.c - */ -enum hdr_type { - UNUSED_HDR, IS_MALLOC, IS_PRE_MSG, IS_PRE_MSG_PTR, - IS_MSG, IS_MSG_PTR }; -void *MEM_malloc(size_t size, int source, enum TAG tag, enum hdr_type type); -void MEM_register_buf(void *buf); -void MEM_free(void *buf); - -/*********************************************************************** - *********************************************************************** - ** Printout functions and debugging - *********************************************************************** - ***********************************************************************/ -static void WARNING(char *format,...) { - va_list ap; - if (TOPC_OPT_verbose >= 0) { - va_start(ap, format); - fprintf(stderr, "*** TOP-C WARNING: "); - vfprintf(stderr, format, ap); - fprintf(stderr, "\n"); - va_end(ap); - } -} - -//This function should perhaps take steps to perform proper shutdown -static void ERROR(char *format,...) { - va_list ap; - va_start(ap, format); - fprintf(stderr, "*** TOP-C: "); - vfprintf(stderr, format, ap); - fprintf(stderr, "\n"); - fflush(stderr); - va_end(ap); - exit(1); -} - -//This function should perhaps take steps to perform proper shutdown -//Could allow arguments, as in ERROR() -static void PERROR(char *str) { - fprintf(stderr, "*** TOP-C(%s:%d): ", __FILE__, __LINE__); - perror(str); - exit(1); -} - -/*********************************************************************** - * For debugging - * syscall(...) => - * CHECK( - * syscall(...) - * ) - */ -#define CHECK(x) {int val=x if (val == -1) {perror("TOP-C"); exit(1);}} diff --git a/topc-2.5.2/src/memory.c b/topc-2.5.2/src/memory.c deleted file mode 100644 index 9c594132..00000000 --- a/topc-2.5.2/src/memory.c +++ /dev/null @@ -1,436 +0,0 @@ - /********************************************************************** - * TOP-C (Task Oriented Parallel C) * - * Copyright (c) 2000-2001 Gene Cooperman * - * * - * This library is free software; you can redistribute it and/or * - * modify it under the terms of the GNU Lesser General Public * - * License as published by the Free Software Foundation; either * - * version 2.1 of the License, or (at your option) any later version. * - * * - * This library is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * - * Lesser General Public License for more details. * - * * - * You should have received a copy of the GNU Lesser General Public * - * License along with this library (see file COPYING); if not, write * - * to the Free Software Foundation, Inc., 59 Temple Place, Suite * - * 330, Boston, MA 02111-1307 USA, or contact Gene Cooperman * - * . * - **********************************************************************/ - -/* EXPORTED FUNCTIONS: TOPC_MSG, TOPC_MSG_PTR, MEM_malloc, MEM_register_buf, - * MEM_free - * This code does malloc/free while recording special header info. - * After GenerateTaskInput/DoTask is called, MEM_register_buf() - * verifies that TOPC_MSG()/TOPC_MSG_PTR() was called at least once. - * If called more than once, extra buffers are silently freed. - * MEM_free - * The code must deal with two kinds of buffers: - * (1) buffers dynamically allocated by MEM_malloc() via a call to malloc() - * (2) buffers located in application space (including NULL pointers) - * for which TOP-C creates a header. - * Buffers of type (2) are created by the application and arise either through - * calls to TOPC_MSG_PTR() or in cases where TOP-C can prove it doesn't - * need to copy the messages into TOP-C space. - * - * Typical sequence: TOPC_MSG/MEM_malloc, MEM_register_buf, MEM_free - * - * A buffer of type (1) or (2) has an associated struct mem_hdr, whose - * type field indicated its current state. - * State transitions: IS_MALLOC->IS_PRE_MSG->IS_MSG->UNUSED_HDR - * or: IS_PRE_MSG_PTR->IS_MSG_PTR->UNUSED_HDR - * Function called resulting in new state: - * MEM_malloc()->IS_MALLOC->TOPC_MSG()->IS_PRE_MSG - * ->MEM_register_buf()->IS_MSG - * ->MEM_free()->UNUSED_HDR (and frees it) - * - * mem_hdr's implemented as doubly linked list - * (eventually, want to turn it into circular buffer): - * mem_hdr_start==mem_hdr_head mem_hdr_register mem_hdr_tail - * <--prev next--> - * MEM_malloc enqueues new mem_hdr as mem_hdr_tail->next, - * and moves mem_hdr_tail toward it. - * Call to malloc() done within mutex crit. section. - * MEM_register_buf moves toward `next', and examines each mem_hdr. - * mem_hdr_head, mem_hdr_register, mem_hdr_tail always move toward `next' - */ - -#include -#include -#include -#include - -#include "comm.h" // comm.h also defines HAVE_PTHREAD, etc., by default -#ifdef HAVE_PTHREAD -# include -#endif - -/*********************************************************************** - * Define reentrant version of mutex_lock/mutex_unlock - * In distributed memory, could remove mutexes (and for master in - * shared memory), but these are cheap. - */ -#ifdef HAVE_PTHREAD -static pthread_mutex_t mem_mgr = PTHREAD_MUTEX_INITIALIZER; -# ifdef DEBUG -# define DEBUG_CHECK debug_check(); -# else -# define DEBUG_CHECK -# endif -/* MUTEX_LOCK/MUTEX_UNLOCK let thread recursively call lock w/o blocking */ - static volatile int recurse_init = 0; - static pthread_key_t recurse_key; -# define MUTEX_LOCK(addr_mutex) \ -{ int *recurse = NULL; \ - if (recurse_init && (recurse = pthread_getspecific(recurse_key)) != NULL \ - && *recurse > 0) \ - *recurse++; \ - else { \ - pthread_mutex_lock(addr_mutex); \ - if ( recurse == NULL ) { \ - if (! recurse_init) { \ - recurse_init = 1; \ - pthread_key_create( &recurse_key, NULL ); \ - } \ - pthread_setspecific(recurse_key, recurse = malloc(sizeof(int))); \ - if ( ! recurse ) PERROR("malloc"); \ - else *recurse = 0; \ - } \ - (*recurse)++; \ - DEBUG_CHECK; \ - } \ -} -# define MUTEX_UNLOCK(addr_mutex) \ - if ( --(*(int *)pthread_getspecific(recurse_key)) <= 0 ) \ - { \ - DEBUG_CHECK; \ - pthread_mutex_unlock(addr_mutex); \ - } -#else -# define MUTEX_LOCK(addr_mutex) -# define MUTEX_UNLOCK(addr_mutex) -# undef volatile -# define volatile -#endif - -/*********************************************************************** - * Access functions for a message - */ - -/* msg = (hdr, buf); Want buf correctly aligned after - * msg=malloc(sizeof_msg(size)); buf=((struct mem_hdr *)msg)+1; - */ -#define ROUNDUP(x) ( (((x)+sizeof(void*)-1) / sizeof(void*)) * sizeof(void*) ) -#define sizeof_msg_header ( ROUNDUP(sizeof(struct mem_hdr)) ) -#define sizeof_msg(size) ( sizeof_msg_header + ROUNDUP(size) ) - -/* (actual declaration in comm.h) */ -// enum hdr_type { -// UNUSED_HDR, IS_MALLOC, IS_PRE_MSG, IS_PRE_MSG_PTR, -// IS_MSG, IS_MSG_PTR }; - -/* mem_hdr is not in use if buf == NULL */ -static struct mem_hdr { - struct mem_hdr *next; - struct mem_hdr *prev; - void *buf; - enum hdr_type type; - enum TAG tag; - int source; -#ifdef HAVE_PTHREAD - pthread_t owner; -#endif - int size; - int id; -} mem_hdr_start -#ifdef HAVE_PTHREAD - = {NULL, NULL, NULL, UNUSED_HDR, NO_TAG, -1, (pthread_t)-1, -1, -1}; -#else - = {NULL, NULL, NULL, UNUSED_HDR, NO_TAG, -1, -1, -1}; -#endif - -/* mem_hdr_head always points to empty mem_hdr_start; acts only as marker */ -/* mem_hdr_register points to last hdr that has been checked */ -static volatile struct mem_hdr *mem_hdr_head = &mem_hdr_start, - *mem_hdr_tail = &mem_hdr_start, - *mem_hdr_register = &mem_hdr_start; -static struct mem_hdr * MEM_buf_hdr(void *buf) /* used for debugging */ - { return (((struct mem_hdr *)(buf)) - 1); } -#define MEM_buf_hdr(buf) (((struct mem_hdr *)(buf)) - 1) -#define buf_of_hdr(hdr) ((void *)(((struct mem_hdr *)(hdr)) + 1)) -#define MEM_buf_type(buf) (MEM_buf_hdr(buf)->type) -#define MEM_buf_tag(buf) (MEM_buf_hdr(buf)->tag) -#define MEM_buf_source(buf) (MEM_buf_hdr(buf)->source) -/* Note this is size of buffer, not including header. - * For including pointer to header in size, use sizeof_msg(MEM_buf_size(buf)). - */ -#define MEM_buf_size(buf) (MEM_buf_hdr(buf)->size) - -static void debug_check() { - struct mem_hdr *hdr; - for (hdr = (struct mem_hdr *)mem_hdr_head; hdr != NULL; hdr = hdr->next) - if ( ((long)(hdr->next) > 0 && (long)(hdr->next) < 1000) - || ((long)(hdr->prev) > 0 && (long)(hdr->prev) < 1000) ) - ERROR("Bad hdr->next"); - for (hdr = (struct mem_hdr *)mem_hdr_register; hdr != NULL ; hdr = hdr->prev) - if (hdr->type == IS_PRE_MSG_PTR || hdr->type == IS_PRE_MSG) - ERROR("debug_check: mem_hdr_register overrun"); -} - -/*********************************************************************** - * malloc a buffer + header - */ -void *MEM_malloc(size_t size, int source, enum TAG tag, enum hdr_type type) { - static int id = 0; - struct mem_hdr *hdr; - if (TOPC_OPT_safety >= SAFETY_NO_MEM_MGR) { - void *ptr; - if (size == 0) - return NULL; - MUTEX_LOCK(&mem_mgr); - ptr = malloc(size); - MUTEX_UNLOCK(&mem_mgr); - if (ptr == NULL && size > 0) - PERROR("malloc"); - else - return ptr; - } - assert(tag != NO_TAG); - MUTEX_LOCK(&mem_mgr); - - /* enqueues(malloc((sizeof_msg(size)); */ - assert(mem_hdr_tail->next == NULL); - mem_hdr_tail->next = malloc(sizeof_msg(size)); - if (mem_hdr_tail->next == NULL) - ERROR("No memory to malloc a new buffer.\n"); - /* cast to discard volatile */ - mem_hdr_tail->next->prev = (struct mem_hdr *)mem_hdr_tail; - mem_hdr_tail = mem_hdr_tail->next; - mem_hdr_tail->next = NULL; - hdr = (struct mem_hdr *)mem_hdr_tail; /* cast to discard volatile */ - hdr->id = id; /* used for debugging */ - if (id++ >= 1000000000) id = 0; - assert(hdr->prev->next == hdr); - assert(hdr->next == NULL); - - hdr->tag = tag; - hdr->source = source; - hdr->size = size; - hdr->type = type; -#ifdef HAVE_PTHREAD - hdr->owner = pthread_self(); -#endif - hdr->buf = buf_of_hdr(hdr); - MUTEX_UNLOCK(&mem_mgr); /* MEM_register_buf needs above fields stable */ - assert(MEM_buf_hdr(hdr->buf) == hdr); -# ifdef DEBUG -printf("rank: %d, mem_hdr_head: %x, mem_hdr_head->next: %x, mem_hdr_tail: %x\n", -COMM_rank(), mem_hdr_head, mem_hdr_head->next, mem_hdr_tail); - printf("rank: %d; buf_of_hdr(hdr): %x, size: %d, source: %d, tag: %d," - " type: %d, id: %d\n", - COMM_rank(), buf_of_hdr(hdr), size, source, tag, type, hdr->id); -# endif - return hdr->buf; -} -void *MEM_malloc_ptr(void *buf, size_t size, int source, enum TAG tag, - enum hdr_type type) { - struct mem_hdr *hdr; - if (TOPC_OPT_safety >= SAFETY_NO_MEM_MGR) - return buf; - hdr = MEM_buf_hdr(MEM_malloc(0, source, tag, type)); - hdr->buf = buf; - hdr->size = size; - return buf; -} - -/*********************************************************************** - * Free any buffer created by MEM_malloc - * (only routine to change type to UNUSED_HDR) - */ -void MEM_free(void *buf) { - struct mem_hdr *hdr = MEM_buf_hdr(buf); - - if (TOPC_OPT_safety >= SAFETY_NO_MEM_MGR) { - if (buf != NULL) - free(buf); - return; - } - MUTEX_LOCK(&mem_mgr); -# ifdef DEBUG -printf("rank: %d, mem_hdr_head: %x, mem_hdr_head->next: %x, mem_hdr_tail: %x\n", -COMM_rank(), mem_hdr_head, mem_hdr_head->next, mem_hdr_tail); - printf("rank: %d; owner: %d, free msg: %x, size: %d, source: %d, tag: %d" - ", id: %d\n", - COMM_rank(), -#ifdef HAVE_PTHREAD - MEM_buf_hdr(buf)->owner, -#endif - buf, MEM_buf_size(buf), - MEM_buf_source(buf), MEM_buf_tag(buf), MEM_buf_hdr(buf)->id); -# endif - if (hdr != mem_hdr_tail || hdr->buf != buf) { - /* This logic for IS_MSG_PTR; Probably efficient enough */ - hdr = (struct mem_hdr *)mem_hdr_tail; /* cast to discard volatile */ - while (hdr->buf != buf && hdr != mem_hdr_head) - hdr = hdr->prev; - assert(hdr != mem_hdr_head); - } - assert(hdr->buf == buf); - - /* dequeue(hdr) */ - assert(hdr != mem_hdr_head); /* mem_hdr_head only marker for head of queue */ - assert(hdr->type != UNUSED_HDR); - assert(hdr->prev->next == hdr); - assert(hdr->next == NULL || hdr->next->prev == hdr); - hdr->type = UNUSED_HDR; - hdr->prev->next = hdr->next; - if (mem_hdr_register == hdr) - mem_hdr_register = hdr->prev; - if (hdr->next == NULL) { - assert(hdr == mem_hdr_tail); - mem_hdr_tail = hdr->prev; - mem_hdr_tail->next = NULL; - } - else - hdr->next->prev = hdr->prev; - free(hdr); - assert(mem_hdr_register == mem_hdr_tail || mem_hdr_register->next != NULL); - MUTEX_UNLOCK(&mem_mgr); -} - -/*********************************************************************** - * Called after TOPC_MSG/TOPC_MSG_PTR - * Since TOPC_MSG() can MEM_malloc a new buffer that TOP-C frees, - * it's important that application not trick us by returning - * an old buffer. So, after callback function calls TOPC_MSG() - * TOP-C always calls MEM_register_buf(). - * (MEM_register_buf and MEM_free only routines to modify mem_hdr_register) - * (MEM_register_buf calls MEM_free, only routines - * to change type to UNUSED_HDR) - */ -static void msg_not_found() { - ERROR("MEM_register_buf: Return value of %s at rank %d does\n" - " not appear to be a new invocation of TOPC_MSG/TOPC_MSG_PTR.\n" - " Must return new invocation or NOTASK\n", - (COMM_rank() == 0 ? "GenerateTaskInput()" : "DoTask()"), COMM_rank() ); -} -void MEM_register_buf(void *buf) { - int found = 0; -#ifdef HAVE_PTHREAD - pthread_t tid = pthread_self(); -#endif - struct mem_hdr *hdr_register, *next_hdr_register; - extern TOPC_BUF NOTASK; - - if (TOPC_OPT_safety >= SAFETY_NO_MEM_MGR) { - return; - } - MUTEX_LOCK(&mem_mgr); - next_hdr_register = NULL; - for (hdr_register = (struct mem_hdr *)mem_hdr_register->next; - hdr_register != NULL; - hdr_register = (struct mem_hdr *)hdr_register->next) { /*cast, disc. vol*/ -#ifdef HAVE_PTHREAD - if ( pthread_equal(hdr_register->owner, tid) ) { -#else - if (1) { -#endif - switch (hdr_register->type) { - case IS_PRE_MSG: - case IS_PRE_MSG_PTR: - if (hdr_register->buf == buf) { /* if it's this buf */ - hdr_register->type = - (hdr_register->type==IS_PRE_MSG ? IS_MSG : IS_MSG_PTR); - found = 1; - } else { - assert(hdr_register->prev->next == hdr_register); - hdr_register = (struct mem_hdr *)hdr_register->prev; /*cast, disc. vol*/ - fprintf(stderr, "*** TOP-C: MEM_register_buf:\n" - " WARNING: application callback function" - " called TOPC_MSG() twice.\n"); - MEM_free(hdr_register->next->buf); /* applic. created extra one */ - } - break; - case IS_MSG_PTR: /* MEM_register_buf seeing these a second time */ - case IS_MSG: - assert(hdr_register->type == IS_MSG_PTR || hdr_register->buf != buf); - break; - default: - assert(hdr_register == mem_hdr_head); - } - } else if (next_hdr_register == NULL - && hdr_register->type != IS_MSG - && hdr_register->type != IS_MSG_PTR) { - /* else somebody else's header, mem_hdr_register will stop here */ - assert(hdr_register->type == IS_PRE_MSG - || hdr_register->type == IS_PRE_MSG_PTR); - assert(hdr_register->buf != buf); /* If we don't own it, not our buf */ -# ifdef DEBUG - -# ifdef HAVE_PTHREAD - printf("thread id %d: hdr_register found IS_MSG_PTR or IS_MSG" - " from owner %d\n", tid, hdr_register->owner); -# endif -# endif - next_hdr_register = hdr_register->prev; - } - } - mem_hdr_register = (next_hdr_register==NULL ? mem_hdr_tail : next_hdr_register); - assert(hdr_register == NULL); - assert(mem_hdr_register == mem_hdr_tail || mem_hdr_register->next != NULL); - MUTEX_UNLOCK(&mem_mgr); - - if (! found && buf != NOTASK.data) - msg_not_found(); - return; -} - -/*********************************************************************** - * Creates a TOPC_BUF; copies data from user space to TOP-C space. - */ -TOPC_BUF TOPC_MSG(void *data, size_t data_size) { - if (data == NULL && data_size > 0) - ERROR("TOPC_MSG() called with null pointer and positive size"); - // Always copy to TOP-C space on master; It's called by GenerateTask() - // for input task buffer, and saved for reuse by CheckTaskResult() - if ( TOPC_OPT_safety < SAFETY_NO_MSG_PTR && COMM_rank() != 0 - && ! COMM_is_shared_memory() && ! COMM_is_on_stack(data, data_size) ) { - /* for size 0, malloc a header only; equiv of TOPC_MSG_PTR() */ - MEM_malloc_ptr( data, data_size, COMM_rank(), MEM_TAG, IS_PRE_MSG_PTR ); - { TOPC_BUF tmp; - tmp.data = data; tmp.data_size = data_size; - return tmp; - } - } else { - data = memcpy( MEM_malloc( data_size, COMM_rank(), MEM_TAG, IS_PRE_MSG ), - data, data_size ); - { TOPC_BUF tmp; - tmp.data = data; tmp.data_size = data_size; - return tmp; - } - } -} - -/*********************************************************************** - * Creates a TOPC_BUF with pointer to buffer in user space. - * TOPC_MSG() is safer; Use this only for optimizations. - */ -TOPC_BUF TOPC_MSG_PTR(void *data, size_t data_size) { - if (TOPC_OPT_safety >= SAFETY_NO_MSG_PTR - || ( TOPC_OPT_aggregated_tasks > 1 - && ! COMM_is_on_stack(data, data_size) ) ) - return TOPC_MSG(data, data_size); - if (data == NULL && data_size > 0) - ERROR("TOPC_MSG_PTR() called with null pointer and positive size"); - /* size 0, malloc a header only */ - MEM_malloc_ptr( data, data_size, COMM_rank(), MEM_TAG, IS_PRE_MSG_PTR ); - if (COMM_is_on_stack(data, data_size)) - WARNING("TOPC_MSG_PTR() was passed a pointer into stack on %s.\n%s", - ( COMM_rank() == 0 ? "master" : "slave" ), - " Data buffer should be either static or global."); - { TOPC_BUF tmp; - tmp.data = data; tmp.data_size = data_size; - return tmp; - } -} diff --git a/topc-2.5.2/src/memory_new.c b/topc-2.5.2/src/memory_new.c deleted file mode 100644 index 070e5b31..00000000 --- a/topc-2.5.2/src/memory_new.c +++ /dev/null @@ -1,410 +0,0 @@ - /********************************************************************** - * TOP-C (Task Oriented Parallel C) * - * Copyright (c) 2000-2001 Gene Cooperman * - * * - * This library is free software; you can redistribute it and/or * - * modify it under the terms of the GNU Lesser General Public * - * License as published by the Free Software Foundation; either * - * version 2.1 of the License, or (at your option) any later version. * - * * - * This library is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * - * Lesser General Public License for more details. * - * * - * You should have received a copy of the GNU Lesser General Public * - * License along with this library (see file COPYING); if not, write * - * to the Free Software Foundation, Inc., 59 Temple Place, Suite * - * 330, Boston, MA 02111-1307 USA, or contact Gene Cooperman * - * . * - **********************************************************************/ - -/* EXPORTED FUNCTIONS: TOPC_MSG, TOPC_MSG_PTR, MEM_malloc, MEM_register_buf, - * MEM_free - * This code is intended to manage memory better than malloc for - * the specific TOP-C data structures. It's not worthwhile now, - * and so is not used, but maybe as the CPU-memory gap continues to grow .... - * This code does malloc/free while recording special header info. - * After GenerateTaskInput/DoTask is called, MEM_register_buf() - * verifies that TOPC_MSG()/TOPC_MSG_PTR() was called at least once. - * If called more than once, extra buffers are silently freed. - * MEM_free - * The code must deal with two kinds of buffers: - * (1) buffers dynamically allocated by MEM_malloc() via a call to malloc() - * (2) buffers located in application space (including NULL pointers) - * for which TOP-C creates a header. - * Buffers of type (2) are created by the application and arise either through - * calls to TOPC_MSG_PTR() or in cases where TOP-C can prove it doesn't - * need to copy the messages into TOP-C space. - * - * Typical sequence: TOPC_MSG/MEM_malloc, MEM_register_buf, MEM_free - * - * A buffer of type (1) or (2) has an associated struct mem_hdr, whose - * type field indicated its current state. - * State transitions: IS_MALLOC->IS_PRE_MSG->IS_MSG->UNUSED_HDR - * or: IS_PRE_MSG_PTR->IS_MSG_PTR->UNUSED_HDR - * Function called resulting in new state: - * MEM_malloc()->IS_MALLOC->TOPC_MSG()->IS_PRE_MSG - * ->MEM_register_buf()->IS_MSG - * ->MEM_free()->UNUSED_HDR (and frees it) - */ - -#include -#include -#include -#include - -#include "comm.h" // comm.h also defines HAVE_PTHREAD, etc., by default -#ifdef HAVE_PTHREAD -# include -# ifdef HAVE_SEMAPHORE -# include // Solaris: needs -lposix4 -# else -# include "sem-pthread.h" -# endif -#endif - -/*********************************************************************** - * Define reentrant version of mutex_lock/mutex_unlock - * In distributed memory, could remove mutexes (and for master in - * shared memory), but these are cheap. - */ -#ifdef HAVE_PTHREAD -static pthread_mutex_t mem_mgr = PTHREAD_MUTEX_INITIALIZER; -# ifdef DEBUG -# define DEBUG_CHECK debug_check(); -# else -# define DEBUG_CHECK -# endif -/* MUTEX_LOCK/MUTEX_UNLOCK let thread recursively call lock w/o blocking */ - static volatile int recurse_init = 0; - static pthread_key_t recurse_key; -# define MUTEX_LOCK(addr_mutex) \ -{ int *recurse = NULL; \ - if (recurse_init && (recurse = pthread_getspecific(recurse_key)) != NULL \ - && *recurse > 0) \ - *recurse++; \ - else { \ - pthread_mutex_lock(addr_mutex); \ - if ( recurse == NULL ) { \ - if (! recurse_init) { \ - recurse_init = 1; \ - pthread_key_create( &recurse_key, NULL ); \ - } \ - pthread_setspecific(recurse_key, recurse = malloc(sizeof(int))); \ - if ( ! recurse ) PERROR("malloc"); \ - else *recurse = 0; \ - } \ - (*recurse)++; \ - DEBUG_CHECK; \ - } \ -} -# define MUTEX_UNLOCK(addr_mutex) \ - if ( --(*(int *)pthread_getspecific(recurse_key)) <= 0 ) \ - { \ - DEBUG_CHECK; \ - pthread_mutex_unlock(addr_mutex); \ - } -#else -# define MUTEX_LOCK(addr_mutex) -# define MUTEX_UNLOCK(addr_mutex) -# undef volatile -# define volatile -#endif - -/*********************************************************************** - * Access functions for a message - */ - -/* msg = (hdr, buf); Want buf correctly aligned after - * msg=malloc(sizeof_msg(size)); buf=((struct mem_hdr *)msg)+1; - */ -#define ROUNDUP(x) ( (((x)+sizeof(void*)-1) / sizeof(void*)) * sizeof(void*) ) -#define sizeof_msg_header ( ROUNDUP(sizeof(struct mem_hdr)) ) -#define sizeof_msg(size) ( sizeof_msg_header + ROUNDUP(size) ) - -/* (actual declaration in comm.h) */ -// enum hdr_type { -// UNUSED_HDR, IS_MALLOC, IS_PRE_MSG, IS_PRE_MSG_PTR, -// IS_MSG, IS_MSG_PTR }; - -/* mem_hdr is not in use if buf == NULL */ -static struct mem_hdr { - struct mem_hdr *next; - struct mem_hdr *prev; - void *buf; - enum hdr_type type; - enum TAG tag; - int source; -#ifdef HAVE_PTHREAD - pthread_t owner; -#endif - int size; - int id; -} mem_hdr_start = {NULL, NULL, NULL}; - -/* mem_hdr_head always points to empty mem_hdr_start; acts only as marker */ -/* mem_hdr_register points to last hdr that has been checked */ -static volatile struct mem_hdr *mem_hdr_head = &mem_hdr_start, - *mem_hdr_tail = &mem_hdr_start, - *mem_hdr_register = &mem_hdr_start; -static struct mem_hdr * MEM_buf_hdr(void *buf) /* used for debugging */ - { return (((struct mem_hdr *)(buf)) - 1); } -#define MEM_buf_hdr(buf) (((struct mem_hdr *)(buf)) - 1) -#define buf_of_hdr(hdr) ((void *)(((struct mem_hdr *)(hdr)) + 1)) -#define MEM_buf_type(buf) (MEM_buf_hdr(buf)->type) -#define MEM_buf_tag(buf) (MEM_buf_hdr(buf)->tag) -#define MEM_buf_source(buf) (MEM_buf_hdr(buf)->source) -/* Note this is size of buffer, not including header. - * For including pointer to header in size, use sizeof_msg(MEM_buf_size(buf)). - */ -#define MEM_buf_size(buf) (MEM_buf_hdr(buf)->size) - -static void debug_check() { - struct mem_hdr *hdr; - for (hdr = (struct mem_hdr *)mem_hdr_register; hdr != NULL ; hdr = hdr->prev) - if (hdr->type == IS_PRE_MSG_PTR || hdr->type == IS_PRE_MSG) - ERROR("debug_check: mem_hdr_register overrun"); -} - -/*********************************************************************** - * malloc a buffer + header - */ -void *MEM_malloc(size_t size, int source, enum TAG tag, enum hdr_type type) { - static int id = 0; - struct mem_hdr *hdr; - if (TOPC_OPT_safety >= SAFETY_NO_MEM_MGR) { - void *ptr; - if (size == 0) - return NULL; - if ((ptr = malloc(size)) == NULL && size > 0) - PERROR("malloc"); - else - return ptr; - } - assert(tag != NO_TAG); - MUTEX_LOCK(&mem_mgr); - - /* enqueues(malloc((sizeof_msg(size)); */ - assert(mem_hdr_tail->next == NULL); - mem_hdr_tail->next = malloc(sizeof_msg(size)); - if (mem_hdr_tail->next == NULL) - ERROR("No memory to malloc a new buffer.\n"); - /* cast to discard volatile */ - mem_hdr_tail->next->prev = (struct mem_hdr *)mem_hdr_tail; - mem_hdr_tail = mem_hdr_tail->next; - mem_hdr_tail->next = NULL; - hdr = (struct mem_hdr *)mem_hdr_tail; /* cast to discard volatile */ - hdr->id = id; /* used for debugging */ - if (id++ >= 1000000000) id = 0; - assert(hdr->prev->next == hdr); - assert(hdr->next == NULL); - - hdr->tag = tag; - hdr->source = source; - hdr->size = size; - hdr->type = type; -#ifdef HAVE_PTHREAD - hdr->owner = pthread_self(); -#endif - hdr->buf = buf_of_hdr(hdr); - MUTEX_UNLOCK(&mem_mgr); /* MEM_register_buf needs above fields stable */ - assert(MEM_buf_hdr(hdr->buf) == hdr); -# ifdef DEBUG -printf("rank: %d, mem_hdr_head: %x, mem_hdr_head->next: %x, mem_hdr_tail: %x\n", -COMM_rank(), mem_hdr_head, mem_hdr_head->next, mem_hdr_tail); - printf("rank: %d; buf_of_hdr(hdr): %x, size: %d, source: %d, tag: %d," - " type: %d, id: %d\n", - COMM_rank(), buf_of_hdr(hdr), size, source, tag, type, hdr->id); -# endif - return hdr->buf; -} -void *MEM_malloc_ptr(void *buf, size_t size, int source, enum TAG tag, - enum hdr_type type) { - struct mem_hdr *hdr; - if (TOPC_OPT_safety >= SAFETY_NO_MEM_MGR) - return buf; - hdr = MEM_buf_hdr(MEM_malloc(0, source, tag, type)); - hdr->buf = buf; - hdr->size = size; - return buf; -} - -/*********************************************************************** - * Free any buffer created by MEM_malloc - * (only routine to change type to UNUSED_HDR) - */ -void MEM_free(void *buf) { - struct mem_hdr *hdr = MEM_buf_hdr(buf); - if (TOPC_OPT_safety >= SAFETY_NO_MEM_MGR) { - if (buf != NULL) - free(buf); - return; - } - MUTEX_LOCK(&mem_mgr); -# ifdef DEBUG -printf("rank: %d, mem_hdr_head: %x, mem_hdr_head->next: %x, mem_hdr_tail: %x\n", -COMM_rank(), mem_hdr_head, mem_hdr_head->next, mem_hdr_tail); - printf("rank: %d; owner: %d, free msg: %x, size: %d, source: %d, tag: %d" - ", id: %d\n", - COMM_rank(), MEM_buf_hdr(buf)->owner, buf, MEM_buf_size(buf), - MEM_buf_source(buf), MEM_buf_tag(buf), MEM_buf_hdr(buf)->id); -# endif - if (hdr != mem_hdr_tail || hdr->buf != buf) { - /* This logic for IS_MSG_PTR; Probably efficient enough */ - hdr = (struct mem_hdr *)mem_hdr_tail; /* cast to discard volatile */ - while (hdr->buf != buf && hdr != mem_hdr_head) - hdr = hdr->prev; - assert(hdr != mem_hdr_head); - } - assert(hdr->buf == buf); - - /* dequeue(hdr) */ - assert(hdr != mem_hdr_head); /* mem_hdr_head only marker for head of queue */ - assert(hdr->type != UNUSED_HDR); - assert(hdr->prev->next == hdr); - assert(hdr->next == NULL || hdr->next->prev == hdr); - hdr->type = UNUSED_HDR; - hdr->prev->next = hdr->next; - if (mem_hdr_register == hdr) - mem_hdr_register = hdr->prev; - if (hdr->next == NULL) { - assert(hdr == mem_hdr_tail); - mem_hdr_tail = hdr->prev; - mem_hdr_tail->next = NULL; - } - else - hdr->next->prev = hdr->prev; - free(hdr); - assert(mem_hdr_register == mem_hdr_tail || mem_hdr_register->next != NULL); - MUTEX_UNLOCK(&mem_mgr); -} - -/*********************************************************************** - * Called after TOPC_MSG/TOPC_MSG_PTR - * Since TOPC_MSG() can MEM_malloc a new buffer that TOP-C frees, - * it's important that application not trick us by returning - * an old buffer. So, after callback function calls TOPC_MSG() - * TOP-C always calls MEM_register_buf(). - * (MEM_register_buf and MEM_free only routines to modify mem_hdr_register) - * (MEM_register_buf calls MEM_free, only routines - * to change type to UNUSED_HDR) - */ -static void msg_not_found() { - ERROR("MEM_register_buf: Return value of %s at rank %d does\n" - " not appear to be a new invocation of TOPC_MSG/TOPC_MSG_PTR.\n" - " Must return new invocation or NOTASK\n", - (COMM_rank() == 0 ? "GenerateTaskInput()" : "DoTask()"), COMM_rank() ); -} -void MEM_register_buf(void *buf) { - int found = 0; -#ifdef HAVE_PTHREAD - pthread_t tid = pthread_self(); -#endif - struct mem_hdr *hdr_register, *next_hdr_register; - extern TOPC_BUF NOTASK; - - if (TOPC_OPT_safety >= SAFETY_NO_MEM_MGR) { - return; - } - MUTEX_LOCK(&mem_mgr); - next_hdr_register = NULL; - for (hdr_register = (struct mem_hdr *)mem_hdr_register->next; - hdr_register != NULL; - hdr_register = (struct mem_hdr *)hdr_register->next) { /*cast, disc. vol*/ -#ifdef HAVE_PTHREAD - if ( pthread_equal(hdr_register->owner, tid) ) { -#else - if (1) { -#endif - switch (hdr_register->type) { - case IS_PRE_MSG: - case IS_PRE_MSG_PTR: - if (hdr_register->buf == buf) { /* if it's this buf */ - hdr_register->type = - (hdr_register->type==IS_PRE_MSG ? IS_MSG : IS_MSG_PTR); - found = 1; - } else { - assert(hdr_register->prev->next == hdr_register); - hdr_register = (struct mem_hdr *)hdr_register->prev; /*cast, disc. vol*/ - MEM_free(hdr_register->next->buf); /* applic. created extra one */ - } - break; - case IS_MSG_PTR: /* MEM_register_buf seeing these a second time */ - case IS_MSG: - assert(hdr_register->type == IS_MSG_PTR || hdr_register->buf != buf); - break; - default: - assert(hdr_register == mem_hdr_head); - } - } else if (next_hdr_register == NULL - && hdr_register->type != IS_MSG - && hdr_register->type != IS_MSG_PTR) { - /* else somebody else's header, mem_hdr_register will stop here */ - assert(hdr_register->type == IS_PRE_MSG - || hdr_register->type == IS_PRE_MSG_PTR); - assert(hdr_register->buf != buf); /* If we don't own it, not our buf */ -# ifdef DEBUG - printf("thread id %d: hdr_register found IS_MSG_PTR or IS_MSG" - " from owner %d\n", tid, hdr_register->owner); -# endif - next_hdr_register = hdr_register->prev; - } - } - mem_hdr_register = (next_hdr_register==NULL ? mem_hdr_tail : next_hdr_register); - assert(hdr_register == NULL); - assert(mem_hdr_register == mem_hdr_tail || mem_hdr_register->next != NULL); - MUTEX_UNLOCK(&mem_mgr); - - if (! found && buf != NOTASK.data) - msg_not_found(); - return; -} - -/*********************************************************************** - * Creates a TOPC_BUF; copies data from user space to TOP-C space. - */ -TOPC_BUF TOPC_MSG(void *data, size_t data_size) { - if (data == NULL && data_size > 0) - ERROR("TOPC_MSG() called with null pointer and positive size"); - // Always copy to TOP-C space on master; It's called by GenerateTask() - // for input task buffer, and saved for reuse by CheckTaskResult() - if ( TOPC_OPT_safety < SAFETY_NO_MSG_PTR && COMM_rank() != 0 - && ! COMM_is_shared_memory() && ! COMM_is_on_stack(data, data_size) ) { - /* for size 0, malloc a header only; equiv of TOPC_MSG_PTR() */ - MEM_malloc_ptr( data, data_size, COMM_rank(), MEM_TAG, IS_PRE_MSG_PTR ); - { TOPC_BUF tmp; - tmp.data = data; tmp.data_size = data_size; - return tmp; - } - } else { - data = memcpy( MEM_malloc( data_size, COMM_rank(), MEM_TAG, IS_PRE_MSG ), - data, data_size ); - { TOPC_BUF tmp; - tmp.data = data; tmp.data_size = data_size; - return tmp; - } - } -} - -/*********************************************************************** - * Creates a TOPC_BUF with pointer to buffer in user space. - * TOPC_MSG() is safer; Use this only for optimizations. - */ -TOPC_BUF TOPC_MSG_PTR(void *data, size_t data_size) { - if (TOPC_OPT_safety >= SAFETY_NO_MSG_PTR - || TOPC_OPT_aggregated_tasks > 1) - return TOPC_MSG(data, data_size); - if (data == NULL && data_size > 0) - ERROR("TOPC_MSG_PTR() called with null pointer and positive size"); - /* size 0, malloc a header only */ - MEM_malloc_ptr( data, data_size, COMM_rank(), MEM_TAG, IS_PRE_MSG_PTR ); - if (COMM_is_on_stack(data, data_size)) - WARNING("TOPC_MSG_PTR() was passed a pointer into stack on %s.\n%s", - ( COMM_rank() == 0 ? "master" : "slave" ), - " Data buffer should be either static or global."); - { TOPC_BUF tmp; - tmp.data = data; tmp.data_size = data_size; - return tmp; - } -} diff --git a/topc-2.5.2/src/mpinu/INTERNALS b/topc-2.5.2/src/mpinu/INTERNALS deleted file mode 100644 index 4f19a091..00000000 --- a/topc-2.5.2/src/mpinu/INTERNALS +++ /dev/null @@ -1,118 +0,0 @@ -Messages are sent with a fixed length message header, that specifices -message tag, source, count, etc. A separate socket is used for -each of the possible n^2 communication patterns among n MPI processes. -Initially, only sockets between master and each slave are set up -(see below for more details). -Messages are buffered in the socket buffer as much as possible. -The primary current exception is when two messages with the same source -and destination, but different tags, are sent. If the receiver specifies -a tag to read the second message first, then the receiver must extract -all messages from the buffer, and internally buffer them, until it finds -the desired one. - -CALL_CHK is a macro defined to automatically check for success of -system calls, instead of having to hand-write the logic everywhere. -(It checks for -1, which is assumed to be failure.) It also checks if -the cause of failure was EINTR (a signal), and if so, it re-starts the -system call. - -SETSOCKOPT(sd) is another macro. Currently, it sets the sockets -to SO_KEEPALIVE. Sockets are NOT set to non-blocking. Instead, select() -is used to avoid blocking on a recv() for which there is nothing ready. -This call to SETSOCKOPT() is currently done only after socket() calls, -but not after accept(). This works, since each connection is created -by a socket() call at one end, and an accept() call at the other end, -and it suffices for one end to keep the connection alive. (Doing select() -on exceptional events would be an alternative to SO_KEEPALIVE, that would -not trigger SIGPIPE events for broken sockets. This would be more robust.) -The sockets are blocking (default) and so send will either succeed (locally) -or return an error. One must test the number of characters seen by recv(), -to verify that it received the entire message expected. -Some implementations, such as MPICH, set TCP_NODELAY so that small messages -are not delayed in being sent out. In keeping with a minimalist -implementation, usually across Ethernet, the possible performance improvements -were not considered attractive enough. - -Although there are no architecture conditionalizatins, things like - "#if 0 ... #else .. . #endif" are used. In these cases, one version of -the code is preferable, but there are potential incompatibilities with some of -the UNIX dialects. - -Global variables are allocated near the beginning of mpi.c . -The main communication table is pg_array. The index into the array of structs -is the rank of the process. Most fields should be obvious. For example, -the sd field is the socket descriptor for communication with the process -of that rank. Initially, sockets are set up only between the original -process (rank 0) and each slave process. In addition, each process -sets up a listener port. The AF_INET address of that port is stored -in the listener_addr field of each pg_array entry. - -At startup (MPI_Init), the socket connection between the original -process and slave is set up along with a listener port for the slave. -The slave then informs the master of the address of its listener port -in its first message (using send/recv). The master then replies by -telling the slave his rank and the total number of slaves, in a message -in the format (struct init_msg). The master then sends to each slave -the addresses of all slave listener ports. Thus, the first time that -a slave wishes to communicate with another slave, the first slave -connects with the listener port of the second, in order to create -a new socket between the two slaves. - -In this implementation, sockets are not set to SO_KEEPALIVE. -So, connected sockets can time out. Any write to a connected socket -is tested with select before the write of the message header. If a socket -is no longer alive, the old one is closed (at each end), and a new one -is connected. Note that this implies that one must also test -a socket with select() before recv(), which would block. Further -the call to select must include the listener port (MPINU_my_list_sd) -in case the original socket is dead and the sender needs to connect -a new socket through the listener port. - -The other major data structure is (struct msg_hdr). Before any message is -sent, this header is sent advertising the rank of the source, the tag of the -message, and the size of the data (and eventually the communicator when -communicators other than MPI_COMM_WORLD are implementated). - -Note that there is a COLL_COMM_TAG which is not valid for ordinary users. -Collective communications can be emulated by ordinary point-to-point -communications, in which case the COLL_COMM_TAG is used to distinguish -such messages. (In fact, there should be several COLL_COMM_TAG's, -one for each type of collective communication operation.) - -======================= - -It would be possible to have second process for communication that would -buffer all incoming processes, and thus also allow greater overlap of -communication and computation. This is not currently done. - -Another concern for future work is that when socket buffers fill up, a sending -process will block. So, send will block on large messages, creating -the possibility of deadlock if two processes send each other large -messages before calling recv(). This is not currently addressed. - -The plan to fix deadlock is to check if there are pending messages from -any process of lower rank before doing a send. Any such pending messages -are received and stored in a buffer. Similarly, if the send is -to the same process, then the message can be directly transferred -to the internal buffer without using any socket. This avoids deadlock, -and it does not require the use of the buffers in the common case -in which all communication uses blocking and is between the master (original -process) and slaves. - -A moderate size internal buffer for messages is allocated in advance, -so that malloc() will be -needed only to store large messages. In order to easily optimize -buffer manageent for a FIFO message queue, the internal buffer can have -its memory compressed whenever a message other than the first or -last one is read. Further, when the last message threatens to overflow -the buffer, all of memory can be moved forward. - -Addressing this issue of blocking could be handled by doing the following -before doing a new MPI_Send. One can check the size field of incoming message -headers. Any small messages can be read into a pre-allocated buffer, and one -can then test that there are no outstanding large messages capable of causing -deadlock. If there are outstanding large messages, those would have to be -read into a large buffer, using malloc(). Thus, currently, malloc() need only -be used if messages are read out of order (for example by matching the tag of -a later message). In this modification, any code requiring an MPI_Send while -a large incoming message is pending would also require malloc(). diff --git a/topc-2.5.2/src/mpinu/Makefile b/topc-2.5.2/src/mpinu/Makefile deleted file mode 100644 index 8900f101..00000000 --- a/topc-2.5.2/src/mpinu/Makefile +++ /dev/null @@ -1,48 +0,0 @@ -# src/mpinu/Makefile. Generated from Makefile.in by configure. - -CC=gcc -# CFLAGS=-g -# CFLAGS=-DDEBUG -O0 -g -CFLAGS=-g -O2 -# LIBS= -lsocket -lnsl needed for Solaris -LIBS= - -RANLIB=ranlib - -LIBOBJS=mpi.o master.o parse.o cmd.o slave.o utils.o sendrecv.o spawn2.o -LIBOBJS=mpi.o master.o parse.o cmd.o slave.o utils.o sendrecv.o - -execute: hello_mpi - ./hello_mpi - -# Under solaris, end-user application will need: libmpi.a -lsocket -lnsl -libmpi.a: ${LIBOBJS} - rm -f libmpi.a - ar qc libmpi.a ${LIBOBJS} ${ARLIBS} - - ${RANLIB} libmpi.a - -hello_mpi: hello_mpi.o libmpi.a - if ( uname -sr | grep "SunOS 5" > /dev/null ) && \ - [ "x${LIBS}" = "x" ] ; then \ - make LIBS="-lsocket -lnsl" hello_mpi; \ - else \ - ${CC} -o hello_mpi -g hello_mpi.o libmpi.a ${LIBS}; \ - fi - -dist: - dir=./`basename $$PWD`; cd ..; \ - tar cvf $$dir/mpinu.tar \ - $$dir/*.[ch] \ - $$dir/procgroup \ - $$dir/README \ - $$dir/INTERNALS \ - $$dir/Makefile -dist-all: - dir=./`basename $$PWD`; cd .. ; \ - echo ${PWD} $$PWD $$dir ; \ - rm -f $$dir/mpinu.tar* $$dir/mpinu-all.tar* ; \ - tar cvf $$dir/mpinu-all.tar $$dir/* ; \ - gzip $$dir/mpinu-all.tar - -clean: - rm -f *.o libmpi.a core hello_mpi checkpoint diff --git a/topc-2.5.2/src/mpinu/Makefile.in b/topc-2.5.2/src/mpinu/Makefile.in deleted file mode 100644 index c7467aee..00000000 --- a/topc-2.5.2/src/mpinu/Makefile.in +++ /dev/null @@ -1,48 +0,0 @@ -# @configure_input@ - -CC=@CC@ -# CFLAGS=-g -# CFLAGS=-DDEBUG -O0 -g -CFLAGS=@CFLAGS@ -# LIBS= -lsocket -lnsl needed for Solaris -LIBS= @LIBSFORSOCKETS@ @LIBSFORSLEEP@ - -RANLIB=@RANLIB@ - -LIBOBJS=mpi.o master.o parse.o cmd.o slave.o utils.o sendrecv.o spawn2.o -LIBOBJS=mpi.o master.o parse.o cmd.o slave.o utils.o sendrecv.o - -execute: hello_mpi - ./hello_mpi - -# Under solaris, end-user application will need: libmpi.a -lsocket -lnsl -libmpi.a: ${LIBOBJS} - rm -f libmpi.a - ar qc libmpi.a ${LIBOBJS} ${ARLIBS} - - ${RANLIB} libmpi.a - -hello_mpi: hello_mpi.o libmpi.a - if ( uname -sr | grep "SunOS 5" > /dev/null ) && \ - [ "x${LIBS}" = "x" ] ; then \ - make LIBS="-lsocket -lnsl" hello_mpi; \ - else \ - ${CC} -o hello_mpi -g hello_mpi.o libmpi.a ${LIBS}; \ - fi - -dist: - dir=./`basename $$PWD`; cd ..; \ - tar cvf $$dir/mpinu.tar \ - $$dir/*.[ch] \ - $$dir/procgroup \ - $$dir/README \ - $$dir/INTERNALS \ - $$dir/Makefile -dist-all: - dir=./`basename $$PWD`; cd .. ; \ - echo ${PWD} $$PWD $$dir ; \ - rm -f $$dir/mpinu.tar* $$dir/mpinu-all.tar* ; \ - tar cvf $$dir/mpinu-all.tar $$dir/* ; \ - gzip $$dir/mpinu-all.tar - -clean: - rm -f *.o libmpi.a core hello_mpi checkpoint diff --git a/topc-2.5.2/src/mpinu/README b/topc-2.5.2/src/mpinu/README deleted file mode 100644 index 25899f45..00000000 --- a/topc-2.5.2/src/mpinu/README +++ /dev/null @@ -1,93 +0,0 @@ - MPINU (MPI from Northeastern University) - Gene Cooperman (gene@ccs.neu.edu) - Markos Kyzas (markos@ccs.neu.edu) - -This is intended to be a minimalist subset of MPI. The goal is to allow -people to run simple MPI subset programs on a network of workstations using a -small MPI library. Most point-to-point (standard mode, only) and -environmental functions are included. MPI_Barrier and MPI_Bcast (which are -collective communications) are also implemented. Buffered, synchronous and -ready mode are not handled, nor are asynchronous messages using requests. -Most functions from the remaining MPI layers (collective communication, -derived datatypes, groups, multiple communicators) are also not supported. -Finally, secure sockets are NOT used, and so this software is subject -to malicious attack or in unusual cases to random events connecting to -the ports used by this implementation. For additional restrictions on the -functionality, see below. - -To use it, call: -make libmpi.a -Then link libmpi.a and include mpi.h in any user files. -Be sure to modify the procgroup file according to the instructions inside. -If you wish, your application can add a flag "-p4pg" followed by -a procgroup name of your choice. - -Although this is a minimalist implementation, attention has been paid -to portability across several UNIX dialects using sockets over TCP/IP. -No architecture-specific conditionalizations are used. Process startup -is handled through the procgroup file as done in MPICH/p4. The example -procgroup file includes a description of the format. The application -can use the -p4pg flag to specify a procgroup file other than the -default one, "./procgroup". Hence, the "mpirun" utility from MPICH -should work here, too. (Don't forget to modify the procgroup file for -your site when you use it. You may also have to change localhost to a -specific hostname if localhost is not hosts.equiv at your site.) This -code is placed in the public domain, with with hopes that others will -extend it along the same philosophical lines. The authors would -appreciate receiving any extensions to this code, so as to possibly -integrate them into future versions. - -The benefits of this distribution include easy customization, and -instructional use for socket programming and internal considerations of -an MPI implementation. An INTERNALS file is provided with this -in mind. The current version is about 1,200 lines of C code. Most -functions are reasonably compact, and the call tree is for the most part -no more than three deep, making the code particularly easy to -follow. We have also tried not to invoke malloc(), brk(), or error -handlers, so as to avoid possible conflicts with user programs. -However, the system is forced to use malloc() for receiving -out-of-order messages, such as when a receiver requests a message with -a specific tag and source and there is a pending message from that -source with a different tag. This is the only time malloc() is used, -currently. (See INTERNALS for the issue of deadlock and malloc().) - -This work was motivated in part by our need to integrate MPI with -interpreted languages, such as LISP and GAP. Since such languages may choose -to use malloc() (or even sbrk()), and to install their own error -handlers, it was important to affect those mechanisms as little as -possible. Attention was also paid to properly handling very large -messages, which often occur in our applications. Finally, a minimalist -MPI greatly aids in debugging, where it is often difficult to assign -responsibility for a phenomenon between MPI and the interpreted -language. In a full MPI implementation, the MPI code can be as large -as some of the interpreted languages. - -The subset implemented lies entirely within the point-to-point and -environment layer of MPI. Not all of even those routines have been -updated to date. - -This is still a work in progress. - -0. In particular, this preliminary version does not work for messages sent -from a process to itself. This will soon be remedied. - -1. While the code always works with MPI_ANY_TAG, if one specifies -a specific tag to receive, then that tag must match the tag of the next -incoming message. (i.e.: It cannot currently take messages from the same -sender out of order.) - -2. The socket buffers are used to limit the use of malloc(). So, MPI_Send() -can block on large messages, creating the possibility of deadlock if several -processes send before doing a receive. See INTERNALS for a description -of these issues. - -3. In particular, it's possible that a large message sent by a process to -itself may block. - -4. In heterogeneous networks, the user is responsible for converting the user -data into new byte orderings. XDR or other mechanisms are not invoked. - -5. The software uses public ports, which are inherently insecure. -Very little checking is done that the remote process is a correct one. -This software is subject to malicious attack, and so should not be -used where security (e.g. secure sockets) is a requirement. diff --git a/topc-2.5.2/src/mpinu/TAGS b/topc-2.5.2/src/mpinu/TAGS deleted file mode 100644 index aa5a49b7..00000000 --- a/topc-2.5.2/src/mpinu/TAGS +++ /dev/null @@ -1,120 +0,0 @@ - -cmd.c,58 -int set_and_exec_cmds(4,39 -#define STDIN_FILENO 42,1377 - -coll_comm.c,42 -int MPI_Bcast 10,345 -MPI_Barrier 29,924 - -hello_mpi.c,100 -#define WORKTAG 4,39 -#define DIETAG 5,58 -int main(9,102 -void master(29,545 -void slave(108,2463 - -master.c,22 -void mpi_master(4,39 - -mpi.c,104 -int MPI_Init(18,496 -int MPI_Initialized(97,2734 -int MPI_Finalize(103,2829 -int new_listener(118,3214 - -parse.c,39 -#define BUF_LEN 4,39 -int parse(9,178 - -sendrecv.c,769 -static void list_accept_new_socket(19,635 -static int list_connect_new_socket(49,1520 -typedef void (*sighandler_t)sighandler_t109,3917 -static void null_handler(111,3973 -void *curr_signal(116,4061 -int select_block_sigs(125,4301 -int MPI_Send(187,6315 - if ( ! IS_SOCKET_CONNECTED(225,7634 -#define EAT_HDR 238,8179 -#define DONT_EAT_HDR 239,8197 -#define BLOCKING 240,8220 -#define NOT_BLOCKING 241,8239 -#define MSG_WAITING 242,8262 -#define NO_MSG_WAITING 243,8284 -static int read_msg_hdr 245,8377 - if 327,11426 - if 335,11732 - if 353,12266 - if 372,12840 -if 395,13636 - if 404,13984 - if 409,14210 - if 436,15458 - if 437,15514 - if 443,15745 -int MPI_Recv(470,16761 -int MPI_Probe(517,18244 -int MPI_Iprobe(531,18586 -int MPI_Get_count(546,19029 - -slave.c,21 -void mpi_slave(4,39 - -spawn2.c,21 -int MPI_Spawn2(4,39 - -utils.c,162 -int MPI_Comm_rank(4,39 -int MPI_Comm_size(11,145 -int MPI_Get_processor_name(18,253 -int MPI_Abort(27,491 -int MPI_Attr_get 38,800 -int MPI_Error_string(58,1294 - -mpi.h,785 -typedef int MPI_Comm;MPI_Comm8,132 - } MPI_Status;MPI_Status12,220 -#define MPI_SUCCESS 14,243 -#define MPI_FAIL 15,265 -#define MPI_COMM_WORLD 17,285 -#define MPI_ANY_TAG 18,310 -#define MPI_ANY_SOURCE 19,333 -#define MPI_HOST 21,360 -#define MPI_TAG_UB 22,379 -#define MPI_IO 23,400 -#define MPI_WTIME_IS_GLOBAL 24,417 -#define MPI_PROC_NULL 25,447 -typedef int MPI_Datatype;MPI_Datatype28,490 -#define MPI_CHAR 30,517 -#define MPI_UNSIGNED_CHAR 31,562 -#define MPI_BYTE 32,607 -#define MPI_SHORT 33,652 -#define MPI_UNSIGNED_SHORT 34,697 -#define MPI_INT 35,742 -#define MPI_UNSIGNED 36,787 -#define MPI_LONG 37,832 -#define MPI_UNSIGNED_LONG 38,877 -#define MPI_FLOAT 39,922 -#define MPI_DOUBLE 40,968 -#define MPI_LONG_DOUBLE 43,1087 -#define MPI_LONG_LONG_INT 44,1133 - -mpiimpl.h,574 -#define ANSIC 26,626 -#define PERROR(PERROR27,667 - #define CALL_CHK(CALL_CHK40,1025 -#define CALL_CHK(CALL_CHK47,1259 -#define MPI_COLL_COMM_TAG 74,2172 -#define MPI_MAX_PROCESSOR_NAME 76,2202 -#define PG_ARRAY_SIZE 77,2237 -#define PROCGROUP_LEN 78,2265 -#define PG_NOSOCKET 79,2293 -struct pg_struct pg_struct81,2368 -#define INT 95,2828 -#define INT 97,2851 -struct init_msg init_msg100,2875 -struct msg_hdr msg_hdr106,3046 -#define SETSOCKOPT(SETSOCKOPT113,3108 -#define SETSOCKOPT(SETSOCKOPT124,3482 -#define IS_SOCKET_CONNECTED(IS_SOCKET_CONNECTED135,3852 diff --git a/topc-2.5.2/src/mpinu/TODO b/topc-2.5.2/src/mpinu/TODO deleted file mode 100644 index 3cddadea..00000000 --- a/topc-2.5.2/src/mpinu/TODO +++ /dev/null @@ -1,111 +0,0 @@ -What if connecting to self for first time? Deadlock? - send -> receive - -0. Implement rest of point-to-point layer -1. Implement all environment inquiries -2. Worry about making MPI internal routines static or otherwise - invisible to end-user. -3. Allow communication between two slaves. -4. MPI_Comm_dup, But have to take messages out of order for that -5. Use execlp instead of system: rsh host -n exec process .. -p4amslave -6. Right now, can't select MPI_Recv according to specific tag, and - take messages out of order. -7. When close(socket), get msg: non-socket operation on socket, - connection reset by peer -8. Collective communication: Is MPI_Send/MPI_Receive blocking? - Also, do we broadcast to ourselves? (Probably not) -9. /* Add long double and long long for ANSI C version ( #+ansi ) */ -10. Should examine addresses to check if other process is part of club, - or have a special int to send in header. (What does MPICH do?) -11. Make sure to wait on defunct processes. -12. Replace int by size_t where appropriate. -13. Test socket (select) before writing to see if it's alive. - If not, re-create. -14. Send rank highpoint port -p4amslave, so that slave doesn't have - to ask rank. Then can reuse list_connect/accept_new_socket() - in master.c and slave.c. -15. Change _mpi_my_list_sd to _mpi_mylist_sd (and in INTERNALS) -16. Allow redirection to be specified on command line of procgroup file -17. MPI_Send() should return failure if socket died and can't - set up new socket. -18. In mipiimpl.h, it allocates static ... MPI_TMP_BUF1, .._BUF2; - Do it better. Use EXTERN trick? -19. If can't exec program, error statement should say something like: - procgroup: stat: command not found: command -20. Catch EPIPE signals, so process can live on after attempting to - write to broken pipe, or else do select first?. (maybe not - necessary if getsockopt() doesn't allow SO_KEEPALIVE - (Can the socket die if not used for a while under these circumstances? - Yes.) -21. Clean up mpinu library; Maybe experiment with variants of - setsockopt(SO_KEEPALIVE) (and catching the SIGPIPE in case of temporary - socket failure). Also, setsockopt(SO_REUSEPORT), could allow use - of a single well-known port instead of having to tell client at what - port to find the master. -ENOTTY: ioctl -tcgetpgrp.3v:.SM ENOTTY -termios.3v:.SM ENOTTY -EPIPE: write (send) -speculation: ENOTTY (Not a typewriter) associated with select() before recv(), - EPIPE with master (broken pipe) -apparently, a SIGPIPE is sent by kernel during select() -Could use signal() to catch it, and then restore signal() -What does MPICH do? -send()/recv(): - EWOULDBLOCK The socket is marked non-blocking and - the requested operation would block. - A process attempting to write - to the socket receives a SIGPIPE signal and the write opera- - tion returns an error. By default, a process exits when it - receives SIGPIPE. A read operation on the socket returns an - error but does not generate SIGPIPE. If the process is - waiting in select(2) when the connection is broken, select() - returns true for any read or write events selected for the - socket. -So, should we try select() once more? - man getsockname says: - SO_KEEPALIVE - Reports whether connections are kept active with - periodic transmission of messages. If the connected - socket fails to respond to these messages, the connec- - tion is broken and processes using that socket are - notified with a SIGPIPE signal. This option returns an - int value. -ioctl(FIONBIO) or fcntl(FNDELAY) (read/write non-blocking possible) => EWOULDBLICK -fcntl(O_NONBLOCK) => EAGAIN - Note that Digital allows: getsockname(SO_SNDTIMED | SO_RCVTIMED, ...) -for timeout info. - same file pointer. It is also associated - with a FD_CLOEXEC (close-on-exec) flag set to - remain open across execve(2V) system calls. - F_GETFD Get the FD_CLOEXEC (close-on-exec) flag asso- - ciated with fd. If the low-order bit is 0, - the file remains open after executing - execve(), otherwise it is closed. - F_SETFD Set the FD_CLOEXEC (close-on-exec) flag asso- - ciated with fd to the low order bit of arg (0 - or 1 as above). - Note: this is a per-process and per- - descriptor flag. Setting or clearing it for - a particular descriptor does not affect the - flag on descriptors copied from it by dup(2V) - or F_DUPFD, nor does it affect the flag on - other processes of that descriptor. - - #include - int getsockopt ( - int socket, - int level, ( SOL_SOCKET ) - int option_nam, (SO_SNDTIMED) - void *option_value, (struct timeval *) - size_t *option_len ); sizeof(struct timeval) - - #include - int setsockopt ( - int socket, - int level, - int option_name, - const void *option_value, - size_t option_len ); - - diff --git a/topc-2.5.2/src/mpinu/cmd.c b/topc-2.5.2/src/mpinu/cmd.c deleted file mode 100644 index 77444bf6..00000000 --- a/topc-2.5.2/src/mpinu/cmd.c +++ /dev/null @@ -1,102 +0,0 @@ -#include "mpi.h" -#include "mpiimpl.h" - -#define NUM_SLAVES_TO_CREATE_AT_ONCE 5 - -static char *global_ssh_cmd, *global_hostname; - -static void alarm_handler(int sig) { - fprintf(stderr, "*** MPINU: Slave %s didn't reply to `%s'.\n", - global_hostname, global_ssh_cmd); - fflush(stderr); - exit(1); -} - -static void exec_system_with_interrupt( char *command ) { - char *argv[4], probe_string[MPI_MAX_PROCESSOR_NAME+100]; - - if ( 0 != strcmp("localhost", global_hostname) ) { - signal( SIGALRM, alarm_handler ); - alarm(15); - sprintf( probe_string, "exec %s %s pwd \">\" /dev/null", - global_ssh_cmd, global_hostname ); - system( probe_string ); - alarm(0); - } - - argv[0] = "sh"; - argv[1] = "-c"; - argv[2] = command; - argv[3] = NULL; - /* It works to call alarm() here, if desired. */ - execv("/bin/sh", argv); - exit(127); -} - -int MPINU_set_and_exec_cmds(hostname, port, argc, argv, outfile) -int argc; -char *hostname, *port, *argv[], *outfile; -{ - char cmd[256], args[256]; - char *ssh_cmd; - int i, fd; - pid_t pid; - FILE *ssh_script; - - ssh_script = fopen(outfile, "w"); - fprintf(ssh_script, "#!/bin/sh\n"); - if ( (ssh_cmd = getenv("SSH")) == NULL ) ssh_cmd = "ssh"; - if ( getenv("CALLBACK_HOST") != NULL ) hostname = getenv("CALLBACK_HOST"); - - args[0] = '\0'; - for (i=1; i < argc; i++) sprintf(args+strlen(args), "%s ", argv[i]); - for(i=1; i < PG_ARRAY_SIZE && MPINU_pg_array[i].processor != NULL; i++) - { - /* If localhost, avoid overhead and portability issues of local loop */ - /* Strictly speaking, should be sprintf(cmd, "cd; exec ..."); - but then: localhost 1 - >slave.out creates slave.out in home dir. */ - if ( 0 == strcmp("localhost", MPINU_pg_array[i].processor) ) - sprintf(cmd, "exec %s %s %s %s -p4amslave", - MPINU_pg_array[i].process, args, hostname, port); - /* Assumes user shell on remote processor accepts "exec" */ - else sprintf(cmd, "exec %s %s exec %s %s %s %s -p4amslave", ssh_cmd, - MPINU_pg_array[i].processor, MPINU_pg_array[i].process, - args, hostname, port); - fprintf(ssh_script, "%s &\n", cmd); - if ( i % NUM_SLAVES_TO_CREATE_AT_ONCE == 0 ) - fprintf(ssh_script, "sleep(1)\n"); - fflush(ssh_script); -#ifdef DEBUG - printf("cmd: %s\n",cmd); -#endif - CALL_CHK( pid = fork, () ); - if (pid == (pid_t)0) { /* if child process */ - - fclose(ssh_script); - /* Could have used "ssh -n" to redirect stdin, but position of "-n" - in "ssh" varies according to different dialects. */ -#ifndef STDIN_FILENO -#define STDIN_FILENO 0 /* Should be standard in most dialects -- just in case */ -#endif - close(STDIN_FILENO); - CALL_CHK( fd = open, ("/dev/null", O_RDONLY) ); - if ( fd != STDIN_FILENO ) { /* fd should be stdin, but check to be safe */ - CALL_CHK( dup2, (fd, STDIN_FILENO) ); - close( fd ); - } - - global_ssh_cmd = ssh_cmd; /* used by exec_system_with_interrupt() */ - global_hostname = MPINU_pg_array[i].processor; - exec_system_with_interrupt(cmd); - exit(127); /* child shouldn't reach here */ - } - if ( i % NUM_SLAVES_TO_CREATE_AT_ONCE == 0 ) - sleep(1); - cmd[0] = '\0'; - } - fclose(ssh_script); - if ( i >= PG_ARRAY_SIZE ) - printf("MPINU: WARNING: more slaves than PG_ARRAY_SIZE(%d); not using all\n", - PG_ARRAY_SIZE); - return i - 1; /* return number of slaves */ -} diff --git a/topc-2.5.2/src/mpinu/coll_comm.c b/topc-2.5.2/src/mpinu/coll_comm.c deleted file mode 100644 index 37873fcf..00000000 --- a/topc-2.5.2/src/mpinu/coll_comm.c +++ /dev/null @@ -1,32 +0,0 @@ -/* Collective communication implemented by blocking send and receive - for point-to-point communication. For an Ethernet-style LAN, it - would be difficult to do better without significant extra complication. - These routines use MPI_COLL_COMM_TAG, which is not available to end-user - programs. */ - -#include "mpi.h" -#include "mpiimpl.h" - -int MPI_Bcast ( buffer, count, datatype, root, comm ) - void *buffer; - int count; - MPI_Datatype datatype; - int root; - MPI_Comm comm; -{ int dest_rank; - MPI_Status status; - - MPINU_coll_comm_flag = 1; - if (MPINU_myrank == root) - for ( dest_rank = 0; dest_rank <= MPINU_num_slaves; dest_rank++ ) - if ( dest_rank != root ) - MPI_Send(buffer, count, datatype, dest_rank, MPI_COLL_COMM_TAG, comm); - else - MPI_Recv(buffer, count, datatype, root, MPI_COLL_COMM_TAG, comm, &status); - MPINU_coll_comm_flag = 0; -} - -MPI_Barrier ( comm ) - MPI_Comm comm; -{ MPI_Bcast("a", 0, MPI_CHAR, 0, comm); /* count == 0, so buf can be const */ -} diff --git a/topc-2.5.2/src/mpinu/hello_mpi.c b/topc-2.5.2/src/mpinu/hello_mpi.c deleted file mode 100644 index b62c7e8c..00000000 --- a/topc-2.5.2/src/mpinu/hello_mpi.c +++ /dev/null @@ -1,168 +0,0 @@ -#include "mpi.h" -#include "mpiimpl.h" - -#define WORKTAG 1 -#define DIETAG 2 - -void master(), slave(); - -int main(argc, argv) - -int argc; -char *argv[]; - -{ int myrank; /* SunOS has problems with this local decl. */ - - MPI_Init(&argc, &argv); /* initialize MPI */ - MPI_Comm_rank(MPI_COMM_WORLD, /* always use this */ - &myrank); /* process rank, 0 thru N-1 */ -printf("MPI_Init done on %d; %d cmd line args\n", myrank, argc);fflush(stdout); - if (myrank == 0) { - master(); - } else { - slave(); - } - MPI_Finalize(); /* cleanup MPI */ - exit(0); -} - -void master() - -{ - int ntasks, rank, work, iter=1; - double result; - MPI_Status status; - - MPI_Comm_size(MPI_COMM_WORLD, /* always use this */ - &ntasks); /* #processes in application */ - -#if 0 - for (rank = 1; rank < ntasks; ++rank) { - MPI_Recv(&result, 1, MPI_DOUBLE, MPI_ANY_SOURCE, - MPI_ANY_TAG, MPI_COMM_WORLD, &status); - } -#endif -/* - * Seed the slaves. - */ - for (rank = 1; rank < ntasks; ++rank) { - - work = 17 /* get_next_work_request */; - - MPI_Send(&work, /* message buffer */ - 1, /* one data item */ - MPI_INT, /* data item is an integer */ - rank, /* destination process rank */ - WORKTAG, /* user chosen message tag */ - MPI_COMM_WORLD);/* always use this */ - } -/* - * Receive a result from any slave and dispatch a new work request - * work requests have been exhausted. - */ - work = 17 /* get_next_work_request */; - - while ( iter-- /* valid new work request */) { - - MPI_Recv(&result, /* message buffer */ - 1, /* one data item */ - MPI_DOUBLE, /* data item is a double real */ - MPI_ANY_SOURCE, /* receive from any sender */ - MPI_ANY_TAG, /* receive any type of message */ - MPI_COMM_WORLD, /* always use this */ - &status); /* info about received message */ - - MPI_Send(&work, 1, MPI_INT, status.MPI_SOURCE, - WORKTAG, MPI_COMM_WORLD); - - work = 17 /* get_next_work_request */; - } -/* - * Receive results for outstanding work requests. - */ - for (rank = 1; rank < ntasks; ++rank) { - MPI_Recv(&result, 1, MPI_DOUBLE, MPI_ANY_SOURCE, - MPI_ANY_TAG, MPI_COMM_WORLD, &status); -#ifdef DEBUG -printf("hello_mpi: master: received result for rank %d.\n", rank); fflush(stdout); -#endif - } - -#if 0 - { int i; - for (i = 0; i < 120; ++i) { - if (poll_new_slaves()) - MPI_Spawn2(); - sleep(1); - } - } -#endif -/* - * Tell all the slaves to exit. - */ - for (rank = 1; rank < ntasks; ++rank) { - MPI_Send(0, 0, MPI_INT, rank, DIETAG, MPI_COMM_WORLD); - } -} - -void slave() - -{ - double result; - int work; - MPI_Status status; - - {int any = 45; - if ( (MPINU_myrank == 1) && (MPINU_num_slaves >= 2) ) - MPI_Send(&any, 1, MPI_INT, 2, WORKTAG, MPI_COMM_WORLD); } - {int any = 0; - MPI_Status status; - if (MPINU_myrank == 2) { - fd_set MPINU_fdset5; - - printf("SLAVE 2 starting\n");fflush(stdout); - printf("MPINU_my_list_sd: %d, MPINU_max_sd: %d\n", - MPINU_my_list_sd, MPINU_max_sd); - FD_ZERO(&MPINU_fdset5); - FD_SET(MPINU_my_list_sd, &MPINU_fdset5); - CALL_CHK( select, (MPINU_max_sd+1, &MPINU_fdset5,NULL,NULL,NULL) ); - printf("accept would have succeeded\n");fflush(stdout); - MPI_Recv(&any, 1, MPI_INT, 1, WORKTAG, MPI_COMM_WORLD, &status); - printf("SLAVE 2 received %d (45 is right)\n", any);fflush(stdout); - } - } - -#if 0 - for (rank = 1; rank < ntasks; ++rank) { - result = 23 /* do the work */; - MPI_Send(&result, 1, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD); - } -#endif - MPI_Probe( 0, MPI_ANY_TAG, MPI_COMM_WORLD, &status); - {int i; MPI_Get_count(&status, 1, &i); printf("hello: count: %d\n", i);} - {int i, flag; MPI_Attr_get( MPI_COMM_WORLD, MPI_TAG_UB, &i, &flag ); - printf("MPI_TAG_UB: %d; flag: %d\n", i, flag); } - MPI_Probe( 0, MPI_ANY_TAG, MPI_COMM_WORLD, &status); - for (;;) { - MPI_Recv(&work, 1, MPI_INT, 0, MPI_ANY_TAG, - MPI_COMM_WORLD, &status); -/* - * Check the tag of the received message. - */ -#ifdef DEBUG -printf("hello_mpi: slave: work: %d; status.MPI_TAG: %d\n", work, status.MPI_TAG);fflush(stdout); -#endif - if (status.MPI_TAG == DIETAG) { - return; - } -#ifdef DEBUG -printf("hello_mpi: slave: work continuing\n");fflush(stdout); -#endif - - result = 23 /* do the work */; - MPI_Send(&result, 1, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD); -#ifdef DEBUG -printf("hello_mpi: slave: message sent\n");fflush(stdout); -#endif - } -} diff --git a/topc-2.5.2/src/mpinu/libmpi.a b/topc-2.5.2/src/mpinu/libmpi.a deleted file mode 100644 index a7ea9f9b..00000000 Binary files a/topc-2.5.2/src/mpinu/libmpi.a and /dev/null differ diff --git a/topc-2.5.2/src/mpinu/master.c b/topc-2.5.2/src/mpinu/master.c deleted file mode 100644 index 4dd9f541..00000000 --- a/topc-2.5.2/src/mpinu/master.c +++ /dev/null @@ -1,138 +0,0 @@ -#include "mpi.h" -#include "mpiimpl.h" - -#define SLAVE_INIT_TIMEOUT 15 - -void MPINU_mpi_master(p4pg_file, argc, argv) -int argc; -char *p4pg_file, *argv[]; -{ - int new_slaves;/* Used for MPINU_set_and_exec_cmds */ - int sd, ns; /* socket descriptors */ - struct init_msg msg1; - char new_port[8]; /* port on which master listens, ASCII number */ - socklen_t fromlen; - int rank, port; - char host[256]; /* hostname */ - char outfile[256]; /* outfile */ - struct hostent *hp; /* ptr to host info structure */ - struct sockaddr_in sin; /* inet info structure */ - struct sockaddr_in new_sin; /* used for each new connection */ - - FD_ZERO(&MPINU_fdset); /* initialize, MPINU_new_listener() will modify */ - MPINU_new_listener(&sd, &sin, &port); - MPINU_my_list_sd = sd; - memcpy( (char *)&(MPINU_pg_array[0].listener_addr), - (char *)&sin, sizeof(sin) ); - - CALL_CHK(gethostname, (host, 256)); - hp = gethostbyname(host); - port = ntohs(sin.sin_port); - sprintf(new_port, "%d", port); -#ifdef DEBUG - printf("master now listening.\n"); - printf("master port: %d\n", port); -#endif - - sprintf( outfile, "/tmp/mpinu-ssh.%d", (int)getpid() ); - MPINU_parse( p4pg_file ); /* read the procgroup file */ - /* create ssh commands and execute them, - cmd.c:NUM_SLAVES_TO_CREATE_AT_ONCE at a time */ - MPINU_num_slaves = MPINU_set_and_exec_cmds(hp->h_name, new_port, - argc, argv, outfile); - - if (MPINU_num_slaves > SOMAXCONN) { - printf("WARNING: This architecture allows only SOMAXCONN=%d connections" - " before\n", - SOMAXCONN); - printf(" connections are dropped from the queue. There are %d slaves.\n", - MPINU_num_slaves); - printf(" Some connections may be lost.\n"); - printf(" (SOMAXCONN is an operating system parameter.)\n"); - } - - for(rank = 1; rank <= MPINU_num_slaves; rank++) - { fd_set zerofds, readfds; - struct timeval timeout; - int is_pending_connection = 0; - - FD_ZERO(&zerofds); - FD_ZERO(&readfds); - FD_SET(sd, &readfds); - timeout.tv_sec = ( rank == 1 ? 120 : SLAVE_INIT_TIMEOUT ); - timeout.tv_usec = 0; - CALL_CHK(is_pending_connection = select, - (sd+1, &readfds, &zerofds, &zerofds, &timeout)); - if ( ! is_pending_connection ) { - MPINU_num_slaves = rank - 1; /* Only rank-1 slaves replied */ - if (MPINU_num_slaves == 0) { - fprintf( stderr, "*** MPINU: No slaves replied after 2 minutes.\n" ); - exit(1); - } else { - fprintf( stderr, "\n*** MPINU: Only %d slaves replied after %d sec.\n" - "*** (master.c:SLAVE_INIT_TIMEOUT = %d s)\n" - "*** Will execute with only %d slaves.\n\n", - MPINU_num_slaves, SLAVE_INIT_TIMEOUT, SLAVE_INIT_TIMEOUT, - MPINU_num_slaves ); - break; - } - } - - fromlen = sizeof(new_sin); - CALL_CHK( ns = accept, (sd, (struct sockaddr *)&new_sin, &fromlen) ); - MPINU_pg_array[rank].sd = ns; - FD_SET(ns, &MPINU_fdset); - if ( ns > MPINU_max_sd ) - MPINU_max_sd = ns; -#ifdef DEBUG - printf("master: accepted a connection\n"); - printf("master: slave %d: new ns: %d, current MPINU_max_sd: %d\n", - rank, ns, MPINU_max_sd); - strcpy( (char *)&msg1, "MSG #1"); - printf("master msg1: %s\n", (char *)&msg1); - send(ns, (char *)&msg1, 7, 0); - printf("rank: %d, htonl(rank): %d\n", rank, htonl(rank)); -#endif - - /* Recv slave's listener_addr and store in field of MPINU_pg_array[rank] */ - CALL_CHK( recv, (ns, (char *)&(MPINU_pg_array[rank].listener_addr), - sizeof(struct sockaddr_in), 0) ); - } - - /* Leave outfile for debugging until all slaves reported back. */ - unlink( outfile ); - - /* Send all listener_addr fields, other info, to slave */ - { struct sockaddr_in buf[PG_ARRAY_SIZE]; - int rank, i; - INT nl_buf; /* INT is nl: network long int */ - - for ( i=0; i <= MPINU_num_slaves; i++ ) - memcpy( &(buf[i]), (char *)&(MPINU_pg_array[i].listener_addr), - sizeof(*buf) ); - for ( rank=1; rank <= MPINU_num_slaves; rank++ ) { - int tmp; - msg1.len = htonl(sizeof(msg1)); - msg1.rank = htonl(rank); - msg1.num_slaves = htonl(MPINU_num_slaves); - /* Pause between sends or some O/S (Linux kernel 2.4.20 ??) can - * disconnect socket if many slaves */ - { struct timespec req; - req.tv_sec = 0; - req.tv_nsec = 100000000; /* 100 million ns = 0.1 s */ - nanosleep( &req, NULL ); - } - send(MPINU_pg_array[rank].sd, (char *)&msg1, sizeof(msg1), 0); - tmp = send( MPINU_pg_array[rank].sd, (char *)buf, - (1+MPINU_num_slaves)*sizeof(*buf), 0 ); - if ( tmp != (1+MPINU_num_slaves)*sizeof(*buf) ) { - printf("MPINU_mpi_master: bad send\n"); fflush(stdout); exit(1); - } - } - - /* Acknowledge that master and slave are synchronized */ - nl_buf = htonl( sizeof(struct sockaddr_in) ); - for ( i=1; i <= MPINU_num_slaves; i++ ) - send( MPINU_pg_array[i].sd, (void *)&nl_buf, sizeof(nl_buf), 0); - } -} diff --git a/topc-2.5.2/src/mpinu/mpi.c b/topc-2.5.2/src/mpinu/mpi.c deleted file mode 100644 index 914376fc..00000000 --- a/topc-2.5.2/src/mpinu/mpi.c +++ /dev/null @@ -1,189 +0,0 @@ -#include "mpi.h" -#include "mpiimpl.h" - -/* index into MPINU_pg_array is same as process rank in MPI_Comm_world */ -struct pg_struct MPINU_pg_array[PG_ARRAY_SIZE]; - -int MPINU_myrank = 0; -int MPINU_num_slaves; -static int ssh_slaves; /* num orig slaves, not counting MPI_Spawn2() */ -int MPINU_coll_comm_flag = 0; -int MPINU_my_list_sd; -fd_set MPINU_fdset; -int MPINU_max_sd; -int MPINU_is_spawn2 = 0; /* Set inside mpi_spawn2 before unexec, then reset */ - /* Used by slave.c to determine if slave from mpi_spawn2 */ -int MPINU_is_initialized = 0; -static void sigpipe_handler(int dummy){ } - -int MPI_Init(argc_ptr, argv_ptr) -int *argc_ptr; -char ***argv_ptr; -{ char *p4pg_file = "procgroup"; - int i, p4pg_flag = 0; - -#ifdef DEBUG - system("hostname"); - printf("entering MPI_Init\n"); - printf(" argc: %d\n", *argc_ptr); - printf("last argv: %s\n", (*argv_ptr)[*argc_ptr - 1]); - fflush(stdout); -#endif - - /* eliminate broken socket exits */ - signal(SIGPIPE, sigpipe_handler); - - if ( sizeof(INT) != 4 ) { - printf("sizeof(INT) != 4: re-define INT in mpiimpl.h\n"); - exit(1); - } - - if (MPINU_is_initialized) { - printf("MPI_Init: can't call MPI_Init after it's already started.\n"); - exit(1); - } - for( i = 0; i < PG_ARRAY_SIZE; i++ ) { - MPINU_pg_array[i].processor = NULL; /* initialize all entries */ - MPINU_pg_array[i].sd = PG_NOSOCKET; - } - - if ( 0 != strcmp( (*argv_ptr)[*argc_ptr - 1], "-p4amslave" ) - && ! MPINU_is_spawn2 ) { - for( i = 0; i < *argc_ptr; i++ ) { - if ( p4pg_flag ) - (*argv_ptr)[i] = (*argv_ptr)[i+2]; - else if ( ! strcmp( (*argv_ptr)[i], "-p4pg" ) ) { - p4pg_file = (*argv_ptr)[i+1]; - i--; - *argc_ptr -= 2; - p4pg_flag = 1; - } - } - if ( p4pg_flag ) (*argv_ptr)[*argc_ptr] = NULL; -#ifdef DEBUG -printf("p4pg_file: %s\n", p4pg_file);fflush(stdout); -#endif - { struct stat buf; - if ( 0 != stat( p4pg_file, &buf ) || ! buf.st_mode & S_IFREG - || ! buf.st_mode & S_IRUSR ) { - fprintf( stderr, "*** MPINU: can't read procgroup file: %s\n", - p4pg_file ); - if ( 0 != strcmp( p4pg_file, "procgroup" ) ) { - fprintf( stderr, - " Either create \"progroup\" in current directory:\n" - " %s/procgroup\n", - getcwd( NULL, 256 ) ); - fprintf( stderr, - " or else add a command line arg:" - " -p4pg ABSOLUTE_PATH_OF_PROCGROUP_FILE\n"); - } - return MPI_FAIL; - } - } - MPINU_mpi_master(p4pg_file, *argc_ptr, *argv_ptr); - ssh_slaves = MPINU_num_slaves; - } - else { /* else slave */ -#ifdef DEBUG - printf("calling MPINU_mpi_slave(%s, %s): %d\n", - (*argv_ptr)[*argc_ptr - 3], (*argv_ptr)[*argc_ptr - 2] ); - fflush(stdout); -#endif - if ( MPINU_is_spawn2 ) MPINU_mpi_slave( NULL, NULL ); - else { - MPINU_mpi_slave( (*argv_ptr)[*argc_ptr - 3], (*argv_ptr)[*argc_ptr - 2] ); - (*argv_ptr)[*argc_ptr - 3] = NULL; - *argc_ptr -= 3; - } - } - MPINU_is_initialized = 1; - return MPI_SUCCESS; -} - -int MPI_Initialized( flag ) - int *flag; -{ *flag = MPINU_is_initialized; - return MPI_SUCCESS; -} - -int MPI_Finalize() -{ int i, statusp; - - MPINU_is_initialized = 0; - for (i = 0; i<= MPINU_num_slaves; i++) - if ( MPINU_pg_array[i].sd != PG_NOSOCKET ) - close(MPINU_pg_array[i].sd); - close(MPINU_my_list_sd); - if (MPINU_myrank == 0) /* master waits for slaves to finish */ - for (i = 1; i<= ssh_slaves; i++) - CALL_CHK( wait, (&statusp) ); - return MPI_SUCCESS; -} - -/* Fill in all three on exit */ -int MPINU_new_listener(sd, sin, port) -int *sd, *port; -struct sockaddr_in *sin; /* inet info structure */ -{ char host[256]; /* hostname for this process */ - struct hostent *hp; /* ptr to host info structure */ - socklen_t socklen; - int i; - - /* use the default protocol 6 = IPPROTO_TCP */ - *sd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); - SETSOCKOPT(*sd); - FD_SET( *sd, &MPINU_fdset ); - if ( *sd > MPINU_max_sd ) - MPINU_max_sd = *sd; -#ifdef DEBUG - printf("MPINU_new_listener: socket: %d\n", *sd);fflush(stdout); -#endif - - CALL_CHK(gethostname, (host, 256)); - hp = gethostbyname(host); - -#if 0 - memset( (char *)sin, (char)0, sizeof(*sin) ); -#else - for ( i = 0; i < (signed)sizeof(*sin); i++ ) - ((char *)sin)[i] = 0; -#endif - - /* Is this next line (h_addr) needed? */ - memcpy( (char *)&(sin->sin_addr), hp->h_addr, hp->h_length); - sin->sin_port = htons(0); - sin->sin_family = hp->h_addrtype; - /* Since INADDR_ANY is 0, zeroing out sin accomplished this, anyway. */ - sin->sin_addr.s_addr = INADDR_ANY; - -#if 0 - printf("sin_family (%d) and AF_INET (%d) should compare.\n", sin->sin_family, AF_INET); - printf("master: hp->h_name: %s\n", hp->h_name); -#endif - - do { - sin->sin_addr.s_addr = INADDR_ANY; - CALL_CHK( bind, (*sd, (struct sockaddr *)sin, sizeof(*sin)) ); - /* CALL_CHK sets errno = 0; O/S sometimes assigns a stale address */ - } while(errno == EADDRINUSE); - - /* i acts as dummy for sin_len below */ - socklen = sizeof(struct sockaddr_in); - CALL_CHK( getsockname, (*sd, (struct sockaddr *)sin, &socklen) ); - *port = ntohs(sin->sin_port); -#ifdef DEBUG - printf("MPINU_new_listener: port: %d == %d; sin_len: %d\n", - ntohs(sin->sin_port), *port, i); fflush(stdout); -#endif - if ( sin->sin_port == 0 ) { - printf("LISTENER FAILED TO GET NEW PORT!!\n"); - exit(1); - } - - /* Under SunOS 4.1, SOMAXCONN = 5; Could have slaves re-try after timeout */ - CALL_CHK( listen, (*sd, SOMAXCONN) ); - /* On Solaris 2.6, getsockname (and maybe bind?) zero out sin->sin_addr - (converting it to localhost for efficiency?); So copy it back in */ - memcpy( (char *)&(sin->sin_addr), hp->h_addr, hp->h_length); - return 0; -} diff --git a/topc-2.5.2/src/mpinu/mpi.h b/topc-2.5.2/src/mpinu/mpi.h deleted file mode 100644 index 431ca007..00000000 --- a/topc-2.5.2/src/mpinu/mpi.h +++ /dev/null @@ -1,66 +0,0 @@ -/* This is public portion of mpi.h */ - -/* Keep C++ compilers from getting confused */ -#if defined(__cplusplus) -extern "C" { -#endif - -typedef int MPI_Comm; -typedef struct { int MPI_SOURCE; - int MPI_TAG; - int mpi_size; - } MPI_Status; - -#define MPI_SUCCESS 0 -#define MPI_FAIL 1 - -#define MPI_COMM_WORLD 0 -#define MPI_ANY_TAG -1 -#define MPI_ANY_SOURCE -1 - -#define MPI_HOST 1 -#define MPI_TAG_UB 2 -#define MPI_IO 3 -#define MPI_WTIME_IS_GLOBAL 4 -#define MPI_PROC_NULL 0 - -/* Datatypes: */ -typedef int MPI_Datatype; - -#define MPI_CHAR ((MPI_Datatype)1) -#define MPI_UNSIGNED_CHAR ((MPI_Datatype)2) -#define MPI_BYTE ((MPI_Datatype)3) -#define MPI_SHORT ((MPI_Datatype)4) -#define MPI_UNSIGNED_SHORT ((MPI_Datatype)5) -#define MPI_INT ((MPI_Datatype)6) -#define MPI_UNSIGNED ((MPI_Datatype)7) -#define MPI_LONG ((MPI_Datatype)8) -#define MPI_UNSIGNED_LONG ((MPI_Datatype)9) -#define MPI_FLOAT ((MPI_Datatype)10) -#define MPI_DOUBLE ((MPI_Datatype)11) -/* These are only in GNU ANSI, not K & R. So, skip it for now. */ -#if 0 -#define MPI_LONG_DOUBLE ((MPI_Datatype)12) -#define MPI_LONG_LONG_INT ((MPI_Datatype)13) -#endif - -int MPI_Abort(MPI_Comm comm, int errorcode); -int MPI_Attr_get(MPI_Comm comm, int keyval, void *attribute_val, int *flag); -int MPI_Comm_rank(MPI_Comm comm, int *rank); -int MPI_Comm_size(MPI_Comm comm, int *size); -#define MPI_MAX_ERROR_STRING 20; -int MPI_Error_string(int errorcode, char *string, int *resultlen); -int MPI_Finalize(void); -int MPI_Get_count(MPI_Status *status, MPI_Datatype datatype, int *count); -int MPI_Get_processor_name(char *name, int *resultlen); -int MPI_Init(int *argc_ptr, char ***argv_ptr); -int MPI_Initialized(int *flag); -int MPI_Iprobe(int source, int tag, MPI_Comm comm, int *flag, MPI_Status *status -); -int MPI_Probe(int source, int tag, MPI_Comm comm, MPI_Status *status); -int MPI_Recv(void *buf, int count, MPI_Datatype datatype, int source, int tag, MPI_Comm comm, MPI_Status *status); -int MPI_Send(void *buf, int count, MPI_Datatype datatype, int dest, int tag, MPI_Comm comm); - -#if defined(__cplusplus) -} -#endif diff --git a/topc-2.5.2/src/mpinu/mpiimpl.h b/topc-2.5.2/src/mpinu/mpiimpl.h deleted file mode 100644 index 9aa13f85..00000000 --- a/topc-2.5.2/src/mpinu/mpiimpl.h +++ /dev/null @@ -1,138 +0,0 @@ -/* This is the private portion of the MPI include file */ - -#include -#include -#include -#include -#include -#include /* Needed for struct timeval for select */ -#include /* Needed for struct timespec for nanosleep */ -#include -#include -#include -#include -#include /* Needed with fcntl.h for Sys V */ -#include -#include -#include -#include -#include - -/* Want to disguise `"' because ANSI C won't do substitution inside quotes. - * #ifdef __STDC__ - * #define quote(arg) #arg - * #else - * #define quote(arg) "arg" - * #endif - * THEN USE: perror(quote(function)) */ -#define ANSIC ( -1 < (unsigned char) 1 ) -#define PERROR(function) if (ANSIC) \ - {fprintf(stderr,__FILE__ "(line %d): ", __LINE__); perror(#function);} \ - else perror("function") -/* -#if ANSIC -#define PERROR(function) fprintf(stderr,__FILE__ "(line %d): ", __LINE__); perror(#function) -#else -#define PERROR(function) perror("function") -#endif -*/ - -/* Re-write this based on select_block_sigs() in sendrecv.c */ -#define CALL_CHK(function,args) \ - while (1) { \ - /* On EINTR (interrupted by signal), just try again */ \ - /* On ECHILD (error no child in wait), ignore error */ \ - /* On EADDRINUSE (bind <= stale address), caller fixes and tries again */ \ - /* On ECONNRESET || EPIPE (broken connection), caller can return MPI_FAIL */ \ - errno = 0; \ - if ( (function args) == -1 ) { \ - /* Remove first if, and fall through, when have confidence it works */ \ - /* printf("errno: %d; ",errno); */ \ - if ( (errno == EADDRINUSE) ) { \ - PERROR(function); errno = EADDRINUSE; break; } \ - if ( (errno == ECHILD) || (errno == EADDRINUSE) ) break; \ - if ((errno == ECONNRESET) || (errno == EPIPE)) break; \ - if ( errno == EINTR ) continue; \ - PERROR(function); exit(1); \ - } \ - else break; /* successful system call */ \ - } - -extern int MPINU_num_slaves; -extern int MPINU_myrank; -extern int MPINU_coll_comm_flag; -extern int MPINU_my_list_sd; -extern fd_set MPINU_fdset; -extern int MPINU_max_sd; -extern int MPINU_is_spawn2; -extern int MPINU_is_initialized; - -#define MPI_COLL_COMM_TAG -2 - -#define MPI_MAX_PROCESSOR_NAME 256 -#define PG_ARRAY_SIZE 1000 -#define PROCGROUP_LEN 10000 -#define PG_NOSOCKET -1 /* must not coincide with socket descriptor int */ - -struct pg_struct { - char *processor; - char *num_threads; - char *process; - int sd; /* socket descriptor */ - int MPINU_max_sd; /* max value of socket descriptor -- used with select() */ - struct sockaddr_in listener_addr; /* listener port to create new sockets */ -}; - -/* index into MPINU_pg_array is same as process rank in MPI_Comm_world */ -extern struct pg_struct MPINU_pg_array[]; - -/* INT must be 32-bit quantity. Re-define to long if necessary. */ -#if (1 << 31) == 0 -#define INT long -#else -#define INT int -#endif - -struct init_msg { /* Initial message from master to slave */ - INT len; /* For consistency check; This should equal sizeof(init_msg) */ - INT rank; - INT num_slaves; -}; - -struct msg_hdr { - INT tag; - INT size; - INT rank; -}; - -#if 0 -#define SETSOCKOPT(sd) \ - { int i = 1; \ - struct timeval timeout; \ - timeout.tv_sec = 2; \ - timeout.tv_usec = 0; \ - CALL_CHK( setsockopt, (sd, SOL_SOCKET, SO_KEEPALIVE, \ - (void *)&i, sizeof(i)) ); \ - CALL_CHK( setsockopt, (sd, SOL_SOCKET, SO_RCVTIMEO, \ - (void *)&timeout, sizeof(timeout)) ); \ - } -#else -#define SETSOCKOPT(sd) \ - { int i = 1; \ - CALL_CHK( setsockopt, (sd, SOL_SOCKET, SO_KEEPALIVE, \ - (void *)&i, sizeof(i)) ); \ - } -#endif - -/* MPI_TMP_NAMELEN used here, but not in *.c source */ -/* This is ugly. It allocates data in each C file in which it's included. */ -static struct sockaddr MPI_TMP_NAME; -static socklen_t MPI_TMP_NAMELEN = sizeof(MPI_TMP_NAME); -#define IS_SOCKET_CONNECTED(socket) \ - ( 1 + getpeername( socket, &MPI_TMP_NAME, &MPI_TMP_NAMELEN ) ) - -void MPINU_mpi_master(); -void MPINU_mpi_slave(); -int MPINU_parse(); -int MPINU_new_listener(); -int MPINU_set_and_exec_cmds(); diff --git a/topc-2.5.2/src/mpinu/parse.c b/topc-2.5.2/src/mpinu/parse.c deleted file mode 100644 index 8266da1e..00000000 --- a/topc-2.5.2/src/mpinu/parse.c +++ /dev/null @@ -1,83 +0,0 @@ -#include "mpi.h" -#include "mpiimpl.h" - -#define BUF_LEN 256 - -/* parse_buf must be as large as procgroup file length; avoids using malloc */ -static char parse_buf[PROCGROUP_LEN]; - -int MPINU_parse( p4pg_file ) -char *p4pg_file; -{ - FILE *fin; - char *t0; - char *c; - char *buf = parse_buf; - int index = 1; - -#ifdef DEBUG -printf("parsing %s\n", p4pg_file);fflush(stdout); -#endif - MPINU_pg_array[0].processor = "local"; - MPINU_pg_array[0].num_threads = "0"; - MPINU_pg_array[0].process = ""; /* Could use strcat of all argv[i] ?? */ - if ( (fin = fopen(p4pg_file, "r")) ) - { /* CHECK IF: PROCGROUP_LEN > length of "procgroup" file */ - /* # in col 0 is comment*/ - while(fgets(buf, BUF_LEN, fin)) - { if ( buf[0] == '#' ) continue; /* # means comment */ - if ( buf[0] == '\n' ) continue; /* skip null lines */ - - t0 = strtok(buf, " \t"); - if ( !strcmp(t0, "local") ) - continue; - else - { - MPINU_pg_array[index].processor = t0; - if ( (t0 = strtok(NULL, " \t")) == NULL ) { - printf("MPINU_parse: strtok: token not found\n"); - exit(1); - } - MPINU_pg_array[index].num_threads = t0; - if ( (t0 = strtok(NULL, "\n")) == NULL ) { - printf("MPINU_parse: strtok: token not found\n"); - exit(1); - } - for ( c = MPINU_pg_array[index].num_threads; - *c != '\0'; c++ ) - if ( ! isdigit(*c) ) { - printf("MPINU_parse: procgroup: num threads must be integer:"); - printf(" (use 1, if not sure)\n"); - exit(1); - } - MPINU_pg_array[index].process = t0; - buf = strchr(t0, '\0') + 1; -#if 0 - strcpy(MPINU_pg_array[index].processor, t0); - t1 = strtok(NULL, " \t"); - if (t1) strcpy(MPINU_pg_array[index].num_threads, t1); - t2 = strtok(NULL, "\n"); - if (t2) strcpy(MPINU_pg_array[index].process, t2); -#endif -#ifdef DEBUG - printf("MPINU_pg_array[%d].process: %s\n", - index, MPINU_pg_array[index].process); -#endif - } - index++; - } - } -#if 0 -#ifdef __alpha - /* ulimit(4,0) is file descriptors on Sun, DEC requires getrlimit */ -#else - if ( ulimit(4, 0) < index + 3 ) { - CALL_CHK(ulimit, (4,0)); /* see if ulimit(4, 0) == -1 */ - printf("MPINU_parse: Not enough file descriptors (%d) for all processes.\n", - ulimit(4,0) ); - exit(1); - } -#endif -#endif - return 0; -} diff --git a/topc-2.5.2/src/mpinu/procgroup b/topc-2.5.2/src/mpinu/procgroup deleted file mode 100644 index 56b8b9c7..00000000 --- a/topc-2.5.2/src/mpinu/procgroup +++ /dev/null @@ -1,16 +0,0 @@ -# This is a comment. -# src/mpinu/procgroup. Generated from procgroup.in by configure. - -local 0 -localhost 1 /home/kason/school/4zp6/repo/GEANT4-GPU/topc-2.5.2/src/mpinu/hello_mpi -localhost 1 /home/kason/school/4zp6/repo/GEANT4-GPU/topc-2.5.2/src/mpinu/hello_mpi -# localhost 1 pargapmpi - -# The general format is that "local 0" implies creation of a master. -# Otherwise there is one line per slave. The "1" is obligatory. -# The first field is the hostname or localhost (in a form valid for "rsh") -# The second field, 1, is obligatory. -# The format is inherited from MPICH, which grew from P4. - -#Example: -# procyon.ccs.neu.edu 1 ./mygap4beta/bin/pargapmpi.sh diff --git a/topc-2.5.2/src/mpinu/procgroup.in b/topc-2.5.2/src/mpinu/procgroup.in deleted file mode 100644 index d3f7d578..00000000 --- a/topc-2.5.2/src/mpinu/procgroup.in +++ /dev/null @@ -1,16 +0,0 @@ -# This is a comment. -# @configure_input@ - -local 0 -localhost 1 @PWD@/src/mpinu/hello_mpi -localhost 1 @PWD@/src/mpinu/hello_mpi -# localhost 1 pargapmpi - -# The general format is that "local 0" implies creation of a master. -# Otherwise there is one line per slave. The "1" is obligatory. -# The first field is the hostname or localhost (in a form valid for "rsh") -# The second field, 1, is obligatory. -# The format is inherited from MPICH, which grew from P4. - -#Example: -# procyon.ccs.neu.edu 1 ./mygap4beta/bin/pargapmpi.sh diff --git a/topc-2.5.2/src/mpinu/sendrecv.c b/topc-2.5.2/src/mpinu/sendrecv.c deleted file mode 100644 index 79f71bca..00000000 --- a/topc-2.5.2/src/mpinu/sendrecv.c +++ /dev/null @@ -1,590 +0,0 @@ -/* NEEDED CHANGES: MPINU_fdset2 -> fd_readset; clean up read_msg_hdr() - add Part 0 (check types), Part I (do select), Part II (check fds's), - Part III (cleanup on exit) -*/ - -#include "mpi.h" -#include "mpiimpl.h" - -/* These must correspond with MPI_XXX in mpi.h */ -static int datatype_size[] = {-1, sizeof(char), sizeof(unsigned char), - sizeof(char), - sizeof(short), sizeof(unsigned short), sizeof(int), - sizeof(unsigned), sizeof(long), sizeof(unsigned long), - sizeof(float), sizeof(double)}; -/* Add long double and long long for ANSI C version */ - -/* ============================================================ */ -int MPINU_socket_dead(int fd){ - int dest = 0; - while( fd != MPINU_pg_array[dest].sd ) - dest++; - MPINU_pg_array[dest].sd = PG_NOSOCKET; - FD_CLR( fd, &MPINU_fdset); - return 0; -} - - -static void list_accept_new_socket(list_sd) -int list_sd; -{ struct sockaddr_in new_sin; - int ns, source; - socklen_t fromlen = sizeof(new_sin); - char buf[sizeof(INT)]; - -#ifdef DEBUG - printf("Rank(%d): accepting new socket\n", MPINU_myrank);fflush(stdout); -#endif - CALL_CHK( ns = accept, (list_sd, (struct sockaddr *)&new_sin, &fromlen) ); - CALL_CHK( recv, (ns, buf, sizeof(INT), 0) ); - source = ntohl(*((INT *)buf)); - - if ( source < 0 || source > MPINU_num_slaves ) - printf("list_accept_new_socket: Bad sender rank received: %d\n", source); - else { -#ifdef DEBUG - printf("accepted socket (%d) from %d\n", ns, source);fflush(stdout); -#endif - if ( MPINU_pg_array[source].sd != PG_NOSOCKET ) { - FD_CLR( MPINU_pg_array[source].sd, &MPINU_fdset ); - CALL_CHK( close, (MPINU_pg_array[source].sd) ); - } - MPINU_pg_array[source].sd = ns; - FD_SET(ns, &MPINU_fdset); - if ( ns > MPINU_max_sd ) - MPINU_max_sd = ns; - } -} - -static int list_connect_new_socket( myrank, dest_rank ) -int myrank, dest_rank; -{ int sd; - char buf[sizeof(long)]; - -#ifdef DEBUG - printf("connecting new socket from %d to %d\n", myrank, dest_rank);fflush(stdout); -#endif - *((INT *)buf) = htonl(myrank); - CALL_CHK( sd = socket, (AF_INET, SOCK_STREAM, IPPROTO_TCP) ); - SETSOCKOPT(sd); - while(-1 == connect(sd, - (struct sockaddr *)&MPINU_pg_array[dest_rank].listener_addr, - sizeof(struct sockaddr_in) ) ) { - if ( errno == EALREADY || errno == EISCONN ) break; - if ( errno != EINTR ) return( -1 ); /* return failure */ - } - CALL_CHK( send, (sd, buf, sizeof(INT), 0) ); - -#ifdef DEBUG - printf("connected new socket(%d) from %d to %d\n", sd, myrank, dest_rank); - fflush(stdout); -#endif - if ( MPINU_pg_array[dest_rank].sd != PG_NOSOCKET ) { - FD_CLR( MPINU_pg_array[dest_rank].sd, &MPINU_fdset ); - CALL_CHK( close, (MPINU_pg_array[dest_rank].sd) ); - } - MPINU_pg_array[dest_rank].sd = sd; - FD_SET(sd, &MPINU_fdset); - if ( sd > MPINU_max_sd ) - MPINU_max_sd = sd; - return( 0 ); -} - -/* ============================================================ */ -/* This blocks certain signals while inside select() */ -/* Note that a signal in the middle of a system call that is */ -/* caught and returns, may either restart the signal or else */ -/* exit the system call. In particular, SIGINT appears to */ -/* cause select to return with some of readfds being set. */ -/* Note also that recv() is called only after read_msg_hdr() */ -/* guarantees that a message is available, or else after a */ -/* select() inside read_msg_hdr() that guarantees a message */ -/* is available. So, recv() should never block. */ - -/* When this works, eliminate re-start after EINTR in mpiimpl.h */ -/* SIGINT may have user-installed signal handler. Call it after - * catching the signal. If we're still here after that, go - * go back and re-start the system call. This can be done - * generically with a single MPINU signal handler, since it - * can check what signal it caught. But we must first save all - * old signal handlers in an array, to raise them or restore them - * later. - */ -/* When this works, do the same for SIGCONT, SIGSTOP, SIGTSTP (^Z) - * SIGPIPE ("broken pipe" => broken socket), if those have other - * signal handlers that should be called; - * I've been told that SO_KEEPALIVE causes a SIGPIPE if no - * activity within a certain time - */ - -typedef void (*sighandler_t)(int); -static int IsSIGINT; -static void null_handler(int signum) { - IsSIGINT = 1; -} - -/* TEMPORARY FOR DEBUGGING */ -static void *curr_signal() -{ struct sigaction action; - sigaction( SIGINT, NULL, &action ); - return (void *)action.sa_handler; -} - -/* Under POSIX, the system calls used here that are interruptible (EINTR) - are: connect(), recv(), select() - */ -static int select_block_sigs( n, readfds, writefds, exceptfds, timeout ) - int n; - fd_set *readfds; - fd_set *writefds; - fd_set *exceptfds; - struct timeval *timeout; -{ sigset_t sigset, oldsigset; - sighandler_t real_handler; - int answer; - - do { - real_handler = signal( SIGINT, null_handler ); - sigfillset( &sigset ); - sigdelset( &sigset, SIGINT ); - /* SO_KEEPALIVE can generate SIGPIPE. If this fnc is called - through mpiimpl.h:CALL_CHK() let it re-start this automatically. - */ - sigdelset( &sigset, SIGPIPE ); - sigprocmask( SIG_BLOCK, &sigset, &oldsigset ); - - IsSIGINT= 0; - answer = select( n, readfds, writefds, exceptfds, timeout ); - -#ifdef DEBUG - printf("Trying to catch select which had SIGINT; isSIGINT=%d\n", IsSIGINT); - {int i; - if (exceptfds != NULL) - for ( i = 0; i <= MPINU_max_sd; i++ ) - if ( FD_ISSET( i, exceptfds) ) - printf("FD_ISSET( %d, &exceptfds): %d\n", i, FD_ISSET(i, exceptfds) ); - } - {int i; - if (readfds != NULL) - for ( i = 0; i <= MPINU_max_sd; i++ ) - if ( FD_ISSET( i, readfds) ) - printf("FD_ISSET( %d, &readfds): %d\n", i, FD_ISSET(i, readfds) ); - } - { int sig_found = 0; - int i; - sigpending( &sigset ); - for ( i = 1; i <= 31; i++ ) { - if ( sigismember( &sigset, i ) ) { - if ( ! sig_found ) { - sig_found = 1; - printf("sigpending after select: %d\n", sigset); - } - printf(" Signal %d\n", i); - } - } - } -#endif - - sigprocmask( SIG_SETMASK, &oldsigset, NULL ); - signal( SIGINT, real_handler ); -#ifdef DEBUG - if ( IsSIGINT ) printf("Rank(%d): select_block_sigs(): Interrupt caught\n", - MPINU_myrank); - if (IsSIGINT) printf(" real_handler: %x\n", real_handler); - if (IsSIGINT) printf(" curr_handler: %x\n", curr_signal() ); - printf("num sd's: %d; FD_ISSET( MPINU_my_list_sd, &MPINU_fdset2 ): %d\n", - answer, FD_ISSET( MPINU_my_list_sd, readfds ) ); -#endif - if ( IsSIGINT ) kill( getpid(), SIGINT ); /* ANSI C calls it raise() */ - } while ( IsSIGINT == 1 ); /* null_handler could have set IsSIGINT = 1 */ - - return answer; -} - - -/* ============================================================ */ - -int MPI_Send( buf, count, datatype, dest, tag, comm ) - void *buf; - int count, dest, tag; - MPI_Datatype datatype; - MPI_Comm comm; -{ struct msg_hdr buf_hdr; - int num_bytes; - - if ( dest > MPINU_num_slaves || dest < 0 || count < 0 || datatype < 1 - || datatype > MPI_DOUBLE /* change MPI_DOUBLE for above */ - || ( (tag < 0) - && ( ! MPINU_coll_comm_flag || tag == MPI_COLL_COMM_TAG ) ) ) { - printf("MPI_Send( .., %d, %d, %d, %d, ..): invalid argument\n", - count, datatype, dest, tag); - exit(1); - } -#ifdef DEBUG -printf("MPI_Send: source: %d, dest: %d, count: %d, size: %d, tag: %d\n", - MPINU_myrank, dest, count, count * datatype_size[(int)datatype], tag ); -#endif - if ( MPINU_pg_array[dest].sd == PG_NOSOCKET ) { - if (dest != MPINU_myrank) { - if ( -1 == list_connect_new_socket( MPINU_myrank, dest ) ) - return MPI_FAIL; /* Return failure if can't connect to dest */ - } - else { - printf("Attempt to send to self ( %d -> %d ) --\n", - MPINU_myrank, dest ); - printf(" not supported in this version.\n"); - exit(1); - } - } - -#ifdef DEBUG -if ( count * datatype_size[(int)datatype] < 0 ) { - printf("sending negative length message.\n"); - printf("datatype: %d, size for it: %d.\n", datatype, datatype_size[(int)datatype]); - exit(1); -} -#endif - if ( ! IS_SOCKET_CONNECTED(MPINU_pg_array[dest].sd) ) { - MPINU_socket_dead(MPINU_pg_array[dest].sd); - return MPI_FAIL; - } - buf_hdr.tag = htonl(tag); - buf_hdr.size = htonl(count * datatype_size[(int)datatype]); - buf_hdr.rank = htonl(MPINU_myrank); - - CALL_CHK( num_bytes = send, (MPINU_pg_array[dest].sd, - (char *)&buf_hdr, sizeof(buf_hdr), 0) ); - - if ((num_bytes == - 1)|| (!IS_SOCKET_CONNECTED(MPINU_pg_array[dest].sd))) { - MPINU_socket_dead(MPINU_pg_array[dest].sd); - return MPI_FAIL; - } - - CALL_CHK( num_bytes = send, (MPINU_pg_array[dest].sd, (char *)buf, - count * datatype_size[(int)datatype], 0) ); - - if((num_bytes == -1) || (!IS_SOCKET_CONNECTED(MPINU_pg_array[dest].sd))) { - MPINU_socket_dead(MPINU_pg_array[dest].sd); - return MPI_FAIL; - } - - return MPI_SUCCESS; -} - -#define EAT_HDR 0 -#define DONT_EAT_HDR 1 -#define BLOCKING 0 -#define NOT_BLOCKING 1 -#define MSG_WAITING 1 -#define NO_MSG_WAITING 0 -/* returns size (in bytes) of data that follows, or -1 if no msg */ -static int read_msg_hdr ( count, datatype, source, tag, comm, flag, - status, eat_hdr ) - int count; - MPI_Datatype datatype; - int *source; /* On entry, MPI_Rank; on exit, fd */ - int tag; - int *flag; /* On entry, non-zero means iprobe (zero timeout) */ - /* On exit, 1 if msg waiting, else 0 */ - MPI_Comm comm; - MPI_Status *status; /* Set on exit */ - int eat_hdr; /* eat_hdr non-zero means not consume msg header */ -{ struct msg_hdr buf_hdr; - int size, fd, recv_flags, num_bytes, num_sd; - fd_set MPINU_fdset2; - struct timeval zerotime; - struct timeval *timeout; - - /* MUST ALSO HANDLE MPI_ANY_TAG and MPI_COLL_COMM_TAG */ - if ( *flag == BLOCKING ) - timeout = NULL; /* wait forever (block) */ - else { /* poll and return */ - zerotime.tv_sec = 0; - zerotime.tv_usec = 0; - timeout = &zerotime; - } -#ifdef DEBUG - printf("Entering read_msg_hdr(): MPINU_myrank: %d, source: %d, tag: %d\n", - MPINU_myrank, *source, tag);fflush(stdout); -#endif -#if (MPI_ANY_SOURCE != -1) || (MPI_ANY_TAG != -1) || (MPI_COLL_COMM_TAG != -2) - printf("sendrecv: read_msg_hdr: inconsistent C constant macros\n"); - exit(1); -#endif - if ( *source > MPINU_num_slaves || *source < MPI_ANY_SOURCE || - tag < MPI_COLL_COMM_TAG ) { - printf("read_msg_hdr: invalid argument\n"); - exit(1); - } - - /* Use select to find active port; if BLOCKING && not MPI_ANY_SOURCE, - then we could have skipped this and gone directly to recv(), except - that we also need to check the listener port */ - TRYAGAIN: ; - if ( *source == MPI_ANY_SOURCE ) { - /* Copy global MPINU_fdset (with everything set) to local MPINU_fdset2 */ - memcpy( (char *)&MPINU_fdset2, (char *)&MPINU_fdset, sizeof(MPINU_fdset) ); - } - else { - fd = MPINU_pg_array[*source].sd; - FD_ZERO( &MPINU_fdset2 ); - if ( fd != PG_NOSOCKET ) - FD_SET( fd, &MPINU_fdset2 ); - /* if no socket, hopefully listener will accept new connection */ - FD_SET( MPINU_my_list_sd, &MPINU_fdset2 ); - } -#ifdef DEBUG - printf("entering select(%d)\n",MPINU_myrank);fflush(stdout); - { struct sockaddr_in sin; - int i = sizeof(struct sockaddr_in); - CALL_CHK( getsockname, (MPINU_my_list_sd, (struct sockaddr *)&sin, &i) ); - printf("CHECKING(%d) listener port w/ sd(%d): sin.sin_port: %d\n", - MPINU_myrank, MPINU_my_list_sd, sin.sin_port);fflush(stdout); - } -#endif - -#if 0 -if (MPINU_myrank == 2) { - { struct sockaddr_in sin; int len; fd_set MPINU_fdset5; - printf("SLAVE 2 starting again\n");fflush(stdout); - printf("MPINU_my_list_sd: %d, MPINU_max_sd: %d\n", - MPINU_my_list_sd, MPINU_max_sd); - fflush(stdout); - FD_ZERO(&MPINU_fdset5); - FD_SET(MPINU_my_list_sd, &MPINU_fdset5); - CALL_CHK( select, (MPINU_max_sd + 1, &MPINU_fdset5, NULL, NULL, NULL) ); - /* CALL_CHK(accept,(MPINU_my_list_sd, (struct sockaddr_in *)&sin, &len));*/ - printf("accept would have succeeded again\n");fflush(stdout); - } - CALL_CHK( select, (MPINU_max_sd + 1, &MPINU_fdset, NULL, NULL, NULL) ); - printf("select succeeded\n");fflush(stdout); -} -#endif - - CALL_CHK( num_sd = select_block_sigs, (MPINU_max_sd+1, &MPINU_fdset2, - NULL, NULL, timeout) ); - if ( (num_sd == 0) && (*flag == BLOCKING ) ) { - printf("read_msg_hdr: BLOCKING exiting without recv'd msg.\n"); - exit(1); - } -#ifdef DEBUG - printf("exiting select(%d)\n",MPINU_myrank);fflush(stdout); - printf("timeout == NULL: %d; num_sd: %d; *flag: %d\n", timeout == NULL, num_sd, *flag); -#endif - if ( FD_ISSET( MPINU_my_list_sd, &MPINU_fdset2 ) ) { - /* A msg on this socket is a request to open a new socket. */ -#if 0 - {int i; - for ( i = 0; i <= MPINU_max_sd; i++ ) - printf("FD_ISSET( %d, &MPINU_fdset2): %d\n", - i, FD_ISSET( i, &MPINU_fdset2) ); - } -#endif - list_accept_new_socket(MPINU_my_list_sd); - FD_SET( MPINU_pg_array[*source].sd, &MPINU_fdset2 );/*in case new socket*/ - goto TRYAGAIN; - } -#if 0 - {int i; - for ( i = 0; i <= MPINU_max_sd; i++ ) - printf("FD_ISSET( %d, &MPINU_fdset2): %d\n", - i, FD_ISSET( i, &MPINU_fdset2) ); - } -#endif - if ( num_sd > 0 ) - *flag = MSG_WAITING; - else { - *flag = NO_MSG_WAITING; /* no messages, return */ - return( -1 ); - } - TRY_NEXT_SOCKET: ; - if ( *source == MPI_ANY_SOURCE ) { /* Determine source, fd */ - FD_CLR( MPINU_my_list_sd, &MPINU_fdset2 ); /* listener not legit source */ - for ( fd = 0; fd <= MPINU_max_sd+1; fd++) - if ( FD_ISSET( fd, &MPINU_fdset2 ) ) break; - if ( fd > MPINU_max_sd ) { - printf("Unknown socket descriptor from select: %d MAX_SD:%d.\n", fd, MPINU_max_sd); - exit(1); - } - } -#ifdef DEBUG - printf("receiving on socket %d out of MPINU_max_sd %d\n", fd, MPINU_max_sd); -#endif - if ( eat_hdr == DONT_EAT_HDR ) recv_flags = MSG_PEEK; - else recv_flags = 0; -#if 1 - CALL_CHK( num_bytes = recv, - ( fd, (char *)&buf_hdr, sizeof(buf_hdr), recv_flags ) ); - - if ( (num_bytes == 0) || (num_bytes == -1)) { - { int dest = 0; - while( fd != MPINU_pg_array[dest].sd ) { dest++; } - if( list_connect_new_socket( MPINU_myrank, dest) == -1) - MPINU_socket_dead(fd); - } - goto TRYAGAIN; - } -#else - num_bytes = recv, - ( fd, (char *)&buf_hdr, sizeof(buf_hdr), recv_flags ); - /* exit(1); */ - } -#endif -#ifdef DEBUG -if ( num_bytes == 0 ) printf("rank(%d): recv returned 0\n", MPINU_myrank ); -#endif - /* If 0 characters received and another socket available */ - /* Why do these "ping"'s to extra sockets occur? */ - if ( num_bytes == 0 && timeout != NULL ) { /* if no msg and non-blocking */ - *flag = NO_MSG_WAITING; /* no messages, return */ - return( -1 ); - } - - if ( num_bytes == 0 && num_sd > 1 ) { - FD_CLR( fd, &MPINU_fdset2 ); /* Clear empty socket and try again */ - num_sd--; - goto TRY_NEXT_SOCKET; - } - /* if 0 characters received and a blocking call (timeout == NULL) */ - if ( num_bytes == 0 && timeout == NULL ) goto TRYAGAIN; /* Why does this happen? */ - if ( num_bytes != sizeof(buf_hdr) ) { - /* Possible non-local error or loss of socket? */ - printf("read_msg_hdr(%d): Header of size %d received instead of %ud.\n", - MPINU_myrank, num_bytes, sizeof(buf_hdr)); - FD_ZERO(&MPINU_fdset2); - FD_SET( fd, &MPINU_fdset2); - zerotime.tv_sec = 0; - zerotime.tv_usec = 0; - CALL_CHK( num_sd=select,(MPINU_max_sd+1, - NULL, NULL, &MPINU_fdset2, &zerotime) ); - printf("Exceptional condition on socket %d?: %d\n", fd, num_sd); - FD_SET( fd, &MPINU_fdset2); - CALL_CHK( num_sd = select, (MPINU_max_sd+1, - NULL, &MPINU_fdset2, NULL, &zerotime) ); - printf("Write condition on socket %d?: %d\n", fd, num_sd); - FD_SET( fd, &MPINU_fdset2); - CALL_CHK( num_sd = select, (MPINU_max_sd+1, - &MPINU_fdset2, NULL, NULL, &zerotime) ); - printf("Read condition on socket %d?: %d\n", fd, num_sd); - CALL_CHK( num_bytes = recv, ( fd, (char *)&buf_hdr, 1, recv_flags ) ); -printf("num_bytes = recv now returns %d\n", num_bytes); -printf("NDELAY (non-blocking): %d\n", O_NDELAY & fcntl( fd, F_GETFL, 0)); - exit(1); - } - status->MPI_TAG = ntohl(buf_hdr.tag); - size = ntohl(buf_hdr.size); - status->mpi_size = size; - status->MPI_SOURCE = ntohl(buf_hdr.rank); - - if (size == -1) { printf("size was -1\n"); exit(1); } - if ( (tag != MPI_ANY_TAG) && (tag != status->MPI_TAG) ) { - printf("Msg received with tag (%d) from source (%d) \ - incompatible with requested tag (%d).\n", - status->MPI_TAG, status->MPI_SOURCE, tag ); - exit(1); - } - if ( eat_hdr == EAT_HDR ) { - if ( count < 0 || datatype < 1 || datatype > MPI_DOUBLE) {/* change for ANSI, cf above*/ - printf("read_msg_hdr: invalid count or datatype argument\n"); - exit(1); - } - if (size > count * datatype_size[(int)datatype]) { - printf("read_msg_hdr: User buffer (size: %d)\n", - count * datatype_size[(int)datatype]); - printf(" not large enough to hold message (size: %d) on processor %d.\n", - size, MPINU_myrank); - exit(1); - } - } - if ( ( *source != status->MPI_SOURCE ) && ( *source != MPI_ANY_SOURCE ) ) { - printf("read_msg_hdr: inconsistent source,\n"); - printf(" expecting source(%d) and received from source(%d) on proc. %d\n", - *source, status->MPI_SOURCE, MPINU_myrank); - exit(1); - } -#ifdef DEBUG - printf("read_msg_hdr: source: %d, dest: %d, size: %d, tag: %d\n", - status->MPI_SOURCE, MPINU_myrank, size, status->MPI_TAG );fflush(stdout); -#endif - *source = fd; /* *source set to fd on exit */ - return( size ); -} - -int MPI_Recv( buf, count, datatype, source, tag, comm, status ) - void *buf; - int count, source, tag; - MPI_Datatype datatype; - MPI_Comm comm; - MPI_Status *status; -{ int size, i; - int is_non_blocking = 0; - -#ifdef DEBUG -printf("MPI_Recv (MPINU_myrank=%d)\n", MPINU_myrank);fflush(stdout); -#endif - size = read_msg_hdr( count, datatype, &source, tag, comm, - &is_non_blocking, status, EAT_HDR ); - /* source was modified to be fd */ -#ifdef DEBUG -printf("fd: %d, *flag: %d\n", source, is_non_blocking);fflush(stdout); -#endif - if ( size < 0 ) { - printf("MPI_Recv(%d): read_msg_hdr claims no message waiting.\n", - MPINU_myrank); - exit(1); - } - while ( size > 0 ) { - CALL_CHK( i = recv, ( source, (char *)buf, size, 0 ) ); - if(i <= 0) { - MPINU_socket_dead(source); - return MPI_FAIL; - } - - buf = (char *)buf + i; /* FreeBSD didn't like: (char *)buf += 1; */ - size -= i; -#ifdef DEBUG -printf("Read i chars: %d; Remaining size: %d\n", i, size);fflush(stdout); -#endif - } - return MPI_SUCCESS; -} - -/* MUST SET STATUS FOR TWO PROBE COMMANDS */ -int MPI_Probe( source, tag, comm, status ) - int source; - int tag; - MPI_Comm comm; - MPI_Status *status; -{ int flag_val = BLOCKING; -int i; -#ifdef DEBUG -printf("MPI_Probe (MPINU_myrank=%d)\n", MPINU_myrank); -#endif - read_msg_hdr( 0, 1, &source, tag, comm, &flag_val, status, DONT_EAT_HDR ); - return MPI_SUCCESS; -} - -int MPI_Iprobe( source, tag, comm, flag, status ) - int source; - int tag; - int *flag; - MPI_Comm comm; - MPI_Status *status; -{ *flag = NOT_BLOCKING; /* on entry */ -#ifdef DEBUG -printf("MPI_IProbe (MPINU_myrank=%d)\n", MPINU_myrank); -#endif - read_msg_hdr( 0, 1, &source, tag, comm, flag, status, DONT_EAT_HDR ); - /* flag updated by read_msg_hdr, can be checked by caller */ - return MPI_SUCCESS; -} - -int MPI_Get_count( status, datatype, count ) - MPI_Status *status; - MPI_Datatype datatype; - int *count; -{ *count = status->mpi_size / datatype_size[(int)datatype]; -#ifdef DEBUG -printf("MPI_Get_count: count: %d\n", *count);fflush(stdout); -#endif - return MPI_SUCCESS; } diff --git a/topc-2.5.2/src/mpinu/slave.c b/topc-2.5.2/src/mpinu/slave.c deleted file mode 100644 index 9512cd46..00000000 --- a/topc-2.5.2/src/mpinu/slave.c +++ /dev/null @@ -1,145 +0,0 @@ -#include "mpi.h" -#include "mpiimpl.h" - -static int RECV(s, buf, len, flags) -int s; -char *buf; -size_t len; -int flags; -{ int size = 0; - int tmp; - int count = 0; - while ( len > size ) { - CALL_CHK( tmp = recv, (s, buf + size, len - size, flags) ); - if ( tmp < 0 ) { - printf("MPINU_mpi_slave: bad receive\n"); fflush(stdout); exit(1); - } - size += tmp; - count++; - if (count > 100) { - printf("size only %d, need %ul\n", size, len); fflush(stdout); exit(1); - } - } - return size; -} - -void MPINU_mpi_slave(master_host, port) -char *master_host; /* master host */ -char *port; /* port to connect to */ -{ - int sd; /* socket descriptor */ - struct init_msg msg1; - struct hostent *mhp; /* ptr to host info structure*/ - struct sockaddr_in sin, list_addr; /* inet info structures */ - int i, size; - - if ( ! MPINU_is_spawn2 ) { -#ifdef DEBUG - printf("MPINU_mpi_slave: slave: host: %s; port: %s\n", master_host, port); - fflush(stdout); -#endif - - /* get the host info such as IP address */ - mhp = gethostbyname(master_host); - -#if 0 - memset( (char *)&sin, (char)0, sizeof(sin) ); -#else - for ( i = 0; (unsigned int)i < sizeof(sin); i++ ) - ((char *)&sin)[i] = 0; -#endif - - /* copy the IP address in hp to sin */ - memcpy( (char *)&sin.sin_addr, mhp->h_addr, mhp->h_length); - - /* assign port ID */ - sin.sin_port = htons(atoi(port)); -#ifdef DEBUG - printf("slave: sin.sin_port: %d\n", ntohs(sin.sin_port));fflush(stdout); -#endif - - /* specify address type */ - sin.sin_family = mhp->h_addrtype; -#ifdef DEBUG - printf("sin_family (%d) and AF_INET (%d) should compare.\n", sin.sin_family, AF_INET);fflush(stdout); -#endif - } /* end: if ( ! MPINU_is_spawn2 ) */ - - /* we are using the default protocol 6 = IPPROTO_TCP */ - CALL_CHK( sd = socket, (AF_INET, SOCK_STREAM, IPPROTO_TCP) ); - SETSOCKOPT(sd); - - CALL_CHK( connect, - (sd, (struct sockaddr *)( MPINU_is_spawn2 - ? &MPINU_pg_array[0].listener_addr : &sin ), - sizeof(sin) ) ); - MPINU_is_spawn2 = 0; /* Will never be used again in this call to spawn2(). */ - MPINU_pg_array[0].sd = sd; - FD_ZERO(&MPINU_fdset); /* initialize, MPINU_new_listener() will modify */ - FD_SET(sd, &MPINU_fdset); - if ( sd > MPINU_max_sd ) - MPINU_max_sd = sd; - -#ifdef DEBUG - printf("slave: slave connected\n");fflush(stdout); - CALL_CHK( recv, (sd, (char *)&msg1, 7, 0) ); - printf("slave msg1: %s\n", &msg1);fflush(stdout); -#endif - - /* slave sets up listener and sends list_addr to master */ - MPINU_new_listener( &MPINU_my_list_sd, &list_addr, &i ); /* Throw away i val */ - FD_SET(MPINU_my_list_sd, &MPINU_fdset); - send( sd, (char *)&list_addr, sizeof(list_addr), 0); - - for( size = 0; size == 0; ) - CALL_CHK( size = recv, (sd, (char *)&msg1, sizeof(msg1), 0) ); - if (size != sizeof(msg1)) { - printf("Incomplete message received.\n"); - exit(1); - } - if ( ntohl(msg1.len) != sizeof(msg1) ) { - printf("MPINU_mpi_slave: size of struct or int not preserved" - " across architectures.\n"); - printf("Either contact maintainer or use homogeneous architecture.\n"); - exit(1); - } - MPINU_myrank = ntohl(msg1.rank); - MPINU_num_slaves = ntohl(msg1.num_slaves); - if (MPINU_myrank > 100000) { - printf("MPINU_mpi_slave: Bad rank received: %d\n", MPINU_myrank); - exit(1); - } -#ifdef DEBUG - printf("MPINU_myrank: %d\n", MPINU_myrank);fflush(stdout); - printf("MPINU_num_slaves: %d\n", MPINU_num_slaves);fflush(stdout); -#endif - - /* Set listener_addr field of MPINU_pg_array field on slave */ - for ( i=0; i <= MPINU_num_slaves; i++ ) { - for( size = 0; size == 0; ) - CALL_CHK( size = recv, (sd, (char *)&(MPINU_pg_array[i].listener_addr), - sizeof(struct sockaddr_in), 0) ); - if (size != sizeof(struct sockaddr_in)) { - printf("MPINU_mpi_slave: Incomplete message received at index %d.\n", i); - exit(1); - } - } -#ifdef DEBUG -for (i=0;i<=MPINU_num_slaves;i++) { - printf("slave(%d)[%d]: listener port: sin.sin_port: %d\n", - MPINU_myrank, i, ntohs(MPINU_pg_array[i].listener_addr.sin_port)); - fflush(stdout); } -#endif - { INT buf[1]; - /* Acknowledge that master and slave are synchronized */ - for( size = 0; size == 0; ) - CALL_CHK( size = recv, (sd, (char *)buf, sizeof(INT), 0) ); - if ( ntohl(buf[0]) != sizeof(struct sockaddr_in) ) { - printf("MPI_Init: slave %d not synchronized.\n", MPINU_myrank); - exit(1); - } -#ifdef DEBUG - printf("MPI_Init: slave %d synchronized.\n", MPINU_myrank);fflush(stdout); -#endif - } -} diff --git a/topc-2.5.2/src/mpinu/spawn2.c b/topc-2.5.2/src/mpinu/spawn2.c deleted file mode 100644 index 2bf027d2..00000000 --- a/topc-2.5.2/src/mpinu/spawn2.c +++ /dev/null @@ -1,65 +0,0 @@ -#include "mpi.h" -#include "mpiimpl.h" - -int MPI_Spawn2() { - int sd, ns; /* socket descriptors */ - struct init_msg msg1; - int fromlen, rank; - struct sockaddr_in new_sin; /* used for each new connection */ - - //Leave the loader alone if no space in host table - if (MPINU_num_slaves == PG_ARRAY_SIZE) return MPI_FAIL; - - //Start up new slave process - MPINU_is_spawn2 = 1; - MPINU_is_initialized = 0; - do_unexec(); - MPINU_is_initialized = 1; - MPINU_is_spawn2 = 0; - if (!attach_new_slaves()) return MPI_FAIL; - - //Allocate new slave record. Easy - rank = ++MPINU_num_slaves; - - //Accept connection from new slave, remember it - fromlen = sizeof(new_sin); - CALL_CHK( ns = accept, (MPINU_my_list_sd, - (struct sockaddr *)&new_sin, &fromlen) ); - MPINU_pg_array[rank].sd = ns; - FD_SET(ns, &MPINU_fdset); - if ( ns > MPINU_max_sd ) - MPINU_max_sd = ns; -#ifdef DEBUG - printf("master: accepted new slave connection\n"); - printf("master: slave %d: new ns: %d, current MPINU_max_sd: %d\n", - rank, ns, MPINU_max_sd); -#endif - - //Receive slave's listener_addr and store in field of MPINU_pg_array[rank] - CALL_CHK( recv, (ns, (char *)&(MPINU_pg_array[rank].listener_addr), - sizeof(struct sockaddr_in), 0) ); - - //Send back number of slaves and the assigned rank - msg1.len = htonl(sizeof(msg1)); - msg1.rank = htonl(rank); - msg1.num_slaves = htonl(MPINU_num_slaves); - send(ns, (char *)&msg1, sizeof(msg1), 0); - - //Send listener_addr fields to slave - { char buf[PG_ARRAY_SIZE * sizeof(struct sockaddr_in)], *ptr; - int i; - - ptr = buf; - for ( i=0; i <= MPINU_num_slaves; i++ ) { - memcpy( ptr, (char *)&(MPINU_pg_array[i].listener_addr), - sizeof(struct sockaddr_in) ); - ptr += sizeof(struct sockaddr_in); - } - send( MPINU_pg_array[rank].sd, buf, - (1+MPINU_num_slaves)*sizeof(struct sockaddr_in), 0 ); - - //Acknowledge that master and slave are synchronized - *((INT *)buf) = htonl( sizeof(struct sockaddr_in) ); - send( MPINU_pg_array[rank].sd, buf, sizeof(INT), 0); - } -} diff --git a/topc-2.5.2/src/mpinu/thwap b/topc-2.5.2/src/mpinu/thwap deleted file mode 100755 index c378a896..00000000 --- a/topc-2.5.2/src/mpinu/thwap +++ /dev/null @@ -1,142 +0,0 @@ -#!/usr/bin/perl - -# -# Rat's thwap script, rewritten in perl and diffed a lot. -# -# django@ccs.neu.edu -# July 24, 1993 -# -# 1/19/94 v2.01 - bdowling -# Added: Interactive prompting (-i) -# Whuggled option handling -# -Allows numeric signals -# -Allows varied ordering -# Changed finding processes slightly -# Added sysV support ?? -# 1997.08.05 jay -# added Solaris support - -$0 =~ s#.*/##; -$| = 1; - -$fakeit = 0; -$iprompt = 0; - -# gdc - /usr/bin/kill -> /bin/kill, Redhat Linux 4.2 had only /bin/kill -@valid_signals = split(/[ \t\n]+/, `/bin/kill -l`); -die "$0: error running 'kill' to gather signals!: $!\n" if $?; - -$signal = "KILL"; - -while ($ARGV[0] =~ /^-/) { - $_ = shift(@ARGV); - if (/^-n$/) { - $fakeit = 1; $iprompt = 0; - } elsif (/^-i$/) { - $iprompt = 1; $fakeit = 0; - } elsif (/^-(\w+)/) { - $signal = $1; - $signal =~ tr/[a-z]/[A-Z]/; - $signal =~ s/^SIG//; - die "$1: $signal is not a valid signal\n" - if (! grep(/^$signal$/, - (@valid_signals, (1..$#valid_signals+1) ) ) ); - } -} -#warn "> $signal\n"; -# we don't need to do this, since Perl can handle named signals just as well -# as numberic ones. In fact, this causes us grief because kill -l does not -# return the same thing on all systems -#if (! ($signal =~ /^[0-9]+$/)) { # We want to work with a numeric signal -# for($x=0;$x<=$#valid_signals;$x++) { -# do { $numsignal = ++$x; last; } if @valid_signals[$x] eq $signal; -# } -#} -#warn "> $signal\n"; - -&usage if ($#ARGV < 0); - -foreach $uname ('/bin/uname', '/usr/bin/uname', '/sbin/uname') { - next unless (-x $uname); - chop($rev = `$uname -r`); - ($OSMAJOR = $rev) =~ s/\..*//; - last; -} - -if ($OSMAJOR == 5) { # System V - $ps_flags = " -f "; - $ps_flags .= " -e " if ($> == 0); - $ps_flags .= " -u $>" if ($> != 0); # Do we need this? Could we just do - # ps -f above? It gets some root procs - # such as rlogin etc. (which is cool!) -} else { # Assume BSD system, what others could we check for? - $ps_flags = "auxww"; # a needed to reap child if parent gone. - $ps_flags .= "a" if ($> == 0); # Only need this if we're root -} - -# Don't want a leading "-" on the flags, so it works on both Alphas and Suns: -$ps_pid = open(PS, "ps $ps_flags |"), "\n"; -$header = ; -$seen_header = 0; -$thwapped = 0; - -while () { - ($foo = $_) =~ s/^\s*//; - ($user, $pid, @rest) = split(' ',$foo); - next if ($pid == $$ || $pid == $ps_pid); # Don't thwap this process! - next if (/thwap/); # Hackish attempt to avoid - # thwapping this process - # when invoked via rsh - - testit: foreach $expr (@ARGV) { - if ($expr =~ /^[0-9]+$/) { # make numbers only match pids - next testit if ($pid != $expr); - } - if (grep(/$expr/, $_)) { -# warn "expr = $expr; user = $user; pid = $pid; rest = @rest\n"; - warn $header if (! $seen_header); - warn "\n" if ($seen_header && $iprompt); - $seen_header = 1; - warn $_; - if (! $iprompt || &AskYN() ) { -# warn "-> kill $signal $pid\n" if (! $fakeit); - if (! $fakeit ) { - # quotes needed around $signal so Perl will interpret both - # numeric and non-numberic signals properly -- dNb - $killed = kill("$signal", $pid); - warn "kill: $!\n" if ! $killed; - $thwapped += $killed; - } else { - $thwapped++; - } - } - last testit; # Okay it's dead jim, we're done this loop. - } - } -} - -close(PS); - -warn "$0: ", ( $fakeit ? "would have " : "" ), - "sent SIG${signal} to $thwapped process", - ($thwapped == 1 ? "" : "es"), "\n"; - -sub usage { - warn <<"EOT"; -Usage: $0 [options] ... -Options: - -n fake mode - only display processes that would be selected - -i interactive mode - prompt on each suspect process - - any valid literal or numeric signal (see kill -l) - -EOT -exit(1); -} - -sub AskYN { - print STDERR "Send SIG", @valid_signals[$numsignal-1], " to this process? (y/n/a)? "; - $ans = ; - $iprompt = ! ($ans =~ /^a/i); - return( $ans =~ /^[ay]/i ); -} - diff --git a/topc-2.5.2/src/mpinu/utils.c b/topc-2.5.2/src/mpinu/utils.c deleted file mode 100644 index 2f682977..00000000 --- a/topc-2.5.2/src/mpinu/utils.c +++ /dev/null @@ -1,65 +0,0 @@ -#include "mpi.h" -#include "mpiimpl.h" - -int MPI_Comm_rank( comm, rank ) - MPI_Comm comm; - int *rank; -{ *rank = MPINU_myrank; - return 0; -} - -int MPI_Comm_size( comm, size) - MPI_Comm comm; - int *size; -{ *size = 1 + MPINU_num_slaves; - return 0; -} - -int MPI_Get_processor_name( name, resultlen ) - char *name; - int *resultlen; -{ gethostname( name, MPI_MAX_PROCESSOR_NAME ); - *resultlen = strlen( name ); - if ( *resultlen < MPI_MAX_PROCESSOR_NAME ) return 0; - else return -1; -} - -int MPI_Abort( comm, errorcode ) - MPI_Comm comm; - int errorcode; -{ printf("MPI_Abort called with errorcode: %d\n", errorcode); - abort(); - return( 0 ); /* return for lint */ -} - -/* MPI_TAG_UB, MPI_HOST <- MPI_PROC_NULL, MPI_IO (myrank), MPI_WTIME_IS_GLOBAL - <- 0 - attr_value can be (int *) */ -int MPI_Attr_get ( comm, keyval, attr_value, flag ) - MPI_Comm comm; - int keyval; - void *attr_value; - int *flag; -{ *flag = 1; - switch( keyval ) { - case MPI_TAG_UB: *(int *)attr_value = ~(1u << (8 * sizeof(INT) - 1) ); - break; - case MPI_HOST: *(int *)attr_value = MPI_PROC_NULL; - break; - case MPI_IO: *(int *)attr_value = MPINU_myrank; - break; - case MPI_WTIME_IS_GLOBAL: *(int *)attr_value = 0; - break; - default: *flag = 0; - } - return( 0 ); -} - -int MPI_Error_string( errorcode, string, resultlen ) - int errorcode, *resultlen; - char *string; -{ static char err[] = "MPINU: MPI_Error_string not implemented.\n"; - string = err; - *resultlen = strlen(err); - return( 0 ); -} diff --git a/topc-2.5.2/src/options.c b/topc-2.5.2/src/options.c deleted file mode 100644 index 64d30253..00000000 --- a/topc-2.5.2/src/options.c +++ /dev/null @@ -1,618 +0,0 @@ - /********************************************************************** - * TOP-C (Task Oriented Parallel C) * - * Copyright (c) 2004 Gene Cooperman * - * * - * This library is free software; you can redistribute it and/or * - * modify it under the terms of the GNU Lesser General Public * - * License as published by the Free Software Foundation; either * - * version 2.1 of the License, or (at your option) any later version. * - * * - * This library is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * - * Lesser General Public License for more details. * - * * - * You should have received a copy of the GNU Lesser General Public * - * License along with this library (see file COPYING); if not, write * - * to the Free Software Foundation, Inc., 59 Temple Place, Suite * - * 330, Boston, MA 02111-1307 USA, or contact Gene Cooperman * - * . * - **********************************************************************/ - -/* ISSUE: In options.c, clean up standalone test */ - -/*********************************************************************** - *********************************************************************** - ** USAGE: get_topc_options( int *argc, char ***argv ); - ** Command line options: --TOPC-XXX= (variable: TOPC_OPT_XXX) - *********************************************************************** - ***********************************************************************/ - -/* gcc -DTEST options.c; ./a.out --TOPC-help for testing */ - -#include // for open() -#include // for open() -#include // for open() -#include // for fopen() -#include -#include -#include -#include -#include // time() -#include -#include -#include -#include "topc.h" -#include "comm.h" // comm.h also defines HAVE_PTHREAD, etc., by default -#ifdef HAVE_PTHREAD -# ifdef HAVE_PTHREAD_SETCONCURRENCY -// Define __USE_UNIX98 this for sake of pthread_setconcurrency() -// Consider no longer using old pthread_setconcurrency() -# define __USE_UNIX98 -# include -# endif -#endif - -#ifdef TEST -int COMM_is_shared_memory(void) { return 1; } -int COMM_node_count() - {extern int TOPC_OPT_num_slaves; return TOPC_OPT_num_slaves + 1;}; -#define UNINITIALIZED -1; -#endif - -#define ARGS_MAX 100 -static char *saved_args[ARGS_MAX]; /* from argv[] */ -static int args_idx = 0; /* from argv[] */ - -/* Defaults; types should also be declared extern in topc.h and comm.h */ -#define bool int -int TOPC_OPT_num_slaves = UNINITIALIZED; -int TOPC_OPT_aggregated_tasks = 1; -int TOPC_OPT_slave_wait = 0; /* seconds */ -int TOPC_OPT_slave_timeout = 1800; -int TOPC_OPT_trace = 2; -bool TOPC_OPT_help = 0; /* --TOPC-help (no arg) sets it to 1 */ -/* Set to 2, to distinguish from --TOPC-help --TOPC-verbose, which - will be detected by TOPC_OPT_verbose == 1 */ -bool TOPC_OPT_verbose = 2; /* --TOPC-verbose (no arg) sets it to 1 */ -bool TOPC_OPT_stats = 0; /* --TOPC-stats (no arg) sets it to 1 */ -char *TOPC_OPT_procgroup = "./procgroup"; -char *TOPC_OPT_topc_log = "-"; /* - = stdout, but should set to topc.log if is "" */ -int TOPC_OPT_safety = SAFETY_NONE; - -enum opt_type { BOOL, INT, STRING }; - -struct option { - char *option; - void *var_ptr; - enum opt_type type; - char *help_string; -}; - -/* COULD COMPUTE DEFAULT NUM_SLAVES FIRST */ - -static struct option cmd_opt[] = { - { "--TOPC-help", &TOPC_OPT_help, BOOL, "display this message" }, - { "--TOPC-stats", &TOPC_OPT_stats, BOOL, "display stats before and after" }, - { "--TOPC-verbose", &TOPC_OPT_verbose, BOOL, "set verbose mode" }, - { "--TOPC-num-slaves", &TOPC_OPT_num_slaves, INT, - "number of slaves (sys-defined default)" }, - { "--TOPC-aggregated-tasks", &TOPC_OPT_aggregated_tasks, INT, - "number of tasks to aggregate" }, - { "--TOPC-slave-wait", &TOPC_OPT_slave_wait, INT, - "secs before slave starts (use w/ gdb attach)"}, - { "--TOPC-slave-timeout", &TOPC_OPT_slave_timeout, INT, - "dist mem: secs to die if no msgs, 0=never"}, - { "--TOPC-trace", &TOPC_OPT_trace, INT, - "trace (0: notrace, 1: trace, 2: user trace fncs.)" }, - { "--TOPC-procgroup", &TOPC_OPT_procgroup, STRING, "procgroup file (--mpi)" }, - { "--TOPC-topc-log", &TOPC_OPT_topc_log, STRING, - "NOT IMPL: log file for TOPC output (\"-\" = stdout)" }, - { "--TOPC-safety", &TOPC_OPT_safety, INT, - "[0..20]: higher turns off optimizations,\n" - " try with --TOPC-verbose" }, - { "", NULL, BOOL, "" } -}; - -#define COL2 27 -#define COL3 55 - -static char *print_arg_type(enum opt_type type) { - switch (type) { - case BOOL: return "[=<0/1>]"; - case INT: return "="; - case STRING: return "="; - default: return ""; - } -} - -static void print_help(char *command) { - struct option *opt; - int len1, len2; - printf("\nTOP-C Version " VER_STR " (" UPDATE_STR "); (%s memory model)\n", - COMM_mem_model); - printf("Usage: %s [ [TOPC_OPTION | APPLICATION_OPTION] ...]\n", command); - printf(" where TOPC_OPTION is one of:\n"); - for ( opt = cmd_opt; opt->option[0] != '\0'; opt++ ) { - printf("%s%s%n", opt->option, print_arg_type(opt->type), &len1 ); - printf("%*s%s %n", COL2 - len1, " ", opt->help_string, &len2 ); - if ( len1 + len2 > COL3 ) printf("\n%*s", COL3, " "); - else printf("%*s", COL3 - len1 - len2, " "); - switch (opt->type) { - case BOOL: - printf("[default: false]\n"); - break; - case INT: - printf("[default: %d]\n", *(int *)(opt->var_ptr)); - break; - case STRING: - printf("[default: \"%s\"]\n", *(char **)(opt->var_ptr)); - break; - default: - ERROR("FATAL: invalid option type: %d\n", opt->type); - } - } - printf("\nThe environment variable TOPC_OPTS and the init file ~/.topcrc\n"); - printf(" are also examined for options (format: --TOPC-xxx ...).\n"); - printf("You can change the defaults in the application source code.\n"); - printf(" For example, to change the default to --TOPC-trace=0,\n"); - printf(" add `TOPC_OPT_trace = 0;' before `TOPC_init(&argc, &argv);'\n"); - if (TOPC_OPT_verbose == 1) { - printf("\nEffect of --TOPC-safety=:\n" - " safety: >=%d: all;" - " >=%d: no TOPC_MSG_PTR;" - " >=%d: no TOP-C memory mgr (uses malloc/free);\n" - " >=%d: no aggregation of tasks;\n" - " >=%d: no TOPC_abort_tasks; >=%d: no receive thread on slave;\n" - " >=%d: default atomic read/write for DoTask, UpdateSharedData;\n" - " =%d: only 2 slaves; =%d: only 1 slave\n" - " >=%d: no timeout (no SIGALRM, dangerous for runaways)\n", - SAFETY_NONE, SAFETY_NO_MSG_PTR, - SAFETY_NO_MEM_MGR, SAFETY_NO_AGGREG, - SAFETY_NO_ABORT_TASKS, SAFETY_NO_RCV_THREAD, - SAFETY_DFLT_ATOMIC_READ_WRITE, SAFETY_TWO_SLAVES, SAFETY_ONE_SLAVE, - SAFETY_NO_TIMEOUT - ); - } else - printf("Try `--TOPC-help --TOPC-verbose' for more information.\n"); - // TOPC_MSG_PTR() requires memory manager to MEM_malloc_ptr() - // header to record pointer. - assert( SAFETY_NO_MEM_MGR > SAFETY_NO_MSG_PTR ); -} - -static void set_option( struct option *opt, char *val ) { - char *endptr; // Used to check validity of strtol() arg. - switch (opt->type) { - case BOOL: - if ( val[0] == '\0' ) { - val = NULL; - break; - } /* else parse val in next case */ - case INT: - case STRING: - if ( val[0] != '=' ) - ERROR( "FATAL: %s=: option takes %s argument.\n", - opt->option, (opt->type==INT ? "an int" : "a string") ); - else - val = val + 1; // val was "=", now val is "" - break; - } - switch (opt->type) { - case BOOL: - if ( val == NULL || *val == '\0' || *val == '1' ) - *(int *)(opt->var_ptr) = 1; - else if ( *val == '0' ) - *(int *)(opt->var_ptr) = 0; - else - WARNING("Boolean option %s must have value 0, 1, or no arg" - " (default: false)\n", opt->option); - break; - case INT: - *(int *)(opt->var_ptr) = - strtol( val, &endptr, 10 ); - if (*endptr != '\0') - ERROR("Invalid integer value for %s=%s\n", opt->option, val); - break; - case STRING: - *(char **)(opt->var_ptr) = malloc( strlen( val ) ); - strcpy( *(char **)(opt->var_ptr), val ); - break; - } -} - -static void get_options(int *argc, char ***argv) { - struct option *opt; - int i, j, end_options = 0; - char *ch; - - for ( i = 1; i < *argc && args_idx < ARGS_MAX; i++) - saved_args[args_idx++] = (*argv)[i]; - -#ifdef TEST -printf("BEGIN: *argc=%d\n", *argc); -#endif - for ( j = 1; j < *argc; j++ ) { -#ifdef TEST -printf("(*argv)[%d]=%s\n", j, (*argv)[j]); -#endif - if ( strncmp( "--", (*argv)[j], 3) == 0 ) - end_options = 1; /* Stop processing TOP-C options; Leave "--" for app */ - if ( ! end_options && strncmp( (*argv)[j], "--TOPC", 6 ) == 0 ) { - /* Convert --TOPC_the_option=XX-YY to: --TOPC-the-option=XX-YY */ - for (ch = (*argv)[j]+6; *ch != '\0' && *ch != '=' && ch-(*argv)[j]<80; - ch++) - if (*ch == '_') - *ch = '-'; - /* Look for matching --TOPC option */ - for ( opt = cmd_opt; opt->option[0] != '\0'; opt++ ) { - if ( strncmp( opt->option, (*argv)[j], strlen(opt->option) ) == 0 ) { - set_option( opt, (*argv)[j] + strlen(opt->option) ); - break; - } - } - if ( opt->option[0] == '\0' ) { // if "--TOPC" did not match anything - printf("\n*** Invalid option: %s\n\n", (*argv)[j]); - print_help(**argv); - exit(1); - } - } - } -#ifdef TEST -printf("END: *argc=%d\n", *argc); -#endif -} -static void get_options_from_string( char * opts_str ) { - int argc = 1; - char * argv[100]; - char **argv_ptr = argv; - - // Copy string since get_options saves argv[] strings in saved_args - opts_str = strcpy( malloc( strlen(opts_str)+1 ), opts_str ); - argv[argc] = strtok( opts_str, " \t" ); - argv[0] = "UNKNOWN_BINARY"; - while ( argv[argc] != NULL ) - argv[++argc] = strtok( NULL, " \t" ); - get_options( &argc, &argv_ptr ); -} - -static void strip_options(int *argc, char ***argv) { - int i, j, end_options = 0; -#ifdef TEST -printf("BEGIN: *argc=%d\n", *argc); -#endif - for ( i = 1, j = 1; j < *argc; j++ ) { -#ifdef TEST -printf("(*argv)[%d]=%s\n", j, (*argv)[j]); -#endif - if ( strncmp( "--", (*argv)[j], 3) == 0 ) - end_options = 1; - if ( end_options || (strncmp((*argv)[j], "--TOPC", 6) != 0) ) { - (*argv)[i] = (*argv)[j]; - i++; - } - } - (*argv)[i] = (*argv)[j]; // Copy final null pointer - *argc = i; -#ifdef TEST -printf("END: *argc=%d\n", *argc); -#endif -} - -static time_t start_time; -// These are defined in procgroup.c -void TOPC_OPT_pre_extend_procgroup - (char *procgroup_file, int num_slaves, int *argc, char ***argv); -void TOPC_OPT_post_extend_procgroup(int *argc, char ***argv); - -// Note this answers true even for other MPI's. -// This minor bug doesn't seem to hurt us. -static int has_procgroup_file() { - static int val = -1; - if (val == -1) { - val = ! COMM_is_shared_memory() - && 0 != strncmp(COMM_mem_model, "sequential", 3); - } - return val; -} - -static void print_config_info() { - char buf[61]; - - printf("\n"); - printf("TOP-C Version " VER_STR " (" UPDATE_STR ")\n"); - system("date"); - system("uptime"); - start_time = time(NULL); - if ( 0 == gethostname(buf, 60) ) - printf("hostname: %.60s\n", buf); - else - printf("hostname: \n"); - TOPC_OPT_getpwd(buf, 60); - printf("current directory: %.60s\n", buf); - printf("safety level: %d\n", TOPC_OPT_safety); - printf("memory model: %s\n", COMM_mem_model); - if ( has_procgroup_file() ) - printf("procgroup file: %s\n", TOPC_OPT_procgroup); -} - -void TOPC_OPT_pre_init( int *argc, char ***argv ) { - struct stat buf; - FILE *topcrc; - char *opts_str; - - // Process .toprc - if ( opts_str = getenv( "HOME" ) ) { -#define MAX_PATH 10000 - char path[MAX_PATH]; - strncat( path, opts_str, MAX_PATH ); - strncat( path + strlen(path), ".topcrc", MAX_PATH - strlen(path) ); - topcrc = fopen( path, "r" ); - if ( topcrc != NULL && (opts_str = fgets( path, MAX_PATH, topcrc )) ) - get_options_from_string( path ); - } - - // Process environment variable, TOPC_OPTS - if ( opts_str = getenv("TOPC_OPTS") ) - get_options_from_string( opts_str ); - - // Process command line arguments from (argc, argv) from main - get_options(argc, argv); - - if (TOPC_OPT_procgroup[0] == '~') { - char *home = getenv("HOME"); - char *tmp = malloc(strlen(TOPC_OPT_procgroup)+strlen(home)); - sprintf(tmp, "%s%s", home, TOPC_OPT_procgroup+1); - TOPC_OPT_procgroup = tmp; - } - if (TOPC_OPT_aggregated_tasks > 1 && COMM_is_shared_memory() ) { - //Problem is do_task_wrapper, which uses static local variables - // for output buffer. - WARNING("TOPC_OPT_aggregated_tasks > 1 not supported for shared memory.\n" - " Resetting TOPC_OPT_aggregated_tasks from %d to %d."); - TOPC_OPT_aggregated_tasks = 1; - } - - if (TOPC_OPT_safety == SAFETY_TWO_SLAVES) - TOPC_OPT_num_slaves = 2; - if (TOPC_OPT_safety >= SAFETY_ONE_SLAVE) - TOPC_OPT_num_slaves = 1; - - if (TOPC_OPT_help) { - print_help( **argv ); // **argv == command name ($0 on command line) - if( TOPC_OPT_stats ) - print_config_info(); - exit( 0 ); - } - -#ifndef TEST - /*If dist. mem, using p4/MPI convention (procgroup/-p4amslave), not a slave.*/ - if ( has_procgroup_file() - && 0 != strncmp((*argv)[*argc-1], "-p4amslave", 11) ) { - if ( 0 == stat( TOPC_OPT_procgroup, &buf ) ) - TOPC_OPT_pre_extend_procgroup(TOPC_OPT_procgroup, TOPC_OPT_num_slaves, - argc, argv); - else /* The MPI may not be MPINU; MPINU can signal err. if necessary */ - WARNING("procgroup file is: %s", TOPC_OPT_procgroup); - } -#endif -} - -void TOPC_OPT_post_init( int *argc, char ***argv ) { - strip_options(argc, argv); - if (! TOPC_is_master()) { -/* Consider this, or "%.60s connecting ..." in pre_init: */ -# if 0 - if ( TOPC_OPT_stats && ! COMM_is_shared_memory() ) { - char buf[60]; - if ( 0 == gethostname(buf, 60) ) - printf("%.60s connected.\n", buf); - else - printf("hostname: \n"); - } -# endif - return; - } - -#ifndef TEST - // If COMM_init() didn't consume any "-p4pg ...", this will strip it. - TOPC_OPT_post_extend_procgroup(argc, argv); -#endif - /* These things are known best only after initialization. */ - if( TOPC_OPT_stats ) { - int i; - print_config_info(); - printf("number of slaves: %d\n", COMM_node_count() - 1); -#ifdef HAVE_PTHREAD -# ifdef HAVE_PTHREAD_SETCONCURRENCY - if (COMM_is_shared_memory()) { - /* threads: slaves + 1 (no thread should need to context switch) */ - printf("number of threads (master+slaves+stubs): %d\n", - pthread_getconcurrency() ); - } -# endif -#endif - printf("CALLED AS: "); - for (i = 0; saved_args[i] != NULL && i < ARGS_MAX; i++) - printf(" %s", saved_args[i]); - printf("\n\n"); - } -} - -/* Returns info as string terminated by '\n' */ -static char * getcpuinfo( char * buf, char * substr ) { - substr = strstr( buf, substr ); - if ( substr != NULL ) - substr = strstr( substr, ":" ); - if ( substr == NULL ) - substr = ""; - return substr; -} -static void print_cpuinfo () { - char buf[10001]; - char *tmp; - char *model, *bogomips, *cache; - int num; - int fd = open("/proc/cpuinfo", O_RDONLY); - if ( fd != -1 ) { - num = read( fd, buf, 10000 ); - if ( num < 10 ) return; - buf[num] = '\0'; - buf[10000] = '\0'; - model = getcpuinfo( buf, "model name" ); - cache = getcpuinfo( buf, "cache size" ); - bogomips = getcpuinfo( buf, "bogomips" ); - close( fd ); - tmp = strchr( buf, '\n' ); - while ( tmp != NULL ) { - tmp[0] = '\0'; /* Now replace markers by end of string */ - tmp = strchr( tmp + 1, '\n' ); - } - printf("CPU%s (cache%s; bogomips%s)\n", model, cache, bogomips); - } -} -/* Copied from Linux include/asm-* /timex.h */ -// i386 sparc mips powerpc alpha arm -#ifdef __GNUC__ -# if defined(__ppc__) -# define __powerpc__ -# endif -# if defined(_PPC_PRECISE) -# define __ppc64__ -# endif -// In macros below, val is "long long" -# if defined(__i386__) -# define CPU_TYPE "Pentium or Pentium-compatible" -// Macro more conventionally known as rdtscll: -# define set_cycles(val) __asm__ __volatile__ ("rdtsc" : "=A" (val)) -# elif defined(__alpha__) -# define CPU_TYPE "Alpha" -// Only the low 32 bits are available as a continuously counting entity. -# define set_cycles(val) { unsigned int ret; \ - __asm__ __volatile__ ("rpcc %0" : "=r"(ret)); val = ret; } -# elif defined(__ppc64__) -# define CPU_TYPE "PowerPC, 64-bit ?" -# define set_cycles(val) { unsigned long ret; \ - /* MULTIPLYING BY 10 TO GET CLOCK RATE. IS THIS CORRECT? */ \ - /* "?" ADDED TO CPU_TYPE UNTIL THIS IS RESOLVED */ \ - __asm__ __volatile__("mftb %0" : "=r" (ret) : ); val = 10 * ret; } -# elif defined(__powerpc__) || defined(__PPC__) -# define CPU_TYPE "PowerPC, 32-bit" -# define set_cycles(val) val = 0 -# elif defined(__sparc64__) -# define CPU_TYPE "Sparc, 64-bit" -// # define set_cycles(val) { unsigned long ret; \ -// __asm__ __volatile__("rd %%tick, %0" : "=r" (ret)); val = ret; } -# define set_cycles(val) val = 0 -# elif defined(__sparc__) -# define CPU_TYPE "Sparc, 32-bit" -# define set_cycles(val) val = 0 -# else -# define CPU_TYPE "Undetermined CPU" -# define set_cycles(val) val = 0 -# endif -#endif -static void print_cpu_speed() { -#if defined(__GNUC__) - int highest; - int vendor[4]; - vendor[3] = 0; - - print_cpuinfo(); - - { - long long begin; - long long end; - set_cycles(begin); - { - struct timespec req; - req.tv_sec = 0; - req.tv_nsec = 100000000; /* 100 million ns = 0.1s s */ - nanosleep( &req, NULL ); - } - set_cycles(end); - /* Ticks polled over 0.1s; print ticks / 100 M */ - printf("CPU speed: %1.2f GHz (%s)\n", - (float)(end - begin)*10*1e-9, CPU_TYPE); - } - -# if defined(__i386__) -# define cpuid(func,ax,bx,cx,dx) \ - __asm__ __volatile__ ("cpuid": \ - "=a" (ax), "=b" (bx), "=c" (cx), "=d" (dx) : "0" (func)); - cpuid(0,highest,vendor[0],vendor[2],vendor[1]); - printf(" (CPU vendor: %s)\n", (char *)vendor); -# endif -#endif -} - -void TOPC_OPT_finalize( int num_tasks, int num_updates, int num_redos ) { - if( TOPC_OPT_stats ) { - struct rusage buf; - - /* getrusage is BSD */ - if ( -1 == getrusage( RUSAGE_SELF, &buf ) ) - PERROR("getrusage"); - - printf("\nMASTER:\n"); - printf("Maximum resident set size: %ld\n", buf.ru_maxrss); - printf("Page faults: %ld\n", buf.ru_majflt); - printf("Swaps: %ld\n", buf.ru_nswap); - printf("Voluntary context switches: %ld\n", buf.ru_nvcsw); - printf("Involuntary context switches: %ld\n", buf.ru_nivcsw); - print_cpu_speed(); - printf("CPU time (user s): %ld\n", - (long)buf.ru_utime.tv_sec /* + buf.ru_utime.tv_usec/1000000 */); - - if ( 0 ) { /* Wait until TOPC_gather() available to collect stats */ - /* getrusage is BSD */ - if ( -1 == getrusage( RUSAGE_CHILDREN, &buf ) ) - PERROR("getrusage"); - - printf("\nSLAVE:\n"); - printf("Maximum resident set size: %ld\n", buf.ru_maxrss); - printf("Page faults: %ld\n", buf.ru_majflt); - printf("Swaps: %ld\n", buf.ru_nswap); - printf("Voluntary context switches: %ld\n", buf.ru_nvcsw); - printf("Involuntary context switches: %ld\n", buf.ru_nivcsw); - printf("CPU time (user s): %ld\n", - (long)buf.ru_utime.tv_sec /* + buf.ru_utime.tv_usec/1000000 */); - } - - printf("\nParallel computation finished\n"); - system("date"); - system("uptime"); - printf("number of tasks: %d, number of UPDATE's: %d," - " number of REDO's: %d\n", num_tasks, num_redos, num_updates); - printf("Elapsed (wall-clock) time (s): %d\n", - (int)(time(NULL) - start_time) ); - printf("\n"); - - /* We should also call TOPC_master_slave() with do_task() to collect - * slave statistics. Do we need to declare do_task() volatile? - */ - } -} - -char *TOPC_OPT_getpwd( char *buf, size_t size ) { - char *p; - struct stat dotstat, pwdstat; - - if ( (p = getenv ("PWD")) != 0 - && *p == '/' - && stat (p, &pwdstat) == 0 - && stat (".", &dotstat) == 0 - && dotstat.st_ino == pwdstat.st_ino - && dotstat.st_dev == pwdstat.st_dev ) - return strncpy(buf, p, size); - else - return getcwd(buf, size); -} - - -#ifdef TEST -int main( int argc, char **argv ) { - TOPC_OPT_pre_init( &argc, &argv ); - TOPC_OPT_pre_init( &argc, &argv ); - exit(0); -} -#endif diff --git a/topc-2.5.2/src/procgroup.c b/topc-2.5.2/src/procgroup.c deleted file mode 100644 index 95ee5ec4..00000000 --- a/topc-2.5.2/src/procgroup.c +++ /dev/null @@ -1,259 +0,0 @@ -/* Usage: - * char *tmp_procgroup, ***argv; - * int *argc; - * TOPC_pre_extend_procgroup(procgroup_file, num_slaves, argc, argv); - * append to argv: -p4pg tmp_procgroup - * MPI_init( argc, argv ); - * TOPC_post_extend_procgroup(argc, argv); - * - * #define TEST // for standalone test of this file - * - * Extends procgroup file using relative pathnames: - * "-" means pathname of current binary - * relative pathname means relative to pathname of _current_ binary. - * - * NOTE: It the current working directory and pathname of the current - * binary are different, then: - * The procgroup is taken relative to the current working directory. - * The binary of the slave process is found relative to the directory - * of the binary of the master process. - * This makes it easy to set up and use multiple architectures, - * as seen in the following procgroup file. - * local 0 - * alphahost.university.edu 1 ../alpha/a.out - * sparchost.university.edu 1 ../sparc/a.out - * linuxhost.university.edu 1 ../linuxhost/a.out - * This procgroup, and the input files of the program can be placed - * in a working directory, along with a link to the desired master binary. - * PRINCIPLES: - * Let SLAVE_PATH be the path of the slave as given in the procgroup file, - * and let MASTER_DIR be the directory of the master process as invoked on - * on the command line. - * If SLAVE_PATH is an absolute path, TOP-C tries to create a slave - * process from a binary at SLAVE_PATH. - * If SLAVE_PATH is relative and if MASTER_DIR is an absolute path, - * then TOP-C tries to create a slave process from MASTER_DIR/SLAVE_PATH - * If SLAVE_PATH and MASTER_DIR are both relative, TOP-C tries to create - * a slave at $PWD/MASTER_DIR/SLAVE_PATH - * If SLAVE_PATH is `-', then TOP-C tries to ceate a slave at - * MASTER_DIR (if it's absolute), or $PWD/MASTER_DIR (if MASTER_DIR is rel.) - * In all cases, if the procgroup line contains command line arguments, - * those command line arguments are passed to the slave application - * as its first arguments, and any arguments on the master command - * line are appended to the list of arguments. - * EXAMPLE: If you are at /home/gene/proj and execute ../mydir/a.out 17, - * TOP-C will look in /home/gene/proj for a procgroup file, - * and if the procgroup file has: ./subdir/binary -remote - * then TOP-C executes: /home/gene/proj/../mydir/subdir/binary -remote 17 - * NOTE ALSO: - * If is less than number of slaves specified by procgroup, - * then use first from procgroup. - * If is more than number of slaves specified by procgroup, - * then re-use hosts from procgroup in the same order. - * (If procgroup=(local,hostA,hostB), and num_slaves=5, - * use (local,hostA,hostB,hostA,hostB,hostA). - */ - -#include -#include -#include -#include -#include "comm.h" // comm.h also defines HAVE_PTHREAD, etc., by default - -#define MAX_HOSTS 1001 - -static char *tmp_procgroup = NULL; - -#define MAX_LEN 161 - -/* Expand relative pathnames, "./a.out", "../subdir/a.out", and "-" */ -static int expand_path( char *path, char *arg0 ) { - char buf[MAX_LEN], *suffix; - int offset, changed=0; - /* sscanf: whitespace=[ \t\n]*, %s=[^ \t\n]+ (largest matches) */ - sscanf( path, " %*s %*s %n", &offset); - suffix = path + offset; - if (strlen(suffix) >= MAX_LEN) - ERROR("procgroup file: a path is longer than %d", MAX_LEN); - strncpy(buf, suffix, MAX_LEN); - if (buf[strlen(buf)-1] == '\n') - buf[strlen(buf)-1] = '\0'; - if ( buf[1] == '\t' ) /* Replace user tab by canonical whitespace */ - buf[1] = ' '; - if ( (buf[0] == '.' && buf[1] == '/') - || (buf[0] == '.' && buf[1] == '.' && buf[2] == '/') - || (buf[0] == '-' && buf[1] == '\0') - || (buf[0] == '-' && buf[1] == ' ') ) { - changed = 1; - /* ADD: $PWD if arg0 is a relative pathname */ - if ( arg0[0] != '/' ) { - TOPC_OPT_getpwd( suffix, 100 ); - suffix[ strlen(suffix) + 1 ] = '\0'; - suffix[ strlen(suffix) ] = '/'; - suffix += strlen(suffix); - } - /* ADD: arg0 */ - sprintf( suffix, "%s\n", arg0 ); - suffix += strlen(suffix); - /* ADD: add buf (if original path a relative pathname) */ - if ( buf[0] == '.' ) { - /* then backtrack to directory or arg0, and add rel. path, buf */ - while ( *(--suffix) != '/' ) {} - sprintf( suffix+1, "%s\n", buf ); - } - /* ADD: add args of buf (if buf is "- ...") */ - if ( buf[0] == '-' && buf[1] == ' ' ) - sprintf( suffix-1, "%s\n", buf+1 ); - } - return changed; -} - -static void read_and_expand_procgroup - (char *procgroup_file, int num_slaves, char *arg0, - char *hosts[], int *num_hosts, int *is_changed) // last three: output vars -{ - FILE *procfile; - int c; - - *num_hosts = *is_changed = 0; - procfile = fopen(procgroup_file, "r"); - // In options.c, we already verified that procgroup_file exists. - if ( procfile == NULL ) { - perror("TOP-C: read_and_expand_procgroup"); - ERROR("TOP-C: TOPC_OPT_pre_extend_procgroup:" - " Couldn't read procgroup file: %s\n", procgroup_file); - } - c = getc(procfile); - while ( c != EOF - && ((num_slaves == UNINITIALIZED) || (*num_hosts <= num_slaves+1)) ) { - switch ( c ) { - case EOF: - break; - case '\n': - c = getc(procfile); - break; - case '#': - while( (c=getc(procfile)) != '\n' && c != EOF ) {} - break; - case ' ': - while( (c=getc(procfile)) == ' ' ) {} - break; - default: - ungetc( c, procfile ); - hosts[(*num_hosts)++]=fgets( malloc(MAX_LEN+1), MAX_LEN+1, procfile ); - if ( strlen(hosts[(*num_hosts)-1]) >= MAX_LEN ) - ERROR("Line of procgroup file is more than %d characters\n", - MAX_LEN); - if (*num_hosts > MAX_HOSTS) - ERROR("*** Number of hosts in procgroup file(%d) exceeds max (%d)\n" - " Increase procgroup.c:MAX_HOSTS\n", *num_hosts, MAX_HOSTS); - if (expand_path( hosts[(*num_hosts)-1], arg0 )) - *is_changed = 1; - c = getc(procfile); - break; - } // end switch - } // end while - fclose(procfile); -} - -static char *write_tmp_procgroup(char *hosts[], int num_hosts, int num_slaves) -{ - char *outname = malloc(80); - FILE *outfile; - char *str; - int i, j, num; - - sprintf(outname, "%s/procgroup.%d", - ( (str = getenv("TMPDIR")) ? str : "/tmp"), getpid()); - outfile = fopen(outname, "w"); - if ( outfile == NULL ) { - perror("TOP-C: write_tmp_procgroup"); - ERROR("Couldn't create temporary file %s\n" - " Check filesystem and environment variable TMPDIR\n", - outname); - } - for ( i=0, j=0; i<=num_slaves; i++, j++ ) { - if ( j >= num_hosts ) j = 1; - num = fprintf(outfile, "%s", hosts[j]); - if (num != (int)strlen(hosts[j])) { - perror("TOP-C: write_tmp_procgroup"); - ERROR("Couldn't write to %s\n", outname); - } - } - fclose(outfile); - return outname; -} - -static void modify_argc_and_argv(char *new_procgroup, int *argc, char ***argv) -{ - static char **new_argv; - int i; - - // Reserve 3 extra slots for: "-p4pg" NULL - new_argv = malloc( (*argc + 3) * sizeof(char **) ); - for (i = 0; i <= *argc; i++) - new_argv[i] = (*argv)[i]; - new_argv[*argc] = "-p4pg"; - new_argv[*argc + 1] = new_procgroup; - new_argv[*argc + 2] = NULL; - *argv = new_argv; - *argc += 2; -} - -/* In TOPC_OPT_pre_init */ -void TOPC_OPT_pre_extend_procgroup - (char *procgroup_file, int num_slaves, int *argc, char ***argv) -{ - char *hosts[MAX_HOSTS]; - int num_hosts; - int is_changed; - int i; - - if ( num_slaves != UNINITIALIZED - && (num_slaves < 1 || num_slaves > 1000) ) - ERROR("TOP-C: Number of slaves, %d, not in range [1..1000].\n", - num_slaves); - - // hosts, num_hosts and is_changed are output parameters - read_and_expand_procgroup(procgroup_file, num_slaves, (*argv)[0], - hosts, &num_hosts, &is_changed); - if (num_slaves == UNINITIALIZED) - num_slaves = num_hosts - 1; - if ( is_changed || (num_hosts != num_slaves+1) ) - procgroup_file = tmp_procgroup - = write_tmp_procgroup(hosts, num_hosts, num_slaves); - for (i = 0; i < num_hosts; i++) - free(hosts[i]); - if (0 != strncmp(procgroup_file, "./procgroup", 12) - && 0 != strncmp((*argv)[*argc-1], "-p4amslave", 11)) - modify_argc_and_argv(procgroup_file, argc, argv); -} - -void TOPC_OPT_post_extend_procgroup(int *argc, char ***argv) { - if( tmp_procgroup ) { - unlink( tmp_procgroup ); - tmp_procgroup = NULL; - // Maybe MPI_init() wasn't mpinu, and so didn't know about -p4pg flag. - if ( *argc >= 3 && 0 == strncmp((*argv)[*argc-2], "-p4pg", 6) ) { - (*argv)[*argc-2] = NULL; - *argc -= 2; - } - } -} - - -#ifdef TEST -main(int myargc, char *myargv[]) { - /* - char *myargv[1] = {"/myhome/me/mya.out"}; - int myargc = 1; - */ - char buf[100]; - - TOPC_OPT_pre_extend_procgroup("procgroup", 9, &myargc, &myargv); - printf("DONE: %s\n", tmp_procgroup); - system( (sprintf(buf, "cat %s", tmp_procgroup), buf) ); - TOPC_OPT_post_extend_procgroup(); - exit(0); -} -#endif diff --git a/topc-2.5.2/src/sem-pthread.h b/topc-2.5.2/src/sem-pthread.h deleted file mode 100644 index a6001362..00000000 --- a/topc-2.5.2/src/sem-pthread.h +++ /dev/null @@ -1,58 +0,0 @@ - /********************************************************************** - * TOP-C (Task Oriented Parallel C) * - * Copyright (c) 2000 Gene Cooperman * - * and Victor Grinberg * - * * - * This library is free software; you can redistribute it and/or * - * modify it under the terms of the GNU Lesser General Public * - * License as published by the Free Software Foundation; either * - * version 2.1 of the License, or (at your option) any later version. * - * * - * This library is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * - * Lesser General Public License for more details. * - * * - * You should have received a copy of the GNU Lesser General Public * - * License along with this library (see file COPYING); if not, write * - * to the Free Software Foundation, Inc., 59 Temple Place, Suite * - * 330, Boston, MA 02111-1307 USA, or contact Gene Cooperman * - * . * - **********************************************************************/ - -/* Would like to declare: static inline, but not all C compilers accept it */ - -typedef struct { - volatile int val; - pthread_mutex_t mutex; - pthread_cond_t cond; - } sem_t; - -static -int sem_init( sem_t *sem, int ignore, unsigned int val ) { - sem->val = val; - pthread_mutex_init(&sem->mutex, NULL); - pthread_cond_init(&sem->cond, NULL); - return 0; -} - -static -int sem_wait( sem_t *sem ) { - pthread_mutex_lock( &sem->mutex ); - (sem->val)--; - while (sem->val < 0) - pthread_cond_wait(&sem->cond, &sem->mutex); - pthread_mutex_unlock( &sem->mutex ); - return 0; -} - -static -int sem_post( sem_t *sem ) { - int do_signal = 0; - pthread_mutex_lock( &sem->mutex ); - (sem->val)++; - if (sem->val >= 0) do_signal = 1; - pthread_mutex_unlock( &sem->mutex ); - if (do_signal) pthread_cond_signal(&sem->cond); - return 0; -} diff --git a/topc-2.5.2/src/topc.c b/topc-2.5.2/src/topc.c deleted file mode 100644 index 972c3476..00000000 --- a/topc-2.5.2/src/topc.c +++ /dev/null @@ -1,1457 +0,0 @@ - /********************************************************************** - * TOP-C (Task Oriented Parallel C) * - * Copyright (c) 2000-2004 Gene Cooperman * - * and Victor Grinberg * - * * - * This library is free software; you can redistribute it and/or * - * modify it under the terms of the GNU Lesser General Public * - * License as published by the Free Software Foundation; either * - * version 2.1 of the License, or (at your option) any later version. * - * * - * This library is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * - * Lesser General Public License for more details. * - * * - * You should have received a copy of the GNU Lesser General Public * - * License along with this library (see file COPYING); if not, write * - * to the Free Software Foundation, Inc., 59 Temple Place, Suite * - * 330, Boston, MA 02111-1307 USA, or contact Gene Cooperman * - * . * - **********************************************************************/ - -#include -#include // malloc(), atoi() -#include // memcpy(), strlen() -#include // getcwd(), chdir(), sleep() -#include // time() -#include -#include -#include "topc.h" // data structures shared with application -#ifdef __cplusplus -# undef TOPC_master_slave -# undef TOPC_raw_begin_master_slave -#endif -#include "comm.h" // not visible to applic.; shared with communication layer - // comm.h defines HAVE_PTHREAD, etc. - -//Compile-time parameters -// Also: comm.h defines TOPC_MAX_SLAVES -// #define TOPC_MAX_SLAVES 1000 /* Max. number of slaves */ -#define UPDATE_QUEUE_SIZE 200 //Size of update ueue -#define NUM_REUSABLE_IDS 200000000 //Should be >> number of slaves -#define MAX_PATH_LEN 256 //for TOPC_OPT_getpwd() -#define MSG_CACHE_SIZE 5000 //Larger updates are queued - //Models socket buf size of O/S - // (SO_SNDBUF / SO_RCVBUF) -//Only allocated if TOPC_OPT_aggregated_tasks > 1 -// 1<<20 (1 MB) chosen so transfer time larger than gigabit Ethernet latency -// For Fast Ethernet, could set this to only 100 KB -#define AGGREG_TASKS_SIZE 1<<20 - -//For ease of further porting -#ifndef FALSE -enum {FALSE, TRUE}; -#endif - -//Global variables -static int num_slaves; //Total number of nodes less 1 -static int num_idle_slaves; //Slaves currently not doing a task -static int num_dead_slaves; //Slaves w/ broken socket, too slow -static int num_tasks, num_tasks_on_slave, num_redos, num_updates; //Statistics -static int last_task_id; //Last task sent to a slave -static int last_update_id; //Task that caused last update -static int slave_being_checked; //Slave whose reply is being checked -static TOPC_BOOL aggregated_inputs_pending;//used: TOPC_OPT_aggregated_tasks>1 - -//Slave array, allocated on master -struct SLAVE_RECORD { - TOPC_BOOL busy; //Is it doing a task? - TOPC_BOOL dead; //Is slave dead? - int msg_cache_free; //Free bytes in slave's msg_cache - int last_update_seen; //ID of last seen queued update - int task_id; //Task being done - int update_id; //Last update task has seen - int slow_on_task_id; //Which task the slave is slow to do - int timer; //Elapsed time that the slave is slow on the task - TOPC_BUF input; //Task input being processed - TOPC_BUF aggreg_inputs; //Permanent buffer for aggregated task inputs - //submit_task_input() changes this -}; -static struct SLAVE_RECORD *slave_array = NULL; -static size_t slave_array_size; //Number of elements in slave array - -//Globals for shared memory -static TOPC_BOOL is_shared_memory = 0; //Set in TOPC_init() -struct THR_PRIV_DATA { - enum TAG tag; -}; -static struct THR_PRIV_DATA *per_slave_thr_priv = NULL, per_slave; -#define THR_PRIV \ - (is_shared_memory ? per_slave_thr_priv[COMM_rank()] : per_slave) - -/*********************************************************************** - *********************************************************************** - ** MPI tags: (enum TAG) now defined in comm.h - *********************************************************************** - ***********************************************************************/ - - -/*********************************************************************** - *********************************************************************** - ** Printout functions: now defined in comm.h - *********************************************************************** - ***********************************************************************/ - - -/*********************************************************************** - *********************************************************************** - ** TOP-C task and action interfaces (see topc.h) - *********************************************************************** - ***********************************************************************/ - -//User functions return TOPC_ACTION structs by value, so these ID -//codes are used to identify special return values -enum ACTION { - NO_ACTION_ID, REDO_ID, UPDATE_ID, CONTINUE_ID -}; - -TOPC_ACTION NO_ACTION = {NO_ACTION_ID, "NO_ACTION", NULL, 0}; -TOPC_ACTION REDO = {REDO_ID, "REDO", NULL, 0}; -TOPC_ACTION UPDATE = {UPDATE_ID, "UPDATE", NULL, 0}; -//Function to form continuation TOPC_ACTION -TOPC_ACTION CONTINUATION(TOPC_BUF msg) { - TOPC_ACTION action; - action.type = CONTINUE_ID; - action.name = "CONTINUATION"; - action.continuation = msg.data; - action.continuation_size = msg.data_size; - return action; -} - -//Special return values -// NOTE: dummy != NULL, so user TOPC_MSG(NULL,0) not confused with NOTASK -static char dummy[] = "NOTASK"; -TOPC_BUF NOTASK = {dummy, 0}; - -/*********************************************************************** - *********************************************************************** - ** Task and updates are identified by reusable IDs, like PIDs on UNIX - *********************************************************************** - ***********************************************************************/ - -/*********************************************************************** - * Compare IDs with respect to rollover. For ease of initialization, - * a negative value of first argument compares less then anything - */ -static int idcmp(int id1, int id2) { - if (id1 == id2) return 0; - if (id1 < id2 || id1 - id2 > NUM_REUSABLE_IDS / 2) return -1; - return 1; -} - -/*********************************************************************** - * Generate new task ID - */ -static int next_task_id() { - if (++last_task_id == NUM_REUSABLE_IDS) last_task_id = 0; - return last_task_id; -} - - -/*********************************************************************** - *********************************************************************** - ** Synchronization (atomic I/O) and recording shared data page accesse - *********************************************************************** - ***********************************************************************/ - -static volatile TOPC_BOOL user_handles_own_synchronization = FALSE; - -// PAGE_is_up_to_date() - -void TOPC_BEGIN_ATOMIC_READ(int dummy_pagenum) { - if (TOPC_OPT_safety < SAFETY_DFLT_ATOMIC_READ_WRITE) - user_handles_own_synchronization = TRUE; - // PAGE_atomic_read(dummy_pagenum, TOPC_rank()); - COMM_begin_atomic_read(); -} -void TOPC_END_ATOMIC_READ(int dummy_pagenum) { - COMM_end_atomic_read(); -} -// TOPC_ATOMIC_READ(dummy_pagenum) defined in topc.h - -void TOPC_BEGIN_ATOMIC_WRITE(int dummy_pagenum) { - // PAGE_atomic_write(dummy_pagenum, TOPC_rank(), last_update_id); - COMM_begin_atomic_write(); -} -void TOPC_END_ATOMIC_WRITE(int dummy_pagenum) { - COMM_end_atomic_write(); -} -// TOPC_ATOMIC_WRITE(dummy_pagenum) defined in topc.h - -/*********************************************************************** - *********************************************************************** - ** Aggregated tasks - ** Aggregated buffer: BUF1_SIZE | BUF1 | BUF2_SIZE | BUF2 | ... - *********************************************************************** - ***********************************************************************/ - -/*********************************************************************** - * Data structure utilities to marshal an aggregated tasks buffer - * When buffer is complete, the last task must be NOTASK - */ - -//These functions for use by debugger. #define used for efficiency -static size_t AGGREG_TASK_SIZE(size_t size) { - return size + sizeof(size_t); } -static size_t AGGREG_MSG_SIZE(void *input_buf) { - return *(size_t *)(input_buf); } -static void * NEXT_AGGREG_MSG(char * aggreg_buf) { - return aggreg_buf + sizeof(size_t) + AGGREG_MSG_SIZE(aggreg_buf); } -static TOPC_BOOL IS_EMPTY(void *input_buf) { - return *(size_t *)(input_buf) == 0; } - -// AGGREG_TASK_SIZE refers to size of task plus header holding size of task -#define AGGREG_TASK_SIZE(size) (size + sizeof(size_t)) -#define IS_EMPTY(input_buf) ( *(size_t *)(input_buf) == 0 ) -#define AGGREG_MSG_SIZE(input_buf) ( *(size_t *)(input_buf) ) -#define AGGREG_MSG_DATA(input_buf) ( input_buf + sizeof(size_t) ) -#define NEXT_AGGREG_MSG(aggreg_buf) \ - ( aggreg_buf + AGGREG_TASK_SIZE( AGGREG_MSG_SIZE(aggreg_buf) ) ) - -static void init_aggregate_buffer(TOPC_BUF * buf) { - if (buf->data == NULL) // If buffer not yet created - buf->data = malloc(4); // NOTE: if we malloc(0), some O/S return NULL - buf->data_size = 0; -} -// NOTASK.data_size is 0 -static void add_to_aggregate_buffer(TOPC_BUF task, TOPC_BUF * buf) { - char * buf_data = buf->data; - // copy header with size of next task - memcpy(buf_data + buf->data_size, &task.data_size, sizeof(size_t)); - // copy data of next task - if (task.data_size > 0) - memcpy(buf_data + buf->data_size + sizeof(size_t), - task.data, task.data_size); - buf->data_size = buf->data_size + sizeof(size_t) + task.data_size; -} - -/*********************************************************************** - *********************************************************************** - ** Define wrappers for callbacks: - ** Potential uses: protected stack call, task aggregation - ** (much of this is only in experimental version) - *********************************************************************** - ***********************************************************************/ - -/*********************************************************************** - * Define wrappers for callback functions - * do_task_wrapper/COMM_do_task() as wrapper that takes - * task input and repeatedly calls - * application-defined do_task() - * to produce for output.data - */ -static TOPC_BUF (*generate_task_input_orig)(void); -static TOPC_BUF (*do_task_orig)(void *input); -static TOPC_ACTION (*check_task_result_orig)(void *input, void* output); -static void (*update_shared_data_orig)(void *input, void *output); - -static TOPC_BUF generate_task_input_wrapper() { - return (*generate_task_input_orig)(); -} -static TOPC_BUF do_task_wrapper(void *input) { - static TOPC_BUF output = {NULL, 0}; - static int output_realloc_size = 0; - TOPC_BUF tmp; - - if (TOPC_OPT_aggregated_tasks > 1) { - assert( ! IS_EMPTY(input) ); - init_aggregate_buffer(&output); - while ( AGGREG_MSG_SIZE(input) > 0 ) { - // Process current task input - ++num_tasks_on_slave; - tmp = (*do_task_orig)((void *)AGGREG_MSG_DATA((char *)input)); - // output.data must hold current messages and tmp and NOTASK at end - if (output_realloc_size - < output.data_size + AGGREG_TASK_SIZE(tmp.data_size) - + AGGREG_TASK_SIZE(NOTASK.data_size)) { - output_realloc_size = - output.data_size + AGGREG_TASK_SIZE(tmp.data_size) - + AGGREG_TASK_SIZE(NOTASK.data_size); - output.data = realloc(output.data, output_realloc_size); - } - add_to_aggregate_buffer(tmp, &output); - MEM_free(tmp.data); - input = NEXT_AGGREG_MSG((char *)input); - } - add_to_aggregate_buffer(NOTASK, &output); - return output; - } else - return (*do_task_orig)(input); -} -static TOPC_ACTION check_task_result_wrapper(void *input, void *output) { - return (*check_task_result_orig)(input, output); -} -static void update_shared_data_wrapper(void *input, void *output) { - (*update_shared_data_orig)(input, output); -} - -//Application-defined callbacks -//The communication layer may redefine them -// (e.g.: COMM_init() may add another wrapper) -TOPC_BUF (*COMM_generate_task_input)(void) = generate_task_input_wrapper; -TOPC_BUF (*COMM_do_task)(void *input) = do_task_wrapper; -TOPC_ACTION (*COMM_check_task_result)(void *input, void *output) - = check_task_result_wrapper; -void (*COMM_update_shared_data)(void *input, void *output) - = update_shared_data_wrapper; -//Can be called by communication layer -// Assigned to slave_loop() in TOPC_master_slave(). -void (*COMM_slave_loop)(void) = NULL; - - -/*********************************************************************** - *********************************************************************** - ** Dead Slaves (used on master) - *********************************************************************** - ***********************************************************************/ - -// Used only for debugging. -static int debug_num_dead_slaves() { - int i; - int dead_slaves = 0; - for(i = 1; i <= num_slaves; i++) - if (slave_array[i].dead == TRUE) - dead_slaves ++; - return dead_slaves; -} - -/*********************************************************************** - * Do bookkeeping to declare slave as dead - */ -static void slave_is_dead(int rank) { - slave_array[rank].dead = TRUE; - num_dead_slaves++; - if (! slave_array[rank].busy) { - num_idle_slaves--; // A dead idle slave is not really idle - } -} - -/*********************************************************************** - * Apply criteria for declaring if a (possibly slow) slave is dead - * Dead if busy on same task for at least TOPC_OPT_slave_timeout seconds - */ -static TOPC_BOOL is_dead_slave(int rank) { - time_t t; - - if (slave_array[rank].dead) - return TRUE; - // If slave doing task during three rounds of tasks for other slaves - if ((slave_array[rank].task_id < last_task_id - 3 * num_slaves) - || ((slave_array[rank].task_id > last_task_id) && - (slave_array[rank].task_id - < NUM_REUSABLE_IDS + last_task_id - 3 * num_slaves))) { - // And if this task was previously found to be slow - if (slave_array[rank].task_id == slave_array[rank].slow_on_task_id) { - // And if TOPC_OPT_slave_timeout seconds have elapsed - if ( time(&t) - slave_array[rank].timer > TOPC_OPT_slave_timeout ) - return TRUE; // declare slave dead - else return FALSE; // timeout not yet elapsed - } else { - // Else slave_array was slow on previous task, but not on current task - // Note current task and reset timer - slave_array[rank].slow_on_task_id = slave_array[rank].task_id; - slave_array[rank].timer = time(&t); - } - } - return FALSE; -} - -/*********************************************************************** - * Check for new dead slave. A dead slave is newly dead if the busy - * field is still TRUE. Make it dead, change its busy field to FALSE, - * and return it. It is now an old dead slave. - * When this is called, if it finds a new dead slave, that slave - * has its tasks resubmitted elsewhere. - */ -static int check_for_dead_slave() { - int rank; - - for (rank = 1; rank <= num_slaves; rank++) { - if (slave_array[rank].busy == TRUE) { - if (slave_array[rank].dead == FALSE) { - // If a message to slave fails, socket connection must have died - // DO WE WANT TO PING SO OFTEN? SHOULD CHANGE THIS. - if (COMM_send_msg(NULL, 0, rank, PING_TAG) == FALSE - || is_dead_slave(rank)) { - slave_is_dead(rank); - slave_array[rank].busy = FALSE; - return rank; - } - } - // Other parts of code declare a slave dead when we can't send a message. - // We recognize those "new dead slaves" because busy is TRUE. - // Catch such "new" dead slaves here, and report them. - if (slave_array[rank].dead == TRUE) { - slave_array[rank].busy = FALSE; - return rank; - } - } - } - return 0; -} - -/*********************************************************************** - * Check for new dead slave, but only once per round of tasks - * (only once out of every `num_slaves' calls to this routine). - */ -static int new_dead_slave() { - static int counter = -1; - if (counter < 0) - counter = num_slaves; - counter --; - - if (counter < 0) { - int id = check_for_dead_slave(); - assert( num_dead_slaves == debug_num_dead_slaves() ); - if (id) { - fprintf(stderr, "***********************************************\n"); - fprintf(stderr, "************** SLAVE %d HAS DIED **************\n", id); - fprintf(stderr, "***********************************************\n"); - fflush(stderr); // stderr should be unbuffered anyway, but why not - if (num_dead_slaves == num_slaves - 1) - fprintf(stderr, "*** ONE SLAVE LEFT. NO WARNING GIVEN IF IT DIES!\n"); - return id; - } - } - return 0; -} - - -/*********************************************************************** - *********************************************************************** - ** Update queue on master - *********************************************************************** - ***********************************************************************/ - -//Assume update messages are either all short or all long. -//If no update messages pending, all messages are short, -// and msg_cache for each slave has space, then -// immediately broadcast them, using the network as our buffer. -//Otherwise, queue the messages, and then update_slave() sends -// all pending updates to a slave just before sending the -// next task input (whether due to REDO, CONTINUATION, or new task) -//If more slaves return while the master was doing its own update, -// then those slaves will see all updates when the master recognizes them. -//Note that an urgent message (e.g.: SOFT_ABORT), can always be -// probed by slave, since all updates fit in slave msg_cache. - -//Update queue -struct UPDATE_RECORD { - int id; //ID of task that resulted in the update - void *input; //Update information - size_t input_size; - void *output; - size_t output_size; - int slaves_updated; //Number of slaves this update has been sent to -}; -static struct UPDATE_RECORD update_queue[UPDATE_QUEUE_SIZE], - *update_queue_tail, *update_queue_head; - -static void free_input_data(void *ptr) { MEM_free(ptr); } -// More efficient version for now: -#define free_input_data(x) (MEM_free(x)) - -/*********************************************************************** - * Send update message to a given slave - */ -static void send_update(int slave, void *input, size_t input_size, - void *output, size_t output_size) { - if (COMM_send_msg(input, input_size, slave, UPDATE_INPUT_TAG) == FALSE) - slave_is_dead(slave); - else if (COMM_send_msg(output, output_size, slave, UPDATE_OUTPUT_TAG) - == FALSE) - slave_is_dead(slave); -} - -/*********************************************************************** - * Broadcast update message - */ -static void broadcast_update(void *input, size_t input_size, - void *output, size_t output_size) { - int slave; - for (slave = 1; slave <= num_slaves; ++slave) { - if (slave_array[slave].dead == FALSE) { - send_update(slave, input, input_size, output, output_size); - slave_array[slave].msg_cache_free -= - (input_size + output_size + 2*sizeof(enum TAG) + 2*sizeof(input_size)); - } - } -} - -// COULD USE getsockopt(,,SO_RCVBUF,result,&result_size); -// TO GET OR CHANGE DEFAULT SOCKET BUFFER SIZE FOR MORE ACCURACY. -// IF SIZE IS MORE THAN NETWORK BUFFER SIZE, THEN CONSIDER INCREASING -// SO_SNDBUF and SO_RCVBUF. -// THIS COULD ALSO BE USEFUL FOR aggregation FOR DIST. MEMORY. - -static TOPC_BOOL broadcast_will_not_block(int input_size, int output_size) { - int slave; - for (slave = 1; slave <= num_slaves; ++slave) - if (input_size + output_size + 2*sizeof(enum TAG) + 2*sizeof(input_size) - > slave_array[slave].msg_cache_free - && slave_array[slave].busy) - return FALSE; - return TRUE; -} - -/*********************************************************************** - * Find first update that the slave hasn't seen. If there are no - * unseen updates, return value points past the end of the queue - */ -static struct UPDATE_RECORD *find_first_unseen_update(int slave) { - struct UPDATE_RECORD *l, *m, *r, *mm; - int mm_id, last_update_seen = slave_array[slave].last_update_seen; - - l = update_queue_head; - r = update_queue_tail; - if (r < l) r += UPDATE_QUEUE_SIZE; - last_update_seen - = last_update_seen + NUM_REUSABLE_IDS / 2 < update_queue_head->id - ? last_update_seen + NUM_REUSABLE_IDS : last_update_seen; - - while (r > l) { - m = l + (r - l) / 2; - mm = m < update_queue + UPDATE_QUEUE_SIZE ? m : m - UPDATE_QUEUE_SIZE; - mm_id = mm->id + NUM_REUSABLE_IDS / 2 < update_queue_head->id - ? mm->id + NUM_REUSABLE_IDS : mm->id; - if (idcmp(last_update_seen, mm_id) < 0) - r = m; - else - l = m + 1; - } - assert(l == r); - return r < update_queue + UPDATE_QUEUE_SIZE ? r : r - UPDATE_QUEUE_SIZE; -} - -/*********************************************************************** - * Send all necessary updates to a slave. Free memory occupied by - * updates that have been sent to all slaves - */ -static void update_slave(int slave) { - struct UPDATE_RECORD *update; - int slaves_updated; - - //Send all unseen updates to the slave. Increment updated slave - //count for each update. When an update has been sent to all - //slaves, remove it from queue. The removal should only happen at - //the head of the queue, because updates are sent in order - update = find_first_unseen_update(slave); - while (update != update_queue_tail) { - send_update(slave, update->input, update->input_size, update->output, - update->output_size); - slave_array[slave].last_update_seen = update->id; - - slaves_updated = ++update->slaves_updated; - assert(slaves_updated < num_slaves || update == update_queue_head); - - if (++update == update_queue + UPDATE_QUEUE_SIZE) - update = update_queue; - if (slaves_updated == num_slaves) { - free_input_data(update_queue_head->input); - COMM_free_receive_buf(update_queue_head->output); - update_queue_head = update; - } - } - //update_slave() always called when slave finishes task - slave_array[slave].msg_cache_free = MSG_CACHE_SIZE; -} - -/*********************************************************************** - * Queue an update for being sent to all slaves eventually. The - * update queue must have space on it - */ -static void queue_update(void *input, size_t input_size, - void *output, size_t output_size) { - int slave; - static int id = 0; - - update_queue_tail->id = id++; - if (id == NUM_REUSABLE_IDS) - id = 0; - update_queue_tail->input = input; - update_queue_tail->input_size = input_size; - update_queue_tail->output = output; - update_queue_tail->output_size = output_size; - update_queue_tail->slaves_updated = 0; - if (++update_queue_tail == update_queue + UPDATE_QUEUE_SIZE) - update_queue_tail = update_queue; - if (update_queue_head == update_queue_tail) - ERROR("Update queue overflow;\n" - " Recompile TOP-C with larger topc.c:UPDATE_QUEUE_SIZE"); - - for (slave = 1; slave <= num_slaves; ++slave) - if (! slave_array[slave].busy) - update_slave(slave); -} - -/*********************************************************************** - * Schedule global update. Long updates are queued. Short updates - * are only queued if there is something on the queue already, to make - * sure updates are not reordered. Unless update is queued, frees - * memory - */ -static void schedule_update(int id, void *input_data, size_t input_size, - void *output_data, size_t output_size) { - if (broadcast_will_not_block(input_size, output_size) - && update_queue_head == update_queue_tail) { - broadcast_update(input_data, input_size, output_data, output_size); - free_input_data(input_data); - COMM_free_receive_buf(output_data); - } - else - queue_update(input_data, input_size, output_data, output_size); - last_update_id = id; -} - -/*********************************************************************** - *********************************************************************** - ** Tracing - *********************************************************************** - ***********************************************************************/ - -/*********************************************************************** - * Default: trace msg; value of NULL: print nothing - * User can redefine initial binding to print buffer-specific tracing msg - */ - -static void do_nothing() {} -void (*TOPC_OPT_trace_input)() = do_nothing; /* args: (void *input) */ -void (*TOPC_OPT_trace_result)() = do_nothing; - /* args: (void *input, void *output) */ - -static void trace_input(void *input, int slave) { - if (TOPC_OPT_trace == FALSE) return; - else if (input == NOTASK.data) { printf("master: NOTASK\n"); return; } - else { printf("master -> %d: ", slave); - if (TOPC_OPT_trace == 2 && *TOPC_OPT_trace_input) - (*TOPC_OPT_trace_input)(input); - printf("\n"); - fflush(stdout); - } -} -static void trace_result(int slave, void *input, void *output) { - if (TOPC_OPT_trace == FALSE) return; - else { printf("%d -> master: ", slave); - if (TOPC_OPT_trace == 2 && TOPC_OPT_trace_result) - (*TOPC_OPT_trace_result)(input, output); - printf("\n"); - fflush(stdout); - } -} -static void trace_action(TOPC_ACTION action, void *data, void *out, int slave) { - if (TOPC_OPT_trace == FALSE) return; - if (action.type == REDO_ID) { printf("REDO: "); trace_input(data, slave); } - else if (action.type == UPDATE_ID) - { printf(" UPDATE: "); - if (TOPC_OPT_trace == 2) - (*TOPC_OPT_trace_result)(data, out); - printf("\n"); - } - else if (action.type == CONTINUE_ID) - { printf(" CONTINUATION: "); trace_input(data, slave); } -} - -/*********************************************************************** - *********************************************************************** - ** Master-slave processing - *********************************************************************** - ***********************************************************************/ - -/*********************************************************************** - * Slave processing loop (slave) - */ -static void slave_loop() { - enum TAG tag; - void *input = NULL, *old_input, *output; - size_t input_size, output_size; - TOPC_BUF result = NOTASK; - - if (!is_shared_memory) /* is_shared_memory inited to 0, reset on master */ - num_tasks = num_tasks_on_slave = num_updates = 0; - for (;;) { - old_input = input; - input = NULL; /* Tell COMM layer to provide buffer */ - COMM_receive_msg(&input, &input_size, NULL, &tag); - // result.data could point into old_input. Now safe to free old_input. - if (old_input) COMM_free_receive_buf(old_input); - /* safe to free old result upon seeing new input from master */ - /* but if TOPC_OPT_aggregated_tasks > 1, result was static buffer */ - if (result.data != NOTASK.data && TOPC_OPT_aggregated_tasks <= 1) { - MEM_free(result.data); - result = NOTASK; - } - /* Some compilers don't like this: THR_PRIV.tag = tag; */ - if (is_shared_memory) per_slave_thr_priv[COMM_rank()].tag = tag; - else per_slave.tag = tag; - switch (tag) { - case UPDATE_INPUT_TAG: - output = NULL; /* Tell COMM layer to provide buffer */ - COMM_receive_msg(&output, &output_size, NULL, &tag); - if (tag != UPDATE_OUTPUT_TAG) - ERROR("Received %d instead of UPDATE_OUTPUT_TAG"); - - if (!is_shared_memory) - ++num_updates; - (*COMM_update_shared_data)(input, output); - // malloc(0) can return NULL instead of a 0-length buffer - if (output) COMM_free_receive_buf(output); - break; - - case TASK_INPUT_TAG: - case REDO_INPUT_TAG: - case CONTINUATION_INPUT_TAG: - if (!is_shared_memory) - ++num_tasks; - COMM_is_abort_pending = 0;//Turn off aborts before new task, REDO, or CONT - // NOTE: result.data can be ptr into buffer for input - result = (*COMM_do_task)(input); - if (TOPC_OPT_aggregated_tasks <= 1) - MEM_register_buf(result.data); - COMM_send_msg(result.data, result.data_size, 0, SLAVE_REPLY_TAG); - break; - - case END_MASTER_SLAVE_TAG: - /* Last chance to free up result from last TASK_INPUT_TAG */ - COMM_free_receive_buf(input); - /* Flush user prints on slave, or master may exit before they're seen */ - fflush(stdout); fflush(stderr); - return; - - case PING_TAG: - break; - - case CHDIR_TAG: - if (0 != chdir((char *)input)) - WARNING("SLAVE %d: Couldn't change directory to:\n %s", - TOPC_rank(), (char *)input); - break; - - /* SLAVE_WAIT_TAG now obsolete; Remove in next version. */ - case SLAVE_WAIT_TAG: - sleep(*(int *)input); - break; - - default: - ERROR("Received invalid tag %d", tag); - } - } -} - -/*********************************************************************** - * Find available slave. Should only be called when it's known that - * there is one (master) - */ -static int find_available_slave() { - static int last_slave = 0; //Slave to which a task was sent last - int i; - - //Loop starts where we left off last time, to spread the load evenly - //across all slaves - for (i = 0; i < num_slaves; ++i) { - if (++last_slave > num_slaves) last_slave = 1; - if ( !slave_array[last_slave].busy && !slave_array[last_slave].dead ) - break; - } - assert(!slave_array[last_slave].busy); - return last_slave; -} - -/*********************************************************************** - * Write barrier: Wait for all slaves to finish tasks (master) - */ -static void wait_for_all_slaves() { - int rank = 1; - for (rank = 1; rank <= num_slaves; rank++) { - if (slave_array[rank].busy) - COMM_probe_msg_blocking(rank); - } -} - -/*********************************************************************** - * Send task input, REDO, or CONTINUATION to slave (master) - */ -static void send_task_input(int slave, TOPC_BUF input, enum TAG tag) { - if ( TOPC_OPT_aggregated_tasks > 1 ) - assert( input.data_size == 0 || AGGREG_MSG_SIZE(input.data) > 0 ); - //Send all pending updates to the slave - update_slave(slave); - - //Record task information and send the task - slave_array[slave].busy = TRUE; - //gdc - incrementing task_id here means REDO and CONTINUATION also get - // new task_id's. Is this the desired behavior? - slave_array[slave].task_id = next_task_id(); - slave_array[slave].update_id = last_update_id; - if (COMM_send_msg(input.data, input.data_size, slave, tag) == FALSE) - slave_is_dead(slave); -} - -/*********************************************************************** - * Receive and process output of a slave computation (master) - */ -static void receive_task_output() { - TOPC_ACTION action; - TOPC_BUF msg_buf; - void *output = NULL; // ptr to data of a message - size_t output_size; - int slave; - enum TAG tag; - // THESE NEXT USED ONLY if TOPC_OPT_aggregated_tasks > 1 - char *input_buf; // ptr to next message of input - char *output_buf; // ptr to next message of output - void *output_orig; // ptr to all messages received by COMM_receive_msg - - // Get a message: - // Ignore incomplete messages (COMM_receive_msg() == FALSE) - // If received from slave that is dead, ignore it (MAYBE FREE output?) - do { - while (COMM_receive_msg(&output, &output_size, &slave, &tag) == FALSE) - /* no body */; - } while ( slave_array[slave].dead == TRUE ); - if ( tag != SLAVE_REPLY_TAG ) { - printf("TOP-C: internal error: tag != SLAVE_REPLY_TAG\n");fflush(stdout); - exit(1); - } - - if (TOPC_OPT_aggregated_tasks > 1) { - input_buf = slave_array[slave].aggreg_inputs.data; - assert( ! IS_EMPTY(input_buf ) ); - if ( IS_EMPTY(input_buf) ) { - ++num_idle_slaves; - return; - } - output_buf = output; - output_orig = output; - } - - NEXT_AGGREG_TASK: - // Now call check_task_result: - slave_being_checked = slave; - if (TOPC_OPT_aggregated_tasks > 1) { - slave_array[slave].input.data_size = AGGREG_MSG_SIZE(input_buf); - slave_array[slave].input.data = AGGREG_MSG_DATA(input_buf); - input_buf = NEXT_AGGREG_MSG(input_buf); - output = AGGREG_MSG_DATA(output_buf); - output_buf = NEXT_AGGREG_MSG(output_buf); - } - - trace_result(slave, slave_array[slave].input.data, output); - action = (*COMM_check_task_result)(slave_array[slave].input.data, output); - - if (TOPC_OPT_aggregated_tasks > 1 - && action.type != NO_ACTION_ID) { - printf("TOPC_OPT_aggregated_tasks > 1; task action wasn't NO_ACTION\n"); - printf("TOP-C doesn't yet implement this case for aggregated tasks.\n"); - fflush(stdout); - exit(1); - } - slave_being_checked = 0; - - //Take required action - switch (action.type) { - case NO_ACTION_ID: - if (TOPC_OPT_aggregated_tasks <= 1) { - // If TOPC_OPT_aggregated_tasks > 1, do this just before returning - slave_array[slave].busy = FALSE; - ++num_idle_slaves; - COMM_free_receive_buf(output); - free_input_data(slave_array[slave].input.data); - } - break; - - case REDO_ID: - trace_action(action, slave_array[slave].input.data, output, slave); - COMM_free_receive_buf(output); - msg_buf.data = slave_array[slave].input.data; - msg_buf.data_size = slave_array[slave].input.data_size; - send_task_input(slave, msg_buf, REDO_INPUT_TAG); - ++num_redos; - break; - - case CONTINUE_ID: - trace_action(action, action.continuation, output, slave); - COMM_free_receive_buf(output); - msg_buf.data = action.continuation; - msg_buf.data_size = action.continuation_size; - send_task_input(slave, msg_buf, CONTINUATION_INPUT_TAG); - break; - - case UPDATE_ID: - trace_action(action, slave_array[slave].input.data, output, slave); - slave_array[slave].busy = FALSE; - ++num_idle_slaves; - // If shared memory, default is that UPDATE acts as write barrier - if ( is_shared_memory && ! user_handles_own_synchronization ) - wait_for_all_slaves(); - // Call application callback on master - (*COMM_update_shared_data)(slave_array[slave].input.data, output); - if ( is_shared_memory ) free_input_data(slave_array[slave].input.data); - else schedule_update( slave_array[slave].task_id, - slave_array[slave].input.data, - slave_array[slave].input.data_size, - output, output_size); - ++num_updates; - break; - - default: - ERROR("check_task_result() returned invalid action %d", action.type); - } - - if (TOPC_OPT_aggregated_tasks > 1) { - if (! IS_EMPTY(input_buf)) - goto NEXT_AGGREG_TASK; - else { - assert( IS_EMPTY(output_buf) ); - COMM_free_receive_buf(output_orig); - slave_array[slave].busy = FALSE; - ++num_idle_slaves; - } - } -} - -/*********************************************************************** - * Submit task for dispatching to a slave. Returns FALSE only when no - * slaves are busy, so there's no chance of getting more tasks from - * application code (master) - */ -static void wait_until_an_idle_slave(void); -static TOPC_BOOL submit_task_input(TOPC_BUF input) { - static int num_inputs = 0; - static TOPC_BUF aggreg_tasks = {NULL, 0}; - static int slave = 1; - int size_for_new_input // leaving space for final NOTASK) - = AGGREG_TASK_SIZE(input.data_size) - + AGGREG_TASK_SIZE(NOTASK.data_size); - - if (TOPC_OPT_aggregated_tasks > 1 && aggreg_tasks.data == NULL) - aggreg_tasks.data = malloc(AGGREG_TASKS_SIZE); - - // Don't try to send messages overflowing AGGREG_TASKS_SIZE - if (TOPC_OPT_aggregated_tasks > 1 - && aggreg_tasks.data_size + size_for_new_input >= AGGREG_TASKS_SIZE) { - if (aggreg_tasks.data_size > 0 && input.data != NOTASK.data) { - submit_task_input(NOTASK); // submit previous tasks - assert(aggreg_tasks.data_size == 0); - wait_until_an_idle_slave(); // and then continue with current task - } - // But if only one message, and it's more than AGGREG_TASKS_SIZE, realloc - if ( size_for_new_input >= AGGREG_TASKS_SIZE ) - aggreg_tasks.data = realloc(aggreg_tasks.data, size_for_new_input); - } - - // MAYBE SHOULD MOVE new_dead_slave() LOGIC FROM wait_until_an_idle_slave - // TO HERE. OR AT LEAST wait_until_an_idle_slave SHOULD CHECK - // EVEN WHEN MANY IDLE SLAVES. ALSO CHECK BEFORE TERMINATION OF PAR. - assert( num_idle_slaves > 0 ); - slave = find_available_slave(); - // trace_input must come after receive_task_output() - if (TOPC_OPT_aggregated_tasks <= 1) - trace_input(input.data, slave); - - if (TOPC_OPT_aggregated_tasks > 1) { - trace_input(input.data, -1); - add_to_aggregate_buffer(input, &aggreg_tasks); - if (input.data != NOTASK.data) { - num_inputs++; - free_input_data(input.data); - } - if (num_inputs >= TOPC_OPT_aggregated_tasks) - add_to_aggregate_buffer(NOTASK, &aggreg_tasks); - // If NOTASK or if have our quota of aggregated tasks, then submit - // If neither, then return FALSE now - if (input.data != NOTASK.data - && num_inputs < TOPC_OPT_aggregated_tasks) { - ++num_tasks; - aggregated_inputs_pending = TRUE; - return FALSE; - } - // Okay, we've got all the tasks, and we'll be sending them out. - if (TOPC_OPT_trace != FALSE) { - printf("master -> %d\n", slave); - fflush(stdout); - } - //Copy from application space to TOP-C space - { - void * tmp = slave_array[slave].aggreg_inputs.data; - slave_array[slave].aggreg_inputs.data = aggreg_tasks.data; - slave_array[slave].aggreg_inputs.data_size = aggreg_tasks.data_size; - aggreg_tasks.data = tmp; - if ( aggreg_tasks.data == NULL ) - aggreg_tasks.data = malloc(AGGREG_TASKS_SIZE); - slave_array[slave].input = slave_array[slave].aggreg_inputs; - // Reset aggreg_tasks for next call - num_inputs = 0; - init_aggregate_buffer(&aggreg_tasks); - } - } else { - //Copy from application space to TOP-C space - slave_array[slave].input.data = input.data; - slave_array[slave].input.data_size = input.data_size; - } - - send_task_input(slave, slave_array[slave].input, TASK_INPUT_TAG); - --num_idle_slaves; - ++num_tasks; - aggregated_inputs_pending = FALSE; - return TRUE; -} - -/*********************************************************************** - * Receive and process result = (input,output) of a slave computation (master) - */ -static void wait_until_an_idle_slave() { - //NOTE: receive_task_output() blocking due to call to COMM_receive_msg(). - while (num_idle_slaves == 0) { - int id; - receive_task_output(); - // If idle slave available, move task of dead slave to idle slave - if (! is_shared_memory && num_idle_slaves > 0) - if ( (id = new_dead_slave()) != 0 ) { - submit_task_input(slave_array[id].input); - if (TOPC_OPT_aggregated_tasks > 1) - submit_task_input(NOTASK); // Force this to be sent now. - } - } - assert( num_idle_slaves > 0 ); -} - -/*********************************************************************** - * Initialize master (master) - */ -static void master_init() { - int slave; - - //Initialize statistics and run parameters - num_tasks = num_tasks_on_slave = num_redos = num_updates = 0; - num_idle_slaves = num_slaves = COMM_node_count() - 1; - num_dead_slaves = 0; //All slaves initially assumed to be alive. - last_task_id = -1; //No last task ID - last_update_id = -1; //No updates seen so far - slave_being_checked = 0; //Not inside check_task_result() - - //Allocate and initialize slave array - if (slave_array && (signed int)slave_array_size != num_slaves + 1) { - free(slave_array); - slave_array = NULL; - if (is_shared_memory && per_slave_thr_priv) { - free(per_slave_thr_priv); - per_slave_thr_priv = NULL; - } - } - if (!slave_array) { - slave_array_size = num_slaves + 1; - slave_array = calloc(slave_array_size, sizeof(struct SLAVE_RECORD)); - if (slave_array == NULL) ERROR("No memory for process table"); - } - for (slave = 1; slave <= num_slaves; ++slave) { - slave_array[slave].last_update_seen = -1; //Seen none yet - slave_array[slave].busy = FALSE; - slave_array[slave].dead = FALSE; - slave_array[slave].task_id = -1; - slave_array[slave].slow_on_task_id = -1; - slave_array[slave].timer = 0; - slave_array[slave].msg_cache_free = MSG_CACHE_SIZE; - } - - //Thread private values for do_task() on slave in shared memory - if (is_shared_memory && !per_slave_thr_priv) { - per_slave_thr_priv = calloc(num_slaves+1, sizeof(struct THR_PRIV_DATA)); - if (per_slave_thr_priv == NULL) ERROR("No memory for THR_PRIV_DATA"); - } - - //Initialize update queue - update_queue_head = update_queue_tail = update_queue; -} - -/*********************************************************************** - * Force slaves to change to same directory as master (ignore if no such dir) - */ -static void master_slave_chdir() { - if ( ! COMM_initialized() ) - ERROR("master_slave_chdir() called before TOPC_init()"); - // If not shared memory, ask slave to change to same directory as master - if ( ! COMM_is_shared_memory() ) { - if (TOPC_is_master()) { - int slave; - char cwd[MAX_PATH_LEN]; - - TOPC_OPT_getpwd(cwd, MAX_PATH_LEN); - cwd[MAX_PATH_LEN-1] = '\0'; - // Emulate master side of master_slave loop - for (slave = 1; slave <= num_slaves; ++slave) { - if (slave_array[slave].dead == FALSE) { - COMM_send_msg(cwd, 1+strlen(cwd), slave, CHDIR_TAG); - COMM_send_msg(NULL, 0, slave, END_MASTER_SLAVE_TAG); - } - } - } - // each slave sees CHDIR_TAG, END_MASTER_SLAVE_TAG (then exits slave loop) - else slave_loop(); - } -} - -/*********************************************************************** - *********************************************************************** - ** Interface (public) functions - *********************************************************************** - ***********************************************************************/ - -/*********************************************************************** - * Get node count (pass to comm layer) - */ -int TOPC_node_count() { - return COMM_node_count(); -} - -/*********************************************************************** - * Get number of slaves - */ -int TOPC_num_slaves() { - return COMM_node_count() - 1; -} - -/*********************************************************************** - * Get number of slaves - */ -int TOPC_num_idle_slaves() { - if (COMM_rank() == 0) - return num_idle_slaves; - else { - ERROR("TOPC_num_idle_slaves: can only be called on master"); - return -1; // eliminate compiler warning - } -} - -/*********************************************************************** - * Get rank of this node (pass to comm layer) - */ -int TOPC_rank() { - return COMM_rank(); -} - -/*********************************************************************** - * Figure out who is the master - */ -TOPC_BOOL TOPC_is_master() { - return COMM_rank() == 0; -} - -/*********************************************************************** - * Initialize TOP-C and COMM (MPI, etc.) (both master and slave) - */ - -void TOPC_init(int *argc, char ***argv) { - void *tmp; - - errno = 0; - tmp = malloc(1000); - if (tmp == NULL && errno != 0) { - perror("TOP-C initialization:"); - if (errno == ENOMEM) - printf("This can happen if your application dynamically OR statically\n" - " allocates a lot of memory. For example,\n" - " char *x[100000000];\n" - " might cause this error, depending on your swap size.\n"); - exit(1); - } - else - free(tmp); - - // Get --TOPC options; In distributed memory, this is also called on slaves. - TOPC_OPT_pre_init( argc, argv ); - - // Spawn slaves - COMM_init(argc, argv); - - is_shared_memory = COMM_is_shared_memory(); - if (TOPC_is_master()) master_init(); - if (!TOPC_is_master() && TOPC_OPT_slave_wait > 0 ) - sleep(TOPC_OPT_slave_wait); - master_slave_chdir(); // Place slaves in same directory as master - - // This strips away TOPC options, so they are invisible to application - TOPC_OPT_post_init( argc, argv ); -} - -/*********************************************************************** - * Shutdown TOP-C and MPI (both master and slave) - */ -void TOPC_finalize() { - if ( TOPC_is_master() ) - TOPC_OPT_finalize(num_tasks, num_redos, num_updates); - COMM_finalize(); -} - -/*********************************************************************** - * Was the shared memory up to date? Should only be called from within - * check_task_result() - */ -TOPC_BOOL TOPC_is_up_to_date() { - int cmp; - - if (slave_being_checked == 0) - ERROR("TOPC_is_up_to_date() called from outside of check_task_result()"); - - cmp = idcmp(slave_array[slave_being_checked].update_id, last_update_id); - assert(cmp <= 0); - return cmp == 0; -} - -/*********************************************************************** - * Is this a REDO or CONTINUATION? Should only be called from within - * do_task() - */ -TOPC_BOOL TOPC_is_REDO(void) { - if (TOPC_is_master()) - ERROR("TOPC_is_REDO() called from outside of do_task()"); - return THR_PRIV.tag == REDO_INPUT_TAG; -} -TOPC_BOOL TOPC_is_CONTINUATION(void) { - if (TOPC_is_master()) - ERROR("TOPC_is_CONTINUATION() called from outside of do_task()"); - return THR_PRIV.tag == CONTINUATION_INPUT_TAG; -} - -/*********************************************************************** - * Parallel execution. This function is called on both master and - * slave, and executes the parallel code supplied in the form of four - * callback routines (both master and slave) - */ -void TOPC_master_slave( - TOPC_BUF (*generate_task_input_)(void), - TOPC_BUF (*do_task_)(), /* args: (void *input) */ - TOPC_ACTION (*check_task_result_)(), /* args: (void *input, void *output) */ - void (*update_shared_data_)() /* args: (void *input, void *output) */ -) { - TOPC_BUF input; - int slave; - - //Used in calls to COMM_is_on_stack() - //Must mark a point on stack before calls to do_task, generate_task_input - //Beware of segmented memory models, where pointer comparisons in different - // segments may not work as expected - COMM_stack_bottom = &input; - - if (!COMM_initialized()) - ERROR("TOPC_master_slave called before TOPC_init()"); - - //Create buffers for aggregated tasks - if (TOPC_OPT_aggregated_tasks > 1) - for (slave = 1; slave <= num_slaves; ++slave) { - slave_array[slave].aggreg_inputs.data_size = 0; // no aggreg tasks yet - slave_array[slave].aggreg_inputs.data = malloc(AGGREG_TASKS_SIZE); - } - - //Store callbacks into global variables. If we want to support - // recursion these need to go on a stack - // xxx_orig() is called by COMM_xxx for xxx a callback function. - generate_task_input_orig = generate_task_input_; - do_task_orig = do_task_; - check_task_result_orig = check_task_result_; - update_shared_data_orig = update_shared_data_; - COMM_slave_loop = slave_loop; // needed for pthreads/SMP COMM layer - - //Master loop --- heart of the TOP-C algorithm - if ( TOPC_is_master() ) { - while (1) { - wait_until_an_idle_slave(); // And process any pending slave replies - input = (*COMM_generate_task_input)(); - if (input.data != NOTASK.data) { - MEM_register_buf(input.data); - submit_task_input(input); // lower num_idle_slaves - } else if (aggregated_inputs_pending) { - submit_task_input(NOTASK); // even by sending pending inputs - } else { // or else insure progress condition - if (num_idle_slaves + num_dead_slaves < num_slaves) - receive_task_output(); // by blocking until slave reply - else break; - } - } // termination condition: _after_ all slaves idle, next input was NOTASK - assert( (input.data == NOTASK.data) - && (num_idle_slaves + num_dead_slaves == num_slaves)); - - //Check if user has not supplied any tasks for this run - if (num_tasks == 0) - WARNING("GenerateTaskInput() returned null input on first invocation"); - - for (slave = 1; slave <= num_slaves; slave++) { - update_slave(slave); // Needed in case we call TOPC_master_slave again. - if (TOPC_OPT_aggregated_tasks > 1) { - slave_array[slave].aggreg_inputs.data_size = 0; - free(slave_array[slave].aggreg_inputs.data); - slave_array[slave].aggreg_inputs.data = NULL; - } - if (COMM_send_msg(NULL, 0, slave, END_MASTER_SLAVE_TAG) == FALSE) - slave_is_dead(slave); - } - } - - //Slave loop - else slave_loop(); -} - -/*********************************************************************** - *********************************************************************** - ** Soft abort - *********************************************************************** - ***********************************************************************/ -void TOPC_abort_tasks() { - if (!TOPC_is_master()) - ERROR("TOPC_abort_tasks called on a slave"); - if (TOPC_OPT_safety < SAFETY_NO_ABORT_TASKS) - COMM_soft_abort(); -} - -/* What about in UpdateSharedData() on master? */ -/* Should we restrict it to is_in_do_task, and add static version in topc.c? */ -TOPC_BOOL TOPC_is_abort_pending() { - if (TOPC_is_master()) - WARNING("TOPC_is_abort_pending: called on master; result not useful"); - return COMM_is_abort_pending; -} - -/*********************************************************************** - *********************************************************************** - ** Alternate TOPC_raw master-slave interface: - ** - ** The idea is that a traditional generate_task_input() is a kind of - ** iterator that needs to be provided by application code. However, - ** sometimes the original sequential code produces task inputs - ** inside of complicated nested loops. In such cases, it is - ** difficult to create a corresponding iterator (and co-routines or - ** threads would in fact be the ideal language construct). - ** - ** To get around this, we replace a single call to master_slave() by: - ** TOPC_raw_begin_master(do_task, check_task_result, update_shared_data) - ** TOPC_raw_submit_task_input(input) - ** TOPC_raw_wait_for_task_result() - ** TOPC_raw_end_master() - ** - ** The application can then call submit_task_input() repeatedly with - ** the new task inputs, before completing the computation by a call - ** to TOPC_end_master_slave(). - ** - ** Slave only calls TOPC_raw_begin_master_slave() and - ** TOPC_raw_end_master_slave(), whereas slave loop is in the former, - ** and the latter does nothing - *********************************************************************** - ***********************************************************************/ - -/*********************************************************************** - * Start parallel execution on master - */ -void TOPC_raw_begin_master_slave( - TOPC_BUF (*do_task_)(), /* args: (void *input) */ - TOPC_ACTION (*check_task_result_)(), /* args: (void *input, void *output) */ - void (*update_shared_data_)() /* args: (void *input, void *output) */ -) { - int stack_marker; - int slave; - - //Used in calls to COMM_is_on_stack() - //Must mark a point on stack before calls to do_task - //Beware of segmented memory models, where pointer comparisons in different - // segments may not work as expected - COMM_stack_bottom = &stack_marker; - - if (!COMM_initialized()) - ERROR("TOPC_raw_begin_master_slave called before TOPC_init()"); - - //Create buffers for aggregated tasks - if (TOPC_OPT_aggregated_tasks > 1) - for (slave = 1; slave <= num_slaves; ++slave) { - slave_array[slave].aggreg_inputs.data_size = 0; // no aggreg tasks yet - slave_array[slave].aggreg_inputs.data = malloc(AGGREG_TASKS_SIZE); - } - - // xxx_orig() is called by COMM_xxx for xxx a callback function. - do_task_orig = do_task_; - check_task_result_orig = check_task_result_; - update_shared_data_orig = update_shared_data_; - COMM_slave_loop = slave_loop; // needed for pthreads/SMP COMM layer - - if (!TOPC_is_master()) - slave_loop(); -} - -/*********************************************************************** - * End parallel execution on master - */ -void TOPC_raw_end_master_slave() { - int slave; - - if (TOPC_is_master()) { - if (num_tasks == 0) - WARNING("TOPC_raw_submit_task_input() never called\n" - " called (or returned NOTASK)."); - if (aggregated_inputs_pending) { - if (num_idle_slaves == 0) - receive_task_output(); - assert(num_idle_slaves > 0); - submit_task_input(NOTASK); - } - while (num_idle_slaves + num_dead_slaves < num_slaves) - receive_task_output(); - - for (slave = 1; slave <= num_slaves; ++slave) { - if (slave_array[slave].dead == FALSE) { - update_slave(slave); //Needed in case we call TOPC_master_slave again. - if (COMM_send_msg(NULL, 0, slave, END_MASTER_SLAVE_TAG) == FALSE) - slave_is_dead(slave); - } - if (TOPC_OPT_aggregated_tasks > 1) { - slave_array[slave].aggreg_inputs.data_size = 0; - free(slave_array[slave].aggreg_inputs.data); - slave_array[slave].aggreg_inputs.data = NULL; - } - } - } -} - -/*********************************************************************** - * Submit task input to TOPC for parallel execution - */ -void TOPC_raw_submit_task_input(TOPC_BUF input) { - static int is_warned = 0; - if (TOPC_is_master() && input.data != NOTASK.data) { - /* argument, input, is result of TOPC_MSG/TOPC_MSG_PTR */ - MEM_register_buf(input.data); - wait_until_an_idle_slave(); - submit_task_input(input); - } else if (!TOPC_is_master() && !is_warned) { - is_warned = 1; - WARNING("TOPC_raw_submit_task_input() called from slave.\n" - " Sample code showing correct usage:\n" - "*** TOPC__raw_begin_master_slave(...);\n" - "*** if ( TOPC_is_master() ) {\n" - "*** ... TOPC_raw_submit_task_input(...) ...\n" - "*** }\n" - "*** TOPC_raw_end_master_slave()\n"); - } -} - -/*********************************************************************** - * If pending task exists, wait for it, call CheckTaskResult() and return true - * If no pending task exists, return false - */ -TOPC_BOOL TOPC_raw_wait_for_task_result() { - if (num_idle_slaves < num_slaves) { - do { - receive_task_output(); - } while (COMM_probe_msg() || num_idle_slaves == 0); - // NOTE: COMM_probe_msg() is non-blocking. - return TRUE; - } - else return FALSE; -} diff --git a/topc-2.5.2/src/topc.h b/topc-2.5.2/src/topc.h deleted file mode 100644 index 18254e5b..00000000 --- a/topc-2.5.2/src/topc.h +++ /dev/null @@ -1,360 +0,0 @@ - /********************************************************************** - * TOP-C (Task Oriented Parallel C) * - * Copyright (c) 2000 Gene Cooperman * - * and Victor Grinberg * - * * - * This library is free software; you can redistribute it and/or * - * modify it under the terms of the GNU Lesser General Public * - * License as published by the Free Software Foundation; either * - * version 2.1 of the License, or (at your option) any later version. * - * * - * This library is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * - * Lesser General Public License for more details. * - * * - * You should have received a copy of the GNU Lesser General Public * - * License along with this library (see file COPYING); if not, write * - * to the Free Software Foundation, Inc., 59 Temple Place, Suite * - * 330, Boston, MA 02111-1307 USA, or contact Gene Cooperman * - * . * - **********************************************************************/ - -/*********************************************************************** - * This is included in topc.c and the application. It defines the - * interface between the two. - */ - -#ifndef _TOPC_H -#define _TOPC_H - -/* Needed to define size_t and stderr */ -#include - -#ifdef __cplusplus -extern "C" { -#endif - -/* major and minor version numbers for TOP-C 2.5.2 */ -#define __TOPC_STANDARD__ 2 -#define __TOPC_MAJOR__ 5 -#define __TOPC_MINOR__ 2 - -/*********************************************************************** - * TOP-C data types (shared with comm.h) - */ -/* These are copied from comm.h */ -#ifndef TOPC_TYPES -#define TOPC_TYPES -typedef int TOPC_BOOL; -typedef struct { - void *data; - size_t data_size; - /* size_t dummy1; [ For SGI Irix 6.5 and gcc 2.7.2 ] */ - /* size_t dummy2; [ For SGI Irix 6.5 and gcc 2.7.2 ] */ -} TOPC_BUF; -/* This define is warning for obsolete TOP-C applications. */ -#define TOPC_MSG_BUF Please_replace_TOPC_MSG_BUF_by_TOPC_MSG -typedef void TOPC_FUNCTION(); -#endif - -/* Utilities: (not required for applications) */ -TOPC_BOOL TOPC_is_master(void); -int TOPC_rank(void); -int TOPC_node_count(void); /* number of nodes, _including_ master */ -int TOPC_num_slaves(void); -int TOPC_num_idle_slaves(void); - -/*********************************************************************** - *********************************************************************** - * TOPC_master_slave() interface - *********************************************************************** - ***********************************************************************/ - - -/*********************************************************************** - * TOP-C task input type for return from set_task_output(). The syntax - * is return TOPC_MSG(input, input_size);. TOPC_MSG used to be a macro - * that stored the length argument globally and returned the pointer. - * In this version it's a function that packs them both into a struct - */ -extern TOPC_BUF NOTASK; - -extern TOPC_BUF TOPC_MSG(void *input, size_t input_size); -extern TOPC_BUF TOPC_MSG_PTR(void *input, size_t input_size); - - -/*********************************************************************** - * TOP-C action type for return from check_task_result(), which should - * actually return either NO_ACTION, REDO, UPDATE, or - * CONTINUATION(TOPC_MSG(input, input_size)). This simulates the syntax - * required by the macros used in a previous version of TOP-C - */ -typedef struct { - int type; - char *name; - void *continuation; - size_t continuation_size; -} TOPC_ACTION; - -extern TOPC_ACTION NO_ACTION, REDO, UPDATE; - -extern TOPC_ACTION CONTINUATION(TOPC_BUF msg); - -/*********************************************************************** - *********************************************************************** - * TOPC options and utilities - *********************************************************************** - ***********************************************************************/ - -/*********************************************************************** - * TOP-C command line options for application (see options.c for defs) - */ - -/* These are copied from comm.h */ -extern int TOPC_OPT_num_slaves; -extern int TOPC_OPT_slave_timeout; -extern int TOPC_OPT_aggregated_tasks; -/* 0: no trace; 1: trace; 2: user functions, (*TOPC_OPT_trace_input)(), etc. */ -extern int TOPC_OPT_trace; -extern int TOPC_OPT_help; -extern int TOPC_OPT_verbose; -extern char * TOPC_OPT_procgroup; -extern char * TOPC_OPT_topc_log; -extern int TOPC_OPT_safety; - -#if defined(__cplusplus) -extern void (*TOPC_OPT_trace_input)(void *input); -extern void (*TOPC_OPT_trace_result)(void *input, void *output); -typedef void (*TOPC_trace_input_ptr)(void *); -typedef void (*TOPC_trace_result_ptr)(void *, void *); -#else -extern void (*TOPC_OPT_trace_input)(); /* args: (void *input) */ -extern void (*TOPC_OPT_trace_result)(); /* args: (void *input, void *output) */ -#endif - -/*********************************************************************** - * TOP-C main functions (interface between topc.c and application) - */ - -/* Declare beginning and end of TOP-C program. */ -void TOPC_init(int *argc, char ***argv); -void TOPC_finalize(void); - -/* Main interface to TOP-C */ -#if defined(__cplusplus) -void TOPC_master_slave( - TOPC_BUF (*generate_task_input_)(void), - TOPC_BUF (*do_task_)(void *input), - TOPC_ACTION (*check_task_result_)(void *input, void *output), - void (*update_shared_data_)(void *input, void *output) -); - -/* Lower level interface to TOP-C, for legacy and highly nested applications */ -void TOPC_raw_begin_master_slave( - TOPC_BUF (*do_task_)(void *input), - TOPC_ACTION (*check_task_result_)(void *input, void *output), - void (*update_shared_data_)(void *input, void *output) -); - -// Thanks to Jason Ansel for suggesting this template trick: -typedef TOPC_BUF (*TOPC_genTaskInputPtr)(); -typedef TOPC_BUF (*TOPC_doTaskPtr)(void *); -typedef TOPC_ACTION (*TOPC_checkTaskResultPtr)(void *, void *); -typedef void (*TOPC_updateSharedDataPtr)(void *, void *); - -} // end of extern "C" - -template - void TOPC_master_slave_cpp( TOPC_BUF (*genTaskInput)(), - TOPC_BUF (*doTask)(Tinput*), - TOPC_ACTION (*checkTaskResult)(Tinput*, Toutput*), - void (*updateSharedData)(Tinput*, Toutput*) ) { - TOPC_master_slave( (TOPC_genTaskInputPtr)genTaskInput, - (TOPC_doTaskPtr)doTask, - (TOPC_checkTaskResultPtr)checkTaskResult, - (TOPC_updateSharedDataPtr)updateSharedData ); - } -template - void TOPC_master_slave_cpp( TOPC_BUF (*genTaskInput)(), - TOPC_BUF (*doTask)(Tinput*), - TOPC_ACTION (*checkTaskResult)(Tinput*, Toutput*), - void * updateSharedData ) { - if ( updateSharedData != NULL ) { - fprintf(stderr, "TOP-C: Bad call to TOPC_master_slave.\n" - " Fourth function (updateSharedData) was not NULL," - " and had args incompatible with checkTaskResult.\n"); - exit(1); - } - TOPC_master_slave( (TOPC_genTaskInputPtr)genTaskInput, - (TOPC_doTaskPtr)doTask, - (TOPC_checkTaskResultPtr)checkTaskResult, - NULL ); - } - -template - void TOPC_raw_begin_master_slave_cpp( TOPC_BUF (*doTask)(Tinput*), - TOPC_ACTION (*checkTaskResult)(Tinput*, Toutput*), - void (*updateSharedData)(Tinput*, Toutput*) ) { - TOPC_raw_begin_master_slave( (TOPC_doTaskPtr)doTask, - (TOPC_checkTaskResultPtr)checkTaskResult, - (TOPC_updateSharedDataPtr)updateSharedData ); -} -template - void TOPC_raw_begin_master_slave_cpp( TOPC_BUF (*doTask)(Tinput*), - TOPC_ACTION (*checkTaskResult)(Tinput*, Toutput*), - void * updateSharedData ) { - if ( updateSharedData != NULL ) { - fprintf(stderr, "TOP-C: Bad call to TOPC_raw_begin_master_slave.\n" - " Third function (updateSharedData) was not NULL," - " and had args incompatible with checkTaskResult.\n"); - exit(1); - } - TOPC_raw_begin_master_slave( (TOPC_doTaskPtr)doTask, - (TOPC_checkTaskResultPtr)checkTaskResult, - NULL ); -} - -extern "C" { -#define TOPC_master_slave TOPC_master_slave_cpp -#define TOPC_raw_begin_master_slave TOPC_raw_begin_master_slave_cpp - -#else -/* Else ANSI C and not C++ */ -/* How does one declare callbacks as taking one or two pointer args in ANSI C?*/ -void TOPC_master_slave( - TOPC_BUF (*generate_task_input_)(void), - TOPC_BUF (*do_task_)(), /* args: (void *input) */ - TOPC_ACTION (*check_task_result_)(), /* args: (void *input, void *output) */ - void (*update_shared_data_)() /* args: (void *input, void *output) */ -); - -/* Lower level interface to TOP-C, for legacy and highly nested applications */ -void TOPC_raw_begin_master_slave( - TOPC_BUF (*do_task_)(), /* args: (void *input) */ - TOPC_ACTION (*check_task_result_)(), /* args: (void *input, void *output) */ - void (*update_shared_data_)() /* args: (void *input, void *output) */ -); -#endif -void TOPC_raw_end_master_slave(void); -void TOPC_raw_submit_task_input(TOPC_BUF input); -TOPC_BOOL TOPC_raw_wait_for_task_result(void); - -/*********************************************************************** - * TOP-C Utility functions (interface between topc.c and application) - */ -TOPC_BOOL TOPC_is_up_to_date(void); -void TOPC_abort_tasks(); -TOPC_BOOL TOPC_is_abort_pending(void); -TOPC_BOOL TOPC_is_REDO(void); -TOPC_BOOL TOPC_is_CONTINUATION(void); - -/*********************************************************************** - *********************************************************************** - * SMP-related functions (e.g.: private (non-shared) variables) - *********************************************************************** - ***********************************************************************/ - - -/*********************************************************************** - * TOPC_thread_private - * - * Usage: - * typedef struct {int val1; float val2;} TOPC_thread_private_t; - * void foo() { - * TOPC_thread_private.val1 = 42; - * TOPC_thread_private.val2 = 3.14; - * } - * void bar() { - * foo(); - * if (TOPC_thread_private.val1 != 42) printf("ERROR"); - * if (TOPC_thread_private.val2 != 3.14) printf("ERROR"); - * } - */ - -/* Move expl. below to doc/ after final testing. - Gene */ -/* -doc: - A TOP-C variable has either global scope or local scope. - It is also shared or private. - A variable is global or local according to the standard C specification. - In the distributed memory (e.g.: --mpi), a variable is always private. - Even a variable whose value is in shared data is private, but - calls to UpdateSharedData() will update the private value with - the latest value. Thus, we say that such variables have lazy updates. - In the sequential memory (e.g.: --seq), a variable is always shared. - Thus UpdateSharedMemory executes only once, in the sequential process. - In shared memory (e.g.: --pthread), a variable is shared by default. - Further UpdateSharedMemory executes only once, in the master thread. - However, certain strategies for high concurrency require the use - of private variables to privately save temporary values and use them - again during a REDO action. - To accomodate this, one can declare a single private variable. - The private variable has global scope, but each thread has a separate - copy that can be read or written only by that thread. - One is allowd only a single private variable, but its type can - be declared arbitrarily. Hence, in the example below, we declare - TOPC_thread_private to be a struct, and then use - TOPC_thread_private.val1 and TOPC_thread_private.val2 separately. -*/ - -/* comm layer: will malloc a TOPC_thread_private_t first time, then re-uses it*/ -void *COMM_thread_private(size_t); -/* If TOPC_thread_private used, app must typedef ... TOPC_thread_private_t; */ -#define TOPC_thread_private \ - ( *(TOPC_thread_private_t *) \ - COMM_thread_private( sizeof(TOPC_thread_private_t) ) ) - -/* EXPERIMENTAL: - * Ideally, we would want to define THREAD_PRIVATE(mytype, myvar); - * to act as if: THREAD_PRIVATE mytype myvar; - * and to expand to: - * #define myvar TOPC_thread_private_var - * typedef mytype TOPC_thread_private_var_t - * TOPC_thread_private_var_t myvar_debug{ return myvar; } // for GDB - * as if: TOPC_thread_private_var_t TOPC_thread_private_var; were defined. - * OPTIONAL: mytype TOPC_thread_private_var_init_value = XXX; - */ - -/*********************************************************************** - * Synchronization (atomic I/O) and pages of shared data - * - * TOPC_ATOMIC_READ(x) and TOPC_ATOMIC_WRITE(x) - * In non-shared memory, this has no effect. - * In shared memory, it provides a read lock or a write lock around code. - * Usage: - * TOPC_ATOMIC_WRITE(x) { hash[i] = 17; } - * Currently, x is not used, but eventually it will be a "page number". - * TOPC_is_up_to_date() will check if each page is up_to_date. - * This eliminates the problem of false sharing. - * Maybe, page 0 will have special meaning: reading page 0 means reading - * all pages and writing page 0 means writing to all pages. - */ - -/* This is copied from comm.h */ -TOPC_BOOL COMM_is_in_atomic_section(void); - -extern void TOPC_BEGIN_ATOMIC_READ(int pagenum); -extern void TOPC_END_ATOMIC_READ(int pagenum); -extern void TOPC_BEGIN_ATOMIC_WRITE(int pagenum); -extern void TOPC_END_ATOMIC_WRITE(int pagenum); - -#define TOPC_ATOMIC_READ(pagenum) \ - for ( TOPC_BEGIN_ATOMIC_READ(pagenum); \ - COMM_is_in_atomic_section(); \ - TOPC_END_ATOMIC_READ(pagenum) ) /* application body appears here */ - -#define TOPC_ATOMIC_WRITE(pagenum) \ - for ( TOPC_BEGIN_ATOMIC_WRITE(pagenum); \ - COMM_is_in_atomic_section(); \ - TOPC_END_ATOMIC_WRITE(pagenum) ) /* application body appears here */ - -TOPC_BOOL TOPC_is_up_to_date(void); - - -#ifdef __cplusplus -} -#endif - -/* end TOPC_H */ -#endif diff --git a/topc-2.5.2/tests/README b/topc-2.5.2/tests/README deleted file mode 100644 index a1d1941c..00000000 --- a/topc-2.5.2/tests/README +++ /dev/null @@ -1,61 +0,0 @@ -Right now there is no formal test suit except for "make check" from -top level. Thses are some of the areas that I try to cover -in my informal test suite. - -configure with (gcc): "CFLAGS=-Wall -W -pedantic" - and recompile TOP-C. - -Some test cases to check are: - sequential vs. mpi vs. pthread - -Should do memory checks with valgrind: - ADD valgrind --tool=memcheck --leak-check=yes TO bin/Makefile:checkit TARGET - -Should verify --TOPC-aggregated-tasks - (also include some large tasks larger than AGGREG_TASKS_SIZE) - Note par8queens-raw and various others use trivial parallelism, - and can be tested with --TOPC-aggregated-tasks . - For example: env TOPC_OPTS=--TOPC-aggregated-tasks=2 make check - [ although it doesn't handle actions besides NO_ACTION ] - parsimple includes large tasks - -Should verify with at least 100 slaves (behavior different as slaves - start late, never start, or die later) - Should add mechanism to cause slaves to randomly die, for testing. - -Should verify when slaves die: env CFLAGS=-DSLAVES_DIE=5 (5 secs or less) - Should run variants of applications that last longer. - -Should verify with two calls to TOPC_master_slave in program - parsimple.c and gauss-elim-*.c do this. - -Should verify --TOPC-safety for different levels - env TOPC_OPTS=--TOPC-safety=10 make check - (and so on for safety level 16, 18, etc.) - -Should verify that it works with C++. - ( cd bin; make TOPCC=./topc++ checkall | grep TEST ) - -Should verify with other compilers - Solaris: env CC=cc CXX=CC ./configure - AIX: env CC=xlc CXX=xlC ./configure - -Should verify that it works with other MPIs - -Verify that TOP-C avoids namespace clash with applications: - The only symbols exported by a TOP-C library should be: - TOPC_*, COMM_*, MEM_*, MPI_*, MPINU_*, and - NO_ACTION, UPDATE, REDO, and CONTINUATION and NOTASK. - The next command tests this: -nm ../lib/*.a | grep ' [DT] ' | grep -v TOPC_ | grep -v COMM_ | grep -v MEM_ \ - | grep -v MPI_ | grep -v MPINU_ \ - | grep -v NO_ACTION | grep -v UPDATE | grep -v REDO | grep -v CONTINUATION \ - | grep -v NOTASK \ - | sort | uniq - -Check the static local variables for routines executed on a slave. -These cannot work in threads, since all threads share the variables. - -spell check on documentation - -Check utils directory and CHANGES to see if information is up to date. diff --git a/topc-2.5.2/tests/TODO b/topc-2.5.2/tests/TODO deleted file mode 100644 index e6289363..00000000 --- a/topc-2.5.2/tests/TODO +++ /dev/null @@ -1,10 +0,0 @@ -make check TEST_FILE=gauss-elim-redo -./a.out --TOPC-safety=2 - in dist. memory mode - often yields a bug with 2 or more slaves, but not always - The master hangs after sending the REDO. Only slaves 1 and 2 - are participating. - There is one busy slave, and the rest are idle. - - To observe it in gdb, it's better to break at TOPC_master_slave and - then continue. More slaves seem to trigger the bug earlier. diff --git a/topc-2.5.2/tests/testsuite b/topc-2.5.2/tests/testsuite deleted file mode 100755 index 5a62bbfa..00000000 --- a/topc-2.5.2/tests/testsuite +++ /dev/null @@ -1,22 +0,0 @@ -#!/bin/sh - -# This test suite is to test the correct functioning of TOP-C. -# It is probably useful only to maintainers. - -test_it () { \ - ( cd ../bin; make checkall TEST_ARGS=--TOPC_safety=$level | grep TEST ); \ -} - -test_it2 () { \ - ( cd ../bin; make checkall TEST_ARGS=--TOPC_safety=$level --TOPC-aggregated-tasks=3 | grep TEST ); \ -} - -level=0; test_it -level=2; test_it -level=4; test_it -level=8; test_it -level=12; test_it -level=14; test_it -level=16; test_it -level=19; test_it -level=20; test_it diff --git a/topc-2.5.2/tests/topc-compare b/topc-2.5.2/tests/topc-compare deleted file mode 100755 index 8350ad0c..00000000 --- a/topc-2.5.2/tests/topc-compare +++ /dev/null @@ -1,31 +0,0 @@ -#!/bin/sh - -if test "$2" = ""; then - echo USAGE: topc-compare TOPC-1.tar.gz TOPC-2.tar.gz - echo " Finds essential differnces in two versions of TOP-C" - exit 1 -fi - -DIR=/ccs/tmp/$USER - -test -r $DIR || mkdir $DIR -rm -rf $DIR/topc-tmp -mkdir $DIR/topc-tmp - -cp $1 $DIR/topc-tmp/topc-new.tar.gz -( cd $DIR/topc-tmp ; gzip -dc topc-new.tar.gz | tar xvf - ; \ - rm topc-new.tar.gz; mv topc-* tmp-new ) - -cp $2 $DIR/topc-tmp/topc-old.tar.gz -( cd $DIR/topc-tmp ; gzip -dc topc-old.tar.gz | tar xvf - ; \ - rm topc-old.tar.gz; mv topc-* tmp-old ) - -cd $DIR/topc-tmp -mv tmp-new topc-new -mv tmp-old topc-old - -( cd topc-new; ./configure; make maintainer-clean ) -( cd topc-old; ./configure; make maintainer-clean ) -diff -r topc-new topc-old | tee topc-diff -echo ==================================================== -grep -i only topc-diff diff --git a/topc-2.5.2/utils/README b/topc-2.5.2/utils/README deleted file mode 100644 index a8d4d5fe..00000000 --- a/topc-2.5.2/utils/README +++ /dev/null @@ -1,26 +0,0 @@ -These are sketches of code to be polished and included in future versions -$of TOP-C. They may also be useful in their current state. -They are: - -ssh-killall: Example: `ssh-killall a.out' to kill runaway a.out on slaves - This is a script that calls ssh-procgroup -ssh-procgroup.c: Calls ssh on hosts in procgroup. Looks for `procgroup' - in current directory. - To create binary, do: gcc -o ssh-procgroup ssh-procgroup.c - EXAMPLE: ssh-procgroup killall -9 -v a.out - (to kill runaway slaves of name a.out, from previous run) -broadcast.c: Implements broadcast() and gather() (and eventually scatter()) - on top of TOPC_master_slave(). -topc.cc: C++ interface replacing callbacks by an abstract class to be - instantiated by an application - THIS DOES NOT COMPILE. IT IS JUST AN ARCHITECTURE. -cygwin: Comments on what to change to use this under Cygwin -recursion: Notes on applying this to applications with recursion -checkpoint.c: Planned integration of checkpointing - ./a.out --TOPC-checkpoint=DAYS (default is 1 day) - User declares restart fnc: TOPC_checkpoint_restart(FNC); - FNC is executed at beginning of TOPC_master_slave - during restart and can fix up file descriptors, local vars on - stack, etc. - Use TOPC_is_master() if you don't want it in all processes - FNC can be NULL, but user must type: TOPC_checkpoint_restart(NULL); diff --git a/topc-2.5.2/utils/broadcast.c b/topc-2.5.2/utils/broadcast.c deleted file mode 100644 index 9a30edf4..00000000 --- a/topc-2.5.2/utils/broadcast.c +++ /dev/null @@ -1,158 +0,0 @@ -// Implements -// void TOPC_broadcast(void (*)(void *) update_data, void *data, int size); -// This code assumes that TOP-C accesses idle slaves in round robin fashion - -/* IMPORTANT: For safety, should have check that master and slave are - * both using broadcast in the current TOPC_master_slave - * and notify user if not true. Probably, exchange some tags. - * */ - -#include -#include "topc.h" - -static void *bcast_data; -static int bcast_data_size; -static void (*bcast_do_it)(void *data); - -static TOPC_BUF bcast_gen_input() { - static int i = 0; - - ++i; - if (i == 1 + 1) - bcast_data = NULL; /* then we've finished bcast_data request */ - else if (i > 1 + 1 && bcast_data != NULL) /* if new bcast_data request */ - i = 1; - - if (i > 1) - return NOTASK; - else - return TOPC_MSG_PTR(bcast_data, bcast_data_size); -} - -static TOPC_BUF bcast_do_task(void *data) { - return TOPC_MSG(NULL, 0); -} - -static TOPC_ACTION bcast_check_result(void *input, void *output) { - return UPDATE; -} - -static void bcast_update_data(void *data, void *output) { - (*bcast_do_it)(data); -} - -// TOPC_broadcast executes: (*update_data)(data); -// on all processes (including master). -void TOPC_broadcast(void (*update_data)(void *), void *data, int size) { - int save_trace = TOPC_OPT_trace; - TOPC_OPT_trace= 0; - bcast_do_it = update_data; - bcast_data = data; - bcast_data_size = size; - TOPC_master_slave(bcast_gen_input, bcast_do_task, bcast_check_result, - bcast_update_data); - TOPC_OPT_trace = save_trace; -} - -//************************************************************************* -// Example usage: -// static struct stats { int rank; struct rusage usage; } mystat; -// static void *get_stat() -// { getrusage(RUSAGE_SELF, &mystat.usage); mystat.rank = TOPC_rank(); -// return &mystat; } -// struct stats *stat_array -// = malloc(sizeof(struct stats) * (TOPC_num_slaves()+1)); -// TOPC_gather( get_stats, stat_array, sizeof(struct stats) ); -// Now, stat_array[5].usage indicates usage of slave stat_array[5].rank . -// Do we want: TOPC_get_last_rank() ? - -static int gather_is_done = 1; -static void * (*gather_do_it)(void); -static void *gather_array; -static int gather_array_elt_size; - -// This code assumes TOP-C sends successive requests to successive slaves. -// Luckily, that is exactly what TOP-C does. -static TOPC_BUF gather_gen_input() { - static int i = 0; - static int num_slaves = -1; - - if (num_slaves == -1) num_slaves = TOPC_num_slaves(); - - ++i; - if (i == num_slaves + 1) - gather_is_done = 1; /* then we've finished gather_array request */ - else if (i > num_slaves + 1 && ! gather_is_done) /* if new gather_array req */ - i = 1; - - if (i > num_slaves) - return NOTASK; - else - return TOPC_MSG(NULL, 0); -} - -static TOPC_BUF gather_do_task(void *input) { - return TOPC_MSG( (*gather_do_it)(), gather_array_elt_size ); -} - -// gatherion_array has size at least: size*(TOPC_num_slaves()+1) -#define gather_array_sub(i) (void *)((char *)gather_array + i*gather_array_elt_size) - -static TOPC_ACTION gather_check_result(void *input, void *output) { - static int slave = 0; - ++slave; - if (slave > TOPC_num_slaves()) slave = 1; - memcpy(gather_array_sub(slave), output, gather_array_elt_size); - return NO_ACTION; -} - -void TOPC_gather(void * (*gather_data)(void), - void *gatherion_array, int elt_size) { - int save_trace = TOPC_OPT_trace; - TOPC_OPT_trace= 0; - gather_is_done = 0; - gather_do_it = gather_data; - gather_array = gatherion_array; - gather_array_elt_size = elt_size; - memcpy(gather_array_sub(0), gather_data(), elt_size); // Do it on master - // and do it from slaves - TOPC_master_slave(gather_gen_input, gather_do_task, gather_check_result, NULL); - TOPC_OPT_trace = save_trace; -} - -//************************************************************************* - -#include -// EXAMPLE: sync. random state among multiple processes -// Useful to do after TOPC_master_slave, when seeds may no longer sync. -// If random() called from within do_task() and want reproducibility, -// then set seed deterministically to next pseudo-random number -// on master just before do_task, and then copy that seed to slave -// just before slave executes do_task. -#if 0 -static void set_random_state(void *state) { - setstate(state); -} -#define SEED_SIZE sizeof(unsigned int) -static char *get_random_state() { - char tmpstate[SEED_SIZE], *oldstate; - oldstate = setstate(tmpstate); - assert(oldstate != NULL); - setstate(oldstate); - return oldstate; -} -#else -static void set_random_state(void *state) { - srandom(*(unsigned int *)state); -} -static unsigned int new_seed; -#define SEED_SIZE sizeof(new_seed) -static unsigned int *get_random_state() { - new_seed = random(); - return &new_seed; -} -#endif - -static void sync_random_state() { - TOPC_broadcast(set_random_state, get_random_state(), SEED_SIZE); -} diff --git a/topc-2.5.2/utils/checkpoint.c b/topc-2.5.2/utils/checkpoint.c deleted file mode 100644 index e327b64b..00000000 --- a/topc-2.5.2/utils/checkpoint.c +++ /dev/null @@ -1,12 +0,0 @@ -#ifdef __GNUC__ - -// For pre-elf, something like this would be enough. - -int main() { - extern unsigned long *__data_start; - extern unsigned long *data_start; - extern unsigned long *_edata; - printf("start: %x; end: %x\n", __data_start, _edata); - printf("start: %x; end: %x\n", data_start, _edata); -} -#endif diff --git a/topc-2.5.2/utils/cygwin b/topc-2.5.2/utils/cygwin deleted file mode 100644 index 24bf71aa..00000000 --- a/topc-2.5.2/utils/cygwin +++ /dev/null @@ -1,59 +0,0 @@ -a.out => a.exe - -scanf different "%s%s " - -Solaris cc (C) -"utils.c", line 45: warning: integer overflow detected: op "<<" - -==== - -July 2, Roman Kurin - -1) src did not compile because of the redefinition of "struct option" in - options.c. On the second try it compiled fine. I am not sure what the -problem was but when I did configure from scratch src compiled fine. hmmmm - -2) expand_path in procgroup.c core dumps. Read on the internet that sscanf -in - cygwin has a bug which prevents it from recognizing white space in the - pattern if whitespace is in the end of the pattern. Like when pattern is - " %*s %*s ", sscanf would not match whitespace at the end of the pattern. - Thus sscanf( path, " %*s %*s %n", &offset); would set offset to some big -number because it does not find a pattern in the "path" variable. - Solution was to replace sscanf( path, " %*s %*s %n", &offset) with - sscanf( path, " %*s %*s%n", &offset); - suffix = path + offset; - if (strlen(suffix)>0) suffix++; - -3) There is a problem in the Makefile in the /bin directory. It assumes that -output - file of gcc is a.out, but on windows platform its a.exe, thus errors. - -4) There is a problem in the manual for topc. - In the section called "If Slaves Fail to Start", there is a simple -program - given as an example. - - #include "topc.h" - int main(int argc, char *argv) { - char host[100]; - printf("%s connecting ...\n", gethostname(host, 99)); - TOPC_init(&argc, &argv); - printf("... %s connected.\n", gethostname(host, 99)); - TOPC_finalize(); - } - - The problem is with lines : - printf("%s connecting ...\n", gethostname(host, 99)); - printf("... %s connected.\n", gethostname(host, 99)); - - gethostname returns the status code and not the name of the host. - - -5) In the distributed mode, topcc fails saying: - Socket died; Not ready for writing. Will try to create a new one. - Socket died; Not ready for writing. Will try to create a new one. - sendrecv.c(line 237): send: Bad address - - I am currently investigating this problem. - diff --git a/topc-2.5.2/utils/recursion b/topc-2.5.2/utils/recursion deleted file mode 100644 index 61753008..00000000 --- a/topc-2.5.2/utils/recursion +++ /dev/null @@ -1,6 +0,0 @@ -RECURSION with TOP-C (similar to Cilk): - Use CONTINUATION() - After every x steps, split pending branches in half and offer to - others. On next communication with master (or on this), - the master will tell us if the split is taken via - the CONTINUATION() action. diff --git a/topc-2.5.2/utils/ssh-killall b/topc-2.5.2/utils/ssh-killall deleted file mode 100755 index a0b46f60..00000000 --- a/topc-2.5.2/utils/ssh-killall +++ /dev/null @@ -1,16 +0,0 @@ -#!/bin/sh - -if test "$1" == ""; then - echo "Usage: ssh-killall PROCESS_NAME" - echo " PROCESS_NAME will be passed as arg to killall on each slave process" - exit 1 -fi - -dir=/home/kason/school/4zp6/repo/GEANT4-GPU/topc-2.5.2/utils - -if test ! -x $dir/ssh-procgroup; then - echo "$dir: gcc -o ssh-procgroup ssh-procgroup.c" - ( cd $dir; gcc -o ssh-procgroup ssh-procgroup.c ) -fi - -$dir/ssh-procgroup killall -9 -v $1 diff --git a/topc-2.5.2/utils/ssh-killall.in b/topc-2.5.2/utils/ssh-killall.in deleted file mode 100755 index d10987b7..00000000 --- a/topc-2.5.2/utils/ssh-killall.in +++ /dev/null @@ -1,16 +0,0 @@ -#!/bin/sh - -if test "$1" == ""; then - echo "Usage: ssh-killall PROCESS_NAME" - echo " PROCESS_NAME will be passed as arg to killall on each slave process" - exit 1 -fi - -dir=@PWD@/utils - -if test ! -x $dir/ssh-procgroup; then - echo "$dir: gcc -o ssh-procgroup ssh-procgroup.c" - ( cd $dir; gcc -o ssh-procgroup ssh-procgroup.c ) -fi - -$dir/ssh-procgroup killall -9 -v $1 diff --git a/topc-2.5.2/utils/ssh-procgroup.c b/topc-2.5.2/utils/ssh-procgroup.c deleted file mode 100644 index 7c3ef407..00000000 --- a/topc-2.5.2/utils/ssh-procgroup.c +++ /dev/null @@ -1,48 +0,0 @@ -/* TO COMPILE: gcc -o ssh-procgroup ssh-procgroup.c */ - -#include -#include -#include - -#define BUF_LEN 100 - -int main( int argc, char **argv ) -{ - char *p4pg_file = "procgroup"; - FILE *fin; - char *t0; - int i = 0; - int j, k; - char *buf; - char pg_array[1000][BUF_LEN]; - - if ( (fin = fopen(p4pg_file, "r")) ) - { - while( fgets( buf = pg_array[i], BUF_LEN, fin ) ) { - if ( buf[0] == '#' ) continue; /* # means comment */ - if ( buf[0] == '\n' ) continue; /* skip null lines */ - - t0 = strtok(buf, " "); - if ( !strcmp(t0, "local") ) - continue; - i++; - } - } else { - fprintf(stderr, "Couldn't find procgroup file in current directory.\n"); - exit(1); - } - - // Now use pg_array to create ssh commands and call system() - for (j = 0; j < i; j++) { - char command[256]; - sprintf( command, "ssh %s", pg_array[j] ); - for (k = 1; k < argc; k++) - sprintf( command + strlen(command), " %s", argv[k] ); - if ( j % 5 != 0 ) - sprintf( command + strlen(command), " &" ); - printf("%s\n", command); - system( command ); - } - - return 0; -} diff --git a/topc-2.5.2/utils/topc.cc b/topc-2.5.2/utils/topc.cc deleted file mode 100644 index b5785dec..00000000 --- a/topc-2.5.2/utils/topc.cc +++ /dev/null @@ -1,230 +0,0 @@ -// C++ interface for TOP-C -// Gene Cooperman -// SEARCH ON parAPP1 and parAPP2 for example applications of this code. -// -// THIS DOES NOT COMPILE. IT IS JUST AN ARCHITECTURE. -// -// The plan is to define a TOPC class with all the TOP-C callbacks. -// For each callback, e.g. doTask(), define a member function, -// and also a static TOPC class function, s_doTask(). -// The member function, doTask(), is declared virtual, so that the -// user can form a derived class in which he or she writes a new doTask(). -// In addition, define a static TOPC class function, master_slave(). -// master_slave() sets the TOPC class member: TOPC * s_currTOPC = this; -// Meanwhile, the static class function, s_doTask(), is effectively -// defined, using casts, as something like: -// TOPC_BUF TOPC::s_doTask(void* in) -// { (TOPC_BUF)(s_currTOPC->doTask((Tin)in)) }; -// To make this all work, the class TOPC is modified to be -// a template class: TOPC -// This context allows us to easily arrange defaults: -// TOPC -// virtual doTask = 0; // pure virtual -// etc. -// In operation, the end user now typically does something like: -// class Input { ... } -// class Output { ... } -// class parAPP1 : TOPC, APPLICATION { ... }; -// class parAPP2 : TOPC, APPLICATION { ... }; -// #include // which whould include topc.h -// int main () { parAPP1 x; x.master_slave(); parAPP2 y; y.master_slave(); } -// TOP-C then looks for a procgroup file in the current directory to -// specify where to run the slaves, and begins executing in parallel. - -using namespace std; - -#include -#include -#include "topc.h" - -// Arbitrary hacks to set constants similar to TOP-C -#ifndef _TOPC_H - typedef void * TOPC_BUF; - inline int TOPC_num_slaves() { return 3; } - inline int TOPC_is_up_to_date() { return true; } - enum TOPC_ACTION {NO_ACTION, REDO, UPDATE, CONTINUATION}; -#endif -static int dummy; - -template -class TOPC { - private: - static TOPC *s_currTOPC; - static TOPC_BUF s_generateTaskInput(); - static TOPC_BUF s_doTask(void* input); - static TOPC_ACTION s_checkTaskResult(TOPC_BUF input, TOPC_BUF output); - static void s_updateSharedData(TOPC_BUF input, TOPC_BUF output); - - bool usingDefaultUpdateSharedData; - - public: - static const Tinput NO_INPUT; - - inline bool TOPC::is_up_to_data() { - return (bool)TOPC_is_up_to_date(); - } - virtual Toutput generateTaskInput(); - virtual Toutput doTask(Tinput) = 0; // pure virtual - virtual TOPC_ACTION checkTaskResult(Tinput input, Toutput); - virtual void updateSharedData(Tinput input, Toutput output); - void master_slave(); -}; - -template -TOPC *TOPC::s_currTOPC = NULL; - -template -// HACK for now: -Tinput const TOPC::NO_INPUT = static_cast(&dummy); - -template -TOPC_BUF TOPC::s_generateTaskInput() { - // IF THIS DOESN'T RETURN TOPC_BUF, IT PROVES USER generateTaskInput() - // DID NOT RETURN A POINTER; USER ERROR; CAN WE SIGNAL ERROR TO USER? - return s_currTOPC->generateTaskInput(); -} -template -Tinput TOPC::generateTaskInput() { - cout << "default generateTaskInput" <= last_slave) return static_cast(NO_INPUT); - slave++; - return static_cast&slave; -} - -template -TOPC_BUF TOPC::s_doTask(void* input) { - return s_currTOPC->doTask(static_cast(input)); -} - -template -TOPC_ACTION TOPC::s_checkTaskResult - (Tinput* input, Toutput* output) { - return s_currTOPC->checkTaskResult(static_cast(input), - static_cast(output)); -} -template -TOPC_ACTION TOPC::checkTaskResult(Tinput input, Toutput output) -{ - // IS THERE A WAY TO TEST IF updateSharedData HAS BEEN SHADOWED? - // IF IT HAS NOT BEEN SHADOWED, THEN RETURN NO_ACTION. - // AT THE VERY LEAST, WE COULD HAVE DEFAULT updateSharedData() - // SET A SPECIAL VALUE IN `this', SO WE'LL KNOW IT WAS RUN AFTERWARDS - cout << "default checkTaskResult" << endl; - // if (usingDefaultUpdateSharedData) return NO_ACTION; - if (! is_up_to_date()) return REDO; - if (output == NULL) return NO_ACTION; - else return UPDATE; -} - -template -void TOPC::s_updateSharedData - (TOPC_BUF input, TOPC_BUF output) { - s_currTOPC->updateSharedData(static_cast(input), - static_cast(output)); -} -template -void TOPC::updateSharedData(Tinput input, Toutput output) -{ - cout << "default updateSharedData" < -void TOPC::master_slave() -{ - TOPC::s_currTOPC = this; - usingDefaultUpdateSharedData = false; - - cout << "master_slave: \n"; - while (1) { - TOPC_BUF input = s_generateTaskInput(); - if (input == NO_INPUT) break; - TOPC_BUF output = s_doTask(input); - cout << "input: " << *(int *)input << "; output: " << *(int *)output - << endl; - char const *actions[] = {"NO_ACTION", "REDO", "UPDATE", "CONTINUATION"}; - cout << "TOPC_ACTION: " << actions[s_checkTaskResult(input, output)] - << endl; - s_updateSharedData(input, output); - cout << endl; - } - - TOPC::s_currTOPC = NULL; - // Now we have static callbacks using type `TOPC_BUF' = `void *', and so - // we can call the C interface to implmment the TOP-C algorithm. - // CALL: - TOPC_master_slave(s_generateTaskInput,s_doTask, - s_checkTaskResult,s_UpdateSharedData); -} - -// ====================================== -// EXAMPLE 1: -// Trivial end-user interface: -// input and output buffers default to `void *' -// generateTaskInput() defaults to running once on each slave -// with task inputs 1, 2, ..., num_slaves; and then quitting. -// To run, create an instance, x, of parAPP1, and call: x.master_slave(); -// After compiling, ./a.out --TOPC-num_slaves=XXX can customize how many slaves - -class parAPP1 : public TOPC { - inline TOPC_BUF doTask(void* input) - { cout << "new parAPP1::doTask" << endl; return input; } -}; - -// ====================================== -// EXAMPLE 2: -// End-user interface: -// Assume input buffer and output buffer both of type `int *' -// The class parAPP2 uses multiple inheritance in this example, and -// the end user calls APPLICATION:app_task in parAPP2::doTask(). - -class APPLICATION { - private: - int INCREMENT; - public: - inline APPLICATION() { INCREMENT = 100; } - int app_task(int input) { return INCREMENT + input; } -}; -class parAPP2 : public TOPC, APPLICATION { - int * generateTaskInput(); - int * doTask(int * input); - TOPC_ACTION checkTaskResult(int * input, int *output); -}; - -// End-user implementation: -int * parAPP2::generateTaskInput() -{ - static bool done = false; - if (done) return NO_INPUT; - done = true; - static int input; - return &input; -} -int * parAPP2::doTask(int * input) -{ - cout << "new parAPP2::doTask: " << *input << endl; - // I think this is now safe in TOP-C. Should check this: - // It's probably now safe even without `static' - static int output = app_task(*input); - return &output; -} -TOPC_ACTION parAPP2::checkTaskResult(int * input, int *output) -{ return NO_ACTION; } - -// ====================================== - -main () -{ - int x = 3; - parAPP1 par1; - cout << "\n============================\nparAPP1: "; - par1.master_slave(); - - cout << "\n============================\nparAPP2: "; - parAPP2 par2; - par2.master_slave(); -}