예제 #1
0
def runSimulationFromRendezvous(threads, histories, time, rendezvous):

    ##--------------------------------------------------------------------------##
    ## ------------------------------ MPI Session ----------------------------- ##
    ##--------------------------------------------------------------------------##
    session = MPI.GlobalMPISession(len(sys.argv), sys.argv)
    Utility.removeAllLogs()
    session.initializeLogs(0, True)

    if session.rank() == 0:
        print "The PyFrensie path is set to: ", pyfrensie_path

    # Set the data path
    Collision.FilledGeometryModel.setDefaultDatabasePath(database_path)

    factory = Manager.ParticleSimulationManagerFactory(rendezvous, histories,
                                                       time, threads)

    manager = factory.getManager()

    Utility.removeAllLogs()
    session.initializeLogs(0, False)

    manager.runSimulation()

    if session.rank() == 0:

        rendezvous_number = manager.getNumberOfRendezvous()

        components = rendezvous.split("rendezvous_")
        archive_name = components[0] + "rendezvous_"
        archive_name += str(rendezvous_number - 1)
        archive_name += "."
        archive_name += components[1].split(".")[1]
예제 #2
0
def extractEstimatorData(rendezvous_file, estimator_id, entity_id):

    # Activate just-in-time initialization to prevent automatic loading of the
    # geometry and data tables
    Utility.activateJustInTimeInitialization()

    # Set the database path
    Collision.FilledGeometryModel.setDefaultDatabasePath(
        os.environ['DATABASE_PATH'])

    # Reload the simulation
    manager = Manager.ParticleSimulationManagerFactory(
        rendezvous_file).getManager()

    # Extract the estimator of interest
    estimator = manager.getEventHandler().getEstimator(estimator_id)

    # Extract the estimator data
    entity_bin_data = estimator.getEntityBinProcessedData(entity_id)
    energy_bins = list(estimator.getEnergyDiscretization())

    start_index = estimator.getNumberOfBins(Event.OBSERVER_ENERGY_DIMENSION)
    end_index = 2 * start_index

    # Print out the extracted data
    print "#bin start (MeV), bin end (MeV), mean, re, vov"

    for i in range(start_index, end_index):
        print energy_bins[i - start_index], energy_bins[
            i + 1 - start_index], entity_bin_data["mean"][i], entity_bin_data[
                "re"][i], entity_bin_data["vov"][i]
def extractEstimatorData(rendezvous_file, estimator_id, entity_id, is_adjoint):

    # Activate just-in-time initialization to prevent automatic loading of the
    # geometry and data tables
    Utility.activateJustInTimeInitialization()

    # Set the database path
    Collision.FilledGeometryModel.setDefaultDatabasePath(
        os.environ['DATABASE_PATH'])

    # Reload the simulation
    manager = Manager.ParticleSimulationManagerFactory(
        rendezvous_file).getManager()

    # Extract the estimator of interest
    estimator = manager.getEventHandler().getEstimator(estimator_id)

    if is_adjoint:
        energy_bins = list(estimator.getSourceEnergyDiscretization())
    else:
        energy_bins = list(estimator.getEnergyDiscretization())

    # Extract the estimator data
    entity_bin_data = estimator.getEntityBinProcessedData(entity_id)

    # Print out the extracted data
    print "#bin start (MeV), bin end (MeV), mean, re, vov, bin mid, mean/(bin width)"

    for i in range(0, len(energy_bins) - 1):
        print energy_bins[i], energy_bins[i + 1], entity_bin_data["mean"][
            i], entity_bin_data["re"][i], entity_bin_data["vov"][i], (
                energy_bins[i + 1] +
                energy_bins[i]) / 2, entity_bin_data["mean"][i] / (
                    energy_bins[i + 1] - energy_bins[i])
예제 #4
0
def runSimulationFromRendezvous(threads, histories, time, rendezvous):

    ##--------------------------------------------------------------------------##
    ## ------------------------------ MPI Session ----------------------------- ##
    ##--------------------------------------------------------------------------##
    session = MPI.GlobalMPISession(len(sys.argv), sys.argv)
    Utility.removeAllLogs()
    session.initializeLogs(0, True)

    if session.rank() == 0:
        print "The PyFrensie path is set to: ", pyfrensie_path

    # Set the data path
    Collision.FilledGeometryModel.setDefaultDatabasePath(database_path)

    factory = Manager.ParticleSimulationManagerFactory(rendezvous, histories,
                                                       time, threads)

    manager = factory.getManager()

    Utility.removeAllLogs()
    session.initializeLogs(0, False)

    manager.runSimulation()

    if session.rank() == 0:

        rendezvous_number = manager.getNumberOfRendezvous()

        components = rendezvous.split("rendezvous_")
        archive_name = components[0] + "rendezvous_"
        archive_name += str(rendezvous_number - 1)
        archive_name += "."
        archive_name += components[1].split(".")[1]

        # Get the event handler
        event_handler = manager.getEventHandler()

        # Get the simulation name and title
        properties = manager.getSimulationProperties()

        filename, title = setSimulationName(properties)

        print "Processing the results:"
        processData(event_handler, filename, title)

        print "Results will be in ", path.dirname(filename)
def extractEstimatorEnergyBins(rendezvous_file, estimator_id):

    # Activate just-in-time initialization to prevent automatic loading of the
    # geometry and data tables
    Utility.activateJustInTimeInitialization()

    # Set the database path
    Collision.FilledGeometryModel.setDefaultDatabasePath(
        os.environ['DATABASE_PATH'])

    # Reload the simulation
    manager = Manager.ParticleSimulationManagerFactory(
        rendezvous_file).getManager()

    # Extract the estimator of interest
    estimator = manager.getEventHandler().getEstimator(estimator_id)

    # Get the energy bins corresponding to the
    return list(estimator.getEnergyDiscretization())
def restartBroomstickSimulation( rendezvous_file_name,
                                 db_path,
                                 num_particles,
                                 threads,
                                 log_file = None,
                                 num_rendezvous = None ):

    ## Initialize the MPI session
    session = MPI.GlobalMPISession( len(sys.argv), sys.argv )

    # Suppress logging on all procs except for the master (proc=0)
    Utility.removeAllLogs()
    session.initializeLogs( 0, True )

    if not log_file is None:
        session.initializeLogs( log_file, 0, True )

    # Set the database path
    Collision.FilledGeometryModel.setDefaultDatabasePath( db_path )

    if not num_rendevous is None:
        new_simulation_properties = MonteCarlo.SimulationGeneralProperties()
        new_simulation_properties.setNumberOfHistories( int(num_particles) )
        new_simulation_properties.setMinNumberOfRendezvous( int(num_rendezvous) )

        factory = Manager.ParticleSimulationManagerFactory( rendezvous_file_name,
                                                            new_simulation_properties,
                                                            threads )
    else:
        factory = Manger.ParticleSimulationManagerFactory( rendezvous_file_name,
                                                           int(num_particles),
                                                           threads )
    
    manager = factory.getManager()

    # Allow logging on all procs
    session.restoreOutputStreams()

    ## Run the simulation
    if session.size() == 1:
        manager.runInterruptibleSimulation()
    else:
        manager.runSimulation()
def extractEstimatorTotalData(rendezvous_file, estimator_id, entity_id):

    # Activate just-in-time initialization to prevent automatic loading of the
    # geometry and data tables
    Utility.activateJustInTimeInitialization()

    # Set the database path
    Collision.FilledGeometryModel.setDefaultDatabasePath(
        os.environ['DATABASE_PATH'])

    # Reload the simulation
    manager = Manager.ParticleSimulationManagerFactory(
        rendezvous_file).getManager()

    # Extract the estimator of interest
    estimator = manager.getEventHandler().getEstimator(estimator_id)

    # Extract the estimator data
    entity_total_data = estimator.getEntityTotalProcessedData(entity_id)

    print entity_total_data["mean"][0], entity_total_data["re"][
        0], entity_total_data["mean"][0] * entity_total_data["re"][0]
예제 #8
0
import PyFrensie.Utility as Utility
import PyFrensie.Utility.MPI as MPI
import PyFrensie.Utility.Prng as Prng
import PyFrensie.Utility.Coordinate as Coordinate
import PyFrensie.Utility.Distribution as Distribution
import PyFrensie.MonteCarlo as MonteCarlo
import PyFrensie.MonteCarlo.Collision as Collision
import PyFrensie.MonteCarlo.ActiveRegion as ActiveRegion
import PyFrensie.MonteCarlo.Event as Event
import PyFrensie.MonteCarlo.Manager as Manager

##---------------------------------------------------------------------------##
## ------------------------------ MPI Session ------------------------------ ##
##---------------------------------------------------------------------------##
session = MPI.GlobalMPISession( len(sys.argv), sys.argv )
Utility.removeAllLogs()
session.initializeLogs( 0, True )

##---------------------------------------------------------------------------##
## ------------------------- SIMULATION VARIABLES -------------------------- ##
##---------------------------------------------------------------------------##

# Set the bivariate interpolation (LOGLOGLOG, LINLINLIN, LINLINLOG)
interp = MonteCarlo.LOGLOGLOG_INTERPOLATION

# Set the bivariate Grid Policy (UNIT_BASE_CORRELATED, CORRELATED, UNIT_BASE)
grid_policy = MonteCarlo.UNIT_BASE_CORRELATED_SAMPLING

# Set the elastic distribution mode ( DECOUPLED, COUPLED, HYBRID )
mode = MonteCarlo.COUPLED_DISTRIBUTION
def plotBroomstickSimulationSpectrum(rendezvous_file,
                                     estimator_id,
                                     entity_id,
                                     mcnp_file,
                                     mcnp_file_start,
                                     mcnp_file_end,
                                     is_a_current,
                                     top_ylims=None,
                                     bottom_ylims=None,
                                     xlims=None,
                                     legend_pos=None):

    # Activate just-in-time initialization to prevent automatic loading of the
    # geometry and data tables
    Utility.activateJustInTimeInitialization()

    # Set the database path
    Collision.FilledGeometryModel.setDefaultDatabasePath(
        os.environ['DATABASE_PATH'])

    # Reload the simulation
    manager = Manager.ParticleSimulationManagerFactory(
        rendezvous_file).getManager()

    # Extract the estimator of interest
    estimator = manager.getEventHandler().getEstimator(estimator_id)

    full_entity_bin_data = estimator.getEntityBinProcessedData(entity_id)

    start_index = estimator.getNumberOfBins(Event.OBSERVER_ENERGY_DIMENSION)
    end_index = 2 * start_index

    entity_bin_data = {"mean": [], "re": [], "e_bins": []}

    for i in range(start_index, end_index):
        entity_bin_data["mean"].append(full_entity_bin_data["mean"][i])
        entity_bin_data["re"].append(full_entity_bin_data["re"][i])

    entity_bin_data["e_bins"] = list(estimator.getEnergyDiscretization())

    # Extract the mcnp data from the output file
    mcnp_file = open(mcnp_file, "r")
    mcnp_file_lines = mcnp_file.readlines()

    mcnp_bin_data = {"e_up": [], "mean": [], "re": []}

    for i in range(mcnp_file_start, mcnp_file_end + 1):
        split_line = mcnp_file_lines[i - 1].split()

        mean_value = float(split_line[1])

        mcnp_bin_data["e_up"].append(float(split_line[0]))
        mcnp_bin_data["mean"].append(mean_value)
        mcnp_bin_data["re"].append(float(split_line[2]))

    output_file_name = "pb_broomstick_"
    output_file_names = []

    if is_a_current:
        output_file_names.append(output_file_name + "current.eps")
        output_file_names.append(output_file_name + "current.png")
        data_type = "Current"
    else:
        output_file_names.append(output_file_name + "flux.eps")
        output_file_names.append(output_file_name + "flux.png")
        data_type = "Flux"

    # Plot the data
    plotSpectralDataWithErrors("FRENSIE",
                               entity_bin_data,
                               "MCNP6",
                               mcnp_bin_data,
                               data_type,
                               log_spacing=False,
                               per_lethargy=False,
                               top_ylims=top_ylims,
                               bottom_ylims=bottom_ylims,
                               xlims=xlims,
                               legend_pos=legend_pos,
                               output_plot_names=output_file_names)
