Last active
June 20, 2017 09:26
-
-
Save Psirus/f1a5679b40cfd38b329849a609bf8b7b to your computer and use it in GitHub Desktop.
Command pattern for PDE evaluate
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <vector> | |
#include <iostream> | |
#include <cmath> | |
#include <eigen3/Eigen/Core> | |
class Cell; | |
// base class for "operations": hessians, gradients, etc. | |
template <typename ReturnType> | |
class Operation | |
{ | |
public: | |
virtual ~Operation() {}; | |
virtual ReturnType Calculate(const Cell& cell) = 0; | |
protected: | |
Operation() {}; | |
}; | |
// dummy cell; saves one value | |
class Cell | |
{ | |
public: | |
Cell(double val) : midPointValue(val) {}; | |
template <typename T> | |
T Integrate(Operation<T>& op) | |
{ | |
return 2*op.Calculate(*this); | |
} | |
double midPointValue; | |
}; | |
// a calculate hessian operation | |
class Hessian0 : public Operation<Eigen::MatrixXd> | |
{ | |
public: | |
Hessian0() {}; | |
virtual Eigen::MatrixXd Calculate(const Cell& cell) override | |
{ | |
Eigen::Matrix2d hessian; | |
hessian << cell.midPointValue, 0, 0, cell.midPointValue; | |
return hessian; | |
} | |
}; | |
// a build gradient operation | |
class Gradient : public Operation<Eigen::VectorXd> | |
{ | |
public: | |
Gradient() {}; | |
virtual Eigen::VectorXd Calculate(const Cell& cell) override | |
{ | |
double x = std::sqrt(cell.midPointValue); | |
return Eigen::Vector2d(x, -x); | |
} | |
}; | |
// a "structure" as a container of cells | |
class Structure | |
{ | |
public: | |
Structure() | |
{ | |
mCells.push_back(Cell(1.0)); | |
mCells.push_back(Cell(2.0)); | |
mCells.push_back(Cell(3.0)); | |
} | |
template <typename T> | |
void DoOnAllCells(Operation<T>& op) | |
{ | |
for (auto& cell : mCells) | |
std::cout << cell.Integrate(op) << std::endl;; | |
} | |
private: | |
std::vector<Cell> mCells; | |
}; | |
int main() | |
{ | |
Structure structure; | |
// create a new operation | |
Hessian0 hessianOperation; | |
// do it on all cell | |
structure.DoOnAllCells(hessianOperation); | |
// just another example | |
Gradient gradientOperation; | |
structure.DoOnAllCells(gradientOperation); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment