Import Geant4 10.7.0.beta source tree

This commit is contained in:
Gabriele Cosmo
2020-06-26 10:23:25 +02:00
parent c02c370437
commit 67ba86d073
1871 changed files with 174422 additions and 131884 deletions
+6 -3
View File
@@ -23,16 +23,19 @@
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
// G4Allocator/G4AllocatorBase class implementation
//
//
//
// Author: G.Cosmo (CERN), November 2000
// --------------------------------------------------------------------
#include "G4Allocator.hh"
#include "G4AllocatorList.hh"
// --------------------------------------------------------------------
G4AllocatorBase::G4AllocatorBase()
{
G4AllocatorList::GetAllocatorList()->Register(this);
}
G4AllocatorBase::~G4AllocatorBase() {;}
// --------------------------------------------------------------------
G4AllocatorBase::~G4AllocatorBase() {}
+31 -31
View File
@@ -23,91 +23,91 @@
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
// G4AllocatorList class implementation
//
//
//
// Authors: M.Asai (SLAC), G.Cosmo (CERN), June 2013
// --------------------------------------------------------------------
#include <iomanip>
#include "G4AllocatorList.hh"
#include "G4Allocator.hh"
#include "G4AllocatorList.hh"
#include "G4ios.hh"
G4ThreadLocal G4AllocatorList* G4AllocatorList::fAllocatorList=0;
G4ThreadLocal G4AllocatorList* G4AllocatorList::fAllocatorList = nullptr;
// --------------------------------------------------------------------
G4AllocatorList* G4AllocatorList::GetAllocatorList()
{
if(!fAllocatorList)
if(fAllocatorList == nullptr)
{
fAllocatorList = new G4AllocatorList;
}
return fAllocatorList;
}
// --------------------------------------------------------------------
G4AllocatorList* G4AllocatorList::GetAllocatorListIfExist()
{
return fAllocatorList;
}
G4AllocatorList::G4AllocatorList()
{
}
// --------------------------------------------------------------------
G4AllocatorList::G4AllocatorList() {}
G4AllocatorList::~G4AllocatorList()
{
fAllocatorList = 0;
}
// --------------------------------------------------------------------
G4AllocatorList::~G4AllocatorList() { fAllocatorList = nullptr; }
// --------------------------------------------------------------------
void G4AllocatorList::Register(G4AllocatorBase* alloc)
{
fList.push_back(alloc);
}
// --------------------------------------------------------------------
void G4AllocatorList::Destroy(G4int nStat, G4int verboseLevel)
{
std::vector<G4AllocatorBase*>::iterator itr=fList.begin();
G4int i=0, j=0;
G4double mem=0, tmem=0;
if(verboseLevel>0)
auto itr = fList.cbegin();
G4int i = 0, j = 0;
G4double mem = 0, tmem = 0;
if(verboseLevel > 0)
{
G4cout << "================== Deleting memory pools ==================="
<< G4endl;
}
for(; itr!=fList.end();++itr)
for(; itr != fList.cend(); ++itr)
{
mem = (*itr)->GetAllocatedSize();
if(i<nStat)
if(i < nStat)
{
i++;
++i;
tmem += mem;
(*itr)->ResetStorage();
continue;
}
j++;
++j;
tmem += mem;
if(verboseLevel>1)
if(verboseLevel > 1)
{
G4cout << "Pool ID '" << (*itr)->GetPoolType() << "', size : "
<< std::setprecision(3) << mem/1048576
G4cout << "Pool ID '" << (*itr)->GetPoolType()
<< "', size : " << std::setprecision(3) << mem / 1048576
<< std::setprecision(6) << " MB" << G4endl;
}
(*itr)->ResetStorage();
delete *itr;
delete *itr;
}
if(verboseLevel>0)
if(verboseLevel > 0)
{
G4cout << "Number of memory pools allocated: " << Size()
<< "; of which, static: " << i << G4endl;
G4cout << "Dynamic pools deleted: " << j
G4cout << "Dynamic pools deleted: " << j
<< " / Total memory freed: " << std::setprecision(2)
<< tmem/1048576 << std::setprecision(6) << " MB" << G4endl;
<< tmem / 1048576 << std::setprecision(6) << " MB" << G4endl;
G4cout << "============================================================"
<< G4endl;
}
fList.clear();
}
G4int G4AllocatorList::Size() const
{
return fList.size();
}
// --------------------------------------------------------------------
G4int G4AllocatorList::Size() const { return fList.size(); }
+32 -39
View File
@@ -23,16 +23,10 @@
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
//
//
//
// ----------------------------------------------------------------------
// G4AllocatorPool
//
// Implementation file
// G4AllocatorPool class implementation
//
// Author: G.Cosmo, November 2000
//
// --------------------------------------------------------------------
#include "G4AllocatorPool.hh"
@@ -40,31 +34,33 @@
// G4AllocatorPool constructor
// ************************************************************
//
G4AllocatorPool::G4AllocatorPool( unsigned int sz )
: esize(sz<sizeof(G4PoolLink) ? sizeof(G4PoolLink) : sz),
csize(sz<1024/2-16 ? 1024-16 : sz*10-16),
chunks(0), head(0), nchunks(0)
{
}
G4AllocatorPool::G4AllocatorPool(unsigned int sz)
: esize(sz < sizeof(G4PoolLink) ? sizeof(G4PoolLink) : sz)
, csize(sz < 1024 / 2 - 16 ? 1024 - 16 : sz * 10 - 16)
{}
// ************************************************************
// G4AllocatorPool copy constructor
// ************************************************************
//
G4AllocatorPool::G4AllocatorPool(const G4AllocatorPool& right)
: esize(right.esize), csize(right.csize),
chunks(right.chunks), head(right.head), nchunks(right.nchunks)
{
}
: esize(right.esize)
, csize(right.csize)
, chunks(right.chunks)
, head(right.head)
, nchunks(right.nchunks)
{}
// ************************************************************
// G4AllocatorPool operator=
// ************************************************************
//
G4AllocatorPool&
G4AllocatorPool::operator= (const G4AllocatorPool& right)
G4AllocatorPool& G4AllocatorPool::operator=(const G4AllocatorPool& right)
{
if (&right == this) { return *this; }
if(&right == this)
{
return *this;
}
chunks = right.chunks;
head = right.head;
nchunks = right.nchunks;
@@ -75,10 +71,7 @@ G4AllocatorPool::operator= (const G4AllocatorPool& right)
// G4AllocatorPool destructor
// ************************************************************
//
G4AllocatorPool::~G4AllocatorPool()
{
Reset();
}
G4AllocatorPool::~G4AllocatorPool() { Reset(); }
// ************************************************************
// Reset
@@ -89,15 +82,15 @@ void G4AllocatorPool::Reset()
// Free all chunks
//
G4PoolChunk* n = chunks;
G4PoolChunk* p = 0;
while (n)
G4PoolChunk* p = nullptr;
while(n)
{
p = n;
n = n->next;
delete p;
}
head = 0;
chunks = 0;
head = nullptr;
chunks = nullptr;
nchunks = 0;
}
@@ -111,18 +104,18 @@ void G4AllocatorPool::Grow()
// elements of size 'esize'
//
G4PoolChunk* n = new G4PoolChunk(csize);
n->next = chunks;
chunks = n;
nchunks++;
n->next = chunks;
chunks = n;
++nchunks;
const int nelem = csize/esize;
char* start = n->mem;
char* last = &start[(nelem-1)*esize];
for (char* p=start; p<last; p+=esize)
const int nelem = csize / esize;
char* start = n->mem;
char* last = &start[(nelem - 1) * esize];
for(char* p = start; p < last; p += esize)
{
reinterpret_cast<G4PoolLink*>(p)->next
= reinterpret_cast<G4PoolLink*>(p+esize);
reinterpret_cast<G4PoolLink*>(p)->next =
reinterpret_cast<G4PoolLink*>(p + esize);
}
reinterpret_cast<G4PoolLink*>(last)->next = 0;
reinterpret_cast<G4PoolLink*>(last)->next = nullptr;
head = reinterpret_cast<G4PoolLink*>(start);
}
@@ -23,70 +23,86 @@
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
/*
* G4BuffercoutDestination.cc
*
* Created on: Apr 14, 2017
* Author: adotti
*/
// G4BuffercoutDestination class implementation
//
// Author: A.Dotti (SLAC), 14 April 2017
// --------------------------------------------------------------------
#include "G4BuffercoutDestination.hh"
#include "G4AutoLock.hh"
#include <iostream>
#include "G4AutoLock.hh"
#include "G4BuffercoutDestination.hh"
G4BuffercoutDestination::G4BuffercoutDestination(size_t max) :
m_buffer_out("") , m_buffer_err(""), m_currentSize_out(0) ,
m_currentSize_err(0), m_maxSize(max) {}
// --------------------------------------------------------------------
G4BuffercoutDestination::G4BuffercoutDestination(std::size_t max)
: m_buffer_out("")
, m_buffer_err("")
, m_maxSize(max)
{}
G4BuffercoutDestination::~G4BuffercoutDestination() {
Finalize();
}
// --------------------------------------------------------------------
G4BuffercoutDestination::~G4BuffercoutDestination() { Finalize(); }
void G4BuffercoutDestination::Finalize() {
// --------------------------------------------------------------------
void G4BuffercoutDestination::Finalize()
{
FlushG4cerr();
FlushG4cout();
}
G4int G4BuffercoutDestination::ReceiveG4cout(const G4String& msg) {
// --------------------------------------------------------------------
G4int G4BuffercoutDestination::ReceiveG4cout(const G4String& msg)
{
m_currentSize_out += msg.size();
m_buffer_out << msg;
//If there is a max size and it has been reached, flush
if ( m_maxSize>0 && m_currentSize_out >= m_maxSize ) {
FlushG4cout();
// If there is a max size and it has been reached, flush
if(m_maxSize > 0 && m_currentSize_out >= m_maxSize)
{
FlushG4cout();
}
return 0;
}
G4int G4BuffercoutDestination::ReceiveG4cerr(const G4String& msg) {
// --------------------------------------------------------------------
G4int G4BuffercoutDestination::ReceiveG4cerr(const G4String& msg)
{
m_currentSize_err += msg.size();
m_buffer_err << msg;
//If there is a max size and it has been reached, flush
if ( m_maxSize>0 && m_currentSize_err >= m_maxSize ) {
FlushG4cerr();
// If there is a max size and it has been reached, flush
if(m_maxSize > 0 && m_currentSize_err >= m_maxSize)
{
FlushG4cerr();
}
return 0;
}
G4int G4BuffercoutDestination::FlushG4cout() {
std::cout<<m_buffer_out.str()<<std::flush;
// --------------------------------------------------------------------
G4int G4BuffercoutDestination::FlushG4cout()
{
std::cout << m_buffer_out.str() << std::flush;
ResetCout();
return 0;
}
void G4BuffercoutDestination::ResetCout() {
// --------------------------------------------------------------------
void G4BuffercoutDestination::ResetCout()
{
m_buffer_out.str("");
m_buffer_out.clear();
m_currentSize_out = 0;
}
G4int G4BuffercoutDestination::FlushG4cerr() {
std::cerr<<m_buffer_err.str()<<std::flush;
// --------------------------------------------------------------------
G4int G4BuffercoutDestination::FlushG4cerr()
{
std::cerr << m_buffer_err.str() << std::flush;
ResetCerr();
return 0;
}
void G4BuffercoutDestination::ResetCerr() {
// --------------------------------------------------------------------
void G4BuffercoutDestination::ResetCerr()
{
m_buffer_err.str("");
m_buffer_err.clear();
m_currentSize_err = 0;
@@ -23,14 +23,19 @@
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
// G4CacheDetails class implementation
//
// Author: A.Dotti, 21 October 2013 - First implementation
// --------------------------------------------------------------------
// Decalare needed static data member for fully specialized version of cache
// Declare needed static data member for fully specialized version of cache
//
#include "G4CacheDetails.hh"
// --------------------------------------------------------------------
G4CacheReference<G4double>::cache_container*&
G4CacheReference<G4double>::cache()
{
G4ThreadLocalStatic std::vector<G4double>* _instance = nullptr;
return _instance;
G4ThreadLocalStatic std::vector<G4double>* _instance = nullptr;
return _instance;
}
+53 -53
View File
@@ -23,79 +23,76 @@
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
// G4DataVector class implementation
//
//
//
// --------------------------------------------------------------
// GEANT 4 class implementation file
//
// G4DataVector.cc
//
// History:
// 18 Sep. 2001, H.Kurashige : Structure created based on object model
// --------------------------------------------------------------
// Author: H.Kurashige, 18 September 2001
// --------------------------------------------------------------------
#include "G4DataVector.hh"
#include <iomanip>
// --------------------------------------------------------------------
G4DataVector::G4DataVector()
: std::vector<G4double>()
{
}
{}
G4DataVector::G4DataVector(size_t cap)
// --------------------------------------------------------------------
G4DataVector::G4DataVector(std::size_t cap)
: std::vector<G4double>(cap, 0.0)
{
}
{}
G4DataVector::G4DataVector(size_t cap, G4double value)
// --------------------------------------------------------------------
G4DataVector::G4DataVector(std::size_t cap, G4double value)
: std::vector<G4double>(cap, value)
{
}
{}
G4DataVector::~G4DataVector()
{
}
// --------------------------------------------------------------------
G4DataVector::~G4DataVector() {}
// --------------------------------------------------------------------
G4bool G4DataVector::Store(std::ofstream& fOut, G4bool ascii)
{
// Ascii mode
if (ascii)
if(ascii)
{
fOut << *this;
return true;
}
}
// Binary Mode
G4int sizeV = G4int(size());
fOut.write((char*)(&sizeV), sizeof sizeV);
G4int sizeV = G4int(size());
fOut.write((char*) (&sizeV), sizeof sizeV);
G4double* value = new G4double[sizeV];
size_t i=0;
for (const_iterator itr=begin(); itr!=end(); itr++, i++)
std::size_t i = 0;
for(auto itr = cbegin(); itr != cend(); ++itr, ++i)
{
value[i] = *itr;
value[i] = *itr;
}
fOut.write((char*)(value), sizeV*(sizeof (G4double)) );
delete [] value;
fOut.write((char*) (value), sizeV * (sizeof(G4double)));
delete[] value;
return true;
}
// --------------------------------------------------------------------
G4bool G4DataVector::Retrieve(std::ifstream& fIn, G4bool ascii)
{
clear();
G4int sizeV=0;
G4int sizeV = 0;
// retrieve in ascii mode
if (ascii)
if(ascii)
{
// contents
fIn >> sizeV;
if (fIn.fail()) { return false; }
if (sizeV<=0)
if(fIn.fail())
{
#ifdef G4VERBOSE
return false;
}
if(sizeV <= 0)
{
#ifdef G4VERBOSE
G4cerr << "G4DataVector::Retrieve():";
G4cerr << " Invalid vector size: " << sizeV << G4endl;
#endif
@@ -103,40 +100,44 @@ G4bool G4DataVector::Retrieve(std::ifstream& fIn, G4bool ascii)
}
reserve(sizeV);
for(G4int i = 0; i < sizeV ; i++)
for(G4int i = 0; i < sizeV; ++i)
{
G4double vData=0.0;
G4double vData = 0.0;
fIn >> vData;
if (fIn.fail()) { return false; }
if(fIn.fail())
{
return false;
}
push_back(vData);
}
return true ;
return true;
}
// retrieve in binary mode
fIn.read((char*)(&sizeV), sizeof sizeV);
fIn.read((char*) (&sizeV), sizeof sizeV);
G4double* value = new G4double[sizeV];
fIn.read((char*)(value), sizeV*(sizeof(G4double)) );
if (G4int(fIn.gcount()) != G4int(sizeV*(sizeof(G4double))) )
fIn.read((char*) (value), sizeV * (sizeof(G4double)));
if(G4int(fIn.gcount()) != G4int(sizeV * (sizeof(G4double))))
{
delete [] value;
delete[] value;
return false;
}
reserve(sizeV);
for(G4int i = 0; i < sizeV; i++)
for(G4int i = 0; i < sizeV; ++i)
{
push_back(value[i]);
}
delete [] value;
delete[] value;
return true;
}
// --------------------------------------------------------------------
std::ostream& operator<<(std::ostream& out, const G4DataVector& pv)
{
out << pv.size() << std::setprecision(12) << G4endl;
for(size_t i = 0; i < pv.size(); i++)
out << pv.size() << std::setprecision(12) << G4endl;
for(std::size_t i = 0; i < pv.size(); ++i)
{
out << pv[i] << G4endl;
}
@@ -144,4 +145,3 @@ std::ostream& operator<<(std::ostream& out, const G4DataVector& pv)
return out;
}
@@ -23,48 +23,45 @@
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
// G4ErrorPropagatorData class implementation
//
//
//
// --------------------------------------------------------------------
// GEANT 4 class implementation file
// Author: P.Arce, 2004
// --------------------------------------------------------------------
#include "G4ErrorPropagatorData.hh"
//-------------------------------------------------------------------
//---------------------------------------------------------------------
G4ThreadLocal G4ErrorPropagatorData* G4ErrorPropagatorData::fpInstance = 0;
G4ThreadLocal G4ErrorPropagatorData* G4ErrorPropagatorData::fpInstance =
nullptr;
G4ThreadLocal G4int G4ErrorPropagatorData::theVerbosity = 0;
//-------------------------------------------------------------------
//---------------------------------------------------------------------
G4ErrorPropagatorData::G4ErrorPropagatorData()
: theMode(G4ErrorMode_PropTest), theState(G4ErrorState_PreInit),
theStage(G4ErrorStage_Inflation), theTarget(0)
{
}
: theMode(G4ErrorMode_PropTest)
, theState(G4ErrorState_PreInit)
, theStage(G4ErrorStage_Inflation)
{}
// --------------------------------------------------------------------
G4ErrorPropagatorData::~G4ErrorPropagatorData()
{
delete fpInstance; fpInstance = 0;
delete fpInstance;
fpInstance = nullptr;
}
// --------------------------------------------------------------------
G4ErrorPropagatorData* G4ErrorPropagatorData::GetErrorPropagatorData()
{
if (fpInstance == 0)
if(fpInstance == nullptr)
{
fpInstance = new G4ErrorPropagatorData;
}
return fpInstance;
}
G4int G4ErrorPropagatorData::verbose()
{
return theVerbosity;
}
// --------------------------------------------------------------------
G4int G4ErrorPropagatorData::verbose() { return theVerbosity; }
void G4ErrorPropagatorData::SetVerbose( G4int ver )
{
theVerbosity = ver;
}
// --------------------------------------------------------------------
void G4ErrorPropagatorData::SetVerbose(G4int ver) { theVerbosity = ver; }
+51 -55
View File
@@ -23,28 +23,25 @@
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
// G4Exception implementation
//
//
//
// ----------------------------------------------------------------------
// G4Exception
// ----------------------------------------------------------------------
// Authors: G.Cosmo, M.Asai - May 1999 - First implementation
// --------------------------------------------------------------------
#include "G4Exception.hh"
#include "G4StateManager.hh"
void G4Exception(const char* originOfException,
const char* exceptionCode,
G4ExceptionSeverity severity,
const char* description)
// --------------------------------------------------------------------
void G4Exception(const char* originOfException, const char* exceptionCode,
G4ExceptionSeverity severity, const char* description)
{
G4VExceptionHandler* exceptionHandler
= G4StateManager::GetStateManager()->GetExceptionHandler();
G4VExceptionHandler* exceptionHandler =
G4StateManager::GetStateManager()->GetExceptionHandler();
G4bool toBeAborted = true;
if(exceptionHandler)
if(exceptionHandler != nullptr)
{
toBeAborted = exceptionHandler
->Notify(originOfException,exceptionCode,severity,description);
toBeAborted = exceptionHandler->Notify(originOfException, exceptionCode,
severity, description);
}
else
{
@@ -59,59 +56,58 @@ void G4Exception(const char* originOfException,
<< description << G4endl;
switch(severity)
{
case FatalException:
G4cerr << es_banner << message.str() << "*** Fatal Exception ***"
<< ee_banner << G4endl;
break;
case FatalErrorInArgument:
G4cerr << es_banner << message.str() << "*** Fatal Error In Argument ***"
<< ee_banner << G4endl;
break;
case RunMustBeAborted:
G4cerr << es_banner << message.str() << "*** Run Must Be Aborted ***"
<< ee_banner << G4endl;
break;
case EventMustBeAborted:
G4cerr << es_banner << message.str() << "*** Event Must Be Aborted ***"
<< ee_banner << G4endl;
break;
default:
G4cout << ws_banner << message.str()
<< "*** This is just a warning message. ***"
<< we_banner << G4endl;
toBeAborted = false;
break;
case FatalException:
G4cerr << es_banner << message.str() << "*** Fatal Exception ***"
<< ee_banner << G4endl;
break;
case FatalErrorInArgument:
G4cerr << es_banner << message.str()
<< "*** Fatal Error In Argument ***" << ee_banner << G4endl;
break;
case RunMustBeAborted:
G4cerr << es_banner << message.str() << "*** Run Must Be Aborted ***"
<< ee_banner << G4endl;
break;
case EventMustBeAborted:
G4cerr << es_banner << message.str() << "*** Event Must Be Aborted ***"
<< ee_banner << G4endl;
break;
default:
G4cout << ws_banner << message.str()
<< "*** This is just a warning message. ***" << we_banner
<< G4endl;
toBeAborted = false;
break;
}
}
if(toBeAborted)
{
if(G4StateManager::GetStateManager()->SetNewState(G4State_Abort))
{
G4cerr << G4endl << "*** G4Exception: Aborting execution ***" << G4endl;
abort();
}
else
{
G4cerr << G4endl << "*** G4Exception: Abortion suppressed ***"
<< G4endl << "*** No guarantee for further execution ***" << G4endl;
}
if(G4StateManager::GetStateManager()->SetNewState(G4State_Abort))
{
G4cerr << G4endl << "*** G4Exception: Aborting execution ***" << G4endl;
abort();
}
else
{
G4cerr << G4endl << "*** G4Exception: Abortion suppressed ***" << G4endl
<< "*** No guarantee for further execution ***" << G4endl;
}
}
}
void G4Exception(const char* originOfException,
const char* exceptionCode,
G4ExceptionSeverity severity,
G4ExceptionDescription & description)
// --------------------------------------------------------------------
void G4Exception(const char* originOfException, const char* exceptionCode,
G4ExceptionSeverity severity,
G4ExceptionDescription& description)
{
G4String des = description.str();
G4Exception(originOfException, exceptionCode, severity, des.c_str());
}
void G4Exception(const char* originOfException,
const char* exceptionCode,
G4ExceptionSeverity severity,
G4ExceptionDescription & description,
const char* comments)
// --------------------------------------------------------------------
void G4Exception(const char* originOfException, const char* exceptionCode,
G4ExceptionSeverity severity,
G4ExceptionDescription& description, const char* comments)
{
description << comments << G4endl;
G4Exception(originOfException, exceptionCode, severity, description);
@@ -23,10 +23,7 @@
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
//
// --------------------------------------------------------------------
//
// G4FilecoutDestination.cc
// G4FilecoutDestination class implementation
//
// Author: A.Dotti (SLAC), April 2017
// --------------------------------------------------------------------
@@ -35,43 +32,52 @@
#include <ios>
// --------------------------------------------------------------------
G4FilecoutDestination::~G4FilecoutDestination()
{
Close();
if ( m_output ) m_output.reset();
if(m_output)
m_output.reset();
}
// --------------------------------------------------------------------
void G4FilecoutDestination::Open(std::ios_base::openmode mode)
{
if ( m_name.isNull() )
if(m_name.isNull())
{
#ifndef __MIC
// Cannot use G4Exception, because G4cout/G4cerr is not setup
throw std::ios_base::failure("No output file name specified");
// Cannot use G4Exception, because G4cout/G4cerr is not setup
throw std::ios_base::failure("No output file name specified");
#endif
}
if ( m_output != nullptr && m_output->is_open() ) Close();
m_output.reset( new std::ofstream(m_name , std::ios_base::out|mode) );
if(m_output != nullptr && m_output->is_open())
Close();
m_output.reset(new std::ofstream(m_name, std::ios_base::out | mode));
}
// --------------------------------------------------------------------
void G4FilecoutDestination::Close()
{
if ( m_output && m_output->is_open() )
if(m_output && m_output->is_open())
{
m_output->close();
}
}
// --------------------------------------------------------------------
G4int G4FilecoutDestination::ReceiveG4cout(const G4String& msg)
{
if ( m_output == nullptr || ! m_output->is_open() ) Open(m_mode);
if(m_output == nullptr || !m_output->is_open())
Open(m_mode);
*m_output << msg;
return 0;
}
// --------------------------------------------------------------------
G4int G4FilecoutDestination::ReceiveG4cerr(const G4String& msg)
{
if ( m_output == nullptr || ! m_output->is_open() ) Open(m_mode);
if(m_output == nullptr || !m_output->is_open())
Open(m_mode);
*m_output << msg;
return 0;
}
@@ -23,46 +23,38 @@
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
// G4GeometryTolerance class implementation
//
//
// class G4GeometryTolerance
//
// Implementation
//
// Author:
// 30.10.06 - G.Cosmo, first implementation
// Author: G.Cosmo (CERN), 30 October 2006
// --------------------------------------------------------------------
#include "G4GeometryTolerance.hh"
#include "G4SystemOfUnits.hh"
#include "G4AutoDelete.hh"
#include "G4SystemOfUnits.hh"
#include "globals.hh"
// ***************************************************************************
// Static class instance
// ***************************************************************************
//
G4ThreadLocal G4GeometryTolerance* G4GeometryTolerance::fpInstance = 0;
G4ThreadLocal G4GeometryTolerance* G4GeometryTolerance::fpInstance = nullptr;
// ***************************************************************************
// Constructor.
// ***************************************************************************
//
G4GeometryTolerance::G4GeometryTolerance() : fInitialised(false)
G4GeometryTolerance::G4GeometryTolerance()
{
fCarTolerance = 1E-9*mm;
fAngTolerance = 1E-9*rad;
fRadTolerance = 1E-9*mm;
fCarTolerance = 1E-9 * mm;
fAngTolerance = 1E-9 * rad;
fRadTolerance = 1E-9 * mm;
}
// ***************************************************************************
// Empty destructor.
// ***************************************************************************
//
G4GeometryTolerance::~G4GeometryTolerance()
{
}
G4GeometryTolerance::~G4GeometryTolerance() {}
// ***************************************************************************
// Returns the instance of the singleton.
@@ -71,12 +63,12 @@ G4GeometryTolerance::~G4GeometryTolerance()
//
G4GeometryTolerance* G4GeometryTolerance::GetInstance()
{
if (fpInstance == 0)
if(fpInstance == nullptr)
{
fpInstance = new G4GeometryTolerance;
fpInstance = new G4GeometryTolerance;
G4AutoDelete::Register(fpInstance);
}
return fpInstance;
return fpInstance;
}
// ***************************************************************************
@@ -105,18 +97,17 @@ G4double G4GeometryTolerance::GetRadialTolerance() const
//
void G4GeometryTolerance::SetSurfaceTolerance(G4double worldExtent)
{
if (!fInitialised)
if(!fInitialised)
{
fCarTolerance = fRadTolerance = worldExtent*1E-11;
fInitialised = true;
fCarTolerance = fRadTolerance = worldExtent * 1E-11;
fInitialised = true;
}
else
{
G4cout << "WARNING - G4GeometryTolerance::SetSurfaceTolerance()" << G4endl
<< " Tolerance can only be set once. Currently set to: "
<< fCarTolerance/mm << " mm." << G4endl;
G4Exception("G4GeometryTolerance::SetSurfaceTolerance()",
"NotApplicable", JustWarning,
"The tolerance has been already set!");
<< fCarTolerance / mm << " mm." << G4endl;
G4Exception("G4GeometryTolerance::SetSurfaceTolerance()", "NotApplicable",
JustWarning, "The tolerance has been already set!");
}
}
@@ -23,39 +23,23 @@
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
// G4LPhysicsFreeVector class implementation
//
//
//
// --------------------------------------------------------------------
// Class G4LPhysicsFreeVector
// Derived from base class G4PhysicsVector
// This is a free vector for Low Energy Physics cross section data
//
// F.W. Jones, TRIUMF, 04-JUN-96
//
// Modified:
// 19 Jun. 2009, V.Ivanchenko : removed hidden bin
// 19 Jun. 2009, V.Ivanchenko : removed FindBinLocation
//
// Author: F.W. Jones (TRIUMF), 04-June-1996 - First implementation
// --------------------------------------------------------------------
#include "G4LPhysicsFreeVector.hh"
// --------------------------------------------------------------------
G4LPhysicsFreeVector::G4LPhysicsFreeVector()
: G4PhysicsFreeVector()
: G4PhysicsFreeVector()
{}
// --------------------------------------------------------------------
G4LPhysicsFreeVector::G4LPhysicsFreeVector(size_t length, G4double, G4double)
G4LPhysicsFreeVector::G4LPhysicsFreeVector(std::size_t length, G4double,
G4double)
: G4PhysicsFreeVector(length)
{}
// --------------------------------------------------------------------
G4LPhysicsFreeVector::~G4LPhysicsFreeVector()
{}
// --------------------------------------------------------------------
G4LPhysicsFreeVector::~G4LPhysicsFreeVector() {}
@@ -23,10 +23,7 @@
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
//
// --------------------------------------------------------------------
//
// G4LockcoutDestination.cc
// G4LockcoutDestination class implementation
//
// Author: A.Dotti (SLAC), April 2017
// --------------------------------------------------------------------
@@ -39,18 +36,19 @@ namespace
G4Mutex out_mutex = G4MUTEX_INITIALIZER;
}
G4LockcoutDestination::~G4LockcoutDestination()
{
}
// --------------------------------------------------------------------
G4LockcoutDestination::~G4LockcoutDestination() {}
G4int G4LockcoutDestination::ReceiveG4cout(const G4String& msg )
// --------------------------------------------------------------------
G4int G4LockcoutDestination::ReceiveG4cout(const G4String& msg)
{
G4AutoLock l(&out_mutex);
// Forward call to base class
return G4coutDestination::ReceiveG4cout(msg);
}
G4int G4LockcoutDestination::ReceiveG4cerr(const G4String& msg )
// --------------------------------------------------------------------
G4int G4LockcoutDestination::ReceiveG4cerr(const G4String& msg)
{
G4AutoLock l(&out_mutex);
return G4coutDestination::ReceiveG4cerr(msg);
+45 -34
View File
@@ -22,69 +22,80 @@
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
// G4MTBarrier class implementation
//
// ---------------------------------------------------------------
/*
* G4MTBarrier.cc
*
* Created on: Feb 10, 2016
* Author: adotti
* Updated on: Feb 9, 2018
* Author: jmadsen
*/
// Author: A.Dotti (SLAC), 10 February 2016
// Revision: J.Madsen (NERSC), 09 February 2018
// --------------------------------------------------------------------
#include "G4MTBarrier.hh"
#include "G4AutoLock.hh"
G4MTBarrier::G4MTBarrier(unsigned int numThreads ) :
m_numActiveThreads(numThreads),
m_counter(0)
// --------------------------------------------------------------------
G4MTBarrier::G4MTBarrier(unsigned int numThreads)
: m_numActiveThreads(numThreads)
{}
void G4MTBarrier::ThisWorkerReady() {
//Step-1: Worker acquires lock on shared resource (the counter)
// --------------------------------------------------------------------
void G4MTBarrier::ThisWorkerReady()
{
// Step-1: Worker acquires lock on shared resource (the counter)
G4AutoLock lock(&m_mutex);
//Step-2: Worker increases counter
// Step-2: Worker increases counter
++m_counter;
//Step-3: Worker broadcasts that the counter has changed
// Step-3: Worker broadcasts that the counter has changed
G4CONDITIONBROADCAST(&m_counterChanged);
//Step-4: Worker waits on condition to continue
G4CONDITIONWAIT(&m_continue,&lock);
// Step-4: Worker waits on condition to continue
G4CONDITIONWAIT(&m_continue, &lock);
}
void G4MTBarrier::Wait() {
while (true)
// --------------------------------------------------------------------
void G4MTBarrier::Wait()
{
while(true)
{
//Step-2: Acquires lock on shared resource (the counter)
G4AutoLock lock(&m_mutex);
//If the counter equals active threads, all threads are ready, exit the loop
if ( m_counter == m_numActiveThreads ) { break; }
//Step-3: Not all workers are ready, wait for the number to change
//before repeating the check
G4CONDITIONWAIT(&m_counterChanged,&lock);
// Step-2: Acquires lock on shared resource (the counter)
G4AutoLock lock(&m_mutex);
// If the counter equals active threads, all threads are ready, exit the
// loop
if(m_counter == m_numActiveThreads)
{
break;
}
// Step-3: Not all workers are ready, wait for the number to change
// before repeating the check
G4CONDITIONWAIT(&m_counterChanged, &lock);
}
}
void G4MTBarrier::ReleaseBarrier() {
//Step-4: re-aquire lock and re-set shared resource for future re-use
// --------------------------------------------------------------------
void G4MTBarrier::ReleaseBarrier()
{
// Step-4: re-aquire lock and re-set shared resource for future re-use
G4AutoLock lock(&m_mutex);
m_counter = 0;
G4CONDITIONBROADCAST(&m_continue);
}
void G4MTBarrier::WaitForReadyWorkers() {
//Step-1: Master enters a loop to wait all workers to be ready
// --------------------------------------------------------------------
void G4MTBarrier::WaitForReadyWorkers()
{
// Step-1: Master enters a loop to wait all workers to be ready
Wait();
//Done, all workers are ready, broadcast a continue signal
// Done, all workers are ready, broadcast a continue signal
ReleaseBarrier();
}
void G4MTBarrier::ResetCounter() {
// --------------------------------------------------------------------
void G4MTBarrier::ResetCounter()
{
G4AutoLock l(&m_mutex);
m_counter = 0;
}
unsigned int G4MTBarrier::GetCounter() {
// --------------------------------------------------------------------
unsigned int G4MTBarrier::GetCounter()
{
G4AutoLock l(&m_mutex);
const unsigned int result = m_counter;
return result;
@@ -23,121 +23,126 @@
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
//
// --------------------------------------------------------------------
// G4MTcoutDestination class implementation
//
// G4MTcoutDestination.cc
//
// --------------------------------------------------------------------
// Authors: M.Asai, A.Dotti (SLAC) - 23 May 2013
// ---------------------------------------------------------------
#include <sstream>
#include <assert.h>
#include <sstream>
#include "G4MTcoutDestination.hh"
#include "G4LockcoutDestination.hh"
#include "G4MasterForwardcoutDestination.hh"
#include "G4FilecoutDestination.hh"
#include "G4BuffercoutDestination.hh"
#include "G4strstreambuf.hh"
#include "G4AutoLock.hh"
#include "G4BuffercoutDestination.hh"
#include "G4FilecoutDestination.hh"
#include "G4LockcoutDestination.hh"
#include "G4MTcoutDestination.hh"
#include "G4MasterForwardcoutDestination.hh"
#include "G4strstreambuf.hh"
namespace
{
G4String empty = "";
}
// --------------------------------------------------------------------
G4MTcoutDestination::G4MTcoutDestination(const G4int& threadId)
: ref_defaultOut(nullptr), ref_masterOut(nullptr),
masterDestinationFlag(true),masterDestinationFmtFlag(true),
id(threadId), useBuffer(false), ignoreCout(false), ignoreInit(true),
prefix("G4WT")
: id(threadId)
{
// TODO: Move these two out of here and in the caller
G4coutbuf.SetDestination(this);
G4cerrbuf.SetDestination(this);
stateMgr=G4StateManager::GetStateManager();
SetDefaultOutput(masterDestinationFlag,masterDestinationFmtFlag);
stateMgr = G4StateManager::GetStateManager();
SetDefaultOutput(masterDestinationFlag, masterDestinationFmtFlag);
}
void G4MTcoutDestination::SetDefaultOutput( G4bool addmasterDestination ,
G4bool formatAlsoMaster )
// --------------------------------------------------------------------
void G4MTcoutDestination::SetDefaultOutput(G4bool addmasterDestination,
G4bool formatAlsoMaster)
{
masterDestinationFlag = addmasterDestination;
masterDestinationFlag = addmasterDestination;
masterDestinationFmtFlag = formatAlsoMaster;
// Formatter: add prefix to each thread
const auto f = [this](G4String& msg)->G4bool {
const auto f = [this](G4String& msg) -> G4bool {
std::ostringstream str;
str<<prefix;
if ( id!=G4Threading::GENERICTHREAD_ID ) str<<id;
str<<" > "<<msg;
str << prefix;
if(id != G4Threading::GENERICTHREAD_ID)
str << id;
str << " > " << msg;
msg = str.str();
return true;
};
// Block cout if not in correct state
const auto filter_out = [this](G4String&)->G4bool {
if (this->ignoreCout ||
( this->ignoreInit &&
this->stateMgr->GetCurrentState() == G4State_Init ) )
{ return false; }
const auto filter_out = [this](G4String&) -> G4bool {
if(this->ignoreCout ||
(this->ignoreInit && this->stateMgr->GetCurrentState() == G4State_Init))
{
return false;
}
return true;
};
// Default behavior, add a destination that uses cout and uses a mutex
auto output = G4coutDestinationUPtr( new G4LockcoutDestination );
auto output = G4coutDestinationUPtr(new G4LockcoutDestination);
ref_defaultOut = output.get();
output->AddCoutTransformer(filter_out);
output->AddCoutTransformer(f);
output->AddCerrTransformer(f);
push_back( std::move(output) );
if ( addmasterDestination )
push_back(std::move(output));
if(addmasterDestination)
{
AddMasterOutput(formatAlsoMaster);
AddMasterOutput(formatAlsoMaster);
}
}
void G4MTcoutDestination::AddMasterOutput(G4bool formatAlsoMaster )
// --------------------------------------------------------------------
void G4MTcoutDestination::AddMasterOutput(G4bool formatAlsoMaster)
{
// Add a destination, that forwards the message to the master thread
auto forwarder = G4coutDestinationUPtr( new G4MasterForwardcoutDestination );
ref_masterOut = forwarder.get();
const auto filter_out = [this](G4String&)->G4bool {
if (this->ignoreCout ||
( this->ignoreInit &&
this->stateMgr->GetCurrentState() == G4State_Idle ) )
{ return false; }
auto forwarder = G4coutDestinationUPtr(new G4MasterForwardcoutDestination);
ref_masterOut = forwarder.get();
const auto filter_out = [this](G4String&) -> G4bool {
if(this->ignoreCout ||
(this->ignoreInit && this->stateMgr->GetCurrentState() == G4State_Idle))
{
return false;
}
return true;
};
forwarder->AddCoutTransformer(filter_out);
if ( formatAlsoMaster )
if(formatAlsoMaster)
{
// Formatter: add prefix to each thread
const auto f = [this](G4String& msg)->G4bool {
std::ostringstream str;
str<<prefix;
if ( id!=G4Threading::GENERICTHREAD_ID ) str<<id;
str<<" > "<<msg;
msg = str.str();
return true;
};
forwarder->AddCoutTransformer(f);
forwarder->AddCerrTransformer(f);
// Formatter: add prefix to each thread
const auto f = [this](G4String& msg) -> G4bool {
std::ostringstream str;
str << prefix;
if(id != G4Threading::GENERICTHREAD_ID)
str << id;
str << " > " << msg;
msg = str.str();
return true;
};
forwarder->AddCoutTransformer(f);
forwarder->AddCerrTransformer(f);
}
push_back( std::move(forwarder ) );
push_back(std::move(forwarder));
}
// --------------------------------------------------------------------
G4MTcoutDestination::~G4MTcoutDestination()
{
if ( useBuffer ) DumpBuffer();
if(useBuffer)
DumpBuffer();
}
// --------------------------------------------------------------------
void G4MTcoutDestination::Reset()
{
clear();
SetDefaultOutput(masterDestinationFlag,masterDestinationFmtFlag);
SetDefaultOutput(masterDestinationFlag, masterDestinationFmtFlag);
}
// --------------------------------------------------------------------
void G4MTcoutDestination::HandleFileCout(G4String fileN, G4bool ifAppend,
G4bool suppressDefault)
{
@@ -145,104 +150,124 @@ void G4MTcoutDestination::HandleFileCout(G4String fileN, G4bool ifAppend,
// stream and should discard everything in G4cerr.
// First we create the destination with the appropriate open mode
std::ios_base::openmode mode = (ifAppend ? std::ios_base::app
: std::ios_base::trunc);
auto output = G4coutDestinationUPtr( new G4FilecoutDestination(fileN,mode));
std::ios_base::openmode mode =
(ifAppend ? std::ios_base::app : std::ios_base::trunc);
auto output = G4coutDestinationUPtr(new G4FilecoutDestination(fileN, mode));
// This reacts only to G4cout, so let's make a filter that removes everything
// from G4cerr
output->AddCerrTransformer( [](G4String&) { return false;} );
output->AddCerrTransformer([](G4String&) { return false; });
push_back(std::move(output));
// Silence G4cout from default formatter
if ( suppressDefault )
if(suppressDefault)
{
ref_defaultOut->AddCoutTransformer( [](G4String&) { return false; } );
if ( ref_masterOut )
ref_masterOut->AddCoutTransformer( [](G4String&) { return false; } );
ref_defaultOut->AddCoutTransformer([](G4String&) { return false; });
if(ref_masterOut)
ref_masterOut->AddCoutTransformer([](G4String&) { return false; });
}
}
// --------------------------------------------------------------------
void G4MTcoutDestination::HandleFileCerr(G4String fileN, G4bool ifAppend,
G4bool suppressDefault)
{
// See HandleFileCout for explanation, switching cout with cerr
std::ios_base::openmode mode = (ifAppend ? std::ios_base::app
: std::ios_base::trunc);
auto output = G4coutDestinationUPtr( new G4FilecoutDestination(fileN,mode));
output->AddCoutTransformer( [](G4String&) { return false;} );
std::ios_base::openmode mode =
(ifAppend ? std::ios_base::app : std::ios_base::trunc);
auto output = G4coutDestinationUPtr(new G4FilecoutDestination(fileN, mode));
output->AddCoutTransformer([](G4String&) { return false; });
push_back(std::move(output));
if ( suppressDefault )
if(suppressDefault)
{
ref_defaultOut->AddCerrTransformer( [](G4String&) { return false; } );
if ( ref_masterOut )
ref_masterOut->AddCerrTransformer( [](G4String&) { return false; } );
ref_defaultOut->AddCerrTransformer([](G4String&) { return false; });
if(ref_masterOut)
ref_masterOut->AddCerrTransformer([](G4String&) { return false; });
}
}
// --------------------------------------------------------------------
void G4MTcoutDestination::SetCoutFileName(const G4String& fileN,
G4bool ifAppend)
G4bool ifAppend)
{
// First let's go back to the default
Reset();
if ( fileN != "**Screen**" )
if(fileN != "**Screen**")
{
HandleFileCout(fileN,ifAppend,true);
HandleFileCout(fileN, ifAppend, true);
}
}
// --------------------------------------------------------------------
void G4MTcoutDestination::EnableBuffering(G4bool flag)
{
// I was using buffered output and now I want to turn it off, dump current
// buffer content and reset output
if ( useBuffer && !flag )
if(useBuffer && !flag)
{
DumpBuffer();
Reset();
DumpBuffer();
Reset();
}
else if ( useBuffer && flag ) { /* do nothing: already using */ }
else if ( !useBuffer && !flag ) { /* do nothing: not using */ }
else if ( !useBuffer && flag )
else if(useBuffer && flag)
{ /* do nothing: already using */
}
else if(!useBuffer && !flag)
{ /* do nothing: not using */
}
else if(!useBuffer && flag)
{
// Remove everything, in this case also removing the forward to the master
// thread, we want everything to be dumpled to a file
clear();
const size_t infiniteSize = 0;
push_back(G4coutDestinationUPtr(new G4BuffercoutDestination(infiniteSize)));
// Remove everything, in this case also removing the forward to the master
// thread, we want everything to be dumpled to a file
clear();
const size_t infiniteSize = 0;
push_back(G4coutDestinationUPtr(new G4BuffercoutDestination(infiniteSize)));
}
else // Should never happen
{
assert(false);
}
else { assert(false); } // Should never happen
useBuffer = flag;
}
// --------------------------------------------------------------------
void G4MTcoutDestination::AddCoutFileName(const G4String& fileN,
G4bool ifAppend)
G4bool ifAppend)
{
// This is like the equivalent SetCoutFileName, but in this case we do not
// remove or silence what is already exisiting
HandleFileCout(fileN,ifAppend,false);
HandleFileCout(fileN, ifAppend, false);
}
// --------------------------------------------------------------------
void G4MTcoutDestination::SetCerrFileName(const G4String& fileN,
G4bool ifAppend)
G4bool ifAppend)
{
// See SetCoutFileName for explanation
Reset();
if ( fileN != "**Screen**")
if(fileN != "**Screen**")
{
HandleFileCerr(fileN,ifAppend,true);
HandleFileCerr(fileN, ifAppend, true);
}
}
// --------------------------------------------------------------------
void G4MTcoutDestination::AddCerrFileName(const G4String& fileN,
G4bool ifAppend)
G4bool ifAppend)
{
HandleFileCerr(fileN,ifAppend,false);
HandleFileCerr(fileN, ifAppend, false);
}
// --------------------------------------------------------------------
void G4MTcoutDestination::SetIgnoreCout(G4int tid)
{
if (tid<0) { ignoreCout = false; }
else { ignoreCout = (tid!=id); }
if(tid < 0)
{
ignoreCout = false;
}
else
{
ignoreCout = (tid != id);
}
}
namespace
@@ -250,6 +275,7 @@ namespace
G4Mutex coutm = G4MUTEX_INITIALIZER;
}
// --------------------------------------------------------------------
void G4MTcoutDestination::DumpBuffer()
{
G4AutoLock l(&coutm);
@@ -258,30 +284,42 @@ void G4MTcoutDestination::DumpBuffer()
msg << "cout buffer(s) for worker with ID:" << id << std::endl;
G4coutDestination::ReceiveG4cout(msg.str());
G4bool sep = false;
std::for_each( begin() , end(),
[this,&sep](G4coutDestinationUPtr& el) {
auto cout = dynamic_cast<G4BuffercoutDestination*>(el.get());
if ( cout != nullptr ) {
cout->FlushG4cout();
if ( sep ) { G4coutDestination::ReceiveG4cout("==========\n"); }
else { sep = true; }
}
} );
std::for_each(begin(), end(), [this, &sep](G4coutDestinationUPtr& el) {
auto cout = dynamic_cast<G4BuffercoutDestination*>(el.get());
if(cout != nullptr)
{
cout->FlushG4cout();
if(sep)
{
G4coutDestination::ReceiveG4cout("==========\n");
}
else
{
sep = true;
}
}
});
sep = false;
msg.str("");
msg.clear();
msg << "=======================\n";
msg << "cerr buffer(s) for worker with ID:" << id
<< " (goes to std error)" << std::endl;
msg << "cerr buffer(s) for worker with ID:" << id << " (goes to std error)"
<< std::endl;
G4coutDestination::ReceiveG4cout(msg.str());
std::for_each( begin() , end(),
[this,&sep](G4coutDestinationUPtr& el) {
auto cout = dynamic_cast<G4BuffercoutDestination*>(el.get());
if ( cout != nullptr ) {
cout->FlushG4cerr();
if (sep ) { G4coutDestination::ReceiveG4cout("==========\n"); }
else { sep = true; }
}
} );
std::for_each(begin(), end(), [this, &sep](G4coutDestinationUPtr& el) {
auto cout = dynamic_cast<G4BuffercoutDestination*>(el.get());
if(cout != nullptr)
{
cout->FlushG4cerr();
if(sep)
{
G4coutDestination::ReceiveG4cout("==========\n");
}
else
{
sep = true;
}
}
});
G4coutDestination::ReceiveG4cout("=======================\n");
}
@@ -23,10 +23,7 @@
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
//
// --------------------------------------------------------------------
//
// G4MasterForwardcoutDestination.cc
// G4MasterForwardcoutDestination class implementation
//
// Author: A.Dotti (SLAC), April 2017
// --------------------------------------------------------------------
@@ -39,30 +36,31 @@ namespace
G4Mutex out_mutex = G4MUTEX_INITIALIZER;
}
G4MasterForwardcoutDestination::~G4MasterForwardcoutDestination()
{
}
// --------------------------------------------------------------------
G4MasterForwardcoutDestination::~G4MasterForwardcoutDestination() {}
G4int G4MasterForwardcoutDestination::ReceiveG4cout(const G4String& msg )
// --------------------------------------------------------------------
G4int G4MasterForwardcoutDestination::ReceiveG4cout(const G4String& msg)
{
// If a master destination is set check that we are not in a recursive
// situation, send the message to the master, using a lock to serialize calls
// Master is probably a (G)UI that is not thread-safe
if ( masterG4coutDestination && this!=masterG4coutDestination)
if(masterG4coutDestination && this != masterG4coutDestination)
{
G4AutoLock l(&out_mutex);
return masterG4coutDestination->ReceiveG4cout_(msg);
G4AutoLock l(&out_mutex);
return masterG4coutDestination->ReceiveG4cout_(msg);
}
return 0;
}
G4int G4MasterForwardcoutDestination::ReceiveG4cerr(const G4String& msg )
// --------------------------------------------------------------------
G4int G4MasterForwardcoutDestination::ReceiveG4cerr(const G4String& msg)
{
if ( masterG4coutDestination && this!=masterG4coutDestination)
if(masterG4coutDestination && this != masterG4coutDestination)
{
G4AutoLock l(&out_mutex);
return masterG4coutDestination->ReceiveG4cerr_(msg);
G4AutoLock l(&out_mutex);
return masterG4coutDestination->ReceiveG4cerr_(msg);
}
return 0;
}
+104 -81
View File
@@ -23,51 +23,74 @@
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
// G4OrderedTable class implementation
//
//
//
// ------------------------------------------------------------
// GEANT 4 class implementation
//
// G4OrderedTable
//
// ------------------------------------------------------------
// Author: M.Maire (LAPP), September 1996
// Revisions: H.Kurashige (Kobe Univ.), January-September 2001
// --------------------------------------------------------------------
#include "G4DataVector.hh"
#include "G4OrderedTable.hh"
#include <iostream>
#include "G4DataVector.hh"
#include <fstream>
#include <iomanip>
#include <iostream>
// --------------------------------------------------------------------
G4OrderedTable::G4OrderedTable()
: std::vector<G4DataVector*>()
{
}
{}
G4OrderedTable::G4OrderedTable(size_t cap)
: std::vector<G4DataVector*>(cap, (G4DataVector*)(0) )
{
}
// --------------------------------------------------------------------
G4OrderedTable::G4OrderedTable(std::size_t cap)
: std::vector<G4DataVector*>(cap, (G4DataVector*) (0))
{}
G4OrderedTable::~G4OrderedTable()
{
}
// --------------------------------------------------------------------
G4OrderedTable::~G4OrderedTable() {}
G4bool G4OrderedTable::Store(const G4String& fileName,
G4bool ascii)
// --------------------------------------------------------------------
void G4OrderedTable::clearAndDestroy()
{
std::ofstream fOut;
// open output file //
if (!ascii)
{ fOut.open(fileName, std::ios::out|std::ios::binary); }
else
{ fOut.open(fileName, std::ios::out); }
// check if the file has been opened successfully
if (!fOut)
G4DataVector* a = nullptr;
while(size() > 0)
{
#ifdef G4VERBOSE
a = back();
pop_back();
for(auto i = cbegin(); i != cend(); ++i)
{
if(*i == a)
{
erase(i);
--i;
}
}
if(a != nullptr)
{
delete a;
}
}
}
// --------------------------------------------------------------------
G4bool G4OrderedTable::Store(const G4String& fileName, G4bool ascii)
{
std::ofstream fOut;
// open output file //
if(!ascii)
{
fOut.open(fileName, std::ios::out | std::ios::binary);
}
else
{
fOut.open(fileName, std::ios::out);
}
// check if the file has been opened successfully
if(!fOut)
{
#ifdef G4VERBOSE
G4cerr << "G4OrderedTable::::Store():";
G4cerr << " Cannot open file: " << fileName << G4endl;
#endif
@@ -75,51 +98,51 @@ G4bool G4OrderedTable::Store(const G4String& fileName,
return false;
}
// Number of elements
G4int tableSize = G4int(size());
if (!ascii)
G4int tableSize = G4int(size()); // Number of elements
if(!ascii)
{
fOut.write( (char*)(&tableSize), sizeof tableSize);
fOut.write((char*) (&tableSize), sizeof tableSize);
}
else
{
fOut << tableSize << G4endl;
}
// Data Vector
G4int vType = G4DataVector::T_G4DataVector;
for (G4OrderedTableIterator itr=begin(); itr!=end(); ++itr)
G4int vType = G4DataVector::T_G4DataVector; // Data Vector
for(auto itr = cbegin(); itr != cend(); ++itr)
{
if (!ascii)
if(!ascii)
{
fOut.write( (char*)(&vType), sizeof vType);
fOut.write((char*) (&vType), sizeof vType);
}
else
{
fOut << vType << G4endl;
}
(*itr)->Store(fOut,ascii);
(*itr)->Store(fOut, ascii);
}
fOut.close();
return true;
}
G4bool G4OrderedTable::Retrieve(const G4String& fileName,
G4bool ascii)
// --------------------------------------------------------------------
G4bool G4OrderedTable::Retrieve(const G4String& fileName, G4bool ascii)
{
std::ifstream fIn;
std::ifstream fIn;
// open input file //
if (!ascii)
{ fIn.open(fileName,std::ios::in|std::ios::binary); }
else
{ fIn.open(fileName,std::ios::in); }
// check if the file has been opened successfully
if (!fIn)
if(!ascii)
{
#ifdef G4VERBOSE
fIn.open(fileName, std::ios::in | std::ios::binary);
}
else
{
fIn.open(fileName, std::ios::in);
}
// check if the file has been opened successfully
if(!fIn)
{
#ifdef G4VERBOSE
G4cerr << "G4OrderedTable::Retrieve():";
G4cerr << " Cannot open file: " << fileName << G4endl;
#endif
@@ -127,62 +150,62 @@ G4bool G4OrderedTable::Retrieve(const G4String& fileName,
return false;
}
// clear
// clear
clearAndDestroy();
// Number of elements
G4int tableSize=0;
if (!ascii)
G4int tableSize = 0;
if(!ascii)
{
fIn.read((char*)(&tableSize), sizeof tableSize);
fIn.read((char*) (&tableSize), sizeof tableSize);
}
else
{
fIn >> tableSize;
}
if (tableSize<=0)
if(tableSize <= 0)
{
#ifdef G4VERBOSE
#ifdef G4VERBOSE
G4cerr << "G4OrderedTable::Retrieve():";
G4cerr << " Invalid table size: " << tableSize << G4endl;
#endif
return false;
}
reserve(tableSize);
reserve(tableSize);
// Physics Vector
for (G4int idx=0; idx<tableSize; ++idx)
for(G4int idx = 0; idx < tableSize; ++idx)
{
G4int vType=0;
if (!ascii)
G4int vType = 0;
if(!ascii)
{
fIn.read( (char*)(&vType), sizeof vType);
fIn.read((char*) (&vType), sizeof vType);
}
else
{
fIn >> vType;
fIn >> vType;
}
if (vType != G4DataVector::T_G4DataVector)
if(vType != G4DataVector::T_G4DataVector)
{
#ifdef G4VERBOSE
#ifdef G4VERBOSE
G4cerr << "G4OrderedTable::Retrieve():";
G4cerr << " Illegal Data Vector type: " << vType << " in ";
G4cerr << fileName << G4endl;
#endif
#endif
fIn.close();
return false;
}
G4DataVector* pVec = new G4DataVector;
if (! (pVec->Retrieve(fIn,ascii)) )
if(!(pVec->Retrieve(fIn, ascii)))
{
#ifdef G4VERBOSE
#ifdef G4VERBOSE
G4cerr << "G4OrderedTable::Retrieve(): ";
G4cerr << " Error in retreiving " << idx
<< "-th Physics Vector from file: ";
G4cerr << fileName << G4endl;
#endif
#endif
fIn.close();
delete pVec;
return false;
@@ -190,23 +213,23 @@ G4bool G4OrderedTable::Retrieve(const G4String& fileName,
// add a PhysicsVector to this OrderedTable
push_back(pVec);
}
}
fIn.close();
return true;
}
std::ostream& operator<<(std::ostream& out,
G4OrderedTable& right)
// --------------------------------------------------------------------
std::ostream& operator<<(std::ostream& out, G4OrderedTable& right)
{
// Printout Data Vector
size_t i=0;
for (G4OrderedTableIterator itr=right.begin(); itr!=right.end(); ++itr)
std::size_t i = 0;
for(auto itr = right.cbegin(); itr != right.cend(); ++itr)
{
out << std::setw(8) << i << "-th Vector ";
out << ": Type " << G4DataVector::T_G4DataVector << G4endl;
out << *(*itr);
i +=1;
i += 1;
}
out << G4endl;
return out;
return out;
}
+227 -214
View File
@@ -23,16 +23,10 @@
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
// --------------------------------------------------------------
// GEANT 4 class implementation file
// G4Physics2DVector class implementation
//
// G4Physics2DVector.cc
//
// Author: Vladimir Ivanchenko
//
// Creation date: 25.09.2011
//
// --------------------------------------------------------------
// Author: Vladimir Ivanchenko, 25.09.2011
// --------------------------------------------------------------------
#include <iomanip>
@@ -40,34 +34,33 @@
// --------------------------------------------------------------
G4Physics2DVector::G4Physics2DVector()
: type(T_G4PhysicsFreeVector),
numberOfXNodes(0), numberOfYNodes(0),
verboseLevel(0), useBicubic(false)
{}
G4Physics2DVector::G4Physics2DVector() { PrepareVectors(); }
// --------------------------------------------------------------
G4Physics2DVector::G4Physics2DVector(size_t nx, size_t ny)
: type(T_G4PhysicsFreeVector),
numberOfXNodes(nx), numberOfYNodes(ny),
verboseLevel(0), useBicubic(false)
G4Physics2DVector::G4Physics2DVector(std::size_t nx, std::size_t ny)
{
if(nx < 2 || ny < 2)
{
G4ExceptionDescription ed;
ed << "G4Physics2DVector is too short: nx= " << nx << " numy= " << ny;
G4Exception("G4Physics2DVector::G4Physics2DVector()", "glob03",
FatalException, ed, "Both lengths should be above 1");
}
numberOfXNodes = nx;
numberOfYNodes = ny;
PrepareVectors();
}
// --------------------------------------------------------------
G4Physics2DVector::~G4Physics2DVector()
{
ClearVectors();
}
G4Physics2DVector::~G4Physics2DVector() { ClearVectors(); }
// --------------------------------------------------------------
G4Physics2DVector::G4Physics2DVector(const G4Physics2DVector& right)
{
type = right.type;
type = right.type;
numberOfXNodes = right.numberOfXNodes;
numberOfYNodes = right.numberOfYNodes;
@@ -75,8 +68,8 @@ G4Physics2DVector::G4Physics2DVector(const G4Physics2DVector& right)
verboseLevel = right.verboseLevel;
useBicubic = right.useBicubic;
xVector = right.xVector;
yVector = right.yVector;
xVector = right.xVector;
yVector = right.yVector;
PrepareVectors();
CopyData(right);
@@ -86,10 +79,13 @@ G4Physics2DVector::G4Physics2DVector(const G4Physics2DVector& right)
G4Physics2DVector& G4Physics2DVector::operator=(const G4Physics2DVector& right)
{
if (&right==this) { return *this; }
if(&right == this)
{
return *this;
}
ClearVectors();
type = right.type;
type = right.type;
numberOfXNodes = right.numberOfXNodes;
numberOfYNodes = right.numberOfYNodes;
@@ -107,13 +103,12 @@ G4Physics2DVector& G4Physics2DVector::operator=(const G4Physics2DVector& right)
void G4Physics2DVector::PrepareVectors()
{
xVector.resize(numberOfXNodes,0.);
yVector.resize(numberOfYNodes,0.);
value.resize(numberOfYNodes,0);
for(size_t j=0; j<numberOfYNodes; ++j) {
G4PV2DDataVector* v = new G4PV2DDataVector();
v->resize(numberOfXNodes,0.);
value[j] = v;
xVector.resize(numberOfXNodes, 0.);
yVector.resize(numberOfYNodes, 0.);
value.resize(numberOfYNodes);
for(std::size_t j = 0; j < numberOfYNodes; ++j)
{
value[j] = new G4PV2DDataVector(numberOfXNodes, 0.);
}
}
@@ -121,149 +116,168 @@ void G4Physics2DVector::PrepareVectors()
void G4Physics2DVector::ClearVectors()
{
for(size_t j=0; j<numberOfYNodes; ++j) {
for(std::size_t j = 0; j < numberOfYNodes; ++j)
{
delete value[j];
}
}
// --------------------------------------------------------------
void G4Physics2DVector::CopyData(const G4Physics2DVector &right)
void G4Physics2DVector::CopyData(const G4Physics2DVector& right)
{
for(size_t i=0; i<numberOfXNodes; ++i) {
for(std::size_t i = 0; i < numberOfXNodes; ++i)
{
xVector[i] = right.xVector[i];
}
for(size_t j=0; j<numberOfYNodes; ++j) {
yVector[j] = right.yVector[j];
for(std::size_t j = 0; j < numberOfYNodes; ++j)
{
yVector[j] = right.yVector[j];
G4PV2DDataVector* v0 = right.value[j];
for(size_t i=0; i<numberOfXNodes; ++i) {
PutValue(i,j,(*v0)[i]);
for(std::size_t i = 0; i < numberOfXNodes; ++i)
{
PutValue(i, j, (*v0)[i]);
}
}
}
// --------------------------------------------------------------
G4double G4Physics2DVector::Value(G4double xx, G4double yy,
size_t& idx, size_t& idy) const
G4double G4Physics2DVector::Value(G4double xx, G4double yy, std::size_t& idx,
std::size_t& idy) const
{
G4double x = xx;
G4double y = yy;
// no interpolation outside the table
if(x < xVector[0]) {
x = xVector[0];
} else if(x > xVector[numberOfXNodes - 1]) {
x = xVector[numberOfXNodes - 1];
}
if(y < yVector[0]) {
y = yVector[0];
} else if(y > yVector[numberOfYNodes - 1]) {
y = yVector[numberOfYNodes - 1];
}
const G4double x =
std::min(std::max(xx, xVector[0]), xVector[numberOfXNodes - 1]);
const G4double y =
std::min(std::max(yy, yVector[0]), yVector[numberOfYNodes - 1]);
// find bins
idx = FindBinLocationX(x, idx);
idy = FindBinLocationY(y, idy);
// interpolate
if(useBicubic) {
if(useBicubic)
{
return BicubicInterpolation(x, y, idx, idy);
} else {
G4double x1 = xVector[idx];
G4double x2 = xVector[idx+1];
G4double y1 = yVector[idy];
G4double y2 = yVector[idy+1];
G4double v11= GetValue(idx, idy);
G4double v12= GetValue(idx+1, idy);
G4double v21= GetValue(idx, idy+1);
G4double v22= GetValue(idx+1, idy+1);
return ((y2 - y)*(v11*(x2 - x) + v12*(x - x1)) +
((y - y1)*(v21*(x2 - x) + v22*(x - x1))))/((x2 - x1)*(y2 - y1));
}
else
{
const G4double x1 = xVector[idx];
const G4double x2 = xVector[idx + 1];
const G4double y1 = yVector[idy];
const G4double y2 = yVector[idy + 1];
const G4double v11 = GetValue(idx, idy);
const G4double v12 = GetValue(idx + 1, idy);
const G4double v21 = GetValue(idx, idy + 1);
const G4double v22 = GetValue(idx + 1, idy + 1);
return ((y2 - y) * (v11 * (x2 - x) + v12 * (x - x1)) +
((y - y1) * (v21 * (x2 - x) + v22 * (x - x1)))) /
((x2 - x1) * (y2 - y1));
}
}
// --------------------------------------------------------------
G4double
G4Physics2DVector::BicubicInterpolation(G4double x, G4double y,
size_t idx, size_t idy) const
G4double G4Physics2DVector::BicubicInterpolation(const G4double x,
const G4double y,
const std::size_t idx,
const std::size_t idy) const
{
// Bicubic interpolation according to
// 1. H.M. Antia, "Numerical Methods for Scientists and Engineers",
// MGH, 1991.
// 2. W.H. Press et al., "Numerical recipes. The Art of Scientific
// Computing", Cambridge University Press, 2007.
G4double x1 = xVector[idx];
G4double x2 = xVector[idx+1];
G4double y1 = yVector[idy];
G4double y2 = yVector[idy+1];
G4double f1 = GetValue(idx, idy);
G4double f2 = GetValue(idx+1, idy);
G4double f3 = GetValue(idx+1, idy+1);
G4double f4 = GetValue(idx, idy+1);
// Bicubic interpolation according to
// 1. H.M. Antia, "Numerical Methods for Scientists and Engineers",
// MGH, 1991.
// 2. W.H. Press et al., "Numerical recipes. The Art of Scientific
// Computing", Cambridge University Press, 2007.
const G4double x1 = xVector[idx];
const G4double x2 = xVector[idx + 1];
const G4double y1 = yVector[idy];
const G4double y2 = yVector[idy + 1];
const G4double f1 = GetValue(idx, idy);
const G4double f2 = GetValue(idx + 1, idy);
const G4double f3 = GetValue(idx + 1, idy + 1);
const G4double f4 = GetValue(idx, idy + 1);
G4double dx = x2 - x1;
G4double dy = y2 - y1;
const G4double dx = x2 - x1;
const G4double dy = y2 - y1;
G4double h1 = (x - x1)/dx;
G4double h2 = (y - y1)/dy;
const G4double h1 = (x - x1) / dx;
const G4double h2 = (y - y1) / dy;
G4double h12 = h1*h1;
G4double h13 = h12*h1;
G4double h22 = h2*h2;
G4double h23 = h22*h2;
const G4double h12 = h1 * h1;
const G4double h13 = h12 * h1;
const G4double h22 = h2 * h2;
const G4double h23 = h22 * h2;
// Three derivatives at each of four points (1-4) defining the
// subregion are computed by numerical centered differencing from
// the functional values already tabulated on the grid.
// Three derivatives at each of four points (1-4) defining the
// subregion are computed by numerical centered differencing from
// the functional values already tabulated on the grid.
G4double f1x = DerivativeX(idx, idy, dx);
G4double f2x = DerivativeX(idx+1, idy, dx);
G4double f3x = DerivativeX(idx+1, idy+1, dx);
G4double f4x = DerivativeX(idx, idy+1, dx);
const G4double f1x = DerivativeX(idx, idy, dx);
const G4double f2x = DerivativeX(idx + 1, idy, dx);
const G4double f3x = DerivativeX(idx + 1, idy + 1, dx);
const G4double f4x = DerivativeX(idx, idy + 1, dx);
G4double f1y = DerivativeY(idx, idy, dy);
G4double f2y = DerivativeY(idx+1, idy, dy);
G4double f3y = DerivativeY(idx+1, idy+1, dy);
G4double f4y = DerivativeY(idx, idy+1, dy);
const G4double f1y = DerivativeY(idx, idy, dy);
const G4double f2y = DerivativeY(idx + 1, idy, dy);
const G4double f3y = DerivativeY(idx + 1, idy + 1, dy);
const G4double f4y = DerivativeY(idx, idy + 1, dy);
G4double dxy = dx*dy;
G4double f1xy = DerivativeXY(idx, idy, dxy);
G4double f2xy = DerivativeXY(idx+1, idy, dxy);
G4double f3xy = DerivativeXY(idx+1, idy+1, dxy);
G4double f4xy = DerivativeXY(idx, idy+1, dxy);
const G4double dxy = dx * dy;
const G4double f1xy = DerivativeXY(idx, idy, dxy);
const G4double f2xy = DerivativeXY(idx + 1, idy, dxy);
const G4double f3xy = DerivativeXY(idx + 1, idy + 1, dxy);
const G4double f4xy = DerivativeXY(idx, idy + 1, dxy);
return
f1 + f1y*h2 + (3*(f4-f1) - 2*f1y - f4y)*h22 + (2*(f1 - f4) + f1y + f4y)*h23
+ f1x*h1 + f1xy*h1*h2 +(3*(f4x - f1x) - 2*f1xy - f4xy)*h1*h22
+ (2*(f1x - f4x) + f1xy + f4xy)*h1*h23
+ (3*(f2 - f1) - 2*f1x - f2x)*h12 + (3*f2y - 3*f1y - 2*f1xy - f2xy)*h12*h2
+ (9*(f1 - f2 + f3 - f4) + 6*f1x + 3*f2x - 3*f3x - 6*f4x + 6*f1y - 6*f2y
- 3*f3y + 3*f4y + 4*f1xy + 2*f2xy + f3xy + 2*f4xy)*h12*h22
+ (6*(-f1 + f2 - f3 + f4) - 4*f1x - 2*f2x + 2*f3x + 4*f4x - 3*f1y
+ 3*f2y + 3*f3y - 3*f4y - 2*f1xy - f2xy - f3xy - 2*f4xy)*h12*h23
+ (2*(f1 - f2) + f1x + f2x)*h13 + (2*(f1y - f2y) + f1xy + f2xy)*h13*h2
+ (6*(-f1 + f2 -f3 + f4) + 3*(-f1x - f2x + f3x + f4x) - 4*f1y
+ 4*f2y + 2*f3y - 2*f4y - 2*f1xy - 2*f2xy - f3xy - f4xy)*h13*h22
+ (4*(f1 - f2 + f3 - f4) + 2*(f1x + f2x - f3x - f4x)
+ 2*(f1y - f2y - f3y + f4y) + f1xy + f2xy + f3xy + f4xy)*h13*h23;
return f1 + f1y * h2 + (3 * (f4 - f1) - 2 * f1y - f4y) * h22 +
(2 * (f1 - f4) + f1y + f4y) * h23 + f1x * h1 + f1xy * h1 * h2 +
(3 * (f4x - f1x) - 2 * f1xy - f4xy) * h1 * h22 +
(2 * (f1x - f4x) + f1xy + f4xy) * h1 * h23 +
(3 * (f2 - f1) - 2 * f1x - f2x) * h12 +
(3 * f2y - 3 * f1y - 2 * f1xy - f2xy) * h12 * h2 +
(9 * (f1 - f2 + f3 - f4) + 6 * f1x + 3 * f2x - 3 * f3x - 6 * f4x +
6 * f1y - 6 * f2y - 3 * f3y + 3 * f4y + 4 * f1xy + 2 * f2xy + f3xy +
2 * f4xy) *
h12 * h22 +
(6 * (-f1 + f2 - f3 + f4) - 4 * f1x - 2 * f2x + 2 * f3x + 4 * f4x -
3 * f1y + 3 * f2y + 3 * f3y - 3 * f4y - 2 * f1xy - f2xy - f3xy -
2 * f4xy) *
h12 * h23 +
(2 * (f1 - f2) + f1x + f2x) * h13 +
(2 * (f1y - f2y) + f1xy + f2xy) * h13 * h2 +
(6 * (-f1 + f2 - f3 + f4) + 3 * (-f1x - f2x + f3x + f4x) - 4 * f1y +
4 * f2y + 2 * f3y - 2 * f4y - 2 * f1xy - 2 * f2xy - f3xy - f4xy) *
h13 * h22 +
(4 * (f1 - f2 + f3 - f4) + 2 * (f1x + f2x - f3x - f4x) +
2 * (f1y - f2y - f3y + f4y) + f1xy + f2xy + f3xy + f4xy) *
h13 * h23;
}
// --------------------------------------------------------------
void
G4Physics2DVector::PutVectors(const std::vector<G4double>& vecX,
const std::vector<G4double>& vecY)
void G4Physics2DVector::PutVectors(const std::vector<G4double>& vecX,
const std::vector<G4double>& vecY)
{
ClearVectors();
numberOfXNodes = vecX.size();
numberOfYNodes = vecY.size();
std::size_t nx = vecX.size();
std::size_t ny = vecY.size();
if(nx < 2 || ny < 2)
{
G4ExceptionDescription ed;
ed << "G4Physics2DVector is too short: nx= " << nx << " ny= " << ny;
G4Exception("G4Physics2DVector::PutVectors()", "glob03", FatalException, ed,
"Both lengths should be above 1");
}
numberOfXNodes = nx;
numberOfYNodes = ny;
PrepareVectors();
for(size_t i = 0; i<numberOfXNodes; ++i) {
for(std::size_t i = 0; i < nx; ++i)
{
xVector[i] = vecX[i];
}
for(size_t j = 0; j<numberOfYNodes; ++j) {
for(std::size_t j = 0; j < ny; ++j)
{
yVector[j] = vecY[j];
}
}
@@ -274,24 +288,28 @@ void G4Physics2DVector::Store(std::ofstream& out) const
{
// binning
G4int prec = out.precision();
out << G4int(type) << " " << numberOfXNodes << " " << numberOfYNodes
<< G4endl;
out << std::setprecision(5);
out << G4int(type) << " " << numberOfXNodes << " " << numberOfYNodes
<< G4endl;
out << std::setprecision(8);
// contents
for(size_t i = 0; i<numberOfXNodes-1; ++i) {
out << xVector[i] << " ";
for(std::size_t i = 0; i < numberOfXNodes - 1; ++i)
{
out << xVector[i] << " ";
}
out << xVector[numberOfXNodes-1] << G4endl;
for(size_t j = 0; j<numberOfYNodes-1; ++j) {
out << yVector[j] << " ";
out << xVector[numberOfXNodes - 1] << G4endl;
for(std::size_t j = 0; j < numberOfYNodes - 1; ++j)
{
out << yVector[j] << " ";
}
out << yVector[numberOfYNodes-1] << G4endl;
for(size_t j = 0; j<numberOfYNodes; ++j) {
for(size_t i = 0; i<numberOfXNodes-1; ++i) {
out << GetValue(i, j) << " ";
out << yVector[numberOfYNodes - 1] << G4endl;
for(std::size_t j = 0; j < numberOfYNodes; ++j)
{
for(std::size_t i = 0; i < numberOfXNodes - 1; ++i)
{
out << GetValue(i, j) << " ";
}
out << GetValue(numberOfXNodes-1,j) << G4endl;
out << GetValue(numberOfXNodes - 1, j) << G4endl;
}
out.precision(prec);
out.close();
@@ -305,35 +323,44 @@ G4bool G4Physics2DVector::Retrieve(std::ifstream& in)
ClearVectors();
// binning
G4int k;
in >> k >> numberOfXNodes >> numberOfYNodes;
if (in.fail() || 0 >= numberOfXNodes || 0 >= numberOfYNodes ||
numberOfXNodes >= INT_MAX || numberOfYNodes >= INT_MAX) {
if( 0 >= numberOfXNodes || numberOfXNodes >= INT_MAX) {
numberOfXNodes = 0;
}
if( 0 >= numberOfYNodes || numberOfYNodes >= INT_MAX) {
numberOfYNodes = 0;
}
return false;
G4int k, nx, ny;
in >> k >> nx >> ny;
if(in.fail() || 2 > nx || 2 > ny || nx >= INT_MAX || ny >= INT_MAX)
{
return false;
}
numberOfXNodes = nx;
numberOfYNodes = ny;
PrepareVectors();
type = G4PhysicsVectorType(k);
type = G4PhysicsVectorType(k);
// contents
G4double val;
for(size_t i = 0; i<numberOfXNodes; ++i) {
for(G4int i = 0; i < nx; ++i)
{
in >> xVector[i];
if (in.fail()) { return false; }
if(in.fail())
{
return false;
}
}
for(size_t j = 0; j<numberOfYNodes; ++j) {
for(G4int j = 0; j < ny; ++j)
{
in >> yVector[j];
if (in.fail()) { return false; }
if(in.fail())
{
return false;
}
}
for(size_t j = 0; j<numberOfYNodes; ++j) {
for(size_t i = 0; i<numberOfXNodes; ++i) {
for(G4int j = 0; j < ny; ++j)
{
for(G4int i = 0; i < nx; ++i)
{
in >> val;
if (in.fail()) { return false; }
if(in.fail())
{
return false;
}
PutValue(i, j, val);
}
}
@@ -343,13 +370,14 @@ G4bool G4Physics2DVector::Retrieve(std::ifstream& in)
// --------------------------------------------------------------
void
G4Physics2DVector::ScaleVector(G4double factor)
void G4Physics2DVector::ScaleVector(G4double factor)
{
G4double val;
for(size_t j = 0; j<numberOfYNodes; ++j) {
for(size_t i = 0; i<numberOfXNodes; ++i) {
val = GetValue(i, j)*factor;
for(std::size_t j = 0; j < numberOfYNodes; ++j)
{
for(std::size_t i = 0; i < numberOfXNodes; ++i)
{
val = GetValue(i, j) * factor;
PutValue(i, j, val);
}
}
@@ -357,71 +385,56 @@ G4Physics2DVector::ScaleVector(G4double factor)
// --------------------------------------------------------------
size_t
G4Physics2DVector::FindBinLocation(G4double z,
const G4PV2DDataVector& v) const
G4double G4Physics2DVector::FindLinearX(G4double rand, G4double yy,
std::size_t& idy) const
{
size_t bin;
size_t binmax = v.size() - 2;
if(z <= v[0]) { bin = 0; }
else if(z >= v[binmax]) { bin = binmax; }
else {
bin = std::lower_bound(v.begin(), v.end(), z) - v.begin() - 1;
}
return bin;
}
// --------------------------------------------------------------
G4double G4Physics2DVector::FindLinearX(G4double rand, G4double yy,
size_t& idy) const
{
G4double y = yy;
// no interpolation outside the table
if(y < yVector[0]) {
y = yVector[0];
} else if(y > yVector[numberOfYNodes - 1]) {
y = yVector[numberOfYNodes - 1];
}
G4double y = std::min(std::max(yy, yVector[0]), yVector[numberOfYNodes - 1]);
// find bins
idy = FindBinLocationY(y, idy);
G4double x1 = InterpolateLinearX(*(value[idy]), rand);
G4double x2 = InterpolateLinearX(*(value[idy+1]), rand);
G4double x1 = InterpolateLinearX(*(value[idy]), rand);
G4double x2 = InterpolateLinearX(*(value[idy + 1]), rand);
G4double res = x1;
G4double del = yVector[idy+1] - yVector[idy];
if(del != 0.0) {
res += (x2 - x1)*(y - yVector[idy])/del;
G4double del = yVector[idy + 1] - yVector[idy];
if(del != 0.0)
{
res += (x2 - x1) * (y - yVector[idy]) / del;
}
return res;
}
// --------------------------------------------------------------
G4double G4Physics2DVector::InterpolateLinearX(G4PV2DDataVector& v,
G4double rand) const
G4double G4Physics2DVector::InterpolateLinearX(G4PV2DDataVector& v,
G4double rand) const
{
size_t nn = v.size();
if(1 >= nn) { return 0.0; }
size_t n1 = 0;
size_t n2 = nn/2;
size_t n3 = nn - 1;
G4double y = rand*v[n3];
while (n1 + 1 != n3)
std::size_t nn = v.size();
if(1 >= nn)
{
return 0.0;
}
std::size_t n1 = 0;
std::size_t n2 = nn / 2;
std::size_t n3 = nn - 1;
G4double y = rand * v[n3];
while(n1 + 1 != n3)
{
if(y > v[n2])
{
if (y > v[n2])
{ n1 = n2; }
else
{ n3 = n2; }
n2 = (n3 + n1 + 1)/2;
n1 = n2;
}
else
{
n3 = n2;
}
n2 = (n3 + n1 + 1) / 2;
}
G4double res = xVector[n1];
G4double del = v[n3] - v[n1];
if(del > 0.0) {
res += (y - v[n1])*(xVector[n3] - res)/del;
if(del > 0.0)
{
res += (y - v[n1]) * (xVector[n3] - res) / del;
}
return res;
}
@@ -23,71 +23,63 @@
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
// G4PhysicsFreeVector class implementation
//
//
//
//--------------------------------------------------------------------
// GEANT 4 class implementation file
//
// G4PhysicsFreeVector.cc
//
// History:
// 02 Dec. 1995, G.Cosmo : Structure created based on object model
// 06 June 1996, K.Amako : The 1st version of implemented
// 01 Jul. 1996, K.Amako : Cache mechanism and hidden bin from the
// user introduced
// 26 Sep. 1996, K.Amako : Constructor with only 'bin size' added
// 11 Nov. 2000, H.Kurashige : use STL vector for dataVector and binVector
// 19 Jun. 2009, V.Ivanchenko : removed hidden bin
//
//--------------------------------------------------------------------
// Authors:
// - 02 Dec. 1995, G.Cosmo: Structure created based on object model
// - 06 Jun. 1996, K.Amako: Implemented the 1st version
// Revisions:
// - 11 Nov. 2000, H.Kurashige: Use STL vector for dataVector and binVector
// --------------------------------------------------------------------
#include "G4PhysicsFreeVector.hh"
G4PhysicsFreeVector::G4PhysicsFreeVector()
// --------------------------------------------------------------------
G4PhysicsFreeVector::G4PhysicsFreeVector()
: G4PhysicsVector()
{
type = T_G4PhysicsFreeVector;
}
G4PhysicsFreeVector::G4PhysicsFreeVector(size_t length)
// --------------------------------------------------------------------
G4PhysicsFreeVector::G4PhysicsFreeVector(std::size_t length)
: G4PhysicsVector()
{
type = T_G4PhysicsFreeVector;
type = T_G4PhysicsFreeVector;
numberOfNodes = length;
dataVector.reserve(numberOfNodes);
binVector.reserve(numberOfNodes);
for (size_t i=0; i<numberOfNodes; ++i)
for(std::size_t i = 0; i < numberOfNodes; ++i)
{
binVector.push_back(0.0);
dataVector.push_back(0.0);
binVector.push_back(0.0);
dataVector.push_back(0.0);
}
}
}
G4PhysicsFreeVector::G4PhysicsFreeVector(const G4DataVector& theBinVector,
// --------------------------------------------------------------------
G4PhysicsFreeVector::G4PhysicsFreeVector(const G4DataVector& theBinVector,
const G4DataVector& theDataVector)
: G4PhysicsVector()
{
type = T_G4PhysicsFreeVector;
type = T_G4PhysicsFreeVector;
numberOfNodes = theBinVector.size();
dataVector.reserve(numberOfNodes);
binVector.reserve(numberOfNodes);
for (size_t i=0; i<numberOfNodes; ++i)
for(std::size_t i = 0; i < numberOfNodes; ++i)
{
binVector.push_back(theBinVector[i]);
dataVector.push_back(theDataVector[i]);
}
if(numberOfNodes > 0)
if(numberOfNodes > 0)
{
edgeMin = binVector[0];
edgeMax = binVector[numberOfNodes-1];
edgeMax = binVector[numberOfNodes - 1];
}
}
G4PhysicsFreeVector::~G4PhysicsFreeVector()
{}
}
// --------------------------------------------------------------------
G4PhysicsFreeVector::~G4PhysicsFreeVector() {}
@@ -23,75 +23,84 @@
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
// G4PhysicsLinearVector class implementation
//
//
//
//--------------------------------------------------------------------
// GEANT 4 class implementation file
//
// G4PhysicsLinearVector.cc
//
// 15 Feb 1996 - K.Amako : 1st version
// 19 Jun 2009 - V.Ivanchenko : removed hidden bin
// 02 Oct 2013 - V.Ivanchenko : removed FindBinLocation
//
//--------------------------------------------------------------------
// Authors:
// - 02 Dec. 1995, G.Cosmo: Structure created based on object model
// - 03 Mar. 1996, K.Amako: Implemented the 1st version
// Revisions:
// - 11 Nov. 2000, H.Kurashige: Use STL vector for dataVector and binVector
// --------------------------------------------------------------------
#include "G4PhysicsLinearVector.hh"
// --------------------------------------------------------------------
G4PhysicsLinearVector::G4PhysicsLinearVector()
: G4PhysicsVector()
{
type = T_G4PhysicsLinearVector;
}
G4PhysicsLinearVector::G4PhysicsLinearVector(G4double theEmin,
G4double theEmax, size_t theNbin)
// --------------------------------------------------------------------
G4PhysicsLinearVector::G4PhysicsLinearVector(G4double theEmin, G4double theEmax,
std::size_t theNbin)
: G4PhysicsVector()
{
numberOfNodes = theNbin + 1;
if(theNbin < 1 || theEmin == theEmax)
{
G4ExceptionDescription ed;
ed << "G4PhysicsLinearVector with wrong parameters: theNbin= " << theNbin
<< " theEmin= " << theEmin << " theEmax= " << theEmax;
G4Exception("G4PhysicsLinearVector::G4PhysicsLinearVector()", "glob03",
FatalException, ed, "theNbins should be > 1");
}
if(numberOfNodes < 2)
{
numberOfNodes = 2;
}
type = T_G4PhysicsLinearVector;
invdBin = 1./((theEmax-theEmin)/(G4double)theNbin);
baseBin = theEmin*invdBin;
invdBin = 1. / ((theEmax - theEmin) / (G4double) numberOfNodes);
baseBin = theEmin * invdBin;
numberOfNodes = theNbin + 1;
dataVector.reserve(numberOfNodes);
binVector.reserve(numberOfNodes);
binVector.reserve(numberOfNodes);
binVector.push_back(theEmin);
dataVector.push_back(0.0);
for (size_t i=1; i<numberOfNodes-1; ++i)
{
binVector.push_back( theEmin + i/invdBin );
dataVector.push_back(0.0);
}
for(std::size_t i = 1; i < numberOfNodes - 1; ++i)
{
binVector.push_back(theEmin + i / invdBin);
dataVector.push_back(0.0);
}
binVector.push_back(theEmax);
dataVector.push_back(0.0);
edgeMin = binVector[0];
edgeMax = binVector[numberOfNodes-1];
edgeMax = binVector[numberOfNodes - 1];
}
}
G4PhysicsLinearVector::~G4PhysicsLinearVector()
{}
// --------------------------------------------------------------------
G4PhysicsLinearVector::~G4PhysicsLinearVector() {}
// --------------------------------------------------------------------
G4bool G4PhysicsLinearVector::Retrieve(std::ifstream& fIn, G4bool ascii)
{
G4bool success = G4PhysicsVector::Retrieve(fIn, ascii);
if (success)
if(success)
{
invdBin = 1./(binVector[1]-edgeMin);
baseBin = edgeMin*invdBin;
invdBin = 1. / (binVector[1] - edgeMin);
baseBin = edgeMin * invdBin;
}
return success;
}
// --------------------------------------------------------------------
void G4PhysicsLinearVector::ScaleVector(G4double factorE, G4double factorV)
{
G4PhysicsVector::ScaleVector(factorE, factorV);
invdBin = 1./(binVector[1]-edgeMin);
baseBin = edgeMin*invdBin;
invdBin = 1. / (binVector[1] - edgeMin);
baseBin = edgeMin * invdBin;
}
@@ -23,81 +23,86 @@
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
// G4PhysicsLogVector class implementation
//
//
//
// --------------------------------------------------------------
// GEANT 4 class implementation file
//
// G4PhysicsLogVector.cc
//
// History:
// 02 Dec. 1995, G.Cosmo : Structure created based on object model
// 15 Feb. 1996, K.Amako : Implemented the 1st version
// 01 Jul. 1996, K.Amako : Hidden bin from the user introduced
// 26 Sep. 1996, K.Amako : Constructor with only 'bin size' added
// 11 Nov. 2000, H.Kurashige : use STL vector for dataVector and binVector
// 9 Mar. 2001, H.Kurashige : added PhysicsVector type and Retrieve
// 05 Sep. 2008, V.Ivanchenko : added protections for zero-length vector
// 19 Jun. 2009, V.Ivanchenko : removed hidden bin
// 02 Oct. 2013 V.Ivanchenko : Remove FindBinLocation method, use G4Log
//
// --------------------------------------------------------------
// Authors:
// - 02 Dec. 1995, G.Cosmo: Structure created based on object model
// - 03 Mar. 1996, K.Amako: Implemented the 1st version
// Revisions:
// - 11 Nov. 2000, H.Kurashige : Use STL vector for dataVector and binVector
// - 19 Jun. 2009, V.Ivanchenko : removed hidden bin
// --------------------------------------------------------------------
#include "G4PhysicsLogVector.hh"
#include "G4Exp.hh"
// --------------------------------------------------------------------
G4PhysicsLogVector::G4PhysicsLogVector()
: G4PhysicsVector()
{
type = T_G4PhysicsLogVector;
}
G4PhysicsLogVector::G4PhysicsLogVector(G4double theEmin,
G4double theEmax, size_t theNbin)
: G4PhysicsVector()
{
type = T_G4PhysicsLogVector;
}
invdBin = 1./(G4Log(theEmax/theEmin)/(G4double)theNbin);
baseBin = G4Log(theEmin)*invdBin;
// --------------------------------------------------------------------
G4PhysicsLogVector::G4PhysicsLogVector(G4double theEmin, G4double theEmax,
std::size_t theNbin)
: G4PhysicsVector()
{
numberOfNodes = theNbin + 1;
if(theNbin < 2 || theEmin == theEmax)
{
G4ExceptionDescription ed;
ed << "G4PhysicsLogVector with wrong parameters: theNbin= " << theNbin
<< " theEmin= " << theEmin << " theEmax= " << theEmax;
G4Exception("G4PhysicsLogVector::G4PhysicsLogVector()", "glob03",
FatalException, ed, "theNbins should be > 2");
}
if(numberOfNodes < 3)
{
numberOfNodes = 3;
}
type = T_G4PhysicsLogVector;
invdBin = 1. / (G4Log(theEmax / theEmin) / (G4double) numberOfNodes);
baseBin = G4Log(theEmin) * invdBin;
dataVector.reserve(numberOfNodes);
binVector.reserve(numberOfNodes);
binVector.push_back(theEmin);
dataVector.push_back(0.0);
for (size_t i=1; i<numberOfNodes-1; ++i)
{
binVector.push_back(G4Exp((baseBin+i)/invdBin));
dataVector.push_back(0.0);
}
for(std::size_t i = 1; i < numberOfNodes - 1; ++i)
{
binVector.push_back(G4Exp((baseBin + i) / invdBin));
dataVector.push_back(0.0);
}
binVector.push_back(theEmax);
dataVector.push_back(0.0);
edgeMin = binVector[0];
edgeMax = binVector[numberOfNodes-1];
}
edgeMax = binVector[numberOfNodes - 1];
}
G4PhysicsLogVector::~G4PhysicsLogVector()
{}
// --------------------------------------------------------------------
G4PhysicsLogVector::~G4PhysicsLogVector() {}
// --------------------------------------------------------------------
G4bool G4PhysicsLogVector::Retrieve(std::ifstream& fIn, G4bool ascii)
{
G4bool success = G4PhysicsVector::Retrieve(fIn, ascii);
if (success)
if(success)
{
invdBin = 1./G4Log(binVector[1]/edgeMin);
baseBin = G4Log(edgeMin)*invdBin;
invdBin = 1. / G4Log(binVector[1] / edgeMin);
baseBin = G4Log(edgeMin) * invdBin;
}
return success;
}
// --------------------------------------------------------------------
void G4PhysicsLogVector::ScaleVector(G4double factorE, G4double factorV)
{
G4PhysicsVector::ScaleVector(factorE, factorV);
invdBin = 1./G4Log(binVector[1]/edgeMin);
baseBin = G4Log(edgeMin)*invdBin;
invdBin = 1. / G4Log(binVector[1] / edgeMin);
baseBin = G4Log(edgeMin) * invdBin;
}
@@ -23,55 +23,70 @@
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
// G4PhysicsModelCatalog class implementation
//
//
// Author: M.Asai (SLAC), 26 September 2013
// --------------------------------------------------------------------
#include "G4PhysicsModelCatalog.hh"
#include "G4Threading.hh"
modelCatalog* G4PhysicsModelCatalog::catalog = 0;
std::vector<G4String>* G4PhysicsModelCatalog::theCatalog = nullptr;
// --------------------------------------------------------------------
G4PhysicsModelCatalog::G4PhysicsModelCatalog()
{ if(!catalog) {
static modelCatalog catal;
catalog = &catal;
{
if(theCatalog == nullptr)
{
static std::vector<G4String> catal;
theCatalog = &catal;
}
}
G4PhysicsModelCatalog::~G4PhysicsModelCatalog()
{}
//{ delete catalog; catalog = 0; }
// --------------------------------------------------------------------
G4PhysicsModelCatalog::~G4PhysicsModelCatalog() {}
// --------------------------------------------------------------------
G4int G4PhysicsModelCatalog::Register(const G4String& name)
{
G4PhysicsModelCatalog();
G4int idx = GetIndex(name);
if(idx>=0) return idx;
if(idx >= 0)
return idx;
#ifdef G4MULTITHREADED
if(G4Threading::IsWorkerThread()) return -1;
if(G4Threading::IsWorkerThread())
return -1;
#endif
catalog->push_back(name);
return catalog->size()-1;
theCatalog->push_back(name);
return theCatalog->size() - 1;
}
// --------------------------------------------------------------------
const G4String& G4PhysicsModelCatalog::GetModelName(G4int idx)
{
static const G4String undef = "Undefined";
if(idx>=0 && idx<Entries()) return (*catalog)[idx];
if(idx >= 0 && idx < Entries())
return (*theCatalog)[idx];
return undef;
}
// --------------------------------------------------------------------
G4int G4PhysicsModelCatalog::GetIndex(const G4String& name)
{
for(G4int idx=0;idx<Entries();++idx)
{ if((*catalog)[idx]==name) return idx; }
for(G4int idx = 0; idx < Entries(); ++idx)
{
if((*theCatalog)[idx] == name)
return idx;
}
return -1;
}
// --------------------------------------------------------------------
G4int G4PhysicsModelCatalog::Entries()
{ return (catalog) ? G4int(catalog->size()) : -1; }
void G4PhysicsModelCatalog::Destroy()
{}
{
return (theCatalog != nullptr) ? G4int(theCatalog->size()) : -1;
}
// --------------------------------------------------------------------
void G4PhysicsModelCatalog::Destroy() {}
@@ -23,104 +23,99 @@
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
// G4PhysicsOrderedFreeVector class implementation
//
//
////////////////////////////////////////////////////////////////////////
// PhysicsOrderedFreeVector Class Implementation
////////////////////////////////////////////////////////////////////////
//
// File: G4PhysicsOrderedFreeVector.cc
// Version: 2.0
// Created: 1996-08-13
// Author: Juliet Armstrong
// Updated: 1997-03-25 by Peter Gumplinger
// > cosmetics (only)
// 1998-11-11 by Peter Gumplinger
// > initialize all data members of the base class in
// derived class constructors
// 2000-11-11 by H.Kurashige
// > use STL vector for dataVector and binVector
// 2009-06-19 by V.Ivanchenko
// > removed hidden bin
// 2013-10-02 by V.Ivanchenko removed FindBinLocation
//
// mail: gum@triumf.ca
//
////////////////////////////////////////////////////////////////////////
// Author: Juliet Armstrong (TRIUMF), 13 August 1996
// Revisions:
// - 11.11.2000, H.Kurashige: use STL vector for dataVector and binVector
// - 19.06.2009, V.Ivanchenko: removed hidden bin
// --------------------------------------------------------------------
#include "G4PhysicsOrderedFreeVector.hh"
// --------------------------------------------------------------------
G4PhysicsOrderedFreeVector::G4PhysicsOrderedFreeVector()
: G4PhysicsVector()
{
type = T_G4PhysicsOrderedFreeVector;
type = T_G4PhysicsOrderedFreeVector;
}
G4PhysicsOrderedFreeVector::G4PhysicsOrderedFreeVector(G4double *Energies,
G4double *Values,
size_t VectorLength)
// --------------------------------------------------------------------
G4PhysicsOrderedFreeVector::G4PhysicsOrderedFreeVector(G4double* Energies,
G4double* Values,
std::size_t VectorLength)
: G4PhysicsVector()
{
type = T_G4PhysicsOrderedFreeVector;
type = T_G4PhysicsOrderedFreeVector;
dataVector.reserve(VectorLength);
binVector.reserve(VectorLength);
dataVector.reserve(VectorLength);
binVector.reserve(VectorLength);
for (size_t i = 0 ; i < VectorLength ; ++i)
{
InsertValues(Energies[i], Values[i]);
}
for(std::size_t i = 0; i < VectorLength; ++i)
{
InsertValues(Energies[i], Values[i]);
}
}
G4PhysicsOrderedFreeVector::~G4PhysicsOrderedFreeVector()
{}
// --------------------------------------------------------------------
G4PhysicsOrderedFreeVector::~G4PhysicsOrderedFreeVector() {}
// --------------------------------------------------------------------
void G4PhysicsOrderedFreeVector::InsertValues(G4double energy, G4double value)
{
std::vector<G4double>::iterator binLoc =
std::lower_bound(binVector.begin(), binVector.end(), energy);
auto binLoc = std::lower_bound(binVector.cbegin(), binVector.cend(), energy);
size_t binIdx = binLoc - binVector.begin(); // Iterator difference!
std::size_t binIdx = binLoc - binVector.cbegin(); // Iterator difference!
std::vector<G4double>::iterator dataLoc = dataVector.begin() + binIdx;
auto dataLoc = dataVector.cbegin() + binIdx;
binVector.insert(binLoc, energy);
dataVector.insert(dataLoc, value);
binVector.insert(binLoc, energy);
dataVector.insert(dataLoc, value);
++numberOfNodes;
edgeMin = binVector.front();
edgeMax = binVector.back();
++numberOfNodes;
edgeMin = binVector.front();
edgeMax = binVector.back();
}
// --------------------------------------------------------------------
G4double G4PhysicsOrderedFreeVector::GetEnergy(G4double aValue)
{
G4double e;
if (aValue <= GetMinValue()) {
e = edgeMin;
} else if (aValue >= GetMaxValue()) {
e = edgeMax;
} else {
size_t closestBin = FindValueBinLocation(aValue);
e = LinearInterpolationOfEnergy(aValue, closestBin);
}
return e;
G4double e;
if(aValue <= GetMinValue())
{
e = edgeMin;
}
else if(aValue >= GetMaxValue())
{
e = edgeMax;
}
else
{
std::size_t closestBin = FindValueBinLocation(aValue);
e = LinearInterpolationOfEnergy(aValue, closestBin);
}
return e;
}
size_t G4PhysicsOrderedFreeVector::FindValueBinLocation(G4double aValue)
// --------------------------------------------------------------------
std::size_t G4PhysicsOrderedFreeVector::FindValueBinLocation(G4double aValue)
{
size_t bin = std::lower_bound(dataVector.begin(), dataVector.end(), aValue)
- dataVector.begin() - 1;
bin = std::min(bin, numberOfNodes-2);
return bin;
std::size_t bin =
std::lower_bound(dataVector.cbegin(), dataVector.cend(), aValue) -
dataVector.cbegin() - 1;
bin = std::min(bin, numberOfNodes - 2);
return bin;
}
G4double G4PhysicsOrderedFreeVector::LinearInterpolationOfEnergy(G4double aValue,
size_t bin)
// --------------------------------------------------------------------
G4double G4PhysicsOrderedFreeVector::LinearInterpolationOfEnergy(
G4double aValue, std::size_t bin)
{
G4double res = binVector[bin];
G4double del = dataVector[bin+1] - dataVector[bin];
if(del > 0.0) {
res += (aValue - dataVector[bin])*(binVector[bin+1] - res)/del;
}
return res;
G4double res = binVector[bin];
G4double del = dataVector[bin + 1] - dataVector[bin];
if(del > 0.0)
{
res += (aValue - dataVector[bin]) * (binVector[bin + 1] - res) / del;
}
return res;
}
+123 -134
View File
@@ -23,92 +23,75 @@
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
// G4PhysicsTable class implementation
//
//
//
// ------------------------------------------------------------
// GEANT 4 class implementation
//
// G4PhysicsTable
//
// ------------------------------------------------------------
// Author: G.Cosmo, 2 December 1995
// First implementation based on object model
// Revisions:
// - 1st March 1996, K.Amako: modified
// - 24th February 2001, H.Kurashige: migration to STL vectors
// --------------------------------------------------------------------
#include <iostream>
#include <fstream>
#include <iomanip>
#include <iostream>
#include "G4PhysicsVector.hh"
#include "G4PhysicsTable.hh"
#include "G4PhysicsVectorType.hh"
#include "G4LPhysicsFreeVector.hh"
#include "G4PhysicsLogVector.hh"
#include "G4PhysicsFreeVector.hh"
#include "G4PhysicsOrderedFreeVector.hh"
#include "G4PhysicsLinearVector.hh"
#include "G4PhysicsLnVector.hh"
#include "G4PhysicsLogVector.hh"
#include "G4PhysicsOrderedFreeVector.hh"
#include "G4PhysicsTable.hh"
#include "G4PhysicsVector.hh"
#include "G4PhysicsVectorType.hh"
// --------------------------------------------------------------------
G4PhysicsTable::G4PhysicsTable()
: G4PhysCollection()
{
}
{}
G4PhysicsTable::G4PhysicsTable(size_t cap)
// --------------------------------------------------------------------
G4PhysicsTable::G4PhysicsTable(std::size_t cap)
: G4PhysCollection()
{
reserve(cap);
vecFlag.reserve(cap);
}
/*
G4PhysicsTable::G4PhysicsTable(const G4PhysicsTable& right)
: G4PhysCollection()
{
*this = right;
}
G4PhysicsTable& G4PhysicsTable::operator=(const G4PhysicsTable& right)
{
if (this != &right)
{
size_t idx = 0;
for (G4PhysCollection::const_iterator itr=right.begin();
itr!=right.end(); ++itr )
{
G4PhysCollection::push_back(*itr);
vecFlag.push_back(right.GetFlag(idx));
idx +=1;
}
}
return *this;
}
*/
// --------------------------------------------------------------------
G4PhysicsTable::~G4PhysicsTable()
{
G4PhysCollection::clear();
vecFlag.clear();
}
void G4PhysicsTable::resize(size_t siz, G4PhysicsVector* vec)
// --------------------------------------------------------------------
void G4PhysicsTable::resize(std::size_t siz, G4PhysicsVector* vec)
{
G4PhysCollection::resize(siz, vec);
vecFlag.resize(siz, true);
}
G4bool G4PhysicsTable::StorePhysicsTable(const G4String& fileName,
G4bool ascii)
// --------------------------------------------------------------------
G4bool G4PhysicsTable::StorePhysicsTable(const G4String& fileName, G4bool ascii)
{
std::ofstream fOut;
// open output file //
if (!ascii)
{ fOut.open(fileName, std::ios::out|std::ios::binary); }
else
{ fOut.open(fileName, std::ios::out); }
std::ofstream fOut;
// check if the file has been opened successfully
if (!fOut)
// open output file
if(!ascii)
{
#ifdef G4VERBOSE
fOut.open(fileName, std::ios::out | std::ios::binary);
}
else
{
fOut.open(fileName, std::ios::out);
}
// check if the file has been opened successfully
if(!fOut)
{
#ifdef G4VERBOSE
G4cerr << "G4PhysicsTable::StorePhysicsTable():";
G4cerr << " Cannot open file: " << fileName << G4endl;
#endif
@@ -117,10 +100,10 @@ G4bool G4PhysicsTable::StorePhysicsTable(const G4String& fileName,
}
// Number of elements
size_t tableSize = size();
if (!ascii)
std::size_t tableSize = size();
if(!ascii)
{
fOut.write( (char*)(&tableSize), sizeof tableSize);
fOut.write((char*) (&tableSize), sizeof tableSize);
}
else
{
@@ -128,54 +111,59 @@ G4bool G4PhysicsTable::StorePhysicsTable(const G4String& fileName,
}
// Physics Vector
for (G4PhysicsTableIterator itr=begin(); itr!=end(); ++itr)
for(auto itr = cbegin(); itr != cend(); ++itr)
{
G4int vType = (*itr)->GetType();
if (!ascii)
if(!ascii)
{
fOut.write( (char*)(&vType), sizeof vType);
fOut.write((char*) (&vType), sizeof vType);
}
else
{
fOut << vType << G4endl;
}
(*itr)->Store(fOut,ascii);
(*itr)->Store(fOut, ascii);
}
fOut.close();
return true;
}
// --------------------------------------------------------------------
G4bool G4PhysicsTable::ExistPhysicsTable(const G4String& fileName) const
{
std::ifstream fIn;
G4bool value=true;
std::ifstream fIn;
G4bool value = true;
// open input file
fIn.open(fileName,std::ios::in);
fIn.open(fileName, std::ios::in);
// check if the file has been opened successfully
if (!fIn)
// check if the file has been opened successfully
if(!fIn)
{
value = false;
}
fIn.close();
return value;
}
G4bool G4PhysicsTable::RetrievePhysicsTable(const G4String& fileName,
G4bool ascii)
{
std::ifstream fIn;
// open input file
if (ascii)
{ fIn.open(fileName,std::ios::in|std::ios::binary); }
else
{ fIn.open(fileName,std::ios::in);}
// check if the file has been opened successfully
if (!fIn)
// --------------------------------------------------------------------
G4bool G4PhysicsTable::RetrievePhysicsTable(const G4String& fileName,
G4bool ascii)
{
std::ifstream fIn;
// open input file
if(ascii)
{
#ifdef G4VERBOSE
fIn.open(fileName, std::ios::in | std::ios::binary);
}
else
{
fIn.open(fileName, std::ios::in);
}
// check if the file has been opened successfully
if(!fIn)
{
#ifdef G4VERBOSE
G4cerr << "G4PhysicsTable::RetrievePhysicsTable():";
G4cerr << " Cannot open file: " << fileName << G4endl;
#endif
@@ -183,54 +171,54 @@ G4bool G4PhysicsTable::RetrievePhysicsTable(const G4String& fileName,
return false;
}
// clear
// clear
clearAndDestroy();
// Number of elements
size_t tableSize=0;
if (!ascii)
std::size_t tableSize = 0;
if(!ascii)
{
fIn.read((char*)(&tableSize), sizeof tableSize);
fIn.read((char*) (&tableSize), sizeof tableSize);
}
else
{
fIn >> tableSize;
}
reserve(tableSize);
reserve(tableSize);
vecFlag.clear();
// Physics Vector
for (size_t idx=0; idx<tableSize; ++idx)
for(std::size_t idx = 0; idx < tableSize; ++idx)
{
G4int vType=0;
if (!ascii)
G4int vType = 0;
if(!ascii)
{
fIn.read( (char*)(&vType), sizeof vType);
fIn.read((char*) (&vType), sizeof vType);
}
else
{
fIn >> vType;
fIn >> vType;
}
G4PhysicsVector* pVec = CreatePhysicsVector(vType);
if (pVec==nullptr)
if(pVec == nullptr)
{
#ifdef G4VERBOSE
#ifdef G4VERBOSE
G4cerr << "G4PhysicsTable::RetrievePhysicsTable():";
G4cerr << " Illegal Physics Vector type: " << vType << " in: ";
G4cerr << fileName << G4endl;
#endif
#endif
fIn.close();
return false;
}
if (! (pVec->Retrieve(fIn,ascii)) )
if(!(pVec->Retrieve(fIn, ascii)))
{
#ifdef G4VERBOSE
#ifdef G4VERBOSE
G4cerr << "G4PhysicsTable::RetrievePhysicsTable():";
G4cerr << " Rrror in retreiving " << idx
<< "-th Physics Vector from file: ";
G4cerr << fileName << G4endl;
#endif
#endif
fIn.close();
return false;
}
@@ -238,79 +226,80 @@ G4bool G4PhysicsTable::RetrievePhysicsTable(const G4String& fileName,
// add a PhysicsVector to this PhysicsTable
G4PhysCollection::push_back(pVec);
vecFlag.push_back(true);
}
}
fIn.close();
return true;
}
std::ostream& operator<<(std::ostream& out,
G4PhysicsTable& right)
// --------------------------------------------------------------------
std::ostream& operator<<(std::ostream& out, G4PhysicsTable& right)
{
// Printout Physics Vector
size_t i=0;
for (G4PhysicsTableIterator itr=right.begin(); itr!=right.end(); ++itr)
std::size_t i = 0;
for(auto itr = right.cbegin(); itr != right.cend(); ++itr)
{
out << std::setw(8) << i << "-th Vector ";
out << ": Type " << G4int((*itr)->GetType()) ;
out << ": Type " << G4int((*itr)->GetType());
out << ": Flag ";
if (right.GetFlag(i))
if(right.GetFlag(i))
{
out << " T";
}
}
else
{
out << " F";
}
}
out << G4endl;
out << *(*itr);
i +=1;
++i;
}
out << G4endl;
return out;
return out;
}
// --------------------------------------------------------------------
void G4PhysicsTable::ResetFlagArray()
{
size_t tableSize = G4PhysCollection::size();
size_t tableSize = G4PhysCollection::size();
vecFlag.clear();
for (size_t idx=0; idx<tableSize; idx++)
for(std::size_t idx = 0; idx < tableSize; ++idx)
{
vecFlag.push_back(true);
}
}
// --------------------------------------------------------------------
G4PhysicsVector* G4PhysicsTable::CreatePhysicsVector(G4int type)
{
G4PhysicsVector* pVector = nullptr;
switch (type)
switch(type)
{
case T_G4PhysicsLinearVector:
pVector = new G4PhysicsLinearVector();
break;
case T_G4PhysicsLinearVector:
pVector = new G4PhysicsLinearVector();
break;
case T_G4PhysicsLogVector:
pVector = new G4PhysicsLogVector();
break;
case T_G4PhysicsLogVector:
pVector = new G4PhysicsLogVector();
break;
case T_G4PhysicsLnVector:
pVector = new G4PhysicsLogVector();
break;
case T_G4PhysicsLnVector:
pVector = new G4PhysicsLogVector();
break;
case T_G4PhysicsFreeVector:
pVector = new G4PhysicsFreeVector();
break;
case T_G4PhysicsFreeVector:
pVector = new G4PhysicsFreeVector();
break;
case T_G4PhysicsOrderedFreeVector:
pVector = new G4PhysicsOrderedFreeVector();
break;
case T_G4PhysicsOrderedFreeVector:
pVector = new G4PhysicsOrderedFreeVector();
break;
case T_G4LPhysicsFreeVector:
pVector = new G4PhysicsFreeVector();
break;
default:
break;
case T_G4LPhysicsFreeVector:
pVector = new G4PhysicsFreeVector();
break;
default:
break;
}
return pVector;
}
+258 -230
View File
@@ -23,52 +23,31 @@
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
// G4PhysicsVector class implementation
//
//
//
// --------------------------------------------------------------
// GEANT 4 class implementation file
//
// G4PhysicsVector.cc
//
// History:
// 02 Dec. 1995, G.Cosmo : Structure created based on object model
// 03 Mar. 1996, K.Amako : Implemented the 1st version
// 01 Jul. 1996, K.Amako : Hidden bin from the user introduced
// 12 Nov. 1998, K.Amako : A bug in GetVectorLength() fixed
// 11 Nov. 2000, H.Kurashige : use STL vector for dataVector and binVector
// 18 Jan. 2001, H.Kurashige : removed ptrNextTable
// 09 Mar. 2001, H.Kurashige : added G4PhysicsVector type
// 05 Sep. 2008, V.Ivanchenko : added protections for zero-length vector
// 11 May 2009, A.Bagulya : added new implementation of methods
// ComputeSecondDerivatives - first derivatives at edge points
// should be provided by a user
// FillSecondDerivatives - default computation base on "not-a-knot"
// algorithm
// 19 Jun. 2009, V.Ivanchenko : removed hidden bin
// 17 Nov. 2009, H.Kurashige : use pointer for DataVector
// 04 May 2010 H.Kurashige : use G4PhyscisVectorCache
// 28 May 2010 H.Kurashige : Stop using pointers to G4PVDataVector
// 16 Aug. 2011 H.Kurashige : Add dBin, baseBin and verboseLevel
// --------------------------------------------------------------
// Authors:
// - 02 Dec. 1995, G.Cosmo: Structure created based on object model
// - 03 Mar. 1996, K.Amako: Implemented the 1st version
// Revisions:
// - 11 Nov. 2000, H.Kurashige: Use STL vector for dataVector and binVector
// - 02 Apr. 2008, A.Bagulya: Added SplineInterpolation() and SetSpline()
// - 19 Jun. 2009, V.Ivanchenko: Removed hidden bin
// - 15 Mar. 2019 M.Novak: added Value method with the known log-energy value
// that can avoid the log call in case of log-vectors
// --------------------------------------------------------------------
#include <iomanip>
#include "G4PhysicsVector.hh"
#include <iomanip>
// --------------------------------------------------------------
G4PhysicsVector::G4PhysicsVector(G4bool val)
: type(T_G4PhysicsVector),
edgeMin(0.), edgeMax(0.), numberOfNodes(0),
useSpline(val),
invdBin(0.), baseBin(0.),
verboseLevel(0)
: useSpline(val)
{}
// --------------------------------------------------------------
G4PhysicsVector::~G4PhysicsVector()
{}
G4PhysicsVector::~G4PhysicsVector() {}
// --------------------------------------------------------------
@@ -86,7 +65,10 @@ G4PhysicsVector::G4PhysicsVector(const G4PhysicsVector& right)
G4PhysicsVector& G4PhysicsVector::operator=(const G4PhysicsVector& right)
{
if (&right==this) { return *this; }
if(&right == this)
{
return *this;
}
invdBin = right.invdBin;
baseBin = right.baseBin;
verboseLevel = right.verboseLevel;
@@ -98,14 +80,14 @@ G4PhysicsVector& G4PhysicsVector::operator=(const G4PhysicsVector& right)
// --------------------------------------------------------------
G4bool G4PhysicsVector::operator==(const G4PhysicsVector &right) const
G4bool G4PhysicsVector::operator==(const G4PhysicsVector& right) const
{
return (this == &right);
}
// --------------------------------------------------------------
G4bool G4PhysicsVector::operator!=(const G4PhysicsVector &right) const
G4bool G4PhysicsVector::operator!=(const G4PhysicsVector& right) const
{
return (this != &right);
}
@@ -122,24 +104,28 @@ void G4PhysicsVector::DeleteData()
void G4PhysicsVector::CopyData(const G4PhysicsVector& vec)
{
type = vec.type;
edgeMin = vec.edgeMin;
edgeMax = vec.edgeMax;
type = vec.type;
edgeMin = vec.edgeMin;
edgeMax = vec.edgeMax;
numberOfNodes = vec.numberOfNodes;
useSpline = vec.useSpline;
useSpline = vec.useSpline;
size_t i;
std::size_t i;
dataVector.resize(numberOfNodes);
for(i=0; i<numberOfNodes; ++i) {
for(i = 0; i < numberOfNodes; ++i)
{
dataVector[i] = (vec.dataVector)[i];
}
binVector.resize(numberOfNodes);
for(i=0; i<numberOfNodes; ++i) {
for(i = 0; i < numberOfNodes; ++i)
{
binVector[i] = (vec.binVector)[i];
}
if(0 < (vec.secDerivative).size()) {
if(0 < (vec.secDerivative).size())
{
secDerivative.resize(numberOfNodes);
for(i=0; i<numberOfNodes; ++i){
for(i = 0; i < numberOfNodes; ++i)
{
secDerivative[i] = (vec.secDerivative)[i];
}
}
@@ -147,7 +133,7 @@ void G4PhysicsVector::CopyData(const G4PhysicsVector& vec)
// --------------------------------------------------------------
G4double G4PhysicsVector::GetLowEdgeEnergy(size_t binNumber) const
G4double G4PhysicsVector::GetLowEdgeEnergy(std::size_t binNumber) const
{
return binVector[binNumber];
}
@@ -157,30 +143,30 @@ G4double G4PhysicsVector::GetLowEdgeEnergy(size_t binNumber) const
G4bool G4PhysicsVector::Store(std::ofstream& fOut, G4bool ascii) const
{
// Ascii mode
if (ascii)
if(ascii)
{
fOut << *this;
return true;
}
}
// Binary Mode
// binning
fOut.write((char*)(&edgeMin), sizeof edgeMin);
fOut.write((char*)(&edgeMax), sizeof edgeMax);
fOut.write((char*)(&numberOfNodes), sizeof numberOfNodes);
fOut.write((char*) (&edgeMin), sizeof edgeMin);
fOut.write((char*) (&edgeMax), sizeof edgeMax);
fOut.write((char*) (&numberOfNodes), sizeof numberOfNodes);
// contents
size_t size = dataVector.size();
fOut.write((char*)(&size), sizeof size);
std::size_t size = dataVector.size();
fOut.write((char*) (&size), sizeof size);
G4double* value = new G4double[2*size];
for(size_t i = 0; i < size; ++i)
G4double* value = new G4double[2 * size];
for(std::size_t i = 0; i < size; ++i)
{
value[2*i] = binVector[i];
value[2*i+1]= dataVector[i];
value[2 * i] = binVector[i];
value[2 * i + 1] = dataVector[i];
}
fOut.write((char*)(value), 2*size*(sizeof (G4double)));
delete [] value;
fOut.write((char*) (value), 2 * size * (sizeof(G4double)));
delete[] value;
return true;
}
@@ -195,67 +181,77 @@ G4bool G4PhysicsVector::Retrieve(std::ifstream& fIn, G4bool ascii)
secDerivative.clear();
// retrieve in ascii mode
if (ascii){
if(ascii)
{
// binning
fIn >> edgeMin >> edgeMax >> numberOfNodes;
if (fIn.fail()) { return false; }
fIn >> edgeMin >> edgeMax >> numberOfNodes;
if(fIn.fail() || numberOfNodes < 2)
{
return false;
}
// contents
G4int siz=0;
G4int siz = 0;
fIn >> siz;
if (fIn.fail() || siz<=0) { return false; }
if(fIn.fail() || siz != G4int(numberOfNodes))
{
return false;
}
binVector.reserve(siz);
dataVector.reserve(siz);
G4double vBin, vData;
for(G4int i = 0; i < siz ; i++)
for(G4int i = 0; i < siz; ++i)
{
vBin = 0.;
vData= 0.;
vBin = 0.;
vData = 0.;
fIn >> vBin >> vData;
if (fIn.fail()) { return false; }
if(fIn.fail())
{
return false;
}
binVector.push_back(vBin);
dataVector.push_back(vData);
}
// to remove any inconsistency
// to remove any inconsistency
numberOfNodes = siz;
edgeMin = binVector[0];
edgeMax = binVector[numberOfNodes-1];
return true ;
edgeMin = binVector[0];
edgeMax = binVector[numberOfNodes - 1];
return true;
}
// retrieve in binary mode
// binning
fIn.read((char*)(&edgeMin), sizeof edgeMin);
fIn.read((char*)(&edgeMax), sizeof edgeMax);
fIn.read((char*)(&numberOfNodes), sizeof numberOfNodes );
fIn.read((char*) (&edgeMin), sizeof edgeMin);
fIn.read((char*) (&edgeMax), sizeof edgeMax);
fIn.read((char*) (&numberOfNodes), sizeof numberOfNodes);
// contents
size_t size;
fIn.read((char*)(&size), sizeof size);
G4double* value = new G4double[2*size];
fIn.read((char*)(value), 2*size*(sizeof(G4double)) );
if (G4int(fIn.gcount()) != G4int(2*size*(sizeof(G4double))) )
std::size_t size;
fIn.read((char*) (&size), sizeof size);
G4double* value = new G4double[2 * size];
fIn.read((char*) (value), 2 * size * (sizeof(G4double)));
if(G4int(fIn.gcount()) != G4int(2 * size * (sizeof(G4double))))
{
delete [] value;
delete[] value;
return false;
}
binVector.reserve(size);
dataVector.reserve(size);
for(size_t i = 0; i < size; ++i)
for(std::size_t i = 0; i < size; ++i)
{
binVector.push_back(value[2*i]);
dataVector.push_back(value[2*i+1]);
binVector.push_back(value[2 * i]);
dataVector.push_back(value[2 * i + 1]);
}
delete [] value;
delete[] value;
// to remove any inconsistency
// to remove any inconsistency
numberOfNodes = size;
edgeMin = binVector[0];
edgeMax = binVector[numberOfNodes-1];
edgeMin = binVector[0];
edgeMax = binVector[numberOfNodes - 1];
return true;
}
@@ -264,248 +260,279 @@ G4bool G4PhysicsVector::Retrieve(std::ifstream& fIn, G4bool ascii)
void G4PhysicsVector::DumpValues(G4double unitE, G4double unitV) const
{
for (size_t i = 0; i < numberOfNodes; ++i)
{
G4cout << binVector[i]/unitE << " " << dataVector[i]/unitV << G4endl;
}
for(std::size_t i = 0; i < numberOfNodes; ++i)
{
G4cout << binVector[i] / unitE << " " << dataVector[i] / unitV << G4endl;
}
}
// --------------------------------------------------------------------
void
G4PhysicsVector::ScaleVector(G4double factorE, G4double factorV)
void G4PhysicsVector::ScaleVector(G4double factorE, G4double factorV)
{
size_t n = dataVector.size();
size_t i;
for(i=0; i<n; ++i) {
binVector[i] *= factorE;
dataVector[i] *= factorV;
std::size_t n = dataVector.size();
std::size_t i;
for(i = 0; i < n; ++i)
{
binVector[i] *= factorE;
dataVector[i] *= factorV;
}
secDerivative.clear();
edgeMin = binVector[0];
edgeMax = binVector[n-1];
edgeMax = binVector[n - 1];
}
// --------------------------------------------------------------
void
G4PhysicsVector::ComputeSecondDerivatives(G4double firstPointDerivative,
G4double endPointDerivative)
// A standard method of computation of second derivatives
// First derivatives at the first and the last point should be provided
// See for example W.H. Press et al. "Numerical recipes in C"
// Cambridge University Press, 1997.
void G4PhysicsVector::ComputeSecondDerivatives(G4double firstPointDerivative,
G4double endPointDerivative)
// A standard method of computation of second derivatives
// First derivatives at the first and the last point should be provided
// See for example W.H. Press et al. "Numerical recipes in C"
// Cambridge University Press, 1997.
{
if(4 > numberOfNodes) // cannot compute derivatives for less than 4 bins
if(4 > numberOfNodes) // cannot compute derivatives for less than 4 bins
{
ComputeSecDerivatives();
return;
}
if(!SplinePossible()) { return; }
if(!SplinePossible())
{
return;
}
useSpline = true;
G4int n = numberOfNodes-1;
G4int n = numberOfNodes - 1;
G4double* u = new G4double[n];
G4double* u = new G4double [n];
G4double p, sig, un;
u[0] = (6.0/(binVector[1]-binVector[0]))
* ((dataVector[1]-dataVector[0])/(binVector[1]-binVector[0])
- firstPointDerivative);
secDerivative[0] = - 0.5;
u[0] = (6.0 / (binVector[1] - binVector[0])) *
((dataVector[1] - dataVector[0]) / (binVector[1] - binVector[0]) -
firstPointDerivative);
secDerivative[0] = -0.5;
// Decomposition loop for tridiagonal algorithm. secDerivative[i]
// and u[i] are used for temporary storage of the decomposed factors.
for(G4int i=1; i<n; ++i)
for(G4int i = 1; i < n; ++i)
{
sig = (binVector[i]-binVector[i-1]) / (binVector[i+1]-binVector[i-1]);
p = sig*(secDerivative[i-1]) + 2.0;
secDerivative[i] = (sig - 1.0)/p;
u[i] = (dataVector[i+1]-dataVector[i])/(binVector[i+1]-binVector[i])
- (dataVector[i]-dataVector[i-1])/(binVector[i]-binVector[i-1]);
u[i] = 6.0*u[i]/(binVector[i+1]-binVector[i-1]) - sig*u[i-1]/p;
sig =
(binVector[i] - binVector[i - 1]) / (binVector[i + 1] - binVector[i - 1]);
p = sig * (secDerivative[i - 1]) + 2.0;
secDerivative[i] = (sig - 1.0) / p;
u[i] =
(dataVector[i + 1] - dataVector[i]) / (binVector[i + 1] - binVector[i]) -
(dataVector[i] - dataVector[i - 1]) / (binVector[i] - binVector[i - 1]);
u[i] =
6.0 * u[i] / (binVector[i + 1] - binVector[i - 1]) - sig * u[i - 1] / p;
}
sig = (binVector[n-1]-binVector[n-2]) / (binVector[n]-binVector[n-2]);
p = sig*secDerivative[n-2] + 2.0;
un = (6.0/(binVector[n]-binVector[n-1]))
*(endPointDerivative -
(dataVector[n]-dataVector[n-1])/(binVector[n]-binVector[n-1])) - u[n-1]/p;
secDerivative[n] = un/(secDerivative[n-1] + 2.0);
sig =
(binVector[n - 1] - binVector[n - 2]) / (binVector[n] - binVector[n - 2]);
p = sig * secDerivative[n - 2] + 2.0;
un = (6.0 / (binVector[n] - binVector[n - 1])) *
(endPointDerivative - (dataVector[n] - dataVector[n - 1]) /
(binVector[n] - binVector[n - 1])) -
u[n - 1] / p;
secDerivative[n] = un / (secDerivative[n - 1] + 2.0);
// The back-substitution loop for the triagonal algorithm of solving
// a linear system of equations.
for(G4int k=n-1; k>0; --k)
{
secDerivative[k] *=
(secDerivative[k+1] -
u[k]*(binVector[k+1]-binVector[k-1])/(binVector[k+1]-binVector[k]));
}
secDerivative[0] = 0.5*(u[0] - secDerivative[1]);
delete [] u;
for(G4int k = n - 1; k > 0; --k)
{
secDerivative[k] *=
(secDerivative[k + 1] - u[k] * (binVector[k + 1] - binVector[k - 1]) /
(binVector[k + 1] - binVector[k]));
}
secDerivative[0] = 0.5 * (u[0] - secDerivative[1]);
delete[] u;
}
// --------------------------------------------------------------
void G4PhysicsVector::FillSecondDerivatives()
{
// Computation of second derivatives using "Not-a-knot" endpoint conditions
// B.I. Kvasov "Methods of shape-preserving spline approximation"
// World Scientific, 2000
{
if(5 > numberOfNodes) // cannot compute derivatives for less than 4 points
{
ComputeSecDerivatives();
return;
}
if(!SplinePossible()) { return; }
if(!SplinePossible())
{
return;
}
useSpline = true;
G4int n = numberOfNodes-1;
G4double* u = new G4double [n];
G4int n = numberOfNodes - 1;
G4double* u = new G4double[n];
G4double p, sig;
u[1] = ((dataVector[2]-dataVector[1])/(binVector[2]-binVector[1]) -
(dataVector[1]-dataVector[0])/(binVector[1]-binVector[0]));
u[1] = 6.0*u[1]*(binVector[2]-binVector[1])
/ ((binVector[2]-binVector[0])*(binVector[2]-binVector[0]));
u[1] = ((dataVector[2] - dataVector[1]) / (binVector[2] - binVector[1]) -
(dataVector[1] - dataVector[0]) / (binVector[1] - binVector[0]));
u[1] = 6.0 * u[1] * (binVector[2] - binVector[1]) /
((binVector[2] - binVector[0]) * (binVector[2] - binVector[0]));
// Decomposition loop for tridiagonal algorithm. secDerivative[i]
// and u[i] are used for temporary storage of the decomposed factors.
secDerivative[1] = (2.0*binVector[1]-binVector[0]-binVector[2])
/ (2.0*binVector[2]-binVector[0]-binVector[1]);
secDerivative[1] = (2.0 * binVector[1] - binVector[0] - binVector[2]) /
(2.0 * binVector[2] - binVector[0] - binVector[1]);
for(G4int i=2; i<n-1; ++i)
for(G4int i = 2; i < n - 1; ++i)
{
sig = (binVector[i]-binVector[i-1]) / (binVector[i+1]-binVector[i-1]);
p = sig*secDerivative[i-1] + 2.0;
secDerivative[i] = (sig - 1.0)/p;
u[i] = (dataVector[i+1]-dataVector[i])/(binVector[i+1]-binVector[i])
- (dataVector[i]-dataVector[i-1])/(binVector[i]-binVector[i-1]);
u[i] = (6.0*u[i]/(binVector[i+1]-binVector[i-1])) - sig*u[i-1]/p;
sig =
(binVector[i] - binVector[i - 1]) / (binVector[i + 1] - binVector[i - 1]);
p = sig * secDerivative[i - 1] + 2.0;
secDerivative[i] = (sig - 1.0) / p;
u[i] =
(dataVector[i + 1] - dataVector[i]) / (binVector[i + 1] - binVector[i]) -
(dataVector[i] - dataVector[i - 1]) / (binVector[i] - binVector[i - 1]);
u[i] =
(6.0 * u[i] / (binVector[i + 1] - binVector[i - 1])) - sig * u[i - 1] / p;
}
sig = (binVector[n-1]-binVector[n-2]) / (binVector[n]-binVector[n-2]);
p = sig*secDerivative[n-3] + 2.0;
u[n-1] = (dataVector[n]-dataVector[n-1])/(binVector[n]-binVector[n-1])
- (dataVector[n-1]-dataVector[n-2])/(binVector[n-1]-binVector[n-2]);
u[n-1] = 6.0*sig*u[n-1]/(binVector[n]-binVector[n-2])
- (2.0*sig - 1.0)*u[n-2]/p;
sig =
(binVector[n - 1] - binVector[n - 2]) / (binVector[n] - binVector[n - 2]);
p = sig * secDerivative[n - 3] + 2.0;
u[n - 1] =
(dataVector[n] - dataVector[n - 1]) / (binVector[n] - binVector[n - 1]) -
(dataVector[n - 1] - dataVector[n - 2]) /
(binVector[n - 1] - binVector[n - 2]);
u[n - 1] = 6.0 * sig * u[n - 1] / (binVector[n] - binVector[n - 2]) -
(2.0 * sig - 1.0) * u[n - 2] / p;
p = (1.0+sig) + (2.0*sig-1.0)*secDerivative[n-2];
secDerivative[n-1] = u[n-1]/p;
p = (1.0 + sig) + (2.0 * sig - 1.0) * secDerivative[n - 2];
secDerivative[n - 1] = u[n - 1] / p;
// The back-substitution loop for the triagonal algorithm of solving
// a linear system of equations.
for(G4int k=n-2; k>1; --k)
{
secDerivative[k] *=
(secDerivative[k+1] -
u[k]*(binVector[k+1]-binVector[k-1])/(binVector[k+1]-binVector[k]));
}
secDerivative[n] = (secDerivative[n-1] - (1.0-sig)*secDerivative[n-2])/sig;
sig = 1.0 - ((binVector[2]-binVector[1])/(binVector[2]-binVector[0]));
secDerivative[1] *= (secDerivative[2] - u[1]/(1.0-sig));
secDerivative[0] = (secDerivative[1] - sig*secDerivative[2])/(1.0-sig);
delete [] u;
for(G4int k = n - 2; k > 1; --k)
{
secDerivative[k] *=
(secDerivative[k + 1] - u[k] * (binVector[k + 1] - binVector[k - 1]) /
(binVector[k + 1] - binVector[k]));
}
secDerivative[n] =
(secDerivative[n - 1] - (1.0 - sig) * secDerivative[n - 2]) / sig;
sig = 1.0 - ((binVector[2] - binVector[1]) / (binVector[2] - binVector[0]));
secDerivative[1] *= (secDerivative[2] - u[1] / (1.0 - sig));
secDerivative[0] = (secDerivative[1] - sig * secDerivative[2]) / (1.0 - sig);
delete[] u;
}
// --------------------------------------------------------------
void
G4PhysicsVector::ComputeSecDerivatives()
// A simplified method of computation of second derivatives
void G4PhysicsVector::ComputeSecDerivatives()
{
// A simplified method of computation of second derivatives
if(3 > numberOfNodes) // cannot compute derivatives for less than 4 bins
{
useSpline = false;
return;
}
if(!SplinePossible()) { return; }
if(!SplinePossible())
{
return;
}
useSpline = true;
size_t n = numberOfNodes-1;
std::size_t n = numberOfNodes - 1;
for(size_t i=1; i<n; ++i)
for(std::size_t i = 1; i < n; ++i)
{
secDerivative[i] =
3.0*((dataVector[i+1]-dataVector[i])/(binVector[i+1]-binVector[i]) -
(dataVector[i]-dataVector[i-1])/(binVector[i]-binVector[i-1]))
/(binVector[i+1]-binVector[i-1]);
3.0 *
((dataVector[i + 1] - dataVector[i]) / (binVector[i + 1] - binVector[i]) -
(dataVector[i] - dataVector[i - 1]) /
(binVector[i] - binVector[i - 1])) /
(binVector[i + 1] - binVector[i - 1]);
}
secDerivative[n] = secDerivative[n-1];
secDerivative[n] = secDerivative[n - 1];
secDerivative[0] = secDerivative[1];
}
// --------------------------------------------------------------
G4bool G4PhysicsVector::SplinePossible()
// Initialise second derivative array. If neighbor energy coincide
// or not ordered than spline cannot be applied
{
// Initialise second derivative array. If neighbor energy coincide
// or not ordered than spline cannot be applied
G4bool result = true;
for(size_t j=1; j<numberOfNodes; ++j)
for(std::size_t j = 1; j < numberOfNodes; ++j)
{
if(binVector[j] <= binVector[j-1]) {
result = false;
if(binVector[j] <= binVector[j - 1])
{
result = false;
useSpline = false;
secDerivative.clear();
break;
}
}
secDerivative.resize(numberOfNodes,0.0);
}
secDerivative.resize(numberOfNodes, 0.0);
return result;
}
// --------------------------------------------------------------
std::ostream& operator<<(std::ostream& out, const G4PhysicsVector& pv)
{
// binning
out << std::setprecision(12) << pv.edgeMin << " "
<< pv.edgeMax << " " << pv.numberOfNodes << G4endl;
G4int prec = out.precision();
out << std::setprecision(12) << pv.edgeMin << " " << pv.edgeMax << " "
<< pv.numberOfNodes << G4endl;
// contents
out << pv.dataVector.size() << G4endl;
for(size_t i = 0; i < pv.dataVector.size(); i++)
out << pv.dataVector.size() << G4endl;
for(std::size_t i = 0; i < pv.dataVector.size(); ++i)
{
out << pv.binVector[i] << " " << pv.dataVector[i] << G4endl;
}
out << std::setprecision(6);
out << std::setprecision(prec);
return out;
}
//---------------------------------------------------------------
G4double G4PhysicsVector::Value(G4double theEnergy, size_t& lastIdx) const
G4double G4PhysicsVector::Value(G4double theEnergy, std::size_t& lastIdx) const
{
G4double y;
if(theEnergy <= edgeMin) {
lastIdx = 0;
y = dataVector[0];
} else if(theEnergy >= edgeMax) {
lastIdx = numberOfNodes-1;
y = dataVector[lastIdx];
} else {
if(theEnergy <= edgeMin)
{
lastIdx = 0;
y = dataVector[0];
}
else if(theEnergy >= edgeMax)
{
lastIdx = numberOfNodes - 1;
y = dataVector[lastIdx];
}
else
{
lastIdx = FindBin(theEnergy, lastIdx);
y = Interpolation(lastIdx, theEnergy);
y = Interpolation(lastIdx, theEnergy);
}
return y;
}
@@ -514,29 +541,30 @@ G4double G4PhysicsVector::Value(G4double theEnergy, size_t& lastIdx) const
G4double G4PhysicsVector::FindLinearEnergy(G4double rand) const
{
if(1 >= numberOfNodes) { return 0.0; }
G4double y = rand*dataVector[numberOfNodes-1];
size_t bin = std::lower_bound(dataVector.begin(), dataVector.end(), y)
- dataVector.begin() - 1;
bin = std::min(bin, numberOfNodes-2);
if(1 >= numberOfNodes)
{
return 0.0;
}
G4double y = rand * dataVector[numberOfNodes - 1];
std::size_t bin = std::lower_bound(dataVector.begin(), dataVector.end(), y) -
dataVector.begin() - 1;
bin = std::min(bin, numberOfNodes - 2);
G4double res = binVector[bin];
G4double del = dataVector[bin+1] - dataVector[bin];
if(del > 0.0) {
res += (y - dataVector[bin])*(binVector[bin+1] - res)/del;
G4double del = dataVector[bin + 1] - dataVector[bin];
if(del > 0.0)
{
res += (y - dataVector[bin]) * (binVector[bin + 1] - res) / del;
}
return res;
}
//---------------------------------------------------------------
void G4PhysicsVector::PrintPutValueError(size_t index)
void G4PhysicsVector::PrintPutValueError(std::size_t index)
{
G4ExceptionDescription ed;
ed << "Vector type " << type << " length= " << numberOfNodes
ed << "Vector type " << type << " length= " << numberOfNodes
<< " an attempt to put data at index= " << index;
G4Exception("G4PhysicsVector::PutValue()","gl0005",FatalException,
ed,"Memory overwritten");
G4Exception("G4PhysicsVector::PutValue()", "gl0005", FatalException, ed,
"Memory overwritten");
}
//---------------------------------------------------------------
+86 -79
View File
@@ -23,37 +23,24 @@
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
// G4Pow class implemenation
//
// -------------------------------------------------------------------
//
// GEANT4 Class file
//
//
// File name: G4Pow
//
// Author: Vladimir Ivanchenko
//
// Creation date: 23.05.2009
//
// Modifications:
// 08.01.2011 V.Ivanchenko extended maxZ from 256 to 512
// 02.05.2013 V.Ivanchenko added expA and logX methods,
// revised A13, logA, powZ, powA to improved accuracy
// 23.03.2018 M.Novak increased accuracy of A13 on the most critical
// [1/4,4] interval by introducing a denser(0.25) grid
//
// -------------------------------------------------------------------
// Author: Vladimir Ivanchenko, 23.05.2009
// Revisions:
// - 23.03.2018, M.Novak: increased accuracy of A13 on the most critical
// [1/4,4] interval by introducing a denser(0.25) grid
// --------------------------------------------------------------------
#include "G4Pow.hh"
#include "G4Threading.hh"
G4Pow* G4Pow::fpInstance = 0;
G4Pow* G4Pow::fpInstance = nullptr;
// -------------------------------------------------------------------
G4Pow* G4Pow::GetInstance()
{
if (fpInstance == 0)
if(fpInstance == nullptr)
{
static G4Pow geant4pow;
fpInstance = &geant4pow;
@@ -64,108 +51,113 @@ G4Pow* G4Pow::GetInstance()
// -------------------------------------------------------------------
G4Pow::G4Pow()
: onethird(1.0/3.0), max2(5)
{
#ifdef G4MULTITHREADED
if(G4Threading::IsWorkerThread())
{
G4Exception ("G4Pow::G4Pow()", "InvalidSetup", FatalException,
"Attempt to instantiate G4Pow in worker thread!");
G4Exception("G4Pow::G4Pow()", "InvalidSetup", FatalException,
"Attempt to instantiate G4Pow in worker thread!");
}
#endif
const G4int maxZ = 512;
const G4int maxZfact = 170;
const G4int numLowA = 17;
const G4int numLowA = 17;
maxA = -0.6 + maxZ;
maxLowA = 4.0;
maxA2 = 1.25 + max2*0.2;
maxAexp = -0.76+ maxZfact*0.5;
maxLowA = 4.0;
maxA2 = 1.25 + max2 * 0.2;
maxAexp = -0.76 + maxZfact * 0.5;
ener.resize(max2+1,1.0);
logen.resize(max2+1,0.0);
lz2.resize(max2+1,0.0);
pz13.resize(maxZ,0.0);
lowa13.resize(numLowA,0.0);
lz.resize(maxZ,0.0);
fexp.resize(maxZfact,0.0);
fact.resize(maxZfact,0.0);
logfact.resize(maxZ,0.0);
ener.resize(max2 + 1, 1.0);
logen.resize(max2 + 1, 0.0);
lz2.resize(max2 + 1, 0.0);
pz13.resize(maxZ, 0.0);
lowa13.resize(numLowA, 0.0);
lz.resize(maxZ, 0.0);
fexp.resize(maxZfact, 0.0);
fact.resize(maxZfact, 0.0);
logfact.resize(maxZ, 0.0);
G4double f = 1.0;
G4double f = 1.0;
G4double logf = 0.0;
fact[0] = 1.0;
fexp[0] = 1.0;
fact[0] = 1.0;
fexp[0] = 1.0;
for(G4int i=1; i<=max2; ++i)
for(G4int i = 1; i <= max2; ++i)
{
ener[i] = powN(500.,i);
logen[i]= G4Log(ener[i]);
lz2[i] = G4Log(1.0 + i*0.2);
ener[i] = powN(500., i);
logen[i] = G4Log(ener[i]);
lz2[i] = G4Log(1.0 + i * 0.2);
}
for(G4int i=1; i<maxZ; ++i)
for(G4int i = 1; i < maxZ; ++i)
{
G4double x = G4double(i);
pz13[i] = std::pow(x,onethird);
lz[i] = G4Log(x);
G4double x = G4double(i);
pz13[i] = std::pow(x, onethird);
lz[i] = G4Log(x);
if(i < maxZfact)
{
f *= x;
fact[i] = f;
fexp[i] = G4Exp(0.5*i);
fexp[i] = G4Exp(0.5 * i);
}
logf += lz[i];
logfact[i] = logf;
}
for (G4int i=4; i<numLowA; ++i) {
lowa13[i] = std::pow(0.25*i,onethird);
for(G4int i = 4; i < numLowA; ++i)
{
lowa13[i] = std::pow(0.25 * i, onethird);
}
}
// -------------------------------------------------------------------
G4Pow::~G4Pow()
{}
G4Pow::~G4Pow() {}
// -------------------------------------------------------------------
G4double G4Pow::A13(G4double A) const {
G4double G4Pow::A13(G4double A) const
{
G4double res = 0.;
if (A>0.) {
const bool invert = (A<1.);
const G4double a = invert ? 1./A : A;
res = (a<maxLowA) ? A13Low(a, invert) : A13High(a, invert);
if(A > 0.)
{
const bool invert = (A < 1.);
const G4double a = invert ? 1. / A : A;
res = (a < maxLowA) ? A13Low(a, invert) : A13High(a, invert);
}
return res;
}
// -------------------------------------------------------------------
G4double G4Pow::A13High(const G4double a, const bool invert) const {
G4double G4Pow::A13High(const G4double a, const bool invert) const
{
G4double res;
if (a<maxA) {
const G4int i = static_cast<G4int>(a+0.5);
const G4double x = (a/i-1.)*onethird;
res = pz13[i]*(1.+x-x*x*(1.-1.666667*x));
} else {
res = G4Exp(G4Log(a)*onethird);
if(a < maxA)
{
const G4int i = static_cast<G4int>(a + 0.5);
const G4double x = (a / i - 1.) * onethird;
res = pz13[i] * (1. + x - x * x * (1. - 1.666667 * x));
}
res = invert ? 1./res : res;
else
{
res = G4Exp(G4Log(a) * onethird);
}
res = invert ? 1. / res : res;
return res;
}
// -------------------------------------------------------------------
G4double G4Pow::A13Low(const G4double a, const bool invert) const {
G4double G4Pow::A13Low(const G4double a, const G4bool invert) const
{
G4double res;
const G4int i = static_cast<G4int>(4.*(a+0.125));
const G4double y = 0.25*i;
const G4double x = (a/y-1.)*onethird;
res = lowa13[i]*(1.+x-x*x*(1.-1.666667*x));
res = invert ? 1./res : res;
const G4int i = static_cast<G4int>(4. * (a + 0.125));
const G4double y = 0.25 * i;
const G4double x = (a / y - 1.) * onethird;
res = lowa13[i] * (1. + x - x * x * (1. - 1.666667 * x));
res = invert ? 1. / res : res;
return res;
}
@@ -173,15 +165,30 @@ G4double G4Pow::A13Low(const G4double a, const bool invert) const {
G4double G4Pow::powN(G4double x, G4int n) const
{
if(0.0 == x) { return 0.0; }
if(std::abs(n) > 8) { return std::pow(x, G4double(n)); }
if(0.0 == x)
{
return 0.0;
}
if(std::abs(n) > 8)
{
return std::pow(x, G4double(n));
}
G4double res = 1.0;
if(n >= 0) { for(G4int i=0; i<n; ++i) { res *= x; } }
if(n >= 0)
{
for(G4int i = 0; i < n; ++i)
{
res *= x;
}
}
else if(n < 0)
{
G4double y = 1.0/x;
G4int nn = -n;
for(G4int i=0; i<nn; ++i) { res *= y; }
G4double y = 1.0 / x;
G4int nn = -n;
for(G4int i = 0; i < nn; ++i)
{
res *= y;
}
}
return res;
}
@@ -23,28 +23,23 @@
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
// G4ReferenceCountedHandle class implementation
//
// -------------------------------------------------------------------
//
// GEANT4 Class file
//
//
// File name: G4ReferenceCountedHandle.cc
//
// -------------------------------------------------------------------
// Author: Radovan Chytracek, CERN - November 2001
// --------------------------------------------------------------------
#include "G4Types.hh"
#include "G4ReferenceCountedHandle.hh"
#include "G4Types.hh"
G4Allocator<G4CountedObject<void>>*& aCountedObjectAllocator()
{
G4ThreadLocalStatic G4Allocator<G4CountedObject<void>>* _instance = nullptr;
return _instance;
G4ThreadLocalStatic G4Allocator<G4CountedObject<void>>* _instance = nullptr;
return _instance;
}
G4Allocator<G4ReferenceCountedHandle<void>>*& aRCHAllocator()
{
G4ThreadLocalStatic G4Allocator<G4ReferenceCountedHandle<void>>*
_instance = nullptr;
return _instance;
G4ThreadLocalStatic G4Allocator<G4ReferenceCountedHandle<void>>* _instance =
nullptr;
return _instance;
}
+26 -29
View File
@@ -23,57 +23,54 @@
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
// G4SliceTimer class implementation
//
//
//
// ----------------------------------------------------------------------
// class G4SliceTimer
//
// Implementation
// ----------------------------------------------------------------------
// Author: M.Asai, 23.10.06 - Derived from G4Timer implementation
// --------------------------------------------------------------------
#include "G4SliceTimer.hh"
#include "G4ios.hh"
#if defined(IRIX6_2)
# if defined(_XOPEN_SOURCE) && (_XOPEN_SOURCE_EXTENDED==1)
# if defined(_XOPEN_SOURCE) && (_XOPEN_SOURCE_EXTENDED == 1)
# define __vfork vfork
# endif
#endif
// Print timer status n std::ostream
std::ostream& operator << (std::ostream& os, const G4SliceTimer& t)
// --------------------------------------------------------------------
std::ostream& operator<<(std::ostream& os, const G4SliceTimer& t)
{
if (t.IsValid())
{
os << "User=" << t.GetUserElapsed()
<< "s Real=" << t.GetRealElapsed()
<< "s Sys=" << t.GetSystemElapsed() << "s";
}
else
{
os << "User=****s Real=****s Sys=****s";
}
return os;
// Print timer status n std::ostream
if(t.IsValid())
{
os << "User = " << t.GetUserElapsed() << "s Real = " << t.GetRealElapsed()
<< "s Sys = " << t.GetSystemElapsed() << "s";
}
else
{
os << "User = ****s Real = ****s Sys = ****s";
}
return os;
}
G4SliceTimer::G4SliceTimer()
: fValidTimes(true), fRealElapsed(0.), fSystemElapsed(0.), fUserElapsed(0.)
{
Clear();
}
// --------------------------------------------------------------------
G4SliceTimer::G4SliceTimer() { Clear(); }
// --------------------------------------------------------------------
G4double G4SliceTimer::GetRealElapsed() const
{
return fRealElapsed/sysconf(_SC_CLK_TCK);
return fRealElapsed / sysconf(_SC_CLK_TCK);
}
// --------------------------------------------------------------------
G4double G4SliceTimer::GetSystemElapsed() const
{
return fSystemElapsed/sysconf(_SC_CLK_TCK);
return fSystemElapsed / sysconf(_SC_CLK_TCK);
}
// --------------------------------------------------------------------
G4double G4SliceTimer::GetUserElapsed() const
{
return fUserElapsed/sysconf(_SC_CLK_TCK);
return fUserElapsed / sysconf(_SC_CLK_TCK);
}
+135 -177
View File
@@ -23,31 +23,21 @@
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
// G4StateManager class implementation
//
//
//
// ------------------------------------------------------------
// GEANT 4 class implementation file
//
// ---------------- G4StateManager ----------------
// by Gabriele Cosmo, November 1996
// ------------------------------------------------------------
// Authors: G.Cosmo, M.Asai - November 1996
// --------------------------------------------------------------------
#include "G4StateManager.hh"
#include "G4ios.hh"
// Initialization of the static pointer of the single class instance
//
G4ThreadLocal G4StateManager* G4StateManager::theStateManager = 0;
G4int G4StateManager::verboseLevel = 0;
G4ThreadLocal G4StateManager* G4StateManager::theStateManager = nullptr;
G4int G4StateManager::verboseLevel = 0;
// --------------------------------------------------------------------
G4StateManager::G4StateManager()
: theCurrentState(G4State_PreInit),
thePreviousState(G4State_PreInit),
theBottomDependent(0),
suppressAbortion(0),
msgptr(0),
exceptionHandler(0)
{
#ifdef G4MULTITHREADED
G4iosInitialization();
@@ -56,16 +46,15 @@ G4StateManager::G4StateManager()
G4StateManager::~G4StateManager()
{
G4VStateDependent* state=0;
G4VStateDependent* state = nullptr;
while (theDependentsList.size()>0)
while(theDependentsList.size() > 0)
{
state = theDependentsList.back();
theDependentsList.pop_back();
for (std::vector<G4VStateDependent*>::iterator
i=theDependentsList.begin(); i!=theDependentsList.end();)
for(auto i = theDependentsList.cbegin(); i != theDependentsList.cend();)
{
if (*i==state)
if(*i == state)
{
i = theDependentsList.erase(i);
}
@@ -73,178 +62,142 @@ G4StateManager::~G4StateManager()
{
++i;
}
}
if ( state ) { delete state; }
}
delete state;
}
theStateManager = 0;
theStateManager = nullptr;
#ifdef G4MULTITHREADED_DEACTIVATE
G4iosFinalization();
#endif
}
// -------------------------------------------------------------------------
// No matter how copy-constructor and operators below are implemented ...
// just dummy implementations, since not relevant for the singleton and
// declared private.
//
G4StateManager::G4StateManager(const G4StateManager &right)
: theCurrentState(right.theCurrentState),
thePreviousState(right.thePreviousState),
theDependentsList(right.theDependentsList),
theBottomDependent(right.theBottomDependent),
suppressAbortion(right.suppressAbortion),
msgptr(right.msgptr),
exceptionHandler(right.exceptionHandler)
// --------------------------------------------------------------------
G4StateManager* G4StateManager::GetStateManager()
{
}
G4StateManager&
G4StateManager::operator=(const G4StateManager &right)
{
if (&right == this) { return *this; }
theCurrentState = right.theCurrentState;
thePreviousState = right.thePreviousState;
theDependentsList = right.theDependentsList;
theBottomDependent = right.theBottomDependent;
suppressAbortion = right.suppressAbortion;
msgptr = right.msgptr;
exceptionHandler = right.exceptionHandler;
return *this;
}
G4bool
G4StateManager::operator==(const G4StateManager &right) const
{
return (this == &right);
}
G4bool
G4StateManager::operator!=(const G4StateManager &right) const
{
return (this != &right);
}
//
// -------------------------------------------------------------------------
G4StateManager*
G4StateManager::GetStateManager()
{
if (!theStateManager)
{
theStateManager = new G4StateManager;
}
return theStateManager;
}
G4bool
G4StateManager::RegisterDependent(G4VStateDependent* aDependent, G4bool bottom)
{
G4bool ack=true;
if(!bottom)
{
theDependentsList.push_back(aDependent);
}
else
{
if(theBottomDependent)
{
theDependentsList.push_back(theBottomDependent);
}
theBottomDependent = aDependent;
}
return ack;
}
G4bool
G4StateManager::DeregisterDependent(G4VStateDependent* aDependent)
{
G4VStateDependent* tmp = 0;
for (std::vector<G4VStateDependent*>::iterator i=theDependentsList.begin();
i!=theDependentsList.end();)
if(theStateManager == nullptr)
{
if (**i==*aDependent)
theStateManager = new G4StateManager;
}
return theStateManager;
}
// --------------------------------------------------------------------
G4bool G4StateManager::RegisterDependent(G4VStateDependent* aDependent,
G4bool bottom)
{
G4bool ack = true;
if(!bottom)
{
theDependentsList.push_back(aDependent);
}
else
{
if(theBottomDependent)
{
theDependentsList.push_back(theBottomDependent);
}
theBottomDependent = aDependent;
}
return ack;
}
// --------------------------------------------------------------------
G4bool G4StateManager::DeregisterDependent(G4VStateDependent* aDependent)
{
G4VStateDependent* tmp = nullptr;
for(auto i = theDependentsList.cbegin(); i != theDependentsList.cend();)
{
if(**i == *aDependent)
{
tmp = *i;
i = theDependentsList.erase(i);
i = theDependentsList.erase(i);
}
else
{
++i;
}
}
return (tmp != 0);
return (tmp != nullptr);
}
const G4ApplicationState&
G4StateManager::GetCurrentState() const
// --------------------------------------------------------------------
const G4ApplicationState& G4StateManager::GetCurrentState() const
{
return theCurrentState;
return theCurrentState;
}
const G4ApplicationState&
G4StateManager::GetPreviousState() const
// --------------------------------------------------------------------
const G4ApplicationState& G4StateManager::GetPreviousState() const
{
return thePreviousState;
return thePreviousState;
}
G4bool
G4StateManager::SetNewState(const G4ApplicationState& requestedState)
{ return SetNewState(requestedState,0); }
G4bool
G4StateManager::SetNewState(const G4ApplicationState& requestedState,
const char* msg)
// --------------------------------------------------------------------
G4bool G4StateManager::SetNewState(const G4ApplicationState& requestedState)
{
if(requestedState==G4State_Abort && suppressAbortion>0)
{
if(suppressAbortion==2) { return false; }
if(theCurrentState==G4State_EventProc) { return false; }
}
msgptr = msg;
size_t i=0;
G4bool ack = true;
G4ApplicationState savedState = thePreviousState;
thePreviousState = theCurrentState;
while ((ack) && (i<theDependentsList.size()))
{
ack = theDependentsList[i]->Notify(requestedState);
i++;
}
if(theBottomDependent)
{
ack = theBottomDependent->Notify(requestedState);
}
if(!ack)
{ thePreviousState = savedState; }
else
{
theCurrentState = requestedState;
if(verboseLevel>0)
{
G4cout<<"#### G4StateManager::SetNewState from "
<<GetStateString(thePreviousState)<<" to "
<<GetStateString(requestedState)<<G4endl;
}
}
msgptr = 0;
return ack;
return SetNewState(requestedState, nullptr);
}
G4VStateDependent*
G4StateManager::RemoveDependent(const G4VStateDependent* aDependent)
// --------------------------------------------------------------------
G4bool G4StateManager::SetNewState(const G4ApplicationState& requestedState,
const char* msg)
{
G4VStateDependent* tmp = 0;
for (std::vector<G4VStateDependent*>::iterator i=theDependentsList.begin();
i!=theDependentsList.end();)
if(requestedState == G4State_Abort && suppressAbortion > 0)
{
if (**i==*aDependent)
if(suppressAbortion == 2)
{
return false;
}
if(theCurrentState == G4State_EventProc)
{
return false;
}
}
msgptr = msg;
std::size_t i = 0;
G4bool ack = true;
G4ApplicationState savedState = thePreviousState;
thePreviousState = theCurrentState;
while((ack) && (i < theDependentsList.size()))
{
ack = theDependentsList[i]->Notify(requestedState);
++i;
}
if(theBottomDependent)
{
ack = theBottomDependent->Notify(requestedState);
}
if(!ack)
{
thePreviousState = savedState;
}
else
{
theCurrentState = requestedState;
if(verboseLevel > 0)
{
G4cout << "#### G4StateManager::SetNewState from "
<< GetStateString(thePreviousState) << " to "
<< GetStateString(requestedState) << G4endl;
}
}
msgptr = nullptr;
return ack;
}
// --------------------------------------------------------------------
G4VStateDependent* G4StateManager::RemoveDependent(
const G4VStateDependent* aDependent)
{
G4VStateDependent* tmp = nullptr;
for(auto i = theDependentsList.cbegin(); i != theDependentsList.cend();)
{
if(**i == *aDependent)
{
tmp = *i;
i = theDependentsList.erase(i);
i = theDependentsList.erase(i);
}
else
{
@@ -254,34 +207,39 @@ G4StateManager::RemoveDependent(const G4VStateDependent* aDependent)
return tmp;
}
G4String
G4StateManager::GetStateString(const G4ApplicationState& aState) const
// --------------------------------------------------------------------
G4String G4StateManager::GetStateString(const G4ApplicationState& aState) const
{
G4String stateName;
switch(aState)
{
case G4State_PreInit:
stateName = "PreInit"; break;
stateName = "PreInit";
break;
case G4State_Init:
stateName = "Init"; break;
stateName = "Init";
break;
case G4State_Idle:
stateName = "Idle"; break;
stateName = "Idle";
break;
case G4State_GeomClosed:
stateName = "GeomClosed"; break;
stateName = "GeomClosed";
break;
case G4State_EventProc:
stateName = "EventProc"; break;
stateName = "EventProc";
break;
case G4State_Quit:
stateName = "Quit"; break;
stateName = "Quit";
break;
case G4State_Abort:
stateName = "Abort"; break;
stateName = "Abort";
break;
default:
stateName = "Unknown"; break;
stateName = "Unknown";
break;
}
return stateName;
}
void
G4StateManager::SetVerboseLevel(G4int val)
{
verboseLevel = val;
}
// --------------------------------------------------------------------
void G4StateManager::SetVerboseLevel(G4int val) { verboseLevel = val; }
+49 -54
View File
@@ -23,104 +23,99 @@
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
// G4Threading implementation
//
// --------------------------------------------------------------
// GEANT 4 class implementation file
//
// G4Threading.cc
//
// ---------------------------------------------------------------
// Author: Andrea Dotti (15 Feb 2013): First Implementation
// ---------------------------------------------------------------
// Author: Andrea Dotti, 15 February 2013 - First Implementation
// Revision: Jonathan R. Madsen, 21 February 2018
// --------------------------------------------------------------------
#include "G4Threading.hh"
#include "G4AutoDelete.hh"
#include "G4AutoLock.hh"
#include "globals.hh"
#if defined (WIN32)
#include <Windows.h>
#if defined(WIN32)
# include <Windows.h>
#else
#include <unistd.h>
#include <sys/types.h>
#include <sys/syscall.h>
# include <sys/syscall.h>
# include <sys/types.h>
# include <unistd.h>
#endif
#if defined(G4MULTITHREADED)
#include <atomic>
# include <atomic>
namespace
{
G4ThreadLocal G4int G4ThreadID = G4Threading::MASTER_ID;
G4bool isMTAppType = false;
}
G4ThreadLocal G4int G4ThreadID = G4Threading::MASTER_ID;
G4bool isMTAppType = false;
} // namespace
G4Pid_t G4Threading::G4GetPidId()
{
// In multithreaded mode return Thread ID
return std::this_thread::get_id();
// In multithreaded mode return Thread ID
return std::this_thread::get_id();
}
G4int G4Threading::G4GetNumberOfCores()
{
return std::thread::hardware_concurrency();
return std::thread::hardware_concurrency();
}
void G4Threading::G4SetThreadId(G4int value ) { G4ThreadID = value; }
void G4Threading::G4SetThreadId(G4int value) { G4ThreadID = value; }
G4int G4Threading::G4GetThreadId() { return G4ThreadID; }
G4bool G4Threading::IsWorkerThread() { return (G4ThreadID>=0); }
G4bool G4Threading::IsMasterThread() { return (G4ThreadID==MASTER_ID); }
G4bool G4Threading::IsWorkerThread() { return (G4ThreadID >= 0); }
G4bool G4Threading::IsMasterThread() { return (G4ThreadID == MASTER_ID); }
#if defined(__linux__) || defined(_AIX)
# if defined(__linux__) || defined(_AIX)
G4bool G4Threading::G4SetPinAffinity(G4int cpu, G4NativeThread& aT)
{
cpu_set_t* aset = new cpu_set_t;
G4AutoDelete::Register(aset);
CPU_ZERO(aset);
CPU_SET(cpu, aset);
pthread_t& _aT = (pthread_t&) (aT);
return (pthread_setaffinity_np(_aT, sizeof(cpu_set_t), aset) == 0);
cpu_set_t* aset = new cpu_set_t;
G4AutoDelete::Register(aset);
CPU_ZERO(aset);
CPU_SET(cpu, aset);
pthread_t& _aT = (pthread_t&) (aT);
return (pthread_setaffinity_np(_aT, sizeof(cpu_set_t), aset) == 0);
}
#else //Not available for Mac, WIN,...
# else // Not available for Mac, WIN,...
G4bool G4Threading::G4SetPinAffinity(G4int, G4NativeThread&)
{
G4Exception("G4Threading::G4SetPinAffinity()",
"NotImplemented", JustWarning,
"Affinity setting not available for this architecture, "
"ignoring...");
return true;
G4Exception("G4Threading::G4SetPinAffinity()", "NotImplemented", JustWarning,
"Affinity setting not available for this architecture, "
"ignoring...");
return true;
}
#endif
# endif
void G4Threading::SetMultithreadedApplication(G4bool value)
{
isMTAppType = value;
isMTAppType = value;
}
G4bool G4Threading::IsMultithreadedApplication()
{
return isMTAppType;
}
G4bool G4Threading::IsMultithreadedApplication() { return isMTAppType; }
namespace
{
std::atomic_int numActThreads(0);
std::atomic_int numActThreads(0);
}
G4int G4Threading::WorkerThreadLeavesPool() { return --numActThreads; }
G4int G4Threading::WorkerThreadJoinsPool() { return ++numActThreads; }
G4int G4Threading::GetNumberOfRunningWorkerThreads()
{
return numActThreads.load();
}
int G4Threading::WorkerThreadLeavesPool() { return numActThreads--; }
int G4Threading::WorkerThreadJoinsPool() { return numActThreads++;}
G4int G4Threading::GetNumberOfRunningWorkerThreads() { return numActThreads.load(); }
#else // Sequential mode
G4Pid_t G4Threading::G4GetPidId()
{
// In sequential mode return Process ID and not Thread ID
#if defined(WIN32)
return GetCurrentProcessId();
#else
return getpid();
#endif
// In sequential mode return Process ID and not Thread ID
# if defined(WIN32)
return GetCurrentProcessId();
# else
return getpid();
# endif
}
G4int G4Threading::G4GetNumberOfCores() { return 1; }
@@ -133,8 +128,8 @@ G4bool G4Threading::G4SetPinAffinity(G4int, G4NativeThread&) { return true; }
void G4Threading::SetMultithreadedApplication(G4bool) {}
G4bool G4Threading::IsMultithreadedApplication() { return false; }
int G4Threading::WorkerThreadLeavesPool() { return 0; }
int G4Threading::WorkerThreadJoinsPool() { return 0; }
G4int G4Threading::WorkerThreadLeavesPool() { return 0; }
G4int G4Threading::WorkerThreadJoinsPool() { return 0; }
G4int G4Threading::GetNumberOfRunningWorkerThreads() { return 0; }
#endif
+54 -60
View File
@@ -23,14 +23,11 @@
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
// G4Timer class implementation
//
//
//
// ----------------------------------------------------------------------
// class G4Timer
//
// Implementation
// 29.04.97 G.Cosmo Added timings for Windows systems
// Author: P.Kent, 21.08.95 - First implementation
// Revision: G.Cosmo, 29.04.97 - Added timings for Windows
// --------------------------------------------------------------------
#include "G4Timer.hh"
#include "G4ios.hh"
@@ -39,13 +36,11 @@
// Global error function
#include "G4ExceptionSeverity.hh"
void G4Exception(const char* originOfException,
const char* exceptionCode,
G4ExceptionSeverity severity,
const char* comments);
void G4Exception(const char* originOfException, const char* exceptionCode,
G4ExceptionSeverity severity, const char* comments);
#if defined(IRIX6_2)
# if defined(_XOPEN_SOURCE) && (_XOPEN_SOURCE_EXTENDED==1)
# if defined(_XOPEN_SOURCE) && (_XOPEN_SOURCE_EXTENDED == 1)
# define __vfork vfork
# endif
#endif
@@ -54,56 +49,57 @@ void G4Exception(const char* originOfException,
# include <sys/types.h>
# include <windows.h>
// extract milliseconds time unit
G4int sysconf(G4int a)
{
if( a == _SC_CLK_TCK ) return 1000;
else return 0;
}
// extract milliseconds time unit
G4int sysconf(G4int a)
{
if(a == _SC_CLK_TCK)
return 1000;
else
return 0;
}
static clock_t filetime2msec( FILETIME* t )
{
return (clock_t)((((G4float)t->dwHighDateTime)*429496.7296)+
(((G4float)t->dwLowDateTime)*.0001) );
}
static clock_t filetime2msec(FILETIME* t)
{
return (clock_t)((((G4float) t->dwHighDateTime) * 429496.7296) +
(((G4float) t->dwLowDateTime) * .0001));
}
clock_t times(struct tms* t)
{
FILETIME ct = { 0, 0 }, et = { 0, 0 }, st = { 0, 0 }, ut = { 0, 0 },
rt = { 0, 0 };
SYSTEMTIME realtime;
clock_t times(struct tms * t)
{
FILETIME ct = {0,0}, et = {0,0}, st = {0,0}, ut = {0,0}, rt = {0,0};
SYSTEMTIME realtime;
GetSystemTime( &realtime );
SystemTimeToFileTime( &realtime, &rt ); // get real time in 10^-9 sec
if( t != 0 )
{
GetProcessTimes( GetCurrentProcess(), &ct, &et, &st, &ut);
// get process time in 10^-9 sec
t->tms_utime = t->tms_cutime = filetime2msec(&ut);
t->tms_stime = t->tms_cstime = filetime2msec(&st);
}
return filetime2msec(&rt);
}
GetSystemTime(&realtime);
SystemTimeToFileTime(&realtime, &rt); // get real time in 10^-9 sec
if(t != 0)
{
GetProcessTimes(GetCurrentProcess(), &ct, &et, &st, &ut);
// get process time in 10^-9 sec
t->tms_utime = t->tms_cutime = filetime2msec(&ut);
t->tms_stime = t->tms_cstime = filetime2msec(&st);
}
return filetime2msec(&rt);
}
#endif /* WIN32 */
// Print timer status on std::ostream
//
std::ostream& operator << (std::ostream& os, const G4Timer& t)
std::ostream& operator<<(std::ostream& os, const G4Timer& t)
{
// so fixed doesn't propagate
std::stringstream ss;
ss << std::fixed;
if (t.IsValid())
if(t.IsValid())
{
ss << "User=" << t.GetUserElapsed()
<< "s Real=" << t.GetRealElapsed()
ss << "User=" << t.GetUserElapsed() << "s Real=" << t.GetRealElapsed()
<< "s Sys=" << t.GetSystemElapsed() << "s";
#ifdef G4MULTITHREADED
// avoid possible FPE error
if(t.GetRealElapsed() > 1.0e-6)
{
G4double cpu_util = (t.GetUserElapsed()+t.GetSystemElapsed()) /
t.GetRealElapsed() * 100.0;
G4double cpu_util = (t.GetUserElapsed() + t.GetSystemElapsed()) /
t.GetRealElapsed() * 100.0;
ss << std::setprecision(1);
ss << " [Cpu=" << std::setprecision(1) << cpu_util << "%]";
}
@@ -120,39 +116,37 @@ std::ostream& operator << (std::ostream& os, const G4Timer& t)
G4Timer::G4Timer()
: fValidTimes(false)
{
}
{}
G4double G4Timer::GetRealElapsed() const
{
if (!fValidTimes)
if(!fValidTimes)
{
G4Exception("G4Timer::GetRealElapsed()", "InvalidCondition",
FatalException, "Timer not stopped or times not recorded!");
G4Exception("G4Timer::GetRealElapsed()", "InvalidCondition", FatalException,
"Timer not stopped or times not recorded!");
}
std::chrono::duration<G4double> diff=fEndRealTime-fStartRealTime;
std::chrono::duration<G4double> diff = fEndRealTime - fStartRealTime;
return diff.count();
}
G4double G4Timer::GetSystemElapsed() const
{
if (!fValidTimes)
if(!fValidTimes)
{
G4Exception("G4Timer::GetSystemElapsed()", "InvalidCondition",
FatalException, "Timer not stopped or times not recorded!");
}
G4double diff=fEndTimes.tms_stime-fStartTimes.tms_stime;
return diff/sysconf(_SC_CLK_TCK);
G4double diff = fEndTimes.tms_stime - fStartTimes.tms_stime;
return diff / sysconf(_SC_CLK_TCK);
}
G4double G4Timer::GetUserElapsed() const
{
if (!fValidTimes)
if(!fValidTimes)
{
G4Exception("G4Timer::GetUserElapsed()", "InvalidCondition",
FatalException, "Timer not stopped or times not recorded");
G4Exception("G4Timer::GetUserElapsed()", "InvalidCondition", FatalException,
"Timer not stopped or times not recorded");
}
G4double diff=fEndTimes.tms_utime-fStartTimes.tms_utime;
return diff/sysconf(_SC_CLK_TCK);
G4double diff = fEndTimes.tms_utime - fStartTimes.tms_utime;
return diff / sysconf(_SC_CLK_TCK);
}
File diff suppressed because it is too large Load Diff
@@ -23,47 +23,44 @@
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
// G4VExceptionHandler class implementation
//
//
//
// ------------------------------------------------------------
// GEANT 4 class implementation file
//
// ---------------- G4VExceptionHandler ----------------
// by Makoto Asai (August 2002)
// ------------------------------------------------------------
// Author: M.Asai, August 2002
// --------------------------------------------------------------------
#include "G4VExceptionHandler.hh"
#include "G4StateManager.hh"
G4VExceptionHandler::G4VExceptionHandler()
G4VExceptionHandler::G4VExceptionHandler()
{
G4StateManager * stateManager = G4StateManager::GetStateManager();
G4StateManager* stateManager = G4StateManager::GetStateManager();
stateManager->SetExceptionHandler(this);
}
G4VExceptionHandler::~G4VExceptionHandler()
G4VExceptionHandler::~G4VExceptionHandler() {}
G4VExceptionHandler::G4VExceptionHandler(const G4VExceptionHandler& right)
{
*this = right;
}
G4VExceptionHandler::G4VExceptionHandler(const G4VExceptionHandler &right)
G4VExceptionHandler& G4VExceptionHandler::operator=(
const G4VExceptionHandler& right)
{
*this = right;
if(&right == this)
{
return *this;
}
*this = right;
return *this;
}
G4VExceptionHandler& G4VExceptionHandler::operator=(const G4VExceptionHandler &right)
G4bool G4VExceptionHandler::operator==(const G4VExceptionHandler& right) const
{
if (&right == this) { return *this; }
*this = right;
return *this;
return (this == &right);
}
G4bool G4VExceptionHandler::operator==(const G4VExceptionHandler &right) const
G4bool G4VExceptionHandler::operator!=(const G4VExceptionHandler& right) const
{
return (this == &right);
}
G4bool G4VExceptionHandler::operator!=(const G4VExceptionHandler &right) const
{
return (this != &right);
return (this != &right);
}
+4 -11
View File
@@ -23,14 +23,11 @@
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
//
//
// G4VNotifier
// G4VNotifier class implementation
//
// Implementation for the generic notifier base class
//
// Author:
// 01.09.04 G.Cosmo Initial version
// Author: G.Cosmo, 01.09.2004 - Initial version
// --------------------------------------------------------------------
#include "G4VNotifier.hh"
@@ -39,14 +36,10 @@
// Constructor
// ***************************************************************************
//
G4VNotifier::G4VNotifier()
{
}
G4VNotifier::G4VNotifier() {}
// ***************************************************************************
// Destructor
// ***************************************************************************
//
G4VNotifier::~G4VNotifier()
{
}
G4VNotifier::~G4VNotifier() {}
@@ -23,49 +23,47 @@
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
// G4VStateDependent class implementation
//
//
//
// ------------------------------------------------------------
// GEANT 4 class implementation file
//
// ---------------- G4VStateDependent ----------------
// by Gabriele Cosmo, November 1996
// ------------------------------------------------------------
// Authors: G.Cosmo, M.Asai - November 1996
// --------------------------------------------------------------------
#include "G4VStateDependent.hh"
#include "G4StateManager.hh"
G4VStateDependent::G4VStateDependent(G4bool bottom)
G4VStateDependent::G4VStateDependent(G4bool bottom)
{
G4StateManager * stateManager = G4StateManager::GetStateManager();
stateManager->RegisterDependent(this,bottom);
G4StateManager* stateManager = G4StateManager::GetStateManager();
stateManager->RegisterDependent(this, bottom);
}
G4VStateDependent::~G4VStateDependent()
{
G4StateManager * stateManager = G4StateManager::GetStateManager();
stateManager->DeregisterDependent(this);
G4StateManager* stateManager = G4StateManager::GetStateManager();
stateManager->DeregisterDependent(this);
}
G4VStateDependent::G4VStateDependent(const G4VStateDependent &right)
G4VStateDependent::G4VStateDependent(const G4VStateDependent& right)
{
*this = right;
*this = right;
}
G4VStateDependent& G4VStateDependent::operator=(const G4VStateDependent &right)
G4VStateDependent& G4VStateDependent::operator=(const G4VStateDependent& right)
{
if (&right == this) { return *this; }
*this = right;
return *this;
if(&right == this)
{
return *this;
}
*this = right;
return *this;
}
G4bool G4VStateDependent::operator==(const G4VStateDependent &right) const
G4bool G4VStateDependent::operator==(const G4VStateDependent& right) const
{
return (this == &right);
return (this == &right);
}
G4bool G4VStateDependent::operator!=(const G4VStateDependent &right) const
G4bool G4VStateDependent::operator!=(const G4VStateDependent& right) const
{
return (this != &right);
return (this != &right);
}
@@ -23,50 +23,54 @@
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
// G4coutDestination class implementation
//
//
// ----------------------------------------------------------------------
// G4coutDestination
// ----------------------------------------------------------------------
// Authors: H.Yoshida, M.Nagamatu, 1997
// --------------------------------------------------------------------
#include "G4coutDestination.hh"
#include <algorithm>
G4coutDestination::~G4coutDestination()
{
}
// --------------------------------------------------------------------
G4coutDestination::~G4coutDestination() {}
// --------------------------------------------------------------------
void G4coutDestination::ResetTransformers()
{
transformersCout.clear(); transformersCerr.clear();
transformersCout.clear();
transformersCerr.clear();
}
// --------------------------------------------------------------------
G4int G4coutDestination::ReceiveG4cout(const G4String& msg)
{
std::cout<<msg<<std::flush;
std::cout << msg << std::flush;
return 0;
}
// --------------------------------------------------------------------
G4int G4coutDestination::ReceiveG4cerr(const G4String& msg)
{
std::cerr<<msg<<std::flush;
std::cerr << msg << std::flush;
return 0;
}
// --------------------------------------------------------------------
G4int G4coutDestination::ReceiveG4cout_(const G4String& msg)
{
// Avoid copy of string if not necessary
if( transformersCout.size() > 0 )
if(transformersCout.size() > 0)
{
G4String m = msg;
G4String m = msg;
G4bool result = true;
for ( const auto& el : transformersCout )
for(const auto& el : transformersCout)
{
result &= el(m);
if ( ! result ) break;
if(!result)
break;
}
return ( result ? ReceiveG4cout(m) : 0 );
return (result ? ReceiveG4cout(m) : 0);
}
else
{
@@ -74,15 +78,16 @@ G4int G4coutDestination::ReceiveG4cout_(const G4String& msg)
}
}
// --------------------------------------------------------------------
G4int G4coutDestination::ReceiveG4cerr_(const G4String& msg)
{
if( transformersCout.size() > 0 )
if(transformersCout.size() > 0)
{
G4String m = msg;
std::for_each( transformersCerr.begin() , transformersCerr.end() ,
[&m](const Transformer& t) { t(m); }
// Call transforming function on message
);
std::for_each(transformersCerr.begin(), transformersCerr.end(),
[&m](const Transformer& t) { t(m); }
// Call transforming function on message
);
return ReceiveG4cerr(m);
}
else
@@ -23,10 +23,7 @@
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
//
// --------------------------------------------------------------------
//
// G4coutFormatters.cc
// G4coutFormatters implementation
//
// Author: A.Dotti (SLAC), April 2017
// --------------------------------------------------------------------
@@ -39,15 +36,16 @@ namespace G4coutFormatters
namespace
{
// Split a single string in an array of strings
String_V split(const G4String& input, char separator='\n')
//
String_V split(const G4String& input, char separator = '\n')
{
String_V output;
G4String::size_type prev_pos=0, pos=0;
while( (pos=input.find(separator,pos))!=G4String::npos)
G4String::size_type prev_pos = 0, pos = 0;
while((pos = input.find(separator, pos)) != G4String::npos)
{
G4String substr( input.substr(prev_pos,pos-prev_pos)) ;
output.push_back(substr);
prev_pos = ++pos;
G4String substr(input.substr(prev_pos, pos - prev_pos));
output.push_back(substr);
prev_pos = ++pos;
}
// output.push_back( input.substr(prev_pos,pos-prev_pos));
return output;
@@ -55,112 +53,108 @@ namespace G4coutFormatters
// Return a syslog style message with input message, type identifies
// the type of the message
G4bool transform( G4String& input , const G4String& type)
//
G4bool transform(G4String& input, const G4String& type)
{
std::time_t result = std::time(nullptr);
std::ostringstream newm;
#if __GNUC__ >= 5
newm << std::put_time(std::localtime(&result),"%d/%b/%Y:%H:%M:%S %z");
newm << std::put_time(std::localtime(&result), "%d/%b/%Y:%H:%M:%S %z");
#else
std::tm* time_ = std::localtime(&result);
newm << time_->tm_mday << "/" << time_->tm_mon << "/" << time_->tm_year;
newm << ":" << time_->tm_hour << ":"<<time_->tm_min<<":"<<time_->tm_sec;
newm << ":" << time_->tm_hour << ":" << time_->tm_min << ":"
<< time_->tm_sec;
#endif
newm<<" "<<type<<" [";
newm << " " << type << " [";
G4String delimiter = "";
for (const auto& el : split(input) )
for(const auto& el : split(input))
{
if ( !el.empty() )
{
newm << delimiter << el ;
delimiter = "\\n";
}
if(!el.empty())
{
newm << delimiter << el;
delimiter = "\\n";
}
}
newm<<" ]"<<G4endl;
newm << " ]" << G4endl;
input = newm.str();
return true;
}
// Style used in master thread
//
G4String masterStyle = "";
// Modify output to look like syslog messages:
// DATE TIME **LOG|ERROR** [ "multi","line","message"]
SetupStyle_f SysLogStyle = [](G4coutDestination* dest)->G4int
{
if ( dest != nullptr )
//
SetupStyle_f SysLogStyle = [](G4coutDestination* dest) -> G4int {
if(dest != nullptr)
{
dest->AddCoutTransformer(std::bind(&transform,std::placeholders::_1,
"INFO"));
dest->AddCerrTransformer(std::bind(&transform,std::placeholders::_1,
"ERROR"));
dest->AddCoutTransformer(
std::bind(&transform, std::placeholders::_1, "INFO"));
dest->AddCerrTransformer(
std::bind(&transform, std::placeholders::_1, "ERROR"));
}
return 0;
};
// Bring back destination to original state
SetupStyle_f DefaultStyle = [](G4coutDestination* dest)->G4int
{
if ( dest != nullptr )
//
SetupStyle_f DefaultStyle = [](G4coutDestination* dest) -> G4int {
if(dest != nullptr)
{
dest->ResetTransformers();
dest->ResetTransformers();
}
return 0;
};
std::unordered_map<std::string,SetupStyle_f> transformers =
{
{ID::SYSLOG,SysLogStyle},
{ID::DEFAULT,DefaultStyle}
std::unordered_map<std::string, SetupStyle_f> transformers = {
{ ID::SYSLOG, SysLogStyle },
{ ID::DEFAULT, DefaultStyle }
};
}
} // namespace
void SetMasterStyle(const G4String& news )
{
masterStyle = news;
}
void SetMasterStyle(const G4String& news) { masterStyle = news; }
G4String GetMasterStyle()
{
return masterStyle;
}
G4String GetMasterStyle() { return masterStyle; }
void SetupStyleGlobally(const G4String& news)
{
static G4coutDestination ss;
G4coutbuf.SetDestination(&ss);
G4cerrbuf.SetDestination(&ss);
G4coutFormatters::HandleStyle(&ss,news);
G4coutFormatters::HandleStyle(&ss, news);
G4coutFormatters::SetMasterStyle(news);
}
String_V Names()
{
String_V result;
for ( const auto& el : transformers )
for(const auto& el : transformers)
{
result.push_back(el.first);
result.push_back(el.first);
}
return result;
}
G4int HandleStyle( G4coutDestination* dest , const G4String& style)
G4int HandleStyle(G4coutDestination* dest, const G4String& style)
{
const auto& handler = transformers.find(style);
return ( handler != transformers.end() ) ? (handler->second)(dest) : -1;
return (handler != transformers.cend()) ? (handler->second)(dest) : -1;
}
void RegisterNewStyle(const G4String& name , SetupStyle_f& fmt)
void RegisterNewStyle(const G4String& name, SetupStyle_f& fmt)
{
if ( transformers.find(name) != transformers.end() )
if(transformers.find(name) != transformers.cend())
{
G4ExceptionDescription msg;
msg << "Format Style with name " << name
<< " already exists. Replacing existing.";
G4Exception("G4coutFormatters::RegisterNewStyle()",
"FORMATTER001", JustWarning, msg);
G4ExceptionDescription msg;
msg << "Format Style with name " << name
<< " already exists. Replacing existing.";
G4Exception("G4coutFormatters::RegisterNewStyle()", "FORMATTER001",
JustWarning, msg);
}
// transformers.insert(std::make_pair(name,fmt));
transformers[name]=fmt;
transformers[name] = fmt;
}
}
} // namespace G4coutFormatters
+40 -35
View File
@@ -23,15 +23,10 @@
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
// G4ios implementation
//
//
//
// --------------------------------------------------------------
// GEANT 4 class implementation file
//
// G4ios.cc
//
// History 1998 Nov. 3 Masayasu Nagamatu
// Authors: H.Yoshida, M.Nagamatu - November 1998
// --------------------------------------------------------------------
#include "G4ios.hh"
#include "G4strstreambuf.hh"
@@ -41,60 +36,70 @@
G4strstreambuf*& _G4coutbuf_p()
{
G4ThreadLocalStatic G4strstreambuf* _instance = new G4strstreambuf();
return _instance;
G4ThreadLocalStatic G4strstreambuf* _instance = new G4strstreambuf();
return _instance;
}
G4strstreambuf*& _G4cerrbuf_p()
{
G4ThreadLocalStatic G4strstreambuf* _instance = new G4strstreambuf();
return _instance;
G4ThreadLocalStatic G4strstreambuf* _instance = new G4strstreambuf();
return _instance;
}
std::ostream*& _G4cout_p()
{
G4ThreadLocalStatic std::ostream* _instance = new std::ostream(_G4coutbuf_p());
return _instance;
G4ThreadLocalStatic std::ostream* _instance =
new std::ostream(_G4coutbuf_p());
return _instance;
}
std::ostream*& _G4cerr_p()
{
G4ThreadLocalStatic std::ostream* _instance = new std::ostream(_G4cerrbuf_p());
return _instance;
G4ThreadLocalStatic std::ostream* _instance =
new std::ostream(_G4cerrbuf_p());
return _instance;
}
#define G4coutbuf (*_G4coutbuf_p())
#define G4cerrbuf (*_G4cerrbuf_p())
#define G4cout (*_G4cout_p())
#define G4cerr (*_G4cerr_p())
# define G4coutbuf (*_G4coutbuf_p())
# define G4cerrbuf (*_G4cerrbuf_p())
# define G4cout (*_G4cout_p())
# define G4cerr (*_G4cerr_p())
void G4iosInitialization()
{
if (_G4coutbuf_p() == 0) _G4coutbuf_p() = new G4strstreambuf;
if (_G4cerrbuf_p() == 0) _G4cerrbuf_p() = new G4strstreambuf;
if (_G4cout_p() == &std::cout || _G4cout_p() == 0) _G4cout_p() = new std::ostream(_G4coutbuf_p());
if (_G4cerr_p() == &std::cerr || _G4cerr_p() == 0) _G4cerr_p() = new std::ostream(_G4cerrbuf_p());
if(_G4coutbuf_p() == nullptr)
_G4coutbuf_p() = new G4strstreambuf;
if(_G4cerrbuf_p() == nullptr)
_G4cerrbuf_p() = new G4strstreambuf;
if(_G4cout_p() == &std::cout || _G4cout_p() == nullptr)
_G4cout_p() = new std::ostream(_G4coutbuf_p());
if(_G4cerr_p() == &std::cerr || _G4cerr_p() == nullptr)
_G4cerr_p() = new std::ostream(_G4cerrbuf_p());
}
void G4iosFinalization()
{
delete _G4cout_p(); _G4cout_p() = &std::cout;
delete _G4cerr_p(); _G4cerr_p() = &std::cerr;
delete _G4coutbuf_p(); _G4coutbuf_p() = nullptr;
delete _G4cerrbuf_p(); _G4cerrbuf_p() = nullptr;
delete _G4cout_p();
_G4cout_p() = &std::cout;
delete _G4cerr_p();
_G4cerr_p() = &std::cerr;
delete _G4coutbuf_p();
_G4coutbuf_p() = nullptr;
delete _G4cerrbuf_p();
_G4cerrbuf_p() = nullptr;
}
// These two functions are guaranteed to be called at load and
// unload of the library containing this code.
namespace
{
#ifndef WIN32
void setupG4ioSystem(void) __attribute__ ((constructor));
void cleanupG4ioSystem(void) __attribute__((destructor));
#endif
void setupG4ioSystem(void) { G4iosInitialization(); }
void cleanupG4ioSystem(void) { G4iosFinalization(); }
}
# ifndef WIN32
void setupG4ioSystem(void) __attribute__((constructor));
void cleanupG4ioSystem(void) __attribute__((destructor));
# endif
void setupG4ioSystem(void) { G4iosInitialization(); }
void cleanupG4ioSystem(void) { G4iosFinalization(); }
} // namespace
#else // Sequential