예제 #10
0
def runSimulation(threads, histories, time):

    ##--------------------------------------------------------------------------##
    ## ------------------------------ MPI Session ----------------------------- ##
    ##--------------------------------------------------------------------------##
    session = MPI.GlobalMPISession(len(sys.argv), sys.argv)
    Utility.removeAllLogs()
    session.initializeLogs(0, True)

    if session.rank() == 0:
        print "The PyFrensie path is set to: ", pyfrensie_path

    properties = setSimulationProperties(histories, time)

    ##--------------------------------------------------------------------------##
    ## ---------------------------- GEOMETRY SETUP ---------------------------- ##
    ##--------------------------------------------------------------------------##

    # Set geometry path and type
    geometry_type = "DagMC"  #(ROOT or DAGMC)

    # Set element zaid and name
    atom = Data.Au_ATOM
    zaid = 79000
    element = "Au"

    # Set geometry path and type
    model_properties = DagMC.DagMCModelProperties(geometry_path)
    model_properties.useFastIdLookup()

    # Set model
    geom_model = DagMC.DagMCModel(model_properties)

    ##--------------------------------------------------------------------------##
    ## -------------------------- EVENT HANDLER SETUP ------------------------- ##
    ##--------------------------------------------------------------------------##

    # Set event handler
    event_handler = Event.EventHandler(properties)

    ## -------------------- Transmission Current Estimator -------------------- ##

    # Setup a surface current estimator for the transmission current
    estimator_id = 1
    surface_ids = [1]
    transmission_current_estimator = Event.WeightMultipliedSurfaceCurrentEstimator(
        estimator_id, 1.0, surface_ids)

    # Set the particle type
    transmission_current_estimator.setParticleTypes([MonteCarlo.ELECTRON])

    # Set the cosine bins
    cosine_bins_1 = [
        -1.000000000000000, 0.000000000000000, 0.939692620785908,
        0.965925826289068, 0.984807753012208, 0.990268068741570,
        0.994521895368273, 0.995396198367179, 0.996194698091746,
        0.996917333733128, 0.997564050259824, 0.998134798421867,
        0.998629534754574, 0.999048221581858, 0.999390827019096,
        0.999657324975557, 0.999847695156391, 0.999961923064171,
        1.000000000000000
    ]

    transmission_current_estimator.setCosineDiscretization(cosine_bins_1)

    # Add the estimator to the event handler
    event_handler.addEstimator(transmission_current_estimator)

    ## --------------------- Reflection Current Estimator --------------------- ##

    # Setup a surface current estimator for the reflection current
    estimator_id = 2
    surface_ids = [2]
    reflection_current_estimator = Event.WeightMultipliedSurfaceCurrentEstimator(
        estimator_id, 1.0, surface_ids)

    # Set the particle type
    reflection_current_estimator.setParticleTypes([MonteCarlo.ELECTRON])

    # Set the cosine bins
    cosine_bins_2 = [-1.0, -0.999999, 0.0, 1.0]
    reflection_current_estimator.setCosineDiscretization(cosine_bins_2)

    # Add the estimator to the event handler
    event_handler.addEstimator(reflection_current_estimator)

    ## ---------------------- Track Length Flux Estimator --------------------- ##

    # Setup a track length flux estimator
    estimator_id = 3
    cell_ids = [1]
    track_flux_estimator = Event.WeightMultipliedCellTrackLengthFluxEstimator(
        estimator_id, 1.0, cell_ids, geom_model)

    # Set the particle type
    track_flux_estimator.setParticleTypes([MonteCarlo.ELECTRON])

    # Set the energy bins
    energy_bins = numpy.logspace(numpy.log10(1.5e-5),
                                 numpy.log10(15.7),
                                 num=101)  #[ 1.5e-5, 99l, 15.7 ]
    track_flux_estimator.setEnergyDiscretization(energy_bins)

    # Add the estimator to the event handler
    event_handler.addEstimator(track_flux_estimator)

    ##--------------------------------------------------------------------------##
    ## ----------------------- SIMULATION MANAGER SETUP ----------------------- ##
    ##--------------------------------------------------------------------------##

    # Initialized database
    database = Data.ScatteringCenterPropertiesDatabase(database_path)
    scattering_center_definition_database = Collision.ScatteringCenterDefinitionDatabase(
    )

    # Set element properties
    element_properties = database.getAtomProperties(atom)

    element_definition = scattering_center_definition_database.createDefinition(
        element, Data.ZAID(zaid))

    version = 0
    if file_type == Data.ElectroatomicDataProperties.ACE_EPR_FILE:
        version = 14

    element_definition.setElectroatomicDataProperties(
        element_properties.getSharedElectroatomicDataProperties(
            file_type, version))

    material_definition_database = Collision.MaterialDefinitionDatabase()
    material_definition_database.addDefinition(element, 1, (element, ),
                                               (1.0, ))

    # Fill model
    model = Collision.FilledGeometryModel(
        database_path, scattering_center_definition_database,
        material_definition_database, properties, geom_model, True)

    # Set particle distribution
    particle_distribution = ActiveRegion.StandardParticleDistribution(
        "source distribution")

    # Set the energy dimension distribution
    delta_energy = Distribution.DeltaDistribution(15.7)
    energy_dimension_dist = ActiveRegion.IndependentEnergyDimensionDistribution(
        delta_energy)
    particle_distribution.setDimensionDistribution(energy_dimension_dist)

    # Set the direction dimension distribution
    particle_distribution.setDirection(0.0, 0.0, 1.0)

    # Set the spatial dimension distribution
    particle_distribution.setPosition(0.0, 0.0, -0.1)

    particle_distribution.constructDimensionDistributionDependencyTree()

    # Set source components
    source_component = [
        ActiveRegion.StandardElectronSourceComponent(0, 1.0, geom_model,
                                                     particle_distribution)
    ]

    # Set source
    source = ActiveRegion.StandardParticleSource(source_component)

    # Set the archive type
    archive_type = "xml"

    name, title = setSimulationName(properties)

    factory = Manager.ParticleSimulationManagerFactory(model, source,
                                                       event_handler,
                                                       properties, name,
                                                       archive_type, threads)

    manager = factory.getManager()

    Utility.removeAllLogs()
    session.initializeLogs(0, False)

    manager.runSimulation()

    if session.rank() == 0:

        print "Processing the results:"
        processCosineBinData(transmission_current_estimator, cosine_bins_1,
                             name, title)

        print "Results will be in ", path.dirname(name)
예제 #11
0
    parser.add_option("--db_path",
                      type="string",
                      dest="db_path",
                      help="the database name (with extension)")
    parser.add_option("--sim_name",
                      type="string",
                      dest="sim_name",
                      default="sphere",
                      help="the simulation name")
    parser.add_option("--log_file",
                      type="string",
                      dest="log_file",
                      help="the file that will be used for logging")
    parser.add_option("--num_particles",
                      type="float",
                      dest="num_particles",
                      default=1e3,
                      help="the number of particles to run")
    options, args = parser.parse_args()

    if options.db_path is None:
        print "The database path must be specified!"
        sys.exit(1)

    # Run the simulation
    runBroomstickSimulation(
        options.sim_name, options.db_path, options.num_particles,
        MonteCarlo.DECOUPLED_HALF_PROFILE_DB_HYBRID_INCOHERENT_MODEL, 0.2,
        Utility.doubleArrayFromString("{1e-3, 998i, 0.2}"), options.threads,
        options.log_file)
예제 #12
0
def runSimulation(threads, histories, time):

    ##--------------------------------------------------------------------------##
    ## ------------------------------ MPI Session ----------------------------- ##
    ##--------------------------------------------------------------------------##
    session = MPI.GlobalMPISession(len(sys.argv), sys.argv)
    Utility.removeAllLogs()
    session.initializeLogs(0, True)

    properties = setSimulationProperties(histories, time)
    name, title = setSimulationName(properties)
    path_to_database = database_path
    path_to_geometry = geometry_path

    ##--------------------------------------------------------------------------##
    ## ---------------------------- GEOMETRY SETUP ---------------------------- ##
    ##--------------------------------------------------------------------------##

    # Set geometry path and type
    geometry_type = "DagMC"  #(ROOT or DAGMC)

    # Set geometry model properties
    if geometry_type == "DagMC":
        model_properties = DagMC.DagMCModelProperties(path_to_geometry)
        model_properties.useFastIdLookup()
        # model_properties.setMaterialPropertyName( "mat" )
        # model_properties.setDensityPropertyName( "rho" )
        # model_properties.setTerminationCellPropertyName( "graveyard" )
        # model_properties.setEstimatorPropertyName( "tally" )
    else:
        print "ERROR: geometry type ", geometry_type, " not supported!"

    # Construct model
    geom_model = DagMC.DagMCModel(model_properties)

    ##--------------------------------------------------------------------------##
    ## -------------------------- EVENT HANDLER SETUP ------------------------- ##
    ##--------------------------------------------------------------------------##

    # Set event handler
    event_handler = Event.EventHandler(properties)

    ## -------------------- Charge Deposition Calorimeter --------------------- ##

    number_of_subzones = 40

    # Setup a cell pulse height estimator
    estimator_id = 1
    cell_ids = range(1, number_of_subzones + 1)
    charge_deposition_estimator = Event.WeightAndChargeMultipliedCellPulseHeightEstimator(
        estimator_id, 1.0, cell_ids)

    # Set the particle type
    charge_deposition_estimator.setParticleTypes([MonteCarlo.ELECTRON])

    # Add the estimator to the event handler
    event_handler.addEstimator(charge_deposition_estimator)

    ##--------------------------------------------------------------------------##
    ## ----------------------- SIMULATION MANAGER SETUP ------------------------ ##
    ##--------------------------------------------------------------------------##

    # Initialized database
    database = Data.ScatteringCenterPropertiesDatabase(path_to_database)
    scattering_center_definition_database = Collision.ScatteringCenterDefinitionDatabase(
    )

    # Set material properties
    version = 0
    if file_type == Data.ElectroatomicDataProperties.ACE_EPR_FILE:
        version = 14

    # Definition for Aluminum
    if material == "Al":
        al_properties = database.getAtomProperties(Data.Al_ATOM)

        al_definition = scattering_center_definition_database.createDefinition(
            material, Data.ZAID(13000))

        al_definition.setElectroatomicDataProperties(
            al_properties.getSharedElectroatomicDataProperties(
                file_type, version))

    elif material == "Be":
        be_properties = database.getAtomProperties(Data.Be_ATOM)

        be_definition = scattering_center_definition_database.createDefinition(
            material, Data.ZAID(4000))

        be_definition.setElectroatomicDataProperties(
            be_properties.getSharedElectroatomicDataProperties(
                file_type, version))

    else:
        print "ERROR: material ", material, " is currently not supported!"

    definition = ((material, 1.0), )

    material_definition_database = Collision.MaterialDefinitionDatabase()
    material_definition_database.addDefinition(material, 1, definition)

    # Fill model
    model = Collision.FilledGeometryModel(
        path_to_database, scattering_center_definition_database,
        material_definition_database, properties, geom_model, True)

    # Set the source energy (14.9 MeV)
    energy = 14.9

    # Set particle distribution
    particle_distribution = ActiveRegion.StandardParticleDistribution(
        "source distribution")

    # Set the energy dimension distribution
    delta_energy = Distribution.DeltaDistribution(energy)
    energy_dimension_dist = ActiveRegion.IndependentEnergyDimensionDistribution(
        delta_energy)
    particle_distribution.setDimensionDistribution(energy_dimension_dist)

    # Set the direction dimension distribution
    particle_distribution.setDirection(0.0, 0.0, 1.0)

    # Set the spatial dimension distribution
    particle_distribution.setPosition(0.0, 0.0, -0.01)

    particle_distribution.constructDimensionDistributionDependencyTree()

    # Set source components
    source_component = [
        ActiveRegion.StandardElectronSourceComponent(0, 1.0, geom_model,
                                                     particle_distribution)
    ]

    # Set source
    source = ActiveRegion.StandardParticleSource(source_component)

    # Set the archive type
    archive_type = "xml"

    factory = Manager.ParticleSimulationManagerFactory(model, source,
                                                       event_handler,
                                                       properties, name,
                                                       archive_type, threads)

    manager = factory.getManager()

    Utility.removeAllLogs()
    session.initializeLogs(0, False)

    manager.runSimulation()

    if session.rank() == 0:

        print "Processing the results:"
        processData(charge_deposition_estimator, name, title,
                    subzone_width * density)

        print "Results will be in ", path.dirname(name)
