Requested updates to source

Rename sample_source -> sample.
Use std::string as type of argument to openmc_create_source.
Use reinterpret_cast when accessing dlsym.
Also moves check for dlerror to be before the attempt to create the
source (avoids null reference if fails) and capture error message
before dlclose, so that the error message is still available.
Formatting updates and some refactoring for examples and tests.
This commit is contained in:
Dan Short 2020-08-28 09:49:36 +01:00
parent 9435020197
commit 21e8d91e90
6 changed files with 40 additions and 49 deletions

View file

@ -8,25 +8,12 @@
class Source : public openmc::CustomSource
{
protected:
double radius_;
double energy_;
// Protect the constructor as we only want the class to be created by the from_string method.
Source(double radius, double energy)
{
radius_ = radius;
energy_ = energy;
}
public:
// Getters for the values that we want to use in sampling.
double radius() { return radius_; }
double energy() { return energy_; }
Source(double radius, double energy) : radius_(radius), energy_(energy) { }
// Defines a function that can create a unique pointer to a new instance of this class
// by extracting the parameters from the provided string.
static std::unique_ptr<Source> from_string(const char* parameters)
static std::unique_ptr<Source> from_string(std::string parameters)
{
std::unordered_map<std::string, std::string> parameter_mapping;
@ -39,13 +26,13 @@ class Source : public openmc::CustomSource
parameter_mapping[key] = value;
}
return std::unique_ptr<Source> (
new Source(std::stod(parameter_mapping["radius"]), std::stod(parameter_mapping["energy"]))
);
double radius = std::stod(parameter_mapping["radius"]);
double energy = std::stod(parameter_mapping["energy"]);
return std::make_unique<Source>(radius, energy);
}
// Samples from an instance of this class.
openmc::Particle::Bank sample_source(uint64_t* seed)
openmc::Particle::Bank sample(uint64_t* seed)
{
openmc::Particle::Bank particle;
// wgt
@ -53,23 +40,27 @@ class Source : public openmc::CustomSource
particle.wgt = 1.0;
// position
double angle = 2.0 * M_PI * openmc::prn(seed);
double radius = this->radius();
double radius = this->radius_;
particle.r.x = radius * std::cos(angle);
particle.r.y = radius * std::sin(angle);
particle.r.z = 0.0;
// angle
particle.u = {1.0, 0.0, 0.0};
particle.E = this->energy();
particle.E = this->energy_;
particle.delayed_group = 0;
return particle;
}
private:
double radius_;
double energy_;
};
// A function to create a unique pointer to an instance of this class when generated
// via a plugin call using dlopen/dlsym.
// You must have external C linkage here otherwise dlopen will not find the file
extern "C" std::unique_ptr<Source> openmc_create_source(const char* parameters)
extern "C" std::unique_ptr<Source> openmc_create_source(std::string parameters)
{
return Source::from_string(parameters);
}