id
int64 0
877k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
66
| repo_stars
int64 94
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 11
values | repo_extraction_date
stringclasses 197
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1,535,006
|
Polymer.h
|
dmorse_pscfpp/docs/notes/draft/cyln/solvers/Polymer.h
|
#ifndef CYLN_POLYMER_H
#define CYLN_POLYMER_H
/*
* PSCF - Polymer Self-Consistent Field Theory
*
* Copyright 2016, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include "Block.h"
#include <pscf/solvers/PolymerTmpl.h>
namespace Pscf {
namespace Cyln
{
/**
* Descriptor and solver for a branched polymer species.
*
* The block concentrations stored in the constituent Block
* objects contain the block concentrations (i.e., volume
* fractions) computed in the most recent call of the compute
* function.
*
* The phi() and mu() accessor functions, which are inherited
* from PolymerTmp<Block>, return the value of phi (spatial
* average volume fraction of a species) or mu (chemical
* potential) computed in the last call of the compute function.
* If the ensemble for this species is closed, phi is read from
* the parameter file and mu is computed. If the ensemble is
* open, mu is read from the parameter file and phi is computed.
*
* \ingroup Pscf_Cyln_Module
*/
class Polymer : public PolymerTmpl<Block>
{
public:
Polymer();
~Polymer();
void setPhi(double phi);
void setMu(double mu);
/**
* Compute solution to modified diffusion equation.
*
* Upon return, q functions and block concentration fields
* are computed for all propagators and blocks.
*/
void compute(const DArray<Block::WField>& wFields);
};
}
}
#endif
| 1,538
|
C++
|
.h
| 49
| 27.244898
| 66
| 0.706161
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,007
|
Propagator.h
|
dmorse_pscfpp/docs/notes/draft/cyln/solvers/Propagator.h
|
#ifndef CYLN_PROPAGATOR_H
#define CYLN_PROPAGATOR_H
/*
* PSCF - Polymer Self-Consistent Field Theory
*
* Copyright 2016, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include <pscf/solvers/PropagatorTmpl.h> // base class template
#include <util/containers/DArray.h> // member template
#include <cyln/field/Field.h> // typedef
namespace Pscf {
namespace Cyln
{
class Block;
using namespace Util;
/**
* MDE solver for one-direction of one block.
*
* \ingroup Pscf_Cyln_Module
*/
class Propagator : public PropagatorTmpl<Propagator>
{
public:
// Public typedefs
/**
* Chemical potential field type.
*/
typedef Field<double> WField;
/**
* Monomer concentration field type.
*/
typedef Field<double> CField;
/**
* Propagator q-field type.
*/
typedef Field<double> QField;
// Member functions
/**
* Constructor.
*/
Propagator();
/**
* Destructor.
*/
~Propagator();
/**
* Associate this propagator with a block.
*
* \param block associated Block object.
*/
void setBlock(Block& block);
/**
* Associate this propagator with a block.
*
* \param ns number of contour length steps
* \param nr number of spatial steps in radial (r) direction
* \param nz number of spatial steps in axial (z) direction
*/
void allocate(int ns, int nr, int nz);
/**
* Solve the modified diffusion equation (MDE) for this block.
*
* This function computes an initial QField at the head of this
* block, and then solves the modified diffusion equation for
* the block to propagate from the head to the tail. The initial
* QField at the head is computed by pointwise multiplication of
* of the tail QFields of all source propagators.
*/
void solve();
/**
* Solve the MDE for a specified initial condition.
*
* This function solves the modified diffusion equation for this
* block with a specified initial condition, which is given by
* head parameter of the function. The function is intended for
* use in testing.
*
* \param head initial condition of QField at head of block
*/
void solve(const QField& head);
/**
* Compute and return partition function for the molecule.
*
* This function computes the partition function Q for the
* molecule as a spatial average of the initial/head Qfield
* for this propagator and the final/tail Qfield of its
* partner.
*/
double computeQ();
/**
* Return q-field at specified step.
*
* \param i step index
*/
const QField& q(int i) const;
/**
* Return q-field at beginning of block (initial condition).
*/
const QField& head() const;
/**
* Return q-field at end of block.
*/
const QField& tail() const;
/**
* Get the associated Block object by reference.
*/
Block & block();
/**
* Has memory been allocated for this propagator?
*/
bool isAllocated() const;
protected:
/**
* Compute initial QField at head from tail QFields of sources.
*/
void computeHead();
private:
// Array of statistical weight fields
DArray<QField> qFields_;
// Workspace
QField work_;
/// Pointer to associated Block.
Block* blockPtr_;
/// Number of contour length steps = # grid points - 1.
int ns_;
/// Number of spatial grid points.
int nx_;
/// Is this propagator allocated?
bool isAllocated_;
};
// Inline member functions
/*
* Return q-field at beginning of block.
*/
inline Propagator::QField const& Propagator::head() const
{ return qFields_[0]; }
/*
* Return q-field at end of block, after solution.
*/
inline Propagator::QField const& Propagator::tail() const
{ return qFields_[ns_-1]; }
/*
* Return q-field at specified step.
*/
inline Propagator::QField const& Propagator::q(int i) const
{ return qFields_[i]; }
/*
* Get the associated Block object.
*/
inline Block& Propagator::block()
{
assert(blockPtr_);
return *blockPtr_;
}
/*
* Associate this propagator with a block and direction
*/
inline void Propagator::setBlock(Block& block)
{ blockPtr_ = █ }
}
}
#endif
| 4,666
|
C++
|
.h
| 163
| 22.588957
| 69
| 0.623345
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,008
|
Block.h
|
dmorse_pscfpp/docs/notes/draft/cyln/solvers/Block.h
|
#ifndef CYLN_BLOCK_H
#define CYLN_BLOCK_H
/*
* PSCF - Polymer Self-Consistent Field Theory
*
* Copyright 2016, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include <pscf/solvers/BlockTmpl.h> // base class template
#include "Propagator.h" // base class argument
#include <pscf/math/TridiagonalSolver.h> // member
#include <cyln/field/Field.h> // member
#include <cyln/field/FFT.h> // member
#include <util/containers/DArray.h> // member
namespace Pscf {
namespace Cyln
{
class Domain;
using namespace Util;
/**
* Block within a branched polymer.
*
* Derived from BlockTmpl<Propagator>. A BlockTmpl<Propagator> has two
* Propagator members and is derived from BlockDescriptor.
*
* \ingroup Pscf_Cyln_Module
*/
class Block : public BlockTmpl<Propagator>
{
public:
/**
* Monomer chemical potential field.
*/
typedef Propagator::WField WField;
/**
* Constrained partition function q(r,s) for fixed s.
*/
typedef Propagator::QField QField;
// Member functions
/**
* Constructor.
*/
Block();
/**
* Destructor.
*/
~Block();
/**
* Initialize discretization and allocate required memory.
*
* \param domain associated Domain object, with grid info
* \param ds desired (optimal) value for contour length step
*/
void setDiscretization(Domain const & domain, double ds);
/**
* Setup MDE solver for this block.
*/
void setupSolver(WField const & w);
/**
* Compute unnormalized concentration for block by integration.
*
* Upon return, grid point r of array cField() contains the
* integral int ds q(r,s)q^{*}(r,L-s) times the prefactor,
* where q(r,s) is the solution obtained from propagator(0),
* and q^{*} is the solution of propagator(1), and s is
* a contour variable that is integrated over the domain
* 0 < s < length(), where length() is the block length.
*
* \param prefactor multiplying integral
*/
void computeConcentration(double prefactor);
/**
* Compute step of integration loop, from i to i+1.
*/
void step(QField const & q, QField& qNew);
/**
* Return associated domain by reference.
*/
Domain const & domain() const;
/**
* Number of contour length steps.
*/
int ns() const;
private:
// Data structures for pseudospectral algorithm
// Fourier transform plan
FFT fft_;
// Work array for wavevector space field.
Field<fftw_complex> qk_;
// Array of elements containing exp(-W[i] ds/2)
Field<double> expW_;
// Array of elements containing exp(-K^2 b^2 ds/6)
DArray<double> expKsq_;
// Data structures for Crank-Nicholson algorithm
/// Solver used in Crank-Nicholson algorithm
TridiagonalSolver solver_;
// Arrays dA_, uA_, lB_ dB_, uB_, luB_ contain elements of the
// the tridiagonal matrices A and B used in propagation by the
// radial part of the Laplacian from step i to i + 1, which
// requires solution of a linear system A q(i+1) = B q(i).
/// Diagonal elements of matrix A
DArray<double> dA_;
/// Off-diagonal upper elements of matrix A
DArray<double> uA_;
/// Off-diagonal lower elements of matrix A
DArray<double> lA_;
/// Diagonal elements of matrix B
DArray<double> dB_;
/// Off-diagonal upper elements of matrix B
DArray<double> uB_;
/// Off-diagonal lower elements of matrix B
DArray<double> lB_;
/// Work vector, dimension = nr = # elements in radial direction
DArray<double> rWork_;
/// Pointer to associated Domain object.
Domain const * domainPtr_;
/// Contour length step size.
double ds_;
/// Number of contour length steps = # grid points - 1.
int ns_;
/*
* Setup data structures associated with Crank-Nicholson stepper
* for radial part of Laplacian.
*/
void setupRadialLaplacian(Domain& domain);
/*
* Setup data structures associated with pseudospectral stepper
* for axial part of Laplacian, using FFTs.
*/
void setupAxialLaplacian(Domain& domain);
};
// Inline member functions
/// Get Domain by reference.
inline Domain const & Block::domain() const
{
UTIL_ASSERT(domainPtr_);
return *domainPtr_;
}
/// Get number of contour steps.
inline int Block::ns() const
{ return ns_; }
}
}
#endif
| 4,770
|
C++
|
.h
| 144
| 27.048611
| 73
| 0.633268
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,009
|
Mixture.h
|
dmorse_pscfpp/docs/notes/draft/cyln/solvers/Mixture.h
|
#ifndef CYLN_MIXTURE_H
#define CYLN_MIXTURE_H
/*
* PSCF - Polymer Self-Consistent Field Theory
*
* Copyright 2016, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include "Polymer.h"
#include "Solvent.h"
#include <pscf/solvers/MixtureTmpl.h>
#include <pscf/inter/Interaction.h>
#include <util/containers/DArray.h>
namespace Pscf {
namespace Cyln
{
class Domain;
/**
* Mixture of polymers and solvents.
*
* A Mixture contains a list of Polymer and Solvent objects. Each
* such object can solve the single-molecule statistical mechanics
* problem for an ideal gas of the associated species in a set of
* specified chemical potential fields, and thereby compute
* concentrations and single-molecule partition functions. A
* Mixture is thus both a chemistry descriptor and an ideal-gas
* solver.
*
* A Mixture is associated with a Domain object, which models a
* spatial domain and a spatial discretization. Knowledge of the
* domain and discretization is needed to solve the ideal-gas
* problem.
*
* \ingroup Pscf_Cylng_Module
*/
class Mixture : public MixtureTmpl<Polymer, Solvent>
{
public:
// Public typedefs
/**
* Monomer chemical potential field type.
*/
typedef Propagator::WField WField;
/**
* Monomer concentration or volume fraction field type.
*/
typedef Propagator::CField CField;
// Public member functions
/**
* Constructor.
*/
Mixture();
/**
* Destructor.
*/
~Mixture();
/**
* Read all parameters and initialize.
*
* This function reads in a complete description of
* the chemical composition and structure of all species,
* as well as the target contour length step size ds.
*
* \param in input parameter stream
*/
void readParameters(std::istream& in);
/**
* Create an association with the domain and allocate memory.
*
* The domain parameter must have already been initialized,
* e.g., by reading its parameters from a file, so that the
* domain dimensions are known on entry.
*
* \param domain associated Domain object (stores address).
*/
void setDomain(Domain const & domain);
/**
* Compute concentrations.
*
* This function calls the compute function of every molecular
* species, and then adds the resulting block concentration
* fields for blocks of each type to compute a total monomer
* concentration (or volume fraction) for each monomer type.
* Upon return, values are set for volume fraction and chemical
* potential (mu) members of each species, and for the
* concentration fields for each Block and Solvent. The total
* concentration for each monomer type is returned in the
* cFields output parameter.
*
* The arrays wFields and cFields must each have size nMonomer(),
* and contain fields that are indexed by monomer type index.
*
* \param wFields array of chemical potential fields (input)
* \param cFields array of monomer concentration fields (output)
*/
void
compute(DArray<WField> const & wFields, DArray<CField>& cFields);
/**
* Get monomer reference volume.
*/
double vMonomer() const;
private:
/// Monomer reference volume (set to 1.0 by default).
double vMonomer_;
/// Optimal contour length step size.
double ds_;
/// Pointer to associated Domain object.
Domain const * domainPtr_;
/// Return associated domain by reference.
Domain const & domain() const;
};
// Inline member function
/*
* Get monomer reference volume (public).
*/
inline double Mixture::vMonomer() const
{ return vMonomer_; }
/*
* Get Domain by constant reference (private).
*/
inline Domain const & Mixture::domain() const
{
UTIL_ASSERT(domainPtr_);
return *domainPtr_;
}
} // namespace Cyln
} // namespace Pscf
#endif
| 4,177
|
C++
|
.h
| 128
| 27.0625
| 71
| 0.672881
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,010
|
Solvent.h
|
dmorse_pscfpp/docs/notes/draft/cyln/solvers/Solvent.h
|
#ifndef CYLN_SOLVENT_H
#define CYLN_SOLVENT_H
/*
* PSCF - Polymer Self-Consistent Field Theory
*
* Copyright 2016, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include "Propagator.h"
#include <pscf/solvers/SolventTmpl.h>
namespace Pscf {
namespace Cyln
{
/**
* Solver for a point particle solvent species.
*
* \ingroup Pscf_Cyln_Module
*/
class Solvent : public SolventTmpl<Propagator>
{
public:
/**
* Monomer concentration field type.
*/
typedef Propagator::CField CField;
/**
* Monomer chemical potential field type.
*/
typedef Propagator::CField WField;
/**
* Constructor.
*/
Solvent();
/**
* Destructor.
*/
~Solvent();
/**
* Compute monomer concentration field and partittion function.
*
* Upon return, monomer concentration field, phi and mu are set.
*
* \param wField monomer chemical potential field
*/
void compute(WField const & wField);
/**
* Get monomer concentration field for this solvent.
*/
const CField& concentration() const
{ return concentration_; }
private:
CField concentration_;
};
} // namespace Cyln
} // namespace Pscf
#endif
| 1,352
|
C++
|
.h
| 56
| 19
| 69
| 0.644201
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,011
|
DomainTest.h
|
dmorse_pscfpp/docs/notes/draft/cyln/tests/misc/DomainTest.h
|
#ifndef CYLN_DOMAIN_TEST_H
#define CYLN_DOMAIN_TEST_H
#include <test/UnitTest.h>
#include <test/UnitTestRunner.h>
#include <cyln/misc/Domain.h>
#include <util/containers/DArray.h>
#include <util/math/Constants.h>
#include <util/format/Dbl.h>
using namespace Util;
using namespace Pscf::Cyln;
class DomainTest : public UnitTest
{
public:
void setUp()
{ }
void tearDown() {}
void testConstructor();
void testSetParameters();
};
void DomainTest::testConstructor()
{
printMethod(TEST_FUNC);
{
Domain v;
//TEST_ASSERT(v.capacity() == 0 );
//TEST_ASSERT(!v.isAllocated() );
}
}
void DomainTest::testSetParameters()
{
printMethod(TEST_FUNC);
printEndl();
Domain v;
v.setParameters(2.0, 3.0, 21, 31);
TEST_ASSERT(eq(v.radius(), 2.0));
TEST_ASSERT(eq(v.length(), 3.0));
TEST_ASSERT(eq(v.nr(), 21));
TEST_ASSERT(eq(v.nz(), 31));
TEST_ASSERT(eq(v.dr(), 0.1));
TEST_ASSERT(eq(v.dz(), 0.1));
TEST_ASSERT(eq(v.volume(), 12.0*Constants::Pi));
//std::cout << std::endl;
}
TEST_BEGIN(DomainTest)
TEST_ADD(DomainTest, testConstructor)
TEST_ADD(DomainTest, testSetParameters)
TEST_END(DomainTest)
#endif
| 1,183
|
C++
|
.h
| 48
| 21.625
| 51
| 0.686607
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,012
|
FieldTestComposite.h
|
dmorse_pscfpp/docs/notes/draft/cyln/tests/field/FieldTestComposite.h
|
#ifndef CYLN_FIELD_TEST_COMPOSITE_H
#define CYLN_FIELD_TEST_COMPOSITE_H
#include <test/CompositeTestRunner.h>
#include "FftTest.h"
#include "FieldTest.h"
TEST_COMPOSITE_BEGIN(FieldTestComposite)
TEST_COMPOSITE_ADD_UNIT(FftTest);
TEST_COMPOSITE_ADD_UNIT(FieldTest);
TEST_COMPOSITE_END
#endif
| 295
|
C++
|
.h
| 10
| 28.1
| 40
| 0.83274
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,013
|
FieldTest.h
|
dmorse_pscfpp/docs/notes/draft/cyln/tests/field/FieldTest.h
|
#ifndef CYLN_FIELD_TEST_H
#define CYLN_FIELD_TEST_H
#include <test/UnitTest.h>
#include <test/UnitTestRunner.h>
#include <cyln/field/Field.h>
#if 0
#include <util/archives/MemoryOArchive.h>
#include <util/archives/MemoryIArchive.h>
#include <util/archives/MemoryCounter.h>
#include <util/archives/BinaryFileOArchive.h>
#include <util/archives/BinaryFileIArchive.h>
#endif
using namespace Util;
using namespace Pscf::Cyln;
class FieldTest : public UnitTest
{
public:
void setUp()
{ }
void tearDown() {}
void testConstructor();
void testAllocate();
void testSubscript();
void testSlice();
#if 0
void testSerialize1Memory();
void testSerialize2Memory();
void testSerialize1File();
void testSerialize2File();
#endif
void fillValues(Field<double>& v);
};
void FieldTest::testConstructor()
{
printMethod(TEST_FUNC);
{
Field<double> v;
TEST_ASSERT(v.capacity() == 0 );
TEST_ASSERT(!v.isAllocated() );
}
}
void FieldTest::testAllocate()
{
printMethod(TEST_FUNC);
{
Field<double> v;
int nr = 10;
int nz = 10;
int capacity = nr*nz;
v.allocate(nr, nz);
TEST_ASSERT(v.capacity() == capacity);
TEST_ASSERT(v.nr() == nr);
TEST_ASSERT(v.nz() == nz);
TEST_ASSERT(v.isAllocated());
}
}
void FieldTest::fillValues(Field<double>& v)
{
// Fill field values
int i, j, k;
k = 0;
for (i=0; i < v.nr(); i++) {
for (j=0; j < v.nz(); j++) {
v[k] = (i+1)*20.0 + j*1.0;
++k;
}
}
}
void FieldTest::testSubscript()
{
printMethod(TEST_FUNC);
{
Field<double> v;
int nr = 10;
int nz = 10;
int capacity = nr*nz;
v.allocate(nr, nz);
TEST_ASSERT(v.capacity() == capacity);
fillValues(v);
TEST_ASSERT(v[0] == 20.0);
TEST_ASSERT(v[10] == 40.0);
TEST_ASSERT(v[11] == 41.0);
TEST_ASSERT(v[12] == 42.0);
TEST_ASSERT(v[19] == 49.0);
TEST_ASSERT(v[20] == 60.0);
}
}
void FieldTest::testSlice()
{
printMethod(TEST_FUNC);
{
Field<double> v;
int nr = 10;
int nz = 10;
int capacity = nr*nz;
v.allocate(nr, nz);
TEST_ASSERT(v.capacity() == capacity);
fillValues(v);
Array<double> const & slice = v.slice(1);
TEST_ASSERT(slice[0] == 40.0);
TEST_ASSERT(slice[1] == 41.0);
TEST_ASSERT(slice[9] == 49.0);
}
}
#if 0
void FieldTest::testSerialize1Memory()
{
printMethod(TEST_FUNC);
{
Field<double> v;
v.allocate(3);
for (int i=0; i < capacity; i++ ) {
v[i] = (i+1)*10.0;
}
int size = memorySize(v);
int i1 = 13;
int i2;
MemoryOArchive oArchive;
oArchive.allocate(size + 12);
oArchive << v;
TEST_ASSERT(oArchive.cursor() == oArchive.begin() + size);
oArchive << i1;
// Show that v is unchanged by packing
TEST_ASSERT(v[1]==20.0);
TEST_ASSERT(v.capacity() == 3);
Field<double> u;
u.allocate(3);
MemoryIArchive iArchive;
iArchive = oArchive;
TEST_ASSERT(iArchive.begin() == oArchive.begin());
TEST_ASSERT(iArchive.cursor() == iArchive.begin());
// Load into u and i2
iArchive >> u;
TEST_ASSERT(iArchive.begin() == oArchive.begin());
TEST_ASSERT(iArchive.end() == oArchive.cursor());
TEST_ASSERT(iArchive.cursor() == iArchive.begin() + size);
iArchive >> i2;
TEST_ASSERT(iArchive.cursor() == iArchive.end());
TEST_ASSERT(iArchive.begin() == oArchive.begin());
TEST_ASSERT(iArchive.end() == oArchive.cursor());
TEST_ASSERT(u[1] == 20.0);
TEST_ASSERT(i2 == 13);
TEST_ASSERT(u.capacity() == 3);
// Release
iArchive.release();
TEST_ASSERT(!iArchive.isAllocated());
TEST_ASSERT(iArchive.begin() == 0);
TEST_ASSERT(iArchive.cursor() == 0);
TEST_ASSERT(iArchive.end() == 0);
TEST_ASSERT(oArchive.cursor() == oArchive.begin() + size + sizeof(int));
// Clear values of u and i2
for (int i=0; i < capacity; i++ ) {
u[i] = 0.0;
}
i2 = 0;
// Reload into u and i2
iArchive = oArchive;
iArchive >> u;
TEST_ASSERT(iArchive.begin() == oArchive.begin());
TEST_ASSERT(iArchive.end() == oArchive.cursor());
TEST_ASSERT(iArchive.cursor() == iArchive.begin() + size);
iArchive >> i2;
TEST_ASSERT(iArchive.cursor() == iArchive.end());
TEST_ASSERT(iArchive.begin() == oArchive.begin());
TEST_ASSERT(iArchive.end() == oArchive.cursor());
TEST_ASSERT(u[1] == 20.0);
TEST_ASSERT(i2 == 13);
TEST_ASSERT(u.capacity() == 3);
}
}
void FieldTest::testSerialize2Memory()
{
printMethod(TEST_FUNC);
{
Field<double> v;
v.allocate(capacity);
for (int i=0; i < capacity; i++ ) {
v[i] = (i+1)*10.0;
}
int size = memorySize(v);
MemoryOArchive oArchive;
oArchive.allocate(size);
oArchive << v;
TEST_ASSERT(oArchive.cursor() == oArchive.begin() + size);
// Show that v is unchanged by packing
TEST_ASSERT(v[1] == 20.0);
TEST_ASSERT(v.capacity() == capacity);
Field<double> u;
// Note: We do not allocate Field<double> u in this test.
// This is the main difference from testSerialize1Memory()
MemoryIArchive iArchive;
iArchive = oArchive;
TEST_ASSERT(iArchive.begin() == oArchive.begin());
TEST_ASSERT(iArchive.cursor() == iArchive.begin());
iArchive >> u;
TEST_ASSERT(iArchive.cursor() == iArchive.begin() + size);
TEST_ASSERT(u[1] == 20.0);
TEST_ASSERT(u.capacity() == 3);
}
}
void FieldTest::testSerialize1File()
{
printMethod(TEST_FUNC);
{
Field<double> v;
v.allocate(3);
for (int i=0; i < capacity; i++ ) {
v[i] = (i+1)*10.0;
}
int i1 = 13;
int i2;
BinaryFileOArchive oArchive;
openOutputFile("binary", oArchive.file());
oArchive << v;
oArchive << i1;
oArchive.file().close();
// Show that v is unchanged by packing
TEST_ASSERT(v[1]==20.0);
TEST_ASSERT(v.capacity() == 3);
Field<double> u;
u.allocate(3);
BinaryFileIArchive iArchive;
openInputFile("binary", iArchive.file());
iArchive >> u;
iArchive >> i2;
iArchive.file().close();
TEST_ASSERT(u[1] == 20.0);
TEST_ASSERT(i2 == 13);
TEST_ASSERT(u.capacity() == 3);
// Clear values of u and i2
for (int i=0; i < capacity; i++ ) {
u[i] = 0.0;
}
i2 = 0;
// Reload into u and i2
openInputFile("binary", iArchive.file());
iArchive >> u;
iArchive >> i2;
TEST_ASSERT(u[1] == 20.0);
TEST_ASSERT(i2 == 13);
TEST_ASSERT(u.capacity() == 3);
}
}
void FieldTest::testSerialize2File()
{
printMethod(TEST_FUNC);
{
Field<double> v;
v.allocate(3);
for (int i=0; i < capacity; i++ ) {
v[i] = (i+1)*10.0;
}
int i1 = 13;
int i2;
BinaryFileOArchive oArchive;
openOutputFile("binary", oArchive.file());
oArchive << v;
oArchive << i1;
oArchive.file().close();
// Show that v is unchanged by packing
TEST_ASSERT(v[1] == 20.0);
TEST_ASSERT(v.capacity() == 3);
Field<double> u;
// u.allocate(3); ->
// Note: We do not allocate first. This is the difference
// from the previous test
BinaryFileIArchive iArchive;
openInputFile("binary", iArchive.file());
iArchive >> u;
iArchive >> i2;
iArchive.file().close();
TEST_ASSERT(eq(u[1], 20.0));
TEST_ASSERT(i2 == 13);
TEST_ASSERT(u.capacity() == 3);
// Clear values of u and i2
for (int i=0; i < capacity; i++ ) {
u[i] = 0.0;
}
i2 = 0;
// Reload into u and i2
openInputFile("binary", iArchive.file());
iArchive >> u;
iArchive >> i2;
TEST_ASSERT(eq(u[1], 20.0));
TEST_ASSERT(i2 == 13);
TEST_ASSERT(u.capacity() == 3);
}
}
#endif
TEST_BEGIN(FieldTest)
TEST_ADD(FieldTest, testConstructor)
TEST_ADD(FieldTest, testAllocate)
TEST_ADD(FieldTest, testSubscript)
TEST_ADD(FieldTest, testSlice)
#if 0
TEST_ADD(FieldTest, testSerialize1Memory)
TEST_ADD(FieldTest, testSerialize2Memory)
TEST_ADD(FieldTest, testSerialize1File)
TEST_ADD(FieldTest, testSerialize2File)
#endif
TEST_END(FieldTest)
#endif
| 8,649
|
C++
|
.h
| 302
| 22.433775
| 78
| 0.589819
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,014
|
FftTest.h
|
dmorse_pscfpp/docs/notes/draft/cyln/tests/field/FftTest.h
|
#ifndef CYLN_FFT_TEST_H
#define CYLN_FFT_TEST_H
#include <test/UnitTest.h>
#include <test/UnitTestRunner.h>
#include <cyln/field/FFT.h>
#include <util/containers/DArray.h>
#include <util/math/Constants.h>
#include <util/format/Dbl.h>
using namespace Util;
using namespace Pscf::Cyln;
class FftTest : public UnitTest
{
public:
void setUp()
{ }
void tearDown() {}
void testConstructor();
void testTransform();
};
void FftTest::testConstructor()
{
printMethod(TEST_FUNC);
{
FFT v;
//TEST_ASSERT(v.capacity() == 0 );
//TEST_ASSERT(!v.isAllocated() );
}
}
void FftTest::testTransform()
{
printMethod(TEST_FUNC);
printEndl();
DArray<double> in;
DArray<fftw_complex> out;
int n = 10;
int m = n/2 + 1;
in.allocate(n);
out.allocate(m);
// Initialize input data
double x;
double twoPi = 2.0*Constants::Pi;
for (int i = 0; i < n; ++i) {
x = twoPi*float(i)/float(n);
in[i] = cos(x);
//std::cout << Dbl(in[i]);
}
//std::cout << std::endl;
FFT v;
v.setup(in, out);
v.forwardTransform(in, out);
DArray<double> inCopy;
inCopy.allocate(n);
v.inverseTransform(out, inCopy);
for (int i = 0; i < n; ++i) {
//std::cout << Dbl(inCopy[i]);
TEST_ASSERT(eq(in[i], inCopy[i]));
}
//std::cout << std::endl;
}
TEST_BEGIN(FftTest)
TEST_ADD(FftTest, testConstructor)
TEST_ADD(FftTest, testTransform)
TEST_END(FftTest)
#endif
| 1,460
|
C++
|
.h
| 64
| 19.25
| 40
| 0.640058
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,015
|
Domain.h
|
dmorse_pscfpp/docs/notes/draft/cyln/misc/Domain.h
|
#ifndef CYLN_DOMAIN_H
#define CYLN_DOMAIN_H
/*
* PSCF - Polymer Self-Consistent Field Theory
*
* Copyright 2016, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include <util/param/ParamComposite.h> // base class
#include <cyln/field/Field.h> // member template
namespace Pscf {
namespace Cyln
{
using namespace Util;
/**
* Cylindrical domain and discretization grid.
*
* \ingroup Pscf_Cyln_Module
*/
class Domain : public ParamComposite
{
public:
/**
* Constructor.
*/
Domain();
/**
* Destructor.
*/
~Domain();
/// \name Initialize parameters
//@{
/**
* Read all parameters and initialize.
*/
void readParameters(std::istream& in);
/**
* Set grid parameters for a planar domain.
*/
void setParameters(double radius, double length, int nr, int nz);
//@}
/// \name Accessors
//@{
/**
* Get radius of cylindrical domain.
*/
double radius() const;
/**
* Get length of domain parallel to rotation axis.
*/
double length() const;
/**
* Get volume of domain.
*/
double volume() const;
/**
* Get radial step size.
*/
double dr() const;
/**
* Get axial step size.
*/
double dz() const;
/**
* Get number of grid points in radial (r) direction.
*/
int nr() const;
/**
* Get number of grid points in axial (z) direction.
*/
int nz() const;
//@}
/// \name Spatial integrals
//@{
/**
* Compute spatial average of a field.
*
* \param f a field that depends on one spatial coordinate
* \return spatial average of field f
*/
double spatialAverage(Field<double> const & f) const;
/**
* Compute inner product of two real fields.
*
* \param f first field
* \param g second field
* \return spatial average of product of two fields.
*/
double innerProduct(Field<double> const & f, Field<double> const & g) const;
//@}
private:
/**
* Upper bound of spatial coordinate.
*/
double radius_;
/**
* Lower bound of spatial coordinate.
*/
double length_;
/**
* Generalized D-dimensional volume of simulation cell.
*/
double volume_;
/**
* Radial discretization step.
*/
double dr_;
/**
* Radial discretization step.
*/
double dz_;
/**
* Number of grid points in radial direction.
*/
int nr_;
/**
* Number of grid points in axial (z) direction.
*/
int nz_;
/**
* Total number of grid points.
*/
int nGrid_;
/**
* Work space vector.
*/
mutable Field<double> work_;
};
// Inline member functions
inline int Domain::nr() const
{ return nr_; }
inline int Domain::nz() const
{ return nz_; }
inline double Domain::dr() const
{ return dr_; }
inline double Domain::dz() const
{ return dz_; }
inline double Domain::length() const
{ return length_; }
inline double Domain::radius() const
{ return radius_; }
inline double Domain::volume() const
{ return volume_; }
} // namespace Cyln
} // namespace Pscf
#endif
| 3,502
|
C++
|
.h
| 146
| 17.876712
| 82
| 0.567331
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,016
|
FFT.h
|
dmorse_pscfpp/docs/notes/draft/cyln/field/FFT.h
|
#ifndef CYLN_FFT_H
#define CYLN_FFT_H
/*
* PSCF Package
*
* Copyright 2016 - 2017, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include <util/containers/DArray.h>
#include <util/containers/Array.h>
#include <util/global.h>
#include <fftw3.h>
namespace Pscf {
namespace Cyln {
using namespace Util;
using namespace Pscf;
/**
* Fourier transform wrapper for real data.
*
* \ingroup Cyln_Field_Module
*/
class FFT
{
public:
/**
* Default constructor.
*/
FFT();
/**
* Destructor.
*/
virtual ~FFT();
/**
* Check and setup grid dimensions if necessary.
*
* \param rField real data on r-space grid
* \param kField complex data on k-space grid
*/
void setup(Array<double>& rField, Array<fftw_complex>& kField);
/**
* Compute forward (real-to-complex) Fourier transform.
*
* \param in array of real values on r-space grid
* \param out array of complex values on k-space grid
*/
void forwardTransform(Array<double>& in, Array<fftw_complex>& out);
/**
* Compute inverse (complex-to-real) Fourier transform.
*
* \param in array of complex values on k-space grid
* \param out array of real values on r-space grid
*/
void inverseTransform(Array<fftw_complex>& in, Array<double>& out);
private:
// Work array for real data.
DArray<double> work_;
// Number of points in r-space grid
int rSize_;
// Number of points in k-space grid
int kSize_;
// Pointer to a plan for a forward transform.
fftw_plan fPlan_;
// Pointer to a plan for an inverse transform.
fftw_plan iPlan_;
// Have array dimension and plan been initialized?
bool isSetup_;
};
}
}
#endif
| 1,912
|
C++
|
.h
| 70
| 21.957143
| 73
| 0.635914
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,017
|
Field.h
|
dmorse_pscfpp/docs/notes/draft/cyln/field/Field.h
|
#ifndef PSSP_FIELD_H
#define PSSP_FIELD_H
/*
* PSCF Package
*
* Copyright 2016 - 2017, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include <util/containers/Array.h>
#include <util/containers/RArray.h>
#include <util/containers/DArray.h>
#include <util/global.h>
#include <fftw3.h>
namespace Pscf {
namespace Cyln
{
using namespace Util;
/**
* 2D dynamic array with aligned data, for use with FFTW library.
*
* \ingroup Cyln_Field_Module
*/
template <typename Data>
class Field
{
public:
/**
* Default constructor.
*/
Field();
/**
* Destructor.
*
* Deletes underlying C array, if allocated previously.
*/
virtual ~Field();
/**
* Allocate memory.
*
* \throw Exception if the Field is already allocated.
*
* \param nr number of grid points in radial direction
* \param nz number of grid points in axial (z) direction
*/
void allocate(int nr, int nz);
/**
* Dellocate the underlying C array.
*
* \throw Exception if the Field is not allocated.
*/
void deallocate();
/**
* Return true if the Field has been allocated, false otherwise.
*/
bool isAllocated() const;
/**
* Return allocated size (equal to 0 if note allocated).
*/
int capacity() const;
/**
* Return number of element in radial (r) direction.
*/
int nr() const;
/**
* Return number of element in axial (z) direction.
*/
int nz() const;
/**
* Get a single element by non-const reference.
*
* Mimic 1D C-array subscripting.
*
* \param i array index
* \return non-const reference to element i
*/
Data& operator[] (int i);
/**
* Get a single element by non-const reference.
*
* Mimics 1D C-array subscripting.
*
* \param i array index
* \return const reference to element i
*/
const Data& operator[] (int i) const;
/**
* Get a 1D constant radius array slice by const reference.
*
* \param i array index
* \return non-const reference to element i
*/
Array<Data> const & slice(int i) const;
/**
* Get a 1D constant radius array slice by non-const reference.
*
* \param i array index
* \return non-const reference to element i
*/
Array<Data>& slice(int i);
/**
* Return pointer to underlying C array.
*/
Data* ptr();
/**
* Return pointer to const to underlying C array.
*/
Data const * ptr() const;
/**
* Serialize a Field to/from an Archive.
*
* \param ar archive
* \param version archive version id
*/
template <class Archive>
void serialize(Archive& ar, const unsigned int version);
protected:
/// Pointer to an array of Data elements.
Data* data_;
/// Allocated size of the data_ array.
int capacity_;
/// Number of elements in radial direction (# of slices)
int nr_;
/// Number of elements in axial direction (# per slice)
int nz_;
/// References arrays containing pointers to slices.
DArray< RArray<Data> > slices_;
private:
/**
* Copy constructor (private and not implemented to prohibit).
*/
Field(const Field& other);
/**
* Assignment operator (private and non implemented to prohibit).
*/
Field& operator = (const Field& other);
};
/*
* Return allocated size (total number of elements).
*/
template <typename Data>
inline int Field<Data>::capacity() const
{ return capacity_; }
/*
* Return number of elements in radial (r) direction.
*/
template <typename Data>
inline int Field<Data>::nr() const
{ return nr_; }
/*
* Return number of elements in axial (z) direction.
*/
template <typename Data>
inline int Field<Data>::nz() const
{ return nz_; }
/*
* Get an element by reference (C-array subscripting)
*/
template <typename Data>
inline Data& Field<Data>::operator[] (int i)
{
assert(data_ != 0);
assert(i >= 0);
assert(i < capacity_);
return *(data_ + i);
}
/*
* Get an element by const reference (C-array subscripting)
*/
template <typename Data>
inline const Data& Field<Data>::operator[] (int i) const
{
assert(data_ != 0);
assert(i >= 0 );
assert(i < capacity_);
return *(data_ + i);
}
/*
* Get a 1D constant radius array slice by const reference.
*/
template <typename Data>
inline Array<Data> const & Field<Data>::slice(int i) const
{ return slices_[i]; }
/*
* Get a 1D constant radius array slice by non-const reference.
*/
template <typename Data>
inline Array<Data>& Field<Data>::slice(int i)
{ return slices_[i]; }
/*
* Get a pointer to the underlying C array.
*/
template <typename Data>
inline Data* Field<Data>::ptr()
{ return data_; }
/*
* Get a pointer to const to the underlying C array.
*/
template <typename Data>
inline const Data* Field<Data>::ptr() const
{ return data_; }
/*
* Return true if the Field has been allocated, false otherwise.
*/
template <typename Data>
inline bool Field<Data>::isAllocated() const
{ return (bool)data_; }
/*
* Serialize a Field to/from an Archive.
*/
template <typename Data>
template <class Archive>
void
Field<Data>::serialize(Archive& ar, const unsigned int version)
{
int nr, nz, capacity;
if (Archive::is_saving()) {
capacity = capacity_;
nr = nr_;
nr = nz_;
}
ar & capacity;
ar & nr;
ar & nz;
if (Archive::is_loading()) {
if (!isAllocated()) {
if (capacity > 0) {
allocate(nr, nz);
} else {
UTIL_CHECK(nr == 0);
UTIL_CHECK(nz == 0);
}
} else {
UTIL_CHECK(capacity != capacity_);
UTIL_CHECK(nr != nr_);
UTIL_CHECK(nz != nz_);
}
}
if (isAllocated()) {
for (int i = 0; i < capacity_; ++i) {
ar & data_[i];
}
}
}
}
}
#include "Field.tpp"
#endif
| 6,499
|
C++
|
.h
| 247
| 20.246964
| 70
| 0.581373
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,018
|
System.h
|
dmorse_pscfpp/src/pspg/System.h
|
#ifndef PSPG_SYSTEM_H
#define PSPG_SYSTEM_H
/*
* PSCF - Polymer Self-Consistent Field Theory
*
* Copyright 2016 - 2022, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include <util/param/ParamComposite.h> // base class
#include <pspg/solvers/Mixture.h> // member
#include <pspg/field/Domain.h> // member
#include <pspg/field/FieldIo.h> // member
#include <pspg/field/WFieldContainer.h> // member
#include <pspg/field/CFieldContainer.h> // member
#include <pspg/field/RDField.h> // member
#include <pspg/field/RDFieldDft.h> // member
#include <pscf/homogeneous/Mixture.h> // member
#include <util/misc/FileMaster.h> // member
#include <util/containers/DArray.h> // member template
#include <util/containers/FSArray.h> // member template
namespace Pscf {
class Interaction;
namespace Pspg
{
template <int D> class Iterator;
template <int D> class IteratorFactory;
template <int D> class Sweep;
template <int D> class SweepFactory;
using namespace Util;
/**
* Main class in SCFT simulation of one system.
*
* A System has (among other components):
*
* - a Mixture (a container for polymer and solvent solvers)
* - an Interaction (list of chi parameters)
* - a Domain (a description of the unit cell and discretization)
* - a container of monomer chemical potential fields (w fields)
* - a container of monomer concentration fields (c fields)
*
* A System may also optionally contain Iterator and Sweep objects.
*
* A minimal main program that uses this class template to implement a
* program for 3-dimensional structures (D=3) looks something like this:
* \code
* int main(int argc, char **argv) {
* Pscf::Pspg::System<3> system;
* system.setOptions(argc, argv);
* system.readParam();
* system.readCommands();
* }
* \endcode
* This main program is given for D=1, 2, and 3 dimensional structures
* in the files pscf_pg1.cpp, pscf_pg2.cpp, and pscf_pg3.cpp
*
* \ingroup Pscf_Pspg_Module
*/
template <int D>
class System : public ParamComposite
{
public:
/// \name Construction and Destruction
///@{
/**
* Constructor.
*/
System();
/**
* Destructor.
*/
~System();
///@}
/// \name Lifetime (Actions)
///@{
/**
* Process command line options.
*
* This function takes the same arguments as any C/C++ main program
* function. The arguments of the main function should d be passed
* to this function unaltered, to allow this function to process the
* command line options.
*
* \param argc number of command line arguments
* \param argv array of pointers to command line arguments
*/
void setOptions(int argc, char **argv);
/**
* Read input parameters (with opening and closing lines).
*
* \param in input parameter stream
*/
virtual void readParam(std::istream& in);
/**
* Read input parameters from default param file.
*
* This function reads the parameter file set by the -p command
* line option.
*/
void readParam();
/**
* Read body of parameter file (without opening, closing lines).
*
* \param in input parameter stream
*/
virtual void readParameters(std::istream& in);
/**
* Read command script.
*
* \param in command script file.
*/
void readCommands(std::istream& in);
/**
* Read commands from default command file.
*
* This function reads the parameter file set by the -c command
* line option.
*/
void readCommands();
///@}
/// \name W Field Modifiers
///@{
/**
* Read chemical potential fields in symmetry adapted basis format.
*
* This function opens and reads the file with the name given by the
* "filename" string, which must contain chemical potential fields
* in symmetry-adapted basis format. The function copies these
* fields to set new values for the system w fields in basis format,
* and also computes and resets the system w fields in r-space
* format. On exit, both w().basis() and w().rgrid() have been
* reset, w().hasData and w().isSymmetric() are true, and
* hasCFields() is false.
*
* \param filename name of input w-field basis file
*/
void readWBasis(const std::string & filename);
/**
* Read chemical potential fields in real space grid (r-grid) format.
*
* This function opens and reads the file with the name given by the
* "filename" string, which must contains chemical potential fields
* in real space grid (r-grid) format. The function sets values for
* system w fields in r-grid format. It does not set attempt to set
* field values in symmetry-adapted basis format, because it cannot
* be known whether the r-grid field exhibits the declared space
* group symmetry. On exit, w().rgrid() is reset and w().hasData()
* is true, while w().isSymmetric() and hasCFields() are false.
*
* \param filename name of input w-field basis file
*/
void readWRGrid(const std::string & filename);
/**
* Set chemical potential fields, in symmetry-adapted basis format.
*
* This function sets values for w fields in both symmetry adapted
* and r-grid format. On exit, values of both w().basis() and
* w().rgrid() are reset, w().hasData() and w().isSymmetric() are
* true, and hasCFields() is false.
*
* \param fields array of new w (chemical potential) fields
*/
void setWBasis(DArray< DArray<double> > const & fields);
/**
* Set new w fields, in real-space (r-grid) format.
*
* This function set values for w fields in r-grid format, but does
* not set components the symmetry-adapted basis format. On exit,
* w.rgrid() is reset, w().hasData() is true, hasCFields() is false
* and w().isSymmetric() is false.
*
* \param fields array of new w (chemical potential) fields
*/
void setWRGrid(DArray< RDField<D> > const & fields);
/**
* Set new w fields, in unfolded real-space (r-grid) format.
*
* The function parameter "fields" is an unfolded array containing
* r-grid fields for all monomer types in a single array, with the
* field for monomer 0 first, followed by the field for monomer 1,
* etc. This function sets w().rgrid() but does not set w().basis().
* On exit, w().hasData is true, while w().isSymmetric() and
* hasCFields() are both false.
*
* \param fields unfolded array of new chemical potential fields
*/
void setWRGrid(DField<cudaReal> & fields);
/**
* Symmetrize r-grid w-fields, compute basis components.
*
* On exit, w().hasData() and w().isSymmetric() are true, while
* hasCFields() is false.
*/
void symmetrizeWFields();
/**
* Construct trial w-fields from c-fields.
*
* This function reads concentration fields in symmetrized basis
* format and constructs an initial guess for corresponding chemical
* potential fields by setting the Lagrange multiplier field xi to
* zero. The result is stored in the system w field container.
*
* Upon return, w().hasData() and w().isSymmetric() are true, while
* hasCFields() is false.
*
* \param filename name of input c-field file (basis format)
*/
void estimateWfromC(const std::string& filename);
///@}
/// \name Unit Cell Modifiers
///@{
/**
* Set parameters of the associated unit cell.
*
* The lattice system declared within the input unitCell must agree
* with Domain::lattice() on input if Domain::lattice() is not null.
*
* \param unitCell new UnitCell<D> (i.e., new parameters)
*/
void setUnitCell(UnitCell<D> const & unitCell);
/**
* Set state of the associated unit cell.
*
* The lattice argument must agree with Domain::lattice() on input
* if Domain::lattice() is not null, and the size of the parameters
* array must agree with the expected number of lattice parameters.
*
* \param lattice lattice system
* \param parameters array of new unit cell parameters.
*/
void setUnitCell(typename UnitCell<D>::LatticeSystem lattice,
FSArray<double, 6> const & parameters);
/**
* Set parameters of the associated unit cell.
*
* The size of the FSArray<double, 6> parameters must agree with the
* expected number of parameters for the current lattice type.
*
* \param parameters array of new unit cell parameters.
*/
void setUnitCell(FSArray<double, 6> const & parameters);
///@}
/// \name Primary SCFT Computations
///@{
/**
* Solve the modified diffusion equation once, without iteration.
*
* This function calls the Mixture::compute() function to solve
* the statistical mechanics problem for a non-interacting system
* subjected to the currrent chemical potential fields (wFields
* and wFieldRGrid). This requires solution of the modified
* diffusion equation for all polymers, computation of Boltzmann
* weights for all solvents, computation of molecular partition
* functions for all species, and computation of concentration
* fields for blocks and solvents, and computation of overall
* concentrations for all monomer types. This function does not
* compute the canonical (Helmholtz) free energy or grand-canonical
* free energy (i.e., pressure). Upon return, the flag hasCFields
* is set true.
*
* \pre The boolean w().hasData() must be true on entry
* \post hasCFields is true on exit
*
* If argument needStress == true, then this function also calls
* Mixture<D>::computeStress() to compute the stress.
*
* \param needStress true if stress is needed, false otherwise
*/
void compute(bool needStress = false);
/**
* Iteratively solve a SCFT problem.
*
* This function calls the iterator to attempt to solve the SCFT
* problem for the current mixture and system parameters, using
* the current chemical potential fields (wFields and wFieldRGrid)
* and current unit cell parameter values as initial guesses.
* Upon exist, hasCFields is set true whether or not convergence
* is obtained to within the desired tolerance. The Helmholtz free
* energy and pressure are computed if and only if convergence is
* obtained.
*
* \pre The w().hasData() flag must be true on entry, to confirm
* that chemical potential fields have been set.
*
* \pre The w().isSymmetric() flag must be set true if the chosen
* iterator uses a basis representation, and thus requires this.
*
* \param isContinuation true iff continuation within a sweep
* \return returns 0 for successful convergence, 1 for failure
*/
int iterate(bool isContinuation = false);
/**
* Sweep in parameter space, solving an SCF problem at each point.
*
* This function uses a Sweep object that was initialized in the
* parameter file to solve the SCF problem at a sequence of points
* along a line in parameter space. The nature of this sequence
* is determined by implementation of a subclass of Sweep and the
* parameters passed to the sweep object in the parameter file.
*
* \pre The w().hasData() flag must be true on entry.
* \pre A sweep object must have been created in the parameter file.
*/
void sweep();
///@}
/// \name Thermodynamic Properties
///@{
/**
* Compute free energy density and pressure for current fields.
*
* This function should be called after a successful call of
* iterator().solve(). Resulting values are returned by the
* freeEnergy() and pressure() accessor functions.
*
* \pre w().hasData must be true.
* \pre hasCFields must be true.
*/
void computeFreeEnergy();
/**
* Get precomputed Helmoltz free energy per monomer / kT.
*
* The value retrieved by this function is pre-computed by the
* computeFreeEnergy() function.
*/
double fHelmholtz() const;
/**
* Get precomputed pressure times monomer volume / kT.
*
* The value retrieved by this function is pre-computed by the
* computeFreeEnergy() function.
*/
double pressure() const;
///@}
/// \name Thermodynamic Data Output
///@{
/**
* Write parameter file to an ostream, omitting the sweep block.
*
* This function omits the Sweep block of the parameter file, if
* any, in order to allow the output produced during a sweep to refer
* only to parameters relevant to a single state point, and to be
* rerunnable as a parameter file for a single SCFT calculation.
*/
void writeParamNoSweep(std::ostream& out) const;
/**
* Write thermodynamic properties to a file.
*
* This function outputs Helmholtz free energy per monomer, pressure
* (in units of kT per monomer volume), the volume fraction and
* chemical potential of each species, and unit cell parameters.
*
* If parameter "out" is a file that already exists, this function
* will append this information to the end of the file, rather than
* overwriting that file. Calling writeParamNoSweep and writeThermo
* in succession with the same file will thus produce a single file
* containing both input parameters and resulting thermodynanic
* properties.
*
* \param out output stream
*/
void writeThermo(std::ostream& out);
///@}
/// \name Field Output
///@{
/**
* Write chemical potential fields in symmetry adapted basis format.
*
* \param filename name of output file
*/
void writeWBasis(const std::string & filename);
/**
* Write chemical potential fields in real space grid (r-grid) format.
*
* \param filename name of output file
*/
void writeWRGrid(const std::string & filename) const;
/**
* Write concentrations in symmetry-adapted basis format.
*
* \param filename name of output file
*/
void writeCBasis(const std::string & filename);
/**
* Write concentration fields in real space grid (r-grid) format.
*
* \param filename name of output file
*/
void writeCRGrid(const std::string & filename) const;
/**
* Write c fields for all blocks and solvents in r-grid format.
*
* Writes concentrations for all blocks of all polymers and all
* solvent species in r-grid format. Columns associated with blocks
* appear ordered by polymer id and then by block id, followed by
* solvent species ordered by solvent id.
*
* \param filename name of output file
*/
void writeBlockCRGrid(const std::string & filename) const;
///@}
/// \name Propagator Output
///@{
/**
* Write specified slice of a propagator at fixed s in r-grid format.
*
* \param filename name of output file
* \param polymerId integer id of the polymer
* \param blockId integer id of the block within the polymer
* \param directionId integer id of the direction (0 or 1)
* \param segmentId integer integration step index
*/
void writeQSlice(std::string const & filename,
int polymerId, int blockId,
int directionId, int segmentId) const;
/**
* Write the final slice of a propagator in r-grid format.
*
* \param filename name of output file
* \param polymerId integer id of the polymer
* \param blockId integer id of the block within the polymer
* \param directionId integer id of the direction (0 or 1)
*/
void writeQTail(std::string const & filename, int polymerId,
int blockId, int directionId) const;
/**
* Write one propagator for one block, in r-grid format.
*
* \param filename name of output file
* \param polymerId integer id of the polymer
* \param blockId integer id of the block within the polymer
* \param directionId integer id of the direction (0 or 1)
*/
void writeQ(std::string const & filename, int polymerId,
int blockId, int directionId) const;
/**
* Write all propagators of all blocks, each to a separate file.
*
* Write all propagators for both directions for all blocks
* of all polymers, with each propagator in a separate file.
* The function writeQ is called internally for each propagator,
* and is passed an automatically generated file name. The file
* name for each propagator is given by a string of the form
* (basename)_(ip)_(ib)_(id), where (basename) denotes the value
* of the std::string function parameter basename, and where
* (ip), (ib), and (id) denote the string representations of
* a polymer indiex ip, a block index ib, and direction index id,
* with id = 0 or 1. For example, if basename == "out/q", then
* the file name of the propagator for direction 1 of block 2
* of polymer 0 would be "out/q_0_2_1".
*
* \param basename common prefix for output file names
*/
void writeQAll(std::string const & basename);
///@}
/// \name Crystallographic Data Output
///@{
/**
* Output information about stars and symmetrized basis functions.
*
* This function opens a file with the specified filename and then
* calls Basis::outputStars.
*
* \param filename name of output file
*/
void writeStars(const std::string & filename) const;
/**
* Output information about waves.
*
* This function opens a file with the specified filename and then
* calls Basis::outputWaves.
*
* \param filename name of output file
*/
void writeWaves(const std::string & filename) const;
/**
* Output all elements of the space group.
*
* \param filename name of output file
*/
void writeGroup(std::string const & filename) const;
///@}
/// \name Field File Operations
///@{
/**
* Convert a field from symmetry-adapted basis to r-grid format.
*
* This and other field conversion functions do not change the w
* or c fields stored by this System - all required calculations
* are performed using temporary or mutable memory.
*
* \param inFileName name of input file
* \param outFileName name of output file
*/
void basisToRGrid(const std::string & inFileName,
const std::string & outFileName);
/**
* Convert a field from real-space grid to symmetrized basis format.
*
* This function checks if the input fields have the declared space
* group symmetry, and prints a warning if it detects deviations
* that exceed some small threshhold, but proceeds to attempt the
* conversion even if such an error is detected. Converting a field
* that does not have the declared space group symmetry to basis
* format is a destructive operation that modifies the fields.
*
* \param inFileName name of input file
* \param outFileName name of output file
*/
void rGridToBasis(const std::string & inFileName,
const std::string & outFileName);
/**
* Convert fields from Fourier (k-grid) to real-space (r-grid) format.
*
* \param inFileName name of input file
* \param outFileName name of output file
*/
void kGridToRGrid(const std::string& inFileName,
const std::string& outFileName);
/**
* Convert fields from real-space (r-grid) to Fourier (k-grid) format.
*
* \param inFileName name of input file
* \param outFileName name of output file
*/
void rGridToKGrid(const std::string & inFileName,
const std::string & outFileName);
/**
* Convert fields from Fourier (k-grid) to symmetrized basis format.
*
* This function checks if the input fields have the declared space
* group symmetry, and prints a warning if it detects deviations
* that exceed some small threshhold, but proceeds to attempt the
* conversion even if such an error is detected. Converting a field
* that does not have the declared space group symmetry to basis
* format is a destructive operation that modifies the fields.
*
* \param inFileName name of input file
* \param outFileName name of output file
*/
void kGridToBasis(const std::string& inFileName,
const std::string& outFileName);
/**
* Convert fields from symmetrized basis to Fourier (k-grid) format.
*
* \param inFileName name of input file (basis format)
* \param outFileName name of output file (k-grid format)
*/
void basisToKGrid(const std::string & inFileName,
const std::string & outFileName);
///@}
/// \name Member Object Accessors
///@{
/**
* Get container of chemical potential fields.
*/
WFieldContainer<D> const & w() const;
/**
* Get container of monomer concentration / volume fration fields.
*/
CFieldContainer<D> const & c() const;
/**
* Get Mixture by reference.
*/
Mixture<D>& mixture();
/**
* Get interaction (i.e., excess free energy model) by reference.
*/
Interaction & interaction();
/**
* Get interaction (i.e., excess free energy model) by const ref.
*/
Interaction const & interaction() const;
/**
* Get Domain by const reference.
*/
Domain<D> const & domain() const;
/**
* Get the iterator by reference.
*/
Iterator<D>& iterator();
/**
* Get crystal UnitCell by const reference.
*/
UnitCell<D> const & unitCell() const;
/**
* Get spatial discretization Mesh by const reference.
*/
Mesh<D> const & mesh() const;
/**
* Get the Basis by reference.
*/
Basis<D> const & basis() const;
/**
* Get the FieldIo by const reference.
*/
FieldIo<D> const & fieldIo() const;
/**
* Get the FFT object by reference.
*/
FFT<D> const & fft() const ;
/**
* Get homogeneous mixture (for reference calculations).
*/
Homogeneous::Mixture& homogeneous();
/**
* Get FileMaster by reference.
*/
FileMaster& fileMaster();
///@}
/// \name Queries
///@{
/**
* Have monomer concentration fields (c fields) been computed?
*
* Returns true if and only if monomer concentration fields have
* been computed by solving the modified diffusion equation for the
* current w fields.
*/
bool hasCFields() const;
/**
* Does this system have an associated Sweep object?
*/
bool hasSweep() const;
///@}
private:
/**
* Mixture object (solves MDE for all species).
*/
Mixture<D> mixture_;
/**
* Domain object (crystallography and mesh).
*/
Domain<D> domain_;
/**
* Filemaster (holds paths to associated I/O files).
*/
FileMaster fileMaster_;
/**
* Homogeneous mixture, for reference.
*/
Homogeneous::Mixture homogeneous_;
/**
* Pointer to Interaction (excess free energy model).
*/
Interaction* interactionPtr_;
/**
* Pointer to an iterator.
*/
Iterator<D>* iteratorPtr_;
/**
* Pointer to iterator factory object
*/
IteratorFactory<D>* iteratorFactoryPtr_;
/**
* Pointer to an Sweep object
*/
Sweep<D>* sweepPtr_;
/**
* Pointer to SweepFactory object
*/
SweepFactory<D>* sweepFactoryPtr_;
/**
* Chemical potential fields.
*/
WFieldContainer<D> w_;
/**
* Monomer concentration / volume fraction fields.
*/
CFieldContainer<D> c_;
/**
* Work array of field coefficients for all monomer types.
*
* Indexed by monomer typeId, size = nMonomer.
*/
mutable DArray< DArray<double> > tmpFieldsBasis_;
/**
* Work array of fields on real space grid.
*
* Indexed by monomer typeId, size = nMonomer.
*/
mutable DArray< RDField<D> > tmpFieldsRGrid_;
/**
* Work array of fields on Fourier grid (k-grid).
*
* Indexed by monomer typeId, size = nMonomer.
*/
mutable DArray<RDFieldDft<D> > tmpFieldsKGrid_;
/**
* Work array (size = # of grid points).
*/
mutable DArray<double> f_;
/**
* Helmholtz free energy per monomer / kT.
*/
double fHelmholtz_;
/**
* Ideal gas contribution to fHelmholtz_.
*
* This encompasses the internal energy and entropy of
* non-interacting free chains in their corresponding
* potential fields defined by w_.
*/
double fIdeal_;
/**
* Multi-chain interaction contribution to fHelmholtz_.
*/
double fInter_;
/**
* Pressure times monomer volume / kT.
*/
double pressure_;
/**
* Has the mixture been initialized?
*/
bool hasMixture_;
/**
* Has memory been allocated for fields in FFT grid formats?
*/
bool isAllocatedGrid_;
/**
* Has memory been allocated for fields in basis format?
*/
bool isAllocatedBasis_;
/**
* Have C fields been computed for the current w fields?
*/
bool hasCFields_;
/**
* Dimemsions of the k-grid (discrete Fourier transform grid).
*/
IntVec<D> kMeshDimensions_;
/**
* Work array for r-grid field.
*/
RDField<D> workArray_;
// Private member functions
/**
* Allocate memory for fields in grid formats (private).
*
* Can be called when mesh is known.
*/
void allocateFieldsGrid();
/**
* Allocate memory for fields in basis formats (private).
*
* Can be called only after the basis is initialized.
*/
void allocateFieldsBasis();
/**
* Read field file header and initialize unit cell and basis.
*
* \param filename name of field file
*/
void readFieldHeader(std::string filename);
/**
* Read a filename string and echo to log file.
*
* Used to read filenames in readCommands.
*
* \param in input stream (i.e., input file)
* \param string string to read and echo
*/
void readEcho(std::istream& in, std::string& string) const;
/**
* Read a floating point number and echo to log file.
*
* Used to read filenames in readCommands.
*
* \param in input stream (i.e., input file)
* \param value number to read and echo
*/
void readEcho(std::istream& in, double& value) const;
/**
* Initialize Homogeneous::Mixture object (private).
*/
void initHomogeneous();
};
// Inline member functions
// Get the associated Mixture<D> object.
template <int D>
inline Mixture<D>& System<D>::mixture()
{ return mixture_; }
// Get the Interaction (excess free energy model).
template <int D>
inline Interaction & System<D>::interaction()
{
UTIL_ASSERT(interactionPtr_);
return *interactionPtr_;
}
// Get the Interaction (excess free energy model).
template <int D>
inline Interaction const & System<D>::interaction() const
{
UTIL_ASSERT(interactionPtr_);
return *interactionPtr_;
}
template <int D>
inline Domain<D> const & System<D>::domain() const
{ return domain_; }
template <int D>
inline UnitCell<D> const & System<D>::unitCell() const
{ return domain_.unitCell(); }
// get the const Mesh<D> object.
template <int D>
inline Mesh<D> const & System<D>::mesh() const
{ return domain_.mesh(); }
// Get the Basis<D> object.
template <int D>
inline Basis<D> const & System<D>::basis() const
{ return domain_.basis(); }
// Get the FFT<D> object.
template <int D>
inline FFT<D> const & System<D>::fft() const
{ return domain_.fft(); }
// Get the const FieldIo<D> object.
template <int D>
inline FieldIo<D> const & System<D>::fieldIo() const
{ return domain_.fieldIo(); }
// Get the Iterator.
template <int D>
inline Iterator<D>& System<D>::iterator()
{
UTIL_ASSERT(iteratorPtr_);
return *iteratorPtr_;
}
// Get the FileMaster.
template <int D>
inline FileMaster& System<D>::fileMaster()
{ return fileMaster_; }
// Get the Homogeneous::Mixture object.
template <int D>
inline
Homogeneous::Mixture& System<D>::homogeneous()
{ return homogeneous_; }
// Get container of w fields (const reference)
template <int D>
inline
WFieldContainer<D> const & System<D>::w() const
{ return w_; }
// Get container of c fields (const reference)
template <int D>
inline
CFieldContainer<D> const & System<D>::c() const
{ return c_; }
// Get precomputed Helmoltz free energy per monomer / kT.
template <int D>
inline double System<D>::fHelmholtz() const
{ return fHelmholtz_; }
// Get precomputed pressure (units of kT / monomer volume).
template <int D>
inline double System<D>::pressure() const
{ return pressure_; }
// Have the c fields been computed for the current w fields?
template <int D>
inline bool System<D>::hasCFields() const
{ return hasCFields_; }
// Does this system have an associated Sweep object?
template <int D>
inline bool System<D>::hasSweep() const
{ return (sweepPtr_ != 0); }
#ifndef PSPG_SYSTEM_TPP
// Suppress implicit instantiation
extern template class System<1>;
extern template class System<2>;
extern template class System<3>;
#endif
} // namespace Pspg
} // namespace Pscf
//#include "System.tpp"
#endif
| 31,398
|
C++
|
.h
| 869
| 29.255466
| 75
| 0.629624
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,019
|
AmIteratorGrid.h
|
dmorse_pscfpp/src/pspg/iterator/AmIteratorGrid.h
|
#ifndef PSPG_AM_ITERATOR_GRID_H
#define PSPG_AM_ITERATOR_GRID_H
/*
* PSCF - Polymer Self-Consistent Field Theory
*
* Copyright 2016 - 2022, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include "Iterator.h" // base class
#include <pscf/iterator/AmIteratorTmpl.h> // base class template
#include <pscf/iterator/AmbdInteraction.h> // member variable
namespace Pscf {
namespace Pspg
{
template <int D>
class System;
using namespace Util;
/**
* Pspg implementation of the Anderson Mixing iterator.
*
* \ingroup Pspg_Iterator_Module
*/
template <int D>
class AmIteratorGrid : public AmIteratorTmpl<Iterator<D>, FieldCUDA>
{
public:
/**
* Constructor.
*
* \param system parent system object
*/
AmIteratorGrid(System<D>& system);
/**
* Destructor.
*/
~AmIteratorGrid();
/**
* Read all parameters and initialize.
*
* \param in input filestream
*/
void readParameters(std::istream& in);
using AmIteratorTmpl<Iterator<D>,FieldCUDA>::solve;
using Iterator<D>::isFlexible;
protected:
using ParamComposite::readOptional;
using Iterator<D>::system;
using Iterator<D>::isFlexible_;
/**
* Setup iterator just before entering iteration loop.
*
* \param isContinuation Is this a continuation within a sweep?
*/
void setup(bool isContinuation);
private:
/// Local copy of interaction, adapted for use AMBD residual definition
AmbdInteraction interaction_;
/// How are stress residuals scaled in error calculation?
double scaleStress_;
// Virtual functions used to implement AM algorithm
/**
* Set vector a equal to vector b (a = b).
*
* \param a the field to be set (LHS, result)
* \param b the field for it to be set to (RHS, input)
*/
void setEqual(FieldCUDA& a, FieldCUDA const & b);
/**
* Compute and return inner product of two real fields.
*/
double dotProduct(FieldCUDA const & a, FieldCUDA const & b);
/**
* Find the maximum magnitude element of a residual vector.
*
* \param a input vector
*/
double maxAbs(FieldCUDA const & a);
#if 0
/**
* Find norm of a residual vector.
*
* \param a input vector
*/
double norm(FieldCUDA const & a);
/**
* Compute the dot product for an element of the U matrix.
*
* \param resBasis RingBuffer of residual basis vectors.
* \param m row of the U matrix
* \param n column of the U matrix
*/
double computeUDotProd(RingBuffer<FieldCUDA> const & resBasis,
int m, int n);
/**
* Compute the dot product for an element of the v vector.
*
* \param resCurrent current residual vector
* \param resBasis RingBuffer of residual basis vectors
* \param m row index for element of the v vector
*/
double computeVDotProd(FieldCUDA const & resCurrent,
RingBuffer<FieldCUDA> const & resBasis,
int m);
/**
* Update the U matrix.
*
* \param U U matrix (dot products of residual basis vectors)
* \param resBasis RingBuffer residual basis vectors
* \param nHist current number of previous states
*/
void updateU(DMatrix<double> & U,
RingBuffer<FieldCUDA> const & resBasis,
int nHist);
/**
* Update the v vector.
*
* \param v v vector
* \param resCurrent current residual vector
* \param resBasis RingBuffer of residual basis vectors
* \param nHist number of histories stored at this iteration
*/
void updateV(DArray<double> & v,
FieldCUDA const & resCurrent,
RingBuffer<FieldCUDA> const & resBasis,
int nHist);
#endif
/**
* Update the series of residual vectors.
*
* \param basis RingBuffer of basis vectors.
* \param hists RingBuffer of previous vectors.
*/
void updateBasis(RingBuffer<FieldCUDA> & basis,
RingBuffer<FieldCUDA> const & hists);
/**
* Compute trial field so as to minimize L2 norm of residual.
*
* \param trial resulting trial field (output)
* \param basis RingBuffer of residual basis vectors.
* \param coeffs coefficients of basis vectors
* \param nHist number of prior states stored
*/
void addHistories(FieldCUDA& trial,
RingBuffer<FieldCUDA> const & basis,
DArray<double> coeffs, int nHist);
/**
* Add predicted error to the trial field.
*
* \param fieldTrial trial field (input/output)
* \param resTrial predicted error for current trial field
* \param lambda Anderson-Mixing mixing parameter
*/
void addPredictedError(FieldCUDA& fieldTrial,
FieldCUDA const & resTrial,
double lambda);
/// Checks if the system has an initial guess
bool hasInitialGuess();
/**
* Compute the number of elements in field or residual.
*/
int nElements();
/*
* Get the current state of the system.
*
* \param curr current field vector (output)
*/
void getCurrent(FieldCUDA& curr);
/**
* Solve MDE for current state of system.
*/
void evaluate();
/**
* Gets the residual vector from system.
*
* \param curr current residual vector (output)
*/
void getResidual(FieldCUDA& resid);
/**
* Update the system with a new trial field vector.
*
* \param newGuess trial field configuration
*/
void update(FieldCUDA& newGuess);
/**
* Output relevant system details to the iteration log file.
*/
void outputToLog();
// --- Private member functions specific to this implementation ---
cudaReal findAverage(cudaReal const * field, int n);
};
} // namespace Pspg
} // namespace Pscf
#endif
| 6,408
|
C++
|
.h
| 193
| 25.279793
| 77
| 0.608314
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,020
|
Iterator.h
|
dmorse_pscfpp/src/pspg/iterator/Iterator.h
|
#ifndef PSPG_ITERATOR_H
#define PSPG_ITERATOR_H
/*
* PSCF - Polymer Self-Consistent Field Theory
*
* Copyright 2016 - 2022, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include <util/param/ParamComposite.h> // base class
#include <pspg/field/DField.h>
#include <util/global.h>
namespace Pscf {
namespace Pspg
{
template <int D>
class System;
using namespace Util;
typedef DField<cudaReal> FieldCUDA;
/**
* Base class for iterative solvers for SCF equations.
*
* \ingroup Pspg_Iterator_Module
*/
template <int D>
class Iterator : public ParamComposite
{
public:
#if 0
/**
* Default constructor.
*/
Iterator();
#endif
/**
* Constructor.
*
* \param system parent System object
*/
Iterator(System<D>& system);
/**
* Destructor.
*/
~Iterator();
/**
* Iterate to solution.
*
* \param isContinuation true iff continuation within a sweep
* \return error code: 0 for success, 1 for failure.
*/
virtual int solve(bool isContinuation) = 0;
/**
* Is the unit cell flexible (true) or rigid (false).
*/
bool isFlexible() const;
protected:
/// Is the unit cell flexible during iteration?
bool isFlexible_;
/**
* Return reference to parent system.
*/
System<D>& system();
private:
/// Pointer to the associated system object.
System<D>* sysPtr_;
};
// Constructor
template<int D>
inline Iterator<D>::Iterator(System<D>& system)
: isFlexible_(false),
sysPtr_(&system)
{ setClassName("Iterator"); }
// Destructor
template<int D>
inline Iterator<D>::~Iterator()
{}
template<int D>
inline bool Iterator<D>::isFlexible() const
{ return isFlexible_; }
template<int D>
inline System<D>& Iterator<D>::system()
{ return *sysPtr_; }
} // namespace Pspg
} // namespace Pscf
#endif
| 2,086
|
C++
|
.h
| 84
| 19.571429
| 67
| 0.625761
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,021
|
AmIteratorBasis.h
|
dmorse_pscfpp/src/pspg/iterator/AmIteratorBasis.h
|
#ifndef PSPG_AM_ITERATOR_BASIS_H
#define PSPG_AM_ITERATOR_BASIS_H
/*
* PSCF - Polymer Self-Consistent Field Theory
*
* Copyright 2016 - 2022, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include "Iterator.h"
#include <pscf/iterator/AmIteratorTmpl.h>
#include <pscf/iterator/AmbdInteraction.h> // member variable
namespace Pscf {
namespace Pspg
{
template <int D>
class System;
using namespace Util;
/**
* Pspg implementation of the Anderson Mixing iterator.
*
* \ingroup Pspg_Iterator_Module
*/
template <int D>
class AmIteratorBasis : public AmIteratorTmpl<Iterator<D>, DArray<double> >
{
public:
/**
* Constructor.
*
* \param system parent system object
*/
AmIteratorBasis(System<D>& system);
/**
* Destructor.
*/
~AmIteratorBasis();
/**
* Read all parameters and initialize.
*
* \param in input filestream
*/
void readParameters(std::istream& in);
using Iterator<D>::isFlexible;
using AmIteratorTmpl<Iterator<D>, DArray<double> >::solve;
protected:
using ParamComposite::readOptional;
using Iterator<D>::system;
using Iterator<D>::isFlexible_;
using AmIteratorTmpl<Iterator<D>, DArray<double> >::setClassName;
using AmIteratorTmpl<Iterator<D>, DArray<double> >::verbose;
/**
* Setup iterator just before entering iteration loop.
*
* \param isContinuation Is this a continuation within a sweep?
*/
void setup(bool isContinuation);
private:
// Local copy of interaction, adapted for use AMBD residual definition
AmbdInteraction interaction_;
/// How are stress residuals scaled in error calculation?
double scaleStress_;
/**
* Set a vector equal to another (assign a = b)
*
* \param a the field to be set (LHS, result)
* \param b the field for it to be set to (RHS, input)
*/
void setEqual(DArray<double>& a, DArray<double> const & b);
/**
* Compute the inner product of two real vectors.
*/
double dotProduct(DArray<double> const & a, DArray<double> const & b);
/**
* Find the maximum magnitude element of a vector.
*/
double maxAbs(DArray<double> const & hist);
/**
* Update the series of residual vectors.
*
* \param basis RingBuffer of residual or field basis vectors
* \param hists RingBuffer of pase residual or field vectors
*/
void updateBasis(RingBuffer< DArray<double> > & basis,
RingBuffer< DArray<double> > const & hists);
/**
* Compute trial field so as to minimize L2 norm of residual.
*
* \param trial resulting trial field (output)
* \param basis RingBuffer of residual basis vectors.
* \param coeffs coefficients of basis vectors
* \param nHist number of prior states stored
*/
void addHistories(DArray<double>& trial,
RingBuffer<DArray<double> > const & basis,
DArray<double> coeffs, int nHist);
/**
* Add predicted error to the trial field.
*
* \param fieldTrial trial field (input/output)
* \param resTrial predicted error for current trial field
* \param lambda Anderson-Mixing mixing parameter
*/
void addPredictedError(DArray<double>& fieldTrial,
DArray<double> const & resTrial,
double lambda);
/// Checks if the system has an initial guess
bool hasInitialGuess();
/**
* Compute the number of elements in field or residual.
*/
int nElements();
/*
* Get the current state of the system.
*
* \param curr current field vector (output)
*/
void getCurrent(DArray<double>& curr);
/**
* Solve MDE for current state of system.
*/
void evaluate();
/**
* Gets the residual vector from system.
*
* \param curr current residual vector (output)
*/
void getResidual(DArray<double>& resid);
/**
* Update the system with a new trial field vector.
*
* \param newGuess trial field configuration
*/
void update(DArray<double>& newGuess);
/**
* Output relevant system details to the iteration log file.
*/
void outputToLog();
// --- Private member functions specific to this implementation ---
cudaReal findAverage(cudaReal * const field, int n);
};
} // namespace Pspg
} // namespace Pscf
#endif
| 4,761
|
C++
|
.h
| 143
| 26.06993
| 78
| 0.627159
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,022
|
IteratorFactory.h
|
dmorse_pscfpp/src/pspg/iterator/IteratorFactory.h
|
#ifndef PSPG_ITERATOR_FACTORY_H
#define PSPG_ITERATOR_FACTORY_H
/*
* PSCF - Polymer Self-Consistent Field Theory
*
* Copyright 2016 - 2022, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include <util/param/Factory.h>
#include <pspg/iterator/Iterator.h>
#include <pspg/System.h>
#include <string>
namespace Pscf {
namespace Pspg {
using namespace Util;
/**
* Factory for subclasses of Iterator.
*
* \ingroup Pspg_Iterator_Module
*/
template <int D>
class IteratorFactory : public Factory< Iterator<D> >
{
public:
/// Constructor
IteratorFactory(System<D>& system);
/**
* Method to create any Iterator supplied with PSCF.
*
* \param className name of the Iterator subclass
* \return Iterator* pointer to new instance of className
*/
Iterator<D>* factory(const std::string &className) const;
using Factory< Iterator<D> >::trySubfactories;
private:
/// Pointer to the system object.
System<D>* sysPtr_;
};
#ifndef PSPG_ITERATOR_FACTORY_TPP
// Suppress implicit instantiation
extern template class IteratorFactory<1>;
extern template class IteratorFactory<2>;
extern template class IteratorFactory<3>;
#endif
}
}
#endif
| 1,326
|
C++
|
.h
| 47
| 24.12766
| 67
| 0.70863
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,023
|
Polymer.h
|
dmorse_pscfpp/src/pspg/solvers/Polymer.h
|
#ifndef PSPG_POLYMER_H
#define PSPG_POLYMER_H
/*
* PSCF - Polymer Self-Consistent Field Theory
*
* Copyright 2016 - 2022, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include "Block.h"
#include <pspg/field/RDField.h>
#include <pscf/solvers/PolymerTmpl.h>
#include <util/containers/FArray.h>
namespace Pscf {
namespace Pspg {
/**
* Descriptor and solver for a branched polymer species.
*
* The block concentrations stored in the constituent Block<D>
* objects contain the block concentrations (i.e., volume
* fractions) computed in the most recent call of the compute
* function.
*
* The phi() and mu() accessor functions, which are inherited
* from PolymerTmp< Block<D> >, return the value of phi (spatial
* average volume fraction of a species) or mu (chemical
* potential) computed in the last call of the compute function.
* If the ensemble for this species is closed, phi is read from
* the parameter file and mu is computed. If the ensemble is
* open, mu is read from the parameter file and phi is computed.
*
* \ingroup Pspg_Solvers_Module
*/
template <int D>
class Polymer : public PolymerTmpl< Block<D> >
{
public:
/**
* Alias for base class.
*/
typedef PolymerTmpl< Block<D> > Base;
/*
* Constructor.
*/
Polymer();
/*
* Destructor.
*/
~Polymer();
/*
* Set the phi (volume fraction) for this species.
*
* \param phi volume fraction (input)
*/
void setPhi(double phi);
/*
* Set the mu (chemical potential) for this species.
*
* \param mu chemical potential (input)
*/
void setMu(double mu);
/**
* Compute solution to MDE and concentrations.
*
* \param unitCell crystallographic unit cell (input)
* \param wavelist precomputed wavevector data (input)
*/
void setupUnitCell(UnitCell<D> const & unitCell,
WaveList<D> const & wavelist);
/**
* Compute solution to MDE and concentrations.
*
* \param wFields chemical potential fields for all monomers (input)
*/
void compute(DArray< RDField<D> > const & wFields);
/**
* Compute stress from a polymer chain, needs a pointer to basis
*
* \param wavelist precomputed wavevector data (input)
*/
void computeStress(WaveList<D> const & wavelist);
/**
* Get derivative of free energy w/ respect to a unit cell parameter.
*
* Get the contribution from this polymer species to the derivative of
* free energy per monomer with respect to unit cell parameter n.
*
* \param n unit cell parameter index
*/
double stress(int n);
// public inherited functions with non-dependent names
using Base::nBlock;
using Base::block;
using Base::ensemble;
using Base::solve;
using Base::length;
protected:
// protected inherited function with non-dependent names
using ParamComposite::setClassName;
private:
// Stress contribution from this polymer species.
FArray<double, 6> stress_;
// Number of unit cell parameters.
int nParams_;
using Base::phi_;
using Base::mu_;
};
template <int D>
double Polymer<D>::stress(int n)
{ return stress_[n]; }
#ifndef PSPG_POLYMER_TPP
// Suppress implicit instantiation
extern template class Polymer<1>;
extern template class Polymer<2>;
extern template class Polymer<3>;
#endif
}
}
//#include "Polymer.tpp"
#endif
| 3,713
|
C++
|
.h
| 119
| 25.420168
| 75
| 0.65376
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,024
|
WaveList.h
|
dmorse_pscfpp/src/pspg/solvers/WaveList.h
|
#ifndef PSPG_WAVE_LIST_H
#define PSPG_WAVE_LIST_H
/*
* PSCF - Polymer Self-Consistent Field Theory
*
* Copyright 2016 - 2022, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include <pscf/math/IntVec.h>
#include <pspg/field/RDFieldDft.h>
#include <pspg/field/RDField.h>
#include <pscf/mesh/MeshIterator.h>
#include <pscf/mesh/Mesh.h>
#include <pscf/crystal/shiftToMinimum.h>
#include <pscf/crystal/UnitCell.h>
#include <util/containers/DArray.h>
#include <util/containers/GArray.h>
#include <util/containers/DMatrix.h>
namespace Pscf {
namespace Pspg
{
using namespace Util;
/**
* Container for wavevector data.
*/
template <int D>
class WaveList{
public:
/**
* Constructor.
*/
WaveList();
/**
* Destructor
*/
~WaveList();
/**
* Allocate memory for all arrays. Call in readParameters.
*
* \param mesh spatial discretization mesh (input)
* \param unitCell crystallographic unit cell (input)
*/
void allocate(Mesh<D> const & mesh,
UnitCell<D> const & unitCell);
/**
* Compute minimum images of wavevectors.
*
* This is only done once, at beginning, using mesh and the initial
* unit cell. This can also be called in the readParameters function.
*
* \param mesh spatial discretization Mesh<D> object
* \param unitCell crystallographic UnitCell<D> object
*/
void computeMinimumImages(Mesh<D> const & mesh,
UnitCell<D> const & unitCell);
/**
* Compute square norm |k|^2 for all wavevectors.
*
* Called once per iteration with unit cell relaxation.
* Implementation can copy geometric data (rBasis, kBasis, etc.)
* into local data structures and implement the actual
* calculation of kSq or dKSq for each wavevector on the GPU.
*
* \param unitCell crystallographic UnitCell<D>
*/
void computeKSq(UnitCell<D> const & unitCell);
/**
* Compute derivatives of |k|^2 w/ respect to unit cell parameters.
*
* Called once per iteration with unit cell relaxation.
*
* \param unitCell crystallographic UnitCell<D>
*/
void computedKSq(UnitCell<D> const & unitCell);
/**
* Get the minimum image vector for a specified wavevector.
*
* \param i index for wavevector
*/
const IntVec<D>& minImage(int i) const;
/**
* Get a pointer to the kSq array on device.
*/
cudaReal* kSq() const;
/**
* Get a pointer to the dkSq array on device.
*/
cudaReal* dkSq() const;
/**
* Get size of k-grid (number of wavewavectors).
*/
int kSize() const;
bool isAllocated() const
{ return isAllocated_; }
bool hasMinimumImages() const
{ return hasMinimumImages_; }
private:
// Bare C array holding precomputed minimum images
int* minImage_d;
// Bare C array holding values of kSq_
cudaReal* kSq_;
// Bare C array holding values of dkSq_
cudaReal* dkSq_;
cudaReal* dkkBasis_d;
cudaReal* dkkBasis;
int* partnerIdTable;
int* partnerIdTable_d;
int* selfIdTable;
int* selfIdTable_d;
bool* implicit;
bool* implicit_d;
IntVec<D> dimensions_;
int kSize_;
int rSize_;
int nParams_;
DArray< IntVec<D> > minImage_;
bool isAllocated_;
bool hasMinimumImages_;
};
template <int D>
inline const IntVec<D>& WaveList<D>::minImage(int i) const
{ return minImage_[i]; }
template <int D>
inline cudaReal* WaveList<D>::kSq() const
{ return kSq_; }
template <int D>
inline cudaReal* WaveList<D>::dkSq() const
{ return dkSq_; }
template <int D>
inline int WaveList<D>::kSize() const
{ return kSize_; }
#ifndef PSPG_WAVE_LIST_TPP
// Suppress implicit instantiation
extern template class WaveList<1>;
extern template class WaveList<2>;
extern template class WaveList<3>;
#endif
}
}
//#include "WaveList.tpp"
#endif
| 4,217
|
C++
|
.h
| 141
| 23.985816
| 74
| 0.639693
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,025
|
Propagator.h
|
dmorse_pscfpp/src/pspg/solvers/Propagator.h
|
#ifndef PSPG_PROPAGATOR_H
#define PSPG_PROPAGATOR_H
/*
* PSCF - Polymer Self-Consistent Field Theory
*
* Copyright 2016 - 2022, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include <pscf/solvers/PropagatorTmpl.h> // base class template
#include <pspg/field/RDField.h> // member template
#include <util/containers/DArray.h> // member template
namespace Pscf { template <int D> class Mesh; }
namespace Pscf {
namespace Pspg
{
template <int D> class Block;
using namespace Util;
/**
* MDE solver for one-direction of one block.
*
* A fully initialized Propagator<D> has an association with a
* Block<D> that owns this propagator and its partner, and has an
* association with a Mesh<D> that describes a spatial grid, in
* addition to associations with partner and source Propagator<D>
* objects that are managed by the PropagatorTmpl base class template.
*
* The associated Block<D> stores information required to numerically
* solve the modified diffusion equation (MDE), including the contour
* step size ds and all parameters that depend on ds. These quantities
* are set and stored by the block because their values must be the
* same for the two propagators owned by each block (i.e., this
* propagator and its partner). The algorithm used by a propagator
* to solve the the MDE simply repeatedly calls the step() function
* of the associated block, because that function has access to all
* the parameters used in the numerical solution.
*
* \ingroup Pspg_Solvers_Module
*/
template <int D>
class Propagator : public PropagatorTmpl< Propagator<D> >
{
public:
// Public typedefs
/**
* Generic field (function of position).
*/
typedef RDField<D> Field;
/**
* Chemical potential field type.
*/
typedef RDField<D> WField;
/**
* Monomer concentration field type.
*/
typedef RDField<D> CField;
/**
* Propagator q-field type.
*/
typedef RDField<D> QField;
// Member functions
/**
* Constructor.
*/
Propagator();
/**
* Destructor.
*/
~Propagator();
/**
* Associate this propagator with a block.
*
* \param block associated Block object.
*/
void setBlock(Block<D>& block);
/**
* Associate this propagator with a block.
*
* \param ns number of contour length steps
* \param mesh spatial discretization mesh
*/
void allocate(int ns, const Mesh<D>& mesh);
/**
* Solve the modified diffusion equation (MDE) for this block.
*
* This function computes an initial QField at the head of this
* propagator, and then solves the modified diffusion equation for
* the block to propagate from the head to the tail. The initial
* QField at the head is computed by pointwise multiplication of
* of the tail QFields of all source propagators.
*/
void solve();
/**
* Solve the MDE for a specified initial condition.
*
* This function solves the modified diffusion equation for this
* block with a specified initial condition, which is given by head
* parameter of the function. The function is intended for use in
* testing.
*
* \param head initial condition of QField at head of block
*/
void solve(const cudaReal * head);
/**
* Compute and return partition function for the molecule.
*
* This function computes the partition function Q for the molecule
* as a spatial average of the product of the initial / head Qfield
* for this propagator and the final / tail Qfield of its partner.
*/
double computeQ();
/**
* Return q-field at specified step.
*
* \param i step index
*/
const cudaReal* q(int i) const;
/**
* Return q-field at beginning of block (initial condition).
*/
cudaReal* head() const;
/**
* Return q-field at end of block.
*/
const cudaReal* tail() const;
/**
* Get the associated Block object by reference.
*/
Block<D>& block();
/**
* Get the associated Block object by const reference.
*/
Block<D> const & block() const;
/**
* Get the number of contour grid points.
*/
int ns() const;
/**
* Has memory been allocated for this propagator?
*/
bool isAllocated() const;
using PropagatorTmpl< Propagator<D> >::nSource;
using PropagatorTmpl< Propagator<D> >::source;
using PropagatorTmpl< Propagator<D> >::partner;
using PropagatorTmpl< Propagator<D> >::setIsSolved;
using PropagatorTmpl< Propagator<D> >::isSolved;
using PropagatorTmpl< Propagator<D> >::hasPartner;
protected:
/**
* Compute initial QField at head from tail QFields of sources.
*/
void computeHead();
private:
// new array purely in device
cudaReal* qFields_d;
// Workspace
// removing this. Does not seem to be used anywhere
//QField work_;
/// Pointer to associated Block.
Block<D>* blockPtr_;
/// Pointer to associated Mesh
Mesh<D> const * meshPtr_;
/// Number of contour length steps = # grid points - 1.
int ns_;
/// Is this propagator allocated?
bool isAllocated_;
/// Work arrays for inner product.
cudaReal* d_temp_;
cudaReal* temp_;
};
// Inline member functions
/*
* Return q-field at beginning of block.
*/
template <int D>
inline
cudaReal* Propagator<D>::head() const
{ return qFields_d; }
/*
* Return q-field at end of block, after solution.
*/
template <int D>
inline
const cudaReal* Propagator<D>::tail() const
{ return qFields_d + ((ns_-1) * meshPtr_->size()); }
/*
* Return q-field at specified step.
*/
template <int D>
inline
const cudaReal* Propagator<D>::q(int i) const
{ return qFields_d + (i * meshPtr_->size()); }
/*
* Get the associated Block object (non-const reference)
*/
template <int D>
inline
Block<D>& Propagator<D>::block()
{
assert(blockPtr_);
return *blockPtr_;
}
/*
* Get the associated Block object (non-const reference)
*/
template <int D>
inline
Block<D> const & Propagator<D>::block() const
{
assert(blockPtr_);
return *blockPtr_;
}
/*
* Get the number ns of contour grid points.
*/
template <int D>
inline
int Propagator<D>::ns() const
{ return ns_; }
template <int D>
inline
bool Propagator<D>::isAllocated() const
{ return isAllocated_; }
/*
* Associate this propagator with a block and direction
*/
template <int D>
inline
void Propagator<D>::setBlock(Block<D>& block)
{ blockPtr_ = █ }
#ifndef PSPG_PROPAGATOR_TPP
// Suppress implicit instantiation
extern template class Propagator<1>;
extern template class Propagator<2>;
extern template class Propagator<3>;
#endif
}
}
//#include "Propagator.tpp"
#endif
| 7,335
|
C++
|
.h
| 239
| 24.941423
| 73
| 0.641579
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,026
|
Block.h
|
dmorse_pscfpp/src/pspg/solvers/Block.h
|
#ifndef PSPG_BLOCK_H
#define PSPG_BLOCK_H
/*
* PSCF - Polymer Self-Consistent Field Theory
*
* Copyright 2016 - 2022, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include "Propagator.h" // base class argument
#include <pscf/solvers/BlockTmpl.h> // base class template
#include <pspg/field/RDField.h> // member
#include <pspg/field/RDFieldDft.h> // member
#include <pspg/field/FFT.h> // member
#include <pspg/field/FFTBatched.h> // member
#include <util/containers/FArray.h>
#include <pscf/crystal/UnitCell.h>
#include <pspg/solvers/WaveList.h>
namespace Pscf {
template <int D> class Mesh;
namespace Pspg {
using namespace Util;
/**
* Block within a branched polymer.
*
* Derived from BlockTmpl<Propagator<D>>. A BlockTmpl<Propagator<D>>
* has two Propagator<D> members and is derived from BlockDescriptor.
*
* \ingroup Pspg_Solvers_Module
*/
template <int D>
class Block : public BlockTmpl< Propagator<D> >
{
public:
/**
* Constructor.
*/
Block();
/**
* Destructor.
*/
~Block();
/**
* Initialize discretization and allocate required memory.
*
* \param ds desired (optimal) value for contour length step
* \param mesh spatial discretization mesh
*/
void setDiscretization(double ds, const Mesh<D>& mesh);
/**
* Setup parameters that depend on the unit cell.
*
* \param unitCell unit cell, defining cell dimensions (input)
* \param waveList container for properties of wavevectors (input)
*/
void setupUnitCell(UnitCell<D> const & unitCell,
WaveList<D> const & waveList);
/**
* Set or reset block length.
*
* \param length new block length
*/
void setLength(double length);
/**
* Set or reset monomer statistical segment length.
*
* \param kuhn new monomer statistical segment length.
*/
void setKuhn(double kuhn);
/**
* Set solver for this block.
*
* \param w chemical potential field for this monomer type
*/
void setupSolver(RDField<D> const & w);
/**
* Initialize FFT and batch FFT classes.
*/
void setupFFT();
/**
* Compute step of integration loop, from i to i+1.
*
* \param q pointer to current slice of propagator q (input)
* \param qNew pointer to current slice of propagator q (output)
*/
void step(cudaReal const * q, cudaReal* qNew);
/**
* Compute unnormalized concentration for block by integration.
*
* Upon return, grid point r of array cField() contains the
* integral int ds q(r,s)q^{*}(r,L-s) times the prefactor,
* where q(r,s) is the solution obtained from propagator(0),
* and q^{*} is the solution of propagator(1), and s is
* a contour variable that is integrated over the domain
* 0 < s < length(), where length() is the block length.
*
* \param prefactor constant prefactor multiplying integral
*/
void computeConcentration(double prefactor);
/**
* Compute derivatives of free energy w/ respect to cell parameters.
*
* The prefactor is the same as that used in computeConcentration.
*
* \param waveList container for properties of wavevectors
* \param prefactor constant prefactor multiplying integral
*/
void computeStress(WaveList<D> const & waveList, double prefactor);
/**
* Get derivative of free energy w/ respect to a unit cell parameter.
*
* \param n unit cell parameter index
*/
double stress(int n);
/**
* Return associated spatial Mesh by const reference.
*/
Mesh<D> const & mesh() const;
/**
* Contour length step size.
*/
double ds() const;
/**
* Number of contour length steps.
*/
int ns() const;
// Functions with non-dependent names from BlockTmpl<Propagator<D>>
using BlockTmpl< Pscf::Pspg::Propagator<D> >::setKuhn;
using BlockTmpl< Pscf::Pspg::Propagator<D> >::propagator;
using BlockTmpl< Pscf::Pspg::Propagator<D> >::cField;
using BlockTmpl< Pscf::Pspg::Propagator<D> >::length;
using BlockTmpl< Pscf::Pspg::Propagator<D> >::kuhn;
// Functions with non-dependent names from BlockDescriptor
using BlockDescriptor::setId;
using BlockDescriptor::setVertexIds;
using BlockDescriptor::setMonomerId;
using BlockDescriptor::setLength;
using BlockDescriptor::id;
using BlockDescriptor::monomerId;
using BlockDescriptor::vertexIds;
using BlockDescriptor::vertexId;
using BlockDescriptor::length;
private:
/// Number of GPU blocks, set in setDiscretization
int nBlocks_;
/// Number of GPU threads per block, set in setDiscretization
int nThreads_;
/// Fourier transform plan
FFT<D> fft_;
/// Batched FFT, used in computeStress
FFTBatched<D> fftBatched_;
/// Stress conntribution from this block
FArray<double, 6> stress_;
// Array of elements containing exp(-K^2 b^2 ds/6) on k-grid
RDField<D> expKsq_;
// Array of elements containing exp(-K^2 b^2 ds/12) on k-grid
RDField<D> expKsq2_;
// Array of elements containing exp(-W[i] ds/2) on r-grid
RDField<D> expW_;
// Array of elements containing exp(-W[i] ds/4) on r-grid
RDField<D> expW2_;
// Work arrays for r-grid fields
RDField<D> qr_;
RDField<D> qr2_;
// Work arrays for wavevector space (k-grid) field
RDFieldDft<D> qk_;
RDFieldDft<D> qk2_;
// Batched FFTs of q
cudaComplex* qkBatched_;
cudaComplex* qk2Batched_;
// Propagators on r-grid
RDField<D> q1_;
RDField<D> q2_;
cudaReal* d_temp_;
cudaReal* temp_;
cudaReal* expKsq_host;
cudaReal* expKsq2_host;
/// Pointer to associated Mesh<D> object.
Mesh<D> const * meshPtr_;
/// Pointer to associated UnitCell<D> object.
UnitCell<D> const* unitCellPtr_;
/// Pointer to associated WaveList<D> object.
WaveList<D> const * waveListPtr_;
/// Dimensions of wavevector mesh in real-to-complex transform
IntVec<D> kMeshDimensions_;
/// Number of wavevectors in discrete Fourier transform (DFT) k-grid
int kSize_;
/// Contour length step size.
double ds_;
/// Number of contour length steps = # s nodes - 1.
int ns_;
/// Have arrays been allocated in setDiscretization ?
bool isAllocated_;
/// Are expKsq_ arrays up to date ? (initialize false)
bool hasExpKsq_;
/// Get associated UnitCell<D> as const reference.
UnitCell<D> const & unitCell() const
{ return *unitCellPtr_; }
/// Get the Wavelist as const reference
WaveList<D> const & wavelist() const
{ return *waveListPtr_; }
/// Number of unit cell parameters
int nParams_;
/**
* Compute expKSq_ arrays.
*/
void computeExpKsq();
};
// Inline member functions
/// Get number of contour steps.
template <int D>
inline int Block<D>::ns() const
{ return ns_; }
/// Get number of contour steps.
template <int D>
inline double Block<D>::ds() const
{ return ds_; }
/// Get derivative of free energy w/ respect to a unit cell parameter.
template <int D>
inline double Block<D>::stress(int n)
{ return stress_[n]; }
/// Get Mesh by reference.
template <int D>
inline Mesh<D> const & Block<D>::mesh() const
{
UTIL_ASSERT(meshPtr_);
return *meshPtr_;
}
#ifndef PSPG_BLOCK_TPP
// Suppress implicit instantiation
extern template class Block<1>;
extern template class Block<2>;
extern template class Block<3>;
#endif
}
}
//#include "Block.tpp"
#endif
| 8,153
|
C++
|
.h
| 237
| 27.966245
| 74
| 0.634436
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,027
|
Mixture.h
|
dmorse_pscfpp/src/pspg/solvers/Mixture.h
|
#ifndef PSPG_MIXTURE_H
#define PSPG_MIXTURE_H
/*
* PSCF - Polymer Self-Consistent Field Theory
*
* Copyright 2016 - 2022, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include "Polymer.h"
#include "Solvent.h"
#include <pscf/solvers/MixtureTmpl.h>
#include <pscf/inter/Interaction.h>
#include <util/containers/DArray.h>
namespace Pscf {
template <int D> class Mesh;
}
namespace Pscf {
namespace Pspg
{
/**
* Solver for a mixture of polymers and solvents.
*
* A Mixture contains a list of Polymer and Solvent objects. Each
* such object can solve the single-molecule statistical mechanics
* problem for an ideal gas of the associated species in a set of
* specified chemical potential fields, and thereby compute
* concentrations and single-molecule partition functions. A
* Mixture is thus both a chemistry descriptor and an ideal-gas
* solver.
*
* A Mixture is associated with a Mesh<D> object, which models a
* spatial discretization mesh.
*
* \ingroup Pspg_Solvers_Module
*/
template <int D>
class Mixture : public MixtureTmpl< Polymer<D>, Solvent<D> >
{
public:
/**
* Constructor.
*/
Mixture();
/**
* Destructor.
*/
~Mixture();
/**
* Read all parameters and initialize.
*
* This function reads in a complete description of
* the chemical composition and structure of all species,
* as well as the target contour length step size ds.
*
* \param in input parameter stream
*/
void readParameters(std::istream& in);
/**
* Create an association with the mesh and allocate memory.
*
* The Mesh<D> object must have already been initialized,
* e.g., by reading its parameters from a file, so that the
* mesh dimensions are known on entry.
*
* \param mesh associated Mesh<D> object (stores address).
*/
void setMesh(Mesh<D> const & mesh);
/**
* Set unit cell parameters used in solver.
*
* \param unitCell crystallographic unit cell
* \param waveList container for wavevector data
*/
void setupUnitCell(UnitCell<D> const & unitCell,
WaveList<D> const & waveList);
/**
* Reset statistical segment length for one monomer type.
*
* This function resets the kuhn or statistical segment length value
* for a monomer type, and updates the associcated value in every
* block of that monomer type.
*
* \param monomerId monomer type id
* \param kuhn new value for the statistical segment length
*/
void setKuhn(int monomerId, double kuhn);
/**
* Compute concentrations.
*
* This function calls the compute function of every molecular
* species, and then adds the resulting block concentration
* fields for blocks of each type to compute a total monomer
* concentration (or volume fraction) for each monomer type.
* Upon return, values are set for volume fraction and chemical
* potential (mu) members of each species, and for the
* concentration fields for each Block and Solvent. The total
* concentration for each monomer type is returned in the
* cFields output parameter.
*
* The arrays wFields and cFields must each have size nMonomer(),
* and contain fields that are indexed by monomer type index.
*
* \param wFields array of chemical potential fields (input)
* \param cFields array of monomer concentration fields (output)
*/
void
compute(DArray< RDField<D> > const & wFields,
DArray< RDField<D> > & cFields);
/**
* Get monomer reference volume.
*
* \param waveList container for wavevector data
*/
void computeStress(WaveList<D> const & waveList);
/**
* Combine cFields for each block/solvent into one DArray.
*
* The array created by this function is used by the command
* WRITE_C_BLOCK_RGRID to write c-fields for all blocks and
* species.
*
* \param blockCFields empty but allocated DArray to store fields
*/
void createBlockCRGrid(DArray< RDField<D> >& blockCFields) const;
/**
* Get derivative of free energy w/ respect to cell parameter.
*
* Get precomputed value of derivative of free energy per monomer
* with respect to unit cell parameter number n.
*
* \param parameterId unit cell parameter index
*/
double stress(int parameterId) const;
#if 0
/**
* Get monomer reference volume.
*/
double vMonomer() const;
#endif
/**
* Is the ensemble canonical (i.e, closed for all species)?
*
* Return true if and only if the ensemble is closed for all polymer
* and solvent species.
*/
bool isCanonical();
// Public members from MixtureTmpl with non-dependent names
using MixtureTmpl< Polymer<D>, Solvent<D> >::nMonomer;
using MixtureTmpl< Polymer<D>, Solvent<D> >::nPolymer;
using MixtureTmpl< Polymer<D>, Solvent<D> >::nSolvent;
using MixtureTmpl< Polymer<D>, Solvent<D> >::nBlock;
using MixtureTmpl< Polymer<D>, Solvent<D> >::polymer;
using MixtureTmpl< Polymer<D>, Solvent<D> >::monomer;
using MixtureTmpl< Polymer<D>, Solvent<D> >::solvent;
protected:
// Public members from MixtureTmpl with non-dependent names
using MixtureTmpl< Polymer<D>, Solvent<D> >::setClassName;
using ParamComposite::read;
using ParamComposite::readOptional;
private:
/// Derivatives of free energy w/ respect to cell parameters.
FArray<double, 6> stress_;
#if 0
/// Monomer reference volume (set to 1.0 by default).
double vMonomer_;
#endif
/// Optimal contour length step size.
double ds_;
/// Number of unit cell parameters.
int nUnitCellParams_;
/// Pointer to associated Mesh<D> object.
Mesh<D> const * meshPtr_;
/// Has the stress been computed?
bool hasStress_;
/// Return associated domain by reference.
Mesh<D> const & mesh() const;
};
// Inline member function
#if 0
/*
* Get monomer reference volume (public).
*/
template <int D>
inline double Mixture<D>::vMonomer() const
{ return vMonomer_; }
#endif
/*
* Get Mesh<D> by constant reference (private).
*/
template <int D>
inline Mesh<D> const & Mixture<D>::mesh() const
{
UTIL_ASSERT(meshPtr_);
return *meshPtr_;
}
/*
* Get derivative of free energy w/ respect to cell parameter.
*/
template <int D>
inline double Mixture<D>::stress(int parameterId) const
{
UTIL_CHECK(hasStress_);
return stress_[parameterId];
}
#ifndef PSPG_MIXTURE_TPP
// Suppress implicit instantiation
extern template class Mixture<1>;
extern template class Mixture<2>;
extern template class Mixture<3>;
#endif
} // namespace Pspg
} // namespace Pscf
//#include "Mixture.tpp"
#endif
| 7,251
|
C++
|
.h
| 214
| 27.775701
| 74
| 0.656706
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,028
|
Solvent.h
|
dmorse_pscfpp/src/pspg/solvers/Solvent.h
|
#ifndef PSPG_SOLVENT_H
#define PSPG_SOLVENT_H
/*
* PSCF - Polymer Self-Consistent Field Theory
*
* Copyright 2016 - 2022, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include <pscf/chem/SolventDescriptor.h> // base class
#include <pspg/solvers/Propagator.h> // typedefs
#include <pspg/field/RDField.h>
namespace Pscf {
template <int D> class Mesh;
}
namespace Pscf {
namespace Pspg {
using namespace Util;
/**
* Solver and descriptor for a solvent species.
*
* \ingroup Pspg_Solvers_Module
*/
template <int D>
class Solvent : public SolventDescriptor
{
public:
/**
* Constructor.
*/
Solvent();
/**
* Destructor.
*/
~Solvent();
/**
* Set association with Mesh, allocate memory.
*
* \param mesh associated Mesh<D> object (input)
*/
void setDiscretization(Mesh<D> const & mesh);
/**
* Compute monomer concentration field and phi and/or mu.
*
* Upon return, concentration field, phi and mu are all set.
*
* \param wField monomer chemical potential field
*/
void compute(RDField<D> const & wField );
/**
* Get the monomer concentration field for this solvent.
*/
RDField<D> const & concField() const;
// Inherited public accessor functions
using Pscf::Species::phi;
using Pscf::Species::mu;
using Pscf::Species::q;
using Pscf::Species::ensemble;
using Pscf::SolventDescriptor::monomerId;
using Pscf::SolventDescriptor::size;
protected:
// Inherited protected data members
using Pscf::Species::phi_;
using Pscf::Species::mu_;
using Pscf::Species::q_;
using Pscf::Species::ensemble_;
using Pscf::SolventDescriptor::monomerId_;
using Pscf::SolventDescriptor::size_;
private:
/// Concentration field for this solvent
RDField<D> concField_;
/// Pointer to associated mesh
Mesh<D> const * meshPtr_;
};
/*
* Get monomer concentration field for this solvent.
*/
template <int D>
inline RDField<D> const & Solvent<D>::concField() const
{ return concField_; }
}
}
#endif
| 2,295
|
C++
|
.h
| 82
| 22.585366
| 67
| 0.647409
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,029
|
SweepParameter.h
|
dmorse_pscfpp/src/pspg/sweep/SweepParameter.h
|
#ifndef PSPG_SWEEP_PARAMETER_H
#define PSPG_SWEEP_PARAMETER_H
/*
* PSCF - Polymer Self-Consistent Field Theory
*
* Copyright 2016 - 2022, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include <iostream>
namespace Pscf {
namespace Pspg {
template <int D> class System;
/**
* Class for storing data about an individual sweep parameter.
*
* This class stores the information required to sweep a single
* parameter value of any of several types. The type of parameter
* is indicated in the public interface and parameter file format
* by a string identifier with any of several allowed values.
* Each parameter is also identified by one or two associated index
* values, denoted here by id(0) and id(1), that specify the index
* or indices for a subobject or array element with which the
* parameter is associated applied. Allowed string representations
* and meanings of parameter types are given below, along with the
* meaning of any associated index value or pair of values.
* To indicate the meaning of index values, we use mId to denote
* a monomer type index, pId to denote a polymer species index,
* bId to denote the index of a block within a polymer, sId to
* denote a solvent species index, and lId to denote a lattice
* parameter index:
* \code
* | Type | Meaning | id(0) | id(1)
* | ----------- | --------------------------- | ----- | -----
* | kuhn | monomer segment length | mId |
* | chi | Flory-Huggins parameter | mId | mId
* | block | block length | pId | bId
* | solvent | solvent size | sId |
* | phi_polymer | polymer volume fraction | pId |
* | mu_polymer | polymer chemical potential | pId |
* | phi_solvent | solvent volume fraction | sId |
* | mu_solvent | solvent chemical potential | sId |
* | cell_param | lattice parameter | lId |
* \endcode
* The two indices for a Flory-Huggins chi parameter refer to indices
* in the chi matrix maintained by Interaction. Changes to element
* chi(i, j) automatically also update chi(j, i) for i !\ j, thus
* maintaining the symmetry of the matrix.
*
* Each SweepParameter also has a "change" value that gives the
* intended difference between the final and initial value of the
* parameter over the course of a sweep, corresponding to a change
* sweep parameter s over the range [0,1]. The initial value of each
* parameter is obtained from a query of the state of the parent
* system at the beginning of a sweep, and thus does not need to
* be supplied as part of the text format for a SweepParameter.
*
* A SweepParameter<D> object is initialized by reading the parameter
* type, index or index and change value from a parameter file as a
* a single line. An overloaded >> operator is defined that allows
* a SweepParameter<D> object named "parameter" to be read from an
* istream named "in" using the syntax "in >> parameter".
*
* The text format for a parameter of a type that requires a single
* index id(0) is:
*
* type id(0) change
*
* where type indicates a type string, id(0) is an integer index value,
* and change is the a floating point value for the change in parameter
* value. The corresponding format for a parameter that requires two
* indices (e.g., block or chi) is instead: "type id(0) id(1) change".
*
* \ingroup Pspg_Sweep_Module
*/
template <int D>
class SweepParameter
{
public:
/**
* Default constructor.
*/
SweepParameter();
/**
* Constructor that stores a pointer to parent system.
*
* \param system parent system
*/
SweepParameter(System<D>& system);
/**
* Set the system associated with this object.
*
* Invoke this function on objects created with the default
* constructor to create an association with a parent system.
*
* \param system parent system
*/
void setSystem(System<D>& system)
{ systemPtr_ = &system;}
/**
* Store the pre-sweep value of the corresponding parameter.
*/
void getInitial();
/**
* Update the corresponding parameter value in the system.
*
* \param newVal new value for the parameter (input)
*/
void update(double newVal);
/**
* Return a string representation of the parameter type.
*/
std::string type() const;
/**
* Write the parameter type to an output stream.
*
* \param out output file stream
*/
void writeParamType(std::ostream& out) const;
/**
* Get a id for a sub-object or element to which this is applied.
*
* This function returns a value from the id_ array. Elements
* of this array store indices associating the parameter with
* a particular subobject or value. Different types of parameters
* require either 1 or 2 such identifiers. The number of required
* identifiers is denoted by private variable nID_.
*
*
*
* \param i array index to access
*/
int id(int i) const
{ return id_[i];}
/**
* Return the current system parameter value.
*/
double current()
{ return get_(); }
/**
* Return the initial system parameter value.
*/
double initial() const
{ return initial_; }
/**
* Return the total change planned for this parameter during sweep.
*/
double change() const
{ return change_; }
/**
* Serialize to or from an archive.
*
* \param ar Archive object
* \param version archive format version index
*/
template <class Archive>
void serialize(Archive ar, const unsigned int version);
private:
/// Enumeration of allowed parameter types.
enum ParamType { Block, Chi, Kuhn, Phi_Polymer, Phi_Solvent,
Mu_Polymer, Mu_Solvent, Solvent, Cell_Param, Null};
/// Type of parameter associated with an object of this class.
ParamType type_;
/// Number of identifiers needed for this parameter type.
int nID_;
/// Identifier indices.
DArray<int> id_;
/// Initial parameter value, retrieved from system at start of sweep.
double initial_;
/// Change in parameter
double change_;
/// Pointer to the parent system.
System<D>* systemPtr_;
/**
* Read type of parameter being swept, and set number of identifiers.
*
* \param in input stream from param file.
*/
void readParamType(std::istream& in);
/**
* Gets the current system parameter value.
*/
double get_();
/**
* Set the system parameter value.
*
* \param newVal new value for this parameter.
*/
void set_(double newVal);
// friends:
template <int U>
friend
std::istream& operator >> (std::istream&, SweepParameter<U>&);
template <int U>
friend
std::ostream&
operator << (std::ostream&, SweepParameter<U> const&);
};
}
}
#include "SweepParameter.tpp"
#endif
| 7,433
|
C++
|
.h
| 201
| 31.114428
| 75
| 0.63601
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,030
|
FieldState.h
|
dmorse_pscfpp/src/pspg/sweep/FieldState.h
|
#ifndef PSPG_FIELD_STATE_H
#define PSPG_FIELD_STATE_H
/*
* PSCF - Polymer Self-Consistent Field Theory
*
* Copyright 2016 - 2021, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include <pscf/crystal/UnitCell.h> // member
#include <pspg/field/FieldIo.h> // member
#include <util/containers/DArray.h> // member template
namespace Pscf {
namespace Pspg
{
using namespace Util;
template <int D> class System;
/**
* Record of a state of a System (fields + unit cell).
*
* - An array of field objects of class FT
* - a UnitCell<D> object
*
* The template parameter D is the dimension of space, while
* parameter FT is a field type.
*
* A FieldState can be used to store either chemical potential or
* concentration fields, along with an associated UnitCell<D>.
* Different choices for class FT can be used to store fields in
* symmetry-adapted basis function, r-grid or k-grid format.
*
* \ingroup Pspg_Sweep_Module
*/
template <int D, class FT>
class FieldState
{
public:
/// \name Construction and Destruction
//@{
/**
* Default constructor.
*/
FieldState();
/**
* Constructor, creates association with a System.
*
* Equivalent to default construction followed by setSystem(system).
*
* \param system associated parent System<D> object.
*/
FieldState(System<D>& system);
/**
* Destructor.
*/
~FieldState();
/**
* Set association with System, after default construction.
*
* \param system associated parent System<D> object.
*/
void setSystem(System<D>& system);
//@}
/// \name Accessors
//@{
/**
* Get array of all fields by const reference.
*
* The array capacity is equal to the number of monomer types.
*/
const DArray<FT>& fields() const;
/**
* Get array of all chemical potential fields (non-const reference).
*
* The array capacity is equal to the number of monomer types.
*/
DArray<FT>& fields();
/**
* Get a field for a single monomer type by const reference.
*
* \param monomerId integer monomer type index
*/
const FT& field(int monomerId) const;
/**
* Get field for a specific monomer type (non-const reference).
*
* \param monomerId integer monomer type index
*/
FT& field(int monomerId);
/**
* Get UnitCell (i.e., lattice type and parameters) by const reference.
*/
const UnitCell<D>& unitCell() const;
/**
* Get the UnitCell by non-const reference.
*/
UnitCell<D>& unitCell();
//@}
protected:
/**
* Has a system been set?
*/
bool hasSystem();
/**
* Get associated System by reference.
*/
System<D>& system();
private:
/**
* Array of fields for all monomer types.
*/
DArray<FT> fields_;
/**
* Crystallographic unit cell (crystal system and cell parameters).
*/
UnitCell<D> unitCell_;
/**
* Pointer to associated system.
*/
System<D>* systemPtr_;
};
// Public inline member functions
// Get an array of all fields (const reference)
template <int D, class FT>
inline
const DArray<FT>& FieldState<D,FT>::fields() const
{ return fields_; }
// Get an array of all fields (non-const reference)
template <int D, class FT>
inline
DArray<FT>& FieldState<D,FT>::fields()
{ return fields_; }
// Get field for monomer type id (const reference)
template <int D, class FT>
inline
FT const & FieldState<D,FT>::field(int id) const
{ return fields_[id]; }
// Get field for monomer type id (non-const reference)
template <int D, class FT>
inline FT& FieldState<D,FT>::field(int id)
{ return fields_[id]; }
// Get the internal Unitcell (const reference)
template <int D, class FT>
inline
UnitCell<D> const & FieldState<D,FT>::unitCell() const
{ return unitCell_; }
// Get the internal Unitcell (non-const reference)
template <int D, class FT>
inline
UnitCell<D>& FieldState<D,FT>::unitCell()
{ return unitCell_; }
// Protected inline member functions
// Has the system been set?
template <int D, class FT>
inline
bool FieldState<D,FT>::hasSystem()
{ return (systemPtr_ != 0); }
// Get the associated System<D> object.
template <int D, class FT>
inline
System<D>& FieldState<D,FT>::system()
{
assert(systemPtr_ != 0);
return *systemPtr_;
}
#ifndef PSPG_FIELD_STATE_TPP
// Suppress implicit instantiation
extern template class FieldState< 1, DArray<double> >;
extern template class FieldState< 2, DArray<double> >;
extern template class FieldState< 3, DArray<double> >;
#endif
} // namespace Pspg
} // namespace Pscf
#endif
| 5,079
|
C++
|
.h
| 172
| 24.093023
| 76
| 0.629934
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,031
|
SweepFactory.h
|
dmorse_pscfpp/src/pspg/sweep/SweepFactory.h
|
#ifndef PSPG_SWEEP_FACTORY_H
#define PSPG_SWEEP_FACTORY_H
/*
* PSCF - Polymer Self-Consistent Field Theory
*
* Copyright 2016 - 2022, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include <util/param/Factory.h>
#include "Sweep.h"
#include <string>
namespace Pscf {
namespace Pspg {
using namespace Util;
/**
* Default Factory for subclasses of Sweep.
*
* \ingroup Pspg_Sweep_Module
*/
template <int D>
class SweepFactory : public Factory< Sweep<D> >
{
public:
/**
* Constructor.
*
* \param system parent System object
*/
SweepFactory(System<D>& system);
/**
* Method to create any Sweep subclass.
*
* \param className name of the Sweep subclass
* \return Sweep<D>* pointer to new instance of speciesName
*/
Sweep<D>* factory(std::string const & className) const;
using Factory< Sweep<D> >::trySubfactories;
private:
System<D>* systemPtr_;
};
#ifndef PSPG_SWEEP_FACTORY_TPP
// Suppress implicit instantiation
extern template class SweepFactory<1>;
extern template class SweepFactory<2>;
extern template class SweepFactory<3>;
#endif
}
}
#endif
| 1,274
|
C++
|
.h
| 49
| 21.632653
| 67
| 0.682684
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,032
|
LinearSweep.h
|
dmorse_pscfpp/src/pspg/sweep/LinearSweep.h
|
#ifndef PSPG_LINEAR_SWEEP_H
#define PSPG_LINEAR_SWEEP_H
/*
* PSCF - Polymer Self-Consistent Field Theory
*
* Copyright 2016 - 2022, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include "Sweep.h" // base class
#include "SweepParameter.h" // member
#include <util/global.h>
#include <iostream>
namespace Pscf {
namespace Pspg {
template <int D> class System;
using namespace Util;
/**
* Base class for a sweep in parameter space where parameters change
* linearly with the sweep variable.
*
* \ingroup Pspg_Sweep_Module
*/
template <int D>
class LinearSweep : public Sweep<D>
{
public:
/**
* Constructor.
* \param system parent System object
*/
LinearSweep(System<D>& system);
/**
* Read parameters from param file.
*
* \param in Input stream from param file.
*/
void readParameters(std::istream& in);
/**
* Setup operation at the beginning of a sweep. Gets initial
* values of individual parameters.
*/
void setup();
/**
* Set the state before an iteration. Called with each new iteration
* in SweepTempl::sweep()
*
* \param s path length coordinate, in [0,1]
*/
void setParameters(double s);
/**
* Output data to a running summary.
*
* \param out output file, open for writing
*/
void outputSummary(std::ostream& out);
protected:
using Sweep<D>::system;
using Sweep<D>::hasSystem;
private:
/// Number of parameters being swept.
int nParameter_;
/// Array of SweepParameter objects.
DArray< SweepParameter<D> > parameters_;
};
#ifndef PSPG_LINEAR_SWEEP_TPP
// Suppress implicit instantiation
extern template class LinearSweep<1>;
extern template class LinearSweep<2>;
extern template class LinearSweep<3>;
#endif
}
}
#endif
| 2,019
|
C++
|
.h
| 73
| 22.342466
| 74
| 0.649114
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,033
|
Sweep.h
|
dmorse_pscfpp/src/pspg/sweep/Sweep.h
|
#ifndef PSPG_SWEEP_H
#define PSPG_SWEEP_H
/*
* PSCF - Polymer Self-Consistent Field Theory
*
* Copyright 2016 - 2022, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include <pspg/sweep/BasisFieldState.h> // base class template parameter
#include <pscf/sweep/SweepTmpl.h> // base class template
#include <util/global.h>
namespace Pscf {
namespace Pspg {
using namespace Util;
template <int D> class System;
/**
* Solve a sequence of problems along a line in parameter space.
*/
template <int D>
class Sweep : public SweepTmpl< BasisFieldState<D> >
{
public:
/**
* Default Constructor.
*/
Sweep();
/**
* Constructor, creates assocation with parent system.
*/
Sweep(System<D>& system);
/**
* Destructor.
*/
~Sweep();
/**
* Set association with parent System.
*/
void setSystem(System<D>& system);
/**
* Read parameters from param file.
*
* \param in Input stream from param file.
*/
virtual void readParameters(std::istream& in);
// Public members inherited from base class template SweepTmpl
using SweepTmpl< BasisFieldState<D> >::historyCapacity;
using SweepTmpl< BasisFieldState<D> >::historySize;
using SweepTmpl< BasisFieldState<D> >::nAccept;
using SweepTmpl< BasisFieldState<D> >::state;
using SweepTmpl< BasisFieldState<D> >::s;
using SweepTmpl< BasisFieldState<D> >::c;
protected:
/**
* Check allocation state of fields in one state, allocate if necessary.
*
* \param state object that represents a stored state of the system.
*/
virtual void checkAllocation(BasisFieldState<D>& state);
/**
* Setup operation at the beginning of a sweep.
*/
virtual void setup();
/**
* Set non-adjustable system parameters to new values.
*
* \param sNew contour variable value for new trial solution.
*/
virtual void setParameters(double sNew) = 0;
/**
* Create a guess for adjustable variables by continuation.
*
* \param sNew contour variable value for new trial solution.
*/
virtual void extrapolate(double sNew);
/**
* Call current iterator to solve SCFT problem.
*
* \param isContinuation true iff is continuation in a sweep
* \return 0 for sucessful solution, 1 on failure to converge
*/
virtual int solve(bool isContinuation);
/**
* Reset system to previous solution after iterature failure.
*
* The implementation of this function should reset the system state
* to correspond to that stored in state(0), i.e., the previous
* converged solution.
*/
virtual void reset();
/**
* Update state(0) and output data after successful convergence
*
* The implementation of this function should copy the current
* system state into state(0) and output any desired information
* about the current converged solution.
*/
virtual void getSolution();
/**
* Cleanup operation at the beginning of a sweep.
*/
virtual void cleanup();
/**
* Has an association with the parent System been set?
*/
bool hasSystem()
{ return (systemPtr_ != 0); }
/**
* Return the parent system by reference.
*/
System<D>& system()
{ return *systemPtr_; }
/// Whether to write real space concentration field files.
bool writeCRGrid_;
/// Whether to write concentration field files in basis format.
bool writeCBasis_;
/// Whether to write real space potential field files.
bool writeWRGrid_;
// Protected members inherited from base classes
using SweepTmpl< BasisFieldState<D> >::ns_;
using SweepTmpl< BasisFieldState<D> >::baseFileName_;
using SweepTmpl< BasisFieldState<D> >::initialize;
using SweepTmpl< BasisFieldState<D> >::setCoefficients;
using ParamComposite::readOptional;
private:
/// Trial state (produced by continuation in setGuess)
BasisFieldState<D> trial_;
/// Unit cell parameters for trial state
FSArray<double, 6> unitCellParameters_;
/// Log file for summary output
std::ofstream logFile_;
/// Pointer to parent system.
System<D>* systemPtr_;
/// Output data to several files after convergence
void outputSolution();
/// Output brief summary of thermodynamic properties
void outputSummary(std::ostream&);
};
} // namespace Pspg
} // namespace Pscf
#endif
| 4,762
|
C++
|
.h
| 140
| 27.65
| 77
| 0.651908
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,034
|
BasisFieldState.h
|
dmorse_pscfpp/src/pspg/sweep/BasisFieldState.h
|
#ifndef PSPG_BASIS_FIELD_STATE_H
#define PSPG_BASIS_FIELD_STATE_H
/*
* PSCF - Polymer Self-Consistent Field Theory
*
* Copyright 2016 - 2021, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include "FieldState.h"
#include <string>
namespace Pscf {
namespace Pspg
{
using namespace Util;
/**
* FieldState for fields in symmetry-adapted basis format.
*/
template <int D>
class BasisFieldState : public FieldState<D, DArray<double> >
{
public:
/**
* Default constructor.
*/
BasisFieldState();
/**
* Constructor, create association with a parent system.
*
* \param system associated parent system
*/
BasisFieldState(System<D>& system);
/**
* Destructor.
*/
~BasisFieldState();
/**
* Allocate all fields.
*
* Precondition: hasSystem() == true
*/
void allocate();
/**
* Read state from file.
*
* \param filename name of input w-field file in symmetry-adapted format.
*/
void read(const std::string & filename);
/**
* Write state to file.
*
* \param filename name of output file, in symmetry-adapated format.
*/
void write(const std::string & filename);
/**
* Copy the current state of the associated system.
*
* Copy the fields and the unit cell.
*/
void getSystemState();
/**
* Set the state of the associated system to this state.
*
* \param newCellParams update system unit cell iff newCellParams == true.
*/
void setSystemState(bool newCellParams);
// Inherited member functions
using FieldState<D, DArray<double> >::fields;
using FieldState<D, DArray<double> >::field;
using FieldState<D, DArray<double> >::unitCell;
using FieldState<D, DArray<double> >::system;
using FieldState<D, DArray<double> >::hasSystem;
using FieldState<D, DArray<double> >::setSystem;
};
#ifndef PSPG_BASIS_FIELD_STATE_TPP
// Suppress implicit instantiation
extern template class BasisFieldState<1>;
extern template class BasisFieldState<2>;
extern template class BasisFieldState<3>;
#endif
} // namespace Pspg
} // namespace Pscf
#endif
| 2,348
|
C++
|
.h
| 82
| 23.109756
| 79
| 0.649154
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,035
|
MixtureTest.h
|
dmorse_pscfpp/src/pspg/tests/solvers/MixtureTest.h
|
#ifndef PSPG_MIXTURE_TEST_H
#define PSPG_MIXTURE_TEST_H
#include <test/UnitTest.h>
#include <test/UnitTestRunner.h>
#include <pspg/solvers/Mixture.h>
#include <pspg/solvers/Polymer.h>
#include <pspg/solvers/Block.h>
#include <pspg/solvers/Propagator.h>
#include <pscf/mesh/Mesh.h>
#include <pscf/crystal/UnitCell.h>
#include <pscf/math/IntVec.h>
#include <util/math/Constants.h>
#include <pspg/math/GpuResources.h>
#include <fstream>
using namespace Util;
using namespace Pscf;
using namespace Pscf::Pspg;
class MixtureTest : public UnitTest
{
public:
void setUp()
{}
void tearDown()
{}
void testConstructor1D()
{
printMethod(TEST_FUNC);
Mixture<1> mixture;
}
void testReadParameters1D()
{
printMethod(TEST_FUNC);
Mixture<1> mixture;
std::ifstream in;
openInputFile("in/Mixture", in);
mixture.readParam(in);
in.close();
}
void testSolver1D()
{
printMethod(TEST_FUNC);
Mixture<1> mixture;
std::ifstream in;
openInputFile("in/Mixture", in);
mixture.readParam(in);
UnitCell<1> unitCell;
in >> unitCell;
IntVec<1> d;
in >> d;
in.close();
Mesh<1> mesh;
mesh.setDimensions(d);
mixture.setMesh(mesh);
// Construct wavelist
WaveList<1> wavelist;
wavelist.allocate(mesh, unitCell);
wavelist.computeMinimumImages(mesh, unitCell);
// Setup unit cell
mixture.setupUnitCell(unitCell, wavelist);
int nMonomer = mixture.nMonomer();
DArray< RDField<1> > d_wFields;
DArray< RDField<1> > d_cFields;
d_wFields.allocate(nMonomer);
d_cFields.allocate(nMonomer);
int nx = mesh.size();
for (int i = 0; i < nMonomer; ++i) {
d_wFields[i].allocate(nx);
d_cFields[i].allocate(nx);
}
UTIL_CHECK(nMonomer == 2); // Hard-coded in here!
double cs;
cudaReal* wFields0 = new cudaReal[nx];
cudaReal* wFields1 = new cudaReal[nx];
for (int i = 0; i < nx; ++i) {
cs = cos(2.0*Constants::Pi*double(i)/double(nx));
wFields0[i] = 0.5 + cs;
wFields1[i] = 0.5 - cs;
}
cudaMemcpy(d_wFields[0].cDField(), wFields0,
nx*sizeof(cudaReal), cudaMemcpyHostToDevice);
cudaMemcpy(d_wFields[1].cDField(), wFields1,
nx*sizeof(cudaReal), cudaMemcpyHostToDevice);
mixture.compute(d_wFields, d_cFields);
// Test if same Q is obtained from different methods
double Q = mixture.polymer(0).propagator(1, 0).computeQ();
TEST_ASSERT(eq(Q, mixture.polymer(0).propagator(0, 1).computeQ()));
TEST_ASSERT(eq(Q, mixture.polymer(0).propagator(0, 0).computeQ()));
TEST_ASSERT(eq(Q, mixture.polymer(0).propagator(1, 1).computeQ()));
#if 0
std::cout << "Propagator(0,0), Q = "
<< mixture.polymer(0).propagator(0, 0).computeQ() << "\n";
std::cout << "Propagator(1,0), Q = "
<< mixture.polymer(0).propagator(1, 0).computeQ() << "\n";
std::cout << "Propagator(1,1), Q = "
<< mixture.polymer(0).propagator(1, 1).computeQ() << "\n";
std::cout << "Propagator(0,1), Q = "
<< mixture.polymer(0).propagator(0, 1).computeQ() << "\n";
#endif
}
void testSolver2D()
{
printMethod(TEST_FUNC);
Mixture<2> mixture;
std::ifstream in;
openInputFile("in/Mixture2d", in);
mixture.readParam(in);
UnitCell<2> unitCell;
in >> unitCell;
IntVec<2> d;
in >> d;
in.close();
Mesh<2> mesh;
mesh.setDimensions(d);
mixture.setMesh(mesh);
// Construct wavelist
WaveList<2> wavelist;
wavelist.allocate(mesh, unitCell);
wavelist.computeMinimumImages(mesh, unitCell);
// Setup unit cell
mixture.setupUnitCell(unitCell, wavelist);
int nMonomer = mixture.nMonomer();
DArray< RDField<2> > d_wFields;
DArray< RDField<2> > d_cFields;
d_wFields.allocate(nMonomer);
d_cFields.allocate(nMonomer);
int nx = mesh.size();
for (int i = 0; i < nMonomer; ++i) {
d_wFields[i].allocate(nx);
d_cFields[i].allocate(nx);
}
UTIL_CHECK(nMonomer == 2); // Hard-coded in here!
cudaReal* wFields0 = new cudaReal[nx];
cudaReal* wFields1 = new cudaReal[nx];
// Generate oscillatory wField
int dx = mesh.dimension(0);
int dy = mesh.dimension(1);
double fx = 2.0*Constants::Pi/double(dx);
double fy = 2.0*Constants::Pi/double(dy);
double cx, cy;
int k = 0;
for (int i = 0; i < dx; ++i) {
cx = cos(fx*double(i));
for (int j = 0; j < dy; ++j) {
cy = cos(fy*double(j));
wFields0[k] = 0.5 + cx + cy;
wFields1[k] = 0.5 - cx - cy;
++k;
}
}
cudaMemcpy(d_wFields[0].cDField(), wFields0,
nx*sizeof(cudaReal), cudaMemcpyHostToDevice);
cudaMemcpy(d_wFields[1].cDField(), wFields1,
nx*sizeof(cudaReal), cudaMemcpyHostToDevice);
mixture.compute(d_wFields, d_cFields);
// Test if same Q is obtained from different methods
double Q = mixture.polymer(0).propagator(1, 0).computeQ();
TEST_ASSERT(eq(Q, mixture.polymer(0).propagator(0, 1).computeQ()));
TEST_ASSERT(eq(Q, mixture.polymer(0).propagator(0, 0).computeQ()));
TEST_ASSERT(eq(Q, mixture.polymer(0).propagator(1, 1).computeQ()));
#if 0
std::cout << "Propagator(0,0), Q = "
<< mixture.polymer(0).propagator(0, 0).computeQ() << "\n";
std::cout << "Propagator(1,0), Q = "
<< mixture.polymer(0).propagator(1, 0).computeQ() << "\n";
std::cout << "Propagator(1,1), Q = "
<< mixture.polymer(0).propagator(1, 1).computeQ() << "\n";
std::cout << "Propagator(0,1), Q = "
<< mixture.polymer(0).propagator(0, 1).computeQ() << "\n";
#endif
}
void testSolver2D_hex()
{
printMethod(TEST_FUNC);
Mixture<2> mixture;
std::ifstream in;
openInputFile("in/Mixture2d_hex", in);
mixture.readParam(in);
UnitCell<2> unitCell;
in >> unitCell;
IntVec<2> d;
in >> d;
in.close();
Mesh<2> mesh;
mesh.setDimensions(d);
mixture.setMesh(mesh);
// Construct wavelist
WaveList<2> wavelist;
wavelist.allocate(mesh, unitCell);
wavelist.computeMinimumImages(mesh, unitCell);
// Setup unit cell
mixture.setupUnitCell(unitCell, wavelist);
int nMonomer = mixture.nMonomer();
DArray< RDField<2> > d_wFields;
DArray< RDField<2> > d_cFields;
d_wFields.allocate(nMonomer);
d_cFields.allocate(nMonomer);
int nx = mesh.size();
for (int i = 0; i < nMonomer; ++i) {
d_wFields[i].allocate(nx);
d_cFields[i].allocate(nx);
}
UTIL_CHECK(nMonomer == 2); // Hard-coded in here!
cudaReal* wFields0 = new cudaReal[nx];
cudaReal* wFields1 = new cudaReal[nx];
// Generate oscillatory wField
int dx = mesh.dimension(0);
int dy = mesh.dimension(1);
double fx = 2.0*Constants::Pi/double(dx);
double fy = 2.0*Constants::Pi/double(dy);
double cx, cy;
int k = 0;
for (int i = 0; i < dx; ++i) {
cx = cos(fx*double(i));
for (int j = 0; j < dy; ++j) {
cy = cos(fy*double(j));
wFields0[k] = 0.5 + cx + cy;
wFields1[k] = 0.5 - cx - cy;
++k;
}
}
cudaMemcpy(d_wFields[0].cDField(), wFields0,
nx*sizeof(cudaReal), cudaMemcpyHostToDevice);
cudaMemcpy(d_wFields[1].cDField(), wFields1,
nx*sizeof(cudaReal), cudaMemcpyHostToDevice);
mixture.compute(d_wFields, d_cFields);
// Test if same Q is obtained from different methods
double Q = mixture.polymer(0).propagator(1, 0).computeQ();
TEST_ASSERT(eq(Q, mixture.polymer(0).propagator(0, 1).computeQ()));
TEST_ASSERT(eq(Q, mixture.polymer(0).propagator(0, 0).computeQ()));
TEST_ASSERT(eq(Q, mixture.polymer(0).propagator(1, 1).computeQ()));
#if 0
std::cout << "Propagator(0,0), Q = "
<< mixture.polymer(0).propagator(0, 0).computeQ() << "\n";
std::cout << "Propagator(1,0), Q = "
<< mixture.polymer(0).propagator(1, 0).computeQ() << "\n";
std::cout << "Propagator(1,1), Q = "
<< mixture.polymer(0).propagator(1, 1).computeQ() << "\n";
std::cout << "Propagator(0,1), Q = "
<< mixture.polymer(0).propagator(0, 1).computeQ() << "\n";
#endif
}
void testSolver3D()
{
printMethod(TEST_FUNC);
Mixture<3> mixture;
std::ifstream in;
openInputFile("in/Mixture3d", in);
mixture.readParam(in);
UnitCell<3> unitCell;
in >> unitCell;
IntVec<3> d;
in >> d;
in.close();
Mesh<3> mesh;
mesh.setDimensions(d);
mixture.setMesh(mesh);
// Construct wavelist
WaveList<3> wavelist;
wavelist.allocate(mesh, unitCell);
wavelist.computeMinimumImages(mesh, unitCell);
// Setup unit cell
mixture.setupUnitCell(unitCell, wavelist);
int nMonomer = mixture.nMonomer();
DArray< RDField<3> > d_wFields;
DArray< RDField<3> > d_cFields;
d_wFields.allocate(nMonomer);
d_cFields.allocate(nMonomer);
int nx = mesh.size();
for (int i = 0; i < nMonomer; ++i) {
d_wFields[i].allocate(nx);
d_cFields[i].allocate(nx);
}
UTIL_CHECK(nMonomer == 2); // Hard-coded in here!
double cs;
cudaReal* wFields0 = new cudaReal[nx];
cudaReal* wFields1 = new cudaReal[nx];
for (int i = 0; i < nx; ++i) {
cs = cos(2.0*Constants::Pi*double(i)/double(nx));
wFields0[i] = 0.5 + cs;
wFields1[i] = 0.5 - cs;
}
cudaMemcpy(d_wFields[0].cDField(), wFields0,
nx*sizeof(cudaReal), cudaMemcpyHostToDevice);
cudaMemcpy(d_wFields[1].cDField(), wFields1,
nx*sizeof(cudaReal), cudaMemcpyHostToDevice);
mixture.compute(d_wFields, d_cFields);
// Test if same Q is obtained from different methods
double Q = mixture.polymer(0).propagator(1, 0).computeQ();
TEST_ASSERT(eq(Q, mixture.polymer(0).propagator(0, 1).computeQ()));
TEST_ASSERT(eq(Q, mixture.polymer(0).propagator(0, 0).computeQ()));
TEST_ASSERT(eq(Q, mixture.polymer(0).propagator(1, 1).computeQ()));
#if 0
std::cout << "Propagator(0,0), Q = "
<< mixture.polymer(0).propagator(0, 0).computeQ() << "\n";
std::cout << "Propagator(1,0), Q = "
<< mixture.polymer(0).propagator(1, 0).computeQ() << "\n";
std::cout << "Propagator(1,1), Q = "
<< mixture.polymer(0).propagator(1, 1).computeQ() << "\n";
std::cout << "Propagator(0,1), Q = "
<< mixture.polymer(0).propagator(0, 1).computeQ() << "\n";
#endif
}
};
TEST_BEGIN(MixtureTest)
TEST_ADD(MixtureTest, testConstructor1D)
TEST_ADD(MixtureTest, testReadParameters1D)
TEST_ADD(MixtureTest, testSolver1D)
TEST_ADD(MixtureTest, testSolver2D)
TEST_ADD(MixtureTest, testSolver2D_hex)
TEST_ADD(MixtureTest, testSolver3D)
TEST_END(MixtureTest)
#endif
| 11,490
|
C++
|
.h
| 312
| 28.964744
| 74
| 0.587395
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,036
|
SolverTestComposite.h
|
dmorse_pscfpp/src/pspg/tests/solvers/SolverTestComposite.h
|
#ifndef PSPG_TEST_SOLVER_TEST_COMPOSITE_H
#define PSPG_TEST_SOLVER_TEST_COMPOSITE_H
#include <test/CompositeTestRunner.h>
#include "PropagatorTest.h"
#include "MixtureTest.h"
TEST_COMPOSITE_BEGIN(SolverTestComposite)
TEST_COMPOSITE_ADD_UNIT(PropagatorTest);
TEST_COMPOSITE_ADD_UNIT(MixtureTest);
TEST_COMPOSITE_END
#endif
| 326
|
C++
|
.h
| 10
| 31.2
| 41
| 0.842949
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,037
|
PropagatorTest.h
|
dmorse_pscfpp/src/pspg/tests/solvers/PropagatorTest.h
|
#ifndef PSPG_PROPAGATOR_TEST_H
#define PSPG_PROPAGATOR_TEST_H
#include <test/UnitTest.h>
#include <test/UnitTestRunner.h>
#include <pspg/solvers/Block.h>
#include <pscf/mesh/MeshIterator.h>
#include <pspg/solvers/Propagator.h>
#include <pscf/mesh/Mesh.h>
#include <pscf/crystal/UnitCell.h>
#include <pscf/math/IntVec.h>
#include <util/math/Constants.h>
#include <pspg/math/GpuResources.h>
#include <fstream>
using namespace Util;
using namespace Pscf;
using namespace Pscf::Pspg;
class PropagatorTest : public UnitTest
{
public:
void setUp()
{}
void tearDown()
{}
template <int D>
void setupBlock(Pscf::Pspg::Block<D>& block)
{
block.setId(0);
double length = 2.0;
block.setLength(length);
block.setMonomerId(1);
double step = sqrt(6.0);
block.setKuhn(step);
return;
}
template <int D>
void setupMesh(Mesh<D>& mesh)
{
IntVec<D> d;
for (int i = 0; i < D; ++i) {
d[i] = 32;
}
mesh.setDimensions(d);
}
template <int D>
void setupUnitCell(UnitCell<D>& unitCell, std::string fname)
{
std::ifstream in;
openInputFile(fname, in);
in >> unitCell;
in.close();
}
void testConstructor1D()
{
printMethod(TEST_FUNC);
Pscf::Pspg::Block<1> block;
}
void testSetDiscretization1D()
{
printMethod(TEST_FUNC);
// Create and initialize block
Pscf::Pspg::Block<1> block;
setupBlock<1>(block);
// Create and initialize mesh
Mesh<1> mesh;
setupMesh<1>(mesh);
double ds = 0.02;
block.setDiscretization(ds, mesh);
TEST_ASSERT(eq(block.length(), 2.0));
TEST_ASSERT(eq(block.ds(), 0.02));
TEST_ASSERT(block.ns() == 101);
TEST_ASSERT(block.mesh().dimensions()[0] == 32);
}
void testSetDiscretization2D()
{
printMethod(TEST_FUNC);
//Create and initialize block
Pscf::Pspg::Block<2> block;
setupBlock<2>(block);
Mesh<2> mesh;
setupMesh<2>(mesh);
double ds = 0.26;
block.setDiscretization(ds, mesh);
TEST_ASSERT(eq(block.length(), 2.0));
TEST_ASSERT(eq(block.ds(), 0.25));
TEST_ASSERT(block.ns() == 9);
TEST_ASSERT(block.mesh().dimensions()[0] == 32);
TEST_ASSERT(block.mesh().dimensions()[1] == 32);
}
void testSetDiscretization3D()
{
printMethod(TEST_FUNC);
//Create and initialize block
Pscf::Pspg::Block<3> block;
setupBlock<3>(block);
Mesh<3> mesh;
setupMesh<3>(mesh);
double ds = 0.3;
block.setDiscretization(ds, mesh);
TEST_ASSERT(eq(block.length(), 2.0));
TEST_ASSERT(block.ns() == 7);
TEST_ASSERT(eq(block.ds(), 1.0/3.0));
TEST_ASSERT(block.mesh().dimensions()[0] == 32);
TEST_ASSERT(block.mesh().dimensions()[1] == 32);
TEST_ASSERT(block.mesh().dimensions()[2] == 32);
}
void testSetupSolver1D()
{
printMethod(TEST_FUNC);
// Create and initialize block
Pscf::Pspg::Block<1> block;
setupBlock<1>(block);
// Create and initialize mesh
Mesh<1> mesh;
setupMesh<1>(mesh);
double ds = 0.02;
block.setDiscretization(ds, mesh);
UnitCell<1> unitCell;
setupUnitCell<1>(unitCell, "in/Lamellar");
TEST_ASSERT(eq(unitCell.rBasis(0)[0], 4.0));
// Setup chemical potential field
int nx = mesh.size();
RDField<1> d_w;
d_w.allocate(mesh.dimensions());
cudaReal* w = new cudaReal[nx];
TEST_ASSERT(d_w.capacity() == mesh.size());
for (int i=0; i < nx; ++i) {
w[i] = 1.0;
}
cudaMemcpy(d_w.cDField(), w, nx*sizeof(cudaReal), cudaMemcpyHostToDevice);
// Construct wavelist
WaveList<1> wavelist;
wavelist.allocate(mesh, unitCell);
wavelist.computeMinimumImages(mesh, unitCell);
block.setupUnitCell(unitCell, wavelist);
block.setupSolver(d_w);
}
void testSetupSolver2D()
{
printMethod(TEST_FUNC);
// Create and initialize block
Pscf::Pspg::Block<2> block;
setupBlock<2>(block);
// Create and initialize mesh
Mesh<2> mesh;
setupMesh<2>(mesh);
double ds = 0.02;
block.setDiscretization(ds, mesh);
UnitCell<2> unitCell;
setupUnitCell<2>(unitCell, "in/Rectangular");
TEST_ASSERT(eq(unitCell.rBasis(0)[0], 3.0));
TEST_ASSERT(eq(unitCell.rBasis(1)[1], 4.0));
// Setup chemical potential field
int nx = mesh.size();
RDField<2> d_w;
d_w.allocate(mesh.dimensions());
cudaReal* w = new cudaReal[nx];
TEST_ASSERT(d_w.capacity() == mesh.size());
for (int i=0; i < nx; ++i) {
w[i] = 1.0;
}
cudaMemcpy(d_w.cDField(), w, nx*sizeof(cudaReal), cudaMemcpyHostToDevice);
// Construct wavelist
WaveList<2> wavelist;
wavelist.allocate(mesh, unitCell);
wavelist.computeMinimumImages(mesh, unitCell);
block.setupUnitCell(unitCell, wavelist);
block.setupSolver(d_w);
}
void testSetupSolver3D()
{
printMethod(TEST_FUNC);
// Create and initialize block
Pscf::Pspg::Block<3> block;
setupBlock<3>(block);
// Create and initialize mesh
Mesh<3> mesh;
setupMesh<3>(mesh);
double ds = 0.02;
block.setDiscretization(ds, mesh);
UnitCell<3> unitCell;
setupUnitCell<3>(unitCell, "in/Orthorhombic");
TEST_ASSERT(eq(unitCell.rBasis(0)[0], 3.0));
TEST_ASSERT(eq(unitCell.rBasis(1)[1], 4.0));
TEST_ASSERT(eq(unitCell.rBasis(2)[2], 5.0));
// Setup chemical potential field
int nx = mesh.size();
RDField<3> d_w;
d_w.allocate(mesh.dimensions());
cudaReal* w = new cudaReal[nx];
TEST_ASSERT(d_w.capacity() == mesh.size());
for (int i=0; i < nx; ++i) {
w[i] = 1.0;
}
cudaMemcpy(d_w.cDField(), w, nx*sizeof(cudaReal), cudaMemcpyHostToDevice);
// Construct wavelist
WaveList<3> wavelist;
wavelist.allocate(mesh, unitCell);
wavelist.computeMinimumImages(mesh, unitCell);
block.setupUnitCell(unitCell, wavelist);
block.setupSolver(d_w);
}
void testSolver1D()
{
printMethod(TEST_FUNC);
// Create and initialize block
Pscf::Pspg::Block<1> block;
setupBlock<1>(block);
// Create and initialize mesh
Mesh<1> mesh;
setupMesh<1>(mesh);
double ds = 0.02;
block.setDiscretization(ds, mesh);
UnitCell<1> unitCell;
setupUnitCell<1>(unitCell, "in/Lamellar");
TEST_ASSERT(eq(unitCell.rBasis(0)[0], 4.0));
// Setup chemical potential field
int nx = mesh.size();
RDField<1> d_w;
d_w.allocate(mesh.dimensions());
cudaReal* w = new cudaReal[nx];
TEST_ASSERT(d_w.capacity() == mesh.size());
double wc = 0.3;
for (int i=0; i < nx; ++i) {
w[i] = wc;
}
cudaMemcpy(d_w.cDField(), w, nx*sizeof(cudaReal), cudaMemcpyHostToDevice);
// Construct wavelist
WaveList<1> wavelist;
wavelist.allocate(mesh, unitCell);
wavelist.computeMinimumImages(mesh, unitCell);
block.setupUnitCell(unitCell, wavelist);
block.setupSolver(d_w);
// Setup fields on host and device
Propagator<1>::QField d_qin, d_qout;
cudaReal* qin = new cudaReal[nx];
cudaReal* qout = new cudaReal[nx];
d_qin.allocate(mesh.dimensions());
d_qout.allocate(mesh.dimensions());
// Run block step
double twoPi = 2.0*Constants::Pi;
for (int i=0; i < nx; ++i) {
qin[i] = cos(twoPi*double(i)/double(nx));
}
cudaMemcpy(d_qin.cDField(), qin, nx*sizeof(cudaReal), cudaMemcpyHostToDevice);
block.setupFFT();
block.step(d_qin.cDField(), d_qout.cDField());
cudaMemcpy(qout, d_qout.cDField(), nx*sizeof(cudaReal), cudaMemcpyDeviceToHost);
// Test block step output against expected output
double a = 4.0;
double b = block.kuhn();
double Gb = twoPi*b/a;
double r = Gb*Gb/6.0;
ds = block.ds();
double expected = exp(-(wc + r)*ds);
for (int i = 0; i < nx; ++i) {
TEST_ASSERT(eq(qout[i], qin[i]*expected));
}
// Test propagator solve
block.propagator(0).solve();
// Copy results from propagator solve
cudaReal* propHead = new cudaReal[nx*block.ns()];
cudaReal* propTail = new cudaReal[nx*block.ns()];
cudaMemcpy(propHead, block.propagator(0).head(), nx*sizeof(cudaReal), cudaMemcpyDeviceToHost);
cudaMemcpy(propTail, block.propagator(0).tail(), nx*sizeof(cudaReal), cudaMemcpyDeviceToHost);
for (int i = 0; i < nx; ++i) {
TEST_ASSERT(eq(propHead[i],1.0));
}
expected = exp(-wc*block.length());
for (int i = 0; i < nx; ++i) {
TEST_ASSERT(eq(propTail[i], expected));
}
}
void testSolver2D()
{
printMethod(TEST_FUNC);
// Create and initialize block
Pscf::Pspg::Block<2> block;
setupBlock<2>(block);
// Create and initialize mesh
Mesh<2> mesh;
setupMesh<2>(mesh);
double ds = 0.02;
block.setDiscretization(ds, mesh);
UnitCell<2> unitCell;
setupUnitCell<2>(unitCell, "in/Rectangular");
TEST_ASSERT(eq(unitCell.rBasis(0)[0], 3.0));
TEST_ASSERT(eq(unitCell.rBasis(1)[1], 4.0));
// Setup chemical potential field
int nx = mesh.size();
RDField<2> d_w;
d_w.allocate(mesh.dimensions());
cudaReal* w = new cudaReal[nx];
TEST_ASSERT(d_w.capacity() == mesh.size());
double wc = 0.3;
for (int i=0; i < nx; ++i) {
w[i] = wc;
}
cudaMemcpy(d_w.cDField(), w, nx*sizeof(cudaReal), cudaMemcpyHostToDevice);
// Construct wavelist
WaveList<2> wavelist;
wavelist.allocate(mesh, unitCell);
wavelist.computeMinimumImages(mesh, unitCell);
block.setupUnitCell(unitCell, wavelist);
block.setupSolver(d_w);
// Setup fields on host and device
Propagator<2>::QField d_qin, d_qout;
cudaReal* qin = new cudaReal[nx];
cudaReal* qout = new cudaReal[nx];
d_qin.allocate(mesh.dimensions());
d_qout.allocate(mesh.dimensions());
// Run block step
MeshIterator<2> iter(mesh.dimensions());
double twoPi = 2.0*Constants::Pi;
for (iter.begin(); !iter.atEnd(); ++iter){
qin[iter.rank()] = cos(twoPi *
(double(iter.position(0))/double(mesh.dimension(0)) +
double(iter.position(1))/double(mesh.dimension(1)) ) );
}
cudaMemcpy(d_qin.cDField(), qin, nx*sizeof(cudaReal), cudaMemcpyHostToDevice);
block.setupFFT();
block.step(d_qin.cDField(), d_qout.cDField());
cudaMemcpy(qout, d_qout.cDField(), nx*sizeof(cudaReal), cudaMemcpyDeviceToHost);
// Test block step output against expected output
double b = block.kuhn();
double Gb;
double expected;
IntVec<2> temp;
temp[0] = 1;
temp[1] = 1;
ds = block.ds();
for (iter.begin(); !iter.atEnd(); ++iter){
Gb = unitCell.ksq(temp);
double factor = b;
double r = Gb*factor*factor/6.0;
expected = exp(-(wc + r)*ds);
TEST_ASSERT(eq(qout[iter.rank()], qin[iter.rank()]*expected));
}
// Test propagator solve
block.propagator(0).solve();
// Copy results from propagator solve
cudaReal* propHead = new cudaReal[nx*block.ns()];
cudaReal* propTail = new cudaReal[nx*block.ns()];
cudaMemcpy(propHead, block.propagator(0).head(), nx*sizeof(cudaReal), cudaMemcpyDeviceToHost);
cudaMemcpy(propTail, block.propagator(0).tail(), nx*sizeof(cudaReal), cudaMemcpyDeviceToHost);
for (iter.begin(); !iter.atEnd(); ++iter){
TEST_ASSERT(eq(propHead[iter.rank()], 1.0));
}
expected = exp(-wc*block.length());
for (iter.begin(); !iter.atEnd(); ++iter){
TEST_ASSERT(eq(propTail[iter.rank()], expected));
}
}
void testSolver3D()
{
printMethod(TEST_FUNC);
// Create and initialize block
Pscf::Pspg::Block<3> block;
setupBlock<3>(block);
// Create and initialize mesh
Mesh<3> mesh;
setupMesh<3>(mesh);
double ds = 0.02;
block.setDiscretization(ds, mesh);
UnitCell<3> unitCell;
setupUnitCell<3>(unitCell, "in/Orthorhombic");
TEST_ASSERT(eq(unitCell.rBasis(0)[0], 3.0));
TEST_ASSERT(eq(unitCell.rBasis(1)[1], 4.0));
TEST_ASSERT(eq(unitCell.rBasis(2)[2], 5.0));
// Setup chemical potential field
int nx = mesh.size();
RDField<3> d_w;
d_w.allocate(mesh.dimensions());
cudaReal* w = new cudaReal[nx];
TEST_ASSERT(d_w.capacity() == mesh.size());
double wc = 0.3;
for (int i=0; i < nx; ++i) {
w[i] = wc;
}
cudaMemcpy(d_w.cDField(), w, nx*sizeof(cudaReal), cudaMemcpyHostToDevice);
// Construct wavelist
WaveList<3> wavelist;
wavelist.allocate(mesh, unitCell);
wavelist.computeMinimumImages(mesh, unitCell);
block.setupUnitCell(unitCell, wavelist);
block.setupSolver(d_w);
// Setup fields on host and device
Propagator<3>::QField d_qin, d_qout;
cudaReal* qin = new cudaReal[nx];
cudaReal* qout = new cudaReal[nx];
d_qin.allocate(mesh.dimensions());
d_qout.allocate(mesh.dimensions());
// Run block step
MeshIterator<3> iter(mesh.dimensions());
double twoPi = 2.0*Constants::Pi;
for (iter.begin(); !iter.atEnd(); ++iter){
qin[iter.rank()] = cos(twoPi *
(double(iter.position(0))/double(mesh.dimension(0)) +
double(iter.position(1))/double(mesh.dimension(1)) +
double(iter.position(2))/double(mesh.dimension(2)) ) );
}
cudaMemcpy(d_qin.cDField(), qin, nx*sizeof(cudaReal), cudaMemcpyHostToDevice);
block.setupFFT();
block.step(d_qin.cDField(), d_qout.cDField());
cudaMemcpy(qout, d_qout.cDField(), nx*sizeof(cudaReal), cudaMemcpyDeviceToHost);
// Test block step output against expected output
double b = block.kuhn();
double Gb;
double expected;
IntVec<3> temp;
temp[0] = 1;
temp[1] = 1;
temp[2] = 1;
ds = block.ds();
for (iter.begin(); !iter.atEnd(); ++iter){
Gb = unitCell.ksq(temp);
double factor = b;
double r = Gb*factor*factor/6.0;
expected = exp(-(wc + r)*ds);
TEST_ASSERT(eq(qout[iter.rank()], qin[iter.rank()]*expected));
}
// Test propagator solve
block.propagator(0).solve();
// Copy results from propagator solve
cudaReal* propHead = new cudaReal[nx*block.ns()];
cudaReal* propTail = new cudaReal[nx*block.ns()];
cudaMemcpy(propHead, block.propagator(0).head(), nx*sizeof(cudaReal), cudaMemcpyDeviceToHost);
cudaMemcpy(propTail, block.propagator(0).tail(), nx*sizeof(cudaReal), cudaMemcpyDeviceToHost);
for (iter.begin(); !iter.atEnd(); ++iter){
TEST_ASSERT(eq(propHead[iter.rank()], 1.0));
}
expected = exp(-wc*block.length());
for (iter.begin(); !iter.atEnd(); ++iter){
TEST_ASSERT(eq(propTail[iter.rank()], expected));
}
}
};
TEST_BEGIN(PropagatorTest)
TEST_ADD(PropagatorTest, testConstructor1D)
TEST_ADD(PropagatorTest, testSetDiscretization1D)
TEST_ADD(PropagatorTest, testSetDiscretization2D)
TEST_ADD(PropagatorTest, testSetDiscretization3D)
TEST_ADD(PropagatorTest, testSetupSolver1D)
TEST_ADD(PropagatorTest, testSetupSolver2D)
TEST_ADD(PropagatorTest, testSetupSolver3D)
TEST_ADD(PropagatorTest, testSolver1D)
TEST_ADD(PropagatorTest, testSolver2D)
TEST_ADD(PropagatorTest, testSolver3D)
TEST_END(PropagatorTest)
#endif
| 15,942
|
C++
|
.h
| 449
| 28.447661
| 100
| 0.617388
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,038
|
SweepTestComposite.h
|
dmorse_pscfpp/src/pspg/tests/sweep/SweepTestComposite.h
|
#ifndef PSPG_TEST_SWEEP_TEST_COMPOSITE_H
#define PSPG_TEST_SWEEP_TEST_COMPOSITE_H
#include <test/CompositeTestRunner.h>
// include the headers for individual tests
#include "BasisFieldStateTest.h"
#include "SweepTest.h"
TEST_COMPOSITE_BEGIN(SweepTestComposite)
TEST_COMPOSITE_ADD_UNIT(BasisFieldStateTest)
TEST_COMPOSITE_ADD_UNIT(SweepTest)
TEST_COMPOSITE_END
#endif
| 371
|
C++
|
.h
| 11
| 32.363636
| 44
| 0.845506
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,039
|
BasisFieldStateTest.h
|
dmorse_pscfpp/src/pspg/tests/sweep/BasisFieldStateTest.h
|
#ifndef PSPC_BASIS_FIELD_STATE_TEST_H
#define PSPC_BASIS_FIELD_STATE_TEST_H
#include <test/UnitTest.h>
#include <test/UnitTestRunner.h>
#include <pspg/System.h>
#include <pspg/sweep/BasisFieldState.h>
#include <pscf/crystal/BFieldComparison.h>
#include <util/tests/LogFileUnitTest.h>
#include <fstream>
using namespace Util;
using namespace Pscf;
using namespace Pscf::Pspg;
class BasisFieldStateTest : public LogFileUnitTest
{
public:
void setUp()
{}
void testConstructor()
{
printMethod(TEST_FUNC);
System<3> system;
BasisFieldState<3> bfs1(system);
BasisFieldState<3> bfs2;
}
void testRead()
{
printMethod(TEST_FUNC);
System<3> system;
BasisFieldState<3> bfs(system);
BFieldComparison comparison;
// Setup system
BasisFieldStateTest::SetUpSystem(system);
// Read in file one way
system.readWBasis("in/bcc/omega.ref");
// Read in file another way
bfs.read("in/bcc/omega.ref");
// Compare
comparison.compare(bfs.fields(), system.w().basis());
// Assert small difference
TEST_ASSERT(comparison.maxDiff() < 5.0e-7);
}
void testWrite()
{
// Write tested with a read/write/read/comparison procedure
printMethod(TEST_FUNC);
System<3> system;
BasisFieldState<3> bfs1(system), bfs2(system);
BFieldComparison comparison;
// Setup system
BasisFieldStateTest::SetUpSystem(system);
// read, write, read
bfs1.read("in/bcc/omega.ref");
bfs1.write("out/testBasisFieldStateWrite.ref");
bfs2.read("out/testBasisFieldStateWrite.ref");
// compare
comparison.compare(bfs1.fields(),bfs2.fields());
// Assert small difference
TEST_ASSERT(comparison.maxDiff() < 5.0e-7);
}
void testGetSystemState()
{
printMethod(TEST_FUNC);
System<3> system;
BasisFieldState<3> bfs(system);
BFieldComparison comparison;
// Setup system
BasisFieldStateTest::SetUpSystem(system);
// Read in state using system
system.readWBasis("in/bcc/omega.ref");
// get it using bfs
bfs.getSystemState();
// compare
comparison.compare(bfs.fields(),system.w().basis());
// Assert small difference
TEST_ASSERT(comparison.maxDiff() < 5.0e-7);
}
void testSetSystemState()
{
printMethod(TEST_FUNC);
System<3> system;
BasisFieldState<3> bfs(system);
BFieldComparison comparison;
// Setup system
BasisFieldStateTest::SetUpSystem(system);
// Read in state using bfs
bfs.read("in/bcc/omega.ref");
// set system state
bfs.setSystemState(true);
// compare
comparison.compare(bfs.fields(),system.w().basis());
// Assert small difference
TEST_ASSERT(comparison.maxDiff() < 5.0e-7);
}
void testSetSystem()
{
printMethod(TEST_FUNC);
System<3> system;
BasisFieldState<3> bfs;
// Setup system
BasisFieldStateTest::SetUpSystem(system);
// Invoke setSystem
bfs.setSystem(system);
}
void SetUpSystem(System<3>& system)
{
system.fileMaster().setInputPrefix(filePrefix());
system.fileMaster().setOutputPrefix(filePrefix());
std::ifstream in;
openInputFile("in/bcc/param.flex", in);
system.readParam(in);
in.close();
FSArray<double, 6> parameters;
parameters.append(1.75);
system.setUnitCell(parameters);
}
};
TEST_BEGIN(BasisFieldStateTest)
TEST_ADD(BasisFieldStateTest, testConstructor)
TEST_ADD(BasisFieldStateTest, testRead)
TEST_ADD(BasisFieldStateTest, testWrite)
TEST_ADD(BasisFieldStateTest, testGetSystemState)
TEST_ADD(BasisFieldStateTest, testSetSystemState)
TEST_ADD(BasisFieldStateTest, testSetSystem)
TEST_END(BasisFieldStateTest)
#endif
| 3,853
|
C++
|
.h
| 125
| 25.208
| 65
| 0.686312
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,040
|
SweepTest.h
|
dmorse_pscfpp/src/pspg/tests/sweep/SweepTest.h
|
#ifndef PSPG_SWEEP_TEST_H
#define PSPG_SWEEP_TEST_H
#include <test/UnitTest.h>
#include <test/UnitTestRunner.h>
#include <pspg/System.h>
#include <pspg/sweep/SweepFactory.h>
#include <pspg/sweep/LinearSweep.h>
#include <pscf/crystal/BFieldComparison.h>
#include <util/tests/LogFileUnitTest.h>
#include <util/format/Dbl.h>
#include <fstream>
#include <sstream>
using namespace Util;
using namespace Pscf;
using namespace Pspg;
class SweepTest : public LogFileUnitTest
{
public:
void setUp()
{ setVerbose(0); }
void testConstructors()
{
printMethod(TEST_FUNC);
System<3> system;
LinearSweep<3> ls(system);
SweepFactory<3> sf(system);
}
void testFactory()
{
printMethod(TEST_FUNC);
System<3> system;
SweepFactory<3> sf(system);
Sweep<3>* sweepPtr;
sweepPtr = sf.factory("LinearSweep");
TEST_ASSERT(sweepPtr != 0);
}
void testParameterRead()
{
printMethod(TEST_FUNC);
// Set up system with some data
System<1> system;
SweepTest::SetUpSystem(system, "in/block/param");
// Set up SweepParameter objects
DArray< SweepParameter<1> > ps;
ps.allocate(4);
for (int i = 0; i < 4; ++i) {
ps[i].setSystem(system);
}
// Open test input file
std::ifstream in;
// Read in data
openInputFile("in/param.test", in);
for (int i = 0; i < 4; ++i) {
in >> ps[i];
}
// Assert that it is read correctly
TEST_ASSERT(ps[0].type()=="block");
TEST_ASSERT(ps[0].id(0)==0);
TEST_ASSERT(ps[0].id(1)==0);
TEST_ASSERT(ps[0].change()==0.25);
TEST_ASSERT(ps[1].type()=="chi");
TEST_ASSERT(ps[1].id(0)==0);
TEST_ASSERT(ps[1].id(1)==1);
TEST_ASSERT(ps[1].change()==5.00);
TEST_ASSERT(ps[2].type()=="kuhn");
TEST_ASSERT(ps[2].id(0)==0);
TEST_ASSERT(ps[2].change()==0.1);
TEST_ASSERT(ps[3].type()=="phi_polymer");
TEST_ASSERT(ps[3].id(0)==0);
TEST_ASSERT(ps[3].change()==-0.01);
}
void testParameterGet()
{
printMethod(TEST_FUNC);
// Set up system
System<1> system;
SweepTest::SetUpSystem(system, "in/block/param");
// Set up SweepParameter objects
DArray< SweepParameter<1> > ps;
ps.allocate(4);
std::ifstream in;
openInputFile("in/param.test", in);
for (int i = 0; i < 4; ++i) {
ps[i].setSystem(system);
in >> ps[i];
}
DArray<double> sysval, paramval;
sysval.allocate(4);
paramval.allocate(4);
// Call get_ function to get value through parameter
for (int i = 0; i < 4; ++i) {
paramval[i] = ps[i].current();
}
// Manually check equality for each one
sysval[0] = system.mixture().polymer(0).block(0).length();
sysval[1] = system.interaction().chi(0,1);
sysval[2] = system.mixture().monomer(0).kuhn();
sysval[3] = system.mixture().polymer(0).phi();
for (int i = 0; i < 4; ++i) {
TEST_ASSERT(sysval[i] == paramval[i]);
}
}
void testParameterSet()
{
printMethod(TEST_FUNC);
// Set up system
System<1> system;
SweepTest::SetUpSystem(system, "in/block/param");
// Set up SweepParameter objects
DArray< SweepParameter<1> > ps;
ps.allocate(4);
std::ifstream in;
openInputFile("in/param.test", in);
for (int i = 0; i < 4; ++i) {
ps[i].setSystem(system);
in >> ps[i];
ps[i].getInitial();
}
DArray<double> sysval, paramval;
sysval.allocate(4);
paramval.allocate(4);
// Set for some arbitrary value of s in [0,1]
double s = 0.295586;
double newVal;
for (int i = 0; i < 4; ++i) {
newVal = ps[i].initial() + s*ps[i].change();
ps[i].update(newVal);
}
// Calculate expected value of parameter using s
for (int i = 0; i < 4; ++i) {
paramval[i] = ps[i].initial() + s*ps[i].change();
}
// Manually check equality for each one
sysval[0] = system.mixture().polymer(0).block(0).length();
sysval[1] = system.interaction().chi(0,1);
sysval[2] = system.mixture().monomer(0).kuhn();
sysval[3] = system.mixture().polymer(0).phi();
for (int i = 0; i < 4; ++i) {
TEST_ASSERT(sysval[i]==paramval[i]);
}
}
void testLinearSweepRead()
{
printMethod(TEST_FUNC);
// Set up system with Linear Sweep Object
System<1> system;
SweepTest::SetUpSystem(system, "in/block/param");
}
void testLinearSweepBlock()
{
printMethod(TEST_FUNC);
openLogFile("out/testLinearSweepBlock");
double maxDiff = testLinearSweepParam("block");
TEST_ASSERT(maxDiff < 5.0e-7);
}
void testLinearSweepChi()
{
printMethod(TEST_FUNC);
openLogFile("out/testLinearSweepChi");
double maxDiff = testLinearSweepParam("chi");
TEST_ASSERT(maxDiff < 5.0e-7);
}
void testLinearSweepKuhn()
{
printMethod(TEST_FUNC);
openLogFile("out/testLinearSweepKuhn");
double maxDiff = testLinearSweepParam("kuhn");
TEST_ASSERT(maxDiff < 5.0e-7);
}
void testLinearSweepPhi()
{
printMethod(TEST_FUNC);
openLogFile("out/testLinearSweepPhi");
double maxDiff = testLinearSweepParam("phi");
TEST_ASSERT(maxDiff < 5.0e-7);
}
void testLinearSweepSolvent()
{
printMethod(TEST_FUNC);
openLogFile("out/testLinearSweepSolvent");
double maxDiff = testLinearSweepParam("solvent");
TEST_ASSERT(maxDiff < 5.0e-7);
}
void SetUpSystem(System<1>& system, std::string fname)
{
system.fileMaster().setInputPrefix(filePrefix());
system.fileMaster().setOutputPrefix(filePrefix());
std::ifstream in;
openInputFile(fname, in);
system.readParam(in);
in.close();
FSArray<double, 6> parameters;
parameters.append(1.3835);
system.setUnitCell(parameters);
}
double testLinearSweepParam(std::string paramname)
{
// Set up system with a LinearSweep object
System<1> system;
SweepTest::SetUpSystem(system, "in/" + paramname + "/param");
// Read expected w fields
DArray< BasisFieldState<1> > fieldsRef;
fieldsRef.allocate(5);
for (int i = 0; i < 5; ++i) {
fieldsRef[i].setSystem(system);
fieldsRef[i].read("in/sweepref/" + paramname + "/" + std::to_string(i) +"_w.bf");
}
// Read initial field guess and sweep
system.readWBasis("in/" + paramname + "/w.bf");
system.sweep();
// Check if sweep had to backtrack. It shouldn't need to.
std::ifstream f(std::string(filePrefix() + "out/" + paramname + "/5_w.bf").c_str());
if (f.good()) {
TEST_THROW("Sweep backtracked due to iteration count greater than maxItr.");
}
// Read outputted fields
DArray< BasisFieldState<1> > fieldsOut;
fieldsOut.allocate(5);
for (int i = 0; i < 5; ++i) {
fieldsOut[i].setSystem(system);
fieldsOut[i].read("out/" + paramname + "/" + std::to_string(i) +"_w.bf");
}
// Compare output
BFieldComparison comparison(1);
double maxDiff = 0.0;
for (int i = 0; i < 5; ++i) {
comparison.compare(fieldsRef[i].fields(), fieldsOut[i].fields());
if (comparison.maxDiff() > maxDiff) {
maxDiff = comparison.maxDiff();
}
}
//setVerbose(1);
if (verbose() > 0) {
Log::file() << std::endl;
Log::file() << "maxDiff = " << Dbl(maxDiff, 14, 6) << std::endl;
}
return maxDiff;
}
};
TEST_BEGIN(SweepTest)
TEST_ADD(SweepTest, testConstructors)
TEST_ADD(SweepTest, testFactory)
TEST_ADD(SweepTest, testParameterRead)
TEST_ADD(SweepTest, testParameterGet)
TEST_ADD(SweepTest, testParameterSet)
TEST_ADD(SweepTest, testLinearSweepRead)
TEST_ADD(SweepTest, testLinearSweepBlock)
TEST_ADD(SweepTest, testLinearSweepChi)
TEST_ADD(SweepTest, testLinearSweepKuhn)
TEST_ADD(SweepTest, testLinearSweepPhi)
TEST_ADD(SweepTest, testLinearSweepSolvent)
TEST_END(SweepTest)
#endif
| 8,231
|
C++
|
.h
| 253
| 26.094862
| 90
| 0.61159
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,041
|
SystemTest.h
|
dmorse_pscfpp/src/pspg/tests/system/SystemTest.h
|
#ifndef PSPG_SYSTEM_TEST_H
#define PSPG_SYSTEM_TEST_H
#include <test/UnitTest.h>
#include <test/UnitTestRunner.h>
#include <pspg/System.h>
#include <pspg/field/RDField.h>
#include <pspg/math/GpuResources.h>
#include <pscf/crystal/BFieldComparison.h>
#include <util/tests/LogFileUnitTest.h>
#include <fstream>
using namespace Util;
using namespace Pscf;
using namespace Pscf::Pspg;
class SystemTest : public LogFileUnitTest
{
public:
void setUp()
{ setVerbose(0); }
void testConstructor1D()
{
printMethod(TEST_FUNC);
System<1> system;
}
void testReadParameters1D()
{
printMethod(TEST_FUNC);
System<1> system;
setupSystem<1>(system,"in/diblock/lam/param.flex");
}
void testConversion1D_lam()
{
printMethod(TEST_FUNC);
openLogFile("out/testConversion1D_lam.log");
System<1> system;
setupSystem<1>(system,"in/diblock/lam/param.flex");
// Read w-fields (reference solution, solved by Fortran PSCF)
system.readWBasis("in/diblock/lam/omega.in");
// Get reference field
DArray< DArray<double> > b_wFields_check;
//copyFieldsBasis(b_wFields_check, system.w().basis());
b_wFields_check = system.w().basis();
// Round trip conversion basis -> rgrid -> basis, read result
system.basisToRGrid("in/diblock/lam/omega.in",
"out/testConversion1D_lam_w.rf");
system.rGridToBasis("out/testConversion1D_lam_w.rf",
"out/testConversion1D_lam_w.bf");
system.readWBasis("out/testConversion1D_lam_w.bf");
// Get test result
DArray< DArray<double> > b_wFields;
//copyFieldsBasis(b_wFields, system.w().basis());
b_wFields = system.w().basis();
// Compare result to original
BFieldComparison comparison (1);
comparison.compare(b_wFields_check, b_wFields);
if (verbose()>0) {
Log::file() << "\n";
Log::file() << "Max error = " << comparison.maxDiff() << "\n";
}
TEST_ASSERT(comparison.maxDiff() < 1.0E-10);
}
void testConversion2D_hex()
{
printMethod(TEST_FUNC);
openLogFile("out/testConversion2D_hex.log");
System<2> system;
setupSystem<2>(system,"in/diblock/hex/param.flex");
// Read w fields
system.readWBasis("in/diblock/hex/omega.in");
// Get reference field
DArray< DArray<double> > b_wFields_check;
//copyFieldsBasis(b_wFields_check, system.w().basis());
b_wFields_check = system.w().basis();
// Round trip basis -> rgrid -> basis, read resulting wField
system.basisToRGrid("in/diblock/hex/omega.in",
"out/testConversion2D_hex_w.rf");
system.rGridToBasis("out/testConversion2D_hex_w.rf",
"out/testConversion2D_hex_w.bf");
system.readWBasis("out/testConversion2D_hex_w.bf");
// Get test result
DArray< DArray<double> > b_wFields;
//copyFieldsBasis(b_wFields, system.w().basis());
b_wFields = system.w().basis();
// Compare result to original
BFieldComparison comparison (1);
comparison.compare(b_wFields_check, b_wFields);
if (verbose()>0) {
Log::file() << "\n";
Log::file() << "Max error = " << comparison.maxDiff() << "\n";
}
TEST_ASSERT(comparison.maxDiff() < 1.0E-10);
}
void testConversion3D_bcc()
{
printMethod(TEST_FUNC);
openLogFile("out/testConversion3D_bcc.log");
System<3> system;
setupSystem<3>(system,"in/diblock/bcc/param.flex");
// Read w fields in system.wFields
system.readWBasis("in/diblock/bcc/omega.in");
// Get reference field
DArray< DArray<double> > b_wFields_check;
copyFieldsBasis(b_wFields_check, system.w().basis());
// Complete round trip basis -> rgrid -> basis
system.basisToRGrid("in/diblock/bcc/omega.in",
"out/testConversion3D_bcc_w.rf");
system.rGridToBasis("out/testConversion3D_bcc_w.rf",
"out/testConversion3D_bcc_w.bf");
system.readWBasis("out/testConversion3D_bcc_w.bf");
// Get test result
DArray< DArray<double> > b_wFields;
copyFieldsBasis(b_wFields, system.w().basis());
// Compare result to original
BFieldComparison comparison (1);
comparison.compare(b_wFields_check, b_wFields);
if (verbose()>0) {
Log::file() << "\n";
Log::file() << "Max error = " << comparison.maxDiff() << "\n";
}
TEST_ASSERT(comparison.maxDiff() < 1.0E-10);
}
/* void testCheckSymmetry3D_bcc()
* {
* printMethod(TEST_FUNC);
* System<3> system;
* system.fileMaster().setInputPrefix(filePrefix());
* system.fileMaster().setOutputPrefix(filePrefix());
*
* openLogFile("out/testSymmetry3D_bcc.log");
*
* // Read system parameter file
* std::ifstream in;
* openInputFile("in/diblock/bcc/param.flex", in);
* system.readParam(in);
* in.close();
*
* system.readWBasis("in/diblock/bcc/omega.in");
* bool hasSymmetry = system.fieldIo().hasSymmetry(system.w().rgrid(0));
* TEST_ASSERT(hasSymmetry);
*
* // Intentionally mess up the field, check that symmetry is destroyed
* system.w().rgrid(0)[23] += 0.1;
* hasSymmetry = system.fieldIo().hasSymmetry(system.w().rgrid(0));
* TEST_ASSERT(!hasSymmetry);
*
* }
*/
template <int D>
void setupSystem(System<D>& system, std::string fname)
{
system.fileMaster().setInputPrefix(filePrefix());
system.fileMaster().setOutputPrefix(filePrefix());
std::ifstream in;
openInputFile(fname, in);
system.readParam(in);
in.close();
}
void copyFieldsBasis(DArray< DArray<double> > & out,
DArray< DArray<double> > const & in)
{
UTIL_CHECK(in.isAllocated());
int nField = in.capacity();
UTIL_CHECK(nField > 0);
// If array out is not allocated, allocate
if (!out.isAllocated()) {
out.allocate(nField);
}
int nPoint = in[0].capacity();
for (int i = 0; i < nField; i++) {
UTIL_CHECK(in[i].capacity() == nPoint);
if (!out[i].isAllocated()) {
out[i].allocate(nPoint);
} else {
UTIL_CHECK(out[i].capacity() == nPoint);
}
}
// Copy arrays
for (int i = 0; i < nField; i++) {
UTIL_CHECK(out[i].capacity() == in[i].capacity());
out[i] = in[i];
}
}
#if 0
template <int D>
void copyFieldsRGrid(DArray< RDField<D> > & out,
DArray< RDField<D> > const & in)
{
UTIL_CHECK(in.isAllocated());
int nField = in.capacity();
UTIL_CHECK(nField > 0);
// If array out is not allocated, allocate
if (!out.isAllocated()) {
out.allocate(nField);
}
IntVec<D> dim = in[0].meshDimensions();
for (int i = 0; i < nField; i++) {
UTIL_CHECK(in[i].meshDimensions() == dim);
if (!out[i].isAllocated()) {
out[i].allocate(dim);
} else {
UTIL_CHECK(out[i].meshDimensions() == dim);
}
}
// Copy arrays
for (int i = 0; i < nField; i++) {
UTIL_CHECK(out[i].capacity() == in[i].capacity());
UTIL_CHECK(out[i].meshDimensions() == in[i].meshDimensions());
out[i] = in[i];
}
}
#endif
};
TEST_BEGIN(SystemTest)
TEST_ADD(SystemTest, testConstructor1D)
TEST_ADD(SystemTest, testReadParameters1D)
TEST_ADD(SystemTest, testConversion1D_lam)
TEST_ADD(SystemTest, testConversion2D_hex)
TEST_ADD(SystemTest, testConversion3D_bcc)
//// TEST_ADD(SystemTest, testCheckSymmetry3D_bcc)
TEST_END(SystemTest)
#endif
| 7,779
|
C++
|
.h
| 220
| 28.813636
| 76
| 0.61311
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,042
|
AmIteratorTest.h
|
dmorse_pscfpp/src/pspg/tests/system/AmIteratorTest.h
|
#ifndef PSPG_AM_ITERATOR_TEST_H
#define PSPG_AM_ITERATOR_TEST_H
#include <test/UnitTest.h>
#include <test/UnitTestRunner.h>
#include <pspg/System.h>
#include <pspg/field/RDField.h>
#include <pspg/math/GpuResources.h>
#include <pscf/crystal/BFieldComparison.h>
#include <util/tests/LogFileUnitTest.h>
#include <fstream>
using namespace Util;
using namespace Pscf;
using namespace Pscf::Pspg;
class AmIteratorTest : public LogFileUnitTest
{
public:
void setUp()
{ setVerbose(0); }
void testIterate1D_lam_rigid()
{
printMethod(TEST_FUNC);
openLogFile("out/testIterate1D_lam_rigid.log");
System<1> system;
setupSystem<1>(system,"in/diblock/lam/param.rigid");
// Read w fields
system.readWBasis("in/diblock/lam/omega.ref");
// Make reference copy of w fields in basis format
DArray< DArray<double> > b_wFields_check;
copyFieldsBasis(b_wFields_check, system.w().basis());
// Iterate and output solution
int error = system.iterate();
if (error) {
TEST_THROW("Iterator failed to converge.");
}
system.writeWBasis("out/testIterate1D_lam_rigid_w.bf");
system.writeCBasis("out/testIterate1D_lam_rigid_c.bf");
// Compare result to original in basis format
// DArray< DArray<double> > b_wFields;
// copyFieldsBasis(b_wFields, system.w().basis());
BFieldComparison comparison(1);
// comparison.compare(b_wFields_check, b_wFields);
comparison.compare(b_wFields_check, system.w().basis());
if (verbose() > 0) {
Log::file() << "\n";
Log::file() << "Max error = " << comparison.maxDiff() << "\n";
}
TEST_ASSERT(comparison.maxDiff() < 5.0E-7);
}
void testIterate1D_lam_flex()
{
printMethod(TEST_FUNC);
openLogFile("out/testIterate1D_lam_flex.log");
System<1> system;
setupSystem<1>(system,"in/diblock/lam/param.flex");
system.readWBasis("in/diblock/lam/omega.ref");
// Make reference copy of w fields
DArray< DArray<double> > b_wFields_check;
copyFieldsBasis(b_wFields_check, system.w().basis());
// Read input w-fields, iterate and output solution
system.readWBasis("in/diblock/lam/omega.in");
int error = system.iterate();
if (error) {
TEST_THROW("Iterator failed to converge.");
};
system.writeWBasis("out/testIterate1D_lam_flex_w.bf");
system.writeCBasis("out/testIterate1D_lam_flex_c.bf");
// Get test result
DArray< DArray<double> > b_wFields;
copyFieldsBasis(b_wFields, system.w().basis());
// Compare result to original
BFieldComparison comparison (1);
comparison.compare(b_wFields_check, b_wFields);
// Compare difference to tolerance epsilon
double diff = comparison.maxDiff();
double epsilon = 5.0E-7;
if (verbose() > 0 || diff > epsilon) {
Log::file() << "\n";
Log::file() << "Max diff = " << comparison.maxDiff() << "\n";
Log::file() << "Rms diff = " << comparison.rmsDiff() << "\n";
Log::file() << "epsilon = " << epsilon << "\n";
}
TEST_ASSERT(diff < epsilon);
}
void testIterate1D_lam_soln()
{
printMethod(TEST_FUNC);
openLogFile("out/testIterate1D_lam_soln.log");
System<1> system;
setupSystem<1>(system,"in/solution/lam/param");
// Make reference copy of w fields
system.readWBasis("in/solution/lam/w.bf");
DArray< DArray<double> > b_wFields_check;
copyFieldsBasis(b_wFields_check, system.w().basis());
// iterate and output solution
int error = system.iterate();
if (error) {
TEST_THROW("Iterator failed to converge.");
};
system.writeWBasis("out/testIterate1D_lam_soln_w.bf");
system.writeCBasis("out/testIterate1D_lam_soln_c.bf");
// Get test result
DArray< DArray<double> > b_wFields;
copyFieldsBasis(b_wFields, system.w().basis());
// Compare result to original
BFieldComparison comparison (1);
comparison.compare(b_wFields_check, b_wFields);
// Compare difference to tolerance epsilon
double diff = comparison.maxDiff();
double epsilon = 2.0E-6;
if (verbose() > 0 || diff > epsilon) {
Log::file() << "\n";
Log::file() << "Max diff = " << comparison.maxDiff() << "\n";
Log::file() << "Rms diff = " << comparison.rmsDiff() << "\n";
Log::file() << "epsilon = " << epsilon << "\n";
}
TEST_ASSERT(diff < epsilon);
}
void testIterate1D_lam_blend()
{
printMethod(TEST_FUNC);
openLogFile("out/testIterate1D_lam_blend.log");
System<1> system;
setupSystem<1>(system,"in/blend/lam/param.closed");
// Make reference copy of w fields
system.readWBasis("in/blend/lam/w.ref");
DArray< DArray<double> > b_wFields_check;
copyFieldsBasis(b_wFields_check, system.w().basis());
// Read input w-fields, iterate and output solution
system.readWBasis("in/blend/lam/w.bf");
int error = system.iterate();
if (error) {
TEST_THROW("Iterator failed to converge.");
};
system.writeWBasis("out/testIterate1D_lam_blend_w.bf");
system.writeCBasis("out/testIterate1D_lam_blend_c.bf");
// Get test result
DArray< DArray<double> > b_wFields;
copyFieldsBasis(b_wFields, system.w().basis());
// Compare result to original
BFieldComparison comparison (1);
comparison.compare(b_wFields_check, b_wFields);
double diff = comparison.maxDiff();
double epsilon = 5.0E-7;
//setVerbose(1);
if (verbose() > 0 || diff > epsilon) {
Log::file() << "\n";
Log::file() << "Max diff = " << comparison.maxDiff() << "\n";
Log::file() << "Rms diff = " << comparison.rmsDiff() << "\n";
Log::file() << "epsilon = " << epsilon << "\n";
}
TEST_ASSERT(diff < epsilon);
}
void testIterate1D_lam_open_soln()
{
printMethod(TEST_FUNC);
openLogFile("out/testIterate1D_lam_open_soln.log");
System<1> system;
setupSystem<1>(system,"in/solution/lam_open/param");
// Make reference copy of w fields
system.readWBasis("in/solution/lam_open/w.ref");
DArray< DArray<double> > b_wFields_check;
copyFieldsBasis(b_wFields_check, system.w().basis());
// Read input w-fields, iterate and output solution
system.readWBasis("in/solution/lam_open/w.bf");
int error = system.iterate();
if (error) {
TEST_THROW("Iterator failed to converge.");
};
system.writeWBasis("out/testIterate1D_lam_open_soln_w.bf");
system.writeCBasis("out/testIterate1D_lam_open_soln_c.bf");
// Get test result
DArray< DArray<double> > b_wFields;
copyFieldsBasis(b_wFields, system.w().basis());
// Compare result to original
BFieldComparison comparison (1);
comparison.compare(b_wFields_check, b_wFields);
// Compare difference to tolerance epsilon
double diff = comparison.maxDiff();
//double epsilon = 5.0E-7;
double epsilon = 6.0E-6;
if (diff > epsilon) {
Log::file() << "\n";
Log::file() << "Max diff = " << comparison.maxDiff() << "\n";
Log::file() << "Rms diff = " << comparison.rmsDiff() << "\n";
Log::file() << "epsilon = " << epsilon << "\n";
}
TEST_ASSERT(diff < epsilon);
}
void testIterate1D_lam_open_blend()
{
printMethod(TEST_FUNC);
openLogFile("out/testIterate1D_lam_open_blend.log");
System<1> system;
setupSystem<1>(system,"in/blend/lam/param.open");
// Make reference copy of w fields
system.readWBasis("in/blend/lam/w.ref");
DArray< DArray<double> > b_wFields_check;
copyFieldsBasis(b_wFields_check, system.w().basis());
// Read input w-fields, iterate and output solution
system.readWBasis("in/blend/lam/w.bf");
int error = system.iterate();
if (error) {
TEST_THROW("Iterator failed to converge.");
};
system.writeWBasis("out/testIterate1D_lam_open_blend_w.bf");
system.writeCBasis("out/testIterate1D_lam_open_blend_c.bf");
// Get test result
DArray< DArray<double> > b_wFields;
copyFieldsBasis(b_wFields, system.w().basis());
// Compare result to original
BFieldComparison comparison (1);
comparison.compare(b_wFields_check, b_wFields);
// Compare difference to tolerance epsilon
double diff = comparison.maxDiff();
double epsilon = 5.0E-7;
if (diff > epsilon) {
Log::file() << "\n";
Log::file() << "Max diff = " << comparison.maxDiff() << "\n";
Log::file() << "Rms diff = " << comparison.rmsDiff() << "\n";
Log::file() << "epsilon = " << epsilon << "\n";
}
TEST_ASSERT(diff < epsilon);
}
void testIterate2D_hex_rigid()
{
printMethod(TEST_FUNC);
openLogFile("out/testIterate2D_hex_rigid.log");
System<2> system;
setupSystem<2>(system,"in/diblock/hex/param.rigid");
// Read reference solution
system.readWBasis("in/diblock/hex/omega.ref");
TEST_ASSERT(system.basis().isInitialized());
// Make reference copy of w fields
DArray< DArray<double> > b_wFields_check;
copyFieldsBasis(b_wFields_check, system.w().basis());
// Read initial guess, iterate, output solution
// PSPC tests start from the reference solution,
// rather than a nearby solution, so I guess do that here too?
// system.readWBasis("in/diblock/hex/omega.in");
Log::file() << "Beginning iteration \n";
int error = system.iterate();
if (error) {
TEST_THROW("Iterator failed to converge.");
};
system.writeWBasis("out/testIterate2D_hex_rigid_w.bf");
system.writeCBasis("out/testIterate2D_hex_rigid_c.bf");
// Get test result
DArray< DArray<double> > b_wFields;
copyFieldsBasis(b_wFields, system.w().basis());
// Compare result to original
BFieldComparison comparison (1);
comparison.compare(b_wFields_check, b_wFields);
// Compare difference to tolerance epsilon
double diff = comparison.maxDiff();
double epsilon = 5.0E-7;
if (diff > epsilon) {
Log::file() << "\n";
Log::file() << "Max diff = " << comparison.maxDiff() << "\n";
Log::file() << "Rms diff = " << comparison.rmsDiff() << "\n";
Log::file() << "epsilon = " << epsilon << "\n";
}
TEST_ASSERT(diff < epsilon);
}
void testIterate2D_hex_flex()
{
printMethod(TEST_FUNC);
openLogFile("out/testIterate2D_hex_flex.log");
System<2> system;
setupSystem<2>(system,"in/diblock/hex/param.flex");
// Read reference solution (produced by Fortran code)
system.readWBasis("in/diblock/hex/omega.ref");
// Make reference copy of w fields
DArray< DArray<double> > b_wFields_check;
copyFieldsBasis(b_wFields_check, system.w().basis());
system.readWBasis("in/diblock/hex/omega.in");
int error = system.iterate();
if (error) {
TEST_THROW("Iterator failed to converge.");
};
system.writeWBasis("out/testIterate2D_hex_flex_w.bf");
system.writeCBasis("out/testIterate2D_hex_flex_c.bf");
// Get test result
DArray< DArray<double> > b_wFields;
copyFieldsBasis(b_wFields, system.w().basis());
// Compare result to original
BFieldComparison comparison (1);
comparison.compare(b_wFields_check, b_wFields);
// Compare difference to tolerance epsilon
double diff = comparison.maxDiff();
double epsilon = 8.0E-7;
if (diff > epsilon) {
Log::file() << "\n";
Log::file() << "Max diff = " << comparison.maxDiff() << "\n";
Log::file() << "Rms diff = " << comparison.rmsDiff() << "\n";
Log::file() << "epsilon = " << epsilon << "\n";
}
TEST_ASSERT(diff < epsilon);
}
void testIterate3D_bcc_rigid()
{
printMethod(TEST_FUNC);
openLogFile("out/testIterate3D_bcc_rigid.log");
System<3> system;
setupSystem<3>(system,"in/diblock/bcc/param.rigid");
system.readWBasis("in/diblock/bcc/omega.ref");
// Make reference copy of w fields
DArray< DArray<double> > b_wFields_check;
copyFieldsBasis(b_wFields_check, system.w().basis());
system.readWBasis("in/diblock/bcc/omega.in");
int error = system.iterate();
if (error) {
TEST_THROW("Iterator failed to converge.");
};
system.writeWBasis("out/testIterate3D_bcc_rigid_w.bf");
system.writeCBasis("out/testIterate3D_bcc_rigid_c.bf");
// Get test result
DArray< DArray<double> > b_wFields;
copyFieldsBasis(b_wFields, system.w().basis());
// Compare result to original
BFieldComparison comparison (1);
comparison.compare(b_wFields_check, b_wFields);
// Compare difference to tolerance epsilon
double diff = comparison.maxDiff();
double epsilon = 7.0E-7;
if (diff > epsilon) {
Log::file() << "\n";
Log::file() << "Max diff = " << comparison.maxDiff() << "\n";
Log::file() << "Rms diff = " << comparison.rmsDiff() << "\n";
Log::file() << "epsilon = " << epsilon << "\n";
}
TEST_ASSERT(diff < epsilon);
}
void testIterate3D_bcc_flex()
{
printMethod(TEST_FUNC);
openLogFile("out/testIterate3D_bcc_flex.log");
System<3> system;
setupSystem<3>(system,"in/diblock/bcc/param.flex");
system.readWBasis("in/diblock/bcc/omega.ref");
// Make reference copy of w fields
DArray< DArray<double> > b_wFields_check;
copyFieldsBasis(b_wFields_check, system.w().basis());
system.readWBasis("in/diblock/bcc/omega.in");
int error = system.iterate();
if (error) {
TEST_THROW("Iterator failed to converge.");
};
system.writeWBasis("out/testIterate3D_bcc_flex_w.bf");
system.writeCBasis("out/testIterate3D_bcc_flex_c.bf");
// Get test result
DArray< DArray<double> > b_wFields;
copyFieldsBasis(b_wFields, system.w().basis());
// Compare result to original
BFieldComparison comparison (1);
comparison.compare(b_wFields_check, b_wFields);
// Compare difference to tolerance epsilon
double diff = comparison.maxDiff();
double epsilon = 5.0E-7;
if (diff > epsilon) {
Log::file() << "\n";
Log::file() << "Max diff = " << comparison.maxDiff() << "\n";
Log::file() << "Rms diff = " << comparison.rmsDiff() << "\n";
Log::file() << "epsilon = " << epsilon << "\n";
}
TEST_ASSERT(diff < epsilon);
}
template <int D>
void setupSystem(System<D>& system, std::string fname)
{
system.fileMaster().setInputPrefix(filePrefix());
system.fileMaster().setOutputPrefix(filePrefix());
std::ifstream in;
openInputFile(fname, in);
system.readParam(in);
in.close();
}
void copyFieldsBasis(DArray< DArray<double> > & out,
DArray< DArray<double> > const & in)
{
UTIL_CHECK(in.isAllocated());
int nField = in.capacity();
UTIL_CHECK(nField > 0);
// If array out is not allocated, allocate
if (!out.isAllocated()) {
out.allocate(nField);
}
int nPoint = in[0].capacity();
for (int i = 0; i < nField; i++) {
UTIL_CHECK(in[i].capacity() == nPoint);
if (!out[i].isAllocated()) {
out[i].allocate(nPoint);
} else {
UTIL_CHECK(out[i].capacity() == nPoint);
}
}
// Copy arrays
for (int i = 0; i < nField; i++) {
UTIL_CHECK(out[i].capacity() == in[i].capacity());
out[i] = in[i];
}
}
#if 0
template <int D>
void copyFieldsRGrid(DArray< RDField<D> > & out,
DArray< RDField<D> > const & in)
{
UTIL_CHECK(in.isAllocated());
int nField = in.capacity();
UTIL_CHECK(nField > 0);
// If array out is not allocated, allocate
if (!out.isAllocated()) {
out.allocate(nField);
}
IntVec<D> dim = in[0].meshDimensions();
for (int i = 0; i < nField; i++) {
UTIL_CHECK(in[i].meshDimensions() == dim);
if (!out[i].isAllocated()) {
out[i].allocate(dim);
} else {
UTIL_CHECK(out[i].meshDimensions() == dim);
}
}
// Copy arrays
for (int i = 0; i < nField; i++) {
UTIL_CHECK(out[i].capacity() == in[i].capacity());
UTIL_CHECK(out[i].meshDimensions() == in[i].meshDimensions());
out[i] = in[i];
}
}
#endif
};
TEST_BEGIN(AmIteratorTest)
TEST_ADD(AmIteratorTest, testIterate1D_lam_rigid)
TEST_ADD(AmIteratorTest, testIterate1D_lam_flex)
TEST_ADD(AmIteratorTest, testIterate1D_lam_soln)
TEST_ADD(AmIteratorTest, testIterate1D_lam_blend)
TEST_ADD(AmIteratorTest, testIterate1D_lam_open_blend)
TEST_ADD(AmIteratorTest, testIterate1D_lam_open_soln)
TEST_ADD(AmIteratorTest, testIterate2D_hex_rigid)
TEST_ADD(AmIteratorTest, testIterate2D_hex_flex)
TEST_ADD(AmIteratorTest, testIterate3D_bcc_rigid)
TEST_ADD(AmIteratorTest, testIterate3D_bcc_flex)
TEST_END(AmIteratorTest)
#endif
| 17,450
|
C++
|
.h
| 444
| 32.177928
| 71
| 0.614629
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,043
|
AmIteratorGridTest.h
|
dmorse_pscfpp/src/pspg/tests/system/AmIteratorGridTest.h
|
#ifndef PSPG_AM_ITERATOR_GRID_TEST_H
#define PSPG_AM_ITERATOR_GRID_TEST_H
#include <test/UnitTest.h>
#include <test/UnitTestRunner.h>
#include <pspg/System.h>
#include <pspg/field/RDField.h>
#include <pspg/math/GpuResources.h>
#include <pscf/crystal/BFieldComparison.h>
#include <util/tests/LogFileUnitTest.h>
#include <fstream>
using namespace Util;
using namespace Pscf;
using namespace Pscf::Pspg;
class AmIteratorGridTest : public LogFileUnitTest
{
public:
void setUp()
{ setVerbose(0); }
void testIterate1D_lam_rigid()
{
printMethod(TEST_FUNC);
openLogFile("out/testIterateGrid1D_lam_rigid.log");
System<1> system;
setupSystem<1>(system,"in/diblock/lam/param.rigid_grid");
// Read w fields
system.readWBasis("in/diblock/lam/omega.ref");
// Get reference field in basis format
DArray< DArray<double> > b_wFields_check;
copyFieldsBasis(b_wFields_check, system.w().basis());
// Iterate and output solution
int error = system.iterate();
if (error) {
TEST_THROW("Iterator failed to converge.");
}
system.writeWBasis("out/testIterate1D_lam_rigid_w.bf");
system.writeCBasis("out/testIterate1D_lam_rigid_c.bf");
// Compare result to original in basis format
DArray< DArray<double> > b_wFields;
copyFieldsBasis(b_wFields, system.w().basis());
BFieldComparison comparison(1);
comparison.compare(b_wFields_check, b_wFields);
if (verbose() > 0) {
Log::file() << "\n";
Log::file() << "Max error = " << comparison.maxDiff() << "\n";
}
TEST_ASSERT(comparison.maxDiff() < 5.0E-7);
#if 0
// Get reference field in r-grid format
DArray< RDField<1> > r_wFields_check;
copyFieldsRGrid(r_wFields_check, system.w().rgrid());
// Compare result to original in rgrid format
DArray< RDField<1> > r_wFields;
copyFieldsBasis(b_wFields, system.w().basis());
BFieldComparison comparison(1);
comparison.compare(b_wFields_check, b_wFields);
if (verbose() > 0) {
Log::file() << "\n";
Log::file() << "Max error = " << comparison.maxDiff() << "\n";
}
TEST_ASSERT(comparison.maxDiff() < 5.0E-7);
#endif
}
void testIterate1D_lam_flex()
{
printMethod(TEST_FUNC);
openLogFile("out/testIterateGrid1D_lam_flex.log");
System<1> system;
setupSystem<1>(system,"in/diblock/lam/param.flex_grid");
system.readWBasis("in/diblock/lam/omega.ref");
// Get reference field
DArray< DArray<double> > b_wFields_check;
copyFieldsBasis(b_wFields_check, system.w().basis());
// Read input w-fields, iterate and output solution
system.readWBasis("in/diblock/lam/omega.in");
int error = system.iterate();
if (error) {
TEST_THROW("Iterator failed to converge.");
};
system.writeWBasis("out/testIterate1D_lam_flex_w.bf");
system.writeCBasis("out/testIterate1D_lam_flex_c.bf");
// Get test result
DArray< DArray<double> > b_wFields;
copyFieldsBasis(b_wFields, system.w().basis());
// Compare result to original
BFieldComparison comparison (1);
comparison.compare(b_wFields_check, b_wFields);
// Compare difference to tolerance epsilon
double diff = comparison.maxDiff();
double epsilon = 5.0E-7;
if (verbose() > 0 || diff > epsilon) {
Log::file() << "\n";
Log::file() << "Max diff = " << comparison.maxDiff() << "\n";
Log::file() << "Rms diff = " << comparison.rmsDiff() << "\n";
Log::file() << "epsilon = " << epsilon << "\n";
}
TEST_ASSERT(diff < epsilon);
}
void testIterate1D_lam_soln()
{
printMethod(TEST_FUNC);
openLogFile("out/testIterateGrid1D_lam_soln.log");
System<1> system;
setupSystem<1>(system,"in/solution/lam/param.grid");
// Get reference field
system.readWBasis("in/solution/lam/w.bf");
DArray< DArray<double> > b_wFields_check;
copyFieldsBasis(b_wFields_check, system.w().basis());
// iterate and output solution
int error = system.iterate();
if (error) {
TEST_THROW("Iterator failed to converge.");
};
system.writeWBasis("out/testIterate1D_lam_soln_w.bf");
system.writeCBasis("out/testIterate1D_lam_soln_c.bf");
// Get test result
DArray< DArray<double> > b_wFields;
copyFieldsBasis(b_wFields, system.w().basis());
// Compare result to original
BFieldComparison comparison (1);
comparison.compare(b_wFields_check, b_wFields);
// Compare difference to tolerance epsilon
double diff = comparison.maxDiff();
double epsilon = 2.0E-6;
if (verbose() > 0 || diff > epsilon) {
Log::file() << "\n";
Log::file() << "Max diff = " << comparison.maxDiff() << "\n";
Log::file() << "Rms diff = " << comparison.rmsDiff() << "\n";
Log::file() << "epsilon = " << epsilon << "\n";
}
TEST_ASSERT(diff < epsilon);
}
void testIterate1D_lam_blend()
{
printMethod(TEST_FUNC);
openLogFile("out/testIterateGrid1D_lam_blend.log");
System<1> system;
setupSystem<1>(system,"in/blend/lam/param.closed_grid");
// Get reference field
system.readWBasis("in/blend/lam/w.ref");
DArray< DArray<double> > b_wFields_check;
copyFieldsBasis(b_wFields_check, system.w().basis());
// Read input w-fields, iterate and output solution
system.readWBasis("in/blend/lam/w.bf");
int error = system.iterate();
if (error) {
TEST_THROW("Iterator failed to converge.");
};
system.writeWBasis("out/testIterate1D_lam_blend_w.bf");
system.writeCBasis("out/testIterate1D_lam_blend_c.bf");
// Get test result
DArray< DArray<double> > b_wFields;
copyFieldsBasis(b_wFields, system.w().basis());
// Compare result to original
BFieldComparison comparison (1);
comparison.compare(b_wFields_check, b_wFields);
double diff = comparison.maxDiff();
double epsilon = 5.0E-7;
setVerbose(1);
if (verbose() > 0 || diff > epsilon) {
Log::file() << "\n";
Log::file() << "Max diff = " << comparison.maxDiff() << "\n";
Log::file() << "Rms diff = " << comparison.rmsDiff() << "\n";
Log::file() << "epsilon = " << epsilon << "\n";
}
TEST_ASSERT(diff < epsilon);
}
void testIterate1D_lam_open_soln()
{
printMethod(TEST_FUNC);
openLogFile("out/testIterateGrid1D_lam_open_soln.log");
System<1> system;
setupSystem<1>(system,"in/solution/lam_open/param.grid");
// Get reference field
system.readWBasis("in/solution/lam_open/w.ref");
DArray< DArray<double> > b_wFields_check;
copyFieldsBasis(b_wFields_check, system.w().basis());
// Read input w-fields, iterate and output solution
system.readWBasis("in/solution/lam_open/w.bf");
int error = system.iterate();
if (error) {
TEST_THROW("Iterator failed to converge.");
};
system.writeWBasis("out/testIterate1D_lam_open_soln_w.bf");
system.writeCBasis("out/testIterate1D_lam_open_soln_c.bf");
// Get test result
DArray< DArray<double> > b_wFields;
copyFieldsBasis(b_wFields, system.w().basis());
// Compare result to original
BFieldComparison comparison (1);
comparison.compare(b_wFields_check, b_wFields);
// Compare difference to tolerance epsilon
double diff = comparison.maxDiff();
//double epsilon = 5.0E-7;
double epsilon = 6.0E-6;
if (diff > epsilon) {
Log::file() << "\n";
Log::file() << "Max diff = " << comparison.maxDiff() << "\n";
Log::file() << "Rms diff = " << comparison.rmsDiff() << "\n";
Log::file() << "epsilon = " << epsilon << "\n";
}
TEST_ASSERT(diff < epsilon);
}
void testIterate1D_lam_open_blend()
{
printMethod(TEST_FUNC);
openLogFile("out/testIterateGrid1D_lam_open_blend.log");
System<1> system;
setupSystem<1>(system,"in/blend/lam/param.open_grid");
// Get reference field
system.readWBasis("in/blend/lam/w.ref");
DArray< DArray<double> > b_wFields_check;
copyFieldsBasis(b_wFields_check, system.w().basis());
// Read input w-fields, iterate and output solution
system.readWBasis("in/blend/lam/w.bf");
int error = system.iterate();
if (error) {
TEST_THROW("Iterator failed to converge.");
};
system.writeWBasis("out/testIterate1D_lam_open_blend_w.bf");
system.writeCBasis("out/testIterate1D_lam_open_blend_c.bf");
// Get test result
DArray< DArray<double> > b_wFields;
copyFieldsBasis(b_wFields, system.w().basis());
// Compare result to original
BFieldComparison comparison (1);
comparison.compare(b_wFields_check, b_wFields);
// Compare difference to tolerance epsilon
double diff = comparison.maxDiff();
double epsilon = 5.0E-7;
if (diff > epsilon) {
Log::file() << "\n";
Log::file() << "Max diff = " << comparison.maxDiff() << "\n";
Log::file() << "Rms diff = " << comparison.rmsDiff() << "\n";
Log::file() << "epsilon = " << epsilon << "\n";
}
TEST_ASSERT(diff < epsilon);
}
void testIterate2D_hex_rigid()
{
printMethod(TEST_FUNC);
openLogFile("out/testIterateGrid2D_hex_rigid.log");
System<2> system;
setupSystem<2>(system,"in/diblock/hex/param.rigid_grid");
// Read reference solution
system.readWBasis("in/diblock/hex/omega.ref");
// Get reference field
DArray< DArray<double> > b_wFields_check;
copyFieldsBasis(b_wFields_check, system.w().basis());
// Read initial guess, iterate, output solution
// PSPC tests start from the reference solution,
// rather than a nearby solution, so I guess do that here too?
// system.readWBasis("in/diblock/hex/omega.in");
int error = system.iterate();
if (error) {
TEST_THROW("Iterator failed to converge.");
};
system.writeWBasis("out/testIterate2D_hex_rigid_w.bf");
system.writeCBasis("out/testIterate2D_hex_rigid_c.bf");
// Get test result
DArray< DArray<double> > b_wFields;
copyFieldsBasis(b_wFields, system.w().basis());
// Compare result to original
BFieldComparison comparison (1);
comparison.compare(b_wFields_check, b_wFields);
// Compare difference to tolerance epsilon
double diff = comparison.maxDiff();
double epsilon = 5.0E-7;
if (diff > epsilon) {
Log::file() << "\n";
Log::file() << "Max diff = " << comparison.maxDiff() << "\n";
Log::file() << "Rms diff = " << comparison.rmsDiff() << "\n";
Log::file() << "epsilon = " << epsilon << "\n";
}
TEST_ASSERT(diff < epsilon);
}
void testIterate2D_hex_flex()
{
printMethod(TEST_FUNC);
openLogFile("out/testIterateGrid2D_hex_flex.log");
System<2> system;
setupSystem<2>(system,"in/diblock/hex/param.flex_grid");
// Read reference solution (produced by Fortran code)
system.readWBasis("in/diblock/hex/omega.ref");
// Get reference field
DArray< DArray<double> > b_wFields_check;
copyFieldsBasis(b_wFields_check, system.w().basis());
system.readWBasis("in/diblock/hex/omega.in");
int error = system.iterate();
if (error) {
TEST_THROW("Iterator failed to converge.");
};
system.writeWBasis("out/testIterate2D_hex_flex_w.bf");
system.writeCBasis("out/testIterate2D_hex_flex_c.bf");
// Get test result
DArray< DArray<double> > b_wFields;
copyFieldsBasis(b_wFields, system.w().basis());
// Compare result to original
BFieldComparison comparison (1);
comparison.compare(b_wFields_check, b_wFields);
// Compare difference to tolerance epsilon
double diff = comparison.maxDiff();
double epsilon = 8.0E-7;
if (diff > epsilon) {
Log::file() << "\n";
Log::file() << "Max diff = " << comparison.maxDiff() << "\n";
Log::file() << "Rms diff = " << comparison.rmsDiff() << "\n";
Log::file() << "epsilon = " << epsilon << "\n";
}
TEST_ASSERT(diff < epsilon);
}
void testIterate3D_bcc_rigid()
{
printMethod(TEST_FUNC);
openLogFile("out/testIterateGrid3D_bcc_rigid.log");
System<3> system;
setupSystem<3>(system,"in/diblock/bcc/param.rigid_grid");
system.readWBasis("in/diblock/bcc/omega.ref");
// Get reference field
DArray< DArray<double> > b_wFields_check;
copyFieldsBasis(b_wFields_check, system.w().basis());
system.readWBasis("in/diblock/bcc/omega.in");
int error = system.iterate();
if (error) {
TEST_THROW("Iterator failed to converge.");
};
system.writeWBasis("out/testIterate3D_bcc_rigid_w.bf");
system.writeCBasis("out/testIterate3D_bcc_rigid_c.bf");
// Get test result
DArray< DArray<double> > b_wFields;
copyFieldsBasis(b_wFields, system.w().basis());
// Compare result to original
BFieldComparison comparison (1);
comparison.compare(b_wFields_check, b_wFields);
// Compare difference to tolerance epsilon
double diff = comparison.maxDiff();
double epsilon = 7.0E-7;
if (diff > epsilon) {
Log::file() << "\n";
Log::file() << "Max diff = " << comparison.maxDiff() << "\n";
Log::file() << "Rms diff = " << comparison.rmsDiff() << "\n";
Log::file() << "epsilon = " << epsilon << "\n";
}
TEST_ASSERT(diff < epsilon);
}
void testIterate3D_bcc_flex()
{
printMethod(TEST_FUNC);
openLogFile("out/testIterateGrid3D_bcc_flex.log");
System<3> system;
setupSystem<3>(system,"in/diblock/bcc/param.flex_grid");
system.readWBasis("in/diblock/bcc/omega.ref");
// Get reference field
DArray< DArray<double> > b_wFields_check;
copyFieldsBasis(b_wFields_check, system.w().basis());
system.readWBasis("in/diblock/bcc/omega.in");
int error = system.iterate();
if (error) {
TEST_THROW("Iterator failed to converge.");
};
system.writeWBasis("out/testIterate3D_bcc_flex_w.bf");
system.writeCBasis("out/testIterate3D_bcc_flex_c.bf");
// Get test result
DArray< DArray<double> > b_wFields;
copyFieldsBasis(b_wFields, system.w().basis());
// Compare result to original
BFieldComparison comparison (1);
comparison.compare(b_wFields_check, b_wFields);
// Compare difference to tolerance epsilon
double diff = comparison.maxDiff();
double epsilon = 5.0E-7;
if (diff > epsilon) {
Log::file() << "\n";
Log::file() << "Max diff = " << comparison.maxDiff() << "\n";
Log::file() << "Rms diff = " << comparison.rmsDiff() << "\n";
Log::file() << "epsilon = " << epsilon << "\n";
}
TEST_ASSERT(diff < epsilon);
}
template <int D>
void setupSystem(System<D>& system, std::string fname)
{
system.fileMaster().setInputPrefix(filePrefix());
system.fileMaster().setOutputPrefix(filePrefix());
std::ifstream in;
openInputFile(fname, in);
system.readParam(in);
in.close();
}
void copyFieldsBasis(DArray< DArray<double> > & out,
DArray< DArray<double> > const & in)
{
UTIL_CHECK(in.isAllocated());
int nField = in.capacity();
UTIL_CHECK(nField > 0);
// If array out is not allocated, allocate
if (!out.isAllocated()) {
out.allocate(nField);
}
int nPoint = in[0].capacity();
for (int i = 0; i < nField; i++) {
UTIL_CHECK(in[i].capacity() == nPoint);
if (!out[i].isAllocated()) {
out[i].allocate(nPoint);
} else {
UTIL_CHECK(out[i].capacity() == nPoint);
}
}
// Copy arrays
for (int i = 0; i < nField; i++) {
UTIL_CHECK(out[i].capacity() == in[i].capacity());
out[i] = in[i];
}
}
#if 0
template <int D>
void copyFieldsRGrid(DArray< RDField<D> > & out,
DArray< RDField<D> > const & in)
{
UTIL_CHECK(in.isAllocated());
int nField = in.capacity();
UTIL_CHECK(nField > 0);
// If array out is not allocated, allocate
if (!out.isAllocated()) {
out.allocate(nField);
}
IntVec<D> dim = in[0].meshDimensions();
for (int i = 0; i < nField; i++) {
UTIL_CHECK(in[i].meshDimensions() == dim);
if (!out[i].isAllocated()) {
out[i].allocate(dim);
} else {
UTIL_CHECK(out[i].meshDimensions() == dim);
}
}
// Copy arrays
for (int i = 0; i < nField; i++) {
UTIL_CHECK(out[i].capacity() == in[i].capacity());
UTIL_CHECK(out[i].meshDimensions() == in[i].meshDimensions());
out[i] = in[i];
}
}
#endif
};
TEST_BEGIN(AmIteratorGridTest)
TEST_ADD(AmIteratorGridTest, testIterate1D_lam_rigid)
TEST_ADD(AmIteratorGridTest, testIterate1D_lam_flex)
TEST_ADD(AmIteratorGridTest, testIterate1D_lam_soln)
TEST_ADD(AmIteratorGridTest, testIterate1D_lam_blend)
TEST_ADD(AmIteratorGridTest, testIterate1D_lam_open_blend)
TEST_ADD(AmIteratorGridTest, testIterate1D_lam_open_soln)
TEST_ADD(AmIteratorGridTest, testIterate2D_hex_rigid)
TEST_ADD(AmIteratorGridTest, testIterate2D_hex_flex)
TEST_ADD(AmIteratorGridTest, testIterate3D_bcc_rigid)
TEST_ADD(AmIteratorGridTest, testIterate3D_bcc_flex)
TEST_END(AmIteratorGridTest)
#endif
| 17,911
|
C++
|
.h
| 456
| 32.138158
| 71
| 0.615682
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,044
|
SystemTestComposite.h
|
dmorse_pscfpp/src/pspg/tests/system/SystemTestComposite.h
|
#ifndef PSPG_TEST_SYSTEM_TEST_COMPOSITE_H
#define PSPG_TEST_SYSTEM_TEST_COMPOSITE_H
#include <test/CompositeTestRunner.h>
#include "SystemTest.h"
#include "AmIteratorTest.h"
#include "AmIteratorGridTest.h"
TEST_COMPOSITE_BEGIN(SystemTestComposite)
TEST_COMPOSITE_ADD_UNIT(SystemTest);
TEST_COMPOSITE_ADD_UNIT(AmIteratorTest);
TEST_COMPOSITE_ADD_UNIT(AmIteratorGridTest);
TEST_COMPOSITE_END
#endif
| 401
|
C++
|
.h
| 12
| 32.083333
| 44
| 0.844156
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,045
|
CudaMemTest.h
|
dmorse_pscfpp/src/pspg/tests/cuda/CudaMemTest.h
|
#ifndef PSPG_CUDA_MEM_TEST_H
#define PSPG_CUDA_MEM_TEST_H
#include <test/UnitTest.h>
#include <test/UnitTestRunner.h>
#include <pspg/field/RDField.h>
#include <util/math/Constants.h>
#include <pspg/math/GpuResources.h>
#include <fstream>
#include <iomanip>
using namespace Util;
using namespace Pscf;
using namespace Pscf::Pspg;
class CudaMemTest : public UnitTest
{
public:
void setUp()
{}
void tearDown()
{}
void testCopyRoundTrip()
{
printMethod(TEST_FUNC);
int nx = 10;
// device array
RDField<1> d_in;
d_in.allocate(10);
// host arrays
cudaReal* in = new cudaReal[nx];
cudaReal* out = new cudaReal[nx];
// random data
double twoPi = 2.0*Constants::Pi;
for (int i=0; i < nx; ++i) {
in[i] = cos(twoPi*double(i)/double(nx));
}
// copy round trip
cudaMemcpy(d_in.cDField(), in, nx*sizeof(cudaReal), cudaMemcpyHostToDevice);
cudaMemcpy(out, d_in.cDField(), nx*sizeof(cudaReal), cudaMemcpyDeviceToHost);
// compare
double maxDiff = 0, currDiff = 0;
for (int i = 0; i < nx; ++i ) {
currDiff = std::abs( in[i] - out[i] );
if ( currDiff > maxDiff ) {
maxDiff = currDiff;
}
TEST_ASSERT( in[i] == out[i] );
}
// std::cout << std::setprecision(16) << maxDiff << std::endl;
}
};
TEST_BEGIN(CudaMemTest)
TEST_ADD(CudaMemTest, testCopyRoundTrip)
TEST_END(CudaMemTest)
#endif
| 1,485
|
C++
|
.h
| 53
| 22.867925
| 83
| 0.626241
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,046
|
CudaResourceTest.h
|
dmorse_pscfpp/src/pspg/tests/cuda/CudaResourceTest.h
|
#ifndef PSPG_CUDA_RESOURCE_TEST_H
#define PSPG_CUDA_RESOURCE_TEST_H
#include <test/UnitTest.h>
#include <test/UnitTestRunner.h>
#include <pspg/field/RDField.h>
#include <util/math/Constants.h>
#include <pspg/math/GpuResources.h>
#include <cstdlib>
#include <cmath>
using namespace Util;
using namespace Pscf;
using namespace Pscf::Pspg;
class CudaResourceTest : public UnitTest
{
public:
void setUp()
{}
void tearDown()
{}
void testReductionSum()
{
printMethod(TEST_FUNC);
// GPU Resources
ThreadGrid::init();
const int nThreads = 32;
ThreadGrid::setThreadsPerBlock(nThreads);
// Data size and number of blocks
const int n = 32*nThreads*2;
int nBlocks;
ThreadGrid::setThreadsLogical(n/2, nBlocks);
// Create device and host arrays
cudaReal sum = 0;
cudaReal sumCheck = 0;
cudaReal* num = new cudaReal[n];
cudaReal* d_temp;
cudaReal* d_num;
cudaMalloc((void**) &d_num, n*sizeof(cudaReal));
cudaMalloc((void**) &d_temp, nBlocks*sizeof(cudaReal));
// Test data
for (int i = 0; i < n; i++) {
num[i] = (cudaReal)(std::rand() % 10000);
}
// Host find max
for (int i = 0; i < n; i++) {
sumCheck+=num[i];
}
// Launch kernel twice and get output
cudaMemcpy(d_num, num, n*sizeof(cudaReal), cudaMemcpyHostToDevice);
reductionSum<<<nBlocks, nThreads, nThreads*sizeof(cudaReal)>>>(d_temp, d_num, n);
reductionSum<<<1, nBlocks/2, nBlocks/2*sizeof(cudaReal)>>>(d_temp, d_temp, nBlocks);
cudaMemcpy(&sum, d_temp, 1*sizeof(cudaReal), cudaMemcpyDeviceToHost);
TEST_ASSERT(sum == sumCheck);
}
void testReductionMaxSmall()
{
printMethod(TEST_FUNC);
// GPU Resources
ThreadGrid::init();
const int nThreads = 32;
ThreadGrid::setThreadsPerBlock(nThreads);
// Data size and number of blocks
const int n = 1*nThreads*2;
int nBlocks;
ThreadGrid::setThreadsLogical(n/2, nBlocks);
// Create device and host arrays
cudaReal max = -1;
cudaReal maxCheck = -10;
cudaReal* num = new cudaReal[n];
cudaReal* d_max;
cudaReal* d_num;
cudaMalloc((void**) &d_max, 1*sizeof(cudaReal));
cudaMalloc((void**) &d_num, n*sizeof(cudaReal));
// Test data
for (int i = 0; i < n; i++) {
num[i] = (cudaReal)(std::rand() % 100);
}
cudaMemcpy(d_num, num, n*sizeof(cudaReal), cudaMemcpyHostToDevice);
// Host find max
maxCheck = 0;
for (int i = 0; i < n; i++) {
if (num[i] > maxCheck) {
maxCheck = num[i];
}
}
// Launch kernel and get output
reductionMax<<<nBlocks, nThreads, nThreads*sizeof(cudaReal)>>>(d_max, d_num, n);
cudaMemcpy(&max, d_max, 1*sizeof(cudaReal), cudaMemcpyDeviceToHost);
TEST_ASSERT(max == maxCheck);
}
void testReductionMaxLarge()
{
printMethod(TEST_FUNC);
// GPU Resources
ThreadGrid::init();
const int nThreads = 32;
ThreadGrid::setThreadsPerBlock(nThreads);
// Data size and number of blocks
const int n = 8*nThreads*2;
int nBlocks;
ThreadGrid::setThreadsLogical(n/2, nBlocks);
// Create device and host arrays
cudaReal max = -1;
cudaReal maxCheck = -10;
cudaReal* num = new cudaReal[n];
cudaReal* d_temp;
cudaReal* d_max;
cudaReal* d_num;
cudaMalloc((void**) &d_num, n*sizeof(cudaReal));
cudaMalloc((void**) &d_temp, nBlocks*sizeof(cudaReal));
cudaMalloc((void**) &d_max, 1*sizeof(cudaReal));
// Test data
for (int i = 0; i < n; i++) {
num[i] = (cudaReal)(std::rand() % 10000);
}
// Host find max
for (int i = 0; i < n; i++) {
if (num[i] > maxCheck) {
maxCheck = num[i];
}
}
// Launch kernel twice and get output
cudaMemcpy(d_num, num, n*sizeof(cudaReal), cudaMemcpyHostToDevice);
reductionMax<<<nBlocks, nThreads, nThreads*sizeof(cudaReal)>>>(d_temp, d_num, n);
reductionMax<<<1, nBlocks/2, nBlocks/2*sizeof(cudaReal)>>>(d_max, d_temp, nBlocks);
cudaMemcpy(&max, d_max, 1*sizeof(cudaReal), cudaMemcpyDeviceToHost);
TEST_ASSERT(max == maxCheck);
}
void testReductionMaxAbsLarge()
{
printMethod(TEST_FUNC);
// GPU Resources
ThreadGrid::init();
const int nThreads = 32;
ThreadGrid::setThreadsPerBlock(nThreads);
// Data size and number of blocks
const int n = 8*nThreads*2;
int nBlocks;
ThreadGrid::setThreadsLogical(n/2, nBlocks);
// Create device and host arrays
cudaReal max = -1;
cudaReal maxCheck = -10;
cudaReal* num = new cudaReal[n];
cudaReal* d_temp;
cudaReal* d_max;
cudaReal* d_num;
cudaMalloc((void**) &d_num, n*sizeof(cudaReal));
cudaMalloc((void**) &d_temp, nBlocks*sizeof(cudaReal));
cudaMalloc((void**) &d_max, 1*sizeof(cudaReal));
// Test data
for (int i = 0; i < n; i++) {
num[i] = (cudaReal)(std::rand() % 10000 - 6000);
}
// Host find max
for (int i = 0; i < n; i++) {
if (fabs(num[i]) > maxCheck) {
maxCheck = fabs(num[i]);
}
}
// Launch kernel twice and get output
cudaMemcpy(d_num, num, n*sizeof(cudaReal), cudaMemcpyHostToDevice);
reductionMaxAbs<<<nBlocks, nThreads, nThreads*sizeof(cudaReal)>>>(d_temp, d_num, n);
reductionMaxAbs<<<1, nBlocks/2, nBlocks/2*sizeof(cudaReal)>>>(d_max, d_temp, nBlocks);
cudaMemcpy(&max, d_max, 1*sizeof(cudaReal), cudaMemcpyDeviceToHost);
TEST_ASSERT(max == maxCheck);
}
void testReductionMinLarge()
{
printMethod(TEST_FUNC);
// GPU Resources
ThreadGrid::init();
const int nThreads = 32;
ThreadGrid::setThreadsPerBlock(nThreads);
// Data size and number of blocks
const int n = 8*nThreads*2;
int nBlocks;
ThreadGrid::setThreadsLogical(n/2, nBlocks);
// Create device and host arrays
cudaReal min = 100000;
cudaReal minCheck = 100000;
cudaReal* num = new cudaReal[n];
cudaReal* d_temp;
cudaReal* d_min;
cudaReal* d_num;
cudaMalloc((void**) &d_num, n*sizeof(cudaReal));
cudaMalloc((void**) &d_temp, nBlocks*sizeof(cudaReal));
cudaMalloc((void**) &d_min, 1*sizeof(cudaReal));
// Test data
for (int i = 0; i < n; i++) {
num[i] = (cudaReal)(std::rand() % 10000);
}
// Host find max
for (int i = 0; i < n; i++) {
if (num[i] < minCheck) {
minCheck = num[i];
}
}
// Launch kernel twice and get output
cudaMemcpy(d_num, num, n*sizeof(cudaReal), cudaMemcpyHostToDevice);
reductionMin<<<nBlocks, nThreads, nThreads*sizeof(cudaReal)>>>(d_temp, d_num, n);
reductionMin<<<1, nBlocks/2, nBlocks/2*sizeof(cudaReal)>>>(d_min, d_temp, nBlocks);
cudaMemcpy(&min, d_min, 1*sizeof(cudaReal), cudaMemcpyDeviceToHost);
TEST_ASSERT(min == minCheck);
}
void testGpuInnerProduct()
{
printMethod(TEST_FUNC);
// GPU Resources
ThreadGrid::init();
const int nThreads = 128;
ThreadGrid::setThreadsPerBlock(nThreads);
// Data size and number of blocks.
// Non-power-of-two to check performance in weird situations
const int n = 14*nThreads + 77;
int nBlocks;
ThreadGrid::setThreadsLogical(n/2, nBlocks);
// Device arrays
DField<cudaReal> d_a, d_b;
d_a.allocate(n);
d_b.allocate(n);
// Host arrays
cudaReal* a = new cudaReal[n];
cudaReal* b = new cudaReal[n];
// Create random data, store on host and device
for (int i = 0; i < n; i++ ) {
a[i] = (cudaReal)(std::rand() % 10000);
b[i] = (cudaReal)(std::rand() % 10000);
}
cudaMemcpy(d_a.cDField(), a, n*sizeof(cudaReal), cudaMemcpyHostToDevice);
cudaMemcpy(d_b.cDField(), b, n*sizeof(cudaReal), cudaMemcpyHostToDevice);
// Inner product on host
cudaReal prodCheck = 0;
for (int i = 0; i < n; i++) {
prodCheck += a[i]*b[i];
}
// Inner product on device
cudaReal prod = gpuInnerProduct(d_a.cDField(),d_b.cDField(),n);
TEST_ASSERT(prodCheck==prod);
}
void testGpuSum()
{
printMethod(TEST_FUNC);
// GPU Resources
ThreadGrid::init();
const int nThreads = 128;
ThreadGrid::setThreadsPerBlock(nThreads);
// Data size and number of blocks.
// Non-power-of-two to check performance in weird situations
const int n = 14*nThreads + 77;
int nBlocks;
ThreadGrid::setThreadsLogical(n/2, nBlocks);
// Device arrays
DField<cudaReal> d_data;
d_data.allocate(n);
// Host arrays
cudaReal* data = new cudaReal[n];
// Create random data, store on host and device
for (int i = 0; i < n; i++) {
data[i] = (cudaReal)(std::rand() % 10000);
}
cudaMemcpy(d_data.cDField(), data, n*sizeof(cudaReal), cudaMemcpyHostToDevice);
// Inner product on host
cudaReal prodCheck = 0;
for (int i = 0; i < n; i++) {
prodCheck += data[i];
}
// Inner product on device
cudaReal prod = gpuSum(d_data.cDField(),n);
TEST_ASSERT(prodCheck==prod);
}
void testGpuMax()
{
printMethod(TEST_FUNC);
// GPU Resources
ThreadGrid::init();
const int nThreads = 128;
ThreadGrid::setThreadsPerBlock(nThreads);
// Data size and number of blocks.
// Non-power-of-two to check performance in weird situations
const int n = 14*nThreads + 77;
int nBlocks;
ThreadGrid::setThreadsLogical(n/2, nBlocks);
// Device arrays
DField<cudaReal> d_data;
d_data.allocate(n);
// Host arrays
cudaReal* data = new cudaReal[n];
// Create random data, store on host and device
for (int i = 0; i < n; i++) {
data[i] = (cudaReal)(std::rand() % 10000);
}
cudaMemcpy(d_data.cDField(), data, n*sizeof(cudaReal), cudaMemcpyHostToDevice);
// Inner product on host
cudaReal maxCheck = 0;
for (int i = 0; i < n; i++) {
if (data[i] > maxCheck) maxCheck = data[i];
}
// Inner product on device
cudaReal max = gpuMax(d_data.cDField(),n);
TEST_ASSERT(max==maxCheck);
}
void testGpuMaxAbs()
{
printMethod(TEST_FUNC);
// GPU Resources
ThreadGrid::init();
const int nThreads = 128;
ThreadGrid::setThreadsPerBlock(nThreads);
// Data size and number of blocks.
// Non-power-of-two to check performance in weird situations
const int n = 14*nThreads + 77;
int nBlocks;
ThreadGrid::setThreadsLogical(n/2, nBlocks);
// Device arrays
DField<cudaReal> d_data;
d_data.allocate(n);
// Host arrays
cudaReal* data = new cudaReal[n];
// Create random data, store on host and device
for (int i = 0; i < n; i++) {
data[i] = (cudaReal)(std::rand() % 10000 - 6000);
}
cudaMemcpy(d_data.cDField(), data, n*sizeof(cudaReal), cudaMemcpyHostToDevice);
// Inner product on host
cudaReal maxCheck = 0;
for (int i = 0; i < n; i++) {
if (fabs(data[i]) > maxCheck) maxCheck = fabs(data[i]);
}
// Inner product on device
cudaReal max = gpuMaxAbs(d_data.cDField(),n);
TEST_ASSERT(max==maxCheck);
}
void testGpuMin()
{
printMethod(TEST_FUNC);
// GPU Resources
ThreadGrid::init();
const int nThreads = 128;
ThreadGrid::setThreadsPerBlock(nThreads);
// Data size and number of blocks.
// Non-power-of-two to check performance in weird situations
const int n = 14*nThreads + 77;
int nBlocks;
ThreadGrid::setThreadsLogical(n/2, nBlocks);
// Device arrays
DField<cudaReal> d_data;
d_data.allocate(n);
// Host arrays
cudaReal* data = new cudaReal[n];
// Create random data, store on host and device
for (int i = 0; i < n; i++) {
data[i] = (cudaReal)(std::rand() % 10000);
}
cudaMemcpy(d_data.cDField(), data, n*sizeof(cudaReal), cudaMemcpyHostToDevice);
// Inner product on host
cudaReal minCheck = 1000000;
for (int i = 0; i < n; i++) {
if (data[i] < minCheck) minCheck = data[i];
}
// Inner product on device
cudaReal min = gpuMin(d_data.cDField(),n);
TEST_ASSERT(min==minCheck);
}
void testGpuMinAbs()
{
printMethod(TEST_FUNC);
// GPU Resources
ThreadGrid::init();
const int nThreads = 128;
ThreadGrid::setThreadsPerBlock(nThreads);
// Data size and number of blocks.
// Non-power-of-two to check performance in weird situations
const int n = 14*nThreads + 77;
int nBlocks;
ThreadGrid::setThreadsLogical(n/2, nBlocks);
// Device arrays
DField<cudaReal> d_data;
d_data.allocate(n);
// Host arrays
cudaReal* data = new cudaReal[n];
// Create random data, store on host and device
for (int i = 0; i < n; i++) {
data[i] = (cudaReal)(std::rand() % 10000 - 6000);
}
cudaMemcpy(d_data.cDField(), data, n*sizeof(cudaReal), cudaMemcpyHostToDevice);
// Inner product on host
cudaReal minCheck = 1E300;
for (int i = 0; i < n; i++) {
if (fabs(data[i]) < minCheck) minCheck = fabs(data[i]);
}
// Inner product on device
cudaReal min = gpuMinAbs(d_data.cDField(),n);
TEST_ASSERT(min==minCheck);
}
};
TEST_BEGIN(CudaResourceTest)
TEST_ADD(CudaResourceTest, testReductionSum)
TEST_ADD(CudaResourceTest, testReductionMaxSmall)
TEST_ADD(CudaResourceTest, testReductionMaxLarge)
TEST_ADD(CudaResourceTest, testReductionMaxAbsLarge)
TEST_ADD(CudaResourceTest, testReductionMinLarge)
TEST_ADD(CudaResourceTest, testGpuInnerProduct)
TEST_ADD(CudaResourceTest, testGpuSum)
TEST_ADD(CudaResourceTest, testGpuMax)
TEST_ADD(CudaResourceTest, testGpuMaxAbs)
TEST_ADD(CudaResourceTest, testGpuMin)
TEST_ADD(CudaResourceTest, testGpuMinAbs)
TEST_END(CudaResourceTest)
#endif
| 14,406
|
C++
|
.h
| 408
| 28.318627
| 92
| 0.614895
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,047
|
CudaTestComposite.h
|
dmorse_pscfpp/src/pspg/tests/cuda/CudaTestComposite.h
|
#ifndef PSPG_TEST_CUDA_TEST_COMPOSITE_H
#define PSPG_TEST_CUDA_TEST_COMPOSITE_H
#include <test/CompositeTestRunner.h>
#include "CudaMemTest.h"
#include "CudaResourceTest.h"
TEST_COMPOSITE_BEGIN(CudaTestComposite)
TEST_COMPOSITE_ADD_UNIT(CudaMemTest);
TEST_COMPOSITE_ADD_UNIT(CudaResourceTest);
TEST_COMPOSITE_END
#endif
| 324
|
C++
|
.h
| 10
| 31
| 42
| 0.841935
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,048
|
FieldTestComposite.h
|
dmorse_pscfpp/src/pspg/tests/field/FieldTestComposite.h
|
#ifndef PSPG_FIELD_TEST_COMPOSITE_H
#define PSPG_FIELD_TEST_COMPOSITE_H
#include <test/CompositeTestRunner.h>
#include "FftTest.h"
#include "DomainTest.h"
#include "FieldIoTest.h"
TEST_COMPOSITE_BEGIN(FieldTestComposite)
TEST_COMPOSITE_ADD_UNIT(FftTest);
TEST_COMPOSITE_ADD_UNIT(DomainTest);
TEST_COMPOSITE_ADD_UNIT(FieldIoTest);
TEST_COMPOSITE_END
#endif
| 360
|
C++
|
.h
| 12
| 28.666667
| 40
| 0.831395
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,049
|
FftTest.h
|
dmorse_pscfpp/src/pspg/tests/field/FftTest.h
|
#ifndef PSPG_FFT_TEST_H
#define PSPG_FFT_TEST_H
#include <test/UnitTest.h>
#include <test/UnitTestRunner.h>
#include <pspg/field/FFT.h>
#include <pspg/field/RDField.h>
#include <pspg/field/RDFieldDft.h>
//#include <pspg/field/RFieldComparison.h>
#include <util/math/Constants.h>
#include <util/format/Dbl.h>
using namespace Util;
using namespace Pscf::Pspg;
class FftTest : public UnitTest
{
public:
void setUp() {}
void tearDown() {}
void testConstructor();
void testTransform1D();
void testTransform2D();
void testTransform3D();
};
void FftTest::testConstructor()
{
printMethod(TEST_FUNC);
{
FFT<1> v;
}
}
void FftTest::testTransform1D() {
printMethod(TEST_FUNC);
// Data size
int n = 100;
IntVec<1> d;
d[0] = n;
RDField<1> d_rField;
RDFieldDft<1> d_kField;
d_rField.allocate(d);
d_kField.allocate(d);
FFT<1> v;
v.setup(d_rField, d_kField);
TEST_ASSERT(d_rField.capacity() == n);
// Initialize input data in a temporary array in host memory
cudaReal* in = new cudaReal[n];
double x;
double twoPi = 2.0*Constants::Pi;
for (int i = 0; i < n; ++i) {
x = twoPi*float(i)/float(n);
in[i] = cos(x);
}
// Copy data to device
cudaMemcpy(d_rField.cDField(), in,
n*sizeof(cudaReal), cudaMemcpyHostToDevice);
// Transform forward, r to k
v.forwardTransform(d_rField, d_kField);
// Inverse transform, k to r
RDField<1> d_rField_out;
d_rField_out.allocate(d);
v.inverseTransform(d_kField, d_rField_out);
// Copy to host memory
cudaReal* out = new cudaReal[n];
cudaMemcpy(out, d_rField_out.cDField(),
n*sizeof(cudaReal), cudaMemcpyDeviceToHost);
for (int i = 0; i < n; ++i) {
TEST_ASSERT( std::abs(in[i] - out[i]) < 1E-10 );
}
}
void FftTest::testTransform2D() {
printMethod(TEST_FUNC);
int n1 = 3, n2 = 3;
IntVec<2> d;
d[0] = n1;
d[1] = n2;
RDField<2> d_rField;
RDFieldDft<2> d_kField;
d_rField.allocate(d);
d_kField.allocate(d);
FFT<2> v;
v.setup(d_rField, d_kField);
TEST_ASSERT(d_rField.capacity() == n1*n2);
// Initialize input data in a temporary array in host memory
cudaReal* in = new cudaReal[n1*n2];
int rank = 0;
double x, y, cx, sy;
double twoPi = 2.0*Constants::Pi;
for (int i = 0; i < n1; i++) {
x = twoPi*float(i)/float(n1);
cx = cos(x);
for (int j = 0; j < n2; j++) {
y = twoPi*float(j)/float(n2);
sy = sin(y);
rank = j + (i * n2);
in[rank] = 0.5 + 0.2*cx + 0.6*cx*cx - 0.1*sy + 0.3*cx*sy;
}
}
// Copy data to device
cudaMemcpy(d_rField.cDField(), in,
n1*n2*sizeof(cudaReal), cudaMemcpyHostToDevice);
// Transform forward, r to k
v.forwardTransform(d_rField, d_kField);
// Inverse transform, k to r
RDField<2> d_rField_out;
d_rField_out.allocate(d);
v.inverseTransform(d_kField, d_rField_out);
// Copy to host memory
cudaReal* out = new cudaReal[n1*n2];
cudaMemcpy(out, d_rField_out.cDField(),
n1*n2*sizeof(cudaReal), cudaMemcpyDeviceToHost);
for (int i = 0; i < n1*n2; ++i) {
TEST_ASSERT( std::abs(in[i] - out[i]) < 1E-10 );
}
}
void FftTest::testTransform3D() {
printMethod(TEST_FUNC);
int n1 = 3, n2 = 3, n3 = 3;
IntVec<3> d;
d[0] = n1;
d[1] = n2;
d[2] = n3;
RDField<3> d_rField;
RDFieldDft<3> d_kField;
d_rField.allocate(d);
d_kField.allocate(d);
FFT<3> v;
v.setup(d_rField, d_kField);
TEST_ASSERT(d_rField.capacity() == n1*n2*n3);
// Initialize input data in a temporary array in host memory
cudaReal* in = new cudaReal[n1*n2*n3];
int rank = 0;
for (int i = 0; i < n1; i++) {
for (int j = 0; j < n2; j++) {
for (int k = 0; k < n3; k++){
rank = k + ((j + (i * n2)) * n3);
in[rank] = 1.0 + double(rank)/double(n1*n2*n3);
}
}
}
// Copy data to device
cudaMemcpy(d_rField.cDField(), in,
n1*n2*n3*sizeof(cudaReal), cudaMemcpyHostToDevice);
// Transform forward, r to k
v.forwardTransform(d_rField, d_kField);
// Inverse transform, k to r
RDField<3> d_rField_out;
d_rField_out.allocate(d);
v.inverseTransform(d_kField, d_rField_out);
// Copy to host memory
cudaReal* out = new cudaReal[n1*n2*n3];
cudaMemcpy(out, d_rField_out.cDField(),
n1*n2*n3*sizeof(cudaReal), cudaMemcpyDeviceToHost);
for (int i = 0; i < n1*n2*n3; ++i) {
TEST_ASSERT( std::abs(in[i] - out[i]) < 1E-10 );
}
}
TEST_BEGIN(FftTest)
TEST_ADD(FftTest, testConstructor)
TEST_ADD(FftTest, testTransform1D)
TEST_ADD(FftTest, testTransform2D)
TEST_ADD(FftTest, testTransform3D)
TEST_END(FftTest)
#endif
| 4,766
|
C++
|
.h
| 161
| 24.875776
| 66
| 0.621319
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,050
|
FieldIoTest.h
|
dmorse_pscfpp/src/pspg/tests/field/FieldIoTest.h
|
#ifndef PSPG_FIELD_IO_TEST_H
#define PSPG_FIELD_IO_TEST_H
#include <test/UnitTest.h>
#include <test/UnitTestRunner.h>
#include <pspg/field/RFieldComparison.h>
#include <pspg/field/KFieldComparison.h>
#include <pspg/field/Domain.h>
#include <pspg/field/FieldIo.h>
#include <pspg/field/RDField.h>
#include <pspg/field/RDFieldDft.h>
#include <pspg/field/FFT.h>
#include <pscf/crystal/BFieldComparison.h>
#include <pscf/crystal/Basis.h>
#include <pscf/crystal/UnitCell.h>
#include <pscf/mesh/Mesh.h>
#include <pscf/mesh/MeshIterator.h>
#include <util/tests/LogFileUnitTest.h>
#include <util/containers/DArray.h>
#include <util/misc/FileMaster.h>
#include <util/format/Dbl.h>
#include <iostream>
#include <fstream>
using namespace Util;
using namespace Pscf;
using namespace Pscf::Pspg;
class FieldIoTest : public LogFileUnitTest
{
FileMaster fileMaster_;
int nMonomer_;
public:
void setUp()
{
setVerbose(0);
nMonomer_ = 2;
}
/*
* Open and read parameter header to initialize Domain<D> system.
*/
template <int D>
void readParam(std::string filename, Domain<D>& domain)
{
std::ifstream in;
openInputFile(filename, in);
domain.readParam(in);
in.close();
}
/*
* Open and read file header to initialize Domain<D> system.
*/
template <int D>
void readHeader(std::string filename, Domain<D>& domain)
{
std::ifstream in;
openInputFile(filename, in);
domain.readRGridFieldHeader(in, nMonomer_);
in.close();
}
// Allocate an array of fields in symmetry adapated format
void allocateFields(int nMonomer, int nBasis,
DArray< DArray<double> >& fields)
{
fields.allocate(nMonomer);
for (int i = 0; i < nMonomer; ++i) {
fields[i].allocate(nBasis);
}
}
// Allocate an array of r-grid fields
template <int D>
void allocateFields(int nMonomer, IntVec<D> dimensions,
DArray< RDField<D> >& fields)
{
fields.allocate(nMonomer);
for (int i = 0; i < nMonomer; ++i) {
fields[i].allocate(dimensions);
}
}
// Allocate an array of k-grid fields
template <int D>
void allocateFields(int nMonomer, IntVec<D> dimensions,
DArray< RDFieldDft<D> >& fields)
{
fields.allocate(nMonomer);
for (int i = 0; i < nMonomer; ++i) {
fields[i].allocate(dimensions);
}
}
template <int D>
void readFieldsBasis(std::string filename, Domain<D>& domain,
DArray< DArray<double> >& fields)
{
std::ifstream in;
openInputFile(filename, in);
domain.fieldIo().readFieldsBasis(in, fields, domain.unitCell());
in.close();
}
template <int D>
void readFields(std::string filename, Domain<D>& domain,
DArray< RDField<D> >& fields)
{
std::ifstream in;
openInputFile(filename, in);
domain.fieldIo().readFieldsRGrid(in, fields, domain.unitCell());
in.close();
}
template <int D>
void readFields(std::string filename, Domain<D>& domain,
DArray< RDFieldDft<D> >& fields)
{
std::ifstream in;
openInputFile(filename, in);
domain.fieldIo().readFieldsKGrid(in, fields, domain.unitCell());
in.close();
}
template <int D>
void writeFields(std::string filename, Domain<D>& domain,
DArray< DArray<double> > const & fields)
{
std::ofstream out;
openOutputFile(filename, out);
domain.fieldIo().writeFieldsBasis(out, fields, domain.unitCell());
out.close();
}
template <int D>
void writeFields(std::string filename, Domain<D>& domain,
DArray< RDField<D> > const & fields)
{
std::ofstream out;
openOutputFile(filename, out);
domain.fieldIo().writeFieldsRGrid(out, fields, domain.unitCell());
out.close();
}
template <int D>
void writeFields(std::string filename, Domain<D>& domain,
DArray< RDFieldDft<D> > const & fields)
{
std::ofstream out;
openOutputFile(filename, out);
domain.fieldIo().writeFieldsKGrid(out, fields, domain.unitCell());
out.close();
}
void testReadHeader()
{
printMethod(TEST_FUNC);
Domain<3> domain;
domain.setFileMaster(fileMaster_);
readHeader("in/w_bcc.rf", domain);
TEST_ASSERT(domain.mesh().dimension(0) == 32);
TEST_ASSERT(domain.mesh().dimension(1) == 32);
TEST_ASSERT(domain.mesh().dimension(2) == 32);
TEST_ASSERT(domain.unitCell().lattice() == UnitCell<3>::Cubic);
TEST_ASSERT(domain.basis().nBasis() == 489);
//TEST_ASSERT(nMonomer_ == 2);
if (verbose() > 0) {
std::cout << "\n";
std::cout << "Cell = " << domain.unitCell() << "\n";
std::cout << "Ngrid = " << domain.mesh().dimensions() << "\n";
if (verbose() > 1) {
domain.basis().outputStars(std::cout);
}
}
DArray< DArray<double> > fb;
allocateFields(nMonomer_, domain.basis().nBasis(), fb);
DArray< RDField<3> > fr;
allocateFields(nMonomer_, domain.mesh().dimensions(), fr);
DArray< RDFieldDft<3> > fk;
allocateFields(nMonomer_, domain.mesh().dimensions(), fk);
}
void testBasisIo3D(std::string rf, std::string bf)
{
Domain<3> domain;
domain.setFileMaster(fileMaster_);
readHeader("in/" + rf, domain);
int nBasis = domain.basis().nBasis();
DArray< DArray<double> > d_bf_0;
allocateFields(nMonomer_, nBasis, d_bf_0);
DArray< DArray<double> > d_bf_1;
allocateFields(nMonomer_, nBasis, d_bf_1);
std::ifstream in;
openInputFile("in/" + bf, in);
domain.fieldIo().readFieldsBasis(in, d_bf_0, domain.unitCell());
in.close();
std::ofstream out;
openOutputFile("out/" + bf, out);
domain.fieldIo().writeFieldsBasis(out, d_bf_0, domain.unitCell());
out.close();
openInputFile("out/" + bf, in);
domain.fieldIo().readFieldsBasis(in, d_bf_1, domain.unitCell());
in.close();
// Perform comparison
BFieldComparison comparison;
comparison.compare(d_bf_0, d_bf_1);
TEST_ASSERT(comparison.maxDiff() < 1.0E-10);
//setVerbose(1);
if (verbose() > 0) {
std::cout << std::endl;
std::cout << Dbl(comparison.maxDiff(),21,13) << std::endl;
std::cout << Dbl(comparison.rmsDiff(),21,13) << std::endl;
}
}
void testBasisIo_bcc()
{
printMethod(TEST_FUNC);
testBasisIo3D("w_bcc.rf", "w_bcc.bf");
}
void testBasisIo_c15_1()
{
printMethod(TEST_FUNC);
testBasisIo3D("c_c15_1.rf","w_c15_1.bf");
}
void testBasisIo_altG()
{
printMethod(TEST_FUNC);
testBasisIo3D("w_altG.rf", "w_altG.bf");
}
void testBasisIo_altG_fort()
{
printMethod(TEST_FUNC);
testBasisIo3D("w_altG.rf", "w_altG_fort.bf");
}
void testRGridIo_bcc()
{
printMethod(TEST_FUNC);
Domain<3> domain;
domain.setFileMaster(fileMaster_);
readHeader("in/w_bcc.rf", domain);
DArray< RDField<3> > d_rf_0;
allocateFields(nMonomer_, domain.mesh().dimensions(), d_rf_0);
DArray< RDField<3> > d_rf_1;
allocateFields(nMonomer_, domain.mesh().dimensions(), d_rf_1);
readFields("in/w_bcc.rf", domain, d_rf_0);
writeFields("out/w_bcc.rf", domain, d_rf_0);
readFields("out/w_bcc.rf", domain, d_rf_1);
RFieldComparison<3> comparison;
comparison.compare(d_rf_0, d_rf_1);
TEST_ASSERT(comparison.maxDiff() < 1.0E-12);
if (verbose() > 0) {
std::cout << "\n";
std::cout << Dbl(comparison.maxDiff(),21,13) << "\n";
std::cout << Dbl(comparison.rmsDiff(),21,13) << "\n";
}
}
void testConvertBasisKGridBasis_bcc()
{
printMethod(TEST_FUNC);
Domain<3> domain;
domain.setFileMaster(fileMaster_);
readHeader("in/w_bcc.rf", domain);
int nBasis = domain.basis().nBasis();
DArray< DArray<double> > d_bf_0;
allocateFields(nMonomer_, nBasis, d_bf_0);
DArray< DArray<double> > d_bf_1;
allocateFields(nMonomer_, nBasis, d_bf_1);
DArray< RDFieldDft<3> > d_kf_0;
allocateFields(nMonomer_, domain.mesh().dimensions(), d_kf_0);
readFieldsBasis("in/w_bcc.bf", domain, d_bf_0);
domain.fieldIo().convertBasisToKGrid(d_bf_0, d_kf_0);
domain.fieldIo().convertKGridToBasis(d_kf_0, d_bf_1);
std::ofstream out;
openOutputFile("out/w_bcc_convert.bf", out);
domain.fieldIo().writeFieldsBasis(out, d_bf_1, domain.unitCell());
out.close();
BFieldComparison comparison;
comparison.compare(d_bf_0, d_bf_1);
//setVerbose(1);
if (verbose() > 0) {
std::cout << "\n";
std::cout << Dbl(comparison.maxDiff(),21,13) << "\n";
std::cout << Dbl(comparison.rmsDiff(),21,13) << "\n";
}
TEST_ASSERT(comparison.maxDiff() < 1.0E-12);
}
void testConvertBasisRGridBasis_bcc()
{
printMethod(TEST_FUNC);
Domain<3> domain;
domain.setFileMaster(fileMaster_);
readHeader("in/w_bcc.rf", domain);
int nBasis = domain.basis().nBasis();
DArray< DArray<double> > d_bf_0;
allocateFields(nMonomer_, nBasis, d_bf_0);
DArray< DArray<double> > d_bf_1;
allocateFields(nMonomer_, nBasis, d_bf_1);
DArray< RDField<3> > d_rf_0;
allocateFields(nMonomer_, domain.mesh().dimensions(), d_rf_0);
readFieldsBasis("in/w_bcc.bf", domain, d_bf_0);
domain.fieldIo().convertBasisToRGrid(d_bf_0, d_rf_0);
domain.fieldIo().convertRGridToBasis(d_rf_0, d_bf_1);
BFieldComparison comparison;
comparison.compare(d_bf_0, d_bf_1);
TEST_ASSERT(comparison.maxDiff() < 1.0E-12);
if (verbose() > 0) {
std::cout << "\n";
std::cout << Dbl(comparison.maxDiff(), 21, 13) << "\n";
std::cout << Dbl(comparison.rmsDiff(), 21, 13) << "\n";
}
}
void testConvertBasisKGridBasis_altG()
{
printMethod(TEST_FUNC);
nMonomer_ = 3;
Domain<3> domain;
domain.setFileMaster(fileMaster_);
readHeader("in/w_altG.rf", domain);
std::ofstream out;
openOutputFile("out/stars_altG", out);
domain.basis().outputStars(out);
out.close();
int nBasis = domain.basis().nBasis();
DArray< DArray<double> > d_bf_0;
allocateFields(nMonomer_, nBasis, d_bf_0);
DArray< DArray<double> > d_bf_1;
allocateFields(nMonomer_, nBasis, d_bf_1);
DArray< RDFieldDft<3> > d_kf_0;
allocateFields(nMonomer_, domain.mesh().dimensions(), d_kf_0);
readFieldsBasis("in/w_altG.bf", domain, d_bf_0);
domain.fieldIo().convertBasisToKGrid(d_bf_0, d_kf_0);
domain.fieldIo().convertKGridToBasis(d_kf_0, d_bf_1);
openOutputFile("out/w_altG_convert.bf", out);
domain.fieldIo().writeFieldsBasis(out, d_bf_1, domain.unitCell());
out.close();
BFieldComparison comparison;
comparison.compare(d_bf_0, d_bf_1);
TEST_ASSERT(comparison.maxDiff() < 1.0E-12);
if (verbose() > 0) {
std::cout << "\n";
std::cout << Dbl(comparison.maxDiff(),21,13) << "\n";
std::cout << Dbl(comparison.rmsDiff(),21,13) << "\n";
}
}
void testConvertBasisKGridBasis_c15_1()
{
printMethod(TEST_FUNC);
Domain<3> domain;
domain.setFileMaster(fileMaster_);
readHeader("in/c_c15_1.rf", domain);
int nBasis = domain.basis().nBasis();
DArray< DArray<double> > d_bf_0;
allocateFields(nMonomer_, nBasis, d_bf_0);
DArray< DArray<double> > d_bf_1;
allocateFields(nMonomer_, nBasis, d_bf_1);
DArray< RDFieldDft<3> > d_kf_0;
allocateFields(nMonomer_, domain.mesh().dimensions(), d_kf_0);
readFieldsBasis("in/w_c15_1.bf", domain, d_bf_0);
domain.fieldIo().convertBasisToKGrid(d_bf_0, d_kf_0);
domain.fieldIo().convertKGridToBasis(d_kf_0, d_bf_1);
std::ofstream out;
openOutputFile("out/w_c15_1_convert.bf", out);
domain.fieldIo().writeFieldsBasis(out, d_bf_1, domain.unitCell());
out.close();
BFieldComparison comparison;
comparison.compare(d_bf_0, d_bf_1);
TEST_ASSERT(comparison.maxDiff() < 1.0E-12);
if (verbose() > 0) {
std::cout << "\n";
std::cout << Dbl(comparison.maxDiff(),21,13) << "\n";
std::cout << Dbl(comparison.rmsDiff(),21,13) << "\n";
}
}
void testKGridIo_bcc()
{
printMethod(TEST_FUNC);
Domain<3> domain;
domain.setFileMaster(fileMaster_);
readHeader("in/w_bcc.rf", domain);
DArray< DArray<double> > d_bf_0;
allocateFields(nMonomer_, domain.basis().nBasis(), d_bf_0);
DArray< RDFieldDft<3> > d_kf_0;
allocateFields(nMonomer_, domain.mesh().dimensions(), d_kf_0);
DArray< RDFieldDft<3> > d_kf_1;
allocateFields(nMonomer_, domain.mesh().dimensions(), d_kf_1);
readFieldsBasis("in/w_bcc.bf", domain, d_bf_0);
domain.fieldIo().convertBasisToKGrid(d_bf_0, d_kf_0);
writeFields("out/w_bcc.kf", domain, d_kf_0);
readFields("out/w_bcc.kf", domain, d_kf_1);
KFieldComparison<3> comparison;
comparison.compare(d_kf_0, d_kf_1);
TEST_ASSERT(comparison.maxDiff() < 1.0E-11);
if (verbose() > 0) {
std::cout << "\n";
std::cout << Dbl(comparison.maxDiff(),21,13) << "\n";
std::cout << Dbl(comparison.rmsDiff(),21,13) << "\n";
}
}
void testKGridIo_altG()
{
printMethod(TEST_FUNC);
Domain<3> domain;
domain.setFileMaster(fileMaster_);
readHeader("in/w_altG.rf", domain);
DArray< DArray<double> > d_bf_0;
allocateFields(nMonomer_, domain.basis().nBasis(), d_bf_0);
DArray< RDFieldDft<3> > d_kf_0;
allocateFields(nMonomer_, domain.mesh().dimensions(), d_kf_0);
DArray< RDFieldDft<3> > d_kf_1;
allocateFields(nMonomer_, domain.mesh().dimensions(), d_kf_1);
readFieldsBasis("in/w_altG.bf", domain, d_bf_0);
domain.fieldIo().convertBasisToKGrid(d_bf_0, d_kf_0);
writeFields("out/w_altG.kf", domain, d_kf_0);
readFields("out/w_altG.kf", domain, d_kf_1);
KFieldComparison<3> comparison;
comparison.compare(d_kf_0, d_kf_1);
TEST_ASSERT(comparison.maxDiff() < 1.0E-11);
if (verbose() > 0) {
std::cout << "\n";
std::cout << Dbl(comparison.maxDiff(),21,13) << "\n";
std::cout << Dbl(comparison.rmsDiff(),21,13) << "\n";
}
}
void testKGridIo_lam()
{
printMethod(TEST_FUNC);
Domain<1> domain;
domain.setFileMaster(fileMaster_);
readHeader("in/w_lam.rf", domain);
DArray< DArray<double> > d_bf_0;
allocateFields(nMonomer_, domain.basis().nBasis(), d_bf_0);
DArray< RDFieldDft<1> > d_kf_0;
allocateFields(nMonomer_, domain.mesh().dimensions(), d_kf_0);
DArray< RDFieldDft<1> > d_kf_1;
allocateFields(nMonomer_, domain.mesh().dimensions(), d_kf_1);
readFieldsBasis("in/w_lam.bf", domain, d_bf_0);
domain.fieldIo().convertBasisToKGrid(d_bf_0, d_kf_0);
writeFields("out/w_lam.kf", domain, d_kf_0);
readFields("out/w_lam.kf", domain, d_kf_1);
KFieldComparison<1> comparison;
comparison.compare(d_kf_0, d_kf_1);
TEST_ASSERT(comparison.maxDiff() < 1.0E-12);
if (verbose() > 0) {
std::cout << "\n";
std::cout << Dbl(comparison.maxDiff(),21,13) << "\n";
std::cout << Dbl(comparison.rmsDiff(),21,13) << "\n";
}
}
void testConvertBasisKGridRGridKGrid_bcc()
{
printMethod(TEST_FUNC);
Domain<3> domain;
domain.setFileMaster(fileMaster_);
readHeader("in/w_bcc.rf", domain);
DArray< DArray<double> > d_bf_0;
allocateFields(nMonomer_, domain.basis().nBasis(), d_bf_0);
DArray< DArray<double> > d_bf_1;
allocateFields(nMonomer_, domain.basis().nBasis(), d_bf_1);
DArray< RDFieldDft<3> > d_kf_0;
allocateFields(nMonomer_, domain.mesh().dimensions(), d_kf_0);
DArray< RDFieldDft<3> > d_kf_1;
allocateFields(nMonomer_, domain.mesh().dimensions(), d_kf_1);
DArray< RDFieldDft<3> > d_kf_2;
allocateFields(nMonomer_, domain.mesh().dimensions(), d_kf_2);
DArray< RDField<3> > d_rf_0;
allocateFields(nMonomer_, domain.mesh().dimensions(), d_rf_0);
readFieldsBasis("in/w_bcc.bf", domain, d_bf_0);
domain.fieldIo().convertBasisToKGrid(d_bf_0, d_kf_0);
d_kf_2 = d_kf_0;
domain.fieldIo().convertKGridToRGrid(d_kf_0, d_rf_0);
#if 0
// Demonstrate that input d_kf_0 is destroyed/overwritten by above
KFieldComparison<3> check;
check.compare(d_kf_2, d_kf_0);
std::cout << std::endl;
std::cout << Dbl(check.maxDiff(), 21, 13) << "\n";
std::cout << Dbl(check.rmsDiff(), 21, 13) << "\n";
#endif
domain.fieldIo().convertRGridToKGrid(d_rf_0, d_kf_1);
KFieldComparison<3> comparison;
comparison.compare(d_kf_2, d_kf_1);
TEST_ASSERT(comparison.maxDiff() < 1.0E-10);
if (verbose() > 0) {
std::cout << std::endl;
std::cout << Dbl(comparison.maxDiff(), 21, 13) << "\n";
std::cout << Dbl(comparison.rmsDiff(), 21, 13) << "\n";
}
}
void testConvertBasisKGridRGridKGrid_c15_1()
{
printMethod(TEST_FUNC);
Domain<3> domain;
domain.setFileMaster(fileMaster_);
readHeader("in/c_c15_1.rf", domain);
DArray< DArray<double> > d_bf_0;
allocateFields(nMonomer_, domain.basis().nBasis(), d_bf_0);
DArray< DArray<double> > d_bf_1;
allocateFields(nMonomer_, domain.basis().nBasis(), d_bf_1);
DArray< RDFieldDft<3> > d_kf_0;
allocateFields(nMonomer_, domain.mesh().dimensions(), d_kf_0);
DArray< RDFieldDft<3> > d_kf_1;
allocateFields(nMonomer_, domain.mesh().dimensions(), d_kf_1);
DArray< RDFieldDft<3> > d_kf_2;
allocateFields(nMonomer_, domain.mesh().dimensions(), d_kf_2);
DArray< RDField<3> > d_rf_0;
allocateFields(nMonomer_, domain.mesh().dimensions(), d_rf_0);
readFieldsBasis("in/w_c15_1.bf", domain, d_bf_0);
domain.fieldIo().convertBasisToKGrid(d_bf_0, d_kf_0);
d_kf_2 = d_kf_0;
domain.fieldIo().convertKGridToRGrid(d_kf_0, d_rf_0);
#if 0
// Demonstrate that input d_kf_0 is destroyed/overwritten by above
KFieldComparison<3> check;
check.compare(d_kf_2, d_kf_0);
std::cout << std::endl;
std::cout << Dbl(check.maxDiff(), 21, 13) << "\n";
std::cout << Dbl(check.rmsDiff(), 21, 13) << "\n";
#endif
domain.fieldIo().convertRGridToKGrid(d_rf_0, d_kf_1);
KFieldComparison<3> comparison;
comparison.compare(d_kf_2, d_kf_1);
TEST_ASSERT(comparison.maxDiff() < 1.0E-10);
if (verbose() > 0) {
std::cout << std::endl;
std::cout << Dbl(comparison.maxDiff(), 21, 13) << "\n";
std::cout << Dbl(comparison.rmsDiff(), 21, 13) << "\n";
}
}
};
TEST_BEGIN(FieldIoTest)
TEST_ADD(FieldIoTest, testReadHeader)
TEST_ADD(FieldIoTest, testBasisIo_bcc)
TEST_ADD(FieldIoTest, testBasisIo_c15_1)
TEST_ADD(FieldIoTest, testBasisIo_altG)
TEST_ADD(FieldIoTest, testBasisIo_altG_fort)
TEST_ADD(FieldIoTest, testRGridIo_bcc)
TEST_ADD(FieldIoTest, testConvertBasisKGridBasis_bcc)
TEST_ADD(FieldIoTest, testConvertBasisRGridBasis_bcc)
TEST_ADD(FieldIoTest, testConvertBasisKGridBasis_altG)
TEST_ADD(FieldIoTest, testConvertBasisKGridBasis_c15_1)
TEST_ADD(FieldIoTest, testKGridIo_bcc)
TEST_ADD(FieldIoTest, testKGridIo_altG)
TEST_ADD(FieldIoTest, testKGridIo_lam)
TEST_ADD(FieldIoTest, testConvertBasisKGridRGridKGrid_bcc)
TEST_ADD(FieldIoTest, testConvertBasisKGridRGridKGrid_c15_1)
TEST_END(FieldIoTest)
#endif
| 19,997
|
C++
|
.h
| 532
| 30.902256
| 72
| 0.618809
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,051
|
DomainTest.h
|
dmorse_pscfpp/src/pspg/tests/field/DomainTest.h
|
#ifndef PSPG_DOMAIN_TEST_H
#define PSPG_DOMAIN_TEST_H
#include <test/UnitTest.h>
#include <test/UnitTestRunner.h>
#include <pspg/field/Domain.h>
#include <pspg/field/FieldIo.h>
#include <pspg/field/FFT.h>
#include <pscf/crystal/Basis.h>
#include <pscf/crystal/UnitCell.h>
#include <pscf/mesh/Mesh.h>
#include <util/tests/LogFileUnitTest.h>
#include <util/containers/DArray.h>
#include <util/misc/FileMaster.h>
#include <iostream>
#include <fstream>
using namespace Util;
using namespace Pscf;
using namespace Pscf::Pspg;
class DomainTest : public LogFileUnitTest
{
FileMaster fileMaster_;
int nMonomer_;
public:
void setUp()
{ setVerbose(0); }
/*
* Open and read file header to initialize Domain<D> system.
*/
template <int D>
void readHeader(std::string filename, Domain<D>& domain)
{
std::ifstream in;
openInputFile(filename, in);
domain.readRGridFieldHeader(in, nMonomer_);
in.close();
}
void testReadParam()
{
printMethod(TEST_FUNC);
Domain<3> domain;
domain.setFileMaster(fileMaster_);
std::ifstream in;
openInputFile("in/Domain", in);
domain.readParam(in);
in.close();
TEST_ASSERT(domain.mesh().dimension(0) == 32);
TEST_ASSERT(domain.mesh().dimension(1) == 32);
TEST_ASSERT(domain.mesh().dimension(2) == 32);
TEST_ASSERT(domain.unitCell().lattice() == UnitCell<3>::Cubic);
if (domain.basis().isInitialized()) {
TEST_ASSERT(domain.basis().nBasis() == 489);
}
}
void testReadHeader()
{
printMethod(TEST_FUNC);
Domain<3> domain;
domain.setFileMaster(fileMaster_);
readHeader("in/w_bcc.rf", domain);
TEST_ASSERT(domain.mesh().dimension(0) == 32);
TEST_ASSERT(domain.mesh().dimension(1) == 32);
TEST_ASSERT(domain.mesh().dimension(2) == 32);
TEST_ASSERT(domain.unitCell().lattice() == UnitCell<3>::Cubic);
TEST_ASSERT(domain.basis().nBasis() == 489);
TEST_ASSERT(nMonomer_ == 2);
if (verbose() > 0) {
std::cout << "\n";
std::cout << "Cell = " << domain.unitCell() << "\n";
std::cout << "Ngrid = " << domain.mesh().dimensions() << "\n";
if (verbose() > 1) {
domain.basis().outputStars(std::cout);
}
}
}
};
TEST_BEGIN(DomainTest)
TEST_ADD(DomainTest, testReadParam)
TEST_ADD(DomainTest, testReadHeader)
TEST_END(DomainTest)
#endif
| 2,449
|
C++
|
.h
| 80
| 25.65
| 71
| 0.647485
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,052
|
GpuResources.h
|
dmorse_pscfpp/src/pspg/math/GpuResources.h
|
#ifndef PSPG_GPU_RESOURCES_H
#define PSPG_GPU_RESOURCES_H
#include "GpuTypes.h" // typedefs used in Pspg
#include "ThreadGrid.h" // Management of GPU execution configuration
#include "LinearAlgebra.h" // Linear algebra kernels used in Pspg
#include "ParallelReductions.h" // Kernels using parallel reduction algorithms
#include "KernelWrappers.h" // Host functions for reductions
#endif
| 421
|
C++
|
.h
| 8
| 51.375
| 79
| 0.739659
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,053
|
LinearAlgebra.h
|
dmorse_pscfpp/src/pspg/math/LinearAlgebra.h
|
#ifndef PSPG_LINEAR_ALGEBRA_H
#define PSPG_LINEAR_ALGEBRA_H
#include "GpuTypes.h"
namespace Pscf {
namespace Pspg {
/** \ingroup Pspg_Math_Module
* @{
*/
__global__ void subtractUniform(cudaReal* result, cudaReal rhs, int size);
__global__ void addUniform(cudaReal* result, cudaReal rhs, int size);
__global__ void pointWiseSubtract(cudaReal* result, const cudaReal* rhs, int size);
__global__ void pointWiseSubtractFloat(cudaReal* result, const float rhs, int size);
__global__ void pointWiseBinarySubtract(const cudaReal* a, const cudaReal* b, cudaReal* result, int size);
__global__ void pointWiseAdd(cudaReal* result, const cudaReal* rhs, int size);
__global__ void pointWiseBinaryAdd(const cudaReal* a, const cudaReal* b, cudaReal* result, int size);
__global__ void pointWiseAddScale(cudaReal* result, const cudaReal* rhs, double scale, int size);
__global__ void inPlacePointwiseMul(cudaReal* a, const cudaReal* b, int size);
__global__ void pointWiseBinaryMultiply(const cudaReal* a, const cudaReal* b, cudaReal* result, int size);
__global__ void assignUniformReal(cudaReal* result, cudaReal uniform, int size);
__global__ void assignReal(cudaReal* result, const cudaReal* rhs, int size);
__global__ void assignExp(cudaReal* exp, const cudaReal* w, double constant, int size);
__global__ void scaleReal(cudaReal* result, double scale, int size);
/** @} */
}
}
#endif
| 1,398
|
C++
|
.h
| 26
| 51.923077
| 106
| 0.758697
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,054
|
KernelWrappers.h
|
dmorse_pscfpp/src/pspg/math/KernelWrappers.h
|
#ifndef PSPG_KERNEL_WRAPPERS_H
#define PSPG_KERNEL_WRAPPERS_H
#include "ParallelReductions.h"
#include "GpuTypes.h"
#include "LinearAlgebra.h"
namespace Pscf {
namespace Pspg {
/** \ingroup Pspg_Math_Module
* @{
*/
__host__ cudaReal gpuSum(cudaReal const * d_in, int size);
__host__ cudaReal gpuInnerProduct(cudaReal const * d_a, cudaReal const * d_b, int size);
__host__ cudaReal gpuMax(cudaReal const * d_in, int size);
__host__ cudaReal gpuMaxAbs(cudaReal const * d_in, int size);
__host__ cudaReal gpuMin(cudaReal const * d_in, int size);
__host__ cudaReal gpuMinAbs(cudaReal const * d_in, int size);
/** @} */
}
}
#endif
| 637
|
C++
|
.h
| 20
| 30.3
| 88
| 0.724876
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,055
|
ThreadGrid.h
|
dmorse_pscfpp/src/pspg/math/ThreadGrid.h
|
#ifndef PSPG_THREADGRID_H
#define PSPG_THREADGRID_H
#include "GpuTypes.h"
#include <util/global.h>
namespace Pscf {
namespace Pspg {
/**
* Global functions and variables to control GPU thread and block counts.
*/
namespace ThreadGrid {
/**
* \defgroup Pspg_ThreadGrid_Module ThreadGrid
*
* Management of GPU resources and setting of execution configurations.
*
* \ingroup Pscf_Pspg_Module
* @{
*/
/**
* Initialize static variables in Pspg::ThreadGrid namespace.
*/
void init();
/**
* Set the number of threads per block to a default value.
*
* Query the hardware to determine a reasonable number.
*/
void setThreadsPerBlock();
/**
* Set the number of threads per block to a specified value.
*
* \param nThreadsPerBlock the number of threads per block (input)
*/
void setThreadsPerBlock(int nThreadsPerBlock);
/**
* Set the total number of threads required for execution.
*
* Calculate the number of blocks, and calculate threads per block if
* necessary. Updates static variables.
*
* \param nThreadsLogical total number of required threads (input)
*/
void setThreadsLogical(int nThreadsLogical);
/**
* Set the total number of threads required for execution.
*
* Recalculate the number of blocks, and calculate threads per block if
* necessary. Also updates the nBlocks output parameter.
*
* \param nThreadsLogical total number of required threads (input)
* \param nBlocks updated number of blocks (output)
*/
void setThreadsLogical(int nThreadsLogical, int& nBlocks);
/**
* Set the total number of threads required for execution.
*
* Computes and sets the number of blocks, and sets threads per block
* if necessary. Updates values of nBlocks and nThreads parameters in
* output parameters that are passed by value.
*
* \param nThreadsLogical total number of required threads (input)
* \param nBlocks updated number of blocks (output)
* \param nThreads updated number threads per block (output)
*/
void setThreadsLogical(int nThreadsLogical, int& nBlocks, int& nThreads);
/**
* Check the execution configuration (threads and block counts).
*
* Check for validity and optimality, based on hardware warp size and
* streaming multiprocessor constraints.
*/
void checkExecutionConfig();
// Accessors
/**
* Get the current number of blocks for execution.
*/
int nBlocks();
/**
* Get the number of threads per block for execution.
*/
int nThreads();
/**
* Return previously requested total number of threads.
*/
int nThreadsLogical();
/**
* Indicates whether there will be unused threads.
*
* Returns true iff nThreads*nBlocks != nThreadsLogical.
*
* \ingroup Pspg_ThreadGrid_Module
*/
bool hasUnusedThreads();
/** @} */
} // namespace ThreadGrid
} // namespace Pspg
} // namespace Pscf
#endif
| 2,897
|
C++
|
.h
| 98
| 26.479592
| 75
| 0.729137
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,056
|
ParallelReductions.h
|
dmorse_pscfpp/src/pspg/math/ParallelReductions.h
|
#ifndef PARALLEL_REDUCTIONS_H
#define PARALLEL_REDUCTIONS_H
#include "GpuTypes.h"
namespace Pscf {
namespace Pspg {
/** \ingroup Pspg_Math_Module
* @{
*/
__global__ void reductionSum(cudaReal* sum, const cudaReal* in, int size);
__global__ void reductionInnerProduct(cudaReal* innerprod, const cudaReal* a, const cudaReal* b, int size);
__global__ void reductionMax(cudaReal* max, const cudaReal* in, int size);
__global__ void reductionMaxAbs(cudaReal* max, const cudaReal* in, int size);
__global__ void reductionMin(cudaReal* min, const cudaReal* in, int size);
__global__ void reductionMinAbs(cudaReal* min, const cudaReal* in, int size);
/** @} */
}
}
#endif
| 674
|
C++
|
.h
| 18
| 35.888889
| 107
| 0.744977
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,057
|
GpuTypes.h
|
dmorse_pscfpp/src/pspg/math/GpuTypes.h
|
#ifndef PSPG_GPU_TYPES_H
#define PSPG_GPU_TYPES_H
#include <cufft.h>
#include <stdio.h>
#include <iostream>
namespace Pscf {
namespace Pspg {
//#define SINGLE_PRECISION
#define DOUBLE_PRECISION
#ifdef SINGLE_PRECISION
typedef cufftReal cudaReal;
typedef cufftComplex cudaComplex;
typedef cufftReal hostReal;
typedef cufftComplex hostComplex;
#else
#ifdef DOUBLE_PRECISION
typedef cufftDoubleReal cudaReal;
typedef cufftDoubleComplex cudaComplex;
typedef cufftDoubleReal hostReal;
typedef cufftDoubleComplex hostComplex;
#endif
#endif
#define gpuErrchk(ans) { gpuAssert((ans), __FILE__, __LINE__);}
inline void gpuAssert(cudaError_t code, const char *file, int line, bool abort=true)
{
if (code != cudaSuccess)
{
fprintf(stderr,"GPUassert: %s %s %d\n", cudaGetErrorString(code), file, line);
if(abort) exit(code);
}
}
}
}
#endif
| 855
|
C++
|
.h
| 34
| 23.352941
| 84
| 0.781863
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,058
|
FFT.h
|
dmorse_pscfpp/src/pspg/field/FFT.h
|
#ifndef PSPG_FFT_H
#define PSPG_FFT_H
/*
* PSCF Package
*
* Copyright 2016 - 2022, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include <pspg/field/RDField.h>
#include <pspg/field/RDFieldDft.h>
#include <pspg/math/GpuResources.h>
#include <pscf/math/IntVec.h>
#include <util/global.h>
#include <cufft.h>
#include <cuda.h>
#include <cuda_runtime.h>
namespace Pscf {
namespace Pspg {
using namespace Util;
using namespace Pscf;
/**
* Fourier transform wrapper for real data.
*
* \ingroup Pspg_Field_Module
*/
template <int D>
class FFT
{
public:
/**
* Default constructor.
*/
FFT();
/**
* Destructor.
*/
virtual ~FFT();
/**
* Setup grid dimensions, plans and work space.
*
* \param meshDimensions Dimensions of real-space grid.
*/
void setup(IntVec<D> const & meshDimensions);
/**
* Check and setup grid dimensions if necessary.
*
* \param rDField real data on r-space grid (device mem)
* \param kDField complex data on k-space grid (device mem)
*/
void setup(RDField<D>& rDField, RDFieldDft<D>& kDField);
/**
* Compute forward (real-to-complex) discrete Fourier transform.
*
* \param rField real values on r-space grid (input, gpu mem)
* \param kField complex values on k-space grid (output, gpu mem)
*/
void forwardTransform(RDField<D> & rField, RDFieldDft<D>& kField)
const;
/**
* Compute forward Fourier transform without destroying input.
*
* \param rField real values on r-space grid (input, gpu mem)
* \param kField complex values on k-space grid (output, gpu mem)
*/
void forwardTransformSafe(RDField<D> const & rField,
RDFieldDft<D>& kField) const;
/**
* Compute inverse (complex-to-real) discrete Fourier transform.
*
* \param kField complex values on k-space grid (input, gpu mem)
* \param rField real values on r-space grid (output, gpu mem)
*/
void inverseTransform(RDFieldDft<D> & kField, RDField<D>& rField)
const;
/**
* Compute inverse (complex to real) DFT without destroying input.
*
* \param kField complex values on k-space grid (input, gpu mem)
* \param rField real values on r-space grid (output, gpu mem)
*/
void inverseTransformSafe(RDFieldDft<D> const & kField,
RDField<D>& rField) const;
/**
* Return the dimensions of the grid for which this was allocated.
*/
const IntVec<D>& meshDimensions() const;
/**
* Has this FFT object been setup?
*/
bool isSetup() const;
/**
* Get the plan for the forward DFT.
*/
cufftHandle& fPlan();
/**
* Get the plan for the inverse DFT.
*/
cufftHandle& iPlan();
private:
// Vector containing number of grid points in each direction.
IntVec<D> meshDimensions_;
// Private r-space array for performing safe transforms.
mutable RDField<D> rFieldCopy_;
// Private k-space array for performing safe transforms.
mutable RDFieldDft<D> kFieldCopy_;
// Number of points in r-space grid
int rSize_;
// Number of points in k-space grid
int kSize_;
// Pointer to a plan for a forward transform.
cufftHandle fPlan_;
// Pointer to a plan for an inverse transform.
cufftHandle iPlan_;
// Have array dimension and plan been initialized?
bool isSetup_;
/**
* Make FFTW plans for transform and inverse transform.
*/
void makePlans(RDField<D>& rDField, RDFieldDft<D>& kDField);
};
// Declarations of explicit specializations
template <>
void FFT<1>::makePlans(RDField<1>& rField, RDFieldDft<1>& kField);
template <>
void FFT<2>::makePlans(RDField<2>& rField, RDFieldDft<2>& kField);
template <>
void FFT<3>::makePlans(RDField<3>& rField, RDFieldDft<3>& kField);
/*
* Return the dimensions of the grid for which this was allocated.
*/
template <int D>
inline const IntVec<D>& FFT<D>::meshDimensions() const
{ return meshDimensions_; }
template <int D>
inline bool FFT<D>::isSetup() const
{ return isSetup_; }
template <int D>
inline cufftHandle& FFT<D>::fPlan()
{ return fPlan_; }
template <int D>
inline cufftHandle& FFT<D>::iPlan()
{ return iPlan_; }
#ifndef PSPG_FFT_TPP
// Suppress implicit instantiation
extern template class FFT<1>;
extern template class FFT<2>;
extern template class FFT<3>;
#endif
static __global__
void scaleRealData(cudaReal* data, cudaReal scale, int size) {
//write code that will scale
int nThreads = blockDim.x * gridDim.x;
int startId = blockIdx.x * blockDim.x + threadIdx.x;
for(int i = startId; i < size; i += nThreads ) {
data[i] *= scale;
}
}
}
}
//#include "FFT.tpp"
#endif
| 5,112
|
C++
|
.h
| 161
| 25.888199
| 72
| 0.637531
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,059
|
Domain.h
|
dmorse_pscfpp/src/pspg/field/Domain.h
|
#ifndef PSPG_DOMAIN_H
#define PSPG_DOMAIN_H
/*
* PSCF - Polymer Self-Consistent Field Theory
*
* Copyright 2016 - 2022, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include <util/param/ParamComposite.h> // base class
#include <pspg/solvers/WaveList.h> // member
#include <pspg/field/FieldIo.h> // member
#include <pspg/field/FFT.h> // member
#include <pscf/crystal/Basis.h> // member
#include <pscf/crystal/SpaceGroup.h> // member
#include <pscf/mesh/Mesh.h> // member
#include <pscf/crystal/UnitCell.h> // member
#include <string>
namespace Pscf {
namespace Pspg
{
using namespace Util;
/**
* Spatial domain and spatial discretization for a periodic structure.
*
* A Domain has (among other components):
*
* - a Mesh
* - a UnitCell
* - a SpaceGroup
* - a Basis
* - an Fft
* - a WaveList
* - a FieldIo
* - a lattice system enumeration value
* - a groupName string
*
* \ingroup Pspg_Field_Module
*/
template <int D>
class Domain : public ParamComposite
{
public:
/// \name Construction, Initialization and Destruction
//@{
/**
* Constructor.
*/
Domain();
/**
* Destructor.
*/
~Domain();
/**
* Create association with a FileMaster, needed by FieldIo.
*
* \param fileMaster associated FileMaster object.
*/
void setFileMaster(FileMaster& fileMaster);
/**
* Read body of parameter block (without opening and closing lines).
*
* Reads unit cell, mesh dimensions and space group name.
*
* \param in input parameter stream
*/
virtual void readParameters(std::istream& in);
/**
* Read initialization data from header of an r-grid field file.
*
* The header for an r-grid field file contains all data needed
* to initialize a domain, i.e., unit cell, mesh and group name.
*
* \param in input parameter stream
* \param nMonomer number of monomers in field file (output)
*/
void readRGridFieldHeader(std::istream& in, int& nMonomer);
/**
* Set the unit cell, given a UnitCell<D> object.
*
* Initializes basis if not done previously.
*
* \param unitCell new unit cell
*/
void setUnitCell(UnitCell<D> const & unitCell);
/**
* Set the unit cell state, given the lattice and parameters.
*
* Initializes basis if not done previously.
*
* \param lattice lattice system
* \param parameters array of unit cell parameters
*/
void setUnitCell(typename UnitCell<D>::LatticeSystem lattice,
FSArray<double, 6> const & parameters);
/**
* Set unit cell parameters.
*
* Initializes basis if not done previously.
* Lattice system must already be set to non-null value on entry.
*
* \param parameters array of unit cell parameters
*/
void setUnitCell(FSArray<double, 6> const & parameters);
/**
* Construct basis if not done already.
*/
void makeBasis();
//@}
/// \name Accessors
//@{
/**
* Get UnitCell by reference.
*/
UnitCell<D>& unitCell();
/**
* Get UnitCell by const reference.
*/
UnitCell<D> const & unitCell() const;
/**
* Get the spatial Mesh by reference.
*/
Mesh<D>& mesh();
/**
* Get the spatial Mesh by const reference.
*/
Mesh<D> const & mesh() const;
/**
* Get the SpaceGroup object by const reference.
*/
SpaceGroup<D> const & group() const;
/**
* Get the Basis by reference.
*/
Basis<D>& basis();
/**
* Get the Basis by const reference.
*/
Basis<D> const & basis() const ;
/**
* Get the FFT object by reference.
*/
FFT<D>& fft();
/**
* Get associated FFT object by const reference.
*/
FFT<D> const & fft() const;
/**
* Get the WaveList object by reference.
*/
WaveList<D>& waveList();
/**
* Get associated WaveList object by const reference.
*/
WaveList<D> const & waveList() const;
/**
* Get associated FieldIo object.
*/
FieldIo<D>& fieldIo();
/**
* Get associated FieldIo object by const reference.
*/
FieldIo<D> const & fieldIo() const;
/**
* Get the lattice system (enumeration value).
*/
typename UnitCell<D>::LatticeSystem lattice() const;
/**
* Get group name.
*/
std::string groupName() const;
//@}
private:
// Private member variables
/**
* Crystallographic unit cell (crystal system and cell parameters).
*/
UnitCell<D> unitCell_;
/**
* Spatial discretization mesh.
*/
Mesh<D> mesh_;
/**
* SpaceGroup object.
*/
SpaceGroup<D> group_;
/**
* Basis object
*/
Basis<D> basis_;
/**
* FFT object.
*/
FFT<D> fft_;
/**
* WaveList object to be used by solvers.
*/
WaveList<D> waveList_;
/**
* FieldIo object for field input/output operations
*/
FieldIo<D> fieldIo_;
/**
* Lattice system (enumeration value).
*/
typename UnitCell<D>::LatticeSystem lattice_;
/**
* Group name.
*/
std::string groupName_;
/**
* Has a FileMaster been set?
*/
bool hasFileMaster_;
/**
* Has the domain been initialized?
*/
bool isInitialized_;
};
// Inline member functions
// Get the UnitCell<D> object by non-const reference.
template <int D>
inline UnitCell<D>& Domain<D>::unitCell()
{ return unitCell_; }
// Get the UnitCell<D> object by const reference.
template <int D>
inline UnitCell<D> const & Domain<D>::unitCell() const
{ return unitCell_; }
// Get the Mesh<D> object by reference.
template <int D>
inline Mesh<D>& Domain<D>::mesh()
{ return mesh_; }
// Get the Mesh<D> object by const reference.
template <int D>
inline Mesh<D> const & Domain<D>::mesh() const
{ return mesh_; }
// Get the SpaceGroup<D> object by const reference.
template <int D>
inline SpaceGroup<D> const & Domain<D>::group() const
{ return group_; }
// Get the Basis<D> object by non-const reference.
template <int D>
inline Basis<D>& Domain<D>::basis()
{ return basis_; }
// Get the Basis<D> object by const reference.
template <int D>
inline Basis<D> const & Domain<D>::basis() const
{ return basis_; }
// Get the FFT<D> object.
template <int D>
inline FFT<D>& Domain<D>::fft()
{ return fft_; }
// Get the FFT<D> object by const reference.
template <int D>
inline FFT<D> const & Domain<D>::fft() const
{ return fft_; }
// Get the WaveList<D> object.
template <int D>
inline WaveList<D>& Domain<D>::waveList()
{ return waveList_; }
// Get the WaveList<D> object by const reference.
template <int D>
inline WaveList<D> const & Domain<D>::waveList() const
{ return waveList_; }
// Get the FieldIo<D> object.
template <int D>
inline FieldIo<D>& Domain<D>::fieldIo()
{ return fieldIo_; }
// Get the FieldIo<D> object by const reference.
template <int D>
inline FieldIo<D> const & Domain<D>::fieldIo() const
{ return fieldIo_; }
// Get the lattice system enumeration value.
template <int D>
inline
typename UnitCell<D>::LatticeSystem Domain<D>::lattice() const
{ return lattice_; }
// Get the groupName string.
template <int D>
inline std::string Domain<D>::groupName() const
{ return groupName_; }
#ifndef PSPG_DOMAIN_TPP
// Suppress implicit instantiation
extern template class Domain<1>;
extern template class Domain<2>;
extern template class Domain<3>;
#endif
} // namespace Pspg
} // namespace Pscf
#endif
| 8,261
|
C++
|
.h
| 289
| 22.688581
| 73
| 0.597317
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,060
|
FFTBatched.h
|
dmorse_pscfpp/src/pspg/field/FFTBatched.h
|
#ifndef PSPG_FFT_BATCHED_H
#define PSPG_FFT_BATCHED_H
/*
* PSCF Package
*
* Copyright 2016 - 2022, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include <pspg/field/RDField.h>
#include <pspg/field/RDFieldDft.h>
#include <pscf/math/IntVec.h>
#include <util/global.h>
#include <cufft.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <pspg/math/GpuResources.h>
//temporary for debugging
#include <iostream>
namespace Pscf {
namespace Pspg {
using namespace Util;
using namespace Pscf;
/**
* Fourier transform wrapper for real data.
*
* \ingroup Pspg_Field_Module
*/
template <int D>
class FFTBatched
{
public:
/**
* Default constructor.
*/
FFTBatched();
/**
* Destructor.
*/
virtual ~FFTBatched();
/**
* Check and setup grid dimensions if necessary.
*
* \param rDField real data on r-space grid (device mem)
* \param kDField complex data on k-space grid (device mem)
*/
void setup(RDField<D>& rDField, RDFieldDft<D>& kDField);
void setup(const IntVec<D>& rDim,const IntVec<D>& kDim, int batchSize);
/**
* Compute forward (real-to-complex) Fourier transform.
*
* \param in array of real values on r-space grid (device mem)
* \param out array of complex values on k-space grid (device mem)
*/
void forwardTransform(RDField<D>& in, RDFieldDft<D>& out);
void forwardTransform(cudaReal* in, cudaComplex* out, int batchSize);
/**
* Compute inverse (complex-to-real) Fourier transform.
*
* \param in array of complex values on k-space grid (device mem)
* \param out array of real values on r-space grid (device mem)
*/
void inverseTransform(RDFieldDft<D>& in, RDField<D>& out);
void inverseTransform(cudaComplex* in, cudaReal* out, int batchSize);
/**
* Return the dimensions of the grid for which this was allocated.
*/
const IntVec<D>& meshDimensions() const;
bool isSetup() const;
cufftHandle& fPlan();
cufftHandle& iPlan();
private:
// Vector containing number of grid points in each direction.
IntVec<D> meshDimensions_;
// Number of points in r-space grid
int rSize_;
// Number of points in k-space grid
int kSize_;
// Pointer to a plan for a forward transform.
cufftHandle fPlan_;
// Pointer to a plan for an inverse transform.
cufftHandle iPlan_;
// Have array dimension and plan been initialized?
bool isSetup_;
/**
* Make FFTW plans for transform and inverse transform.
*/
void makePlans(RDField<D>& rDField, RDFieldDft<D>& kDField);
void makePlans(const IntVec<D>& rDim, const IntVec<D>& kDField, int batchSize);
};
/*
* Return the dimensions of the grid for which this was allocated.
*/
template <int D>
inline const IntVec<D>& FFTBatched<D>::meshDimensions() const
{ return meshDimensions_; }
template <int D>
inline bool FFTBatched<D>::isSetup() const
{ return isSetup_; }
template <int D>
inline cufftHandle& FFTBatched<D>::fPlan()
{ return fPlan_; }
template <int D>
inline cufftHandle& FFTBatched<D>::iPlan()
{ return iPlan_; }
#ifndef PSPG_FFT_BATCHED_TPP
// Suppress implicit instantiation
extern template class FFTBatched<1>;
extern template class FFTBatched<2>;
extern template class FFTBatched<3>;
#endif
}
}
//#include "FFTBatched.tpp"
#endif
| 3,607
|
C++
|
.h
| 114
| 26.491228
| 85
| 0.666763
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,061
|
KFieldComparison.h
|
dmorse_pscfpp/src/pspg/field/KFieldComparison.h
|
#ifndef PSPG_K_FIELD_COMPARISON_H
#define PSPG_K_FIELD_COMPARISON_H
/*
* PSCF - Polymer Self-Consistent Field Theory
*
* Copyright 2016 - 2022, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include <util/containers/DArray.h>
#include <pspg/field/RDFieldDft.h>
#include <pspg/math/GpuResources.h>
namespace Pscf {
namespace Pspg {
using namespace Util;
/**
* Comparator for RDFieldDft (k-grid) arrays.
*
* \ingroup Pspg_Field_Module
*/
template <int D>
class KFieldComparison {
public:
/**
* Default constructor.
*
* Initializes maxDiff and rmsDiff to zero.
*/
KFieldComparison();
// Use compiler defined destructor and assignment operator.
/**
* Compare individual fields.
*
* Array dimensions must agree. An Exception is thrown if the
* capacities of fields a and b are not equal.
*
* \param a 1st field
* \param b 2nd field
* \return maximum element-by-element difference (maxDiff)
*/
double compare(RDFieldDft<D> const& a, RDFieldDft<D> const& b);
/**
* Compare arrays of fields associated with different monomer types.
*
* All array dimensions must agree.
*
* An exception is thrown if the capacities of the enclosing
* DArrays (the number of monomers) are not equal or if the
* capacities of any pair of individual fields (number of grid
* points or basis functions) are not equal.
*
* \param a 1st DArray of field
* \param b 2nd DArray of field
* \return maximum element-by-element difference (maxDiff)
*/
double compare(DArray<RDFieldDft<D> > const& a,
DArray<RDFieldDft<D> > const& b);
/**
* Return the precomputed maximum element-by-element difference.
*
* This function returns the maximum difference between corresponding
* field array elements found by the most recent comparison.
*/
double maxDiff() const
{ return maxDiff_; }
/**
* Return the precomputed root-mean-squared difference.
*
* This function returns the root-mean-squared difference between
* corresponding elements found by the most recent comparison.
*/
double rmsDiff() const
{ return rmsDiff_; }
private:
// Maximum element-by-element difference.
double maxDiff_;
// Room-mean-squared element-by-element difference.
double rmsDiff_;
};
#ifndef PSPG_K_FIELD_COMPARISON_TPP
// Suppress implicit instantiation
extern template class KFieldComparison<1>;
extern template class KFieldComparison<2>;
extern template class KFieldComparison<3>;
#endif
} // namespace Pspg
} // namespace Pscf
#endif
| 2,875
|
C++
|
.h
| 87
| 27.114943
| 74
| 0.669688
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,062
|
DField.h
|
dmorse_pscfpp/src/pspg/field/DField.h
|
#ifndef PSPG_DFIELD_H
#define PSPG_DFIELD_H
/*
* PSCF Package
*
* Copyright 2016 - 2022, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include <util/global.h>
namespace Pscf {
namespace Pspg
{
using namespace Util;
/**
* Dynamic array on the GPU with alligned data.
*
* This class wraps an aligned C array with elements of type Data on the
* device. All member functions may be called from the host. As a result,
* the class does not offer access to individual elements via operator[]
*
* \ingroup Pspg_Field_Module
*/
template <typename Data>
class DField
{
public:
/**
* Default constructor.
*/
DField();
/**
* Destructor.
*
* Deletes underlying C array, if allocated previously.
*/
virtual ~DField();
/**
* Allocate the underlying C array on the device.
*
* \throw Exception if the Field is already allocated.
*
* \param capacity number of elements to allocate.
*/
void allocate(int capacity);
/**
* Dellocate the underlying C array.
*
* \throw Exception if the Field is not allocated.
*/
void deallocate();
/**
* Return true if the Field has been allocated, false otherwise.
*/
bool isAllocated() const;
/**
* Return allocated size.
*
* \return Number of elements allocated in array.
*/
int capacity() const;
/**
* Return pointer to underlying C array.
*/
Data* cDField();
/**
* Return pointer to const to underlying C array.
*/
const Data* cDField() const;
/**
* Assignment operator.
*
* \param other DField<Data> on rhs of assignent (input)
*/
virtual DField<Data>& operator = (const DField<Data>& other);
/**
* Copy constructor.
*
* \param other DField<Data> to be copied (input)
*/
DField(const DField& other);
protected:
/// Pointer to an array of Data elements on the device / GPU.
Data* data_;
/// Allocated size of the data_ array.
int capacity_;
};
/*
* Return allocated size.
*/
template <typename Data>
inline int DField<Data>::capacity() const
{ return capacity_; }
/*
* Get a pointer to the underlying C array.
*/
template <typename Data>
inline Data* DField<Data>::cDField()
{ return data_; }
/*
* Get a pointer to const to the underlying C array.
*/
template <typename Data>
inline const Data* DField<Data>::cDField() const
{ return data_; }
/*
* Return true if the Field has been allocated, false otherwise.
*/
template <typename Data>
inline bool DField<Data>::isAllocated() const
{ return (bool)data_; }
}
}
#include "DField.tpp"
#endif
| 2,925
|
C++
|
.h
| 114
| 20.307018
| 75
| 0.620244
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,063
|
RDFieldDft.h
|
dmorse_pscfpp/src/pspg/field/RDFieldDft.h
|
#ifndef PSPG_R_DFIELD_DFT_H
#define PSPG_R_DFIELD_DFT_H
/*
* PSCF Package
*
* Copyright 2016 - 2022, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include "DField.h"
#include <pspg/math/GpuResources.h>
#include <pscf/math/IntVec.h>
#include <util/global.h>
#include <cufft.h>
namespace Pscf {
namespace Pspg
{
using namespace Util;
using namespace Pscf;
/**
* Discrete Fourier Transform (DFT) of a real field on an FFT mesh.
*
* The DFT is stored internally as a C array of cudaComplex elements
* located in global GPU memory. All member functions are C++ functions
* that can be called from the host CPU.
*
* \ingroup Pspg_Field_Module
*/
template <int D>
class RDFieldDft : public DField<cudaComplex>
{
public:
/**
* Default constructor.
*/
RDFieldDft();
/**
* Copy constructor.
*
* Allocates new memory and copies all elements by value.
*
*\param other the RDFieldDft to be copied.
*/
RDFieldDft(const RDFieldDft<D>& other);
/**
* Destructor.
*
* Deletes underlying C array, if allocated previously.
*/
virtual ~RDFieldDft();
/**
* Assignment operator.
*
* If this Field is not allocated, allocates and copies all elements.
*
* If this and the other Field are both allocated, the capacities must
* be exactly equal. If so, this method copies all elements.
*
* \param other the RHS Field
*/
RDFieldDft<D>& operator = (const RDFieldDft<D>& other);
/**
* Allocate the underlying C array for an FFT grid.
*
* \throw Exception if the RDFieldDft is already allocated.
*
* \param meshDimensions vector of mesh dimensions
*/
void allocate(const IntVec<D>& meshDimensions);
/**
* Return vector of mesh dimensions by constant reference.
*/
const IntVec<D>& meshDimensions() const;
/**
* Return vector of dft (Fourier) grid dimensions by const reference.
*
* The last element of dftDimensions() and meshDimensions() differ by
* about a factor of two: dftDimension()[D-1] = meshDimensions()/2 + 1.
* For D > 1, other elements are equal.
*/
const IntVec<D>& dftDimensions() const;
/**
* Serialize a Field to/from an Archive.
*
* \param ar archive
* \param version archive version id
*/
template <class Archive>
void serialize(Archive& ar, const unsigned int version);
using DField<cudaComplex>::allocate;
using DField<cudaComplex>::operator =;
private:
// Vector containing number of grid points in each direction.
IntVec<D> meshDimensions_;
// Vector containing dimensions of dft (Fourier) grid.
IntVec<D> dftDimensions_;
};
/*
* Allocate the underlying C array for an FFT grid.
*/
template <int D>
void RDFieldDft<D>::allocate(const IntVec<D>& meshDimensions)
{
int size = 1;
for (int i = 0; i < D; ++i) {
UTIL_CHECK(meshDimensions[i] > 0);
meshDimensions_[i] = meshDimensions[i];
if (i < D - 1) {
dftDimensions_[i] = meshDimensions[i];
size *= meshDimensions[i];
} else {
dftDimensions_[i] = (meshDimensions[i]/2 + 1);
size *= (meshDimensions[i]/2 + 1);
}
}
DField<cudaComplex>::allocate(size);
}
/*
* Return mesh dimensions by constant reference.
*/
template <int D>
inline const IntVec<D>& RDFieldDft<D>::meshDimensions() const
{ return meshDimensions_; }
/*
* Return dimensions of dft grid by constant reference.
*/
template <int D>
inline const IntVec<D>& RDFieldDft<D>::dftDimensions() const
{ return dftDimensions_; }
/*
* Serialize a Field to/from an Archive.
*/
template <int D>
template <class Archive>
void RDFieldDft<D>::serialize(Archive& ar, const unsigned int version)
{
int capacity;
if (Archive::is_saving()) {
capacity = capacity_;
}
ar & capacity;
if (Archive::is_loading()) {
if (!isAllocated()) {
if (capacity > 0) {
allocate(capacity);
}
} else {
if (capacity != capacity_) {
UTIL_THROW("Inconsistent Field capacities");
}
}
}
if (isAllocated()) {
cudaComplex* tempData = new cudaComplex[capacity];
cudaMemcpy(tempData, data_, capacity * sizeof(cudaComplex),
cudaMemcpyDeviceToHost);
for (int i = 0; i < capacity_; ++i) {
ar & tempData[i].x;
ar & tempData[i].y;
}
delete[] tempData;
}
ar & meshDimensions_;
}
}
}
#include "RDFieldDft.tpp"
#endif
| 4,956
|
C++
|
.h
| 167
| 23.161677
| 76
| 0.606213
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,064
|
FieldIo.h
|
dmorse_pscfpp/src/pspg/field/FieldIo.h
|
#ifndef PSPG_FIELD_IO_H
#define PSPG_FIELD_IO_H
/*
* PSCF - Polymer Self-Consistent Field Theory
*
* Copyright 2016 - 2022, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include <pspg/field/FFT.h> // member
#include <pspg/field/RDField.h> // function parameter
#include <pspg/field/RDFieldDft.h> // function parameter
#include <pscf/crystal/Basis.h> // member
#include <pscf/crystal/SpaceGroup.h> // member
#include <pscf/crystal/UnitCell.h> // member
#include <pscf/mesh/Mesh.h> // member
#include <util/misc/FileMaster.h> // member
#include <util/containers/DArray.h> // function parameter
#include <util/containers/Array.h> // function parameter
namespace Pscf {
namespace Pspg
{
using namespace Util;
using namespace Pscf;
/**
* File input/output operations for fields in several file formats.
*
* \ingroup Pspg_Field_Module
*/
template <int D>
class FieldIo
{
public:
/**
* Constructor.
*/
FieldIo();
/**
* Destructor.
*/
~FieldIo();
/**
* Get and store addresses of associated objects.
*
* \param mesh associated spatial discretization Mesh<D>
* \param fft associated FFT object for fast transforms
* \param lattice lattice system type (enumeration value)
* \param groupName space group name string
* \param group associated space group
* \param basis associated Basis object
* \param fileMaster associated FileMaster (for file paths)
*/
void associate(Mesh<D> const & mesh,
FFT<D> const & fft,
typename UnitCell<D>::LatticeSystem& lattice,
std::string& groupName,
SpaceGroup<D>& group,
Basis<D>& basis,
FileMaster const & fileMaster);
/// \name Field File IO
//@{
/**
* Read concentration or chemical potential field components from file.
*
* This function reads components in a symmetry adapted basis from
* file in.
*
* The capacity of DArray fields is equal to nMonomer, and element
* fields[i] is a DArray containing components of the field
* associated with monomer type i.
*
* \param in input stream (i.e., input file)
* \param fields array of fields (symmetry adapted basis components)
* \param unitCell crystallographic unit cell (output)
*/
void
readFieldsBasis(std::istream& in,
DArray< DArray<double> >& fields,
UnitCell<D>& unitCell) const;
/**
* Read concentration or chemical potential field components from file.
*
* This function opens an input file with the specified filename,
* reads components in symmetry-adapted form from that file, and
* closes the file.
*
* \param filename name of input file
* \param fields array of fields (symmetry adapted basis components)
* \param unitCell crystallographic unit cell (output)
*/
void readFieldsBasis(std::string filename,
DArray< DArray<double> >& fields,
UnitCell<D>& unitCell) const;
/**
* Write concentration or chemical potential field components to file.
*
* This function writes components in a symmetry adapted basis.
*
* \param out output stream (i.e., output file)
* \param fields array of fields (symmetry adapted basis components)
* \param unitCell crystallographic unit cell
*/
void writeFieldsBasis(std::ostream& out,
DArray< DArray<double> > const & fields,
UnitCell<D> const & unitCell) const;
/**
* Write concentration or chemical potential field components to file.
*
* This function opens an output file with the specified filename,
* writes components in symmetry-adapted form to that file, and then
* closes the file.
*
* \param filename name of input file
* \param fields array of fields (symmetry adapted basis components)
* \param unitCell crystallographic unit cell
*/
void writeFieldsBasis(std::string filename,
DArray< DArray<double> > const & fields,
UnitCell<D> const & unitCell) const;
/**
* Read array of RField objects (fields on an r-space grid) from file.
*
* The capacity of array fields is equal to nMonomer, and element
* fields[i] is the RField<D> associated with monomer type i.
*
* \param in input stream (i.e., input file)
* \param fields array of RField fields (r-space grid)
* \param unitCell crystallographic unit cell (output)
*/
void readFieldsRGrid(std::istream& in,
DArray< RDField<D> >& fields,
UnitCell<D>& unitCell) const;
/**
* Read array of RField objects (fields on an r-space grid) from file.
*
* The capacity of array fields is equal to nMonomer, and element
* fields[i] is the RField<D> associated with monomer type i.
*
* This function opens an input file with the specified filename,
* reads fields in RField<D> real-space grid format from that file,
* and then closes the file.
*
* \param filename name of input file
* \param fields array of RField fields (r-space grid)
* \param unitCell crystallographic unit cell (output)
*/
void readFieldsRGrid(std::string filename,
DArray< RDField<D> >& fields,
UnitCell<D>& unitCell) const;
/**
* Write array of RField objects (fields on an r-space grid) to file.
*
* \param out output stream (i.e., output file)
* \param fields array of RField fields (r-space grid)
* \param unitCell crystallographic unit cell
*/
void writeFieldsRGrid(std::ostream& out,
DArray< RDField<D> > const& fields,
UnitCell<D> const & unitCell) const;
/**
* Write array of RField objects (fields on an r-space grid) to file.
*
* This function opens an output file with the specified filename,
* writes fields in RField<D> real-space grid format to that file,
* and then closes the file.
*
* \param filename name of output file
* \param fields array of RField fields (r-space grid)
* \param unitCell crystallographic unit cell
*/
void writeFieldsRGrid(std::string filename,
DArray< RDField<D> > const& fields,
UnitCell<D> const & unitCell) const;
/**
* Read a single RField objects (field on an r-space grid) from file.
*
* \param in input stream
* \param field RField field (r-space grid)
* \param unitCell crystallographic unit cell
*/
void readFieldRGrid(std::istream& in, RDField<D> &field,
UnitCell<D>& unitCell) const;
/**
* Read a single RField objects (field on an r-space grid).
*
* \param filename name of input file
* \param field RField field (r-space grid)
* \param unitCell crystallographic unit cell
*/
void readFieldRGrid(std::string filename, RDField<D> &field,
UnitCell<D>& unitCell) const;
/**
* Write a single RField objects (field on an r-space grid) to file.
*
* \param out output stream
* \param field RField field (r-space grid)
* \param unitCell crystallographic unit cell
* \param writeHeader should a file header be written?
*/
void writeFieldRGrid(std::ostream& out,
RDField<D> const & field,
UnitCell<D> const & unitCell,
bool writeHeader = true) const;
/**
* Write a single RField objects (field on an r-space grid) to file.
*
* \param filename name of input file
* \param field RField field (r-space grid)
* \param unitCell crystallographic unit cell
*/
void writeFieldRGrid(std::string filename, RDField<D> const & field,
UnitCell<D> const & unitCell) const;
/**
* Read array of RDFieldDft objects (k-space fields) from file.
*
* The capacity of the array is equal to nMonomer, and element
* fields[i] is the discrete Fourier transform of the field for
* monomer type i.
*
* \param in input stream (i.e., input file)
* \param fields array of RDFieldDft fields (k-space grid)
* \param unitCell crystallographic unit cell (output)
*/
void readFieldsKGrid(std::istream& in,
DArray< RDFieldDft<D> >& fields,
UnitCell<D>& unitCell) const;
/**
* Read array of RDFieldDft objects (k-space fields) from file.
*
* This function opens a file with name filename, reads discrete
* Fourier components (Dft) of fields from that file, and closes
* the file.
*
* The capacity of the array is equal to nMonomer, and element
* fields[i] is the discrete Fourier transform of the field for
* monomer type i.
*
* \param filename name of input file
* \param fields array of RDFieldDft fields (k-space grid)
* \param unitCell crystallographic unit cell (output)
*/
void readFieldsKGrid(std::string filename,
DArray< RDFieldDft<D> >& fields,
UnitCell<D>& unitCell) const;
/**
* Write array of RDFieldDft objects (k-space fields) to file.
*
* The capacity of the array fields is equal to nMonomer. Element
* fields[i] is the discrete Fourier transform of the field for
* monomer type i.
*
* \param out output stream (i.e., output file)
* \param fields array of RDFieldDft fields
* \param unitCell crystallographic unit cell
*/
void writeFieldsKGrid(std::ostream& out,
DArray< RDFieldDft<D> > const& fields,
UnitCell<D> const & unitCell) const;
/**
* Write array of RDFieldDft objects (k-space fields) to a file.
*
* This function opens a file with name filename, writes discrete
* Fourier transform components (DFT) components of fields to that
* file, and closes the file.
*
* \param filename name of output file.
* \param fields array of RDFieldDft fields (k-space grid)
* \param unitCell crystallographic unit cell
*/
void writeFieldsKGrid(std::string filename,
DArray< RDFieldDft<D> > const& fields,
UnitCell<D> const & unitCell) const;
/**
* Reader header of field file (fortran pscf format)
*
* \param in input stream (i.e., input file)
* \param nMonomer number of monomers read from file (output)
* \param unitCell crystallographic unit cell (output)
*/
void readFieldHeader(std::istream& in,
int& nMonomer,
UnitCell<D>& unitCell) const;
/**
* Write header for field file (fortran pscf format)
*
* \param out output stream (i.e., output file)
* \param nMonomer number of monomer types
* \param unitCell crystallographic unit cell
*/
void writeFieldHeader(std::ostream& out, int nMonomer,
UnitCell<D> const & unitCell) const;
//@}
/// \name Field Format Conversion
//@{
/**
* Convert field from symmetrized basis to Fourier transform (k-grid).
*
* \param components coefficients of symmetry-adapted basis functions
* \param dft discrete Fourier transform of a real field
*/
void convertBasisToKGrid(DArray<double> const& components,
RDFieldDft<D>& dft) const;
/**
* Convert fields from symmetrized basis to Fourier transform (kgrid).
*
* The in and out parameters are arrays of fields, in which element
* number i is the field associated with monomer type i.
*
* \param in components of fields in symmetry adapted basis
* \param out fields defined as discrete Fourier transforms (k-grid)
*/
void convertBasisToKGrid(DArray< DArray<double> > const & in,
DArray< RDFieldDft<D> >& out) const;
/**
* Convert field from Fourier transform (k-grid) to symmetrized basis.
*
* \param dft complex DFT (k-grid) representation of a field.
* \param components coefficients of symmetry-adapted basis functions.
*/
void convertKGridToBasis(RDFieldDft<D> const& dft,
DArray<double>& components) const;
/**
* Convert fields from Fourier transform (kgrid) to symmetrized basis.
*
* The in and out parameters are each an array of fields, in which
* element i is the field associated with monomer type i.
*
* \param in fields defined as discrete Fourier transforms (k-grid)
* \param out components of fields in symmetry adapted basis
*/
void convertKGridToBasis(DArray< RDFieldDft<D> > const & in,
DArray< DArray<double> > & out) const;
/**
* Convert fields from symmetrized basis to spatial grid (rgrid).
*
* \param in fields in symmetry adapted basis form
* \param out fields defined on real-space grid
*/
void convertBasisToRGrid(DArray< DArray<double> > const & in,
DArray< RDField<D> >& out) const;
/**
* Convert fields from spatial grid (rgrid) to symmetrized basis.
*
* \param in fields defined on real-space grid
* \param out fields in symmetry adapted basis form
*/
void convertRGridToBasis(DArray< RDField<D> > const & in,
DArray< DArray<double> > & out) const;
/**
* Convert fields from k-grid (DFT) to real space (rgrid) format.
*
* \param in fields in discrete Fourier format (k-grid)
* \param out fields defined on real-space grid (r-grid)
*/
void convertKGridToRGrid(DArray< RDFieldDft<D> > const & in,
DArray< RDField<D> > & out) const;
/**
* Convert fields from spatial grid (rgrid) to k-grid format.
*
* \param in fields defined on real-space grid (r-grid)
* \param out fields in discrete Fourier format (k-grid)
*/
void convertRGridToKGrid(DArray< RDField<D> > const & in,
DArray< RDFieldDft<D> > & out) const;
//@}
private:
// DFT work array for two-step conversion basis <-> kgrid <-> rgrid.
mutable RDFieldDft<D> workDft_;
// Pointers to associated objects.
/// Pointer to spatial discretization mesh.
Mesh<D> const * meshPtr_;
/// Pointer to FFT object.
FFT<D> const * fftPtr_;
/// Pointer to lattice system
typename UnitCell<D>::LatticeSystem * latticePtr_;
/// Pointer to group name string
std::string * groupNamePtr_;
/// Pointer to a SpaceGroup object
SpaceGroup<D> * groupPtr_;
/// Pointer to a Basis object
Basis<D> * basisPtr_;
/// Pointer to Filemaster (holds paths to associated I/O files).
FileMaster const * fileMasterPtr_;
// Private accessor functions:
/// Get spatial discretization mesh by const reference.
Mesh<D> const & mesh() const
{
UTIL_ASSERT(meshPtr_);
return *meshPtr_;
}
/// Get FFT object by const reference.
FFT<D> const & fft() const
{
UTIL_ASSERT(fftPtr_);
return *fftPtr_;
}
/// Get lattice system enumeration value by reference.
typename UnitCell<D>::LatticeSystem & lattice() const
{
UTIL_ASSERT(latticePtr_);
return *latticePtr_;
}
/// Get group name string
std::string & groupName() const
{
UTIL_ASSERT(groupNamePtr_);
return *groupNamePtr_;
}
/// Get Basis by reference.
SpaceGroup<D> & group() const
{
UTIL_ASSERT(basisPtr_);
return *groupPtr_;
}
/// Get Basis by reference.
Basis<D> & basis() const
{
UTIL_ASSERT(basisPtr_);
return *basisPtr_;
}
/// Get FileMaster by const reference.
FileMaster const & fileMaster() const
{
UTIL_ASSERT(fileMasterPtr_);
return *fileMasterPtr_;
}
/**
* Check state of work array, allocate if necessary.
*/
void checkWorkDft() const;
};
#ifndef PSPG_FIELD_IO_TPP
extern template class FieldIo<1>;
extern template class FieldIo<2>;
extern template class FieldIo<3>;
#endif
} // namespace Pspc
} // namespace Pscf
#endif
| 17,589
|
C++
|
.h
| 438
| 30.917808
| 76
| 0.599251
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,065
|
CFieldContainer.h
|
dmorse_pscfpp/src/pspg/field/CFieldContainer.h
|
#ifndef PSPG_C_FIELD_CONTAINER_H
#define PSPG_C_FIELD_CONTAINER_H
/*
* PSCF - Polymer Self-Consistent Field Theory
*
* Copyright 2016 - 2022, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include <util/containers/DArray.h> // member template
#include <pspg/field/RDField.h> // member template parameter
namespace Pscf {
namespace Pspg {
using namespace Util;
/**
* A list of c fields stored in both basis and r-grid format.
*
* A CFieldContainer<D> contains representations of a list of nMonomer
* fields that are associated with different monomer types in two
* different related formats:
*
* - A DArray of DArray<double> containers holds components of each
* field in a symmetry-adapted Fourier expansion (i.e., in basis
* format). This is accessed by the basis() and basis(int)
* member functions.
*
* - A DArray of RDField<D> containers holds valus of each field on
* the nodes of a regular grid. This is accessed by the rgrid()
* and rgrid(int) member functions.
*
* \ingroup Pspg_Field_Module
*/
template <int D>
class CFieldContainer
{
public:
/**
* Constructor.
*/
CFieldContainer();
/**
* Destructor.
*/
~CFieldContainer();
/**
* Set stored value of nMonomer.
*
* May only be called once.
*
* \param nMonomer number of monomer types.
*/
void setNMonomer(int nMonomer);
/**
* Allocate or re-allocate memory for fields in rgrid format.
*
* \param dimensions dimensions of spatial mesh
*/
void allocateRGrid(IntVec<D> const & dimensions);
/**
* De-allocate fields in rgrid format.
*/
void deallocateRGrid();
/**
* Allocate or re-allocate memory for fields in basis format.
*
* \param nBasis number of basis functions
*/
void allocateBasis(int nBasis);
/**
* De-allocate fields in basis format.
*/
void deallocateBasis();
/**
* Allocate memory for both r-grid and basis field formats.
*
* This function may only be called once.
*
* \param nMonomer number of monomer types
* \param nBasis number of basis functions
* \param dimensions dimensions of spatial mesh
*/
void allocate(int nMonomer, int nBasis, IntVec<D> const & dimensions);
/**
* Get array of all fields in basis format (non-const).
*/
DArray< DArray<double> > & basis()
{ return basis_; }
/**
* Get array of all fields in basis format (const)
*
* The array capacity is equal to the number of monomer types.
*/
DArray< DArray<double> > const & basis() const
{ return basis_; }
/**
* Get the field for one monomer type in basis format (non-const).
*
* \param monomerId integer monomer type index (0, ... ,nMonomer-1)
*/
DArray<double> & basis(int monomerId)
{ return basis_[monomerId]; }
/**
* Get the field for one monomer type in basis format (const)
*
* \param monomerId integer monomer type index (0, ... ,nMonomer-1)
*/
DArray<double> const & basis(int monomerId) const
{ return basis_[monomerId]; }
/**
* Get array of all fields in r-grid format (non-const).
*/
DArray< RDField<D> > & rgrid()
{ return rgrid_; }
/**
* Get array of all fields in r-grid format (const).
*/
DArray< RDField<D> > const & rgrid() const
{ return rgrid_; }
/**
* Get field for one monomer type in r-grid format (non-const)
*
* \param monomerId integer monomer type index (0,..,nMonomer-1)
*/
RDField<D> & rgrid(int monomerId)
{ return rgrid_[monomerId]; }
/**
* Get field for one monomer type in r-grid format (const).
*
* \param monomerId integer monomer type index (0,..,nMonomer-1)
*/
RDField<D> const & rgrid(int monomerId) const
{ return rgrid_[monomerId]; }
/**
* Has memory been allocated for fields in r-grid format?
*/
bool isAllocatedRGrid() const
{ return isAllocatedRGrid_; }
/**
* Has memory been allocated for fields in basis format?
*/
bool isAllocatedBasis() const
{ return isAllocatedBasis_; }
private:
/*
* Array of fields in symmetry-adapted basis format
*
* Element basis_[i] is an array that contains the components
* of the field associated with monomer i, in a symmetry-adapted
* Fourier basis expansion.
*/
DArray< DArray<double> > basis_;
/*
* Array of fields in real-space grid (r-grid) format
*
* Element basis_[i] is an RDField<D> that contains values of the
* field associated with monomer i on the nodes of a regular mesh.
*/
DArray< RDField<D> > rgrid_;
/*
* Number of monomer types.
*/
int nMonomer_;
/*
* Has memory been allocated for fields in r-grid format?
*/
bool isAllocatedRGrid_;
/*
* Has memory been allocated for fields in basis format?
*/
bool isAllocatedBasis_;
};
#ifndef PSPG_FIELD_CONTAINER_TPP
// Suppress implicit instantiation
extern template class CFieldContainer<1>;
extern template class CFieldContainer<2>;
extern template class CFieldContainer<3>;
#endif
} // namespace Pspg
} // namespace Pscf
#endif
| 5,655
|
C++
|
.h
| 179
| 25.374302
| 76
| 0.619511
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,066
|
WFieldContainer.h
|
dmorse_pscfpp/src/pspg/field/WFieldContainer.h
|
#ifndef PSPG_W_FIELD_CONTAINER_H
#define PSPG_W_FIELD_CONTAINER_H
/*
* PSCF - Polymer Self-Consistent Field Theory
*
* Copyright 2016 - 2022, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include <util/param/ParamComposite.h> // base class
#include <pscf/math/IntVec.h> // function parameter
#include <pscf/crystal/UnitCell.h> // function parameter
#include <pspg/field/RDField.h> // member template parameter
#include <util/containers/DArray.h> // member template
namespace Pscf {
namespace Pspg {
template <int D> class FieldIo;
using namespace Util;
/**
* A list of fields stored in both basis and r-grid format.
*
* A WFieldContainer<D> contains representations of a list of nMonomer
* fields that are associated with different monomer types in two
* different related formats:
*
* - A DArray of DArray<double> containers holds components of each
* field in a symmetry-adapted Fourier expansion (i.e., in basis
* format). This is accessed by the basis() and basis(int)
* member functions.
*
* - A DArray of RDField<D> containers holds valus of each field on
* the nodes of a regular grid. This is accessed by the rgrid()
* and rgrid(int) member functions.
*
* A WFieldContainer is designed to automatically update one of these
* representations when the other is modified, when appropriate.
* A pointer to an associated FieldIo<D> is used for these conversions.
* The setBasis function allows the user to input new components in
* basis format and internally recomputes the values in r-grid format.
* The setRgrid function allows the user to reset the fields in
* r-grid format, but recomputes the components in basis format if
* and only if the user declares that the fields are known to be
* invariant under all symmetries of the space group. A boolean
* flag named isSymmetric is used to keep track of whether the
* current field is symmetric, and thus whether the basis format
* exists.
*
* \ingroup Pspg_Field_Module
*/
template <int D>
class WFieldContainer : public ParamComposite
{
public:
/**
* Constructor.
*/
WFieldContainer();
/**
* Destructor.
*/
~WFieldContainer();
/**
* Create association with FieldIo (store pointer).
*/
void setFieldIo(FieldIo<D> const & fieldIo);
/**
* Set stored value of nMonomer.
*
* May only be called once.
*
* \param nMonomer number of monomer types.
*/
void setNMonomer(int nMonomer);
/**
* Allocate or re-allocate memory for fields in rgrid format.
*
* \param dimensions dimensions of spatial mesh
*/
void allocateRGrid(IntVec<D> const & dimensions);
/**
* De-allocate fields in rgrid format.
*/
void deallocateRGrid();
/**
* Allocate or re-allocate memory for fields in basis format.
*
* \param nBasis number of basis functions
*/
void allocateBasis(int nBasis);
/**
* De-allocate fields in basis format.
*/
void deallocateBasis();
/**
* Allocate memory for all fields.
*
* This function may only be called once.
*
* \param nMonomer number of monomer types
* \param nBasis number of basis functions
* \param dimensions dimensions of spatial mesh
*/
void allocate(int nMonomer, int nBasis, IntVec<D> const & dimensions);
/**
* Set field component values, in symmetrized Fourier format.
*
* This function also computes and stores the corresponding
* r-grid representation. On return, hasData and isSymmetric
* are both true.
*
* \param fields array of new fields in basis format
*/
void setBasis(DArray< DArray<double> > const & fields);
/**
* Set fields values in real-space (r-grid) format.
*
* If the isSymmetric parameter is true, this function assumes that
* the fields are known to be symmetric and so computes and stores
* the corresponding basis components. If isSymmetric is false, it
* only sets the values in the r-grid format.
*
* On return, hasData is true and the persistent isSymmetric flag
* defined by the class is set to the value of the isSymmetric
* input parameter.
*
* \param fields array of new fields in r-grid format
* \param isSymmetric is this field symmetric under the space group?
*/
void setRGrid(DArray< RDField<D> > const & fields,
bool isSymmetric = false);
/**
* Set new w fields, in unfolded real-space (r-grid) format.
*
* The array fields is an unfolded array that contains fields for
* all monomer types, with the field for monomer 0 first, etc.
*
* \param fields unfolded array of new w (chemical potential) fields
*/
void setRGrid(DField<cudaReal> & fields);
/**
* Read field component values from input stream, in symmetrized
* Fourier format.
*
* This function also computes and stores the corresponding
* r-grid representation. On return, hasData and isSymmetric
* are both true.
*
* This object must already be allocated and associated with
* a FieldIo object to run this function.
*
* \param in input stream from which to read fields
* \param unitCell associated crystallographic unit cell
*/
void readBasis(std::istream& in, UnitCell<D>& unitCell);
/**
* Read field component values from file, in symmetrized
* Fourier format.
*
* This function also computes and stores the corresponding
* r-grid representation. On return, hasData and isSymmetric
* are both true.
*
* This object must already be allocated and associated with
* a FieldIo object to run this function.
*
* \param filename file from which to read fields
* \param unitCell associated crystallographic unit cell
*/
void readBasis(std::string filename, UnitCell<D>& unitCell);
/**
* Reads fields from an input stream in real-space (r-grid) format.
*
* If the isSymmetric parameter is true, this function assumes that
* the fields are known to be symmetric and so computes and stores
* the corresponding basis components. If isSymmetric is false, it
* only sets the values in the r-grid format.
*
* On return, hasData is true and the persistent isSymmetric flag
* defined by the class is set to the value of the isSymmetric
* input parameter.
*
* This object must already be allocated and associated with
* a FieldIo object to run this function.
*
* \param in input stream from which to read fields
* \param unitCell associated crystallographic unit cell
* \param isSymmetric is this field symmetric under the space group?
*/
void readRGrid(std::istream& in, UnitCell<D>& unitCell,
bool isSymmetric = false);
/**
* Reads fields from a file in real-space (r-grid) format.
*
* If the isSymmetric parameter is true, this function assumes that
* the fields are known to be symmetric and so computes and stores
* the corresponding basis components. If isSymmetric is false, it
* only sets the values in the r-grid format.
*
* On return, hasData is true and the persistent isSymmetric flag
* defined by the class is set to the value of the isSymmetric
* input parameter.
*
* This object must already be allocated and associated with
* a FieldIo object to run this function.
*
* \param filename file from which to read fields
* \param unitCell associated crystallographic unit cell
* \param isSymmetric is this field symmetric under the space group?
*/
void readRGrid(std::string filename, UnitCell<D>& unitCell,
bool isSymmetric = false);
/**
* Symmetrize r-grid fields, compute corresponding basis components.
*
* This function may be used after setting or reading w fields in
* r-grid format that are known to be symmetric under the space
* group to remove small deviations from symmetry and generate
* basis components.
*
* The function symmetrizes the fields by converting from r-grid
* to basis format and then back again, while also storing the
* resulting basis components and setting isSymmetric() true.
*
* This function assumes that the current wFieldsRGrid fields
* are known by the user to be symmetric, and does NOT check this.
* Applying this function to fields that are not symmetric will
* silently corrupt the fields.
*
* On entry, hasData() must be true and isSymmetric() must be false.
* On exit, isSymmetric() is true.
*/
void symmetrize();
/**
* Get array of all fields in basis format.
*
* The array capacity is equal to the number of monomer types.
*/
DArray< DArray<double> > const & basis() const;
/**
* Get the field for one monomer type in basis format.
*
* An Exception is thrown if isSymmetric is false.
*
* \param monomerId integer monomer type index (0,...,nMonomer-1)
*/
DArray<double> const & basis(int monomerId) const;
/**
* Get array of all fields in r-space grid format.
*
* The array capacity is equal to the number of monomer types.
*/
DArray< RDField<D> > const & rgrid() const;
/**
* Get the field for one monomer type in r-space grid format.
*
* \param monomerId integer monomer type index (0,..,nMonomer-1)
*/
RDField<D> const & rgrid(int monomerId) const;
/**
* Has memory been allocated for fields in r-grid format?
*/
bool isAllocatedRGrid() const;
/**
* Has memory been allocated for fields in basis format?
*/
bool isAllocatedBasis() const;
/**
* Has field data been set in either format?
*
* This flag is set true in setBasis and setRGrid.
*/
bool hasData() const;
/**
* Are fields symmetric under all elements of the space group?
*
* A valid basis format exists if and only if isSymmetric is true.
* This flat is set true if the fields were input in basis format
* by the function setBasis, or if they were set in grid format
* by the function setRGrid but isSymmetric was set true.
*/
bool isSymmetric() const;
private:
/*
* Array of fields in symmetry-adapted basis format
*
* Element basis_[i] is an array that contains the components
* of the field associated with monomer i, in a symmetry-adapted
* Fourier expansion.
*/
DArray< DArray<double> > basis_;
/*
* Array of fields in real-space grid (r-grid) format
*
* Element basis_[i] is an RDField<D> that contains values of the
* field associated with monomer i on the nodes of a regular mesh.
*/
DArray< RDField<D> > rgrid_;
/*
* Pointer to associated FieldIo object
*/
FieldIo<D> const * fieldIoPtr_;
/*
* Integer vector of grid dimensions.
*
* Element i is the number of grid points along direction i
*/
IntVec<D> meshDimensions_;
/*
* Total number grid points (product of mesh dimensions)
*/
int meshSize_;
/*
* Number of basis functions in symmetry-adapted basis
*/
int nBasis_;
/*
* Number of monomer types (number of fields)
*/
int nMonomer_;
/*
* Has memory been allocated for fields in r-grid format?
*/
bool isAllocatedRGrid_;
/*
* Has memory been allocated for fields in basis format?
*/
bool isAllocatedBasis_;
/*
* Has field data been initialized ?
*/
bool hasData_;
/*
* Are the fields symmetric under space group operations?
*
* Set true when fields are set using the symmetry adapted basis
* format via function setBasis. False by otherwise.
*/
bool isSymmetric_;
};
// Inline member functions
// Get array of all fields in basis format (const)
template <int D>
inline
DArray< DArray<double> > const & WFieldContainer<D>::basis() const
{ return basis_; }
// Get one field in basis format (const)
template <int D>
inline
DArray<double> const & WFieldContainer<D>::basis(int id) const
{ return basis_[id]; }
// Get all fields in r-grid format (const)
template <int D>
inline
DArray< RDField<D> > const &
WFieldContainer<D>::rgrid() const
{ return rgrid_; }
// Get one field in r-grid format (const)
template <int D>
inline
RDField<D> const & WFieldContainer<D>::rgrid(int id) const
{ return rgrid_[id]; }
// Has memory been allocated for fields in r-grid format?
template <int D>
inline bool WFieldContainer<D>::isAllocatedRGrid() const
{ return isAllocatedRGrid_; }
// Has memory been allocated for fields in basis format?
template <int D>
inline bool WFieldContainer<D>::isAllocatedBasis() const
{ return isAllocatedBasis_; }
// Has field data been initialized ?
template <int D>
inline bool WFieldContainer<D>::hasData() const
{ return hasData_; }
// Are the fields symmetric under space group operations?
template <int D>
inline bool WFieldContainer<D>::isSymmetric() const
{ return isSymmetric_; }
#ifndef PSPG_W_FIELD_CONTAINER_TPP
// Suppress implicit instantiation
extern template class WFieldContainer<1>;
extern template class WFieldContainer<2>;
extern template class WFieldContainer<3>;
#endif
} // namespace Pspg
} // namespace Pscf
#endif
| 14,269
|
C++
|
.h
| 385
| 30.615584
| 76
| 0.655287
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,067
|
RFieldComparison.h
|
dmorse_pscfpp/src/pspg/field/RFieldComparison.h
|
#ifndef PSPG_R_FIELD_COMPARISON_H
#define PSPG_R_FIELD_COMPARISON_H
/*
* PSCF - Polymer Self-Consistent Field Theory
*
* Copyright 2016 - 2022, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include <pscf/math/FieldComparison.h>
#include "RDField.h"
namespace Pscf {
namespace Pspg {
using namespace Util;
/**
* Comparator for fields in real-space (r-grid) format.
*
* \ingroup Pspg_Field_Module
*/
template <int D>
class RFieldComparison
{
public:
/**
* Constructor.
*/
RFieldComparison();
/**
* Comparator for individual fields.
*
* \param a first array of fields
* \param b second array of fields
*/
double compare(RDField<D> const& a, RDField<D> const& b);
/**
* Comparator for array of fields.
*
* \param a first array of fields
* \param b second array of fields
*/
double
compare(DArray<RDField<D>> const& a, DArray<RDField<D>> const& b);
/**
* Get precomputed maximum element-by-element difference.
*/
double maxDiff() const
{ return fieldComparison_.maxDiff(); }
/**
* Get precomputed rms difference.
*/
double rmsDiff() const
{ return fieldComparison_.rmsDiff(); }
private:
// True if a comparison has been made, false otherwise.
bool compared_;
// Composition usage of FieldComparison, rather than inheritance.
FieldComparison< DArray< cudaReal > > fieldComparison_;
};
#ifndef PSPG_R_FIELD_COMPARISON_TPP
extern template class RFieldComparison<1>;
extern template class RFieldComparison<2>;
extern template class RFieldComparison<3>;
#endif
} // namespace Pspg
} // namespace Pscf
#endif
| 1,842
|
C++
|
.h
| 65
| 23.092308
| 72
| 0.660399
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,068
|
RDField.h
|
dmorse_pscfpp/src/pspg/field/RDField.h
|
#ifndef PSPG_R_DFIELD_H
#define PSPG_R_DFIELD_H
/*
* PSCF Package
*
* Copyright 2016 - 2022, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include "DField.h"
#include <pscf/math/IntVec.h>
#include <util/global.h>
#include <pspg/math/GpuResources.h>
#include <cufft.h>
namespace Pscf {
namespace Pspg
{
using namespace Util;
using namespace Pscf;
/**
* Field of real single precision values on an FFT mesh on a device.
*
* cudaReal = float or double, depending on preprocessor macro.
*
* \ingroup Pspg_Field_Module
*/
template <int D>
class RDField : public DField<cudaReal>
{
public:
/**
* Default constructor.
*/
RDField();
/**
* Copy constructor.
*
* Allocates new memory and copies all elements by value.
*
*\param other the RField to be copied.
*/
RDField(const RDField& other);
/**
* Destructor.
*
* Deletes underlying C array, if allocated previously.
*/
virtual ~RDField();
/**
* Assignment operator.
*
* If this Field is not allocated, launch a kernel to swap memory.
*
* If this and the other Field are both allocated, the capacities must
* be exactly equal. If so, this method copies all elements.
*
* \param other the RHS RField
*/
RDField& operator = (const RDField& other);
/**
* Allocate the underlying C array for an FFT grid.
*
* \throw Exception if the RField is already allocated.
*
* \param meshDimensions number of grid points in each direction
*/
void allocate(const IntVec<D>& meshDimensions);
/**
* Return mesh dimensions by constant reference.
*/
const IntVec<D>& meshDimensions() const;
/**
* Serialize a Field to/from an Archive.
*
* \param ar archive
* \param version archive version id
*/
template <class Archive>
void serialize(Archive& ar, const unsigned int version);
using DField<cudaReal>::allocate;
using DField<cudaReal>::operator=;
private:
// Vector containing number of grid points in each direction.
IntVec<D> meshDimensions_;
};
/*
* Allocate the underlying C array for an FFT grid.
*/
template <int D>
void RDField<D>::allocate(const IntVec<D>& meshDimensions)
{
int size = 1;
for (int i = 0; i < D; ++i) {
UTIL_CHECK(meshDimensions[i] > 0);
meshDimensions_[i] = meshDimensions[i];
size *= meshDimensions[i];
}
DField<cudaReal>::allocate(size);
}
/*
* Return mesh dimensions by constant reference.
*/
template <int D>
inline const IntVec<D>& RDField<D>::meshDimensions() const
{ return meshDimensions_; }
/*
* Serialize a Field to/from an Archive.
*/
template <int D>
template <class Archive>
void RDField<D>::serialize(Archive& ar, const unsigned int version)
{
int capacity;
if (Archive::is_saving()) {
capacity = capacity_;
}
ar & capacity;
if (Archive::is_loading()) {
if (!isAllocated()) {
if (capacity > 0) {
allocate(capacity);
}
} else {
if (capacity != capacity_) {
UTIL_THROW("Inconsistent Field capacities");
}
}
}
if (isAllocated()) {
double* tempData = new double[capacity];
cudaMemcpy(tempData, data_, capacity * sizeof(cudaReal),
cudaMemcpyDeviceToHost);
for (int i = 0; i < capacity_; ++i) {
ar & tempData[i];
}
delete[] tempData;
}
ar & meshDimensions_;
}
}
}
#include "RDField.tpp"
#endif
| 3,881
|
C++
|
.h
| 142
| 20.985915
| 75
| 0.601187
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,069
|
NanException.h
|
dmorse_pscfpp/src/pscf/iterator/NanException.h
|
#ifndef PSCF_NAN_EXCEPTION_H
#define PSCF_NAN_EXCEPTION_H
/*
* PSCF - Polymer Self-Consistent Field Theory
*
* Copyright 2016 - 2022, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include <util/global.h>
#include <util/misc/Exception.h>
namespace Pscf {
using namespace Util;
/**
* Exception thrown when not-a-number (NaN) is encountered.
*
* An exception to be thrown when a required numerical parameter has a
* value of NaN. This may happen, for instance, as a result of dividing
* by zero. A NanException is used rather than a generic Exception in
* these instances so that the NanException can be caught by a try-catch
* block.
*
* A NanException behaves identically to a generic Exception, but with a
* pre-defined error message rather than a user-specified message. There
* is no preprocessor macro to throw a NanException, so they must be thrown
* using the constructor. This will typically assume the following syntax,
* where values of the file and line parameters are given by the built-in
* macros __FILE__ and __LINE__, respectively:
* \code
* throw Exception("MyClass::myFunction", __FILE__, __LINE__ );
* \endcode
*
* \ingroup Pscf_Iterator_Module
*/
class NanException : public Exception
{
public:
/**
* Constructor.
*
* Constructs error message that includes file and line number. Values
* of the file and line parameters should be given by the built-in macros
* __FILE__ and __LINE__, respectively, in the calling function.
*
* \param function name of the function from which the Exception was thrown
* \param file name of the file from which the Exception was thrown
* \param line line number in file
* \param echo if echo, then echo to Log::file() when constructed.
*/
NanException(const char *function, const char *file, int line,
int echo = 1);
/**
* Constructor without function name parameter.
*
* \param file name of the file from which the Exception was thrown
* \param line line number in file
* \param echo if echo, then echo to std out when constructed.
*/
NanException(const char *file, int line, int echo = 1);
/**
* Destructor
*/
~NanException();
};
}
#endif
| 2,473
|
C++
|
.h
| 65
| 32.584615
| 80
| 0.668474
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,070
|
AmIteratorTmpl.h
|
dmorse_pscfpp/src/pscf/iterator/AmIteratorTmpl.h
|
#ifndef PSCF_AM_ITERATOR_TMPL_H
#define PSCF_AM_ITERATOR_TMPL_H
/*
* PSCF - Polymer Self-Consistent Field Theory
*
* Copyright 2016 - 2022, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include <util/containers/DArray.h> // member template
#include <util/containers/DMatrix.h> // member template
#include <util/containers/RingBuffer.h> // member template
namespace Pscf {
using namespace Util;
/**
* Template for Anderson mixing iterator algorithm.
*
* Anderson mixing is an algorithm for solving a system of N nonlinear
* equations of the form r_{i}(x) = 0 for i = 0, ..., N-1, where x
* denotes a vector or array of unknown coordinate values. A vector
* of array of unknowns is referred here the "field" vector, while a
* vector or array of values of the errors r_{0},..., r_{N-1} is
* referred to as the residual vector.
*
* The template parameter Iterator is a base class that must be derived
* from Util::ParamComposite, and must declare a virtual solve(bool)
* function with the same interface as that declared here.
*
* The template type parameter T is the type of the data structure used
* to store both field and residual vectors.
*
* \ingroup Pscf_Iterator_Module
*/
template <typename Iterator, typename T>
class AmIteratorTmpl : virtual public Iterator
{
public:
/**
* Constructor
*/
AmIteratorTmpl();
/**
* Destructor
*/
~AmIteratorTmpl();
/**
* Read all parameters and initialize.
*
* \param in input filestream
*/
void readParameters(std::istream& in);
/**
* Iterate to a solution
*
* \param isContinuation true iff continuation within a sweep
* \return 0 for convergence, 1 for failure
*/
int solve(bool isContinuation = false);
protected:
/// Type of error criterion used to test convergence
std::string errorType_;
// Members of parent classes with non-dependent names
using Iterator::setClassName;
using ParamComposite::read;
using ParamComposite::readOptional;
/**
* Set value of maxItr.
*
* Provided to allow subclasses to set a modified default value
* before calling readParameters, in which maxItr is optional.
* Global default, set in constructor, is maxItr = 200.
*
* \param maxItr maximum number of iterations attempted
*/
void setMaxItr(int maxItr);
/**
* Set value of maxHist (number of retained previous states)
*
* Provided to allow subclasses to set a modified default value
* before calling readParameters, in which maxItr is optional.
* Global default, set in constructor, is maxHist = 50.
*
* \param maxHist maximum number of retained previous states
*/
void setMaxHist(int maxHist);
/**
* Set and validate value of errorType string.
*
* Provided to allow subclasses to set a modified default value
* before calling readParameters, in which errorType is optional.
* Global default, set in constructor, is relNormResid = 50.
*
* \param errorType error type string
*/
void setErrorType(std::string errorType);
/**
* Read and validate the optional errorType string parameter.
*
* \param in input filestream
*/
void readErrorType(std::istream& in);
/**
* Checks if a string is a valid error type.
*
* Virtual to allow extension of allowed error type string values.
*
* \return true if type is valid, false otherwise.
*/
virtual bool isValidErrorType();
/**
* Find the L2 norm of a vector.
*
* The default implementation calls dotProduct internally.
* Virtual to allow more optimized versions.
*
* \param hist residual vector
*/
virtual double norm(T const & hist);
/**
* Allocate memory required by AM algorithm, if necessary.
*
* If the required memory has been allocated previously, this
* function does nothing and returns.
*/
void allocateAM();
/**
* Clear information about history.
*
* This function clears the the history and basis vector ring
* buffer containers.
*/
virtual void clear();
/**
* Initialize just before entry to iterative loop.
*
* This function is called by the solve function before entering the
* loop over iterations. The default functions calls allocateAM()
* if isAllocatedAM() is false, and otherwise calls clear() if
* isContinuation is false.
*
* \param isContinuation true iff continuation within a sweep
*/
virtual void setup(bool isContinuation);
/**
* Compute and return error used to test for convergence.
*
* \param verbose verbosity level of output report
* \return error measure used to test for convergence.
*/
virtual double computeError(int verbose);
/**
* Return the current residual vector by const reference.
*/
T const & residual() const;
/**
* Return the current field or state vector by const reference.
*/
T const & field() const;
/**
* Verbosity level, allowed values 0, 1, or 2.
*/
int verbose() const;
/**
* Have data structures required by the AM algorithm been allocated?
*/
bool isAllocatedAM() const;
private:
// Private member variables
/// Error tolerance.
double epsilon_;
/// Free parameter for minimization.
double lambda_;
/// Maximum number of iterations to attempt.
int maxItr_;
/// Maximum number of basis vectors
int maxHist_;
/// Number of basis vectors defined as differences.
int nBasis_;
/// Current iteration counter.
int itr_;
/// Number of elements in field or residual vectors.
int nElem_;
/// Verbosity level.
int verbose_;
/// Output summary of timing results?
bool outputTime_;
/// Has the allocateAM function been called.
bool isAllocatedAM_;
/// History of previous field vectors.
RingBuffer<T> fieldHists_;
/// Basis vectors of field histories (differences of fields).
RingBuffer<T> fieldBasis_;
/// History of residual vectors.
RingBuffer<T> resHists_;
/// Basis vectors of residual histories (differences of residuals)
RingBuffer<T> resBasis_;
/// Matrix containing the dot products of vectors in resBasis_
DMatrix<double> U_;
/// Coefficients for mixing previous states.
DArray<double> coeffs_;
/// Dot products of current residual with residual basis vectors.
DArray<double> v_;
/// New trial field (big W in Arora et al. 2017)
T fieldTrial_;
/// Predicted field residual for trial state (big D)
T resTrial_;
/// Workspace for calculations
T temp_;
// --- Non-virtual private functions (implemented here) ---- //
/**
* Compute optimal coefficients of residual basis vectors.
*/
void computeResidCoeff();
/**
* Compute the trial field and set in the system.
*
* This implements a two-step process:
* - Correct the current state and predicted residual by adding
* linear combination of state and residual basis vectors.
* - Call addPredictedError to attempt to correct predicted
* residual
*/
void updateGuess();
// --- Private virtual functions with default implementations --- //
/**
* Update the U matrix.
*
* \param U U matrix
* \param resBasis RingBuffer of residual basis vectors.
* \param nHist number of histories stored at this iteration
*/
virtual void updateU(DMatrix<double> & U,
RingBuffer<T> const & resBasis, int nHist);
/**
* Update the v vector.
*
* \param v v vector
* \param resCurrent current residual vector
* \param resBasis RingBuffer of residual basis vectors.
* \param nHist number of histories stored at this iteration
*/
virtual void updateV(DArray<double> & v, T const & resCurrent,
RingBuffer<T> const & resBasis, int nHist);
// --- Pure virtual methods for doing AM iterator math --- //
/**
* Set one vector equal to another.
*
* \param a the vector to be set (lhs of assignment)
* \param b the vector value to assign (rhs of assignment)
*/
virtual void setEqual(T& a, T const & b) = 0;
/**
* Compute the inner product of two vectors.
*
* \param a first vector
* \param b second vector
*/
virtual double dotProduct(T const & a, T const & b) = 0;
/**
* Find the maximum magnitude element of a residual vector.
*
* \param hist residual vector
*/
virtual double maxAbs(T const & hist) = 0;
/**
* Update a basis that spans differences of past vectors.
*
* This function is applied to update bases for both residual
* vectors and field vectors.
*
* \param basis RingBuffer of residual basis vectors
* \param hists RingBuffer of history of residual vectors
*/
virtual
void updateBasis(RingBuffer<T> & basis,
RingBuffer<T> const & hists) = 0;
/**
* Add linear combination of field basis vectors to the trial field.
*
* \param trial object for calculation results to be stored in
* \param basis list of history basis vectors
* \param coeffs list of coefficients of basis vectors
* \param nHist number of histories stored at this iteration
*/
virtual
void addHistories(T& trial,
RingBuffer<T> const & basis,
DArray<double> coeffs,
int nHist) = 0;
/**
* Remove predicted error from trial in attempt to correct for it.
*
* \param fieldTrial field for calculation results to be stored in
* \param resTrial predicted error for current mixing of histories
* \param lambda Anderson-Mixing parameter for mixing in histories
*/
virtual
void addPredictedError(T& fieldTrial, T const & resTrial,
double lambda) = 0;
// -- Pure virtual functions to exchange data with parent system -- //
/**
* Does the system have an initial guess?
*/
virtual bool hasInitialGuess() = 0;
/**
* Compute and return the number of residual or field vector elements.
*
* The private variable nElem_ is assigned the return value of this
* function on entry to allocateAM to set the number of elements of
* the residual and field vectors.
*/
virtual int nElements() = 0;
/**
* Get the current field vector from the system.
*
* \param curr current field vector (output)
*/
virtual void getCurrent(T& curr) = 0;
/**
* Run a calculation to update the system state.
*
* This function normally solves the modified diffusion equations,
* calculates monomer concentration fields, and computes stresses
* if appropriate.
*/
virtual void evaluate() = 0;
/**
* Compute the residual vector from the current system state.
*
* \param resid current residual vector.
*/
virtual void getResidual(T& resid) = 0;
/**
* Update the system with a passed in trial field vector.
*
* \param newGuess new field vector (input)
*/
virtual void update(T& newGuess) = 0;
/**
* Output relevant system details to the iteration log.
*/
virtual void outputToLog() = 0;
};
/*
* Return the current residual vector by const reference.
*/
template <typename Iterator, typename T>
T const & AmIteratorTmpl<Iterator,T>::residual() const
{ return resHists_[0]; }
/*
* Return the current field/state vector by const reference.
*/
template <typename Iterator, typename T>
T const & AmIteratorTmpl<Iterator,T>::field() const
{ return fieldHists_[0]; }
/*
* Integer level for verbosity of the log output (0-2).
*/
template <typename Iterator, typename T>
int AmIteratorTmpl<Iterator,T>::verbose() const
{ return verbose_; }
/*
* Has memory required by AM algorithm been allocated?
*/
template <typename Iterator, typename T>
bool AmIteratorTmpl<Iterator,T>::isAllocatedAM() const
{ return isAllocatedAM_; }
}
#include "AmIteratorTmpl.tpp"
#endif
| 13,053
|
C++
|
.h
| 369
| 28.260163
| 76
| 0.635699
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,071
|
AmbdInteraction.h
|
dmorse_pscfpp/src/pscf/iterator/AmbdInteraction.h
|
#ifndef PSCF_AMBD_INTERACTION_H
#define PSCF_AMBD_INTERACTION_H
/*
* PSCF - Polymer Self-Consistent Field Theory
*
* Copyright 2016 - 2022, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include <pscf/inter/Interaction.h> // base class
#include <util/containers/Array.h> // argument (template)
#include <util/containers/Matrix.h> // argument (template)
#include <util/global.h>
namespace Pscf {
using namespace Util;
/**
* Modified interaction to compute residual defn. of Arora et al.
*
* This class computes and provides access to copies of chi and as
* well as several other auxiliary quantities that are needed to
* compute the SCFT residual for multi-component systems as defined
* by Arora, Morse, Bates and Dorfman (AMBD) (JCP 2017) for use
* in Anderson-mixing iteration (see reference below). The class
* is designed to be used as a augmented local copy of the
* interaction class within iterator classes that use this residual
* definition. When used in this way, it should be updated just
* before entering the iteration loop.
*
* Reference:
* A. Arora, D.C. Morse, F.S. Bates and K.D Dorfman,
* J. Chem. Phys vol. 146, 244902 (2017).
*
* \ingroup Pscf_Iterator_Module
*/
class AmbdInteraction
{
public:
/**
* Constructor.
*/
AmbdInteraction();
/**
* Destructor.
*/
virtual ~AmbdInteraction();
/**
* Set number of monomers and allocate required memory.
*
* \param nMonomer number of different monomer types
*/
void setNMonomer(int nMonomer);
/**
* Update all computed quantities.
*
* \param interaction Interaction object with current chi matrix
*/
void update(Interaction const & interaction);
/**
* Return one element of the chi matrix.
*
* \param i row index
* \param j column index
*/
double chi(int i, int j) const;
/**
* Return one element of the inverse chi matrix.
*
* \param i row index
* \param j column index
*/
double chiInverse(int i, int j) const;
/**
* Return one element of the potent matrix P.
*
* This matrix is defined by AMBD as:
*
* P = I - e e^{T} chi^{-1} /S
*
* where I is the Nmonomer x Nmonomer identity matrix, the column
* vector e is a vector for which e_i = 1 for all i, and S is
* the sum of the N^{2} elements of the matrix chi^{-1}, also
* given by S = e^{T} chi^{-1} e.
*
* \param i row index
* \param j column index
*/
double p(int i, int j) const;
/**
* Return sum of elements of the inverse chi matrix.
*/
double sumChiInverse() const;
/**
* Get number of monomer types.
*/
int nMonomer() const;
private:
// Symmetric matrix of interaction parameters (local copy).
DMatrix<double> chi_;
// Inverse of matrix chi_.
DMatrix<double> chiInverse_;
// Idempotent matrix P used in residual definition.
DMatrix<double> p_;
// Sum of elements of matrix chiInverse_
double sumChiInverse_;
/// Number of monomers
int nMonomer_;
/// Has private memory been allocated?
bool isAllocated_;
};
// Inline function
inline int AmbdInteraction::nMonomer() const
{ return nMonomer_; }
inline double AmbdInteraction::chi(int i, int j) const
{ return chi_(i, j); }
inline double AmbdInteraction::chiInverse(int i, int j) const
{ return chiInverse_(i, j); }
inline double AmbdInteraction::p(int i, int j) const
{ return p_(i, j); }
inline double AmbdInteraction::sumChiInverse() const
{ return sumChiInverse_; }
} // namespace Pscf
#endif
| 3,949
|
C++
|
.h
| 121
| 26.735537
| 70
| 0.634281
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,072
|
PropagatorTmpl.h
|
dmorse_pscfpp/src/pscf/solvers/PropagatorTmpl.h
|
#ifndef PSCF_PROPAGATOR_TMPL_H
#define PSCF_PROPAGATOR_TMPL_H
/*
* PSCF - Polymer Self-Consistent Field Theory
*
* Copyright 2016 - 2022, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include <util/containers/GArray.h>
namespace Pscf
{
using namespace Util;
/**
* Template for propagator classes.
*
* The template argument TP should be a concrete propagator class that
* is derived from the template PropagatorTmpl<TP>. By convention, each
* implementation of SCFT is defined in a different sub-namespace of
* namespace Pscf. For each such implementation, there is a concrete
* propagator class, named Propagator by convention, that is a subclass
* of the template instance PropagatorTmpl<Propagator>, using the syntax
* shown below:
* \code
*
* class Propagator : public PropagatorTmpl<Propagator>
* {
* ...
* };
*
* \endcode
* This usage is an example of the so-called "curiously recurring
* template pattern" (CRTP). It is used here to allow the template
* PropagatorTmpl<Propagator> to have a member variables that store
* pointers to other instances of derived class Propagator (or TP).
*
* The Propagator class is used in templates BlockTmpl, PolymerTmpl
* and SystemTmpl. The usage in those templates require that it define
* the following public typedefs and member functions:
* \code
*
* class Propagator : public PropagatorTmpl<Propagator>
* {
* public:
*
* // Chemical potential field type.
* typedef DArray<double> WField;
*
* // Monomer concentration field type.
* typedef DArray<double> CField;
*
* // Solve the modified diffusion equation for this direction.
* void solve();
*
* // Compute and return the molecular partition function Q.
* double computeQ();
*
* };
*
* \endcode
* The typedefs WField and CField define the types of the objects used
* to represent a chemical potential field for a particular monomer type
* and a monomer concentration field. In the above example, both of these
* typenames are defined to be synonyms for DArrray<double>, i.e., for
* dynamically allocated arrays of double precision floating point
* numbers. Other implementations may use more specialized types.
*
* \ingroup Pscf_Solver_Module
*/
template <class TP>
class PropagatorTmpl
{
public:
/**
* Constructor.
*/
PropagatorTmpl();
/// \name Mutators
///@{
/**
* Associate this propagator with a direction index.
*
* \param directionId direction = 0 or 1.
*/
void setDirectionId(int directionId);
/**
* Set the partner of this propagator.
*
* The partner of a propagator is the propagator for the same block
* that propagates in the opposite direction.
*
* \param partner reference to partner propagator
*/
void setPartner(const TP& partner);
/**
* Add a propagator to the list of sources for this one.
*
* A source is a propagator that terminates at the root vertex
* of this one and is needed to compute the initial condition
* for this one, and that thus must be computed before this.
*
* \param source reference to source propagator
*/
void addSource(const TP& source);
/**
* Set the isSolved flag to true or false.
*/
void setIsSolved(bool isSolved);
///@}
/// \name Accessors
///@{
/**
* Get a source propagator.
*
* \param id index of source propagator, < nSource
*/
const TP& source(int id) const;
/**
* Get partner propagator.
*/
const TP& partner() const;
/**
* Get direction index for this propagator.
*/
int directionId() const;
/**
* Number of source / prerequisite propagators.
*/
int nSource() const;
/**
* Does this have a partner propagator?
*/
bool hasPartner() const;
/**
* Has the modified diffusion equation been solved?
*/
bool isSolved() const;
/**
* Are all source propagators are solved?
*/
bool isReady() const;
///@}
private:
/// Direction of propagation (0 or 1).
int directionId_;
/// Pointer to partner - same block,opposite direction.
TP const * partnerPtr_;
/// Pointers to propagators that feed source vertex.
GArray<TP const *> sourcePtrs_;
/// Set true after solving modified diffusion equation.
bool isSolved_;
};
// Inline member functions
/*
* Get the direction index.
*/
template <class TP>
inline int PropagatorTmpl<TP>::directionId() const
{ return directionId_; }
/*
* Get the number of source propagators.
*/
template <class TP>
inline int PropagatorTmpl<TP>::nSource() const
{ return sourcePtrs_.size(); }
/*
* Get a source propagator.
*/
template <class TP>
inline const TP&
PropagatorTmpl<TP>::source(int id) const
{ return *(sourcePtrs_[id]); }
/**
* Does this have a partner propagator?
*/
template <class TP>
inline
bool PropagatorTmpl<TP>::hasPartner() const
{ return partnerPtr_; }
/*
* Is the computation of this propagator completed?
*/
template <class TP>
inline bool PropagatorTmpl<TP>::isSolved() const
{ return isSolved_; }
// Noninline member functions
/*
* Constructor.
*/
template <class TP>
PropagatorTmpl<TP>::PropagatorTmpl()
: directionId_(-1),
partnerPtr_(0),
sourcePtrs_(),
isSolved_(false)
{}
/*
* Set the directionId.
*/
template <class TP>
void PropagatorTmpl<TP>::setDirectionId(int directionId)
{ directionId_ = directionId; }
/*
* Set the partner propagator.
*/
template <class TP>
void PropagatorTmpl<TP>::setPartner(const TP& partner)
{ partnerPtr_ = &partner; }
/*
* Add a source propagator to the list.
*/
template <class TP>
void PropagatorTmpl<TP>::addSource(const TP& source)
{ sourcePtrs_.append(&source); }
/*
* Get partner propagator.
*/
template <class TP>
const TP& PropagatorTmpl<TP>::partner()
const
{
UTIL_CHECK(partnerPtr_);
return *partnerPtr_;
}
/*
* Mark this propagator as solved (true) or not (false).
*/
template <class TP>
void PropagatorTmpl<TP>::setIsSolved(bool isSolved)
{ isSolved_ = isSolved; }
/*
* Check if all source propagators are marked completed.
*/
template <class TP>
bool PropagatorTmpl<TP>::isReady() const
{
for (int i=0; i < sourcePtrs_.size(); ++i) {
if (!sourcePtrs_[i]->isSolved()) {
return false;
}
}
return true;
}
}
#endif
| 7,045
|
C++
|
.h
| 244
| 23.598361
| 75
| 0.639609
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,073
|
BlockTmpl.h
|
dmorse_pscfpp/src/pscf/solvers/BlockTmpl.h
|
#ifndef PSCF_BLOCK_TMPL_H
#define PSCF_BLOCK_TMPL_H
/*
* PSCF - Polymer Self-Consistent Field Theory
*
* Copyright 2016 - 2022, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include <pscf/chem/BlockDescriptor.h> // base class
#include <util/containers/Pair.h> // member template
#include <cmath>
namespace Pscf
{
using namespace Util;
/**
* Class template for a block in a block copolymer.
*
* Class TP is a concrete propagator class. A BlockTmpl<TP> object
* has:
*
* - two TP propagator objects, one per direction
* - a single monomer concentration field
* - a single kuhn length
*
* Each implementation of self-consistent field theory (SCFT) is defined
* in a different sub-namespace of Pscf. Each such implementation defines
* a concrete propagator class and a concrete block class, which ar
* named Propagator and Block by convention.The Block class in each
* implementation is derived from BlockTmpl<Propagator>, using the
* following syntax:
* \code
*
* class Block : public BlockTmpl<Propagator>
* {
* ....
* }
*
* \endcode
* The algorithms for taking one step of integration of the modified
* diffusion equation and for computing the monomer concentration field
* arising from monomers in one block must be implemented in the Block
* class. These algorithms must be implemented in member functions of
* the concrete Block class with the following interfaces:
* \code
*
*
* // ---------------------------------------------------------------
* // Take one step of integration of the modified diffusion equation.
* // ---------------------------------------------------------------
* void step(Propagator::QField const & in, Propagator::QField& out);
*
* // ---------------------------------------------------------------
* // Compute monomer concentration field for this block.
* //
* // \param prefactor numerical prefactor of phi/(Q*length)
* // ---------------------------------------------------------------
* void computeConcentration(double prefactor);
*
* \endcode
* These core algorithms are implemented in the Block class, rather than
* the Propagator class, because the data required to implement these
* algorithms generally depends on the monomer type and contour length
* step size ds of a particular block, and can thus be shared by the two
* propagators associated with a particular block. The data required
* to implement these algorithms cannot, however, be shared among
* propagators in different blocks of the same monomer type because the
* requirement that the length of each block be divided into an integer
* number of contour length steps implies that different blocks of
* arbitrary user-specified length must generally be assumed to have
* slightly different values for the step size ds.
*
* The step() function is called in the implementation of the
* PropagatorTmpl::solve() member function, within a loop over steps.
* The computeConcentration() function is called in the implementation
* of the PolymerTmpl::solve() member function, within a loop over all
* blocks of the molecule that is called after solution of the modified
* diffusion equation for all propagators.
*
* \ingroup Pscf_Solver_Module
*/
template <class TP>
class BlockTmpl : public BlockDescriptor
{
public:
// Modified diffusion equation propagator for one block.
typedef TP Propagator;
// Monomer concentration field.
typedef typename TP::CField CField;
// Chemical potential field.
typedef typename TP::WField WField;
/**
* Constructor.
*/
BlockTmpl();
/**
* Destructor.
*/
virtual ~BlockTmpl();
/**
* Set monomer statistical segment length.
*
* \param kuhn monomer statistical segment length
*/
virtual void setKuhn(double kuhn);
/**
* Get a Propagator for a specified direction.
*
* For a block with v0 = vertexId(0) and v1 = vertexId(1),
* propagator(0) propagates from vertex v0 to v1, while
* propagator(1) propagates from vertex v1 to v0.
*
* \param directionId integer index for direction (0 or 1)
*/
TP& propagator(int directionId);
/**
* Get a const Propagator for a specified direction.
*
* See above for number conventions.
*
* \param directionId integer index for direction (0 or 1)
*/
TP const & propagator(int directionId) const;
/**
* Get the associated monomer concentration field.
*/
typename TP::CField& cField();
/**
* Get the associated const monomer concentration field.
*/
typename TP::CField const & cField() const;
/**
* Get monomer statistical segment length.
*/
double kuhn() const;
private:
/// Pair of Propagator objects (one for each direction).
Pair<Propagator> propagators_;
/// Monomer concentration field.
CField cField_;
/// Monomer statistical segment length.
double kuhn_;
};
// Inline member functions
/*
* Get a Propagator indexed by direction.
*/
template <class TP>
inline
TP& BlockTmpl<TP>::propagator(int directionId)
{ return propagators_[directionId]; }
/*
* Get a const Propagator indexed by direction.
*/
template <class TP>
inline
TP const & BlockTmpl<TP>::propagator(int directionId) const
{ return propagators_[directionId]; }
/*
* Get the monomer concentration field.
*/
template <class TP>
inline
typename TP::CField& BlockTmpl<TP>::cField()
{ return cField_; }
/*
* Get the const monomer concentration field.
*/
template <class TP>
inline
typename TP::CField const & BlockTmpl<TP>::cField() const
{ return cField_; }
/*
* Get the monomer statistical segment length.
*/
template <class TP>
inline double BlockTmpl<TP>::kuhn() const
{ return kuhn_; }
// Non-inline functions
/*
* Constructor.
*/
template <class TP>
BlockTmpl<TP>::BlockTmpl()
: propagators_(),
cField_(),
kuhn_(0.0)
{
propagator(0).setDirectionId(0);
propagator(1).setDirectionId(1);
propagator(0).setPartner(propagator(1));
propagator(1).setPartner(propagator(0));
}
/*
* Destructor.
*/
template <class TP>
BlockTmpl<TP>::~BlockTmpl()
{}
/*
* Set the monomer statistical segment length.
*/
template <class TP>
void BlockTmpl<TP>::setKuhn(double kuhn)
{ kuhn_ = kuhn; }
}
#endif
| 6,855
|
C++
|
.h
| 206
| 28.228155
| 75
| 0.646622
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,074
|
PolymerTmpl.h
|
dmorse_pscfpp/src/pscf/solvers/PolymerTmpl.h
|
#ifndef PSCF_POLYMER_TMPL_H
#define PSCF_POLYMER_TMPL_H
/*
* PSCF - Polymer Self-Consistent Field Theory
*
* Copyright 2016 - 2022, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include <pscf/chem/Species.h> // base class
#include <util/param/ParamComposite.h> // base class
#include <pscf/chem/Monomer.h> // member template argument
#include <pscf/chem/Vertex.h> // member template argument
#include <pscf/chem/PolymerType.h> // member
#include <util/containers/Pair.h> // member template
#include <util/containers/DArray.h> // member template
#include <util/containers/DMatrix.h>
#include <cmath>
namespace Pscf
{
class Block;
using namespace Util;
/**
* Descriptor and MDE solver for an acyclic block polymer.
*
* A PolymerTmpl<Block> object has arrays of Block and Vertex
* objects. Each Block has two propagator MDE solver objects.
* The solve() member function solves the modified diffusion
* equation (MDE) for the entire molecule and computes monomer
* concentration fields for all blocks.
*
* \ingroup Pscf_Solver_Module
*/
template <class Block>
class PolymerTmpl : public Species, public ParamComposite
{
public:
// Modified diffusion equation solver for one block.
typedef typename Block::Propagator Propagator;
// Monomer concentration field.
typedef typename Propagator::CField CField;
// Chemical potential field.
typedef typename Propagator::WField WField;
/**
* Constructor.
*/
PolymerTmpl();
/**
* Destructor.
*/
~PolymerTmpl();
/**
* Read and initialize.
*
* \param in input parameter stream
*/
virtual void readParameters(std::istream& in);
/**
* Solve modified diffusion equation.
*
* Upon return, propagators for all blocks, molecular partition
* function q, phi and mu, and the block concentration fields for
* all blocks are set.
*
* This function should be called within a member function named
* "compute" of each concrete subclass. This compute function must
* take an array of chemical potential fields (w-fields) as an
* argument. Before calling the solve() function declared here,
* the compute() function of each such subclass must store
* information required to solve the MDE within each block within
* a set of implementation dependent private members of the class
* class that represents a block of a block polymer. The
* implementation of PolymerTmpl::solve() the calls the solve()
* function for all propagators in the molecule in a predeternined
* order.
*
* The optional parameter phiTot is only relevant to problems
* such as thin films in which the material is excluded from part
* of the unit cell by an inhogeneous constraint on the sum of
* monomer concentration (i.e., a "mask").
*
* \param phiTot fraction of volume occupied by material
*/
virtual void solve(double phiTot = 1.0);
/// \name Accessors (objects, by reference)
///@{
/**
* Get a specified Block.
*
* \param id block index, 0 <= id < nBlock
*/
Block& block(int id);
/**
* Get a specified Block by const reference.
*
* \param id block index, 0 <= id < nBlock
*/
Block const& block(int id) const ;
/**
* Get a specified Vertex by const reference.
*
* Both chain ends and junctions are vertices.
*
* \param id vertex index, 0 <= id < nVertex
*/
const Vertex& vertex(int id) const;
/**
* Get propagator for a specific block and direction.
*
* \param blockId integer index of associated block
* \param directionId integer index for direction (0 or 1)
*/
Propagator& propagator(int blockId, int directionId);
/**
* Get a const propagator for a specific block and direction.
*
* \param blockId integer index of associated block
* \param directionId integer index for direction (0 or 1)
*/
Propagator const & propagator(int blockId, int directionId) const;
/**
* Get propagator indexed in order of computation.
*
* The propagator index must satisfy 0 <= id < 2*nBlock.
*
* \param id propagator index, in order of computation plan
*/
Propagator& propagator(int id);
/**
* Get propagator identifier, indexed by order of computation.
*
* The return value is a pair of integers. The first integer
* is a block index between 0 and nBlock - 1, and the second
* is a propagator direction id, which must be 0 or 1.
*
* \param id propagator index, in order of computation plan
*/
const Pair<int>& propagatorId(int id) const;
///@}
/// \name Accessors (by value)
///@{
/**
* Number of blocks.
*/
int nBlock() const;
/**
* Number of vertices (junctions and chain ends).
*
* A theorem of graph theory tells us that, for any linear or
* acyclic branched polymer, nVertex = nBlock + 1.
*/
int nVertex() const;
/**
* Number of propagators (nBlock*2).
*/
int nPropagator() const; //
/**
* Sum of the lengths of all blocks in the polymer.
*/
double length() const;
///@}
protected:
/**
* Make a plan for order in which propagators should be computed.
*
* The algorithm creates a plan for computing propagators in an
* that guarantees that the inital conditions required for each
* propagator are known before it is processed. The algorithm is
* works for any acyclic branched block copolymer. This function
* is called in the default implementation of readParameters,
* and must be called the readParameters method of any subclass.
*/
virtual void makePlan();
private:
/// Array of Block objects in this polymer.
DArray<Block> blocks_;
/// Array of Vertex objects in this polymer.
DArray<Vertex> vertices_;
/// Propagator ids, indexed in order of computation.
DArray< Pair<int> > propagatorIds_;
/// Number of blocks in this polymer
int nBlock_;
/// Number of vertices (ends or junctions) in this polymer
int nVertex_;
/// Number of propagators (two per block).
int nPropagator_;
/// Polymer type (Branched or Linear)
PolymerType::Enum type_;
};
/*
* Number of vertices (ends and/or junctions)
*/
template <class Block>
inline int PolymerTmpl<Block>::nVertex() const
{ return nVertex_; }
/*
* Number of blocks.
*/
template <class Block>
inline int PolymerTmpl<Block>::nBlock() const
{ return nBlock_; }
/*
* Number of propagators.
*/
template <class Block>
inline int PolymerTmpl<Block>::nPropagator() const
{ return nPropagator_; }
/*
* Total length of all blocks = volume / reference volume
*/
template <class Block>
inline double PolymerTmpl<Block>::length() const
{
double value = 0.0;
for (int blockId = 0; blockId < nBlock_; ++blockId) {
value += blocks_[blockId].length();
}
return value;
}
/*
* Get a specified Vertex.
*/
template <class Block>
inline
const Vertex& PolymerTmpl<Block>::vertex(int id) const
{ return vertices_[id]; }
/*
* Get a specified Block.
*/
template <class Block>
inline Block& PolymerTmpl<Block>::block(int id)
{ return blocks_[id]; }
/*
* Get a specified Block by const reference.
*/
template <class Block>
inline Block const & PolymerTmpl<Block>::block(int id) const
{ return blocks_[id]; }
/*
* Get a propagator id, indexed in order of computation.
*/
template <class Block>
inline
Pair<int> const & PolymerTmpl<Block>::propagatorId(int id) const
{
UTIL_CHECK(id >= 0);
UTIL_CHECK(id < nPropagator_);
return propagatorIds_[id];
}
/*
* Get a propagator indexed by block and direction.
*/
template <class Block>
inline
typename Block::Propagator&
PolymerTmpl<Block>::propagator(int blockId, int directionId)
{ return block(blockId).propagator(directionId); }
/*
* Get a const propagator indexed by block and direction.
*/
template <class Block>
inline
typename Block::Propagator const &
PolymerTmpl<Block>::propagator(int blockId, int directionId) const
{ return block(blockId).propagator(directionId); }
/*
* Get a propagator indexed in order of computation.
*/
template <class Block>
inline
typename Block::Propagator& PolymerTmpl<Block>::propagator(int id)
{
Pair<int> propId = propagatorId(id);
return propagator(propId[0], propId[1]);
}
// Non-inline functions
/*
* Constructor.
*/
template <class Block>
PolymerTmpl<Block>::PolymerTmpl()
: Species(),
blocks_(),
vertices_(),
propagatorIds_(),
nBlock_(0),
nVertex_(0),
nPropagator_(0)
{ setClassName("PolymerTmpl"); }
/*
* Destructor.
*/
template <class Block>
PolymerTmpl<Block>::~PolymerTmpl()
{}
template <class Block>
void PolymerTmpl<Block>::readParameters(std::istream& in)
{
// Read polymer type (linear by default)
type_ = PolymerType::Linear;
readOptional<PolymerType::Enum>(in, "type", type_);
read<int>(in, "nBlock", nBlock_);
// Note: For any acyclic graph, nVertex = nBlock + 1
nVertex_ = nBlock_ + 1;
// Allocate all arrays (blocks_, vertices_ and propagatorIds_)
blocks_.allocate(nBlock_);
vertices_.allocate(nVertex_);
propagatorIds_.allocate(2*nBlock_);
// Set block id and polymerType for all blocks
for (int blockId = 0; blockId < nBlock_; ++blockId) {
blocks_[blockId].setId(blockId);
blocks_[blockId].setPolymerType(type_);
}
// Set all vertex ids
for (int vertexId = 0; vertexId < nVertex_; ++vertexId) {
vertices_[vertexId].setId(vertexId);
}
// If polymer is linear polymer, set all block vertex Ids:
// In a linear chain, block i connects vertex i and vertex i+1.
if (type_ == PolymerType::Linear) {
for (int blockId = 0; blockId < nBlock_; ++blockId) {
blocks_[blockId].setVertexIds(blockId, blockId + 1);
}
}
// Read all other required block data
readDArray<Block>(in, "blocks", blocks_, nBlock_);
/*
* The parameter file format for each block in the array blocks_
* is different for branched and linear polymer. These formats
* are defined in >> and << stream io operators for a Pscf::Block.
* The choice of format is controlled by the Block::polymerType.
*
* For a branched polymer, the text format for each block is:
*
* monomerId length vertexId(0) vertexId(1)
*
* where monomerId is the index of the block monomer type, length
* is the block length, and vertexId(0) and vertexId(1) are the
* indices of the two vertices to which the block is attached.
*
* For a linear polymer, blocks must be entered sequentially, in
* their order along the chain, and block vertex id values are
* set automatically. In this case, the format for one block is:
*
* monomerId length
*
* with no need for explicit vertex ids.
*/
// Add blocks to attached vertices
int vertexId0, vertexId1;
Block* blockPtr;
for (int blockId = 0; blockId < nBlock_; ++blockId) {
blockPtr = &(blocks_[blockId]);
vertexId0 = blockPtr->vertexId(0);
vertexId1 = blockPtr->vertexId(1);
vertices_[vertexId0].addBlock(*blockPtr);
vertices_[vertexId1].addBlock(*blockPtr);
}
// Polymer topology is now fully specified.
// Construct a plan for the order in which block propagators
// should be computed when solving the MDE.
makePlan();
// Read phi or mu (but not both)
bool hasPhi = readOptional(in, "phi", phi_).isActive();
if (hasPhi) {
ensemble_ = Species::Closed;
} else {
ensemble_ = Species::Open;
read(in, "mu", mu_);
}
// Set sources for all propagators
Vertex const * vertexPtr = 0;
Propagator const * sourcePtr = 0;
Propagator * propagatorPtr = 0;
Pair<int> propagatorId;
int blockId, directionId, vertexId, i;
for (blockId = 0; blockId < nBlock(); ++blockId) {
// Add sources
for (directionId = 0; directionId < 2; ++directionId) {
vertexId = block(blockId).vertexId(directionId);
vertexPtr = &vertex(vertexId);
propagatorPtr = &block(blockId).propagator(directionId);
for (i = 0; i < vertexPtr->size(); ++i) {
propagatorId = vertexPtr->inPropagatorId(i);
if (propagatorId[0] == blockId) {
UTIL_CHECK(propagatorId[1] != directionId);
} else {
sourcePtr =
&block(propagatorId[0]).propagator(propagatorId[1]);
propagatorPtr->addSource(*sourcePtr);
}
}
}
}
}
/*
* Make a plan for the order of computation of block propagators.
*/
template <class Block>
void PolymerTmpl<Block>::makePlan()
{
if (nPropagator_ != 0) {
UTIL_THROW("nPropagator !=0 on entry");
}
// Allocate and initialize isFinished matrix
DMatrix<bool> isFinished;
isFinished.allocate(nBlock_, 2);
for (int iBlock = 0; iBlock < nBlock_; ++iBlock) {
for (int iDirection = 0; iDirection < 2; ++iDirection) {
isFinished(iBlock, iDirection) = false;
}
}
Pair<int> propagatorId;
Vertex* inVertexPtr = 0;
int inVertexId = -1;
bool isReady;
while (nPropagator_ < nBlock_*2) {
for (int iBlock = 0; iBlock < nBlock_; ++iBlock) {
for (int iDirection = 0; iDirection < 2; ++iDirection) {
if (isFinished(iBlock, iDirection) == false) {
inVertexId = blocks_[iBlock].vertexId(iDirection);
inVertexPtr = &vertices_[inVertexId];
isReady = true;
for (int j = 0; j < inVertexPtr->size(); ++j) {
propagatorId = inVertexPtr->inPropagatorId(j);
if (propagatorId[0] != iBlock) {
if (!isFinished(propagatorId[0], propagatorId[1])) {
isReady = false;
break;
}
}
}
if (isReady) {
propagatorIds_[nPropagator_][0] = iBlock;
propagatorIds_[nPropagator_][1] = iDirection;
isFinished(iBlock, iDirection) = true;
++nPropagator_;
}
}
}
}
}
}
/*
* Compute a solution to the MDE and block concentrations.
*/
template <class Block>
void PolymerTmpl<Block>::solve(double phiTot)
{
// Clear all propagators
for (int j = 0; j < nPropagator(); ++j) {
propagator(j).setIsSolved(false);
}
// Solve modified diffusion equation for all propagators in
// the order specified by function makePlan.
for (int j = 0; j < nPropagator(); ++j) {
UTIL_CHECK(propagator(j).isReady());
propagator(j).solve();
}
// Compute molecular partition function q_
q_ = block(0).propagator(0).computeQ();
// The Propagator::computeQ function returns a spatial average.
// Correct for partial occupation of the unit cell.k
q_ = q_/phiTot;
// Compute mu_ or phi_, depending on ensemble
if (ensemble() == Species::Closed) {
mu_ = log(phi_/q_);
} else
if (ensemble() == Species::Open) {
phi_ = exp(mu_)*q_;
}
// Compute block concentration fields
double prefactor = phi_ / ( q_ * length() );
for (int i = 0; i < nBlock(); ++i) {
block(i).computeConcentration(prefactor);
}
}
}
#endif
| 16,692
|
C++
|
.h
| 478
| 27.621339
| 76
| 0.611763
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,075
|
MixtureTmpl.h
|
dmorse_pscfpp/src/pscf/solvers/MixtureTmpl.h
|
#ifndef PSCF_MIXTURE_TMPL_H
#define PSCF_MIXTURE_TMPL_H
/*
* PSCF - Polymer Self-Consistent Field Theory
*
* Copyright 2016 - 2022, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include <pscf/chem/Monomer.h>
#include <util/param/ParamComposite.h>
#include <util/containers/DArray.h>
namespace Pscf
{
using namespace Util;
/**
* A mixture of polymer and solvent species.
*
* \ingroup Pscf_Solver_Module
*/
template <class TP, class TS>
class MixtureTmpl : public ParamComposite
{
public:
// Public typedefs
/**
* Polymer species solver typename.
*/
typedef TP Polymer;
/**
* Solvent species solver typename.
*/
typedef TS Solvent;
// Public member functions
/**
* Constructor.
*/
MixtureTmpl();
/**
* Destructor.
*/
~MixtureTmpl();
/**
* Read parameters from file and initialize.
*
* \param in input parameter file
*/
virtual void readParameters(std::istream& in);
/// \name Accessors (by non-const reference)
///@{
/**
* Get a Monomer type descriptor (const reference).
*
* \param id integer monomer type index (0 <= id < nMonomer)
*/
Monomer const & monomer(int id) const;
/**
* Get a polymer object.
*
* \param id integer polymer species index (0 <= id < nPolymer)
*/
Polymer& polymer(int id);
/**
* Get a polymer object by const reference.
*
* \param id integer polymer species index (0 <= id < nPolymer)
*/
Polymer const & polymer(int id) const;
/**
* Set a solvent solver object.
*
* \param id integer solvent species index (0 <= id < nSolvent)
*/
Solvent& solvent(int id);
/**
* Set a solvent solver object.
*
* \param id integer solvent species index (0 <= id < nSolvent)
*/
Solvent const & solvent(int id) const;
///@}
/// \name Accessors (by value)
///@{
/**
* Get number of monomer types.
*/
int nMonomer() const;
/**
* Get number of polymer species.
*/
int nPolymer() const;
/**
* Get number of total blocks in the mixture across all polymers.
*/
int nBlock() const;
/**
* Get number of solvent (point particle) species.
*/
int nSolvent() const;
/**
* Get monomer reference volume (set to 1.0 by default).
*/
double vMonomer() const;
///@}
protected:
/**
* Get a Monomer type descriptor (non-const reference).
*
* \param id integer monomer type index (0 <= id < nMonomer)
*/
Monomer& monomer(int id);
private:
/**
* Array of monomer type descriptors.
*/
DArray<Monomer> monomers_;
/**
* Array of polymer species solver objects.
*
* Array capacity = nPolymer.
*/
DArray<Polymer> polymers_;
/**
* Array of solvent species objects.
*
* Array capacity = nSolvent.
*/
DArray<Solvent> solvents_;
/**
* Number of monomer types.
*/
int nMonomer_;
/**
* Number of polymer species.
*/
int nPolymer_;
/**
* Number of solvent species.
*/
int nSolvent_;
/**
* Number of blocks total, across all polymers.
*/
int nBlock_;
/**
* Monomer reference volume (set to 1.0 by default).
*/
double vMonomer_;
};
// Inline member functions
template <class TP, class TS>
inline int MixtureTmpl<TP,TS>::nMonomer() const
{ return nMonomer_; }
template <class TP, class TS>
inline int MixtureTmpl<TP,TS>::nPolymer() const
{ return nPolymer_; }
template <class TP, class TS>
inline int MixtureTmpl<TP,TS>::nSolvent() const
{ return nSolvent_; }
template <class TP, class TS>
inline int MixtureTmpl<TP,TS>::nBlock() const
{ return nBlock_; }
template <class TP, class TS>
inline Monomer const & MixtureTmpl<TP,TS>::monomer(int id) const
{
UTIL_CHECK(id < nMonomer_);
return monomers_[id];
}
template <class TP, class TS>
inline Monomer& MixtureTmpl<TP,TS>::monomer(int id)
{
UTIL_CHECK(id < nMonomer_);
return monomers_[id];
}
template <class TP, class TS>
inline TP& MixtureTmpl<TP,TS>::polymer(int id)
{
UTIL_CHECK(id < nPolymer_);
return polymers_[id];
}
template <class TP, class TS>
inline TP const & MixtureTmpl<TP,TS>::polymer(int id) const
{
UTIL_CHECK(id < nPolymer_);
return polymers_[id];
}
template <class TP, class TS>
inline TS& MixtureTmpl<TP,TS>::solvent(int id)
{
UTIL_CHECK(id < nSolvent_);
return solvents_[id];
}
template <class TP, class TS>
inline TS const & MixtureTmpl<TP,TS>::solvent(int id) const
{
UTIL_CHECK(id < nSolvent_);
return solvents_[id];
}
template <class TP, class TS>
inline double MixtureTmpl<TP,TS>::vMonomer() const
{ return vMonomer_; }
// Non-inline member functions
/*
* Constructor.
*/
template <class TP, class TS>
MixtureTmpl<TP,TS>::MixtureTmpl()
: ParamComposite(),
monomers_(),
polymers_(),
solvents_(),
nMonomer_(0),
nPolymer_(0),
nSolvent_(0),
nBlock_(0),
vMonomer_(1.0)
{}
/*
* Destructor.
*/
template <class TP, class TS>
MixtureTmpl<TP,TS>::~MixtureTmpl()
{}
/*
* Read all parameters and initialize.
*/
template <class TP, class TS>
void MixtureTmpl<TP,TS>::readParameters(std::istream& in)
{
// Read nMonomer and monomers array
read<int>(in, "nMonomer", nMonomer_);
monomers_.allocate(nMonomer_);
for (int i = 0; i < nMonomer_; ++i) {
monomers_[i].setId(i);
}
readDArray< Monomer >(in, "monomers", monomers_, nMonomer_);
/*
* The input format for a single monomer is defined in the istream
* extraction operation (operator >>) for a Pscf::Monomer, in file
* pscf/chem/Monomer.cpp. The text representation contains only the
* value for the monomer statistical segment Monomer::kuhn.
*/
// Read nPolymer
read<int>(in, "nPolymer", nPolymer_);
UTIL_CHECK(nPolymer_ > 0);
// Optionally read nSolvent, with nSolvent=0 by default
nSolvent_ = 0;
readOptional<int>(in, "nSolvent", nSolvent_);
// Read polymers and compute nBlock
nBlock_ = 0;
if (nPolymer_ > 0) {
polymers_.allocate(nPolymer_);
for (int i = 0; i < nPolymer_; ++i) {
readParamComposite(in, polymer(i));
nBlock_ = nBlock_ + polymer(i).nBlock();
}
// Set statistical segment lengths for all blocks
double kuhn;
int monomerId;
for (int i = 0; i < nPolymer_; ++i) {
for (int j = 0; j < polymer(i).nBlock(); ++j) {
monomerId = polymer(i).block(j).monomerId();
kuhn = monomer(monomerId).kuhn();
polymer(i).block(j).setKuhn(kuhn);
}
}
}
// Read solvents
if (nSolvent_ > 0) {
solvents_.allocate(nSolvent_);
for (int i = 0; i < nSolvent_; ++i) {
readParamComposite(in, solvent(i));
}
}
// Optionally read monomer reference value
vMonomer_ = 1.0; // Default value
readOptional(in, "vMonomer", vMonomer_);
}
}
#endif
| 7,716
|
C++
|
.h
| 279
| 21.114695
| 72
| 0.58132
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,076
|
MeshIterator.h
|
dmorse_pscfpp/src/pscf/mesh/MeshIterator.h
|
#ifndef PSCF_MESH_ITERATOR_H
#define PSCF_MESH_ITERATOR_H
/*
* PSCF - Polymer Self-Consistent Field Theory
*
* Copyright 2016 - 2022, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include <pscf/math/IntVec.h> // member
namespace Pscf
{
using namespace Util;
/**
* Iterator over points in a Mesh<D>.
*
* A mesh iterator iterates over the points of a mesh, keeping track
* of both the IntVec<D> position and integer rank of the current
* point as it goes.
*
* \ingroup Pscf_Mesh_Module
*/
template <int D>
class MeshIterator
{
public:
/**
* Default constructor
*/
MeshIterator();
/**
* Constructor
*
* \param dimensions IntVec<D> of grid dimensions
*/
MeshIterator(const IntVec<D>& dimensions);
// Compiler copy constructor.
// Compiler default destructor.
/**
* Set the grid dimensions in all directions.
*
* \param dimensions IntVec<D> of grid dimensions.
*/
void setDimensions(const IntVec<D>& dimensions);
/**
* Set iterator to the first point in the mesh.
*/
void begin();
/**
* Increment iterator to next mesh point.
*/
void operator ++();
/**
* Is this the end (i.e., one past the last point)?
*/
bool atEnd() const;
/**
* Get current position in the grid, as integer vector.
*/
IntVec<D> position() const;
/**
* Get component i of the current position vector.
*
* \param i index of Cartesian direction 0 <=i < D.
*/
int position(int i) const;
/**
* Get the rank of current element.
*/
int rank() const;
private:
/// Dimensions of grid
IntVec<D> dimensions_;
/// Current position in grid.
IntVec<D> position_;
/// Integer rank of current position.
int rank_;
/// Total number of grid points
int size_;
/// Recursive function for multi-dimensional increment.
void increment(int i);
};
// Explicit specialization declarations
template<>
void MeshIterator<1>::operator ++();
template<>
void MeshIterator<2>::operator ++();
template<>
void MeshIterator<3>::operator ++();
// Inline member functions
// Return the entire IntVec<D>
template <int D>
inline IntVec<D> MeshIterator<D>::position() const
{ return position_; }
// Return one component of the position IntVec<D>
template <int D>
inline int MeshIterator<D>::position(int i) const
{
assert(i >=0);
assert(i < D);
return position_[i];
}
// Return the rank
template <int D>
inline int MeshIterator<D>::rank() const
{ return rank_; }
// Is this the end (i.e., one past the last point)?
template <int D>
inline bool MeshIterator<D>::atEnd() const
{ return (bool)(rank_ == size_); }
// Inline explicit specializations
template <>
inline void MeshIterator<1>::operator ++ ()
{
position_[0]++;
if (position_[0] == dimensions_[0]) {
position_[0] = 0;
}
rank_++;
}
template <>
inline void MeshIterator<2>::operator ++ ()
{
position_[1]++;
if (position_[1] == dimensions_[1]) {
position_[1] = 0;
increment(0);
}
rank_++;
}
template <>
inline void MeshIterator<3>::operator ++ ()
{
position_[2]++;
if (position_[2] == dimensions_[2]) {
position_[2] = 0;
increment(1);
}
rank_++;
}
#ifndef PSCF_MESH_ITERATOR_TPP
// Suppress implicit instantiation
extern template class MeshIterator<1>;
extern template class MeshIterator<2>;
extern template class MeshIterator<3>;
#endif
}
#endif
| 3,891
|
C++
|
.h
| 147
| 20.816327
| 70
| 0.602429
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,077
|
Mesh.h
|
dmorse_pscfpp/src/pscf/mesh/Mesh.h
|
#ifndef PSCF_MESH_H
#define PSCF_MESH_H
/*
* PSCF - Polymer Self-Consistent Field Theory
*
* Copyright 2016 - 2022, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include <pscf/math/IntVec.h> // member
#include <iostream> // interface
#include <util/format/Int.h> // operator << implementation
namespace Pscf
{
using namespace Util;
// Forward declaration
template <int D> class Mesh;
/**
* Input stream extractor for reading a Mesh<D> object.
*
* \param in input stream
* \param mesh Mesh<D> object to be read
* \return modified input stream
*/
template <int D>
std::istream& operator >> (std::istream& in, Mesh<D>& mesh);
/**
* Output stream inserter for writing a Mesh<D> object.
*
* \param out output stream
* \param mesh Mesh<D> to be written
* \return modified output stream
*/
template <int D>
std::ostream& operator << (std::ostream& out, Mesh<D> const & mesh);
/**
* Description of a regular grid of points in a periodic domain.
*
* The coordinates of a point on a grid form an IntVec<D>, referred
* to here as a grid position. Each element of a grid position must
* lie in the range 0 <= position[i] < dimension(i), where i indexes
* a Cartesian axis, and dimension(i) is the dimension of the grid
* along axis i.
*
* Each grid position is also assigned a non-negative integer rank.
* Mesh position ranks are ordered sequentially like elements in
* a multi-dimensional C array, with the last coordinate being the
* most rapidly varying.
*
* \ingroup Pscf_Mesh_Module
*/
template <int D>
class Mesh
{
public:
/**
* Default constructor
*
* Grid dimensions and size are initialized to zero. All functions
* that set the dimensions and size after construction require that
* all dimensions are positive, yielding a positive size.
*/
Mesh();
/**
* Copy constructor.
*
* \param other Mesh<D> object being copied.
*/
Mesh(Mesh<D> const & other);
/**
* Constructor from grid dimensions.
*
* \param dimensions IntVec<D> of grid dimensions
*/
Mesh(IntVec<D> const & dimensions);
/**
* Assignment operator.
*
* \param other Mesh<D> object being copied.
*/
Mesh<D>& operator = (Mesh<D> const & other);
/**
* Set the grid dimensions for an existing mesh.
*
* \param dimensions IntVec<D> of grid dimensions.
*/
void setDimensions(IntVec<D> const & dimensions);
/**
* Get an IntVec<D> of the grid dimensions.
*/
IntVec<D> dimensions() const;
/**
* Get grid dimension along Cartesian direction i.
*
* \param i index of Cartesian direction 0 <=i < Util::Dimension
*/
int dimension(int i) const;
/**
* Get total number of grid points.
*
* Value size() == 0 will be obtained iff the mesh was default
* constructed and has not yet been given meaningful initial
* values.
*/
int size() const;
/**
* Get the position IntVec<D> of a grid point with a specified rank.
*
* \param rank integer rank of a grid point.
* \return IntVec<D> containing coordinates of specified point.
*/
IntVec<D> position(int rank) const;
/**
* Get the rank of a grid point with specified position.
*
* \param position integer position of a grid point
* \return integer rank of specified grid point
*/
int rank(IntVec<D> const & position) const;
/**
* Is this coordinate in range?
*
* \param coordinate coordinate value for direction i
* \param i index for Cartesian direction
* \return true iff 0 <= coordinate < dimension(i).
*/
bool isInMesh(int coordinate, int i) const;
/**
* Is this IntVec<D> grid position within the grid?
*
* Returns true iff 0 <= coordinate[i] < dimension(i) for all i.
*
* \param position grid point position
* \return true iff 0 <= coordinate[i] < dimension(i) for all i.
*/
bool isInMesh(IntVec<D> const & position) const;
/**
* Shift a periodic coordinate into range.
*
* Upon return, the coordinate will be shifted to lie within the
* range 0 <= coordinate < dimension(i) by subtracting an integer
* multiple of dimension(i), giving coordinate - shift*dimension(i).
* The return value is the required integer `shift'.
*
* \param coordinate coordinate in Cartesian direction i.
* \param i index of Cartesian direction, i >= 0.
* \return multiple of dimension(i) subtracted from input value.
*/
int shift(int& coordinate, int i) const;
/**
* Shift a periodic position into primary grid.
*
* Upon return, each element of the parameter position is shifted
* to lie within the range 0 <= position[i] < dimension(i) by
* adding or subtracting an integer multiple of dimension(i). The
* IntVec<D> of shift values is returned.
*
* \param position IntVec<D> position within a grid.
* \return IntVec<D> of integer shifts.
*/
IntVec<D> shift(IntVec<D>& position) const;
/**
* Serialize to/from an archive.
*
* \param ar archive
* \param version archive version id
*/
template <class Archive>
void serialize(Archive& ar, const unsigned int version);
private:
/// Dimensions of grid
IntVec<D> dimensions_;
/// Number of elements per increment in each direction
IntVec<D> offsets_;
/// Total number of grid points
int size_;
//friends:
friend std::istream& operator >> <>(std::istream&, Mesh<D> & );
friend std::ostream& operator << <>(std::ostream&, Mesh<D> const & );
};
// Inline member function implementations
template <int D>
inline IntVec<D> Mesh<D>::dimensions() const
{ return dimensions_; }
template <int D>
inline int Mesh<D>::dimension(int i) const
{
assert(i >=0);
assert(i < Dimension);
return dimensions_[i];
}
template <int D>
inline int Mesh<D>::size() const
{ return size_; }
/*
* Serialize Mesh to/from an archive.
*/
template <int D>
template <class Archive>
void Mesh<D>::serialize(Archive& ar, const unsigned int version)
{
for (int i=0; i < D; ++i) {
ar & dimensions_[0];
}
}
template <int D>
std::istream& operator >> (std::istream& in, Mesh<D>& mesh)
{
IntVec<D> dimensions;
in >> dimensions;
for (int i = 0; i < D; ++i) {
UTIL_CHECK(dimensions[i] > 0);
}
mesh.setDimensions(dimensions);
return in;
}
template <int D>
std::ostream& operator << (std::ostream& out, Mesh<D> const & mesh)
{
for (int i = 0; i < D; ++i) {
out << " " << Int(mesh.dimensions_[i], 6);
}
return out;
}
#ifndef PSCF_MESH_TPP
// Suppress implicit instantiation
extern template class Mesh<1>;
extern template class Mesh<2>;
extern template class Mesh<3>;
#endif
}
//#include "Mesh.tpp"
#endif
| 7,399
|
C++
|
.h
| 232
| 26.073276
| 75
| 0.621474
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,078
|
SweepTmpl.h
|
dmorse_pscfpp/src/pscf/sweep/SweepTmpl.h
|
#ifndef PSCF_SWEEP_TMPL_H
#define PSCF_SWEEP_TMPL_H
/*
* PSCF - Polymer Self-Consistent Field Theory
*
* Copyright 2016 - 2022, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include <util/param/ParamComposite.h> // base class
namespace Pscf {
using namespace Util;
/**
* Solve a sequence of problems along a path through parameter space.
*
* \ingroup Pscf_Sweep_Module
*/
template <typename State>
class SweepTmpl : public ParamComposite
{
public:
// Constructor is protected (see below).
/**
* Destructor.
*/
~SweepTmpl();
/**
* Read ns and baseFileName parameters.
*
* \param in input stream
*/
virtual void readParameters(std::istream& in);
/**
* Iterate to solution.
*/
virtual void sweep();
protected:
/// Number of steps.
int ns_;
/// Base name for output files
std::string baseFileName_;
/**
* Constructor (protected).
*
* The value of historyCapacity depends on the order of continuation,
* e.g., 2 for 1st order or linear continuation or 3 for 2nd order
* or quadratic contination. The value passed to this constructor is
* a default value that may overridden by a optional parameter in
* the parameter file format implemented in readParam.
*
* \param historyCapacity default maximum number of stored states
*/
SweepTmpl(int historyCapacity);
/**
* Get reference to a stored state, with i=0 being most recent.
*
* Call state(i) to return the ith from most recent previous state.
*
* \param i history index (i=0 is most recent)
*/
State& state(int i)
{
UTIL_CHECK(i < historySize_);
return *stateHistory_[i];
}
/**
* Get the value of s for a stored solution, with i = 0 most recent.
*
* This function returns the value of the contour variable s for a
* stored state. Call s(i) to get the value of s for the ith most
* recent state.
*
* \param i history index (i = 0 is most the recent converged state)
*/
double s(int i) const
{
UTIL_CHECK(i < historySize_);
return sHistory_[i];
}
/**
* Get a coefficient of a previous state in a continuation.
*
* An extrapolated trial value for each field or other variables
* that describes a state is constructed as a linear superposition
* of corresponding values in previous states. Coefficient c(i) is
* the coefficient of state state(i) in this linear superposition,
* where i = 0 denotes the most recent accepted solution and
* increasing index i corresponds to increasingly far in the past.
* Valid values of i are in the range 0 <= i < historySize().
*
* The function setCoefficients(double sNew) method computes and
* stores values coefficients c(0), ..., c(historySize-1) from
* values of sNew (the contour variable of the new state) and
* previous values of s. These coefficient values can then be
* retrieved by this function.
*
* \param i history index (i=0 is most recent)
*/
double c(int i) const
{
UTIL_CHECK(i >= 0);
UTIL_CHECK(i < historySize_);
return c_[i];
}
/**
* Get the current number of stored previous states.
*/
int historySize() const
{ return historySize_; }
/**
* Get the maximum number of stored previous states.
*
* The value of historyCapacity is a constant that is one greater
* than the maximum order of continuation (e.g., 3 for 2nd order
* continuation). The value is set by passing it as an argument
* to the constructor, and is constant after construction.
*/
int historyCapacity() const
{ return historyCapacity_; }
/**
* Get the number of converged solutions accepted thus far.
*
* This value is reset to zero by the initialize function, which
* must be called by the setup function, and is incremented by one
* by the accept function.
*/
int nAccept() const
{ return nAccept_; }
/**
* Initialize variables that track history of solutions.
*
* This *must* be called within implementation of the setup function.
*/
void initialize();
/**
* Check allocation of one state, allocate if necessary.
*
* This virtual function is called by SweepTmpl::initialize() during
* setup before a sweep to check allocation state and/or allocate
* memory for fields in all stored State objects.
*
* \param state an object that represents a state of the system
*/
virtual void checkAllocation(State & state) = 0;
/**
* Setup operation at the beginning of a sweep.
*
* The implementations of this function must call initialize().
*/
virtual void setup() = 0;
/**
* Set non-adjustable system parameters to new values.
*
* This function should set set values for variables that are treated
* as input parameters by the SCFT solver, such as block polymer
* block lengths, chi parameters, species volume fractions or
* chemical potentials, etc. The function must modify the values
* stored in the parent system to values appropriate to a new value
* of a contour variable value sNew that is passed as a parameter.
* The functional dependence of parameters on the contour variable
* over a range [0,1] is defined by the subclass implementation.
*
* \param sNew new value of path length coordinate, in range [0,1]
*/
virtual void setParameters(double sNew) = 0;
/**
* Create initial guess for the next state by extrapolation.
*
* This function should set extrapolated values of the variables that
* are modified by the iterative SCFT solver, i.e., values of fields
* (coefficients of basis functions or values grid points) and unit
* cell parameters or domain dimensions for problems involving an
* adjustable domain. Values should be extrapolated to a new
* contour variable sNew by constructing a linear combination of
* corresponding values obtained in previous converged states.
* After computing the desired extrapolated values, this function
* must set these values in the parent system.
*
* Extrapolated values of adjustable variables at the new contour
* variable sNew that is passed as a parameter should be computed
* for each adjustable variable by constructing a Lagrange polynomial
* in s that passes through all stored values, and evaluating the
* resulting polynomial at sNew. This yields an expression for
* the extrapolated value as a linear combination of stored values
* with coefficients that depend only the values of sNew and the
* values of s at previous states. This function should call the
* setCoefficients function to compute these coefficients.
*
* \param sNew new value of path length coordinate.
*/
virtual void extrapolate(double sNew) = 0;
/**
* Compute coefficients of previous states for continuation.
*
* This function must be called by the implementation of extrapolate.
*
* \param sNew new value of path length coordinate.
*/
void setCoefficients(double sNew);
/**
* Call current iterator to solve SCFT problem.
*
* Return 0 for sucessful solution, 1 on failure to converge.
*/
virtual int solve(bool isContinuation) = 0;
/**
* Reset system to previous solution after iterature failure.
*
* The implementation of this function should reset the system
* state to correspond to that stored in state(0).
*/
virtual void reset() = 0;
/**
* Update state(0) and output data after successful solution.
*
* This function is called by accept(). The implementation of this
* function should copy the current system state into state(0),
* output any desired information about the current solution,
* and perform any other operations that should be performed
* immediately after acceptance of a converged solution.
*/
virtual void getSolution() = 0;
/**
* Clean up operation at the end of a sweep
*
* Empty default implementation.
*/
virtual void cleanup();
private:
/// Array of State objects, not sequential (work space)
DArray<State> states_;
/// Values of s associated with previous solutions
DArray<double> sHistory_;
/// Pointers to State objects containing old solutions.
DArray<State*> stateHistory_;
/// Coefficients for use during continuation
DArray<double> c_;
/// Maximum number of stored previous states.
int historyCapacity_;
/// Current number of stored previous states.
int historySize_;
/// Number of converged solutions accepted thus far.
int nAccept_;
/// Should the state of the iterator be re-used during continuation.
bool reuseState_;
/**
* Accept a new solution, and update history.
*
* This function is called by sweep after a converged solution is
* obtained at a new value of the contour variable s. The function
* calls the pure virtual function getSolution() internally to
* copy the system state to the most recent stored solution.
*
* \param s value of s associated with new solution.
*/
void accept(double s);
/**
* Default constructor (private, not implemented to prevent use).
*/
SweepTmpl();
};
} // namespace Pscf
#include "SweepTmpl.tpp"
#endif
| 10,130
|
C++
|
.h
| 263
| 31.562738
| 75
| 0.655029
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,079
|
Monomer.h
|
dmorse_pscfpp/src/pscf/chem/Monomer.h
|
#ifndef PSCF_MONOMER_H
#define PSCF_MONOMER_H
/*
* PSCF - Polymer Self-Consistent Field Theory
*
* Copyright 2016 - 2022, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include <string>
#include <iostream>
namespace Pscf
{
/**
* Descriptor for a monomer or particle type.
*
* Iostream extractor (>>) and inserter (<<) operators are defined for
* a Monomer, allowing the description of a monomer to be read from or
* written to file like a primitive variable. The text representation
* contains only the value of the kuhn (statistical segment) length,
* as described \ref pscf_Monomer_page "here".
*
* Data for all monomers in a system is normally read from a parameter
* file into an array-valued parameter named "monomers".
*
* \ingroup Pscf_Chem_Module
*/
class Monomer
{
public:
/**
* Constructor.
*/
Monomer();
/**
* Set the integer index for this monomer type.
*
* \param id new value for index
*/
void setId(int id);
/**
* Unique integer index for monomer type.
*/
int id() const;
/**
* Statistical segment length (random walk step size).
*/
double kuhn() const;
/**
* Set statistical segment length.
*/
void setKuhn(double kuhn);
/**
* Serialize to or from an archive.
*
* \param ar Archive object
* \param version archive format version index
*/
template <class Archive>
void serialize(Archive ar, const unsigned int version);
private:
// Integer identifier
int id_;
// Statistical segment length / kuhn length
double kuhn_;
//friends
friend
std::istream& operator >> (std::istream& in, Monomer& monomer);
friend
std::ostream& operator << (std::ostream& out, const Monomer& monomer);
};
/**
* istream extractor for a Monomer.
*
* \param in input stream
* \param monomer Monomer to be read from stream
* \return modified input stream
*/
std::istream& operator >> (std::istream& in, Monomer& monomer);
/**
* ostream inserter for a Monomer.
*
* \param out output stream
* \param monomer Monomer to be written to stream
* \return modified output stream
*/
std::ostream& operator << (std::ostream& out, const Monomer& monomer);
// inline member functions
/*
* Get monomer type index.
*/
inline int Monomer::id() const
{ return id_; }
/*
* Statistical segment length.
*/
inline double Monomer::kuhn() const
{ return kuhn_; }
/*
* Set statistical segment length.
*
* \param kuhn new value for statistical segement length
*/
inline void Monomer::setKuhn(double kuhn)
{ kuhn_ = kuhn; }
/*
* Serialize to or from an archive.
*/
template <class Archive>
void Monomer::serialize(Archive ar, const unsigned int version)
{
ar & id_;
ar & kuhn_;
}
}
#endif
| 3,085
|
C++
|
.h
| 115
| 21.843478
| 76
| 0.638031
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,080
|
BlockDescriptor.h
|
dmorse_pscfpp/src/pscf/chem/BlockDescriptor.h
|
#ifndef PSCF_BLOCK_DESCRIPTOR_H
#define PSCF_BLOCK_DESCRIPTOR_H
/*
* PSCF - Polymer Self-Consistent Field Theory
*
* Copyright 2016 - 2022, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include "PolymerType.h"
#include <util/containers/Pair.h>
#include <iostream>
namespace Pscf
{
using namespace Util;
/**
* Description of a linear homopolymer block within a block polymer.
*
* This class defines the blockId, monomerId, length and vertexIds of
* a block within a block polymer. It serves as a base class for the
* BlockTmpl class template, which is a template for classes that solve
* the modified diffusion equation for the two propagators associated
* with a block. VertexIds should be set for all blocks in a block
* polymer before the associated Vertex objects are initialized.
*
* \ref user_param_block_sec "Parameter File Format"
* \ingroup Pscf_Chem_Module
*/
class BlockDescriptor
{
public:
/**
* Constructor.
*/
BlockDescriptor();
/**
* Destructor.
*/
virtual ~BlockDescriptor();
/**
* Serialize to/from archive.
*
* \param ar input or output Archive
* \param versionId archive format version index
*/
template <class Archive>
void serialize(Archive& ar, unsigned int versionId);
/// \name Setters
//@{
/**
* Set the id for this block.
*
* \param id integer index for this block
*/
void setId(int id);
/**
* Set indices of associated vertices.
*
* \param vertexAId integer id of vertex A
* \param vertexBId integer id of vertex B
*/
void setVertexIds(int vertexAId, int vertexBId);
/**
* Set the monomer id.
*
* \param monomerId integer id of monomer type (>=0)
*/
void setMonomerId(int monomerId);
/**
* Set the length of this block.
*
* The ``length" is steric volume / reference volume.
*
* \param length block length (number of monomers).
*/
virtual void setLength(double length);
/**
* Set the polymer type.
*
* By convention, if the polymer type of a block with block index id is
* PolymerType::Linear, then vertexId(0) = id and vertexId(1) = id + 1.
* The PolymerType enumeration value for the block is used by the
* inserter and extractor operators to define a shorter string
* representation for blocks in linear polymers, for which the string
* representation does not include values for vertex ids. Vertex id
* values for blocks in a linear poiymer must be set explicitly by
* calling the setVertexIds function with consecutive values, as done
* in the PolymerTmpl::readParameters function.
*
* \param type type of polymer (branched or linear)
*/
void setPolymerType(PolymerType::Enum type);
//@}
/// \name Accessors (getters)
//@{
/**
* Get the id of this block.
*/
int id() const;
/**
* Get the monomer type id.
*/
int monomerId() const;
/**
* Get the pair of associated vertex ids.
*/
const Pair<int>& vertexIds() const;
/**
* Get id of an associated vertex.
*
* \param i index of vertex (0 or 1)
*/
int vertexId(int i) const;
/**
* Get the length (number of monomers) in this block.
*/
double length() const;
/**
* Get the type of the parent polymer (branched or linear).
*/
PolymerType::Enum polymerType() const;
//@}
private:
/// Identifier for this block, unique within the polymer.
int id_;
/// Identifier for the associated monomer type.
int monomerId_;
/// Length of this block = volume / monomer reference volume.
double length_;
/// Indexes of associated vertices
Pair<int> vertexIds_;
/// Type of polymer (branched or linear)
PolymerType::Enum polymerType_;
friend
std::istream& operator >> (std::istream& in, BlockDescriptor &block);
friend
std::ostream& operator << (std::ostream& out,
const BlockDescriptor &block);
};
/**
* istream extractor for a BlockDescriptor.
*
* \param in input stream
* \param block BlockDescriptor to be read from stream
* \return modified input stream
*/
std::istream& operator >> (std::istream& in, BlockDescriptor &block);
/**
* ostream inserter for a BlockDescriptor.
*
* \param out output stream
* \param block BlockDescriptor to be written to stream
* \return modified output stream
*/
std::ostream& operator << (std::ostream& out, const BlockDescriptor &block);
// Inline member functions
/*
* Get the id of this block.
*/
inline int BlockDescriptor::id() const
{ return id_; }
/*
* Get the monomer type id.
*/
inline int BlockDescriptor::monomerId() const
{ return monomerId_; }
/*
* Get the pair of associated vertex ids.
*/
inline const Pair<int>& BlockDescriptor::vertexIds() const
{ return vertexIds_; }
/*
* Get id of an associated vertex.
*/
inline int BlockDescriptor::vertexId(int i) const
{ return vertexIds_[i]; }
/*
* Get the length (number of monomers) in this block.
*/
inline double BlockDescriptor::length() const
{ return length_; }
/*
* Get the polymer type (branched or linear).
*/
inline PolymerType::Enum BlockDescriptor::polymerType() const
{ return polymerType_; }
/*
* Serialize to/from an archive.
*/
template <class Archive>
void BlockDescriptor::serialize(Archive& ar, unsigned int)
{
ar & id_;
ar & monomerId_;
ar & vertexIds_;
ar & length_;
}
}
#endif
| 6,049
|
C++
|
.h
| 198
| 24.39899
| 79
| 0.632848
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,081
|
Species.h
|
dmorse_pscfpp/src/pscf/chem/Species.h
|
#ifndef PSCF_SPECIES_H
#define PSCF_SPECIES_H
/*
* PSCF - Polymer Self-Consistent Field Theory
*
* Copyright 2016 - 2022, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include <util/global.h>
namespace Pscf
{
/**
* Base class for a molecular species (polymer or solvent).
*
* Species is a base class for both polymeric and solvent species.
* Each Species has values of phi, mu and q, and an ensemble that are
* defined as protected variables. The value of either phi or mu must
* be provided as an input parameter, and value of the other variable
* must then be computed. The class that actually solves the
* single-molecule statistical mechanics problem must be a subclass
* of Species so that it may directly modify the protected variable
* phi or mu (depending on the ensemble) and q.
*
* \ingroup Pscf_Chem_Module
*/
class Species
{
public:
/**
* Statistical ensemble for number of molecules.
*/
enum Ensemble {Unknown, Closed, Open};
/**
* Default constructor.
*/
Species();
/**
* Get the overall volume fraction for this species.
*/
double phi() const;
/**
* Get the chemical potential for this species (units kT=1).
*/
double mu() const;
/**
* Get the molecular partition function for this species.
*/
double q() const;
/**
* Get the statistical ensemble for this species (open or closed).
*/
Ensemble ensemble();
protected:
/**
* Volume fraction, set by either setPhi or compute function.
*/
double phi_;
/**
* Chemical potential, set by either setPhi or compute function.
*/
double mu_;
/**
* Partition function, set by compute function.
*/
double q_;
/**
* Statistical ensemble for this species (open or closed).
*/
Ensemble ensemble_;
};
/*
* Get species volume fraction.
*/
inline double Species::phi() const
{ return phi_; }
/*
* Get species chemical potential.
*/
inline double Species::mu() const
{ return mu_; }
/*
* Get statistical ensemble for this species (open or closed).
*/
inline Species::Ensemble Species::ensemble()
{ return ensemble_; }
/**
* istream extractor for a Species::Ensemble.
*
* \param in input stream
* \param policy Species::Ensemble to be read
* \return modified input stream
*/
std::istream& operator >> (std::istream& in, Species::Ensemble& policy);
/**
* ostream inserter for an Species::Ensemble.
*
* \param out output stream
* \param policy Species::Ensemble to be written
* \return modified output stream
*/
std::ostream& operator << (std::ostream& out, Species::Ensemble policy);
/**
* Serialize a Species::Ensemble
*
* \param ar archive object
* \param policy object to be serialized
* \param version archive version id
*/
template <class Archive>
void serialize(Archive& ar, Species::Ensemble& policy,
const unsigned int version)
{ serializeEnum(ar, policy, version); }
}
#endif
| 3,333
|
C++
|
.h
| 114
| 23.754386
| 75
| 0.642902
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,082
|
Vertex.h
|
dmorse_pscfpp/src/pscf/chem/Vertex.h
|
#ifndef PSCF_VERTEX_H
#define PSCF_VERTEX_H
/*
* PSCF - Polymer Self-Consistent Field Theory
*
* Copyright 2016 - 2022, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include <util/containers/GArray.h>
#include <util/containers/Pair.h>
namespace Pscf
{
class BlockDescriptor;
using namespace Util;
/**
* A junction or chain end in a block polymer.
*
* \ingroup Pscf_Chem_Module
*/
class Vertex
{
public:
/**
* Constructor.
*/
Vertex();
/**
* Destructor.
*/
~Vertex();
/**
* Set the integer identifier of this vertex.
*
* \param id identifier
*/
void setId(int id);
/**
* Add block to the list of attached blocks.
*
* Preconditions: The id for this vertex must have been set, vertex
* ids must have been set for the block, and the id of this vertex
* must match one of the ids for the two vertices attached to the
* block.
*
* \param block attached BlockDescriptor object
*/
void addBlock(BlockDescriptor const & block);
/**
* Get the id of this vertex.
*/
int id() const;
/**
* Get the number of attached blocks.
*/
int size() const;
/**
* Get the block and direction of an incoming propagator.
*
* The first element of the integer pair is the block id,
* and the second is a direction id which is 0 if this
* vertex is vertex 1 of the block, and 1 if this vertex
* is vertex 0.
*
* \param i index of incoming propagator
* \return Pair<int> containing block index, direction index
*/
Pair<int> const & inPropagatorId(int i) const;
/**
* Get the block and direction of an outgoing propagator
*
* The first element of the integer pair is the block id,
* and the second is a direction id which is 0 if this
* vertex is vertex 0 of the block, and 1 if this vertex
* is vertex 1.
*
* \param i index of incoming propagator
* \return Pair<int> containing block index, direction index
*/
Pair<int> const & outPropagatorId(int i) const;
private:
GArray< Pair<int> > inPropagatorIds_;
GArray< Pair<int> > outPropagatorIds_;
int id_;
};
inline int Vertex::id() const
{ return id_; }
inline int Vertex::size() const
{ return outPropagatorIds_.size(); }
inline
Pair<int> const & Vertex::inPropagatorId(int i) const
{ return inPropagatorIds_[i]; }
inline
Pair<int> const & Vertex::outPropagatorId(int i) const
{ return outPropagatorIds_[i]; }
}
#endif
| 2,776
|
C++
|
.h
| 96
| 23.03125
| 72
| 0.628021
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,083
|
SolventDescriptor.h
|
dmorse_pscfpp/src/pscf/chem/SolventDescriptor.h
|
#ifndef PSCF_SOLVENT_DESCRIPTOR_H
#define PSCF_SOLVENT_DESCRIPTOR_H
/*
* PSCF - Polymer Self-Consistent Field Theory
*
* Copyright 2016 - 2022, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include <pscf/chem/Species.h> // base class
#include <util/param/ParamComposite.h> // base class
namespace Pscf {
using namespace Util;
/**
* Descriptor for a solvent species.
*
* \ingroup Pscf_Chem_Module
*/
class SolventDescriptor : public Species, public ParamComposite
{
public:
/**
* Constructor.
*/
SolventDescriptor();
/**
* Constructor.
*/
~SolventDescriptor();
/**
* Read and initialize.
*
* \param in input parameter stream
*/
virtual void readParameters(std::istream& in);
/// \name Setters (set member data)
///@{
/**
* Set input value of phi (volume fraction), if ensemble is closed.
*
* This function may be used to modify phi during a sweep, after
* initialization. An exception is thrown if this function is called
* when the ensemble is open on entry.
*
* \param phi desired volume fraction for this species
*/
void setPhi(double phi);
/**
* Set input value of mu (chemical potential), if ensemble is open.
*
* This function may be used to modify mu during a sweep, after
* initialization. An Exception is thrown if this function is called
* when the ensemble is closed on entry.
*
* \param mu desired chemical potential for this species
*/
void setMu(double mu);
/**
* Set the monomer id for this solvent.
*
* \param monomerId integer id of monomer type, in [0,nMonomer-1]
*/
void setMonomerId(int monomerId);
/**
* Set the size or volume of this solvent species.
*
* The ``size" is steric volume / reference volume.
*
* \param size volume of solvent
*/
void setSize(double size);
///@}
/// \name Accessors (getters)
///@{
/**
* Get the monomer type id.
*/
int monomerId() const;
/**
* Get the size (number of monomers) in this solvent.
*/
double size() const;
///@}
// Inherited accessor functions
using Pscf::Species::phi;
using Pscf::Species::mu;
using Pscf::Species::q;
using Pscf::Species::ensemble;
protected:
// Inherited data members
using Pscf::Species::phi_;
using Pscf::Species::mu_;
using Pscf::Species::q_;
using Pscf::Species::ensemble_;
/// Identifier for the associated monomer type.
int monomerId_;
/// Size of this block = volume / monomer reference volume.
double size_;
};
// Inline member functions
/*
* Get the monomer type id.
*/
inline int SolventDescriptor::monomerId() const
{ return monomerId_; }
/*
* Get the size (number of monomers) in this block.
*/
inline double SolventDescriptor::size() const
{ return size_; }
}
#endif
| 3,220
|
C++
|
.h
| 111
| 22.855856
| 73
| 0.616889
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,084
|
PolymerType.h
|
dmorse_pscfpp/src/pscf/chem/PolymerType.h
|
#ifndef PSCF_POLYMER_TYPE_H
#define PSCF_POLYMER_TYPE_H
/*
* PSCF - Polymer Self-Consistent Field Theory
*
* Copyright 2016 - 2022, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include <util/archives/serialize.h>
#include <iostream>
namespace Pscf
{
using namespace Util;
/**
* Struct containing an enumeration of polymer structure types.
*
* The enumeration PolymerType::Enum has allowed values
* PolymerType::Branched and PolymerType::Linear.
*
* \ingroup Pscf_Chem_Module
*/
struct PolymerType {
enum Enum {Branched, Linear};
};
/**
* Input stream extractor for a PolymerType::Enum enumeration.
*
* \param in input stream
* \param type value of PolymerType to be read from file
*/
std::istream& operator >> (std::istream& in, PolymerType::Enum& type);
/**
* Input stream extractor for a PolymerType::Enum enumeration.
*
* \param out output stream
* \param type value of PolymerType to be written
*/
std::ostream& operator << (std::ostream& out, PolymerType::Enum& type);
/**
* Serialize a PolymerType::Enum enumeration.
*
* \param ar archive
* \param data enumeration data to be serialized
* \param version version id
*/
template <class Archive>
inline void
serialize(Archive& ar, PolymerType::Enum& data, const unsigned int version)
{ serializeEnum(ar, data, version); }
}
#endif
| 1,489
|
C++
|
.h
| 51
| 25.607843
| 78
| 0.702589
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,085
|
SpaceGroup.h
|
dmorse_pscfpp/src/pscf/crystal/SpaceGroup.h
|
#ifndef PSCF_SPACE_GROUP_H
#define PSCF_SPACE_GROUP_H
/*
* Simpatico - Simulation Package for Polymeric and Molecular Liquids
*
* Copyright 2016 - 2022, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include <pscf/crystal/SpaceSymmetry.h>
#include <pscf/crystal/SymmetryGroup.h>
#include <pscf/math/IntVec.h>
#include <util/containers/FSArray.h>
#include <util/param/Label.h>
#include <iostream>
namespace Pscf
{
using namespace Util;
/**
* Crystallographic space group.
*
* \ingroup Pscf_Crystal_Module
*/
template <int D>
class SpaceGroup : public SymmetryGroup< SpaceSymmetry<D> >
{
public:
/**
* Determines if this space group has an inversion center.
*
* Returns true if an inversion center exists, and false otherwise.
* If an inversion center exists, its location is returned as the
* output value of output argument "center".
*
* \param center location of inversion center, if any (output)
*/
bool
hasInversionCenter(typename SpaceSymmetry<D>::Translation& center)
const;
/**
* Shift the origin of space used in the coordinate system.
*
* This function modifies each symmetry elements in the group so as
* to refer to an equivalent symmetry defined using a new coordinate
* system with a shifted origin. The argument gives the coordinates
* of the origin of the new coordinate system as defined in the old
* coordinate system.
*
* \param origin location of origin of the new coordinate system
*/
void
shiftOrigin(typename SpaceSymmetry<D>::Translation const & origin);
/**
* Check if input mesh dimensions are compatible with space group.
*
* This function checks if a mesh with the specified dimensions is
* invariant under all operations of this space group, i.e., whether
* each crystal symmetry operation maps the position of every node
* of the mesh onto the position of another node. It is only possible
* define how a symmetry operation transforms a function that is
* defined only on the nodes of mesh if the mesh is invariant under
* the symmetry operation, in this sense. An invariant mesh must thus
* be used necessary to describe a function whose values on the mesh
* nodes are invariant under all operations in the space group.
*
* If the mesh is not invariant under all operations of the space
* group, an explanatory error message is printed and an Exception
* is thrown to halt execution.
*
* The mesh for a unit cell within a Bravais lattice is assumed to
* be a regular orthogonal mesh in a space of reduced coordinates,
* which are the components of position defined using a Bravais
* basis (i.e., a basis of Bravais lattice basis vectors). Each
* element of the dimensions vector is equal to the number of grid
* points along a direction corresponding to a Bravais lattice vector.
* A Bravais basis is also used to define elements of the matrix
* representation of the point group operation and the translation
* vector in the representation of a crystal symmetry operation as
* an instance of class Pscf::SpaceSymmetry<D>.
*
* \param dimensions vector of mesh dimensions
*/
void checkMeshDimensions(IntVec<D> const & dimensions) const;
// Using declarations for some inherited functions
using SymmetryGroup< SpaceSymmetry <D> >::size;
};
// Template function definition
/**
* Output stream inserter operator for a SpaceGroup<D>.
*
* \param out output stream
* \param g space group
* \ingroup Pscf_Crystal_Module
*/
template <int D>
std::ostream& operator << (std::ostream& out, SpaceGroup<D> const & g)
{
int size = g.size();
out << "dim " << D << std::endl;
out << "size " << size << std::endl;
for (int i = 0; i < size; ++i) {
out << std::endl;
out << g[i];
}
return out;
}
/**
* Input stream extractor operator for a SpaceGroup<D>.
*
* \param in input stream
* \param g space group
*
* \ingroup Pscf_Crystal_Module
*/
template <int D>
std::istream& operator >> (std::istream& in, SpaceGroup<D>& g)
{
int dim, size;
in >> Label("dim") >> dim;
UTIL_CHECK(D == dim);
in >> Label("size") >> size;
SpaceSymmetry<D> s;
g.clear();
for (int i = 0; i < size; ++i) {
in >> s;
g.add(s);
}
return in;
}
/**
* Open and read a group file.
*
* \param groupName name of group, or group file (input)
* \param group space group (output)
*
* \ingroup Pscf_Crystal_Module
*/
template <int D>
void readGroup(std::string groupName, SpaceGroup<D>& group);
/**
* Open and write a group file.
*
* \param filename output file name
* \param group space group
*
* \ingroup Pscf_Crystal_Module
*/
template <int D>
void writeGroup(std::string filename, SpaceGroup<D> const & group);
#ifndef PSCF_SPACE_GROUP_TPP
extern template class SpaceGroup<1>;
extern template class SpaceGroup<2>;
extern template class SpaceGroup<3>;
extern template void readGroup(std::string, SpaceGroup<1>& );
extern template void readGroup(std::string, SpaceGroup<2>& );
extern template void readGroup(std::string, SpaceGroup<3>& );
extern template void writeGroup(std::string, SpaceGroup<1> const &);
extern template void writeGroup(std::string, SpaceGroup<2> const &);
extern template void writeGroup(std::string, SpaceGroup<3> const &);
#endif
}
#endif
| 5,823
|
C++
|
.h
| 161
| 30.732919
| 75
| 0.67092
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,086
|
BFieldComparison.h
|
dmorse_pscfpp/src/pscf/crystal/BFieldComparison.h
|
#ifndef PSCF_B_FIELD_COMPARISON_H
#define PSCF_B_FIELD_COMPARISON_H
/*
* PSCF - Polymer Self-Consistent Field Theory
*
* Copyright 2016 - 2022, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include <pscf/math/FieldComparison.h>
#include <util/containers/DArray.h>
namespace Pscf {
using namespace Util;
/**
* Comparator for fields in symmetry-adapted basis format.
*
* \ingroup Pscf_Crystal_Module
*/
class BFieldComparison : public FieldComparison< DArray<double> >
{
public:
/**
* Constructor.
*
* The basis function with index 0 in a symmetry adapted basis is
* always a spatially homogeneous function, i.e., a constant. In
* some situations, we may be interested in determining whether
* two fields are equivalent to within a constant.
*
* Set begin = 0, which is the default, to include the coefficient
* of the first basis function in the comparison, thus determining
* how close to fields are to being strictly equal.
*
* Set begin = 1 to exclude the coefficient of the first basis
* function, thus comparing only deviatoric parts of the fields.
*
* \param begin index of first element to include in comparison.
*/
BFieldComparison(int begin = 0);
};
} // namespace Pscf
#endif
| 1,406
|
C++
|
.h
| 41
| 29.536585
| 72
| 0.699115
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,087
|
Basis.h
|
dmorse_pscfpp/src/pscf/crystal/Basis.h
|
#ifndef PSCF_BASIS_H
#define PSCF_BASIS_H
/*
* PSCF - Polymer Self-Consistent Field Theory
*
* Copyright 2016 - 2022, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include <pscf/math/IntVec.h> // inline waveId
#include <pscf/mesh/Mesh.h> // inline waveId
#include <util/containers/DArray.h> // member
#include <util/containers/GArray.h> // member
namespace Pscf {
template <int D> class UnitCell;
template <int D> class SpaceGroup;
using namespace Util;
/**
* Symmetry-adapted Fourier basis for pseudo-spectral scft.
*
* <b> %Basis Functions, Waves, and Stars </b>:
*
* This class constructs a symmetry adapted Fourier basis for periodic
* structures with a specified space group symmetry. Each basis function
* is such an expansion is a periodic function that is invariant under
* translations by any Bravais lattice transtlation and under any
* symmetry operations of the specified space group. Each such basis
* function is also an eigenfunction of the Laplacian.
*
* A Fourier series expansion of a periodic function that is invariant
* under under all translations in a specified Bravais lattice is given
* by expansion of plane waves with wavevectors that all belong to the
* corresponding reciprocal lattice. Components of all wavevectors
* are represented within the Basis class using reciprocal lattice basis
* vectors as a basis. In this coordinate system, the coordinates of
* of each reciprocal lattice vector (i.e., any allowed wavevector in
* the Fourier expansion of a periodic function) is given by a list of
* D integers, where D is the dimension of space. We often refer to
* the integer coefficients of a reciprocal lattice vector in this
* basis as the indices of the vector.
*
* Each basis function in a symmetry-adapated Fourier basis is equal
* to a linear superposition of complex exponential plan waves
* associated with a set of reciprocal lattice vectors that are related
* by space group symmetry operations. We refer to such a set of
* symmetry related wavevectors throughout the code and documentation
* as a "star". For example, in any 3D cubic space group, the
* wavevectors in each star have coefficients {ijk} that are related
* by changes in sign of individual coefficients and/or permutations
* of the three indices. Each wave in the Fourier expansion of a
* function belongs to one and only one star. The basis function
* associated with a star is thus defined by specifying a complex-valued
* coefficient for the complex exponential plane wave exp(iG.r)
* associated with each wave G in the associated star, where we use
* G.r to represent a dot product of wavevector G and position vector r.
*
* <b> %Wave and %Star Arrays: </b>
*
* Individual wavevectors and stars are represented by instances of
* the local classes Basis::Wave and Basis::Star, respectively. After
* construction of a basis is completed by calling the makeBasis
* function, a Basis has a private array of waves (i.e., instances of
* Basis::Wave) and an array stars (instances of Basis::Star), which
* we will refer to in this documentation as the wave array and the
* star array. (The actual array containers are private member
* variables named waves_ and stars_, respectively). Individual
* elements of the wave array may be accessed by const reference by
* the accessor function wave(int id) function, and elements of the
* star array may be acccess by the function star(int id).
*
* Elements of the wave array are listed in order of non-decreasing
* Cartesian wavevector magnitude, with wavevectors in the same star
* listed as as a consecutive block. Wavevectors within each star are
* listed in order of decreasing order as determined by the integer
* indices, as defined by the member function Wave::indicesBz, with more
* signficant digits on the left. For example, the waves of the {211}
* star of a cubic structure with full cubic symmetry will be listed
* in the order:
* \code
* 1 1 1
* 1 1 -1
* 1 -1 1
* 1 -1 -1
* -1 1 1
* -1 1 -1
* -1 -1 1
* -1 -1 -1
* \endcode
* Further information about each wavevector and each star is
* contained in public member variables of the Wave::Wave and
* Wave::Star classes. See the documentation of these local classes
* for some further details.
*
* <b> Discrete Fourier Transforms and Wavevector Aliasing </b>:
*
* This class is designed for contexts in which the values of real
* periodic functions are represented numerically by values evaluated
* on a regular grid of points within each primitive unit cell of
* the crystal, and in which a discrete Fourier transform (DFT) is
* used to transform between Fourier and real-space representations
* of such function. Construction of a symmetry adapted Fourier
* basis requires a description of this spatial discretization grid,
* given by an instance of class Mesh<D>, in addition UnitCell<D>
* and SpaceGroup<D> objects.
*
* Interpretation of indices for wavevectors in this context is
* complicated by the phenomena of ``aliasing" of wavevectors used in
* the Fourier expansion of periodic functions that are defined only
* at the nodes of a regular grid. In what follows, let N_i denote
* the the number of lattice grid points along direction i in a
* coordinate system in which Bravais lattice vectors are used as
* basis vectors to construct corresponding Cartesian vectors.
* Any two reciprocal lattice vectors for which the integer indices
* associate with any direction i differs by an integer multiple of
* N_i are equivalent in the sense that the equivalent that they
* yield equivalent values for the complex exponential exp(iG.r)
* for all values of r that lie on lattice nodes. Such vectors
* are referred to as aliases of one another. Two different schemes
* are used in here to assign a choose a unique choice for a list
* of indices for each distinct wavevector.
*
* (1) The "DFT" (discrete Fourier transform) indices of a wavevector
* is the choice of a list of indices such that the index associated
* with direction i, denoted by m_i, is in the range 0 <= m_i < N_i.
*
* (2) The "BZ" (Brillouin zone) indices of a wavevector is a list of
* indices of the wavevector or one of its aliases chosen such that
* the the Cartesian norm of the wavevector constructed as a linear
* superposition of reciprocal lattice vectors multiplied these
* indices is less than or equal to the norm of any other alias of
* the wavevector. In cases in which a set of two or more aliases
* of a wavevector have the same Cartesian norm, the BZ indices are
* chosen to be those of the member of the set for which the indices
* are "largest" when lists of indices are compared by treating
* earlier indices are more signficant, as done in the ordering of
* waves within a star in the waves array.
*
* The number of distinct waves in the waves array is equal to the
* number of grid points in the corresponding spatial mesh. Each wave
* has a unique list of DFT indices and also a unique list of BZ
* indices, which are listed in the "indicesDft" and "indicesBz"
* IntVec<D> members of the Basis<D>::Wave class. Values of the
* square magnitude of wavevectors are always computed using the
* indices of each wavevector.
*
* <b> Space Group Symmetry </b>:
*
* A space group symmetry is defined by a pair (R,t) in which R is a
* linear transformation that may represented as a matrix and t is a
* translation vector. The translation vector may be either zero or a
* vector whose components in a basis of Bravais lattice vectors are
* all fractions (i.e., translations by fractions of a unit cell).
* The effect of such a symmetry operation on a position vector r is
* to transform r to a tranformed position r' given by r' = R.r + t,
* where R.r represents the result of applying linear transformation
* (or matrix) R to vector r.
*
* Applying such a symmetry operation to a plane wave f(r) = exp(iG.r)
* with a wavevector G transforms f(r) into a different plane wave
* f'(r) given by f'(r) = exp[i G.(Rr + t)] = exp[i(G'.r + theta)]
* with a transformed wavevector G' given by G' = G.R, with a phase
* shift theta given by the dot product theta = G.t. This operation
* can be expressed using matrix notation by expressing all position
* vectors such as r, r' and t as column vectors, all wavevectors
* such as G and G' as row vectors, and a linear transformation
* denoted by R by a matrix. When applying symmetry operations to
* wavevectors defined using a discrete Fourier transform, the equation
* G' = G.R is interpreted using the representation of wavevectors
* G and G' using their BZ (Brillouin zone) indices.
*
* The plane waves in a star all have the same Cartesian magnitude,
* as a result of the fact that the linear transformation represented
* by R for a symmetry operation (R,t) must be a norm preserving
* (i.e., unitary) transformation such as a rotation, reflection or
* inversion. For any such operation, |G| = |G.R|, where |...|
* represents a Cartesian norm (i.e., a Euclidean norm defined using
* Cartesian representations of G and R).
*
* The requirement that a basis function be invariant under all of the
* symmetry operations in a space group imposes a set of relationships
* among the coefficients of different waves in the expansion of the
* basis function associated with a star. Suppose G and G' are two
* wavevectors in the same star that are related by a transformation
* or matrix R associated with a symmetry operation S=(R,t), such that
* G'=G.R. Let c and c' be the complex coefficients of planes waves
* associated with G and G' within the sum that defines a basis
* function. The requirement that the basis function be invariant
* under the action of symmetry S requires that c' = c exp(iG.t). The
* resulting set of requirements among all the waves in a star implies
* that the coefficients associated with different waves in a star must
* all have the same absolute magnitude, because |exp(iG.t)|=1, and
* imposes a set of relationships among the phases (complex arguments)
* of these coefficients. The magnitude of the coefficients of all waves
* in a star is uniquely determined in this class by imposing a
* normalization condition requiring that the sum of squares of absolute
* magnitudes of coefficients of waves in a star be equal to unity, or
* that the square magnitude of each coefficient be the inverse of the
* number of distinct distinct waves in the star. The combination of
* this normalization condition and the phase conditions imposed by the
* requirement of invariance under space group symmetries defines the
* basis function associated with each star to within an overall
* complex prefactor of unit absolute magnitude (i.e., a phasor).
*
* Space group symmetries are represented internally in the class
* SpaceSymmetry<D> class using a coordinate system in which all position
* and translation vectors are expanded using the basis of Bravais basis
* vectors defined in UnitCell<D>, while wavevectors are expanded using
* the corresponding reciprocal lattice basis vectors. In this coordinate
* system, for any symmetry operation S = (R,t), elements of the matrix
* representation of the linear transformation R are all integers
* (usually 0, +1, or -1) and elements of the translation vector t are
* all rational numbers with small denominators (e.g., 1/4, 1/3, 1/2,
* etc.) in the range [0,1].
*
* <b> Cancelled Stars </b>
*
* A star is said to be "cancelled" if there is no way to construct
* nonzero basis function from the waves in that star that is invariant
* under all of the elements of the space group. The notion of
* cancellation is equivalent to the notion of systematic cancellation
* used in analysis of Bragg scattering from crystals - waves belonging
* to cancelled stars exhibit systematic cancellation in scattering,
* and do not yield Bragg peaks.
*
* A star is cancelled iff, for any wavevector G in the star, there
* exist two symmetry operations S = (R,t) and S' = (R',t') in the
* space group for which G.R = G.R' but G.t != G.t'. It can shown
* that if this is satisfied for any wavevector in the star, it must
* be satisfied for all wavevector in the star.
*
* The Wave class has a bool member variable named cancel that is
* set true for cancelled stars and false otherwise. Each basis
* function in the symmetry-adapted Fourier basis is associated
* with a non-cancelled star.
*
* The class Star has two integer members named starId and basisId
* that correspond to different ways of indexing stars. The index
* starId is the index of the a star within an ordered list of all
* stars, including cancelled stars. The starId is also the array
* element index of the star with the stars_ array, which includes
* cancelled stars. The basisId of an uncancelled star is its index
* within a contracted list that contains only uncancelled stars,
* skipping over cancelled stars. The basisId is not defined for
* a cancelled star, and the member variable basisId is set to -1
* all cancelled stars by convention. A single Star object may be
* accessed by its starId using the function Basis::star(int starId),
* and an uncancelled star may be accessed by its basisId using the
* function Basis::basisFunction(int basisId).
*
* <b> Open and Closed Stars </b>
*
* Every star is either "open" or "closed" under the action of the
* inversion operation. A star is closed under inversion if, for
* every wavevector G in the star, the negation -G is in the same
* star. The negation of a wavevector is defined by inverting all
* of its BZ indices. A star that is not closed under inversion,
* or "closed", is "open".
*
* In a basis for a crystal contains an inversion center, for which
* which the space group includes a symmetry operation r -> -r + t,
* all stars are closed. Open stars only apear in space groups that
* do not contain an inversion center. A crystal with an inversion
* center is said to be "centrosymmetric". Open stars thus only
* exist in space groups for non-centrosymmetric crystals.
*
* Open stars come in pairs that are related by inversion, such that
* for every wavevector G in one star in the pair, the negation -G is
* in the other star. Pairs of open stars that are related by inversion
* are listed consecutively in the Stars array, and correspond to
* neighboring blocks of waves in the waves array.
*
* The local Star class has an integer member "starInvert" that is
* set to if a star is closed, 1 if it is the first member of a pair
* of open stars that are related by inverse, and -1 if the is the
* second member of such a pair of stars.
*
* Each star is assigned a unique characteristic wave that can be
* used as a unique identifier for the star. Local class Star has an
* IntVec<D> member named waveBz that lists the BZ indices of the
* characteristic wave of the star. The characteristic wave is taken
* to be the first wave in the star for stars with starInvert = 0 or
* starInvert = 1. In stars with startInvert = -1, the characteristic
* wave is taken to be the negation of the characteristic wave of
* its partner, which is the previous star.
*
* <b> Phase Conventions for %Basis Functions </b>
*
* Closed stars:
* Phases of the coefficients of waves in each closed star are
* chosen so that the associated basis function is a real function
* of position. This is done by choosing coefficients such that
* the coefficient associated with each wavevector and its
* negation are complex conjugates. This requirement, together
* with the normalization condition, determines the basis function
* to within an overall sign. The sign of the basis function is
* fixed by requiring that the coefficient of the characteristic
* wave of the star (the first wave listed) has a non-negative
* real part, and a negative imaginary part in the special case
* in which the coefficient must be chosen to be pure imaginary.
*
* Basis functions associated with pairs of stars that are related
* by inversion are defined so as to be complex conjugates of one
* another. This is done by requiring that the coefficient of the
* characteristic wave of each such star is real and positive.
*
* <b> Fourier expansion of a real Function </b>
*
* The expansion of a real function with a specified space group
* symmetry is specified by specifying a real coefficient for each
* closed star and a pair of real coefficients for each pair of closed
* stars. The number of required real coefficients is thus the same as
* the same number as the number of uncancelled stars or basis
* functions. By convention, these coefficients should be stored in
* an array in which the index of the coefficient of a the basis
* function associated with a closed star is the same as the index of
* the closed star, and the indices of the two real coefficients of
* each pair of basis functions arising from open stars that are
* related by inversion correspond to the indices of these two stars.
*
* Suppose two open stars stars that are related by inversion appear
* in the stars array with indices j and j+1. Let f(r) denote the
* basis function associated with star j and let its complex conjugate
* f^{*}(r) denote the basis function associated with star j+1. Let
* A denote an array of real coefficients used to expand a real
* periodic basis function. Let a = A[j] and b = A[j+1] denote the
* coefficients that appear in corresponding elements j and j + 1
* of array A. The contribution of stars j and j+1 to the desired
* real periodic function is given by an expression
*
* (a - ib) f(r) + (a + ib) f^{*}(r)
*
* in which i denotes the square root of -1.
*
* The contribution of a basis function f(r) associated with a
* closed star is simply given by the product of the associated
* real coefficient and this real basis function.
*
* \ingroup Pscf_Crystal_Module
*/
template <int D>
class Basis
{
public:
/**
* Wavevector used to construct a basis function.
*/
class Wave
{
public:
/**
* Coefficient of wave within the associated star basis function.
*/
std::complex<double> coeff;
/**
* Integer indices of wave, on a discrete Fourier transform mesh.
*
* Components of this IntVec<D> are non-negative. Component i lies
* within the range [0, meshDimension(i)], where meshDimension(i)
* is the number of grid points.
*/
IntVec<D> indicesDft;
/**
* Integer indices of wave, in first Brillouin zone.
*
* Components of this IntVec<D> may be negative or positive, and
* differ from corresponding components of indicesDft by integer
* multiples of a corresponding mesh dimension, so that indicesBz
* and indicesDft correspond to equivalent aliased wavevectors
* for functions evaluated on the chosen discretization mesh.
* The shifts relative to indicesDft are chosen so as to minimize
* the norm of the Cartesian wavevector constructed by taking a
* linear combination of Bravais lattice basis vectors multiplied
* by components of indicesBz.
*/
IntVec<D> indicesBz;
/**
* Index of the star that contains this wavevector.
*/
int starId;
/**
* Is this wave represented implicitly in DFT of real field?
*
* In the discrete Fourier transform (DFT) of a real function,
* the coefficients of nonzero wavevector G and -G must be
* complex conjugates. As a result, only one of these two
* coefficients is stored in the container RFieldDft used to
* store the DFT of a real function. For each such pair, the
* member variable Basis::Wave::implicit is set false for the
* the wavevector whose coefficient is represented explicitly,
* and is set true for the wavevector whose coefficient is
* left implicit.
*/
bool implicit;
/*
* Default constructor.
*/
Wave()
: coeff(0.0),
indicesDft(0),
indicesBz(0),
starId(0),
implicit(false),
sqNorm(0.0)
{}
private:
/**
* Square magnitude of associated wavevector
*/
double sqNorm;
friend class Basis<D>;
};
/**
* A list of wavevectors that are related by space-group symmetries.
*
* The wavevectors in a star form a continuous block within the array
* waves defined by the Basis classes. Within this block, waves are
* listed in descending lexigraphical order of their integer (ijk)
* indices as given by Basis::Wave::indexBz.
*/
class Star
{
public:
/**
* Number of wavevectors in this star.
*/
int size;
/**
* Wave index of first wavevector in star.
*/
int beginId;
/**
* Wave index of last wavevector in star.
*/
int endId;
/**
* Index for inversion symmetry of star.
*
* A star is said to be closed under inversion iff, for each vector
* G in the star, -G is also in the star. If a star S is not closed
* under inversion, then there is another star S' that is related
* to S by inversion, i.e., such that for each G in S, -G is in S'.
* Stars that are related by inversion are listed consecutively
* within the waves array of the Basis class.
*
* If a star is closed under inversion, then invertFlag = 0.
*
* If a star is not closed under inversion, then invertFlag = +1
* or -1, with inverFlag = +1 for the first star in the pair of
* stars related by inversion and invertFlag = -1 for the second.
*
* In a centro-symmetric group (i.e., a group that includes the
* inversion operation, with an inversion center at the origin
* of the coordinate system), all stars are closed under
* inversion. In this case, all stars in the basis must thus
* have starInvert = 0.
*
* In a non-centro-symmetric group, a stars may either be closed
* closed under inversion (starInvert = 0) or belong to a pair
* of consecutive stars that are related by inversion
* (starInver = +1 or -1).
*/
int invertFlag;
/**
* Integer indices indexBz of a characteristic wave of this star.
*
* Wave given here is the value of indexBz for a characteristic
* wave for the star. For invertFlag = 0 or 1, the characteristic
* wave is the first wave in the star. For invertFlag = -1, this
* is the negation of the waveBz of the partner star for which
* invertFlag = 1.
*
* The coefficient of wave waveBz is always real and positive.
*/
IntVec<D> waveBz;
/**
* Index of this star in ordered array of all stars.
*
* This is the index of this star within array stars_.
*/
int starId;
/**
* Index of basis function associated with this star.
*
* If this star is not cancelled (cancel == false), then basisId
* is set equal to the index of the associated basis function in
* in a list of nonzero basis functions or (equivalently) in a
* list of non-cancelled stars.
*
* If this star is cancelled (cancel == true), then basisId = -1.
*/
int basisId;
/**
* Is this star cancelled, i.e., associated with a zero function?
*
* The cancel flag is true iff no nonzero basis function can be
* constructed from the waves of this star that is invariant under
* all elements of the space group. Basis functions are thus
* associated only with stars for which cancel == false.
*
* Each cancelled star contains a set of waves that are related
* by symmetry for which the X-ray or neutron scattering intensity
* would exhibit a systematic cancellation required by the space
* group symmetry.
*/
bool cancel;
/*
* Default constructor.
*/
Star()
: size(0),
beginId(0),
endId(0),
invertFlag(0),
waveBz(0),
starId(0),
basisId(0),
cancel(false)
{}
};
// Public member functions of Basis<D>
/**
* Default constructor.
*/
Basis();
/**
* Destructor.
*/
~Basis();
/**
* Construct basis for a specific mesh and space group.
*
* This function implements the algorithm for constructing a
* basis. It is called internally by the overloaded makeBasis
* function that takes a file name as an argument rather than a
* SpaceGroup<D> object.
*
* \param mesh spatial discretization grid
* \param unitCell crystallographic unitCell
* \param group crystallographic space group
*/
void makeBasis(Mesh<D> const & mesh,
UnitCell<D> const & unitCell,
SpaceGroup<D> const & group);
/**
* Construct basis for a specific mesh and space group name.
*
* This function attempts to identify a file with a name given by
* groupName that contains a listing of all of the symmetry elements
* in the space group. It looks first for a file with the specified
* name defined relative to the current working directory. Failing
* that, it looks for a file with the specified name in a standard
* data directory tree that contains space group files for all
* possible space groups (i.e,. all 230 3D groups, 17 2D groups and
* 2 1d groups) with file names derived from international table
* names. Those files are located in the data/groups directory
* tree of the package root directory.
*
* If a file containing a valid group is found, this function passes
* the resulting SpaceGroup<D> object to the overloaded function
* makeBasis(Mesh<D> const&, UnitCell<D> const&, SpaceGroup<D> const&).
*
* This function throws an exception if a file with specified name
* is not found or does not contain a valid space group.
*
* \param mesh spatial discretization grid
* \param unitCell crystallographic unitCell
* \param groupName string identifier for the space group
*/
void makeBasis(Mesh<D> const & mesh,
UnitCell<D> const & unitCell,
std::string groupName);
/**
* Print a list of all waves to an output stream.
*
* \param out output stream to which to write
* \param outputAll output cancelled waves only if true
*/
void outputWaves(std::ostream& out, bool outputAll = false) const;
/**
* Print a list of all stars to an output stream.
*
* \param out output stream to which to write
* \param outputAll output cancelled waves only if true
*/
void outputStars(std::ostream& out, bool outputAll = false) const;
/**
* Returns true if valid, false otherwise.
*/
bool isValid() const;
/**
* Returns true iff this basis is fully initialized.
*/
bool isInitialized() const;
// Accessors
/**
* Total number of wavevectors.
*/
int nWave() const;
/**
* Total number of wavevectors in uncancelled stars.
*/
int nBasisWave() const;
/**
* Total number of stars.
*/
int nStar() const;
/**
* Total number of nonzero symmetry-adapted basis functions.
*/
int nBasis() const;
/**
* Get a specific Wave, access by integer index.
*
* \param id index for a wave vector.
*/
Wave const & wave(int id) const;
/**
* Get a Star, accessed by integer star index.
*
* This function return both cancelled and un-cancelled stars.
*
* \param id index for a star
*/
Star const & star(int id) const;
/**
* Get an uncancelled Star, accessed by basis function index.
*
* \param id index for a basis function, or an uncancelled star.
*/
Star const & basisFunction(int id) const;
/**
* Get the integer index of a wave, as required by wave(int id).
*
* This function returns the index of a wavevector within the wave
* array, as required as in input to function Wave::wave(int id).
* The vector of input components is shifted internally to an
* equivalent value that lies within the conventional DFT mesh,
* in which all components are non-negative integers.
*
* \param vector vector of integer indices of a wave vector.
*/
int waveId(IntVec<D> vector) const;
private:
/**
* Array of all Wave objects (all wavevectors).
*
* Waves are ordered in non-decreasing order by wavevector norm, with
* waves in the same star order in a consecutive block, with waves in
* each star ordered by integer indices.
*
* The capacity of array stars_ is equal to nWave_, which is also equal
* to the number of points in the associated spatial mesh.
*/
DArray<Wave> waves_;
/**
* Array of Star objects (all stars of wavevectors).
*
* The final size of array stars_ is equal to nStar_.
*/
GArray<Star> stars_;
/**
* Look-up table for identification of waves by IntVec
*
* After allocation, the capacity_ of waveIds_ is equal to nWave_.
* The array index of each element of waveIds_ corresponds to the
* rank of the wavevector within a k-space DFT mesh, and the value
* is the index of the corresponding Wave within the waves_ array.
*/
DArray<int> waveIds_;
/**
* Look-up table for uncancelled stars index by basis function id.
*
* After allocation, the capacity_ of starIds_ is equal to nBasis_.
* The array index of each element of starIds_ corresponds to the
* index of a basis function, while the element value is the index
* of the corresponding un-cancelled Star in the stars_ array.
*/
DArray<int> starIds_;
/**
* Total number of wavevectors, including those in cancelled stars.
*
* This must equal the number of grid points in the mesh.
*/
int nWave_;
/**
* Total number of wavevectors in uncancelled stars
*/
int nBasisWave_;
/**
* Total number of stars, including cancelled stars.
*/
int nStar_;
/**
* Total number of basis functions, or uncancelled stars.
*/
int nBasis_;
/**
* Pointer to an associated UnitCell<D>
*/
UnitCell<D> const * unitCellPtr_;
/**
* Pointer to an associated Mesh<D>
*/
Mesh<D> const * meshPtr_;
/**
* Has this basis been fully initialized?
*/
bool isInitialized_;
/**
* Construct an array of ordered waves.
*/
void makeWaves();
/**
* Identify stars of wavevectors related by symmetry.
*/
void makeStars(const SpaceGroup<D>& group);
/**
* Access associated Mesh<D> as const reference.
*/
Mesh<D> const & mesh() const
{ return *meshPtr_; }
/**
* Access associated UnitCell<D> as const reference.
*/
UnitCell<D> const & unitCell() const
{ return *unitCellPtr_; }
};
// Inline functions
template <int D>
inline int Basis<D>::nWave() const
{ return nWave_; }
template <int D>
inline int Basis<D>::nBasisWave() const
{ return nBasisWave_; }
template <int D>
inline int Basis<D>::nStar() const
{ return nStar_; }
template <int D>
inline
typename Basis<D>::Wave const & Basis<D>::wave(int id) const
{ return waves_[id]; }
template <int D>
inline
typename Basis<D>::Star const & Basis<D>::star(int id) const
{ return stars_[id]; }
template <int D>
inline
typename Basis<D>::Star const & Basis<D>::basisFunction(int id) const
{ return stars_[starIds_[id]]; }
template <int D>
int Basis<D>::waveId(IntVec<D> vector) const
{
meshPtr_->shift(vector);
int rank = mesh().rank(vector);
return waveIds_[rank];
}
template <int D>
inline bool Basis<D>::isInitialized() const
{ return isInitialized_; }
#ifndef PSCF_BASIS_TPP
extern template class Basis<1>;
extern template class Basis<2>;
extern template class Basis<3>;
#endif
} // namespace Pscf
#endif
| 34,294
|
C++
|
.h
| 765
| 38.240523
| 76
| 0.672137
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,088
|
UnitCell.h
|
dmorse_pscfpp/src/pscf/crystal/UnitCell.h
|
#ifndef PSCF_UNIT_CELL_H
#define PSCF_UNIT_CELL_H
/*
* PSCF - Polymer Self-Consistent Field Theory
*
* Copyright 2016 - 2022, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include "UnitCellBase.h"
#include <iostream>
#include <iomanip>
namespace Pscf
{
using namespace Util;
/**
* Base template for UnitCell<D> classes, D=1, 2 or 3.
*
* Explicit specializations are defined for D=1, 2, and 3. In each
* case, class UnitCell<D> is derived from UnitCellBase<D> and defines
* an enumeration UnitCell<D>::LatticeSystem of the possible types of
* Bravais lattice systems in D-dimensional space. Each explicit
* specialization UnitCell<D> has a member variable of this type that
* is returned by a function named lattice(). The value of the lattice
* variable is initialized to an enumeration value named Null, which
* denotes unknown or unitialized.
*
* Iostream inserter (<<) and extractor (>>) operators are defined for
* all explicit specializations of UnitCell<D>, allowing a UnitCell
* to be read from or written to file like a primitive variable.
* The text representation for a UnitCell<D> contains a text
* representation of the LatticeSystem<D> enumeration (i.e., the
* unit cell type) and a list of one or more unit cell parameters
* (lengths and angles), as described \ref user_unitcell_page "here".
*
* \ingroup Pscf_Crystal_Module
*/
template <int D>
class UnitCell : public UnitCellBase<D>
{};
// Function declations (friends of explicit instantiations)
/**
* istream input extractor for a UnitCell<D>.
*
* \param in input stream
* \param cell UnitCell<D> to be read
* \return modified input stream
* \ingroup Pscf_Crystal_Module
*/
template <int D>
std::istream& operator >> (std::istream& in, UnitCell<D>& cell);
/**
* ostream output inserter for a UnitCell<D>.
*
* \param out output stream
* \param cell UnitCell<D> to be written
* \return modified output stream
* \ingroup Pscf_Crystal_Module
*/
template <int D>
std::ostream& operator << (std::ostream& out, UnitCell<D> const& cell);
/**
* Serialize to/from an archive.
*
* \param ar input or output archive
* \param cell UnitCell<D> object to be serialized
* \param version archive version id
* \ingroup Pscf_Crystal_Module
*/
template <class Archive, int D>
void
serialize(Archive& ar, UnitCell<D>& cell, const unsigned int version);
/**
* Read UnitCell<D> from a field file header (fortran PSCF format).
*
* If the unit cell has a non-null lattice system on entry, the
* value read from file must match this existing value, or this
* function throws an exception. If the lattice system is null on
* entry, the lattice system value is read from file. In either case,
* unit cell parameters (dimensions and angles) are updated using
* values read from file.
*
* \param in input stream
* \param cell UnitCell<D> to be read
* \ingroup Pscf_Crystal_Module
*/
template <int D>
void readUnitCellHeader(std::istream& in, UnitCell<D>& cell);
/**
* Write UnitCell<D> to a field file header (fortran PSCF format).
*
* \param out output stream
* \param cell UnitCell<D> to be written
* \ingroup Pscf_Crystal_Module
*/
template <int D>
void writeUnitCellHeader(std::ostream& out, UnitCell<D> const& cell);
/*
* Read common part of field header (fortran PSCF format).
*
* \param ver1 major file format version number (output)
* \param ver2 major file format version number (output)
* \param cell UnitCell<D> object (output)
* \param groupName string identifier for space group (output)
* \param nMonomer number of monomers (output)
* \ingroup Pscf_Crystal_Module
*/
template <int D>
void readFieldHeader(std::istream& in, int& ver1, int& ver2,
UnitCell<D>& cell, std::string& groupName,
int& nMonomer);
/*
* Write common part of field header (fortran PSCF format).
*
* \param ver1 major file format version number (input)
* \param ver2 major file format version number (input)
* \param cell UnitCell<D> object (input)
* \param groupName string identifier for space group (input)
* \param nMonomer number of monomers (input)
* \ingroup Pscf_Crystal_Module
*/
template <int D>
void writeFieldHeader(std::ostream &out, int ver1, int ver2,
UnitCell<D> const & cell,
std::string const & groupName,
int nMonomer);
// 1D Unit Cell
/**
* 1D crystal unit cell.
*
* \ingroup Pscf_Crystal_Module
*/
template <>
class UnitCell<1> : public UnitCellBase<1>
{
public:
/**
* Enumeration of 1D lattice system types.
*/
enum LatticeSystem {Lamellar, Null};
/**
* Constructor
*/
UnitCell();
/**
* Assignment operator.
*
* \param other UnitCell<1> object to be cloned.
*/
UnitCell<1>& operator = (const UnitCell<1>& other);
/**
* Set the lattice system, but not unit cell parameters.
*
* Upon return, values of lattice and nParameter are set.
*
* \param lattice lattice system enumeration value
*/
void set(UnitCell<1>::LatticeSystem lattice);
/**
* Set the unit cell state (lattice system and parameters).
*
* \param lattice lattice system enumeration value
* \param parameters array of unit cell parameters
*/
void set(UnitCell<1>::LatticeSystem lattice,
FSArray<double, 6> const & parameters);
/**
* Return lattice system enumeration value.
*
* This value is initialized to Null during construction.
*/
LatticeSystem lattice() const
{ return lattice_; }
using UnitCellBase<1>::isInitialized;
private:
// Lattice type (lamellar or Null)
LatticeSystem lattice_;
// Set number of parameters required to describe current lattice type
void setNParameter();
// Set all internal data after setting parameter values
void setBasis();
// Private and unimplemented to prevent copy construction.
UnitCell(UnitCell<1> const &);
// friends:
template <int D>
friend std::istream& operator >> (std::istream&, UnitCell<D>& );
template <int D>
friend std::ostream& operator << (std::ostream&, UnitCell<D> const&);
template <class Archive, int D>
friend void serialize(Archive& , UnitCell<D>& , const unsigned int);
template <int D>
friend void readUnitCellHeader(std::istream&, UnitCell<D>& );
template <int D>
friend void writeUnitCellHeader(std::ostream&, UnitCell<D> const&);
};
/**
* istream extractor for a 1D UnitCell<1>::LatticeSystem.
*
* \param in input stream
* \param lattice UnitCell<1>::LatticeSystem to be read
* \return modified input stream
* \ingroup Pscf_Crystal_Module
*/
std::istream& operator >> (std::istream& in,
UnitCell<1>::LatticeSystem& lattice);
/**
* ostream inserter for a 1D UnitCell<1>::LatticeSystem.
*
* \param out output stream
* \param lattice UnitCell<1>::LatticeSystem to be written
* \return modified output stream
* \ingroup Pscf_Crystal_Module
*/
std::ostream& operator << (std::ostream& out,
UnitCell<1>::LatticeSystem lattice);
/**
* Serialize a UnitCell<1>::LatticeSystem enumeration value
*
* \param ar archive
* \param lattice enumeration data to be serialized
* \param version version id
*/
template <class Archive>
inline
void serialize(Archive& ar, UnitCell<1>::LatticeSystem& lattice,
const unsigned int version)
{ serializeEnum(ar, lattice, version); }
// 2D Unit Cell
/**
* 2D crystal unit cell.
*
* \ingroup Pscf_Crystal_Module
*/
template <>
class UnitCell<2> : public UnitCellBase<2>
{
public:
/**
* Enumeration of 2D lattice system types.
*/
enum LatticeSystem {Square, Rectangular, Rhombic, Hexagonal,
Oblique, Null};
/**
* Constructor
*/
UnitCell();
/**
* Assignment operator.
*
* \param other UnitCell<2> object to be cloned.
*/
UnitCell<2>& operator = (const UnitCell<2>& other);
/**
* Set the lattice system, but not unit cell parameters.
*
* Upon return, values of lattice and nParameter are set.
*
* \param lattice lattice system enumeration value
*/
void set(UnitCell<2>::LatticeSystem lattice);
/**
* Set the unit cell state (lattice system and parameters).
*
* \param lattice lattice system enumeration value
* \param parameters array of unit cell parameters
*/
void set(UnitCell<2>::LatticeSystem lattice,
FSArray<double, 6> const & parameters);
/**
* Return lattice system enumeration value.
*
* This value is initialized to Null during construction.
*/
LatticeSystem lattice() const
{ return lattice_; }
private:
// Lattice system (square, rectangular, etc.)
LatticeSystem lattice_;
// Set number of parameters required to describe current lattice type
void setNParameter();
// Set all internal data after setting parameter values
void setBasis();
// Private and unimplemented to prevent copy construction.
UnitCell(UnitCell<2> const &);
// friends:
template <int D>
friend std::istream& operator >> (std::istream&, UnitCell<D>& );
template <int D>
friend std::ostream& operator << (std::ostream&, UnitCell<D> const&);
template <class Archive, int D>
friend void serialize(Archive& , UnitCell<D>& , const unsigned int );
template <int D>
friend void readUnitCellHeader(std::istream&, UnitCell<D>& );
template <int D>
friend void writeUnitCellHeader(std::ostream&, UnitCell<D> const&);
};
/**
* istream extractor for a 2D UnitCell<2>::LatticeSystem.
*
* \param in input stream
* \param lattice UnitCell<2>::LatticeSystem to be read
* \return modified input stream
* \ingroup Pscf_Crystal_Module
*/
std::istream& operator >> (std::istream& in,
UnitCell<2>::LatticeSystem& lattice);
/**
* ostream inserter for a 2D UnitCell<2>::LatticeSystem.
*
* \param out output stream
* \param lattice UnitCell<2>::LatticeSystem to be written
* \return modified output stream
*/
std::ostream& operator << (std::ostream& out,
UnitCell<2>::LatticeSystem lattice);
/**
* Serialize a UnitCell<2>::LatticeSystem enumeration value
*
* \param ar archive
* \param lattice enumeration data to be serialized
* \param version version id
*/
template <class Archive>
inline
void serialize(Archive& ar, UnitCell<2>::LatticeSystem& lattice,
const unsigned int version)
{ serializeEnum(ar, lattice, version); }
// 3D crystal unit cell
/**
* 3D crystal unit cell.
*
* \ingroup Pscf_Crystal_Module
*/
template <>
class UnitCell<3> : public UnitCellBase<3>
{
public:
/**
* Enumeration of the 7 possible 3D Bravais lattice systems.
*
* Allowed non-null values are: Cubic, Tetragonal, Orthorhombic,
* Monoclinic, Triclinic, Rhombohedral, and Hexagonal.
*/
enum LatticeSystem {Cubic, Tetragonal, Orthorhombic, Monoclinic,
Triclinic, Rhombohedral, Hexagonal, Null};
/**
* Constructor
*/
UnitCell();
/**
* Assignment operator.
*
* \param other UnitCell<3> object to be cloned.
*/
UnitCell<3>& operator = (const UnitCell<3>& other);
/**
* Set the lattice system, but not unit cell parameters.
*
* Upon return, values of lattice and nParameter are set.
*
* \param lattice lattice system enumeration value
*/
void set(UnitCell<3>::LatticeSystem lattice);
/**
* Set the unit cell state.
*
* \param lattice lattice system enumeration value
* \param parameters array of unit cell parameters
*/
void set(UnitCell<3>::LatticeSystem lattice,
FSArray<double, 6> const & parameters);
/**
* Return lattice system enumeration value.
*
* This value is initialized to Null during construction.
*/
LatticeSystem lattice() const
{ return lattice_; }
private:
LatticeSystem lattice_;
// Set number of parameters required to describe current lattice type
void setNParameter();
// Set all internal data after setting parameter values
void setBasis();
// Private and unimplemented to prevent copy construction.
UnitCell(UnitCell<3> const &);
// friends:
template <int D>
friend std::istream& operator >> (std::istream&, UnitCell<D>& );
template <int D>
friend std::ostream& operator << (std::ostream&, UnitCell<D> const&);
template <class Archive, int D>
friend void serialize(Archive& , UnitCell<D>& , const unsigned int);
template <int D>
friend void readUnitCellHeader(std::istream&, UnitCell<D>& );
template <int D>
friend void writeUnitCellHeader(std::ostream&, UnitCell<D> const&);
};
/**
* istream extractor for a 3D UnitCell<3>::LatticeSystem.
*
* \param in input stream
* \param lattice UnitCell<3>::LatticeSystem to be read
* \return modified input stream
* \ingroup Pscf_Crystal_Module
*/
std::istream& operator >> (std::istream& in,
UnitCell<3>::LatticeSystem& lattice);
/**
* ostream inserter for an 3D UnitCell<3>::LatticeSystem.
*
* \param out output stream
* \param lattice UnitCell<3>::LatticeSystem to be written
* \return modified output stream
* \ingroup Pscf_Crystal_Module
*/
std::ostream& operator << (std::ostream& out,
UnitCell<3>::LatticeSystem lattice);
/**
* Serialize a UnitCell<3>::LatticeSystem enumeration value
*
* \param ar archive
* \param lattice enumeration data to be serialized
* \param version version id
*/
template <class Archive>
inline
void serialize(Archive& ar, UnitCell<3>::LatticeSystem& lattice,
const unsigned int version)
{ serializeEnum(ar, lattice, version); }
}
#include "UnitCell.tpp"
#endif
| 15,002
|
C++
|
.h
| 432
| 28.469907
| 75
| 0.643996
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,089
|
groupFile.h
|
dmorse_pscfpp/src/pscf/crystal/groupFile.h
|
#ifndef PSSP_GROUP_FILE_H
#define PSSP_GROUP_FILE_H
/*
* PSCF - Polymer Self-Consistent Field Theory
*
* Copyright 2016 - 2022, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include <string>
namespace Pscf {
/**
* Generates the file name from a group name.
*
* \param D dimensionality of space (D=1,2 or 3)
* \param groupName standard name of space group
* \ingroup Pscf_Crystal_Module
*/
std::string makeGroupFileName(int D, std::string groupName);
} // namespace Pscf
#endif
| 574
|
C++
|
.h
| 20
| 26.15
| 67
| 0.733577
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,090
|
UnitCellBase.h
|
dmorse_pscfpp/src/pscf/crystal/UnitCellBase.h
|
#ifndef PSCF_UNIT_CELL_BASE_H
#define PSCF_UNIT_CELL_BASE_H
/*
* PSCF - Polymer Self-Consistent Field Theory
*
* Copyright 2016 - 2022, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include <util/containers/FArray.h>
#include <util/containers/FSArray.h>
#include <util/containers/FMatrix.h>
#include <pscf/math/IntVec.h>
#include <pscf/math/RealVec.h>
#include <util/math/Constants.h>
namespace Pscf
{
using namespace Util;
/**
* Base class template for a crystallographic unit cell.
*
* \ingroup Pscf_Crystal_Module
*/
template <int D>
class UnitCellBase
{
public:
/**
* Constructor.
*/
UnitCellBase();
/**
* Destructor.
*/
~UnitCellBase();
/**
* Set all the parameters of unit cell.
*
* The lattice system must already be set to a non-null value.
*
* \param parameters array of unit cell parameters
*/
void setParameters(FSArray<double, 6> const & parameters);
/**
* Compute square magnitude of reciprocal lattice vector.
*
* \param k vector of components of a reciprocal lattice vector
*/
virtual double ksq(IntVec<D> const & k) const;
/**
* Compute derivative of square wavevector w/respect to cell parameter.
*
* This function computes and returns a derivative with respect to
* unit cell parameter number n of the square of a reciprocal lattice
* vector with integer coefficients given by the elements of vec.
*
* \param vec vector of components of a reciprocal lattice vector
* \param n index of a unit cell parameter
*/
virtual double dksq(IntVec<D> const & vec, int n) const;
/**
* Get the number of parameters in the unit cell.
*/
int nParameter() const;
/**
* Get the parameters of this unit cell.
*/
FSArray<double, 6> parameters() const;
/**
* Get a single parameter of this unit cell.
*
* \param i array index of the desired parameter
*/
double parameter(int i) const;
/**
* Get Bravais basis vector i, denoted by a_i.
*
* \param i array index of the desired Bravais basis vector
*/
const RealVec<D>& rBasis(int i) const;
/**
* Get reciprocal basis vector i, denoted by b_i.
*
* \param i array index of the desired reciprocal basis vector
*/
const RealVec<D>& kBasis(int i) const;
/**
* Get component j of derivative of rBasis vector a_i w/respect to k.
*
* \param k index of cell parameter
* \param i index of the desired basis vector a_i
* \param j index of a Cartesian component of a_i
*/
double drBasis(int k, int i, int j) const;
/**
* Get component j of derivative of kBasis vector b_i w/respect to k.
*
* \param k index of cell parameter
* \param i array index of the desired reciprocal basis vector b_i
* \param j index of a Cartesian component of b_i
*/
double dkBasis(int k, int i, int j) const;
/**
* Get derivative of dot product ai.aj with respect to parameter k.
*
* \param k index of cell parameter
* \param i array index of 1st Bravais basis vector a_i
* \param j array index of 2nd Bravais basis vector a_i
*/
double drrBasis(int k, int i, int j) const;
/**
* Get derivative of dot product bi.bj with respect to parameter k.
*
* \param k index of cell parameter
* \param i array index of 1st reciprocal basis vector b_i
* \param j array index of 2nd reciprocal basis vector b_i
*/
double dkkBasis(int k, int i, int j) const;
/**
* Has this unit cell been initialized?
*/
bool isInitialized() const
{ return isInitialized_; }
protected:
/**
* Array of Bravais lattice basis vectors.
*/
FArray<RealVec<D>, D> rBasis_;
/**
* Array of reciprocal lattice basis vectors.
*/
FArray<RealVec<D>, D> kBasis_;
/**
* Array of derivatives of rBasis.
*
* Element drBasis_[k](i,j) is the derivative with respect to
* parameter k of component j of Bravais basis vector i.
*/
FArray<FMatrix<double, D, D>, 6> drBasis_;
/**
* Array of derivatives of kBasis
*
* Element dkBasis_[k](i,j) is the derivative with respect to
* parameter k of component j of reciprocal basis vector i.
*/
FArray<FMatrix<double, D, D>, 6> dkBasis_;
/**
* Array of derivatives of a_i.a_j
*
* Element drrBasis_[k](i,j) is the derivative with respect
* to parameter k of the dot product (a_i.a_j) of Bravais
* lattice basis vectors a_i and a_j.
*/
FArray<FMatrix<double, D, D>, 6> drrBasis_;
/**
* Array of derivatives of b_i.b_j
*
* Element dkkBasis_[k](i,j) is the derivative with respect
* to parameter k of the dot product (b_i.b_j) of reciprocal
* lattice basis vectors b_i and b_j.
*/
FArray<FMatrix<double, D, D>, 6> dkkBasis_;
/**
* Parameters used to describe the unit cell.
*/
FArray<double, 6> parameters_;
/**
* Number of parameters required to specify unit cell.
*/
int nParameter_;
/**
* Has this unit cell been fully initialized?
*/
bool isInitialized_;
/**
* Compute all private data, given latticeSystem and parameters.
*
* Calls initializeToZero, setBasis, computeDerivatives internally.
*/
void setLattice();
private:
/**
* Initialize all arrays to zero.
*
* Sets all elements of the following arrays to zero:
* rBasis_, kBasis_, drBasis_, dkBasis, drrBasis_ and dkkBasis_.
*/
void initializeToZero();
/**
* Set values of rBasis, kBasis, and drBasis.
*
* Invoke initializeToZero before this, computeDerivatives after.
*
* \pre Lattice system, nParam and parameters must be set.
*/
virtual void setBasis() = 0;
/**
* Compute values of dkBasis_, drrBasis_, and dkkBasis_.
*/
void computeDerivatives();
};
/*
* Get the number of Parameters in the unit cell.
*/
template <int D>
inline
int UnitCellBase<D>::nParameter() const
{ return nParameter_; }
/*
* Get the unit cell parameters.
*/
template <int D>
inline
FSArray<double, 6> UnitCellBase<D>::parameters() const
{
FSArray<double, 6> parameters;
for (int i = 0; i < nParameter_; ++i) {
parameters.append(parameters_[i]);
}
return parameters;
}
/*
* Get a single parameter of the unit cell.
*/
template <int D>
inline
double UnitCellBase<D>::parameter(int i) const
{ return parameters_[i]; }
/*
* Get Bravais basis vector i.
*/
template <int D>
inline
const RealVec<D>& UnitCellBase<D>::rBasis(int i) const
{ return rBasis_[i]; }
/*
* Get reciprocal basis vector i.
*/
template <int D>
inline
const RealVec<D>& UnitCellBase<D>::kBasis(int i) const
{ return kBasis_[i]; }
/*
* Get component j of derivative of r basis vector i w/respect to param k.
*/
template <int D>
inline
double UnitCellBase<D>::drBasis(int k, int i, int j) const
{ return drBasis_[k](i,j); }
/*
* Get component j of derivative of r basis vector i w/respect to param k.
*/
template <int D>
inline
double UnitCellBase<D>::dkBasis(int k, int i, int j) const
{ return dkBasis_[k](i, j); }
/*
* Get the derivative of ki*kj with respect to parameter k.
*/
template <int D>
inline
double UnitCellBase<D>::dkkBasis(int k, int i, int j) const
{ return dkkBasis_[k](i, j); }
/*
* Get the derivative of ri*rj with respect to parameter k.
*/
template <int D>
inline
double UnitCellBase<D>::drrBasis(int k, int i, int j) const
{ return drrBasis_[k](i, j); }
// Non-inline member functions
/*
* Constructor.
*/
template <int D>
UnitCellBase<D>::UnitCellBase()
: nParameter_(0),
isInitialized_(false)
{}
/*
* Destructor.
*/
template <int D>
UnitCellBase<D>::~UnitCellBase()
{}
/*
* Set all the parameters in the unit cell.
*/
template <int D>
void UnitCellBase<D>::setParameters(FSArray<double, 6> const& parameters)
{
UTIL_CHECK(parameters.size() == nParameter_);
isInitialized_ = false;
for (int i = 0; i < nParameter_; ++i) {
parameters_[i] = parameters[i];
}
setLattice();
}
/*
* Get square magnitude of reciprocal basis vector.
*/
template <int D>
double UnitCellBase<D>::ksq(IntVec<D> const & k) const
{
RealVec<D> g(0.0);
RealVec<D> p;
for (int i = 0; i < D; ++i) {
p.multiply(kBasis_[i], k[i]);
g += p;
}
double value = 0.0;
for (int i = 0; i < D; ++i) {
value += g[i]*g[i];
}
return value;
}
/*
* Get magnitude of derivative of square of reciprocal basis vector.
*/
template <int D>
double UnitCellBase<D>::dksq(IntVec<D> const & vec, int n) const
{
double element = 0.0;
double value = 0.0;
for (int p = 0; p < D; ++p){
for (int q = 0; q < D; ++q){
element = dkkBasis(n, p, q);
value += vec[p]*vec[q]*element;
}
}
return value;
}
// Protected member functions
/*
* Initialize internal arrays to zero.
*/
template <int D>
void UnitCellBase<D>::initializeToZero()
{
// Initialize all elements to zero
int i, j, k;
for (i = 0; i < D; ++i) {
for (j = 0; j < D; ++j) {
rBasis_[i][j] = 0.0;
kBasis_[i][j] = 0.0;
}
}
for (k = 0; k < 6; ++k){
for (i = 0; i < D; ++i) {
for (j = 0; j < D; ++j) {
drBasis_[k](i,j) = 0.0;
dkBasis_[k](i,j) = 0.0;
drrBasis_[k](i,j) = 0.0;
dkkBasis_[k](i,j) = 0.0;
}
}
}
}
/*
* Compute quantities involving derivatives.
*/
template <int D>
void UnitCellBase<D>::computeDerivatives()
{
// Compute dkBasis
int p, q, r, s, t;
for (p = 0; p < nParameter_; ++p) {
for (q = 0; q < D; ++q) {
for (r = 0; r < D; ++r) {
// Loop over free indices s, t
for (s = 0; s < D; ++s) {
for (t = 0; t < D; ++t) {
dkBasis_[p](q,r)
-= kBasis_[q][s]*drBasis_[p](t,s)*kBasis_[t][r];
}
}
dkBasis_[p](q,r) /= 2.0*Constants::Pi;
}
}
}
// Compute drrBasis and dkkBasis
for (p = 0; p < nParameter_; ++p) {
for (q = 0; q < D; ++q) {
for (r = 0; r < D; ++r) {
for (s = 0; s < D; ++s) {
drrBasis_[p](q,r) += rBasis_[q][s]*drBasis_[p](r,s);
drrBasis_[p](q,r) += rBasis_[r][s]*drBasis_[p](q,s);
dkkBasis_[p](q,r) += kBasis_[q][s]*dkBasis_[p](r,s);
dkkBasis_[p](q,r) += kBasis_[r][s]*dkBasis_[p](q,s);
}
}
}
}
}
/*
* Set all lattice parameters.
*/
template <int D>
void UnitCellBase<D>::setLattice()
{
initializeToZero();
setBasis();
computeDerivatives();
isInitialized_ = true;
}
}
#endif
| 11,785
|
C++
|
.h
| 406
| 22.37931
| 76
| 0.568019
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,091
|
SpaceSymmetry.h
|
dmorse_pscfpp/src/pscf/crystal/SpaceSymmetry.h
|
#ifndef PSCF_SPACE_SYMMETRY_H
#define PSCF_SPACE_SYMMETRY_H
/*
* PSCF - Polymer Self-Consistent Field Theory
*
* Copyright 2016 - 2022, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include <pscf/math/IntVec.h>
#include <util/math/Rational.h>
#include <util/containers/FMatrix.h>
#include <util/containers/FArray.h>
#include <util/format/Int.h>
#include <iostream>
namespace Pscf {
using namespace Util;
template <int D> class SpaceSymmetry;
// Non-member function declarations
/**
* Are two SpaceSymmetry objects equivalent?
*
* \param A first symmetry
* \param B second symmetry
* \return True if A == B, false otherwise
* \ingroup Pscf_Crystal_Module
*/
template <int D>
bool operator == (const SpaceSymmetry<D>& A, const SpaceSymmetry<D>& B);
/**
* Are two SpaceSymmetry objects not equivalent?
*
* \param A first symmetry
* \param B second symmetry
* \return True if A != B, false otherwise
* \ingroup Pscf_Crystal_Module
*/
template <int D>
bool operator != (const SpaceSymmetry<D>& A, const SpaceSymmetry<D>& B);
/**
* Return the product A*B of two symmetry objects.
*
* \param A first symmetry
* \param B second symmetry
* \return product A*B
* \ingroup Pscf_Crystal_Module
*/
template <int D>
SpaceSymmetry<D>
operator * (const SpaceSymmetry<D>& A, const SpaceSymmetry<D>& B);
/**
* Return the IntVec<D> product S*V of a rotation matrix and an IntVec<D>.
*
* The product is defined to be the matrix product of the rotation matrix
* and the integer vector S.R * V.
*
* \param S symmetry operation
* \param V integer vector
* \return product S*V
* \ingroup Pscf_Crystal_Module
*/
template <int D>
IntVec<D> operator * (const SpaceSymmetry<D>& S, const IntVec<D>& V);
/**
* Return the IntVec<D> product V*S of an IntVec<D> and a rotation matrix.
*
* The product is defined to be the matrix product of the integer vector
* and the space group rotation matrix S.R * V.
*
* \param V integer vector
* \param S symmetry operation
* \return product V*S
* \ingroup Pscf_Crystal_Module
*/
template <int D>
IntVec<D> operator * (const IntVec<D>& V, const SpaceSymmetry<D>& S);
/**
* Output stream inserter for a SpaceSymmetry<D>
*
* \param out output stream
* \param A SpaceSymmetry<D> object to be output
* \return modified output stream
* \ingroup Pscf_Crystal_Module
*/
template <int D>
std::ostream& operator << (std::ostream& out, const SpaceSymmetry<D>& A);
/**
* Input stream extractor for a SpaceSymmetry<D>
*
* \param in input stream
* \param A SpaceSymmetry<D> object to be input
* \return modified input stream
* \ingroup Pscf_Crystal_Module
*/
template <int D>
std::istream& operator >> (std::istream& in, SpaceSymmetry<D>& A);
/**
* A SpaceSymmetry represents a crystallographic space group symmetry.
*
* Crystallographic space group symmetry operation combines a point group
* operation (e.g., 2, 3, and 4 fold rotations about axes, reflections, or
* inversion) with possible translations by a fraction of a unit cell.
*
* Both the rotation matrix R and the translation t are represented using
* a basis of Bravais lattice basis vectors. Because Bravais basis vectors
* must map onto other lattice vectors, this implies that elements of all
* elements of the rotation matrix must be integers. To guarantee that the
* inverse of the rotation matrix is also a matrix of integers, we require
* that the determinant of the rotation matrix must be +1 or -1. The
* translation vector is represented by a vector of D rational numbers
* (i.e., fractions) of the form n/m with m = 2, 3, or 4 and n < m.
*
* The basis used to describe a crytallographic group may be either a
* primitive or non-primitive unit cell. Thus, for example, the space
* group of a bcc crystal may be expressed either using a basis of 3
* three orthogonal simple cubic unit vectors, with a translation
* t = (1/2, 1/2, 1/2), or as a point group using a set of three
* non-orthogonal basis vectors for the primitive unit cell.
*
* \ingroup Pscf_Crystal_Module
*/
template <int D>
class SpaceSymmetry
{
public:
/// Typedef for matrix used to represent point group operation.
typedef FMatrix<int, D, D> Rotation;
/// Typedef for vector used to represent fractional translation.
typedef FArray<Rational, D> Translation;
/**
* Default constructor.
*
* All elements of the rotation matrix are initialized to zero.
*/
SpaceSymmetry();
/**
* Copy constructor.
*/
SpaceSymmetry(const SpaceSymmetry<D>& other);
/**
* Assignment operator.
*/
SpaceSymmetry<D>& operator = (const SpaceSymmetry<D>& other);
/**
* Shift components of translation to [0,1).
*/
void normalize();
/**
* Shift the origin of space used in the coordinate system.
*
* This function modifies the translation vector so as to refer to
* an equivalent symmetry defined using a new coordinate system
* with a shifted origin. The argument gives the coordinates of
* the origin of the new coordinate system as defined in the old
* coordinate system.
*
* \param origin location of origin of the new coordinate system
*/
void shiftOrigin(Translation const & origin);
/**
* Compute and return the inverse of this symmetry element.
*/
SpaceSymmetry<D> inverse() const;
/**
* Compute and return the inverse of the rotation matrix.
*/
SpaceSymmetry<D>::Rotation inverseRotation() const;
/**
* Compute and return the determinant of the rotation matrix.
*/
int determinant() const;
/**
* Return an element of the matrix by reference.
*
* \param i 1st (row) index
* \param j 2nd (column) index
*/
int& R(int i, int j);
/**
* Return an element of the matrix by value.
*
* \param i 1st (row) index
* \param j 2nd (column) index
*/
int R(int i, int j) const;
/**
* Return a component of the translation by reference.
*
* \param i component index
*/
Rational& t(int i);
/**
* Return an element of the translation by value.
*
* \param i component index
*/
Rational t(int i) const;
// Static method
/**
* Return the identity element.
*/
static const SpaceSymmetry<D>& identity();
private:
/**
* Matrix representation of point group operation.
*
* Because it is expressed in a Bravais basis, and Bravais lattice
* vectors must map onto other Bravais lattice vectors, elements of
* this matrix are integers.
*/
Rotation R_;
/**
* Translation vector
*/
Translation t_;
// Static member variables
/// Identity element (static member stored for reference)
static SpaceSymmetry<D> identity_;
/// Has the static identity_ been constructed?
static bool hasIdentity_;
/// Construct static identity_ object.
static void makeIdentity();
// friends:
friend
bool operator == <> (const SpaceSymmetry<D>& A,
const SpaceSymmetry<D>& B);
friend
bool operator != <> (const SpaceSymmetry<D>& A,
const SpaceSymmetry<D>& B);
friend
SpaceSymmetry<D>
operator * <> (const SpaceSymmetry<D>& A,
const SpaceSymmetry<D>& B);
friend
IntVec<D> operator * <> (const IntVec<D>& V,
const SpaceSymmetry<D>& S);
friend
IntVec<D> operator * <>(const SpaceSymmetry<D>& S, const IntVec<D>& V);
friend
std::ostream& operator << <> (std::ostream& out,
const SpaceSymmetry<D>& A);
friend
std::istream& operator >> <> (std::istream& in,
SpaceSymmetry<D>& A);
};
// Explicit specialization of members
template <>
SpaceSymmetry<1>::Rotation SpaceSymmetry<1>::inverseRotation() const;
template <>
SpaceSymmetry<2>::Rotation SpaceSymmetry<2>::inverseRotation() const;
template <>
SpaceSymmetry<3>::Rotation SpaceSymmetry<3>::inverseRotation() const;
template <>
int SpaceSymmetry<1>::determinant() const;
template <>
int SpaceSymmetry<2>::determinant() const;
template <>
int SpaceSymmetry<3>::determinant() const;
// Inline method definitions
template <int D>
inline
bool operator != (const SpaceSymmetry<D>& A, const SpaceSymmetry<D>& B)
{ return !(A == B); }
/*
* Return an element of the matrix by reference.
*/
template <int D>
inline
int& SpaceSymmetry<D>::R(int i, int j)
{ return R_(i, j); }
/*
* Return an element of the matrix by value
*/
template <int D>
inline
int SpaceSymmetry<D>::R(int i, int j) const
{ return R_(i, j); }
/*
* Return an element of the translation vector by reference.
*/
template <int D>
inline
Rational& SpaceSymmetry<D>::t(int i)
{ return t_[i]; }
/*
* Return an element of the translation vector by value
*/
template <int D>
inline
Rational SpaceSymmetry<D>::t(int i) const
{ return t_[i]; }
/*
* Return the identity symmetry operation.
*/
template <int D>
inline
const SpaceSymmetry<D>& SpaceSymmetry<D>::identity()
{
if (!hasIdentity_) makeIdentity();
return identity_;
}
// Friend function template definitions
/*
* Equality operator.
*/
template <int D>
bool operator == (const SpaceSymmetry<D>& A, const SpaceSymmetry<D>& B)
{
int i, j;
for (i = 0; i < D; ++i) {
if (A.t_[i] != B.t_[i]) {
return false;
}
for (j = 0; j < D; ++j) {
if (A.R_(i, j) != B.R_(i,j)) {
return false;
}
}
}
return true;
}
/*
* Group multipication operator for SpaceSymmetry<D> objects.
*/
template <int D>
SpaceSymmetry<D>
operator * (const SpaceSymmetry<D>& A, const SpaceSymmetry<D>& B)
{
SpaceSymmetry<D> C;
int i, j, k;
// Compute rotation matrix (matrix product)
for (i = 0; i < D; ++i) {
for (j = 0; j < D; ++j) {
C.R_(i, j) = 0;
for (k = 0; k < D; ++k) {
C.R_(i, j) += A.R_(i, k)*B.R_(k, j);
}
}
}
// Compute translation vector
for (i = 0; i < D; ++i) {
C.t_[i] = A.t_[i];
}
for (i = 0; i < D; ++i) {
for (j = 0; j < D; ++j) {
C.t_[i] += A.R_(i, j)*B.t_[j];
}
}
C.normalize();
return C;
}
/*
* Matrix / IntVec<D> multiplication.
*/
template <int D>
IntVec<D> operator * (const SpaceSymmetry<D>& S, const IntVec<D>& V)
{
IntVec<D> U;
int i, j;
for (i = 0; i < D; ++i) {
U[i] = 0;
for (j = 0; j < D; ++j) {
U[i] += S.R_(i,j)*V[j];
}
}
return U;
}
/*
* IntVec<D> / Matrix multiplication.
*/
template <int D>
IntVec<D> operator * (const IntVec<D>& V, const SpaceSymmetry<D>& S)
{
IntVec<D> U;
int i, j;
for (i = 0; i < D; ++i) {
U[i] = 0;
for (j = 0; j < D; ++j) {
U[i] += V[j]*S.R_(j,i);
}
}
return U;
}
/*
* Output stream inserter for a SpaceSymmetry<D>.
*/
template <int D>
std::ostream& operator << (std::ostream& out, const SpaceSymmetry<D>& A)
{
int i, j;
for (i = 0; i < D; ++i) {
for (j = 0; j < D; ++j) {
out << " " << Int(A.R_(i,j),2);
}
out << std::endl;
}
for (i = 0; i < D; ++i) {
out << " " << A.t_[i];
}
out << std::endl;
return out;
}
/*
* Input stream extractor for a SpaceSymmetry<D>.
*/
template <int D>
std::istream& operator >> (std::istream& in, SpaceSymmetry<D>& A)
{
int i, j;
for (i = 0; i < D; ++i) {
for (j = 0; j < D; ++j) {
in >> A.R_(i,j);
}
}
for (i = 0; i < D; ++i) {
in >> A.t_[i];
}
return in;
}
// Define static members
template<int D>
SpaceSymmetry<D> SpaceSymmetry<D>::identity_ = SpaceSymmetry<D>();
template<int D>
bool SpaceSymmetry<D>::hasIdentity_ = false;
#ifndef PSCF_SPACE_SYMMETRY_TPP
// Suppress implicit instantiation
extern template class SpaceSymmetry<1>;
extern template class SpaceSymmetry<2>;
extern template class SpaceSymmetry<3>;
#endif
}
#endif
| 13,122
|
C++
|
.h
| 431
| 24.232019
| 78
| 0.595559
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,092
|
TWave.h
|
dmorse_pscfpp/src/pscf/crystal/TWave.h
|
#ifndef PSSP_TWAVE_H
#define PSSP_TWAVE_H
/*
* PSCF - Polymer Self-Consistent Field Theory
*
* Copyright 2016 - 2022, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include <pscf/math/IntVec.h>
namespace Pscf {
using namespace Util;
/**
* Simple wave struct for use within Basis construction.
*
* \ingroup Pscf_Crystal_Module
*/
template <int D>
struct TWave
{
double sqNorm;
double phase;
IntVec<D> indicesDft;
IntVec<D> indicesBz;
};
/**
* Comparator for TWave objects, based on TWave::sqNorm.
*
* Used to sort in ascending order of wavevector norm.
*
* \ingroup Pscf_Crystal_Module
*/
template <int D>
struct TWaveNormComp {
/**
* Function (a, b) returns true iff a.sqNorm < b.sqNorm.
*/
bool operator() (const TWave<D>& a, const TWave<D>& b) const
{ return (a.sqNorm < b.sqNorm); }
};
/**
* Comparator for TWave objects, based on TWave::indicesDft.
*
* Used to sort set of unique waves in ascending order of dft indices.
*
* \ingroup Pscf_Crystal_Module
*/
template <int D>
struct TWaveDftComp {
/**
* Function (a, b) returns true iff a.indicesDft < b.indicesDft
*/
bool operator() (const TWave<D>& a, const TWave<D>& b) const
{ return (a.indicesDft < b.indicesDft); }
};
/**
* Comparator for TWave objects, based on TWave::indicesBz.
*
* Used to sort in descending order of Bz (Brillouin zone) indices.
*
* \ingroup Pscf_Crystal_Module
*/
template <int D>
struct TWaveBzComp {
/**
* Function (a, b) returns true iff a.indicesBz > b.indicesBz
*/
bool operator() (const TWave<D>& a, const TWave<D>& b) const
{ return (a.indicesBz > b.indicesBz); }
};
} // namespace Pscf
#endif
| 1,900
|
C++
|
.h
| 71
| 22.225352
| 72
| 0.64022
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,093
|
shiftToMinimum.h
|
dmorse_pscfpp/src/pscf/crystal/shiftToMinimum.h
|
#ifndef PSCF_SHIFT_MINIMUM_H
#define PSCF_SHIFT_MINIMUM_H
/*
* PSCF - Polymer Self-Consistent Field Theory
*
* Copyright 2016 - 2022, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include <pscf/crystal/UnitCell.h>
#include <pscf/math/IntVec.h>
#include <iostream>
namespace Pscf
{
using namespace Util;
/**
* Returns minimum magnitude image of DFT wavevector.
*
* \param v IntVec<D> containing integer indices of wavevector.
* \param d dimensions of the discrete Fourier transform grid.
* \param cell UnitCell
* \ingroup Pscf_Crystal_Module
*/
template <int D>
IntVec<D> shiftToMinimum(IntVec<D>& v, IntVec<D> d, UnitCell<D> const & cell);
// Explicit specializations
template <>
IntVec<1> shiftToMinimum(IntVec<1>& v, IntVec<1> d, UnitCell<1> const & cell);
template <>
IntVec<2> shiftToMinimum(IntVec<2>& v, IntVec<2> d, UnitCell<2> const & cell);
template <>
IntVec<3> shiftToMinimum(IntVec<3>& v, IntVec<3> d, UnitCell<3> const & cell);
}
#endif
| 1,082
|
C++
|
.h
| 33
| 29.787879
| 81
| 0.719231
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,094
|
SymmetryGroup.h
|
dmorse_pscfpp/src/pscf/crystal/SymmetryGroup.h
|
#ifndef PSCF_SYMMETRY_GROUP_H
#define PSCF_SYMMETRY_GROUP_H
/*
* Pscfatico - Simulation Package for Polymeric and Molecular Liquids
*
* Copyright 2016 - 2022, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
//#include <iostream>
#include <vector>
namespace Pscf
{
/**
* Class template for a group of elements.
*
* This is written as a template to allow the creation of groups that
* use different types of objects to represent symmetry elements. The
* simplest distinction is between point groups and full space groups.
*
* The algorithm requires only the template parameter class Symmetry
* satisfy the following requirements:
*
* 1) A Symmetry must be default constructible.
* 2) An operator * is provided to represent element multiplication.
* 3) Operators == and != are provided to represent equality & inequality.
* 4) A method Symmetry::inverse() must return the inverse of a Symmetry.
* 5) A static method Symmetry::identity() must return the identity.
*
* \ingroup Crystal_Module
*/
template <class Symmetry>
class SymmetryGroup
{
public:
/**
* Default constructor.
*
* After construction, the group contains only the identity element.
*/
SymmetryGroup();
/**
* Copy constructor.
*/
SymmetryGroup(const SymmetryGroup<Symmetry>& other);
/**
* Destructor.
*/
~SymmetryGroup();
/**
* Assignment operator.
*/
SymmetryGroup<Symmetry>&
operator = (const SymmetryGroup<Symmetry>& other);
/**
* Add a new element to the group.
*
* Return false if the element was already present, true otherwise.
*
* \param symmetry new symmetry element.
* \return true if this is a new element, false if already present.
*/
bool add(Symmetry& symmetry);
/**
* Generate a complete group from the current elements.
*/
void makeCompleteGroup();
/**
* Remove all elements except the identity.
*
* Return group to its state after default construction.
*/
void clear();
/**
* Find a symmetry within a group.
*
* Return a pointer to a symmetry if it is in the group,
* or a null pointer if it is not.
*/
const Symmetry* find(const Symmetry& symmetry) const;
/**
* Return a reference to the identity element.
*/
const Symmetry& identity() const;
/**
* Return number of elements in group (i.e., the order of the group).
*/
int size() const;
/**
* Element access operator (by reference).
*
* \param i integer id for a symmetry element.
*/
Symmetry& operator [] (int i);
/**
* Element access operator (by reference).
*
* \param i integer id for a symmetry element.
*/
const Symmetry& operator [] (int i) const;
/**
* Equality operator.
*
* Return true if this and other are equivalent symmetry groups,
* false otherwise.
*
* \param other the group to which this one is compared.
*/
bool operator == (SymmetryGroup<Symmetry> const & other) const;
/**
* Inequality operator.
*
* Return true if this and other are inequivalent symmetry groups,
* and false if they are equivalent.
*
* \param other the group to which this one is compared.
*/
bool operator != (SymmetryGroup<Symmetry> const & other) const;
/**
* Return true if valid complete group, or throw an Exception.
*/
bool isValid() const;
private:
// Array of symmetry elements
std::vector<Symmetry> elements_;
// Identity element
Symmetry identity_;
};
// Inline member function definitions
/*
* Return the current size of the group.
*/
template <class Symmetry>
inline
int SymmetryGroup<Symmetry>::size() const
{ return elements_.size(); }
/*
* Return identity element.
*/
template <class Symmetry>
inline
const Symmetry& SymmetryGroup<Symmetry>::identity() const
{ return identity_; }
/*
* Element access operator (by reference).
*/
template <class Symmetry>
inline
Symmetry& SymmetryGroup<Symmetry>::operator [] (int i)
{ return elements_[i]; }
/*
* Element access operator (by reference).
*/
template <class Symmetry>
inline
const Symmetry& SymmetryGroup<Symmetry>::operator [] (int i) const
{ return elements_[i]; }
#ifndef PSCF_SYMMETRY_GROUP_TPP
template <int D> class SpaceSymmetry;
extern template class SymmetryGroup< SpaceSymmetry<1> >;
extern template class SymmetryGroup< SpaceSymmetry<2> >;
extern template class SymmetryGroup< SpaceSymmetry<3> >;
#endif
}
#endif
| 4,959
|
C++
|
.h
| 164
| 24.5
| 77
| 0.644944
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,095
|
BlockStubTest.h
|
dmorse_pscfpp/src/pscf/tests/solvers/BlockStubTest.h
|
#ifndef BLOCK_STUB_TEST_H
#define BLOCK_STUB_TEST_H
#include <test/UnitTest.h>
#include <test/UnitTestRunner.h>
#include "BlockStub.h"
#include <fstream>
using namespace Pscf;
//using namespace Util;
class BlockStubTest : public UnitTest
{
public:
void setUp()
{
//setVerbose(1);
}
void tearDown()
{ setVerbose(0); }
void testConstructor()
{
printMethod(TEST_FUNC);
BlockStub v;
TEST_ASSERT(&v.propagator(0).block() == &v);
TEST_ASSERT(&v.propagator(1).block() == &v);
TEST_ASSERT(&v.propagator(0).partner() == &v.propagator(1));
TEST_ASSERT(&v.propagator(1).partner() == &v.propagator(0));
}
void testReadWrite() {
printMethod(TEST_FUNC);
BlockStub v;
std::ifstream in;
openInputFile("in/BlockDescriptor", in);
in >> v;
TEST_ASSERT(v.monomerId() == 1);
TEST_ASSERT(eq(v.length(), 2.0));
TEST_ASSERT(v.vertexId(0) == 3);
TEST_ASSERT(v.vertexId(1) == 4);
if (verbose() > 0) {
std::cout << std::endl ;
std::cout << v << std::endl ;
}
}
};
TEST_BEGIN(BlockStubTest)
TEST_ADD(BlockStubTest, testConstructor)
TEST_ADD(BlockStubTest, testReadWrite)
TEST_END(BlockStubTest)
#endif
| 1,253
|
C++
|
.h
| 47
| 21.851064
| 66
| 0.634599
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,096
|
PropagatorStub.h
|
dmorse_pscfpp/src/pscf/tests/solvers/PropagatorStub.h
|
#ifndef PSCF_PROPAGATOR_STUB_H
#define PSCF_PROPAGATOR_STUB_H
/*
* PSCF - Polymer Self-Consistent Field Theory
*
* Copyright 2016 - 2022, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include <pscf/solvers/PropagatorTmpl.h>
#include <util/containers/DArray.h>
namespace Pscf
{
class PropagatorStub;
class BlockStub;
class PropagatorStub : public PropagatorTmpl<PropagatorStub>
{
public:
// Public typedefs
/**
* Chemical potential field type.
*/
typedef DArray<double> WField;
/**
* Monomer concentration field type.
*/
typedef DArray<double> CField;
// Member functions
/**
* Constructor.
*/
PropagatorStub(){}
/**
* Associate this propagator with a block.
*
* \param block associated Block object.
*/
void setBlock(BlockStub& block);
/**
* Get the associated Block object by reference.
*/
BlockStub & block();
/**
* Solve the modified diffusion equation for this block.
*
* \param w chemical potential field for appropriate monomer type
*/
void solve()
{ setIsSolved(true); };
/**
* Compute monomer concentration for this block.
*/
void computeConcentration(double prefactor)
{};
/**
* Compute and return molecular partition function.
*/
double computeQ()
{ return 1.0; };
private:
/// Pointer to associated Block.
BlockStub* blockPtr_;
};
/*
* Associate this propagator with a block and direction
*/
inline void PropagatorStub::setBlock(BlockStub& block)
{ blockPtr_ = █ }
/*
* Get the associated Block object.
*/
inline BlockStub& PropagatorStub::block()
{ return *blockPtr_; }
}
#endif
| 1,908
|
C++
|
.h
| 74
| 20.175676
| 70
| 0.638628
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,097
|
MixtureStubTest.h
|
dmorse_pscfpp/src/pscf/tests/solvers/MixtureStubTest.h
|
#ifndef PSCF_MIXTURE_STUB_TEST_H
#define PSCF_MIXTURE_STUB_TEST_H
#include <test/UnitTest.h>
#include <test/UnitTestRunner.h>
#include "MixtureStub.h"
#include <fstream>
using namespace Pscf;
class MixtureStubTest : public UnitTest
{
public:
void setUp()
{
//setVerbose(1);
}
void tearDown()
{
setVerbose(0);
}
void testConstructor()
{
printMethod(TEST_FUNC);
MixtureStub p;
}
void testReadParam()
{
printMethod(TEST_FUNC);
std::ifstream in;
openInputFile("in/Mixture", in);
MixtureStub sys;
sys.readParam(in);
if (verbose() > 0) {
std::cout << std::endl;
sys.writeParam(std::cout);
}
}
};
TEST_BEGIN(MixtureStubTest)
TEST_ADD(MixtureStubTest, testConstructor)
TEST_ADD(MixtureStubTest, testReadParam)
TEST_END(MixtureStubTest)
#endif
| 877
|
C++
|
.h
| 41
| 16.926829
| 42
| 0.673195
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,098
|
MixtureStub.h
|
dmorse_pscfpp/src/pscf/tests/solvers/MixtureStub.h
|
#ifndef PSCF_MIXTURE_STUB_H
#define PSCF_MIXTURE_STUB_H
/*
* PSCF - Polymer Self-Consistent Field Theory
*
* Copyright 2016 - 2022, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include "PolymerStub.h"
#include "SolventStub.h"
#include <pscf/solvers/MixtureTmpl.h>
namespace Pscf
{
class MixtureStub
: public MixtureTmpl<PolymerStub, SolventStub>
{
public:
MixtureStub()
{ setClassName("Mixture"); }
};
}
#endif
| 521
|
C++
|
.h
| 22
| 20.772727
| 67
| 0.741803
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,099
|
SolversTestComposite.h
|
dmorse_pscfpp/src/pscf/tests/solvers/SolversTestComposite.h
|
#ifndef PSCF_SOLVERS_TEST_COMPOSITE_H
#define PSCF_SOLVERS_TEST_COMPOSITE_H
#include <test/CompositeTestRunner.h>
#include "BlockStubTest.h"
#include "PolymerStubTest.h"
#include "MixtureStubTest.h"
TEST_COMPOSITE_BEGIN(SolversTestComposite)
TEST_COMPOSITE_ADD_UNIT(BlockStubTest);
TEST_COMPOSITE_ADD_UNIT(PolymerStubTest);
TEST_COMPOSITE_ADD_UNIT(MixtureStubTest);
TEST_COMPOSITE_END
#endif
| 396
|
C++
|
.h
| 12
| 31.666667
| 42
| 0.847368
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,100
|
BlockStub.h
|
dmorse_pscfpp/src/pscf/tests/solvers/BlockStub.h
|
#ifndef PSCF_BLOCK_STUB_H
#define PSCF_BLOCK_STUB_H
/*
* PSCF - Polymer Self-Consistent Field Theory
*
* Copyright 2016 - 2022, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include "PropagatorStub.h"
#include <pscf/solvers/BlockTmpl.h>
namespace Pscf
{
class BlockStub : public BlockTmpl<PropagatorStub>
{
public:
typedef PropagatorStub Propagator;
typedef PropagatorStub::WField WField;
/**
* Constructor.
*/
BlockStub()
{
propagator(0).setBlock(*this);
propagator(1).setBlock(*this);
}
/**
* Compute monomer concentration for this block.
*/
void setupSolver(WField const & wField)
{}
/**
* Compute monomer concentration for this block.
*/
void computeConcentration(double prefactor)
{}
};
}
#endif
| 926
|
C++
|
.h
| 38
| 19.184211
| 67
| 0.662457
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,101
|
PolymerStub.h
|
dmorse_pscfpp/src/pscf/tests/solvers/PolymerStub.h
|
#ifndef PSCF_POLYMER_STUB_H
#define PSCF_POLYMER_STUB_H
/*
* PSCF - Polymer Self-Consistent Field Theory
*
* Copyright 2016 - 2022, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include "BlockStub.h"
#include <pscf/solvers/PolymerTmpl.h>
namespace Pscf
{
class PolymerStub : public PolymerTmpl<BlockStub>
{
public:
PolymerStub()
{ setClassName("Polymer"); }
};
}
#endif
| 471
|
C++
|
.h
| 20
| 20.85
| 67
| 0.740406
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,102
|
PolymerStubTest.h
|
dmorse_pscfpp/src/pscf/tests/solvers/PolymerStubTest.h
|
#ifndef POLYMER_STUB_TEST_H
#define POLYMER_STUB_TEST_H
#include <test/UnitTest.h>
#include <test/UnitTestRunner.h>
#include "PolymerStub.h"
#include <util/containers/Pair.h>
#include <fstream>
using namespace Pscf;
class PolymerStubTest : public UnitTest
{
public:
void setUp()
{
//setVerbose(1);
}
void tearDown()
{ setVerbose(0); }
void testConstructor()
{
printMethod(TEST_FUNC);
PolymerStub p;
}
void testReadParam()
{
printMethod(TEST_FUNC);
std::ifstream in;
openInputFile("in/Polymer", in);
PolymerStub p;
p.readParam(in);
if (verbose() > 0) {
std::cout << std::endl;
p.writeParam(std::cout);
}
#if 0
for (int i = 0; i < p.nVertex(); ++i) {
std::cout << p.vertex(i).size() << "\n";
}
#endif
if (verbose() > 0) {
std::cout << "\nVertices: id, size, block ids\n";
for (int i = 0; i < p.nVertex(); ++i) {
std::cout << i << " " << p.vertex(i).size();
for (int j = 0; j < p.vertex(i).size(); ++j) {
std::cout << " " << p.vertex(i).inPropagatorId(j)[0];
}
std::cout << std::endl;
}
}
#if 0
for (int i = 0; i < p.nPropagator(); ++i) {
std::cout << p.propagatorId(i)[0] << " "
<< p.propagatorId(i)[1] << "\n";
}
#endif
if (verbose() > 0) {
std::cout << "\nPropagator order:\n";
}
Pair<int> propId;
PropagatorStub* propPtr = 0;
for (int i = 0; i < p.nPropagator(); ++i) {
propId = p.propagatorId(i);
if (verbose() > 0) {
std::cout << propId[0] << " " << propId[1] << "\n";
}
propPtr = &p.propagator(i);
TEST_ASSERT(propPtr->block().id() == propId[0]);
TEST_ASSERT(propPtr->directionId() == propId[1]);
propPtr->setIsSolved(false);
}
// Check computation plan
for (int i = 0; i < p.nPropagator(); ++i) {
TEST_ASSERT(p.propagator(i).isReady());
p.propagator(i).setIsSolved(true);
}
}
void testReadStarParam()
{
printMethod(TEST_FUNC);
std::ifstream in;
openInputFile("in/Polymer2", in);
PolymerStub p;
p.readParam(in);
if (verbose() > 0) {
std::cout << std::endl;
p.writeParam(std::cout);
}
#if 0
for (int i = 0; i < p.nVertex(); ++i) {
std::cout << p.vertex(i).size() << "\n";
}
#endif
if (verbose() > 0) {
std::cout << std::endl;
std::cout << "\nVertices: id, size, block ids\n";
for (int i = 0; i < p.nVertex(); ++i) {
std::cout << i << " " << p.vertex(i).size();
for (int j = 0; j < p.vertex(i).size(); ++j) {
std::cout << " " << p.vertex(i).inPropagatorId(j)[0];
}
std::cout << "\n";
}
}
#if 0
for (int i = 0; i < p.nPropagator(); ++i) {
std::cout << p.propagatorId(i)[0] << " "
<< p.propagatorId(i)[1] << "\n";
}
#endif
if (verbose() > 0) {
std::cout << "\nPropagator order:\n";
}
Pair<int> propId;
PropagatorStub* propPtr = 0;
for (int i = 0; i < p.nPropagator(); ++i) {
propId = p.propagatorId(i);
if (verbose() > 0) {
std::cout << propId[0] << " " << propId[1] << "\n";
}
propPtr = &p.propagator(i);
TEST_ASSERT(propPtr->block().id() == propId[0]);
TEST_ASSERT(propPtr->directionId() == propId[1]);
propPtr->setIsSolved(false);
}
// Check computation plan
for (int i = 0; i < p.nPropagator(); ++i) {
TEST_ASSERT(p.propagator(i).isReady());
p.propagator(i).setIsSolved(true);
}
}
};
TEST_BEGIN(PolymerStubTest)
TEST_ADD(PolymerStubTest, testConstructor)
TEST_ADD(PolymerStubTest, testReadParam)
TEST_ADD(PolymerStubTest, testReadStarParam)
TEST_END(PolymerStubTest)
#endif
| 4,126
|
C++
|
.h
| 136
| 22.433824
| 69
| 0.501017
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,103
|
SolventStub.h
|
dmorse_pscfpp/src/pscf/tests/solvers/SolventStub.h
|
#ifndef PSCF_SOLVENT_STUB_H
#define PSCF_SOLVENT_STUB_H
/*
* PSCF - Polymer Self-Consistent Field Theory
*
* Copyright 2016 - 2022, The Regents of the University of Minnesota
* Distributed under the terms of the GNU General Public License.
*/
#include <pscf/chem/Species.h>
#include <util/param/ParamComposite.h>
namespace Pscf
{
class SolventStub : public Species, public ParamComposite
{
public:
SolventStub()
{ setClassName("Solvent"); }
void compute(PropagatorStub::WField const &)
{}
};
}
#endif
| 549
|
C++
|
.h
| 22
| 21.818182
| 67
| 0.72973
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,104
|
MeshTest.h
|
dmorse_pscfpp/src/pscf/tests/mesh/MeshTest.h
|
#ifndef PSCF_MESH_TEST_H
#define PSCF_MESH_TEST_H
#include <test/UnitTest.h>
#include <test/UnitTestRunner.h>
#include <pscf/mesh/Mesh.h>
#include <pscf/math/IntVec.h>
#include <iostream>
#include <fstream>
using namespace Util;
using namespace Pscf;
class MeshTest : public UnitTest
{
public:
void setUp()
{
// setVerbose(1);
}
void tearDown()
{}
void test3DMesh() {
printMethod(TEST_FUNC);
Mesh<3> mesh;
IntVec<3> d;
d[0] = 2;
d[1] = 1;
d[2] = 3;
mesh.setDimensions(d);
IntVec<3> p;
p[0] = 1;
p[1] = 0;
p[2] = 1;
int rank = mesh.rank(p);
IntVec<3> q = mesh.position(rank);
TEST_ASSERT(q == p);
if (verbose() > 0) {
printEndl();
std::cout << "position = " << p << std::endl;
std::cout << "rank = " << rank << std::endl;
std::cout << "position = " << q << std::endl;
}
}
void test3DMeshAssign()
{
printMethod(TEST_FUNC);
// Make reference mesh
IntVec<3> d;
d[0] = 2;
d[1] = 1;
d[2] = 3;
Mesh<3> a(d);
// Construct test vector
IntVec<3> p;
p[0] = 1;
p[1] = 0;
p[2] = 1;
// Test assignment
Mesh<3> b;
TEST_ASSERT(b.size() == 0);
TEST_ASSERT(b.dimension(1) == 0);
b = a;
TEST_ASSERT(a.dimensions() == b.dimensions());
TEST_ASSERT(a.size() == b.size());
int rank = a.rank(p);
IntVec<3> q = b.position(rank);
TEST_ASSERT(q == p);
// Test copy constructor
Mesh<3> c(a);
TEST_ASSERT(a.dimensions() == c.dimensions());
TEST_ASSERT(a.size() == c.size());
rank = c.rank(p);
q = a.position(rank);
TEST_ASSERT(q == p);
}
void test3DMeshIO()
{
printMethod(TEST_FUNC);
Mesh<3> mesh;
std::ifstream in;
openInputFile("in/mesh3D", in);
in >> mesh;
in.close();
if (verbose() > 0) {
printEndl();
std::cout << mesh << std::endl;
}
}
};
TEST_BEGIN(MeshTest)
TEST_ADD(MeshTest, test3DMesh)
TEST_ADD(MeshTest, test3DMeshAssign)
TEST_ADD(MeshTest, test3DMeshIO)
TEST_END(MeshTest)
#endif
| 2,214
|
C++
|
.h
| 93
| 18.010753
| 57
| 0.537947
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,105
|
MeshIteratorTest.h
|
dmorse_pscfpp/src/pscf/tests/mesh/MeshIteratorTest.h
|
#ifndef PSCF_MESH_ITERATOR_TEST_H
#define PSCF_MESH_ITERATOR_TEST_H
#include <test/UnitTest.h>
#include <test/UnitTestRunner.h>
#include <pscf/mesh/MeshIterator.h>
#include <pscf/math/IntVec.h>
#include <iostream>
#include <fstream>
using namespace Util;
using namespace Pscf;
class MeshIteratorTest : public UnitTest
{
public:
void setUp()
{
//setVerbose(1);
}
void tearDown()
{}
void test3D(IntVec<3>& d)
{
MeshIterator<3> iter;
iter.setDimensions(d);
IntVec<3> x; // current position
IntVec<3> xp; // previous position
int i ; // current rank
int ip ; // previous rank
for (iter.begin(); !iter.atEnd(); ++iter) {
if (verbose() > 0) {
std::cout << iter.rank() << " "
<< iter.position() << std::endl;
}
if (iter.rank() == 0) {
x = iter.position();
i = iter.rank();
for (int k = 0; k < 3; ++k) {
TEST_ASSERT(x[k] == 0);
}
} else {
xp = x;
ip = i;
x = iter.position();
i = iter.rank();
TEST_ASSERT(ip == i - 1);
if (x[2] != 0) {
TEST_ASSERT(xp[2] == x[2] - 1);
TEST_ASSERT(xp[1] == x[1]);
TEST_ASSERT(xp[0] == x[0]);
} else {
TEST_ASSERT(xp[2] == d[2] - 1);
if (x[1] != 0) {
TEST_ASSERT(xp[1] == x[1] - 1);
} else {
TEST_ASSERT(xp[1] == d[1] - 1);
TEST_ASSERT(xp[0] == x[0] - 1);
}
}
}
}
}
void test2D(IntVec<2>& d)
{
MeshIterator<2> iter;
iter.setDimensions(d);
IntVec<2> x; // current position
IntVec<2> xp; // previous position
int i ; // current rank
int ip ; // previous rank
for (iter.begin(); !iter.atEnd(); ++iter) {
if (verbose() > 0) {
std::cout << iter.rank() << " "
<< iter.position() << std::endl;
}
if (iter.rank() == 0) {
x = iter.position();
i = iter.rank();
TEST_ASSERT(x[1] == 0);
TEST_ASSERT(x[0] == 0);
} else {
xp = x;
ip = i;
x = iter.position();
i = iter.rank();
TEST_ASSERT(ip == i - 1);
if (x[1] != 0) {
TEST_ASSERT(xp[1] == x[1] - 1);
TEST_ASSERT(xp[0] == x[0]);
} else {
TEST_ASSERT(xp[1] == d[1] - 1);
TEST_ASSERT(xp[0] == x[0] - 1);
}
}
}
}
void testMeshIterator3D()
{
printMethod(TEST_FUNC);
if (verbose() > 0) {
std::cout << std::endl;
}
IntVec<3> d;
d[0] = 2;
d[1] = 1;
d[2] = 3;
test3D(d);
if (verbose() > 0) {
std::cout << std::endl;
}
d[0] = 1;
d[1] = 3;
d[2] = 2;
test3D(d);
}
void testMeshIterator2D()
{
printMethod(TEST_FUNC);
if (verbose() > 0) {
std::cout << std::endl;
}
IntVec<2> twoD;
twoD[0] = 2;
twoD[1] = 3;
test2D(twoD);
}
};
TEST_BEGIN(MeshIteratorTest)
TEST_ADD(MeshIteratorTest, testMeshIterator3D)
TEST_ADD(MeshIteratorTest, testMeshIterator2D)
TEST_END(MeshIteratorTest)
#endif
| 3,475
|
C++
|
.h
| 130
| 17.9
| 56
| 0.440096
|
dmorse/pscfpp
| 30
| 20
| 8
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.