예제 #13
0
def runAdjointSimulation( sim_name,
                          db_path,
                          geom_name,
                          num_particles,
                          incoherent_model_type,
                          threads,
                          use_energy_bins = False,
                          log_file= None ):

    ## Initialize the MPI session
    session = MPI.GlobalMPISession( len(sys.argv), sys.argv )

    # Suppress logging on all procs except for the master (proc=0)
    Utility.removeAllLogs()
    session.initializeLogs( 0, True )

    if not log_file is None:
        session.initializeLogs( log_file, 0, True )

    ## Set the simulation properties
    simulation_properties = MonteCarlo.SimulationProperties()

    # Simulate photons only
    simulation_properties.setParticleMode( MonteCarlo.ADJOINT_PHOTON_MODE )
    simulation_properties.setIncoherentAdjointModelType( incoherent_model_type )
    simulation_properties.setMinAdjointPhotonEnergy( 1e-3 )
    
    if incoherent_model_type == MonteCarlo.DB_IMPULSE_INCOHERENT_ADJOINT_MODEL:
        simulation_properties.setMaxAdjointPhotonEnergy( energy_bins[-1]*1.5 )
    else:
        simulation_properties.setMaxAdjointPhotonEnergy( energy_bins[-1] )

    
    simulation_properties.setCriticalAdjointPhotonLineEnergies( [0.186211, 0.241995, 0.2656, 0.2952228, 0.3046, 0.3519321, 0.60932, 0.6496, 0.665447, 0.76836,  0.78596, 0.80618, 0.934056, 1.120294, 1.15521, 1.238122, 1.280976, 1.377669, 1.401515, 1.407988, 1.50921, 1.661274, 1.729595, 1.764491, 1.847429, 2.118514, 2.204059, 2.44770] )
    simulation_properties.setAdjointPhotonRouletteThresholdWeight( 0.0025 )
    simulation_properties.setAdjointPhotonRouletteSurvivalWeight(  0.005 )
    simulation_properties.setNumberOfAdjointPhotonHashGridBins( 100 )

    # Set the number of histories to run and the number of rendezvous
    simulation_properties.setNumberOfHistories( num_particles )
    simulation_properties.setMinNumberOfRendezvous( 100 )
    simulation_properties.setNumberOfSnapshotsPerBatch( 1 )

    ## Set up the materials
    database = Data.ScatteringCenterPropertiesDatabase( db_path )

    # Extract the properties from the database
    c_atom_properties = database.getAtomProperties( Data.ZAID(6000) )
    n_atom_properties = database.getAtomProperties( Data.ZAID(7000) )
    o_atom_properties = database.getAtomProperties( Data.ZAID(8000) )
    na_atom_properties = database.getAtomProperties( Data.ZAID(11000) )
    mg_atom_properties = database.getAtomProperties( Data.ZAID(12000) )
    al_atom_properties = database.getAtomProperties( Data.ZAID(13000) )
    si_atom_properties = database.getAtomProperties( Data.ZAID(14000) )
    ar_atom_properties = database.getAtomProperties( Data.ZAID(18000) )
    k_atom_properties = database.getAtomProperties( Data.ZAID(19000) )
    ca_atom_properties = database.getAtomProperties( Data.ZAID(20000) )
    ti_atom_properties = database.getAtomProperties( Data.ZAID(22000) )
    mn_atom_properties = database.getAtomProperties( Data.ZAID(25000) )
    fe_atom_properties = database.getAtomProperties( Data.ZAID(26000) )

    # Set the atom definitions
    scattering_center_definitions = Collision.ScatteringCenterDefinitionDatabase()

    c_atom_definition = scattering_center_definitions.createDefinition( "C", Data.ZAID(6000) )
    n_atom_definition = scattering_center_definitions.createDefinition( "N", Data.ZAID(7000) )
    o_atom_definition = scattering_center_definitions.createDefinition( "O", Data.ZAID(8000) )
    na_atom_definition = scattering_center_definitions.createDefinition( "Na", Data.ZAID(11000) )
    mg_atom_definition = scattering_center_definitions.createDefinition( "Mg", Data.ZAID(12000) )
    al_atom_definition = scattering_center_definitions.createDefinition( "Al", Data.ZAID(13000) )
    si_atom_definition = scattering_center_definitions.createDefinition( "Si", Data.ZAID(14000) )
    ar_atom_definition = scattering_center_definitions.createDefinition( "Ar", Data.ZAID(18000) )
    k_atom_definition = scattering_center_definitions.createDefinition( "K", Data.ZAID(19000) )
    ca_atom_definition = scattering_center_definitions.createDefinition( "Ca", Data.ZAID(20000) )
    ti_atom_definition = scattering_center_definitions.createDefinition( "Ti", Data.ZAID(22000) )
    mn_atom_definition = scattering_center_definitions.createDefinition( "Mn", Data.ZAID(25000) )
    fe_atom_definition = scattering_center_definitions.createDefinition( "Fe", Data.ZAID(26000) )

    data_file_type = Data.AdjointPhotoatomicDataProperties.Native_EPR_FILE
    file_version = 0

    c_atom_definition.setAdjointPhotoatomicDataProperties( c_atom_properties.getSharedAdjointPhotoatomicDataProperties( data_file_type, file_version ) )
    n_atom_definition.setAdjointPhotoatomicDataProperties( n_atom_properties.getSharedAdjointPhotoatomicDataProperties( data_file_type, file_version ) )
    o_atom_definition.setAdjointPhotoatomicDataProperties( o_atom_properties.getSharedAdjointPhotoatomicDataProperties( data_file_type, file_version ) )
    na_atom_definition.setAdjointPhotoatomicDataProperties( na_atom_properties.getSharedAdjointPhotoatomicDataProperties( data_file_type, file_version ) )
    mg_atom_definition.setAdjointPhotoatomicDataProperties( mg_atom_properties.getSharedAdjointPhotoatomicDataProperties( data_file_type, file_version ) )
    al_atom_definition.setAdjointPhotoatomicDataProperties( al_atom_properties.getSharedAdjointPhotoatomicDataProperties( data_file_type, file_version ) )
    si_atom_definition.setAdjointPhotoatomicDataProperties( si_atom_properties.getSharedAdjointPhotoatomicDataProperties( data_file_type, file_version ) )
    ar_atom_definition.setAdjointPhotoatomicDataProperties( ar_atom_properties.getSharedAdjointPhotoatomicDataProperties( data_file_type, file_version ) )
    k_atom_definition.setAdjointPhotoatomicDataProperties( k_atom_properties.getSharedAdjointPhotoatomicDataProperties( data_file_type, file_version ) )
    ca_atom_definition.setAdjointPhotoatomicDataProperties( ca_atom_properties.getSharedAdjointPhotoatomicDataProperties( data_file_type, file_version ) )
    ti_atom_definition.setAdjointPhotoatomicDataProperties( ti_atom_properties.getSharedAdjointPhotoatomicDataProperties( data_file_type, file_version ) )
    mn_atom_definition.setAdjointPhotoatomicDataProperties( mn_atom_properties.getSharedAdjointPhotoatomicDataProperties( data_file_type, file_version ) )
    fe_atom_definition.setAdjointPhotoatomicDataProperties( fe_atom_properties.getSharedAdjointPhotoatomicDataProperties( data_file_type, file_version ) )

    # Set the definition for material 1 (ave soil US from PNNL-15870 Rev1)
    material_definitions = Collision.MaterialDefinitionDatabase()
    material_definitions.addDefinition( "Soil", 1, ["O", "Na", "Mg", "Al", "Si", "K", "Ca", "Ti", "Mn", "Fe"], [0.670604, 0.005578, 0.011432, 0.053073, 0.201665, 0.007653, 0.026664, 0.002009, 0.000272, 0.021050] )
    
    material_definitions.addDefinition( "Air", 2, ["C", "N", "O", "Ar"], [0.000150, 0.784431, 0.231781, 0.004671] )

    # Set up the geometry
    model_properties = DagMC.DagMCModelProperties( geom_name )
    model_properties.setMaterialPropertyName( "mat" )
    model_properties.setDensityPropertyName( "rho" )
    model_properties.setTerminationCellPropertyName( "termination.cell" )
    model_properties.setReflectingSurfacePropertyName( "reflecting.surface" )
    model_properties.setSurfaceFluxName( "surface.flux" )
    model_properties.useFastIdLookup()

    # Load the model
    model = DagMC.DagMCModel( model_properties )

    # Fill the model with the defined material
    filled_model = Collision.FilledGeometryModel( db_path, scattering_center_definitions, material_definitions, simulation_properties, model, True )

    # Set up the source
    particle_distribution = ActiveRegion.StandardParticleDistribution( "isotropic point source" )

    uniform_energy = Distribution.UniformDistribution( 1e-3, energy_bins[-1] )
    energy_dimension_dist = ActiveRegion.IndependentEnergyDimensionDistribution( uniform_energy )
    particle_distribution.setDimensionDistribution( energy_dimension_dist )
    particle_distribution.setPosition( 0.0, 0.0, 5200.0 )
    particle_distribution.constructDimensionDistributionDependencyTree()

    # The generic distribution will be used to generate photons
    adjoint_photon_distribution = ActiveRegion.StandardAdjointPhotonSourceComponent( 0, 1.0, filled_model, particle_distribution )

    # Assign the photon source component to the source
    source = ActiveRegion.StandardParticleSource( [adjoint_photon_distribution] )

    ## Set up the event handler
    event_handler = Event.EventHandler( model, simulation_properties )

    # Create the discrete forward source line energy response function
    discrete_energy_response_function = ActiveRegion.EnergyParticleResponseFunction( Distribution.DiscreteDistribution( [0.186211, 0.241995, 0.2656, 0.2952228, 0.3046, 0.3519321, 0.60932, 0.6496, 0.665447, 0.76836, 0.78596, 0.80618, 0.934056, 1.120294, 1.15521, 1.238122, 1.280976, 1.377669, 1.401515, 1.407988, 1.50921, 1.661274, 1.729595, 1.764491, 1.847429, 2.118514, 2.204059, 2.44770],
                                                                                                                        [0.013622652525055947, 0.02713677292834634, 0.1908668348290806, 0.068936609755915, 0.10478963480812267, 0.13323253568461313, 0.17024573169362503, 0.012724455655272039, 0.0057297475318298504, 0.01831573116967687, 0.00396703617487893, 0.004730503514195252, 0.011627906976744184, 0.05583790540489965, 0.006111481201488011, 0.021833668909663845, 0.005366726296958854, 0.014925037986242614, 0.004977507653385827, 0.00895951377609449, 0.007971497219332189, 0.003918383844432301, 0.010770877463492038, 0.057260050448724176, 0.007578536088801728, 0.004341284870622224, 0.01842800577839986, 0.005793369810106211] ) )

    # Create the flux-to-effective dose from ICRP-116 table A.1, ISO values)
    flux_to_dose_response_function = ActiveRegion.SourceEnergyParticleResponseFunction( Distribution.TabularDistribution_LinLin( [0.01, 0.015, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.1, 0.15, 0.2, 0.3, 0.4, 0.5, 0.511, 0.6, 0.662, 0.8, 1.0, 1.117, 1.33, 1.5, 2.0, 3.0],
                                                                                                                                 [0.0288, 0.0560, 0.0812, 0.127, 0.158, 0.180, 0.199, 0.218, 0.239, 0.287, 0.429, 0.589, 0.932, 1.28, 1.63, 1.67, 1.97, 2.17, 2.62, 3.25, 3.60, 4.20, 4.66, 5.90, 8.08] ) )

    # Create the complete response function
    response = ActiveRegion.StandardParticleResponse( discrete_energy_response_function*flux_to_dose_response_function/1000.0 )

    source_norm = 1462129.344*(energy_bins[-1] - 1e-3)

    # Create the cell track-length flux estimator
    cell_flux_estimator = Event.WeightMultipliedCellTrackLengthFluxEstimator( 1, source_norm, [2], model )
    cell_flux_estimator.setParticleTypes( [MonteCarlo.ADJOINT_PHOTON] )
    cell_flux_estimator.setResponseFunctions( [response] )

    event_handler.addEstimator( cell_flux_estimator )

    # Create the second estimator
    if use_energy_bins:
        cell_flux_estimator_2 = Event.WeightMultipliedCellTrackLengthFluxEstimator( 2, source_norm, [2], model )
        cell_flux_estimator_2.setSourceEnergyDiscretization( energy_bins )
        cell_flux_estimator_2.setParticleTypes( [MonteCarlo.ADJOINT_PHOTON] )
        cell_flux_estimator_2.setResponseFunctions( [response] )
        
        event_handler.addEstimator( cell_flux_estimator_2 )

    # Set up the simulation manager
    factory = Manager.ParticleSimulationManagerFactory( filled_model,
                                                        source,
                                                        event_handler,
                                                        simulation_properties,
                                                        sim_name,
                                                        "xml",
                                                        threads )

    # Create the simulation manager
    manager = factory.getManager()
    manager.useSingleRendezvousFile()

    # Allow logging on all procs
    session.restoreOutputStreams()

    ## Run the simulation
    if session.size() == 1:
        manager.runInterruptibleSimulation()
    else:
        manager.runSimulation()
