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,206
FFT.h
dmorse_pscfpp/src/pspc/field/FFT.h
#ifndef PSPC_FFT_H #define PSPC_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 <pspc/field/RField.h> #include <pspc/field/RFieldDft.h> #include <pscf/math/IntVec.h> #include <util/global.h> #include <fftw3.h> namespace Pscf { namespace Pspc { using namespace Util; using namespace Pscf; /** * Fourier transform wrapper for real data. * * \ingroup Pspc_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); /** * Setup grid dimensions, plans and work space. * * \param rField real data on r-space grid * \param kField complex data on k-space grid */ void setup(RField<D>& rField, RFieldDft<D>& kField); /** * Compute forward (real-to-complex) Fourier transform. * * This function computes a scaled Fourier transform, which is obtained * by dividing the unscaled transform computed by FFTW by the number of * elements. A scaled copy of the input data is copied to a temporary * real array before being passed to the FFT forward transform function. * * This function does not overwrite or corrupt the input array. * * \param in array of real values on r-space grid * \param out array of complex values on k-space grid */ void forwardTransform(RField<D> const & in, RFieldDft<D>& out) const; /** * Compute inverse (complex-to-real) Fourier transform. * * This function computes the same unscaled inverse transform as the * FFTW library. * * NOTE: The inverse transform generally overwrites and corrupts its * input. This is the behavior of the complex-to-real transform of the * underlying FFTW library. See Sec. 2.3 of the FFTW documentation at * https://www.fftw.org/fftw3_doc, One-Dimensional DFTs of Real Data: * "...the inverse transform (complex to real) has the side-effect of * overwriting its input array, ..." * * \param in array of complex values on k-space grid (overwritten) * \param out array of real values on r-space grid */ void inverseTransform(RFieldDft<D>& in, RField<D>& out) const; /** * Compute inverse (complex-to-real) Fourier transform without destroying input. * * \param in array of complex values on k-space grid * \param out array of real values on r-space grid */ void inverseTransformSafe(RFieldDft<D> const & in, RField<D>& out) const; /** * Return the dimensions of the grid for which this was allocated. */ IntVec<D> const & meshDimensions() const; /** * Has this FFT object been setup? */ bool isSetup() const; private: /// Private r-space array for performing safe transforms. mutable RField<D> rFieldCopy_; /// Private k-space array for performing safe transforms. mutable RFieldDft<D> kFieldCopy_; /// 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. fftw_plan fPlan_; /// Pointer to a plan for an inverse transform. fftw_plan iPlan_; /// Have array dimension and plan been initialized? bool isSetup_; /** * Make FFTW plans for transform and inverse transform. */ void makePlans(RField<D>& rField, RFieldDft<D>& kField); }; // Declarations of explicit specializations template <> void FFT<1>::makePlans(RField<1>& rField, RFieldDft<1>& kField); template <> void FFT<2>::makePlans(RField<2>& rField, RFieldDft<2>& kField); template <> void FFT<3>::makePlans(RField<3>& rField, RFieldDft<3>& kField); /* * Has this object been setup? */ template <int D> inline bool FFT<D>::isSetup() const { return isSetup_; } /* * Return the dimensions of the grid for which this was allocated. */ template <int D> inline IntVec<D> const & FFT<D>::meshDimensions() const { return meshDimensions_; } #ifndef PSPC_FFT_TPP // Suppress implicit instantiation extern template class FFT<1>; extern template class FFT<2>; extern template class FFT<3>; #endif } // namespace Pscf::Pspc } // namespace Pscf #endif
4,850
C++
.h
143
28.146853
85
0.653682
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,207
Domain.h
dmorse_pscfpp/src/pspc/field/Domain.h
#ifndef PSPC_DOMAIN_H #define PSPC_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 <pspc/field/FieldIo.h> // member #include <pspc/field/FFT.h> // member #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 <string> namespace Pscf { namespace Pspc { 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 FieldIo * - a lattice system enum value * - a groupName string * * \ingroup Pspc_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). * * \param in input parameter stream */ virtual void readParameters(std::istream& in); /** * Read header of an r-grid field file to initialize this Domain. * * Useful for unit testing. * * \param in input parameter stream * \param nMonomer number of monomers in field file (output) */ void readRGridFieldHeader(std::istream& in, int& nMonomer); /** * Set unit cell. * * Initializes basis if not done previously. * * \param unitCell new unit cell */ void setUnitCell(UnitCell<D> const & unitCell); /** * Set unit cell state. * * 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 (i.e., lattice type and parameters) by reference. */ UnitCell<D>& unitCell(); /** * Get UnitCell (i.e., lattice type and parameters) by reference. */ UnitCell<D> const & unitCell() const; /** * Get spatial discretization mesh by reference. */ Mesh<D>& mesh(); /** * Get spatial discretization mesh by const reference. */ Mesh<D> const & mesh() const; /** * Get associated SpaceGroup object by const reference. */ SpaceGroup<D> const & group() const ; /** * Get associated Basis object by reference. */ Basis<D>& basis(); /** * Get associated Basis object by const reference. */ Basis<D> const & basis() const ; /** * Get associated FFT object. */ FFT<D>& fft(); /** * Get associated FFT object by const reference. */ FFT<D> const & fft() const; /** * Get associated FieldIo object. */ FieldIo<D>& fieldIo(); /** * Get associated FieldIo object by const reference. */ FieldIo<D> const & fieldIo() const; /** * Get lattice system. */ 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 to be used by iterator */ FFT<D> fft_; /** * 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_; // members of parent class with non-dependent names using ParamComposite::read; using ParamComposite::readOptional; }; // 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. template <int D> inline FFT<D> const & Domain<D>::fft() const { return fft_; } // 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 PSPC_DOMAIN_TPP // Suppress implicit instantiation extern template class Domain<1>; extern template class Domain<2>; extern template class Domain<3>; #endif } // namespace Pspc } // namespace Pscf #endif
7,573
C++
.h
268
22.343284
73
0.597707
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,208
Field.h
dmorse_pscfpp/src/pspc/field/Field.h
#ifndef PSPC_FIELD_H #define PSPC_FIELD_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 Pspc { using namespace Util; /** * Dynamic array with aligned data, for use with FFTW library. * * \ingroup Pspc_Field_Module */ template <typename Data> class Field { public: /** * Default constructor. */ Field(); /** * Destructor. * * Deletes underlying C array, if allocated previously. */ virtual ~Field(); /** * Allocate the underlying C array. * * \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; /** * Get an element by non-const reference. * * Mimic C-array subscripting. * * \param i array index * \return non-const reference to element i */ Data & operator[] (int i); /** * Get an element by const reference. * * Mimics C-array subscripting. * * \param i array index * \return const reference to element i */ Data const & operator[] (int i) const; /** * Return pointer to underlying C array. */ Data* cField(); /** * Return pointer to const to underlying C array. */ Data const * cField() 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_; private: /** * Copy constructor (private and not implemented to prohibit). */ Field(Field const & other); /** * Assignment operator (private and non implemented to prohibit). */ Field& operator = (Field const & other); }; /* * Return allocated size. */ template <typename Data> inline int Field<Data>::capacity() const { return capacity_; } /* * 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 Data const & Field<Data>::operator[] (int i) const { assert(data_ != 0); assert(i >= 0 ); assert(i < capacity_); return *(data_ + i); } /* * Get a pointer to the underlying C array. */ template <typename Data> inline Data* Field<Data>::cField() { return data_; } /* * Get a pointer to const to the underlying C array. */ template <typename Data> inline Data const * Field<Data>::cField() 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 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()) { for (int i = 0; i < capacity_; ++i) { ar & data_[i]; } } } } } #include "Field.tpp" #endif
4,581
C++
.h
185
18.713514
71
0.576077
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,209
KFieldComparison.h
dmorse_pscfpp/src/pspc/field/KFieldComparison.h
#ifndef PSPC_K_FIELD_COMPARISON_H #define PSPC_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 <pspc/field/RFieldDft.h> namespace Pscf { namespace Pspc { using namespace Util; /** * Comparator for RFieldDft (k-grid) arrays. * * \ingroup Pspc_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(RFieldDft<D> const& a, RFieldDft<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<RFieldDft<D> > const& a, DArray<RFieldDft<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 PSPC_K_FIELD_COMPARISON_TPP // Suppress implicit instantiation extern template class KFieldComparison<1>; extern template class KFieldComparison<2>; extern template class KFieldComparison<3>; #endif } // namespace Pspc } // namespace Pscf #endif
2,833
C++
.h
86
26.953488
74
0.66728
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,210
Mask.h
dmorse_pscfpp/src/pspc/field/Mask.h
#ifndef PSPC_MASK_H #define PSPC_MASK_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 <pspc/field/RField.h> // member template parameter #include <util/containers/DArray.h> // member template namespace Pscf { namespace Pspc { template <int D> class FieldIo; using namespace Util; /** * A field to which the total density is constrained. * * A Mask<D> contains representations of a single field in two formats: * * - A DArray<double> that contains components of the field in a * symmetry-adapted Fourier expansion (i.e., in basis format). This * is accessed by the basis() and basis(int) member functions. * * - An RField<D> object contains values of the field on the nodes of a * regular mesh. This is accessed by the rgrid() and rgrid(int) member * functions. * * A Mask 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 field in * r-grid format, but recomputes the components in basis format if * and only if the user declares that the field 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 Pspc_Field_Module */ template <int D> class Mask : public ParamComposite { public: /** * Constructor. */ Mask(); /** * Destructor. */ ~Mask(); /** * Create association with FieldIo (store pointer). */ void setFieldIo(FieldIo<D> const & fieldIo); /** * Allocate memory for the field. * * A Mask<D> may only be allocated once. An Exception will * be thrown if this function is called more than once. * * \param nBasis number of basis functions * \param dimensions dimensions of spatial mesh */ void allocate(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 field components of field in basis format */ void setBasis(DArray<double> const & field); /** * Set field values in real-space (r-grid) format. * * If the isSymmetric parameter is true, this function assumes that * the field 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 field new field in r-grid format * \param isSymmetric is this field symmetric under the space group? */ void setRGrid(RField<D> const & field, bool isSymmetric = false); /** * Read field 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 field * \param unitCell associated crystallographic unit cell */ void readBasis(std::istream& in, UnitCell<D>& unitCell); /** * Read field 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 field * \param unitCell associated crystallographic unit cell */ void readBasis(std::string filename, UnitCell<D>& unitCell); /** * Reads field from an input stream in real-space (r-grid) format. * * If the isSymmetric parameter is true, this function assumes that * the field is known to be symmetric and so computes and stores * the corresponding basis format. 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 field * \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 field from a file in real-space (r-grid) format. * * If the isSymmetric parameter is true, this function assumes that * the field is known to be symmetric and so computes and stores * the corresponding basis format. 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 field * \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); /** * Get the field in basis format. * * The array capacity is equal to the number of monomer types. */ DArray<double> const & basis() const; /** * Get array of all field in r-space grid format. * * The array capacity is equal to the number of monomer types. */ RField<D> const & rgrid() const; /** * Volume fraction of the unit cell occupied by the polymers/solvents. * * This value is equivalent to the spatial average of the mask, which is * the q=0 coefficient of the discrete Fourier transform. * * If hasData_ = true and isSymmetric_ = false (data only exists in * rgrid format), then this object must be associated with a FieldIo * object in order to call phiTot(). In other cases, the FieldIo * association is not necessary. */ double phiTot() const; /** * Has memory been allocated? */ bool isAllocated() const; /** * Has field data been set in either format? * * This flag is set true in setBasis and setRGrid. */ bool hasData() const; /** * Are field 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 field 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: /* * Components of field in symmetry-adapted basis format */ DArray<double> basis_; /* * Field in real-space grid (r-grid) format */ RField<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 field) */ int nMonomer_; /* * Has memory been allocated for field? */ bool isAllocated_; /* * Has field data been initialized ? */ bool hasData_; /* * Are the field symmetric under space group operations? * * Set true when field are set using the symmetry adapted basis * format via function setBasis. False by otherwise. */ bool isSymmetric_; }; // Inline member functions // Get array of all field in basis format (const) template <int D> inline DArray<double> const & Mask<D>::basis() const { UTIL_ASSERT(hasData_); UTIL_ASSERT(isSymmetric_); return basis_; } // Get all field in r-grid format (const) template <int D> inline RField<D> const & Mask<D>::rgrid() const { UTIL_ASSERT(hasData_); return rgrid_; } // Has memory been allocated? template <int D> inline bool Mask<D>::isAllocated() const { return isAllocated_; } // Have the field data been set? template <int D> inline bool Mask<D>::hasData() const { return hasData_; } // Is the field symmetric under space group operations? template <int D> inline bool Mask<D>::isSymmetric() const { return isSymmetric_; } #ifndef PSPC_W_FIELD_CONTAINER_TPP // Suppress implicit instantiation extern template class Mask<1>; extern template class Mask<2>; extern template class Mask<3>; #endif } // namespace Pspc } // namespace Pscf #endif
10,684
C++
.h
297
29.592593
78
0.650841
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,211
FieldIo.h
dmorse_pscfpp/src/pspc/field/FieldIo.h
#ifndef PSPC_FIELD_IO_H #define PSPC_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 <pspc/field/FFT.h> // member #include <pspc/field/RField.h> // function parameter #include <pspc/field/RFieldDft.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 Pspc { using namespace Util; using namespace Pscf; /** * File input/output operations and format conversions for fields. * * This class provides functions to read and write arrays that contain * fields in any of three representations (symmetry-adapted basis, * r-space grid, or Fourier k-space grid), and to convert among these * representations. The functions that implement IO operations define * file formats for these field representations. * * \ingroup Pspc_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 SpaceGroup object * \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 - Symmetry Adapted Basis Format ///@{ /** * Read single concentration or chemical potential field from file. * * This function reads the field in symmetry adapted basis format * from input stream in. * * \param in input stream (i.e., input file) * \param field array to store the field (basis format) * \param unitCell associated crystallographic unit cell */ void readFieldBasis(std::istream& in, DArray<double>& field, UnitCell<D> & unitCell) const; /** * Read single concentration or chemical potential field from file. * * This function opens an input file with the specified filename, * reads field in symmetry adapted basis format from that file, and * closes the file. * * \param filename name of input file * \param field array to store the field (basis format) * \param unitCell associated crystallographic unit cell */ void readFieldBasis(std::string filename, DArray<double>& field, UnitCell<D> & unitCell) const; /** * Write single concentration or chemical potential field to output * stream out. * * This function writes the field in symmetry adapted basis format. * * \param out output stream (i.e., output file) * \param field field to be written (symmetry adapted basis format) * \param unitCell associated crystallographic unit cell */ void writeFieldBasis(std::ostream& out, DArray<double> const & field, UnitCell<D> const & unitCell) const; /** * Write single concentration or chemical potential field to file. * * This function opens an output file with the specified filename, * writes the field in symmetry adapted basis format to that file, * and closes the file. * * \param filename name of output file * \param field field to be written (symmetry adapted basis format) * \param unitCell associated crystallographic unit cell */ void writeFieldBasis(std::string filename, DArray<double> const & field, UnitCell<D> const & unitCell) const; /** * Read concentration or chemical potential field components from file. * * This function reads fields in a symmetry adapted basis from * input stream 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 associated crystallographic unit cell */ 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 associated crystallographic unit cell */ 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 associated 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 associated crystallographic unit cell */ void writeFieldsBasis(std::string filename, DArray< DArray<double> > const & fields, UnitCell<D> const & unitCell) const; ///@} /// \name Field File IO - Real Space Grid Format ///@{ /** * Read single RField (field on an r-space grid) from istream. * * \param in input stream (i.e., input file) * \param field fields defined on r-space grid * \param unitCell associated crystallographic unit cell */ void readFieldRGrid(std::istream &in, RField<D> & field, UnitCell<D>& unitCell) const; /** * Read single RField (field on an r-space grid) from named file. * * This function opens an input file with the specified filename, * reads a field in RField<D> real-space grid format, and closes * the file. * * \param filename name of input file * \param field fields defined on r-space grid * \param unitCell associated crystallographic unit cell */ void readFieldRGrid(std::string filename, RField<D> & field, UnitCell<D>& unitCell) const; /** * Read array of RField objects (fields on r-space grid) from istream. * * 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 associated crystallographic unit cell */ void readFieldsRGrid(std::istream& in, DArray< RField<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 associated crystallographic unit cell */ void readFieldsRGrid(std::string filename, DArray< RField<D> >& fields, UnitCell<D> & unitCell) const; /** * Write a single RField (field on an r-space grid) to ostream. * * \param out output stream * \param field field defined on r-space grid * \param unitCell associated crystallographic unit cell * \param writeHeader should a file header be written? */ void writeFieldRGrid(std::ostream &out, RField<D> const & field, UnitCell<D> const & unitCell, bool writeHeader = true) const; /** * Write a single RField (fields on an r-space grid) to a file. * * This function opens an output file with the specified filename, * write a field in RField<D> real-space grid format to that file, * and then closes the file. * * \param filename name of output file * \param field field defined on r-space grid * \param unitCell associated crystallographic unit cell */ void writeFieldRGrid(std::string filename, RField<D> const & field, UnitCell<D> const & unitCell) const; /** * Write array of RField objects (fields on r-space grid) to ostream. * * \param out output stream (i.e., output file) * \param fields array of RField fields (r-space grid) * \param unitCell associated crystallographic unit cell */ void writeFieldsRGrid(std::ostream& out, DArray< RField<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 associated crystallographic unit cell */ void writeFieldsRGrid(std::string filename, DArray< RField<D> > const & fields, UnitCell<D> const & unitCell) const; ///@} /// \name Field File IO - Fourier Space (K-Space) Grid Format ///@{ /** * Read array of RFieldDft 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 RFieldDft fields (k-space grid) * \param unitCell associated crystallographic unit cell */ void readFieldsKGrid(std::istream& in, DArray< RFieldDft<D> >& fields, UnitCell<D> & unitCell) const; /** * Read array of RFieldDft 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 RFieldDft fields (k-space grid) * \param unitCell associated crystallographic unit cell */ void readFieldsKGrid(std::string filename, DArray< RFieldDft<D> >& fields, UnitCell<D> & unitCell) const; /** * Write array of RFieldDft 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 RFieldDft fields * \param unitCell associated crystallographic unit cell */ void writeFieldsKGrid(std::ostream& out, DArray< RFieldDft<D> > const & fields, UnitCell<D> const & unitCell) const; /** * Write array of RFieldDft 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 RFieldDft fields (k-space grid) * \param unitCell associated crystallographic unit cell */ void writeFieldsKGrid(std::string filename, DArray< RFieldDft<D> > const & fields, UnitCell<D> const & unitCell) const; ///@} /// \name File IO Utilities ///@{ /** * Reader header of field file (fortran pscf format) * * This reads the common part of the header for all field file * formats. This contains the dimension of space, the unit cell, the * group name and the the number of monomers. The unit cell data is * read into the associated UnitCell<D>, which is thus updated. * * If the associated basis is not initialized, this function will * attempt to initialize it using the unit cell read from file and * the associated group (if available) or group name. * * This function throws an exception if the values of "dim" read * from file do not match the FieldIo template parameter D. * * The function does not impose any requirements on the value * of the input parameter nMonomer; it is overwritten and will * contain the value of "N_monomer" from the field file header * at termination of the function. * * If the UnitCell object passed to this function already * contains unit cell data, the function will check to ensure * that the crystal system and space group in the field file * header match the data already stored. A warning will also * be printed if the lattice parameters do not match. If, * instead, the function is passed an empty UnitCell object, * we assume that the UnitCell data is unknown or that the * field file header does not need to be cross-checked with * existing data. In this case, the field file header data is * stored directly in the UnitCell object that was passed in. * * \param in input stream (i.e., input file) * \param nMonomer number of fields contained in the field file * \param unitCell associated crystallographic unit cell */ 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 or fields * \param unitCell associated crystallographic unit cell */ void writeFieldHeader(std::ostream& out, int nMonomer, UnitCell<D> const & unitCell) const; ///@} /// \name Field Format Conversion ///@{ /** * Convert a 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, RFieldDft<D>& dft) const; /** * Convert fields from symmetrized basis to Fourier transform (k-grid). * * The in and out parameters are arrays of fields, in which element * number i is the field associated with monomer type i. * * \param in fields expanded in symmetry-adapted Fourier basis * \param out fields defined as discrete Fourier transforms (k-grid) */ void convertBasisToKGrid(DArray< DArray<double> > const & in, DArray< RFieldDft<D> >& out) const; /** * Convert a field from Fourier transform (kgrid) to symmetrized basis. * * If the checkSymmetry parameter is true, this function checks if * the input field satisfies the space group symmetry to within a * tolerance given by the epsilon parameter, and prints a warning to * Log::file() if it does not. * * \param in discrete Fourier transform (k-grid) of a field * \param out components of field in asymmetry-adapted Fourier basis * \param checkSymmetry flag indicating whether to check symmetry * \param epsilon error tolerance for symmetry test (if any) */ void convertKGridToBasis(RFieldDft<D> const & in, DArray<double> & out, bool checkSymmetry = true, double epsilon = 1.0e-8) const; /** * Convert fields from Fourier transform (k-grid) 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. * * If the checkSymmetry parameter is true, this function checks if * the input fields all satisfies the space group symmetry to within * a tolerance given by the parameter epsilon, and prints a warning * to Log::file() if one or more fields do not. * * \param in fields defined as discrete Fourier transforms (k-grid) * \param out components of fields in symmetry adapted basis * \param checkSymmetry flag indicate whether to check symmetry * \param epsilon error tolerance for symmetry test (if any) */ void convertKGridToBasis(DArray< RFieldDft<D> > const & in, DArray< DArray<double> > & out, bool checkSymmetry = true, double epsilon = 1.0e-8) const; /** * Convert a field from symmetrized basis to spatial grid (r-grid). * * \param in field in symmetry adapted basis form * \param out field defined on real-space grid */ void convertBasisToRGrid(DArray<double> const & in, RField<D> & out) const; /** * Convert fields from symmetrized basis to spatial grid (r-grid). * * \param in fields in symmetry adapted basis form * \param out fields defined on real-space grid */ void convertBasisToRGrid(DArray< DArray<double> > const & in, DArray< RField<D> > & out) const ; /** * Convert a field from spatial grid (r-grid) to symmetrized basis. * * \param in field defined on real-space grid * \param out field in symmetry adapted basis form * \param checkSymmetry boolean indicating whether to check that the * symmetry of the input field matches the space group symmetry. If * input does not have correct symmetry, prints warning to Log::file() * \param epsilon if checkSymmetry = true, epsilon is the error * threshold used when comparing the k-grid and symmetry-adapted formats * to determine whether field has the declared space group symmetry */ void convertRGridToBasis(RField<D> const & in, DArray<double> & out, bool checkSymmetry = true, double epsilon = 1.0e-8) const; /** * Convert fields from spatial grid (r-grid) to symmetrized basis. * * \param in fields defined on real-space grid * \param out fields in symmetry adapted basis form * \param checkSymmetry boolean indicating whether to check that the * symmetry of the input field matches the space group symmetry. If * input does not have correct symmetry, prints warning to Log::file() * \param epsilon if checkSymmetry = true, epsilon is the error * threshold used when comparing the k-grid and symmetry-adapted formats * to determine whether field has the declared space group symmetry */ void convertRGridToBasis(DArray< RField<D> > const & in, DArray< DArray<double> > & out, bool checkSymmetry = true, double epsilon = 1.0e-8) const; /** * Convert fields from k-grid (DFT) to real space (r-grid) format. * * This function simply calls the inverse FFT for an array of fields. * The inverse FFT provided by the underlying FFTW library overwrites * its input, which is why argument "in" not a const reference. * * \param in fields in discrete Fourier format (k-grid) * \param out fields defined on real-space grid (r-grid) */ void convertKGridToRGrid(DArray< RFieldDft<D> > & in, DArray< RField<D> > & out) const; /** * Convert a field from k-grid (DFT) to real space (r-grid) format. * * This function simply calls the inverse FFT for a single field. * The inverse FFT provided by the underlying FFTW library overwrites * its input, which is why argument "in" not a const reference. * * \param in field in discrete Fourier format (k-grid) * \param out field defined on real-space grid (r-grid) */ void convertKGridToRGrid(RFieldDft<D> & in, RField<D> & out) const; /** * Convert fields from spatial grid (r-grid) 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< RField<D> > const & in, DArray< RFieldDft<D> > & out) const; /** * Convert a field from spatial grid (r-grid) to k-grid format. * * \param in field defined on real-space grid (r-grid) * \param out field in discrete Fourier format (k-grid) */ void convertRGridToKGrid(RField<D> const & in, RFieldDft<D> & out) const; ///@} /// \name Test Space Group Symmetry ///@{ /** * Check if an r-grid field has the declared space group symmetry. * * \param in field in real space grid (r-grid) format * \param epsilon error threshold used when comparing the k-grid and * symmetry-adapted formats to determine whether field has the declared * space group symmetry. * \param verbose if field does not have symmetry and verbose = true, * function will write error values to Log::file(). * \return true if the field is symmetric, false otherwise */ bool hasSymmetry(RField<D> const & in, double epsilon = 1.0e-8, bool verbose = true) const; /** * Check if a k-grid field has declared space group symmetry. * * \param in field in real space grid (r-grid) format * \param epsilon error threshold used when comparing the k-grid and * symmetry-adapted formats to determine whether field has the declared * space group symmetry. * \param verbose if field does not have symmetry and verbose = true, * function will write error values to Log::file(). * \return true if the field is symmetric, false otherwise */ bool hasSymmetry(RFieldDft<D> const & in, double epsilon = 1.0e-8, bool verbose = true) const; ///@} private: // DFT work array for two-step conversion basis <-> kgrid <-> r-grid. mutable RFieldDft<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 group name string by const reference. typename UnitCell<D>::LatticeSystem & lattice() const { UTIL_ASSERT(latticePtr_); return *latticePtr_; } /// Get group name string by const reference. std::string & groupName() const { UTIL_ASSERT(groupNamePtr_); return *groupNamePtr_; } /// Get SpaceGroup by const reference. SpaceGroup<D> & group() const { UTIL_ASSERT(groupPtr_); return *groupPtr_; } /// Get Basis by const reference. Basis<D> & basis() const { UTIL_ASSERT(basisPtr_); return *basisPtr_; } /// Get FileMaster by reference. FileMaster const & fileMaster() const { UTIL_ASSERT(fileMasterPtr_); return *fileMasterPtr_; } /** * Check state of work array, allocate if necessary. */ void checkWorkDft() const; }; #ifndef PSPC_FIELD_IO_TPP extern template class FieldIo<1>; extern template class FieldIo<2>; extern template class FieldIo<3>; #endif } // namespace Pspc } // namespace Pscf #endif
27,959
C++
.h
645
34.007752
78
0.614206
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,212
RFieldDft.h
dmorse_pscfpp/src/pspc/field/RFieldDft.h
#ifndef PSPC_R_FIELD_DFT_H #define PSPC_R_FIELD_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 "Field.h" #include <pscf/math/IntVec.h> #include <util/global.h> #include <fftw3.h> namespace Pscf { namespace Pspc { using namespace Util; using namespace Pscf; /** * Fourier transform of a real field on an FFT mesh. * * \ingroup Pspc_Field_Module */ template <int D> class RFieldDft : public Field<fftw_complex> { public: /** * Default constructor. */ RFieldDft(); /** * Copy constructor. * * Allocates new memory and copies all elements by value. * *\param other the RFieldDft to be copied. */ RFieldDft(RFieldDft<D> const & other); /** * Destructor. * * Deletes underlying C array, if allocated previously. */ virtual ~RFieldDft(); /** * 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 */ RFieldDft<D>& operator = (RFieldDft<D> const & other); using Field<fftw_complex>::allocate; /** * Allocate the underlying C array for an FFT grid. * * \throw Exception if the RFieldDft is already allocated. * * \param meshDimensions vector of grid points in each direction */ void allocate(IntVec<D> const & meshDimensions); /** * Return vector of spatial mesh dimensions by constant reference. */ IntVec<D> const & meshDimensions() const; /** * Return vector of dft (Fourier) grid dimensions by constant 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. */ IntVec<D> const & 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); 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 RFieldDft<D>::allocate(IntVec<D> const & 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 *= dftDimensions_[i]; } } Field<fftw_complex>::allocate(size); } /* * Return mesh dimensions by constant reference. */ template <int D> inline IntVec<D> const & RFieldDft<D>::meshDimensions() const { return meshDimensions_; } /* * Return dimensions of dft grid by constant reference. */ template <int D> inline IntVec<D> const & RFieldDft<D>::dftDimensions() const { return dftDimensions_; } /* * Serialize a Field to/from an Archive. */ template <int D> template <class Archive> void RFieldDft<D>::serialize(Archive& ar, const unsigned int version) { Field<fftw_complex>::serialize(ar, version); ar & meshDimensions_; ar & dftDimensions_; } #ifndef PSPC_R_FIELD_DFT_TPP extern template class RFieldDft<1>; extern template class RFieldDft<2>; extern template class RFieldDft<3>; #endif } } #endif
4,108
C++
.h
141
23.368794
77
0.627759
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,213
CFieldContainer.h
dmorse_pscfpp/src/pspc/field/CFieldContainer.h
#ifndef PSPC_C_FIELD_CONTAINER_H #define PSPC_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 <pspc/field/RField.h> // member template parameter namespace Pscf { namespace Pspc { 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 RField<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 Pspc_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< RField<D> > & rgrid() { return rgrid_; } /** * Get array of all fields in r-grid format (const). */ DArray< RField<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) */ RField<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) */ RField<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 RField<D> that contains values of the * field associated with monomer i on the nodes of a regular mesh. */ DArray< RField<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 PSPC_FIELD_CONTAINER_TPP // Suppress implicit instantiation extern template class CFieldContainer<1>; extern template class CFieldContainer<2>; extern template class CFieldContainer<3>; #endif } // namespace Pspc } // namespace Pscf #endif
5,647
C++
.h
179
25.329609
76
0.618951
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,214
WFieldContainer.h
dmorse_pscfpp/src/pspc/field/WFieldContainer.h
#ifndef PSPC_W_FIELD_CONTAINER_H #define PSPC_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 <pspc/field/RField.h> // member template parameter #include <util/containers/DArray.h> // member template namespace Pscf { namespace Pspc { 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 RField<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 Pspc_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< RField<D> > const & fields, bool isSymmetric = false); /** * 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); /** * 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< RField<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) */ RField<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 RField<D> that contains values of the * field associated with monomer i on the nodes of a regular mesh. */ DArray< RField<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< RField<D> > const & WFieldContainer<D>::rgrid() const { return rgrid_; } // Get one field in r-grid format (const) template <int D> inline RField<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 PSPC_W_FIELD_CONTAINER_TPP // Suppress implicit instantiation extern template class WFieldContainer<1>; extern template class WFieldContainer<2>; extern template class WFieldContainer<3>; #endif } // namespace Pspc } // namespace Pscf #endif
12,942
C++
.h
355
30.076056
76
0.653819
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,215
RFieldComparison.h
dmorse_pscfpp/src/pspc/field/RFieldComparison.h
#ifndef PSPC_R_FIELD_COMPARISON_H #define PSPC_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 "RField.h" namespace Pscf { namespace Pspc { using namespace Util; /** * Comparator for fields in real-space (r-grid) format. * * \ingroup Pspc_Field_Module */ template <int D> class RFieldComparison : public FieldComparison< RField<D> > {}; #ifndef PSPC_R_FIELD_COMPARISON_CPP extern template class RFieldComparison<1>; extern template class RFieldComparison<2>; extern template class RFieldComparison<3>; #endif } // namespace Pspc } // namespace Pscf #endif
814
C++
.h
29
25.344828
67
0.746787
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,216
paths.h
dmorse_pscfpp/make/config/paths.h
#ifndef PSCF_PATHS_H #define PSCF_PATHS_H /** * \file paths.h * \brief File containing absolute paths to data, for use in code and tests. * * These paths are set in by the "setup" script, which must be rerun if the * pscfpp directory tree is relocated. */ #define PSCF_ROOT_DIR PWD/ #define PSCF_DATA_DIR PWD/data/ #define PSCF_XMPL_DIR PWD/examples/ #endif
362
C++
.h
13
26.615385
75
0.757225
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,217
AmIteratorOld.tpp
dmorse_pscfpp/docs/notes/attic/pspg/AmIteratorOld.tpp
#ifndef PSPG_AM_ITERATOR_OLD_TPP #define PSPG_AM_ITERATOR_OLD_TPP /* * PSCF - Polymer Self-Consistent Field Theory * * Copyright 2016 - 2019, The Regents of the University of Minnesota * Distributed under the terms of the GNU General Public License. */ #include "AmIteratorOld.h" #include <pspg/System.h> #include <pspg/math/GpuResources.h> #include <pscf/inter/ChiInteraction.h> #include <util/format/Dbl.h> #include <util/containers/FArray.h> #include <util/misc/Timer.h> #include <sys/time.h> namespace Pscf { namespace Pspg { using namespace Util; template <int D> AmIteratorOld<D>::AmIteratorOld(System<D>& system) : Iterator<D>(system), epsilon_(0), lambda_(0), nHist_(0), maxHist_(0), isFlexible_(0) { setClassName("AmIteratorOld"); } template <int D> AmIteratorOld<D>::~AmIteratorOld() { delete[] temp_; cudaFree(d_temp_); } template <int D> void AmIteratorOld<D>::readParameters(std::istream& in) { isFlexible_ = 0; errorType_ = "normResid"; // default type of error read(in, "maxItr", maxItr_); read(in, "epsilon", epsilon_); read(in, "maxHist", maxHist_); readOptional(in, "errorType", errorType_); // Read in additional parameters readOptional(in, "isFlexible", isFlexible_); if (!(errorType_ == "normResid" || errorType_ == "maxResid")) { UTIL_THROW("Invalid iterator error type in parameter file."); } } template <int D> void AmIteratorOld<D>::setup() { // GPU resources const int size = system().mesh().size(); int NUMBER_OF_BLOCKS, THREADS_PER_BLOCK; ThreadGrid::setThreadsLogical(size, NUMBER_OF_BLOCKS, THREADS_PER_BLOCK); d_resHists_.allocate(maxHist_ + 1); d_omHists_.allocate(maxHist_ + 1); if (isFlexible_) { devCpHists_.allocate(maxHist_+1); CpHists_.allocate(maxHist_+1); } wArrays_.allocate(system().mixture().nMonomer()); dArrays_.allocate(system().mixture().nMonomer()); tempDev.allocate(system().mixture().nMonomer()); for (int i = 0; i < system().mixture().nMonomer(); ++i) { wArrays_[i].allocate(system().mesh().size()); dArrays_[i].allocate(system().mesh().size()); tempDev[i].allocate(system().mesh().size()); } histMat_.allocate(maxHist_ + 1); //allocate d_temp_ here i suppose cudaMalloc((void**)&d_temp_, NUMBER_OF_BLOCKS * sizeof(cudaReal)); temp_ = new cudaReal[NUMBER_OF_BLOCKS]; } template <int D> int AmIteratorOld<D>::solve() { // Define Timer objects Timer solverTimer; Timer stressTimer; Timer updateTimer; Timer::TimePoint now; bool done; // Solve MDE for initial state solverTimer.start(); system().mixture().compute(system().wFieldsRGrid(), system().cFieldsRGrid()); now = Timer::now(); solverTimer.stop(now); // Compute stress for initial state if (isFlexible_) { stressTimer.start(now); system().mixture().computeStress(system().wavelist()); for (int m = 0; m < system().unitCell().nParameter() ; ++m){ Log::file() << "Stress " << m << " = " << system().mixture().stress(m)<<"\n"; } for (int m = 0; m < system().unitCell().nParameter() ; ++m){ Log::file() << "Parameter " << m << " = " << (system().unitCell()).parameter(m)<<"\n"; } now = Timer::now(); stressTimer.stop(now); } // Anderson-Mixing iterative loop int itr; for (itr = 1; itr <= maxItr_; ++itr) { updateTimer.start(now); Log::file() << "---------------------" << std::endl; Log::file() << " Iteration " << itr << std::endl; if (itr <= maxHist_) { lambda_ = 1.0 - pow(0.9, itr); nHist_ = itr - 1; } else { lambda_ = 1.0; nHist_ = maxHist_; } computeDeviation(); done = isConverged(); if (done) { updateTimer.stop(); if (itr > maxHist_ + 1) { invertMatrix_.deallocate(); coeffs_.deallocate(); vM_.deallocate(); } Log::file() << "------- CONVERGED ---------"<< std::endl; // Output final timing results double updateTime = updateTimer.time(); double solverTime = solverTimer.time(); double stressTime = 0.0; double totalTime = updateTime + solverTime; if (isFlexible_) { stressTime = stressTimer.time(); totalTime += stressTime; } Log::file() << "\n"; Log::file() << "Iterator times contributions:\n"; Log::file() << "\n"; Log::file() << "solver time = " << solverTime << " s, " << solverTime/totalTime << "\n"; Log::file() << "stress time = " << stressTime << " s, " << stressTime/totalTime << "\n"; Log::file() << "update time = " << updateTime << " s, " << updateTime/totalTime << "\n"; Log::file() << "total time = " << totalTime << " s "; Log::file() << "\n\n"; if (isFlexible_) { Log::file() << "\n"; Log::file() << "Final stress values:" << "\n"; for (int m = 0; m < system().unitCell().nParameter() ; ++m){ Log::file() << "Stress " << m << " = " << system().mixture().stress(m)<<"\n"; } Log::file() << "\n"; Log::file() << "Final unit cell parameter values:" << "\n"; for (int m = 0; m < system().unitCell().nParameter() ; ++m){ Log::file() << "Parameter " << m << " = " << (system().unitCell()).parameter(m)<<"\n"; } Log::file() << "\n"; } return 0; } else { // Resize history based matrix appropriately // consider making these working space local if (itr <= maxHist_ + 1) { if (nHist_ > 0) { invertMatrix_.allocate(nHist_, nHist_); coeffs_.allocate(nHist_); vM_.allocate(nHist_); } } int status = minimizeCoeff(itr); if (status == 1) { //abort the calculations and treat as failure (time out) //perform some clean up stuff invertMatrix_.deallocate(); coeffs_.deallocate(); vM_.deallocate(); return 1; } buildOmega(itr); if (itr <= maxHist_) { if (nHist_ > 0) { invertMatrix_.deallocate(); coeffs_.deallocate(); vM_.deallocate(); } } now = Timer::now(); updateTimer.stop(now); // Solve MDE solverTimer.start(now); system().mixture().compute(system().wFieldsRGrid(), system().cFieldsRGrid()); now = Timer::now(); solverTimer.stop(now); if (isFlexible_) { stressTimer.start(now); system().mixture().computeStress(system().wavelist()); for (int m = 0; m < system().unitCell().nParameter() ; ++m){ Log::file() << "Stress " << m << " = " << system().mixture().stress(m)<<"\n"; } for (int m = 0; m < system().unitCell().nParameter() ; ++m){ Log::file() << "Parameter " << m << " = " << (system().unitCell()).parameter(m)<<"\n"; } now = Timer::now(); stressTimer.stop(now); } } } if (itr > maxHist_ + 1) { invertMatrix_.deallocate(); coeffs_.deallocate(); vM_.deallocate(); } // Failure: Not converged after maxItr iterations. return 1; } template <int D> void AmIteratorOld<D>::computeDeviation() { // GPU resources const int size = system().mesh().size(); int NUMBER_OF_BLOCKS, THREADS_PER_BLOCK; ThreadGrid::setThreadsLogical(size, NUMBER_OF_BLOCKS, THREADS_PER_BLOCK); //need to average float average = 0; for (int i = 0; i < system().mixture().nMonomer(); ++i) { average += gpuSum(system().wFieldRGrid(i).cDField(), size); } average /= (system().mixture().nMonomer() * size); for (int i = 0; i < system().mixture().nMonomer(); ++i) { subtractUniform <<< NUMBER_OF_BLOCKS, THREADS_PER_BLOCK >>> (system().wFieldRGrid(i).cDField(), average, size); } d_omHists_.append(system().wFieldsRGrid()); if (isFlexible_) { CpHists_.append(system().unitCell().parameters()); } for (int i = 0; i < system().mixture().nMonomer(); ++i) { assignUniformReal <<< NUMBER_OF_BLOCKS, THREADS_PER_BLOCK >>> (tempDev[i].cDField(), 0, size); } for (int i = 0; i < system().mixture().nMonomer(); ++i) { for (int j = 0; j < system().mixture().nMonomer(); ++j) { pointWiseAddScale <<< NUMBER_OF_BLOCKS, THREADS_PER_BLOCK >>> (tempDev[i].cDField(), system().cFieldRGrid(j).cDField(), system().interaction().chi(i, j), size); //this is a good add but i dont necessarily know if its right pointWiseAddScale <<< NUMBER_OF_BLOCKS, THREADS_PER_BLOCK >>> (tempDev[i].cDField(), system().wFieldRGrid(j).cDField(), -system().interaction().idemp(i, j), size); } } float sum_chi_inv = (float) system().interaction().sum_inv(); for (int i = 0; i < system().mixture().nMonomer(); ++i) { pointWiseSubtractFloat <<< NUMBER_OF_BLOCKS, THREADS_PER_BLOCK >>> (tempDev[i].cDField(), 1/sum_chi_inv, size); } d_resHists_.append(tempDev); if (isFlexible_) { FArray<double, 6> tempCp; for (int i = 0; i<(system().unitCell()).nParameter(); i++){ //format???? tempCp [i] = -((system().mixture()).stress(i)); } devCpHists_.append(tempCp); } } template <int D> bool AmIteratorOld<D>::isConverged() { const int nMonomer = system().mixture().nMonomer(); const int nParameter = system().unitCell().nParameter(); const int size = system().mesh().size(); double matsenError; double dError = 0; double wError = 0; for (int i = 0; i < nMonomer; ++i) { dError += gpuInnerProduct(d_resHists_[0][i].cDField(), d_resHists_[0][i].cDField(), size); wError += gpuInnerProduct(system().wFieldRGrid(i).cDField(), system().wFieldRGrid(i).cDField(), size); } if (isFlexible_) { for ( int i = 0; i < nParameter; i++) { dError += devCpHists_[0][i] * devCpHists_[0][i]; wError += system().unitCell().parameter(i) * system().unitCell().parameter(i); } } Log::file() << " dError :" << Dbl(dError) << '\n'; Log::file() << " wError :" << Dbl(wError) << '\n'; matsenError = sqrt(dError / wError); Log::file() << " Error :" << Dbl(matsenError) << '\n'; // Find max residuals. cudaReal* tempRes = new cudaReal[nMonomer*size + nParameter]; double maxSCF=0.0, maxStress=0.0, maxRes=0.0; for (int i = 0; i < nMonomer; i++ ) { cudaMemcpy(&tempRes[i*size], d_resHists_[0][i].cDField(), size*sizeof(cudaReal), cudaMemcpyDeviceToHost); } for (int i = 0; i < nMonomer*size; i++ ) { if (fabs(tempRes[i] > maxSCF)) maxSCF = tempRes[i]; } maxRes = maxSCF; Log::file() << " Max SCF Residual :" << Dbl(maxRes) << '\n'; if (isFlexible_) { for (int i = 0; i < nParameter; i++ ) { if (fabs(devCpHists_[0][i]) > maxStress) maxStress = devCpHists_[0][i]; } // Compare SCF and stress residuals if (maxStress*10 > maxRes) maxRes = maxStress; Log::file() << " Max Stress Residual :" << Dbl(maxStress*10) << '\n'; } // Return convergence boolean for chosen error type if (errorType_ == "normResid") { return matsenError < epsilon_; } else if (errorType_ == "maxResid") { return maxRes < epsilon_; } else { UTIL_THROW("Invalid iterator error type in parameter file."); } } template <int D> int AmIteratorOld<D>::minimizeCoeff(int itr) { if (itr == 1) { //do nothing histMat_.reset(); return 0; } else { float elm, elm_cp; //clear last column and shift everything downwards if necessary histMat_.clearColumn(nHist_); //calculate the new values for d(k)d(k') matrix for (int i = 0; i < maxHist_ + 1; ++i) { if (i < nHist_ + 1) { elm = 0; for (int j = 0; j < system().mixture().nMonomer(); ++j) { elm += gpuInnerProduct(d_resHists_[0][j].cDField(), d_resHists_[i][j].cDField(), system().mesh().size()); } histMat_.evaluate(elm, nHist_, i); } } //build new Umn array for (int i = 0; i < nHist_; ++i) { for (int j = i; j < nHist_; ++j) { invertMatrix_(i, j) = histMat_.makeUmn(i, j, nHist_); if (isFlexible_) { elm_cp = 0; for (int m = 0; m < system().unitCell().nParameter(); ++m){ elm_cp += ((devCpHists_[0][m] - devCpHists_[i+1][m]) * (devCpHists_[0][m] - devCpHists_[j+1][m])); } invertMatrix_(i,j) += elm_cp; } invertMatrix_(j, i) = invertMatrix_(i, j); } } for (int i = 0; i < nHist_; ++i) { vM_[i] = histMat_.makeVm(i, nHist_); if (isFlexible_) { elm_cp = 0; for (int m = 0; m < system().unitCell().nParameter(); ++m){ vM_[i] += ((devCpHists_[0][m] - devCpHists_[i+1][m]) * (devCpHists_[0][m])); } } } if (itr == 2) { coeffs_[0] = vM_[0] / invertMatrix_(0, 0); } else { LuSolver solver; solver.allocate(nHist_); solver.computeLU(invertMatrix_); /* int status = solver.solve(vM_, coeffs_); if (status) { if (status == 1) { //matrix is singular do something return 1; } }*/ solver.solve(vM_, coeffs_); //for the sake of simplicity during porting //we leaves out checks for singular matrix here //--GK 09 11 2019 } return 0; } } template <int D> void AmIteratorOld<D>::buildOmega(int itr) { // GPU resources const int size = system().mesh().size(); int NUMBER_OF_BLOCKS, THREADS_PER_BLOCK; ThreadGrid::setThreadsLogical(size, NUMBER_OF_BLOCKS, THREADS_PER_BLOCK); if (itr == 1) { for (int i = 0; i < system().mixture().nMonomer(); ++i) { assignReal <<< NUMBER_OF_BLOCKS, THREADS_PER_BLOCK >>> (system().wFieldRGrid(i).cDField(), d_omHists_[0][i].cDField(), size); pointWiseAddScale <<< NUMBER_OF_BLOCKS, THREADS_PER_BLOCK >>> (system().wFieldRGrid(i).cDField(), d_resHists_[0][i].cDField(), lambda_, size); } if (isFlexible_) { cellParameters_.clear(); for (int m = 0; m < (system().unitCell()).nParameter() ; ++m){ cellParameters_.append(CpHists_[0][m] +lambda_* devCpHists_[0][m]); } system().unitCell().setParameters(cellParameters_); system().mixture().setupUnitCell(system().unitCell(), system().wavelist()); system().wavelist().computedKSq(system().unitCell()); } } else { //should be strictly correct. coeffs_ is a vector of size 1 if itr ==2 for (int j = 0; j < system().mixture().nMonomer(); ++j) { assignReal <<< NUMBER_OF_BLOCKS, THREADS_PER_BLOCK >>> (wArrays_[j].cDField(), d_omHists_[0][j].cDField(), size); assignReal <<< NUMBER_OF_BLOCKS, THREADS_PER_BLOCK >>> (dArrays_[j].cDField(), d_resHists_[0][j].cDField(), size); } for (int i = 0; i < nHist_; ++i) { for (int j = 0; j < system().mixture().nMonomer(); ++j) { //wArrays pointWiseBinarySubtract <<< NUMBER_OF_BLOCKS, THREADS_PER_BLOCK >>> (d_omHists_[i + 1][j].cDField(), d_omHists_[0][j].cDField(), tempDev[0].cDField(), size); pointWiseAddScale <<< NUMBER_OF_BLOCKS, THREADS_PER_BLOCK >>> (wArrays_[j].cDField(), tempDev[0].cDField(), coeffs_[i], size); //dArrays pointWiseBinarySubtract <<< NUMBER_OF_BLOCKS, THREADS_PER_BLOCK >>> (d_resHists_[i + 1][j].cDField(), d_resHists_[0][j].cDField(), tempDev[0].cDField(), size); pointWiseAddScale <<< NUMBER_OF_BLOCKS, THREADS_PER_BLOCK >>> (dArrays_[j].cDField(), tempDev[0].cDField(), coeffs_[i], size); } } for (int i = 0; i < system().mixture().nMonomer(); ++i) { assignReal <<< NUMBER_OF_BLOCKS, THREADS_PER_BLOCK >>> (system().wFieldRGrid(i).cDField(), wArrays_[i].cDField(), size); pointWiseAddScale <<< NUMBER_OF_BLOCKS, THREADS_PER_BLOCK >>> (system().wFieldRGrid(i).cDField(), dArrays_[i].cDField(), lambda_, size); } if (isFlexible_) { for (int m = 0; m < system().unitCell().nParameter() ; ++m){ wCpArrays_[m] = CpHists_[0][m]; dCpArrays_[m] = devCpHists_[0][m]; } for (int i = 0; i < nHist_; ++i) { for (int m = 0; m < system().unitCell().nParameter() ; ++m) { wCpArrays_[m] += coeffs_[i] * ( CpHists_[i+1][m]- CpHists_[0][m]); dCpArrays_[m] += coeffs_[i] * ( devCpHists_[i+1][m]- devCpHists_[0][m]); } } cellParameters_.clear(); for (int m = 0; m < system().unitCell().nParameter() ; ++m){ cellParameters_.append(wCpArrays_[m] + lambda_* dCpArrays_[m]); } system().unitCell().setParameters(cellParameters_); system().mixture().setupUnitCell(system().unitCell(), system().wavelist()); system().wavelist().computedKSq(system().unitCell()); } } } } } #endif
19,841
C++
.tpp
476
29.731092
123
0.488897
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,218
Field.tpp
dmorse_pscfpp/docs/notes/draft/cyln/field/Field.tpp
#ifndef CYLN_FIELD_TPP #define CYLN_FIELD_TPP /* * PSCF Package * * Copyright 2016 - 2017, The Regents of the University of Minnesota * Distributed under the terms of the GNU General Public License. */ #include "Field.h" #include <fftw3.h> namespace Pscf { namespace Cyln { using namespace Util; /* * Default constructor. */ template <typename Data> Field<Data>::Field() : data_(0), capacity_(0), nr_(0), nz_(0), slices_() {} /* * Destructor. */ template <typename Data> Field<Data>::~Field() { if (isAllocated()) { fftw_free(data_); capacity_ = 0; } } /* * Allocate the underlying C array. * * Throw an Exception if the Field has already allocated. * * \param capacity number of elements to allocate. */ template <typename Data> void Field<Data>::allocate(int nr, int nz) { if (isAllocated()) { UTIL_THROW("Attempt to re-allocate a Field"); } if (nr <= 0) { UTIL_THROW("Attempt to allocate with nr <= 0"); } if (nz <= 0) { UTIL_THROW("Attempt to allocate with nz <= 0"); } nr_ = nr; nz_ = nz; capacity_ = nr*nz; data_ = (Data*) fftw_malloc(sizeof(Data)*capacity_); // Allocate and associaetd array of 1D slices slices_.allocate(nr_); for (int i = 0; i < nr_; ++i) { slices_[i].associate(data_ + nz_*i, nz_); } } /* * Deallocate the underlying C array. * * Throw an Exception if this Field is not allocated. */ template <typename Data> void Field<Data>::deallocate() { if (!isAllocated()) { UTIL_THROW("Array is not allocated"); } fftw_free(data_); deallocate(slices_); capacity_ = 0; nr_ = 0; nz_ = 0; } } } #endif
1,860
C++
.tpp
85
16.835294
67
0.572887
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,219
System.tpp
dmorse_pscfpp/src/pspg/System.tpp
#ifndef PSPG_SYSTEM_TPP #define PSPG_SYSTEM_TPP /* * 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 "System.h" #include <pspg/sweep/Sweep.h> #include <pspg/sweep/SweepFactory.h> #include <pspg/iterator/Iterator.h> #include <pspg/iterator/IteratorFactory.h> #include <pspg/field/RDField.h> #include <pspg/math/GpuResources.h> #include <pscf/inter/Interaction.h> #include <pscf/math/IntVec.h> #include <pscf/homogeneous/Clump.h> #include <util/param/BracketPolicy.h> #include <util/format/Str.h> #include <util/format/Int.h> #include <util/format/Dbl.h> #include <util/misc/ioUtil.h> #include <string> #include <unistd.h> //#include <getopt.h> namespace Pscf { namespace Pspg { using namespace Util; /* * Constructor. */ template <int D> System<D>::System() : mixture_(), domain_(), fileMaster_(), homogeneous_(), interactionPtr_(0), iteratorPtr_(0), iteratorFactoryPtr_(0), sweepPtr_(0), sweepFactoryPtr_(0), w_(), c_(), fHelmholtz_(0.0), fIdeal_(0.0), fInter_(0.0), pressure_(0.0), hasMixture_(false), isAllocatedGrid_(false), isAllocatedBasis_(false), hasCFields_(false) { setClassName("System"); domain_.setFileMaster(fileMaster_); w_.setFieldIo(domain_.fieldIo()); interactionPtr_ = new Interaction(); iteratorFactoryPtr_ = new IteratorFactory<D>(*this); sweepFactoryPtr_ = new SweepFactory<D>(*this); BracketPolicy::set(BracketPolicy::Optional); ThreadGrid::init(); } /* * Destructor. */ template <int D> System<D>::~System() { if (interactionPtr_) { delete interactionPtr_; } if (iteratorPtr_) { delete iteratorPtr_; } if (iteratorFactoryPtr_) { delete iteratorFactoryPtr_; } if (sweepPtr_) { delete sweepPtr_; } if (sweepFactoryPtr_) { delete sweepFactoryPtr_; } } /* * Process command line options. */ template <int D> void System<D>::setOptions(int argc, char **argv) { bool eflag = false; // echo bool pFlag = false; // param file bool cFlag = false; // command file bool iFlag = false; // input prefix bool oFlag = false; // output prefix bool tFlag = false; // GPU input threads (max. # of threads per block) char* pArg = 0; char* cArg = 0; char* iArg = 0; char* oArg = 0; int tArg = 0; // Read program arguments int c; opterr = 0; while ((c = getopt(argc, argv, "er:p:c:i:o:t:")) != -1) { switch (c) { case 'e': eflag = true; break; case 'p': // parameter file pFlag = true; pArg = optarg; break; case 'c': // command file cFlag = true; cArg = optarg; break; case 'i': // input prefix iFlag = true; iArg = optarg; break; case 'o': // output prefix oFlag = true; oArg = optarg; break; case 't': //number of threads per block, user set tArg = atoi(optarg); tFlag = true; break; case '?': Log::file() << "Unknown option -" << optopt << std::endl; UTIL_THROW("Invalid command line option"); } } // Set flag to echo parameters as they are read. if (eflag) { Util::ParamComponent::setEcho(true); } // If option -p, set parameter file name if (pFlag) { fileMaster().setParamFileName(std::string(pArg)); } // If option -c, set command file name if (cFlag) { fileMaster().setCommandFileName(std::string(cArg)); } // If option -i, set path prefix for input files if (iFlag) { fileMaster().setInputPrefix(std::string(iArg)); } // If option -o, set path prefix for output files if (oFlag) { fileMaster().setOutputPrefix(std::string(oArg)); } // If option -t, set the threads per block. if (tFlag) { ThreadGrid::setThreadsPerBlock(tArg); } } /* * Read parameter file (including open and closing brackets). */ template <int D> void System<D>::readParam(std::istream& in) { readBegin(in, className().c_str()); readParameters(in); readEnd(in); } /* * Read default parameter file. */ template <int D> void System<D>::readParam() { readParam(fileMaster().paramFile()); } /* * Read parameters and initialize. */ template <int D> void System<D>::readParameters(std::istream& in) { // Read the Mixture{ ... } block readParamComposite(in, mixture()); hasMixture_ = true; int nm = mixture().nMonomer(); int np = mixture().nPolymer(); int ns = mixture().nSolvent(); UTIL_CHECK(nm > 0); UTIL_CHECK(np >= 0); UTIL_CHECK(ns >= 0); UTIL_CHECK(np + ns > 0); // Read the Interaction{ ... } block interaction().setNMonomer(mixture().nMonomer()); readParamComposite(in, interaction()); // Read the Domain{ ... } block readParamComposite(in, domain_); mixture().setMesh(mesh()); UTIL_CHECK(domain_.mesh().size() > 0); UTIL_CHECK(domain_.unitCell().nParameter() > 0); UTIL_CHECK(domain_.unitCell().lattice() != UnitCell<D>::Null); // Allocate memory for w and c fields allocateFieldsGrid(); if (domain_.basis().isInitialized()) { allocateFieldsBasis(); } // Optionally instantiate an Iterator object std::string className; bool isEnd; iteratorPtr_ = iteratorFactoryPtr_->readObjectOptional(in, *this, className, isEnd); if (!iteratorPtr_) { Log::file() << "Notification: No iterator was constructed\n"; } // Optionally instantiate a Sweep object (if an iterator exists) if (iteratorPtr_) { sweepPtr_ = sweepFactoryPtr_->readObjectOptional(in, *this, className, isEnd); } #if 0 // Initialize iterator std::string className; bool isEnd; iteratorPtr_ = iteratorFactoryPtr_->readObject(in, *this, className, isEnd); if (!iteratorPtr_) { std::string msg = "Unrecognized Iterator subclass name "; msg += className; UTIL_THROW(msg.c_str()); } // Optionally instantiate a Sweep object sweepPtr_ = sweepFactoryPtr_->readObjectOptional(in, *this, className, isEnd); if (sweepPtr_) { sweepPtr_->setSystem(*this); } #endif // Initialize homogeneous object homogeneous_.setNMolecule(np+ns); homogeneous_.setNMonomer(nm); initHomogeneous(); } /* * Read and execute commands from a specified command file. */ template <int D> void System<D>::readCommands(std::istream &in) { UTIL_CHECK(isAllocatedGrid_); std::string command, filename, inFileName, outFileName; bool readNext = true; while (readNext) { in >> command; if (in.eof()) { break; } else { Log::file() << command << std::endl; } if (command == "FINISH") { Log::file() << std::endl; readNext = false; } else if (command == "READ_W_BASIS") { readEcho(in, filename); readWBasis(filename); } else if (command == "READ_W_RGRID") { readEcho(in, filename); readWRGrid(filename); } else if (command == "ESTIMATE_W_FROM_C") { // Read c field file in r-grid format readEcho(in, inFileName); estimateWfromC(inFileName); } else if (command == "SET_UNIT_CELL") { UnitCell<D> unitCell; in >> unitCell; Log::file() << " " << unitCell << std::endl; setUnitCell(unitCell); } else if (command == "COMPUTE") { // Solve the modified diffusion equation for current w fields compute(); } else if (command == "ITERATE") { // Attempt to iteratively solve a SCFT problem int error = iterate(); if (error) { readNext = false; } } else if (command == "SWEEP") { // Attempt to solve a sequence of SCFT problems along a path // through parameter space sweep(); } else if (command == "WRITE_PARAM") { readEcho(in, filename); std::ofstream file; fileMaster().openOutputFile(filename, file); writeParamNoSweep(file); file.close(); } else if (command == "WRITE_THERMO") { readEcho(in, filename); std::ofstream file; fileMaster().openOutputFile(filename, file, std::ios_base::app); writeThermo(file); file.close(); } else if (command == "WRITE_W_BASIS") { UTIL_CHECK(w_.hasData()); UTIL_CHECK(w_.isSymmetric()); readEcho(in, filename); fieldIo().writeFieldsBasis(filename, w_.basis(), domain_.unitCell()); } else if (command == "WRITE_W_RGRID") { UTIL_CHECK(w_.hasData()); readEcho(in, filename); fieldIo().writeFieldsRGrid(filename, w_.rgrid(), domain_.unitCell()); } else if (command == "WRITE_C_BASIS") { readEcho(in, filename); UTIL_CHECK(hasCFields_); UTIL_CHECK(w_.isSymmetric()); fieldIo().writeFieldsBasis(filename, c_.basis(), domain_.unitCell()); } else if (command == "WRITE_C_RGRID") { UTIL_CHECK(hasCFields_); readEcho(in, filename); fieldIo().writeFieldsRGrid(filename, c_.rgrid(), domain_.unitCell()); } else if (command == "WRITE_BLOCK_C_RGRID") { readEcho(in, filename); writeBlockCRGrid(filename); } else if (command == "WRITE_Q_SLICE") { int polymerId, blockId, directionId, segmentId; readEcho(in, filename); in >> polymerId; in >> blockId; in >> directionId; in >> segmentId; Log::file() << Str("polymer ID ", 21) << polymerId << "\n" << Str("block ID ", 21) << blockId << "\n" << Str("direction ID ", 21) << directionId << "\n" << Str("segment ID ", 21) << segmentId << std::endl; writeQSlice(filename, polymerId, blockId, directionId, segmentId); } else if (command == "WRITE_Q_TAIL") { int polymerId, blockId, directionId; readEcho(in, filename); in >> polymerId; in >> blockId; in >> directionId; Log::file() << Str("polymer ID ", 21) << polymerId << "\n" << Str("block ID ", 21) << blockId << "\n" << Str("direction ID ", 21) << directionId << "\n"; writeQTail(filename, polymerId, blockId, directionId); } else if (command == "WRITE_Q") { int polymerId, blockId, directionId; readEcho(in, filename); in >> polymerId; in >> blockId; in >> directionId; Log::file() << Str("polymer ID ", 21) << polymerId << "\n" << Str("block ID ", 21) << blockId << "\n" << Str("direction ID ", 21) << directionId << "\n"; writeQ(filename, polymerId, blockId, directionId); } else if (command == "WRITE_Q_ALL") { readEcho(in, filename); writeQAll(filename); } else if (command == "WRITE_STARS") { readEcho(in, filename); writeStars(filename); } else if (command == "WRITE_WAVES") { readEcho(in, filename); writeWaves(filename); } else if (command == "WRITE_GROUP") { readEcho(in, filename); writeGroup(filename); //writeGroup(filename, domain_.group()); } else if (command == "BASIS_TO_RGRID") { readEcho(in, inFileName); readEcho(in, outFileName); basisToRGrid(inFileName, outFileName); } else if (command == "RGRID_TO_BASIS") { readEcho(in, inFileName); readEcho(in, outFileName); rGridToBasis(inFileName, outFileName); } else if (command == "KGRID_TO_RGRID") { readEcho(in, inFileName); readEcho(in, outFileName); kGridToRGrid(inFileName, outFileName); } else if (command == "RGRID_TO_KGRID") { readEcho(in, inFileName); readEcho(in, outFileName); rGridToKGrid(inFileName, outFileName); } else if (command == "KGRID_TO_BASIS") { readEcho(in, inFileName); readEcho(in, outFileName); kGridToBasis(inFileName, outFileName); } else if (command == "BASIS_TO_KGRID") { readEcho(in, inFileName); readEcho(in, outFileName); basisToKGrid(inFileName, outFileName); } else { Log::file() << " Error: Unknown command " << command << std::endl; readNext = false; } } } /* * Read and execute commands from the default command file. */ template <int D> void System<D>::readCommands() { if (fileMaster().commandFileName().empty()) { UTIL_THROW("Empty command file name"); } readCommands(fileMaster().commandFile()); } // W-Field Modifier Functions /* * Read w-field in symmetry adapted basis format. */ template <int D> void System<D>::readWBasis(const std::string & filename) { // If basis fields are not allocated, peek at field file header to // get unit cell parameters, initialize basis and allocate fields. if (!isAllocatedBasis_) { readFieldHeader(filename); allocateFieldsBasis(); } // Read w fields w_.readBasis(filename, domain_.unitCell()); domain_.waveList().computeKSq(domain_.unitCell()); domain_.waveList().computedKSq(domain_.unitCell()); mixture_.setupUnitCell(domain_.unitCell(), domain_.waveList()); hasCFields_ = false; } template <int D> void System<D>::readWRGrid(const std::string & filename) { // If basis fields are not allocated, peek at field file header to // get unit cell parameters, initialize basis and allocate fields. if (!isAllocatedBasis_) { readFieldHeader(filename); allocateFieldsBasis(); } w_.readRGrid(filename, domain_.unitCell()); domain_.waveList().computeKSq(domain_.unitCell()); domain_.waveList().computedKSq(domain_.unitCell()); mixture_.setupUnitCell(domain_.unitCell(), domain_.waveList()); hasCFields_ = false; } /* * Set new w-field values. */ template <int D> void System<D>::setWBasis(DArray< DArray<double> > const & fields) { w_.setBasis(fields); hasCFields_ = false; } /* * Set new w-field values, using r-grid fields as inputs. */ template <int D> void System<D>::setWRGrid(DArray< RDField<D> > const & fields) { w_.setRGrid(fields); hasCFields_ = false; } /* * Set new w-field values, using unfoldeded array of r-grid fields. */ template <int D> void System<D>::setWRGrid(DField<cudaReal> & fields) { w_.setRGrid(fields); hasCFields_ = false; } /* * Construct estimate for w-fields from c-fields. * * Modifies wFields and wFieldsRGrid. */ template <int D> void System<D>::estimateWfromC(std::string const & filename) { UTIL_CHECK(hasMixture_); const int nMonomer = mixture_.nMonomer(); UTIL_CHECK(nMonomer > 0); // If basis fields are not allocated, peek at field file header to // get unit cell parameters, initialize basis and allocate fields. if (!isAllocatedBasis_) { readFieldHeader(filename); allocateFieldsBasis(); } UTIL_CHECK(domain_.basis().isInitialized()); const int nBasis = domain_.basis().nBasis(); UTIL_CHECK(nBasis > 0); // Allocate temporary storage DArray< DArray<double> > tmpCFieldsBasis; tmpCFieldsBasis.allocate(nMonomer); for (int i = 0; i < nMonomer; ++i) { tmpCFieldsBasis[i].allocate(nBasis); } // Read c fields from input file fieldIo().readFieldsBasis(filename, tmpCFieldsBasis, domain_.unitCell()); // Compute w fields from c fields for (int i = 0; i < nBasis; ++i) { for (int j = 0; j < nMonomer; ++j) { tmpFieldsBasis_[j][i] = 0.0; for (int k = 0; k < nMonomer; ++k) { tmpFieldsBasis_[j][i] += interaction().chi(j,k) * tmpCFieldsBasis[k][i]; } } } // Store estimated w fields in System w container w_.setBasis(tmpFieldsBasis_); hasCFields_ = false; } /* * Set new w-field values, using array of r-grid fields as input. */ template <int D> void System<D>::symmetrizeWFields() { w_.symmetrize(); } // Unit Cell Modifiers /* * Set the associated unit cell. */ template <int D> void System<D>::setUnitCell(UnitCell<D> const & unitCell) { domain_.setUnitCell(unitCell); mixture_.setupUnitCell(unitCell, domain_.waveList()); if (!isAllocatedBasis_) { allocateFieldsBasis(); } } /* * Set the associated unit cell. */ template <int D> void System<D>::setUnitCell(typename UnitCell<D>::LatticeSystem lattice, FSArray<double, 6> const & parameters) { domain_.setUnitCell(lattice, parameters); mixture_.setupUnitCell(domain_.unitCell(), domain_.waveList()); if (!isAllocatedBasis_) { allocateFieldsBasis(); } } /* * Set parameters of the associated unit cell. */ template <int D> void System<D>::setUnitCell(FSArray<double, 6> const & parameters) { domain_.setUnitCell(parameters); mixture_.setupUnitCell(domain_.unitCell(), domain_.waveList()); if (!isAllocatedBasis_) { allocateFieldsBasis(); } } // Primary SCFT Computations /* * Solve MDE for current w-fields, without iteration. */ template <int D> void System<D>::compute(bool needStress) { UTIL_CHECK(w_.hasData()); // Solve the modified diffusion equation (without iteration) mixture().compute(w_.rgrid(), c_.rgrid()); hasCFields_ = true; // Convert c fields from r-grid to basis format if (w_.isSymmetric()) { fieldIo().convertRGridToBasis(c_.rgrid(), c_.basis()); } if (needStress) { mixture().computeStress(domain_.waveList()); } } /* * Iteratively solve a SCFT problem for specified parameters. */ template <int D> int System<D>::iterate(bool isContinuation) { UTIL_CHECK(w_.hasData()); hasCFields_ = false; Log::file() << std::endl; Log::file() << std::endl; // Call iterator int error = iterator().solve(isContinuation); hasCFields_ = true; if (w_.isSymmetric()) { fieldIo().convertRGridToBasis(c_.rgrid(), c_.basis()); } if (!error) { if (!iterator().isFlexible()) { mixture().computeStress(domain_.waveList()); } computeFreeEnergy(); writeThermo(Log::file()); } return error; } /* * Perform sweep along a line in parameter space. */ template <int D> void System<D>::sweep() { UTIL_CHECK(w_.hasData()); UTIL_CHECK(w_.isSymmetric()); UTIL_CHECK(sweepPtr_); UTIL_CHECK(hasSweep()); Log::file() << std::endl; Log::file() << std::endl; // Perform sweep sweepPtr_->sweep(); } // Thermodynamic Properties /* * Compute Helmholtz free energy and pressure */ template <int D> void System<D>::computeFreeEnergy() { UTIL_CHECK(w_.hasData()); UTIL_CHECK(hasCFields_); // Initialize to zero fHelmholtz_ = 0.0; double phi, mu; int np = mixture_.nPolymer(); int ns = mixture_.nSolvent(); // Compute polymer ideal gas contributions to fHelhmoltz_ if (np > 0) { Polymer<D>* polymerPtr; double phi, mu, length; int np = mixture().nPolymer(); for (int i = 0; i < np; ++i) { polymerPtr = &mixture().polymer(i); phi = polymerPtr->phi(); mu = polymerPtr->mu(); // Recall: mu = ln(phi/q) length = polymerPtr->length(); if (phi > 1E-08) { fHelmholtz_ += phi*( mu - 1.0 )/length; } } } // Compute solvent ideal gas contributions to fHelhmoltz_ if (ns > 0) { Solvent<D>* solventPtr; double size; for (int i = 0; i < ns; ++i) { solventPtr = &mixture_.solvent(i); phi = solventPtr->phi(); mu = solventPtr->mu(); size = solventPtr->size(); if (phi > 1E-08) { fHelmholtz_ += phi*( mu - 1.0 )/size; } } } int nm = mixture().nMonomer(); int nx = mesh().size(); // GPU resources int nBlocks, nThreads; ThreadGrid::setThreadsLogical(nx, nBlocks, nThreads); // Compute Legendre transform subtraction double temp = 0.0; for (int i = 0; i < nm; i++) { pointWiseBinaryMultiply<<<nBlocks,nThreads>>> (w_.rgrid(i).cDField(), c_.rgrid()[i].cDField(), workArray_.cDField(), nx); temp += gpuSum(workArray_.cDField(),nx) / double(nx); } fHelmholtz_ -= temp; fIdeal_ = fHelmholtz_; // Compute excess interaction free energy for (int i = 0; i < nm; ++i) { for (int j = i + 1; j < nm; ++j) { assignUniformReal<<<nBlocks, nThreads>>> (workArray_.cDField(), interaction().chi(i, j), nx); inPlacePointwiseMul<<<nBlocks, nThreads>>> (workArray_.cDField(), c_.rgrid()[i].cDField(), nx); inPlacePointwiseMul<<<nBlocks, nThreads>>> (workArray_.cDField(), c_.rgrid()[j].cDField(), nx); fHelmholtz_ += gpuSum(workArray_.cDField(), nx) / double(nx); } } fInter_ = fHelmholtz_ - fIdeal_; // Initialize pressure pressure_ = -fHelmholtz_; // Polymer corrections to pressure if (np > 0) { Polymer<D>* polymerPtr; double length; for (int i = 0; i < np; ++i) { polymerPtr = &mixture_.polymer(i); phi = polymerPtr->phi(); mu = polymerPtr->mu(); length = polymerPtr->length(); if (phi > 1E-08) { pressure_ += mu * phi /length; } } } // Solvent corrections to pressure if (ns > 0) { Solvent<D>* solventPtr; double size; for (int i = 0; i < ns; ++i) { solventPtr = &mixture_.solvent(i); phi = solventPtr->phi(); mu = solventPtr->mu(); size = solventPtr->size(); if (phi > 1E-08) { pressure_ += mu * phi /size; } } } } // Output Operations /* * Write parameter file, omitting the sweep block. */ template <int D> void System<D>::writeParamNoSweep(std::ostream& out) const { out << "System{" << std::endl; mixture_.writeParam(out); interaction().writeParam(out); domain_.writeParam(out); if (iteratorPtr_) { iteratorPtr_->writeParam(out); } out << "}" << std::endl; } template <int D> void System<D>::writeThermo(std::ostream& out) { out << std::endl; out << "fHelmholtz " << Dbl(fHelmholtz(), 18, 11) << std::endl; out << "pressure " << Dbl(pressure(), 18, 11) << std::endl; out << std::endl; out << "fIdeal " << Dbl(fIdeal_, 18, 11) << std::endl; out << "fInter " << Dbl(fInter_, 18, 11) << std::endl; out << std::endl; int np = mixture_.nPolymer(); int ns = mixture_.nSolvent(); if (np > 0) { out << "polymers:" << std::endl; out << " " << " phi " << " mu " << std::endl; for (int i = 0; i < np; ++i) { out << Int(i, 5) << " " << Dbl(mixture_.polymer(i).phi(),18, 11) << " " << Dbl(mixture_.polymer(i).mu(), 18, 11) << std::endl; } out << std::endl; } if (ns > 0) { out << "solvents:" << std::endl; out << " " << " phi " << " mu " << std::endl; for (int i = 0; i < ns; ++i) { out << Int(i, 5) << " " << Dbl(mixture_.solvent(i).phi(),18, 11) << " " << Dbl(mixture_.solvent(i).mu(), 18, 11) << std::endl; } out << std::endl; } out << "cellParams:" << std::endl; for (int i = 0; i < unitCell().nParameter(); ++i) { out << Int(i, 5) << " " << Dbl(unitCell().parameter(i), 18, 11) << std::endl; } out << std::endl; } /* * Write w-fields in symmetry-adapted basis format. */ template <int D> void System<D>::writeWBasis(const std::string & filename) { UTIL_CHECK(w_.hasData()); UTIL_CHECK(w_.isSymmetric()); fieldIo().writeFieldsBasis(filename, w_.basis(), unitCell()); } /* * Write w-fields in real space grid file format. */ template <int D> void System<D>::writeWRGrid(const std::string & filename) const { UTIL_CHECK(w_.hasData()); fieldIo().writeFieldsRGrid(filename, w_.rgrid(), unitCell()); } /* * Write all concentration fields in symmetry-adapted basis format. */ template <int D> void System<D>::writeCBasis(const std::string & filename) { UTIL_CHECK(hasCFields_); UTIL_CHECK(w_.isSymmetric()); fieldIo().writeFieldsBasis(filename, c_.basis(), unitCell()); } /* * Write all concentration fields in real space (r-grid) format. */ template <int D> void System<D>::writeCRGrid(const std::string & filename) const { UTIL_CHECK(hasCFields_); fieldIo().writeFieldsRGrid(filename, c_.rgrid(), unitCell()); } /* * Write all concentration fields in real space (r-grid) format, for each * block (or solvent) individually rather than for each species. */ template <int D> void System<D>::writeBlockCRGrid(const std::string & filename) const { UTIL_CHECK(hasCFields_); // Create and allocate the DArray of fields to be written DArray< RDField<D> > blockCFields; blockCFields.allocate(mixture_.nSolvent() + mixture_.nBlock()); int n = blockCFields.capacity(); for (int i = 0; i < n; i++) { blockCFields[i].allocate(mesh().dimensions()); } // Get data from Mixture and write to file mixture_.createBlockCRGrid(blockCFields); fieldIo().writeFieldsRGrid(filename, blockCFields, unitCell()); } /* * Write the last time slice of the propagator in r-grid format. */ template <int D> void System<D>::writeQSlice(const std::string & filename, int polymerId, int blockId, int directionId, int segmentId) const { UTIL_CHECK(polymerId >= 0); UTIL_CHECK(polymerId < mixture_.nPolymer()); Polymer<D> const& polymer = mixture_.polymer(polymerId); UTIL_CHECK(blockId >= 0); UTIL_CHECK(blockId < polymer.nBlock()); UTIL_CHECK(directionId >= 0); UTIL_CHECK(directionId <= 1); Propagator<D> const& propagator = polymer.propagator(blockId, directionId); RDField<D> field; field.allocate(mesh().size()); cudaMemcpy(field.cDField(), propagator.q(segmentId), mesh().size() * sizeof(cudaReal), cudaMemcpyDeviceToDevice); fieldIo().writeFieldRGrid(filename, field, unitCell()); } /* * Write the last time slice of the propagator in r-grid format. */ template <int D> void System<D>::writeQTail(const std::string & filename, int polymerId, int blockId, int directionId) const { UTIL_CHECK(polymerId >= 0); UTIL_CHECK(polymerId < mixture_.nPolymer()); Polymer<D> const& polymer = mixture_.polymer(polymerId); UTIL_CHECK(blockId >= 0); UTIL_CHECK(blockId < polymer.nBlock()); UTIL_CHECK(directionId >= 0); UTIL_CHECK(directionId <= 1); Propagator<D> const& propagator = polymer.propagator(blockId, directionId); RDField<D> field; field.allocate(mesh().size()); cudaMemcpy(field.cDField(), propagator.tail(), mesh().size()*sizeof(cudaReal), cudaMemcpyDeviceToDevice); fieldIo().writeFieldRGrid(filename, field, unitCell()); } /* * Write the propagator for a block and direction. */ template <int D> void System<D>::writeQ(const std::string & filename, int polymerId, int blockId, int directionId) const { UTIL_CHECK(polymerId >= 0); UTIL_CHECK(polymerId < mixture_.nPolymer()); Polymer<D> const& polymer = mixture_.polymer(polymerId); UTIL_CHECK(blockId >= 0); UTIL_CHECK(blockId < polymer.nBlock()); UTIL_CHECK(directionId >= 0); UTIL_CHECK(directionId <= 1); Propagator<D> const& propagator = polymer.propagator(blockId, directionId); int ns = propagator.ns(); // Open file std::ofstream file; fileMaster_.openOutputFile(filename, file); // Write header fieldIo().writeFieldHeader(file, 1, unitCell()); file << "ngrid" << std::endl << " " << mesh().dimensions() << std::endl << "nslice" << std::endl << " " << ns << std::endl; // Write data RDField<D> field; field.allocate(mesh().size()); bool hasHeader = false; for (int i = 0; i < ns; ++i) { file << "slice " << i << std::endl; cudaMemcpy(field.cDField(), propagator.q(i), mesh().size() * sizeof(cudaReal), cudaMemcpyDeviceToDevice); fieldIo().writeFieldRGrid(file, field, unitCell(), hasHeader); } } /* * Write propagators for all blocks of all polymers to files. */ template <int D> void System<D>::writeQAll(std::string const & basename) { std::string filename; int np, nb, ip, ib, id; np = mixture_.nPolymer(); for (ip = 0; ip < np; ++ip) { //Polymer<D> const * polymerPtr = &mixture_.polymer(ip); //nb = polymerPtr->nBlock(); nb = mixture_.polymer(ip).nBlock(); for (ib = 0; ib < nb; ++ib) { for (id = 0; id < 2; ++id) { filename = basename; filename += "_"; filename += toString(ip); filename += "_"; filename += toString(ib); filename += "_"; filename += toString(id); filename += ".rq"; writeQ(filename, ip, ib, id); } } } } /* * Write description of symmetry-adapted stars and basis to file. */ template <int D> void System<D>::writeStars(const std::string & filename) const { UTIL_CHECK(domain_.basis().isInitialized()); std::ofstream outFile; fileMaster_.openOutputFile(filename, outFile); fieldIo().writeFieldHeader(outFile, mixture_.nMonomer(), unitCell()); basis().outputStars(outFile); } /* * Write a list of waves and associated stars to file. */ template <int D> void System<D>::writeWaves(const std::string & filename) const { UTIL_CHECK(domain_.basis().isInitialized()); std::ofstream outFile; fileMaster_.openOutputFile(filename, outFile); fieldIo().writeFieldHeader(outFile, mixture_.nMonomer(), unitCell()); basis().outputWaves(outFile); } /* * Write all elements of the space group to a file. */ template <int D> void System<D>::writeGroup(const std::string & filename) const { Pscf::writeGroup(filename, domain_.group()); } // Field File Operations /* * Convert fields from symmetry-adpated basis to real-space grid format. */ template <int D> void System<D>::basisToRGrid(const std::string & inFileName, const std::string & outFileName) { // If basis fields are not allocated, peek at field file header to // get unit cell parameters, initialize basis and allocate fields. if (!isAllocatedBasis_) { readFieldHeader(inFileName); allocateFieldsBasis(); } // Read, convert and write fields UnitCell<D> tmpUnitCell; fieldIo().readFieldsBasis(inFileName, tmpFieldsBasis_, tmpUnitCell); fieldIo().convertBasisToRGrid(tmpFieldsBasis_, tmpFieldsRGrid_); fieldIo().writeFieldsRGrid(outFileName, tmpFieldsRGrid_, tmpUnitCell); } /* * Convert fields from real-space grid to symmetry-adapted basis format. */ template <int D> void System<D>::rGridToBasis(const std::string & inFileName, const std::string & outFileName) { // If basis fields are not allocated, peek at field file header to // get unit cell parameters, initialize basis and allocate fields. if (!isAllocatedBasis_) { readFieldHeader(inFileName); allocateFieldsBasis(); } // Read, convert and write fields UnitCell<D> tmpUnitCell; fieldIo().readFieldsRGrid(inFileName, tmpFieldsRGrid_, tmpUnitCell); fieldIo().convertRGridToBasis(tmpFieldsRGrid_, tmpFieldsBasis_); fieldIo().writeFieldsBasis(outFileName, tmpFieldsBasis_, tmpUnitCell); } /* * Convert fields from Fourier (k-grid) to real-space (r-grid) format. */ template <int D> void System<D>::kGridToRGrid(const std::string & inFileName, const std::string& outFileName) { // If basis fields are not allocated, peek at field file header to // get unit cell parameters, initialize basis and allocate fields. if (!isAllocatedBasis_) { readFieldHeader(inFileName); allocateFieldsBasis(); } // Read, convert and write fields UnitCell<D> tmpUnitCell; fieldIo().readFieldsKGrid(inFileName, tmpFieldsKGrid_, tmpUnitCell); for (int i = 0; i < mixture_.nMonomer(); ++i) { fft().inverseTransform(tmpFieldsKGrid_[i], tmpFieldsRGrid_[i]); } fieldIo().writeFieldsRGrid(outFileName, tmpFieldsRGrid_, tmpUnitCell); } /* * Convert fields from real-space (r-grid) to Fourier (k-grid) format. */ template <int D> void System<D>::rGridToKGrid(const std::string & inFileName, const std::string & outFileName) { // If basis fields are not allocated, peek at field file header to // get unit cell parameters, initialize basis and allocate fields. if (!isAllocatedBasis_) { readFieldHeader(inFileName); allocateFieldsBasis(); } // Read, convert and write fields UnitCell<D> tmpUnitCell; fieldIo().readFieldsRGrid(inFileName, tmpFieldsRGrid_, tmpUnitCell); for (int i = 0; i < mixture_.nMonomer(); ++i) { fft().forwardTransform(tmpFieldsRGrid_[i], tmpFieldsKGrid_[i]); } fieldIo().writeFieldsKGrid(outFileName, tmpFieldsKGrid_, tmpUnitCell); } /* * Convert fields from Fourier (k-grid) to symmetry-adapted basis format. */ template <int D> void System<D>::kGridToBasis(const std::string & inFileName, const std::string& outFileName) { // If basis fields are not allocated, peek at field file header to // get unit cell parameters, initialize basis and allocate fields. if (!isAllocatedBasis_) { readFieldHeader(inFileName); allocateFieldsBasis(); } // Read, convert and write fields UnitCell<D> tmpUnitCell; fieldIo().readFieldsKGrid(inFileName, tmpFieldsKGrid_, tmpUnitCell); fieldIo().convertKGridToBasis(tmpFieldsKGrid_, tmpFieldsBasis_); fieldIo().writeFieldsBasis(outFileName, tmpFieldsBasis_, tmpUnitCell); } /* * Convert fields from symmetry-adapted basis to Fourier (k-grid) format. */ template <int D> void System<D>::basisToKGrid(const std::string & inFileName, const std::string & outFileName) { // If basis fields are not allocated, peek at field file header to // get unit cell parameters, initialize basis and allocate fields. if (!isAllocatedBasis_) { readFieldHeader(inFileName); allocateFieldsBasis(); } // Read, convert and write fields UnitCell<D> tmpUnitCell; fieldIo().readFieldsBasis(inFileName, tmpFieldsBasis_, tmpUnitCell); fieldIo().convertBasisToKGrid(tmpFieldsBasis_, tmpFieldsKGrid_); fieldIo().writeFieldsKGrid(outFileName, tmpFieldsKGrid_, tmpUnitCell); } // Private member functions /* * Allocate memory for fields. */ template <int D> void System<D>::allocateFieldsGrid() { // Preconditions UTIL_CHECK(hasMixture_); int nMonomer = mixture().nMonomer(); UTIL_CHECK(nMonomer > 0); UTIL_CHECK(domain_.mesh().size() > 0); UTIL_CHECK(!isAllocatedGrid_); // Alias for mesh dimensions IntVec<D> const & dimensions = domain_.mesh().dimensions(); // Allocate W Fields w_.setNMonomer(nMonomer); w_.allocateRGrid(dimensions); // Allocate C Fields c_.setNMonomer(nMonomer); c_.allocateRGrid(dimensions); // Allocate temporary work space tmpFieldsRGrid_.allocate(nMonomer); tmpFieldsKGrid_.allocate(nMonomer); for (int i = 0; i < nMonomer; ++i) { tmpFieldsRGrid_[i].allocate(dimensions); tmpFieldsKGrid_[i].allocate(dimensions); } workArray_.allocate(mesh().size()); ThreadGrid::setThreadsLogical(mesh().size()); isAllocatedGrid_ = true; } /* * Allocate memory for fields. */ template <int D> void System<D>::allocateFieldsBasis() { // Preconditions and constants UTIL_CHECK(hasMixture_); const int nMonomer = mixture().nMonomer(); UTIL_CHECK(nMonomer > 0); UTIL_CHECK(isAllocatedGrid_); UTIL_CHECK(!isAllocatedBasis_); UTIL_CHECK(domain_.unitCell().nParameter() > 0); UTIL_CHECK(domain_.mesh().size() > 0); UTIL_CHECK(domain_.basis().isInitialized()); const int nBasis = basis().nBasis(); UTIL_CHECK(nBasis > 0); w_.allocateBasis(nBasis); c_.allocateBasis(nBasis); // Temporary work space tmpFieldsBasis_.allocate(nMonomer); for (int i = 0; i < nMonomer; ++i) { tmpFieldsBasis_[i].allocate(nBasis); } // Allocate memory for waveList if (!domain_.waveList().hasMinimumImages()) { domain_.waveList().computeMinimumImages(domain_.mesh(), domain_.unitCell()); } isAllocatedBasis_ = true; } /* * Peek at field file header, initialize unit cell parameters and basis. */ template <int D> void System<D>::readFieldHeader(std::string filename) { UTIL_CHECK(hasMixture_); UTIL_CHECK(mixture_.nMonomer() > 0); // Open field file std::ifstream file; fileMaster_.openInputFile(filename, file); // Read field file header, and initialize basis if needed int nMonomer; domain_.fieldIo().readFieldHeader(file, nMonomer, domain_.unitCell()); // FieldIo::readFieldHeader initializes a basis if needed file.close(); // Postconditions UTIL_CHECK(mixture_.nMonomer() == nMonomer); UTIL_CHECK(domain_.unitCell().nParameter() > 0); UTIL_CHECK(domain_.unitCell().lattice() != UnitCell<D>::Null); UTIL_CHECK(domain_.unitCell().isInitialized()); UTIL_CHECK(domain_.basis().isInitialized()); UTIL_CHECK(domain_.basis().nBasis() > 0); } /* * Read a filename string and echo to log file (used in readCommands). */ template <int D> void System<D>::readEcho(std::istream& in, std::string& string) const { in >> string; Log::file() << " " << Str(string, 20) << std::endl; } /* * Read floating point number, echo to log file (used in readCommands). */ template <int D> void System<D>::readEcho(std::istream& in, double& value) const { in >> value; if (in.fail()) { UTIL_THROW("Unable to read floating point parameter."); } Log::file() << " " << Dbl(value, 20) << std::endl; } /* * Initialize Pscf::Homogeneous::Mixture homogeneous_ member. */ template <int D> void System<D>::initHomogeneous() { // Set number of molecular species and monomers int nm = mixture().nMonomer(); int np = mixture().nPolymer(); int ns = mixture().nSolvent(); UTIL_CHECK(homogeneous_.nMolecule() == np + ns); UTIL_CHECK(homogeneous_.nMonomer() == nm); int i; // molecule index int j; // monomer index // Loop over polymer molecule species if (np > 0) { DArray<double> cTmp; cTmp.allocate(nm); int k; // block or clump index int nb; // number of blocks int nc; // number of clumps for (i = 0; i < np; ++i) { // Initial array of clump sizes for (j = 0; j < nm; ++j) { cTmp[j] = 0.0; } // Compute clump sizes for all monomer types. nb = mixture_.polymer(i).nBlock(); for (k = 0; k < nb; ++k) { Block<D>& block = mixture_.polymer(i).block(k); j = block.monomerId(); cTmp[j] += block.length(); } // Count the number of clumps of nonzero size nc = 0; for (j = 0; j < nm; ++j) { if (cTmp[j] > 1.0E-8) { ++nc; } } homogeneous_.molecule(i).setNClump(nc); // Set clump properties for this Homogeneous::Molecule k = 0; // Clump index for (j = 0; j < nm; ++j) { if (cTmp[j] > 1.0E-8) { homogeneous_.molecule(i).clump(k).setMonomerId(j); homogeneous_.molecule(i).clump(k).setSize(cTmp[j]); ++k; } } homogeneous_.molecule(i).computeSize(); } } // Add solvent contributions if (ns > 0) { double size; int monomerId; for (int is = 0; is < ns; ++is) { i = is + np; monomerId = mixture_.solvent(is).monomerId(); size = mixture_.solvent(is).size(); homogeneous_.molecule(i).setNClump(1); homogeneous_.molecule(i).clump(0).setMonomerId(monomerId); homogeneous_.molecule(i).clump(0).setSize(size); homogeneous_.molecule(i).computeSize(); } } } #if 0 /* * Check if fields are symmetric under space group. */ template <int D> bool System<D>::checkRGridFieldSymmetry(const std::string & inFileName) const { // If basis fields are not allocated, peek at field file header to // get unit cell parameters, initialize basis and allocate fields. if (!isAllocatedBasis_) { readFieldHeader(inFileName); allocateFieldsBasis(); } UTIL_CHECK(domain_.basis().isInitialized()); const int nBasis = domain_.basis().nBasis(); UTIL_CHECK(nBasis > 0); UnitCell<D> tmpUnitCell; fieldIo().readFieldsRGrid(inFileName, tmpFieldsRGrid_, tmpUnitCell); for (int i = 0; i < mixture_.nMonomer(); ++i) { bool symmetric = fieldIo().hasSymmetry(tmpFieldsRGrid_[i]); if (!symmetric) { return false; } } return true; } #endif } // namespace Pspg } // namespace Pscf #endif
46,236
C++
.tpp
1,362
25.328194
76
0.559169
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,220
IteratorFactory.tpp
dmorse_pscfpp/src/pspg/iterator/IteratorFactory.tpp
#ifndef PSPG_ITERATOR_FACTORY_TPP #define PSPG_ITERATOR_FACTORY_TPP #include "IteratorFactory.h" // Subclasses of Iterator #include "AmIteratorBasis.h" #include "AmIteratorGrid.h" namespace Pscf { namespace Pspg { using namespace Util; /* * Constructor */ template <int D> IteratorFactory<D>::IteratorFactory(System<D>& system) : sysPtr_(&system) {} /* * Return a pointer to a instance of Iterator subclass className. */ template <int D> Iterator<D>* IteratorFactory<D>::factory(const std::string &className) const { Iterator<D>* ptr = 0; // Try subfactories first ptr = trySubfactories(className); if (ptr) return ptr; // Try to match classname if (className == "Iterator" || className == "AmIteratorBasis") { ptr = new AmIteratorBasis<D>(*sysPtr_); } else if (className == "AmIteratorGrid") { ptr = new AmIteratorGrid<D>(*sysPtr_); } return ptr; } } } #endif
1,001
C++
.tpp
38
21.657895
79
0.656513
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,221
AmIteratorBasis.tpp
dmorse_pscfpp/src/pspg/iterator/AmIteratorBasis.tpp
#ifndef PSPG_AM_ITERATOR_BASIS_TPP #define PSPG_AM_ITERATOR_BASIS_TPP /* * 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 "AmIteratorBasis.h" #include <pspg/System.h> #include <pscf/inter/Interaction.h> #include <pscf/iterator/NanException.h> #include <pspg/field/RDField.h> #include <util/global.h> namespace Pscf { namespace Pspg{ using namespace Util; // Constructor template <int D> AmIteratorBasis<D>::AmIteratorBasis(System<D>& system) : Iterator<D>(system) { setClassName("AmIteratorBasis"); } // Destructor template <int D> AmIteratorBasis<D>::~AmIteratorBasis() {} // Read parameter file block template <int D> void AmIteratorBasis<D>::readParameters(std::istream& in) { // Call parent class readParameters AmIteratorTmpl<Iterator<D>,DArray<double> >::readParameters(in); AmIteratorTmpl<Iterator<D>,DArray<double> >::readErrorType(in); // Allocate local modified copy of Interaction class interaction_.setNMonomer(system().mixture().nMonomer()); // Default parameter values isFlexible_ = 1; scaleStress_ = 10.0; // Read in additional parameters readOptional(in, "isFlexible", isFlexible_); readOptional(in, "scaleStress", scaleStress_); } // -- Protected virtual function -- // // Setup before entering iteration loop template <int D> void AmIteratorBasis<D>::setup(bool isContinuation) { // Setup by AM algorithm AmIteratorTmpl<Iterator<D>, DArray<double> >::setup(isContinuation); // Update chi matrix and related properties in member interaction_ interaction_.update(system().interaction()); } // -- Private virtual functions used to implement AM algorithm -- // template <int D> void AmIteratorBasis<D>::setEqual(DArray<double>& a, DArray<double> const & b) { a = b; } template <int D> double AmIteratorBasis<D>::dotProduct(DArray<double> const & a, DArray<double> const & b) { const int n = a.capacity(); UTIL_CHECK(b.capacity() == n); double product = 0.0; for (int i=0; i < n; ++i) { // if either value is NaN, throw NanException if (std::isnan(a[i]) || std::isnan(b[i])) { throw NanException("AmIteratorBasis::dotProduct", __FILE__, __LINE__, 0); } product += a[i] * b[i]; } return product; } // Compute and return maximum element of residual vector. template <int D> double AmIteratorBasis<D>::maxAbs(DArray<double> const & a) { const int n = a.capacity(); double max = 0.0; double value; for (int i = 0; i < n; i++) { value = a[i]; if (std::isnan(value)) { // if value is NaN, throw NanException throw NanException("AmIteratorBasis::dotProduct", __FILE__, __LINE__, 0); } if (fabs(value) > max) max = fabs(value); } return max; } #if 0 template <int D> double AmIteratorBasis<D>::norm(DArray<double> const & a) { const int n = a.capacity(); double data; double normSq = 0.0; for (int i=0; i < n; ++i) { data = a[i]; normSq += data*data; } return sqrt(normSq); } // Compute one element of U matrix of by computing a dot product template <int D> double AmIteratorBasis<D>::computeUDotProd(RingBuffer<DArray<double> > const & resBasis, int m, int n) { const int length = resBasis[0].capacity(); double dotprod = 0.0; for(int i = 0; i < length; i++) { dotprod += resBasis[m][i] * resBasis[n][i]; } return dotprod; } // Compute one element of V vector by computing a dot product template <int D> double AmIteratorBasis<D>::computeVDotProd(DArray<double> const & resCurrent, RingBuffer<DArray<double> > const & resBasis, int m) { const int length = resBasis[0].capacity(); double dotprod = 0.0; for(int i = 0; i < length; i++) { dotprod += resCurrent[i] * resBasis[m][i]; } return dotprod; } // Update entire U matrix template <int D> void AmIteratorBasis<D>::updateU(DMatrix<double> & U, RingBuffer<DArray<double> > const & resBasis, int nHist) { // Update matrix U by shifting elements diagonally int maxHist = U.capacity1(); for (int m = maxHist-1; m > 0; --m) { for (int n = maxHist-1; n > 0; --n) { U(m,n) = U(m-1,n-1); } } // Compute U matrix's new row 0 and col 0 for (int m = 0; m < nHist; ++m) { double dotprod = computeUDotProd(resBasis,0,m); U(m,0) = dotprod; U(0,m) = dotprod; } } template <int D> void AmIteratorBasis<D>::updateV(DArray<double> & v, DArray<double> const & resCurrent, RingBuffer<DArray<double> > const & resBasis, int nHist) { // Compute U matrix's new row 0 and col 0 // Also, compute each element of v_ vector for (int m = 0; m < nHist; ++m) { v[m] = computeVDotProd(resCurrent,resBasis,m); } } #endif // Update basis template <int D> void AmIteratorBasis<D>::updateBasis(RingBuffer<DArray<double> > & basis, RingBuffer<DArray<double> > const& hists) { // Make sure at least two histories are stored UTIL_CHECK(hists.size() >= 2); const int n = hists[0].capacity(); DArray<double> newbasis; newbasis.allocate(n); for (int i = 0; i < n; i++) { // sequential histories basis vectors newbasis[i] = hists[0][i] - hists[1][i]; } basis.append(newbasis); } template <int D> void AmIteratorBasis<D>::addHistories(DArray<double>& trial, RingBuffer<DArray<double> > const & basis, DArray<double> coeffs, int nHist) { int n = trial.capacity(); for (int i = 0; i < nHist; i++) { for (int j = 0; j < n; j++) { // Not clear on the origin of the -1 factor trial[j] += coeffs[i] * -1 * basis[i][j]; } } } template <int D> void AmIteratorBasis<D>::addPredictedError(DArray<double>& fieldTrial, DArray<double> const & resTrial, double lambda) { int n = fieldTrial.capacity(); for (int i = 0; i < n; i++) { fieldTrial[i] += lambda * resTrial[i]; } } // Does the system have an initial field guess? template <int D> bool AmIteratorBasis<D>::hasInitialGuess() { return system().w().hasData(); } // Compute and return the number of elements in a field vector template <int D> int AmIteratorBasis<D>::nElements() { const int nMonomer = system().mixture().nMonomer(); const int nBasis = system().basis().nBasis(); int nEle = nMonomer*nBasis; if (isFlexible_) { nEle += system().unitCell().nParameter(); } return nEle; } // Get the current field from the system template <int D> void AmIteratorBasis<D>::getCurrent(DArray<double>& curr) { // Straighten out fields into linear arrays const int nMonomer = system().mixture().nMonomer(); const int nBasis = system().basis().nBasis(); const DArray< DArray<double> > * currSys = &system().w().basis(); for (int i = 0; i < nMonomer; i++) { for (int k = 0; k < nBasis; k++) { curr[i*nBasis+k] = (*currSys)[i][k]; } } if (isFlexible_) { const int begin = nMonomer*nBasis; const int nParam = system().unitCell().nParameter(); FSArray<double,6> const & parameters = system().unitCell().parameters(); for (int i = 0; i < nParam; i++) { curr[begin + i] = scaleStress_ * parameters[i]; } } } // Perform the main system computation (solve the MDE) template <int D> void AmIteratorBasis<D>::evaluate() { // Solve MDEs for current omega field system().compute(); // If flexible, compute stress if (isFlexible_) { system().mixture().computeStress(system().domain().waveList()); } } // Compute the residual for the current system state template <int D> void AmIteratorBasis<D>::getResidual(DArray<double>& resid) { UTIL_CHECK(system().basis().isInitialized()); const int nMonomer = system().mixture().nMonomer(); const int nBasis = system().basis().nBasis(); const int n = nElements(); // Initialize residuals for (int i = 0 ; i < n; ++i) { resid[i] = 0.0; } // Compute SCF residual vector elements for (int i = 0; i < nMonomer; ++i) { for (int j = 0; j < nMonomer; ++j) { for (int k = 0; k < nBasis; ++k) { int idx = i*nBasis + k; resid[idx] += interaction_.chi(i,j)*system().c().basis(j)[k] - interaction_.p(i,j)*system().w().basis(j)[k]; } } } // If not canonical, account for incompressibility if (!system().mixture().isCanonical()) { for (int i = 0; i < nMonomer; ++i) { resid[i*nBasis] -= 1.0/interaction_.sumChiInverse(); } } else { // Explicitly set homogeneous residual components for (int i = 0; i < nMonomer; ++i) { resid[i*nBasis] = 0.0; } } // If variable unit cell, compute stress residuals if (isFlexible_) { const int nParam = system().unitCell().nParameter(); for (int i = 0; i < nParam ; i++) { resid[nMonomer*nBasis + i] = -1.0 * scaleStress_ * system().mixture().stress(i); } // Note: // Combined -1 factor and stress scaling here. This is okay: // - Residuals only show up as dot products (U, v, norm) // or with their absolute value taken (max), so the // sign on a given residual vector element is not relevant // as long as it is consistent across all vectors // - The scaling is applied here and to the unit cell param // storage, so that updating is done on the same scale, // and then undone right before passing to the unit cell. } } // Update the current system field coordinates template <int D> void AmIteratorBasis<D>::update(DArray<double>& newGuess) { UTIL_CHECK(system().basis().isInitialized()); const int nMonomer = system().mixture().nMonomer(); const int nBasis = system().basis().nBasis(); DArray< DArray<double> > wField; wField.allocate(nMonomer); // Restructure in format of monomers, basis functions for (int i = 0; i < nMonomer; i++) { wField[i].allocate(nBasis); for (int k = 0; k < nBasis; k++) { wField[i][k] = newGuess[i*nBasis + k]; } } // If canonical, explicitly set homogeneous field components if (system().mixture().isCanonical()) { for (int i = 0; i < nMonomer; ++i) { wField[i][0] = 0.0; // initialize to 0 for (int j = 0; j < nMonomer; ++j) { wField[i][0] += interaction_.chi(i,j) * system().c().basis(j)[0]; } } } system().setWBasis(wField); if (isFlexible_) { const int nParam = system().unitCell().nParameter(); const int begin = nMonomer*nBasis; FSArray<double,6> parameters; double value; for (int i = 0; i < nParam; i++) { value = newGuess[begin + i]/scaleStress_; parameters.append(value); } system().setUnitCell(parameters); } } template<int D> void AmIteratorBasis<D>::outputToLog() { if (isFlexible_) { const int nParam = system().unitCell().nParameter(); for (int i = 0; i < nParam; i++) { Log::file() << "Parameter " << i << " = " << Dbl(system().unitCell().parameters()[i]) << "\n"; } } } } } #endif
12,889
C++
.tpp
365
26.646575
84
0.55396
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,222
AmIteratorGrid.tpp
dmorse_pscfpp/src/pspg/iterator/AmIteratorGrid.tpp
#ifndef PSPG_AM_ITERATOR_GRID_TPP #define PSPG_AM_ITERATOR_GRID_TPP /* * 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 "AmIteratorGrid.h" #include <pspg/System.h> #include <pscf/inter/Interaction.h> #include <pspg/field/RDField.h> #include <util/global.h> namespace Pscf { namespace Pspg { using namespace Util; // Constructor template <int D> AmIteratorGrid<D>::AmIteratorGrid(System<D>& system) : Iterator<D>(system) {} // Destructor template <int D> AmIteratorGrid<D>::~AmIteratorGrid() {} // Read parameter file block template <int D> void AmIteratorGrid<D>::readParameters(std::istream& in) { // Call parent class readParameters AmIteratorTmpl<Iterator<D>,FieldCUDA>::readParameters(in); AmIteratorTmpl<Iterator<D>,FieldCUDA>::readErrorType(in); // Allocate local modified copy of Interaction class interaction_.setNMonomer(system().mixture().nMonomer()); // Default parameter values isFlexible_ = 1; scaleStress_ = 10.0; // Read in additional parameters readOptional(in, "isFlexible", isFlexible_); readOptional(in, "scaleStress", scaleStress_); } // Protected virtual function // Setup before entering iteration loop template <int D> void AmIteratorGrid<D>::setup(bool isContinuation) { AmIteratorTmpl<Iterator<D>, FieldCUDA>::setup(isContinuation); interaction_.update(system().interaction()); } // Private virtual functions used to implement AM algorithm template <int D> void AmIteratorGrid<D>::setEqual(FieldCUDA& a, FieldCUDA const & b) { // GPU resources int nBlocks, nThreads; ThreadGrid::setThreadsLogical(a.capacity(), nBlocks, nThreads); UTIL_CHECK(b.capacity() == a.capacity()); assignReal<<<nBlocks, nThreads>>>(a.cDField(), b.cDField(), a.capacity()); } template <int D> double AmIteratorGrid<D>::dotProduct(FieldCUDA const & a, FieldCUDA const& b) { const int n = a.capacity(); UTIL_CHECK(b.capacity() == n); double product = (double)gpuInnerProduct(a.cDField(), b.cDField(), n); return product; } template <int D> double AmIteratorGrid<D>::maxAbs(FieldCUDA const & a) { int n = a.capacity(); cudaReal max = gpuMaxAbs(a.cDField(), n); return (double)max; } template <int D> void AmIteratorGrid<D>::updateBasis(RingBuffer<FieldCUDA> & basis, RingBuffer<FieldCUDA> const & hists) { // Make sure at least two histories are stored UTIL_CHECK(hists.size() >= 2); const int n = hists[0].capacity(); FieldCUDA newbasis; newbasis.allocate(n); // GPU resources int nBlocks, nThreads; ThreadGrid::setThreadsLogical(n, nBlocks, nThreads); pointWiseBinarySubtract<<<nBlocks,nThreads>>> (hists[0].cDField(),hists[1].cDField(),newbasis.cDField(),n); basis.append(newbasis); } template <int D> void AmIteratorGrid<D>::addHistories(FieldCUDA& trial, RingBuffer<FieldCUDA> const & basis, DArray<double> coeffs, int nHist) { // GPU resources int nBlocks, nThreads; ThreadGrid::setThreadsLogical(trial.capacity(), nBlocks, nThreads); for (int i = 0; i < nHist; i++) { pointWiseAddScale<<<nBlocks, nThreads>>> (trial.cDField(), basis[i].cDField(), -1*coeffs[i], trial.capacity()); } } template <int D> void AmIteratorGrid<D>::addPredictedError(FieldCUDA& fieldTrial, FieldCUDA const & resTrial, double lambda) { // GPU resources int nBlocks, nThreads; ThreadGrid::setThreadsLogical(fieldTrial.capacity(), nBlocks, nThreads); pointWiseAddScale<<<nBlocks, nThreads>>> (fieldTrial.cDField(), resTrial.cDField(), lambda, fieldTrial.capacity()); } template <int D> bool AmIteratorGrid<D>::hasInitialGuess() { return system().w().hasData(); } template <int D> int AmIteratorGrid<D>::nElements() { const int nMonomer = system().mixture().nMonomer(); const int nMesh = system().mesh().size(); int nEle = nMonomer*nMesh; if (isFlexible_) { nEle += system().unitCell().nParameter(); } return nEle; } template <int D> void AmIteratorGrid<D>::getCurrent(FieldCUDA& curr) { const int nMonomer = system().mixture().nMonomer(); const int nMesh = system().mesh().size(); const int n = nElements(); // GPU resources int nBlocks, nThreads; ThreadGrid::setThreadsLogical(nMesh, nBlocks, nThreads); // Pointer to fields on system DArray<RDField<D>> const * currSys = &system().w().rgrid(); // Loop to unfold the system fields and store them in one long array for (int i = 0; i < nMonomer; i++) { assignReal<<<nBlocks,nThreads>>>(curr.cDField() + i*nMesh, (*currSys)[i].cDField(), nMesh); } // If flexible unit cell, also store unit cell parameters if (isFlexible_) { const int nParam = system().unitCell().nParameter(); const FSArray<double,6> currParam = system().unitCell().parameters(); // convert into a cudaReal array cudaReal* temp = new cudaReal[nParam]; for (int k = 0; k < nParam; k++) temp[k] = (cudaReal)scaleStress_*currParam[k]; // Copy parameters to the end of the curr array cudaMemcpy(curr.cDField() + nMonomer*nMesh, temp, nParam*sizeof(cudaReal), cudaMemcpyHostToDevice); delete[] temp; } } template <int D> void AmIteratorGrid<D>::evaluate() { // Solve MDEs for current omega field system().compute(); // Compute stress if done if (isFlexible_) { system().mixture().computeStress(system().domain().waveList()); } } template <int D> void AmIteratorGrid<D>::getResidual(FieldCUDA& resid) { const int n = nElements(); const int nMonomer = system().mixture().nMonomer(); const int nMesh = system().mesh().size(); // GPU resources int nBlocks, nThreads; ThreadGrid::setThreadsLogical(nMesh, nBlocks, nThreads); // Initialize residuals to zero. Kernel will take care of potential // additional elements (n vs nMesh). assignUniformReal<<<nBlocks, nThreads>>>(resid.cDField(), 0, n); // Compute SCF residuals for (int i = 0; i < nMonomer; i++) { int startIdx = i*nMesh; for (int j = 0; j < nMonomer; j++) { pointWiseAddScale<<<nBlocks, nThreads>>> (resid.cDField() + startIdx, system().c().rgrid(j).cDField(), interaction_.chi(i, j), nMesh); pointWiseAddScale<<<nBlocks, nThreads>>> (resid.cDField() + startIdx, system().w().rgrid(j).cDField(), -interaction_.p(i, j), nMesh); } } // If ensemble is not canonical, account for incompressibility. if (!system().mixture().isCanonical()) { cudaReal factor = 1/(cudaReal)interaction_.sumChiInverse(); for (int i = 0; i < nMonomer; ++i) { subtractUniform<<<nBlocks, nThreads>>>(resid.cDField() + i*nMesh, factor, nMesh); } } else { for (int i = 0; i < nMonomer; i++) { // Find current average cudaReal average = findAverage(resid.cDField()+i*nMesh, nMesh); // subtract out average to set residual average to zero subtractUniform<<<nBlocks, nThreads>>>(resid.cDField() + i*nMesh, average, nMesh); } } // If variable unit cell, compute stress residuals if (isFlexible_) { const int nParam = system().unitCell().nParameter(); cudaReal* stress = new cudaReal[nParam]; for (int i = 0; i < nParam; i++) { stress[i] = (cudaReal)(-1*scaleStress_*system().mixture().stress(i)); } cudaMemcpy(resid.cDField()+nMonomer*nMesh, stress, nParam*sizeof(cudaReal), cudaMemcpyHostToDevice); } } template <int D> void AmIteratorGrid<D>::update(FieldCUDA& newGuess) { const int nMonomer = system().mixture().nMonomer(); const int nMesh = system().mesh().size(); // GPU resources int nBlocks, nThreads; ThreadGrid::setThreadsLogical(nMesh, nBlocks, nThreads); // If canonical, explicitly set homogeneous field components if (system().mixture().isCanonical()) { cudaReal average, wAverage, cAverage; for (int i = 0; i < nMonomer; i++) { // Find current spatial average average = findAverage(newGuess.cDField() + i*nMesh, nMesh); // Subtract average from field, setting average to zero subtractUniform<<<nBlocks, nThreads>>>(newGuess.cDField() + i*nMesh, average, nMesh); // Compute the new average omega value, add it to all elements wAverage = 0; for (int j = 0; j < nMonomer; j++) { // Find average concentration for j monomers cAverage = findAverage(system().c().rgrid(j).cDField(), nMesh); wAverage += interaction_.chi(i,j) * cAverage; } addUniform<<<nBlocks, nThreads>>>(newGuess.cDField() + i*nMesh, wAverage, nMesh); } } system().setWRGrid(newGuess); system().symmetrizeWFields(); // If flexible unit cell, update cell parameters if (isFlexible_) { FSArray<double,6> parameters; const int nParam = system().unitCell().nParameter(); cudaReal* temp = new cudaReal[nParam]; cudaMemcpy(temp, newGuess.cDField() + nMonomer*nMesh, nParam*sizeof(cudaReal), cudaMemcpyDeviceToHost); for (int i = 0; i < nParam; i++) { parameters.append(1/scaleStress_ * (double)temp[i]); } system().setUnitCell(parameters); delete[] temp; } } template<int D> void AmIteratorGrid<D>::outputToLog() { if (isFlexible_) { const int nParam = system().unitCell().nParameter(); for (int i = 0; i < nParam; i++) { Log::file() << "Parameter " << i << " = " << Dbl(system().unitCell().parameters()[i]) << "\n"; } } } // --- Private member functions that are specific to this implementation --- template<int D> cudaReal AmIteratorGrid<D>::findAverage(cudaReal const * field, int n) { cudaReal average = gpuSum(field, n)/n; return average; } } } #endif
11,345
C++
.tpp
290
29.965517
85
0.592051
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,223
Propagator.tpp
dmorse_pscfpp/src/pspg/solvers/Propagator.tpp
#ifndef PSPG_PROPAGATOR_TPP #define PSPG_PROPAGATOR_TPP /* * 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" #include "Block.h" #include <thrust/reduce.h> #include "device_launch_parameters.h" #include <cuda.h> //#include <device_functions.h> #include <thrust/count.h> #include <pspg/math/GpuResources.h> #include <pscf/mesh/Mesh.h> //#include <Windows.h> namespace Pscf { namespace Pspg { using namespace Util; /* * Constructor. */ template <int D> Propagator<D>::Propagator() : blockPtr_(0), meshPtr_(0), ns_(0), temp_(0), isAllocated_(false) { } /* * Destructor. */ template <int D> Propagator<D>::~Propagator() { if (temp_) { delete[] temp_; cudaFree(d_temp_); } } template <int D> void Propagator<D>::allocate(int ns, const Mesh<D>& mesh) { ns_ = ns; meshPtr_ = &mesh; ThreadGrid::setThreadsLogical(mesh.size()); gpuErrchk(cudaMalloc((void**)&qFields_d, sizeof(cudaReal)* mesh.size() * ns)); gpuErrchk(cudaMalloc((void**)&d_temp_, ThreadGrid::nBlocks() * sizeof(cudaReal))); temp_ = new cudaReal[ThreadGrid::nBlocks()]; isAllocated_ = true; } /* * Compute initial head QField from final tail QFields of sources. */ template <int D> void Propagator<D>::computeHead() { // Reference to head of this propagator //QField& qh = qFields_[0]; // Initialize qh field to 1.0 at all grid points int nx = meshPtr_->size(); // GPU resources int nBlocks, nThreads; ThreadGrid::setThreadsLogical(nx, nBlocks, nThreads); //qh[ix] = 1.0; //qFields_d points to the first element in gpu memory assignUniformReal<<<nBlocks, nThreads>>>(qFields_d, 1.0, nx); // Pointwise multiply tail QFields of all sources // this could be slow with many sources. Should launch 1 kernel for the whole // function of computeHead const cudaReal* qt; for (int is = 0; is < nSource(); ++is) { if (!source(is).isSolved()) { UTIL_THROW("Source not solved in computeHead"); } //need to modify tail to give the total_size - mesh_size pointer qt = source(is).tail(); //qh[ix] *= qt[ix]; inPlacePointwiseMul<<<nBlocks, nThreads>>>(qFields_d, qt, nx); } } /* * Solve the modified diffusion equation for this block. */ template <int D> void Propagator<D>::solve() { UTIL_CHECK(isAllocated()); computeHead(); // Setup solver and solve block().setupFFT(); //cudaReal* qf; //qf = new cudaReal; int currentIdx; for (int iStep = 0; iStep < ns_ - 1; ++iStep) { currentIdx = iStep * meshPtr_->size(); //block has to learn to deal with the cudaReal block().step(qFields_d + currentIdx, qFields_d + currentIdx + meshPtr_->size()); } //delete qf; setIsSolved(true); } /* * Solve the modified diffusion equation with specified initial field. */ template <int D> void Propagator<D>::solve(const cudaReal * head) { int nx = meshPtr_->size(); // GPU resources int nBlocks, nThreads; ThreadGrid::setThreadsLogical(nx, nBlocks, nThreads); // Initialize initial (head) field cudaReal* qh = qFields_d; // qh[i] = head[i]; assignReal<<<nBlocks, nThreads>>>(qh, head, nx); // Setup solver and solve int currentIdx; for (int iStep = 0; iStep < ns_ - 1; ++iStep) { currentIdx = iStep * nx; block().step(qFields_d + currentIdx, qFields_d + currentIdx + nx); } setIsSolved(true); } /* * Integrate to calculate monomer concentration for this block */ template <int D> double Propagator<D>::computeQ() { // Preconditions if (!isSolved()) { UTIL_THROW("Propagator is not solved."); } if (!hasPartner()) { UTIL_THROW("Propagator has no partner set."); } if (!partner().isSolved()) { UTIL_THROW("Partner propagator is not solved"); } const cudaReal * qh = head(); const cudaReal * qt = partner().tail(); int nx = meshPtr_->size(); // Take inner product of head and partner tail fields // cannot reduce assuming one propagator, qh == 1 // polymers are divided into blocks midway through double Q = 0; Q = gpuInnerProduct(qh, qt, nx); Q /= double(nx); return Q; } } } #endif
4,735
C++
.tpp
159
23.90566
89
0.610903
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,224
WaveList.tpp
dmorse_pscfpp/src/pspg/solvers/WaveList.tpp
#ifndef PSPG_WAVE_LIST_TPP #define PSPG_WAVE_LIST_TPP /* * 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 "WaveList.h" #include "cuComplex.h" #include <pspg/math/GpuResources.h> namespace Pscf { namespace Pspg { // Need a reference table that maps index to a pair wavevector // Ideally we can have a group of thread dealing with only // the non-implicit part and the implicit part static __global__ void makeDksqHelperWave(cudaReal* dksq, const int* waveBz, const cudaReal* dkkBasis, const int* partnerId, const int* selfId, const bool* implicit, int nParams, int kSize, int size, int dim) { // Actual size is nStar*nParams // Each thread does nParams calculation // Big performance hit if thread >= 0.5dimension(n-1) int nThreads = blockDim.x * gridDim.x; int startID = blockIdx.x * blockDim.x + threadIdx.x; //loop through the entire array int pId; for (int param = 0; param < nParams; ++param) { for (int i = startID; i < size; i += nThreads) { for (int j = 0; j < dim; ++j) { for (int k = 0; k < dim; ++k) { if (!implicit[i]) { // Not = need += so still need memset dksq[(param * size) + i] += waveBz[selfId[i] * dim + j] * waveBz[ selfId[i] * dim + k] * dkkBasis[k + (j * dim) + (param * dim * dim)]; } else { pId = partnerId[i]; dksq[(param * size) + i] += waveBz[selfId[pId] * dim + j] * waveBz[selfId[pId] * dim + k] * dkkBasis[k + (j * dim) + (param * dim * dim)]; } } //dim } //dim } //size } //nParams } static __global__ void makeDksqReduction(cudaReal* dksq, const int* partnerId, int nParams, int kSize, int rSize) { int nThreads = blockDim.x * gridDim.x; int startID = blockIdx.x * blockDim.x + threadIdx.x; // Add i in the implicit part into their partner's result int pId; for(int param = 0; param < nParams; ++param) { for (int i = startID + kSize; i < rSize; i += nThreads) { pId = partnerId[i]; dksq[(param * rSize) + pId] += dksq[(param * rSize) + i]; } } } template <int D> WaveList<D>::WaveList() : minImage_d(nullptr), dkSq_(nullptr), partnerIdTable(nullptr), partnerIdTable_d(nullptr), kSize_(0), rSize_(0), nParams_(0), isAllocated_(false), hasMinimumImages_(false) { #if 0 minImage_d = nullptr; dkSq_ = nullptr; partnerIdTable = nullptr; partnerIdTable_d = nullptr; kSize_ = 0; rSize_ = 0; nParams_ = 0; isAllocated_ = false; #endif } template <int D> WaveList<D>::~WaveList() { if (isAllocated_) { cudaFree(minImage_d); cudaFree(dkSq_); cudaFree(partnerIdTable_d); cudaFree(selfIdTable_d); cudaFree(implicit_d); cudaFree(dkkBasis_d); delete[] kSq_; delete implicit; } } template <int D> void WaveList<D>::allocate(Mesh<D> const & mesh, UnitCell<D> const & unitCell) { UTIL_CHECK(mesh.size() > 0); UTIL_CHECK(unitCell.nParameter() > 0); UTIL_CHECK(!isAllocated_); rSize_ = mesh.size(); dimensions_ = mesh.dimensions(); nParams_ = unitCell.nParameter(); // Compute DFT mesh size kSize_ kSize_ = 1; for(int i = 0; i < D; ++i) { if (i < D - 1) { kSize_ *= mesh.dimension(i); } else { kSize_ *= (mesh.dimension(i)/ 2 + 1); } } minImage_.allocate(kSize_); gpuErrchk( cudaMalloc((void**) &minImage_d, sizeof(int) * rSize_ * D) ); kSq_ = new cudaReal[rSize_]; gpuErrchk( cudaMalloc((void**) &dkSq_, sizeof(cudaReal) * rSize_ * nParams_) ); partnerIdTable = new int[mesh.size()]; gpuErrchk( cudaMalloc((void**) &partnerIdTable_d, sizeof(int) * mesh.size()) ); selfIdTable = new int[mesh.size()]; gpuErrchk( cudaMalloc((void**) &selfIdTable_d, sizeof(int) * mesh.size()) ); implicit = new bool[mesh.size()]; gpuErrchk( cudaMalloc((void**) &implicit_d, sizeof(bool) * mesh.size()) ); dkkBasis = new cudaReal[6 * D * D]; gpuErrchk( cudaMalloc((void**) &dkkBasis_d, sizeof(cudaReal) * 6 * D * D) ); isAllocated_ = true; } template <int D> void WaveList<D>::computeMinimumImages(Mesh<D> const & mesh, UnitCell<D> const & unitCell) { // Precondition UTIL_CHECK (isAllocated_); UTIL_CHECK (mesh.size() > 0); UTIL_CHECK (unitCell.nParameter() > 0); UTIL_CHECK (unitCell.lattice() != UnitCell<D>::Null); UTIL_CHECK (unitCell.isInitialized()); MeshIterator<D> itr(mesh.dimensions()); IntVec<D> waveId; IntVec<D> G2; IntVec<D> tempIntVec; int partnerId; //min image needs mesh size of them //partner only need kSize of them //does setting iterator over kdim solves thing? int kDimRank = 0; int implicitRank = kSize_; //kDimRank + implicitRank = rSize int* invertedIdTable = new int[rSize_]; for (itr.begin(); !itr.atEnd(); ++itr) { // If not implicit if (itr.position(D - 1) < mesh.dimension(D-1)/2 + 1) { implicit[kDimRank] = false; selfIdTable[kDimRank] = itr.rank(); invertedIdTable[itr.rank()] = kDimRank; kDimRank++; } else { implicit[implicitRank] = true; selfIdTable[implicitRank] = itr.rank(); invertedIdTable[itr.rank()] = implicitRank; implicitRank++; } } int* tempMinImage = new int[rSize_ * D]; for (itr.begin(); !itr.atEnd(); ++itr) { kSq_[itr.rank()] = unitCell.ksq(itr.position()); #if 0 //we get position but set mesh dim to be larger, should be okay shiftToMinimum(itr.position(), mesh.dimensions(), minImage_ + (itr.rank() * D)); #endif // We get position but set mesh dim to be larger, should be okay // not the most elegant code with repeated copying but reduces // repeated code from pscf waveId = itr.position(); tempIntVec = shiftToMinimum(waveId, mesh.dimensions(), unitCell); for(int i = 0; i < D; i++) { (tempMinImage + (itr.rank() * D))[i] = tempIntVec[i]; } if(itr.position(D - 1) < mesh.dimension(D-1)/2 + 1) { minImage_[invertedIdTable[itr.rank()]] = tempIntVec; } for(int j = 0; j < D; ++j) { G2[j] = -waveId[j]; } mesh.shift(G2); partnerId = mesh.rank(G2); partnerIdTable[invertedIdTable[itr.rank()]] = invertedIdTable[partnerId]; } #if 0 /* std::cout<< "Sum kDimRank implicitRank: " << kDimRank + (implicitRank-kSize_)<<std::endl; std::cout<< "This is kDimRank sanity check "<<kDimRank<<std::endl; for (int i = 0; i < rSize_; i++) { std::cout << i << ' ' << selfIdTable[i]<< ' '<<partnerIdTable[i]<<' ' << implicit[i] << std::endl; } */ #endif gpuErrchk( cudaMemcpy(minImage_d, tempMinImage, sizeof(int) * rSize_ * D, cudaMemcpyHostToDevice) ); // Partner is much smaller but we keep this for now gpuErrchk( cudaMemcpy(partnerIdTable_d, partnerIdTable, sizeof(int) * mesh.size(), cudaMemcpyHostToDevice) ); gpuErrchk( cudaMemcpy(selfIdTable_d, selfIdTable, sizeof(int) * mesh.size(), cudaMemcpyHostToDevice) ); gpuErrchk( cudaMemcpy(implicit_d, implicit, sizeof(bool) * mesh.size(), cudaMemcpyHostToDevice) ); delete[] tempMinImage; hasMinimumImages_ = true; } template <int D> void WaveList<D>::computeKSq(UnitCell<D> const & unitCell) { //pass for now } template <int D> void WaveList<D>::computedKSq(UnitCell<D> const & unitCell) { // dkkbasis is something determined from unit cell size // min image needs to be on device but okay since its only done once. // Second to last parameter is number of stars originally // Precondition UTIL_CHECK (hasMinimumImages_); UTIL_CHECK (unitCell.nParameter() > 0); UTIL_CHECK (unitCell.lattice() != UnitCell<D>::Null); UTIL_CHECK (unitCell.isInitialized()); // GPU resources int nBlocks, nThreads; ThreadGrid::setThreadsLogical(rSize_, nBlocks, nThreads); int idx; for(int i = 0 ; i < unitCell.nParameter(); ++i) { for(int j = 0; j < D; ++j) { for(int k = 0; k < D; ++k) { idx = k + (j * D) + (i * D * D); dkkBasis[idx] = unitCell.dkkBasis(i, j, k); } } } cudaMemcpy(dkkBasis_d, dkkBasis, sizeof(cudaReal) * unitCell.nParameter() * D * D, cudaMemcpyHostToDevice); cudaMemset(dkSq_, 0, unitCell.nParameter() * rSize_ * sizeof(cudaReal)); makeDksqHelperWave<<<nBlocks, nThreads>>> (dkSq_, minImage_d, dkkBasis_d, partnerIdTable_d, selfIdTable_d, implicit_d, unitCell.nParameter(), kSize_, rSize_, D); makeDksqReduction<<<nBlocks, nThreads>>> (dkSq_, partnerIdTable_d, unitCell.nParameter(), kSize_, rSize_); } } } #endif
10,331
C++
.tpp
285
26.529825
82
0.540004
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,225
Polymer.tpp
dmorse_pscfpp/src/pspg/solvers/Polymer.tpp
#ifndef PSPG_POLYMER_TPP #define PSPG_POLYMER_TPP /* * 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 <pspg/math/GpuResources.h> namespace Pscf { namespace Pspg { template <int D> Polymer<D>::Polymer() { setClassName("Polymer"); } template <int D> Polymer<D>::~Polymer() {} template <int D> void Polymer<D>::setPhi(double phi) { UTIL_CHECK(ensemble() == Species::Closed); UTIL_CHECK(phi >= 0.0); UTIL_CHECK(phi <= 1.0); phi_ = phi; } template <int D> void Polymer<D>::setMu(double mu) { UTIL_CHECK(ensemble() == Species::Open); mu_ = mu; } /* * Set unit cell dimensions in all solvers. */ template <int D> void Polymer<D>::setupUnitCell(UnitCell<D> const & unitCell, const WaveList<D>& wavelist) { nParams_ = unitCell.nParameter(); for (int j = 0; j < nBlock(); ++j) { block(j).setupUnitCell(unitCell, wavelist); } } /* * Compute solution to MDE and concentrations. */ template <int D> void Polymer<D>::compute(DArray< RDField<D> > const & wFields) { // Setup solvers for all blocks int monomerId; for (int j = 0; j < nBlock(); ++j) { monomerId = block(j).monomerId(); block(j).setupSolver(wFields[monomerId]); } // Call generic solver() method base class template. solve(); } /* * Compute stress from a polymer chain. */ template <int D> void Polymer<D>::computeStress(WaveList<D> const & wavelist) { double prefactor; prefactor = 0; // Initialize stress_ to 0 for (int i = 0; i < nParams_; ++i) { stress_ [i] = 0.0; } for (int i = 0; i < nBlock(); ++i) { prefactor = exp(mu_)/length(); block(i).computeStress(wavelist, prefactor); for (int j=0; j < nParams_; ++j){ stress_ [j] += block(i).stress(j); //std::cout<<"stress_[j] "<<stress_[j]<<std::endl; } } } } } #endif
2,209
C++
.tpp
82
21.390244
92
0.587899
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,226
Mixture.tpp
dmorse_pscfpp/src/pspg/solvers/Mixture.tpp
#ifndef PSPG_MIXTURE_TPP #define PSPG_MIXTURE_TPP /* * 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 "Mixture.h" #include <pspg/math/GpuResources.h> #include <cmath> namespace Pscf { namespace Pspg { template <int D> Mixture<D>::Mixture() : ds_(-1.0), nUnitCellParams_(0), meshPtr_(0), hasStress_(false) { setClassName("Mixture"); } template <int D> Mixture<D>::~Mixture() {} template <int D> void Mixture<D>::readParameters(std::istream& in) { MixtureTmpl< Polymer<D>, Solvent<D> >::readParameters(in); read(in, "ds", ds_); UTIL_CHECK(nMonomer() > 0); UTIL_CHECK(nPolymer()+ nSolvent() > 0); UTIL_CHECK(ds_ > 0); } template <int D> void Mixture<D>::setMesh(Mesh<D> const& mesh) { UTIL_CHECK(nMonomer() > 0); UTIL_CHECK(nPolymer()+ nSolvent() > 0); UTIL_CHECK(ds_ > 0); meshPtr_ = &mesh; // Set discretization for all blocks int i, j; for (i = 0; i < nPolymer(); ++i) { for (j = 0; j < polymer(i).nBlock(); ++j) { polymer(i).block(j).setDiscretization(ds_, mesh); } } // Set spatial discretization for solvents if (nSolvent() > 0) { for (int i = 0; i < nSolvent(); ++i) { solvent(i).setDiscretization(mesh); } } } template <int D> void Mixture<D>::setupUnitCell(UnitCell<D> const & unitCell, WaveList<D> const& wavelist) { nUnitCellParams_ = unitCell.nParameter(); for (int i = 0; i < nPolymer(); ++i) { polymer(i).setupUnitCell(unitCell, wavelist); } hasStress_ = false; } /* * Reset statistical segment length for one monomer type. */ template <int D> void Mixture<D>::setKuhn(int monomerId, double kuhn) { // Set new Kuhn length for relevant Monomer object monomer(monomerId).setKuhn(kuhn); // Update kuhn length for all blocks of this monomer type for (int i = 0; i < nPolymer(); ++i) { for (int j = 0; j < polymer(i).nBlock(); ++j) { if (monomerId == polymer(i).block(j).monomerId()) { polymer(i).block(j).setKuhn(kuhn); } } } hasStress_ = false; } /* * Compute concentrations (but not total free energy). */ template <int D> void Mixture<D>::compute(DArray< RDField<D> > const & wFields, DArray< RDField<D> > & cFields) { UTIL_CHECK(meshPtr_); UTIL_CHECK(mesh().size() > 0); UTIL_CHECK(nMonomer() > 0); UTIL_CHECK(nPolymer() + nSolvent() > 0); UTIL_CHECK(wFields.capacity() == nMonomer()); UTIL_CHECK(cFields.capacity() == nMonomer()); int nMesh = mesh().size(); int nm = nMonomer(); int i, j; // GPU resources int nBlocks, nThreads; ThreadGrid::setThreadsLogical(nMesh, nBlocks, nThreads); // Clear all monomer concentration fields for (i = 0; i < nm; ++i) { UTIL_CHECK(cFields[i].capacity() == nMesh); UTIL_CHECK(wFields[i].capacity() == nMesh); assignUniformReal<<<nBlocks, nThreads>>>(cFields[i].cDField(), 0.0, nMesh); } // Solve MDE for all polymers for (i = 0; i < nPolymer(); ++i) { polymer(i).compute(wFields); } // Accumulate monomer concentration fields int monomerId; for (i = 0; i < nPolymer(); ++i) { for (j = 0; j < polymer(i).nBlock(); ++j) { monomerId = polymer(i).block(j).monomerId(); UTIL_CHECK(monomerId >= 0); UTIL_CHECK(monomerId < nm); RDField<D>& monomerField = cFields[monomerId]; RDField<D>& blockField = polymer(i).block(j).cField(); UTIL_CHECK(blockField.capacity()==nMesh); pointWiseAdd<<<nBlocks, nThreads>>>(monomerField.cDField(), blockField.cDField(), nMesh); } } // Process solvent species for (i = 0; i < nSolvent(); i++) { monomerId = solvent(i).monomerId(); UTIL_CHECK(monomerId >= 0); UTIL_CHECK(monomerId < nm); // Compute solvent concentration solvent(i).compute(wFields[monomerId]); // Add solvent contribution to relevant monomer concentration RDField<D>& monomerField = cFields[monomerId]; RDField<D> const & solventField = solvent(i).concField(); UTIL_CHECK(solventField.capacity() == nMesh); pointWiseAdd<<<nBlocks, nThreads>>>(monomerField.cDField(), solventField.cDField(), nMesh); } hasStress_ = false; } /* * Compute Total Stress. */ template <int D> void Mixture<D>::computeStress(WaveList<D> const & wavelist) { int i, j; // Compute stress for each polymer. for (i = 0; i < nPolymer(); ++i) { polymer(i).computeStress(wavelist); } // Accumulate total stress for (i = 0; i < nUnitCellParams_; ++i) { stress_[i] = 0.0; for (j = 0; j < nPolymer(); ++j) { stress_[i] += polymer(j).stress(i); } } // Note: Solvent does not contribute to derivatives of f_Helmholtz // with respect to unit cell parameters at fixed volume fractions. hasStress_ = true; } template <int D> bool Mixture<D>::isCanonical() { // Check ensemble of all polymers for (int i = 0; i < nPolymer(); ++i) { if (polymer(i).ensemble() == Species::Open) { return false; } } // Check ensemble of all solvents for (int i = 0; i < nSolvent(); ++i) { if (solvent(i).ensemble() == Species::Open) { return false; } } // Returns true if false was never returned return true; } /* * Combine cFields for each block (and solvent) into one DArray */ template <int D> void Mixture<D>::createBlockCRGrid(DArray< RDField<D> > & blockCFields) const { UTIL_CHECK(nMonomer() > 0); UTIL_CHECK(nBlock() + nSolvent() > 0); int np = nSolvent() + nBlock(); int nx = mesh().size(); int i, j; UTIL_CHECK(blockCFields.capacity() == nBlock() + nSolvent()); // GPU resources int nBlocks, nThreads; ThreadGrid::setThreadsLogical(nx, nBlocks, nThreads); // Clear all monomer concentration fields, check capacities for (i = 0; i < np; ++i) { UTIL_CHECK(blockCFields[i].capacity() == nx); assignUniformReal<<<nBlocks, nThreads>>>(blockCFields[i].cDField(), 0.0, nx); } // Process polymer species int sectionId = -1; if (nPolymer() > 0) { // Write each block's r-grid data to blockCFields for (i = 0; i < nPolymer(); ++i) { for (j = 0; j < polymer(i).nBlock(); ++j) { sectionId++; UTIL_CHECK(sectionId >= 0); UTIL_CHECK(sectionId < np); UTIL_CHECK(blockCFields[sectionId].capacity() == nx); const cudaReal* blockField = polymer(i).block(j).cField().cDField(); cudaMemcpy(blockCFields[sectionId].cDField(), blockField, mesh().size() * sizeof(cudaReal), cudaMemcpyDeviceToDevice); } } } // Process solvent species if (nSolvent() > 0) { // Write each solvent's r-grid data to blockCFields for (i = 0; i < nSolvent(); ++i) { sectionId++; UTIL_CHECK(sectionId >= 0); UTIL_CHECK(sectionId < np); UTIL_CHECK(blockCFields[sectionId].capacity() == nx); const cudaReal* solventField = solvent(i).concField().cDField(); cudaMemcpy(blockCFields[sectionId].cDField(), solventField, mesh().size() * sizeof(cudaReal), cudaMemcpyDeviceToDevice); } } } } // namespace Pspg } // namespace Pscf #endif
8,326
C++
.tpp
237
26.493671
86
0.554864
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,227
Block.tpp
dmorse_pscfpp/src/pspg/solvers/Block.tpp
#ifndef PSPG_BLOCK_TPP #define PSPG_BLOCK_TPP /* * 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/math/GpuResources.h> #include <pscf/mesh/Mesh.h> #include <pscf/mesh/MeshIterator.h> #include <pscf/crystal/shiftToMinimum.h> #include <util/containers/FMatrix.h> // member template #include <util/containers/DArray.h> // member template #include <util/containers/FArray.h> // member template #include <sys/time.h> using namespace Util; namespace Pscf { namespace Pspg { // CUDA kernels (only used in this file) static __global__ void mulDelKsq(cudaReal* result, const cudaComplex* q1, const cudaComplex* q2, const cudaReal* delKsq, int paramN, int kSize, int rSize) { int nThreads = blockDim.x * gridDim.x; int startID = blockIdx.x * blockDim.x + threadIdx.x; for (int i = startID; i < kSize; i += nThreads) { #ifdef SINGLE_PRECISION result[i] = cuCmulf( q1[i], cuConjf(q2[i])).x * delKsq[paramN * rSize + i]; #else result[i] = cuCmul( q1[i], cuConj(q2[i])).x * delKsq[paramN * rSize + i]; #endif } } static __global__ void pointwiseMulSameStart(const cudaReal* a, const cudaReal* expW, const cudaReal* expW2, cudaReal* q1, cudaReal* q2, int size) { int nThreads = blockDim.x * gridDim.x; int startID = blockIdx.x * blockDim.x + threadIdx.x; cudaReal input; for (int i = startID; i < size; i += nThreads) { input = a[i]; q1[i] = expW[i] * input; q2[i] = expW2[i] * input; } } static __global__ void pointwiseMulTwinned(const cudaReal* qr1, const cudaReal* qr2, const cudaReal* expW, cudaReal* q1, cudaReal* q2, int size) { int nThreads = blockDim.x * gridDim.x; int startID = blockIdx.x * blockDim.x + threadIdx.x; cudaReal scale; for (int i = startID; i < size; i += nThreads) { scale = expW[i]; q1[i] = qr1[i] * scale; q2[i] = qr2[i] * scale; } } static __global__ void scaleComplexTwinned(cudaComplex* qk1, cudaComplex* qk2, const cudaReal* expksq1, const cudaReal* expksq2, int size) { int nThreads = blockDim.x * gridDim.x; int startID = blockIdx.x * blockDim.x + threadIdx.x; for (int i = startID; i < size; i += nThreads) { qk1[i].x *= expksq1[i]; qk1[i].y *= expksq1[i]; qk2[i].x *= expksq2[i]; qk2[i].y *= expksq2[i]; } } static __global__ void scaleComplex(cudaComplex* a, cudaReal* scale, int size) { int nThreads = blockDim.x * gridDim.x; int startID = blockIdx.x * blockDim.x + threadIdx.x; for(int i = startID; i < size; i += nThreads) { a[i].x *= scale[i]; a[i].y *= scale[i]; } } static __global__ void richardsonExpTwinned(cudaReal* qNew, const cudaReal* q1, const cudaReal* qr, const cudaReal* expW2, int size) { int nThreads = blockDim.x * gridDim.x; int startID = blockIdx.x * blockDim.x + threadIdx.x; cudaReal q2; for (int i = startID; i < size; i += nThreads) { q2 = qr[i] * expW2[i]; qNew[i] = (4.0 * q2 - q1[i]) / 3.0; } } static __global__ void multiplyScaleQQ(cudaReal* result, const cudaReal* p1, const cudaReal* p2, double scale, int size) { int nThreads = blockDim.x * gridDim.x; int startID = blockIdx.x * blockDim.x + threadIdx.x; for(int i = startID; i < size; i += nThreads) { result[i] += scale * p1[i] * p2[i]; } } // Block<D> member functions /* * Constructor. */ template <int D> Block<D>::Block() : meshPtr_(0), kMeshDimensions_(0), ds_(0.0), ns_(0), temp_(0), isAllocated_(false), hasExpKsq_(false), expKsq_host(0), expKsq2_host(0) { propagator(0).setBlock(*this); propagator(1).setBlock(*this); } /* * Destructor. */ template <int D> Block<D>::~Block() { if (temp_) { delete[] temp_; cudaFree(d_temp_); } if (expKsq_host) { delete[] expKsq_host; delete[] expKsq2_host; } } template <int D> void Block<D>::setDiscretization(double ds, Mesh<D> const & mesh) { UTIL_CHECK(mesh.size() > 1); UTIL_CHECK(ds > 0.0); UTIL_CHECK(!isAllocated_); // GPU Resources ThreadGrid::setThreadsLogical(mesh.size(),nBlocks_,nThreads_); // Set association to mesh meshPtr_ = &mesh; // Set contour length discretization for this block int tempNs; tempNs = floor( length()/(2.0 *ds) + 0.5 ); if (tempNs == 0) { tempNs = 1; } ns_ = 2*tempNs + 1; ds_ = length()/double(ns_ - 1); // Compute Fourier space kMeshDimensions_ for (int i = 0; i < D; ++i) { if (i < D - 1) { kMeshDimensions_[i] = mesh.dimensions()[i]; } else { kMeshDimensions_[i] = mesh.dimensions()[i]/2 + 1; } } kSize_ = 1; for(int i = 0; i < D; ++i) { kSize_ *= kMeshDimensions_[i]; } // Allocate work arrays expKsq_.allocate(kMeshDimensions_); expKsq2_.allocate(kMeshDimensions_); expW_.allocate(mesh.dimensions()); expW2_.allocate(mesh.dimensions()); qr_.allocate(mesh.dimensions()); qr2_.allocate(mesh.dimensions()); qk_.allocate(mesh.dimensions()); qk2_.allocate(mesh.dimensions()); q1_.allocate(mesh.dimensions()); q2_.allocate(mesh.dimensions()); propagator(0).allocate(ns_, mesh); propagator(1).allocate(ns_, mesh); gpuErrchk( cudaMalloc((void**)&qkBatched_, ns_ * kSize_ * sizeof(cudaComplex)) ); gpuErrchk( cudaMalloc((void**)&qk2Batched_, ns_ * kSize_ * sizeof(cudaComplex)) ); cField().allocate(mesh.dimensions()); gpuErrchk(cudaMalloc((void**)&d_temp_, nBlocks_ * sizeof(cudaReal))); temp_ = new cudaReal[nBlocks_]; expKsq_host = new cudaReal[kSize_]; expKsq2_host = new cudaReal[kSize_]; isAllocated_ = true; hasExpKsq_ = false; } /* * Set or reset the the block length. */ template <int D> void Block<D>::setLength(double length) { BlockDescriptor::setLength(length); if (isAllocated_) { UTIL_CHECK(ns_ > 1); ds_ = length/double(ns_ - 1); } hasExpKsq_ = false; } /* * Set or reset the the block length. */ template <int D> void Block<D>::setKuhn(double kuhn) { BlockTmpl< Propagator<D> >::setKuhn(kuhn); hasExpKsq_ = false; } /* * Setup data that depend on the unit cell parameters. */ template <int D> void Block<D>::setupUnitCell(const UnitCell<D>& unitCell, const WaveList<D>& wavelist) { nParams_ = unitCell.nParameter(); // store pointer to unit cell and wavelist unitCellPtr_ = &unitCell; waveListPtr_ = &wavelist; hasExpKsq_ = false; } template <int D> void Block<D>::computeExpKsq() { UTIL_CHECK(isAllocated_); MeshIterator<D> iter; iter.setDimensions(kMeshDimensions_); IntVec<D> G, Gmin; double Gsq; double factor = -1.0*kuhn()*kuhn()*ds_/6.0; // Setup expKsq values on Host then transfer to device int kSize = 1; for(int i = 0; i < D; ++i) { kSize *= kMeshDimensions_[i]; } int i; for (iter.begin(); !iter.atEnd(); ++iter) { i = iter.rank(); Gsq = unitCell().ksq(wavelist().minImage(iter.rank())); expKsq_host[i] = exp(Gsq*factor); expKsq2_host[i] = exp(Gsq*factor / 2); } cudaMemcpy(expKsq_.cDField(), expKsq_host, kSize * sizeof(cudaReal), cudaMemcpyHostToDevice); cudaMemcpy(expKsq2_.cDField(), expKsq2_host, kSize * sizeof(cudaReal), cudaMemcpyHostToDevice); hasExpKsq_ = true; } /* * Setup the contour length step algorithm. */ template <int D> void Block<D>::setupSolver(RDField<D> const & w) { // Preconditions int nx = mesh().size(); UTIL_CHECK(nx > 0); UTIL_CHECK(isAllocated_); // Populate expW_ assignExp<<<nBlocks_, nThreads_>>>(expW_.cDField(), w.cDField(), (double)0.5* ds_, nx); assignExp<<<nBlocks_, nThreads_>>>(expW2_.cDField(), w.cDField(), (double)0.25 * ds_, nx); // Compute expKsq arrays if necessary if (!hasExpKsq_) { computeExpKsq(); } } /* * Integrate to calculate monomer concentration for this block */ template <int D> void Block<D>::computeConcentration(double prefactor) { // Preconditions int nx = mesh().size(); UTIL_CHECK(nx > 0); UTIL_CHECK(ns_ > 0); UTIL_CHECK(ds_ > 0); UTIL_CHECK(propagator(0).isAllocated()); UTIL_CHECK(propagator(1).isAllocated()); UTIL_CHECK(cField().capacity() == nx) // Initialize cField to zero at all points assignUniformReal<<<nBlocks_, nThreads_>>> (cField().cDField(), 0.0, nx); Pscf::Pspg::Propagator<D> const & p0 = propagator(0); Pscf::Pspg::Propagator<D> const & p1 = propagator(1); multiplyScaleQQ<<<nBlocks_, nThreads_>>> (cField().cDField(), p0.q(0), p1.q(ns_ - 1), 1.0, nx); multiplyScaleQQ<<<nBlocks_, nThreads_>>> (cField().cDField(), p0.q(ns_-1), p1.q(0), 1.0, nx); for (int j = 1; j < ns_ - 1; j += 2) { // Odd indices multiplyScaleQQ<<<nBlocks_, nThreads_>>> (cField().cDField(), p0.q(j), p1.q(ns_ - 1 - j), 4.0, nx); } for (int j = 2; j < ns_ - 2; j += 2) { // Even indices multiplyScaleQQ<<<nBlocks_, nThreads_>>> (cField().cDField(), p0.q(j), p1.q(ns_ - 1 - j), 2.0, nx); } scaleReal<<<nBlocks_, nThreads_>>> (cField().cDField(), (prefactor * ds_/3.0), nx); } template <int D> void Block<D>::setupFFT() { if (!fft_.isSetup()) { fft_.setup(qr_, qk_); fftBatched_.setup(mesh().dimensions(), kMeshDimensions_, ns_); } } /* * Propagate solution by one step. */ template <int D> void Block<D>::step(const cudaReal* q, cudaReal* qNew) { // Preconditions UTIL_CHECK(isAllocated_); UTIL_CHECK(hasExpKsq_); // Check real-space mesh sizes int nx = mesh().size(); UTIL_CHECK(nx > 0); UTIL_CHECK(qr_.capacity() == nx); UTIL_CHECK(expW_.capacity() == nx); // Fourier-space mesh sizes int nk = qk_.capacity(); UTIL_CHECK(expKsq_.capacity() == nk); // Apply pseudo-spectral algorithm pointwiseMulSameStart<<<nBlocks_, nThreads_>>> (q, expW_.cDField(), expW2_.cDField(), qr_.cDField(), qr2_.cDField(), nx); fft_.forwardTransform(qr_, qk_); fft_.forwardTransform(qr2_, qk2_); scaleComplexTwinned<<<nBlocks_, nThreads_>>> (qk_.cDField(), qk2_.cDField(), expKsq_.cDField(), expKsq2_.cDField(), nk); fft_.inverseTransform(qk_, qr_); fft_.inverseTransform(qk2_, q2_); pointwiseMulTwinned<<<nBlocks_, nThreads_>>> (qr_.cDField(), q2_.cDField(), expW_.cDField(), q1_.cDField(), qr_.cDField(), nx); fft_.forwardTransform(qr_, qk_); scaleComplex<<<nBlocks_, nThreads_>>>(qk_.cDField(), expKsq2_.cDField(), nk); fft_.inverseTransform(qk_, qr_); richardsonExpTwinned<<<nBlocks_, nThreads_>>>(qNew, q1_.cDField(), qr_.cDField(), expW2_.cDField(), nx); //remove the use of q2 } /* * Compute stress contribution from this block. */ template <int D> void Block<D>::computeStress(WaveList<D> const & wavelist, double prefactor) { int nx = mesh().size(); // Preconditions UTIL_CHECK(nx > 0); UTIL_CHECK(ns_ > 0); UTIL_CHECK(ds_ > 0); UTIL_CHECK(propagator(0).isAllocated()); UTIL_CHECK(propagator(1).isAllocated()); double dels, normal, increment; normal = 3.0*6.0; FArray<double, 6> dQ; int i; for (i = 0; i < 6; ++i) { dQ [i] = 0.0; stress_[i] = 0.0; } Pscf::Pspg::Propagator<D> const & p0 = propagator(0); Pscf::Pspg::Propagator<D> const & p1 = propagator(1); fftBatched_.forwardTransform(p0.head(), qkBatched_, ns_); fftBatched_.forwardTransform(p1.head(), qk2Batched_, ns_); cudaMemset(qr2_.cDField(), 0, mesh().size() * sizeof(cudaReal)); for (int j = 0; j < ns_ ; ++j) { dels = ds_; if (j != 0 && j != ns_ - 1) { if (j % 2 == 0) { dels = dels*2.0; } else { dels = dels*4.0; } } for (int n = 0; n < nParams_ ; ++n) { mulDelKsq<<<nBlocks_, nThreads_ >>> (qr2_.cDField(), qkBatched_ + (j*kSize_), qk2Batched_ + (kSize_ * (ns_ -1 -j)), wavelist.dkSq(), n , kSize_, nx); increment = gpuSum(qr2_.cDField(), mesh().size()); increment = (increment * kuhn() * kuhn() * dels)/normal; dQ [n] = dQ[n]-increment; } } // Normalize for (i = 0; i < nParams_; ++i) { stress_[i] = stress_[i] - (dQ[i] * prefactor); } } } } #endif
14,390
C++
.tpp
427
25.126464
83
0.536394
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,228
Solvent.tpp
dmorse_pscfpp/src/pspg/solvers/Solvent.tpp
#ifndef PSPC_SOLVENT_TPP #define PSPC_SOLVENT_TPP /* * 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 "Solvent.h" #include <pscf/mesh/Mesh.h> namespace Pscf { namespace Pspg { template <int D> Solvent<D>::Solvent() { setClassName("Solvent"); } template <int D> Solvent<D>::~Solvent() {} /* * Create an association with a Mesh & allocate the concentration field. */ template <int D> void Solvent<D>::setDiscretization(Mesh<D> const & mesh) { meshPtr_ = &mesh; concField_.allocate(mesh.dimensions()); } /* * Compute concentration, q, phi or mu. */ template <int D> void Solvent<D>::compute(RDField<D> const & wField) { int nx = meshPtr_->size(); // Number of grid points // GPU Resources int nBlocks, nThreads; ThreadGrid::setThreadsLogical(nx, nBlocks, nThreads); // Initialize concField_ to zero assignUniformReal<<<nBlocks, nThreads>>>(concField_.cDField(), 0, nx); // Evaluate unnormalized integral and q_ double s = size(); q_ = 0.0; assignExp<<<nBlocks, nThreads>>>(concField_.cDField(), wField.cDField(), s, nx); q_ = (double)gpuSum(concField_.cDField(),nx); q_ = q_/double(nx); // Compute mu_ or phi_ and prefactor double prefactor; if (ensemble_ == Species::Closed) { prefactor = phi_/q_; mu_ = log(prefactor); } else { prefactor = exp(mu_); phi_ = prefactor*q_; } // Normalize concentration scaleReal<<<nBlocks, nThreads>>>(concField_.cDField(), prefactor, nx); } } } #endif
1,771
C++
.tpp
60
24.466667
86
0.634377
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,229
FieldState.tpp
dmorse_pscfpp/src/pspg/sweep/FieldState.tpp
#ifndef PSPG_FIELD_STATE_TPP #define PSPG_FIELD_STATE_TPP /* * 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 "FieldState.h" #include <pspg/System.h> #include <pspg/field/FFT.h> #include <pscf/mesh/Mesh.h> #include <pscf/crystal/Basis.h> #include <util/misc/FileMaster.h> // #include <util/format/Str.h> // #include <util/format/Int.h> // #include <util/format/Dbl.h> namespace Pscf { namespace Pspg { using namespace Util; /* * Constructor. */ template <int D, class FT> FieldState<D, FT>::FieldState() : fields_(), unitCell_(), systemPtr_(0) {} /* * Constructor. */ template <int D, class FT> FieldState<D, FT>::FieldState(System<D>& system) : fields_(), unitCell_(), systemPtr_(0) { setSystem(system); } /* * Destructor. */ template <int D, class FT> FieldState<D, FT>::~FieldState() {} /* * Set association with system, after default construction. */ template <int D, class FT> void FieldState<D, FT>::setSystem(System<D>& system) { if (hasSystem()) { UTIL_CHECK(systemPtr_ = &system); } else { systemPtr_ = &system; } } } // namespace Pspg } // namespace Pscf #endif
1,444
C++
.tpp
60
19.266667
67
0.616338
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,230
LinearSweep.tpp
dmorse_pscfpp/src/pspg/sweep/LinearSweep.tpp
#ifndef PSPG_LINEAR_SWEEP_TPP #define PSPG_LINEAR_SWEEP_TPP /* * 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 "LinearSweep.h" #include <pspg/System.h> #include <cstdio> namespace Pscf { namespace Pspg { using namespace Util; template <int D> LinearSweep<D>::LinearSweep(System<D>& system) : Sweep<D>(system) {} template <int D> void LinearSweep<D>::readParameters(std::istream& in) { // Call the base class's readParameters function. Sweep<D>::readParameters(in); // Read in the number of sweep parameters and allocate. this->read(in, "nParameter", nParameter_); parameters_.allocate(nParameter_); // Read in array of SweepParameters, calling << for each this->template readDArray< SweepParameter<D> >(in, "parameters", parameters_, nParameter_); // Verify net zero change in volume fractions if being swept double sum = 0.0; for (int i = 0; i < nParameter_; ++i) { if (parameters_[i].type() == "phi_polymer" || parameters_[i].type() == "phi_solvent") { sum += parameters_[i].change(); } } UTIL_CHECK(sum > -0.000001); UTIL_CHECK(sum < 0.000001); } template <int D> void LinearSweep<D>::setup() { // Verify that the LinearSweep has a system pointer UTIL_CHECK(hasSystem()); // Call base class's setup function Sweep<D>::setup(); // Set system pointer and initial value for each parameter object for (int i = 0; i < nParameter_; ++i) { parameters_[i].setSystem(system()); parameters_[i].getInitial(); } } template <int D> void LinearSweep<D>::setParameters(double s) { // Update the system parameter values double newVal; for (int i = 0; i < nParameter_; ++i) { newVal = parameters_[i].initial() + s*parameters_[i].change(); parameters_[i].update(newVal); } } template <int D> void LinearSweep<D>::outputSummary(std::ostream& out) {} } } #endif
2,194
C++
.tpp
67
27.208955
97
0.641663
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,231
BasisFieldState.tpp
dmorse_pscfpp/src/pspg/sweep/BasisFieldState.tpp
#ifndef PSPG_BASIS_FIELD_STATE_TPP #define PSPG_BASIS_FIELD_STATE_TPP /* * 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 "BasisFieldState.h" #include "FieldState.tpp" #include <pspg/System.h> #include <pscf/crystal/Basis.h> #include <util/global.h> namespace Pscf { namespace Pspg { using namespace Util; /* * Default constructor. */ template <int D> BasisFieldState<D>::BasisFieldState() : FieldState<D, DArray<double> >() {} /* * Constructor. */ template <int D> BasisFieldState<D>::BasisFieldState(System<D>& system) : FieldState<D, DArray<double> >(system) {} /* * Destructor. */ template <int D> BasisFieldState<D>::~BasisFieldState() {} /* * Allocate all fields. */ template <int D> void BasisFieldState<D>::allocate() { // Precondition UTIL_CHECK(hasSystem()); int nMonomer = system().mixture().nMonomer(); UTIL_CHECK(nMonomer > 0); if (fields().isAllocated()) { UTIL_CHECK(fields().capacity() == nMonomer); } else { fields().allocate(nMonomer); } int nBasis = system().basis().nBasis(); UTIL_CHECK(nBasis > 0); for (int i = 0; i < nMonomer; ++i) { if (field(i).isAllocated()) { UTIL_CHECK(field(i).capacity() == nBasis); } else { field(i).allocate(nBasis); } } } /** * Read fields in symmetry-adapted basis format. */ template <int D> void BasisFieldState<D>::read(const std::string & filename) { allocate(); system().fieldIo().readFieldsBasis(filename, fields(), unitCell()); } /** * Write fields in symmetry-adapted basis format. */ template <int D> void BasisFieldState<D>::write(const std::string & filename) { system().fieldIo().writeFieldsBasis(filename, fields(), unitCell()); } /* * Get current state of associated System. */ template <int D> void BasisFieldState<D>::getSystemState() { // Get system unit cell unitCell() = system().unitCell(); // Get system wFields allocate(); int nMonomer = system().mixture().nMonomer(); int nBasis = system().basis().nBasis(); int i, j; for (i = 0; i < nMonomer; ++i) { DArray<double>& stateField = field(i); const DArray<double>& systemField = system().w().basis(i); for (j = 0; j < nBasis; ++j) { stateField[j] = systemField[j]; } } } /* * Set System state to current state of the BasisFieldState object. */ template <int D> void BasisFieldState<D>::setSystemState(bool newCellParams) { system().setWBasis(fields()); if (newCellParams) { system().setUnitCell(unitCell()); } } } // namespace Pspg } // namespace Pscf #endif
3,004
C++
.tpp
114
21.157895
74
0.613319
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,232
SweepFactory.tpp
dmorse_pscfpp/src/pspg/sweep/SweepFactory.tpp
#ifndef PSPG_SWEEP_FACTORY_TPP #define PSPG_SWEEP_FACTORY_TPP /* * 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 "SweepFactory.h" #include "LinearSweep.h" namespace Pscf{ namespace Pspg{ using namespace Util; template <int D> SweepFactory<D>::SweepFactory(System<D>& system) : systemPtr_(&system) {} /* * Return a pointer to a Sweep subclass with name className */ template <int D> Sweep<D>* SweepFactory<D>::factory(std::string const & className) const { Sweep<D> *ptr = 0; // First check if name is known by any subfactories ptr = trySubfactories(className); if (ptr) return ptr; // Explicit class names if (className == "Sweep" || className == "LinearSweep") { ptr = new LinearSweep<D>(*systemPtr_); } return ptr; } } } #endif
993
C++
.tpp
36
23.305556
74
0.675847
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,233
Sweep.tpp
dmorse_pscfpp/src/pspg/sweep/Sweep.tpp
#ifndef PSPG_SWEEP_TPP /* * 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" #include <pscf/sweep/SweepTmpl.tpp> #include <pspg/System.h> #include <pspg/iterator/Iterator.h> #include <pscf/inter/Interaction.h> #include <util/misc/FileMaster.h> #include <util/misc/ioUtil.h> namespace Pscf { namespace Pspg { using namespace Util; // Maximum number of previous states = order of continuation + 1 #define PSPG_HISTORY_CAPACITY 3 /* * Default constructor. */ template <int D> Sweep<D>::Sweep() : SweepTmpl< BasisFieldState<D> >(PSPG_HISTORY_CAPACITY), writeCRGrid_(false), writeCBasis_(false), writeWRGrid_(false), systemPtr_(0) {} /* * Constructor, creates association with parent system. */ template <int D> Sweep<D>::Sweep(System<D> & system) : SweepTmpl< BasisFieldState<D> >(PSPG_HISTORY_CAPACITY), writeCRGrid_(false), writeCBasis_(false), writeWRGrid_(false), systemPtr_(&system) {} /* * Destructor. */ template <int D> Sweep<D>::~Sweep() {} /* * Set association with a parent system. */ template <int D> void Sweep<D>::setSystem(System<D>& system) { systemPtr_ = &system; } /* * Read parameters */ template <int D> void Sweep<D>::readParameters(std::istream& in) { // Call the base class's readParameters function. SweepTmpl< BasisFieldState<D> >::readParameters(in); // Read optional flags indicating which field types to output readOptional(in, "writeCRGrid", writeCRGrid_); readOptional(in, "writeCBasis", writeCBasis_); readOptional(in, "writeWRGrid", writeWRGrid_); } /* * Check allocation of one state object, allocate if necessary. */ template <int D> void Sweep<D>::checkAllocation(BasisFieldState<D>& state) { UTIL_CHECK(hasSystem()); state.setSystem(system()); state.allocate(); state.unitCell() = system().unitCell(); } /* * Setup operations at the beginning of a sweep. */ template <int D> void Sweep<D>::setup() { initialize(); checkAllocation(trial_); // Open log summary file std::string fileName = baseFileName_; fileName += "sweep.log"; system().fileMaster().openOutputFile(fileName, logFile_); }; /* * Set non-adjustable system parameters to new values. * * \param s path length coordinate, in range [0,1] */ template <int D> void Sweep<D>::setParameters(double s) { // Empty default implementation allows Sweep<D> to be compiled. UTIL_THROW("Calling unimplemented function Sweep::setParameters"); }; /* * Create guess for adjustable variables by polynomial extrapolation. */ template <int D> void Sweep<D>::extrapolate(double sNew) { UTIL_CHECK(historySize() > 0); // If historySize() == 1, do nothing: Use previous system state // as trial for the new state. if (historySize() > 1) { UTIL_CHECK(historySize() <= historyCapacity()); // Does the iterator allow a flexible unit cell ? bool isFlexible = system().iterator().isFlexible(); // Compute coefficients of polynomial extrapolation to sNew setCoefficients(sNew); // Set extrapolated trial w fields double coeff; int nMonomer = system().mixture().nMonomer(); int nBasis = system().basis().nBasis(); DArray<double>* newFieldPtr; DArray<double>* oldFieldPtr; int i, j, k; for (i=0; i < nMonomer; ++i) { newFieldPtr = &(trial_.field(i)); // Previous state k = 0 (most recent) oldFieldPtr = &state(0).field(i); coeff = c(0); for (j=0; j < nBasis; ++j) { (*newFieldPtr)[j] = coeff*(*oldFieldPtr)[j]; } // Previous states k >= 1 (older) for (k = 1; k < historySize(); ++k) { oldFieldPtr = &state(k).field(i); coeff = c(k); for (j=0; j < nBasis; ++j) { (*newFieldPtr)[j] += coeff*(*oldFieldPtr)[j]; } } } // Make sure unitCellParameters_ is up to date with system // (if we are sweeping in a lattice parameter, then the system // parameters will be up-to-date but unitCellParameters_ wont be) FSArray<double, 6> oldParameters = unitCellParameters_; unitCellParameters_ = system().unitCell().parameters(); // If isFlexible, then extrapolate the flexible unit cell parameters if (isFlexible) { double coeff; double parameter; #if 0 const FSArray<int,6> indices = system().iterator().flexibleParams(); const int nParameter = indices.size(); // Add contributions from all previous states for (k = 0; k < historySize(); ++k) { coeff = c(k); for (int i = 0; i < nParameter; ++i) { if (k == 0) { unitCellParameters_[indices[i]] = 0; } parameter = state(k).unitCell().parameter(indices[i]); unitCellParameters_[indices[i]] += coeff*parameter; } } #endif // Add contributions from all previous states const int nParameter = unitCellParameters_.size(); for (k = 0; k < historySize(); ++k) { coeff = c(k); for (int i = 0; i < nParameter; ++i) { if (k == 0) { unitCellParameters_[i] = 0.0; } parameter = state(k).unitCell().parameter(i); unitCellParameters_[i] += coeff*parameter; } } } // Reset trial_.unitCell() object trial_.unitCell().setParameters(unitCellParameters_); // Check if any unit cell parameters have changed bool newCellParams(true); for (int i = 0; i < oldParameters.size(); i++) { if (fabs(oldParameters[i] - unitCellParameters_[i]) < 1e-10) { newCellParams = false; break; } } // Transfer data from trial_ state to parent system trial_.setSystemState(newCellParams); } }; /* * Call current iterator to solve SCFT problem. * * Return 0 for sucessful solution, 1 on failure to converge. */ template <int D> int Sweep<D>::solve(bool isContinuation) { return system().iterate(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). */ template <int D> void Sweep<D>::reset() { bool isFlexible = system().iterator().isFlexible(); state(0).setSystemState(isFlexible); } /* * 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. */ template <int D> void Sweep<D>::getSolution() { state(0).setSystem(system()); state(0).getSystemState(); // Output converged solution to several files outputSolution(); // Output summary to log file outputSummary(logFile_); }; template <int D> void Sweep<D>::outputSolution() { std::ofstream out; std::string outFileName; std::string indexString = toString(nAccept() - 1); // Open parameter file, with thermodynamic properties at end outFileName = baseFileName_; outFileName += indexString; outFileName += ".stt"; system().fileMaster().openOutputFile(outFileName, out); // Write data file, with thermodynamic properties at end out << "System{" << std::endl; system().mixture().writeParam(out); system().interaction().writeParam(out); out << "}" << std::endl; out << std::endl; out << "unitCell " << system().unitCell(); system().writeThermo(out); out.close(); // Write w fields outFileName = baseFileName_; outFileName += indexString; outFileName += "_w"; outFileName += ".bf"; system().writeWBasis(outFileName); // Optionally write c rgrid files if (writeCRGrid_) { outFileName = baseFileName_; outFileName += indexString; outFileName += "_c"; outFileName += ".rf"; system().writeCRGrid(outFileName); } // Optionally write c basis files if (writeCBasis_) { outFileName = baseFileName_; outFileName += indexString; outFileName += "_c"; outFileName += ".bf"; system().writeCBasis(outFileName); } // Optionally write w rgrid files if (writeWRGrid_) { outFileName = baseFileName_; outFileName += indexString; outFileName += "_w"; outFileName += ".rf"; system().writeWRGrid(outFileName); } } template <int D> void Sweep<D>::outputSummary(std::ostream& out) { int i = nAccept() - 1; double sNew = s(0); out << Int(i,5) << Dbl(sNew) << Dbl(system().fHelmholtz(),16) << Dbl(system().pressure(),16); out << std::endl; } template <int D> void Sweep<D>::cleanup() { logFile_.close(); } } // namespace Pspg } // namespace Pscf #endif
9,886
C++
.tpp
295
25.8
80
0.590498
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,234
SweepParameter.tpp
dmorse_pscfpp/src/pspg/sweep/SweepParameter.tpp
#ifndef PSPG_SWEEP_PARAMETER_TPP #define PSPG_SWEEP_PARAMETER_TPP /* * 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/System.h> #include <pspg/solvers/Mixture.h> #include <pspg/solvers/Polymer.h> #include <pspg/solvers/Block.h> #include <pscf/crystal/UnitCell.h> #include <pscf/inter/Interaction.h> #include <util/containers/FSArray.h> #include <util/global.h> #include <algorithm> #include <iomanip> namespace Pscf { namespace Pspg { using namespace Util; /* * Default constructor. */ template <int D> SweepParameter<D>::SweepParameter() : type_(SweepParameter<D>::Null), nID_(0), id_(), initial_(0.0), change_(0.0), systemPtr_(0) {} /* * Constructor, creates association with system. */ template <int D> SweepParameter<D>::SweepParameter(System<D>& system) : type_(SweepParameter<D>::Null), nID_(0), id_(), initial_(0.0), change_(0.0), systemPtr_(&system) {} /* * Read type, set nId and allocate id_ array. */ template <int D> void SweepParameter<D>::readParamType(std::istream& in) { std::string buffer; in >> buffer; std::transform(buffer.begin(), buffer.end(), buffer.begin(), ::tolower); if (buffer == "block" || buffer == "block_length") { type_ = Block; nID_ = 2; // polymer and block identifiers } else if (buffer == "chi") { type_ = Chi; nID_ = 2; // two monomer type identifiers } else if (buffer == "kuhn") { type_ = Kuhn; nID_ = 1; // monomer type identifier } else if (buffer == "phi_polymer") { type_ = Phi_Polymer; nID_ = 1; //species identifier. } else if (buffer == "phi_solvent") { type_ = Phi_Solvent; nID_ = 1; //species identifier. } else if (buffer == "mu_polymer") { type_ = Mu_Polymer; nID_ = 1; //species identifier. } else if (buffer == "mu_solvent") { type_ = Mu_Solvent; nID_ = 1; //species identifier. } else if (buffer == "solvent" || buffer == "solvent_size") { type_ = Solvent; nID_ = 1; //species identifier. } else if (buffer == "cell_param") { type_ = Cell_Param; nID_ = 1; //lattice parameter identifier. } else { std::string msg = "Invalid SweepParameter::ParamType value: "; msg += buffer; //UTIL_THROW("Invalid SweepParameter::ParamType value"); UTIL_THROW(msg.c_str()); } if (id_.isAllocated()) id_.deallocate(); id_.allocate(nID_); } /* * Write type enum value */ template <int D> void SweepParameter<D>::writeParamType(std::ostream& out) const { out << type(); } /* * Get the current value from the parent system. */ template <int D> void SweepParameter<D>::getInitial() { initial_ = get_(); } /* * Set a new value in the parent system. */ template <int D> void SweepParameter<D>::update(double newVal) { set_(newVal); } /* * Get string representation of type enum value. */ template <int D> std::string SweepParameter<D>::type() const { if (type_ == Block) { return "block"; } else if (type_ == Chi) { return "chi"; } else if (type_ == Kuhn) { return "kuhn"; } else if (type_ == Phi_Polymer) { return "phi_polymer"; } else if (type_ == Phi_Solvent) { return "phi_solvent"; } else if (type_ == Mu_Polymer) { return "mu_polymer"; } else if (type_ == Mu_Solvent) { return "mu_solvent"; } else if (type_ == Solvent) { return "solvent_size"; } else if (type_ == Cell_Param) { return "cell_param"; } else { UTIL_THROW("This should never happen."); } } template <int D> double SweepParameter<D>::get_() { if (type_ == Block) { return systemPtr_->mixture().polymer(id(0)).block(id(1)).length(); } else if (type_ == Chi) { return systemPtr_->interaction().chi(id(0),id(1)); } else if (type_ == Kuhn) { return systemPtr_->mixture().monomer(id(0)).kuhn(); } else if (type_ == Phi_Polymer) { return systemPtr_->mixture().polymer(id(0)).phi(); } else if (type_ == Phi_Solvent) { return systemPtr_->mixture().solvent(id(0)).phi(); } else if (type_ == Mu_Polymer) { return systemPtr_->mixture().polymer(id(0)).mu(); } else if (type_ == Mu_Solvent) { return systemPtr_->mixture().solvent(id(0)).mu(); } else if (type_ == Solvent) { return systemPtr_->mixture().solvent(id(0)).size(); } else if (type_ == Cell_Param) { return systemPtr_->unitCell().parameter(id(0)); } else { UTIL_THROW("This should never happen."); } } template <int D> void SweepParameter<D>::set_(double newVal) { if (type_ == Block) { systemPtr_->mixture().polymer(id(0)).block(id(1)).setLength(newVal); } else if (type_ == Chi) { systemPtr_->interaction().setChi(id(0), id(1), newVal); } else if (type_ == Kuhn) { systemPtr_->mixture().setKuhn(id(0), newVal); } else if (type_ == Phi_Polymer) { systemPtr_->mixture().polymer(id(0)).setPhi(newVal); } else if (type_ == Phi_Solvent) { systemPtr_->mixture().solvent(id(0)).setPhi(newVal); } else if (type_ == Mu_Polymer) { systemPtr_->mixture().polymer(id(0)).setMu(newVal); } else if (type_ == Mu_Solvent) { systemPtr_->mixture().solvent(id(0)).setMu(newVal); } else if (type_ == Solvent) { systemPtr_->mixture().solvent(id(0)).setSize(newVal); } else if (type_ == Cell_Param) { FSArray<double,6> params = systemPtr_->unitCell().parameters(); params[id(0)] = newVal; systemPtr_->setUnitCell(params); } else { UTIL_THROW("This should never happen."); } } template <int D> template <class Archive> void SweepParameter<D>::serialize(Archive ar, const unsigned int version) { serializeEnum(ar, type_, version); ar & nID_; for (int i = 0; i < nID_; ++i) { ar & id_[i]; } ar & initial_; ar & change_; } // Definitions of operators, with no explicit instantiations. /** * Inserter for reading a SweepParameter from an istream. * * \param in input stream * \param param SweepParameter<D> object to read */ template <int D> std::istream& operator >> (std::istream& in, SweepParameter<D>& param) { // Read the parameter type. param.readParamType(in); // Read the identifiers associated with this parameter type. for (int i = 0; i < param.nID_; ++i) { in >> param.id_[i]; } // Read in the range in the parameter to sweep over in >> param.change_; return in; } /** * Extractor for writing a SweepParameter to ostream. * * \param out output stream * \param param SweepParameter<D> object to write */ template <int D> std::ostream& operator << (std::ostream& out, SweepParameter<D> const & param) { param.writeParamType(out); out << " "; for (int i = 0; i < param.nID_; ++i) { out << param.id(i); out << " "; } out << param.change_; return out; } } } #endif
7,728
C++
.tpp
250
24.384
77
0.565486
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,235
KFieldComparison.tpp
dmorse_pscfpp/src/pspg/field/KFieldComparison.tpp
#ifndef PSPG_K_FIELD_COMPARISON_TPP #define PSPG_K_FIELD_COMPARISON_TPP /* * 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 "KFieldComparison.h" #include <cmath> namespace Pscf { namespace Pspg { // Default Constructor template <int D> KFieldComparison<D>::KFieldComparison() : maxDiff_(0.0), rmsDiff_(0.0) {}; // Comparator for individual fields. template <int D> double KFieldComparison<D>::compare(RDFieldDft<D> const& a, RDFieldDft<D> const& b) { UTIL_CHECK(a.capacity() > 0); UTIL_CHECK(a.capacity() == b.capacity()); // Create temporary host arrays int nPoints = a.capacity(); cudaComplex* temp_a = new cudaComplex[nPoints]; cudaComplex* temp_b = new cudaComplex[nPoints]; cudaMemcpy(temp_a, a.cDField(), nPoints*sizeof(cudaComplex), cudaMemcpyDeviceToHost); cudaMemcpy(temp_b, b.cDField(), nPoints*sizeof(cudaComplex), cudaMemcpyDeviceToHost); double diffSq, diff, d0, d1; maxDiff_ = 0.0; rmsDiff_ = 0.0; for (int i = 0; i < nPoints; ++i) { d0 = temp_a[i].x - temp_b[i].x; d1 = temp_a[i].y - temp_b[i].y; diffSq = d0*d0 + d1*d1; diff = sqrt(diffSq); if (diff > maxDiff_) { maxDiff_ = diff; } rmsDiff_ += diffSq; } rmsDiff_ = rmsDiff_/double(nPoints); rmsDiff_ = sqrt(rmsDiff_); return maxDiff_; } // Comparator for arrays of fields template <int D> double KFieldComparison<D>::compare(DArray< RDFieldDft<D> > const & a, DArray< RDFieldDft<D> > const & b) { UTIL_CHECK(a.capacity() > 0); UTIL_CHECK(a.capacity() == b.capacity()); UTIL_CHECK(a[0].capacity() > 0); // Create temporary host arrays DArray< cudaComplex* > temp_a; DArray< cudaComplex* > temp_b; int nFields = a.capacity(); int nPoints = a[0].capacity(); temp_a.allocate(nFields); temp_b.allocate(nFields); for (int i = 0; i < nFields; i++) { temp_a[i] = new cudaComplex[nPoints]; temp_b[i] = new cudaComplex[nPoints]; cudaMemcpy(temp_a[i], a[i].cDField(), nPoints*sizeof(cudaComplex), cudaMemcpyDeviceToHost); cudaMemcpy(temp_b[i], b[i].cDField(), nPoints*sizeof(cudaComplex), cudaMemcpyDeviceToHost); } double diffSq, diff, d0, d1; maxDiff_ = 0.0; rmsDiff_ = 0.0; int i, j; for (i = 0; i < nFields; ++i) { for (j = 0; j < nPoints; ++j) { d0 = temp_a[i][j].x - temp_b[i][j].x; d1 = temp_a[i][j].y - temp_b[i][j].y; diffSq = d0*d0 + d1*d1; diff = sqrt(diffSq); if (diff > maxDiff_) { maxDiff_ = diff; } rmsDiff_ += diffSq; } } rmsDiff_ = rmsDiff_/double(nFields*nPoints); rmsDiff_ = sqrt(rmsDiff_); return maxDiff_; } } } #endif
3,099
C++
.tpp
91
26.912088
100
0.581776
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,236
Domain.tpp
dmorse_pscfpp/src/pspg/field/Domain.tpp
#ifndef PSPG_DOMAIN_TPP #define PSPG_DOMAIN_TPP /* * 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 "Domain.h" namespace Pscf { namespace Pspg { using namespace Util; /* * Constructor. */ template <int D> Domain<D>::Domain() : unitCell_(), mesh_(), basis_(), fft_(), fieldIo_(), lattice_(UnitCell<D>::Null), groupName_(), hasFileMaster_(false), isInitialized_(false) { setClassName("Domain"); } /* * Destructor. */ template <int D> Domain<D>::~Domain() {} template <int D> void Domain<D>::setFileMaster(FileMaster& fileMaster) { fieldIo_.associate(mesh_, fft_, lattice_, groupName_, group_, basis_, fileMaster); hasFileMaster_ = true; } /* * Read parameters and initialize. */ template <int D> void Domain<D>::readParameters(std::istream& in) { UTIL_CHECK(hasFileMaster_); bool hasUnitCell = false; // Uncomment for backwards compatibility for old format (<v1.0) #if 0 // Optionally read unit cell readOptional(in, "unitCell", unitCell_); if (unitCell_.lattice() != UnitCell<D>::Null) { lattice_ = unitCell_.lattice(); hasUnitCell = true; } #endif read(in, "mesh", mesh_); UTIL_CHECK(mesh().size() > 0); fft_.setup(mesh_.dimensions()); // If no unit cell was read, read lattice system if (!hasUnitCell) { read(in, "lattice", lattice_); unitCell_.set(lattice_); } UTIL_CHECK(unitCell().lattice() != UnitCell<D>::Null); UTIL_CHECK(unitCell().nParameter() > 0); // Allocate memory for WaveList waveList().allocate(mesh(), unitCell()); // Read group name and initialize space group read(in, "groupName", groupName_); readGroup(groupName_, group_); // Make symmetry-adapted basis if (unitCell().isInitialized()) { basis().makeBasis(mesh(), unitCell(), group_); } isInitialized_ = true; } template <int D> void Domain<D>::readRGridFieldHeader(std::istream& in, int& nMonomer) { // Read common section of standard field header int ver1, ver2; Pscf::readFieldHeader(in, ver1, ver2, unitCell_, groupName_, nMonomer); // Read grid dimensions std::string label; in >> label; if (label != "mesh" && label != "ngrid") { std::string msg = "\n"; msg += "Error reading field file:\n"; msg += "Expected mesh or ngrid, but found ["; msg += label; msg += "]"; UTIL_THROW(msg.c_str()); } IntVec<D> nGrid; in >> nGrid; // Initialize mesh, fft and basis mesh_.setDimensions(nGrid); fft_.setup(mesh_.dimensions()); // Initialize group and basis readGroup(groupName_, group_); basis_.makeBasis(mesh_, unitCell_, group_); isInitialized_ = true; } /* * Set the unit cell, make basis if needed. */ template <int D> void Domain<D>::setUnitCell(UnitCell<D> const & unitCell) { if (lattice_ == UnitCell<D>::Null) { lattice_ = unitCell.lattice(); } else { UTIL_CHECK(lattice_ == unitCell.lattice()); } unitCell_ = unitCell; if (!basis_.isInitialized()) { makeBasis(); } waveList_.computeKSq(unitCell_); waveList_.computedKSq(unitCell_); } /* * Set the unit cell, make basis if needed. */ template <int D> void Domain<D>::setUnitCell(typename UnitCell<D>::LatticeSystem lattice, FSArray<double, 6> const & parameters) { if (lattice_ == UnitCell<D>::Null) { lattice_ = lattice; } else { UTIL_CHECK(lattice_ == lattice); } unitCell_.set(lattice, parameters); if (!basis_.isInitialized()) { makeBasis(); } waveList_.computeKSq(unitCell_); waveList_.computedKSq(unitCell_); } /* * Set parameters of the associated unit cell, make basis if needed. */ template <int D> void Domain<D>::setUnitCell(FSArray<double, 6> const & parameters) { UTIL_CHECK(unitCell_.lattice() != UnitCell<D>::Null); UTIL_CHECK(unitCell_.nParameter() == parameters.size()); unitCell_.setParameters(parameters); if (!basis_.isInitialized()) { makeBasis(); } waveList_.computeKSq(unitCell_); waveList_.computedKSq(unitCell_); } template <int D> void Domain<D>::makeBasis() { UTIL_CHECK(mesh_.size() > 0); UTIL_CHECK(unitCell_.lattice() != UnitCell<D>::Null); UTIL_CHECK(unitCell_.nParameter() > 0); UTIL_CHECK(unitCell_.isInitialized()); #if 0 // Check group, read from file if necessary if (group_.size() == 1) { UTIL_CHECK(groupName_ != ""); readGroup(groupName_, group_); } #endif // Check basis, construct if not initialized if (!basis().isInitialized()) { basis_.makeBasis(mesh_, unitCell_, group_); } UTIL_CHECK(basis().isInitialized()); // Compute minimum images in WaveList UTIL_CHECK(waveList().isAllocated()); if (!waveList().hasMinimumImages()) { waveList().computeMinimumImages(mesh(), unitCell()); } } } // namespace Pspg } // namespace Pscf #endif
5,619
C++
.tpp
188
23.164894
75
0.587941
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,237
RDFieldDft.tpp
dmorse_pscfpp/src/pspg/field/RDFieldDft.tpp
#ifndef PSPG_R_DFIELD_DFT_TPP #define PSPG_R_DFIELD_DFT_TPP /* * PSCF Package * * Copyright 2016 - 2022, The Regents of the University of Minnesota * Distributed under the terms of the GNU General Public License. */ #include "RDFieldDft.h" namespace Pscf { namespace Pspg { using namespace Util; /** * Default constructor. */ template <int D> RDFieldDft<D>::RDFieldDft() : DField<cudaComplex>() {} /* * Destructor. */ template <int D> RDFieldDft<D>::~RDFieldDft() {} /* * Copy constructor. * * Allocates new memory and copies all elements by value. * *\param other the RField<D> to be copied. */ template <int D> RDFieldDft<D>::RDFieldDft(const RDFieldDft<D>& other) : DField<cudaComplex>(other) { meshDimensions_ = other.meshDimensions_; dftDimensions_ = other.dftDimensions_; } /* * Assignment, element-by-element. * * This operator will allocate memory if not allocated previously. * * \throw Exception if other Field is not allocated. * \throw Exception if both Fields are allocated with unequal capacities. * * \param other the rhs Field */ template <int D> RDFieldDft<D>& RDFieldDft<D>::operator = (const RDFieldDft<D>& other) { DField<cudaComplex>::operator = (other); meshDimensions_ = other.meshDimensions_; dftDimensions_ = other.dftDimensions_; return *this; } } } #endif
1,459
C++
.tpp
60
20.383333
75
0.678003
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,238
CFieldContainer.tpp
dmorse_pscfpp/src/pspg/field/CFieldContainer.tpp
#ifndef PSPG_C_FIELD_CONTAINER_TPP #define PSPG_C_FIELD_CONTAINER_TPP /* * 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 "CFieldContainer.h" namespace Pscf { namespace Pspg { using namespace Util; /* * Constructor. */ template <int D> CFieldContainer<D>::CFieldContainer() : basis_(), rgrid_(), nMonomer_(0), isAllocatedRGrid_(false), isAllocatedBasis_(false) {} /* * Destructor. */ template <int D> CFieldContainer<D>::~CFieldContainer() {} /* * Set the stored value of nMonomer (this may only be called once). */ template <int D> void CFieldContainer<D>::setNMonomer(int nMonomer) { UTIL_CHECK(nMonomer_ == 0); UTIL_CHECK(nMonomer > 0); nMonomer_ = nMonomer; } /* * Allocate memory for fields in r-grid format. */ template <int D> void CFieldContainer<D>::allocateRGrid(IntVec<D> const & meshDimensions) { UTIL_CHECK(nMonomer_ > 0); // If already allocated, deallocate. if (isAllocatedRGrid_) { deallocateRGrid(); } // Allocate arrays rgrid_.allocate(nMonomer_); for (int i = 0; i < nMonomer_; ++i) { rgrid_[i].allocate(meshDimensions); } isAllocatedRGrid_ = true; } /* * De-allocate memory for fields in r-grid format */ template <int D> void CFieldContainer<D>::deallocateRGrid() { UTIL_CHECK(isAllocatedRGrid_); UTIL_CHECK(nMonomer_ > 0); for (int i = 0; i < nMonomer_ ; ++i) { rgrid_[i].deallocate(); } rgrid_.deallocate(); isAllocatedRGrid_ = false; } /* * Allocate memory for fields in basis format. */ template <int D> void CFieldContainer<D>::allocateBasis(int nBasis) { UTIL_CHECK(nMonomer_ > 0); // If already allocated, deallocate. if (isAllocatedBasis_) { deallocateBasis(); } // Allocate basis_.allocate(nMonomer_); for (int i = 0; i < nMonomer_; ++i) { basis_[i].allocate(nBasis); } isAllocatedBasis_ = true; } /* * De-allocate memory for fields in basis format. */ template <int D> void CFieldContainer<D>::deallocateBasis() { UTIL_CHECK(nMonomer_ > 0); UTIL_CHECK(isAllocatedBasis_); for (int i = 0; i < nMonomer_; ++i) { basis_[i].deallocate(); } basis_.deallocate(); isAllocatedBasis_ = false; } /* * Allocate memory for all fields. */ template <int D> void CFieldContainer<D>::allocate(int nMonomer, int nBasis, IntVec<D> const & meshDimensions) { setNMonomer(nMonomer); allocateRGrid(meshDimensions); allocateBasis(nBasis); } } // namespace Pspg } // namespace Pscf #endif
2,959
C++
.tpp
119
19.504202
70
0.614594
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,239
RFieldComparison.tpp
dmorse_pscfpp/src/pspg/field/RFieldComparison.tpp
#ifndef PSPG_R_FIELD_COMPARISON_TPP #define PSPG_R_FIELD_COMPARISON_TPP /* * 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 "RFieldComparison.h" namespace Pscf { namespace Pspg { // Default Constructor template <int D> RFieldComparison<D>::RFieldComparison() {}; // Comparator for individual fields template <int D> double RFieldComparison<D>::compare(RDField<D> const& a, RDField<D> const& b) { // Copy data to host. int nPoints = a.capacity(); cudaReal* temp_a = new cudaReal[nPoints]; cudaReal* temp_b = new cudaReal[nPoints]; cudaMemcpy(temp_a, a.cDField(), nPoints*sizeof(cudaReal), cudaMemcpyDeviceToHost); cudaMemcpy(temp_b, b.cDField(), nPoints*sizeof(cudaReal), cudaMemcpyDeviceToHost); DArray< cudaReal > h_a, h_b; h_a.allocate(nPoints); h_b.allocate(nPoints); for (int j = 0; j < nPoints; j++) { h_a[j] = temp_a[j]; h_b[j] = temp_b[j]; } fieldComparison_.compare(h_a,h_b); compared_ = true; return fieldComparison_.maxDiff(); } // Comparator for arrays of fields template <int D> double RFieldComparison<D>::compare(DArray<RDField<D>> const& a, DArray<RDField<D>> const& b) { int nFields = a.capacity(); int nPoints = a[0].capacity(); // Array on host (used for cudaMemcpy) DArray< cudaReal* > temp_a, temp_b; temp_a.allocate(nFields); temp_b.allocate(nFields); // DArrays on host (for compatibility with FieldComparison) DArray< DArray< cudaReal > > h_a, h_b; h_a.allocate(nFields); h_b.allocate(nFields); for (int i = 0; i < nFields; i++) { temp_a[i] = new cudaReal[nPoints]; temp_b[i] = new cudaReal[nPoints]; cudaMemcpy(temp_a[i], a[i].cDField(), nPoints*sizeof(cudaReal), cudaMemcpyDeviceToHost); cudaMemcpy(temp_b[i], b[i].cDField(), nPoints*sizeof(cudaReal), cudaMemcpyDeviceToHost); h_a[i].allocate(nPoints); h_b[i].allocate(nPoints); for (int j = 0; j < nPoints; j++) { h_a[i][j] = temp_a[i][j]; h_b[i][j] = temp_b[i][j]; } } // Perform comparison fieldComparison_.compare(h_a,h_b); compared_ = true; return fieldComparison_.maxDiff(); } } } #endif
2,685
C++
.tpp
75
27.173333
80
0.579985
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,240
DField.tpp
dmorse_pscfpp/src/pspg/field/DField.tpp
#ifndef PSPG_DFIELD_TPP #define PSPG_DFIELD_TPP /* * 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 <cuda_runtime.h> namespace Pscf { namespace Pspg { using namespace Util; /* * Default constructor. */ template <typename Data> DField<Data>::DField() : data_(0), capacity_(0) {} /* * Destructor. */ template <typename Data> DField<Data>::~DField() { if (isAllocated()) { cudaFree(data_); capacity_ = 0; } } /* * Allocate the underlying C array. * * Throw an Exception if the Field has already allocated. * * \param capacity number of elements to allocate. */ template <typename Data> void DField<Data>::allocate(int capacity) { if (isAllocated()) { UTIL_THROW("Attempt to re-allocate a DField"); } if (capacity <= 0) { UTIL_THROW("Attempt to allocate with capacity <= 0"); } gpuErrchk(cudaMalloc((void**) &data_, capacity * sizeof(Data))); capacity_ = capacity; } /* * Deallocate the underlying C array. * * Throw an Exception if this Field is not allocated. */ template <typename Data> void DField<Data>::deallocate() { if (!isAllocated()) { UTIL_THROW("Array is not allocated"); } cudaFree(data_); capacity_ = 0; } /* * Copy constructor. * * Allocates new memory and copies all elements by value. * *\param other the Field to be copied. */ template <typename Data> DField<Data>::DField(const DField<Data>& other) { if (!other.isAllocated()) { UTIL_THROW("Other Field must be allocated."); } allocate(other.capacity_); cudaMemcpy(data_, other.cDField(), capacity_ * sizeof(Data), cudaMemcpyDeviceToDevice); } /* * Assignment. * * This operator will allocate memory if not allocated previously. * * \throw Exception if other Field is not allocated. * \throw Exception if both Fields are allocated with unequal capacities. * * \param other the rhs Field */ template <typename Data> DField<Data>& DField<Data>::operator = (const DField<Data>& other) { // Check for self assignment if (this == &other) return *this; // Precondition if (!other.isAllocated()) { UTIL_THROW("Other Field must be allocated."); } if (!isAllocated()) { allocate(other.capacity()); } else if (capacity_ != other.capacity_) { UTIL_THROW("Cannot assign Fields of unequal capacity"); } // Copy elements cudaMemcpy(data_, other.cDField(), capacity_ * sizeof(Data), cudaMemcpyDeviceToDevice); return *this; } } } #endif
2,942
C++
.tpp
116
20.172414
75
0.623441
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,241
WFieldContainer.tpp
dmorse_pscfpp/src/pspg/field/WFieldContainer.tpp
#ifndef PSPG_W_FIELD_CONTAINER_TPP #define PSPG_W_FIELD_CONTAINER_TPP /* * 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 "WFieldContainer.h" #include <pspg/field/FieldIo.h> namespace Pscf { namespace Pspg { using namespace Util; /* * Constructor. */ template <int D> WFieldContainer<D>::WFieldContainer() : basis_(), rgrid_(), fieldIoPtr_(0), meshDimensions_(), meshSize_(0), nBasis_(0), nMonomer_(0), isAllocatedRGrid_(false), isAllocatedBasis_(false), hasData_(false), isSymmetric_(false) {} /* * Destructor. */ template <int D> WFieldContainer<D>::~WFieldContainer() {} /* * Create an association with a FieldIo object. */ template <int D> void WFieldContainer<D>::setFieldIo(FieldIo<D> const & fieldIo) { fieldIoPtr_ = &fieldIo; } /* * Set the stored value of nMonomer (this may only be called once). */ template <int D> void WFieldContainer<D>::setNMonomer(int nMonomer) { UTIL_CHECK(nMonomer_ == 0); UTIL_CHECK(nMonomer > 0); nMonomer_ = nMonomer; } /* * Allocate memory for fields in r-grid format. */ template <int D> void WFieldContainer<D>::allocateRGrid(IntVec<D> const & meshDimensions) { UTIL_CHECK(nMonomer_ > 0); // If already allocated, deallocate. if (isAllocatedRGrid_) { deallocateRGrid(); } // Store mesh dimensions meshDimensions_ = meshDimensions; meshSize_ = 1; for (int i = 0; i < D; ++i) { UTIL_CHECK(meshDimensions[i] > 0); meshSize_ *= meshDimensions[i]; } // Allocate arrays rgrid_.allocate(nMonomer_); for (int i = 0; i < nMonomer_; ++i) { rgrid_[i].allocate(meshDimensions); } isAllocatedRGrid_ = true; } /* * De-allocate memory for fields in r-grid format */ template <int D> void WFieldContainer<D>::deallocateRGrid() { UTIL_CHECK(isAllocatedRGrid_); UTIL_CHECK(nMonomer_ > 0); for (int i = 0; i < nMonomer_; ++i) { rgrid_[i].deallocate(); } rgrid_.deallocate(); meshDimensions_ = 0; meshSize_ = 0; isAllocatedRGrid_ = false; } /* * Allocate memory for fields in basis format. */ template <int D> void WFieldContainer<D>::allocateBasis(int nBasis) { UTIL_CHECK(nMonomer_ > 0); UTIL_CHECK(nBasis > 0); // If already allocated, deallocate. if (isAllocatedBasis_) { deallocateBasis(); } // Allocate nBasis_ = nBasis; basis_.allocate(nMonomer_); for (int i = 0; i < nMonomer_; ++i) { basis_[i].allocate(nBasis); } isAllocatedBasis_ = true; } /* * De-allocate memory for fields in basis format. */ template <int D> void WFieldContainer<D>::deallocateBasis() { UTIL_CHECK(isAllocatedBasis_); UTIL_CHECK(nMonomer_ > 0); for (int i = 0; i < nMonomer_; ++i) { basis_[i].deallocate(); } basis_.deallocate(); nBasis_ = 0; isAllocatedBasis_ = false; } /* * Allocate memory for all fields. */ template <int D> void WFieldContainer<D>::allocate(int nMonomer, int nBasis, IntVec<D> const & meshDimensions) { setNMonomer(nMonomer); allocateRGrid(meshDimensions); allocateBasis(nBasis); } /* * Set new w-field values. */ template <int D> void WFieldContainer<D>::setBasis(DArray< DArray<double> > const & fields) { UTIL_CHECK(isAllocatedBasis_); UTIL_CHECK(fields.capacity() == nMonomer_); // Update system wFields for (int i = 0; i < nMonomer_; ++i) { DArray<double> const & f = fields[i]; DArray<double> & w = basis_[i]; UTIL_CHECK(f.capacity() == nBasis_); UTIL_CHECK(w.capacity() == nBasis_); for (int j = 0; j < nBasis_; ++j) { w[j] = f[j]; } } // Update system wFieldsRGrid fieldIoPtr_->convertBasisToRGrid(basis_, rgrid_); hasData_ = true; isSymmetric_ = true; } /* * Set new field values, using r-grid fields as inputs. */ template <int D> void WFieldContainer<D>::setRGrid(DArray< RDField<D> > const & fields, bool isSymmetric) { UTIL_CHECK(isAllocatedRGrid_); UTIL_CHECK(fields.capacity() == nMonomer_); // Update system wFieldsRGrid for (int i = 0; i < nMonomer_; ++i) { UTIL_CHECK(fields[i].capacity() == nBasis_) rgrid_[i] = fields[i]; } if (isSymmetric) { fieldIoPtr_->convertRGridToBasis(rgrid_, basis_); } hasData_ = true; isSymmetric_ = isSymmetric; } /* * Set new w-field values, using unfoldeded array of r-grid fields. */ template <int D> void WFieldContainer<D>::setRGrid(DField<cudaReal> & fields) { UTIL_CHECK(isAllocatedRGrid_); // GPU resources int nBlocks, nThreads; ThreadGrid::setThreadsLogical(meshSize_, nBlocks, nThreads); for (int i = 0; i < nMonomer_; i++) { assignReal<<<nBlocks, nThreads>>>(rgrid_[i].cDField(), fields.cDField() + i*meshSize_, meshSize_); } hasData_ = true; isSymmetric_ = false; } /* * 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. */ template <int D> void WFieldContainer<D>::readBasis(std::istream& in, UnitCell<D>& unitCell) { UTIL_CHECK(isAllocatedBasis()); fieldIoPtr_->readFieldsBasis(in, basis_, unitCell); // Update system wFieldsRGrid fieldIoPtr_->convertBasisToRGrid(basis_, rgrid_); hasData_ = true; isSymmetric_ = true; } /* * 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. */ template <int D> void WFieldContainer<D>::readBasis(std::string filename, UnitCell<D>& unitCell) { UTIL_CHECK(isAllocatedBasis()); fieldIoPtr_->readFieldsBasis(filename, basis_, unitCell); // Update system wFieldsRGrid fieldIoPtr_->convertBasisToRGrid(basis_, rgrid_); hasData_ = true; isSymmetric_ = true; } /* * 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. */ template <int D> void WFieldContainer<D>::readRGrid(std::istream& in, UnitCell<D>& unitCell, bool isSymmetric) { UTIL_CHECK(isAllocatedRGrid()); fieldIoPtr_->readFieldsRGrid(in, rgrid_, unitCell); if (isSymmetric) { fieldIoPtr_->convertRGridToBasis(rgrid_, basis_); } hasData_ = true; isSymmetric_ = isSymmetric; } /* * 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. */ template <int D> void WFieldContainer<D>::readRGrid(std::string filename, UnitCell<D>& unitCell, bool isSymmetric) { UTIL_CHECK(isAllocatedRGrid()); fieldIoPtr_->readFieldsRGrid(filename, rgrid_, unitCell); if (isSymmetric) { fieldIoPtr_->convertRGridToBasis(rgrid_, basis_); } hasData_ = true; isSymmetric_ = isSymmetric; } /* * Set new w-field values, using array of r-grid fields as input. */ template <int D> void WFieldContainer<D>::symmetrize() { UTIL_CHECK(hasData_); fieldIoPtr_->convertRGridToBasis(rgrid_, basis_); fieldIoPtr_->convertBasisToRGrid(basis_, rgrid_); isSymmetric_ = true; } } // namespace Pspg } // namespace Pscf #endif
9,196
C++
.tpp
305
23.377049
75
0.60627
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,242
RDField.tpp
dmorse_pscfpp/src/pspg/field/RDField.tpp
#ifndef PSPG_R_DFIELD_TPP #define PSPG_R_DFIELD_TPP /* * PSCF Package * * Copyright 2016 - 2022, The Regents of the University of Minnesota * Distributed under the terms of the GNU General Public License. */ #include "RDField.h" namespace Pscf { namespace Pspg { using namespace Util; /** * Default constructor. */ template <int D> RDField<D>::RDField() : DField<cudaReal>() {} /* * Destructor. */ template <int D> RDField<D>::~RDField() {} /* * Copy constructor. * * Allocates new memory and copies all elements by value. * *\param other the Field to be copied. */ template <int D> RDField<D>::RDField(const RDField<D>& other) : DField<cudaReal>(other), meshDimensions_(0) { meshDimensions_ = other.meshDimensions_; } /* * Assignment, element-by-element. * * This operator will allocate memory if not allocated previously. * * \throw Exception if other Field is not allocated. * \throw Exception if both Fields are allocated with unequal capacities. * * \param other the rhs Field */ template <int D> RDField<D>& RDField<D>::operator = (const RDField<D>& other) { DField<cudaReal>::operator = (other); meshDimensions_ = other.meshDimensions_; return *this; } } } #endif
1,334
C++
.tpp
60
18.516667
75
0.664557
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,243
FFTBatched.tpp
dmorse_pscfpp/src/pspg/field/FFTBatched.tpp
#ifndef PSPG_FFT_BATCHED_TPP #define PSPG_FFT_BATCHED_TPP /* * PSCF Package * * Copyright 2016 - 2022, The Regents of the University of Minnesota * Distributed under the terms of the GNU General Public License. */ #include "FFTBatched.h" #include <pspg/math/GpuResources.h> namespace Pscf { namespace Pspg { static __global__ void scaleComplexData(cudaComplex* 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].x *= scale; data[i].y *= scale; } } static __global__ void scaleRealData(cudaReal* data, cudaReal scale, int size) { 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; } } using namespace Util; /* * Default constructor. */ template <int D> FFTBatched<D>::FFTBatched() : meshDimensions_(0), rSize_(0), kSize_(0), fPlan_(0), iPlan_(0), isSetup_(false) {} /* * Destructor. */ template <int D> FFTBatched<D>::~FFTBatched() { if (fPlan_) { cufftDestroy(fPlan_); } if (iPlan_) { cufftDestroy(iPlan_); } } /* * Check and (if necessary) setup mesh dimensions. */ template <int D> void FFTBatched<D>::setup(RDField<D>& rField, RDFieldDft<D>& kField) { // Preconditions UTIL_CHECK(!isSetup_); IntVec<D> rDimensions = rField.meshDimensions(); IntVec<D> kDimensions = kField.meshDimensions(); UTIL_CHECK(rDimensions == kDimensions); // Set Mesh dimensions rSize_ = 1; kSize_ = 1; for (int i = 0; i < D; ++i) { UTIL_CHECK(rDimensions[i] > 0); meshDimensions_[i] = rDimensions[i]; rSize_ *= rDimensions[i]; if (i < D - 1) { kSize_ *= rDimensions[i]; } else { kSize_ *= (rDimensions[i]/2 + 1); } } //turned off to allow batch solution of MDE //UTIL_CHECK(rField.capacity() == rSize_); //UTIL_CHECK(kField.capacity() == kSize_); // Make FFTW plans (explicit specializations) makePlans(rField, kField); isSetup_ = true; } template <int D> void FFTBatched<D>::setup(const IntVec<D>& rDim, const IntVec<D>& kDim, int batchSize) { // Preconditions UTIL_CHECK(!isSetup_); // Set Mesh dimensions rSize_ = 1; kSize_ = 1; for (int i = 0; i < D; ++i) { UTIL_CHECK(rDim[i] > 0); meshDimensions_[i] = rDim[i]; rSize_ *= rDim[i]; if (i < D - 1) { kSize_ *= rDim[i]; } else { kSize_ *= (rDim[i]/2 + 1); } } //turned off to allow batch solution of MDE //UTIL_CHECK(rField.capacity() == rSize_); //UTIL_CHECK(kField.capacity() == kSize_); // Make FFTW plans (explicit specializations) makePlans(rDim, kDim, batchSize); isSetup_ = true; } /* * Make plans for batch size of 2 */ template <int D> void FFTBatched<D>::makePlans(RDField<D>& rField, RDFieldDft<D>& kField) { int n[D]; int rdist = 1; int kdist = 1; for(int i = 0; i < D; i++) { n[i] = rField.meshDimensions()[i]; if( i == D - 1 ) { kdist *= n[i]/2 + 1; } else { kdist *= n[i]; } rdist *= n[i]; } #ifdef SINGLE_PRECISION if(cufftPlanMany(&fPlan_, D, n, //plan, rank, n NULL, 1, rdist, //inembed, istride, idist NULL, 1, kdist, //onembed, ostride, odist CUFFT_R2C, 2) != CUFFT_SUCCESS) { std::cout<<"plan creation failed "<<std::endl; exit(1); } if(cufftPlanMany(&iPlan_, D, n, //plan, rank, n NULL, 1, rdist, //inembed, istride, idist NULL, 1, kdist, //onembed, ostride, odist CUFFT_C2R, 2) != CUFFT_SUCCESS) { std::cout<<"plan creation failed "<<std::endl; exit(1); } #else if(cufftPlanMany(&fPlan_, D, n, //plan, rank, n NULL, 1, rdist, //inembed, istride, idist NULL, 1, kdist, //onembed, ostride, odist CUFFT_D2Z, 2) != CUFFT_SUCCESS) { std::cout<<"plan creation failed "<<std::endl; exit(1); } if(cufftPlanMany(&iPlan_, D, n, //plan, rank, n NULL, 1, rdist, //inembed, istride, idist NULL, 1, kdist, //onembed, ostride, odist CUFFT_Z2D, 2) != CUFFT_SUCCESS) { std::cout<<"plan creation failed "<<std::endl; exit(1); } #endif } /* * Make plans for variable batch size */ template <int D> void FFTBatched<D>::makePlans(const IntVec<D>& rDim, const IntVec<D>& kDim, int batchSize) { int n[D]; int rdist = 1; int kdist = 1; for(int i = 0; i < D; i++) { n[i] = rDim[i]; if( i == D - 1 ) { kdist *= n[i]/2 + 1; } else { kdist *= n[i]; } rdist *= n[i]; } #ifdef SINGLE_PRECISION if(cufftPlanMany(&fPlan_, D, n, //plan, rank, n NULL, 1, rdist, //inembed, istride, idist NULL, 1, kdist, //onembed, ostride, odist CUFFT_R2C, batchSize) != CUFFT_SUCCESS) { std::cout<<"plan creation failed "<<std::endl; exit(1); } if(cufftPlanMany(&iPlan_, D, n, //plan, rank, n NULL, 1, kdist, //inembed, istride, idist NULL, 1, rdist, //onembed, ostride, odist CUFFT_C2R, batchSize) != CUFFT_SUCCESS) { std::cout<<"plan creation failed "<<std::endl; exit(1); } #else if(cufftPlanMany(&fPlan_, D, n, //plan, rank, n NULL, 1, rdist, //inembed, istride, idist NULL, 1, kdist, //onembed, ostride, odist CUFFT_D2Z, batchSize) != CUFFT_SUCCESS) { std::cout<<"plan creation failed "<<std::endl; exit(1); } if(cufftPlanMany(&iPlan_, D, n, //plan, rank, n NULL, 1, kdist, //inembed, istride, idist NULL, 1, rdist, //onembed, ostride, odist CUFFT_Z2D, batchSize) != CUFFT_SUCCESS) { std::cout<<"plan creation failed "<<std::endl; exit(1); } #endif } /* * Execute forward transform. */ template <int D> void FFTBatched<D>::forwardTransform(RDField<D>& rField, RDFieldDft<D>& kField) { // GPU resources int nBlocks, nThreads; ThreadGrid::setThreadsLogical(rSize_*2, nBlocks, nThreads); // Check dimensions or setup if (isSetup_) { UTIL_CHECK(rField.capacity() == 2*rSize_); UTIL_CHECK(kField.capacity() == 2*kSize_); } else { //UTIL_CHECK(0); //should never reach here in a parallel block. breaks instantly setup(rField, kField); } // Copy rescaled input data prior to work array cudaReal scale = 1.0/cudaReal(rSize_); //scale for every batch scaleRealData<<<nBlocks, nThreads>>>(rField.cDField(), scale, rSize_ * 2); //perform fft #ifdef SINGLE_PRECISION if(cufftExecR2C(fPlan_, rField.cDField(), kField.cDField()) != CUFFT_SUCCESS) { std::cout<<"CUFFT error: forward"<<std::endl; return; } #else if(cufftExecD2Z(fPlan_, rField.cDField(), kField.cDField()) != CUFFT_SUCCESS) { std::cout<<"CUFFT error: forward"<<std::endl; return; } #endif } /* * Execute forward transform. */ template <int D> void FFTBatched<D>::forwardTransform (cudaReal* rField, cudaComplex* kField, int batchSize) { // GPU resources int nBlocks, nThreads; ThreadGrid::setThreadsLogical(rSize_*batchSize, nBlocks, nThreads); // Check dimensions or setup if (isSetup_) { } else { std::cerr<<"Need to setup before running transform"<<std::endl; exit(1); } // Copy rescaled input data prior to work array cudaReal scale = 1.0/cudaReal(rSize_); //scale for every batch scaleRealData<<<nBlocks, nThreads>>>(rField, scale, rSize_ * batchSize); //perform fft #ifdef SINGLE_PRECISION if(cufftExecR2C(fPlan_, rField, kField) != CUFFT_SUCCESS) { std::cout<<"CUFFT error: forward"<<std::endl; return; } #else if(cufftExecD2Z(fPlan_, rField, kField) != CUFFT_SUCCESS) { std::cout<<"CUFFT error: forward"<<std::endl; return; } #endif } /* * Execute inverse (complex-to-real) transform. */ template <int D> void FFTBatched<D>::inverseTransform(RDFieldDft<D>& kField, RDField<D>& rField) { if (!isSetup_) { //UTIL_CHECK(0); setup(rField, kField); } #ifdef SINGLE_PRECISION if(cufftExecC2R(iPlan_, kField.cDField(), rField.cDField()) != CUFFT_SUCCESS) { std::cout<<"CUFFT error: inverse"<<std::endl; return; } #else if(cufftExecZ2D(iPlan_, kField.cDField(), rField.cDField()) != CUFFT_SUCCESS) { std::cout<<"CUFFT error: inverse"<<std::endl; return; } #endif } /* * Execute inverse (complex-to-real) transform. */ template <int D> void FFTBatched<D>::inverseTransform (cudaComplex* kField, cudaReal* rField, int batchSize) { if (!isSetup_) { std::cerr<<"Need to setup before running FFTbatchec"<<std::endl; } #ifdef SINGLE_PRECISION if(cufftExecC2R(iPlan_, kField, rField) != CUFFT_SUCCESS) { std::cout<<"CUFFT error: inverse"<<std::endl; return; } #else if(cufftExecZ2D(iPlan_, kField, rField) != CUFFT_SUCCESS) { std::cout<<"CUFFT error: inverse"<<std::endl; return; } #endif } } } #endif
10,382
C++
.tpp
326
23.613497
93
0.545637
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,244
FFT.tpp
dmorse_pscfpp/src/pspg/field/FFT.tpp
#ifndef PSPG_FFT_TPP #define PSPG_FFT_TPP /* * PSCF Package * * Copyright 2016 - 2022, The Regents of the University of Minnesota * Distributed under the terms of the GNU General Public License. */ #include "FFT.h" #include <pspg/math/GpuResources.h> //forward declaration //static __global__ void scaleRealData(cudaReal* data, rtype scale, int size); namespace Pscf { namespace Pspg { using namespace Util; /* * Default constructor. */ template <int D> FFT<D>::FFT() : meshDimensions_(0), rSize_(0), kSize_(0), fPlan_(0), iPlan_(0), isSetup_(false) {} /* * Destructor. */ template <int D> FFT<D>::~FFT() { if (fPlan_) { cufftDestroy(fPlan_); } if (iPlan_) { cufftDestroy(iPlan_); } } /* * Setup mesh dimensions. */ template <int D> void FFT<D>::setup(IntVec<D> const& meshDimensions) { // Precondition UTIL_CHECK(!isSetup_); // Create local r-grid and k-grid field objects RDField<D> rField; rField.allocate(meshDimensions); RDFieldDft<D> kField; kField.allocate(meshDimensions); setup(rField, kField); } /* * Check and (if necessary) setup mesh dimensions. */ template <int D> void FFT<D>::setup(RDField<D>& rField, RDFieldDft<D>& kField) { // Preconditions UTIL_CHECK(!isSetup_); IntVec<D> rDimensions = rField.meshDimensions(); IntVec<D> kDimensions = kField.meshDimensions(); UTIL_CHECK(rDimensions == kDimensions); // Set Mesh dimensions rSize_ = 1; kSize_ = 1; for (int i = 0; i < D; ++i) { UTIL_CHECK(rDimensions[i] > 0); meshDimensions_[i] = rDimensions[i]; rSize_ *= rDimensions[i]; if (i < D - 1) { kSize_ *= rDimensions[i]; } else { kSize_ *= (rDimensions[i]/2 + 1); } } UTIL_CHECK(rField.capacity() == rSize_); UTIL_CHECK(kField.capacity() == kSize_); // Make FFTW plans (explicit specializations) makePlans(rField, kField); // Allocate rFieldCopy_ array if necessary if (!rFieldCopy_.isAllocated()) { rFieldCopy_.allocate(rDimensions); } else { if (rFieldCopy_.capacity() != rSize_) { rFieldCopy_.deallocate(); rFieldCopy_.allocate(rDimensions); } } UTIL_CHECK(rFieldCopy_.capacity() == rSize_); // Allocate kFieldCopy_ array if necessary if (!kFieldCopy_.isAllocated()) { kFieldCopy_.allocate(kDimensions); } else { if (kFieldCopy_.capacity() != rSize_) { kFieldCopy_.deallocate(); kFieldCopy_.allocate(kDimensions); } } UTIL_CHECK(kFieldCopy_.capacity() == kSize_); isSetup_ = true; } /* * Execute forward transform. */ template <int D> void FFT<D>::forwardTransform(RDField<D> & rField, RDFieldDft<D>& kField) const { // GPU resources int nBlocks, nThreads; ThreadGrid::setThreadsLogical(rSize_, nBlocks, nThreads); // Check dimensions or setup UTIL_CHECK(isSetup_); UTIL_CHECK(rField.capacity() == rSize_); UTIL_CHECK(kField.capacity() == kSize_); // Rescale outputted data. cudaReal scale = 1.0/cudaReal(rSize_); scaleRealData<<<nBlocks, nThreads>>>(rField.cDField(), scale, rSize_); //perform fft #ifdef SINGLE_PRECISION if(cufftExecR2C(fPlan_, rField.cDField(), kField.cDField()) != CUFFT_SUCCESS) { std::cout << "CUFFT error: forward" << std::endl; return; } #else if(cufftExecD2Z(fPlan_, rField.cDField(), kField.cDField()) != CUFFT_SUCCESS) { std::cout << "CUFFT error: forward" << std::endl; return; } #endif } /* * Execute forward transform without destroying input. */ template <int D> void FFT<D>::forwardTransformSafe(RDField<D> const & rField, RDFieldDft<D>& kField) const { UTIL_CHECK(rFieldCopy_.capacity() == rField.capacity()); rFieldCopy_ = rField; forwardTransform(rFieldCopy_, kField); } /* * Execute inverse (complex-to-real) transform. */ template <int D> void FFT<D>::inverseTransform(RDFieldDft<D> & kField, RDField<D>& rField) const { UTIL_CHECK(isSetup_); UTIL_CHECK(rField.capacity() == rSize_); UTIL_CHECK(kField.capacity() == kSize_); UTIL_CHECK(rField.meshDimensions() == meshDimensions_); UTIL_CHECK(kField.meshDimensions() == meshDimensions_); #ifdef SINGLE_PRECISION if(cufftExecC2R(iPlan_, kField.cDField(), rField.cDField()) != CUFFT_SUCCESS) { std::cout << "CUFFT error: inverse" << std::endl; return; } #else if(cufftExecZ2D(iPlan_, kField.cDField(), rField.cDField()) != CUFFT_SUCCESS) { std::cout << "CUFFT error: inverse" << std::endl; return; } #endif } /* * Execute inverse (complex-to-real) transform without destroying input. */ template <int D> void FFT<D>::inverseTransformSafe(RDFieldDft<D> const & kField, RDField<D>& rField) const { UTIL_CHECK(kFieldCopy_.capacity()==kField.capacity()); kFieldCopy_ = kField; inverseTransform(kFieldCopy_, rField); } } } #if 0 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; } } #endif #endif
5,721
C++
.tpp
195
23.174359
87
0.607195
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,245
FieldIo.tpp
dmorse_pscfpp/src/pspg/field/FieldIo.tpp
#ifndef PSPG_FIELD_IO_TPP #define PSPG_FIELD_IO_TPP /* * 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 "FieldIo.h" #include <pscf/crystal/shiftToMinimum.h> #include <pscf/crystal/UnitCell.h> #include <pscf/mesh/MeshIterator.h> #include <pscf/math/IntVec.h> #include <util/misc/Log.h> #include <util/format/Str.h> #include <util/format/Int.h> #include <util/format/Dbl.h> #include <iomanip> #include <string> #include <cmath> namespace Pscf { namespace Pspg { using namespace Util; /* * Constructor. */ template <int D> FieldIo<D>::FieldIo() : meshPtr_(0), fftPtr_(0), latticePtr_(0), groupNamePtr_(0), groupPtr_(0), basisPtr_(0), fileMasterPtr_(0) {} /* * Destructor. */ template <int D> FieldIo<D>::~FieldIo() {} /* * Get and store addresses of associated objects. */ template <int D> void FieldIo<D>::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) { meshPtr_ = &mesh; fftPtr_ = &fft; latticePtr_ = &lattice; groupNamePtr_ = &groupName; groupPtr_ = &group; basisPtr_ = &basis; fileMasterPtr_ = &fileMaster; } template <int D> void FieldIo<D>::readFieldsBasis(std::istream& in, DArray< DArray<double> >& fields, UnitCell<D>& unitCell) const { // Read generic part of field file header. // Set nMonomer to number of field components in file int nMonomer; FieldIo<D>::readFieldHeader(in, nMonomer, unitCell); UTIL_CHECK(nMonomer > 0); // Read number of stars from field file into StarIn std::string label; in >> label; if (label != "N_star" && label != "N_basis") { std::string msg = "\n"; msg += "Error reading field file:\n"; msg += "Expected N_basis or N_star, but found ["; msg += label; msg += "]"; UTIL_THROW(msg.c_str()); } int nStarIn; in >> nStarIn; UTIL_CHECK(nStarIn > 0); // Check dimensions of fields array int nMonomerFields = fields.capacity(); UTIL_CHECK(nMonomer == nMonomerFields); int i, j; int fieldCapacity = fields[0].capacity(); for (i = 0; i < nMonomer; ++i) { UTIL_CHECK(fields[i].capacity() == fieldCapacity); } // Define nStar and nBasis int nStar = basis().nStar(); int nBasis = basis().nBasis(); // Initialize all elements of field components to zero for (j = 0; j < nMonomer; ++j) { UTIL_CHECK(fields[j].capacity() == nBasis); for (i = 0; i < nBasis; ++i) { fields[j][i] = 0.0; } } // Allocate buffer arrays used to read components DArray<double> temp, temp2; temp.allocate(nMonomer); temp2.allocate(nMonomer); // Variables needed in loop over stars typename Basis<D>::Star const * starPtr; typename Basis<D>::Star const * starPtr2; IntVec<D> waveIn, waveIn2; int starId, starId2; int basisId, basisId2; int waveId, waveId2; std::complex<double> coeff, phasor; IntVec<D> waveBz, waveDft; int nWaveVector; int nReversedPair = 0; bool waveExists; // Loop over stars in input file to read field components i = 0; while (i < nStarIn) { // Read next line of data for (int j = 0; j < nMonomer; ++j) { in >> temp[j]; // field components } in >> waveIn; // wave of star in >> nWaveVector; // # of waves in star // Check if waveIn is in first Brillouin zone (FBZ) for the mesh. waveBz = shiftToMinimum(waveIn, mesh().dimensions(), unitCell); waveExists = (waveIn == waveBz); if (!waveExists) { // If wave is not in FBZ, ignore and continue ++i; } else { // If wave is in FBZ, process the line // Find the star containing waveIn waveDft = waveIn; mesh().shift(waveDft); waveId = basis().waveId(waveDft); starId = basis().wave(waveId).starId; starPtr = &basis().star(starId); UTIL_CHECK(!(starPtr->cancel)); // basisId = starId; basisId = starPtr->basisId; if (starPtr->invertFlag == 0) { if (starPtr->waveBz == waveIn) { // Copy components of closed star to fields array for (int j = 0; j < nMonomer; ++j) { fields[j][basisId] = temp[j]; } } else { Log::file() << "Inconsistent wave of closed star on input\n" << "wave from file = " << waveIn << "\n" << "starId of wave = " << starId << "\n" << "waveBz of star = " << starPtr->waveBz << "\n"; } ++i; // increment input line counter i } else { // If starPtr->invertFlag != 0 // Read the next line for (int j = 0; j < nMonomer; ++j) { in >> temp2[j]; // components of field } in >> waveIn2; // wave of star in >> nWaveVector; // # of wavevectors in star // Check that waveIn2 is also in the 1st BZ waveBz = shiftToMinimum(waveIn2, mesh().dimensions(), unitCell); UTIL_CHECK(waveIn2 == waveBz); // Identify the star containing waveIn2 waveDft = waveIn2; mesh().shift(waveDft); waveId2 = basis().waveId(waveDft); starId2 = basis().wave(waveId2).starId; starPtr2 = &basis().star(starId2); UTIL_CHECK(!(starPtr2->cancel)); //basisId2 = starId2; basisId2 = starPtr2->basisId; if (starPtr->invertFlag == 1) { // This is a pair of open stars written in the same // order as in this basis. Check preconditions: UTIL_CHECK(starPtr2->invertFlag == -1); UTIL_CHECK(starId2 = starId + 1); UTIL_CHECK(basisId2 = basisId + 1); UTIL_CHECK(starPtr->waveBz == waveIn); UTIL_CHECK(starPtr2->waveBz == waveIn2); // Copy components for both stars into fields array for (int j = 0; j < nMonomer; ++j) { fields[j][basisId] = temp[j]; fields[j][basisId2] = temp2[j]; } } else if (starPtr->invertFlag == -1) { // This is a pair of open stars written in opposite // order from in this basis. Check preconditions: UTIL_CHECK(starPtr2->invertFlag == 1); UTIL_CHECK(starId == starId2 + 1); UTIL_CHECK(basisId == basisId2 + 1); UTIL_CHECK(waveId == starPtr->beginId); // Check that waveIn2 is negation of waveIn IntVec<D> nVec; nVec.negate(waveIn); nVec = shiftToMinimum(nVec, mesh().dimensions(), unitCell); UTIL_CHECK(waveIn2 == nVec); /* * Consider two related stars, C and D, that are listed in * the order (C,D) in the basis used in this code (the * reading program), but that were listed in the opposite * order (D,C) in the program that wrote the file (the * writing program). In the basis of the reading program, * star C has star index starId2, while star D has index * starId = starid2 + 1. * * Let f(r) and f^{*}(r) denote the basis functions used * by the reading program for stars C and D, respectively. * Let u(r) and u^{*}(r) denote the corresponding basis * functions used by the writing program for stars C * and D. Let exp(i phi) denote the unit magnitude * coefficient (i.e., phasor) within f(r) of the wave * with wave index waveId2, which was the characteristic * wave for star C in the writing program. The * coefficient of this wave within the basis function * u(r) used by the writing program must instead be real * and positive. This implies that * u(r) = exp(-i phi) f(r). * * Focus on the contribution to the field for a specific * monomer type j. Let a and b denote the desired * coefficients of stars C and D in the reading program, * for which the total contribution of both stars to the * field is: * * (a - ib) f(r) + (a + ib) f^{*}(r) * * Let A = temp[j] and B = temp2[j] denote the * coefficients read from file in order (A,B). Noting * that the stars were listed in the order (D,C) in the * basis used by the writing program, the contribution * of both stars must be (A-iB)u^{*}(r)+(A+iB)u(r), or: * * (A+iB) exp(-i phi)f(r) + (A-iB) exp(i phi) f^{*}(r) * * Comparing coefficients of f^{*}(r), we find that * * (a + ib) = (A - iB) exp(i phi) * * This equality is implemented below, where the * variable "phasor" is set equal to exp(i phi). */ phasor = basis().wave(waveId2).coeff; phasor = phasor/std::abs(phasor); for (int j = 0; j < nMonomer; ++j) { coeff = std::complex<double>(temp[j],-temp2[j]); coeff *= phasor; fields[j][basisId2] = real(coeff); fields[j][basisId ] = imag(coeff); } // Increment count of number of reversed open pairs ++nReversedPair; } else { UTIL_THROW("Invalid starInvert value"); } // Increment counter by 2 because two lines were read i = i + 2; } // if (wavePtr->invertFlag == 0) ... else ... } // if (!waveExists) ... else ... } // end while (i < nStarIn) if (nReversedPair > 0) { Log::file() << "\n"; Log::file() << nReversedPair << " reversed pairs of open stars" << " detected in FieldIo::readFieldsBasis\n"; } } template <int D> void FieldIo<D>::readFieldsBasis(std::string filename, DArray< DArray<double> >& fields, UnitCell<D>& unitCell) const { std::ifstream file; fileMaster().openInputFile(filename, file); readFieldsBasis(file, fields, unitCell); file.close(); } template <int D> void FieldIo<D>::writeFieldsBasis(std::ostream &out, DArray< DArray<double> > const& fields, UnitCell<D> const & unitCell) const { int nMonomer = fields.capacity(); UTIL_CHECK(nMonomer > 0); UTIL_CHECK(basis().isInitialized()); // Write header writeFieldHeader(out, nMonomer, unitCell); out << "N_basis " << std::endl << " " << basis().nBasis() << std::endl; // Define nStar and nBasis int nStar = basis().nStar(); //int nBasis = nStar; int nBasis = basis().nBasis(); // Write fields int ib = 0; for (int i = 0; i < nStar; ++i) { if (!basis().star(i).cancel) { UTIL_CHECK(ib == basis().star(i).basisId); for (int j = 0; j < nMonomer; ++j) { out << Dbl(fields[j][ib], 20, 10); } out << " "; for (int j = 0; j < D; ++j) { out << Int(basis().star(i).waveBz[j], 5); } out << Int(basis().star(i).size, 5) << std::endl; ++ib; } } } template <int D> void FieldIo<D>::writeFieldsBasis(std::string filename, DArray< DArray<double> > const& fields, UnitCell<D> const & unitCell) const { std::ofstream file; fileMaster().openOutputFile(filename, file); writeFieldsBasis(file, fields, unitCell); file.close(); } template <int D> void FieldIo<D>::readFieldsRGrid(std::istream &in, DArray<RDField<D> >& fields, UnitCell<D>& unitCell) const { // Read generic part of field header int nMonomer; FieldIo<D>::readFieldHeader(in, nMonomer, unitCell); UTIL_CHECK(nMonomer > 0); UTIL_CHECK(nMonomer == fields.capacity()); // Read grid dimensions std::string label; in >> label; if (label != "mesh" && label != "ngrid") { std::string msg = "\n"; msg += "Error reading field file:\n"; msg += "Expected mesh or ngrid, but found ["; msg += label; msg += "]"; UTIL_THROW(msg.c_str()); } IntVec<D> nGrid; in >> nGrid; UTIL_CHECK(nGrid == mesh().dimensions()); DArray<cudaReal*> temp_out; temp_out.allocate(nMonomer); for(int i = 0; i < nMonomer; ++i) { temp_out[i] = new cudaReal[mesh().size()]; } IntVec<D> offsets; offsets[D - 1] = 1; for(int i = D - 1 ; i > 0; --i ) { offsets[i - 1] = offsets[i] * mesh().dimension(i); } IntVec<D> position; for(int i = 0; i < D; ++i) { position[i] = 0; } int rank = 0; int positionId; for(int i = 0; i < mesh().size(); i++) { rank = 0; for(int dim = 0; dim < D; ++dim) { rank += offsets[dim] * position[dim]; } for(int k = 0; k < nMonomer; ++k) { in >> std::setprecision(15)>> temp_out[k][rank]; } //add position positionId = 0; while( positionId < D) { position[positionId]++; if ( position[positionId] == mesh().dimension(positionId) ) { position[positionId] = 0; positionId++; continue; } break; } } for (int i = 0; i < nMonomer; i++) { cudaMemcpy(fields[i].cDField(), temp_out[i], mesh().size() * sizeof(cudaReal), cudaMemcpyHostToDevice); delete[] temp_out[i]; temp_out[i] = nullptr; } } template <int D> void FieldIo<D>::readFieldsRGrid(std::string filename, DArray< RDField<D> >& fields, UnitCell<D>& unitCell) const { std::ifstream file; fileMaster().openInputFile(filename, file); readFieldsRGrid(file, fields, unitCell); file.close(); } template <int D> void FieldIo<D>::writeFieldsRGrid(std::ostream &out, DArray<RDField<D> > const& fields, UnitCell<D> const & unitCell) const { int nMonomer = fields.capacity(); UTIL_CHECK(nMonomer > 0); writeFieldHeader(out, nMonomer, unitCell); out << "mesh " << std::endl << " " << mesh().dimensions() << std::endl; DArray<cudaReal*> temp_out; temp_out.allocate(nMonomer); for (int i = 0; i < nMonomer; ++i) { temp_out[i] = new cudaReal[mesh().size()]; cudaMemcpy(temp_out[i], fields[i].cDField(), mesh().size() * sizeof(cudaReal), cudaMemcpyDeviceToHost); } IntVec<D> offsets; offsets[D - 1] = 1; for(int i = D - 1 ; i > 0; --i ) { offsets[i - 1] = offsets[i] * mesh().dimension(i); } IntVec<D> position; for(int i = 0; i < D; ++i) { position[i] = 0; } int rank = 0; int positionId; for(int i = 0; i < mesh().size(); i++) { rank = 0; for(int dim = 0; dim < D; ++dim) { rank += offsets[dim] * position[dim]; } for(int k = 0; k < nMonomer; ++k) { out << " " << Dbl(temp_out[k][rank], 18, 15); } out<<'\n'; //add position positionId = 0; while( positionId < D) { position[positionId]++; if ( position[positionId] == mesh().dimension(positionId) ) { position[positionId] = 0; positionId++; continue; } break; } } for(int i = 0; i < nMonomer; ++i) { delete[] temp_out[i]; temp_out[i] = nullptr; } } template <int D> void FieldIo<D>::writeFieldsRGrid(std::string filename, DArray< RDField<D> > const & fields, UnitCell<D> const & unitCell) const { std::ofstream file; fileMaster().openOutputFile(filename, file); writeFieldsRGrid(file, fields, unitCell); file.close(); } template <int D> void FieldIo<D>::readFieldRGrid(std::istream &in, RDField<D> &field, UnitCell<D>& unitCell) const { int nMonomer; FieldIo<D>::readFieldHeader(in, nMonomer, unitCell); UTIL_CHECK(nMonomer == 1); std::string label; in >> label; if (label != "mesh" && label != "ngrid") { std::string msg = "\n"; msg += "Error reading field file:\n"; msg += "Expected mesh or ngrid, but found ["; msg += label; msg += "]"; UTIL_THROW(msg.c_str()); } IntVec<D> nGrid; in >> nGrid; UTIL_CHECK(nGrid == mesh().dimensions()); cudaReal* temp_out = new cudaReal[mesh().size()]; IntVec<D> offsets; offsets[D - 1] = 1; for(int i = D - 1 ; i > 0; --i ) { offsets[i - 1] = offsets[i] * mesh().dimension(i); } IntVec<D> position; for(int i = 0; i < D; ++i) { position[i] = 0; } int rank = 0; int positionId; for(int i = 0; i < mesh().size(); i++) { rank = 0; for(int dim = 0; dim < D; ++dim) { rank += offsets[dim] * position[dim]; } in >> std::setprecision(15) >> temp_out[rank]; //add position positionId = 0; while( positionId < D) { position[positionId]++; if ( position[positionId] == mesh().dimension(positionId) ) { position[positionId] = 0; positionId++; continue; } break; } } cudaMemcpy(field.cDField(), temp_out, mesh().size() * sizeof(cudaReal), cudaMemcpyHostToDevice); delete[] temp_out; temp_out = nullptr; } template <int D> void FieldIo<D>::readFieldRGrid(std::string filename, RDField<D> &field, UnitCell<D>& unitCell) const { std::ifstream file; fileMaster().openInputFile(filename, file); readFieldRGrid(file, field, unitCell); file.close(); } template <int D> void FieldIo<D>::writeFieldRGrid(std::ostream &out, RDField<D> const & field, UnitCell<D> const & unitCell, bool writeHeader) const { if (writeHeader) { writeFieldHeader(out, 1, unitCell); out << "mesh " << std::endl << " " << mesh().dimensions() << std::endl; } cudaReal* temp_out = new cudaReal[mesh().size()];; cudaMemcpy(temp_out, field.cDField(), mesh().size() * sizeof(cudaReal), cudaMemcpyDeviceToHost); IntVec<D> offsets; offsets[D - 1] = 1; for(int i = D - 1 ; i > 0; --i ) { offsets[i - 1] = offsets[i] * mesh().dimension(i); } IntVec<D> position; for(int i = 0; i < D; ++i) { position[i] = 0; } int rank = 0; int positionId; for(int i = 0; i < mesh().size(); i++) { rank = 0; for(int dim = 0; dim < D; ++dim) { rank += offsets[dim] * position[dim]; } out << " " << Dbl(temp_out[rank], 18, 15); out<<'\n'; //add position positionId = 0; while( positionId < D) { position[positionId]++; if ( position[positionId] == mesh().dimension(positionId) ) { position[positionId] = 0; positionId++; continue; } break; } } delete[] temp_out; temp_out = nullptr; } template <int D> void FieldIo<D>::writeFieldRGrid(std::string filename, RDField<D> const & field, UnitCell<D> const & unitCell) const { std::ofstream file; fileMaster().openOutputFile(filename, file); writeFieldRGrid(file, field, unitCell); file.close(); } template <int D> void FieldIo<D>::readFieldsKGrid(std::istream &in, DArray< RDFieldDft<D> >& fields, UnitCell<D>& unitCell) const { // Read header int nMonomer; readFieldHeader(in, nMonomer, unitCell); UTIL_CHECK(nMonomer > 0); UTIL_CHECK(nMonomer == fields.capacity()); std::string label; in >> label; if (label != "mesh" && label != "ngrid") { std::string msg = "\n"; msg += "Error reading field file:\n"; msg += "Expected mesh or ngrid, but found ["; msg += label; msg += "]"; UTIL_THROW(msg.c_str()); } IntVec<D> nGrid; in >> nGrid; UTIL_CHECK(nGrid == mesh().dimensions()); DArray<cudaComplex*> temp_out; temp_out.allocate(nMonomer); int kSize = 1; for (int i = 0; i < D; i++) { if (i == D - 1) { kSize *= (mesh().dimension(i) / 2 + 1); } else { kSize *= mesh().dimension(i); } } for(int i = 0; i < nMonomer; ++i) { temp_out[i] = new cudaComplex[kSize]; } // Read Fields; int idum; MeshIterator<D> itr(mesh().dimensions()); for (int i = 0; i < kSize; ++i) { in >> idum; for (int j = 0; j < nMonomer; ++j) { in >> temp_out [j][i].x; in >> temp_out [j][i].y; } } for(int i = 0; i < nMonomer; ++i) { cudaMemcpy(fields[i].cDField(), temp_out[i], kSize * sizeof(cudaComplex), cudaMemcpyHostToDevice); delete[] temp_out[i]; temp_out[i] = nullptr; } } template <int D> void FieldIo<D>::readFieldsKGrid(std::string filename, DArray< RDFieldDft<D> >& fields, UnitCell<D>& unitCell) const { std::ifstream file; fileMaster().openInputFile(filename, file); readFieldsKGrid(file, fields, unitCell); file.close(); } template <int D> void FieldIo<D>::writeFieldsKGrid(std::ostream &out, DArray<RDFieldDft<D> > const& fields, UnitCell<D> const & unitCell) const { int nMonomer = fields.capacity(); UTIL_CHECK(nMonomer > 0); // Write header writeFieldHeader(out, nMonomer, unitCell); out << "mesh " << std::endl << " " << mesh().dimensions() << std::endl; DArray<cudaComplex*> temp_out; int kSize = 1; for (int i = 0; i < D; i++) { if (i == D - 1) { kSize *= (mesh().dimension(i) / 2 + 1); } else { kSize *= mesh().dimension(i); } } temp_out.allocate(nMonomer); for(int i = 0; i < nMonomer; ++i) { temp_out[i] = new cudaComplex[kSize]; cudaMemcpy(temp_out[i], fields[i].cDField(), kSize * sizeof(cudaComplex), cudaMemcpyDeviceToHost); } // Write fields MeshIterator<D> itr(mesh().dimensions()); for (int i = 0; i < kSize; i++) { out << Int(i, 5); for (int j = 0; j < nMonomer; ++j) { out << " " << Dbl(temp_out[j][i].x, 18, 11) << Dbl(temp_out[j][i].y, 18, 11); } out << std::endl; } for(int i = 0; i < nMonomer; ++i) { delete[] temp_out[i]; temp_out[i] = nullptr; } } template <int D> void FieldIo<D>::writeFieldsKGrid(std::string filename, DArray< RDFieldDft<D> > const & fields, UnitCell<D> const & unitCell) const { std::ofstream file; fileMaster().openOutputFile(filename, file); writeFieldsKGrid(file, fields, unitCell); file.close(); } #if 0 template <int D> void FieldIo<D>::readFieldHeader(std::istream& in, int& nMonomer, UnitCell<D>& unitCell) const { // Preconditions UTIL_CHECK(latticePtr_); UTIL_CHECK(groupNamePtr_); int ver1, ver2; std::string groupNameIn; Pscf::readFieldHeader(in, ver1, ver2, unitCell, groupNameIn, nMonomer); // Note:: Function definition in pscf/crystal/UnitCell.tpp // Check data from header UTIL_CHECK(ver1 == 1); UTIL_CHECK(ver2 == 0); UTIL_CHECK(unitCell.isInitialized()); UTIL_CHECK(unitCell.lattice() != UnitCell<D>::Null); UTIL_CHECK(unitCell.nParameter() > 0); UTIL_CHECK(nMonomer > 0); if (groupNameIn != groupName()) { Log::file() << std::endl << "Warning - " << "Mismatched group names in FieldIo::readFieldHeader \n" << " FieldIo::groupName :" << groupName() << "\n" << " Field file groupName :" << groupNameIn << "\n"; } } #endif /* * Read common part of field header. * * Return the number of monomers in the file. * Set the unitCell. * If necessary, make the Basis. */ template <int D> void FieldIo<D>::readFieldHeader(std::istream& in, int& nMonomer, UnitCell<D>& unitCell) const { // Preconditions UTIL_CHECK(latticePtr_); UTIL_CHECK(groupNamePtr_); if (unitCell.lattice() == UnitCell<D>::Null) { UTIL_CHECK(unitCell.nParameter() == 0); } else { UTIL_CHECK(unitCell.nParameter() > 0); if (lattice() != UnitCell<D>::Null) { UTIL_CHECK(unitCell.lattice() == lattice()); } } // Read field header to set unitCell, groupNameIn, nMonomer int ver1, ver2; std::string groupNameIn; Pscf::readFieldHeader(in, ver1, ver2, unitCell, groupNameIn, nMonomer); // Note: Function definition in pscf/crystal/UnitCell.tpp // Checks of data from header UTIL_CHECK(ver1 == 1); UTIL_CHECK(ver2 == 0); UTIL_CHECK(unitCell.isInitialized()); UTIL_CHECK(unitCell.lattice() != UnitCell<D>::Null); UTIL_CHECK(unitCell.nParameter() > 0); // Validate or initialize lattice type if (lattice() == UnitCell<D>::Null) { lattice() = unitCell.lattice(); } else { if (lattice() != unitCell.lattice()) { Log::file() << std::endl << "Error - " << "Mismatched lattice types, FieldIo::readFieldHeader:\n" << " FieldIo::lattice :" << lattice() << "\n" << " Unit cell lattice :" << unitCell.lattice() << "\n"; UTIL_THROW("Mismatched lattice types"); } } // Validate or initialize group name if (groupName() == "") { groupName() = groupNameIn; } else { if (groupNameIn != groupName()) { Log::file() << std::endl << "Error - " << "Mismatched group names in FieldIo::readFieldHeader:\n" << " FieldIo::groupName :" << groupName() << "\n" << " Field file header :" << groupNameIn << "\n"; UTIL_THROW("Mismatched group names"); } } // Check group, read from file if necessary UTIL_CHECK(groupPtr_); if (group().size() == 1) { if (groupName() != "I") { readGroup(groupName(), group()); } } // Check basis, construct if not initialized UTIL_CHECK(basisPtr_); if (!basis().isInitialized()) { basisPtr_->makeBasis(mesh(), unitCell, group()); } UTIL_CHECK(basis().isInitialized()); } template <int D> void FieldIo<D>::writeFieldHeader(std::ostream &out, int nMonomer, UnitCell<D> const & unitCell) const { out << "format 1 0" << std::endl; out << "dim" << std::endl << " " << D << std::endl; writeUnitCellHeader(out, unitCell); out << "group_name" << std::endl << " " << groupName() << std::endl; out << "N_monomer" << std::endl << " " << nMonomer << std::endl; } template <int D> void FieldIo<D>::convertBasisToKGrid(DArray<double> const& components, RDFieldDft<D>& dft) const { UTIL_CHECK(mesh().dimensions() == dft.meshDimensions()); UTIL_CHECK(basis().isInitialized()); const int nBasis = basis().nBasis(); const int nStar = basis().nStar(); UTIL_CHECK(nBasis > 0); UTIL_CHECK(nStar >= nBasis); // Compute DFT array size int kSize = 1; for (int i = 0; i < D; i++) { if (i == D - 1) { kSize *= (mesh().dimension(i) / 2 + 1); } else { kSize *= mesh().dimension(i); } } kSize = dft.capacity(); // Allocate dft_out cudaComplex* dft_out; dft_out = new cudaComplex[kSize]; // Create Mesh<D> with dimensions of DFT Fourier grid. Mesh<D> dftMesh(dft.dftDimensions()); typename Basis<D>::Star const* starPtr; // pointer to current star typename Basis<D>::Wave const* wavePtr; // pointer to current wave std::complex<double> component; // coefficient for star std::complex<double> coeff; // coefficient for wave IntVec<D> indices; // dft grid indices of wave int rank; // dft grid rank of wave int is; // star index int ib; // basis index int iw; // wave index // Initialize all dft_out components to zero for (rank = 0; rank < dftMesh.size(); ++rank) { dft_out[rank].x = 0.0; dft_out[rank].y = 0.0; } // Loop over stars, skipping cancelled stars is = 0; while (is < basis().nStar()) { starPtr = &(basis().star(is)); if (starPtr->cancel) { ++is; continue; } // Set basis id for uncancelled star ib = starPtr->basisId; if (starPtr->invertFlag == 0) { // Make complex coefficient for star basis function UTIL_ASSERT(!isnan(components[ib])); UTIL_ASSERT(!isinf(components[ib])); component = std::complex<double>(components[ib], 0.0); // Loop over waves in closed star for (iw = starPtr->beginId; iw < starPtr->endId; ++iw) { wavePtr = &basis().wave(iw); if (!wavePtr->implicit) { coeff = component*(wavePtr->coeff); UTIL_ASSERT(!isnan(coeff.real())); UTIL_ASSERT(!isnan(coeff.imag())); indices = wavePtr->indicesDft; rank = dftMesh.rank(indices); dft_out[rank].x = coeff.real(); dft_out[rank].y = coeff.imag(); } } ++is; } else if (starPtr->invertFlag == 1) { UTIL_ASSERT(!isnan(components[ib])); UTIL_ASSERT(!isnan(components[ib+1])); UTIL_ASSERT(!isinf(components[ib])); UTIL_ASSERT(!isinf(components[ib+1])); // Loop over waves in first star component = std::complex<double>(components[ib], -components[ib+1]); component /= sqrt(2.0); starPtr = &(basis().star(is)); for (iw = starPtr->beginId; iw < starPtr->endId; ++iw) { wavePtr = &basis().wave(iw); if (!(wavePtr->implicit)) { coeff = component*(wavePtr->coeff); UTIL_ASSERT(!isnan(coeff.real())); UTIL_ASSERT(!isnan(coeff.imag())); indices = wavePtr->indicesDft; rank = dftMesh.rank(indices); dft_out[rank].x = (cudaReal)coeff.real(); dft_out[rank].y = (cudaReal)coeff.imag(); } } // Loop over waves in second star starPtr = &(basis().star(is+1)); UTIL_CHECK(starPtr->invertFlag == -1); component = std::complex<double>(components[ib], +components[ib+1]); component /= sqrt(2.0); for (iw = starPtr->beginId; iw < starPtr->endId; ++iw) { wavePtr = &basis().wave(iw); if (!(wavePtr->implicit)) { coeff = component*(wavePtr->coeff); UTIL_ASSERT(!isnan(coeff.real())); UTIL_ASSERT(!isnan(coeff.imag())); indices = wavePtr->indicesDft; rank = dftMesh.rank(indices); dft_out[rank].x = (cudaReal)coeff.real(); dft_out[rank].y = (cudaReal)coeff.imag(); } } // Increment star counter by 2 (two stars were processed) is += 2; } else { UTIL_THROW("Invalid invertFlag value"); } } // Copy dft_out (host) to dft (device) cudaMemcpy(dft.cDField(), dft_out, kSize * sizeof(cudaComplex), cudaMemcpyHostToDevice); delete[] dft_out; } template <int D> void FieldIo<D>::convertKGridToBasis(RDFieldDft<D> const& dft, DArray<double>& components) const { UTIL_CHECK(basis().isInitialized()); const int nStar = basis().nStar(); // Number of stars const int nBasis = basis().nBasis(); // Number of basis functions // Allocate dft_in int kSize = 1; for (int i = 0; i < D; i++) { if (i == D - 1) { kSize *= (mesh().dimension(i) / 2 + 1); } else { kSize *= mesh().dimension(i); } } cudaComplex* dft_in; dft_in = new cudaComplex[kSize]; // Copy dft (device) to dft_in (host) cudaMemcpy(dft_in, dft.cDField(), kSize * sizeof(cudaComplex), cudaMemcpyDeviceToHost); // Create Mesh<D> with dimensions of DFT Fourier grid. Mesh<D> dftMesh(dft.dftDimensions()); // Declare variables needed in loop over stars typename Basis<D>::Star const* starPtr; // pointer to current star typename Basis<D>::Wave const* wavePtr; // pointer to current wave std::complex<double> component; // component for star std::complex<double> coefficient; // coefficient in basis int rank; // dft grid rank of wave int is; // star index int ib; // basis index int iw; // wave id, within star bool isImplicit; // Initialize all elements of components to zero for (is = 0; is < nBasis; ++is) { components[is] = 0.0; } // Loop over all stars is = 0; while (is < nStar) { starPtr = &(basis().star(is)); // Skip if star is cancelled if (starPtr->cancel) { ++is; continue; } // Set basis id for uncancelled star ib = starPtr->basisId; if (starPtr->invertFlag == 0) { // Choose a characteristic wave that is not implicit. // Start with the first, alternately searching from // the beginning and end of star. int beginId = starPtr->beginId; int endId = starPtr->endId; iw = 0; isImplicit = true; while (isImplicit) { wavePtr = &basis().wave(beginId + iw); if (!wavePtr->implicit) { isImplicit = false; } else { UTIL_CHECK(beginId + iw < endId - 1 - iw); wavePtr = &basis().wave(endId - 1 - iw); if (!wavePtr->implicit) { isImplicit = false; } } ++iw; } UTIL_CHECK(wavePtr->starId == is); // Compute component value rank = dftMesh.rank(wavePtr->indicesDft); component = std::complex<double>(dft_in[rank].x, dft_in[rank].y); bool componentError = false; #if UTIL_DEBUG if (std::isnan(component.real())) componentError = true; if (std::isnan(component.imag())) componentError = true; #endif coefficient = wavePtr->coeff; #if UTIL_DEBUG if (std::isnan(coefficient.real())) componentError = true; if (std::isnan(coefficient.imag())) componentError = true; if (std::isnormal(coefficient)) componentError = true; #endif component /= coefficient; #if UTIL_DEBUG if (std::isnan(component.real())) componentError = true; if (std::isnan(component.imag())) componentError = true; if (std::isinf(component.real())) componentError = true; if (std::isinf(component.imag())) componentError = true; #endif // Verify that imaginary component is very small #ifdef SINGLE_PRECISION if (abs(component.imag()) > 1.0E-4) componentError = true; #else if (abs(component.imag()) > 1.0E-8) componentError = true; #endif // Verbose reporting of any detected error if (componentError) { std::complex<double> waveComponent = std::complex<double>(dft_in[rank].x, dft_in[rank].y); Log::file() << " Error in FieldIo::convertKGridToBasis\n" << "Star Id " << starPtr->starId << "\n" << "Basis Id " << starPtr->basisId << "\n" << "Star WaveBz " << starPtr->waveBz << "\n" << "Wave indices " << wavePtr->indicesDft << "\n" << "Wave coeff " << wavePtr->indicesDft << "\n" << "Wave component " << Dbl(waveComponent.real()) << Dbl(waveComponent.imag()) << "\n" << "Wave coefficient" << Dbl(coefficient.real()) << Dbl(coefficient.imag()) << "\n" << "Star component " << Dbl(component.real()) << Dbl(component.imag()) << "\n"; UTIL_THROW("Error: Component error in FieldIo::convertKGridToBasis"); } // Store real part components[ib] = component.real(); ++is; } else if (starPtr->invertFlag == 1) { // Identify a characteristic wave that is not implicit: // Either first wave of 1st star or last wave of 2nd star. wavePtr = &basis().wave(starPtr->beginId); if (wavePtr->implicit) { starPtr = &(basis().star(is+1)); UTIL_CHECK(starPtr->invertFlag == -1); wavePtr = &basis().wave(starPtr->endId - 1); UTIL_CHECK(!(wavePtr->implicit)); UTIL_CHECK(wavePtr->starId == is+1); } rank = dftMesh.rank(wavePtr->indicesDft); // Compute component value component = std::complex<double>(dft_in[rank].x, dft_in[rank].y); UTIL_CHECK(abs(wavePtr->coeff) > 1.0E-8); component /= wavePtr->coeff; component *= sqrt(2.0); // Compute basis function coefficient values if (starPtr->invertFlag == 1) { components[ib] = component.real(); components[ib+1] = -component.imag(); } else { components[ib] = component.real(); components[ib+1] = component.imag(); } // Increment star counter by 2 (two stars were processed) is += 2; } else { UTIL_THROW("Invalid invertFlag value"); } } // loop over star index is // Deallocate arrays (clean up) delete[] dft_in; } template <int D> void FieldIo<D>::convertBasisToKGrid(DArray< DArray<double> > const & in, DArray< RDFieldDft<D> >& out) const { UTIL_CHECK(in.capacity() == out.capacity()); const int n = in.capacity(); for (int i = 0; i < n; ++i) { convertBasisToKGrid(in[i], out[i]); } } template <int D> void FieldIo<D>::convertKGridToBasis(DArray< RDFieldDft<D> > const & in, DArray< DArray<double> > & out) const { UTIL_ASSERT(in.capacity() == out.capacity()); int n = in.capacity(); for (int i = 0; i < n; ++i) { convertKGridToBasis(in[i], out[i]); } } template <int D> void FieldIo<D>::convertBasisToRGrid(DArray< DArray<double> > const & in, DArray< RDField<D> >& out) const { UTIL_CHECK(basis().isInitialized()); UTIL_CHECK(in.capacity() == out.capacity()); const int nMonomer = in.capacity(); DArray< RDFieldDft<D> > workDft; workDft.allocate(nMonomer); for(int i = 0; i < nMonomer; ++i) { workDft[i].allocate(mesh().dimensions()); } convertBasisToKGrid(in, workDft); for (int i = 0; i < nMonomer; ++i) { fft().inverseTransformSafe(workDft[i], out[i]); workDft[i].deallocate(); } } template <int D> void FieldIo<D>::convertRGridToBasis(DArray< RDField<D> > const & in, DArray< DArray<double> > & out) const { UTIL_CHECK(basis().isInitialized()); UTIL_CHECK(in.capacity() == out.capacity()); const int nMonomer = in.capacity(); // Allocate work space DArray< RDFieldDft<D> > workDft; workDft.allocate(nMonomer); for(int i = 0; i < nMonomer; ++i) { workDft[i].allocate(mesh().dimensions()); } // Forward FFT, then KGrid to Basis for (int i = 0; i < nMonomer; ++i) { fft().forwardTransformSafe(in[i], workDft [i]); } convertKGridToBasis(workDft, out); // Deallocate work space for (int i = 0; i < nMonomer; ++i) { workDft[i].deallocate(); } } template <int D> void FieldIo<D>::convertKGridToRGrid(DArray< RDFieldDft<D> > const & in, DArray< RDField<D> >& out) const { UTIL_ASSERT(in.capacity() == out.capacity()); int n = in.capacity(); for (int i = 0; i < n; ++i) { fft().inverseTransformSafe(in[i], out[i]); } } template <int D> void FieldIo<D>::convertRGridToKGrid(DArray< RDField<D> > const & in, DArray< RDFieldDft<D> >& out) const { UTIL_ASSERT(in.capacity() == out.capacity()); int n = in.capacity(); for (int i = 0; i < n; ++i) { fft().forwardTransformSafe(in[i], out[i]); } } template <int D> void FieldIo<D>::checkWorkDft() const { if (!workDft_.isAllocated()) { workDft_.allocate(mesh().dimensions()); } else { UTIL_CHECK(workDft_.meshDimensions() == fft().meshDimensions()); } } } // namespace Pspc } // namespace Pscf #endif
46,295
C++
.tpp
1,225
26.482449
84
0.494785
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,246
AmIteratorTmpl.tpp
dmorse_pscfpp/src/pscf/iterator/AmIteratorTmpl.tpp
#ifndef PSCF_AM_ITERATOR_TMPL_TPP #define PSCF_AM_ITERATOR_TMPL_TPP /* * 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> #include <pscf/math/LuSolver.h> #include "NanException.h" #include <util/containers/FArray.h> #include <util/format/Dbl.h> #include <util/format/Int.h> #include <util/misc/Timer.h> #include <cmath> namespace Pscf { using namespace Util; // Public member functions /* * Constructor */ template <typename Iterator, typename T> AmIteratorTmpl<Iterator,T>::AmIteratorTmpl() : errorType_("relNormResid"), epsilon_(0), lambda_(0), maxItr_(200), maxHist_(50), nBasis_(0), itr_(0), nElem_(0), verbose_(0), outputTime_(false), isAllocatedAM_(false) { setClassName("AmIteratorTmpl"); } /* * Destructor */ template <typename Iterator, typename T> AmIteratorTmpl<Iterator,T>::~AmIteratorTmpl() {} /* * Read parameter file block. */ template <typename Iterator, typename T> void AmIteratorTmpl<Iterator,T>::readParameters(std::istream& in) { // Error tolerance for scalar error. Stop when error < epsilon. read(in, "epsilon", epsilon_); // Maximum number of iterations (optional parameter) // Default set in constructor (200) or before calling this function readOptional(in, "maxItr", maxItr_); // Maximum number of previous states in history (optional) // Default set in constructor (50) or before calling this function readOptional(in, "maxHist", maxHist_); // Verbosity level of error reporting, values 0-2 (optional) // Initialized to 0 by default in constructor // verbose_ = 0 => concise // verbose_ = 1 => report all error measures at end // verbose_ = 2 => report all error measures every iteration readOptional(in, "verbose", verbose_); // Flag to output timing results (true) or skip (false) // Initialized to false by default in constructor readOptional(in, "outputTime", outputTime_); } /* * Iteratively solve a SCF problem. */ template <typename Iterator, typename T> int AmIteratorTmpl<Iterator,T>::solve(bool isContinuation) { // Initialization and allocate operations on entry to loop. setup(isContinuation); // Preconditions for generic Anderson-mixing (AM) algorithm. UTIL_CHECK(hasInitialGuess()); UTIL_CHECK(isAllocatedAM_); // Timers for analyzing performance Timer timerMDE; Timer timerStress; Timer timerAM; Timer timerResid; Timer timerError; Timer timerCoeff; Timer timerOmega; Timer timerTotal; // Start overall timer timerTotal.start(); // Solve MDE for initial state timerMDE.start(); evaluate(); timerMDE.stop(); // Iterative loop nBasis_ = fieldBasis_.size(); for (itr_ = 0; itr_ < maxItr_; ++itr_) { // Append current field to fieldHists_ ringbuffer getCurrent(temp_); fieldHists_.append(temp_); timerAM.start(); if (verbose_ > 1) { Log::file() << "------------------------------- \n"; } Log::file() << " Iteration " << Int(itr_,5); if (nBasis_ < maxHist_) { lambda_ = 1.0 - pow(0.9, nBasis_ + 1); } else { lambda_ = 1.0; } // Compute residual vector timerResid.start(); getResidual(temp_); // Append current residual to resHists_ ringbuffer resHists_.append(temp_); timerResid.stop(); // Compute scalar error, output report to log file. timerError.start(); double error; try { error = computeError(verbose_); } catch (const NanException&) { Log::file() << ", error = NaN" << std::endl; break; // Exit loop if a NanException is caught } if (verbose_ < 2) { Log::file() << ", error = " << Dbl(error, 15) << std::endl; } timerError.stop(); // Output additional details of this iteration to the log file outputToLog(); // Check for convergence if (error < epsilon_) { // Stop timers timerAM.stop(); timerTotal.stop(); if (verbose_ > 1) { Log::file() << "-------------------------------\n"; } Log::file() << " Converged\n"; // Output error report if not done previously if (verbose_ == 1) { Log::file() << "\n"; computeError(2); } // Output timing results, if requested. if (outputTime_) { double total = timerTotal.time(); Log::file() << "\n"; Log::file() << "Iterator times contributions:\n"; Log::file() << "\n"; Log::file() << "MDE solution: " << timerMDE.time() << " s, " << timerMDE.time()/total << "\n"; Log::file() << "residual computation: " << timerResid.time() << " s, " << timerResid.time()/total << "\n"; Log::file() << "mixing coefficients: " << timerCoeff.time() << " s, " << timerCoeff.time()/total << "\n"; Log::file() << "checking convergence: " << timerError.time() << " s, " << timerError.time()/total << "\n"; Log::file() << "updating guess: " << timerOmega.time() << " s, " << timerOmega.time()/total << "\n"; Log::file() << "total time: " << total << " s \n"; } Log::file() << "\n"; // Successful completion (i.e., converged within tolerance) return 0; } else { // Compute optimal coefficients for basis vectors timerCoeff.start(); computeResidCoeff(); timerCoeff.stop(); // Compute the trial updated field and update the system timerOmega.start(); updateGuess(); timerOmega.stop(); timerAM.stop(); // Perform the main calculation of the parent system - // solve MDEs, compute phi's, compute stress if needed timerMDE.start(); evaluate(); timerMDE.stop(); } } // Failure: iteration counter itr reached maxItr without converging timerTotal.stop(); Log::file() << "Iterator failed to converge.\n"; return 1; } // Protected member functions /* * Set value of maxItr. */ template <typename Iterator, typename T> void AmIteratorTmpl<Iterator,T>::setMaxItr(int maxItr) { maxItr_ = maxItr; } /* * Set value of maxHist (number of retained previous states) */ template <typename Iterator, typename T> void AmIteratorTmpl<Iterator,T>::setMaxHist(int maxHist) { maxHist_ = maxHist; } /* * Set and validate value of error type string. */ template <typename Iterator, typename T> void AmIteratorTmpl<Iterator,T>::setErrorType(std::string errorType) { errorType_ = errorType; if (!isValidErrorType()) { std::string msg = "Invalid iterator error type ["; msg += errorType; msg += "] input in AmIteratorTmpl::setErrorType"; UTIL_THROW(msg.c_str()); } } /* * Read and validate errorType string parameter. */ template <typename Iterator, typename T> void AmIteratorTmpl<Iterator,T>::readErrorType(std::istream& in) { // Read optional string // Note: errorType_ is initialized to "relNormResid" in constructor readOptional(in, "errorType", errorType_); if (!isValidErrorType()) { std::string msg = "Invalid iterator error type ["; msg += errorType_; msg += "] in parameter file"; UTIL_THROW(msg.c_str()); } } template <typename Iterator, typename T> bool AmIteratorTmpl<Iterator,T>::isValidErrorType() { // Process possible synonyms if (errorType_ == "norm") errorType_ = "normResid"; if (errorType_ == "rms") errorType_ = "rmsResid"; if (errorType_ == "max") errorType_ = "maxResid"; if (errorType_ == "relNorm") errorType_ = "relNormResid"; // Check value bool valid; valid = (errorType_ == "normResid" || errorType_ == "rmsResid" || errorType_ == "maxResid" || errorType_ == "relNormResid"); return valid; } /* * Allocate memory required by the Anderson-Mixing algorithm, if needed. * (protected, non-virtual) */ template <typename Iterator, typename T> void AmIteratorTmpl<Iterator,T>::allocateAM() { // If already allocated, do nothing and return if (isAllocatedAM_) return; // Compute and set number of elements in a residual vector nElem_ = nElements(); // Allocate ring buffers fieldHists_.allocate(maxHist_+1); resHists_.allocate(maxHist_+1); fieldBasis_.allocate(maxHist_); resBasis_.allocate(maxHist_); // Allocate arrays used in iteration fieldTrial_.allocate(nElem_); resTrial_.allocate(nElem_); temp_.allocate(nElem_); // Allocate arrays/matrices used in coefficient calculation U_.allocate(maxHist_, maxHist_); v_.allocate(maxHist_); coeffs_.allocate(maxHist_); isAllocatedAM_ = true; } template <typename Iterator, typename T> void AmIteratorTmpl<Iterator,T>::clear() { if (!isAllocatedAM_) return; // Clear histories and bases (ring buffers) Log::file() << "Clearing ring buffers\n"; resHists_.clear(); fieldHists_.clear(); resBasis_.clear(); fieldBasis_.clear(); return; } // Private non-virtual member functions /* * Compute coefficients of basis vectors. */ template <typename Iterator, typename T> void AmIteratorTmpl<Iterator,T>::computeResidCoeff() { // If first iteration and history is empty // then initialize U, v and coeff arrays if (itr_ == 0 && nBasis_ == 0) { int m, n; for (m = 0; m < maxHist_; ++m) { v_[m] = 0.0; coeffs_[m] = 0.0; for (n = 0; n < maxHist_; ++n) { U_(m, n) = 0.0; } } } // Do nothing else on first iteration if (itr_ == 0) return; // Update basis spanning differences of past field vectors updateBasis(fieldBasis_, fieldHists_); // Update basis spanning differences of past residual vectors updateBasis(resBasis_, resHists_); // Update nBasis_ nBasis_ = fieldBasis_.size(); UTIL_CHECK(fieldBasis_.size() == nBasis_); // Update the U matrix and v vector. updateU(U_, resBasis_, nBasis_); updateV(v_, resHists_[0], resBasis_, nBasis_); // Note: resHists_[0] is the current residual vector // Solve matrix equation problem to compute coefficients // that minmize the L2 norm of the residual vector. if (nBasis_ == 1) { // Solve explicitly for coefficient coeffs_[0] = v_[0] / U_(0,0); } else if (nBasis_ < maxHist_) { // Create temporary smaller version of U_, v_, coeffs_ . // This is done to avoid reallocating U_ with each iteration. DMatrix<double> tempU; DArray<double> tempv,tempcoeffs; tempU.allocate(nBasis_,nBasis_); tempv.allocate(nBasis_); tempcoeffs.allocate(nBasis_); for (int i = 0; i < nBasis_; ++i) { tempv[i] = v_[i]; for (int j = 0; j < nBasis_; ++j) { tempU(i,j) = U_(i,j); } } // Solve matrix equation LuSolver solver; solver.allocate(nBasis_); solver.computeLU(tempU); solver.solve(tempv,tempcoeffs); // Transfer solution to full-sized member variable for (int i = 0; i < nBasis_; ++i) { coeffs_[i] = tempcoeffs[i]; } } else if (nBasis_ == maxHist_) { LuSolver solver; solver.allocate(maxHist_); solver.computeLU(U_); solver.solve(v_, coeffs_); } return; } template <typename Iterator, typename T> void AmIteratorTmpl<Iterator,T>::updateGuess() { // Set field and residual trial vectors to current values setEqual(fieldTrial_, fieldHists_[0]); setEqual(resTrial_, resHists_[0]); // Add linear combinations of field and residual basis vectors if (nBasis_ > 0) { // Combine basis vectors into trial guess and predicted residual addHistories(fieldTrial_, fieldBasis_, coeffs_, nBasis_); addHistories(resTrial_, resBasis_, coeffs_, nBasis_); } // Correct for predicted error addPredictedError(fieldTrial_, resTrial_,lambda_); // Update system using new trial field update(fieldTrial_); return; } // Private virtual member functions /* * Initialize just before entry to iterative loop. * (virtual) */ template <typename Iterator, typename T> void AmIteratorTmpl<Iterator,T>::setup(bool isContinuation) { if (!isAllocatedAM()) { allocateAM(); } else { if (!isContinuation) { clear(); } } } /* * Compute L2 norm of a vector. */ template <typename Iterator, typename T> double AmIteratorTmpl<Iterator,T>::norm(T const & a) { double normSq = dotProduct(a, a); return sqrt(normSq); } // Update entire U matrix template <typename Iterator, typename T> void AmIteratorTmpl<Iterator, T> ::updateU(DMatrix<double> & U, RingBuffer<T> const & resBasis, int nHist) { // Update matrix U by shifting elements diagonally int maxHist = U.capacity1(); for (int m = maxHist-1; m > 0; --m) { for (int n = maxHist-1; n > 0; --n) { U(m,n) = U(m-1,n-1); } } // Compute U matrix's new row 0 and col 0 for (int m = 0; m < nHist; ++m) { double dotprod = dotProduct(resBasis[0],resBasis[m]); U(m,0) = dotprod; U(0,m) = dotprod; } } template <typename Iterator, typename T> void AmIteratorTmpl<Iterator, T>::updateV(DArray<double> & v, T const & resCurrent, RingBuffer<T> const & resBasis, int nHist) { for (int m = 0; m < nHist; ++m) { v[m] = dotProduct(resCurrent, resBasis[m]); } } template <typename Iterator, typename T> double AmIteratorTmpl<Iterator,T>::computeError(int verbose) { double error = 0.0; if (verbose > 1) { Log::file() << "\n"; // Find max residual vector element double maxRes = maxAbs(resHists_[0]); Log::file() << "Max Residual = " << Dbl(maxRes,15) << "\n"; // Find norm of residual vector double normRes = norm(resHists_[0]); Log::file() << "Residual Norm = " << Dbl(normRes,15) << "\n"; // Find root-mean-squared residual element value double rmsRes = normRes/sqrt(nElem_); Log::file() << "RMS Residual = " << Dbl(rmsRes,15) << "\n"; // Find norm of residual vector relative to field double normField = norm(fieldHists_[0]); double relNormRes = normRes/normField; Log::file() << "Relative Norm = " << Dbl(relNormRes,15) << std::endl; // Check if calculation has diverged (normRes will be NaN) UTIL_CHECK(!std::isnan(normRes)); // Set error value if (errorType_ == "maxResid") { error = maxRes; } else if (errorType_ == "normResid") { error = normRes; } else if (errorType_ == "rmsResid") { error = rmsRes; } else if (errorType_ == "relNormResid") { error = relNormRes; } else { UTIL_THROW("Invalid iterator error type in parameter file."); } } else { // Set error value if (errorType_ == "maxResid") { error = maxAbs(resHists_[0]); } else if (errorType_ == "normResid") { error = norm(resHists_[0]); } else if (errorType_ == "rmsResid") { error = norm(resHists_[0])/sqrt(nElem_); } else if (errorType_ == "relNormResid") { double normRes = norm(resHists_[0]); double normField = norm(fieldHists_[0]); error = normRes/normField; } else { UTIL_THROW("Invalid iterator error type in parameter file."); } //Log::file() << ", error = " << Dbl(error, 15) << "\n"; } return error; } } #endif
17,513
C++
.tpp
489
27.051125
78
0.560681
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,247
MeshIterator.tpp
dmorse_pscfpp/src/pscf/mesh/MeshIterator.tpp
#ifndef PSCF_MESH_ITERATOR_TPP #define PSCF_MESH_ITERATOR_TPP /* * 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 "MeshIterator.h" namespace Pscf { /* * Default constructor */ template <int D> MeshIterator<D>::MeshIterator() : dimensions_(0), position_(0), rank_(0), size_(0) {} /* * Constructor */ template <int D> MeshIterator<D>::MeshIterator(const IntVec<D>& dimensions) : dimensions_(0), position_(0), rank_(0), size_(0) { setDimensions(dimensions); } /* * Set the mesh dimensions. */ template <int D> void MeshIterator<D>::setDimensions(const IntVec<D>& dimensions) { for (int i = 0; i < D; ++i) { if (dimensions[i] <= 0) { UTIL_THROW("Mesh dimensions must be positive"); } } dimensions_ = dimensions; size_ = 1; for (int i = 0; i < D; ++i) { size_ *= dimensions_[i]; } } /* * Reset iterator to point to first element. */ template <int D> void MeshIterator<D>::begin() { rank_ = 0; for (int i = 0; i < D; ++i) { position_[i] = 0; } } /* * Increment this iterator to the next mesh point (default templ.). * * Note: Explicit instantiations are defined for D = 1, 2 and 3. * This default implementation should thus not normally be used. */ template <int D> inline void MeshIterator<D>::operator ++() { position_[D-1]++; if (position_[D-1] == dimensions_[D-1]) { position_[D-1] = 0; if (D > 1) { increment(D-2); } } rank_++; } /* * Recursive increment function (private). */ template <int D> inline void MeshIterator<D>::increment(int i) { position_[i]++; if (position_[i] == dimensions_[i]) { position_[i] = 0; if (i > 0) { increment(i-1); } } } } #endif
2,115
C++
.tpp
93
17.311828
69
0.557711
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,248
Mesh.tpp
dmorse_pscfpp/src/pscf/mesh/Mesh.tpp
#ifndef PSCF_MESH_TPP #define PSCF_MESH_TPP /* * 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 "Mesh.h" #include <util/global.h> namespace Pscf { using namespace Util; // Default constructor template <int D> Mesh<D>::Mesh() : dimensions_(0), offsets_(0), size_(0) {} // Copy constructor template <int D> Mesh<D>::Mesh(Mesh<D> const & other) : dimensions_(other.dimensions_), offsets_(other.offsets_), size_(other.size_) {} // Construct from dimensions template <int D> Mesh<D>::Mesh(IntVec<D> const & dimensions) : dimensions_(0), offsets_(0), size_(0) { setDimensions(dimensions); } // Assignment operator. template <int D> Mesh<D>& Mesh<D>::operator = (Mesh<D> const & other) { setDimensions(other.dimensions_); return *this; } // Set or reset the state of existing Mesh<D> template <int D> void Mesh<D>::setDimensions(IntVec<D> const & dimensions) { int i; for (i = 0; i < D; ++i) { if (dimensions[i] <= 0) { UTIL_THROW("Mesh dimensions must be positive"); } } dimensions_ = dimensions; offsets_[D -1] = 1; for (i = D - 1; i > 0; --i) { offsets_[i-1] = offsets_[i]*dimensions_[i]; } size_ = offsets_[0]*dimensions_[0]; } // Return rank of IntVec position template <int D> int Mesh<D>::rank(IntVec<D> const & position) const { int i; int result = 0; for (i = 0; i < D - 1; ++i) { assert(position[i] >= 0); assert(position[i] < dimensions_[i]); result += position[i]*offsets_[i]; } assert(position[i] >= 0); assert(position[i] < dimensions_[i]); result += position[i]; return result; } // Return IntVec vector corresponding to rank id template <int D> IntVec<D> Mesh<D>::position(int id) const { IntVec<D> position; int remainder = id; int i; for (i = 0; i < D - 1; ++i) { position[i] = remainder/offsets_[i]; remainder -= position[i]*offsets_[i]; } position[i] = remainder; return position; } // Is a single coordinate in the primary range? template <int D> bool Mesh<D>::isInMesh(int coordinate, int i) const { bool result = true; if (coordinate < 0) result = false; if (coordinate >= dimensions_[i]) result = false; return result; } // Is IntVec<D> argument in the primary cell of this mesh? template <int D> bool Mesh<D>::isInMesh(IntVec<D> const & position) const { bool result = true; for (int i = 0; i < D; ++i) { if (position[i] < 0) result = false; if (position[i] >= dimensions_[i]) result = false; } return result; } // Shift a single coordinate to the primary range template <int D> int Mesh<D>::shift(int& coordinate, int i) const { int shift; if (coordinate >= 0) { shift = coordinate/dimensions_[i]; } else { shift = -1 + ((coordinate+1)/dimensions_[i]); } coordinate -= shift*dimensions_[i]; return shift; } // Shift the vector to the primary cell template <int D> IntVec<D> Mesh<D>::shift(IntVec<D>& position) const { IntVec<D> shifts; for (int i = 0; i < D; ++i) { shifts[i] = shift(position[i], i); } return shifts; } } #endif
3,658
C++
.tpp
137
20.905109
67
0.572937
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,249
SweepTmpl.tpp
dmorse_pscfpp/src/pscf/sweep/SweepTmpl.tpp
#ifndef PSCF_SWEEP_TMPL_TPP #define PSCF_SWEEP_TMPL_TPP /* * 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 "SweepTmpl.h" #include <util/misc/Log.h> namespace Pscf { using namespace Util; /* * Constructor */ template <class State> SweepTmpl<State>::SweepTmpl(int historyCapacity) : ns_(0), baseFileName_(), historyCapacity_(historyCapacity), historySize_(0), nAccept_(0), reuseState_(true) { setClassName("SweepTmpl"); } /* * Destructor. */ template <class State> SweepTmpl<State>::~SweepTmpl() {} /* * Read parameters. */ template <class State> void SweepTmpl<State>::readParameters(std::istream& in) { // Default values baseFileName_ = ""; // Read parameters read<int>(in, "ns", ns_); readOptional<std::string>(in, "baseFileName", baseFileName_); readOptional<int>(in, "historyCapacity", historyCapacity_); readOptional<bool>(in, "reuseState", reuseState_); // Allocate required arrays UTIL_CHECK(historyCapacity_ > 0); states_.allocate(historyCapacity_); stateHistory_.allocate(historyCapacity_); sHistory_.allocate(historyCapacity_); c_.allocate(historyCapacity_); } template <class State> void SweepTmpl<State>::sweep() { // Compute and output ds double ds = 1.0/double(ns_); double ds0 = ds; Log::file() << std::endl; Log::file() << "ns = " << ns_ << std::endl; Log::file() << "ds = " << ds << std::endl; // Initial setup, before a sweep setup(); // Solve for initial state of sweep double sNew = 0.0; Log::file() << std::endl; Log::file() << "===========================================\n"; Log::file() << "Attempt s = " << sNew << std::endl; int error; bool isContinuation = false; // False on first step error = solve(isContinuation); if (error) { UTIL_THROW("Failure to converge initial state of sweep"); } else { accept(sNew); } // Loop over states on path bool finished = false; // Are we finished with the loop? while (!finished) { // Loop over iteration attempts, with decreasing ds as needed error = 1; while (error) { // Set a new contour variable value sNew sNew = s(0) + ds; Log::file() << std::endl; Log::file() << "===========================================\n"; Log::file() << "Attempt s = " << sNew << std::endl; // Set non-adjustable system parameters to new values setParameters(sNew); // Guess new state variables by polynomial extrapolation. // This function must both compute the extrapolation and // set initial guess values in the parent system. extrapolate(sNew); // Attempt iterative SCFT solution isContinuation = reuseState_; error = solve(isContinuation); // Process success or failure if (error) { Log::file() << "Backtrack and halve sweep step size:" << std::endl; // Upon failure, reset state to last converged solution reset(); // Decrease ds by half ds *= 0.50; if (ds < 0.1*ds0) { UTIL_THROW("Sweep decreased ds too many times."); } } else { // Upon successful convergence, update history and nAccept accept(sNew); } } if (sNew + ds > 1.0000001) { finished = true; } } Log::file() << "===========================================\n"; // Clean up after end of the entire sweep cleanup(); } /* * Initialize history variables (must be called by setup function). */ template <class State> void SweepTmpl<State>::initialize() { UTIL_CHECK(historyCapacity_ > 1); UTIL_CHECK(states_.capacity() == historyCapacity_); UTIL_CHECK(sHistory_.capacity() == historyCapacity_); UTIL_CHECK(stateHistory_.capacity() == historyCapacity_); // Check allocation of all states, allocate if necessary for (int i = 0; i < historyCapacity_; ++i) { checkAllocation(states_[i]); } // Set pointers in stateHistory_ to refer to objects in array states_ nAccept_ = 0; historySize_ = 0; for (int i = 0; i < historyCapacity_; ++i) { sHistory_[i] = 0.0; stateHistory_[i] = &states_[i]; } } template <class State> void SweepTmpl<State>::accept(double sNew) { // Shift elements of sHistory_ for (int i = historyCapacity_ - 1; i > 0; --i) { sHistory_[i] = sHistory_[i-1]; } sHistory_[0] = sNew; // Shift elements of stateHistory_ (pointers to stored solutions) State* temp; temp = stateHistory_[historyCapacity_-1]; for (int i = historyCapacity_ - 1; i > 0; --i) { stateHistory_[i] = stateHistory_[i-1]; } stateHistory_[0] = temp; // Update counters nAccept_ and historySize_ ++nAccept_; if (historySize_ < historyCapacity_) { ++historySize_; } // Call getSolution to copy system state to state(0). getSolution(); } /* * Use Lagrange polynomials to compute coefficients for continuation. */ template <class State> void SweepTmpl<State>::setCoefficients(double sNew) { UTIL_CHECK(historySize_ <= historyCapacity_); if (historySize_ == 1) { c_[0] = 1.0; } else { double num, den; int i, j; for (i = 0; i < historySize_; ++i) { num = 1.0; den = 1.0; for (j = 0; j < historySize_; ++j) { if (j != i) { num *= (sNew - s(j)); den *= (s(i) - s(j)); } } c_[i] = num/den; } } // Theory: The coefficient c_[i] is a Lagrange polynomial // function c_[i](sNew) of sNew that is defined such that // c_[i](s(i)) = 1 and c_[i](s(j)) = 0 for any j != i. // Given a set of values y(i) previously obtained at contour // variable values s(i) for all 0 <= i < historySize_, a // linear combination f(sNew) = \sum_i c_[i](sNew)*y(i) summed // over i = 0, ..., historySize_ - 1 gives a polynomial in // sNew that passes through all previous values, such that // f(sNew) = y(i) for sNew = s(i). } /* * Clean up after the end of a sweep (empty default implementation). */ template <class State> void SweepTmpl<State>::cleanup() {} } // namespace Pscf #endif
7,000
C++
.tpp
205
26.24878
75
0.551934
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,250
SpaceSymmetry.tpp
dmorse_pscfpp/src/pscf/crystal/SpaceSymmetry.tpp
#ifndef PSCF_SPACE_SYMMETRY_TPP #define PSCF_SPACE_SYMMETRY_TPP /* * 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 "SpaceSymmetry.h" namespace Pscf { using namespace Util; /* * Default constructor. */ template <int D> SpaceSymmetry<D>::SpaceSymmetry() : R_(), t_() { int i, j; for (i = 0; i < D; ++i) { t_[i] = 0; for (j = 0; j < D; ++j) { if (i == j) { R_(i, j) = 1; } else { R_(i, j) = 0; } } } } /* * Copy constructor. */ template <int D> SpaceSymmetry<D>::SpaceSymmetry(const SpaceSymmetry<D>& other) { int i, j; for (i = 0; i < D; ++i) { t_[i] = other.t_[i]; for (j = 0; j < D; ++j) { R_(i, j) = other.R_(i,j); } } normalize(); } /* * Assignment operator. */ template <int D> SpaceSymmetry<D>& SpaceSymmetry<D>::operator = (const SpaceSymmetry<D>& other) { if (this != &other) { int i, j; for (i = 0; i < D; ++i) { t_[i] = other.t_[i]; for (j = 0; j < D; ++j) { R_(i, j) = other.R_(i,j); } } } normalize(); return *this; } /* * Shift translation to lie in range [0,1). */ template <int D> void SpaceSymmetry<D>::normalize() { for (int i = 0; i < D; ++i) { int num = t_[i].num(); int den = t_[i].den(); UTIL_ASSERT(den > 0); if (den == 1) { num = 0; } else { while (num < 0) { num += den; } while (num >= den) { num -= den; } } if (num != t_[i].num()) { t_[i] = Rational(num, den); } } } /* * Make identity (private static method). */ template <int D> void SpaceSymmetry<D>::makeIdentity() { int i, j; for (i = 0; i < D; ++i) { identity_.t_[i] = 0; for (j = 0; j < D; ++j) { if (i == j) { identity_.R_(i, j) = 1; } else { identity_.R_(i, j) = 0; } } } } /* * Return inverse of this SpaceSymmetry<D>. */ template <int D> SpaceSymmetry<D> SpaceSymmetry<D>::inverse() const { SpaceSymmetry<D> C; // Compute inverse of rotation matrix C.R_ = inverseRotation(); // Compute translation -R^{-1}t int i, j; for (i = 0; i < D; ++i) { C.t_[i] = 0; for (j = 0; j < D; ++j) { C.t_[i] -= C.R_(i, j)*t_[j]; } } C.normalize(); //UTIL_CHECK(C.determinant()*determinant() == 1); return C; } /* * Shift the origin of the coordinate system. */ template <int D> void SpaceSymmetry<D>::shiftOrigin( SpaceSymmetry<D>::Translation const & origin) { int i, j; for (i = 0; i < D; ++i) { t_[i] -= origin[i]; for (j = 0; j < D; ++j) { t_[i] += R_(i,j)*origin[j]; } } normalize(); } } #endif
3,360
C++
.tpp
148
15.304054
72
0.431164
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,251
UnitCell.tpp
dmorse_pscfpp/src/pscf/crystal/UnitCell.tpp
#ifndef PSCF_UNIT_CELL_TPP #define PSCF_UNIT_CELL_TPP /* * 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 "UnitCell.h" #include <util/format/Dbl.h> #include <util/format/Int.h> #include <iomanip> namespace Pscf { using namespace Util; template <int D> std::istream& operator >> (std::istream& in, UnitCell<D>& cell) { cell.isInitialized_ = false; in >> cell.lattice_; cell.setNParameter(); for (int i = 0; i < cell.nParameter_; ++i) { in >> cell.parameters_[i]; } cell.setLattice(); return in; } template <int D> std::ostream& operator << (std::ostream& out, UnitCell<D> const & cell) { out << cell.lattice_; for (int i = 0; i < cell.nParameter_; ++i) { out << Dbl(cell.parameters_[i], 18, 10); } return out; } /* * Serialize to/from an archive. */ template <class Archive, int D> void serialize(Archive& ar, UnitCell<D>& cell, const unsigned int version) { serializeEnum(ar, cell.lattice_, version); ar & cell.nParameter_; for (int i = 0; i < cell.nParameter_; ++i) { ar & cell.parameters_[i]; } } template <int D> void readUnitCellHeader(std::istream& in, UnitCell<D>& cell) { cell.isInitialized_ = false; std::string label; in >> label; UTIL_CHECK(label == "crystal_system"); if (cell.lattice_ == UnitCell<D>::LatticeSystem::Null) { in >> cell.lattice_; cell.setNParameter(); } else { typename UnitCell<D>::LatticeSystem lattice; in >> lattice; UTIL_CHECK(lattice == cell.lattice_); } in >> label; UTIL_CHECK(label == "N_cell_param"); int nParameter; in >> nParameter; UTIL_CHECK(nParameter == cell.nParameter_); in >> label; UTIL_CHECK(label == "cell_param"); for (int i = 0; i < cell.nParameter_; ++i) { in >> std::setprecision(15) >> cell.parameters_[i]; } cell.setLattice(); } template <int D> void writeUnitCellHeader(std::ostream& out, UnitCell<D> const& cell) { out << "crystal_system" << std::endl << " " << cell.lattice_<< std::endl; out << "N_cell_param" << std::endl << " " << cell.nParameter_<< std::endl; out << "cell_param " << std::endl; for (int i = 0; i < cell.nParameter_; ++i) { out << " " << Dbl(cell.parameters_[i], 18, 10); } out << std::endl; } /* * Read common part of field header (fortran PSCF format). */ template <int D> void readFieldHeader(std::istream& in, int& ver1, int& ver2, UnitCell<D>& cell, std::string& groupName, int& nMonomer) { std::string label; in >> label; UTIL_CHECK(label == "format"); in >> ver1 >> ver2; in >> label; UTIL_CHECK(label == "dim"); int dim; in >> dim; UTIL_CHECK(dim == D); readUnitCellHeader(in, cell); in >> label; UTIL_CHECK(label == "group_name"); in >> groupName; in >> label; UTIL_CHECK(label == "N_monomer"); in >> nMonomer; UTIL_CHECK(nMonomer > 0); } /* * Write common part of field header (fortran PSCF format). */ template <int D> void writeFieldHeader(std::ostream &out, int ver1, int ver2, UnitCell<D> const & cell, std::string const & groupName, int nMonomer) { out << "format " << Int(ver1,3) << " " << Int(ver2,3) << std::endl; out << "dim" << std::endl << " " << D << std::endl; writeUnitCellHeader(out, cell); out << "group_name" << std::endl << " " << groupName << std::endl; out << "N_monomer" << std::endl << " " << nMonomer << std::endl; } } #endif
4,271
C++
.tpp
140
22.907143
74
0.522744
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,252
SymmetryGroup.tpp
dmorse_pscfpp/src/pscf/crystal/SymmetryGroup.tpp
#ifndef PSCF_SYMMETRY_GROUP_TPP #define PSCF_SYMMETRY_GROUP_TPP /* * 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 "SymmetryGroup.h" #include <util/global.h> namespace Pscf { using namespace Util; // Member function definitions (non-inline) /* * Default constructor */ template <class Symmetry> SymmetryGroup<Symmetry>::SymmetryGroup() { identity_ = Symmetry::identity(); elements_.push_back(identity_); } /* * Copy constructor */ template <class Symmetry> SymmetryGroup<Symmetry>::SymmetryGroup(const SymmetryGroup& other) { elements_.clear(); identity_ = other.identity(); for (int i = 0; i < other.size(); ++i) { elements_.push_back(other.elements_[i]); } } /* * Destructor */ template <class Symmetry> SymmetryGroup<Symmetry>::~SymmetryGroup() {} /* * Assignment operator. */ template <class Symmetry> SymmetryGroup<Symmetry>& SymmetryGroup<Symmetry>::operator = (const SymmetryGroup& other) { if (this != &other) { identity_ = other.identity(); elements_.clear(); for (int i = 0; i < other.size(); ++i) { elements_.push_back(other.elements_[i]); } } return *this; } /* * Find an element in the group, return const pointer to its address. * * Return a null pointer if symmetry is not a member of the group. */ template <class Symmetry> Symmetry const * SymmetryGroup<Symmetry>::find(Symmetry const& symmetry) const { for (int i=0; i < size(); ++i) { if (symmetry == elements_[i]) { return &(elements_[i]); } } // Return null pointer if not found return 0; } /* * Add a new element to the group. */ template <class Symmetry> bool SymmetryGroup<Symmetry>::add(Symmetry& symmetry) { // Check if symmetry is already present const Symmetry* ptr = find(symmetry); // If not already present, add symmetry to this group bool added; if (ptr == 0) { elements_.push_back(symmetry); added = true; } else { added = false; } return added; } /* * Create a complete group. */ template <class Symmetry> void SymmetryGroup<Symmetry>::makeCompleteGroup() { Symmetry a, b, c; int i, j, n; bool added, complete; // Add all inverses n = size(); for (i = 0; i < n; ++i) { a = elements_[i].inverse(); add(a); } // Add all products of existing elements, and their inverses complete = false; while (!complete) { complete = true; n = size(); for (i = 0; i < n; ++i) { a = elements_[i]; for (j = 0; j < n; ++j) { b = elements_[j]; c = a*b; added = add(c); if (added) { complete = false; } b = c.inverse(); added = add(b); if (added) { complete = false; } } } } } /* * Clear all elements except the identity. */ template <class Symmetry> void SymmetryGroup<Symmetry>::clear() { elements_.clear(); identity_ = Symmetry::identity(); elements_.push_back(identity_); } /* * Determine if two space groups are equivalent. */ template <class Symmetry> bool SymmetryGroup<Symmetry>::operator == (SymmetryGroup<Symmetry> const & other) const { if (size() != other.size()) { return false; } else { Symmetry const * ptr = 0; for (int i = 0; i < size(); ++i) { ptr = other.find(elements_[i]); if (ptr == 0) return false; } for (int i = 0; i < other.size(); ++i) { ptr = find(other.elements_[i]); if (ptr == 0) return false; } } return true; } /* * Determine if two space groups are inequivalent. */ template <class Symmetry> bool SymmetryGroup<Symmetry>::operator != (SymmetryGroup<Symmetry> const & other) const { return !(*this == other); } /* * Check validity of this group. */ template <class Symmetry> bool SymmetryGroup<Symmetry>::isValid() const { Symmetry a, b, c; int i, j, n; // Check for inclusion of identity element c = Symmetry::identity(); if (find(c) == 0) { UTIL_THROW("Identity element is not in group"); } // Check inverses, uniqueness, and completeness n = size(); for (i = 0; i < n; ++i) { a = elements_[i]; c = a.inverse(); if (find(c) == 0) { UTIL_THROW("Inverse of element not in group"); } for (j = 0; j < n; ++j) { b = elements_[j]; if (i != j) { if (a == b) { UTIL_THROW("An element of the group is not unique"); } } c = a*b; if (find(c) == 0) { UTIL_THROW("Product of two element is not in group"); } } } // If no Exceptions have been thrown, return true return true; } } #endif
5,592
C++
.tpp
210
19.228571
76
0.532213
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,253
Basis.tpp
dmorse_pscfpp/src/pscf/crystal/Basis.tpp
#ifndef PSCF_BASIS_TPP #define PSCF_BASIS_TPP /* * 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 "Basis.h" #include "TWave.h" #include "groupFile.h" #include <pscf/crystal/UnitCell.h> #include <pscf/crystal/SpaceGroup.h> #include <pscf/crystal/shiftToMinimum.h> #include <pscf/mesh/Mesh.h> #include <pscf/mesh/MeshIterator.h> #include <algorithm> #include <vector> #include <set> #include <fstream> namespace Pscf { /* * Constructor. */ template <int D> Basis<D>::Basis() : waves_(), stars_(), waveIds_(), starIds_(), nWave_(0), nBasisWave_(0), nStar_(0), nBasis_(0), unitCellPtr_(0), meshPtr_(0), isInitialized_(false) {} /* * Destructor. */ template <int D> Basis<D>::~Basis() {} /* * Construct basis for pseudo-spectral scft. */ template <int D> void Basis<D>::makeBasis(Mesh<D> const & mesh, UnitCell<D> const & unitCell, std::string groupName) { SpaceGroup<D> group; readGroup(groupName, group); makeBasis(mesh, unitCell, group); } /* * Construct a symmetry-adapted basis for pseudo-spectral scft. */ template <int D> void Basis<D>::makeBasis(Mesh<D> const & mesh, UnitCell<D> const & unitCell, SpaceGroup<D> const & group) { // Precondition: Check compatibility of mesh with space group group.checkMeshDimensions(mesh.dimensions()); // Save pointers to mesh and unit cell meshPtr_ = &mesh; unitCellPtr_ = &unitCell; // Allocate arrays nWave_ = mesh.size(); waves_.allocate(nWave_); waveIds_.allocate(nWave_); // Make sorted array of waves makeWaves(); // Identify stars of waves that are related by symmetry makeStars(group); // Apply validity test suite bool valid = isValid(); if (!valid) { UTIL_THROW("Basis failed validity check"); } isInitialized_ = true; } /* * Construct ordered list of waves. * * On exit: * - Array waves_ contains list of waves ordered by sqNorm. * - Each wave has indicesDft, indicesBz and sqNorm set. * - Array stars_ is still empty. */ template <int D> void Basis<D>::makeWaves() { IntVec<D> meshDimensions = mesh().dimensions(); std::vector< TWave<D> > twaves; twaves.reserve(nWave_); // Loop over dft mesh to generate all waves, add to twaves TWave<D> w; IntVec<D> v; MeshIterator<D> itr(mesh().dimensions()); for (itr.begin(); !itr.atEnd(); ++itr) { w.indicesDft = itr.position(); v = shiftToMinimum(w.indicesDft, meshDimensions, *unitCellPtr_); w.indicesBz = v; w.sqNorm = unitCell().ksq(v); twaves.push_back(w); } // Sort temporary array twaves TWaveNormComp<D> comp; std::sort(twaves.begin(), twaves.end(), comp); // Copy temporary array twaves into member variable waves_ for (int i = 0; i < nWave_; ++i) { waves_[i].sqNorm = twaves[i].sqNorm; waves_[i].indicesDft = twaves[i].indicesDft; waves_[i].indicesBz = twaves[i].indicesBz; } } /* * Complete construction of a basis by grouping presorted waves into * stars and completing initialization of all Wave and Star objects. */ template <int D> void Basis<D>::makeStars(SpaceGroup<D> const & group) { /* * Conceptual definitions: * - A "list" is a set of wavevectors of equal magnitude. * - A "star" is a set of wavevectors that are related by symmetry. * Each list may contain one or more complete stars. Lists are * identified as an intermediate step in identification of stars. * * Local wavevector containers: * During processing, wavevectors are temporarily stored in * TWave<D> objects. The following local containers of TWave<D> * objects used: * list - a std::set of waves of equal norm (a "list") * tempList - an ordered list, with contiguous stars * star - a std::set of symmetry-related waves (a "star") * tempStar - a sorted star, sorted by descending indicesBz */ // Local TWave<D> containers and associated iterators std::set< TWave<D>, TWaveDftComp<D> > list; std::set< TWave<D>, TWaveDftComp<D> > star; std::vector< TWave<D> > tempStar; GArray< TWave<D> > tempList; typename std::set< TWave<D>, TWaveDftComp<D> >::iterator rootItr; typename std::set< TWave<D>, TWaveDftComp<D> >::iterator setItr; // Local variables TWave<D> wave; Basis<D>::Star newStar; std::complex<double> coeff; double Gsq; double Gsq_max; double phase_diff; const double twoPi = 2.0*Constants::Pi; const double epsilon = 1.0E-8; IntVec<D> meshDimensions = mesh().dimensions(); IntVec<D> rootVecBz; // BZ indices for root of this star IntVec<D> vec; // Indices of temporary wavevector IntVec<D> nVec; // Indices of negation of a wavevector int listId = 0; // id for this list int listBegin = 0; // id of first wave in this list int listEnd = 0; // (id of last wave in this list) + 1 int listSize; // listEnd - listBegin int starId = 0; // id for this star int starBegin = 0; // id of first wave in this star int i, j, k; bool cancel; /* * Overview of algorithm: * * Precondition: Wavevectors in the array waves_ are sorted in * nondecreasing order by wavevector norm. * * Loop over index i of array waves_ { * * Search for end of a "list" (i.e., contiguous block of waves * of equal magnitude) by identifying changes in magnitude. * The resulting list has indices [listBegin,listEnd-1]. * Set newList true. * * // Each list may contain one or more stars. * // Process the newly identified list to identify stars * If (newList) { * * Copy all waves in the range into std::set list * * Set rootItr to the first wave in list * * // Loop over stars within the list * while (list.size() > 0) { * * // To generate a star from a root wave rootItr, * // loop over symmetry operations of space group. * For each symmetry operation group[j] { * Compute vec = (rootItr->indicesBz)*group[j] * Set phase = rootItr->indicesBz .dot. (group[j].t) * Check for cancellation of the star, set "cancel" flag * Add wave to std::set<TWave> star if not added before * // Here, use of a std::set simplifies test of uniqueness * } * * Copy all waves from star to std::vector<TWave> tempStar * Sort tempStar by indicesBz, in descending order * // Here, use of a std::vector for tempStar allows sorting * For each wave in tempStar { * Append the wave to std::vector<TWave> tempList * Erase the wave from std::set<TWave> list * // Here, use of a std::set for list simplifies erasure * } * * Initialize a Star object named newStar, assign values * to members beginId, endId, size, cancel * * // Assign values of newStar.invertFlag, rootItr, nextInvert * if (nextInvert == -1) { * // This is the second star in pair * newStar.invertFlag = -1; * nextInvert = 1; * Set rootItr to the first wave in remaining list * } else { * Search for negation of rootItr in this star * if negation is in this star { * newStar.invertFlag = 0 * nextInvert = 1; * Set rootItr to the first wave in remaining list * } else * Search for negation of rootItr in this remaining list * if the negation is in the remaining list { * newStar.invertFlag = 1 * nextInvert = -1; * set rootItr to negation of current root * } * } * * Append newStar object to GArray<Star> stars_ * * } // end loop over stars in a single list * * // At this point, tempList contains the contents of the * // waves_ array occupying the range [beginId, endId-1], * // grouped by stars, with waves within each star sorted * // by indexBz. * * // Overwrite the block of array waves_ with indices in the * // range [beginId, endId-1] with the contents of tempList. * For each wave in tempList { * Copy a TWave in tempList to a Basis:Wave in waves_ * Assign a complex coefficient of unit norm to the Wave * } * * // At this point, coefficients of waves have unit magnitude * // and correct relative phases within each star, but not * // the final absolute phases or magnitude. * * } // end processing of one list (waves of equal norm) * * } // End initial processing of all waves and stars * * // Set phases of wave coefficients * For each star in array stars_ { * if star is closed under inversion (star.invertFlag == 0) { * if star is cancelled { * set coefficients of all waves to zero * } else { * Set the root to the first wave in the star * Check closure (i.e., negation of root is in this star) * For each wave in star: * Divide coeff by the root coefficient * } * if (coeffs of root & negation are not complex conjugates){ * Divide all coeffs by a common phasor chosen to obtain * complex conjugate coefficients for root and partner * } * } * } else * if (star.invertFlag == 1) { * Set root of this star to the 1st wave in the star * Find negation of root (aka "partner") in the next star * If this star is cancelled { * Set coefficients in this star and next to zero * } else { * For each wave in this star: * Divide coeff by the root coefficient * } * For each wave in the next star: * Divide coeff by the partner coefficient * } * } * } * // Note: If star.invertFlag = -1, do nothing because properties * // of this star were all set when processing its partner. * } * * // For all waves, normalize coefficients and set starId * For each star in array stars_ { * For each wave in this star { * Set Wave.starId * Divide coefficient by sqrt(double(star.size)) * } * } * * // For all waves, set implicit member and add to look up table * For each wave in array waves_ { * Set Wave::implicit attribute * Assign waveIds_[rank] = i * } */ // Loop over all waves nBasis_ = 0; nBasisWave_ = 0; Gsq_max = waves_[0].sqNorm; for (i = 1; i <= nWave_; ++i) { // Determine if this wave begins a new list bool newList = false; if (i == nWave_) { listEnd = i; listSize = listEnd - listBegin; newList = true; } else { Gsq = waves_[i].sqNorm; if (Gsq > Gsq_max + epsilon) { Gsq_max = Gsq; listEnd = i; listSize = listEnd - listBegin; newList = true; } } // Process completed list of wavectors of equal norm if (newList) { // Copy waves of equal norm into std::set "list" list.clear(); tempList.clear(); for (j = listBegin; j < listEnd; ++j) { wave.indicesDft = waves_[j].indicesDft; wave.indicesBz = waves_[j].indicesBz; wave.sqNorm = waves_[j].sqNorm; if (j > listBegin) { UTIL_CHECK( std::abs(wave.sqNorm-waves_[j].sqNorm) < 2.0*epsilon ); } list.insert(wave); } // On entry to each iteration of the loop over stars, // rootItr and nextInvert are known. The iterator rootItr // points to the wave in the remaining list that will be // used as the root of the next star. The flag nextInvert // is equal to -1 iff the previous star was the first of // a pair that are open under inversion, and is equal // to + 1 otherwise. // Initial values for first star in this list rootItr = list.begin(); int nextInvert = 1; // Loop over stars with a list of waves of equal norm, // removing each star from the list as it is identified. // The root of the next star must have been chosen on // entry to each iteration of this loop. while (list.size() > 0) { rootVecBz = rootItr->indicesBz; Gsq = rootItr->sqNorm; cancel = false; star.clear(); // Construct a star from root vector, by applying every // symmetry operation in the group to the root wavevector. for (j = 0; j < group.size(); ++j) { // Apply symmetry (i.e., multiply by rotation matrix) // vec = rotated wavevector. vec = rootVecBz*group[j]; // Check that rotated vector has same norm as root. UTIL_CHECK(std::abs(Gsq - unitCell().ksq(vec)) < epsilon); // Initialize TWave object associated with rotated wave wave.sqNorm = Gsq; wave.indicesBz = shiftToMinimum(vec, meshDimensions, *unitCellPtr_); wave.indicesDft = vec; mesh().shift(wave.indicesDft); // Compute phase for coeff. of wave in basis function. // Convention -pi < phase <= pi. wave.phase = 0.0; for (k = 0; k < D; ++k) { wave.phase += rootVecBz[k]*(group[j].t(k)); } while (wave.phase > 0.5) { wave.phase -= 1.0; } while (wave.phase <= -0.5) { wave.phase += 1.0; } wave.phase *= twoPi; // Check for cancellation of star: The star is // cancelled if application of any symmetry operation // in the group to the root vector yields a rotated // vector equivalent to the root vector but with a // nonzero phase, creating a contradiction. if (wave.indicesDft == rootItr->indicesDft) { if (std::abs(wave.phase) > 1.0E-6) { cancel = true; } } // Search for an equivalent wave already in the star. // Note: Equivalent waves have equal DFT indices. setItr = star.find(wave); if (setItr == star.end()) { // If no equivalent wave is found in the star, // then add this wave to the star star.insert(wave); } else { // If an equivalent wave is found, check if the // phases are equivalent. If not, the star is // cancelled. phase_diff = setItr->phase - wave.phase; while (phase_diff > 0.5) { phase_diff -= 1.0; } while (phase_diff <= -0.5) { phase_diff += 1.0; } if (std::abs(phase_diff) > 1.0E-6) { cancel = true; } } } // Copy all waves from set star to std::vector tempStar tempStar.clear(); setItr = star.begin(); for ( ; setItr != star.end(); ++setItr) { tempStar.push_back(*setItr); } // Sort tempStar, in descending order by indicesBz. TWaveBzComp<D> waveBzComp; std::sort(tempStar.begin(), tempStar.end(), waveBzComp); // Append contents of tempStar to tempList, erase from list int tempStarSize = tempStar.size(); for (j = 0; j < tempStarSize; ++j) { list.erase(tempStar[j]); tempList.append(tempStar[j]); } UTIL_CHECK((int)(tempList.size()+list.size()) == listSize); // If this star is not cancelled, increment the number of // basis functions (nBasis_) & waves in basis (nBasisWave_) if (!cancel) { ++nBasis_; nBasisWave_ += star.size(); } // Initialize a Star object // newStar.eigen = Gsq; newStar.beginId = starBegin; newStar.endId = newStar.beginId + star.size(); newStar.size = star.size(); newStar.cancel = cancel; // Note: newStar.starInvert is not yet known // Determine invertFlag, rootItr and nextInvert if (nextInvert == -1) { // If this star is 2nd of a pair related by inversion, // set root for next star to 1st wave of remaining list. newStar.invertFlag = -1; rootItr = list.begin(); nextInvert = 1; } else { // If this star is not the 2nd of a pair of partners, // then determine if it is closed under inversion. // Compute negation nVec of root vector in FBZ nVec.negate(rootVecBz); // Shift negation nVec to the DFT mesh (*meshPtr_).shift(nVec); // Search for negation of root vector within this star bool negationFound = false; setItr = star.begin(); for ( ; setItr != star.end(); ++setItr) { if (nVec == setItr->indicesDft) { negationFound = true; break; } } if (negationFound) { // If this star is closed under inversion, the root // of next star is the 1st vector of remaining list. newStar.invertFlag = 0; rootItr = list.begin(); nextInvert = 1; } else { // This star is open under inversion, and is the // first star of a pair related by inversion newStar.invertFlag = 1; nextInvert = -1; // Find negation of the root of this star in the // remaining list, and use this negation as the // root of the next star. setItr = list.begin(); for ( ; setItr != list.end(); ++setItr) { if (nVec == setItr->indicesDft) { negationFound = true; rootItr = setItr; break; } } // If negationFound, then rootItr->indicesDft = nVec // Failure to find the negation here is an error: // It must be either in this star or remaining list if (!negationFound) { std::cout << "Negation not found for: " << "\n"; std::cout << " vec (ft):" << rootItr->indicesDft <<"\n"; std::cout << " vec (bz):" << rootItr->indicesBz <<"\n"; std::cout << "-vec (dft):" << nVec << "\n"; UTIL_CHECK(negationFound); } } } stars_.append(newStar); ++starId; starBegin = newStar.endId; } // End loop over stars within a list. UTIL_CHECK(list.size() == 0); UTIL_CHECK(tempList.size() == listEnd - listBegin); // Copy tempList into corresponding section of waves_, // overwriting the section of waves_ used to create the list. // Compute a complex coefficient of unit norm for each wave. for (j = 0; j < tempList.size(); ++j) { k = j + listBegin; waves_[k].indicesDft = tempList[j].indicesDft; waves_[k].indicesBz = tempList[j].indicesBz; waves_[k].sqNorm = tempList[j].sqNorm; coeff = std::complex<double>(0.0, tempList[j].phase); coeff = exp(coeff); if (std::abs(imag(coeff)) < 1.0E-6) { coeff = std::complex<double>(real(coeff), 0.0); } if (std::abs(real(coeff)) < 1.0E-6) { coeff = std::complex<double>(0.0, imag(coeff)); } waves_[k].coeff = coeff; } // Processing of list is now complete. // Here, waves_[k].coeff has unit absolute magnitude, and // correct relative phases for waves within a star, but // the coeff may not be unity for the first or last wave in // the star. ++listId; listBegin = listEnd; } // Finished processing a list of waves of equal norm } // End loop over all waves nStar_ = stars_.size(); // Complete initial processing of all lists and stars /* * Conventions for phases of wave coefficients (imposed below): * - Coefficients of the root of each star and its negation must * be complex conjugates. * - In a closed star (starInvert = 0), the coefficient of the * root must have a non-negative real part. If the root * coefficient is pure imaginary, the imaginary part must * be negative. * - In a pair of open stars that are related by inversion * symmetry, the coefficients of the first wave of the first star * and the last wave of the second star (i.e., the roots of both * stars) must have real coefficients. */ // Final processing of phases of of waves in stars: std::complex<double> rootCoeff; // Coefficient of root wave std::complex<double> partCoeff; // Coefficient of partner of root std::complex<double> d; int rootId, partId; for (i = 0; i < nStar_; ++i) { // Treat open and closed stars differently if (stars_[i].invertFlag == 0) { // Identify root of this star (star i) // Set the root to be the first wave in the star rootId = stars_[i].beginId; stars_[i].waveBz = waves_[rootId].indicesBz; if (stars_[i].cancel) { // If the star is cancelled, set all coefficients to zero std::complex<double> czero(0.0, 0.0); for (j = stars_[i].beginId; j < stars_[i].endId; ++j) { waves_[j].coeff = czero; } } else { // if not cancelled // Compute nVec = negation of root, shifted to DFT mesh nVec.negate(waves_[rootId].indicesBz); (*meshPtr_).shift(nVec); // Find negation of root in this star, set partId to index bool negationFound = false; for (j = stars_[i].beginId; j < stars_[i].endId; ++j) { if (nVec == waves_[j].indicesDft) { partId = j; negationFound = true; break; } } // For invertFlag == 0, failure to find nVec in this // star is a fatal error UTIL_CHECK(negationFound); // Divide all coefficients by the root coefficient rootCoeff = waves_[rootId].coeff; for (j = stars_[i].beginId; j < stars_[i].endId; ++j) { waves_[j].coeff /= rootCoeff; } rootCoeff = waves_[rootId].coeff; UTIL_CHECK(std::abs(real(rootCoeff) - 1.0) < 1.0E-9); UTIL_CHECK(std::abs(imag(rootCoeff)) < 1.0E-9); // Require coefficients of root and negation are conjugates if (partId != rootId) { partCoeff = waves_[partId].coeff; UTIL_CHECK(std::abs(std::abs(partCoeff) - 1.0) < 1.0E-9); if (std::abs(partCoeff - rootCoeff) > 1.0E-6) { d = sqrt(partCoeff); if (real(d) < -1.0E-4) { d = -d; } else if (std::abs(real(d)) <= 1.0E-4) { if (imag(d) < 0.0) { d = -d; } } for (j=stars_[i].beginId; j < stars_[i].endId; ++j){ waves_[j].coeff /= d; } } } } // end if (cancel) ... else ... } // end if (stars_[i].invertFlag == 0) else if (stars_[i].invertFlag == 1) { // Process a pair of open stars related by inversion. // Preconditions: UTIL_CHECK(stars_[i].size == stars_[i+1].size); UTIL_CHECK(stars_[i].cancel == stars_[i+1].cancel); // UTIL_CHECK(stars_[i+1].invertFlag == -1); // Identify root of this star (star i) // Set the root to be the first wave in the star rootId = stars_[i].beginId; stars_[i].waveBz = waves_[rootId].indicesBz; // Compute nVec = negation of root vector, shifted to DFT mesh nVec.negate(waves_[rootId].indicesBz); (*meshPtr_).shift(nVec); // Seek negation of root wave in the next star (star i+1) bool negationFound = false; for (j = stars_[i+1].beginId; j < stars_[i+1].endId; ++j) { if (nVec == waves_[j].indicesDft) { partId = j; stars_[i+1].waveBz = waves_[j].indicesBz; negationFound = true; break; } } // For invertFlag == 1, absence of nVec in next star is fatal UTIL_CHECK(negationFound); if (stars_[i].cancel) { std::complex<double> czero(0.0, 0.0); for (j = stars_[i].beginId; j < stars_[i].endId; ++j) { waves_[j].coeff = czero; } for (j = stars_[i+1].beginId; j < stars_[i+1].endId; ++j) { waves_[j].coeff = czero; } } else { // if star is not cancelled // Divide all coefficients in this star by root coeff rootCoeff = waves_[rootId].coeff; for (j = stars_[i].beginId; j < stars_[i].endId; ++j) { waves_[j].coeff /= rootCoeff; } // Divide coefficients in next star by a partner coeff. partCoeff = waves_[partId].coeff; for (j = stars_[i+1].beginId; j < stars_[i+1].endId; ++j) { waves_[j].coeff /= partCoeff; } } // end if (cancel) ... else ... } // end if (invertFlag==0) ... else if (invertFlag==1) ... // Note: If invertFlag == -1, do nothing and continue // Related stars with invertFlag == 1 and -1 are treated together } // end loop over stars // For all waves, normalize coefficients and set starId for (i = 0; i < nStar_; ++i) { double snorm = 1.0/sqrt(double(stars_[i].size)); for (j = stars_[i].beginId; j < stars_[i].endId; ++j) { waves_[j].coeff *= snorm; waves_[j].starId = i; } } // Set tiny real and imaginary parts to zero (due to round-off) for (i = 0; i < nWave_; ++i) { if (std::abs(real(waves_[i].coeff)) < 1.0E-8) { waves_[i].coeff = std::complex<double>(0.0, imag(waves_[i].coeff)); } if (std::abs(imag(waves_[i].coeff)) < 1.0E-8) { waves_[i].coeff = std::complex<double>(real(waves_[i].coeff), 0.0); } } // For each wave, set implicit attribute and add to look-up table for (i = 0; i < nWave_; ++i) { vec = waves_[i].indicesDft; // Validity check - check that vec is in dft mesh for (j = 0; j < D; ++j) { UTIL_CHECK(vec[j] >= 0); UTIL_CHECK(vec[j] < meshDimensions[j]); } // Set implicit attribute if ((vec[D-1] + 1) > (meshDimensions[D-1]/2 + 1)) { waves_[i].implicit = true; } else { waves_[i].implicit = false; } // Look up table for waves waveIds_[mesh().rank(vec)] = i; } // Set Star::starId and Star::basisId, and to look-up table starIds_. starIds_.allocate(nBasis_); j = 0; for (i = 0; i < nStar_; ++i) { stars_[i].starId = i; if (stars_[i].cancel) { stars_[i].basisId = -1; } else { stars_[i].basisId = j; UTIL_CHECK(j < nBasis_); starIds_[j] = i; ++j; } } UTIL_CHECK(j == nBasis_); } // Return value of nBasis template <int D> int Basis<D>::nBasis() const { return nBasis_; } template <int D> void Basis<D>::outputWaves(std::ostream& out, bool outputAll) const { out << "N_wave" << std::endl; if (outputAll) { out << " " << nWave_ << std::endl; } else { out << " " << nBasisWave_ << std::endl; } int i, j, k, starId; k = 0; for (i = 0; i < nWave_; ++i) { starId = waves_[i].starId; if (outputAll || (!stars_[starId].cancel)) { out << Int(k, 8); out << Int(i, 8); for (j = 0; j < D; ++j) { out << Int(waves_[i].indicesBz[j], 5); } out << Int(waves_[i].starId, 6); out << " " << Dbl(waves_[i].coeff.real(), 15); out << " " << Dbl(waves_[i].coeff.imag(), 15); out << std::endl; k++; } } } template <int D> void Basis<D>::outputStars(std::ostream& out, bool outputAll) const { // Output number of stars in appropriate format if (outputAll) { out << "N_star" << std::endl << " " << nStar_ << std::endl; } else { out << "N_basis" << std::endl << " " << nBasis_ << std::endl; } // Loop over stars int i, j; for (i = 0; i < nStar_; ++i) { if (outputAll || (!stars_[i].cancel)) { out << Int(stars_[i].basisId, 6); // basisId out << Int(i, 6); // starId out << Int(stars_[i].size, 5) << Int(stars_[i].beginId, 8) << Int(stars_[i].endId, 8) << Int(stars_[i].invertFlag, 4); if (outputAll) { out << Int(stars_[i].cancel, 4); } for (j = 0; j < D; ++j) { out << Int(stars_[i].waveBz[j], 6); } out << std::endl; } } } template <int D> bool Basis<D>::isValid() const { double Gsq; IntVec<D> v; int is, ib, iw, iwp, j; // Check total number of waves == # of grid points if (nWave_ != mesh().size()) { std::cout << "nWave != size of mesh" << std::endl; return false; } // Loop over dft mesh to check consistency of waveIds_ and waves_ MeshIterator<D> itr(mesh().dimensions()); for (itr.begin(); !itr.atEnd(); ++itr) { v = itr.position(); iw = waveId(v); if (wave(iw).indicesDft != v) { std::cout << "Inconsistent waveId and Wave::indicesDft" << std::endl; return false; } } // Loop over elements of waves_, check consistency of wave data. for (iw = 0; iw < nWave_; ++iw) { // Check sqNorm v = waves_[iw].indicesBz; Gsq = unitCell().ksq(v); if (std::abs(Gsq - waves_[iw].sqNorm) > 1.0E-8) { std::cout << "\n"; std::cout << "Incorrect sqNorm:" << "\n" << "wave.indicesBz = " << "\n" << "wave.sqNorm = " << waves_[iw].sqNorm << "\n" << "|v|^{2} = " << Gsq << "\n"; return false; } // Check that wave indicesBz is an image of indicesDft mesh().shift(v); if (v != waves_[iw].indicesDft) { std::cout << "\n"; std::cout << "shift(indicesBz) != indicesDft" << std::endl; return false; } // Compare Wave::starId to Star::beginId and Star::endId is = waves_[iw].starId; if (iw < stars_[is].beginId) { std::cout << "\n"; std::cout << "Wave::starId < Star::beginId" << std::endl; return false; } if (iw >= stars_[is].endId) { std::cout << "\n"; std::cout << " Wave::starId >= Star::endId" << std::endl; return false; } } // Loop over all stars (elements of stars_ array) int nWave = 0; for (is = 0; is < nStar_; ++is) { // Check star size nWave += stars_[is].size; if (stars_[is].size != stars_[is].endId - stars_[is].beginId) { std::cout << "\n"; std::cout << "Inconsistent Star::size:" << std::endl; std::cout << "Star id " << is << std::endl; std::cout << "star size " << stars_[is].size << std::endl; std::cout << "Star begin " << stars_[is].beginId << std::endl; std::cout << "Star end " << stars_[is].endId << std::endl; return false; } if (is > 0) { if (stars_[is].beginId != stars_[is-1].endId) { std::cout << "\n"; std::cout << "Star ranges not consecutive:" << std::endl; std::cout << "Star id " << is << std::endl; std::cout << "stars_[" << is << "]" << ".beginId = " << stars_[is].beginId << std::endl; std::cout << "stars_[" << is-1 << "]" << ".endId = " << stars_[is-1].endId << std::endl; return false; } } // Check star ids of waves in star for (iw = stars_[is].beginId; iw < stars_[is].endId; ++iw) { if (waves_[iw].starId != is) { std::cout << "\n"; std::cout << "Inconsistent Wave::starId :" << std::endl; std::cout << "star id " << is << std::endl; std::cout << "star beginId " << stars_[is].beginId << "\n"; std::cout << "star endId " << stars_[is].endId << "\n"; std::cout << "wave id " << iw << "\n"; std::cout << "wave starId " << waves_[iw].starId << "\n"; return false; } } // Check Star::starId is equal to array index if (stars_[is].starId != is) { std::cout << "\n"; std::cout << "stars_[is].starId != is for " << "is = " << is << "\n"; return false; } // Check Star::basisId and starIds_ look up table ib = stars_[is].basisId; if (stars_[is].cancel) { if (ib != -1) { std::cout << "\n"; std::cout << "basisId != -1 for cancelled star\n"; std::cout << "star id = " << is << "\n"; return false; } } else { if (starIds_[ib] != is) { std::cout << "\n"; std::cout << "starIds_[stars_[is].basisId] != is for: \n"; std::cout << "is = " << is << "\n"; std::cout << "ib = stars_[is].basisId = " << ib << "\n"; std::cout << "starIds_[ib] = " << starIds_[ib] << "\n"; return false; } } // Check ordering of waves in star for (iw = stars_[is].beginId + 1; iw < stars_[is].endId; ++iw) { if (waves_[iw].indicesBz > waves_[iw-1].indicesBz) { std::cout << "\n"; std::cout << "Failure of ordering by indicesB within star" << std::endl; return false; } if (waves_[iw].indicesBz == waves_[iw-1].indicesBz) { std::cout << "\n"; std::cout << "Equal values of indicesBz within star" << std::endl; return false; } } } // End do loop over all stars // Check that all waves in mesh are accounted for in stars if (stars_[nStar_-1].endId != mesh().size()) { std::cout << "\n"; std::cout << "Star endId of last star != mesh size" << std::endl; return false; } if (nWave != mesh().size()) { std::cout << "\n"; std::cout << "Sum of star sizes != mesh size" << std::endl; return false; } // Loop over closed stars and related pairs of stars. // Test closure under inversion and conjugacy of coefficients. std::complex<double> cdel; bool negationFound, cancel; is = 0; while (is < nStar_) { cancel = stars_[is].cancel; if (stars_[is].invertFlag == 0) { // Test that star is closed under inversion and real int begin = stars_[is].beginId; int end = stars_[is].endId; for (iw = begin; iw < end; ++iw) { v.negate(waves_[iw].indicesBz); mesh().shift(v); negationFound = false; for (iwp = begin; iw < end; ++iwp) { if (waves_[iwp].indicesDft == v) { negationFound = true; if (!cancel) { cdel = conj(waves_[iwp].coeff); cdel -= waves_[iw].coeff; } break; } } if (!negationFound) { std::cout << "\n"; std::cout << "Negation not found in closed star" << std::endl; std::cout << "G = " << waves_[iw].indicesBz << "coeff = " << waves_[iw].coeff << std::endl; std::cout << "All waves in star " << is << "\n"; for (j=begin; j < end; ++j) { std::cout << waves_[j].indicesBz << " " << waves_[j].coeff << "\n"; } return false; } if (!cancel && std::abs(cdel) > 1.0E-8) { std::cout << "\n"; std::cout << "Function for closed star is not real:" << "\n"; std::cout << "+G = " << waves_[iw].indicesBz << " coeff = " << waves_[iw].coeff << "\n"; std::cout << "-G = " << waves_[iwp].indicesBz << " coeff = " << waves_[iwp].coeff << "\n"; std::cout << "Coefficients are not conjugates." << "\n"; std::cout << "All waves in star " << is << "\n"; for (j=begin; j < end; ++j) { std::cout << waves_[j].indicesBz << " " << waves_[j].coeff << "\n"; } return false; } if (cancel && std::abs(waves_[iw].coeff) > 1.0E-8) { std::cout << "\n"; std::cout << "Nonzero coefficient in a cancelled star" << "\n"; std::cout << "G = " << waves_[iw].indicesBz << " coeff = " << waves_[iw].coeff << "\n"; return false; } } // Finished processing a closed star, increment counter is ++is; } else { // Test pairs of open stars if (stars_[is].invertFlag != 1) { std::cout << "\n"; std::cout << "Expected invertFlag == 1" << std::endl; return false; } if (stars_[is+1].invertFlag != -1) { std::cout << "\n"; std::cout << "Expected invertFlag == -1" << std::endl; return false; } if (stars_[is+1].size != stars_[is].size) { std::cout << "\n"; std::cout << "Partner stars of different size" << std::endl; return false; } if (stars_[is+1].cancel != stars_[is].cancel) { std::cout << "\n"; std::cout << "Partners stars with different cancel flags" << std::endl; return false; } // Begin and end wave ids for the first and second stars int begin1 = stars_[is].beginId; int end1 = stars_[is].endId; int begin2 = stars_[is+1].beginId; int end2 = stars_[is+1].endId; // Check existence of negation and conjugate coefficients // Loop over waves in first star for (iw = begin1; iw < end1; ++iw) { v.negate(waves_[iw].indicesBz); mesh().shift(v); negationFound = false; // Loop over second star, searching for negation for (iwp = begin2; iw < end2; ++iwp) { if (waves_[iwp].indicesDft == v) { negationFound = true; if (!cancel) { cdel = conj(waves_[iwp].coeff); cdel -= waves_[iw].coeff; } break; } } if (!negationFound) { std::cout << "\n"; std::cout << "Negation not found for G in open star" << std::endl; std::cout << "First star id = " << is << std::endl; std::cout << "+G = " << waves_[iw].indicesBz << "coeff = " << waves_[iw].coeff << std::endl; std::cout << "Waves in star " << is << " (starInvert ==1):" << "\n"; for (j = begin1; j < end1; ++j) { std::cout << waves_[j].indicesBz << " " << waves_[j].coeff << "\n"; } std::cout << "Waves in star " << is+1 << " (starInvert == -1):" << "\n"; for (j=begin2; j < end2; ++j) { std::cout << waves_[j].indicesBz << " " << waves_[j].coeff << "\n"; } return false; } else if (!cancel && std::abs(cdel) > 1.0E-8) { std::cout << "\n"; std::cout << "Error of coefficients in open stars:" << "\n"; std::cout << "First star id = " << is << std::endl; std::cout << "+G = " << waves_[iw].indicesBz << " coeff = " << waves_[iw].coeff << "\n"; std::cout << "-G = " << waves_[iwp].indicesBz << " coeff = " << waves_[iwp].coeff << "\n"; std::cout << "Coefficients are not conjugates." << "\n"; std::cout << "Waves in star " << is << " (starInvert ==1):" << "\n"; for (j = begin1; j < end1; ++j) { std::cout << waves_[j].indicesBz << " " << waves_[j].coeff << "\n"; } std::cout << "Waves in star " << is+1 << " (starInvert == -1):" << "\n"; for (j=begin2; j < end2; ++j) { std::cout << waves_[j].indicesBz << " " << waves_[j].coeff << "\n"; } return false; } } // Finished processing a pair, increment star counter by 2 is += 2; } // end if (stars_[is].invertFlag == 0) ... else ... } // end while (is < nStar_) loop over stars // Loop over basis functions for (ib = 0; ib < nBasis_; ++ib) { is = starIds_[ib]; if (stars_[is].cancel) { std::cout << "\n"; std::cout << "Star referred to by starIds_ is cancelled\n"; return false; } if (stars_[is].basisId != ib) { std::cout << "\n"; std::cout << "Eror: stars_[starIds_[ib]].basisId != ib\n"; std::cout << "Basis function index ib = " << ib << "\n"; std::cout << "is = starIds_[ib] = " << is << "\n"; std::cout << "stars_[is].basisId = " << stars_[is].basisId << "\n"; return false; } } // The end of this function is reached iff all tests passed. return true; } } #endif
47,749
C++
.tpp
1,128
29.194149
76
0.466091
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,254
SpaceGroup.tpp
dmorse_pscfpp/src/pscf/crystal/SpaceGroup.tpp
#ifndef PSCF_SPACE_GROUP_TPP #define PSCF_SPACE_GROUP_TPP /* * 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/SpaceGroup.h> #include <pscf/crystal/groupFile.h> namespace Pscf { using namespace Util; /* * Find inversion center, if any. */ template <int D> bool SpaceGroup<D>::hasInversionCenter( typename SpaceSymmetry<D>::Translation& center) const { bool isInversion = false; int i, j, k; for (i = 0; i < size(); ++i) { isInversion = true; for (j = 0; j < D; ++j) { for (k = 0; k < D; ++k) { if (j == k) { if ((*this)[i].R(j,k) != -1) isInversion = false; } else { if ((*this)[i].R(j,k) != 0) isInversion = false; } } } if (isInversion) { for (int j = 0; j < D; ++j) { center[j] = (*this)[i].t(j)/2; } return true; } } return false; } template <int D> void SpaceGroup<D>::shiftOrigin( typename SpaceSymmetry<D>::Translation const & origin) { for (int i = 0; i < size(); ++i) { (*this)[i].shiftOrigin(origin); } } /* * Check if a mesh is compatible with this space group. */ template <int D> void SpaceGroup<D>::checkMeshDimensions(IntVec<D> const & dimensions) const { // --------------------------------------------------------------- // Check compatibility of mesh dimensions & translations // --------------------------------------------------------------- // Identify required divisor of mesh dimension in each direction int numerator, denominator; IntVec<D> divisors; for (int i = 0; i < D; ++i) { // Find maximum denominator divisors[i] = 1; for (int j = 0; j < size(); ++j) { numerator = (*this)[j].t(i).num(); denominator = (*this)[j].t(i).den(); if (numerator != 0) { UTIL_CHECK(denominator > 0); if (denominator > divisors[i]) { divisors[i] = denominator; } } } // Make sure each divisor is a multiple of all denominators for (int j = 0; j < size(); ++j) { numerator = (*this)[j].t(i).num(); denominator = (*this)[j].t(i).den(); if (numerator != 0) { if (denominator < divisors[i]) { if (divisors[i]%denominator != 0) { divisors[i] = divisors[i]*denominator; } } } } } // Check that mesh dimensions are multiples of required divisor for (int i = 1; i < D; ++i) { if (dimensions[i]%divisors[i] != 0) { Log::file() << "\n" << "Mesh dimensions incompatible with the space group:\n" << " dimensions[" << i << "] = " << dimensions[i] << "\n" << " This dimension must be a multiple of " << divisors[i] << "\n\n"; UTIL_THROW("Error: Mesh not incompatible with space group"); } } // --------------------------------------------------------------- // Check compatibility of mesh dimensions & point group operations // --------------------------------------------------------------- // Identify pairs of directions that are related by point group ops FMatrix<bool, D, D> areRelated; for (int i = 0; i < D; ++i) { for (int j = 0; j < D; ++j) { areRelated(i, j) = false; } areRelated(i, i) = true; } for (int k = 0; k < size(); ++k) { for (int i = 0; i < D; ++i) { for (int j = 0; j < D; ++j) { if (i != j) { if ( (*this)[k].R(i,j) != 0) { areRelated(i, j) = true; areRelated(j, i) = true; } } } } } // Check if mesh dimensions are equal for related directions for (int i = 0; i < D; ++i) { for (int j = 0; j < i; ++j) { if (areRelated(i,j) && (dimensions[i] != dimensions[j])) { Log::file() << "\n" << "Mesh dimensions incompatible with the space group - \n" << "Unequal dimensions for related directions:\n" << " dimensions[" << i << "] = " << dimensions[i] << "\n" << " dimensions[" << j << "] = " << dimensions[j] << "\n\n"; UTIL_THROW("Error: Mesh not incompatible with space group"); } } } } /* * Read a group from file */ template <int D> void readGroup(std::string groupName, SpaceGroup<D>& group) { if (groupName == "I") { // Create identity group by default group.makeCompleteGroup(); } else { bool foundFile = false; { // Search first in this directory std::ifstream in; in.open(groupName); if (in.is_open()) { in >> group; UTIL_CHECK(group.isValid()); foundFile = true; } } if (!foundFile) { // Search in the data directory containing standard space groups std::string fileName = makeGroupFileName(D, groupName); std::ifstream in; in.open(fileName); if (in.is_open()) { in >> group; UTIL_CHECK(group.isValid()); } else { Log::file() << "\nFailed to open group file: " << fileName << "\n"; Log::file() << "\n Error: Unknown space group\n"; UTIL_THROW("Unknown space group"); } } } } /* * Open an output file and write group to file. */ template <int D> void writeGroup(std::string filename, SpaceGroup<D> const & group) { std::ofstream out; out.open(filename); out << group; } } #endif
6,443
C++
.tpp
192
23.385417
76
0.452152
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,255
FieldComparison.tpp
dmorse_pscfpp/src/pscf/math/FieldComparison.tpp
#ifndef PSCF_FIELD_COMPARISON_TPP #define PSCF_FIELD_COMPARISON_TPP /* * 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 "FieldComparison.h" #include <cmath> namespace Pscf { using namespace Util; // Default Constructor template <class FT> FieldComparison<FT>::FieldComparison(int begin) : maxDiff_(0.0), rmsDiff_(0.0), begin_(begin) {}; // Comparator for individual fields. template <class FT> double FieldComparison<FT>::compare(FT const& a, FT const& b) { UTIL_CHECK(a.capacity() > 0); UTIL_CHECK(a.capacity() == b.capacity()); int n = a.capacity(); double diff; maxDiff_ = 0.0; rmsDiff_ = 0.0; for (int i = begin_; i < n; ++i) { diff = std::abs(a[i] - b[i]); if (std::isnan(diff)) { // If either field has a NaN component, set error to very // high value and exit the function maxDiff_ = 1e8; rmsDiff_ = 1e8; return maxDiff_; } else if (diff > maxDiff_) { maxDiff_ = diff; } rmsDiff_ += diff*diff; } rmsDiff_ = rmsDiff_/double(n); rmsDiff_ = sqrt(rmsDiff_); return maxDiff_; } // Comparator for arrays of fields template <class FT> double FieldComparison<FT>::compare(DArray<FT> const & a, DArray<FT> const & b) { UTIL_CHECK(a.capacity() > 0); UTIL_CHECK(a.capacity() == b.capacity()); UTIL_CHECK(a[0].capacity() > 0); int m = a.capacity(); double diff; maxDiff_ = 0.0; rmsDiff_ = 0.0; int i, j, n; for (i = 0; i < m; ++i) { n = a[i].capacity(); UTIL_CHECK(n > 0); UTIL_CHECK(n == b[i].capacity()); for (j = begin_; j < n; ++j) { diff = std::abs(a[i][j] - b[i][j]); if (std::isnan(diff)) { // If either field has a NaN component, set error to very // high value and exit the function maxDiff_ = 1e8; rmsDiff_ = 1e8; return maxDiff_; } else if (diff > maxDiff_) { maxDiff_ = diff; } rmsDiff_ += diff*diff; } } rmsDiff_ = rmsDiff_/double(m*n); rmsDiff_ = sqrt(rmsDiff_); return maxDiff_; } } #endif
2,508
C++
.tpp
83
22.421687
72
0.534133
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,256
System.tpp
dmorse_pscfpp/src/pspc/System.tpp
#ifndef PSPC_SYSTEM_TPP #define PSPC_SYSTEM_TPP /* * 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 "System.h" #include <pspc/sweep/Sweep.h> #include <pspc/sweep/SweepFactory.h> #include <pspc/iterator/Iterator.h> #include <pspc/iterator/IteratorFactory.h> #include <pspc/solvers/Polymer.h> #include <pspc/solvers/Solvent.h> #include <pspc/field/BFieldComparison.h> #include <pspc/field/RFieldComparison.h> #include <pscf/inter/Interaction.h> #include <pscf/math/IntVec.h> #include <pscf/homogeneous/Clump.h> #include <util/param/BracketPolicy.h> #include <util/format/Str.h> #include <util/format/Int.h> #include <util/format/Dbl.h> #include <util/misc/ioUtil.h> #include <string> #include <unistd.h> namespace Pscf { namespace Pspc { using namespace Util; /* * Constructor. */ template <int D> System<D>::System() : mixture_(), domain_(), fileMaster_(), homogeneous_(), interactionPtr_(0), iteratorPtr_(0), iteratorFactoryPtr_(0), sweepPtr_(0), sweepFactoryPtr_(0), w_(), c_(), h_(), mask_(), fHelmholtz_(0.0), fIdeal_(0.0), fInter_(0.0), fExt_(0.0), pressure_(0.0), hasMixture_(false), isAllocatedRGrid_(false), isAllocatedBasis_(false), hasCFields_(false), hasFreeEnergy_(false) { setClassName("System"); domain_.setFileMaster(fileMaster_); w_.setFieldIo(domain_.fieldIo()); h_.setFieldIo(domain_.fieldIo()); mask_.setFieldIo(domain_.fieldIo()); interactionPtr_ = new Interaction(); iteratorFactoryPtr_ = new IteratorFactory<D>(*this); sweepFactoryPtr_ = new SweepFactory<D>(*this); BracketPolicy::set(BracketPolicy::Optional); } /* * Destructor. */ template <int D> System<D>::~System() { if (interactionPtr_) { delete interactionPtr_; } if (iteratorPtr_) { delete iteratorPtr_; } if (iteratorFactoryPtr_) { delete iteratorFactoryPtr_; } if (sweepPtr_) { delete sweepPtr_; } if (sweepFactoryPtr_) { delete sweepFactoryPtr_; } } /* * Process command line options. */ template <int D> void System<D>::setOptions(int argc, char **argv) { bool eflag = false; // echo bool pFlag = false; // param file bool cFlag = false; // command file bool iFlag = false; // input prefix bool oFlag = false; // output prefix char* pArg = 0; char* cArg = 0; char* iArg = 0; char* oArg = 0; // Read program arguments int c; opterr = 0; while ((c = getopt(argc, argv, "er:p:c:i:o:f")) != -1) { switch (c) { case 'e': eflag = true; break; case 'p': // parameter file pFlag = true; pArg = optarg; break; case 'c': // command file cFlag = true; cArg = optarg; break; case 'i': // input prefix iFlag = true; iArg = optarg; break; case 'o': // output prefix oFlag = true; oArg = optarg; break; case '?': Log::file() << "Unknown option -" << optopt << std::endl; UTIL_THROW("Invalid command line option"); } } // Set flag to echo parameters as they are read. if (eflag) { Util::ParamComponent::setEcho(true); } // If option -p, set parameter file name if (pFlag) { fileMaster_.setParamFileName(std::string(pArg)); } // If option -c, set command file name if (cFlag) { fileMaster_.setCommandFileName(std::string(cArg)); } // If option -i, set path prefix for input files if (iFlag) { fileMaster_.setInputPrefix(std::string(iArg)); } // If option -o, set path prefix for output files if (oFlag) { fileMaster_.setOutputPrefix(std::string(oArg)); } } /* * Read parameters and initialize. */ template <int D> void System<D>::readParameters(std::istream& in) { // Read the Mixture{ ... } block readParamComposite(in, mixture_); hasMixture_ = true; int nm = mixture_.nMonomer(); int np = mixture_.nPolymer(); int ns = mixture_.nSolvent(); UTIL_CHECK(nm > 0); UTIL_CHECK(np >= 0); UTIL_CHECK(ns >= 0); UTIL_CHECK(np + ns > 0); // Read the Interaction{ ... } block interaction().setNMonomer(nm); readParamComposite(in, interaction()); // Read the Domain{ ... } block readParamComposite(in, domain_); mixture_.setMesh(domain_.mesh()); mixture_.setupUnitCell(unitCell()); // Allocate field array members of System allocateFieldsGrid(); if (domain_.basis().isInitialized()) { allocateFieldsBasis(); } // Optionally instantiate an Iterator object std::string className; bool isEnd; iteratorPtr_ = iteratorFactoryPtr_->readObjectOptional(in, *this, className, isEnd); if (!iteratorPtr_) { Log::file() << "Notification: No iterator was constructed\n"; } // Optionally instantiate a Sweep object if (iteratorPtr_) { sweepPtr_ = sweepFactoryPtr_->readObjectOptional(in, *this, className, isEnd); } // Initialize homogeneous object // NOTE: THIS OBJECT IS NOT USED AT ALL. homogeneous_.setNMolecule(np+ns); homogeneous_.setNMonomer(nm); initHomogeneous(); } /* * Read default parameter file. */ template <int D> void System<D>::readParam(std::istream& in) { readBegin(in, className().c_str()); readParameters(in); readEnd(in); } /* * Read default parameter file. */ template <int D> void System<D>::readParam() { readParam(fileMaster_.paramFile()); } /* * Read and execute commands from a specified command file. */ template <int D> void System<D>::readCommands(std::istream &in) { UTIL_CHECK(isAllocatedRGrid_); std::string command, filename, inFileName, outFileName; bool readNext = true; while (readNext) { in >> command; if (in.eof()) { break; } else { Log::file() << command << std::endl; } if (command == "FINISH") { Log::file() << std::endl; readNext = false; } else if (command == "READ_W_BASIS") { readEcho(in, filename); readWBasis(filename); } else if (command == "READ_W_RGRID") { readEcho(in, filename); readWRGrid(filename); } else if (command == "ESTIMATE_W_FROM_C") { readEcho(in, inFileName); estimateWfromC(inFileName); } else if (command == "SET_UNIT_CELL") { UnitCell<D> unitCell; in >> unitCell; Log::file() << " " << unitCell << std::endl; setUnitCell(unitCell); } else if (command == "COMPUTE") { // Solve the modified diffusion equation, without iteration compute(); } else if (command == "ITERATE") { // Attempt to iteratively solve a single SCFT problem bool isContinuation = false; int fail = iterate(isContinuation); if (fail) { readNext = false; } } else if (command == "SWEEP") { // Attempt to solve a sequence of SCFT problems along a path // through parameter space sweep(); } else if (command == "WRITE_PARAM") { readEcho(in, filename); std::ofstream file; fileMaster().openOutputFile(filename, file); writeParamNoSweep(file); file.close(); } else if (command == "WRITE_THERMO") { readEcho(in, filename); std::ofstream file; fileMaster().openOutputFile(filename, file, std::ios_base::app); writeThermo(file); file.close(); } else if (command == "WRITE_W_BASIS") { readEcho(in, filename); writeWBasis(filename); } else if (command == "WRITE_W_RGRID") { readEcho(in, filename); writeWRGrid(filename); } else if (command == "WRITE_C_BASIS") { readEcho(in, filename); writeCBasis(filename); } else if (command == "WRITE_C_RGRID") { readEcho(in, filename); writeCRGrid(filename); } else if (command == "WRITE_BLOCK_C_RGRID") { readEcho(in, filename); writeBlockCRGrid(filename); } else if (command == "WRITE_Q_SLICE") { int polymerId, blockId, directionId, segmentId; readEcho(in, filename); in >> polymerId; in >> blockId; in >> directionId; in >> segmentId; Log::file() << Str("polymer ID ", 21) << polymerId << "\n" << Str("block ID ", 21) << blockId << "\n" << Str("direction ID ", 21) << directionId << "\n" << Str("segment ID ", 21) << segmentId << std::endl; writeQSlice(filename, polymerId, blockId, directionId, segmentId); } else if (command == "WRITE_Q_TAIL") { readEcho(in, filename); int polymerId, blockId, directionId; in >> polymerId; in >> blockId; in >> directionId; Log::file() << Str("polymer ID ", 21) << polymerId << "\n" << Str("block ID ", 21) << blockId << "\n" << Str("direction ID ", 21) << directionId << "\n"; writeQTail(filename, polymerId, blockId, directionId); } else if (command == "WRITE_Q") { readEcho(in, filename); int polymerId, blockId, directionId; in >> polymerId; in >> blockId; in >> directionId; Log::file() << Str("polymer ID ", 21) << polymerId << "\n" << Str("block ID ", 21) << blockId << "\n" << Str("direction ID ", 21) << directionId << "\n"; writeQ(filename, polymerId, blockId, directionId); } else if (command == "WRITE_Q_ALL") { readEcho(in, filename); writeQAll(filename); } else if (command == "WRITE_STARS") { readEcho(in, filename); writeStars(filename); } else if (command == "WRITE_WAVES") { readEcho(in, filename); writeWaves(filename); } else if (command == "WRITE_GROUP") { readEcho(in, filename); writeGroup(filename); } else if (command == "BASIS_TO_RGRID") { readEcho(in, inFileName); readEcho(in, outFileName); basisToRGrid(inFileName, outFileName); } else if (command == "RGRID_TO_BASIS") { readEcho(in, inFileName); readEcho(in, outFileName); rGridToBasis(inFileName, outFileName); } else if (command == "KGRID_TO_RGRID") { readEcho(in, inFileName); readEcho(in, outFileName); kGridToRGrid(inFileName, outFileName); } else if (command == "RGRID_TO_KGRID") { readEcho(in, inFileName); readEcho(in, outFileName); rGridToKGrid(inFileName, outFileName); } else if (command == "BASIS_TO_KGRID") { readEcho(in, inFileName); readEcho(in, outFileName); basisToKGrid(inFileName, outFileName); } else if (command == "KGRID_TO_BASIS") { readEcho(in, inFileName); readEcho(in, outFileName); kGridToBasis(inFileName, outFileName); } else if (command == "CHECK_RGRID_SYMMETRY") { double epsilon; readEcho(in, inFileName); readEcho(in, epsilon); bool hasSymmetry; hasSymmetry = checkRGridFieldSymmetry(inFileName, epsilon); if (hasSymmetry) { Log::file() << std::endl << "Symmetry of r-grid file matches this space group." << std::endl << std::endl; } else { Log::file() << std::endl << "Symmetry of r-grid file does not match this space group" << std::endl << "to within error threshold of " << Dbl(epsilon) << "." << std::endl << std::endl; } } else if (command == "COMPARE_BASIS") { // Get two filenames for comparison std::string filecompare1, filecompare2; readEcho(in, filecompare1); readEcho(in, filecompare2); DArray< DArray<double> > Bfield1, Bfield2; domain_.fieldIo().readFieldsBasis(filecompare1, Bfield1, domain_.unitCell()); domain_.fieldIo().readFieldsBasis(filecompare2, Bfield2, domain_.unitCell()); // Note: Bfield1 & Bfield2 are allocated by readFieldsBasis // Compare and output report compare(Bfield1, Bfield2); } else if (command == "COMPARE_RGRID") { // Get two filenames for comparison std::string filecompare1, filecompare2; readEcho(in, filecompare1); readEcho(in, filecompare2); DArray< RField<D> > Rfield1, Rfield2; domain_.fieldIo().readFieldsRGrid(filecompare1, Rfield1, domain_.unitCell()); domain_.fieldIo().readFieldsRGrid(filecompare2, Rfield2, domain_.unitCell()); // Note: Rfield1, Rfield2 will be allocated by readFieldsRGrid // Compare and output report compare(Rfield1, Rfield2); } else if (command == "READ_H_BASIS") { readEcho(in, filename); if (!h_.isAllocatedBasis()) { h_.allocateBasis(basis().nBasis()); } if (!h_.isAllocatedRGrid()) { h_.allocateRGrid(mesh().dimensions()); } h_.readBasis(filename, domain_.unitCell()); } else if (command == "READ_H_RGRID") { readEcho(in, filename); if (!h_.isAllocatedRGrid()) { h_.allocateRGrid(mesh().dimensions()); } h_.readRGrid(filename, domain_.unitCell()); } else if (command == "WRITE_H_BASIS") { readEcho(in, filename); UTIL_CHECK(h_.hasData()); UTIL_CHECK(h_.isSymmetric()); fieldIo().writeFieldsBasis(filename, h_.basis(), unitCell()); } else if (command == "WRITE_H_RGRID") { readEcho(in, filename); UTIL_CHECK(h_.hasData()); fieldIo().writeFieldsRGrid(filename, h_.rgrid(), unitCell()); } else if (command == "READ_MASK_BASIS") { UTIL_CHECK(domain_.basis().isInitialized()); readEcho(in, filename); if (!mask_.isAllocated()) { mask_.allocate(basis().nBasis(), mesh().dimensions()); } mask_.readBasis(filename, domain_.unitCell()); } else if (command == "READ_MASK_RGRID") { readEcho(in, filename); if (!mask_.isAllocated()) { mask_.allocate(basis().nBasis(), mesh().dimensions()); } mask_.readBasis(filename, domain_.unitCell()); } else if (command == "WRITE_MASK_BASIS") { readEcho(in, filename); UTIL_CHECK(mask_.hasData()); UTIL_CHECK(mask_.isSymmetric()); fieldIo().writeFieldBasis(filename, mask_.basis(), unitCell()); } else if (command == "WRITE_MASK_RGRID") { readEcho(in, filename); UTIL_CHECK(mask_.hasData()); fieldIo().writeFieldRGrid(filename, mask_.rgrid(), unitCell()); } else { Log::file() << "Error: Unknown command " << command << std::endl; readNext = false; } } } /* * Read and execute commands from the default command file. */ template <int D> void System<D>::readCommands() { if (fileMaster_.commandFileName().empty()) { UTIL_THROW("Empty command file name"); } readCommands(fileMaster_.commandFile()); } // W Field Modifier Functions /* * Read w-field in symmetry adapted basis format. */ template <int D> void System<D>::readWBasis(const std::string & filename) { // If basis fields are not allocated, peek at field file header to // get unit cell parameters, initialize basis and allocate fields. if (!isAllocatedBasis_) { readFieldHeader(filename); allocateFieldsBasis(); } // Read w fields w_.readBasis(filename, domain_.unitCell()); mixture_.setupUnitCell(domain_.unitCell()); hasCFields_ = false; hasFreeEnergy_ = false; } /* * Read w-fields in real-space grid (r-grid) format. */ template <int D> void System<D>::readWRGrid(const std::string & filename) { // If basis fields are not allocated, peek at field file header to // get unit cell parameters, initialize basis and allocate fields. if (!isAllocatedBasis_) { readFieldHeader(filename); allocateFieldsBasis(); } // Read w fields w_.readRGrid(filename, domain_.unitCell()); mixture_.setupUnitCell(domain_.unitCell()); hasCFields_ = false; hasFreeEnergy_ = false; } /* * Set new w-field values. */ template <int D> void System<D>::setWBasis(DArray< DArray<double> > const & fields) { UTIL_CHECK(domain_.basis().isInitialized()); UTIL_CHECK(isAllocatedBasis_); w_.setBasis(fields); hasCFields_ = false; hasFreeEnergy_ = false; } /* * Set new w-field values, using r-grid fields as inputs. */ template <int D> void System<D>::setWRGrid(DArray< RField<D> > const & fields) { UTIL_CHECK(isAllocatedRGrid_); w_.setRGrid(fields); hasCFields_ = false; hasFreeEnergy_ = false; } /* * Construct estimate for w fields from c fields, by setting xi=0. * * Modifies wFields and wFieldsRGrid. */ template <int D> void System<D>::estimateWfromC(std::string const & filename) { UTIL_CHECK(hasMixture_); const int nm = mixture_.nMonomer(); UTIL_CHECK(nm > 0); // If basis fields are not allocated, peek at field file header to // get unit cell parameters, initialize basis and allocate fields. if (!isAllocatedBasis_) { readFieldHeader(filename); allocateFieldsBasis(); } const int nb = domain_.basis().nBasis(); UTIL_CHECK(nb > 0); // Read c fields and set unit cell domain_.fieldIo().readFieldsBasis(filename, tmpFieldsBasis_, domain_.unitCell()); DArray<double> wtmp; wtmp.allocate(nm); // Compute estimated w fields from c fields int i, j, k; for (i = 0; i < nb; ++i) { for (j = 0; j < nm; ++j) { wtmp[j] = 0.0; for (k = 0; k < nm; ++k) { wtmp[j] += interaction().chi(j,k)*tmpFieldsBasis_[k][i]; } } for (j = 0; j < nm; ++j) { tmpFieldsBasis_[j][i] = wtmp[j]; } } // Store initial guess for w fields w_.setBasis(tmpFieldsBasis_); hasCFields_ = false; hasFreeEnergy_ = false; } // Unit Cell Modifier / Setter /* * Set parameters of the system unit cell. */ template <int D> void System<D>::setUnitCell(UnitCell<D> const & unitCell) { domain_.setUnitCell(unitCell); mixture_.setupUnitCell(domain_.unitCell()); if (!isAllocatedBasis_) { allocateFieldsBasis(); } } /* * Set state of the system unit cell. */ template <int D> void System<D>::setUnitCell(typename UnitCell<D>::LatticeSystem lattice, FSArray<double, 6> const & parameters) { domain_.setUnitCell(lattice, parameters); mixture_.setupUnitCell(domain_.unitCell()); if (!isAllocatedBasis_) { allocateFieldsBasis(); } } /* * Set parameters of the system unit cell. */ template <int D> void System<D>::setUnitCell(FSArray<double, 6> const & parameters) { domain_.setUnitCell(parameters); mixture_.setupUnitCell(domain_.unitCell()); if (!isAllocatedBasis_) { allocateFieldsBasis(); } } // Primary SCFT Computations /* * Solve MDE for current w-fields, without iteration. */ template <int D> void System<D>::compute(bool needStress) { UTIL_CHECK(w_.isAllocatedRGrid()); UTIL_CHECK(c_.isAllocatedRGrid()); UTIL_CHECK(w_.hasData()); // Solve the modified diffusion equation (without iteration) mixture_.compute(w_.rgrid(), c_.rgrid(), mask_.phiTot()); hasCFields_ = true; hasFreeEnergy_ = false; // Compute stress if requested if (needStress) { mixture_.computeStress(); } // If w fields are symmetric, compute basis components for c-fields if (w_.isSymmetric()) { UTIL_CHECK(c_.isAllocatedBasis()); domain_.fieldIo().convertRGridToBasis(c_.rgrid(), c_.basis(), false); } } /* * Iteratively solve a SCFT problem for specified parameters. */ template <int D> int System<D>::iterate(bool isContinuation) { UTIL_CHECK(iteratorPtr_); UTIL_CHECK(w_.hasData()); UTIL_CHECK(w_.isSymmetric()); hasCFields_ = false; hasFreeEnergy_ = false; Log::file() << std::endl; Log::file() << std::endl; // Call iterator (return 0 for convergence, 1 for failure) int error = iterator().solve(isContinuation); hasCFields_ = true; // If converged, compute related properties if (!error) { if (!iterator().isFlexible()) { mixture().computeStress(); } writeThermo(Log::file()); } return error; } /* * Perform sweep along a line in parameter space. */ template <int D> void System<D>::sweep() { UTIL_CHECK(w_.hasData()); UTIL_CHECK(w_.isSymmetric()); UTIL_CHECK(hasSweep()); Log::file() << std::endl; Log::file() << std::endl; // Perform sweep sweepPtr_->sweep(); } // Thermodynamic Properties /* * Compute Helmoltz free energy and pressure */ template <int D> void System<D>::computeFreeEnergy() { UTIL_CHECK(domain_.basis().isInitialized()); UTIL_CHECK(w_.hasData()); UTIL_CHECK(w_.isSymmetric()); UTIL_CHECK(hasCFields_); UTIL_CHECK(!hasFreeEnergy_); // Initialize to zero fHelmholtz_ = 0.0; fIdeal_ = 0.0; fInter_ = 0.0; double phi, mu; int np = mixture_.nPolymer(); int ns = mixture_.nSolvent(); // Compute polymer ideal gas contributions to fHelhmoltz_ if (np > 0) { Polymer<D>* polymerPtr; double length; for (int i = 0; i < np; ++i) { polymerPtr = &mixture_.polymer(i); phi = polymerPtr->phi(); mu = polymerPtr->mu(); length = polymerPtr->length(); // Recall: mu = ln(phi/q) if (phi > 1.0E-08) { fIdeal_ += phi*( mu - 1.0 )/length; } } } // Compute solvent ideal gas contributions to fHelhmoltz_ if (ns > 0) { Solvent<D>* solventPtr; double size; for (int i = 0; i < ns; ++i) { solventPtr = &mixture_.solvent(i); phi = solventPtr->phi(); mu = solventPtr->mu(); size = solventPtr->size(); if (phi > 1.0E-08) { fIdeal_ += phi*( mu - 1.0 )/size; } } } int nm = mixture_.nMonomer(); int nBasis = domain_.basis().nBasis(); double temp(0.0); // Compute Legendre transform subtraction // Use expansion in symmetry-adapted orthonormal basis for (int i = 0; i < nm; ++i) { for (int k = 0; k < nBasis; ++k) { temp -= w_.basis(i)[k] * c_.basis(i)[k]; } } // If the system has a mask, then the volume that should be used // in calculating free energy/pressure is the volume available to // the polymers, not the total unit cell volume. We thus divide // all terms that involve integrating over the unit cell volume by // mask().phiTot(), the volume fraction of the unit cell that is // occupied by the polymers. This properly scales them to the // correct value. fExt_, fInter_, and the Legendre transform // component of fIdeal_ all require this scaling. If no mask is // present, mask.phiTot() = 1 and no scaling occurs. temp /= mask().phiTot(); fIdeal_ += temp; fHelmholtz_ += fIdeal_; // Compute contribution from external fields, if fields exist if (hasExternalFields()) { fExt_ = 0.0; for (int i = 0; i < nm; ++i) { for (int k = 0; k < nBasis; ++k) { fExt_ += h_.basis(i)[k] * c_.basis(i)[k]; } } fExt_ /= mask().phiTot(); fHelmholtz_ += fExt_; } // Compute excess interaction free energy [ phi^{T}*chi*phi ] double chi; for (int i = 0; i < nm; ++i) { for (int j = i + 1; j < nm; ++j) { chi = interaction().chi(i,j); for (int k = 0; k < nBasis; ++k) { fInter_ += chi * c_.basis(i)[k] * c_.basis(j)[k]; } } } fInter_ /= mask().phiTot(); fHelmholtz_ += fInter_; // Initialize pressure pressure_ = -fHelmholtz_; // Polymer corrections to pressure if (np > 0) { Polymer<D>* polymerPtr; double length; for (int i = 0; i < np; ++i) { polymerPtr = &mixture_.polymer(i); phi = polymerPtr->phi(); mu = polymerPtr->mu(); length = polymerPtr->length(); if (phi > 1E-08) { pressure_ += mu * phi /length; } } } // Solvent corrections to pressure if (ns > 0) { Solvent<D>* solventPtr; double size; for (int i = 0; i < ns; ++i) { solventPtr = &mixture_.solvent(i); phi = solventPtr->phi(); mu = solventPtr->mu(); size = solventPtr->size(); if (phi > 1E-08) { pressure_ += mu * phi /size; } } } hasFreeEnergy_ = true; } // Output Operations /* * Write parameter file, omitting any sweep block. */ template <int D> void System<D>::writeParamNoSweep(std::ostream& out) const { out << "System{" << std::endl; mixture().writeParam(out); interaction().writeParam(out); domain_.writeParam(out); if (iteratorPtr_) { iterator().writeParam(out); } out << "}" << std::endl; } /* * Write thermodynamic properties to file. */ template <int D> void System<D>::writeThermo(std::ostream& out) { if (!hasFreeEnergy_) { computeFreeEnergy(); } out << std::endl; out << "fHelmholtz " << Dbl(fHelmholtz(), 18, 11) << std::endl; out << "pressure " << Dbl(pressure(), 18, 11) << std::endl; out << std::endl; out << "fIdeal " << Dbl(fIdeal_, 18, 11) << std::endl; out << "fInter " << Dbl(fInter_, 18, 11) << std::endl; if (hasExternalFields()) { out << "fExt " << Dbl(fExt_, 18, 11) << std::endl; } out << std::endl; int np = mixture_.nPolymer(); int ns = mixture_.nSolvent(); if (np > 0) { out << "polymers:" << std::endl; out << " " << " phi " << " mu " << std::endl; for (int i = 0; i < np; ++i) { out << Int(i, 5) << " " << Dbl(mixture_.polymer(i).phi(),18, 11) << " " << Dbl(mixture_.polymer(i).mu(), 18, 11) << std::endl; } out << std::endl; } if (ns > 0) { out << "solvents:" << std::endl; out << " " << " phi " << " mu " << std::endl; for (int i = 0; i < ns; ++i) { out << Int(i, 5) << " " << Dbl(mixture_.solvent(i).phi(),18, 11) << " " << Dbl(mixture_.solvent(i).mu(), 18, 11) << std::endl; } out << std::endl; } out << "cellParams:" << std::endl; for (int i = 0; i < unitCell().nParameter(); ++i) { out << Int(i, 5) << " " << Dbl(unitCell().parameter(i), 18, 11) << std::endl; } out << std::endl; } /* * Write w-fields in symmetry-adapted basis format. */ template <int D> void System<D>::writeWBasis(std::string const & filename) const { UTIL_CHECK(domain_.basis().isInitialized()); UTIL_CHECK(isAllocatedBasis_); UTIL_CHECK(w_.hasData()); UTIL_CHECK(w_.isSymmetric()); domain_.fieldIo().writeFieldsBasis(filename, w_.basis(), domain_.unitCell()); } /* * Write w-fields in real space grid file format. */ template <int D> void System<D>::writeWRGrid(const std::string & filename) const { UTIL_CHECK(isAllocatedRGrid_); UTIL_CHECK(w_.hasData()); domain_.fieldIo().writeFieldsRGrid(filename, w_.rgrid(), domain_.unitCell()); } /* * Write all concentration fields in symmetry-adapted basis format. */ template <int D> void System<D>::writeCBasis(const std::string & filename) const { UTIL_CHECK(domain_.basis().isInitialized()); UTIL_CHECK(isAllocatedBasis_); UTIL_CHECK(hasCFields_); UTIL_CHECK(w_.isSymmetric()); domain_.fieldIo().writeFieldsBasis(filename, c_.basis(), domain_.unitCell()); } /* * Write all concentration fields in real space (r-grid) format. */ template <int D> void System<D>::writeCRGrid(const std::string & filename) const { UTIL_CHECK(isAllocatedRGrid_); UTIL_CHECK(hasCFields_); domain_.fieldIo().writeFieldsRGrid(filename, c_.rgrid(), domain_.unitCell()); } /* * Write all concentration fields in real space (r-grid) format, for * each block (or solvent) individually rather than for each species. */ template <int D> void System<D>::writeBlockCRGrid(const std::string & filename) const { UTIL_CHECK(isAllocatedRGrid_); UTIL_CHECK(hasCFields_); // Create and allocate the DArray of fields to be written DArray< RField<D> > blockCFields; blockCFields.allocate(mixture_.nSolvent() + mixture_.nBlock()); int n = blockCFields.capacity(); for (int i = 0; i < n; i++) { blockCFields[i].allocate(domain_.mesh().dimensions()); } // Get data from Mixture and write to file mixture_.createBlockCRGrid(blockCFields); domain_.fieldIo().writeFieldsRGrid(filename, blockCFields, domain_.unitCell()); } /* * Write the last time slice of the propagator in r-grid format. */ template <int D> void System<D>::writeQSlice(const std::string & filename, int polymerId, int blockId, int directionId, int segmentId) const { UTIL_CHECK(polymerId >= 0); UTIL_CHECK(polymerId < mixture_.nPolymer()); Polymer<D> const& polymer = mixture_.polymer(polymerId); UTIL_CHECK(blockId >= 0); UTIL_CHECK(blockId < polymer.nBlock()); UTIL_CHECK(directionId >= 0); UTIL_CHECK(directionId <= 1); Propagator<D> const & propagator = polymer.propagator(blockId, directionId); RField<D> const& field = propagator.q(segmentId); domain_.fieldIo().writeFieldRGrid(filename, field, domain_.unitCell()); } /* * Write the last time slice of the propagator in r-grid format. */ template <int D> void System<D>::writeQTail(const std::string & filename, int polymerId, int blockId, int directionId) const { UTIL_CHECK(polymerId >= 0); UTIL_CHECK(polymerId < mixture_.nPolymer()); Polymer<D> const& polymer = mixture_.polymer(polymerId); UTIL_CHECK(blockId >= 0); UTIL_CHECK(blockId < polymer.nBlock()); UTIL_CHECK(directionId >= 0); UTIL_CHECK(directionId <= 1); RField<D> const& field = polymer.propagator(blockId, directionId).tail(); domain_.fieldIo().writeFieldRGrid(filename, field, domain_.unitCell()); } /* * Write the propagator for a block and direction. */ template <int D> void System<D>::writeQ(const std::string & filename, int polymerId, int blockId, int directionId) const { UTIL_CHECK(polymerId >= 0); UTIL_CHECK(polymerId < mixture_.nPolymer()); Polymer<D> const& polymer = mixture_.polymer(polymerId); UTIL_CHECK(blockId >= 0); UTIL_CHECK(blockId < polymer.nBlock()); UTIL_CHECK(directionId >= 0); UTIL_CHECK(directionId <= 1); Propagator<D> const& propagator = polymer.propagator(blockId, directionId); int ns = propagator.ns(); // Open file std::ofstream file; fileMaster_.openOutputFile(filename, file); // Write header fieldIo().writeFieldHeader(file, 1, domain_.unitCell()); file << "mesh " << std::endl << " " << domain_.mesh().dimensions() << std::endl << "nslice" << std::endl << " " << ns << std::endl; // Write data bool hasHeader = false; for (int i = 0; i < ns; ++i) { file << "slice " << i << std::endl; fieldIo().writeFieldRGrid(file, propagator.q(i), domain_.unitCell(), hasHeader); } file.close(); } /* * Write propagators for all blocks of all polymers to files. */ template <int D> void System<D>::writeQAll(std::string const & basename) { std::string filename; int np, nb, ip, ib, id; np = mixture_.nPolymer(); for (ip = 0; ip < np; ++ip) { nb = mixture_.polymer(ip).nBlock(); for (ib = 0; ib < nb; ++ib) { for (id = 0; id < 2; ++id) { filename = basename; filename += "_"; filename += toString(ip); filename += "_"; filename += toString(ib); filename += "_"; filename += toString(id); filename += ".rq"; writeQ(filename, ip, ib, id); } } } } /* * Write description of symmetry-adapted stars and basis to file. */ template <int D> void System<D>::writeStars(std::string const & filename) const { UTIL_CHECK(domain_.basis().isInitialized()); std::ofstream file; fileMaster_.openOutputFile(filename, file); fieldIo().writeFieldHeader(file, mixture_.nMonomer(), domain_.unitCell()); domain_.basis().outputStars(file); file.close(); } /* * Write a list of waves and associated stars to file. */ template <int D> void System<D>::writeWaves(std::string const & filename) const { UTIL_CHECK(domain_.basis().isInitialized()); std::ofstream file; fileMaster_.openOutputFile(filename, file); fieldIo().writeFieldHeader(file, mixture_.nMonomer(), domain_.unitCell()); domain_.basis().outputWaves(file); file.close(); } /* * Write all elements of the space group to a file. */ template <int D> void System<D>::writeGroup(const std::string & filename) const { Pscf::writeGroup(filename, domain_.group()); } // Field format conversion functions /* * Convert fields from symmetry-adapted basis to real-space grid format. */ template <int D> void System<D>::basisToRGrid(const std::string & inFileName, const std::string & outFileName) { // If basis fields are not allocated, peek at field file header to // get unit cell parameters, initialize basis and allocate fields. if (!isAllocatedBasis_) { readFieldHeader(inFileName); allocateFieldsBasis(); } // Read, convert, and write fields UnitCell<D> tmpUnitCell; fieldIo().readFieldsBasis(inFileName, tmpFieldsBasis_, tmpUnitCell); fieldIo().convertBasisToRGrid(tmpFieldsBasis_, tmpFieldsRGrid_); fieldIo().writeFieldsRGrid(outFileName, tmpFieldsRGrid_, tmpUnitCell); } /* * Convert fields from real-space grid to symmetry-adapted basis format. */ template <int D> void System<D>::rGridToBasis(const std::string & inFileName, const std::string & outFileName) { // If basis fields are not allocated, peek at field file header to // get unit cell parameters, initialize basis and allocate fields. if (!isAllocatedBasis_) { readFieldHeader(inFileName); allocateFieldsBasis(); } // Read, convert and write fields UnitCell<D> tmpUnitCell; fieldIo().readFieldsRGrid(inFileName, tmpFieldsRGrid_, tmpUnitCell); fieldIo().convertRGridToBasis(tmpFieldsRGrid_, tmpFieldsBasis_); fieldIo().writeFieldsBasis(outFileName, tmpFieldsBasis_, tmpUnitCell); } /* * Convert fields from Fourier (k-grid) to real-space (r-grid) format. */ template <int D> void System<D>::kGridToRGrid(const std::string & inFileName, const std::string& outFileName) { // If basis fields are not allocated, peek at field file header to // get unit cell parameters, initialize basis and allocate fields. if (!isAllocatedBasis_) { readFieldHeader(inFileName); allocateFieldsBasis(); } // Read, convert and write fields UnitCell<D> tmpUnitCell; fieldIo().readFieldsKGrid(inFileName, tmpFieldsKGrid_, tmpUnitCell); for (int i = 0; i < mixture_.nMonomer(); ++i) { domain_.fft().inverseTransform(tmpFieldsKGrid_[i], tmpFieldsRGrid_[i]); } fieldIo().writeFieldsRGrid(outFileName, tmpFieldsRGrid_, tmpUnitCell); } /* * Convert fields from real-space (r-grid) to Fourier (k-grid) format. */ template <int D> void System<D>::rGridToKGrid(const std::string & inFileName, const std::string & outFileName) { // If basis fields are not allocated, peek at field file header to // get unit cell parameters, initialize basis and allocate fields. if (!isAllocatedBasis_) { readFieldHeader(inFileName); allocateFieldsBasis(); } // Read, convert and write fields UnitCell<D> tmpUnitCell; fieldIo().readFieldsRGrid(inFileName, tmpFieldsRGrid_, tmpUnitCell); for (int i = 0; i < mixture_.nMonomer(); ++i) { domain_.fft().forwardTransform(tmpFieldsRGrid_[i], tmpFieldsKGrid_[i]); } domain_.fieldIo().writeFieldsKGrid(outFileName, tmpFieldsKGrid_, tmpUnitCell); } /* * Convert fields from Fourier (k-grid) to symmetry-adapted basis format. */ template <int D> void System<D>::kGridToBasis(const std::string & inFileName, const std::string& outFileName) { // If basis fields are not allocated, peek at field file header to // get unit cell parameters, initialize basis and allocate fields. if (!isAllocatedBasis_) { readFieldHeader(inFileName); allocateFieldsBasis(); } // Read, convert and write fields UnitCell<D> tmpUnitCell; domain_.fieldIo().readFieldsKGrid(inFileName, tmpFieldsKGrid_, tmpUnitCell); domain_.fieldIo().convertKGridToBasis(tmpFieldsKGrid_, tmpFieldsBasis_); domain_.fieldIo().writeFieldsBasis(outFileName, tmpFieldsBasis_, tmpUnitCell); } /* * Convert fields from symmetry-adapted basis to Fourier (k-grid) format. */ template <int D> void System<D>::basisToKGrid(const std::string & inFileName, const std::string & outFileName) { // If basis fields are not allocated, peek at field file header to // get unit cell parameters, initialize basis and allocate fields. if (!isAllocatedBasis_) { readFieldHeader(inFileName); allocateFieldsBasis(); } // Read, convert and write fields UnitCell<D> tmpUnitCell; domain_.fieldIo().readFieldsBasis(inFileName, tmpFieldsBasis_, tmpUnitCell); domain_.fieldIo().convertBasisToKGrid(tmpFieldsBasis_, tmpFieldsKGrid_); domain_.fieldIo().writeFieldsKGrid(outFileName, tmpFieldsKGrid_, tmpUnitCell); } /* * Convert fields from real-space grid to symmetry-adapted basis format. */ template <int D> bool System<D>::checkRGridFieldSymmetry(const std::string & inFileName, double epsilon) { // If basis fields are not allocated, peek at field file header to // get unit cell parameters, initialize basis and allocate fields. if (!isAllocatedBasis_) { readFieldHeader(inFileName); allocateFieldsBasis(); } // Read fields UnitCell<D> tmpUnitCell; domain_.fieldIo().readFieldsRGrid(inFileName, tmpFieldsRGrid_, tmpUnitCell); // Check symmetry for all fields for (int i = 0; i < mixture_.nMonomer(); ++i) { bool symmetric; symmetric = domain_.fieldIo().hasSymmetry(tmpFieldsRGrid_[i], epsilon); if (!symmetric) { return false; } } return true; } /* * Compare two fields in basis format. */ template <int D> void System<D>::compare(const DArray< DArray<double> > field1, const DArray< DArray<double> > field2) { BFieldComparison comparison(1); comparison.compare(field1,field2); Log::file() << "\n Basis expansion field comparison results" << std::endl; Log::file() << " Maximum Absolute Difference: " << comparison.maxDiff() << std::endl; Log::file() << " Root-Mean-Square Difference: " << comparison.rmsDiff() << "\n" << std::endl; } /* * Compare two fields in coordinate grid format. */ template <int D> void System<D>::compare(const DArray< RField<D> > field1, const DArray< RField<D> > field2) { RFieldComparison<D> comparison; comparison.compare(field1, field2); Log::file() << "\n Real-space field comparison results" << std::endl; Log::file() << " Maximum Absolute Difference: " << comparison.maxDiff() << std::endl; Log::file() << " Root-Mean-Square Difference: " << comparison.rmsDiff() << "\n" << std::endl; } // Private member functions /* * Allocate memory for fields. */ template <int D> void System<D>::allocateFieldsGrid() { // Preconditions UTIL_CHECK(hasMixture_); int nMonomer = mixture_.nMonomer(); UTIL_CHECK(nMonomer > 0); UTIL_CHECK(domain_.mesh().size() > 0); UTIL_CHECK(!isAllocatedRGrid_); // Alias for mesh dimensions IntVec<D> const & dimensions = domain_.mesh().dimensions(); // Allocate w (chemical potential) fields w_.setNMonomer(nMonomer); w_.allocateRGrid(dimensions); // Allocate c (monomer concentration) fields c_.setNMonomer(nMonomer); c_.allocateRGrid(dimensions); h_.setNMonomer(nMonomer); // Allocate work space field arrays tmpFieldsRGrid_.allocate(nMonomer); tmpFieldsKGrid_.allocate(nMonomer); for (int i = 0; i < nMonomer; ++i) { tmpFieldsRGrid_[i].allocate(dimensions); tmpFieldsKGrid_[i].allocate(dimensions); } isAllocatedRGrid_ = true; } /* * Allocate memory for fields. */ template <int D> void System<D>::allocateFieldsBasis() { // Preconditions and constants UTIL_CHECK(hasMixture_); const int nMonomer = mixture_.nMonomer(); UTIL_CHECK(nMonomer > 0); UTIL_CHECK(isAllocatedRGrid_); UTIL_CHECK(!isAllocatedBasis_); UTIL_CHECK(domain_.basis().isInitialized()); const int nBasis = domain_.basis().nBasis(); UTIL_CHECK(nBasis > 0); w_.allocateBasis(nBasis); c_.allocateBasis(nBasis); // Temporary work fields tmpFieldsBasis_.allocate(nMonomer); for (int i = 0; i < nMonomer; ++i) { tmpFieldsBasis_[i].allocate(nBasis); } isAllocatedBasis_ = true; } /* * Peek at field file header, initialize unit cell parameters and basis. */ template <int D> void System<D>::readFieldHeader(std::string filename) { UTIL_CHECK(hasMixture_); UTIL_CHECK(mixture_.nMonomer() > 0); // Open field file std::ifstream file; fileMaster_.openInputFile(filename, file); // Read field file header, and initialize basis if needed int nMonomer; domain_.fieldIo().readFieldHeader(file, nMonomer, domain_.unitCell()); // FieldIo::readFieldHeader initializes a basis if needed file.close(); // Postconditions UTIL_CHECK(mixture_.nMonomer() == nMonomer); UTIL_CHECK(domain_.unitCell().nParameter() > 0); UTIL_CHECK(domain_.unitCell().lattice() != UnitCell<D>::Null); UTIL_CHECK(domain_.unitCell().isInitialized()); UTIL_CHECK(domain_.basis().isInitialized()); UTIL_CHECK(domain_.basis().nBasis() > 0); } /* * Read a filename string and echo to log file (used in readCommands). */ template <int D> void System<D>::readEcho(std::istream& in, std::string& string) const { in >> string; if (in.fail()) { UTIL_THROW("Unable to read string parameter."); } Log::file() << " " << Str(string, 20) << std::endl; } /* * Read floating point number, echo to log file (used in readCommands). */ template <int D> void System<D>::readEcho(std::istream& in, double& value) const { in >> value; if (in.fail()) { UTIL_THROW("Unable to read floating point parameter."); } Log::file() << " " << Dbl(value, 20) << std::endl; } /* * Initialize the homogeneous_ member object, which describes * thermodynamics of a homogeneous reference system. */ template <int D> void System<D>::initHomogeneous() { UTIL_CHECK(hasMixture_); // Set number of molecular species and monomers int nm = mixture_.nMonomer(); int np = mixture_.nPolymer(); int ns = mixture_.nSolvent(); UTIL_CHECK(homogeneous_.nMolecule() == np + ns); UTIL_CHECK(homogeneous_.nMonomer() == nm); int i; // molecule index int j; // monomer index // Loop over polymer molecule species if (np > 0) { // Allocate array of clump sizes DArray<double> s; s.allocate(nm); int k; // block or clump index int nb; // number of blocks int nc; // number of clumps // Loop over polymer species for (i = 0; i < np; ++i) { // Initial array of clump sizes for this polymer for (j = 0; j < nm; ++j) { s[j] = 0.0; } // Compute clump sizes for all monomer types. nb = mixture_.polymer(i).nBlock(); for (k = 0; k < nb; ++k) { Block<D>& block = mixture_.polymer(i).block(k); j = block.monomerId(); s[j] += block.length(); } // Count the number of clumps of nonzero size nc = 0; for (j = 0; j < nm; ++j) { if (s[j] > 1.0E-8) { ++nc; } } homogeneous_.molecule(i).setNClump(nc); // Set clump properties for this Homogeneous::Molecule k = 0; // Clump index for (j = 0; j < nm; ++j) { if (s[j] > 1.0E-8) { homogeneous_.molecule(i).clump(k).setMonomerId(j); homogeneous_.molecule(i).clump(k).setSize(s[j]); ++k; } } homogeneous_.molecule(i).computeSize(); } } // Add solvent contributions if (ns > 0) { double size; int monomerId; for (int is = 0; is < ns; ++is) { i = is + np; monomerId = mixture_.solvent(is).monomerId(); size = mixture_.solvent(is).size(); homogeneous_.molecule(i).setNClump(1); homogeneous_.molecule(i).clump(0).setMonomerId(monomerId); homogeneous_.molecule(i).clump(0).setSize(size); homogeneous_.molecule(i).computeSize(); } } } } // namespace Pspc } // namespace Pscf #endif
51,854
C++
.tpp
1,495
25.341806
80
0.546704
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,257
IteratorFactory.tpp
dmorse_pscfpp/src/pspc/iterator/IteratorFactory.tpp
#ifndef PSPC_ITERATOR_FACTORY_TPP #define PSPC_ITERATOR_FACTORY_TPP #include "IteratorFactory.h" // Subclasses of Iterator #include "AmIterator.h" #include "FilmIterator.h" namespace Pscf { namespace Pspc { using namespace Util; /* * Constructor */ template <int D> IteratorFactory<D>::IteratorFactory(System<D>& system) : sysPtr_(&system) {} /* * Return a pointer to a instance of Iterator subclass className. */ template <int D> Iterator<D>* IteratorFactory<D>::factory(const std::string &className) const { Iterator<D>* ptr = 0; // Try subfactories first ptr = trySubfactories(className); if (ptr) return ptr; // Try to match classname if (className == "Iterator" || className == "AmIterator") { ptr = new AmIterator<D>(*sysPtr_); } else if (className == "AmIteratorFilm") { ptr = new FilmIterator<D, AmIterator<D> >(*sysPtr_); } return ptr; } } } #endif
991
C++
.tpp
37
22.189189
79
0.654295
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,258
FilmIterator.tpp
dmorse_pscfpp/src/pspc/iterator/FilmIterator.tpp
#ifndef PSPC_FILM_ITERATOR_TPP #define PSPC_FILM_ITERATOR_TPP /* * 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 "FilmIterator.h" #include "pscf/crystal/UnitCell.h" #include "pscf/math/RealVec.h" #include "pspc/System.h" namespace Pscf { namespace Pspc { using namespace Util; // 1D Partial Specializations /* * Constructor. */ template <typename IteratorType> FilmIterator<1, IteratorType>::FilmIterator(System<1>& system) : FilmIteratorBase<1, IteratorType>(system) { setClassName(iterator().className().append("Film").c_str()); } /* * Construct an array indicating whether each lattice parameter is * flexible, based on normalVecId and unitCell definitions in param * file as well as the optional user input flexibleParams. Store this * array in flexibleParams_ member of this object, as well the * flexibleParams_ member of the iterator within this object. * Uses the flexibleParams_ member of the iterator within this object * as a starting point. */ template <typename IteratorType> void FilmIterator<1, IteratorType>::setFlexibleParams() { // Create flexibleParams array FSArray<bool,6> params; params.append(false); // parameter is not flexible if (iterator().flexibleParams()[0]) { Log::file() << "Warning - The lattice parameter is not allowed " << "to be flexible for a 1D thin film system." << std::endl; } // Store params in flexibleParams_ member of this object setFlexibleParams(params); // Pass params into the iterator member of this object iterator().setFlexibleParams(params); } /* * Check that user-defined lattice basis vectors are compatible with * the thin film constraint (in 1D, there is nothing to do; the lattice * basis vector is correct in all cases). */ template <typename IteratorType> void FilmIterator<1, IteratorType>::checkLatticeVectors() const {} // do nothing // 2D Partial Specializations /* * Constructor. */ template <typename IteratorType> FilmIterator<2, IteratorType>::FilmIterator(System<2>& system) : FilmIteratorBase<2, IteratorType>(system) { setClassName(iterator().className().append("Film").c_str()); } /* * Construct an array indicating whether each lattice parameter is * flexible, based on normalVecId and unitCell definitions in param * file as well as the optional user input flexibleParams. Store this * array in flexibleParams_ member of this object, as well the * flexibleParams_ member of the iterator within this object. * Uses the flexibleParams_ member of the iterator within this object * as a starting point. */ template <typename IteratorType> void FilmIterator<2, IteratorType>::setFlexibleParams() { FSArray<bool,6> params; FSArray<bool,6> current = iterator().flexibleParams(); UTIL_CHECK(current.size() == system().unitCell().nParameter()); if (iterator().nFlexibleParams() == 0) { // lattice is already rigid setFlexibleParams(current); return; } // Initialize params to an array of false values for (int i = 0; i < current.size(); i++) { params.append(false); } // If the lattice system is square, no params are flexible. Otherwise, // params should, at most, contain only the index of the lattice basis // vector that is not normalVecId. The length of normalVecId is fixed //and gamma = 90 degrees for all 2D thin film calculations. if (system().domain().unitCell().lattice() != UnitCell<2>::Square) { for (int i = 0; i < params.size(); i++) { if ((i != normalVecId()) && (i < 2)) { params[i] = true; } } } // Store params in flexibleParams_ member of this object setFlexibleParams(params); // Before updating iterator_.flexibleParams_, check if the number // of flexible lattice parameters has changed during this function. if (nFlexibleParams() < iterator().nFlexibleParams()) { Log::file() << "***Notice - Some lattice parameters will be held constant\n" << "to comply with the thin film constraint.***" << std::endl; } // Pass params into the iterator member of this object iterator().setFlexibleParams(params); } /* * Check that user-defined lattice basis vectors are compatible with * the thin film constraint (in 2D, we require that gamma = 90°) */ template <typename IteratorType> void FilmIterator<2, IteratorType>::checkLatticeVectors() const { RealVec<2> a, b; a = system().domain().unitCell().rBasis(0); b = system().domain().unitCell().rBasis(1); double gamma = dot(a,b); if (gamma > 1e-8) { // Dot product between a and b should be 0 UTIL_THROW("ERROR: Lattice basis vectors must be orthogonal when wall is present"); } } // 3D Partial Specializations /* * Constructor. */ template <typename IteratorType> FilmIterator<3, IteratorType>::FilmIterator(System<3>& system) : FilmIteratorBase<3, IteratorType>(system) { setClassName(iterator().className().append("Film").c_str()); } /* * Construct an array indicating whether each lattice parameter is * flexible, based on normalVecId and unitCell definitions in param * file as well as the optional user input flexibleParams. Store this * array in flexibleParams_ member of this object, as well the * flexibleParams_ member of the iterator within this object. * Uses the flexibleParams_ member of the iterator within this object * as a starting point. */ template <typename IteratorType> void FilmIterator<3, IteratorType>::setFlexibleParams() { FSArray<bool,6> params; FSArray<bool,6> current = iterator().flexibleParams(); UTIL_CHECK(current.size() == system().unitCell().nParameter()); UnitCell<3>::LatticeSystem lattice = system().domain().unitCell().lattice(); // Initialize params to an array of false values for (int i = 0; i < current.size(); i++) { params.append(false); } if (iterator().nFlexibleParams() == 0) { // lattice is already rigid setFlexibleParams(params); return; } // There can be up to 3 flexible lattice parameters in 3D: the length // of the two lattice vectors that are not normalVecId, and the angle // between them. The other two angles must be 90 degrees, and the // length of normalVecId is fixed. The crystal system determines which // parameters are flexible. if (lattice == UnitCell<3>::Rhombohedral) { Log::file() << "Rhombohedral lattice systems are not compatible " << "with a thin film constraint.\n" << "See thin film documentation for more details.\n"; UTIL_THROW("Cannot use rhombohedral lattice in a thin film system."); } else if (lattice == UnitCell<3>::Hexagonal) { UTIL_CHECK(normalVecId() == 2); // this is required for hexagonal if (current[0]) { params[0] = true; // a is the only allowed flexible parameter } } else if (lattice == UnitCell<3>::Tetragonal) { // if normalVecId = 2, the only allowed flexibleParam is 0 // if normalVecId < 2, the only allowed flexibleParam is 1 if (current[0] && normalVecId() == 2) { params[0] = true; } else if (current[1] && normalVecId() < 2) { params[1] = true; } } else if (lattice != UnitCell<3>::Cubic) { for (int i = 0; i < 3; i++) { // This if-statement applies for orthorhombic/monoclinic/triclinic if (i != normalVecId() && current[i]) { params[i] = true; } } // beta can be flexible in a monoclinic lattice if normalVecId = 1 if (lattice == UnitCell<3>::Monoclinic && normalVecId() == 1 && current[3]) { params[3] = true; } // The angle between the two lattice basis vectors that are not // normalVecId can be flexible in a triclinic lattice if (lattice == UnitCell<3>::Triclinic && current[normalVecId()+3]) { params[normalVecId()+3] = true; } } // Store params in flexibleParams_ member of this object setFlexibleParams(params); // Before updating iterator_.flexibleParams_, check if the number // of flexible lattice parameters has changed during this function. if (nFlexibleParams() < iterator().nFlexibleParams()) { Log::file() << "***Notice - Some lattice parameters will be held constant\n" << "to comply with the thin film constraint.***" << std::endl; } // Pass params into the iterator member of this object iterator().setFlexibleParams(params); } /* * Check that user-defined lattice basis vectors are compatible with * the thin film constraint (in 3D, we require that there be one * lattice basis vector that is orthogonal to the walls, and two that * are parallel to the walls; the orthogonal vector is normalVecId). */ template <typename IteratorType> void FilmIterator<3, IteratorType>::checkLatticeVectors() const { RealVec<3> a, b, c; a = system().domain().unitCell().rBasis(0); b = system().domain().unitCell().rBasis(1); c = system().domain().unitCell().rBasis(2); double alpha, beta, gamma; gamma = dot(a,b); beta = dot(a,c); alpha = dot(b,c); if (normalVecId() == 0) { if (beta > 1e-8 || gamma > 1e-8) { UTIL_THROW("ERROR: If normalVecId = 0, beta and gamma must be 90 degrees"); } } else if (normalVecId() == 1) { if (alpha > 1e-8 || gamma > 1e-8) { UTIL_THROW("ERROR: If normalVecId = 1, alpha and gamma must be 90 degrees"); } } else { // normalVecId == 2 if (alpha > 1e-8 || beta > 1e-8) { UTIL_THROW("ERROR: If normalVecId = 2, alpha and beta must be 90 degrees"); } } } } // namespace Pspc } // namespace Pscf #endif
10,550
C++
.tpp
249
35.2249
92
0.641031
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,259
FilmIteratorBase.tpp
dmorse_pscfpp/src/pspc/iterator/FilmIteratorBase.tpp
#ifndef PSPC_FILM_ITERATOR_BASE_TPP #define PSPC_FILM_ITERATOR_BASE_TPP /* * 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 "FilmIteratorBase.h" #include "pscf/crystal/UnitCell.h" #include "pscf/crystal/groupFile.h" #include "pscf/math/RealVec.h" #include "pscf/crystal/SpaceGroup.h" #include "pspc/System.h" #include "pspc/field/RField.h" #include "pspc/field/FieldIo.h" #include "util/containers/FArray.h" #include "util/format/Dbl.h" #include <cmath> #include <iostream> namespace Pscf { namespace Pspc { using namespace Util; /* * Constructor. */ template <int D, typename IteratorType> FilmIteratorBase<D, IteratorType>::FilmIteratorBase(System<D>& system) : Iterator<D>(system), iterator_(system), parameters_(), normalVecId_(-1), t_(-1.0), T_(-1.0), chiBottom_(), chiTop_(), chiBottomCurrent_(), chiTopCurrent_(), ungenerated_(true) { setClassName(iterator_.className().append("FilmBase").c_str()); system.mask().setFieldIo(system.fieldIo()); system.h().setFieldIo(system.fieldIo()); } /* * Destructor. */ template <int D, typename IteratorType> FilmIteratorBase<D, IteratorType>::~FilmIteratorBase() {} /* * Read iterator and wall data from parameter file */ template <int D, typename IteratorType> void FilmIteratorBase<D, IteratorType>::readParameters(std::istream& in) { // Make iterator_ a child paramComponent of this object, so that it // will be read/written correctly to/from param file with correct // indentation setParent(iterator_,false); addComponent(iterator_,false); // Read the Iterator parameters iterator_.readParameters(in); // Read required data defining the walls read(in, "normalVecId", normalVecId_); read(in, "interfaceThickness", t_); read(in, "wallThickness", T_); // Make sure inputs are valid if (normalVecId_ > D || normalVecId_ < 0) { UTIL_THROW("bad value for normalVecId, must be in [0,D)"); } if (t_ > T_) { UTIL_THROW("wallThickness must be larger than interfaceThickness"); } if ((T_ <= 0) || (t_ <= 0)) { UTIL_THROW("wallThickness and interfaceThickness must be >0"); } // Allocate chiBottom_ and chiTop_ and set to zero before // reading them in int nm = system().mixture().nMonomer(); chiBottom_.allocate(nm); chiTop_.allocate(nm); for (int i = 0; i < nm; i++) { chiBottom_[i] = 0.0; chiTop_[i] = 0.0; } readDArray(in, "chiBottom", chiBottom_, nm); readDArray(in, "chiTop", chiTop_, nm); // If lattice parameters are flexible, determine which parameters // are allowed to vary, store them in this object, and pass them // into iterator_. The flexibleParams_ member of the iterator_ // should always be matched to that of this class. setFlexibleParams(); } /* * Allocate required memory, perform necessary checks to ensure user * input is compatible with a film constraint, and create the mask / * external fields that will be used to represent the walls during * iteration. */ template <int D, typename IteratorType> void FilmIteratorBase<D, IteratorType>::setup() { UTIL_CHECK(system().basis().isInitialized()); UTIL_CHECK(system().unitCell().isInitialized()); // Allocate the mask and external field containers if needed if (!system().mask().isAllocated()) { system().mask().allocate(system().basis().nBasis(), system().mesh().dimensions()); } if (!isAthermal()) { if (!system().h().isAllocatedRGrid()) { system().h().allocateRGrid(system().mesh().dimensions()); } if (!system().h().isAllocatedBasis()) { system().h().allocateBasis(system().basis().nBasis()); } } // Ensure that space group symmetry is compatible with the wall checkSpaceGroup(); if (ungenerated_) { // Generate the field representation of the walls (and external // fields if needed) and provide them to iterator_ to use during // iteration. generateWallFields(); ungenerated_ = false; } else { // Update the concentration field of the walls based on the // current state of Domain<D> and provide it to iterator_, as // well as the external fields for each species if needed updateWallFields(); } } /* * Iterate to a solution */ template <int D, typename IteratorType> int FilmIteratorBase<D, IteratorType>::solve(bool isContinuation) { // Setup the FilmIteratorBase object, set external fields and mask setup(); // solve return iterator_.solve(isContinuation); } /* * Generate the concentration field for the walls and pass it into * iterator. Adjust phi values of species in the system to accommodate * the volume occupied by the wall. Finally, generate the external * fields that are created by the wall, if needed (if the wall is not * athermal), and provide them to the iterator. */ template <int D, typename IteratorType> void FilmIteratorBase<D, IteratorType>::generateWallFields() { UTIL_CHECK(interfaceThickness() > 0); UTIL_CHECK(wallThickness() > interfaceThickness()); UTIL_CHECK(system().mask().isAllocated()); if (ungenerated_) ungenerated_ = false; // Ensure that unit cell is compatible with wall checkLatticeVectors(); // Get the length L of the lattice basis vector normal to the walls RealVec<D> a; a = system().domain().unitCell().rBasis(normalVecId_); double norm_sqd(0.0); // norm squared for (int i = 0; i < D; i++) { norm_sqd += a[i]*a[i]; } double L(sqrt(norm_sqd)); // Create a 3 element vector 'dim' that contains the grid dimensions. // If system is 2D (1D), then the z (y & z) dimensions are set to 1. IntVec<3> dim; for (int ind = 0; ind < 3; ind++) { if (ind < D) { dim[ind] = system().domain().mesh().dimensions()[ind]; } else { dim[ind] = 1; } } // Generate an r-grid representation of the walls RField<D> rGrid; rGrid.allocate(system().domain().mesh().dimensions()); int x, y, z; int counter = 0; FArray<int,3> coords; double d, rho_w; for (x = 0; x < dim[0]; x++) { coords[0] = x; for (y = 0; y < dim[1]; y++) { coords[1] = y; for (z = 0; z < dim[2]; z++) { coords[2] = z; // Get the distance 'd' traveled along the lattice basis // vector that is normal to the walls d = coords[normalVecId_] * L / dim[normalVecId_]; // Calculate wall volume fraction (rho_w) at gridpoint (x,y,z) rho_w = 0.5*(1+tanh(4*(((.5*(T_-L))+fabs(d-(L/2)))/t_))); rGrid[counter++] = 1-rho_w; } } } // Store this mask in System system().mask().setRGrid(rGrid,true); // Store lattice parameters associated with this maskBasis parameters_ = system().domain().unitCell().parameters(); // Generate external fields if needed generateExternalFields(); } /* * Update the mask in the iterator (the region in which the polymers are * confined) if the lattice parameters have been updated since mask was * last generated. Also update external fields. * * If the lattice parameters have not changed but the wall/polymer chi * parameters have been updated since external fields were last generated, * update the external fields (but not the mask). */ template <int D, typename IteratorType> void FilmIteratorBase<D, IteratorType>::updateWallFields() { // Check if system lattice parameters are different than parameters_ FSArray<double, 6> sysParams = system().domain().unitCell().parameters(); UTIL_CHECK(sysParams.size() == parameters_.size()); bool identical = true; // are the two arrays identical? for (int i = 0; i < parameters_.size(); i++) { if (fabs(sysParams[i] - parameters_[i]) > 1e-10) { identical = false; break; } } // Regenerate wall fields if the lattice parameters have changed if (!identical) { generateWallFields(); } else { // If we did not regenerate wall fields, check if we need to // regenerate external field (if chi array has changed) bool newExternalFields = false; // Do we need new external fields? for (int i = 0; i < chiBottom_.capacity(); i++) { if ((chiBottom_[i] != chiBottomCurrent_[i]) || (chiTop_[i] != chiTopCurrent_[i])) { newExternalFields = true; break; } } if (newExternalFields) { generateExternalFields(); } } } /* * Generate the external fields that are imposed as a result of chemical * interactions between the walls and the monomer species. */ template <int D, typename IteratorType> void FilmIteratorBase<D, IteratorType>::generateExternalFields() { // Set chiBottomCurrent_ and chiTopCurrent_ equal to the current chi // arrays associated with the external fields that are about to be set chiBottomCurrent_ = chiBottom_; chiTopCurrent_ = chiTop_; // If walls are athermal then there is no external field needed. // If an external field already exists in the System, we need to // overwrite it with a field of all zeros, otherwise do nothing if ((isAthermal()) && (!system().h().hasData())) { return; } // If this point is reached, external field must be generated UTIL_CHECK(system().h().isAllocatedRGrid()); UTIL_CHECK(system().h().isAllocatedBasis()); int nm = system().mixture().nMonomer(); // Get length L of the lattice basis vector normal to the walls RealVec<D> a; a = system().domain().unitCell().rBasis(normalVecId_); double norm_sqd(0.0); // norm squared for (int i = 0; i < D; i++) { norm_sqd += a[i]*a[i]; } double L(sqrt(norm_sqd)); // Create a 3 element vector 'dim' that contains the grid // dimensions. If system is 2D (1D), then the z (y and z) // dimensions are set to 1. IntVec<3> dim; for (int ind = 0; ind < 3; ind++) { if (ind < D) { dim[ind] = system().domain().mesh().dimensions()[ind]; } else { dim[ind] = 1; } } // Generate an r-grid representation of the external fields DArray< RField<D> > hRGrid; hRGrid.allocate(nm); for (int i = 0; i < nm; i++) { hRGrid[i].allocate(system().domain().mesh().dimensions()); } int i, x, y, z; int counter = 0; FArray<int,3> coords; double d, rho_w; for (i = 0; i < nm; i++) { for (x = 0; x < dim[0]; x++) { coords[0] = x; for (y = 0; y < dim[1]; y++) { coords[1] = y; for (z = 0; z < dim[2]; z++) { coords[2] = z; // Get the distance 'd' traveled along the lattice // basis vector that is orthogonal to the walls d = coords[normalVecId_] * L / dim[normalVecId_]; // Calculate wall volume fraction (rho_w) at gridpoint // (x,y,z) rho_w = 0.5*(1+tanh(4*(((.5*(T_-L))+fabs(d-(L/2)))/t_))); if (d < (L/2)) { hRGrid[i][counter++] = rho_w * chiBottom_[i]; } else { hRGrid[i][counter++] = rho_w * chiTop_[i]; } } } } counter = 0; } // Pass h into the System system().h().setRGrid(hRGrid,true); } /* * Check that user-defined space group is compatible * with the thin film constraint */ template <int D, typename IteratorType> void FilmIteratorBase<D, IteratorType>::checkSpaceGroup() const { // Setup std::string groupName = system().groupName(); SpaceGroup<D> group; std::ifstream in; // Open and read file containing space group's symmetry operations if (groupName == "I") { // Create identity group by default group.makeCompleteGroup(); } else { bool foundFile = false; { // Search first in this directory in.open(groupName); if (in.is_open()) { in >> group; UTIL_CHECK(group.isValid()); foundFile = true; } } if (!foundFile) { // Search in the data directory containing standard space groups std::string fileName = makeGroupFileName(D, groupName); in.open(fileName); if (in.is_open()) { in >> group; UTIL_CHECK(group.isValid()); } else { Log::file() << "\nFailed to open group file: " << fileName << "\n"; Log::file() << "\n Error: Unknown space group\n"; UTIL_THROW("Unknown space group"); } } } // Make sure all symmetry operations are allowed int nv = normalVecId(); bool symmetric = isSymmetric(); std::string msg = "Space group contains forbidden symmetry operations"; for (int i = 0; i < group.size(); i++) { for (int j = 0; j < D; j++) { int r = group[i].R(nv,j); if (j == nv) { if (r != 1) { if ((r != -1) || (!symmetric)) { UTIL_THROW(msg.c_str()); } } } else { // j != nv if (r != 0) { UTIL_THROW(msg.c_str()); } } } if (group[i].t(nv) != 0) { UTIL_THROW(msg.c_str()); } } } /* * Check whether or not the two walls are chemically identical using * the chi array. */ template <int D, typename IteratorType> bool FilmIteratorBase<D, IteratorType>::isSymmetric() const { int nm = system().mixture().nMonomer(); UTIL_CHECK(nm > 0); UTIL_CHECK(chiBottom_.capacity() == nm); UTIL_CHECK(chiTop_.capacity() == nm); for (int i = 0; i < nm; i++) { if (fabs(chiBottom_[i]-chiTop_[i]) > 1e-7) { return false; } } return true; } /* * Check whether or not the walls are athermal (only true if all values * in chi array are zero) */ template <int D, typename IteratorType> bool FilmIteratorBase<D, IteratorType>::isAthermal() const { int nm = system().mixture().nMonomer(); UTIL_CHECK(nm > 0); UTIL_CHECK(chiBottom_.capacity() == nm); UTIL_CHECK(chiTop_.capacity() == nm); for (int i = 0; i < nm; i++) { if ((fabs(chiBottom_[i]) >= 1e-7) || (fabs(chiTop_[i]) >= 1e-7)) { return false; } } return true; } } // namespace Pspc } // namespace Pscf #endif
15,712
C++
.tpp
430
28.332558
77
0.574525
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,260
AmIterator.tpp
dmorse_pscfpp/src/pspc/iterator/AmIterator.tpp
#ifndef PSPC_AM_ITERATOR_TPP #define PSPC_AM_ITERATOR_TPP /* * 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 "AmIterator.h" #include <pspc/System.h> #include <pscf/inter/Interaction.h> #include <pscf/iterator/NanException.h> #include <util/global.h> #include <cmath> namespace Pscf{ namespace Pspc{ using namespace Util; // Constructor template <int D> AmIterator<D>::AmIterator(System<D>& system) : Iterator<D>(system) { setClassName("AmIterator"); } // Destructor template <int D> AmIterator<D>::~AmIterator() { } // Read parameters from file template <int D> void AmIterator<D>::readParameters(std::istream& in) { // Call parent class readParameters AmIteratorTmpl< Iterator<D>, DArray<double> >::readParameters(in); AmIteratorTmpl< Iterator<D>, DArray<double> >::readErrorType(in); // Allocate local modified copy of Interaction class interaction_.setNMonomer(system().mixture().nMonomer()); // Default parameter values isFlexible_ = 1; scaleStress_ = 10.0; int np = system().unitCell().nParameter(); UTIL_CHECK(np > 0); UTIL_CHECK(np <= 6); UTIL_CHECK(system().unitCell().lattice() != UnitCell<D>::Null); // Read optional isFlexible boolean (true by default) readOptional(in, "isFlexible", isFlexible_); // Populate flexibleParams_ based on isFlexible_ (all 0s or all 1s), // then optionally overwrite with user input from param file if (isFlexible_) { flexibleParams_.clear(); for (int i = 0; i < np; i++) { flexibleParams_.append(true); // Set all values to true } // Read optional flexibleParams_ array to overwrite current array readOptionalFSArray(in, "flexibleParams", flexibleParams_, np); if (nFlexibleParams() == 0) isFlexible_ = false; } else { // isFlexible_ = false flexibleParams_.clear(); for (int i = 0; i < np; i++) { flexibleParams_.append(false); // Set all values to false } } // Read optional scaleStress value readOptional(in, "scaleStress", scaleStress_); } // Protected virtual function // Setup before entering iteration loop template <int D> void AmIterator<D>::setup(bool isContinuation) { AmIteratorTmpl<Iterator<D>, DArray<double> >::setup(isContinuation); interaction_.update(system().interaction()); } // Private virtual functions used to implement AM algorithm // Assign one array to another template <int D> void AmIterator<D>::setEqual(DArray<double>& a, DArray<double> const & b) { a = b; } // Compute and return inner product of two vectors. template <int D> double AmIterator<D>::dotProduct(DArray<double> const & a, DArray<double> const & b) { const int n = a.capacity(); UTIL_CHECK(b.capacity() == n); double product = 0.0; for (int i = 0; i < n; i++) { // if either value is NaN, throw NanException if (std::isnan(a[i]) || std::isnan(b[i])) { throw NanException("AmIterator::dotProduct",__FILE__,__LINE__,0); } product += a[i] * b[i]; } return product; } // Compute and return maximum element of a vector. template <int D> double AmIterator<D>::maxAbs(DArray<double> const & a) { const int n = a.capacity(); double max = 0.0; double value; for (int i = 0; i < n; i++) { value = a[i]; if (std::isnan(value)) { // if value is NaN, throw NanException throw NanException("AmIterator::dotProduct",__FILE__,__LINE__,0); } if (fabs(value) > max) { max = fabs(value); } } return max; } // Update basis template <int D> void AmIterator<D>::updateBasis(RingBuffer< DArray<double> > & basis, RingBuffer< DArray<double> > const & hists) { // Make sure at least two histories are stored UTIL_CHECK(hists.size() >= 2); const int n = hists[0].capacity(); DArray<double> newbasis; newbasis.allocate(n); // New basis vector is difference between two most recent states for (int i = 0; i < n; i++) { newbasis[i] = hists[0][i] - hists[1][i]; } basis.append(newbasis); } template <int D> void AmIterator<D>::addHistories(DArray<double>& trial, RingBuffer<DArray<double> > const & basis, DArray<double> coeffs, int nHist) { int n = trial.capacity(); for (int i = 0; i < nHist; i++) { for (int j = 0; j < n; j++) { // Not clear on the origin of the -1 factor trial[j] += coeffs[i] * -1 * basis[i][j]; } } } template <int D> void AmIterator<D>::addPredictedError(DArray<double>& fieldTrial, DArray<double> const & resTrial, double lambda) { int n = fieldTrial.capacity(); for (int i = 0; i < n; i++) { fieldTrial[i] += lambda * resTrial[i]; } } // Private virtual functions to exchange data with parent system // Does the system have an initial field guess? template <int D> bool AmIterator<D>::hasInitialGuess() { return system().w().hasData(); } // Compute and return number of elements in a residual vector template <int D> int AmIterator<D>::nElements() { const int nMonomer = system().mixture().nMonomer(); const int nBasis = system().basis().nBasis(); int nEle = nMonomer*nBasis; if (isFlexible()) { nEle += nFlexibleParams(); } return nEle; } // Get the current field from the system template <int D> void AmIterator<D>::getCurrent(DArray<double>& curr) { // Straighten out fields into linear arrays const int nMonomer = system().mixture().nMonomer(); const int nBasis = system().basis().nBasis(); const DArray< DArray<double> > * currSys = &system().w().basis(); for (int i = 0; i < nMonomer; i++) { for (int k = 0; k < nBasis; k++) { curr[i*nBasis+k] = (*currSys)[i][k]; } } const int nParam = system().unitCell().nParameter(); const FSArray<double,6> currParam = system().unitCell().parameters(); int counter = 0; for (int i = 0; i < nParam; i++) { if (flexibleParams_[i]) { curr[nMonomer*nBasis + counter] = scaleStress_*currParam[i]; counter++; } } UTIL_CHECK(counter == nFlexibleParams()); return; } // Perform the main system computation (solve the MDE) template <int D> void AmIterator<D>::evaluate() { // Solve MDEs for current omega field system().compute(); // Compute stress if required if (isFlexible()) { system().mixture().computeStress(); } } // Compute the residual for the current system state template <int D> void AmIterator<D>::getResidual(DArray<double>& resid) { const int n = nElements(); const int nMonomer = system().mixture().nMonomer(); const int nBasis = system().basis().nBasis(); // Initialize residual vector to zero for (int i = 0 ; i < n; ++i) { resid[i] = 0.0; } // Compute SCF residual vector elements for (int i = 0; i < nMonomer; ++i) { for (int j = 0; j < nMonomer; ++j) { double chi = interaction_.chi(i,j); double p = interaction_.p(i,j); DArray<double> const & c = system().c().basis(j); DArray<double> const & w = system().w().basis(j); for (int k = 0; k < nBasis; ++k) { int idx = i*nBasis + k; resid[idx] += chi*c[k] - p*w[k]; } } } // If iterator has mask, account for it in residual values if (system().hasMask()) { for (int i = 0; i < nMonomer; ++i) { for (int k = 0; k < nBasis; ++k) { int idx = i*nBasis + k; resid[idx] -= system().mask().basis()[k] / interaction_.sumChiInverse(); } } } // If iterator has external fields, account for them in the values // of the residuals if (system().hasExternalFields()) { for (int i = 0; i < nMonomer; ++i) { for (int j = 0; j < nMonomer; ++j) { for (int k = 0; k < nBasis; ++k) { int idx = i*nBasis + k; resid[idx] += interaction_.p(i,j) * system().h().basis(j)[k]; } } } } // If not canonical, account for incompressibility if (!system().mixture().isCanonical()) { if (!system().hasMask()) { for (int i = 0; i < nMonomer; ++i) { resid[i*nBasis] -= 1.0 / interaction_.sumChiInverse(); } } } else { // Explicitly set homogeneous residual components for (int i = 0; i < nMonomer; ++i) { resid[i*nBasis] = 0.0; } } // If variable unit cell, compute stress residuals if (isFlexible()) { const int nParam = system().unitCell().nParameter(); // Combined -1 factor and stress scaling here. This is okay: // - residuals only show up as dot products (U, v, norm) // or with their absolute value taken (max), so the // sign on a given residual vector element is not relevant // as long as it is consistent across all vectors // - The scaling is applied here and to the unit cell param // storage, so that updating is done on the same scale, // and then undone right before passing to the unit cell. int counter = 0; for (int i = 0; i < nParam ; i++) { if (flexibleParams_[i]) { resid[nMonomer*nBasis + counter] = scaleStress_ * -1 * system().mixture().stress(i); counter++; } } UTIL_CHECK(counter == nFlexibleParams()); } } // Update the current system field coordinates template <int D> void AmIterator<D>::update(DArray<double>& newGuess) { // Convert back to field format const int nMonomer = system().mixture().nMonomer(); const int nBasis = system().basis().nBasis(); DArray< DArray<double> > wField; wField.allocate(nMonomer); // Restructure in format of monomers, basis functions for (int i = 0; i < nMonomer; i++) { wField[i].allocate(nBasis); for (int k = 0; k < nBasis; k++) { wField[i][k] = newGuess[i*nBasis + k]; } } // If canonical, explicitly set homogeneous field components if (system().mixture().isCanonical()) { double chi; for (int i = 0; i < nMonomer; ++i) { wField[i][0] = 0.0; // initialize to 0 for (int j = 0; j < nMonomer; ++j) { chi = interaction_.chi(i,j); wField[i][0] += chi * system().c().basis(j)[0]; } } // If iterator has external fields, include them in homogeneous field if (system().hasExternalFields()) { for (int i = 0; i < nMonomer; ++i) { wField[i][0] += system().h().basis(i)[0]; } } } system().setWBasis(wField); if (isFlexible()) { const int nParam = system().unitCell().nParameter(); FSArray<double,6> parameters = system().unitCell().parameters(); int counter = 0; for (int i = 0; i < nParam; i++) { if (flexibleParams_[i]) { parameters[i] = 1.0/scaleStress_ * newGuess[nMonomer*nBasis + counter]; counter++; } } UTIL_CHECK(counter == nFlexibleParams()); system().setUnitCell(parameters); } } template<int D> void AmIterator<D>::outputToLog() { if (isFlexible() && verbose() > 1) { const int nParam = system().unitCell().nParameter(); for (int i = 0; i < nParam; i++) { if (flexibleParams_[i]) { Log::file() << " Cell Param " << i << " = " << Dbl(system().unitCell().parameters()[i], 15) << " , stress = " << Dbl(system().mixture().stress(i), 15) << "\n"; } } } } } } #endif
13,008
C++
.tpp
358
27.460894
78
0.546891
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,261
Propagator.tpp
dmorse_pscfpp/src/pspc/solvers/Propagator.tpp
#ifndef PSPC_PROPAGATOR_TPP #define PSPC_PROPAGATOR_TPP /* * 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" #include "Block.h" #include <pscf/mesh/Mesh.h> namespace Pscf { namespace Pspc { using namespace Util; /* * Constructor. */ template <int D> Propagator<D>::Propagator() : blockPtr_(0), meshPtr_(0), ns_(0), isAllocated_(false) {} /* * Destructor. */ template <int D> Propagator<D>::~Propagator() {} /* * Allocate memory used by this propagator. */ template <int D> void Propagator<D>::allocate(int ns, const Mesh<D>& mesh) { UTIL_CHECK(!isAllocated_); ns_ = ns; meshPtr_ = &mesh; qFields_.allocate(ns); for (int i = 0; i < ns; ++i) { qFields_[i].allocate(mesh.dimensions()); } isAllocated_ = true; } /* * Reallocate memory used by this propagator using new ns value. */ template <int D> void Propagator<D>::reallocate(int ns) { UTIL_CHECK(isAllocated_); UTIL_CHECK(ns_ != ns); ns_ = ns; // Deallocate all memory previously used by this propagator. qFields_.deallocate(); // NOTE: The qFields_ container is a DArray<QField>, where QField // is a typedef for DFields<D>. The DArray::deallocate() function // calls "delete [] ptr", where ptr is a pointer to the underlying // C array. The C++ delete [] command calls the destructor for // each element in an array before deleting the array itself. // The RField<D> destructor deletes the the double* array that // stores the field associated with each slice of the propagator. // Allocate new memory for qFields_ using new value of ns qFields_.allocate(ns); for (int i = 0; i < ns; ++i) { qFields_[i].allocate(meshPtr_->dimensions()); } } /* * Compute initial head QField from final tail QFields of sources. */ template <int D> void Propagator<D>::computeHead() { // Reference to head of this propagator QField& qh = qFields_[0]; // Initialize qh field to 1.0 at all grid points int ix; int nx = meshPtr_->size(); for (ix = 0; ix < nx; ++ix) { qh[ix] = 1.0; } // Pointwise multiply tail QFields of all sources for (int is = 0; is < nSource(); ++is) { if (!source(is).isSolved()) { UTIL_THROW("Source not solved in computeHead"); } QField const& qt = source(is).tail(); for (ix = 0; ix < nx; ++ix) { qh[ix] *= qt[ix]; } } } /* * Solve the modified diffusion equation for this block. */ template <int D> void Propagator<D>::solve() { UTIL_CHECK(isAllocated()); computeHead(); for (int iStep = 0; iStep < ns_ - 1; ++iStep) { block().step(qFields_[iStep], qFields_[iStep + 1]); } setIsSolved(true); } /* * Solve the modified diffusion equation with a specified initial condition. */ template <int D> void Propagator<D>::solve(QField const & head) { int nx = meshPtr_->size(); UTIL_CHECK(head.capacity() == nx); // Initialize initial (head) field QField& qh = qFields_[0]; for (int i = 0; i < nx; ++i) { qh[i] = head[i]; } // Setup solver and solve for (int iStep = 0; iStep < ns_ - 1; ++iStep) { block().step(qFields_[iStep], qFields_[iStep + 1]); } setIsSolved(true); } /* * Compute spatial average of product of head and tail of partner. */ template <int D> double Propagator<D>::computeQ() { // Preconditions if (!isSolved()) { UTIL_THROW("Propagator is not solved."); } if (!hasPartner()) { UTIL_THROW("Propagator has no partner set."); } if (!partner().isSolved()) { UTIL_THROW("Partner propagator is not solved"); } QField const& qh = head(); QField const& qt = partner().tail(); int nx = meshPtr_->size(); UTIL_CHECK(qt.capacity() == nx); UTIL_CHECK(qh.capacity() == nx); // Take inner product of head and partner tail fields double Q = 0; for (int i =0; i < nx; ++i) { Q += qh[i]*qt[i]; } Q /= double(nx); return Q; } } } #endif
4,513
C++
.tpp
158
22.708861
78
0.584161
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,262
Polymer.tpp
dmorse_pscfpp/src/pspc/solvers/Polymer.tpp
#ifndef PSPC_POLYMER_TPP #define PSPC_POLYMER_TPP /* * 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" namespace Pscf { namespace Pspc { template <int D> Polymer<D>::Polymer() { setClassName("Polymer");} template <int D> Polymer<D>::~Polymer() {} template <int D> void Polymer<D>::setPhi(double phi) { UTIL_CHECK(ensemble() == Species::Closed); UTIL_CHECK(phi >= 0.0); UTIL_CHECK(phi <= 1.0); phi_ = phi; } template <int D> void Polymer<D>::setMu(double mu) { UTIL_CHECK(ensemble() == Species::Open); mu_ = mu; } /* * Set unit cell dimensions in all solvers. */ template <int D> void Polymer<D>::setupUnitCell(UnitCell<D> const & unitCell) { // Set association to unitCell unitCellPtr_ = &unitCell; for (int j = 0; j < nBlock(); ++j) { block(j).setupUnitCell(unitCell); } } /* * Compute solution to MDE and block concentrations. */ template <int D> void Polymer<D>::compute(DArray< RField<D> > const & wFields, double phiTot) { // Setup solvers for all blocks int monomerId; for (int j = 0; j < nBlock(); ++j) { monomerId = block(j).monomerId(); block(j).setupSolver(wFields[monomerId]); } // Call base class PolymerTmpl solve() function solve(phiTot); } /* * Compute stress from a polymer chain. */ template <int D> void Polymer<D>::computeStress() { // Initialize all stress_ elements zero for (int i = 0; i < 6; ++i) { stress_[i] = 0.0; } // Compute and accumulate stress contributions from all blocks double prefactor = exp(mu_)/length(); for (int i = 0; i < nBlock(); ++i) { block(i).computeStress(prefactor); for (int j = 0; j < unitCellPtr_->nParameter() ; ++j){ stress_[j] += block(i).stress(j); } } } } } #endif
2,155
C++
.tpp
81
20.938272
68
0.588407
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,263
Mixture.tpp
dmorse_pscfpp/src/pspc/solvers/Mixture.tpp
#ifndef PSPC_MIXTURE_TPP #define PSPC_MIXTURE_TPP /* * 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 "Mixture.h" #include <pscf/mesh/Mesh.h> #include <cmath> namespace Pscf { namespace Pspc { template <int D> Mixture<D>::Mixture() : ds_(-1.0), meshPtr_(0), unitCellPtr_(0), hasStress_(false) { setClassName("Mixture"); } template <int D> Mixture<D>::~Mixture() {} template <int D> void Mixture<D>::readParameters(std::istream& in) { MixtureTmpl< Polymer<D>, Solvent<D> >::readParameters(in); read(in, "ds", ds_); UTIL_CHECK(nMonomer() > 0); UTIL_CHECK(nPolymer()+ nSolvent() > 0); UTIL_CHECK(ds_ > 0); } template <int D> void Mixture<D>::setMesh(Mesh<D> const& mesh) { UTIL_CHECK(nMonomer() > 0); UTIL_CHECK(nPolymer()+ nSolvent() > 0); UTIL_CHECK(ds_ > 0); // Save address of mesh meshPtr_ = &mesh; // Set discretization in space and s for all polymer blocks if (nPolymer() > 0) { int i, j; for (i = 0; i < nPolymer(); ++i) { for (j = 0; j < polymer(i).nBlock(); ++j) { polymer(i).block(j).setDiscretization(ds_, mesh); } } } // Set spatial discretization for solvents if (nSolvent() > 0) { for (int i = 0; i < nSolvent(); ++i) { solvent(i).setDiscretization(mesh); } } } template <int D> void Mixture<D>::setupUnitCell(const UnitCell<D>& unitCell) { // Set association of unitCell to this Mixture unitCellPtr_ = &unitCell; // SetupUnitCell for all polymers if (nPolymer() > 0) { for (int i = 0; i < nPolymer(); ++i) { polymer(i).setupUnitCell(unitCell); } } hasStress_ = false; } /* * Reset statistical segment length for one monomer type. */ template <int D> void Mixture<D>::setKuhn(int monomerId, double kuhn) { // Set new Kuhn length for relevant Monomer object monomer(monomerId).setKuhn(kuhn); // Update kuhn length for all blocks of this monomer type for (int i = 0; i < nPolymer(); ++i) { for (int j = 0; j < polymer(i).nBlock(); ++j) { if (monomerId == polymer(i).block(j).monomerId()) { polymer(i).block(j).setKuhn(kuhn); } } } hasStress_ = false; } /* * Compute concentrations (but not total free energy). */ template <int D> void Mixture<D>::compute(DArray< RField<D> > const & wFields, DArray< RField<D> > & cFields, double phiTot) { UTIL_CHECK(meshPtr_); UTIL_CHECK(mesh().size() > 0); UTIL_CHECK(nMonomer() > 0); UTIL_CHECK(nPolymer() + nSolvent() > 0); UTIL_CHECK(wFields.capacity() == nMonomer()); UTIL_CHECK(cFields.capacity() == nMonomer()); int nMesh = mesh().size(); int nm = nMonomer(); int i, j, k; // Clear all monomer concentration fields, check capacities for (i = 0; i < nm; ++i) { UTIL_CHECK(cFields[i].capacity() == nMesh); UTIL_CHECK(wFields[i].capacity() == nMesh); for (j = 0; j < nMesh; ++j) { cFields[i][j] = 0.0; } } // Process polymer species // Solve MDE for all polymers for (i = 0; i < nPolymer(); ++i) { polymer(i).compute(wFields, phiTot); } // Accumulate block contributions to monomer concentrations int monomerId; for (i = 0; i < nPolymer(); ++i) { for (j = 0; j < polymer(i).nBlock(); ++j) { monomerId = polymer(i).block(j).monomerId(); UTIL_CHECK(monomerId >= 0); UTIL_CHECK(monomerId < nm); RField<D>& monomerField = cFields[monomerId]; RField<D> const & blockField = polymer(i).block(j).cField(); UTIL_CHECK(blockField.capacity() == nMesh); for (k = 0; k < nMesh; ++k) { monomerField[k] += blockField[k]; } } } // Process solvent species // For each solvent, call compute and accumulate cFields for (i = 0; i < nSolvent(); ++i) { monomerId = solvent(i).monomerId(); UTIL_CHECK(monomerId >= 0); UTIL_CHECK(monomerId < nm); // Compute solvent concentration solvent(i).compute(wFields[monomerId], phiTot); // Add solvent contribution to relevant monomer concentration RField<D>& monomerField = cFields[monomerId]; RField<D> const & solventField = solvent(i).cField(); UTIL_CHECK(solventField.capacity() == nMesh); for (k = 0; k < nMesh; ++k) { monomerField[k] += solventField[k]; } } hasStress_ = false; } /* * Compute total stress for this mixture. */ template <int D> void Mixture<D>::computeStress() { int i, j; // Initialize all stress components to zero for (i = 0; i < 6; ++i) { stress_[i] = 0.0; } if (nPolymer() > 0) { // Compute stress for all polymers, after solving MDE for (i = 0; i < nPolymer(); ++i) { polymer(i).computeStress(); } // Accumulate stress for all the polymer chains for (i = 0; i < unitCellPtr_->nParameter(); ++i) { for (j = 0; j < nPolymer(); ++j) { stress_[i] += polymer(j).stress(i); } } } // Note: Solvent does not contribute to derivatives of f_Helmholtz // with respect to unit cell parameters at fixed volume fractions. hasStress_ = true; } template <int D> bool Mixture<D>::isCanonical() { // Check ensemble of all polymers for (int i = 0; i < nPolymer(); ++i) { if (polymer(i).ensemble() == Species::Open) { return false; } } // Check ensemble of all solvents for (int i = 0; i < nSolvent(); ++i) { if (solvent(i).ensemble() == Species::Open) { return false; } } // Returns true if false was never returned return true; } /* * Combine cFields for each block (and solvent) into one DArray */ template <int D> void Mixture<D>::createBlockCRGrid(DArray< RField<D> >& blockCFields) const { UTIL_CHECK(nMonomer() > 0); UTIL_CHECK(nBlock() + nSolvent() > 0); int np = nSolvent() + nBlock(); int nx = mesh().size(); int i, j; UTIL_CHECK(blockCFields.capacity() == nBlock() + nSolvent()); // Clear all monomer concentration fields, check capacities for (i = 0; i < np; ++i) { UTIL_CHECK(blockCFields[i].capacity() == nx); for (j = 0; j < nx; ++j) { blockCFields[i][j] = 0.0; } } // Process polymer species int sectionId = -1; if (nPolymer() > 0) { // Write each block's r-grid data to blockCFields for (i = 0; i < nPolymer(); ++i) { for (j = 0; j < polymer(i).nBlock(); ++j) { sectionId++; UTIL_CHECK(sectionId >= 0); UTIL_CHECK(sectionId < np); UTIL_CHECK(blockCFields[sectionId].capacity() == nx); blockCFields[sectionId] = polymer(i).block(j).cField(); } } } // Process solvent species if (nSolvent() > 0) { // Write each solvent's r-grid data to blockCFields for (i = 0; i < nSolvent(); ++i) { sectionId++; UTIL_CHECK(sectionId >= 0); UTIL_CHECK(sectionId < np); UTIL_CHECK(blockCFields[sectionId].capacity() == nx); blockCFields[sectionId] = solvent(i).cField(); } } } } // namespace Pspc } // namespace Pscf #endif
8,058
C++
.tpp
246
24.792683
72
0.544353
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,264
Block.tpp
dmorse_pscfpp/src/pspc/solvers/Block.tpp
#ifndef PSPC_BLOCK_TPP #define PSPC_BLOCK_TPP /* * 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 <pscf/mesh/Mesh.h> #include <pscf/mesh/MeshIterator.h> #include <pscf/crystal/UnitCell.h> #include <pscf/crystal/shiftToMinimum.h> #include <pscf/math/IntVec.h> #include <util/containers/DMatrix.h> #include <util/containers/DArray.h> #include <util/containers/FArray.h> #include <util/containers/FSArray.h> namespace Pscf { namespace Pspc { using namespace Util; /* * Constructor. */ template <int D> Block<D>::Block() : meshPtr_(0), kMeshDimensions_(0), ds_(0.0), dsTarget_(0.0), ns_(0), isAllocated_(false), hasExpKsq_(false) { propagator(0).setBlock(*this); propagator(1).setBlock(*this); } /* * Destructor. */ template <int D> Block<D>::~Block() {} template <int D> void Block<D>::setDiscretization(double ds, const Mesh<D>& mesh) { // Preconditions UTIL_CHECK(mesh.size() > 1); UTIL_CHECK(ds > 0.0); UTIL_CHECK(!isAllocated_); // Set contour length discretization dsTarget_ = ds; int tempNs; tempNs = floor( length()/(2.0 *ds) + 0.5 ); if (tempNs == 0) { tempNs = 1; } ns_ = 2*tempNs + 1; ds_ = length()/double(ns_-1); // Set association to mesh meshPtr_ = &mesh; fft_.setup(mesh.dimensions()); // Compute Fourier space kMeshDimensions_ for (int i = 0; i < D; ++i) { if (i < D - 1) { kMeshDimensions_[i] = mesh.dimensions()[i]; } else { kMeshDimensions_[i] = mesh.dimensions()[i]/2 + 1; } } // Set number kSize of points in k-space mesh int kSize = 1; for (int i = 0; i < D; ++i) { kSize *= kMeshDimensions_[i]; } // Allocate work arrays for MDE solution expKsq_.allocate(kMeshDimensions_); expKsq2_.allocate(kMeshDimensions_); expW_.allocate(mesh.dimensions()); expW2_.allocate(mesh.dimensions()); qr_.allocate(mesh.dimensions()); qk_.allocate(mesh.dimensions()); qr2_.allocate(mesh.dimensions()); qk2_.allocate(mesh.dimensions()); // Allocate work array for stress calculation dGsq_.allocate(kSize, 6); // Allocate block concentration field cField().allocate(mesh.dimensions()); // Allocate memory for solutions to MDE (requires ns_) propagator(0).allocate(ns_, mesh); propagator(1).allocate(ns_, mesh); isAllocated_ = true; hasExpKsq_ = false; } /* * Set or reset the the block length. */ template <int D> void Block<D>::setLength(double newLength) { BlockDescriptor::setLength(newLength); if (isAllocated_) { // if setDiscretization has already been called // Reset contour length discretization UTIL_CHECK(dsTarget_ > 0); int oldNs = ns_; int tempNs; tempNs = floor( length()/(2.0 *dsTarget_) + 0.5 ); if (tempNs == 0) { tempNs = 1; } ns_ = 2*tempNs + 1; ds_ = length()/double(ns_-1); if (oldNs != ns_) { // If propagators are already allocated and ns_ has changed, // reallocate memory for solutions to MDE propagator(0).reallocate(ns_); propagator(1).reallocate(ns_); } } hasExpKsq_ = false; } /* * Set or reset the the block length. */ template <int D> void Block<D>::setKuhn(double kuhn) { BlockTmpl< Propagator<D> >::setKuhn(kuhn); hasExpKsq_ = false; } /* * Setup data that depend on the unit cell parameters. */ template <int D> void Block<D>::setupUnitCell(const UnitCell<D>& unitCell) { unitCellPtr_ = &unitCell; hasExpKsq_ = false; } template <int D> void Block<D>::computeExpKsq() { UTIL_CHECK(isAllocated_); UTIL_CHECK(unitCellPtr_); UTIL_CHECK(unitCellPtr_->isInitialized()); MeshIterator<D> iter; iter.setDimensions(kMeshDimensions_); IntVec<D> G, Gmin; double Gsq; double factor = -1.0*kuhn()*kuhn()*ds_/6.0; int i; for (iter.begin(); !iter.atEnd(); ++iter) { i = iter.rank(); G = iter.position(); Gmin = shiftToMinimum(G, mesh().dimensions(), unitCell()); Gsq = unitCell().ksq(Gmin); expKsq_[i] = exp(Gsq*factor); expKsq2_[i] = exp(Gsq*factor*0.5); } hasExpKsq_ = true; } /* * Setup the contour length step algorithm. */ template <int D> void Block<D>::setupSolver(RField<D> const& w) { // Preconditions int nx = mesh().size(); UTIL_CHECK(nx > 0); UTIL_CHECK(isAllocated_); // Compute expW arrays for (int i = 0; i < nx; ++i) { // First, check that w[i]*ds_ is not unreasonably large: // (if this condition is not met, solution will have large // error, and user should consider using a smaller ds_) //UTIL_CHECK(std::abs(w[i]*ds_) < 1.0); // Calculate values expW_[i] = exp(-0.5*w[i]*ds_); expW2_[i] = exp(-0.5*0.5*w[i]*ds_); } // Compute expKsq arrays if necessary if (!hasExpKsq_) { computeExpKsq(); } } /* * Integrate to calculate monomer concentration for this block */ template <int D> void Block<D>::computeConcentration(double prefactor) { // Preconditions UTIL_CHECK(isAllocated_); int nx = mesh().size(); UTIL_CHECK(nx > 0); UTIL_CHECK(ns_ > 0); UTIL_CHECK(ds_ > 0); UTIL_CHECK(propagator(0).isAllocated()); UTIL_CHECK(propagator(1).isAllocated()); UTIL_CHECK(cField().capacity() == nx); // Initialize cField to zero at all points int i; for (i = 0; i < nx; ++i) { cField()[i] = 0.0; } Propagator<D> const & p0 = propagator(0); Propagator<D> const & p1 = propagator(1); // Evaluate unnormalized integral // Endpoint contributions for (i = 0; i < nx; ++i) { cField()[i] += p0.q(0)[i]*p1.q(ns_ - 1)[i]; cField()[i] += p0.q(ns_ -1)[i]*p1.q(0)[i]; } // Odd indices int j; for (j = 1; j < (ns_ -1); j += 2) { for (i = 0; i < nx; ++i) { cField()[i] += p0.q(j)[i] * p1.q(ns_ - 1 - j)[i] * 4.0; } } // Even indices for (j = 2; j < (ns_ -2); j += 2) { for (i = 0; i < nx; ++i) { cField()[i] += p0.q(j)[i] * p1.q(ns_ - 1 - j)[i] * 2.0; } } // Normalize the integral prefactor *= ds_ / 3.0; for (i = 0; i < nx; ++i) { cField()[i] *= prefactor; } } /* * Integrate to Stress exerted by the chain for this block */ template <int D> void Block<D>::computeStress(double prefactor) { // Preconditions int nx = mesh().size(); UTIL_CHECK(nx > 0); UTIL_CHECK(ns_ > 0); UTIL_CHECK(ds_ > 0); UTIL_CHECK(propagator(0).isAllocated()); UTIL_CHECK(propagator(1).isAllocated()); stress_.clear(); double dels, normal, increment; int nParam, c, m; normal = 3.0*6.0; int kSize_ = 1; for (int i = 0; i < D; ++i) { kSize_ *= kMeshDimensions_[i]; } nParam = unitCell().nParameter(); c = kSize_; FSArray<double, 6> dQ; // Initialize work array and stress_ to zero at all points int i; for (i = 0; i < nParam; ++i) { dQ.append(0.0); stress_.append(0.0); } computedGsq(); Propagator<D> const & p0 = propagator(0); Propagator<D> const & p1 = propagator(1); // Evaluate unnormalized integral for (int j = 0; j < ns_ ; ++j) { qr_ = p0.q(j); fft_.forwardTransform(qr_, qk_); qr2_ = p1.q(ns_ - 1 - j); fft_.forwardTransform(qr2_, qk2_); dels = ds_; if (j != 0 && j != ns_ - 1) { if (j % 2 == 0) { dels = dels*2.0; } else { dels = dels*4.0; } } for (int n = 0; n < nParam ; ++n) { increment = 0.0; for (m = 0; m < c ; ++m) { double prod = 0; prod = (qk2_[m][0] * qk_[m][0]) + (qk2_[m][1] * qk_[m][1]); prod *= dGsq_(m,n); increment += prod; } increment = (increment * kuhn() * kuhn() * dels)/normal; dQ[n] = dQ[n] - increment; } } // Normalize for (i = 0; i < nParam; ++i) { stress_[i] = stress_[i] - (dQ[i] * prefactor); } } /* * Compute dGsq_ array (derivatives of Gsq for all wavevectors) */ template <int D> void Block<D>::computedGsq() { IntVec<D> temp; IntVec<D> vec; IntVec<D> Partner; MeshIterator<D> iter; iter.setDimensions(kMeshDimensions_); for (int n = 0; n < unitCell().nParameter() ; ++n) { for (iter.begin(); !iter.atEnd(); ++iter) { temp = iter.position(); vec = shiftToMinimum(temp, mesh().dimensions(), unitCell()); dGsq_(iter.rank(), n) = unitCell().dksq(vec, n); for (int p = 0; p < D; ++p) { if (temp [p] != 0) { Partner[p] = mesh().dimensions()[p] - temp[p]; } else { Partner[p] = 0; } } if (Partner[D-1] > kMeshDimensions_[D-1]) { dGsq_(iter.rank(), n) *= 2; } } } } /* * Propagate solution by one step. */ template <int D> void Block<D>::step(RField<D> const & q, RField<D>& qNew) { // Internal prereconditions UTIL_CHECK(isAllocated_); int nx = mesh().size(); int nk = qk_.capacity(); UTIL_CHECK(nx > 0); UTIL_CHECK(nk > 0); UTIL_CHECK(qr_.capacity() == nx); UTIL_CHECK(expW_.capacity() == nx); UTIL_CHECK(expKsq_.capacity() == nk); UTIL_CHECK(hasExpKsq_); // Preconditions on parameters UTIL_CHECK(q.isAllocated()); UTIL_CHECK(q.capacity() == nx); UTIL_CHECK(qNew.isAllocated()); UTIL_CHECK(qNew.capacity() == nx); // Apply pseudo-spectral algorithm // Full step for ds, half-step for ds/2 int i; for (i = 0; i < nx; ++i) { qr_[i] = q[i]*expW_[i]; qr2_[i] = q[i]*expW2_[i]; } fft_.forwardTransform(qr_, qk_); fft_.forwardTransform(qr2_, qk2_); for (i = 0; i < nk; ++i) { qk_[i][0] *= expKsq_[i]; qk_[i][1] *= expKsq_[i]; qk2_[i][0] *= expKsq2_[i]; qk2_[i][1] *= expKsq2_[i]; } fft_.inverseTransform(qk_, qr_); fft_.inverseTransform(qk2_, qr2_); for (i = 0; i < nx; ++i) { qr_[i] = qr_[i]*expW_[i]; qr2_[i] = qr2_[i]*expW_[i]; } // Finish second half-step for ds/2 fft_.forwardTransform(qr2_, qk2_); for (i = 0; i < nk; ++i) { qk2_[i][0] *= expKsq2_[i]; qk2_[i][1] *= expKsq2_[i]; } fft_.inverseTransform(qk2_, qr2_); for (i = 0; i < nx; ++i) { qr2_[i] = qr2_[i]*expW2_[i]; } // Richardson extrapolation for (i = 0; i < nx; ++i) { qNew[i] = (4.0*qr2_[i] - qr_[i])/3.0; } } } } #endif
11,648
C++
.tpp
387
22.682171
74
0.52312
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,265
Solvent.tpp
dmorse_pscfpp/src/pspc/solvers/Solvent.tpp
#ifndef PSPC_SOLVENT_TPP #define PSPC_SOLVENT_TPP /* * 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 "Solvent.h" #include <pscf/mesh/Mesh.h> namespace Pscf { namespace Pspc { /* * Constructor */ template <int D> Solvent<D>::Solvent() : SolventDescriptor() { setClassName("Solvent"); } /* * Destructor */ template <int D> Solvent<D>::~Solvent() {} /* * Create an association with a Mesh & allocate the concentration field. */ template <int D> void Solvent<D>::setDiscretization(Mesh<D> const & mesh) { meshPtr_ = &mesh; cField_.allocate(mesh.dimensions()); } /* * Compute concentration, q, and phi or mu. */ template <int D> void Solvent<D>::compute(RField<D> const & wField, double phiTot) { int nx = meshPtr_->size(); // Number of grid points // Initialize cField_ to zero for (int i = 0; i < nx; ++i) { cField_[i] = 0.0; } // Evaluate unnormalized integral and q_ double s = size(); q_ = 0.0; for (int i = 0; i < nx; ++i) { cField_[i] = exp(-s*wField[i]); q_ += cField_[i]; } q_ = q_/double(nx); // spatial average q_ = q_/phiTot; // correct for partial occupation // Note: phiTot = 1.0 except in the case of a mask that confines // material to a fraction of the unit cell. // Compute mu_ or phi_ and prefactor double prefactor; if (ensemble_ == Species::Closed) { prefactor = phi_/q_; mu_ = log(prefactor); } else { prefactor = exp(mu_); phi_ = prefactor*q_; } // Normalize concentration for (int i = 0; i < nx; ++i) { cField_[i] *= prefactor; } } } } #endif
1,932
C++
.tpp
73
21.109589
74
0.581749
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,266
FieldState.tpp
dmorse_pscfpp/src/pspc/sweep/FieldState.tpp
#ifndef PSPC_FIELD_STATE_TPP #define PSPC_FIELD_STATE_TPP /* * 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 "FieldState.h" #include <pspc/System.h> #include <pspc/field/FFT.h> #include <pscf/mesh/Mesh.h> #include <pscf/crystal/Basis.h> #include <util/misc/FileMaster.h> // #include <util/format/Str.h> // #include <util/format/Int.h> // #include <util/format/Dbl.h> namespace Pscf { namespace Pspc { using namespace Util; /* * Constructor. */ template <int D, class FT> FieldState<D, FT>::FieldState() : fields_(), unitCell_(), systemPtr_(0) {} /* * Constructor. */ template <int D, class FT> FieldState<D, FT>::FieldState(System<D>& system) : fields_(), unitCell_(), systemPtr_(0) { setSystem(system); } /* * Destructor. */ template <int D, class FT> FieldState<D, FT>::~FieldState() {} /* * Set association with system, after default construction. */ template <int D, class FT> void FieldState<D, FT>::setSystem(System<D>& system) { if (hasSystem()) { UTIL_CHECK(systemPtr_ = &system); } else { systemPtr_ = &system; } } } // namespace Pspc } // namespace Pscf #endif
1,444
C++
.tpp
60
19.266667
67
0.616338
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,267
LinearSweep.tpp
dmorse_pscfpp/src/pspc/sweep/LinearSweep.tpp
#ifndef PSPC_LINEAR_SWEEP_TPP #define PSPC_LINEAR_SWEEP_TPP /* * 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 "LinearSweep.h" #include <pspc/System.h> #include <cstdio> namespace Pscf { namespace Pspc { using namespace Util; template <int D> LinearSweep<D>::LinearSweep(System<D>& system) : Sweep<D>(system) {} template <int D> void LinearSweep<D>::readParameters(std::istream& in) { // Call the base class's readParameters function. Sweep<D>::readParameters(in); // Read in the number of sweep parameters and allocate. this->read(in, "nParameter", nParameter_); parameters_.allocate(nParameter_); // Read in array of SweepParameters, calling << for each this->template readDArray< SweepParameter<D> >(in, "parameters", parameters_, nParameter_); // Verify net zero change in volume fractions if being swept double sum = 0.0; for (int i = 0; i < nParameter_; ++i) { if (parameters_[i].type() == "phi_polymer" || parameters_[i].type() == "phi_solvent") { sum += parameters_[i].change(); } } UTIL_CHECK(sum > -0.000001); UTIL_CHECK(sum < 0.000001); } template <int D> void LinearSweep<D>::setup() { // Verify that the LinearSweep has a system pointer UTIL_CHECK(hasSystem()); // Call base class's setup function Sweep<D>::setup(); // Set system pointer and initial value for each parameter object for (int i = 0; i < nParameter_; ++i) { parameters_[i].setSystem(system()); parameters_[i].getInitial(); } } template <int D> void LinearSweep<D>::setParameters(double s) { // Update the system parameter values double newVal; for (int i = 0; i < nParameter_; ++i) { newVal = parameters_[i].initial() + s*parameters_[i].change(); parameters_[i].update(newVal); } } template <int D> void LinearSweep<D>::outputSummary(std::ostream& out) {} } } #endif
2,194
C++
.tpp
67
27.208955
97
0.641663
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,268
BasisFieldState.tpp
dmorse_pscfpp/src/pspc/sweep/BasisFieldState.tpp
#ifndef PSPC_BASIS_FIELD_STATE_TPP #define PSPC_BASIS_FIELD_STATE_TPP /* * 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 "BasisFieldState.h" #include "FieldState.tpp" #include <util/global.h> namespace Pscf { namespace Pspc { using namespace Util; /* * Default constructor. */ template <int D> BasisFieldState<D>::BasisFieldState() : FieldState<D, DArray<double> >() {} /* * Constructor. */ template <int D> BasisFieldState<D>::BasisFieldState(System<D>& system) : FieldState<D, DArray<double> >(system) {} /* * Destructor. */ template <int D> BasisFieldState<D>::~BasisFieldState() {} /* * Allocate all fields. */ template <int D> void BasisFieldState<D>::allocate() { // Precondition UTIL_CHECK(hasSystem()); int nMonomer = system().mixture().nMonomer(); UTIL_CHECK(nMonomer > 0); if (fields().isAllocated()) { UTIL_CHECK(fields().capacity() == nMonomer); } else { fields().allocate(nMonomer); } int nBasis = system().basis().nBasis(); UTIL_CHECK(nBasis > 0); for (int i = 0; i < nMonomer; ++i) { if (field(i).isAllocated()) { UTIL_CHECK(field(i).capacity() == nBasis); } else { field(i).allocate(nBasis); } } } /* * Read fields in symmetry-adapted basis format. */ template <int D> void BasisFieldState<D>::read(const std::string & filename) { allocate(); system().fieldIo().readFieldsBasis(filename, fields(), unitCell()); } /** * Write fields in symmetry-adapted basis format. */ template <int D> void BasisFieldState<D>::write(const std::string & filename) { system().fieldIo().writeFieldsBasis(filename, fields(), unitCell()); } /* * Gjt current state of associated System. */ template <int D> void BasisFieldState<D>::getSystemState() { // Get system wFields allocate(); int nMonomer = system().mixture().nMonomer(); int nBasis = system().basis().nBasis(); int i, j; for (i = 0; i < nMonomer; ++i) { DArray<double>& stateField = field(i); const DArray<double>& systemField = system().w().basis(i); for (j = 0; j < nBasis; ++j) { stateField[j] = systemField[j]; } } // Get system unit cell unitCell() = system().unitCell(); } /* * Set System state to current state of the BasisFieldState object. */ template <int D> void BasisFieldState<D>::setSystemState(bool isFlexible) { system().setWBasis(fields()); if (isFlexible) { system().setUnitCell(unitCell()); } } } // namespace Pspc } // namespace Pscf #endif
2,934
C++
.tpp
112
20.964286
74
0.610635
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,269
SweepFactory.tpp
dmorse_pscfpp/src/pspc/sweep/SweepFactory.tpp
#ifndef PSPC_SWEEP_FACTORY_TPP #define PSPC_SWEEP_FACTORY_TPP /* * 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 "SweepFactory.h" // subclasses of Sweep #include "LinearSweep.h" // #include "NonlinearSweep.h" Eventually! namespace Pscf{ namespace Pspc{ using namespace Util; template <int D> SweepFactory<D>::SweepFactory(System<D>& system) : systemPtr_(&system) {} /** * Return a pointer to a Sweep subclass with name className */ template <int D> Sweep<D>* SweepFactory<D>::factory(std::string const & className) const { Sweep<D> *ptr = 0; // First check if name is known by any subfactories ptr = trySubfactories(className); if (ptr) return ptr; // Explicit class names if (className == "Sweep" || className == "LinearSweep") { ptr = new LinearSweep<D>(*systemPtr_); } return ptr; } } } #endif
1,173
C++
.tpp
38
23.789474
79
0.612299
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,270
Sweep.tpp
dmorse_pscfpp/src/pspc/sweep/Sweep.tpp
#ifndef PSPC_SWEEP_TPP /* * 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" #include <pspc/System.h> #include <pscf/inter/Interaction.h> #include <pscf/sweep/SweepTmpl.tpp> #include <util/misc/FileMaster.h> #include <util/misc/ioUtil.h> namespace Pscf { namespace Pspc { using namespace Util; // Maximum number of previous states = order of continuation + 1 # define PSPC_HISTORY_CAPACITY 3 /* * Default constructor (for unit testing). */ template <int D> Sweep<D>::Sweep() : SweepTmpl< BasisFieldState<D> >(PSPC_HISTORY_CAPACITY), writeCRGrid_(false), writeCBasis_(false), writeWRGrid_(false), systemPtr_(0) {} /* * Constructor, creates association with parent system. */ template <int D> Sweep<D>::Sweep(System<D> & system) : SweepTmpl< BasisFieldState<D> >(PSPC_HISTORY_CAPACITY), writeCRGrid_(false), writeCBasis_(false), writeWRGrid_(false), systemPtr_(&system) {} /* * Destructor. */ template <int D> Sweep<D>::~Sweep() {} /* * Set association with a parent system (for unit testing). */ template <int D> void Sweep<D>::setSystem(System<D>& system) { systemPtr_ = &system; } /* * Read parameters */ template <int D> void Sweep<D>::readParameters(std::istream& in) { // Call the base class's readParameters function. SweepTmpl< BasisFieldState<D> >::readParameters(in); // Read optional flags indicating which field types to output readOptional(in, "writeCRGrid", writeCRGrid_); readOptional(in, "writeCBasis", writeCBasis_); readOptional(in, "writeWRGrid", writeWRGrid_); } /* * Check allocation of one state object, allocate if necessary. */ template <int D> void Sweep<D>::checkAllocation(BasisFieldState<D>& state) { UTIL_CHECK(hasSystem()); state.setSystem(system()); state.allocate(); state.unitCell() = system().unitCell(); } /* * Setup operations at the beginning of a sweep. */ template <int D> void Sweep<D>::setup() { initialize(); checkAllocation(trial_); // Open log summary file std::string fileName = baseFileName_; fileName += "sweep.log"; system().fileMaster().openOutputFile(fileName, logFile_); logFile_ << " step ds free_energy pressure" << std::endl; }; /* * Set non-adjustable system parameters to new values. * * \param s path length coordinate, in range [0,1] */ template <int D> void Sweep<D>::setParameters(double s) { // Empty default implementation allows Sweep<D> to be compiled. UTIL_THROW("Calling unimplemented function Sweep::setParameters"); }; /* * Create guess for adjustable variables by polynomial extrapolation. */ template <int D> void Sweep<D>::extrapolate(double sNew) { UTIL_CHECK(historySize() > 0); // If historySize() == 1, do nothing: Use previous system state // as trial for the new state. if (historySize() > 1) { UTIL_CHECK(historySize() <= historyCapacity()); // Does the iterator allow a flexible unit cell ? bool isFlexible = system().iterator().isFlexible(); // Compute coefficients of polynomial extrapolation to sNew setCoefficients(sNew); // Set extrapolated trial w fields double coeff; int nMonomer = system().mixture().nMonomer(); int nBasis = system().basis().nBasis(); DArray<double>* newFieldPtr; DArray<double>* oldFieldPtr; int i, j, k; for (i=0; i < nMonomer; ++i) { newFieldPtr = &(trial_.field(i)); // Previous state k = 0 (most recent) oldFieldPtr = &state(0).field(i); coeff = c(0); for (j=0; j < nBasis; ++j) { (*newFieldPtr)[j] = coeff*(*oldFieldPtr)[j]; } // Previous states k >= 1 (older) for (k = 1; k < historySize(); ++k) { oldFieldPtr = &state(k).field(i); coeff = c(k); for (j=0; j < nBasis; ++j) { (*newFieldPtr)[j] += coeff*(*oldFieldPtr)[j]; } } } // Make sure unitCellParameters_ is up to date with system // (if we are sweeping in a lattice parameter, then the system // parameters will be up-to-date but unitCellParameters_ wont be) FSArray<double, 6> oldParameters = unitCellParameters_; unitCellParameters_ = system().unitCell().parameters(); // If isFlexible, then extrapolate the flexible unit cell parameters if (isFlexible) { double coeff; double parameter; const FSArray<bool,6> flexParams = system().iterator().flexibleParams(); const int nParameter = system().unitCell().nParameter(); UTIL_CHECK(flexParams.size() == nParameter); // Add contributions from all previous states for (k = 0; k < historySize(); ++k) { coeff = c(k); for (int i = 0; i < nParameter; ++i) { if (flexParams[i]) { if (k == 0) { unitCellParameters_[i] = 0; } parameter = state(k).unitCell().parameter(i); unitCellParameters_[i] += coeff*parameter; } } } } // Reset trial_.unitCell() object trial_.unitCell().setParameters(unitCellParameters_); // Check if any unit cell parameters have changed bool newCellParams(true); for (int i = 0; i < oldParameters.size(); i++) { if (fabs(oldParameters[i] - unitCellParameters_[i]) < 1e-10) { newCellParams = false; break; } } // Transfer data from trial_ state to parent system trial_.setSystemState(newCellParams); } }; /* * Call current iterator to solve SCFT problem. * * Return 0 for sucessful solution, 1 on failure to converge. */ template <int D> int Sweep<D>::solve(bool isContinuation) { return system().iterate(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). */ template <int D> void Sweep<D>::reset() { bool isFlexible = system().iterator().isFlexible(); state(0).setSystemState(isFlexible); } /* * 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. */ template <int D> void Sweep<D>::getSolution() { state(0).setSystem(system()); state(0).getSystemState(); // Output converged solution to several files outputSolution(); // Output summary to log file outputSummary(logFile_); }; template <int D> void Sweep<D>::outputSolution() { std::ofstream out; std::string outFileName; std::string indexString = toString(nAccept() - 1); // Open parameter file, with thermodynamic properties at end outFileName = baseFileName_; outFileName += indexString; outFileName += ".stt"; system().fileMaster().openOutputFile(outFileName, out); // Write data file, with thermodynamic properties at end system().writeParamNoSweep(out); out << std::endl; system().writeThermo(out); out.close(); // Write w fields outFileName = baseFileName_; outFileName += indexString; outFileName += "_w"; outFileName += ".bf"; UTIL_CHECK(system().w().hasData()); UTIL_CHECK(system().w().isSymmetric()); system().fieldIo().writeFieldsBasis(outFileName, system().w().basis(), system().unitCell()); // Optionally write c rgrid files if (writeCRGrid_) { outFileName = baseFileName_; outFileName += indexString; outFileName += "_c"; outFileName += ".rf"; system().fieldIo().writeFieldsRGrid(outFileName, system().c().rgrid(), system().unitCell()); } // Optionally write c basis files if (writeCBasis_) { outFileName = baseFileName_; outFileName += indexString; outFileName += "_c"; outFileName += ".bf"; UTIL_CHECK(system().hasCFields()); system().fieldIo().writeFieldsBasis(outFileName, system().c().basis(), system().unitCell()); } // Optionally write w rgrid files if (writeWRGrid_) { outFileName = baseFileName_; outFileName += indexString; outFileName += "_w"; outFileName += ".rf"; system().fieldIo().writeFieldsRGrid(outFileName, system().w().rgrid(), system().unitCell()); } } template <int D> void Sweep<D>::outputSummary(std::ostream& out) { int i = nAccept() - 1; double sNew = s(0); if (!system().hasFreeEnergy()) system().computeFreeEnergy(); out << Int(i,5) << Dbl(sNew) << Dbl(system().fHelmholtz(),16) << Dbl(system().pressure(),16); out << std::endl; } template <int D> void Sweep<D>::cleanup() { logFile_.close(); } } // namespace Pspc } // namespace Pscf #endif
10,227
C++
.tpp
294
26.105442
77
0.574921
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,271
SweepParameter.tpp
dmorse_pscfpp/src/pspc/sweep/SweepParameter.tpp
#ifndef PSPC_SWEEP_PARAMETER_TPP #define PSPC_SWEEP_PARAMETER_TPP /* * 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 <pspc/solvers/Block.h> #include <pspc/solvers/Mixture.h> #include <pspc/solvers/Polymer.h> #include <pspc/iterator/AmIterator.h> #include <pspc/iterator/FilmIterator.h> #include <pspc/System.h> #include <pscf/crystal/UnitCell.h> #include <pscf/inter/Interaction.h> #include <util/global.h> #include <util/containers/FSArray.h> #include <algorithm> #include <iomanip> namespace Pscf { namespace Pspc { using namespace Util; /* * Default constructor. */ template <int D> SweepParameter<D>::SweepParameter() : type_(SweepParameter<D>::Null), nID_(0), id_(), initial_(0.0), change_(0.0), systemPtr_(0) {} /* * Constructor, creates association with system. */ template <int D> SweepParameter<D>::SweepParameter(System<D>& system) : type_(SweepParameter<D>::Null), nID_(0), id_(), initial_(0.0), change_(0.0), systemPtr_(&system) {} /* * Read type, set nId and allocate id_ array. */ template <int D> void SweepParameter<D>::readParamType(std::istream& in) { std::string buffer; in >> buffer; std::transform(buffer.begin(), buffer.end(), buffer.begin(), ::tolower); if (buffer == "block" || buffer == "block_length") { type_ = Block; nID_ = 2; // polymer and block identifiers } else if (buffer == "chi") { type_ = Chi; nID_ = 2; // two monomer type identifiers } else if (buffer == "kuhn") { type_ = Kuhn; nID_ = 1; // monomer type identifier } else if (buffer == "phi_polymer") { type_ = Phi_Polymer; nID_ = 1; // species identifier. } else if (buffer == "phi_solvent") { type_ = Phi_Solvent; nID_ = 1; // species identifier. } else if (buffer == "mu_polymer") { type_ = Mu_Polymer; nID_ = 1; // species identifier. } else if (buffer == "mu_solvent") { type_ = Mu_Solvent; nID_ = 1; // species identifier. } else if (buffer == "solvent" || buffer == "solvent_size") { type_ = Solvent; nID_ = 1; // species identifier. } else if (buffer == "cell_param") { type_ = Cell_Param; nID_ = 1; // lattice parameter identifier. } else if (buffer == "chi_bottom") { // Note: this option is only relevant for thin film systems type_ = Chi_Bottom; nID_ = 1; // monomer type } else if (buffer == "chi_top") { // Note: this option is only relevant for thin film systems type_ = Chi_Top; nID_ = 1; // monomer type } else { UTIL_THROW("Invalid SweepParameter::ParamType value"); } if (id_.isAllocated()) id_.deallocate(); id_.allocate(nID_); } /* * Write type enum value */ template <int D> void SweepParameter<D>::writeParamType(std::ostream& out) const { out << type(); } /* * Get the current value from the parent system. */ template <int D> void SweepParameter<D>::getInitial() { initial_ = get_(); } /* * Set a new value in the parent system. */ template <int D> void SweepParameter<D>::update(double newVal) { set_(newVal); } /* * Get string representation of type enum value. */ template <int D> std::string SweepParameter<D>::type() const { if (type_ == Block) { return "block"; } else if (type_ == Chi) { return "chi"; } else if (type_ == Kuhn) { return "kuhn"; } else if (type_ == Phi_Polymer) { return "phi_polymer"; } else if (type_ == Phi_Solvent) { return "phi_solvent"; } else if (type_ == Mu_Polymer) { return "mu_polymer"; } else if (type_ == Mu_Solvent) { return "mu_solvent"; } else if (type_ == Solvent) { return "solvent_size"; } else if (type_ == Cell_Param) { return "cell_param"; } else if (type_ == Chi_Bottom) { return "chi_bottom"; } else if (type_ == Chi_Top) { return "chi_top"; } else { UTIL_THROW("This should never happen."); } } template <int D> double SweepParameter<D>::get_() { if (type_ == Block) { return systemPtr_->mixture().polymer(id(0)).block(id(1)).length(); } else if (type_ == Chi) { return systemPtr_->interaction().chi(id(0), id(1)); } else if (type_ == Kuhn) { return systemPtr_->mixture().monomer(id(0)).kuhn(); } else if (type_ == Phi_Polymer) { return systemPtr_->mixture().polymer(id(0)).phi(); } else if (type_ == Phi_Solvent) { return systemPtr_->mixture().solvent(id(0)).phi(); } else if (type_ == Mu_Polymer) { return systemPtr_->mixture().polymer(id(0)).mu(); } else if (type_ == Mu_Solvent) { return systemPtr_->mixture().solvent(id(0)).mu(); } else if (type_ == Solvent) { return systemPtr_->mixture().solvent(id(0)).size(); } else if (type_ == Cell_Param) { return systemPtr_->unitCell().parameter(id(0)); } else if (type_ == Chi_Bottom) { // Note: this option is only relevant for thin film systems UTIL_CHECK(isFilmIterator()); if (systemPtr_->iterator().className() == "AmIteratorFilm") { FilmIterator<D, AmIterator<D> >* itrPtr_(0); itrPtr_ = static_cast<FilmIterator<D, AmIterator<D> >* >(&(systemPtr_->iterator())); return itrPtr_->chiBottom(id(0)); } else { UTIL_THROW("Iterator type is not compatible with this sweep parameter."); } } else if (type_ == Chi_Top) { // Note: this option is only relevant for thin film systems UTIL_CHECK(isFilmIterator()); if (systemPtr_->iterator().className() == "AmIteratorFilm") { FilmIterator<D, AmIterator<D> >* itrPtr_(0); itrPtr_ = static_cast<FilmIterator<D, AmIterator<D> >* >(&(systemPtr_->iterator())); return itrPtr_->chiTop(id(0)); } else { UTIL_THROW("Iterator type is not compatible with this sweep parameter."); } } else { UTIL_THROW("This should never happen."); } } template <int D> void SweepParameter<D>::set_(double newVal) { if (type_ == Block) { systemPtr_->mixture().polymer(id(0)).block(id(1)).setLength(newVal); } else if (type_ == Chi) { systemPtr_->interaction().setChi(id(0), id(1), newVal); } else if (type_ == Kuhn) { systemPtr_->mixture().setKuhn(id(0), newVal); } else if (type_ == Phi_Polymer) { systemPtr_->mixture().polymer(id(0)).setPhi(newVal); } else if (type_ == Phi_Solvent) { systemPtr_->mixture().solvent(id(0)).setPhi(newVal); } else if (type_ == Mu_Polymer) { systemPtr_->mixture().polymer(id(0)).setMu(newVal); } else if (type_ == Mu_Solvent) { systemPtr_->mixture().solvent(id(0)).setMu(newVal); } else if (type_ == Solvent) { systemPtr_->mixture().solvent(id(0)).setSize(newVal); } else if (type_ == Cell_Param) { FSArray<double,6> params = systemPtr_->unitCell().parameters(); params[id(0)] = newVal; systemPtr_->setUnitCell(params); } else if (type_ == Chi_Bottom) { // Note: this option is only relevant for thin film systems UTIL_CHECK(isFilmIterator()); if (systemPtr_->iterator().className() == "AmIteratorFilm") { FilmIterator<D, AmIterator<D> >* itrPtr_(0); itrPtr_ = static_cast<FilmIterator<D, AmIterator<D> >* >(&(systemPtr_->iterator())); itrPtr_->setChiBottom(id(0), newVal); } else { UTIL_THROW("Iterator type is not compatible with this sweep parameter."); } } else if (type_ == Chi_Top) { // Note: this option is only relevant for thin film systems UTIL_CHECK(isFilmIterator()); if (systemPtr_->iterator().className() == "AmIteratorFilm") { FilmIterator<D, AmIterator<D> >* itrPtr_(0); itrPtr_ = static_cast<FilmIterator<D, AmIterator<D> >* >(&(systemPtr_->iterator())); itrPtr_->setChiTop(id(0), newVal); } else { UTIL_THROW("Iterator type is not compatible with this sweep parameter."); } } else { UTIL_THROW("This should never happen."); } } /* * Check if the system iterator is a thin film iterator. */ template <int D> bool SweepParameter<D>::isFilmIterator() const { std::string name = systemPtr_->iterator().className(); if (name.size() < 4) { return false; } else { return (name.substr(name.size() - 4) == "Film"); } } template <int D> template <class Archive> void SweepParameter<D>::serialize(Archive ar, const unsigned int version) { serializeEnum(ar, type_, version); ar & nID_; for (int i = 0; i < nID_; ++i) { ar & id_[i]; } ar & initial_; ar & change_; } // Definitions of operators, with no explicit instantiations. /* * Inserter for reading a SweepParameter from an istream. */ template <int D> std::istream& operator >> (std::istream& in, SweepParameter<D>& param) { // Read the parameter type. param.readParamType(in); // Read the identifiers associated with this parameter type. for (int i = 0; i < param.nID_; ++i) { in >> param.id_[i]; } // Read in the range in the parameter to sweep over in >> param.change_; return in; } /* * Extractor for writing a SweepParameter to ostream. */ template <int D> std::ostream& operator << (std::ostream& out, SweepParameter<D> const & param) { param.writeParamType(out); out << " "; for (int i = 0; i < param.nID_; ++i) { out << param.id(i); out << " "; } out << param.change_; return out; } } } #endif
10,466
C++
.tpp
308
26.821429
96
0.565874
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,272
KFieldComparison.tpp
dmorse_pscfpp/src/pspc/field/KFieldComparison.tpp
#ifndef PSPC_K_FIELD_COMPARISON_TPP #define PSPC_K_FIELD_COMPARISON_TPP /* * 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 "KFieldComparison.h" #include <cmath> namespace Pscf { namespace Pspc { // Default Constructor template <int D> KFieldComparison<D>::KFieldComparison() : maxDiff_(0.0), rmsDiff_(0.0) {}; // Comparator for individual fields. template <int D> double KFieldComparison<D>::compare(RFieldDft<D> const& a, RFieldDft<D> const& b) { UTIL_CHECK(a.capacity() > 0); UTIL_CHECK(a.capacity() == b.capacity()); int n = a.capacity(); double diffSq, diff, d0, d1; maxDiff_ = 0.0; rmsDiff_ = 0.0; for (int i = 0; i < n; ++i) { d0 = a[i][0] - b[i][0]; d1 = a[i][1] - b[i][1]; diffSq = d0*d0 + d1*d1; diff = sqrt(diffSq); if (std::isnan(diff)) { // If either field has a NaN component, set error to very // high value and exit the function maxDiff_ = 1e8; rmsDiff_ = 1e8; return maxDiff_; } else if (diff > maxDiff_) { maxDiff_ = diff; } rmsDiff_ += diffSq; //std::cout << i // << " " << a[i][0] << " " << a[i][1] // << " " << b[i][0] << " " << b[i][1] // << " " << diff << std::endl; } rmsDiff_ = rmsDiff_/double(n); rmsDiff_ = sqrt(rmsDiff_); return maxDiff_; } // Comparator for arrays of fields template <int D> double KFieldComparison<D>::compare(DArray< RFieldDft<D> > const & a, DArray< RFieldDft<D> > const & b) { UTIL_CHECK(a.capacity() > 0); UTIL_CHECK(a.capacity() == b.capacity()); UTIL_CHECK(a[0].capacity() > 0); int m = a.capacity(); double diffSq, diff, d0, d1; maxDiff_ = 0.0; rmsDiff_ = 0.0; int i, j, n; for (i = 0; i < m; ++i) { n = a[i].capacity(); UTIL_CHECK(n > 0); UTIL_CHECK(n == b[i].capacity()); for (j = 0; j < n; ++j) { d0 = a[i][j][0] - b[i][j][0]; d1 = a[i][j][1] - b[i][j][1]; diffSq = d0*d0 + d1*d1; diff = sqrt(diffSq); if (std::isnan(diff)) { // If either field has a NaN component, set error to very // high value and exit the function maxDiff_ = 1e8; rmsDiff_ = 1e8; return maxDiff_; } else if (diff > maxDiff_) { maxDiff_ = diff; } rmsDiff_ += diffSq; } } rmsDiff_ = rmsDiff_/double(m*n); rmsDiff_ = sqrt(rmsDiff_); return maxDiff_; } } } #endif
2,915
C++
.tpp
93
23.322581
84
0.495915
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,273
Domain.tpp
dmorse_pscfpp/src/pspc/field/Domain.tpp
#ifndef PSPC_DOMAIN_TPP #define PSPC_DOMAIN_TPP /* * 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 "Domain.h" namespace Pscf { namespace Pspc { using namespace Util; /* * Constructor. */ template <int D> Domain<D>::Domain() : unitCell_(), mesh_(), group_(), basis_(), fft_(), fieldIo_(), lattice_(UnitCell<D>::Null), groupName_(), hasFileMaster_(false), isInitialized_(false) { setClassName("Domain"); } /* * Destructor. */ template <int D> Domain<D>::~Domain() {} template <int D> void Domain<D>::setFileMaster(FileMaster& fileMaster) { fieldIo_.associate(mesh_, fft_, lattice_, groupName_, group_, basis_, fileMaster); hasFileMaster_ = true; } /* * Read parameters and initialize. */ template <int D> void Domain<D>::readParameters(std::istream& in) { // Preconditins UTIL_CHECK(!isInitialized_); UTIL_CHECK(hasFileMaster_); bool hasUnitCell = false; // Uncomment for backwards compatibility with old format (< v1.0) #if 0 readOptional(in, "unitCell", unitCell_); if (unitCell_.lattice() != UnitCell<D>::Null) { lattice_ = unitCell_.lattice(); hasUnitCell = true; } #endif read(in, "mesh", mesh_); fft_.setup(mesh_.dimensions()); // If no unit cell was read, read lattice system if (lattice_ == UnitCell<D>::Null) { read(in, "lattice", lattice_); unitCell_.set(lattice_); } // Read group name and initialized space group read(in, "groupName", groupName_); readGroup(groupName_, group_); // Initialize unit cell if unit cell parameters are known if (hasUnitCell) { basis().makeBasis(mesh(), unitCell(), group_); } isInitialized_ = true; } /* * Read header of r-grid field in order to initialize the Domain. * * Useful for unit testing. */ template <int D> void Domain<D>::readRGridFieldHeader(std::istream& in, int& nMonomer) { // Read common section of standard field header int ver1, ver2; Pscf::readFieldHeader(in, ver1, ver2, unitCell_, groupName_, nMonomer); lattice_ = unitCell_.lattice(); // Read grid dimensions std::string label; in >> label; if (label != "mesh" && label != "ngrid") { std::string msg = "\n"; msg += "Error reading field file:\n"; msg += "Expected mesh or ngrid, but found ["; msg += label; msg += "]"; UTIL_THROW(msg.c_str()); } IntVec<D> nGrid; in >> nGrid; // Initialize mesh, fft mesh_.setDimensions(nGrid); fft_.setup(mesh_.dimensions()); // Initialize group and basis readGroup(groupName_, group_); basis_.makeBasis(mesh_, unitCell_, group_); isInitialized_ = true; } template <int D> void Domain<D>::setUnitCell(UnitCell<D> const & unitCell) { if (lattice_ == UnitCell<D>::Null) { lattice_ = unitCell.lattice(); } else { UTIL_CHECK(lattice_ == unitCell.lattice()); } unitCell_ = unitCell; if (!basis_.isInitialized()) { makeBasis(); } } /* * Set parameters of the associated unit cell. */ template <int D> void Domain<D>::setUnitCell(typename UnitCell<D>::LatticeSystem lattice, FSArray<double, 6> const & parameters) { if (lattice_ == UnitCell<D>::Null) { lattice_ = lattice; } else { UTIL_CHECK(lattice_ == lattice); } unitCell_.set(lattice, parameters); if (!basis_.isInitialized()) { makeBasis(); } } /* * Set parameters of the associated unit cell. */ template <int D> void Domain<D>::setUnitCell(FSArray<double, 6> const & parameters) { UTIL_CHECK(unitCell_.lattice() != UnitCell<D>::Null); UTIL_CHECK(unitCell_.nParameter() == parameters.size()); unitCell_.setParameters(parameters); if (!basis_.isInitialized()) { makeBasis(); } } template <int D> void Domain<D>::makeBasis() { UTIL_CHECK(mesh_.size() > 0); UTIL_CHECK(unitCell_.lattice() != UnitCell<D>::Null); // Check group, read from file if necessary if (group_.size() == 1) { if (groupName_ != "I") { UTIL_CHECK(groupName_ != ""); readGroup(groupName_, group_); } } // Check basis, construct if not initialized if (!basis().isInitialized()) { basis_.makeBasis(mesh_, unitCell_, group_); } UTIL_CHECK(basis().isInitialized()); } } // namespace Pspc } // namespace Pscf #endif
5,017
C++
.tpp
175
21.971429
75
0.577459
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,274
RFieldDft.tpp
dmorse_pscfpp/src/pspc/field/RFieldDft.tpp
#ifndef PSPC_R_FIELD_DFT_TPP #define PSPC_R_FIELD_DFT_TPP /* * PSCF Package * * Copyright 2016 - 2022, The Regents of the University of Minnesota * Distributed under the terms of the GNU General Public License. */ #include "RFieldDft.h" namespace Pscf { namespace Pspc { using namespace Util; /** * Default constructor. */ template <int D> RFieldDft<D>::RFieldDft() : Field<fftw_complex>() {} /* * Destructor. */ template <int D> RFieldDft<D>::~RFieldDft() {} /* * Copy constructor. * * Allocates new memory and copies all elements by value. * *\param other the RField<D> to be copied. */ template <int D> RFieldDft<D>::RFieldDft(const RFieldDft<D>& other) : Field<fftw_complex>() { if (!other.isAllocated()) { UTIL_THROW("Other Field must be allocated."); } data_ = (fftw_complex*) fftw_malloc(sizeof(fftw_complex)*other.capacity_); capacity_ = other.capacity_; for (int i = 0; i < capacity_; ++i) { data_[i][0] = other.data_[i][0]; data_[i][1] = other.data_[i][1]; } meshDimensions_ = other.meshDimensions_; dftDimensions_ = other.dftDimensions_; } /* * Assignment, element-by-element. * * This operator will allocate memory if not allocated previously. * * \throw Exception if other Field is not allocated. * \throw Exception if both Fields are allocated with unequal capacities. * * \param other the rhs Field */ template <int D> RFieldDft<D>& RFieldDft<D>::operator = (const RFieldDft<D>& other) { // Check for self assignment if (this == &other) return *this; // Precondition if (!other.isAllocated()) { UTIL_THROW("Other Field must be allocated."); } if (!isAllocated()) { allocate(other.capacity()); } else if (capacity_ != other.capacity_) { UTIL_THROW("Cannot assign Fields of unequal capacity"); } // Copy elements for (int i = 0; i < capacity_; ++i) { data_[i][0] = other.data_[i][0]; data_[i][1] = other.data_[i][1]; } meshDimensions_ = other.meshDimensions_; dftDimensions_ = other.dftDimensions_; return *this; } } } #endif
2,279
C++
.tpp
84
22.083333
80
0.61549
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,275
Mask.tpp
dmorse_pscfpp/src/pspc/field/Mask.tpp
#ifndef PSPC_MASK_TPP #define PSPC_MASK_TPP /* * 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 "Mask.h" #include <pspc/field/FieldIo.h> #include <pspc/field/RFieldDft.h> namespace Pscf { namespace Pspc { using namespace Util; /* * Constructor. */ template <int D> Mask<D>::Mask() : basis_(), rgrid_(), fieldIoPtr_(0), meshDimensions_(), meshSize_(0), nBasis_(0), isAllocated_(false), hasData_(false), isSymmetric_(false) {} /* * Destructor. */ template <int D> Mask<D>::~Mask() {} /* * Create an association with a FieldIo object. */ template <int D> void Mask<D>::setFieldIo(FieldIo<D> const & fieldIo) { fieldIoPtr_ = &fieldIo; } /* * Allocate memory for field. */ template <int D> void Mask<D>::allocate(int nBasis, IntVec<D> const & meshDimensions) { UTIL_CHECK(!isAllocated_); // Set mesh and basis dimensions nBasis_ = nBasis; meshDimensions_ = meshDimensions; meshSize_ = 1; for (int i = 0; i < D; ++i) { UTIL_CHECK(meshDimensions[i] > 0); meshSize_ *= meshDimensions[i]; } // Allocate field arrays basis_.allocate(nBasis); rgrid_.allocate(meshDimensions); isAllocated_ = true; } /* * Set new w-field values. */ template <int D> void Mask<D>::setBasis(DArray<double> const & field) { UTIL_CHECK(field.capacity() == nBasis_); for (int j = 0; j < nBasis_; ++j) { basis_[j] = field[j]; } fieldIoPtr_->convertBasisToRGrid(basis_, rgrid_); hasData_ = true; isSymmetric_ = true; } /* * Set new field values, using r-grid field as inputs. */ template <int D> void Mask<D>::setRGrid(RField<D> const & field, bool isSymmetric) { for (int j = 0; j < meshSize_; ++j) { rgrid_[j] = field[j]; } if (isSymmetric) { fieldIoPtr_->convertRGridToBasis(rgrid_, basis_); } hasData_ = true; isSymmetric_ = isSymmetric; } /* * Read field 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. */ template <int D> void Mask<D>::readBasis(std::istream& in, UnitCell<D>& unitCell) { fieldIoPtr_->readFieldBasis(in, basis_, unitCell); // Update system wFieldsRGrid fieldIoPtr_->convertBasisToRGrid(basis_, rgrid_); hasData_ = true; isSymmetric_ = true; } /* * Read field 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. */ template <int D> void Mask<D>::readBasis(std::string filename, UnitCell<D>& unitCell) { fieldIoPtr_->readFieldBasis(filename, basis_, unitCell); // Update system wFieldsRGrid fieldIoPtr_->convertBasisToRGrid(basis_, rgrid_); hasData_ = true; isSymmetric_ = true; } /* * Reads field from an input stream in real-space (r-grid) format. * * If the isSymmetric parameter is true, this function assumes that * the field is known to be symmetric and so computes and stores * the corresponding basis format. 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. */ template <int D> void Mask<D>::readRGrid(std::istream& in, UnitCell<D>& unitCell, bool isSymmetric) { fieldIoPtr_->readFieldRGrid(in, rgrid_, unitCell); if (isSymmetric) { fieldIoPtr_->convertRGridToBasis(rgrid_, basis_); } hasData_ = true; isSymmetric_ = isSymmetric; } /* * Reads field from a file in real-space (r-grid) format. * * If the isSymmetric parameter is true, this function assumes that * the field is known to be symmetric and so computes and stores * the corresponding basis format. 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. */ template <int D> void Mask<D>::readRGrid(std::string filename, UnitCell<D>& unitCell, bool isSymmetric) { fieldIoPtr_->readFieldRGrid(filename, rgrid_, unitCell); if (isSymmetric) { fieldIoPtr_->convertRGridToBasis(rgrid_, basis_); } hasData_ = true; isSymmetric_ = isSymmetric; } /* * Return volume fraction of the unit cell occupied by the * polymers/solvents. */ template <int D> double Mask<D>::phiTot() const { if (isSymmetric() && hasData()) { // Data in basis format is available return basis()[0]; } else if (!hasData()) { // system does not have a mask return 1.0; } else { // Data is only available in r-grid format RFieldDft<D> kgrid; kgrid.allocate(rgrid_.meshDimensions()); fieldIoPtr_->convertRGridToKGrid(rgrid_, kgrid); UTIL_CHECK(kgrid[0][1] < 1e-8); return kgrid[0][0]; } } } // namespace Pspc } // namespace Pscf #endif
5,704
C++
.tpp
194
23.742268
72
0.628238
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,276
Field.tpp
dmorse_pscfpp/src/pspc/field/Field.tpp
#ifndef PSPC_FIELD_TPP #define PSPC_FIELD_TPP /* * PSCF Package * * Copyright 2016 - 2022, The Regents of the University of Minnesota * Distributed under the terms of the GNU General Public License. */ #include "Field.h" #include <util/misc/Memory.h> #include <fftw3.h> namespace Pscf { namespace Pspc { using namespace Util; /* * Default constructor. */ template <typename Data> Field<Data>::Field() : data_(0), capacity_(0) {} /* * Destructor. */ template <typename Data> Field<Data>::~Field() { if (isAllocated()) { fftw_free(data_); capacity_ = 0; } } /* * Allocate the underlying C array. * * Throw an Exception if the Field has already allocated. * * \param capacity number of elements to allocate. */ template <typename Data> void Field<Data>::allocate(int capacity) { if (isAllocated()) { UTIL_THROW("Attempt to re-allocate a Field"); } if (capacity <= 0) { UTIL_THROW("Attempt to allocate with capacity <= 0"); } data_ = (Data*) fftw_malloc(sizeof(Data)*capacity); capacity_ = capacity; } /* * Deallocate the underlying C array. * * Throw an Exception if this Field is not allocated. */ template <typename Data> void Field<Data>::deallocate() { if (!isAllocated()) { UTIL_THROW("Array is not allocated"); } fftw_free(data_); capacity_ = 0; } } } #endif
1,502
C++
.tpp
70
17.028571
67
0.618847
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,277
CFieldContainer.tpp
dmorse_pscfpp/src/pspc/field/CFieldContainer.tpp
#ifndef PSPC_C_FIELD_CONTAINER_TPP #define PSPC_C_FIELD_CONTAINER_TPP /* * 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 "CFieldContainer.h" namespace Pscf { namespace Pspc { using namespace Util; /* * Constructor. */ template <int D> CFieldContainer<D>::CFieldContainer() : basis_(), rgrid_(), nMonomer_(0), isAllocatedRGrid_(false), isAllocatedBasis_(false) {} /* * Destructor. */ template <int D> CFieldContainer<D>::~CFieldContainer() {} /* * Set the stored value of nMonomer (this may only be called once). */ template <int D> void CFieldContainer<D>::setNMonomer(int nMonomer) { UTIL_CHECK(nMonomer_ == 0); UTIL_CHECK(nMonomer > 0); nMonomer_ = nMonomer; } /* * Allocate memory for fields in r-grid format. */ template <int D> void CFieldContainer<D>::allocateRGrid(IntVec<D> const & meshDimensions) { UTIL_CHECK(nMonomer_ > 0); // If already allocated, deallocate. if (isAllocatedRGrid_) { deallocateRGrid(); } // Allocate arrays rgrid_.allocate(nMonomer_); for (int i = 0; i < nMonomer_; ++i) { rgrid_[i].allocate(meshDimensions); } isAllocatedRGrid_ = true; } /* * De-allocate memory for fields in r-grid format */ template <int D> void CFieldContainer<D>::deallocateRGrid() { UTIL_CHECK(isAllocatedRGrid_); UTIL_CHECK(nMonomer_ > 0); for (int i = 0; i < nMonomer_ ; ++i) { rgrid_[i].deallocate(); } rgrid_.deallocate(); isAllocatedRGrid_ = false; } /* * Allocate memory for fields in basis format. */ template <int D> void CFieldContainer<D>::allocateBasis(int nBasis) { UTIL_CHECK(nMonomer_ > 0); // If already allocated, deallocate. if (isAllocatedBasis_) { deallocateBasis(); } // Allocate basis_.allocate(nMonomer_); for (int i = 0; i < nMonomer_; ++i) { basis_[i].allocate(nBasis); } isAllocatedBasis_ = true; } /* * De-allocate memory for fields in basis format. */ template <int D> void CFieldContainer<D>::deallocateBasis() { UTIL_CHECK(nMonomer_ > 0); UTIL_CHECK(isAllocatedBasis_); for (int i = 0; i < nMonomer_; ++i) { basis_[i].deallocate(); } basis_.deallocate(); isAllocatedBasis_ = false; } /* * Allocate memory for all fields. */ template <int D> void CFieldContainer<D>::allocate(int nMonomer, int nBasis, IntVec<D> const & meshDimensions) { setNMonomer(nMonomer); allocateRGrid(meshDimensions); allocateBasis(nBasis); } } // namespace Pspc } // namespace Pscf #endif
2,959
C++
.tpp
119
19.504202
70
0.614594
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,278
WFieldContainer.tpp
dmorse_pscfpp/src/pspc/field/WFieldContainer.tpp
#ifndef PSPC_W_FIELD_CONTAINER_TPP #define PSPC_W_FIELD_CONTAINER_TPP /* * 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 "WFieldContainer.h" #include <pspc/field/FieldIo.h> namespace Pscf { namespace Pspc { using namespace Util; /* * Constructor. */ template <int D> WFieldContainer<D>::WFieldContainer() : basis_(), rgrid_(), fieldIoPtr_(0), meshDimensions_(), meshSize_(0), nBasis_(0), nMonomer_(0), isAllocatedRGrid_(false), isAllocatedBasis_(false), hasData_(false), isSymmetric_(false) {} /* * Destructor. */ template <int D> WFieldContainer<D>::~WFieldContainer() {} /* * Create an association with a FieldIo object. */ template <int D> void WFieldContainer<D>::setFieldIo(FieldIo<D> const & fieldIo) { fieldIoPtr_ = &fieldIo; } /* * Set the stored value of nMonomer (this may only be called once). */ template <int D> void WFieldContainer<D>::setNMonomer(int nMonomer) { UTIL_CHECK(nMonomer_ == 0); UTIL_CHECK(nMonomer > 0); nMonomer_ = nMonomer; } /* * Allocate memory for fields in r-grid format. */ template <int D> void WFieldContainer<D>::allocateRGrid(IntVec<D> const & meshDimensions) { UTIL_CHECK(nMonomer_ > 0); // If already allocated, deallocate. if (isAllocatedRGrid_) { deallocateRGrid(); } // Store mesh dimensions meshDimensions_ = meshDimensions; meshSize_ = 1; for (int i = 0; i < D; ++i) { UTIL_CHECK(meshDimensions[i] > 0); meshSize_ *= meshDimensions[i]; } // Allocate arrays rgrid_.allocate(nMonomer_); for (int i = 0; i < nMonomer_; ++i) { rgrid_[i].allocate(meshDimensions); } isAllocatedRGrid_ = true; } /* * De-allocate memory for fields in r-grid format */ template <int D> void WFieldContainer<D>::deallocateRGrid() { UTIL_CHECK(isAllocatedRGrid_); UTIL_CHECK(nMonomer_ > 0); for (int i = 0; i < nMonomer_; ++i) { rgrid_[i].deallocate(); } rgrid_.deallocate(); meshDimensions_ = 0; meshSize_ = 0; isAllocatedRGrid_ = false; } /* * Allocate memory for fields in basis format. */ template <int D> void WFieldContainer<D>::allocateBasis(int nBasis) { UTIL_CHECK(nMonomer_ > 0); UTIL_CHECK(nBasis > 0); // If already allocated, deallocate. if (isAllocatedBasis_) { deallocateBasis(); } // Allocate nBasis_ = nBasis; basis_.allocate(nMonomer_); for (int i = 0; i < nMonomer_; ++i) { basis_[i].allocate(nBasis); } isAllocatedBasis_ = true; } /* * De-allocate memory for fields in basis format. */ template <int D> void WFieldContainer<D>::deallocateBasis() { UTIL_CHECK(isAllocatedBasis_); UTIL_CHECK(nMonomer_ > 0); for (int i = 0; i < nMonomer_; ++i) { basis_[i].deallocate(); } basis_.deallocate(); nBasis_ = 0; isAllocatedBasis_ = false; } /* * Allocate memory for all fields. */ template <int D> void WFieldContainer<D>::allocate(int nMonomer, int nBasis, IntVec<D> const & meshDimensions) { setNMonomer(nMonomer); allocateRGrid(meshDimensions); allocateBasis(nBasis); } /* * Set new w-field values. */ template <int D> void WFieldContainer<D>::setBasis(DArray< DArray<double> > const & fields) { UTIL_CHECK(fields.capacity() == nMonomer_); // Update system wFields for (int i = 0; i < nMonomer_; ++i) { DArray<double> const & f = fields[i]; DArray<double> & w = basis_[i]; UTIL_CHECK(f.capacity() == nBasis_); UTIL_CHECK(w.capacity() == nBasis_); for (int j = 0; j < nBasis_; ++j) { w[j] = f[j]; } } // Update system wFieldsRGrid fieldIoPtr_->convertBasisToRGrid(basis_, rgrid_); hasData_ = true; isSymmetric_ = true; } /* * Set new field values, using r-grid fields as inputs. */ template <int D> void WFieldContainer<D>::setRGrid(DArray< RField<D> > const & fields, bool isSymmetric) { UTIL_CHECK(fields.capacity() == nMonomer_); // Update system wFieldsRGrid for (int i = 0; i < nMonomer_; ++i) { RField<D> const & f = fields[i]; RField<D>& w = rgrid_[i]; UTIL_CHECK(f.capacity() == meshSize_); UTIL_CHECK(w.capacity() == meshSize_); for (int j = 0; j < meshSize_; ++j) { w[j] = f[j]; } } if (isSymmetric) { fieldIoPtr_->convertRGridToBasis(rgrid_, basis_); } hasData_ = true; isSymmetric_ = isSymmetric; } /* * 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. */ template <int D> void WFieldContainer<D>::readBasis(std::istream& in, UnitCell<D>& unitCell) { UTIL_CHECK(isAllocatedBasis()); fieldIoPtr_->readFieldsBasis(in, basis_, unitCell); // Update system wFieldsRGrid fieldIoPtr_->convertBasisToRGrid(basis_, rgrid_); hasData_ = true; isSymmetric_ = true; } /* * 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. */ template <int D> void WFieldContainer<D>::readBasis(std::string filename, UnitCell<D>& unitCell) { UTIL_CHECK(isAllocatedBasis()); fieldIoPtr_->readFieldsBasis(filename, basis_, unitCell); // Update system wFieldsRGrid fieldIoPtr_->convertBasisToRGrid(basis_, rgrid_); hasData_ = true; isSymmetric_ = true; } /* * 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. */ template <int D> void WFieldContainer<D>::readRGrid(std::istream& in, UnitCell<D>& unitCell, bool isSymmetric) { UTIL_CHECK(isAllocatedRGrid()); fieldIoPtr_->readFieldsRGrid(in, rgrid_, unitCell); if (isSymmetric) { fieldIoPtr_->convertRGridToBasis(rgrid_, basis_); } hasData_ = true; isSymmetric_ = isSymmetric; } /* * 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. */ template <int D> void WFieldContainer<D>::readRGrid(std::string filename, UnitCell<D>& unitCell, bool isSymmetric) { UTIL_CHECK(isAllocatedRGrid()); fieldIoPtr_->readFieldsRGrid(filename, rgrid_, unitCell); if (isSymmetric) { fieldIoPtr_->convertRGridToBasis(rgrid_, basis_); } hasData_ = true; isSymmetric_ = isSymmetric; } } // namespace Pspc } // namespace Pscf #endif
8,337
C++
.tpp
279
23.215054
72
0.60477
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,279
FFT.tpp
dmorse_pscfpp/src/pspc/field/FFT.tpp
#ifndef PSPC_FFT_TPP #define PSPC_FFT_TPP /* * PSCF Package * * Copyright 2016 - 2022, The Regents of the University of Minnesota * Distributed under the terms of the GNU General Public License. */ #include "FFT.h" namespace Pscf { namespace Pspc { using namespace Util; /* * Default constructor. */ template <int D> FFT<D>::FFT() : rFieldCopy_(), meshDimensions_(0), rSize_(0), kSize_(0), fPlan_(0), iPlan_(0), isSetup_(false) {} /* * Destructor. */ template <int D> FFT<D>::~FFT() { if (fPlan_) { fftw_destroy_plan(fPlan_); } if (iPlan_) { fftw_destroy_plan(iPlan_); } } /* * Setup mesh dimensions. */ template <int D> void FFT<D>::setup(IntVec<D> const& meshDimensions) { // Precondition UTIL_CHECK(!isSetup_); // Create local r-grid and k-grid field objects RField<D> rField; rField.allocate(meshDimensions); RFieldDft<D> kField; kField.allocate(meshDimensions); setup(rField, kField); } /* * Check and (if necessary) setup mesh dimensions. */ template <int D> void FFT<D>::setup(RField<D>& rField, RFieldDft<D>& kField) { // Preconditions UTIL_CHECK(!isSetup_); IntVec<D> rDimensions = rField.meshDimensions(); IntVec<D> kDimensions = kField.meshDimensions(); UTIL_CHECK(rDimensions == kDimensions); // Set and check mesh dimensions rSize_ = 1; kSize_ = 1; for (int i = 0; i < D; ++i) { UTIL_CHECK(rDimensions[i] > 0); meshDimensions_[i] = rDimensions[i]; rSize_ *= rDimensions[i]; if (i < D - 1) { kSize_ *= rDimensions[i]; } else { kSize_ *= (rDimensions[i]/2 + 1); } } UTIL_CHECK(rField.capacity() == rSize_); UTIL_CHECK(kField.capacity() == kSize_); // Allocate rFieldCopy_ array if necessary if (!rFieldCopy_.isAllocated()) { rFieldCopy_.allocate(rDimensions); } else { if (rFieldCopy_.capacity() != rSize_) { rFieldCopy_.deallocate(); rFieldCopy_.allocate(rDimensions); } } UTIL_CHECK(rFieldCopy_.capacity() == rSize_); // Allocate kFieldCopy_ array if necessary if (!kFieldCopy_.isAllocated()) { kFieldCopy_.allocate(kDimensions); } else { if (kFieldCopy_.capacity() != rSize_) { kFieldCopy_.deallocate(); kFieldCopy_.allocate(kDimensions); } } UTIL_CHECK(kFieldCopy_.capacity() == kSize_); // Make FFTW plans (see explicit specializations FFT.cpp) makePlans(rField, kField); isSetup_ = true; } /* * Execute forward transform. */ template <int D> void FFT<D>::forwardTransform(RField<D> const & rField, RFieldDft<D>& kField) const { UTIL_CHECK(isSetup_) UTIL_CHECK(rFieldCopy_.capacity() == rSize_); UTIL_CHECK(rField.capacity() == rSize_); UTIL_CHECK(kField.capacity() == kSize_); UTIL_CHECK(rField.meshDimensions() == meshDimensions_); UTIL_CHECK(kField.meshDimensions() == meshDimensions_); // Copy rescaled input data prior to work array double scale = 1.0/double(rSize_); for (int i = 0; i < rSize_; ++i) { rFieldCopy_[i] = rField[i]*scale; } // Execute preplanned forward transform fftw_execute_dft_r2c(fPlan_, &rFieldCopy_[0], &kField[0]); } /* * Execute inverse (complex-to-real) transform. */ template <int D> void FFT<D>::inverseTransform(RFieldDft<D> & kField, RField<D>& rField) const { UTIL_CHECK(isSetup_) UTIL_CHECK(rField.capacity() == rSize_); UTIL_CHECK(kField.capacity() == kSize_); UTIL_CHECK(rField.meshDimensions() == meshDimensions_); UTIL_CHECK(kField.meshDimensions() == meshDimensions_); fftw_execute_dft_c2r(iPlan_, &kField[0], &rField[0]); } /* * Execute inverse (complex-to-real) transform without destroying input. */ template <int D> void FFT<D>::inverseTransformSafe(RFieldDft<D> const & kField, RField<D>& rField) const { UTIL_CHECK(kFieldCopy_.capacity()==kField.capacity()); kFieldCopy_ = kField; inverseTransform(kFieldCopy_, rField); } } } #endif
4,392
C++
.tpp
153
22.51634
88
0.599287
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,280
RField.tpp
dmorse_pscfpp/src/pspc/field/RField.tpp
#ifndef PSPC_R_FIELD_TPP #define PSPC_R_FIELD_TPP /* * PSCF Package * * Copyright 2016 - 2022, The Regents of the University of Minnesota * Distributed under the terms of the GNU General Public License. */ #include "RField.h" namespace Pscf { namespace Pspc { using namespace Util; /** * Default constructor. */ template <int D> RField<D>::RField() : Field<double>() {} /* * Destructor. */ template <int D> RField<D>::~RField() {} /* * Copy constructor. * * Allocates new memory and copies all elements by value. * *\param other the Field to be copied. */ template <int D> RField<D>::RField(const RField<D>& other) : Field<double>(), meshDimensions_(0) { if (!other.isAllocated()) { UTIL_THROW("Other Field must be allocated."); } data_ = (double*) fftw_malloc(sizeof(double)*other.capacity_); capacity_ = other.capacity_; for (int i = 0; i < capacity_; ++i) { data_[i] = other.data_[i]; } meshDimensions_ = other.meshDimensions_; } /* * Assignment, element-by-element. * * This operator will allocate memory if not allocated previously. * * \throw Exception if other Field is not allocated. * \throw Exception if both Fields are allocated with unequal capacities. * * \param other the rhs Field */ template <int D> RField<D>& RField<D>::operator = (const RField<D>& other) { // Check for self assignment if (this == &other) return *this; // Precondition if (!other.isAllocated()) { UTIL_THROW("Other Field must be allocated."); } if (!isAllocated()) { allocate(other.capacity()); } else if (capacity_ != other.capacity_) { UTIL_THROW("Cannot assign Fields of unequal capacity"); } // Copy elements for (int i = 0; i < capacity_; ++i) { data_[i] = other[i]; } meshDimensions_ = other.meshDimensions_; return *this; } /* * Allocate the underlying C array for an FFT grid. */ template <int D> void RField<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]; } Field<double>::allocate(size); } } } #endif
2,432
C++
.tpp
96
20.28125
75
0.605082
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,281
FieldIo.tpp
dmorse_pscfpp/src/pspc/field/FieldIo.tpp
#ifndef PSPC_FIELD_IO_TPP #define PSPC_FIELD_IO_TPP /* * 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 "FieldIo.h" #include <pscf/crystal/shiftToMinimum.h> #include <pscf/mesh/MeshIterator.h> #include <pscf/math/IntVec.h> #include <util/misc/Log.h> #include <util/format/Str.h> #include <util/format/Int.h> #include <util/format/Dbl.h> #include <iomanip> #include <string> namespace Pscf { namespace Pspc { using namespace Util; /* * Constructor. */ template <int D> FieldIo<D>::FieldIo() : meshPtr_(0), fftPtr_(0), groupNamePtr_(0), groupPtr_(0), basisPtr_(0), fileMasterPtr_() {} /* * Destructor. */ template <int D> FieldIo<D>::~FieldIo() {} /* * Get and store addresses of associated objects. */ template <int D> void FieldIo<D>::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) { meshPtr_ = &mesh; fftPtr_ = &fft; latticePtr_ = &lattice; groupNamePtr_ = &groupName; groupPtr_ = &group; basisPtr_ = &basis; fileMasterPtr_ = &fileMaster; } template <int D> void FieldIo<D>::readFieldBasis(std::istream& in, DArray<double>& field, UnitCell<D>& unitCell) const { DArray<DArray<double> > fields; if (field.isAllocated()) { fields.allocate(1); fields[0].allocate(field.capacity()); } // otherwise pass unallocated field into readFieldsBasis readFieldsBasis(in, fields, unitCell); UTIL_CHECK(fields.capacity() == 1); // Check that it only read 1 field field = fields[0]; } template <int D> void FieldIo<D>::readFieldBasis(std::string filename, DArray<double>& field, UnitCell<D>& unitCell) const { DArray<DArray<double> > fields; if (field.isAllocated()) { fields.allocate(1); fields[0].allocate(field.capacity()); } // otherwise pass unallocated field into readFieldsBasis readFieldsBasis(filename, fields, unitCell); UTIL_CHECK(fields.capacity() == 1); // Check that it only read 1 field field = fields[0]; } template <int D> void FieldIo<D>::writeFieldBasis(std::ostream& out, DArray<double> const & field, UnitCell<D> const & unitCell) const { DArray<DArray<double> > fields; fields.allocate(1); fields[0].allocate(field.capacity()); fields[0] = field; writeFieldsBasis(out, fields, unitCell); } template <int D> void FieldIo<D>::writeFieldBasis(std::string filename, DArray<double> const & field, UnitCell<D> const & unitCell) const { DArray<DArray<double> > fields; fields.allocate(1); fields[0].allocate(field.capacity()); fields[0] = field; writeFieldsBasis(filename, fields, unitCell); } template <int D> void FieldIo<D>::readFieldsBasis(std::istream& in, DArray< DArray<double> >& fields, UnitCell<D>& unitCell) const { int nMonomer; FieldIo<D>::readFieldHeader(in, nMonomer, unitCell); UTIL_CHECK(basis().isInitialized()); // Read the number of stars into nStarIn std::string label; in >> label; if (label != "N_star" && label != "N_basis") { std::string msg = "\n"; msg += "Error reading field file:\n"; msg += "Expected N_basis or N_star, but found ["; msg += label; msg += "]"; UTIL_THROW(msg.c_str()); } int nStarIn; in >> nStarIn; UTIL_CHECK(nStarIn > 0); // If "fields" parameter is allocated, check if dimensions // match those of the system's mesh. Otherwise, allocate. int fieldCapacity; if (fields.isAllocated()) { // If outer DArray is allocated, require that it matches the // number of inputted fields and that internal DArrays are also // allocated all with the same dimensions. int nMonomerFields = fields.capacity(); UTIL_CHECK(nMonomerFields > 0); UTIL_CHECK(nMonomerFields == nMonomer); // Check that all internal DArrays have same dimension. fieldCapacity = fields[0].capacity(); for (int i = 0; i < nMonomer; ++i) { UTIL_CHECK( fields[i].capacity() == fieldCapacity ); } } else { // Else, allocate fields to the number of inputted fields // and the internal dimensions to the number of stars. fields.allocate(nMonomer); fieldCapacity = nStarIn; for (int i = 0; i < nMonomer; ++i) { fields[i].allocate(fieldCapacity); } } // Initialize all field array elements to zero for (int i = 0; i < nMonomer; ++i) { for (int j = 0; j < fieldCapacity; ++j) { fields[i][j] = 0.0; } } // Reset nStarIn = min(nStarIn, fieldCapacity) if (fieldCapacity < nStarIn) { nStarIn = fieldCapacity; } // Allocate temp arrays used to read in components DArray<double> temp, temp2; temp.allocate(nMonomer); temp2.allocate(nMonomer); typename Basis<D>::Star const * starPtr; typename Basis<D>::Star const * starPtr2; IntVec<D> waveIn, waveIn2; int sizeIn, sizeIn2; int starId, starId2; int basisId, basisId2; int waveId, waveId2; std::complex<double> coeff, phasor; IntVec<D> waveBz, waveDft; int nReversedPair = 0; bool waveExists, sizeMatches; // Loop over stars in input file to read field components int i = 0; while (i < nStarIn) { // Read next line of data for (int j = 0; j < nMonomer; ++j) { in >> temp[j]; // field components } in >> waveIn; // wave of star in >> sizeIn; // # of waves in star ++i; sizeMatches = false; waveExists = false; // Check if waveIn is in first Brillouin zone (FBZ) for the mesh. waveBz = shiftToMinimum(waveIn, mesh().dimensions(), unitCell); waveExists = (waveIn == waveBz); if (waveExists) { // Find the star containing waveIn waveDft = waveIn; mesh().shift(waveDft); waveId = basis().waveId(waveDft); starId = basis().wave(waveId).starId; starPtr = &basis().star(starId); UTIL_CHECK(!(starPtr->cancel)); basisId = starPtr->basisId; if (starPtr->size == sizeIn) { sizeMatches = true; } else { Log::file() << "Warning: Inconsistent star size (line ignored)\n" << "wave from file = " << waveIn << "\n" << "size from file = " << sizeIn << "\n" << "size of star = " << starPtr->size << "\n"; sizeMatches = false; } } if (waveExists && sizeMatches) { // Attempt to process wave if (starPtr->invertFlag == 0) { if (starPtr->waveBz == waveIn) { // Copy components of closed star to fields array for (int j = 0; j < nMonomer; ++j) { fields[j][basisId] = temp[j]; } } else { Log::file() << "Inconsistent wave of closed star on input\n" << "wave from file = " << waveIn << "\n" << "starId of wave = " << starId << "\n" << "waveBz of star = " << starPtr->waveBz << "\n"; } } else { // Read the next line for (int j = 0; j < nMonomer; ++j) { in >> temp2[j]; // components of field } in >> waveIn2; // wave of star in >> sizeIn2; // # of wavevectors in star ++i; // Check that waveIn2 is also in the 1st BZ waveBz = shiftToMinimum(waveIn2, mesh().dimensions(), unitCell); UTIL_CHECK(waveIn2 == waveBz); // Identify the star containing waveIn2 waveDft = waveIn2; mesh().shift(waveDft); waveId2 = basis().waveId(waveDft); starId2 = basis().wave(waveId2).starId; starPtr2 = &basis().star(starId2); UTIL_CHECK(!(starPtr2->cancel)); basisId2 = starPtr2->basisId; UTIL_CHECK(starPtr2->size == sizeIn2); UTIL_CHECK(sizeIn == sizeIn2); if (starPtr->invertFlag == 1) { // This is a pair of open stars written in the same // order as in this basis. Check preconditions: UTIL_CHECK(starPtr2->invertFlag == -1); UTIL_CHECK(starId2 = starId + 1); UTIL_CHECK(basisId2 = basisId + 1); UTIL_CHECK(starPtr->waveBz == waveIn); UTIL_CHECK(starPtr2->waveBz == waveIn2); // Copy components for both stars into fields array for (int j = 0; j < nMonomer; ++j) { fields[j][basisId] = temp[j]; fields[j][basisId2] = temp2[j]; } } else if (starPtr->invertFlag == -1) { // This is a pair of open stars written in opposite // order from in this basis. Check preconditions: UTIL_CHECK(starPtr2->invertFlag == 1); UTIL_CHECK(starId == starId2 + 1); UTIL_CHECK(basisId == basisId2 + 1); UTIL_CHECK(waveId == starPtr->beginId); // Check that waveIn2 is negation of waveIn IntVec<D> nVec; nVec.negate(waveIn); nVec = shiftToMinimum(nVec, mesh().dimensions(), unitCell); UTIL_CHECK(waveIn2 == nVec); /* * Consider two related stars, C and D, that are listed * in the order (C,D) in the basis used in this code (the * reading program), but that were listed in the opposite * order (D,C) in the program that wrote the file (the * writing program). In the basis of the reading program, * star C has star index starId2, while star D has index * starId = starid2 + 1. * * Let f(r) and f^{*}(r) denote the basis functions used * by the reading program for stars C and D, respectively. * Let u(r) and u^{*}(r) denote the corresponding basis * functions used by the writing program for stars C * and D. Let exp(i phi) denote the unit magnitude * coefficient (i.e., phasor) within f(r) of the wave * with wave index waveId2, which was the characteristic * wave for star C in the writing program. The * coefficient of this wave within the basis function * u(r) used by the writing program must instead be real * and positive. This implies that * u(r) = exp(-i phi) f(r). * * Focus on the contribution to the field for a specific * monomer type j. Let a and b denote the desired * coefficients of stars C and D in the reading program, * for which the total contribution of both stars to the * field is: * * (a - ib) f(r) + (a + ib) f^{*}(r) * * Let A = temp[j] and B = temp2[j] denote the * coefficients read from file in order (A,B). Noting * that the stars were listed in the order (D,C) in the * basis used by the writing program, the contribution * of both stars must be (A-iB)u^{*}(r)+(A+iB)u(r), or: * * (A+iB) exp(-i phi)f(r) + (A-iB) exp(i phi) f^{*}(r) * * Comparing coefficients of f^{*}(r), we find that * * (a + ib) = (A - iB) exp(i phi) * * This equality is implemented below, where the * variable "phasor" is set equal to exp(i phi). */ phasor = basis().wave(waveId2).coeff; phasor = phasor/std::abs(phasor); for (int j = 0; j < nMonomer; ++j) { coeff = std::complex<double>(temp[j],-temp2[j]); coeff *= phasor; fields[j][basisId2] = real(coeff); fields[j][basisId ] = imag(coeff); } // Increment count of number of reversed open pairs ++nReversedPair; } else { UTIL_THROW("Invalid starInvert value"); } } // if (wavePtr->invertFlag == 0) ... else ... } // if (waveExists && sizeMatches) } // end while (i < nStarIn) if (nReversedPair > 0) { Log::file() << "\n"; Log::file() << nReversedPair << " reversed pairs of open stars" << " detected in FieldIo::readFieldsBasis\n"; } } template <int D> void FieldIo<D>::readFieldsBasis(std::string filename, DArray<DArray<double> >& fields, UnitCell<D>& unitCell) const { std::ifstream file; fileMaster().openInputFile(filename, file); readFieldsBasis(file, fields, unitCell); file.close(); } template <int D> void FieldIo<D>::writeFieldsBasis(std::ostream &out, DArray<DArray<double> > const & fields, UnitCell<D> const & unitCell) const { int nMonomer = fields.capacity(); UTIL_CHECK(nMonomer > 0); UTIL_CHECK(basis().isInitialized()); // Write header writeFieldHeader(out, nMonomer, unitCell); int nStar = basis().nStar(); int nBasis = basis().nBasis(); out << "N_basis " << std::endl << " " << nBasis << std::endl; // Write fields int ib = 0; for (int i = 0; i < nStar; ++i) { if (!basis().star(i).cancel) { for (int j = 0; j < nMonomer; ++j) { out << Dbl(fields[j][ib], 20, 10); } out << " "; for (int j = 0; j < D; ++j) { out << Int(basis().star(i).waveBz[j], 5); } out << Int(basis().star(i).size, 5) << std::endl; ++ib; } } } template <int D> void FieldIo<D>::writeFieldsBasis(std::string filename, DArray<DArray<double> > const & fields, UnitCell<D> const & unitCell) const { std::ofstream file; fileMaster().openOutputFile(filename, file); writeFieldsBasis(file, fields, unitCell); file.close(); } template <int D> void FieldIo<D>::readFieldsRGrid(std::istream &in, DArray<RField<D> >& fields, UnitCell<D>& unitCell) const { int nMonomer; FieldIo<D>::readFieldHeader(in, nMonomer, unitCell); // If "fields" parameter is allocated, check if dimensions match // those of the system's mesh. Otherwise, allocate. if (fields.isAllocated()) { int nMonomerFields = fields.capacity(); UTIL_CHECK(nMonomerFields > 0); UTIL_CHECK(nMonomerFields == nMonomer); for (int i = 0; i < nMonomer; ++i) { UTIL_CHECK(fields[i].meshDimensions() == mesh().dimensions()); } } else { fields.allocate(nMonomer); for (int i = 0; i < nMonomer; ++i) { fields[i].allocate(mesh().dimensions()); } } // Read and check input stream mesh dimensions std::string label; in >> label; if (label != "mesh" && label != "ngrid") { std::string msg = "\n"; msg += "Error reading field file:\n"; msg += "Expected mesh or ngrid, but found ["; msg += label; msg += "]"; UTIL_THROW(msg.c_str()); } IntVec<D> nGrid; in >> nGrid; UTIL_CHECK(nGrid == mesh().dimensions()); // Setup temporary workspace array. DArray<RField<D> > temp; temp.allocate(nMonomer); for (int i = 0; i < nMonomer; ++i) { temp[i].allocate(mesh().dimensions()); } // Read Fields; MeshIterator<D> itr(mesh().dimensions()); for (itr.begin(); !itr.atEnd(); ++itr) { for (int i = 0; i < nMonomer; ++i) { in >> std::setprecision(15) >> temp[i][itr.rank()]; } } int p = 0; int q = 0; int r = 0; int s = 0; int n1 = 0; int n2 = 0; int n3 = 0; if (D==3) { while (n1 < mesh().dimension(0)) { q = p; n2 = 0; while (n2 < mesh().dimension(1)) { r = q; n3 = 0; while (n3 < mesh().dimension(2)) { for (int i = 0; i < nMonomer; ++i) { fields[i][s] = temp[i][r]; } r = r + (mesh().dimension(0) * mesh().dimension(1)); ++s; ++n3; } q = q + mesh().dimension(0); ++n2; } ++n1; ++p; } } else if (D==2) { while (n1 < mesh().dimension(0)) { r =q; n2 = 0; while (n2 < mesh().dimension(1)) { for (int i = 0; i < nMonomer; ++i) { fields[i][s] = temp[i][r]; } r = r + (mesh().dimension(0)); ++s; ++n2; } ++q; ++n1; } } else if (D==1) { while (n1 < mesh().dimension(0)) { for (int i = 0; i < nMonomer; ++i) { fields[i][s] = temp[i][r]; } ++r; ++s; ++n1; } } else{ Log::file() << "Invalid Dimensions"; } } template <int D> void FieldIo<D>::readFieldsRGrid(std::string filename, DArray< RField<D> >& fields, UnitCell<D>& unitCell) const { std::ifstream file; fileMaster().openInputFile(filename, file); readFieldsRGrid(file, fields, unitCell); file.close(); } template <int D> void FieldIo<D>::writeFieldsRGrid(std::ostream &out, DArray<RField<D> > const & fields, UnitCell<D> const & unitCell) const { int nMonomer = fields.capacity(); UTIL_CHECK(nMonomer > 0); writeFieldHeader(out, nMonomer, unitCell); out << "mesh " << std::endl << " " << mesh().dimensions() << std::endl; DArray<RField<D> > temp; temp.allocate(nMonomer); for (int i = 0; i < nMonomer; ++i) { temp[i].allocate(mesh().dimensions()); } int p = 0; int q = 0; int r = 0; int s = 0; int n1 =0; int n2 =0; int n3 =0; if (D==3) { while (n3 < mesh().dimension(2)) { q = p; n2 = 0; while (n2 < mesh().dimension(1)) { r =q; n1 = 0; while (n1 < mesh().dimension(0)) { for (int i = 0; i < nMonomer; ++i) { temp[i][s] = fields[i][r]; } r = r + (mesh().dimension(1) * mesh().dimension(2)); ++s; ++n1; } q = q + mesh().dimension(2); ++n2; } ++n3; ++p; } } else if (D==2) { while (n2 < mesh().dimension(1)) { r =q; n1 = 0; while (n1 < mesh().dimension(0)) { for (int i = 0; i < nMonomer; ++i) { temp[i][s] = fields[i][r]; } r = r + (mesh().dimension(1)); ++s; ++n1; } ++q; ++n2; } } else if (D==1) { while (n1 < mesh().dimension(0)) { for (int i = 0; i < nMonomer; ++i) { temp[i][s] = fields[i][r]; } ++r; ++s; ++n1; } } else { Log::file() << "Invalid Dimensions"; } // Write fields MeshIterator<D> itr(mesh().dimensions()); for (itr.begin(); !itr.atEnd(); ++itr) { for (int j = 0; j < nMonomer; ++j) { out << " " << Dbl(temp[j][itr.rank()], 18, 15); } out << std::endl; } } template <int D> void FieldIo<D>::writeFieldsRGrid(std::string filename, DArray< RField<D> > const & fields, UnitCell<D> const & unitCell) const { std::ofstream file; fileMaster().openOutputFile(filename, file); writeFieldsRGrid(file, fields, unitCell); file.close(); } template <int D> void FieldIo<D>::readFieldRGrid(std::istream &in, RField<D> & field, UnitCell<D>& unitCell) const { int nMonomer; FieldIo<D>::readFieldHeader(in, nMonomer, unitCell); // Only reading in a file with a single field. UTIL_CHECK(nMonomer == 1); // If "field" parameter is allocated, check if dimensions match // those of the system's mesh. Otherwise, allocate. if (field.isAllocated()) { UTIL_CHECK(field.meshDimensions() == mesh().dimensions()); } else { field.allocate(mesh().dimensions()); } // Read and check input stream mesh dimensions std::string label; in >> label; if (label != "mesh" && label != "ngrid") { std::string msg = "\n"; msg += "Error reading field file:\n"; msg += "Expected mesh or ngrid, but found ["; msg += label; msg += "]"; UTIL_THROW(msg.c_str()); } IntVec<D> nGrid; in >> nGrid; UTIL_CHECK(nGrid == mesh().dimensions()); // Setup temporary workspace. RField<D> temp; temp.allocate(mesh().dimensions()); // Read Field; MeshIterator<D> itr(mesh().dimensions()); for (itr.begin(); !itr.atEnd(); ++itr) { in >> std::setprecision(15) >> temp[itr.rank()]; } int p = 0; int q = 0; int r = 0; int s = 0; int n1 = 0; int n2 = 0; int n3 = 0; if (D==3) { while (n1 < mesh().dimension(0)) { q = p; n2 = 0; while (n2 < mesh().dimension(1)) { r = q; n3 = 0; while (n3 < mesh().dimension(2)) { field[s] = temp[r]; r = r + (mesh().dimension(0) * mesh().dimension(1)); ++s; ++n3; } q = q + mesh().dimension(0); ++n2; } ++n1; ++p; } } else if (D==2) { while (n1 < mesh().dimension(0)) { r =q; n2 = 0; while (n2 < mesh().dimension(1)) { field[s] = temp[r]; r = r + (mesh().dimension(0)); ++s; ++n2; } ++q; ++n1; } } else if (D==1) { while (n1 < mesh().dimension(0)) { field[s] = temp[r]; ++r; ++s; ++n1; } } else{ Log::file() << "Invalid Dimensions"; } } template <int D> void FieldIo<D>::readFieldRGrid(std::string filename, RField<D> & field, UnitCell<D>& unitCell) const { std::ifstream file; fileMaster().openInputFile(filename, file); readFieldRGrid(file, field, unitCell); file.close(); } template <int D> void FieldIo<D>::writeFieldRGrid(std::ostream &out, RField<D> const & field, UnitCell<D> const & unitCell, bool writeHeader) const { if (writeHeader) { writeFieldHeader(out, 1, unitCell); out << "mesh " << std::endl << " " << mesh().dimensions() << std::endl; } RField<D> temp; temp.allocate(mesh().dimensions()); int p = 0; int q = 0; int r = 0; int s = 0; int n1 =0; int n2 =0; int n3 =0; if (D==3) { while (n3 < mesh().dimension(2)) { q = p; n2 = 0; while (n2 < mesh().dimension(1)) { r =q; n1 = 0; while (n1 < mesh().dimension(0)) { temp[s] = field[r]; r = r + (mesh().dimension(1) * mesh().dimension(2)); ++s; ++n1; } q = q + mesh().dimension(2); ++n2; } ++n3; ++p; } } else if (D==2) { while (n2 < mesh().dimension(1)) { r =q; n1 = 0; while (n1 < mesh().dimension(0)) { temp[s] = field[r]; r = r + (mesh().dimension(1)); ++s; ++n1; } ++q; ++n2; } } else if (D==1) { while (n1 < mesh().dimension(0)) { temp[s] = field[r]; ++r; ++s; ++n1; } } else { Log::file() << "Invalid Dimensions"; } // Write field MeshIterator<D> itr(mesh().dimensions()); for (itr.begin(); !itr.atEnd(); ++itr) { out << " " << Dbl(temp[itr.rank()], 18, 15); out << std::endl; } } template <int D> void FieldIo<D>::writeFieldRGrid(std::string filename, RField<D> const & field, UnitCell<D> const & unitCell) const { std::ofstream file; fileMaster().openOutputFile(filename, file); writeFieldRGrid(file, field, unitCell); file.close(); } template <int D> void FieldIo<D>::readFieldsKGrid(std::istream &in, DArray<RFieldDft<D> >& fields, UnitCell<D>& unitCell) const { int nMonomer; FieldIo<D>::readFieldHeader(in, nMonomer, unitCell); // If "fields" parameter is allocated, check if dimensions match // those of the system's mesh. Otherwise, allocate. if (fields.isAllocated()) { int nMonomerFields = fields.capacity(); UTIL_CHECK(nMonomerFields > 0) UTIL_CHECK(nMonomerFields == nMonomer) for (int i = 0; i < nMonomer; ++i) { UTIL_CHECK(fields[i].meshDimensions() == mesh().dimensions()); } } else { fields.allocate(nMonomer); for (int i = 0; i < nMonomer; ++i) { fields[i].allocate(mesh().dimensions()); } } // Read and check input stream mesh dimensions std::string label; in >> label; if (label != "mesh" && label != "ngrid") { std::string msg = "\n"; msg += "Error reading field file:\n"; msg += "Expected mesh or ngrid, but found ["; msg += label; msg += "]"; UTIL_THROW(msg.c_str()); } IntVec<D> nGrid; in >> nGrid; UTIL_CHECK(nGrid == mesh().dimensions()); // Read fields; int i, idum; MeshIterator<D> itr(fields[0].dftDimensions()); i = 0; for (itr.begin(); !itr.atEnd(); ++itr) { in >> idum; UTIL_CHECK(i == idum); UTIL_CHECK(i == itr.rank()); for (int i = 0; i < nMonomer; ++i) { for (int j = 0; j < 2; ++j) { in >> fields[i][itr.rank()][j]; } } ++i; } } template <int D> void FieldIo<D>::readFieldsKGrid(std::string filename, DArray< RFieldDft<D> >& fields, UnitCell<D>& unitCell) const { std::ifstream file; fileMaster().openInputFile(filename, file); readFieldsKGrid(file, fields, unitCell); file.close(); } template <int D> void FieldIo<D>::writeFieldsKGrid(std::ostream &out, DArray<RFieldDft<D> > const & fields, UnitCell<D> const & unitCell) const { // Inspect fields array int nMonomer = fields.capacity(); UTIL_CHECK(nMonomer > 0); for (int i = 0; i < nMonomer; ++i) { UTIL_CHECK(fields[i].meshDimensions() == mesh().dimensions()); } // Write header writeFieldHeader(out, nMonomer, unitCell); out << "mesh " << std::endl << " " << mesh().dimensions() << std::endl; // Write fields MeshIterator<D> itr(fields[0].dftDimensions()); int i = 0; for (itr.begin(); !itr.atEnd(); ++itr) { UTIL_CHECK(i == itr.rank()); out << Int(itr.rank(), 5); for (int j = 0; j < nMonomer; ++j) { out << " " << Dbl(fields[j][itr.rank()][0], 20, 12) << Dbl(fields[j][itr.rank()][1], 20, 12); } out << std::endl; ++i; } } template <int D> void FieldIo<D>::writeFieldsKGrid(std::string filename, DArray< RFieldDft<D> > const & fields, UnitCell<D> const & unitCell) const { std::ofstream file; fileMaster().openOutputFile(filename, file); writeFieldsKGrid(file, fields, unitCell); file.close(); } /* * Read common part of field header and extract * the number of monomers (number of fields) in the file. */ template <int D> void FieldIo<D>::readFieldHeader(std::istream& in, int& nMonomer, UnitCell<D>& unitCell) const { // Preconditions UTIL_CHECK(latticePtr_); UTIL_CHECK(groupNamePtr_); if (unitCell.lattice() == UnitCell<D>::Null) { UTIL_CHECK(unitCell.nParameter() == 0); } else { UTIL_CHECK(unitCell.nParameter() > 0); if (lattice() != UnitCell<D>::Null) { UTIL_CHECK(unitCell.lattice() == lattice()); } } // Read field header to set unitCell, groupNameIn, nMonomer int ver1, ver2; std::string groupNameIn; Pscf::readFieldHeader(in, ver1, ver2, unitCell, groupNameIn, nMonomer); // Note: Function definition in pscf/crystal/UnitCell.tpp // Checks of data from header UTIL_CHECK(ver1 == 1); UTIL_CHECK(ver2 == 0); UTIL_CHECK(unitCell.isInitialized()); UTIL_CHECK(unitCell.lattice() != UnitCell<D>::Null); UTIL_CHECK(unitCell.nParameter() > 0); // Validate or initialize lattice type if (lattice() == UnitCell<D>::Null) { lattice() = unitCell.lattice(); } else { if (lattice() != unitCell.lattice()) { Log::file() << std::endl << "Error - " << "Mismatched lattice types, FieldIo::readFieldHeader:\n" << " FieldIo::lattice :" << lattice() << "\n" << " Unit cell lattice :" << unitCell.lattice() << "\n"; UTIL_THROW("Mismatched lattice types"); } } // Validate or initialize group name if (groupName() == "") { groupName() = groupNameIn; } else { if (groupNameIn != groupName()) { Log::file() << std::endl << "Error - " << "Mismatched group names in FieldIo::readFieldHeader:\n" << " FieldIo::groupName :" << groupName() << "\n" << " Field file header :" << groupNameIn << "\n"; UTIL_THROW("Mismatched group names"); } } // Check group, read from file if necessary UTIL_CHECK(groupPtr_); if (group().size() == 1) { if (groupName() != "I") { readGroup(groupName(), group()); } } // Check basis, construct if not initialized UTIL_CHECK(basisPtr_); if (!basis().isInitialized()) { basisPtr_->makeBasis(mesh(), unitCell, group()); } UTIL_CHECK(basis().isInitialized()); } template <int D> void FieldIo<D>::writeFieldHeader(std::ostream &out, int nMonomer, UnitCell<D> const & unitCell) const { int ver1 = 1; int ver2 = 0; Pscf::writeFieldHeader(out, ver1, ver2, unitCell, groupName(), nMonomer); // Note: This function is defined in pscf/crystal/UnitCell.tpp } template <int D> void FieldIo<D>::convertBasisToKGrid(DArray<double> const & in, RFieldDft<D>& out) const { UTIL_CHECK(basis().isInitialized()); // Create Mesh<D> with dimensions of DFT Fourier grid. Mesh<D> dftMesh(out.dftDimensions()); typename Basis<D>::Star const* starPtr; // pointer to current star typename Basis<D>::Wave const* wavePtr; // pointer to current wave std::complex<double> component; // coefficient for star std::complex<double> coeff; // coefficient for wave IntVec<D> indices; // dft grid indices of wave int rank; // dft grid rank of wave int is; // star index int ib; // basis index int iw; // wave index // Initialize all dft coponents to zero for (rank = 0; rank < dftMesh.size(); ++rank) { out[rank][0] = 0.0; out[rank][1] = 0.0; } // Loop over stars, skipping cancelled stars is = 0; while (is < basis().nStar()) { starPtr = &(basis().star(is)); if (starPtr->cancel) { ++is; continue; } // Set basisId for uncancelled star ib = starPtr->basisId; if (starPtr->invertFlag == 0) { // Make complex coefficient for star basis function component = std::complex<double>(in[ib], 0.0); // Loop over waves in closed star for (iw = starPtr->beginId; iw < starPtr->endId; ++iw) { wavePtr = &basis().wave(iw); if (!wavePtr->implicit) { coeff = component*(wavePtr->coeff); indices = wavePtr->indicesDft; rank = dftMesh.rank(indices); out[rank][0] = coeff.real(); out[rank][1] = coeff.imag(); } } ++is; } else if (starPtr->invertFlag == 1) { // Loop over waves in first star component = std::complex<double>(in[ib], -in[ib+1]); component /= sqrt(2.0); starPtr = &(basis().star(is)); for (iw = starPtr->beginId; iw < starPtr->endId; ++iw) { wavePtr = &basis().wave(iw); if (!(wavePtr->implicit)) { coeff = component*(wavePtr->coeff); indices = wavePtr->indicesDft; rank = dftMesh.rank(indices); out[rank][0] = coeff.real(); out[rank][1] = coeff.imag(); } } // Loop over waves in second star starPtr = &(basis().star(is+1)); UTIL_CHECK(starPtr->invertFlag == -1); component = std::complex<double>(in[ib], +in[ib+1]); component /= sqrt(2.0); for (iw = starPtr->beginId; iw < starPtr->endId; ++iw) { wavePtr = &basis().wave(iw); if (!(wavePtr->implicit)) { coeff = component*(wavePtr->coeff); indices = wavePtr->indicesDft; rank = dftMesh.rank(indices); out[rank][0] = coeff.real(); out[rank][1] = coeff.imag(); } } // Increment is by 2 (two stars were processed) is += 2; } else { UTIL_THROW("Invalid invertFlag value"); } } } template <int D> void FieldIo<D>::convertKGridToBasis(RFieldDft<D> const & in, DArray<double>& out, bool checkSymmetry, double epsilon) const { UTIL_CHECK(basis().isInitialized()); if (checkSymmetry) { // Check if kgrid has symmetry bool symmetric = hasSymmetry(in, epsilon, true); if (!symmetric) { Log::file() << std::endl << "WARNING: non-negligible error in conversion to " << "symmetry-adapted basis format." << std::endl << " See error values printed above for each " << "asymmetric field." << std::endl << " The field that is output by the above operation " << "will be a" << std::endl << " symmetrized version of the input field." << std::endl << std::endl; } } // Create Mesh<D> with dimensions of DFT Fourier grid. Mesh<D> dftMesh(in.dftDimensions()); typename Basis<D>::Star const* starPtr; // pointer to current star typename Basis<D>::Wave const* wavePtr; // pointer to current wave std::complex<double> component; // coefficient for star int rank; // dft grid rank of wave int is; // star index int ib; // basis index // Initialize all components to zero for (is = 0; is < basis().nBasis(); ++is) { out[is] = 0.0; } // Loop over stars is = 0; while (is < basis().nStar()) { starPtr = &(basis().star(is)); if (starPtr->cancel) { ++is; continue; } // Set basis id for uncancelled star ib = starPtr->basisId; if (starPtr->invertFlag == 0) { // Choose a wave in the star that is not implicit int beginId = starPtr->beginId; int endId = starPtr->endId; int iw = 0; bool isImplicit = true; while (isImplicit) { wavePtr = &basis().wave(beginId + iw); if (!wavePtr->implicit) { isImplicit = false; } else { UTIL_CHECK(beginId + iw < endId - 1 - iw); wavePtr = &basis().wave(endId - 1 - iw); if (!wavePtr->implicit) { isImplicit = false; } } ++iw; } UTIL_CHECK(wavePtr->starId == is); // Compute component value rank = dftMesh.rank(wavePtr->indicesDft); component = std::complex<double>(in[rank][0], in[rank][1]); component /= wavePtr->coeff; out[ib] = component.real(); ++is; } else if (starPtr->invertFlag == 1) { // Identify a characteristic wave that is not implicit: // Either the first wave of the 1st star or last wave of 2nd wavePtr = &basis().wave(starPtr->beginId); UTIL_CHECK(wavePtr->starId == is); if (wavePtr->implicit) { starPtr = &(basis().star(is+1)); UTIL_CHECK(starPtr->invertFlag == -1); wavePtr = &basis().wave(starPtr->endId - 1); UTIL_CHECK(!(wavePtr->implicit)); UTIL_CHECK(wavePtr->starId == is+1); } rank = dftMesh.rank(wavePtr->indicesDft); component = std::complex<double>(in[rank][0], in[rank][1]); UTIL_CHECK(std::abs(wavePtr->coeff) > 1.0E-8); component /= wavePtr->coeff; component *= sqrt(2.0); // Compute basis function coefficient values if (starPtr->invertFlag == 1) { out[ib] = component.real(); out[ib+1] = -component.imag(); } else { out[ib] = component.real(); out[ib+1] = component.imag(); } is += 2; } else { UTIL_THROW("Invalid invertFlag value"); } } // loop over star index is } template <int D> void FieldIo<D>::convertBasisToKGrid(DArray< DArray <double> > const & in, DArray< RFieldDft<D> >& out) const { UTIL_ASSERT(in.capacity() == out.capacity()); int n = in.capacity(); for (int i = 0; i < n; ++i) { convertBasisToKGrid(in[i], out[i]); } } template <int D> void FieldIo<D>::convertKGridToBasis(DArray< RFieldDft<D> > const & in, DArray< DArray <double> > & out, bool checkSymmetry, double epsilon) const { UTIL_ASSERT(in.capacity() == out.capacity()); int n = in.capacity(); bool symmetric(true); for (int i = 0; i < n; ++i) { if (checkSymmetry) { // Check if kgrid has symmetry bool tmp_sym = hasSymmetry(in[i], epsilon, true); if (!tmp_sym) symmetric = false; } convertKGridToBasis(in[i], out[i], false); } // Print warning if any input field is assymmetric if (!symmetric) { Log::file() << std::endl << "WARNING: non-negligible error in conversion to " << "symmetry-adapted basis format." << std::endl << "See error values printed above for each asymmetric field." << std::endl << "The field that is output by this operation will be " << "a symmetrized version of" << std::endl << "the input field." << std::endl << std::endl; } } template <int D> void FieldIo<D>::convertBasisToRGrid(DArray<double> const & in, RField<D>& out) const { checkWorkDft(); convertBasisToKGrid(in, workDft_); fft().inverseTransformSafe(workDft_, out); } template <int D> void FieldIo<D>::convertBasisToRGrid(DArray< DArray <double> > const & in, DArray< RField<D> >& out) const { UTIL_ASSERT(in.capacity() == out.capacity()); checkWorkDft(); int n = in.capacity(); for (int i = 0; i < n; ++i) { convertBasisToKGrid(in[i], workDft_); fft().inverseTransformSafe(workDft_, out[i]); } } template <int D> void FieldIo<D>::convertRGridToBasis(RField<D> const & in, DArray<double> & out, bool checkSymmetry, double epsilon) const { checkWorkDft(); fft().forwardTransform(in, workDft_); convertKGridToBasis(workDft_, out, checkSymmetry, epsilon); } template <int D> void FieldIo<D>::convertRGridToBasis(DArray< RField<D> > const & in, DArray< DArray <double> > & out, bool checkSymmetry, double epsilon) const { UTIL_ASSERT(in.capacity() == out.capacity()); checkWorkDft(); int n = in.capacity(); bool symmetric(true); for (int i = 0; i < n; ++i) { fft().forwardTransform(in[i], workDft_); if (checkSymmetry) { // Check if kgrid has symmetry bool tmp_sym = hasSymmetry(workDft_, epsilon, true); if (!tmp_sym) symmetric = false; } convertKGridToBasis(workDft_, out[i], false); } // Print warning if any input fields is asymmetric if (!symmetric) { Log::file() << std::endl << "WARNING: non-negligible error in conversion to " << "symmetry-adapted basis format." << std::endl << " See error values printed above for each " << "asymmetric field." << std::endl << " The field that is output by the above operation " << "will be a" << std::endl << " symmetrized version of the input field." << std::endl << std::endl; } } /* * Apply inverse FFT to an array of k-grid fields. */ template <int D> void FieldIo<D>::convertKGridToRGrid(DArray< RFieldDft<D> > & in, DArray< RField<D> >& out) const { UTIL_ASSERT(in.capacity() == out.capacity()); int n = in.capacity(); for (int i = 0; i < n; ++i) { fft().inverseTransformSafe(in[i], out[i]); } } /* * Apply inverse FFT to a single k-grid field. */ template <int D> void FieldIo<D>::convertKGridToRGrid(RFieldDft<D>& in, RField<D>& out) const { fft().inverseTransformSafe(in, out); } /* * Apply forward FFT to an array of r-grid fields. */ template <int D> void FieldIo<D>::convertRGridToKGrid(DArray< RField<D> > const & in, DArray< RFieldDft<D> >& out) const { UTIL_ASSERT(in.capacity() == out.capacity()); int n = in.capacity(); for (int i = 0; i < n; ++i) { fft().forwardTransform(in[i], out[i]); } } /* * Apply forward FFT to a single r-grid field. */ template <int D> void FieldIo<D>::convertRGridToKGrid(RField<D> const & in, RFieldDft<D>& out) const { fft().forwardTransform(in, out); } /* * Test if an RField<D> has declared space group symmetry. * Return true if symmetric, false otherwise. Print error values * if verbose == true and hasSymmetry == false. */ template <int D> bool FieldIo<D>::hasSymmetry(RField<D> const & in, double epsilon, bool verbose) const { checkWorkDft(); fft().forwardTransform(in, workDft_); return hasSymmetry(workDft_, epsilon, verbose); } /* * Test if an RFieldDft has the declared space group symmetry. * Return true if symmetric, false otherwise. Print error values * if verbose == true and hasSymmetry == false. */ template <int D> bool FieldIo<D>::hasSymmetry(RFieldDft<D> const & in, double epsilon, bool verbose) const { UTIL_CHECK(basis().isInitialized()); typename Basis<D>::Star const* starPtr; // pointer to current star typename Basis<D>::Wave const* wavePtr; // pointer to current wave std::complex<double> waveCoeff; // coefficient from wave std::complex<double> rootCoeff; // coefficient from root std::complex<double> diff; // coefficient difference int is; // star index int iw; // wave index int beginId, endId; // star begin, end ids int rank; // dft grid rank of wave double cancelledError(0.0); // max error from cancelled stars double uncancelledError(0.0); // max error from uncancelled stars // Create Mesh<D> with dimensions of DFT Fourier grid. Mesh<D> dftMesh(in.dftDimensions()); // Loop over all stars for (is = 0; is < basis().nStar(); ++is) { starPtr = &(basis().star(is)); if (starPtr->cancel) { // Check that coefficients are zero for all waves in star beginId = starPtr->beginId; endId = starPtr->endId; for (iw = beginId; iw < endId; ++iw) { wavePtr = &basis().wave(iw); if (!wavePtr->implicit) { rank = dftMesh.rank(wavePtr->indicesDft); waveCoeff = std::complex<double>(in[rank][0], in[rank][1]); if (std::abs(waveCoeff) > cancelledError) { cancelledError = std::abs(waveCoeff); if ((!verbose) && (cancelledError > epsilon)) { return false; } } } } } else { // Check consistency of coeff values from all waves bool hasRoot = false; beginId = starPtr->beginId; endId = starPtr->endId; for (iw = beginId; iw < endId; ++iw) { wavePtr = &basis().wave(iw); if (!(wavePtr->implicit)) { rank = dftMesh.rank(wavePtr->indicesDft); waveCoeff = std::complex<double>(in[rank][0], in[rank][1]); waveCoeff /= wavePtr->coeff; if (hasRoot) { diff = waveCoeff - rootCoeff; if (std::abs(diff) > uncancelledError) { uncancelledError = std::abs(diff); if ((!verbose) && (uncancelledError > epsilon)) { return false; } } } else { rootCoeff = waveCoeff; hasRoot = true; } } } } } // end loop over star index is if ((cancelledError < epsilon) && (uncancelledError < epsilon)) { return true; } else if (verbose) { Log::file() << std::endl << "Maximum coefficient of a cancelled star: " << cancelledError << std::endl << "Maximum error of coefficient for uncancelled star: " << uncancelledError << std::endl; } return false; } template <int D> void FieldIo<D>::checkWorkDft() const { if (!workDft_.isAllocated()) { workDft_.allocate(mesh().dimensions()); } else { UTIL_CHECK(workDft_.meshDimensions() == fft().meshDimensions()); } } } // namespace Pspc } // namespace Pscf #endif
52,710
C++
.tpp
1,442
24.823162
77
0.47945
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,282
main.cpp
n1rml_esp32_airmouse/main/main.cpp
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "freertos/event_groups.h" #include "esp_system.h" #include "esp_wifi.h" #include "esp_event.h" #include "esp_log.h" #include "nvs_flash.h" #include "esp_bt.h" #include "driver/gpio.h" #include "config.h" #include "ble_hid/hal_ble.h" #include "esp_gap_ble_api.h" #include "driver/gpio.h" #include "driver/uart.h" // #include "keyboard.h" #include "mpu6050.h" #include "MPU6050_6Axis_MotionApps20.h" /** demo mouse speed */ #define MOUSE_SPEED 20 #define SCROLL_SENS 0.5 #define CONSOLE_UART_TAG "CONSOLE_UART" //MPU Pins #define PIN_SDA 22 #define PIN_CLK 23 // BUTTON Pins #define BUTTON_0 GPIO_NUM_13 #define BUTTON_1 GPIO_NUM_25 #define BUTTON_2 GPIO_NUM_34 // MPU vars Quaternion q; // [w, x, y, z] quaternion container VectorFloat gravity; // [x, y, z] gravity vector float ypr[3]; // [yaw, pitch, roll] yaw/pitch/roll container and gravity vector uint16_t packetSize = 42; // expected DMP packet size (default is 42 bytes) uint16_t fifoCount; // count of all bytes currently in FIFO uint8_t fifoBuffer[64]; // FIFO storage buffer uint8_t mpuIntStatus; // holds actual interrupt status byte from MPU float yaw = 0.0, pitch = 0.0, roll = 0.0; float vertZero = 0, horzZero = 0, scrlZero = 0; float vertValue, horzValue, scrlValue; static config_data_t config; QueueHandle_t hid_ble; void blink_task(void *pvParameter) { // Initialize GPIO pins gpio_pad_select_gpio(INDICATOR_LED_PIN); gpio_set_direction(INDICATOR_LED_PIN, GPIO_MODE_OUTPUT); int blinkTime; while(1) { if (halBLEIsConnected()) blinkTime=1000; else blinkTime=250; /* Blink off (output low) */ gpio_set_level(INDICATOR_LED_PIN, 0); vTaskDelay(blinkTime / portTICK_PERIOD_MS); /* Blink on (output high) */ gpio_set_level(INDICATOR_LED_PIN, 1); vTaskDelay(blinkTime / portTICK_PERIOD_MS); } } void uart_console(void *pvParameters) { char character; hid_cmd_t mouseCmd; hid_cmd_t keyboardCmd; static uint8_t absMouseReport[HID_ABSMOUSE_IN_RPT_LEN]; //Install UART driver, and get the queue. uart_driver_install(CONSOLE_UART_NUM, UART_FIFO_LEN * 2, UART_FIFO_LEN * 2, 0, NULL, 0); ESP_LOGI("UART","console UART processing task started"); while(1) { // read single byte uart_read_bytes(CONSOLE_UART_NUM, (uint8_t*) &character, 1, portMAX_DELAY); // uart_parse_command(character, &cmdBuffer); if(halBLEIsConnected() == 0) { ESP_LOGI(CONSOLE_UART_TAG,"Not connected, ignoring '%c'", character); } else { //Do not send anything if queues are uninitialized if(hid_ble == NULL) { ESP_LOGE(CONSOLE_UART_TAG,"queues not initialized"); continue; } switch (character){ case 'a': mouseCmd.cmd[0] = 0x10; mouseCmd.cmd[1] = -MOUSE_SPEED; xQueueSend(hid_ble,(void *)&mouseCmd, (TickType_t) 0); ESP_LOGI(CONSOLE_UART_TAG,"mouse: a"); break; case 's': mouseCmd.cmd[0] = 0x11; mouseCmd.cmd[1] = MOUSE_SPEED; xQueueSend(hid_ble,(void *)&mouseCmd, (TickType_t) 0); ESP_LOGI(CONSOLE_UART_TAG,"mouse: s"); break; case 'd': mouseCmd.cmd[0] = 0x10; mouseCmd.cmd[1] = MOUSE_SPEED; xQueueSend(hid_ble,(void *)&mouseCmd, (TickType_t) 0); ESP_LOGI(CONSOLE_UART_TAG,"mouse: d"); break; case 'w': mouseCmd.cmd[0] = 0x11; mouseCmd.cmd[1] = -MOUSE_SPEED; xQueueSend(hid_ble,(void *)&mouseCmd, (TickType_t) 0); ESP_LOGI(CONSOLE_UART_TAG,"mouse: w"); break; case 'l': mouseCmd.cmd[0] = 0x13; xQueueSend(hid_ble,(void *)&mouseCmd, (TickType_t) 0); ESP_LOGI(CONSOLE_UART_TAG,"mouse: l"); break; case 'r': mouseCmd.cmd[0] = 0x14; xQueueSend(hid_ble,(void *)&mouseCmd, (TickType_t) 0); ESP_LOGI(CONSOLE_UART_TAG,"mouse: r"); break; case 'q': ESP_LOGI(CONSOLE_UART_TAG,"received q: sending key y for test purposes"); keyboardCmd.cmd[0] = 0x20; keyboardCmd.cmd[1] = 28; xQueueSend(hid_ble,(void *)&keyboardCmd, (TickType_t) 0); break; case '0': ESP_LOGI(CONSOLE_UART_TAG,"abs mouse: click left"); absMouseReport[0] = 0x01; hid_dev_send_report(hidd_le_env.gatt_if, halBLEGetConnID(), HID_RPT_ID_ABSMOUSE_IN, HID_REPORT_TYPE_INPUT, HID_ABSMOUSE_IN_RPT_LEN, absMouseReport); absMouseReport[0] = 0x00; hid_dev_send_report(hidd_le_env.gatt_if, halBLEGetConnID(), HID_RPT_ID_ABSMOUSE_IN, HID_REPORT_TYPE_INPUT, HID_ABSMOUSE_IN_RPT_LEN, absMouseReport); break; case '1': ESP_LOGI(CONSOLE_UART_TAG,"abs mouse: X left, Y bottom"); absMouseReport[1] = absMouseReport[2] = 0x00; absMouseReport[3] = 0x7F; absMouseReport[4] = 0xFF; hid_dev_send_report(hidd_le_env.gatt_if, halBLEGetConnID(), HID_RPT_ID_ABSMOUSE_IN, HID_REPORT_TYPE_INPUT, HID_ABSMOUSE_IN_RPT_LEN, absMouseReport); break; case '2': ESP_LOGI(CONSOLE_UART_TAG,"abs mouse: X center, Y bottom"); absMouseReport[1] = 0x40; absMouseReport[2] = 0x00; absMouseReport[3] = 0x7F; absMouseReport[4] = 0xFF; hid_dev_send_report(hidd_le_env.gatt_if, halBLEGetConnID(), HID_RPT_ID_ABSMOUSE_IN, HID_REPORT_TYPE_INPUT, HID_ABSMOUSE_IN_RPT_LEN, absMouseReport); break; case '3': ESP_LOGI(CONSOLE_UART_TAG,"abs mouse: X right, Y bottom"); absMouseReport[1] = 0x7F; absMouseReport[2] = 0xFF; absMouseReport[3] = 0x7F; absMouseReport[4] = 0xFF; hid_dev_send_report(hidd_le_env.gatt_if, halBLEGetConnID(), HID_RPT_ID_ABSMOUSE_IN, HID_REPORT_TYPE_INPUT, HID_ABSMOUSE_IN_RPT_LEN, absMouseReport); break; case '4': ESP_LOGI(CONSOLE_UART_TAG,"abs mouse: X left, Y center"); absMouseReport[1] = absMouseReport[2] = 0x00; absMouseReport[3] = 0x40; absMouseReport[4] = 0x00; hid_dev_send_report(hidd_le_env.gatt_if, halBLEGetConnID(), HID_RPT_ID_ABSMOUSE_IN, HID_REPORT_TYPE_INPUT, HID_ABSMOUSE_IN_RPT_LEN, absMouseReport); break; case '5': ESP_LOGI(CONSOLE_UART_TAG,"abs mouse: X center, Y center"); absMouseReport[1] = 0x40; absMouseReport[2] = 0x00; absMouseReport[3] = 0x40; absMouseReport[4] = 0x00; hid_dev_send_report(hidd_le_env.gatt_if, halBLEGetConnID(), HID_RPT_ID_ABSMOUSE_IN, HID_REPORT_TYPE_INPUT, HID_ABSMOUSE_IN_RPT_LEN, absMouseReport); break; case '6': ESP_LOGI(CONSOLE_UART_TAG,"abs mouse: X right, Y center"); absMouseReport[1] = 0x7F; absMouseReport[2] = 0xFF; absMouseReport[3] = 0x40; absMouseReport[4] = 0x00; hid_dev_send_report(hidd_le_env.gatt_if, halBLEGetConnID(), HID_RPT_ID_ABSMOUSE_IN, HID_REPORT_TYPE_INPUT, HID_ABSMOUSE_IN_RPT_LEN, absMouseReport); break; case '7': ESP_LOGI(CONSOLE_UART_TAG,"abs mouse: X left, Y top"); absMouseReport[1] = absMouseReport[2] = 0x00; absMouseReport[3] = absMouseReport[4] = 0x00; hid_dev_send_report(hidd_le_env.gatt_if, halBLEGetConnID(), HID_RPT_ID_ABSMOUSE_IN, HID_REPORT_TYPE_INPUT, HID_ABSMOUSE_IN_RPT_LEN, absMouseReport); break; case '8': ESP_LOGI(CONSOLE_UART_TAG,"abs mouse: X center, Y top"); absMouseReport[1] = 0x40; absMouseReport[2] = 0x00; absMouseReport[3] = absMouseReport[4] = 0x00; hid_dev_send_report(hidd_le_env.gatt_if, halBLEGetConnID(), HID_RPT_ID_ABSMOUSE_IN, HID_REPORT_TYPE_INPUT, HID_ABSMOUSE_IN_RPT_LEN, absMouseReport); break; case '9': ESP_LOGI(CONSOLE_UART_TAG,"abs mouse: X right, Y top"); absMouseReport[1] = 0x7F; absMouseReport[2] = 0xFF; absMouseReport[3] = absMouseReport[4] = 0x00; hid_dev_send_report(hidd_le_env.gatt_if, halBLEGetConnID(), HID_RPT_ID_ABSMOUSE_IN, HID_REPORT_TYPE_INPUT, HID_ABSMOUSE_IN_RPT_LEN, absMouseReport); break; default: ESP_LOGI(CONSOLE_UART_TAG,"received: %d",character); break; } } } } void mpu_poll(void *pvParameter) { hid_cmd_t mouseCmd; MPU6050 mpu = MPU6050(); gpio_pad_select_gpio(BUTTON_2); gpio_set_direction(BUTTON_2, GPIO_MODE_INPUT); gpio_set_pull_mode(BUTTON_2, GPIO_PULLUP_ONLY); mpu.initialize(); mpu.dmpInitialize(); // This need to be setup individually mpu.setXGyroOffset(220); mpu.setYGyroOffset(76); mpu.setZGyroOffset(-85); mpu.setZAccelOffset(1788); mpu.setDMPEnabled(true); while (1) { mpuIntStatus = mpu.getIntStatus(); // get current FIFO count fifoCount = mpu.getFIFOCount(); if ((mpuIntStatus & 0x10) || fifoCount == 1024) { // reset so we can continue cleanly mpu.resetFIFO(); // otherwise, check for DMP data ready interrupt frequently) } else if (mpuIntStatus & 0x02) { // wait for correct available data length, should be a VERY short wait while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount(); // read a packet from FIFO mpu.getFIFOBytes(fifoBuffer, packetSize); mpu.dmpGetQuaternion(&q, fifoBuffer); mpu.dmpGetGravity(&gravity, &q); mpu.dmpGetYawPitchRoll(ypr, &q, &gravity); yaw = ypr[2] /M_PI * 180; pitch = ypr[1] /M_PI * 180; roll = ypr[0] /M_PI * 180; vertValue = yaw - vertZero; horzValue = roll - horzZero; scrlValue = pitch - scrlZero; vertZero = yaw; horzZero = roll; scrlValue = pitch; if (halBLEIsConnected()) { if (vertValue != 0 || horzValue != 0) { mouseCmd.cmd[0] = 0x01; mouseCmd.cmd[1] = horzValue * MOUSE_SPEED; mouseCmd.cmd[2] = vertValue * MOUSE_SPEED; xQueueSend(hid_ble,(void *)&mouseCmd, (TickType_t) 0); } if (scrlValue != 0 && gpio_get_level(BUTTON_2) == 0) { mouseCmd.cmd[0] = 0x12; mouseCmd.cmd[1] = scrlValue * SCROLL_SENS; xQueueSend(hid_ble,(void *)&mouseCmd, (TickType_t) 0); // ESP_LOGI("SCRL","BOOST"); } } } //Best result is to match with DMP refresh rate // Its last value in components/MPU6050/MPU6050_6Axis_MotionApps20.h file line 310 // Now its 0x13, which means DMP is refreshed with 10Hz rate vTaskDelay(25 / portTICK_PERIOD_MS); } vTaskDelete(NULL); } void button_poll(void *pvParameter) { hid_cmd_t mouseCmd; gpio_pad_select_gpio(BUTTON_0); gpio_set_direction(BUTTON_0, GPIO_MODE_INPUT); gpio_set_pull_mode(BUTTON_0, GPIO_PULLUP_ONLY); // gpio_pullup_dis(BUTTON_0); gpio_pad_select_gpio(BUTTON_1); gpio_set_direction(BUTTON_1, GPIO_MODE_INPUT); gpio_set_pull_mode(BUTTON_1, GPIO_PULLUP_ONLY); // gpio_pullup_dis(BUTTON_1); bool mlb = false, mrb = false; while (1) { if (!gpio_get_level(BUTTON_0) && !mlb) { // ESP_LOGI("MLB","klik"); mouseCmd.cmd[0] = 0x16; xQueueSend(hid_ble,(void *)&mouseCmd, (TickType_t) 0); mlb = true; } else if (gpio_get_level(BUTTON_0) == 1 && mlb) { // ESP_LOGI("MLB","release"); mouseCmd.cmd[0] = 0x19; xQueueSend(hid_ble,(void *)&mouseCmd, (TickType_t) 0); mlb = false; } if (!gpio_get_level(BUTTON_1) && !mrb) { // ESP_LOGI("MRB","klik"); mouseCmd.cmd[0] = 0x17; xQueueSend(hid_ble,(void *)&mouseCmd, (TickType_t) 0); mrb = true; } else if (gpio_get_level(BUTTON_1) == 1 && mrb) { // ESP_LOGI("MRB","release"); mouseCmd.cmd[0] = 0x1A; xQueueSend(hid_ble,(void *)&mouseCmd, (TickType_t) 0); mrb = false; } vTaskDelay(25 / portTICK_PERIOD_MS); } vTaskDelete(NULL); } void task_initI2C(void *ignore) { i2c_config_t conf; conf.mode = I2C_MODE_MASTER; conf.sda_io_num = (gpio_num_t)PIN_SDA; conf.scl_io_num = (gpio_num_t)PIN_CLK; conf.sda_pullup_en = GPIO_PULLUP_ENABLE; conf.scl_pullup_en = GPIO_PULLUP_ENABLE; conf.master.clk_speed = 400000; ESP_ERROR_CHECK(i2c_param_config(I2C_NUM_0, &conf)); ESP_ERROR_CHECK(i2c_driver_install(I2C_NUM_0, I2C_MODE_MASTER, 0, 0, 0)); vTaskDelete(NULL); } extern "C" void app_main() { esp_err_t ret; esp_log_level_set("*", ESP_LOG_VERBOSE); // Initialize NVS. ret = nvs_flash_init(); if (ret == ESP_ERR_NVS_NO_FREE_PAGES) { ESP_ERROR_CHECK(nvs_flash_erase()); ret = nvs_flash_init(); } ESP_ERROR_CHECK( ret ); // Read config nvs_handle my_handle; ESP_LOGI("MAIN","loading configuration from NVS"); ret = nvs_open("config_c", NVS_READWRITE, &my_handle); if(ret != ESP_OK) ESP_LOGE("MAIN","error opening NVS"); size_t available_size = MAX_BT_DEVICENAME_LENGTH; strcpy(config.bt_device_name, GATTS_TAG); nvs_get_str (my_handle, "btname", config.bt_device_name, &available_size); if(ret != ESP_OK) { ESP_LOGE("MAIN","error reading NVS - bt name, setting to default"); strcpy(config.bt_device_name, GATTS_TAG); } else ESP_LOGI("MAIN","bt device name is: %s",config.bt_device_name); ret = nvs_get_u8(my_handle, "locale", &config.locale); nvs_close(my_handle); halBLEInit(0,1,0,config.bt_device_name); ESP_LOGI("HIDD","MAIN finished..."); hid_ble = xQueueCreate(32,sizeof(hid_cmd_t)); esp_log_level_set("*", ESP_LOG_DEBUG); // now start the tasks for processing UART input and indicator LED xTaskCreate(&task_initI2C, "mpu_init", 2048, NULL, configMAX_PRIORITIES, NULL); xTaskCreate(&uart_console, "console", 4096, NULL, configMAX_PRIORITIES, NULL); xTaskCreate(&blink_task, "blink", 4096, NULL, configMAX_PRIORITIES, NULL); vTaskDelay(1000/portTICK_PERIOD_MS); xTaskCreate(&mpu_poll, "mpu_loop", 8192, NULL, configMAX_PRIORITIES, NULL); xTaskCreate(&button_poll, "button_loop", 4096, NULL, configMAX_PRIORITIES, NULL); }
13,634
C++
.cpp
384
31.088542
94
0.667122
n1rml/esp32_airmouse
37
9
3
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,285
config.h
n1rml_esp32_airmouse/main/config.h
#ifndef _CONFIG_H_ #define _CONFIG_H_ #define MODULE_ID "ESP32_airmouse_p2" #define GATTS_TAG "41R" #define MAX_BT_DEVICENAME_LENGTH 40 // serial port of monitor and for debugging #define CONSOLE_UART_NUM UART_NUM_0 // indicator LED #define INDICATOR_LED_PIN (GPIO_NUM_2) typedef struct config_data { char bt_device_name[MAX_BT_DEVICENAME_LENGTH]; uint8_t locale; } config_data_t; #endif
407
C++
.h
14
26.928571
50
0.758442
n1rml/esp32_airmouse
37
9
3
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,286
hidd_le_prf_int.h
n1rml_esp32_airmouse/main/ble_hid/hidd_le_prf_int.h
// Copyright 2017-2018 Espressif Systems (Shanghai) PTE LTD // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef __HID_DEVICE_LE_PRF__ #define __HID_DEVICE_LE_PRF__ #include "esp_gatts_api.h" #include "esp_gatt_defs.h" #include "esp_gap_ble_api.h" #include "hid_dev.h" typedef enum { ESP_HIDD_EVENT_REG_FINISH = 0, ESP_BAT_EVENT_REG, ESP_HIDD_EVENT_DEINIT_FINISH, ESP_HIDD_EVENT_BLE_CONNECT, ESP_HIDD_EVENT_BLE_DISCONNECT, ESP_HIDD_EVENT_BLE_VENDOR_REPORT_WRITE_EVT, } esp_hidd_cb_event_t; /// HID config status typedef enum { ESP_HIDD_STA_CONN_SUCCESS = 0x00, ESP_HIDD_STA_CONN_FAIL = 0x01, } esp_hidd_sta_conn_state_t; /// HID init status typedef enum { ESP_HIDD_INIT_OK = 0, ESP_HIDD_INIT_FAILED = 1, } esp_hidd_init_state_t; /// HID deinit status typedef enum { ESP_HIDD_DEINIT_OK = 0, ESP_HIDD_DEINIT_FAILED = 0, } esp_hidd_deinit_state_t; /** * @brief HIDD callback parameters union */ typedef union { /** * @brief ESP_HIDD_EVENT_INIT_FINISH */ struct hidd_init_finish_evt_param { esp_hidd_init_state_t state; /*!< Initial status */ esp_gatt_if_t gatts_if; } init_finish; /*!< HID callback param of ESP_HIDD_EVENT_INIT_FINISH */ /** * @brief ESP_HIDD_EVENT_DEINIT_FINISH */ struct hidd_deinit_finish_evt_param { esp_hidd_deinit_state_t state; /*!< De-initial status */ } deinit_finish; /*!< HID callback param of ESP_HIDD_EVENT_DEINIT_FINISH */ /** * @brief ESP_HIDD_EVENT_CONNECT */ struct hidd_connect_evt_param { uint16_t conn_id; esp_bd_addr_t remote_bda; /*!< HID Remote bluetooth connection index */ } connect; /*!< HID callback param of ESP_HIDD_EVENT_CONNECT */ /** * @brief ESP_HIDD_EVENT_DISCONNECT */ struct hidd_disconnect_evt_param { esp_bd_addr_t remote_bda; /*!< HID Remote bluetooth device address */ } disconnect; /*!< HID callback param of ESP_HIDD_EVENT_DISCONNECT */ /** * @brief ESP_HIDD_EVENT_BLE_VENDOR_REPORT_WRITE_EVT */ struct hidd_vendor_write_evt_param { uint16_t conn_id; /*!< HID connection index */ uint16_t report_id; /*!< HID report index */ uint16_t length; /*!< data length */ uint8_t *data; /*!< The pointer to the data */ } vendor_write; /*!< HID callback param of ESP_HIDD_EVENT_BLE_VENDOR_REPORT_WRITE_EVT */ } esp_hidd_cb_param_t; /** * @brief HID device event callback function type * @param event : Event type * @param param : Point to callback parameter, currently is union type */ typedef void (*esp_hidd_event_cb_t) (esp_hidd_cb_event_t event, esp_hidd_cb_param_t *param); //HID BLE profile log tag #define HID_LE_PRF_TAG "HID_LE_PRF" /// Maximal number of HIDS that can be added in the DB #ifndef USE_ONE_HIDS_INSTANCE #define HIDD_LE_NB_HIDS_INST_MAX (2) #else #define HIDD_LE_NB_HIDS_INST_MAX (1) #endif #define HIDD_GREAT_VER 0x01 //Version + Subversion #define HIDD_SUB_VER 0x00 //Version + Subversion #define HIDD_VERSION ((HIDD_GREAT_VER<<8)|HIDD_SUB_VER) //Version + Subversion #define HID_MAX_APPS 1 // Number of HID reports defined in the service #define HID_NUM_REPORTS 9 // HID Report IDs for the service #define HID_RPT_ID_MOUSE_IN 1 // Mouse input report ID #define HID_RPT_ID_KEY_IN 2 // Keyboard input report ID #define HID_RPT_ID_CC_IN 3 //Consumer Control input report ID #define HID_RPT_ID_ABSMOUSE_IN 4 // Absolute mouse report ID #define HID_RPT_ID_JOY_IN 5 // Vendor output report ID #define HID_RPT_ID_LED_OUT 0 // LED output report ID #define HID_RPT_ID_FEATURE 0 // Feature report ID #define HIDD_APP_ID 0x1812//ATT_SVC_HID #define BATTRAY_APP_ID 0x180f #define ATT_SVC_HID 0x1812 /// Maximal number of Report Char. that can be added in the DB for one HIDS - Up to 11 #define HIDD_LE_NB_REPORT_INST_MAX (5) /// Maximal length of Report Char. Value #define HIDD_LE_REPORT_MAX_LEN (255) /// Maximal length of Report Map Char. Value #define HIDD_LE_REPORT_MAP_MAX_LEN (512) /// Length of Boot Report Char. Value Maximal Length #define HIDD_LE_BOOT_REPORT_MAX_LEN (8) /// Boot KB Input Report Notification Configuration Bit Mask #define HIDD_LE_BOOT_KB_IN_NTF_CFG_MASK (0x40) /// Boot KB Input Report Notification Configuration Bit Mask #define HIDD_LE_BOOT_MOUSE_IN_NTF_CFG_MASK (0x80) /// Boot Report Notification Configuration Bit Mask #define HIDD_LE_REPORT_NTF_CFG_MASK (0x20) /* HID information flags */ #define HID_FLAGS_REMOTE_WAKE 0x01 // RemoteWake #define HID_FLAGS_NORMALLY_CONNECTABLE 0x02 // NormallyConnectable /* Control point commands */ #define HID_CMD_SUSPEND 0x00 // Suspend #define HID_CMD_EXIT_SUSPEND 0x01 // Exit Suspend /* HID protocol mode values */ #define HID_PROTOCOL_MODE_BOOT 0x00 // Boot Protocol Mode #define HID_PROTOCOL_MODE_REPORT 0x01 // Report Protocol Mode /* Attribute value lengths */ #define HID_PROTOCOL_MODE_LEN 1 // HID Protocol Mode #define HID_INFORMATION_LEN 4 // HID Information #define HID_REPORT_REF_LEN 2 // HID Report Reference Descriptor #define HID_EXT_REPORT_REF_LEN 2 // External Report Reference Descriptor // HID feature flags #define HID_KBD_FLAGS HID_FLAGS_REMOTE_WAKE /* HID Report type */ #define HID_REPORT_TYPE_INPUT 1 #define HID_REPORT_TYPE_OUTPUT 2 #define HID_REPORT_TYPE_FEATURE 3 /// HID Service Attributes Indexes enum { HIDD_LE_IDX_SVC, // Included Service HIDD_LE_IDX_INCL_SVC, // HID Information HIDD_LE_IDX_HID_INFO_CHAR, HIDD_LE_IDX_HID_INFO_VAL, // HID Control Point HIDD_LE_IDX_HID_CTNL_PT_CHAR, HIDD_LE_IDX_HID_CTNL_PT_VAL, // Report Map HIDD_LE_IDX_REPORT_MAP_CHAR, HIDD_LE_IDX_REPORT_MAP_VAL, HIDD_LE_IDX_REPORT_MAP_EXT_REP_REF, // Protocol Mode HIDD_LE_IDX_PROTO_MODE_CHAR, HIDD_LE_IDX_PROTO_MODE_VAL, // Report mouse input HIDD_LE_IDX_REPORT_MOUSE_IN_CHAR, HIDD_LE_IDX_REPORT_MOUSE_IN_VAL, HIDD_LE_IDX_REPORT_MOUSE_IN_CCC, HIDD_LE_IDX_REPORT_MOUSE_REP_REF, //Report Key input HIDD_LE_IDX_REPORT_KEY_IN_CHAR, HIDD_LE_IDX_REPORT_KEY_IN_VAL, HIDD_LE_IDX_REPORT_KEY_IN_CCC, HIDD_LE_IDX_REPORT_KEY_IN_REP_REF, ///Report Led output HIDD_LE_IDX_REPORT_LED_OUT_CHAR, HIDD_LE_IDX_REPORT_LED_OUT_VAL, HIDD_LE_IDX_REPORT_LED_OUT_REP_REF, HIDD_LE_IDX_REPORT_CC_IN_CHAR, HIDD_LE_IDX_REPORT_CC_IN_VAL, HIDD_LE_IDX_REPORT_CC_IN_CCC, HIDD_LE_IDX_REPORT_CC_IN_REP_REF, /// Report absolute mouse HIDD_LE_IDX_REPORT_ABSMOUSE_IN_CHAR, HIDD_LE_IDX_REPORT_ABSMOUSE_IN_VAL, HIDD_LE_IDX_REPORT_ABSMOUSE_IN_CCC, HIDD_LE_IDX_REPORT_ABSMOUSE_REP_REF, // Boot Keyboard Input Report HIDD_LE_IDX_BOOT_KB_IN_REPORT_CHAR, HIDD_LE_IDX_BOOT_KB_IN_REPORT_VAL, HIDD_LE_IDX_BOOT_KB_IN_REPORT_NTF_CFG, // Boot Keyboard Output Report HIDD_LE_IDX_BOOT_KB_OUT_REPORT_CHAR, HIDD_LE_IDX_BOOT_KB_OUT_REPORT_VAL, // Boot Mouse Input Report HIDD_LE_IDX_BOOT_MOUSE_IN_REPORT_CHAR, HIDD_LE_IDX_BOOT_MOUSE_IN_REPORT_VAL, HIDD_LE_IDX_BOOT_MOUSE_IN_REPORT_NTF_CFG, // Report HIDD_LE_IDX_REPORT_CHAR, HIDD_LE_IDX_REPORT_VAL, HIDD_LE_IDX_REPORT_REP_REF, //HIDD_LE_IDX_REPORT_NTF_CFG, HIDD_LE_IDX_NB, }; /// Attribute Table Indexes enum { HIDD_LE_INFO_CHAR, HIDD_LE_CTNL_PT_CHAR, HIDD_LE_REPORT_MAP_CHAR, HIDD_LE_REPORT_CHAR, HIDD_LE_PROTO_MODE_CHAR, HIDD_LE_BOOT_KB_IN_REPORT_CHAR, HIDD_LE_BOOT_KB_OUT_REPORT_CHAR, HIDD_LE_BOOT_MOUSE_IN_REPORT_CHAR, HIDD_LE_CHAR_MAX //= HIDD_LE_REPORT_CHAR + HIDD_LE_NB_REPORT_INST_MAX, }; ///att read event table Indexs enum { HIDD_LE_READ_INFO_EVT, HIDD_LE_READ_CTNL_PT_EVT, HIDD_LE_READ_REPORT_MAP_EVT, HIDD_LE_READ_REPORT_EVT, HIDD_LE_READ_PROTO_MODE_EVT, HIDD_LE_BOOT_KB_IN_REPORT_EVT, HIDD_LE_BOOT_KB_OUT_REPORT_EVT, HIDD_LE_BOOT_MOUSE_IN_REPORT_EVT, HID_LE_EVT_MAX }; /// Client Characteristic Configuration Codes enum { HIDD_LE_DESC_MASK = 0x10, HIDD_LE_BOOT_KB_IN_REPORT_CFG = HIDD_LE_BOOT_KB_IN_REPORT_CHAR | HIDD_LE_DESC_MASK, HIDD_LE_BOOT_MOUSE_IN_REPORT_CFG = HIDD_LE_BOOT_MOUSE_IN_REPORT_CHAR | HIDD_LE_DESC_MASK, HIDD_LE_REPORT_CFG = HIDD_LE_REPORT_CHAR | HIDD_LE_DESC_MASK, }; /// Features Flag Values enum { HIDD_LE_CFG_KEYBOARD = 0x01, HIDD_LE_CFG_MOUSE = 0x02, HIDD_LE_CFG_PROTO_MODE = 0x04, HIDD_LE_CFG_MAP_EXT_REF = 0x08, HIDD_LE_CFG_BOOT_KB_WR = 0x10, HIDD_LE_CFG_BOOT_MOUSE_WR = 0x20, }; /// Report Char. Configuration Flag Values enum { HIDD_LE_CFG_REPORT_IN = 0x01, HIDD_LE_CFG_REPORT_OUT = 0x02, //HOGPD_CFG_REPORT_FEAT can be used as a mask to check Report type HIDD_LE_CFG_REPORT_FEAT = 0x03, HIDD_LE_CFG_REPORT_WR = 0x10, }; /// Pointer to the connection clean-up function #define HIDD_LE_CLEANUP_FNCT (NULL) /* * TYPE DEFINITIONS **************************************************************************************** */ /// HIDD Features structure typedef struct { /// Service Features uint8_t svc_features; /// Number of Report Char. instances to add in the database uint8_t report_nb; /// Report Char. Configuration uint8_t report_char_cfg[HIDD_LE_NB_REPORT_INST_MAX]; } hidd_feature_t; typedef struct { bool in_use; bool congest; uint16_t conn_id; bool connected; esp_bd_addr_t remote_bda; uint32_t trans_id; uint8_t cur_srvc_id; } hidd_clcb_t; // HID report mapping table typedef struct { uint16_t handle; // Handle of report characteristic uint16_t cccdHandle; // Handle of CCCD for report characteristic uint8_t id; // Report ID uint8_t type; // Report type uint8_t mode; // Protocol mode (report or boot) } hidRptMap_t; typedef struct { /// hidd profile id uint8_t app_id; /// Notified handle uint16_t ntf_handle; ///Attribute handle Table uint16_t att_tbl[HIDD_LE_IDX_NB]; /// Supported Features hidd_feature_t hidd_feature[HIDD_LE_NB_HIDS_INST_MAX]; /// Current Protocol Mode uint8_t proto_mode[HIDD_LE_NB_HIDS_INST_MAX]; /// Number of HIDS added in the database uint8_t hids_nb; uint8_t pending_evt; uint16_t pending_hal; } hidd_inst_t; /// Report Reference structure typedef struct { ///Report ID uint8_t report_id; ///Report Type uint8_t report_type; }hids_report_ref_t; /// HID Information structure typedef struct { /// bcdHID uint16_t bcdHID; /// bCountryCode uint8_t bCountryCode; /// Flags uint8_t flags; }hids_hid_info_t; /* service engine control block */ typedef struct { hidd_clcb_t hidd_clcb[HID_MAX_APPS]; /* connection link*/ esp_gatt_if_t gatt_if; bool enabled; bool is_take; bool is_primery; hidd_inst_t hidd_inst; esp_hidd_event_cb_t hidd_cb; uint8_t inst_id; } hidd_le_env_t; extern hidd_le_env_t hidd_le_env; extern uint8_t hidProtocolMode; void hidd_clcb_alloc (uint16_t conn_id, esp_bd_addr_t bda); bool hidd_clcb_dealloc (uint16_t conn_id); void hidd_le_create_service(esp_gatt_if_t gatts_if); void hidd_set_attr_value(uint16_t handle, uint16_t val_len, const uint8_t *value); void hidd_get_attr_value(uint16_t handle, uint16_t *length, uint8_t **value); esp_err_t hidd_register_cb(void); #endif ///__HID_DEVICE_LE_PRF__
12,895
C++
.h
339
34.297935
100
0.637502
n1rml/esp32_airmouse
37
9
3
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,287
hid_dev.h
n1rml_esp32_airmouse/main/ble_hid/hid_dev.h
// Copyright 2017-2018 Espressif Systems (Shanghai) PTE LTD // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef HID_DEV_H__ #define HID_DEV_H__ #include "hidd_le_prf_int.h" #ifdef __cplusplus extern "C" { #endif /* HID Report type */ #define HID_TYPE_INPUT 1 #define HID_TYPE_OUTPUT 2 #define HID_TYPE_FEATURE 3 // HID Keyboard/Keypad Usage IDs (subset of the codes available in the USB HID Usage Tables spec) #define HID_KEY_RESERVED 0 // No event inidicated #define HID_KEY_A 4 // Keyboard a and A #define HID_KEY_B 5 // Keyboard b and B #define HID_KEY_C 6 // Keyboard c and C #define HID_KEY_D 7 // Keyboard d and D #define HID_KEY_E 8 // Keyboard e and E #define HID_KEY_F 9 // Keyboard f and F #define HID_KEY_G 10 // Keyboard g and G #define HID_KEY_H 11 // Keyboard h and H #define HID_KEY_I 12 // Keyboard i and I #define HID_KEY_J 13 // Keyboard j and J #define HID_KEY_K 14 // Keyboard k and K #define HID_KEY_L 15 // Keyboard l and L #define HID_KEY_M 16 // Keyboard m and M #define HID_KEY_N 17 // Keyboard n and N #define HID_KEY_O 18 // Keyboard o and O #define HID_KEY_P 19 // Keyboard p and p #define HID_KEY_Q 20 // Keyboard q and Q #define HID_KEY_R 21 // Keyboard r and R #define HID_KEY_S 22 // Keyboard s and S #define HID_KEY_T 23 // Keyboard t and T #define HID_KEY_U 24 // Keyboard u and U #define HID_KEY_V 25 // Keyboard v and V #define HID_KEY_W 26 // Keyboard w and W #define HID_KEY_X 27 // Keyboard x and X #define HID_KEY_Y 28 // Keyboard y and Y #define HID_KEY_Z 29 // Keyboard z and Z #define HID_KEY_1 30 // Keyboard 1 and ! #define HID_KEY_2 31 // Keyboard 2 and @ #define HID_KEY_3 32 // Keyboard 3 and # #define HID_KEY_4 33 // Keyboard 4 and % #define HID_KEY_5 34 // Keyboard 5 and % #define HID_KEY_6 35 // Keyboard 6 and ^ #define HID_KEY_7 36 // Keyboard 7 and & #define HID_KEY_8 37 // Keyboard 8 and * #define HID_KEY_9 38 // Keyboard 9 and ( #define HID_KEY_0 39 // Keyboard 0 and ) #define HID_KEY_RETURN 40 // Keyboard Return (ENTER) #define HID_KEY_ESCAPE 41 // Keyboard ESCAPE #define HID_KEY_DELETE 42 // Keyboard DELETE (Backspace) #define HID_KEY_TAB 43 // Keyboard Tab #define HID_KEY_SPACEBAR 44 // Keyboard Spacebar #define HID_KEY_MINUS 45 // Keyboard - and (underscore) #define HID_KEY_EQUAL 46 // Keyboard = and + #define HID_KEY_LEFT_BRKT 47 // Keyboard [ and { #define HID_KEY_RIGHT_BRKT 48 // Keyboard ] and } #define HID_KEY_BACK_SLASH 49 // Keyboard \ and | #define HID_KEY_SEMI_COLON 51 // Keyboard ; and : #define HID_KEY_SGL_QUOTE 52 // Keyboard ' and " #define HID_KEY_GRV_ACCENT 53 // Keyboard Grave Accent and Tilde #define HID_KEY_COMMA 54 // Keyboard , and < #define HID_KEY_DOT 55 // Keyboard . and > #define HID_KEY_FWD_SLASH 56 // Keyboard / and ? #define HID_KEY_CAPS_LOCK 57 // Keyboard Caps Lock #define HID_KEY_F1 58 // Keyboard F1 #define HID_KEY_F2 59 // Keyboard F2 #define HID_KEY_F3 60 // Keyboard F3 #define HID_KEY_F4 61 // Keyboard F4 #define HID_KEY_F5 62 // Keyboard F5 #define HID_KEY_F6 63 // Keyboard F6 #define HID_KEY_F7 64 // Keyboard F7 #define HID_KEY_F8 65 // Keyboard F8 #define HID_KEY_F9 66 // Keyboard F9 #define HID_KEY_F10 67 // Keyboard F10 #define HID_KEY_F11 68 // Keyboard F11 #define HID_KEY_F12 69 // Keyboard F12 #define HID_KEY_PRNT_SCREEN 70 // Keyboard Print Screen #define HID_KEY_SCROLL_LOCK 71 // Keyboard Scroll Lock #define HID_KEY_PAUSE 72 // Keyboard Pause #define HID_KEY_INSERT 73 // Keyboard Insert #define HID_KEY_HOME 74 // Keyboard Home #define HID_KEY_PAGE_UP 75 // Keyboard PageUp #define HID_KEY_DELETE_FWD 76 // Keyboard Delete Forward #define HID_KEY_END 77 // Keyboard End #define HID_KEY_PAGE_DOWN 78 // Keyboard PageDown #define HID_KEY_RIGHT_ARROW 79 // Keyboard RightArrow #define HID_KEY_LEFT_ARROW 80 // Keyboard LeftArrow #define HID_KEY_DOWN_ARROW 81 // Keyboard DownArrow #define HID_KEY_UP_ARROW 82 // Keyboard UpArrow #define HID_KEY_NUM_LOCK 83 // Keypad Num Lock and Clear #define HID_KEY_DIVIDE 84 // Keypad / #define HID_KEY_MULTIPLY 85 // Keypad * #define HID_KEY_SUBTRACT 86 // Keypad - #define HID_KEY_ADD 87 // Keypad + #define HID_KEY_ENTER 88 // Keypad ENTER #define HID_KEYPAD_1 89 // Keypad 1 and End #define HID_KEYPAD_2 90 // Keypad 2 and Down Arrow #define HID_KEYPAD_3 91 // Keypad 3 and PageDn #define HID_KEYPAD_4 92 // Keypad 4 and Lfet Arrow #define HID_KEYPAD_5 93 // Keypad 5 #define HID_KEYPAD_6 94 // Keypad 6 and Right Arrow #define HID_KEYPAD_7 95 // Keypad 7 and Home #define HID_KEYPAD_8 96 // Keypad 8 and Up Arrow #define HID_KEYPAD_9 97 // Keypad 9 and PageUp #define HID_KEYPAD_0 98 // Keypad 0 and Insert #define HID_KEYPAD_DOT 99 // Keypad . and Delete #define HID_KEY_MUTE 127 // Keyboard Mute #define HID_KEY_VOLUME_UP 128 // Keyboard Volume up #define HID_KEY_VOLUME_DOWN 129 // Keyboard Volume down #define HID_KEY_LEFT_CTRL 224 // Keyboard LeftContorl #define HID_KEY_LEFT_SHIFT 225 // Keyboard LeftShift #define HID_KEY_LEFT_ALT 226 // Keyboard LeftAlt #define HID_KEY_LEFT_GUI 227 // Keyboard LeftGUI #define HID_KEY_RIGHT_CTRL 228 // Keyboard LeftContorl #define HID_KEY_RIGHT_SHIFT 229 // Keyboard LeftShift #define HID_KEY_RIGHT_ALT 230 // Keyboard LeftAlt #define HID_KEY_RIGHT_GUI 231 // Keyboard RightGUI typedef uint8_t keyboard_cmd_t; #define HID_MOUSE_LEFT 253 #define HID_MOUSE_MIDDLE 254 #define HID_MOUSE_RIGHT 255 typedef uint8_t mouse_cmd_t; // HID Consumer Usage IDs (subset of the codes available in the USB HID Usage Tables spec) #define HID_CONSUMER_POWER 48 // Power #define HID_CONSUMER_RESET 49 // Reset #define HID_CONSUMER_SLEEP 50 // Sleep #define HID_CONSUMER_MENU 64 // Menu #define HID_CONSUMER_SELECTION 128 // Selection #define HID_CONSUMER_ASSIGN_SEL 129 // Assign Selection #define HID_CONSUMER_MODE_STEP 130 // Mode Step #define HID_CONSUMER_RECALL_LAST 131 // Recall Last #define HID_CONSUMER_QUIT 148 // Quit #define HID_CONSUMER_HELP 149 // Help #define HID_CONSUMER_CHANNEL_UP 156 // Channel Increment #define HID_CONSUMER_CHANNEL_DOWN 157 // Channel Decrement #define HID_CONSUMER_PLAY 176 // Play #define HID_CONSUMER_PAUSE 177 // Pause #define HID_CONSUMER_RECORD 178 // Record #define HID_CONSUMER_FAST_FORWARD 179 // Fast Forward #define HID_CONSUMER_REWIND 180 // Rewind #define HID_CONSUMER_SCAN_NEXT_TRK 181 // Scan Next Track #define HID_CONSUMER_SCAN_PREV_TRK 182 // Scan Previous Track #define HID_CONSUMER_STOP 183 // Stop #define HID_CONSUMER_EJECT 184 // Eject #define HID_CONSUMER_RANDOM_PLAY 185 // Random Play #define HID_CONSUMER_SELECT_DISC 186 // Select Disk #define HID_CONSUMER_ENTER_DISC 187 // Enter Disc #define HID_CONSUMER_REPEAT 188 // Repeat #define HID_CONSUMER_STOP_EJECT 204 // Stop/Eject #define HID_CONSUMER_PLAY_PAUSE 205 // Play/Pause #define HID_CONSUMER_PLAY_SKIP 206 // Play/Skip #define HID_CONSUMER_VOLUME 224 // Volume #define HID_CONSUMER_BALANCE 225 // Balance #define HID_CONSUMER_MUTE 226 // Mute #define HID_CONSUMER_BASS 227 // Bass #define HID_CONSUMER_VOLUME_UP 233 // Volume Increment #define HID_CONSUMER_VOLUME_DOWN 234 // Volume Decrement typedef uint8_t consumer_cmd_t; #define HID_CC_RPT_MUTE 1 #define HID_CC_RPT_POWER 2 #define HID_CC_RPT_LAST 3 #define HID_CC_RPT_ASSIGN_SEL 4 #define HID_CC_RPT_PLAY 5 #define HID_CC_RPT_PAUSE 6 #define HID_CC_RPT_RECORD 7 #define HID_CC_RPT_FAST_FWD 8 #define HID_CC_RPT_REWIND 9 #define HID_CC_RPT_SCAN_NEXT_TRK 10 #define HID_CC_RPT_SCAN_PREV_TRK 11 #define HID_CC_RPT_STOP 12 #define HID_CC_RPT_CHANNEL_UP 0x01 #define HID_CC_RPT_CHANNEL_DOWN 0x03 #define HID_CC_RPT_VOLUME_UP 0x40 #define HID_CC_RPT_VOLUME_DOWN 0x80 // HID Consumer Control report bitmasks #define HID_CC_RPT_NUMERIC_BITS 0xF0 #define HID_CC_RPT_CHANNEL_BITS 0xCF #define HID_CC_RPT_VOLUME_BITS 0x3F #define HID_CC_RPT_BUTTON_BITS 0xF0 #define HID_CC_RPT_SELECTION_BITS 0xCF // Macros for the HID Consumer Control 2-byte report #define HID_CC_RPT_SET_NUMERIC(s, x) (s)[0] &= HID_CC_RPT_NUMERIC_BITS; \ (s)[0] = (x) #define HID_CC_RPT_SET_CHANNEL(s, x) (s)[0] &= HID_CC_RPT_CHANNEL_BITS; \ (s)[0] |= ((x) & 0x03) << 4 #define HID_CC_RPT_SET_VOLUME_UP(s) (s)[0] &= HID_CC_RPT_VOLUME_BITS; \ (s)[0] |= 0x40 #define HID_CC_RPT_SET_VOLUME_DOWN(s) (s)[0] &= HID_CC_RPT_VOLUME_BITS; \ (s)[0] |= 0x80 #define HID_CC_RPT_SET_BUTTON(s, x) (s)[1] &= HID_CC_RPT_BUTTON_BITS; \ (s)[1] |= (x) #define HID_CC_RPT_SET_SELECTION(s, x) (s)[1] &= HID_CC_RPT_SELECTION_BITS; \ (s)[1] |= ((x) & 0x03) << 4 // HID keyboard input report length #define HID_KEYBOARD_IN_RPT_LEN 8 // HID keyboard input report length #define HID_JOYSTICK_IN_RPT_LEN 12 // HID LED output report length #define HID_LED_OUT_RPT_LEN 1 // HID mouse input report length #define HID_MOUSE_IN_RPT_LEN 5 // HID mouse input report length #define HID_ABSMOUSE_IN_RPT_LEN 6 // HID consumer control input report length #define HID_CC_IN_RPT_LEN 2 // HID report mapping table typedef struct { uint16_t handle; // Handle of report characteristic uint16_t cccdHandle; // Handle of CCCD for report characteristic uint8_t id; // Report ID uint8_t type; // Report type uint8_t mode; // Protocol mode (report or boot) } hid_report_map_t; // HID dev configuration structure typedef struct { uint32_t idleTimeout; // Idle timeout in milliseconds uint8_t hidFlags; // HID feature flags } hid_dev_cfg_t; void hid_dev_register_reports(uint8_t num_reports, hid_report_map_t *p_report); void hid_dev_send_report(esp_gatt_if_t gatts_if, uint16_t conn_id, uint8_t id, uint8_t type, uint8_t length, uint8_t *data); void hid_consumer_build_report(uint8_t *buffer, consumer_cmd_t cmd); #ifdef __cplusplus } #endif #endif /* HID_DEV_H__ */
12,258
C++
.h
241
48.518672
97
0.608445
n1rml/esp32_airmouse
37
9
3
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
true
false
false
false
false
false
false
1,535,288
hal_ble.h
n1rml_esp32_airmouse/main/ble_hid/hal_ble.h
/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. * * Copyright 2019 Benjamin Aigner <beni@asterics-foundation.org> */ /** @file * @brief This file is a wrapper for the BLE-HID example of Espressif. */ #ifndef _HAL_BLE_H_ #define _HAL_BLE_H_ #ifdef __cplusplus extern "C" { #endif #include <freertos/FreeRTOS.h> #include <freertos/event_groups.h> #include <freertos/queue.h> #include <esp_log.h> #include "esp_bt.h" #include "esp_bt_defs.h" #include "esp_gap_ble_api.h" #include "esp_gatts_api.h" #include "esp_gatt_defs.h" #include "esp_bt_main.h" #include "esp_bt_device.h" #include "hid_dev.h" #include "nvs_flash.h" /** @brief Stack size for BLE task */ #define TASK_BLE_STACKSIZE 2048 /** @brief Queue for sending mouse/keyboard/joystick reports * @see hid_cmd_t */ extern QueueHandle_t hid_ble; /** @brief Activate/deactivate pairing mode * @param enable If set to != 0, pairing will be enabled. Disabled if == 0 * @return ESP_OK on success, ESP_FAIL otherwise*/ esp_err_t halBLESetPairing(uint8_t enable); /** @brief Get connection status * @return 0 if not connected, != 0 if connected */ uint8_t halBLEIsConnected(void); /** @brief En- or Disable BLE interface. * * This method is used to enable or disable the BLE interface. Currently, the ESP32 * cannot use WiFi and BLE simultaneously. Therefore, when enabling wifi, it is * necessary to disable BLE prior calling taskWebGUIEnDisable. * * @note Calling this method prior to initializing BLE via halBLEInit will * result in an error! * @return ESP_OK on success, ESP_FAIL otherwise * @param onoff If != 0, switch on BLE, switch off if 0. * */ esp_err_t halBLEEnDisable(int onoff); /** @brief Reset the BLE data * * Used for slot/config switchers. * It resets the keycode array and sets all HID reports to 0 * (release all keys, avoiding sticky keys on a config change) * @param exceptDevice if you want to reset only a part of the devices, set flags * accordingly: * * (1<<0) excepts keyboard * (1<<1) excepts joystick * (1<<2) excepts mouse * If nothing is set (exceptDevice = 0) all are reset * */ void halBLEReset(uint8_t exceptDevice); /** @brief Main init function to start HID interface (C interface) * @see hid_ble */ esp_err_t halBLEInit(uint8_t enableKeyboard, uint8_t enableMouse, uint8_t enableJoystick, char* deviceName); /** @brief Returns current connection ID * * The conn id is used for sending HID reports */ uint16_t halBLEGetConnID(); /** @brief One HID command */ typedef struct hid_cmd hid_cmd_t; /** @brief One HID command */ struct hid_cmd { /** Explanation of bytefields: * see https://github.com/benjaminaigner/usb_bridge/blob/master/example/src/parser.c#L119 */ uint8_t cmd[3]; }; #ifdef __cplusplus } #endif #endif /* _HAL_BLE_H_ */
3,466
C++
.h
98
33.510204
108
0.738287
n1rml/esp32_airmouse
37
9
3
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,294
MainTest.cpp
crustio_crust-sworker/test/unit/MainTest.cpp
#include "MainTest.h" int main() { int ret = test_enclave(); return ret; } int test_enclave() { std::string HRED = "\033[1;31m"; std::string HGREEN = "\033[1;32m"; std::string NC = "\033[0m"; bool test_ret = true; printf("\nRunning enclave test...\n\n"); /* Launch the enclave */ sgx_enclave_id_t eid; sgx_status_t ret = sgx_create_enclave(ENCLAVE_TEST_FILE_PATH, SGX_DEBUG_FLAG, NULL, NULL, &eid, NULL); if (ret != SGX_SUCCESS) { printf("%s*** Create enclave failed!%s\n", HRED.c_str(), NC.c_str()); return -1; } /* Running enclave utils tests */ ret = ecall_test_enclave_unit(eid, &test_ret); printf("\n"); if (SGX_SUCCESS != ret) { printf("%s*** Invoke SGX failed!%s\n", HRED.c_str(), NC.c_str()); return -1; } if (!test_ret) { printf("%s*** Test enclave utils APIs failed!%s\n", HRED.c_str(), NC.c_str()); return -1; } printf("%s*** Pass enclave test!%s\n", HGREEN.c_str(), NC.c_str()); return test_ret ? 0 : -1; }
1,070
C++
.cpp
37
23.837838
106
0.563353
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,295
EncalveTestEntrance.cpp
crustio_crust-sworker/test/unit/enclave/EncalveTestEntrance.cpp
#include "EncalveTestEntrance.h" void print_err(const char *info) { std::string HRED = "\033[1;31m"; std::string NC = "\033[0m"; eprint_info("%s%s%s", HRED.c_str(), info, NC.c_str()); } void print_success(const char *info) { std::string HGREEN = "\033[1;32m"; std::string NC = "\033[0m"; eprint_info("%s%s%s", HGREEN.c_str(), info, NC.c_str()); } bool test_all_utils() { bool ret = true; if (!test_char_to_int()) { print_err("x Test char_to_int failed!\n"); ret = ret && false; } print_success("+ Test char_to_int successfully!\n"); if (!test_hexstring()) { print_err("x Test hexstring failed!\n"); ret = ret && false; } print_success("+ Test hexstring successfully!\n"); if (!test_hexstring_safe()) { print_err("x Test hexstring_safe failed!\n"); ret = ret && false; } print_success("+ Test hexstring_safe successfully!\n"); if (!test_hex_string_to_bytes()) { print_err("x Test hex_string_to_bytes failed!\n"); ret = ret && false; } print_success("+ Test hex_string_to_bytes successfully!\n"); if (!test_seal_data_mrenclave()) { print_err("x Test seal_data_mrenclave failed!\n"); ret = ret && false; } print_success("+ Test seal_data_mrenclave successfully!\n"); if (!test_remove_char()) { print_err("x Test remove_char failed!\n"); ret = ret && false; } print_success("+ Test remove_char successfully!\n"); if (!test_base58_encode()) { print_err("x Test base58_encode failed!\n"); ret = ret && false; } print_success("+ Test base58_encode successfully!\n"); if (!test_hash_to_cid()) { print_err("x Test hash_to_cid failed!\n"); ret = ret && false; } print_success("+ Test hash_to_cid successfully!\n"); return ret; } bool test_all_storage() { bool ret = true; if (!test_get_hashs_from_block()) { print_err("x Test get_hashs_from_block failed!\n"); ret = ret && false; } print_success("+ Test get_hashs_from_block successfully!\n"); return ret; } bool test_enclave_unit() { bool ret = true; print_success("------------ Test utils ------------\n\n"); if (!test_all_utils()) { ret = ret && false; } print_success("\n------------ Test storage ------------\n\n"); if (!test_all_storage()) { ret = ret && false; } return ret; }
2,528
C++
.cpp
92
22.086957
66
0.564156
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,296
UtilsTest.cpp
crustio_crust-sworker/test/unit/enclave/utilsTest/UtilsTest.cpp
#include "UtilsTest.h" bool test_char_to_int() { std::string char_nums = "0123456789"; std::string char_lowerletters = "abcdef"; std::string char_upperletters = "ABCDEF"; std::string char_others = "hijklmn`~!@#$%^&*()_-=+[{}]\\|:;\"'<,.>?/"; for (auto c : char_nums) { if (char_to_int(c) != c - '0') return false; } for (auto c : char_lowerletters) { if (char_to_int(c) != c - 'a' + 10) return false; } for (auto c : char_upperletters) { if (char_to_int(c) != c - 'A' + 10) return false; } for (auto c : char_others) { if (char_to_int(c) != 0) return false; } return true; } bool test_hexstring() { size_t tmp_len = 32; uint8_t *tmp_buffer = (uint8_t*)malloc(tmp_len); if (tmp_buffer == NULL) { return true; } memset(tmp_buffer, 0, tmp_len); char *hex_tmp_buffer = hexstring(tmp_buffer, tmp_len); for (size_t i = 0; i < tmp_len * 2; i++) { if (!(hex_tmp_buffer[i] >= '0' && hex_tmp_buffer[i] <= '9') && !(hex_tmp_buffer[i] >= 'a' && hex_tmp_buffer[i] <= 'f')) return false; } return true; } bool test_hexstring_safe() { size_t tmp_len = 32; uint8_t *tmp_buffer = (uint8_t*)malloc(tmp_len); if (tmp_buffer == NULL) { return true; } memset(tmp_buffer, 0, tmp_len); std::string hex_tmp_buffer = hexstring_safe(tmp_buffer, tmp_len); for (size_t i = 0; i < tmp_len; i++) { if (!(hex_tmp_buffer[i] >= '0' && hex_tmp_buffer[i] <= '9') && !(hex_tmp_buffer[i] >= 'a' && hex_tmp_buffer[i] <= 'f')) return false; } return true; } bool test_hex_string_to_bytes() { std::string hex_str = "\ 00010203040506070809\ a0a1a2a3a4a5a6a7a8a9\ b0b1b2b3b4b5b6b7b8b9\ c0c1c2c3c4c5c6c7c8c9\ d0d1d2d3d4d5d6d7d8d9\ e0e1e2e3e4e5e6e7e8e9\ f0f1f2f3f4f5f6f7f8f9"; uint8_t bytes[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, }; uint8_t *hex_2_bytes = hex_string_to_bytes(hex_str.c_str(), hex_str.size()); if (memcmp(hex_2_bytes, bytes, hex_str.size() / 2) != 0) return false; return true; } bool test_seal_data_mrenclave() { size_t buffer_len = 32; uint8_t *tmp_buffer = (uint8_t*)malloc(buffer_len); if (tmp_buffer == NULL) { return true; } memset(tmp_buffer, 0, buffer_len); size_t sealed_data_size = 0; sgx_sealed_data_t *sealed_data = NULL; if (CRUST_SUCCESS != seal_data_mrenclave(tmp_buffer, buffer_len, &sealed_data, &sealed_data_size)) { return false; } return true; } bool test_remove_char() { std::string str_null = ""; std::string str_same = "1111111111"; std::string str_single = "1"; std::string str_normal = "1212121212"; remove_char(str_null, '1'); if (str_null.compare("") != 0) { return false; } remove_char(str_same, '1'); if (str_same.compare("") != 0) { return false; } remove_char(str_single, '1'); if (str_single.compare("") != 0) { return false; } remove_char(str_normal, '1'); if (str_normal.compare("22222") != 0) { return false; } return true; } bool test_base58_encode() { std::string input_str = "12208ad1b49139d0c987ed74c5df798c039d3c6eb034907284778974bd63abadc658"; uint8_t *input = hex_string_to_bytes(input_str.c_str(), input_str.size()); std::string res = base58_encode(input, input_str.size() / 2); delete input; if (res != "QmXgYSFx8vSeGgb5qBEw3wYXmQPwYYLHiVZzxN1FM93SmD") { log_err("The base58 encode result must be QmXgYSFx8vSeGgb5qBEw3wYXmQPwYYLHiVZzxN1FM93SmD\n"); return false; } return true; } bool test_hash_to_cid() { std::string input_str = "8ad1b49139d0c987ed74c5df798c039d3c6eb034907284778974bd63abadc658"; uint8_t *input = hex_string_to_bytes(input_str.c_str(), input_str.size()); std::string res = hash_to_cid(input); delete input; if (res != "QmXgYSFx8vSeGgb5qBEw3wYXmQPwYYLHiVZzxN1FM93SmD") { log_err("The hash to cid result must be QmXgYSFx8vSeGgb5qBEw3wYXmQPwYYLHiVZzxN1FM93SmD\n"); return false; } return true; }
4,751
C++
.cpp
160
24.0875
102
0.595207
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,297
StorageTest.cpp
crustio_crust-sworker/test/unit/enclave/storageTest/StorageTest.cpp
#include "StorageTest.h" bool test_get_hashs_from_block() { std::string block1_hex_str = "122a0a22122035d209a850b6909fa3dad99c3f96415f1a4b92ac23062c92cd3562b6bef3b7c11200188e8010122a0a2212201825c65359a2f165ea0c0301a6dac34176e3742c96cd12449006b086205ac3781200188e8010122a0a2212201687310fe656495e943b4b57c709a487f94d7e00e310b0303781c04ee890e3221200188e8010122a0a2212206e11ef1a3bb54778d417c3f91bc2b557448b2567a3d0f3598a33316fd1a36c271200188e8010122a0a2212208ad1b49139d0c987ed74c5df798c039d3c6eb034907284778974bd63abadc658120018ee91030a1a080218e091432080801020808010208080102080801020e09103"; uint8_t *block1_data = hex_string_to_bytes(block1_hex_str.c_str(), block1_hex_str.size()); std::vector<uint8_t *> hashs; crust_status_t crust_status = get_hashs_from_block(block1_data, block1_hex_str.size() / 2, hashs); if (block1_data != NULL) { delete block1_data; } // Assert if (crust_status != CRUST_SUCCESS) { log_err("Get hashs from block error, code is %d\n", crust_status); return false; } if (hashs.size() != 5) { log_err("Get hashs failed, block must have 5 hashs\n"); return false; } std::string hash_str = hexstring_safe(hashs[2], HASH_LENGTH); if (hash_str != "1687310fe656495e943b4b57c709a487f94d7e00e310b0303781c04ee890e322") { log_err("The 3rd hash must be 1687310fe656495e943b4b57c709a487f94d7e00e310b0303781c04ee890e322\n"); return false; } // Clear hashs for (size_t i = 0; i < hashs.size(); i++) { delete hashs[i]; } hashs.clear(); return true; }
1,628
C++
.cpp
36
39.472222
532
0.746363
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,298
EnclaveTest.cpp
crustio_crust-sworker/test/src/enclave/EnclaveTest.cpp
#include "Enclave.h" #include "Storage.h" #include "Persistence.h" #include "Identity.h" #include "IdentityTest.h" #include "WorkloadTest.h" #include "SrdTest.h" #include "ValidatorTest.h" void ecall_handle_report_result() { if (ENC_UPGRADE_STATUS_NONE != Workload::get_instance()->get_upgrade_status()) { return; } Workload::get_instance()->handle_report_result(); } void ecall_add_validate_proof() { Workload::get_instance()->report_add_validated_srd_proof(); Workload::get_instance()->report_add_validated_file_proof(); } void ecall_validate_srd_test() { validate_srd(); } void ecall_validate_srd_bench() { validate_srd_bench(); } void ecall_validate_file_test() { validate_meaningful_file(); } void ecall_validate_file_bench() { validate_meaningful_file_bench(); } void ecall_store_metadata() { crust_status_t crust_status = CRUST_SUCCESS; if (CRUST_SUCCESS != (crust_status = id_store_metadata())) { log_err("Store enclave data failed!Error code:%lx\n", crust_status); } } void ecall_test_add_file(long file_num) { WorkloadTest::get_instance()->test_add_file(file_num); } void ecall_test_delete_file(uint32_t file_num) { WorkloadTest::get_instance()->test_delete_file(file_num); } void ecall_test_delete_file_unsafe(uint32_t file_num) { WorkloadTest::get_instance()->test_delete_file_unsafe(file_num); } crust_status_t ecall_srd_increase_test(const char *uuid) { if (ENC_UPGRADE_STATUS_NONE != Workload::get_instance()->get_upgrade_status()) { return CRUST_UPGRADE_IS_UPGRADING; } return srd_increase_test(uuid); } size_t ecall_srd_decrease_test(size_t change) { size_t ret = srd_decrease_test(change); return ret; } void ecall_clean_file() { Workload *wl = Workload::get_instance(); sgx_thread_mutex_lock(&wl->file_mutex); wl->sealed_files.clear(); sgx_thread_mutex_unlock(&wl->file_mutex); } crust_status_t ecall_get_file_info(const char *data) { Workload *wl = Workload::get_instance(); sgx_thread_mutex_lock(&wl->file_mutex); crust_status_t crust_status = CRUST_UNEXPECTED_ERROR; for (int i = wl->sealed_files.size() - 1; i >= 0; i--) { if (wl->sealed_files[i][FILE_HASH].ToString().compare(data) == 0) { std::string file_info_str = wl->sealed_files[i].dump(); remove_char(file_info_str, '\n'); remove_char(file_info_str, '\\'); remove_char(file_info_str, ' '); ocall_store_file_info_test(file_info_str.c_str()); crust_status = CRUST_SUCCESS; } } sgx_thread_mutex_unlock(&wl->file_mutex); return crust_status; } crust_status_t ecall_gen_upgrade_data_test(size_t block_height) { return id_gen_upgrade_data_test(block_height); } crust_status_t ecall_gen_and_upload_work_report_test(const char *block_hash, size_t block_height) { if (ENC_UPGRADE_STATUS_NONE != Workload::get_instance()->get_upgrade_status()) { return CRUST_UPGRADE_WAIT_FOR_NEXT_ERA; } crust_status_t ret = gen_and_upload_work_report_test(block_hash, block_height, 0, false); return ret; } void ecall_srd_change_test(long change, bool real) { if (ENC_UPGRADE_STATUS_NONE != Workload::get_instance()->get_upgrade_status()) { return; } srd_change_test(change, real); } void ecall_validate_file_bench_real() { validate_meaningful_file_bench_real(); } void ecall_validate_srd_bench_real() { validate_srd_bench_real(); }
3,540
C++
.cpp
126
24.309524
97
0.678772
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,299
SrdTest.cpp
crustio_crust-sworker/test/src/enclave/srd/SrdTest.cpp
#include "SrdTest.h" extern long g_srd_task; extern sgx_thread_mutex_t g_srd_task_mutex; void srd_change_test(long change, bool real) { // Set srd change number long real_change = 0; change_srd_task(change, &real_change); // ----- Do srd change ----- // Workload *wl = Workload::get_instance(); if (ENC_UPGRADE_STATUS_SUCCESS == wl->get_upgrade_status()) { return; } sgx_thread_mutex_lock(&g_srd_task_mutex); long tmp_g_srd_task = g_srd_task; g_srd_task = 0; sgx_thread_mutex_unlock(&g_srd_task_mutex); // Srd loop while (tmp_g_srd_task != 0) { // Get real srd space long srd_change_num = 0; if (tmp_g_srd_task > SRD_MAX_INC_PER_TURN) { srd_change_num = SRD_MAX_INC_PER_TURN; tmp_g_srd_task -= SRD_MAX_INC_PER_TURN; } else { srd_change_num = tmp_g_srd_task; tmp_g_srd_task = 0; } // Do srd crust_status_t crust_status = CRUST_SUCCESS; if (srd_change_num != 0) { if (real) { ocall_srd_change(&crust_status, srd_change_num); } else { ocall_srd_change_test(&crust_status, srd_change_num); } if (CRUST_SRD_NUMBER_EXCEED == crust_status) { sgx_thread_mutex_lock(&g_srd_task_mutex); g_srd_task = 0; sgx_thread_mutex_unlock(&g_srd_task_mutex); } } // Update srd info std::string srd_info_str = wl->get_srd_info().dump(); ocall_set_srd_info(reinterpret_cast<const uint8_t *>(srd_info_str.c_str()), srd_info_str.size()); } } crust_status_t srd_increase_test(const char *uuid) { Workload *wl = Workload::get_instance(); // Get uuid bytes uint8_t *p_uuid_u = hex_string_to_bytes(uuid, UUID_LENGTH * 2); if (p_uuid_u == NULL) { log_err("Get uuid bytes failed! Invalid uuid:%s\n", uuid); return CRUST_UNEXPECTED_ERROR; } Defer def_uuid([&p_uuid_u](void) { free(p_uuid_u); }); // Generate base random data // Generate current G hash index // ----- Generate srd file ----- // // Create directory // Generate all M hashs and store file to disk uint8_t *m_hashs = (uint8_t *)enc_malloc(HASH_LENGTH); if (m_hashs == NULL) { log_err("Malloc memory failed!\n"); return CRUST_MALLOC_FAILED; } Defer defer_hashs([&m_hashs](void) { free(m_hashs); }); memset(m_hashs, 0, HASH_LENGTH); sgx_read_rand(m_hashs, HASH_LENGTH); // Generate G hashs sgx_sha256_hash_t g_hash; sgx_sha256_msg(m_hashs, SRD_RAND_DATA_NUM * HASH_LENGTH, &g_hash); // Change G path name std::string g_hash_hex = hexstring_safe(&g_hash, HASH_LENGTH); // ----- Update srd_hashs ----- // // Add new g_hash to srd_hashs // Because add this p_hash_u to the srd_hashs, so we cannot free p_hash_u uint8_t *srd_item = (uint8_t *)enc_malloc(SRD_LENGTH); if (srd_item == NULL) { log_err("Malloc for srd item failed!\n"); return CRUST_MALLOC_FAILED; } memset(srd_item, 0, SRD_LENGTH); memcpy(srd_item, p_uuid_u, UUID_LENGTH); memcpy(srd_item + UUID_LENGTH, g_hash, HASH_LENGTH); sgx_thread_mutex_lock(&wl->srd_mutex); wl->srd_hashs.push_back(srd_item); log_info("Seal random data -> %s, %luG success\n", g_hash_hex.c_str(), wl->srd_hashs.size()); sgx_thread_mutex_unlock(&wl->srd_mutex); // ----- Update srd info ----- // wl->set_srd_info(uuid, 1); return CRUST_SUCCESS; } size_t srd_decrease_test(size_t change) { Workload *wl = Workload::get_instance(); // ----- Choose to be deleted hash ----- // SafeLock sl(wl->srd_mutex); sl.lock(); wl->deal_deleted_srd_nolock(); // Get real change change = std::min(change, wl->srd_hashs.size()); if (change <= 0) { return 0; } // Get change hashs // Note: Cannot push srd hash pointer to vector because it will be deleted later std::vector<std::string> del_srds; std::vector<size_t> del_indexes; for (size_t i = 1; i <= change; i++) { size_t index = wl->srd_hashs.size() - i; del_srds.push_back(hexstring_safe(wl->srd_hashs[index], SRD_LENGTH)); del_indexes.push_back(index); } std::reverse(del_indexes.begin(), del_indexes.end()); wl->delete_srd_meta(del_indexes); sl.unlock(); // Delete srd files return change; }
4,578
C++
.cpp
136
26.889706
105
0.579435
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,300
WorkloadTest.cpp
crustio_crust-sworker/test/src/enclave/workload/WorkloadTest.cpp
#include "WorkloadTest.h" WorkloadTest *WorkloadTest::workloadTest = NULL; WorkloadTest *WorkloadTest::get_instance() { if (WorkloadTest::workloadTest == NULL) { WorkloadTest::workloadTest = new WorkloadTest(); } return WorkloadTest::workloadTest; } void WorkloadTest::test_add_file(long file_num) { Workload *wl = Workload::get_instance(); sgx_thread_mutex_lock(&wl->file_mutex); long acc = 0; for (long i = 0; i < file_num; i++) { uint8_t *n_u = new uint8_t[32]; sgx_read_rand(n_u, HASH_LENGTH); sgx_sha256_hash_t hash; sgx_sha256_msg(n_u, HASH_LENGTH, &hash); json::JSON file_entry_json; uint8_t *p_cid_buffer = (uint8_t *)enc_malloc(CID_LENGTH / 2); sgx_read_rand(p_cid_buffer, CID_LENGTH / 2); std::string cid = hexstring_safe(p_cid_buffer, CID_LENGTH / 2); file_entry_json[FILE_CID] = cid; file_entry_json[FILE_HASH] = reinterpret_cast<uint8_t *>(hash); file_entry_json[FILE_SIZE] = 100000000; file_entry_json[FILE_SEALED_SIZE] = 999900000; file_entry_json[FILE_BLOCK_NUM] = 100000000; file_entry_json[FILE_CHAIN_BLOCK_NUM] = 100000000; // Status indicates current new file's status, which must be one of valid, lost and unconfirmed file_entry_json[FILE_STATUS] = "100000000000"; free(p_cid_buffer); free(n_u); wl->add_file_nolock(file_entry_json); wl->set_file_spec(FILE_STATUS_VALID, file_entry_json[FILE_SEALED_SIZE].ToInt()); std::string file_info; file_info.append("{ \"" FILE_SIZE "\" : ").append(std::to_string(file_entry_json[FILE_SIZE].ToInt())).append(" , ") .append("\"" FILE_SEALED_SIZE "\" : ").append(std::to_string(file_entry_json[FILE_SEALED_SIZE].ToInt())).append(" , ") .append("\"" FILE_CHAIN_BLOCK_NUM "\" : ").append(std::to_string(1111)).append(" }"); ocall_store_file_info(cid.c_str(), file_info.c_str(), FILE_TYPE_VALID); acc++; } sgx_thread_mutex_unlock(&wl->file_mutex); } void WorkloadTest::test_delete_file(uint32_t file_num) { Workload *wl = Workload::get_instance(); sgx_thread_mutex_lock(&wl->file_mutex); if (wl->sealed_files.size() == 0) { sgx_thread_mutex_unlock(&wl->file_mutex); return; } for (uint32_t i = 0, j = 0; i < file_num && j < 200;) { uint32_t index = 0; sgx_read_rand(reinterpret_cast<uint8_t *>(&index), sizeof(uint32_t)); index = index % wl->sealed_files.size(); auto status = &wl->sealed_files[index][FILE_STATUS]; if (status->get_char(CURRENT_STATUS) != FILE_STATUS_DELETED) { wl->set_file_spec(status->get_char(CURRENT_STATUS), -wl->sealed_files[index][FILE_SEALED_SIZE].ToInt()); status->set_char(CURRENT_STATUS, FILE_STATUS_DELETED); i++; j = 0; } else { j++; } } sgx_thread_mutex_unlock(&wl->file_mutex); } void WorkloadTest::test_delete_file_unsafe(uint32_t file_num) { Workload *wl = Workload::get_instance(); sgx_thread_mutex_lock(&wl->file_mutex); file_num = std::min(wl->sealed_files.size(), (size_t)file_num); wl->sealed_files.erase(wl->sealed_files.begin(), wl->sealed_files.begin() + file_num); sgx_thread_mutex_unlock(&wl->file_mutex); wl->clean_wl_file_spec(); }
3,427
C++
.cpp
84
33.928571
130
0.611878
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,301
ValidatorTest.cpp
crustio_crust-sworker/test/src/enclave/validator/ValidatorTest.cpp
#include "ValidatorTest.h" #include "Identity.h" #include "Srd.h" #include <algorithm> // Srd related variables std::vector<uint8_t *> g_del_srd_v; sgx_thread_mutex_t g_del_srd_v_mutex = SGX_THREAD_MUTEX_INITIALIZER; std::map<int, uint8_t *> g_validate_srd_m; std::map<int, uint8_t *>::const_iterator g_validate_srd_m_iter; sgx_thread_mutex_t g_validate_srd_m_iter_mutex = SGX_THREAD_MUTEX_INITIALIZER; uint32_t g_validated_srd_num = 0; sgx_thread_mutex_t g_validated_srd_num_mutex = SGX_THREAD_MUTEX_INITIALIZER; // File related method and variables std::vector<json::JSON *> g_changed_files_v; sgx_thread_mutex_t g_changed_files_v_mutex = SGX_THREAD_MUTEX_INITIALIZER; std::map<std::string, json::JSON> g_validate_files_m; std::map<std::string, json::JSON>::const_iterator g_validate_files_m_iter; sgx_thread_mutex_t g_validate_files_m_iter_mutex = SGX_THREAD_MUTEX_INITIALIZER; uint32_t g_validated_files_num = 0; sgx_thread_mutex_t g_validated_files_num_mutex = SGX_THREAD_MUTEX_INITIALIZER; uint32_t g_validate_random = 0; sgx_thread_mutex_t g_validate_random_mutex = SGX_THREAD_MUTEX_INITIALIZER; std::string oneg_cid = ""; json::JSON oneg_file; /** * @description: validate srd disk */ void validate_srd_bench() { if (ENC_UPGRADE_STATUS_SUCCESS == Workload::get_instance()->get_upgrade_status()) { return; } crust_status_t crust_status = CRUST_SUCCESS; Workload *wl = Workload::get_instance(); sgx_thread_mutex_lock(&wl->srd_mutex); std::map<int, uint8_t *> tmp_validate_srd_m; size_t srd_validate_num = std::max((size_t)(wl->srd_hashs.size() * SRD_VALIDATE_RATE), (size_t)SRD_VALIDATE_MIN_NUM); srd_validate_num = std::min(srd_validate_num, wl->srd_hashs.size()); // Randomly choose validate srd files uint32_t rand_val; uint32_t rand_idx = 0; if (srd_validate_num >= wl->srd_hashs.size()) { for (size_t i = 0; i < wl->srd_hashs.size(); i++) { tmp_validate_srd_m[i] = wl->srd_hashs[i]; } } else { for (size_t i = 0; i < srd_validate_num; i++) { sgx_read_rand((uint8_t *)&rand_val, 4); rand_idx = rand_val % wl->srd_hashs.size(); tmp_validate_srd_m[rand_idx] = wl->srd_hashs[rand_idx]; } } sgx_thread_mutex_unlock(&wl->srd_mutex); // ----- Validate SRD ----- // sgx_status_t sgx_status = SGX_SUCCESS; sgx_thread_mutex_lock(&g_validate_srd_m_iter_mutex); g_validate_srd_m.insert(tmp_validate_srd_m.begin(), tmp_validate_srd_m.end()); tmp_validate_srd_m.clear(); g_validate_srd_m_iter = g_validate_srd_m.begin(); sgx_thread_mutex_unlock(&g_validate_srd_m_iter_mutex); // Generate validate random flag sgx_thread_mutex_lock(&g_validate_random_mutex); sgx_read_rand((uint8_t *)&g_validate_random, sizeof(g_validate_random)); sgx_thread_mutex_unlock(&g_validate_random_mutex); // Reset index and finish number sgx_thread_mutex_lock(&g_validated_srd_num_mutex); g_validated_srd_num = 0; sgx_thread_mutex_unlock(&g_validated_srd_num_mutex); for (size_t i = 0; i < g_validate_srd_m.size(); i++) { // If ocall failed, add srd to deleted buffer if (SGX_SUCCESS != (sgx_status = ocall_recall_validate_srd_bench())) { log_err("Invoke validate srd task failed! Error code:%lx\n", sgx_status); // Increase validate srd iterator sgx_thread_mutex_lock(&g_validate_srd_m_iter_mutex); uint32_t g_hash_index = g_validate_srd_m_iter->first; uint8_t *p_g_hash = g_validate_srd_m_iter->second; g_validate_srd_m_iter++; sgx_thread_mutex_unlock(&g_validate_srd_m_iter_mutex); // Increase validated srd finish num sgx_thread_mutex_lock(&g_validated_srd_num_mutex); g_validated_srd_num++; sgx_thread_mutex_unlock(&g_validated_srd_num_mutex); // Push current g_hash to delete buffer sgx_thread_mutex_lock(&g_del_srd_v_mutex); g_del_srd_v.push_back(p_g_hash); sgx_thread_mutex_unlock(&g_del_srd_v_mutex); wl->add_srd_to_deleted_buffer(g_hash_index); } } // Wait srd validation complete size_t wait_interval = 1000; size_t wait_time = 0; size_t timeout = (size_t)REPORT_SLOT * BLOCK_INTERVAL * 1000000; while (true) { SafeLock sl(g_validated_srd_num_mutex); sl.lock(); if (g_validated_srd_num >= g_validate_srd_m.size()) { wl->report_add_validated_srd_proof(); break; } sl.unlock(); ocall_usleep(wait_interval); // Check if timeout wait_time += wait_interval; if (wait_time > timeout) { break; } } // Delete failed srd metadata sgx_thread_mutex_lock(&g_del_srd_v_mutex); for (auto hash : g_del_srd_v) { std::string del_path = hexstring_safe(hash, HASH_LENGTH); ocall_delete_folder_or_file(&crust_status, del_path.c_str(), STORE_TYPE_SRD); } // Clear deleted srd buffer g_del_srd_v.clear(); sgx_thread_mutex_unlock(&g_del_srd_v_mutex); // Clear validate buffer sgx_thread_mutex_lock(&g_validate_srd_m_iter_mutex); g_validate_srd_m.clear(); sgx_thread_mutex_unlock(&g_validate_srd_m_iter_mutex); } /** * @description: Validate srd real */ void validate_srd_bench_real() { Workload *wl = Workload::get_instance(); // Get current validate random sgx_thread_mutex_lock(&g_validate_random_mutex); uint32_t cur_validate_random = g_validate_random; sgx_thread_mutex_unlock(&g_validate_random_mutex); // Get srd info from iterator SafeLock sl_iter(g_validate_srd_m_iter_mutex); sl_iter.lock(); uint32_t g_hash_index = 0; uint8_t *p_g_hash = wl->srd_hashs[g_hash_index]; g_validate_srd_m_iter++; sl_iter.unlock(); // Get g_hash corresponding path std::string g_hash = hexstring_safe(p_g_hash, HASH_LENGTH); bool deleted = false; Defer finish_defer([&cur_validate_random, &deleted, &p_g_hash, &g_hash_index, &wl](void) { // Get current validate random sgx_thread_mutex_lock(&g_validate_random_mutex); uint32_t now_validate_srd_random = g_validate_random; sgx_thread_mutex_unlock(&g_validate_random_mutex); // Check if validata random is the same if (cur_validate_random == now_validate_srd_random) { sgx_thread_mutex_lock(&g_validated_srd_num_mutex); g_validated_srd_num++; sgx_thread_mutex_unlock(&g_validated_srd_num_mutex); // Deal with result if (deleted) { sgx_thread_mutex_lock(&g_del_srd_v_mutex); g_del_srd_v.push_back(p_g_hash); sgx_thread_mutex_unlock(&g_del_srd_v_mutex); wl->add_srd_to_deleted_buffer(g_hash_index); } } }); // Get M hashs uint8_t *m_hashs_org = NULL; size_t m_hashs_size = 0; srd_get_file(get_m_hashs_file_path(g_hash.c_str()).c_str(), &m_hashs_org, &m_hashs_size); if (m_hashs_org == NULL) { if (!wl->add_srd_to_deleted_buffer(g_hash_index)) { return; } log_err("Get m hashs file(%s) failed.\n", g_hash.c_str()); deleted = true; return; } Defer hashs_org_defer([&m_hashs_org](void) { free(m_hashs_org); }); uint8_t *m_hashs = (uint8_t *)enc_malloc(m_hashs_size); if (m_hashs == NULL) { log_err("Malloc memory failed!\n"); return; } Defer hashs_defer([&m_hashs](void) { free(m_hashs); }); memset(m_hashs, 0, m_hashs_size); memcpy(m_hashs, m_hashs_org, m_hashs_size); // Compare M hashs sgx_sha256_hash_t m_hashs_sha256; sgx_sha256_msg(m_hashs, m_hashs_size, &m_hashs_sha256); if (memcmp(p_g_hash, m_hashs_sha256, HASH_LENGTH) != 0) { log_err("Wrong m hashs file(%s).\n", g_hash.c_str()); deleted = true; return; } // Get leaf data uint32_t rand_val; sgx_read_rand((uint8_t*)&rand_val, 4); size_t srd_block_index = rand_val % SRD_RAND_DATA_NUM; std::string leaf_path = get_leaf_path(g_hash.c_str(), srd_block_index, m_hashs + srd_block_index * HASH_LENGTH); uint8_t *leaf_data = NULL; size_t leaf_data_len = 0; srd_get_file(leaf_path.c_str(), &leaf_data, &leaf_data_len); if (leaf_data == NULL) { if (!wl->add_srd_to_deleted_buffer(g_hash_index)) { return; } log_err("Get leaf file(%s) failed.\n", g_hash.c_str()); deleted = true; return; } Defer leaf_defer([&leaf_data](void) { free(leaf_data); }); // Compare leaf data sgx_sha256_hash_t leaf_hash; sgx_sha256_msg(leaf_data, leaf_data_len, &leaf_hash); if (memcmp(m_hashs + srd_block_index * HASH_LENGTH, leaf_hash, HASH_LENGTH) != 0) { log_err("Wrong leaf data hash '%s'(file path:%s).\n", g_hash.c_str(), g_hash.c_str()); deleted = true; } } /** * @description: Validate Meaningful files */ void validate_meaningful_file_bench() { if (ENC_UPGRADE_STATUS_SUCCESS == Workload::get_instance()->get_upgrade_status()) { return; } Workload *wl = Workload::get_instance(); // Lock wl->sealed_files if (oneg_cid.compare("") == 0) { long target_size_min = 1024 * 1024 * 1024; long target_size_max = (100 + 1024) * 1024 * 1024; for (auto el : wl->sealed_files) { if (el[FILE_SIZE].ToInt() >= target_size_min && el[FILE_SIZE].ToInt() <= target_size_max) { oneg_cid = el[FILE_CID].ToString(); break; } } } size_t file_idx = 0; wl->is_file_dup_nolock(oneg_cid, file_idx); oneg_file = wl->sealed_files[file_idx]; std::map<std::string, json::JSON> tmp_validate_files_m; sgx_thread_mutex_lock(&wl->file_mutex); // Get to be checked files indexes size_t check_file_num = std::max((size_t)(wl->sealed_files.size() * MEANINGFUL_VALIDATE_RATE), (size_t)MEANINGFUL_VALIDATE_MIN_NUM); check_file_num = std::min(check_file_num, wl->sealed_files.size()); uint32_t rand_val; size_t rand_index = 0; if (check_file_num >= wl->sealed_files.size()) { for (size_t i = 0; i < wl->sealed_files.size(); i++) { tmp_validate_files_m[oneg_file[FILE_CID].ToString()] = wl->sealed_files[i]; } } else { for (size_t i = 0; i < check_file_num; i++) { sgx_read_rand((uint8_t *)&rand_val, 4); rand_index = rand_val % wl->sealed_files.size(); tmp_validate_files_m[oneg_file[FILE_CID].ToString()] = wl->sealed_files[rand_index]; } } sgx_thread_mutex_unlock(&wl->file_mutex); // ----- Validate file ----- // // Used to indicate which meaningful file status has been changed // If new file hasn't been verified, skip this validation sgx_status_t sgx_status = SGX_SUCCESS; sgx_thread_mutex_lock(&g_validate_files_m_iter_mutex); g_validate_files_m.insert(tmp_validate_files_m.begin(), tmp_validate_files_m.end()); tmp_validate_files_m.clear(); g_validate_files_m_iter = g_validate_files_m.begin(); sgx_thread_mutex_unlock(&g_validate_files_m_iter_mutex); // Generate validate random flag sgx_thread_mutex_lock(&g_validate_random_mutex); sgx_read_rand((uint8_t *)&g_validate_random, sizeof(g_validate_random)); sgx_thread_mutex_unlock(&g_validate_random_mutex); // Reset validate file finish flag sgx_thread_mutex_lock(&g_validated_files_num_mutex); g_validated_files_num = 0; sgx_thread_mutex_unlock(&g_validated_files_num_mutex); for (size_t i = 0; i < g_validate_files_m.size(); i++) { // If ocall failed, add file to deleted buffer if (SGX_SUCCESS != (sgx_status = ocall_recall_validate_file_bench())) { log_err("Invoke validate file task failed! Error code:%lx\n", sgx_status); // Get current file info sgx_thread_mutex_lock(&g_validate_files_m_iter_mutex); json::JSON *file = const_cast<json::JSON *>(&g_validate_files_m_iter->second); g_validate_files_m_iter++; sgx_thread_mutex_unlock(&g_validate_files_m_iter_mutex); // Increase validated files number sgx_thread_mutex_lock(&g_validated_files_num_mutex); g_validated_files_num++; sgx_thread_mutex_unlock(&g_validated_files_num_mutex); // Add file to deleted buffer sgx_thread_mutex_lock(&g_changed_files_v_mutex); g_changed_files_v.push_back(file); sgx_thread_mutex_unlock(&g_changed_files_v_mutex); } } // If report file flag is true, check if validating file is complete size_t wait_interval = 1000; size_t wait_time = 0; size_t timeout = (size_t)REPORT_SLOT * BLOCK_INTERVAL * 1000000; while (true) { SafeLock sl(g_validated_files_num_mutex); sl.lock(); if (g_validated_files_num >= g_validate_files_m.size()) { wl->report_add_validated_file_proof(); break; } sl.unlock(); ocall_usleep(wait_interval); // Check if timeout wait_time += wait_interval; if (wait_time > timeout) { break; } } // Change file status sgx_thread_mutex_lock(&g_changed_files_v_mutex); std::vector<json::JSON *> tmp_changed_files_v; tmp_changed_files_v.insert(tmp_changed_files_v.begin(), g_changed_files_v.begin(), g_changed_files_v.end()); g_changed_files_v.clear(); sgx_thread_mutex_unlock(&g_changed_files_v_mutex); if (tmp_changed_files_v.size() > 0) { sgx_thread_mutex_lock(&wl->file_mutex); for (auto file : tmp_changed_files_v) { std::string cid = (*file)[FILE_CID].ToString(); size_t index = 0; if(wl->is_file_dup_nolock(cid, index)) { long cur_block_num = wl->sealed_files[index][CHAIN_BLOCK_NUMBER].ToInt(); long val_block_num = g_validate_files_m[cid][CHAIN_BLOCK_NUMBER].ToInt(); // We can get original file and new sealed file(this situation maybe exist) // If these two files are not the same one, cannot delete the file if (cur_block_num == val_block_num) { char old_status = (*file)[FILE_STATUS].get_char(CURRENT_STATUS); char new_status = old_status; const char *old_status_ptr = NULL; const char *new_status_ptr = NULL; if (FILE_STATUS_VALID == old_status) { new_status = FILE_STATUS_LOST; new_status_ptr = FILE_TYPE_LOST; old_status_ptr = FILE_TYPE_VALID; } else if (FILE_STATUS_LOST == old_status) { new_status = FILE_STATUS_VALID; new_status_ptr = FILE_TYPE_VALID; old_status_ptr = FILE_TYPE_LOST; } else { continue; } log_info("File status changed, hash: %s status: %s -> %s\n", cid.c_str(), file_status_2_name[old_status].c_str(), file_status_2_name[new_status].c_str()); // Change file status wl->sealed_files[index][FILE_STATUS].set_char(CURRENT_STATUS, new_status); if (FILE_STATUS_LOST == new_status) { wl->sealed_files[index][FILE_LOST_INDEX] = (*file)[FILE_LOST_INDEX]; } else { wl->sealed_files[index][FILE_LOST_INDEX] = -1; } // Reduce valid file wl->set_file_spec(new_status, g_validate_files_m[cid][FILE_SIZE].ToInt()); wl->set_file_spec(old_status, -g_validate_files_m[cid][FILE_SIZE].ToInt()); // Sync with APP sealed file info ocall_change_file_type(cid.c_str(), old_status_ptr, new_status_ptr); } } else { log_err("Deal with bad file(%s) failed!\n", cid.c_str()); } } sgx_thread_mutex_unlock(&wl->file_mutex); } // Clear validate buffer sgx_thread_mutex_lock(&g_validate_files_m_iter_mutex); g_validate_files_m.clear(); sgx_thread_mutex_unlock(&g_validate_files_m_iter_mutex); } /** * @description: Validate meaningful files real */ void validate_meaningful_file_bench_real() { Workload *wl = Workload::get_instance(); // Get current validate random sgx_thread_mutex_lock(&g_validate_random_mutex); uint32_t cur_validate_random = g_validate_random; sgx_thread_mutex_unlock(&g_validate_random_mutex); // Get file info from iterator SafeLock sl_iter(g_validate_files_m_iter_mutex); sl_iter.lock(); if (g_validate_files_m.size() == 0) { return; } std::string cid = g_validate_files_m_iter->first; json::JSON *file = const_cast<json::JSON *>(&g_validate_files_m_iter->second); g_validate_files_m_iter++; sl_iter.unlock(); bool changed = false; bool lost = false; bool service_unavailable = false; Defer finish_defer([&cur_validate_random, &changed, &service_unavailable, &file, &wl](void) { // Get current validate random sgx_thread_mutex_lock(&g_validate_random_mutex); uint32_t now_validate_random = g_validate_random; sgx_thread_mutex_unlock(&g_validate_random_mutex); // Check if validate random is the same if (cur_validate_random == now_validate_random) { // Get current validate files size sgx_thread_mutex_lock(&g_validate_files_m_iter_mutex); size_t tmp_validate_files_m_num = g_validate_files_m.size(); sgx_thread_mutex_unlock(&g_validate_files_m_iter_mutex); // Increase validated files number sgx_thread_mutex_lock(&g_validated_files_num_mutex); if (service_unavailable) { if (g_validated_files_num < tmp_validate_files_m_num) { g_validated_files_num = tmp_validate_files_m_num; wl->set_report_file_flag(false); log_err("IPFS is offline! Please start it.\n"); } } else { g_validated_files_num++; } sgx_thread_mutex_unlock(&g_validated_files_num_mutex); // Deal with result if (changed) { sgx_thread_mutex_lock(&g_changed_files_v_mutex); g_changed_files_v.push_back(file); sgx_thread_mutex_unlock(&g_changed_files_v_mutex); } } }); // If file status is not FILE_STATUS_VALID, return auto status = (*file)[FILE_STATUS]; if (status.get_char(CURRENT_STATUS) == FILE_STATUS_PENDING || status.get_char(CURRENT_STATUS) == FILE_STATUS_DELETED) { return; } std::string root_cid = (*file)[FILE_CID].ToString(); std::string root_hash = (*file)[FILE_HASH].ToString(); size_t file_block_num = (*file)[FILE_BLOCK_NUM].ToInt(); // Get tree string uint8_t *p_tree = NULL; size_t tree_sz = 0; crust_status_t crust_status = persist_get_unsafe(root_cid, &p_tree, &tree_sz); if (CRUST_SUCCESS != crust_status) { if (wl->is_in_deleted_file_buffer(root_cid)) { return; } log_err("Validate meaningful data failed! Get tree:%s failed! Error code:%lx\n", root_cid.c_str(), crust_status); if (status.get_char(CURRENT_STATUS) == FILE_STATUS_VALID) { lost = true; } return; } Defer defer_tree([&p_tree](void) { free(p_tree); }); // Validate merkle tree sgx_sha256_hash_t tree_hash; sgx_sha256_msg(p_tree, tree_sz, &tree_hash); if (memcmp((*file)[FILE_HASH].ToBytes(), &tree_hash, HASH_LENGTH) != 0) { log_err("File:%s merkle tree is not valid! Root hash doesn't equal!\n", root_cid.c_str()); if (status.get_char(CURRENT_STATUS) == FILE_STATUS_VALID) { lost = true; } return; } // ----- Validate file block ----- // // Get to be checked block index std::set<size_t> block_idx_s; size_t tmp_idx = 0; uint32_t rand_val; for (size_t i = 0; i < MEANINGFUL_VALIDATE_MIN_BLOCK_NUM && i < file_block_num; i++) { sgx_read_rand((uint8_t *)&rand_val, 4); tmp_idx = rand_val % file_block_num; if (block_idx_s.find(tmp_idx) == block_idx_s.end()) { block_idx_s.insert(tmp_idx); } } // Validate lost data if have if (status.get_char(CURRENT_STATUS) == FILE_STATUS_LOST) { block_idx_s.insert((*file)[FILE_LOST_INDEX].ToInt()); } // Do check for (auto check_block_idx : block_idx_s) { // Get current node hash uint8_t *p_leaf = p_tree + check_block_idx * FILE_ITEM_LENGTH; std::string file_item = hexstring_safe(p_leaf, FILE_ITEM_LENGTH); std::string uuid = file_item.substr(0, UUID_LENGTH * 2); std::string leaf_hash = file_item.substr(UUID_LENGTH * 2, HASH_LENGTH * 2); // Compute current node hash by data uint8_t *p_sealed_data = NULL; size_t sealed_data_sz = 0; std::string leaf_path = uuid + root_cid + "/" + leaf_hash; crust_status = storage_get_file(leaf_path.c_str(), &p_sealed_data, &sealed_data_sz); if (CRUST_SUCCESS != crust_status) { if (wl->is_in_deleted_file_buffer(root_cid)) { continue; } if (status.get_char(CURRENT_STATUS) == FILE_STATUS_VALID) { log_err("Get file(%s) block:%ld failed!\n", leaf_path.c_str(), check_block_idx); (*file)[FILE_LOST_INDEX] = check_block_idx; } lost = true; continue; } Defer def_sealed_data([&p_sealed_data](void) { free(p_sealed_data); }); // Validate sealed hash sgx_sha256_hash_t got_hash; sgx_sha256_msg(p_sealed_data, sealed_data_sz, &got_hash); if (memcmp(p_leaf + UUID_LENGTH, got_hash, HASH_LENGTH) != 0) { if (status.get_char(CURRENT_STATUS) == FILE_STATUS_VALID) { log_err("File(%s) Index:%ld block hash is not expected!\n", root_cid.c_str(), check_block_idx); log_err("Get hash : %s\n", hexstring(got_hash, HASH_LENGTH)); log_err("Org hash : %s\n", leaf_hash.c_str()); (*file)[FILE_LOST_INDEX] = check_block_idx; } lost = true; continue; } } if ((!lost && status.get_char(CURRENT_STATUS) == FILE_STATUS_LOST) || (lost && status.get_char(CURRENT_STATUS) == FILE_STATUS_VALID)) { changed = true; } }
23,595
C++
.cpp
595
30.921008
136
0.579571
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,302
IdentityTest.cpp
crustio_crust-sworker/test/src/enclave/identity/IdentityTest.cpp
#include "IdentityTest.h" extern sgx_thread_mutex_t g_gen_work_report; crust_status_t id_gen_upgrade_data_test(size_t block_height) { SafeLock sl(g_gen_work_report); sl.lock(); crust_status_t crust_status = CRUST_SUCCESS; sgx_status_t sgx_status = SGX_SUCCESS; Workload *wl = Workload::get_instance(); // ----- Generate and upload work report ----- // // Current era has reported, wait for next slot if (block_height <= wl->get_report_height()) { return CRUST_BLOCK_HEIGHT_EXPIRED; } if (block_height < REPORT_SLOT + wl->get_report_height()) { return CRUST_UPGRADE_WAIT_FOR_NEXT_ERA; } size_t report_height = wl->get_report_height(); while (block_height > REPORT_SLOT + report_height) { report_height += REPORT_SLOT; } char report_hash[HASH_LENGTH * 2]; if (report_hash == NULL) { return CRUST_MALLOC_FAILED; } memset(report_hash, 0, HASH_LENGTH * 2); ocall_get_block_hash(&crust_status, report_height, report_hash, HASH_LENGTH * 2); if (CRUST_SUCCESS != crust_status) { return CRUST_UPGRADE_GET_BLOCK_HASH_FAILED; } // Send work report // Wait a random time:[10, 50] block time size_t random_time = 0; sgx_read_rand(reinterpret_cast<uint8_t *>(&random_time), sizeof(size_t)); random_time = ((random_time % (UPGRADE_WAIT_BLOCK_MAX - UPGRADE_WAIT_BLOCK_MIN + 1)) + UPGRADE_WAIT_BLOCK_MIN) * BLOCK_INTERVAL; log_info("Upgrade: Will generate and send work report after %ld blocks...\n", random_time / BLOCK_INTERVAL); if (CRUST_SUCCESS != (crust_status = gen_and_upload_work_report_test(report_hash, report_height, random_time, false, false))) { log_err("Fatal error! Send work report failed! Error code:%lx\n", crust_status); return CRUST_UPGRADE_GEN_WORKREPORT_FAILED; } log_debug("Upgrade: generate and send work report successfully!\n"); // ----- Generate upgrade data ----- // // Sign upgrade data std::string report_height_str = std::to_string(report_height); sgx_ecc_state_handle_t ecc_state = NULL; sgx_status = sgx_ecc256_open_context(&ecc_state); if (SGX_SUCCESS != sgx_status) { return CRUST_SGX_SIGN_FAILED; } Defer defer_ecc_state([&ecc_state](void) { if (ecc_state != NULL) { sgx_ecc256_close_context(ecc_state); } }); json::JSON srd_json = wl->get_upgrade_srd_info(&crust_status); if (CRUST_SUCCESS != crust_status) { return crust_status; } log_debug("Serialize srd data successfully!\n"); json::JSON file_json = wl->get_upgrade_file_info(&crust_status); if (CRUST_SUCCESS != crust_status) { return crust_status; } log_debug("Serialize file data successfully!\n"); std::vector<uint8_t> sig_buffer; // Pub key const uint8_t *p_pub_key = reinterpret_cast<const uint8_t *>(&wl->get_pub_key()); vector_end_insert(sig_buffer, p_pub_key, sizeof(sgx_ec256_public_t)); // Block height vector_end_insert(sig_buffer, report_height_str); // Block hash vector_end_insert(sig_buffer, reinterpret_cast<uint8_t *>(report_hash), HASH_LENGTH * 2); // Srd root vector_end_insert(sig_buffer, srd_json[WL_SRD_ROOT_HASH].ToBytes(), HASH_LENGTH); // Files root vector_end_insert(sig_buffer, file_json[WL_FILE_ROOT_HASH].ToBytes(), HASH_LENGTH); sgx_ec256_signature_t sgx_sig; sgx_status = sgx_ecdsa_sign(sig_buffer.data(), sig_buffer.size(), const_cast<sgx_ec256_private_t *>(&wl->get_pri_key()), &sgx_sig, ecc_state); if (SGX_SUCCESS != sgx_status) { return CRUST_SGX_SIGN_FAILED; } log_debug("Generate upgrade signature successfully!\n"); // ----- Get final upgrade data ----- // std::vector<uint8_t> upgrade_data; do { json::JSON upgrade_json; // Public key upgrade_json[UPGRADE_PUBLIC_KEY] = hexstring_safe(&wl->get_pub_key(), sizeof(sgx_ec256_public_t)); // BLock height upgrade_json[UPGRADE_BLOCK_HEIGHT] = report_height_str; // Block hash upgrade_json[UPGRADE_BLOCK_HASH] = std::string(report_hash, HASH_LENGTH * 2); // Srd upgrade_json[UPGRADE_SRD] = srd_json[WL_SRD]; // Files upgrade_json[UPGRADE_FILE] = file_json[WL_FILES]; // Srd root upgrade_json[UPGRADE_SRD_ROOT] = srd_json[WL_SRD_ROOT_HASH].ToString(); // Files root upgrade_json[UPGRADE_FILE_ROOT] = file_json[WL_FILE_ROOT_HASH].ToString(); // Signature upgrade_json[UPGRADE_SIG] = hexstring_safe(&sgx_sig, sizeof(sgx_ec256_signature_t)); upgrade_data = upgrade_json.dump_vector(&crust_status); if (CRUST_SUCCESS != crust_status) { return crust_status; } } while (0); // Store upgrade data crust_status = safe_ocall_store2(OCALL_STORE_UPGRADE_DATA, upgrade_data.data(), upgrade_data.size()); if (CRUST_SUCCESS != crust_status) { return crust_status; } log_debug("Store upgrade data successfully!\n"); wl->set_upgrade_status(ENC_UPGRADE_STATUS_SUCCESS); return crust_status; }
5,216
C++
.cpp
131
33.610687
132
0.639677
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,303
ReportTest.cpp
crustio_crust-sworker/test/src/enclave/report/ReportTest.cpp
#include "ReportTest.h" extern sgx_thread_mutex_t g_gen_work_report; /** * @description: Generate and upload signed validation report * @param block_hash (in) -> block hash * @param block_height (in) -> block height * @param wait_time -> Waiting time before upload * @param is_upgrading -> Is this upload kind of upgrade * @param locked -> Lock this upload or not * @return: sign status */ crust_status_t gen_and_upload_work_report_test(const char *block_hash, size_t block_height, long /*wait_time*/, bool is_upgrading, bool locked /*=true*/) { SafeLock gen_sl(g_gen_work_report); if (locked) { gen_sl.lock(); } crust_status_t crust_status = CRUST_SUCCESS; // Wait indicated time // Generate work report if (CRUST_SUCCESS != (crust_status = gen_work_report(block_hash, block_height, is_upgrading))) { return crust_status; } // Upload work report ocall_upload_workreport(&crust_status); // Confirm work report result return crust_status; }
1,028
C++
.cpp
30
30.333333
153
0.687879
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,304
AppTest.cpp
crustio_crust-sworker/test/src/app/AppTest.cpp
#include "AppTest.h" bool offline_chain_mode = false; bool g_use_sys_disk = false; bool g_upgrade_flag = false; extern std::string config_file_path; crust::Log *p_log = crust::Log::get_instance(); /** * @description: application main entry * @param argc -> the number of command parameters * @param argv[] -> parameter array * @return: exit flag */ int SGX_CDECL main(int argc, char *argv[]) { // Get configure file path if exists bool is_set_config = false; for (int i = 1; i < argc; i++) { if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) { goto show_help; } else if (strcmp(argv[i], "-c") == 0 || strcmp(argv[i], "--config") == 0) { if (i + 1 >= argc) { p_log->err("-c option needs configure file path as argument!\n"); return 1; } config_file_path = std::string(argv[i + 1]); is_set_config = true; i++; } else if (strcmp(argv[i], "--upgrade") == 0) { g_upgrade_flag = true; i++; } else if (strcmp(argv[i], "-v") == 0 || strcmp(argv[i], "--version") == 0) { printf("Release version: %s\ \nSWorker version: %s\n", VERSION, SWORKER_VERSION); return 0; } else if (strcmp(argv[i], "--use-sysdisk") == 0) { g_use_sys_disk = true; } else if (strcmp(argv[i], "--offline") == 0) { offline_chain_mode = true; } else if (strcmp(argv[i], "--debug") == 0) { p_log->set_debug(true); p_log->debug("Debug log is opened.\n"); } else { goto show_help; } } // Check if configure path has been indicated if (!is_set_config) { p_log->err("Please indicate configure file path!\n"); goto show_help; } // Main branch return main_daemon(); show_help: printf(" Usage: \n"); printf(" %s <option> <argument>\n", argv[0]); printf(" option: \n"); printf(" -h, --help: help information. \n"); printf(" -c, --config: required, indicate configure file path, followed by configure file path. Like: '--config Config.json'\n"); printf(" If no file provided, default path is etc/Config.json. \n"); printf(" -v, --version: show whole version and sworker version. \n"); printf(" --offline: add this flag, program will not interact with the chain. \n"); printf(" --debug: add this flag, program will output debug logs. \n"); printf(" --upgrade: used to upgrade.\n"); return 0; } /** * @description: run main progress * @return: exit flag */ int main_daemon() { return process_run_test(); }
2,927
C++
.cpp
91
25.021978
143
0.516095
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,305
ApiHandlerTest.cpp
crustio_crust-sworker/test/src/app/http/ApiHandlerTest.cpp
#include "ApiHandlerTest.h" #include "ECalls.h" #include "ECallsTest.h" extern size_t g_block_height; extern sgx_enclave_id_t global_eid; /** * @description: Start rest service * @return: Start status */ json::JSON http_handler_test(UrlEndPoint urlendpoint, json::JSON req) { std::string req_route = req["target"].ToString(); std::string cur_path; json::JSON res_json; std::string method = req["method"].ToString(); EnclaveData *ed = EnclaveData::get_instance(); EnclaveDataTest *edTest = EnclaveDataTest::get_instance(); crust::Log *p_log = crust::Log::get_instance(); std::string req_body = req["body"].ToString(); remove_char(req_body, '\\'); // ----- Respond to GET request ----- // if(method.compare("GET") == 0) { cur_path = urlendpoint.base + "/upgrade/start"; if (req_route.size() == cur_path.size() && req_route.compare(cur_path) == 0) { int ret_code = 200; std::string ret_info; if (UPGRADE_STATUS_NONE != ed->get_upgrade_status() && UPGRADE_STATUS_STOP_WORKREPORT != ed->get_upgrade_status()) { res_json[HTTP_STATUS_CODE] = 300; res_json[HTTP_MESSAGE] = "Another upgrading is still running!"; goto getcleanup; } // Block current work-report for a while ed->set_upgrade_status(UPGRADE_STATUS_STOP_WORKREPORT); sgx_status_t sgx_status = SGX_SUCCESS; crust_status_t crust_status = CRUST_SUCCESS; if (SGX_SUCCESS != (sgx_status = Ecall_enable_upgrade(global_eid, &crust_status, g_block_height+REPORT_SLOT+REPORT_INTERVAL_BLCOK_NUMBER_LOWER_LIMIT))) { ret_info = "Invoke SGX API failed!"; ret_code = 401; p_log->err("%sError code:%lx\n", ret_info.c_str(), sgx_status); } else { if (CRUST_SUCCESS == crust_status) { ret_info = "Receive upgrade inform successfully!"; ret_code = 200; // Set upgrade status ed->set_upgrade_status(UPGRADE_STATUS_PROCESS); // Give current tasks some time to go into enclave queue. sleep(10); p_log->info("%s\n", ret_info.c_str()); } else { switch (crust_status) { case CRUST_UPGRADE_BLOCK_EXPIRE: ret_info = "Block expired!Wait for next slot."; ret_code = 402; break; case CRUST_UPGRADE_NO_VALIDATE: ret_info = "Necessary validation not completed!"; ret_code = 403; break; case CRUST_UPGRADE_RESTART: ret_info = "Cannot report due to restart!Wait for next slot."; ret_code = 404; break; case CRUST_UPGRADE_NO_FILE: ret_info = "Cannot get files for check!Please check ipfs!"; ret_code = 405; break; default: ret_info = "Unknown error."; ret_code = 406; } g_block_height += REPORT_SLOT; } } res_json[HTTP_STATUS_CODE] = ret_code; res_json[HTTP_MESSAGE] = ret_info; goto getcleanup; } cur_path = urlendpoint.base + "/report/work"; if (req_route.size() == cur_path.size() && req_route.compare(cur_path) == 0) { crust_status_t crust_status = CRUST_SUCCESS; uint8_t *hash_u = (uint8_t *)malloc(32); int tmp_int; int ret_code = 400; std::string ret_info; for (uint32_t i = 0; i < 32 / sizeof(tmp_int); i++) { tmp_int = rand(); memcpy(hash_u + i * sizeof(tmp_int), &tmp_int, sizeof(tmp_int)); } std::string block_hash = hexstring_safe(hash_u, 32); g_block_height += REPORT_SLOT; free(hash_u); if (SGX_SUCCESS != Ecall_gen_and_upload_work_report_test(global_eid, &crust_status, block_hash.c_str(), g_block_height + REPORT_SLOT)) { res_json[HTTP_STATUS_CODE] = 400; ret_info = "Get signed work report failed!"; p_log->err("%s\n", ret_info.c_str()); } else { if (CRUST_SUCCESS == crust_status) { // Send signed validation report to crust chain p_log->info("Send work report successfully!\n"); std::string work_str = EnclaveData::get_instance()->get_workreport(); res_json[HTTP_MESSAGE] = work_str; res_json[HTTP_STATUS_CODE] = 200; goto getcleanup; } if (crust_status == CRUST_BLOCK_HEIGHT_EXPIRED) { ret_code = 401; ret_info = "Block height expired."; p_log->info("%s\n", ret_info.c_str()); } else if (crust_status == CRUST_FIRST_WORK_REPORT_AFTER_REPORT) { ret_code = 402; ret_info = "Can't generate work report for the first time after restart"; p_log->info("%s\n", ret_info.c_str()); } else { ret_code = 403; ret_info = "Get signed validation report failed!"; p_log->err("%s Error code: %x\n", ret_info.c_str(), crust_status); } } res_json[HTTP_STATUS_CODE] = ret_code; res_json[HTTP_MESSAGE] = ret_info; goto getcleanup; } // --- Srd change API --- // cur_path = urlendpoint.base + "/report/result"; if (req_route.size() == cur_path.size() && req_route.compare(cur_path) == 0) { res_json[HTTP_STATUS_CODE] = 200; std::string ret_info; // Confirm new file report_add_callback(); ret_info = "Reporting result task has beening added!"; res_json[HTTP_MESSAGE] = ret_info; goto getcleanup; } cur_path = urlendpoint.base + "/validate/add_proof"; if (req_route.size() == cur_path.size() && req_route.compare(cur_path) == 0) { Ecall_add_validate_proof(global_eid); res_json[HTTP_STATUS_CODE] = 200; res_json[HTTP_MESSAGE] = "validate add proof."; goto getcleanup; } cur_path = urlendpoint.base + "/validate/srd"; if (req_route.size() == cur_path.size() && req_route.compare(cur_path) == 0) { Ecall_validate_srd_test(global_eid); res_json[HTTP_STATUS_CODE] = 200; res_json[HTTP_MESSAGE] = "validate srd."; goto getcleanup; } cur_path = urlendpoint.base + "/validate/srd_bench"; if (req_route.size() == cur_path.size() && req_route.compare(cur_path) == 0) { Ecall_validate_srd_bench(global_eid); res_json[HTTP_STATUS_CODE] = 200; res_json[HTTP_MESSAGE] = "validate srd."; goto getcleanup; } cur_path = urlendpoint.base + "/validate/file"; if (req_route.size() == cur_path.size() && req_route.compare(cur_path) == 0) { Ecall_validate_file_test(global_eid); res_json[HTTP_STATUS_CODE] = 200; res_json[HTTP_MESSAGE] = "validate file."; goto getcleanup; } cur_path = urlendpoint.base + "/validate/file_bench"; if (req_route.size() == cur_path.size() && req_route.compare(cur_path) == 0) { Ecall_validate_file_bench(global_eid); res_json[HTTP_STATUS_CODE] = 200; res_json[HTTP_MESSAGE] = "validate file bench."; goto getcleanup; } cur_path = urlendpoint.base + "/store_metadata"; if (req_route.size() == cur_path.size() && req_route.compare(cur_path) == 0) { Ecall_store_metadata(global_eid); res_json[HTTP_STATUS_CODE] = 200; res_json[HTTP_MESSAGE] = "store metadata"; goto getcleanup; } cur_path = urlendpoint.base + "/test/add_file"; if (req_route.size() == cur_path.size() && req_route.compare(cur_path) == 0) { json::JSON req_json = json::JSON::Load_unsafe(req_body); long file_num = req_json["file_num"].ToInt(); Ecall_test_add_file(global_eid, file_num); res_json[HTTP_MESSAGE] = "Add file successfully!"; res_json[HTTP_STATUS_CODE] = 200; goto getcleanup; } cur_path = urlendpoint.base + "/test/delete_file"; if (req_route.size() == cur_path.size() && req_route.compare(cur_path) == 0) { json::JSON req_json = json::JSON::Load_unsafe(req_body); uint32_t file_num = req_json["file_num"].ToInt(); Ecall_test_delete_file(global_eid, file_num); res_json[HTTP_MESSAGE] = "Delete file successfully!"; res_json[HTTP_STATUS_CODE] = 200; goto getcleanup; } cur_path = urlendpoint.base + "/test/delete_file_unsafe"; if (req_route.size() == cur_path.size() && req_route.compare(cur_path) == 0) { json::JSON req_json = json::JSON::Load_unsafe(req_body); uint32_t file_num = req_json["file_num"].ToInt(); Ecall_test_delete_file_unsafe(global_eid, file_num); EnclaveData::get_instance()->restore_file_info(reinterpret_cast<const uint8_t *>("{}"), 2); res_json[HTTP_MESSAGE] = "Delete file successfully!"; res_json[HTTP_STATUS_CODE] = 200; goto getcleanup; } cur_path = urlendpoint.base + "/clean_file"; if (req_route.size() == cur_path.size() && req_route.compare(cur_path) == 0) { Ecall_clean_file(global_eid); res_json[HTTP_MESSAGE] = "Clean file successfully!"; res_json[HTTP_STATUS_CODE] = 200; goto getcleanup; } cur_path = urlendpoint.base + "/file_info"; if (req_route.size() == cur_path.size() && req_route.compare(cur_path) == 0) { json::JSON req_json = json::JSON::Load_unsafe(req_body); std::string hash = req_json["hash"].ToString(); crust_status_t crust_status = CRUST_SUCCESS; Ecall_get_file_info(global_eid, &crust_status, hash.c_str()); if (CRUST_SUCCESS == crust_status) { res_json[HTTP_MESSAGE] = edTest->get_file_info(); res_json[HTTP_STATUS_CODE] = 200; } else { res_json[HTTP_MESSAGE] = ""; res_json[HTTP_STATUS_CODE] = 400; } } getcleanup: return res_json; } // ----- Respond to POST request ----- // if(method.compare("POST") == 0) { cur_path = urlendpoint.base + "/storage/delete_sync"; if (req_route.size() == cur_path.size() && req_route.compare(cur_path) == 0) { std::string ret_info; int ret_code = 400; // Delete file json::JSON req_json = json::JSON::Load_unsafe(req_body); std::string cid = req_json["cid"].ToString(); // Check cid if (cid.size() != CID_LENGTH) { ret_info = "Delete file failed! Invalid cid:" + cid; p_log->err("%s\n", ret_info.c_str()); ret_code = 400; res_json[HTTP_STATUS_CODE] = ret_code; res_json[HTTP_MESSAGE] = ret_info; goto postcleanup; } sgx_status_t sgx_status = SGX_SUCCESS; crust_status_t crust_status = CRUST_SUCCESS; ret_info = "Deleting file failed!"; if (SGX_SUCCESS != (sgx_status = Ecall_delete_file(global_eid, &crust_status, cid.c_str()))) { ret_code = 401; ret_info = "Delete file failed!"; p_log->err("Delete file(%s) failed!Invoke SGX API failed!Error code:%lx\n", cid.c_str(), sgx_status); } else if (CRUST_SUCCESS != crust_status) { ret_code = 402; ret_info = "Delete file failed!"; p_log->err("Delete file(%s) failed!Error code:%lx\n", cid.c_str(), crust_status); } else { EnclaveData::get_instance()->del_file_info(cid); p_log->info("Delete file(%s) successfully!\n", cid.c_str()); res_json[HTTP_STATUS_CODE] = 200; res_json[HTTP_MESSAGE] = "Deleting file successfully!"; goto postcleanup; } res_json[HTTP_STATUS_CODE] = ret_code; res_json[HTTP_MESSAGE] = ret_info; goto postcleanup; } cur_path = urlendpoint.base + "/srd/set_change"; if (req_route.size() == cur_path.size() && req_route.compare(cur_path) == 0) { int ret_code = 400; std::string ret_info; // Check input parameters json::JSON req_json = json::JSON::Load_unsafe(req_body); long change_srd_num = req_json["change"].ToInt(); if (change_srd_num == 0) { p_log->info("Invalid change\n"); ret_info = "Invalid change"; ret_code = 400; } else { // Start changing srd if (SGX_SUCCESS != Ecall_srd_change_test(global_eid, change_srd_num, false)) { ret_info = "Change srd failed!"; ret_code = 401; } else { ret_info = "Change srd successfully!"; ret_code = 200; } p_log->info("%s\n", ret_info.c_str()); } res_json[HTTP_STATUS_CODE] = ret_code; res_json[HTTP_MESSAGE] = ret_info; goto postcleanup; } cur_path = urlendpoint.base + "/srd/change_real"; if (req_route.size() == cur_path.size() && req_route.compare(cur_path) == 0) { int ret_code = 400; std::string ret_info; // Check input parameters json::JSON req_json = json::JSON::Load_unsafe(req_body); long change_srd_num = req_json["change"].ToInt(); crust_status_t crust_status = CRUST_SUCCESS; if (change_srd_num == 0) { p_log->info("Invalid change\n"); ret_info = "Invalid change"; ret_code = 400; } else { // Start changing srd if (SGX_SUCCESS == Ecall_srd_change_test(global_eid, change_srd_num, true) && CRUST_SUCCESS == crust_status) { ret_info = "Change srd successfully!"; ret_code = 200; } else { ret_info = "Set srd change failed!"; ret_code = 400; } } res_json[HTTP_STATUS_CODE] = ret_code; res_json[HTTP_MESSAGE] = ret_info; goto postcleanup; } postcleanup: return res_json; } return res_json; }
16,249
C++
.cpp
385
28.350649
163
0.490391
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,306
ValidateTest.cpp
crustio_crust-sworker/test/src/app/process/ValidateTest.cpp
#include "ValidateTest.h" #include "ECallsTest.h" ctpl::thread_pool *g_validate_pool = NULL; std::vector<std::shared_ptr<std::future<void>>> g_validate_tasks_v; extern sgx_enclave_id_t global_eid; void validate_file_test() { if (g_validate_pool == NULL) { g_validate_pool = new ctpl::thread_pool(Config::get_instance()->srd_thread_num - 2); } // Push new task sgx_enclave_id_t eid = global_eid; g_validate_tasks_v.push_back(std::make_shared<std::future<void>>(g_validate_pool->push([eid](int /*id*/){ Ecall_validate_file_bench_real(eid); }))); // Check and remove complete task for (auto it = g_validate_tasks_v.begin(); it != g_validate_tasks_v.end(); ) { if ((*it)->wait_for(std::chrono::seconds(0)) == std::future_status::ready) { it = g_validate_tasks_v.erase(it); } else { it++; } } } void validate_srd_test() { if (g_validate_pool == NULL) { g_validate_pool = new ctpl::thread_pool(Config::get_instance()->srd_thread_num - 2); } // Push new task sgx_enclave_id_t eid = global_eid; g_validate_tasks_v.push_back(std::make_shared<std::future<void>>(g_validate_pool->push([eid](int /*id*/){ Ecall_validate_srd_bench_real(eid); }))); // Check and remove complete task for (auto it = g_validate_tasks_v.begin(); it != g_validate_tasks_v.end(); ) { if ((*it)->wait_for(std::chrono::seconds(0)) == std::future_status::ready) { it = g_validate_tasks_v.erase(it); } else { it++; } } }
1,652
C++
.cpp
53
25.056604
109
0.581658
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,307
SrdTest.cpp
crustio_crust-sworker/test/src/app/process/SrdTest.cpp
#include "SrdTest.h" #include "Srd.h" #include "ECalls.h" #include "ECallsTest.h" #include "Ctpl.h" crust::Log *p_log = crust::Log::get_instance(); extern sgx_enclave_id_t global_eid; bool srd_change_test(long change) { Config *p_config = Config::get_instance(); if (change > 0) { long left_task = change; json::JSON disk_info_json = get_increase_srd_info(left_task); long true_increase = change - left_task; // Print disk info for (auto info : disk_info_json.ArrayRange()) { if (info[WL_DISK_USE].ToInt() > 0) { p_log->info("Available space is %ldG in '%s', this turn will use %ldG space\n", info[WL_DISK_AVAILABLE_FOR_SRD].ToInt(), info[WL_DISK_PATH].ToString().c_str(), info[WL_DISK_USE].ToInt()); } } p_log->info("Start sealing %luG srd files (thread number: %d) ...\n", true_increase, p_config->srd_thread_num); // ----- Do srd ----- // // Use omp parallel to seal srd disk, the number of threads is equal to the number of CPU cores ctpl::thread_pool pool(p_config->srd_thread_num); std::vector<std::shared_ptr<std::future<crust_status_t>>> tasks_v; long task = true_increase; while (task > 0) { for (int i = 0; i < disk_info_json.size() && task > 0; i++, task--) { sgx_enclave_id_t eid = global_eid; std::string uuid = disk_info_json[i][WL_DISK_UUID].ToString(); tasks_v.push_back(std::make_shared<std::future<crust_status_t>>(pool.push([eid, uuid](int /*id*/){ sgx_status_t sgx_status = SGX_SUCCESS; crust_status_t increase_ret = CRUST_SUCCESS; if (SGX_SUCCESS != (sgx_status = Ecall_srd_increase_test(eid, &increase_ret, uuid.c_str())) || CRUST_SUCCESS != increase_ret) { // If failed, add current task to next turn long real_change = 0; crust_status_t change_ret = CRUST_SUCCESS; Ecall_change_srd_task(eid, &change_ret, 1, &real_change); sgx_status = SGX_ERROR_UNEXPECTED; } if (SGX_SUCCESS != sgx_status) { increase_ret = CRUST_UNEXPECTED_ERROR; } decrease_running_srd_task(); return increase_ret; }))); } } // Wait for srd task long srd_success_num = 0; for (auto it : tasks_v) { try { if (CRUST_SUCCESS == it->get()) { srd_success_num++; } } catch (std::exception &e) { p_log->err("Catch exception:"); std::cout << e.what() << std::endl; } } if (srd_success_num == 0) { return false; } if (srd_success_num < change) { p_log->info("Srd task: %dG, success: %dG, failed: %dG due to timeout or no more disk space.\n", change, srd_success_num, change - srd_success_num); } else { p_log->info("Increase %dG srd files success.\n", change); } } else if (change < 0) { size_t true_decrease = 0; sgx_status_t sgx_status = SGX_SUCCESS; if (SGX_SUCCESS != (sgx_status = Ecall_srd_decrease_test(global_eid, &true_decrease, (size_t)-change))) { p_log->err("Decrease %ldG srd failed! Error code:%lx\n", change, sgx_status); } else { p_log->info("Decrease %luG srd successfully.\n", true_decrease); } } return true; }
4,034
C++
.cpp
106
25.54717
114
0.484663
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,308
AsyncTest.cpp
crustio_crust-sworker/test/src/app/process/AsyncTest.cpp
#include "AsyncTest.h" #include "ECallsTest.h" crust::Log *p_log = crust::Log::get_instance(); extern sgx_enclave_id_t global_eid; /** * @description: Add delete meaningful file task * @param hash -> Meaningful file root hash */ void report_add_callback() { sgx_enclave_id_t eid = global_eid; std::async(std::launch::async, [eid](){ sgx_status_t sgx_status = SGX_SUCCESS; if (SGX_SUCCESS != (sgx_status = Ecall_handle_report_result(eid))) { p_log->err("Report result failed!Invoke SGX API failed!Error code:%lx\n", sgx_status); } }); }
598
C++
.cpp
19
27.210526
98
0.649306
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,309
EnclaveDataTest.cpp
crustio_crust-sworker/test/src/app/process/EnclaveDataTest.cpp
#include "EnclaveDataTest.h" #include "ECalls.h" EnclaveDataTest *EnclaveDataTest::enclavedataTest = NULL; EnclaveDataTest *EnclaveDataTest::get_instance() { if (EnclaveDataTest::enclavedataTest == NULL) { EnclaveDataTest::enclavedataTest = new EnclaveDataTest(); } return EnclaveDataTest::enclavedataTest; } void EnclaveDataTest::set_file_info(std::string file_info) { g_file_info = file_info; } std::string EnclaveDataTest::get_file_info() { return g_file_info; }
503
C++
.cpp
19
23.526316
65
0.753653
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,310
ProcessTest.cpp
crustio_crust-sworker/test/src/app/process/ProcessTest.cpp
#include "ProcessTest.h" #include "WebServer.h" extern bool initialize_config(void); extern bool initialize_enclave(); extern bool initialize_components(void); extern bool start_task(task_func_t func); extern bool do_upgrade(); extern sgx_enclave_id_t global_eid; extern Config *p_config; extern std::map<task_func_t, std::shared_ptr<std::future<void>>> g_tasks_m; extern crust::Log *p_log; extern bool offline_chain_mode; extern int g_start_server_success; extern bool g_upgrade_flag; size_t g_block_height; /** * @description: Main function to start application * @return: Start status */ int process_run_test() { pid_t worker_pid = getpid(); sgx_status_t sgx_status = SGX_SUCCESS; crust_status_t crust_status = CRUST_SUCCESS; int return_status = 1; int check_interval = 15; int upgrade_timeout = 5 * REPORT_SLOT * BLOCK_INTERVAL; int upgrade_tryout = upgrade_timeout / check_interval; int entry_tryout = 3; size_t srd_task = 0; long srd_real_change = 0; std::string srd_task_str; EnclaveData *ed = EnclaveData::get_instance(); crust::DataBase *db = NULL; p_log->info("WorkerPID = %d\n", worker_pid); // Init conifigure if (!initialize_config()) { p_log->err("Init configuration failed!\n"); return_status = -1; goto cleanup; } // There are three startup mode: upgrade, restore and normal // Upgrade mode will communicate with old version for data transferring. // Resotre mode will restore enclave data from database. // Normal mode will start up a new enclave. // ----- Upgrade mode ----- // if (g_upgrade_flag) { // Check and do upgrade do_upgrade(); p_log->info("Upgrade from old version successfully!\n"); } else { // Init related components if (!initialize_components()) { p_log->err("Init component failed!\n"); return_status = -1; goto cleanup; } entry_network_flag: // Init enclave if (!initialize_enclave()) { p_log->err("Init enclave failed!\n"); return_status = -1; goto cleanup; } p_log->info("Worker global eid: %d\n", global_eid); // Start enclave if (SGX_SUCCESS != Ecall_restore_metadata(global_eid, &crust_status) || CRUST_SUCCESS != crust_status) { // ----- Normal startup ----- // // Restore data failed p_log->info("Starting a new enclave...(code:%lx)\n", crust_status); // Generate ecc key pair if (SGX_SUCCESS != Ecall_gen_key_pair(global_eid, &sgx_status, p_config->chain_account_id.c_str(), p_config->chain_account_id.size()) || SGX_SUCCESS != sgx_status) { p_log->err("Generate key pair failed!\n"); return_status = -1; goto cleanup; } p_log->info("Generate key pair successfully!\n"); // Get id info if (SGX_SUCCESS != Ecall_id_get_info(global_eid)) { p_log->err("Get id info from enclave failed!\n"); return_status = -1; goto cleanup; } // Entry network if (!offline_chain_mode) { crust_status = entry_network(); if (CRUST_SUCCESS != crust_status) { if (CRUST_INIT_QUOTE_FAILED == crust_status && entry_tryout > 0) { entry_tryout--; sgx_destroy_enclave(global_eid); global_eid = 0; sleep(60); goto entry_network_flag; } goto cleanup; return_status = -1; } } } else { // ----- Restore data successfully ----- // // Compare crust account it in configure file and recovered file if (SGX_SUCCESS != Ecall_cmp_chain_account_id(global_eid, &crust_status, p_config->chain_account_id.c_str(), p_config->chain_account_id.size()) || CRUST_SUCCESS != crust_status) { p_log->err("Configure chain account id doesn't equal to recovered one!\n"); return_status = -1; goto cleanup; } p_log->info("Workload information:\n%s\n", ed->gen_workload_str().c_str()); p_log->info("Restore enclave data successfully, sworker is running now.\n"); } } db = crust::DataBase::get_instance(); // Get srd remaining task if (CRUST_SUCCESS == db->get(WL_SRD_REMAINING_TASK, srd_task_str)) { std::stringstream sstream(srd_task_str); size_t srd_task_remain = 0; sstream >> srd_task_remain; srd_task = std::max(srd_task, srd_task_remain); } // Restore or add srd task if (srd_task > 0) { p_log->info("Detect %ldGB srd task, will execute later.\n", srd_task); if (SGX_SUCCESS != (sgx_status = Ecall_change_srd_task(global_eid, &crust_status, srd_task, &srd_real_change))) { p_log->err("Set srd change failed!Invoke SGX api failed! Error code:%lx\n", sgx_status); } else { switch (crust_status) { case CRUST_SUCCESS: p_log->info("Add srd task successfully! %ldG has been added, will be executed later.\n", srd_real_change); break; case CRUST_SRD_NUMBER_EXCEED: p_log->warn("Add srd task failed!Srd number has reached the upper limit! Real srd task is %ldG.\n", srd_real_change); break; default: p_log->info("Unexpected error has occurred!\n"); } } } // Construct uuid to disk path map ed->construct_uuid_disk_path_map(); // Start http service if (!start_task(start_webservice)) { p_log->err("Start web service failed!\n"); goto cleanup; } // Check block height and post report to chain //start_task(work_report_loop); // Start thread to check srd reserved //start_task(srd_check_reserved); // Main validate loop //start_task(main_loop); // Check loop while (true) { // Deal with upgrade if (UPGRADE_STATUS_PROCESS == ed->get_upgrade_status()) { if (EnclaveQueue::get_instance()->get_upgrade_ecalls_num() == 0) { ed->set_upgrade_status(UPGRADE_STATUS_END); } } if (UPGRADE_STATUS_END == ed->get_upgrade_status()) { p_log->info("Start generating upgrade data...\n"); if (SGX_SUCCESS != (sgx_status = Ecall_gen_upgrade_data_test(global_eid, &crust_status, g_block_height+REPORT_SLOT+REPORT_INTERVAL_BLCOK_NUMBER_LOWER_LIMIT))) { p_log->err("Generate upgrade metadata failed! Invoke SGX API failed! Error code:%lx. Try next turn!\n", sgx_status); } else if (CRUST_SUCCESS != crust_status) { p_log->warn("Generate upgrade metadata failed! Code:%lx. Try next turn!\n", crust_status); } else { p_log->info("Generate upgrade metadata successfully!\n"); ed->set_upgrade_status(UPGRADE_STATUS_COMPLETE); } } // Upgrade tryout if (UPGRADE_STATUS_NONE != ed->get_upgrade_status()) { if (--upgrade_tryout < 0) { p_log->err("Upgrade timeout!Current version will restore work!\n"); ed->set_upgrade_status(UPGRADE_STATUS_NONE); upgrade_tryout = upgrade_timeout / check_interval; // Restore related work //if (!restore_tasks()) //{ // p_log->err("Restore tasks failed! Will exist...\n"); // goto cleanup; //} } } // Sleep and check exit flag if (!sleep_interval(check_interval, [&ed](void) { if (UPGRADE_STATUS_EXIT == ed->get_upgrade_status()) { // Wait tasks end bool has_task_running = false; for (auto task : g_tasks_m) { if(task.first == start_webservice) { continue; } if (task.second->wait_for(std::chrono::seconds(0)) != std::future_status::ready) { has_task_running = true; } } return has_task_running; } return true; })) { goto cleanup; } } cleanup: // Release database p_log->info("Release database for exit...\n"); if (db != NULL) { delete db; } // Stop web service p_log->info("Kill web service for exit...\n"); stop_webservice(); // Destroy enclave // TODO: Fix me, why destory enclave leads to coredump p_log->info("Destroy enclave for exit...\n"); sgx_destroy_enclave(global_eid); return return_status; }
9,467
C++
.cpp
257
26.245136
145
0.535224
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,311
ECallsTest.cpp
crustio_crust-sworker/test/src/app/ecalls/ECallsTest.cpp
#include "ECallsTest.h" EnclaveQueue *eq = EnclaveQueue::get_instance(); sgx_status_t Ecall_handle_report_result(sgx_enclave_id_t eid) { sgx_status_t ret = SGX_SUCCESS; if (SGX_SUCCESS != (ret = eq->try_get_enclave(__FUNCTION__))) { return ret; } ret = ecall_handle_report_result(eid); eq->free_enclave(__FUNCTION__); return ret; } sgx_status_t Ecall_add_validate_proof(sgx_enclave_id_t eid) { sgx_status_t ret = SGX_SUCCESS; if (SGX_SUCCESS != (ret = eq->try_get_enclave(__FUNCTION__))) { return ret; } ret = ecall_add_validate_proof(eid); eq->free_enclave(__FUNCTION__); return ret; } sgx_status_t Ecall_validate_srd_test(sgx_enclave_id_t eid) { sgx_status_t ret = SGX_SUCCESS; if (SGX_SUCCESS != (ret = eq->try_get_enclave(__FUNCTION__))) { return ret; } ret = ecall_validate_srd_test(eid); eq->free_enclave(__FUNCTION__); return ret; } sgx_status_t Ecall_validate_srd_bench(sgx_enclave_id_t eid) { sgx_status_t ret = SGX_SUCCESS; if (SGX_SUCCESS != (ret = eq->try_get_enclave(__FUNCTION__))) { return ret; } ret = ecall_validate_srd_bench(eid); eq->free_enclave(__FUNCTION__); return ret; } sgx_status_t Ecall_validate_file_test(sgx_enclave_id_t eid) { sgx_status_t ret = SGX_SUCCESS; if (SGX_SUCCESS != (ret = eq->try_get_enclave(__FUNCTION__))) { return ret; } ret = ecall_validate_file_test(eid); eq->free_enclave(__FUNCTION__); return ret; } sgx_status_t Ecall_validate_file_bench(sgx_enclave_id_t eid) { sgx_status_t ret = SGX_SUCCESS; if (SGX_SUCCESS != (ret = eq->try_get_enclave(__FUNCTION__))) { return ret; } ret = ecall_validate_file_bench(eid); eq->free_enclave(__FUNCTION__); return ret; } sgx_status_t Ecall_store_metadata(sgx_enclave_id_t eid) { sgx_status_t ret = SGX_SUCCESS; if (SGX_SUCCESS != (ret = eq->try_get_enclave(__FUNCTION__))) { return ret; } ret = ecall_store_metadata(eid); eq->free_enclave(__FUNCTION__); return ret; } sgx_status_t Ecall_test_add_file(sgx_enclave_id_t eid, long file_num) { sgx_status_t ret = SGX_SUCCESS; if (SGX_SUCCESS != (ret = eq->try_get_enclave(__FUNCTION__))) { return ret; } ret = ecall_test_add_file(eid, file_num); eq->free_enclave(__FUNCTION__); return ret; } sgx_status_t Ecall_test_delete_file(sgx_enclave_id_t eid, uint32_t file_num) { sgx_status_t ret = SGX_SUCCESS; if (SGX_SUCCESS != (ret = eq->try_get_enclave(__FUNCTION__))) { return ret; } ret = ecall_test_delete_file(eid, file_num); eq->free_enclave(__FUNCTION__); return ret; } sgx_status_t Ecall_test_delete_file_unsafe(sgx_enclave_id_t eid, uint32_t file_num) { sgx_status_t ret = SGX_SUCCESS; if (SGX_SUCCESS != (ret = eq->try_get_enclave(__FUNCTION__))) { return ret; } ret = ecall_test_delete_file_unsafe(eid, file_num); eq->free_enclave(__FUNCTION__); return ret; } sgx_status_t Ecall_srd_increase_test(sgx_enclave_id_t eid, crust_status_t *status, const char *uuid) { sgx_status_t ret = SGX_SUCCESS; if (SGX_SUCCESS != (ret = eq->try_get_enclave(__FUNCTION__))) { return ret; } ret = ecall_srd_increase_test(eid, status, uuid); eq->free_enclave(__FUNCTION__); return ret; } sgx_status_t Ecall_srd_decrease_test(sgx_enclave_id_t eid, size_t *size, size_t change) { sgx_status_t ret = SGX_SUCCESS; if (SGX_SUCCESS != (ret = eq->try_get_enclave(__FUNCTION__))) { return ret; } ret = ecall_srd_decrease_test(eid, size, change); eq->free_enclave(__FUNCTION__); return ret; } sgx_status_t Ecall_clean_file(sgx_enclave_id_t eid) { sgx_status_t ret = SGX_SUCCESS; if (SGX_SUCCESS != (ret = eq->try_get_enclave(__FUNCTION__))) { return ret; } ret = ecall_clean_file(eid); eq->free_enclave(__FUNCTION__); return ret; } sgx_status_t Ecall_get_file_info(sgx_enclave_id_t eid, crust_status_t *status, const char *data) { sgx_status_t ret = SGX_SUCCESS; if (SGX_SUCCESS != (ret = eq->try_get_enclave(__FUNCTION__))) { return ret; } ret = ecall_get_file_info(eid, status, data); eq->free_enclave(__FUNCTION__); return ret; } sgx_status_t Ecall_gen_upgrade_data_test(sgx_enclave_id_t eid, crust_status_t *status, size_t block_height) { sgx_status_t ret = SGX_SUCCESS; if (SGX_SUCCESS != (ret = eq->try_get_enclave(__FUNCTION__))) { return ret; } ret = ecall_gen_upgrade_data_test(eid, status, block_height); eq->free_enclave(__FUNCTION__); return ret; } sgx_status_t Ecall_gen_and_upload_work_report_test(sgx_enclave_id_t eid, crust_status_t *status, const char *block_hash, size_t block_height) { sgx_status_t ret = SGX_SUCCESS; if (SGX_SUCCESS != (ret = eq->try_get_enclave(__FUNCTION__))) { return ret; } ret = ecall_gen_and_upload_work_report_test(eid, status, block_hash, block_height); eq->free_enclave(__FUNCTION__); return ret; } sgx_status_t Ecall_srd_change_test(sgx_enclave_id_t eid, long change, bool real) { sgx_status_t ret = SGX_SUCCESS; if (SGX_SUCCESS != (ret = eq->try_get_enclave(__FUNCTION__))) { return ret; } ret = ecall_srd_change_test(eid, change, real); eq->free_enclave(__FUNCTION__); return ret; } sgx_status_t Ecall_validate_file_bench_real(sgx_enclave_id_t eid) { sgx_status_t ret = SGX_SUCCESS; if (SGX_SUCCESS != (ret = eq->try_get_enclave(__FUNCTION__))) { return ret; } ret = ecall_validate_file_bench_real(eid); eq->free_enclave(__FUNCTION__); return ret; } sgx_status_t Ecall_validate_srd_bench_real(sgx_enclave_id_t eid) { sgx_status_t ret = SGX_SUCCESS; if (SGX_SUCCESS != (ret = eq->try_get_enclave(__FUNCTION__))) { return ret; } ret = ecall_validate_srd_bench_real(eid); eq->free_enclave(__FUNCTION__); return ret; }
6,135
C++
.cpp
211
24.469194
141
0.631093
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,312
OCallsTest.cpp
crustio_crust-sworker/test/src/app/ocalls/OCallsTest.cpp
#include "OCallsTest.h" crust::Log *p_log = crust::Log::get_instance(); crust_status_t ocall_srd_change_test(long change) { return srd_change_test(change) ? CRUST_SUCCESS : CRUST_UNEXPECTED_ERROR; } crust_status_t ocall_get_file_bench(const char * /*file_path*/, unsigned char **p_file, size_t *len) { crust_status_t crust_status = CRUST_SUCCESS; if (access("<%CRUST_TEST_SRD_PATH%>", 0) == -1) { return CRUST_ACCESS_FILE_FAILED; } // Judge if given path is file struct stat s; if (stat ("<%CRUST_TEST_SRD_PATH%>", &s) == 0) { if (s.st_mode & S_IFDIR) return CRUST_OPEN_FILE_FAILED; } std::ifstream in; in.open("<%CRUST_TEST_SRD_PATH%>", std::ios::out | std::ios::binary); if (! in) { return CRUST_OPEN_FILE_FAILED; } in.seekg(0, std::ios::end); *len = in.tellg(); in.seekg(0, std::ios::beg); uint8_t *p_data = (uint8_t *)malloc(*len); memset(p_data, 0, *len); in.read(reinterpret_cast<char *>(p_data), *len); in.close(); *p_file = p_data; return crust_status; } void ocall_store_file_info_test(const char *info) { EnclaveDataTest::get_instance()->set_file_info(info); } crust_status_t ocall_get_file_block(const char *file_path, unsigned char **p_file, size_t *len) { std::string file_path_r = std::string("<%CRUST_FILE_PATH%>").append(file_path); if (access(file_path_r.c_str(), 0) == -1) { return CRUST_ACCESS_FILE_FAILED; } // Judge if given path is file struct stat s; if (stat (file_path_r.c_str(), &s) == 0) { if (s.st_mode & S_IFDIR) return CRUST_OPEN_FILE_FAILED; } std::ifstream in; in.open(file_path_r, std::ios::out | std::ios::binary); if (! in) { return CRUST_OPEN_FILE_FAILED; } in.seekg(0, std::ios::end); *len = in.tellg(); in.seekg(0, std::ios::beg); uint8_t *p_data = (uint8_t *)malloc(*len); memset(p_data, 0, *len); in.read(reinterpret_cast<char *>(p_data), *len); in.close(); *p_file = p_data; return CRUST_SUCCESS; } void ocall_recall_validate_file_bench() { validate_file_test(); } void ocall_recall_validate_srd_bench() { validate_srd_test(); }
2,268
C++
.cpp
78
24.25641
100
0.606187
crustio/crust-sworker
36
11
15
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false