#include "ModuleBase.h" #include #include #include namespace mdd { class ModuleMath : public ModuleBase { private: const std::map> _ops = { {"add", [](double a, double b) {return a + b; }}, {"subtract", [](double a, double b) {return a - b; }}, {"multiply", [](double a, double b) {return a * b; }}, {"divide", [](double a, double b) {return a / b; }}, {"power", [](double a, double b) {return pow(a, b); }}, {"logarithm", [](double a, double b) {return log(b) / log(a); }}, {"minimum", [](double a, double b) {return std::min(a, b); }}, {"maximum", [](double a, double b) {return std::max(a, b); }}, {"lesser", [](double a, double b) {return a > b; }}, {"greater", [](double a, double b) {return a < b; }} }; std::function _operation; std::vector applyOperation(const std::vector& val1, const std::vector& val2); public: ModuleMath(); bool configure(const std::string& config) override; std::string getConfiguration(); state update() override; }; ModuleMath::ModuleMath() : ModuleBase(R"JSON( [{ "name":"operation", "value":"add", "options": [ "add", "subtract", "multiply", "divide", "power", "logarithm", "minimum", "maximum", "lesser", "greater" ] }])JSON") { _ops.at("add"); _operation = _ops.find("add")->second; std::vector default_val = {1}; inputs.push_back(std::make_shared(this, "Value", 0, default_val)); inputs.push_back(std::make_shared(this, "Value", 1, default_val)); outputs.push_back(std::make_shared(this, "Value", 0, default_val)); setType("Math"); } bool ModuleMath::configure(const std::string& config) { json config_parsed = json::parse(config); for (size_t i = 0; i < config_parsed.size(); i++) { if (config_parsed[i].contains("name")) { if (config_parsed[i]["name"].get() == "operation") { const std::string op = config_parsed[i]["value"].get(); auto it = _ops.find(op); if (it != _ops.end()) { _operation = it->second; return true; } } } } return false; } std::string ModuleMath::getConfiguration() { json ret = json::parse(ModuleBase::getConfiguration()); for (auto it = _ops.begin(); it != _ops.end(); it++) { if (it->second(256,2) == _operation(256, 2)) { ret[0]["value"] = it->first; break; } } return ret.dump(); } std::vector ModuleMath::applyOperation(const std::vector&val1, const std::vector&val2) { std::vector ret; //= json::array(); size_t length= std::max(val1.size(), val2.size()); for (int i = 0; i < length; i++) { if (val1.size() == val2.size()) { ret.push_back(_operation(val1[i], val2[i])); } else if (1 == val1.size()) { ret.push_back(_operation(val1[0], val2[i])); } else if (1 == val2.size()) { ret.push_back(_operation(val1[i], val2[0])); } } return ret; } state ModuleMath::update() { std::vector ret = applyOperation(getInput(0)->getValue(), getInput(1)->getValue()); return getOutput(0)->setValue(ret); } } //gdb //catch throw //run