예제 #14
0
def runForwardSimulation( sim_name,
                          db_path,
                          geom_name,
                          num_particles,
                          incoherent_model_type,
                          threads,
                          use_energy_bins = False,
                          use_native = False,
                          log_file = None,
                          enable_relax = True ):

    ## Initialize the MPI session
    session = MPI.GlobalMPISession( len(sys.argv), sys.argv )

    # Suppress logging on all procs except for the master (proc=0)
    Utility.removeAllLogs()
    session.initializeLogs( 0, True )

    if not log_file is None:
        session.initializeLogs( log_file, 0, True )

    ## Set the simulation properties
    simulation_properties = MonteCarlo.SimulationProperties()

    # Simulate photons only
    simulation_properties.setParticleMode( MonteCarlo.PHOTON_MODE )
    simulation_properties.setIncoherentModelType( incoherent_model_type )
    simulation_properties.setNumberOfPhotonHashGridBins( 100 )

    # Enable atomic relaxation
    if enable_relax:
        simulation_properties.setAtomicRelaxationModeOn( MonteCarlo.PHOTON )
    else:
        simulation_properties.setAtomicRelaxationModeOff( MonteCarlo.PHOTON )

    # Set the number of histories to run and the number of rendezvous
    simulation_properties.setNumberOfHistories( num_particles )
    simulation_properties.setMinNumberOfRendezvous( 10 )
    simulation_properties.setNumberOfSnapshotsPerBatch( 10 )

    ## Set up the materials
    database = Data.ScatteringCenterPropertiesDatabase( db_path )

    # Extract the properties from the database
    c_atom_properties = database.getAtomProperties( Data.ZAID(6000) )
    n_atom_properties = database.getAtomProperties( Data.ZAID(7000) )
    o_atom_properties = database.getAtomProperties( Data.ZAID(8000) )
    na_atom_properties = database.getAtomProperties( Data.ZAID(11000) )
    mg_atom_properties = database.getAtomProperties( Data.ZAID(12000) )
    al_atom_properties = database.getAtomProperties( Data.ZAID(13000) )
    si_atom_properties = database.getAtomProperties( Data.ZAID(14000) )
    ar_atom_properties = database.getAtomProperties( Data.ZAID(18000) )
    k_atom_properties = database.getAtomProperties( Data.ZAID(19000) )
    ca_atom_properties = database.getAtomProperties( Data.ZAID(20000) )
    ti_atom_properties = database.getAtomProperties( Data.ZAID(22000) )
    mn_atom_properties = database.getAtomProperties( Data.ZAID(25000) )
    fe_atom_properties = database.getAtomProperties( Data.ZAID(26000) )

    # Set the atom definitions
    scattering_center_definitions = Collision.ScatteringCenterDefinitionDatabase()

    c_atom_definition = scattering_center_definitions.createDefinition( "C", Data.ZAID(6000) )
    n_atom_definition = scattering_center_definitions.createDefinition( "N", Data.ZAID(7000) )
    o_atom_definition = scattering_center_definitions.createDefinition( "O", Data.ZAID(8000) )
    na_atom_definition = scattering_center_definitions.createDefinition( "Na", Data.ZAID(11000) )
    mg_atom_definition = scattering_center_definitions.createDefinition( "Mg", Data.ZAID(12000) )
    al_atom_definition = scattering_center_definitions.createDefinition( "Al", Data.ZAID(13000) )
    si_atom_definition = scattering_center_definitions.createDefinition( "Si", Data.ZAID(14000) )
    ar_atom_definition = scattering_center_definitions.createDefinition( "Ar", Data.ZAID(18000) )
    k_atom_definition = scattering_center_definitions.createDefinition( "K", Data.ZAID(19000) )
    ca_atom_definition = scattering_center_definitions.createDefinition( "Ca", Data.ZAID(20000) )
    ti_atom_definition = scattering_center_definitions.createDefinition( "Ti", Data.ZAID(22000) )
    mn_atom_definition = scattering_center_definitions.createDefinition( "Mn", Data.ZAID(25000) )
    fe_atom_definition = scattering_center_definitions.createDefinition( "Fe", Data.ZAID(26000) )

    if use_native:
        data_file_type = Data.PhotoatomicDataProperties.Native_EPR_FILE
        file_version = 0
    else:
        data_file_type = Data.PhotoatomicDataProperties.ACE_EPR_FILE
        file_version = 12

    c_atom_definition.setPhotoatomicDataProperties( c_atom_properties.getSharedPhotoatomicDataProperties( data_file_type, file_version ) )
    n_atom_definition.setPhotoatomicDataProperties( n_atom_properties.getSharedPhotoatomicDataProperties( data_file_type, file_version ) )
    o_atom_definition.setPhotoatomicDataProperties( o_atom_properties.getSharedPhotoatomicDataProperties( data_file_type, file_version ) )
    na_atom_definition.setPhotoatomicDataProperties( na_atom_properties.getSharedPhotoatomicDataProperties( data_file_type, file_version ) )
    mg_atom_definition.setPhotoatomicDataProperties( mg_atom_properties.getSharedPhotoatomicDataProperties( data_file_type, file_version ) )
    al_atom_definition.setPhotoatomicDataProperties( al_atom_properties.getSharedPhotoatomicDataProperties( data_file_type, file_version ) )
    si_atom_definition.setPhotoatomicDataProperties( si_atom_properties.getSharedPhotoatomicDataProperties( data_file_type, file_version ) )
    ar_atom_definition.setPhotoatomicDataProperties( ar_atom_properties.getSharedPhotoatomicDataProperties( data_file_type, file_version ) )
    k_atom_definition.setPhotoatomicDataProperties( k_atom_properties.getSharedPhotoatomicDataProperties( data_file_type, file_version ) )
    ca_atom_definition.setPhotoatomicDataProperties( ca_atom_properties.getSharedPhotoatomicDataProperties( data_file_type, file_version ) )
    ti_atom_definition.setPhotoatomicDataProperties( ti_atom_properties.getSharedPhotoatomicDataProperties( data_file_type, file_version ) )
    mn_atom_definition.setPhotoatomicDataProperties( mn_atom_properties.getSharedPhotoatomicDataProperties( data_file_type, file_version ) )
    fe_atom_definition.setPhotoatomicDataProperties( fe_atom_properties.getSharedPhotoatomicDataProperties( data_file_type, file_version ) )

    # Set the definition for material 1 (ave soil US from PNNL-15870 Rev1)
    material_definitions = Collision.MaterialDefinitionDatabase()
    material_definitions.addDefinition( "Soil", 1, ["O", "Na", "Mg", "Al", "Si", "K", "Ca", "Ti", "Mn", "Fe"], [0.670604, 0.005578, 0.011432, 0.053073, 0.201665, 0.007653, 0.026664, 0.002009, 0.000272, 0.021050] )
    
    material_definitions.addDefinition( "Air", 2, ["C", "N", "O", "Ar"], [0.000150, 0.784431, 0.231781, 0.004671] )

    # Set up the geometry
    model_properties = DagMC.DagMCModelProperties( geom_name )
    model_properties.setMaterialPropertyName( "mat" )
    model_properties.setDensityPropertyName( "rho" )
    model_properties.setTerminationCellPropertyName( "termination.cell" )
    model_properties.setReflectingSurfacePropertyName( "reflecting.surface" )
    model_properties.setSurfaceFluxName( "surface.flux" )
    model_properties.useFastIdLookup()

    # Load the model
    model = DagMC.DagMCModel( model_properties )

    # Fill the model with the defined material
    filled_model = Collision.FilledGeometryModel( db_path, scattering_center_definitions, material_definitions, simulation_properties, model, True )

    # Set up the source
    particle_distribution = ActiveRegion.StandardParticleDistribution( "contaminated soil dist" )

    decay_energy_dist = Distribution.DiscreteDistribution( [0.186211, 0.241995, 0.2656, 0.2952228, 0.3046, 0.3519321, 0.60932, 0.6496, 0.665447, 0.76836, 0.78596, 0.80618, 0.934056, 1.120294, 1.15521, 1.238122, 1.280976, 1.377669, 1.401515, 1.407988, 1.50921, 1.661274, 1.729595, 1.764491, 1.847429, 2.118514, 2.204059, 2.44770],
                                                        [3.64, 7.251, 51.0, 18.42, 28.0, 35.60, 45.49, 3.4, 1.531, 4.894, 1.06, 1.264, 3.107, 14.92, 1.633, 5.834, 1.434, 3.988, 1.330, 2.394, 2.130, 1.047, 2.878, 15.30, 2.025, 1.160, 4.924, 1.548] )
        
    energy_dimension_dist = ActiveRegion.IndependentEnergyDimensionDistribution( decay_energy_dist )
    particle_distribution.setDimensionDistribution( energy_dimension_dist )

    uniform_xy_position_dist = Distribution.UniformDistribution( -5.0, 5.0 )
    uniform_z_position_dist = Distribution.UniformDistribution( 5000, 5100 )

    x_position_dimension_dist = ActiveRegion.IndependentPrimarySpatialDimensionDistribution( uniform_xy_position_dist )
    y_position_dimension_dist = ActiveRegion.IndependentSecondarySpatialDimensionDistribution( uniform_xy_position_dist )
    z_position_dimension_dist = ActiveRegion.IndependentTertiarySpatialDimensionDistribution( uniform_z_position_dist )

    particle_distribution.setDimensionDistribution( x_position_dimension_dist )
    particle_distribution.setDimensionDistribution( y_position_dimension_dist )
    particle_distribution.setDimensionDistribution( z_position_dimension_dist )

    particle_distribution.constructDimensionDistributionDependencyTree()

    # The generic distribution will be used to generate photons
    photon_distribution = ActiveRegion.StandardPhotonSourceComponent( 0, 1.0, model, particle_distribution )

    # Assign the photon source component to the source
    source = ActiveRegion.StandardParticleSource( [photon_distribution] )

    # Set up the event handler
    event_handler = Event.EventHandler( model, simulation_properties )

    # Create the estimator response functions (flux-to-effective dose from
    # ICRP-116 table A.1, ISO values)
    flux_to_dose_dist = Distribution.TabularDistribution_LinLin( [0.01, 0.015, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.1, 0.15, 0.2, 0.3, 0.4, 0.5, 0.511, 0.6, 0.662, 0.8, 1.0, 1.117, 1.33, 1.5, 2.0, 3.0],
                                                                 [0.0288, 0.0560, 0.0812, 0.127, 0.158, 0.180, 0.199, 0.218, 0.239, 0.287, 0.429, 0.589, 0.932, 1.28, 1.63, 1.67, 1.97, 2.17, 2.62, 3.25, 3.60, 4.20, 4.66, 5.90, 8.08] )
    
    partial_response_function = ActiveRegion.EnergyParticleResponseFunction( flux_to_dose_dist )

    # convert from pSv to nSv
    response_function = partial_response_function / 1000.0

    response = ActiveRegion.StandardParticleResponse( response_function )

    source_norm = 1462129.344

    # Create the surface flux estimator
    surface_flux_estimator = Event.WeightMultipliedSurfaceFluxEstimator( 1, source_norm, [13], model )
    surface_flux_estimator.setParticleTypes( [MonteCarlo.PHOTON] )
    surface_flux_estimator.setCosineCutoffValue( 0.1 )
    surface_flux_estimator.setResponseFunctions( [response] )
    
    event_handler.addEstimator( surface_flux_estimator )

    # Create the second surface flux estimator
    if use_energy_bins:
        surface_flux_estimator_2 = Event.WeightMultipliedSurfaceFluxEstimator( 2, source_norm, [13], model )
        surface_flux_estimator_2.setEnergyDiscretization( energy_bins )
        surface_flux_estimator_2.setParticleTypes( [MonteCarlo.PHOTON] )
        surface_flux_estimator_2.setCosineCutoffValue( 0.1 )
        surface_flux_estimator_2.setResponseFunctions( [response] )

        event_handler.addEstimator( surface_flux_estimator_2 )

    # Set up the simulation manager
    factory = Manager.ParticleSimulationManagerFactory( filled_model,
                                                        source,
                                                        event_handler,
                                                        simulation_properties,
                                                        sim_name,
                                                        "xml",
                                                        threads )

    # Create the simulation manager
    manager = factory.getManager()
    manager.useSingleRendezvousFile()

    # Allow logging on all procs
    session.restoreOutputStreams()

    ## Run the simulation
    if session.size() == 1:
        manager.runInterruptibleSimulation()
    else:
        manager.runSimulation()
예제 #15
0
    parser.add_option("--sim_name",
                      type="string",
                      dest="sim_name",
                      default="sphere",
                      help="the simulation name")
    parser.add_option("--log_file",
                      type="string",
                      dest="log_file",
                      help="the file that will be used for logging")
    parser.add_option("--num_particles",
                      type="float",
                      dest="num_particles",
                      default=1e3,
                      help="the number of particles to run")
    parser.add_option("--source_energy",
                      type="float",
                      dest="source_energy",
                      default=1.0,
                      help="the source energy in MeV")
    options, args = parser.parse_args()

    if options.db_path is None:
        print "The database path must be specified!"
        sys.exit(1)

    # Run the simulation
    sphereSimulation(options.sim_name, options.db_path, options.num_particles,
                     options.source_energy,
                     Utility.doubleArrayFromString("{1e-9,100l,1.0}"),
                     options.threads, options.log_file)
예제 #16
0
    parser.add_option("--db_path",
                      type="string",
                      dest="db_path",
                      help="the database name (with extension)")
    parser.add_option("--sim_name",
                      type="string",
                      dest="sim_name",
                      default="sphere",
                      help="the simulation name")
    parser.add_option("--log_file",
                      type="string",
                      dest="log_file",
                      help="the file that will be used for logging")
    parser.add_option("--num_particles",
                      type="float",
                      dest="num_particles",
                      default=1e3,
                      help="the number of particles to run")
    options, args = parser.parse_args()

    if options.db_path is None:
        print "The database path must be specified!"
        sys.exit(1)

    # Run the simulation
    runBroomstickSimulation(
        options.sim_name, options.db_path, options.num_particles,
        MonteCarlo.DECOUPLED_HALF_PROFILE_DB_HYBRID_INCOHERENT_MODEL, 0.1,
        Utility.doubleArrayFromString("{1e-3, 988i, 0.0999, 9i, 0.1}"),
        options.threads, options.log_file)
예제 #17
0
def runSimulation(threads, histories, time):

    ##--------------------------------------------------------------------------##
    ## ------------------------------ MPI Session ----------------------------- ##
    ##--------------------------------------------------------------------------##
    session = MPI.GlobalMPISession(len(sys.argv), sys.argv)
    Utility.removeAllLogs()
    session.initializeLogs(0, True)

    if session.rank() == 0:
        print "The PyFrensie path is set to: ", pyfrensie_path

    properties = setSimulationProperties(histories, time)

    ##--------------------------------------------------------------------------##
    ## ---------------------------- GEOMETRY SETUP ---------------------------- ##
    ##--------------------------------------------------------------------------##

    # Set geometry path and type
    model_properties = DagMC.DagMCModelProperties(geometry_path)
    model_properties.useFastIdLookup()

    # Construct model
    geom_model = DagMC.DagMCModel(model_properties)

    ##--------------------------------------------------------------------------##
    ## -------------------------- EVENT HANDLER SETUP ------------------------- ##
    ##--------------------------------------------------------------------------##

    # Set event handler
    event_handler = Event.EventHandler(properties)

    # Set the energy bins
    bins = list(Utility.doubleArrayFromString("{ 1e-4, 58i, 6e-3, 99i, 1e-2}"))

    ## ------------------------ Surface Flux Estimator ------------------------ ##

    # Setup an adjoint surface flux estimator
    estimator_id = 2
    surface_ids = [1, 16, 18]
    surface_flux_estimator = Event.WeightMultipliedSurfaceFluxEstimator(
        estimator_id, 1.0, surface_ids, geom_model)

    # Set the particle type
    surface_flux_estimator.setParticleTypes([MonteCarlo.ADJOINT_ELECTRON])

    # Set the energy bins
    surface_flux_estimator.setSourceEnergyDiscretization(bins)

    # Create response function
    delta_energy = Distribution.DeltaDistribution(energy)
    particle_response_function = ActiveRegion.EnergyParticleResponseFunction(
        delta_energy)
    response_function = ActiveRegion.StandardParticleResponse(
        particle_response_function)

    # Set the response function
    surface_flux_estimator.setResponseFunctions([response_function])

    # Add the estimator to the event handler
    event_handler.addEstimator(surface_flux_estimator)

    ## -------------------------- Particle Tracker ---------------------------- ##

    # particle_tracker = Event.ParticleTracker( 0, 1000 )

    # # Add the particle tracker to the event handler
    # event_handler.addParticleTracker( particle_tracker )

    ##--------------------------------------------------------------------------##
    ## ----------------------- SIMULATION MANAGER SETUP ----------------------- ##
    ##--------------------------------------------------------------------------##

    # Initialized database
    database = Data.ScatteringCenterPropertiesDatabase(database_path)
    scattering_center_definition_database = Collision.ScatteringCenterDefinitionDatabase(
    )

    # Set element properties
    element_properties = database.getAtomProperties(atom)

    element_definition = scattering_center_definition_database.createDefinition(
        element, Data.ZAID(zaid))

    # version = 0
    if "debug" in pyfrensie_path:
        version = 1
    else:
        version = 0
    file_type = Data.AdjointElectroatomicDataProperties.Native_EPR_FILE

    element_definition.setAdjointElectroatomicDataProperties(
        element_properties.getSharedAdjointElectroatomicDataProperties(
            file_type, version))

    material_definition_database = Collision.MaterialDefinitionDatabase()
    material_definition_database.addDefinition(element, 1, (element, ),
                                               (1.0, ))

    # Fill model
    model = Collision.FilledGeometryModel(
        database_path, scattering_center_definition_database,
        material_definition_database, properties, geom_model, True)

    # Set particle distribution
    particle_distribution = ActiveRegion.StandardParticleDistribution(
        "source distribution")

    # Set the energy dimension distribution
    uniform_energy = Distribution.UniformDistribution(energy_cutoff, energy)
    energy_dimension_dist = ActiveRegion.IndependentEnergyDimensionDistribution(
        uniform_energy)
    particle_distribution.setDimensionDistribution(energy_dimension_dist)

    # Set the spatial dimension distribution
    particle_distribution.setPosition(0.0, 0.0, 0.0)

    particle_distribution.constructDimensionDistributionDependencyTree()

    # Set source components
    source_component = [
        ActiveRegion.StandardAdjointElectronSourceComponent(
            0, 1.0, model, particle_distribution)
    ]

    # Set source
    source = ActiveRegion.StandardParticleSource(source_component)

    # Set the archive type
    archive_type = "xml"

    # Set the simulation name and title
    name, title = setSimulationName(properties)

    factory = Manager.ParticleSimulationManagerFactory(model, source,
                                                       event_handler,
                                                       properties, name,
                                                       archive_type, threads)

    manager = factory.getManager()

    Utility.removeAllLogs()
    session.initializeLogs(0, False)

    manager.runSimulation()

    if session.rank() == 0:

        print "Processing the results:"
        processData(event_handler, name, title)
        print "Results will be in ", path.dirname(name)
예제 #18
0
def runSimulation(threads, histories, time):

    ##--------------------------------------------------------------------------##
    ## ------------------------------ MPI Session ----------------------------- ##
    ##--------------------------------------------------------------------------##
    session = MPI.GlobalMPISession(len(sys.argv), sys.argv)
    Utility.removeAllLogs()
    session.initializeLogs(0, True)

    if session.rank() == 0:
        print "The PyFrensie path is set to: ", pyfrensie_path

    properties = setSimulationProperties(histories, time)

    ##--------------------------------------------------------------------------##
    ## ---------------------------- GEOMETRY SETUP ---------------------------- ##
    ##--------------------------------------------------------------------------##

    # Set element zaid and name
    atom = Data.H_ATOM
    zaid = 1000
    element = "H"

    # Set geometry path and type
    model_properties = DagMC.DagMCModelProperties(geometry_path)
    model_properties.useFastIdLookup()

    # Set model
    geom_model = DagMC.DagMCModel(model_properties)

    ##--------------------------------------------------------------------------##
    ## -------------------------- EVENT HANDLER SETUP ------------------------- ##
    ##--------------------------------------------------------------------------##

    # Set event handler
    event_handler = Event.EventHandler(properties)

    # Set the energy bins
    if energy == 0.1:
        bins = list(Utility.doubleArrayFromString("{ 1e-4, 5e-4, 198i, 1e-1}"))
    elif energy == 0.01:
        bins = list(
            Utility.doubleArrayFromString("{ 1e-4, 58i, 6e-3, 99i, 1e-2}"))
    elif energy == 0.001:
        bins = list(Utility.doubleArrayFromString("{ 1e-4, 197i, 1e-3}"))
    else:
        print "ERROR: energy ", energy, " not supported!"

    ## -------------------------- Track Length Flux --------------------------- ##

    # Setup a track length flux estimator
    estimator_id = 1
    cell_ids = [1]
    track_flux_estimator = Event.WeightMultipliedCellTrackLengthFluxEstimator(
        estimator_id, 1.0, cell_ids, geom_model)

    # Set the particle type
    track_flux_estimator.setParticleTypes([MonteCarlo.ELECTRON])

    # Set the energy bins
    track_flux_estimator.setEnergyDiscretization(bins)

    # Add the estimator to the event handler
    event_handler.addEstimator(track_flux_estimator)

    ## ------------------------ Surface Flux Estimator ------------------------ ##

    # Setup a surface flux estimator
    estimator_id = 2
    surface_ids = [1]
    surface_flux_estimator = Event.WeightMultipliedSurfaceFluxEstimator(
        estimator_id, 1.0, surface_ids, geom_model)

    # Set the particle type
    surface_flux_estimator.setParticleTypes([MonteCarlo.ELECTRON])

    # Set the energy bins
    surface_flux_estimator.setEnergyDiscretization(bins)

    # Add the estimator to the event handler
    event_handler.addEstimator(surface_flux_estimator)

    ## ---------------------- Surface Current Estimator ----------------------- ##

    # Setup a surface current estimator
    estimator_id = 3
    surface_ids = [1]
    surface_current_estimator = Event.WeightMultipliedSurfaceCurrentEstimator(
        estimator_id, 1.0, surface_ids)

    # Set the particle type
    surface_current_estimator.setParticleTypes([MonteCarlo.ELECTRON])

    # Set the energy bins
    surface_current_estimator.setEnergyDiscretization(bins)

    # Add the estimator to the event handler
    event_handler.addEstimator(surface_current_estimator)

    ##--------------------------------------------------------------------------##
    ## ----------------------- SIMULATION MANAGER SETUP ----------------------- ##
    ##--------------------------------------------------------------------------##

    # Initialized database
    database = Data.ScatteringCenterPropertiesDatabase(database_path)
    scattering_center_definition_database = Collision.ScatteringCenterDefinitionDatabase(
    )

    # Set element properties
    element_properties = database.getAtomProperties(atom)

    element_definition = scattering_center_definition_database.createDefinition(
        element, Data.ZAID(zaid))

    version = 0
    if file_type == Data.ElectroatomicDataProperties.ACE_EPR_FILE:
        version = 14

    element_definition.setElectroatomicDataProperties(
        element_properties.getSharedElectroatomicDataProperties(
            file_type, version))

    material_definition_database = Collision.MaterialDefinitionDatabase()
    material_definition_database.addDefinition(element, 1, (element, ),
                                               (1.0, ))

    # Fill model
    model = Collision.FilledGeometryModel(
        database_path, scattering_center_definition_database,
        material_definition_database, properties, geom_model, True)

    # Set particle distribution
    particle_distribution = ActiveRegion.StandardParticleDistribution(
        "source distribution")

    # Set the energy dimension distribution
    delta_energy = Distribution.DeltaDistribution(energy)
    energy_dimension_dist = ActiveRegion.IndependentEnergyDimensionDistribution(
        delta_energy)
    particle_distribution.setDimensionDistribution(energy_dimension_dist)

    # Set the spatial dimension distribution
    particle_distribution.setPosition(0.0, 0.0, 0.0)

    particle_distribution.constructDimensionDistributionDependencyTree()

    # Set source components
    source_component = [
        ActiveRegion.StandardElectronSourceComponent(0, 1.0, geom_model,
                                                     particle_distribution)
    ]

    # Set source
    source = ActiveRegion.StandardParticleSource(source_component)

    # Set the archive type
    archive_type = "xml"

    name, title = setSimulationName(properties)

    factory = Manager.ParticleSimulationManagerFactory(model, source,
                                                       event_handler,
                                                       properties, name,
                                                       archive_type, threads)

    manager = factory.getManager()

    Utility.removeAllLogs()
    session.initializeLogs(0, False)

    manager.runSimulation()

    if session.rank() == 0:

        print "Processing the results:"
        processData(event_handler, name, title)

        print "Results will be in ", path.dirname(name)
예제 #19
0
def runSimulation(threads, histories, time):

    ##--------------------------------------------------------------------------##
    ## ------------------------------ MPI Session ----------------------------- ##
    ##--------------------------------------------------------------------------##
    session = MPI.GlobalMPISession(len(sys.argv), sys.argv)
    Utility.removeAllLogs()
    session.initializeLogs(0, True)

    if session.rank() == 0:
        print "The PyFrensie path is set to: ", pyfrensie_path

    properties = setSimulationProperties(histories, time)

    ##--------------------------------------------------------------------------##
    ## ---------------------------- GEOMETRY SETUP ---------------------------- ##
    ##--------------------------------------------------------------------------##

    # Set geometry path and type
    model_properties = DagMC.DagMCModelProperties(geometry_path)
    model_properties.useFastIdLookup()

    # Construct model
    geom_model = DagMC.DagMCModel(model_properties)

    ##--------------------------------------------------------------------------##
    ## -------------------------- EVENT HANDLER SETUP ------------------------- ##
    ##--------------------------------------------------------------------------##

    # Set event handler
    event_handler = Event.EventHandler(properties)

    ## -------------------- Energy Deposition Calorimeter --------------------- ##

    # Setup a cell pulse height estimator
    estimator_id = 1
    cell_ids = [2]
    energy_deposition_estimator = Event.WeightAndEnergyMultipliedCellPulseHeightEstimator(
        estimator_id, 1.0, cell_ids)

    # Add the estimator to the event handler
    event_handler.addEstimator(energy_deposition_estimator)

    ##--------------------------------------------------------------------------##
    ## ----------------------- SIMULATION MANAGER SETUP ----------------------- ##
    ##--------------------------------------------------------------------------##

    # Initialized database
    database = Data.ScatteringCenterPropertiesDatabase(database_path)
    scattering_center_definition_database = Collision.ScatteringCenterDefinitionDatabase(
    )

    # Set element properties
    element_properties = database.getAtomProperties(atom)

    element_definition = scattering_center_definition_database.createDefinition(
        element, Data.ZAID(zaid))

    version = 0
    if file_type == Data.ElectroatomicDataProperties.ACE_EPR_FILE:
        version = 14

    element_definition.setElectroatomicDataProperties(
        element_properties.getSharedElectroatomicDataProperties(
            file_type, version))

    material_definition_database = Collision.MaterialDefinitionDatabase()
    material_definition_database.addDefinition(element, 1, (element, ),
                                               (1.0, ))

    # Fill model
    model = Collision.FilledGeometryModel(
        database_path, scattering_center_definition_database,
        material_definition_database, properties, geom_model, True)

    # Set particle distribution
    particle_distribution = ActiveRegion.StandardParticleDistribution(
        "source distribution")

    # Set the energy dimension distribution
    delta_energy = Distribution.DeltaDistribution(energy)
    energy_dimension_dist = ActiveRegion.IndependentEnergyDimensionDistribution(
        delta_energy)
    particle_distribution.setDimensionDistribution(energy_dimension_dist)

    # Set the direction dimension distribution
    particle_distribution.setDirection(0.0, 0.0, 1.0)

    # Set the spatial dimension distribution
    particle_distribution.setPosition(0.0, 0.0, 0.0)

    particle_distribution.constructDimensionDistributionDependencyTree()

    # Set source components
    source_component = [
        ActiveRegion.StandardElectronSourceComponent(0, 1.0, geom_model,
                                                     particle_distribution)
    ]

    # Set source
    source = ActiveRegion.StandardParticleSource(source_component)

    # Set the archive type
    archive_type = "xml"

    # Set the simulation name and title
    name, title = setSimulationName(properties)

    factory = Manager.ParticleSimulationManagerFactory(model, source,
                                                       event_handler,
                                                       properties, name,
                                                       archive_type, threads)

    manager = factory.getManager()

    Utility.removeAllLogs()
    session.initializeLogs(0, False)

    manager.runSimulation()

    if session.rank() == 0:

        print "Processing the results:"
        processData(energy_deposition_estimator, name, title, test_range,
                    calorimeter_thickness)

        print "Results will be in ", path.dirname(name)
예제 #20
0
energy_bins = [0, 0.5, 1]

# thread is of type "int"
threads = int(4)

# not sure if we need
log_file = None

##---------------------------------------------------------------------------##
## Initialize the MPI Session
##---------------------------------------------------------------------------##

session = MPI.GlobalMPISession(len(sys.argv), sys.argv)

# Suppress logging on all procs except for the master (proc=0)
Utility.removeAllLogs()
session.initializeLogs(0, True)

if not log_file is None:
    session.initializeLogs(log_file, 0, True)

##---------------------------------------------------------------------------##
## Set the simulation properties
##---------------------------------------------------------------------------##

simulation_properties = MonteCarlo.SimulationProperties()

# Simulate neutrons only
simulation_properties.setParticleMode(MonteCarlo.NEUTRON_MODE)
simulation_properties.setUnresolvedResonanceProbabilityTableModeOff()
simulation_properties.setNumberOfNeutronHashGridBins(100)
예제 #21
0
    1.238122,
    1.280976,
    1.377669,
    1.401515,
    1.407988,
    1.50921,
    1.661274,
    1.729595,
    1.764491,
    1.847429,
    2.118514,
    2.204059,
    2.44770
]

energy_bins = list(Utility.doubleArrayFromString("{1e-3, 998i, 2.44770}"))

gamma_line_indices = set()

# Loop through each gamma line and determine the bin that it falls in
for i in range(0, len(gamma_lines)):
    gamma_energy = gamma_lines[i]

    for j in range(0, len(energy_bins) - 1):
        if gamma_energy > energy_bins[j] and gamma_energy <= energy_bins[j +
                                                                         1]:
            #print name, "in bin", j, "->", gamma_energy, energy_bins[j], energy_bins[j+1]
            index = 0

            if j in gamma_line_indices:
                print "Error: x-ray line energy bin width too large!"
예제 #22
0
def plotContSoilSimulationSpectrum(rendezvous_file,
                                   estimator_id,
                                   entity_id,
                                   mcnp_file,
                                   mcnp_file_start,
                                   mcnp_file_end,
                                   is_a_current,
                                   is_forward,
                                   col_bin=None,
                                   top_ylims=None,
                                   bottom_ylims=None,
                                   xlims=None,
                                   legend_pos=None):

    # Activate just-in-time initialization to prevent automatic loading of the
    # geometry and data tables
    Utility.activateJustInTimeInitialization()

    # Set the database path
    Collision.FilledGeometryModel.setDefaultDatabasePath(
        os.environ['DATABASE_PATH'])

    # Reload the simulation
    manager = Manager.ParticleSimulationManagerFactory(
        rendezvous_file).getManager()

    # Print the leakage current
    # estimator = manager.getEventHandler().getEstimator( 2 )
    # print estimator.getEntityTotalProcessedData( 20 )
    # print estimator.getEntityTotalProcessedData( 21 )
    # print estimator.getEntityTotalProcessedData( 22 )
    # print estimator.getEntityTotalProcessedData( 23 )
    # print estimator.getEntityTotalProcessedData( 24 )
    # print estimator.getEntityTotalProcessedData( 25 )

    # Extract the estimator of interest
    estimator = manager.getEventHandler().getEstimator(estimator_id)

    full_entity_bin_data = estimator.getEntityBinProcessedData(entity_id)

    num_energy_bins = 0

    if is_forward:
        num_energy_bins = estimator.getNumberOfBins(
            Event.OBSERVER_ENERGY_DIMENSION)
    else:
        num_energy_bins = estimator.getNumberOfBins(
            Event.OBSERVER_SOURCE_ENERGY_DIMENSION)

    start_index = 0
    end_index = num_energy_bins

    if not col_bin is None:
        num_col_bins = estimator.getNumberOfBins(
            Event.OBSERVER_COLLISION_NUMBER_DIMENSION)

        if col_bin >= num_col_bins:
            print "There are only", num_col_bins, "collision number bins!"
            sys.exit(1)

        start_index = col_bin * num_energy_bins
        end_index = start_index + num_energy_bins

    entity_bin_data = {
        "mean": [],
        "re": [],
        "e_bins": [],
        "vov": [],
        "fom": []
    }

    for i in range(start_index, end_index):
        entity_bin_data["mean"].append(full_entity_bin_data["mean"][i])
        entity_bin_data["re"].append(full_entity_bin_data["re"][i])
        #entity_bin_data["vov"].append( full_entity_bin_data["vov"][i] )
        entity_bin_data["fom"].append(full_entity_bin_data["fom"][i])

    if is_forward:
        entity_bin_data["e_bins"] = list(estimator.getEnergyDiscretization())
    else:
        entity_bin_data["e_bins"] = list(
            estimator.getSourceEnergyDiscretization())

    # Extract the mcnp data from the output file
    mcnp_file = open(mcnp_file, "r")
    mcnp_file_lines = mcnp_file.readlines()

    mcnp_bin_data = {"e_up": [], "mean": [], "re": []}

    mcnp_first_nonzero_index = 0
    first_nonzero_value_found = False

    for i in range(mcnp_file_start, mcnp_file_end + 1):
        split_line = mcnp_file_lines[i - 1].split()

        mean_value = float(split_line[1])

        mcnp_bin_data["e_up"].append(float(split_line[0]))
        mcnp_bin_data["mean"].append(mean_value)
        mcnp_bin_data["re"].append(float(split_line[2]))

    for i in range(0, len(mcnp_bin_data["e_up"])):
        print i, mcnp_bin_data["e_up"][i], entity_bin_data["e_bins"][
            i + 1], mcnp_bin_data["mean"][i], entity_bin_data["mean"][
                i], entity_bin_data["re"][i]
        #print i, entity_bin_data["e_bins"][i], entity_bin_data["e_bins"][i+1], entity_bin_data["mean"][i], entity_bin_data["re"][i], entity_bin_data["vov"][i], entity_bin_data["fom"][i]

    output_file_name = "h_infinite_medium_"
    output_file_names = []

    if is_a_current:
        output_file_names.append(output_file_name + "current.eps")
        output_file_names.append(output_file_name + "current.png")
        data_type = "Current"
    else:
        output_file_names.append(output_file_name + "flux.eps")
        output_file_names.append(output_file_name + "flux.png")
        data_type = "Flux"

    # Plot the data
    plotSpectralDataWithErrors("FRENSIE",
                               entity_bin_data,
                               "MCNP6",
                               mcnp_bin_data,
                               data_type,
                               log_spacing=False,
                               per_lethargy=False,
                               top_ylims=top_ylims,
                               bottom_ylims=bottom_ylims,
                               xlims=xlims,
                               legend_pos=legend_pos,
                               output_plot_names=output_file_names)
예제 #23
0
def sphereSimulation(sim_name,
                     db_path,
                     num_particles,
                     source_energy,
                     energy_bins,
                     threads,
                     log_file=None):
    ##---------------------------------------------------------------------------##
    ## Initialize the MPI Session
    ##---------------------------------------------------------------------------##

    session = MPI.GlobalMPISession(len(sys.argv), sys.argv)

    # Suppress logging on all procs except for the master (proc=0)
    Utility.removeAllLogs()
    session.initializeLogs(0, True)

    if not log_file is None:
        session.initializeLogs(log_file, 0, True)

##---------------------------------------------------------------------------##
## Set the simulation properties
##---------------------------------------------------------------------------##

    simulation_properties = MonteCarlo.SimulationProperties()

    # Simulate neutrons only
    simulation_properties.setParticleMode(MonteCarlo.NEUTRON_MODE)
    simulation_properties.setUnresolvedResonanceProbabilityTableModeOff()
    simulation_properties.setNumberOfNeutronHashGridBins(100)

    # Set the number of histories to run and the number of rendezvous
    simulation_properties.setNumberOfHistories(num_particles)
    simulation_properties.setMinNumberOfRendezvous(10)

    ##---------------------------------------------------------------------------##
    ## Set up the materials
    ##---------------------------------------------------------------------------##

    # Load the database
    database = Data.ScatteringCenterPropertiesDatabase(db_path)

    # Set the definition of H1 for this simulation
    scattering_center_definitions = Collision.ScatteringCenterDefinitionDatabase(
    )

    # Extract the properties for H1 from the database
    nuclide_properties = database.getNuclideProperties(Data.ZAID(82204))
    nuclide_definition = scattering_center_definitions.createDefinition(
        "Pb204", Data.ZAID(82204))
    nuclide_definition.setNuclearDataProperties(
        nuclide_properties.getSharedNuclearDataProperties(
            Data.NuclearDataProperties.ACE_FILE, 8, 293.6, False))

    nuclide_properties = database.getNuclideProperties(Data.ZAID(82206))
    nuclide_definition = scattering_center_definitions.createDefinition(
        "Pb206", Data.ZAID(82206))
    nuclide_definition.setNuclearDataProperties(
        nuclide_properties.getSharedNuclearDataProperties(
            Data.NuclearDataProperties.ACE_FILE, 8, 293.6, False))

    nuclide_properties = database.getNuclideProperties(Data.ZAID(82207))
    nuclide_definition = scattering_center_definitions.createDefinition(
        "Pb207", Data.ZAID(82207))
    nuclide_definition.setNuclearDataProperties(
        nuclide_properties.getSharedNuclearDataProperties(
            Data.NuclearDataProperties.ACE_FILE, 8, 293.6, False))

    nuclide_properties = database.getNuclideProperties(Data.ZAID(82208))
    nuclide_definition = scattering_center_definitions.createDefinition(
        "Pb208", Data.ZAID(82208))
    nuclide_definition.setNuclearDataProperties(
        nuclide_properties.getSharedNuclearDataProperties(
            Data.NuclearDataProperties.ACE_FILE, 8, 293.6, False))

    material_definitions = Collision.MaterialDefinitionDatabase()
    material_definitions.addDefinition("Pb_nat", 1,
                                       ["Pb204", "Pb206", "Pb207", "Pb208"],
                                       [0.014, 0.241, 0.221, 0.524])

    ##---------------------------------------------------------------------------##
    ## Set up the geometry
    ##---------------------------------------------------------------------------##

    # Set the model properties before loading the model
    model_properties = DagMC.DagMCModelProperties("sphere.h5m")
    model_properties.setMaterialPropertyName("mat")
    model_properties.setDensityPropertyName("rho")
    model_properties.setTerminationCellPropertyName("termination.cell")
    model_properties.setSurfaceFluxName("surface.flux")
    model_properties.setSurfaceCurrentName("surface.current")
    model_properties.useFastIdLookup()

    # Load the model
    model = DagMC.DagMCModel(model_properties)

    # Fill the model with the defined materials
    filled_model = Collision.FilledGeometryModel(
        db_path, scattering_center_definitions, material_definitions,
        simulation_properties, model, True)

    ##---------------------------------------------------------------------------##
    ## Set up the source
    ##---------------------------------------------------------------------------##

    # Define the generic particle distribution
    particle_distribution = ActiveRegion.StandardParticleDistribution(
        "source distribution")

    particle_distribution.setEnergy(source_energy)
    particle_distribution.setPosition(0.0, 0.0, 0.0)
    particle_distribution.constructDimensionDistributionDependencyTree()

    # The generic distribution will be used to generate neutrons
    neutron_distribution = ActiveRegion.StandardNeutronSourceComponent(
        0, 1.0, model, particle_distribution)

    # Assign the neutron source component to the source
    source = ActiveRegion.StandardParticleSource([neutron_distribution])

    ##---------------------------------------------------------------------------##
    ## Set up the event handler
    ##---------------------------------------------------------------------------##

    # The model must be passed to the event handler so that the estimators
    # defined in the model can be constructed
    event_handler = Event.EventHandler(model, simulation_properties)

    # Set the energy and collision number bins in estimator 1
    event_handler.getEstimator(1).setEnergyDiscretization(energy_bins)

    # Set the energy and collision number bins in estimator 2
    event_handler.getEstimator(2).setEnergyDiscretization(energy_bins)

    ##---------------------------------------------------------------------------##
    ## Set up the simulation manager
    ##---------------------------------------------------------------------------##

    # The factory will use the simulation properties and the MPI session
    # properties to determine the appropriate simulation manager to construct
    factory = Manager.ParticleSimulationManagerFactory(filled_model, source,
                                                       event_handler,
                                                       simulation_properties,
                                                       sim_name, "xml",
                                                       threads)

    # Create the simulation manager
    manager = factory.getManager()

    # Allow logging on all procs
    session.restoreOutputStreams()

    ##---------------------------------------------------------------------------##
    ## Run the simulation
    ##---------------------------------------------------------------------------##

    if session.size() == 1:
        manager.runInterruptibleSimulation()
    else:
        manager.runSimulation()
def extractEstimatorRelaxData(rendezvous_file, estimator_id, entity_id,
                              mcnp_file, mcnp_file_start, mcnp_file_end,
                              relax_bins):

    # Activate just-in-time initialization to prevent automatic loading of the
    # geometry and data tables
    Utility.activateJustInTimeInitialization()

    # Set the database path
    Collision.FilledGeometryModel.setDefaultDatabasePath(
        os.environ['DATABASE_PATH'])

    # Reload the simulation
    manager = Manager.ParticleSimulationManagerFactory(
        rendezvous_file).getManager()

    # Extract the estimator of interest
    estimator = manager.getEventHandler().getEstimator(estimator_id)

    energy_bins = list(estimator.getEnergyDiscretization())

    # Extract the estimator data
    entity_bin_data = estimator.getEntityBinProcessedData(entity_id)

    # Only take the data at the second collision number bin
    start_index = estimator.getNumberOfBins(Event.OBSERVER_ENERGY_DIMENSION)
    end_index = 2 * start_index

    entity_bin_data["mean"] = entity_bin_data["mean"][start_index:end_index]
    entity_bin_data["re"] = entity_bin_data["re"][start_index:end_index]
    entity_bin_data["vov"] = entity_bin_data["vov"][start_index:end_index]
    entity_bin_data["fom"] = entity_bin_data["fom"][start_index:end_index]

    # Open the mcnp output file
    mcnp_file = open(mcnp_file, "r")
    mcnp_file_lines = mcnp_file.readlines()
    mcnp_file_lines = mcnp_file_lines[mcnp_file_start - 1:mcnp_file_end]

    # Extract and print the data
    print "#bin start (MeV), bin end (MeV), bin mid (MeV), FRENSIE mean/(bin width), MCNP mean/(bin width), F/M, F/M unc"

    for i in range(0, len(energy_bins) - 1):
        if i in relax_bins:
            mcnp_line = mcnp_file_lines[i].split()

            bin_width = energy_bins[i + 1] - energy_bins[i]
            frensie_mean = entity_bin_data["mean"][i] / bin_width
            mcnp_mean = float(mcnp_line[1]) / bin_width
            f_over_m = frensie_mean / mcnp_mean

            sigma_f = frensie_mean * entity_bin_data["re"][i]
            sigma_m = mcnp_mean * float(mcnp_line[2])

            f_squared = frensie_mean * frensie_mean
            m_squared = mcnp_mean * mcnp_mean

            f_over_m_unc = m.sqrt(sigma_f * sigma_f + (f_squared / m_squared) *
                                  sigma_m * sigma_m) / mcnp_mean

            print energy_bins[i], energy_bins[
                i + 1], (energy_bins[i] + energy_bins[i + 1]
                         ) / 2, frensie_mean, mcnp_mean, f_over_m, f_over_m_unc
예제 #25
0
    "KO4": 8.82612e-2,
    "KO5": 8.8264e-2,
    "KP2": 8.8283e-2,
    "KP3": 8.82847e-2
}

sorted_x_ray_line_names = [
    "KL2", "KL3", "KM2", "KM3", "KM4", "KM5", "KN2", "KN3", "KN4", "KN5",
    "KO2", "KO3", "KO4", "KO5", "KP2", "KP3"
]

#energy_bins = list(Utility.doubleArrayFromString( "{1e-3, 499i, 0.1}" ))
#energy_bins = list(Utility.doubleArrayFromString( "{1e-3, 499i, 0.2}" ))
#energy_bins = list(Utility.doubleArrayFromString( "{1e-3, 499i, 0.5}" ))
#energy_bins = list(Utility.doubleArrayFromString( "{1e-3, 499i, 1.0}" ))
energy_bins = list(Utility.doubleArrayFromString("{1e-3, 499i, 10.0}"))

x_ray_line_indices = set()

# Loop through each x-ray line and determine the bin that it falls in
for i in range(0, len(sorted_x_ray_line_names)):
    name = sorted_x_ray_line_names[i]
    x_ray_energy = x_ray_lines[name]

    for j in range(0, len(energy_bins) - 1):
        if x_ray_energy > energy_bins[j] and x_ray_energy <= energy_bins[j +
                                                                         1]:
            #print name, "in bin", j, "->", x_ray_energy, energy_bins[j], energy_bins[j+1]
            index = 0

            if j in x_ray_line_indices:
예제 #26
0
#! /usr/bin/env python
import PyFrensie.Data.Native as Native
import PyFrensie.Utility as Utility
import PyFrensie.Utility.Prng as Prng
import PyFrensie.Utility.Interpolation as Interpolation
import PyFrensie.MonteCarlo.Collision as Collision
import PyTrilinos.Teuchos as Teuchos
import numpy
import matplotlib.pyplot as plt

Utility.initFrensiePrng()

datadir = '/home/software/mcnpdata/'
datadir = '/home/lkersting/frensie/src/packages/test_files/'
#datadir = '/home/lkersting/research/frensie-repos/lkersting/src/packages/test_files/'

source = Teuchos.FileInputSource(datadir + '/cross_sections.xml')
xml_obj = source.getObject()
cs_list = Teuchos.XMLParameterListReader().toParameterList(xml_obj)

h_data_list = cs_list.get('Al-Native')
pb_data_list = cs_list.get('Pb-Native')
h_adjoint_file_name = datadir + h_data_list.get(
    'adjoint_electroatomic_file_path')
h_native_file_name = datadir + h_data_list.get('electroatomic_file_path')
pb_native_file_name = datadir + pb_data_list.get('electroatomic_file_path')

h_native_data = Native.ElectronPhotonRelaxationDataContainer(
    h_native_file_name)
h_adjoint_data = Native.AdjointElectronPhotonRelaxationDataContainer(
    h_adjoint_file_name)
예제 #27
0
def runBroomstickSimulation(sim_name,
                            db_path,
                            num_particles,
                            incoherent_model_type,
                            source_energy,
                            energy_bins,
                            threads,
                            log_file=None):

    ## Initialize the MPI session
    session = MPI.GlobalMPISession(len(sys.argv), sys.argv)

    # Suppress logging on all procs except for the master (proc=0)
    Utility.removeAllLogs()
    session.initializeLogs(0, True)

    if not log_file is None:
        session.initializeLogs(log_file, 0, True)

    ## Set the simulation properties
    simulation_properties = MonteCarlo.SimulationProperties()

    # Simulate photons only
    simulation_properties.setParticleMode(MonteCarlo.PHOTON_MODE)
    simulation_properties.setIncoherentModelType(incoherent_model_type)
    simulation_properties.setNumberOfPhotonHashGridBins(100)

    # Set the number of histories to run and the number of rendezvous
    simulation_properties.setNumberOfHistories(num_particles)
    simulation_properties.setMinNumberOfRendezvous(100)
    simulation_properties.setNumberOfSnapshotsPerBatch(1)

    ## Set up the materials
    database = Data.ScatteringCenterPropertiesDatabase(db_path)

    # Extract the properties for H from the database
    atom_properties = database.getAtomProperties(Data.ZAID(82000))

    # Set the definition for H for this simulation
    scattering_center_definitions = Collision.ScatteringCenterDefinitionDatabase(
    )
    atom_definition = scattering_center_definitions.createDefinition(
        "Pb", Data.ZAID(82000))

    if incoherent_model_type == MonteCarlo.IMPULSE_INCOHERENT_MODEL or incoherent_model_type == MonteCarlo.FULL_PROFILE_DB_IMPULSE_INCOHERENT_MODEL:
        atom_definition.setPhotoatomicDataProperties(
            atom_properties.getSharedPhotoatomicDataProperties(
                Data.PhotoatomicDataProperties.Native_EPR_FILE, 0))
    else:
        atom_definition.setPhotoatomicDataProperties(
            atom_properties.getSharedPhotoatomicDataProperties(
                Data.PhotoatomicDataProperties.ACE_EPR_FILE, 12))

    # Set the definition for material 1
    material_definitions = Collision.MaterialDefinitionDatabase()
    material_definitions.addDefinition("Pb", 1, ["Pb"], [1.0])

    ## Set up the geometry
    model_properties = DagMC.DagMCModelProperties("broomstick.h5m")
    model_properties.setMaterialPropertyName("mat")
    model_properties.setDensityPropertyName("rho")
    model_properties.setTerminationCellPropertyName("termination.cell")
    model_properties.setSurfaceFluxName("surface.flux")
    model_properties.setSurfaceCurrentName("surface.current")
    model_properties.useFastIdLookup()

    # Load the model
    model = DagMC.DagMCModel(model_properties)

    # Fill the model with the defined material
    filled_model = Collision.FilledGeometryModel(
        db_path, scattering_center_definitions, material_definitions,
        simulation_properties, model, True)

    ## Set up the source
    particle_distribution = ActiveRegion.StandardParticleDistribution(
        "mono-directional mono-energetic dist")

    particle_distribution.setEnergy(source_energy)
    particle_distribution.setPosition(0.0, 0.0, -500.1)
    particle_distribution.setDirection(0.0, 0.0, 1.0)
    particle_distribution.constructDimensionDistributionDependencyTree()

    # The generic distribution will be used to generate photons
    photon_distribution = ActiveRegion.StandardPhotonSourceComponent(
        0, 1.0, model, particle_distribution)

    # Assign the photon source component to the source
    source = ActiveRegion.StandardParticleSource([photon_distribution])

    ## Set up the event handler
    event_handler = Event.EventHandler(model, simulation_properties)

    # Set the energy and collision number bins in estimator 1
    event_handler.getEstimator(1).setEnergyDiscretization(energy_bins)
    event_handler.getEstimator(1).setCollisionNumberDiscretization([0, 1, 10])

    # Set the energy and collision number bins in estimator 2
    event_handler.getEstimator(2).setEnergyDiscretization(energy_bins)
    event_handler.getEstimator(2).setCollisionNumberDiscretization([0, 1, 10])

    ## Set up the simulation manager
    factory = Manager.ParticleSimulationManagerFactory(filled_model, source,
                                                       event_handler,
                                                       simulation_properties,
                                                       sim_name, "xml",
                                                       threads)

    # Create the simulation manager
    manager = factory.getManager()
    manager.useSingleRendezvousFile()

    # Allow logging on all procs
    session.restoreOutputStreams()

    ## Run the simulation
    if session.size() == 1:
        manager.runInterruptibleSimulation()
    else:
        manager.runSimulation()
예제 #28
0
    
    # Parse the command line options
    parser = OptionParser()
    parser.add_option("--threads", type="int", dest="threads", default=1,
                      help="the number of threads to use")
    parser.add_option("--db_path", type="string", dest="db_path",
                      help="the database name (with extension)")
    parser.add_option("--sim_name", type="string", dest="sim_name", default="sphere",
                      help="the simulation name")
    parser.add_option("--log_file", type="string", dest="log_file",
                      help="the file that will be used for logging")
    parser.add_option("--num_particles", type="float", dest="num_particles", default=1e3,
                      help="the number of particles to run")
    options,args = parser.parse_args()

    if options.db_path is None:
        print "The database path must be specified!"
        sys.exit(1)

    # Run the simulation
    runBroomstickSimulation( options.sim_name,
                             options.db_path,
                             options.num_particles,
                             MonteCarlo.IMPULSE_INCOHERENT_MODEL,
                             1.0,
                             Utility.doubleArrayFromString( "{1e-3, 998i, 1.0}" ),
                             options.threads,
                             options.log_file )
    
    
예제 #29
0
def runSimulation(threads, histories, time):

    ##--------------------------------------------------------------------------##
    ## ------------------------------ MPI Session ----------------------------- ##
    ##--------------------------------------------------------------------------##
    session = MPI.GlobalMPISession(len(sys.argv), sys.argv)
    Utility.removeAllLogs()
    session.initializeLogs(0, True)

    if session.rank() == 0:
        print "The PyFrensie path is set to: ", pyfrensie_path

    properties = setSimulationProperties(histories, time)

    ##--------------------------------------------------------------------------##
    ## ---------------------------- GEOMETRY SETUP ---------------------------- ##
    ##--------------------------------------------------------------------------##

    # Set geometry path and type
    model_properties = DagMC.DagMCModelProperties(geometry_path)
    model_properties.useFastIdLookup()

    # Construct model
    geom_model = DagMC.DagMCModel(model_properties)

    ##--------------------------------------------------------------------------##
    ## -------------------------- EVENT HANDLER SETUP ------------------------- ##
    ##--------------------------------------------------------------------------##

    # Set event handler
    event_handler = Event.EventHandler(properties)

    ## -------------------- Energy Deposition Calorimeter --------------------- ##

    number_of_subzones = 50

    # Setup a cell pulse height estimator
    estimator_id = 1
    cell_ids = range(1, number_of_subzones + 1)
    energy_deposition_estimator = Event.WeightAndEnergyMultipliedCellPulseHeightEstimator(
        estimator_id, 1.0, cell_ids)

    # Add the estimator to the event handler
    event_handler.addEstimator(energy_deposition_estimator)

    ##--------------------------------------------------------------------------##
    ## ----------------------- SIMULATION MANAGER SETUP ----------------------- ##
    ##--------------------------------------------------------------------------##

    # Initialized database
    database = Data.ScatteringCenterPropertiesDatabase(database_path)
    scattering_center_definition_database = Collision.ScatteringCenterDefinitionDatabase(
    )

    # Set material properties
    version = 0
    if file_type == Data.ElectroatomicDataProperties.ACE_EPR_FILE:
        version = 14

    # Definition for Aluminum
    if material == "Al":
        al_properties = database.getAtomProperties(Data.Al_ATOM)

        al_definition = scattering_center_definition_database.createDefinition(
            material, Data.ZAID(13000))

        al_definition.setElectroatomicDataProperties(
            al_properties.getSharedElectroatomicDataProperties(
                file_type, version))

        definition = (("Al", 1.0), )

    else:
        h_properties = database.getAtomProperties(Data.H_ATOM)

        h_definition = scattering_center_definition_database.createDefinition(
            "H", Data.ZAID(1000))

        h_definition.setElectroatomicDataProperties(
            h_properties.getSharedElectroatomicDataProperties(
                file_type, version))

        c_properties = database.getAtomProperties(Data.C_ATOM)

        c_definition = scattering_center_definition_database.createDefinition(
            "C", Data.ZAID(6000))

        c_definition.setElectroatomicDataProperties(
            c_properties.getSharedElectroatomicDataProperties(
                file_type, version))

        # Definition for polystyrene
        if material == "polystyrene":
            definition = (("H", -0.077418), ("C", -0.922582))

        # Definition for polyethylene
        elif material == "polyethylene":
            definition = (("H", -0.14), ("C", -0.86))

        else:
            print "ERROR: material ", material, " is currently not supported!"

    material_definition_database = Collision.MaterialDefinitionDatabase()
    material_definition_database.addDefinition(material, 1, definition)

    # Fill model
    model = Collision.FilledGeometryModel(
        database_path, scattering_center_definition_database,
        material_definition_database, properties, geom_model, True)

    # Set particle distribution
    particle_distribution = ActiveRegion.StandardParticleDistribution(
        "source distribution")

    # Set the energy dimension distribution
    delta_energy = Distribution.DeltaDistribution(energy)
    energy_dimension_dist = ActiveRegion.IndependentEnergyDimensionDistribution(
        delta_energy)
    particle_distribution.setDimensionDistribution(energy_dimension_dist)

    # Set the direction dimension distribution
    particle_distribution.setDirection(0.0, 0.0, 1.0)

    # Set the spatial dimension distribution
    particle_distribution.setPosition(0.0, 0.0, -0.01)

    particle_distribution.constructDimensionDistributionDependencyTree()

    # Set source components
    source_component = [
        ActiveRegion.StandardElectronSourceComponent(0, 1.0, geom_model,
                                                     particle_distribution)
    ]

    # Set source
    source = ActiveRegion.StandardParticleSource(source_component)

    # Set the archive type
    archive_type = "xml"

    # Set the simulation name and title
    name, title = setSimulationName(properties)

    factory = Manager.ParticleSimulationManagerFactory(model, source,
                                                       event_handler,
                                                       properties, name,
                                                       archive_type, threads)

    manager = factory.getManager()

    Utility.removeAllLogs()
    session.initializeLogs(0, False)

    manager.runSimulation()

    if session.rank() == 0:

        print "Processing the results:"
        processData(energy_deposition_estimator, name, title,
                    subzone_width * density)

        print "Results will be in ", path.dirname(name)