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,534,792
analyzer.cpp
ustb-owl_TinyMIPS/src/compiler/front/analyzer.cpp
#include "front/analyzer.h" #include <iostream> #include <cassert> #include "util/style.h" using namespace tinylang::front; using namespace tinylang::define; TypePtr Analyzer::LogError(const char *message) { using namespace tinylang::util; // print error message std::cerr << style("B") << "analyzer"; std::cerr << " (line " << line_pos_.top(); std::cerr << "): " << style("Br") << "error"; std::cerr << ": " << message << std::endl; // increase error count ++error_num_; return nullptr; } TypePtr Analyzer::LogError(const char *message, const std::string &id) { using namespace tinylang::util; // print error message std::cerr << style("B") << "analyzer"; std::cerr << " (line " << line_pos_.top(); std::cerr << ", id: " << id; std::cerr << "): " << style("Br") << "error"; std::cerr << ": " << message << std::endl; // increase error count ++error_num_; return nullptr; } TypePtr Analyzer::AnalyzeFunDef(const std::string &id, TypePtrList args, TypePtr ret) { // NOTE: current env is argument env const auto &func_env = env_->outer(); // check if is in root env if (!func_env->is_root()) { return LogError("nested function is not allowed", id); } // check if is existed if (func_env->GetItem(id, false)) { return LogError("identifier has already beed defined", id); } // create return type auto right_ret = std::move(ret); if (!right_ret->IsRightValue()) { right_ret = right_ret->GetRightValue(true); } // create function symbol auto type = std::make_shared<FuncType>(std::move(args), std::move(right_ret)); func_env->AddItem(id, std::move(type)); return MakeVoidType(); } TypePtr Analyzer::AnalyzeFunCall(const std::string &id, const TypePtrList &args) { // get type of id auto type = env_->GetItem(id); if (!type) return LogError("identifier has not been defined", id); // check return type auto ret = type->GetReturnType(args); if (!ret) return LogError("invalid function call", id); return ret; } TypePtr Analyzer::AnalyzeControl(Keyword type, const TypePtr &expr) { switch (type) { case Keyword::Break: case Keyword::Continue: { // check if is in a while loop if (!while_count_) { return LogError("using break/continue outside the loop"); } break; } case Keyword::Return: { // check if is in a function if (!cur_ret_) { return LogError("using 'return' outside the function"); } else { auto type = expr; if (!type) type = MakeVoidType(); // check if is compatible assert(cur_ret_->IsVoid() || !cur_ret_->IsRightValue()); if (!cur_ret_->CanAccept(type)) { return LogError("type mismatch when returning"); } } break; } default: assert(false); } return MakeVoidType(); } TypePtr Analyzer::AnalyzeVarElem(const std::string &id, TypePtr type, const TypePtr &init) { // check if is defined if (env_->GetItem(id, false)) { return LogError("identifier has already beed defined", id); } if (type) { // check if is compatible if (init && !type->CanAccept(init)) { return LogError("type mismatch when initializing", id); } // add symbol info env_->AddItem(id, std::move(type)); } else { assert(init != nullptr); // check if can be deduced if (init->IsVoid() || init->IsFunction()) { return LogError("initializing a vairable with invalid type", id); } // add symbol info auto left_type = init; if (left_type->IsRightValue()) { left_type = left_type->GetRightValue(false); } env_->AddItem(id, std::move(left_type)); } return MakeVoidType(); } TypePtr Analyzer::AnalyzeLetElem(const std::string &id, TypePtr type, const TypePtr &init) { assert(init != nullptr); TypePtr const_type; // check if is defined if (env_->GetItem(id, false)) { return LogError("identifier has already beed defined", id); } if (type) { // check if is compatible if (!type->CanAccept(init)) { return LogError("type mismatch when initializing", id); } const_type = std::move(type); } else { // check if can be deduced if (init->IsVoid() || init->IsFunction()) { return LogError("initializing a vairable with 'void' type", id); } const_type = init; if (const_type->IsRightValue()) { const_type = const_type->GetRightValue(false); } } // add symbol info if (!const_type->IsConst()) { const_type = std::make_shared<ConstType>(std::move(const_type)); } env_->AddItem(id, std::move(const_type)); return MakeVoidType(); } TypePtr Analyzer::AnalyzeType(Keyword type, unsigned int ptr) { auto ret = MakePlainType(type, false); if (ptr) { ret = std::make_shared<PointerType>(std::move(ret), ptr); } return ret; } TypePtr Analyzer::AnalyzeArgElem(const std::string &id, TypePtr type) { if (env_->GetItem(id, false)) { return LogError("duplicated argument name", id); } assert(!type->IsRightValue()); env_->AddItem(id, std::move(type)); return type; } TypePtr Analyzer::AnalyzeBinary(Operator op, const TypePtr &lhs, const TypePtr &rhs) { // preprocess some types if (lhs->IsVoid() || rhs->IsVoid() || lhs->IsFunction() || rhs->IsFunction()) { return LogError("invalid operation"); } switch (op) { // integer operations #1 case Operator::Add: case Operator::Sub: { TypePtr ret; if (lhs->IsPointer() || rhs->IsPointer()) { if (lhs->IsPointer() && rhs->IsPointer()) { return LogError("invalid pointer operation"); } ret = lhs->IsPointer() ? lhs : rhs; } else if (lhs->GetSize() != rhs->GetSize()) { ret = lhs->GetSize() > rhs->GetSize() ? lhs : rhs; } else if (lhs->IsUnsigned() || rhs->IsUnsigned()) { ret = lhs->IsUnsigned() ? lhs : rhs; } else { ret = lhs; } return ret->IsRightValue() ? ret : ret->GetRightValue(true); } // integer operations #2 case Operator::Mul: case Operator::Div: case Operator::Mod: case Operator::And: case Operator::Or: case Operator::Xor: case Operator::Shl: case Operator::Shr: { TypePtr ret; if (lhs->IsPointer() || rhs->IsPointer()) { return LogError("operation cannot be done with pointers"); } else if (lhs->GetSize() != rhs->GetSize()) { ret = lhs->GetSize() > rhs->GetSize() ? lhs : rhs; } else if (lhs->IsUnsigned() || rhs->IsUnsigned()) { ret = lhs->IsUnsigned() ? lhs : rhs; } else { ret = lhs; } return ret->IsRightValue() ? ret : ret->GetRightValue(true); } // relational operations case Operator::LogicAnd: case Operator::LogicOr: case Operator::Less: case Operator::LessEqual: case Operator::Great: case Operator::GreatEqual: case Operator::Equal: case Operator::NotEqual: { if (lhs->IsPointer() ^ rhs->IsPointer()) { return LogError("lhs and rhs must be both pointer/non-pointer"); } else if (lhs->IsUnsigned() ^ rhs->IsUnsigned()) { return LogError("lhs and rhs must be both signed/unsigned"); } return MakePlainType(Keyword::UInt32, true); } // assign operations case Operator::Assign: case Operator::AssAdd: case Operator::AssSub: case Operator::AssMul: case Operator::AssDiv: case Operator::AssMod: case Operator::AssAnd: case Operator::AssOr: case Operator::AssXor: case Operator::AssShl: case Operator::AssShr: { // check if is compatible if (!lhs->CanAccept(rhs)) { return LogError("type mismatch when assigning"); } // check if is compound assign operator if (op != Operator::Assign) { auto de_ass = GetDeAssignedOp(op); if (!AnalyzeBinary(de_ass, lhs, rhs)) return nullptr; } return MakeVoidType(); } default: assert(false); return nullptr; } } TypePtr Analyzer::AnalyzeCast(const TypePtr &expr, const TypePtr &type) { if (!expr->CanCastTo(type)) return LogError("invalid type casting"); assert(!type->IsRightValue()); return expr->IsRightValue() ? type->GetRightValue(true) : type; } TypePtr Analyzer::AnalyzeUnary(Operator op, const TypePtr &opr) { switch (op) { // integer operations case Operator::Add: case Operator::Sub: case Operator::Not: { if (!opr->IsInteger()) return LogError("expected integer types"); return opr->IsRightValue() ? opr : opr->GetRightValue(true); } // logic operations case Operator::LogicNot: { if (!opr->IsInteger() && !opr->IsPointer()) { return LogError("expected integer/pointer types"); } return std::make_shared<ConstType>( MakePlainType(Keyword::UInt32, true)); } // pointer operations case Operator::Mul: { if (!opr->IsPointer()) return LogError("expected pointer types"); auto deref = opr->GetDerefedType(); // dereference operation will make a left value return deref->IsRightValue() ? deref->GetRightValue(false) : deref; } // get address operations case Operator::And: { if (opr->IsVoid() || opr->IsFunction() || opr->IsRightValue()) { return LogError("invalid 'address-of' operation"); } auto right = opr->IsRightValue() ? opr : opr->GetRightValue(true); return std::make_shared<PointerType>(std::move(right), 1); } // other default: assert(false); return nullptr; } } TypePtr Analyzer::AnalyzeId(const std::string &id) { // get type of id auto type = env_->GetItem(id); if (!type) return LogError("identifier has not been defined", id); return type; } TypePtr Analyzer::AnalyzeNum() { return MakePlainType(Keyword::Int32, true); } TypePtr Analyzer::AnalyzeString() { auto char_type = MakePlainType(Keyword::UInt8, true); auto str_type = std::make_shared<PointerType>(std::move(char_type), 1); return std::make_shared<ConstType>(std::move(str_type)); } TypePtr Analyzer::AnalyzeChar() { return MakePlainType(Keyword::UInt8, true); } TypePtr Analyzer::AnalyzeArray(const TypePtrList &elems) { TypePtr deduced; for (const auto &i : elems) { // check if is invalid type if (i->IsVoid() || i->IsFunction()) { return LogError("invalid type of array element"); } // deduce type of array if (!deduced) { deduced = i; } else if (i->IsPointer()) { if (!deduced->IsPointer() || !IsPointerCompatible(*deduced, *i)) { return LogError("type mismatch in array elements"); } } else if (deduced->GetSize() != i->GetSize()) { deduced = deduced->GetSize() > i->GetSize() ? deduced : i; } else if (deduced->IsUnsigned() || i->IsUnsigned()) { deduced = deduced->IsUnsigned() ? deduced : i; } } // remove const specifier and make right value assert(deduced != nullptr); if (deduced->IsConst()) deduced = deduced->GetDeconstedType(); if (!deduced->IsRightValue()) deduced = deduced->GetRightValue(true); // create new type auto arr_type = std::make_shared<PointerType>(std::move(deduced), 1); return std::make_shared<ConstType>(std::move(arr_type)); } TypePtr Analyzer::AnalyzeIndex(const std::string &id, const TypePtr &index) { // get type of id auto type = env_->GetItem(id); if (!type) return LogError("identifier has not been defined", id); // check if is a pointer if (!type->IsPointer()) return LogError("invalid pointer", id); // check index type if (!index->IsInteger()) return LogError("invalid index", id); // get dereferenced type auto deref = type->GetDerefedType(); assert(deref != nullptr); // indexing operation will make a left value return deref->IsRightValue() ? deref->GetRightValue(false) : deref; }
12,028
C++
.cpp
349
29.223496
73
0.632012
ustb-owl/TinyMIPS
34
6
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,793
parser.cpp
ustb-owl_TinyMIPS/src/compiler/front/parser.cpp
#include "front/parser.h" #include <iostream> #include <utility> #include <stack> #include "util/style.h" using namespace tinylang::front; using namespace tinylang::define; namespace { // table of operator's precedence // -1 if it's not a binary/assign operator const int op_prec_table[] = { 90, 90, 100, 100, 100, 60, 60, 70, 70, 70, 70, 20, 10, -1, 50, 30, -1, 40, 80, 80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; template <typename T, typename... Args> inline ASTPtr MakeAST(unsigned int line_pos, Args &&... args) { auto ast = std::make_unique<T>(std::forward<Args>(args)...); ast->set_line_pos(line_pos); return ast; } inline int GetOpPrec(Operator op) { return op_prec_table[static_cast<int>(op)]; } } ASTPtr Parser::LogError(const char *message) { using namespace tinylang::util; // print error message std::cerr << style("B") << "parser"; std::cerr << " (line " << lexer_.line_pos(); std::cerr << "): " << style("Br") << "error"; std::cerr << ": " << message << std::endl; // increase error count ++error_num_; return nullptr; } ASTPtr Parser::ParseStatement() { if (cur_token_ == Token::Keyword) { // switch by keyword switch (lexer_.key_val()) { case Keyword::Var: return ParseVarDef(); case Keyword::Let: return ParseLetDef(); case Keyword::Def: return ParseFunDef(); case Keyword::If: return ParseIf(); case Keyword::While: return ParseWhile(); case Keyword::Break: case Keyword::Continue: case Keyword::Return: return ParseControl(); default: return LogError("invalid statement"); } } else { return ParseExpression(); } } ASTPtr Parser::ParseVarDef() { auto line_pos = lexer_.line_pos(); // get definition list if (NextToken() != Token::Id) return LogError("expected identifier"); ASTPtrList defs; for (;;) { auto elem = ParseVarElem(); if (!elem) return nullptr; defs.push_back(std::move(elem)); // eat ',' if (!IsTokenChar(',')) break; NextToken(); } return MakeAST<VarDefAST>(line_pos, std::move(defs)); } ASTPtr Parser::ParseLetDef() { auto line_pos = lexer_.line_pos(); // get definition list if (NextToken() != Token::Id) return LogError("expected identifier"); ASTPtrList defs; for (;;) { auto elem = ParseLetElem(); if (!elem) return nullptr; defs.push_back(std::move(elem)); // eat ',' if (!IsTokenChar(',')) break; NextToken(); } return MakeAST<LetDefAST>(line_pos, std::move(defs)); } ASTPtr Parser::ParseFunDef() { auto line_pos = lexer_.line_pos(); // get identifier if (NextToken() != Token::Id) return LogError("expected identifier"); auto id = lexer_.id_val(); NextToken(); // get argument list if (!CheckChar('(')) return nullptr; ASTPtrList args; if (!IsTokenChar(')')) { // parse all argument definitions for (;;) { auto arg = ParseArgElem(); if (!arg) return nullptr; args.push_back(std::move(arg)); // eat ',' if (!IsTokenChar(',')) break; NextToken(); } } if (!CheckChar(')')) return nullptr; // check & get return type ASTPtr type; if (IsTokenChar(':')) { NextToken(); type = ParseType(); if (!type) return nullptr; } // get function body ASTPtr body; if (IsTokenChar('{')) { body = ParseBlock(); if (!body) return nullptr; } return MakeAST<FunDefAST>(line_pos, id, std::move(args), std::move(type), std::move(body)); } ASTPtr Parser::ParseIf() { auto line_pos = lexer_.line_pos(); NextToken(); // get condition expression auto cond = ParseExpression(); if (!cond) return nullptr; // get then body auto then = ParseBlock(); if (!then) return nullptr; // get else then body ASTPtr else_then; if (IsTokenKeyword(Keyword::Else)) { NextToken(); else_then = IsTokenKeyword(Keyword::If) ? ParseIf() : ParseBlock(); if (!else_then) return nullptr; } return MakeAST<IfAST>(line_pos, std::move(cond), std::move(then), std::move(else_then)); } ASTPtr Parser::ParseWhile() { auto line_pos = lexer_.line_pos(); NextToken(); // get condition expression auto cond = ParseExpression(); if (!cond) return nullptr; // get body auto body = ParseBlock(); if (!body) return nullptr; return MakeAST<WhileAST>(line_pos, std::move(cond), std::move(body)); } ASTPtr Parser::ParseControl() { auto line_pos = lexer_.line_pos(); // get keyword type auto type = lexer_.key_val(); NextToken(); // check return expression ASTPtr expr; // TODO: tricky operation if (type == Keyword::Return && lexer_.line_pos() == line_pos) { expr = ParseExpression(); if (!expr) return nullptr; } return MakeAST<ControlAST>(line_pos, type, std::move(expr)); } ASTPtr Parser::ParseVarElem() { auto line_pos = lexer_.line_pos(); // get identifier if (cur_token_ != Token::Id) return LogError("expected identifier"); auto id = lexer_.id_val(); NextToken(); // get type ASTPtr type; if (IsTokenChar(':')) { NextToken(); type = ParseType(); if (!type) return nullptr; } // get initialization expression ASTPtr init; if (IsTokenOperator(Operator::Assign)) { NextToken(); init = ParseExpression(); if (!init) return nullptr; } // check type & init if (!type && !init) return LogError("initializer required"); return MakeAST<VarElemAST>(line_pos, id, std::move(type), std::move(init)); } ASTPtr Parser::ParseLetElem() { auto line_pos = lexer_.line_pos(); // get identifier if (cur_token_ != Token::Id) return LogError("expected identifier"); auto id = lexer_.id_val(); NextToken(); // get type ASTPtr type; if (IsTokenChar(':')) { NextToken(); type = ParseType(); if (!type) return nullptr; } // get initialization expression ASTPtr init; if (!IsTokenOperator(Operator::Assign)) { return LogError("expected initialization expression"); } NextToken(); init = ParseExpression(); if (!init) return nullptr; return MakeAST<LetElemAST>(line_pos, id, std::move(type), std::move(init)); } ASTPtr Parser::ParseType() { auto line_pos = lexer_.line_pos(); // check if is type if (cur_token_ != Token::Keyword) return LogError("expected type"); switch (lexer_.key_val()) { case Keyword::Int32: case Keyword::Int8: case Keyword::UInt32: case Keyword::UInt8: break; default: return LogError("expected type"); } // get type auto type = lexer_.key_val(); NextToken(); // get pointer count unsigned int ptr = 0; while (IsTokenOperator(Operator::Mul)) { NextToken(); ++ptr; } return MakeAST<TypeAST>(line_pos, type, ptr); } ASTPtr Parser::ParseArgElem() { auto line_pos = lexer_.line_pos(); // get identifier if (cur_token_ != Token::Id) return LogError("expected identifier"); auto id = lexer_.id_val(); NextToken(); // check ':' if (!CheckChar(':')) return nullptr; // get type auto type = ParseType(); if (!type) return nullptr; return MakeAST<ArgElemAST>(line_pos, id, std::move(type)); } ASTPtr Parser::ParseBlock() { auto line_pos = lexer_.line_pos(); if (!CheckChar('{')) return nullptr; // get statement list ASTPtrList stmts; while (!IsTokenChar('}')) { auto stmt = ParseStatement(); if (!stmt) return nullptr; stmts.push_back(std::move(stmt)); } // eat '}' NextToken(); return MakeAST<BlockAST>(line_pos, std::move(stmts)); } ASTPtr Parser::ParseExpression() { auto line_pos = lexer_.line_pos(); std::stack<ASTPtr> oprs; std::stack<Operator> ops; // get the first expression auto expr = ParseCast(); if (!expr) return nullptr; oprs.push(std::move(expr)); // convert to postfix expression while (cur_token_ == Token::Operator) { // get operator auto op = lexer_.op_val(); if (GetOpPrec(op) < 0) break; NextToken(); // handle operator while (!ops.empty() && GetOpPrec(ops.top()) >= GetOpPrec(op)) { // create a new binary AST auto cur_op = ops.top(); ops.pop(); auto rhs = std::move(oprs.top()); oprs.pop(); auto lhs = std::move(oprs.top()); oprs.pop(); oprs.push(MakeAST<BinaryAST>(line_pos, cur_op, std::move(lhs), std::move(rhs))); } ops.push(op); // get next expression expr = ParseCast(); if (!expr) return nullptr; oprs.push(std::move(expr)); } // clear stacks while (!ops.empty()) { // create a new binary AST auto cur_op = ops.top(); ops.pop(); auto rhs = std::move(oprs.top()); oprs.pop(); auto lhs = std::move(oprs.top()); oprs.pop(); oprs.push(MakeAST<BinaryAST>(line_pos, cur_op, std::move(lhs), std::move(rhs))); } return std::move(oprs.top()); } ASTPtr Parser::ParseCast() { auto line_pos = lexer_.line_pos(); // get unary expression auto expr = ParseUnary(); if (!expr) return nullptr; // check if need to cast if (IsTokenKeyword(Keyword::As)) { NextToken(); auto type = ParseType(); if (!type) return nullptr; // create a new cast AST expr = MakeAST<CastAST>(line_pos, std::move(expr), std::move(type)); } return expr; } ASTPtr Parser::ParseUnary() { auto line_pos = lexer_.line_pos(); // check if need to get operator if (cur_token_ == Token::Operator) { // get & check unary operator auto op = lexer_.op_val(); switch (op) { case Operator::Add: case Operator::Sub: case Operator::LogicNot: case Operator::Not: case Operator::Mul: case Operator::And: break; default: return LogError("invalid unary operator"); } NextToken(); // get factor auto expr = ParseFactor(); if (!expr) return nullptr; return MakeAST<UnaryAST>(line_pos, op, std::move(expr)); } else { return ParseFactor(); } } ASTPtr Parser::ParseFactor() { if (cur_token_ == Token::Operator) { return ParseUnary(); } else if (cur_token_ == Token::Id) { auto line_pos = lexer_.line_pos(); auto id = lexer_.id_val(); // look ahead NextToken(); if (cur_token_ == Token::Id) { // just an identifier return MakeAST<IdAST>(line_pos, id); } else if (IsTokenChar('(')) { return ParseFunCall(); } else if (IsTokenChar('[')) { return ParseIndex(); } else { return ParseId(); } } else if (IsTokenChar('(')) { // bracket expression NextToken(); auto expr = ParseExpression(); if (!expr || !CheckChar(')')) return nullptr; return expr; } else { // other values return ParseValue(); } } ASTPtr Parser::ParseFunCall() { auto line_pos = lexer_.line_pos(); auto id = lexer_.id_val(); // eat '(' NextToken(); // get expression list ASTPtrList args; if (!IsTokenChar(')')) { for (;;) { auto expr = ParseExpression(); if (!expr) return nullptr; args.push_back(std::move(expr)); // eat ',' if (!IsTokenChar(',')) break; NextToken(); } } if (!CheckChar(')')) return nullptr; return MakeAST<FunCallAST>(line_pos, id, std::move(args)); } ASTPtr Parser::ParseIndex() { auto line_pos = lexer_.line_pos(); auto id = lexer_.id_val(); // eat '[' NextToken(); // get expression auto expr = ParseExpression(); if (!expr || !CheckChar(']')) return nullptr; return MakeAST<IndexAST>(line_pos, id, std::move(expr)); } ASTPtr Parser::ParseValue() { switch (cur_token_) { case Token::Num: return ParseNum(); case Token::Char: return ParseChar(); case Token::String: return ParseString(); default: { if (IsTokenChar('{')) { return ParseArray(); } else { return LogError("invalid value"); } } } } ASTPtr Parser::ParseId() { auto line_pos = lexer_.line_pos(); auto id = lexer_.id_val(); // parser has already looked ahead // so there is no 'NextToken()' return MakeAST<IdAST>(line_pos, id); } ASTPtr Parser::ParseNum() { auto line_pos = lexer_.line_pos(); auto num = lexer_.num_val(); NextToken(); return MakeAST<NumAST>(line_pos, num); } ASTPtr Parser::ParseString() { auto line_pos = lexer_.line_pos(); auto str = lexer_.str_val(); NextToken(); return MakeAST<StringAST>(line_pos, str); } ASTPtr Parser::ParseChar() { auto line_pos = lexer_.line_pos(); auto c = lexer_.char_val(); NextToken(); return MakeAST<CharAST>(line_pos, c); } ASTPtr Parser::ParseArray() { auto line_pos = lexer_.line_pos(); // eat '{' NextToken(); // get elements ASTPtrList elems; while (!IsTokenChar('}')) { // get next expression auto elem = ParseExpression(); if (!elem) return nullptr; elems.push_back(std::move(elem)); // check comma if (!IsTokenChar(',')) break; NextToken(); } // check '}' if (!CheckChar('}')) return nullptr; // check if array is empty if (elems.empty()) return LogError("array cannot be empty"); return MakeAST<ArrayAST>(line_pos, std::move(elems)); } bool Parser::CheckChar(char c) { if (!IsTokenChar(c)) { std::string msg = "expected '"; msg = msg + c + "'"; LogError(msg.c_str()); return false; } NextToken(); return true; }
13,272
C++
.cpp
482
23.556017
75
0.628489
ustb-owl/TinyMIPS
34
6
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,794
sema.cpp
ustb-owl_TinyMIPS/src/compiler/front/sema.cpp
#include "define/ast.h" using namespace tinylang::front; using namespace tinylang::define; TypePtr VarDefAST::SemaAnalyze(Analyzer &ana) { for (const auto &i : defs_) { auto type = i->SemaAnalyze(ana); if (!type) return nullptr; } return set_type(MakeVoidType()); } TypePtr LetDefAST::SemaAnalyze(Analyzer &ana) { for (const auto &i : defs_) { auto type = i->SemaAnalyze(ana); if (!type) return nullptr; } return set_type(MakeVoidType()); } TypePtr FunDefAST::SemaAnalyze(Analyzer &ana) { /* * env structure: * root * | * +-- arguments * | * +-- body */ auto guard_pos = ana.SetLinePos(line_pos()); // create argument env auto guard_env = ana.NewEnvironment(); // analyze arguments TypePtrList args; for (const auto &i : args_) { auto type = i->SemaAnalyze(ana); if (!type) return nullptr; args.push_back(type); } // analyze function definition auto type = MakeVoidType(); if (type_) { type = type_->SemaAnalyze(ana); if (!type) return nullptr; } // register return type of function auto guard_func = ana.EnterFunction(type); // analyze function declaration auto ret = ana.AnalyzeFunDef(id_, std::move(args), std::move(type)); // analyze body (if is not declaration) if (body_) { auto body = body_->SemaAnalyze(ana); if (!body) return nullptr; } // set type of function AST to function's type set_type(ana.env()->outer()->GetItem(id_)); return ret; } TypePtr FunCallAST::SemaAnalyze(Analyzer &ana) { auto guard = ana.SetLinePos(line_pos()); TypePtrList args; for (const auto &i : args_) { auto type = i->SemaAnalyze(ana); if (!type) return nullptr; args.push_back(type); } return set_type(ana.AnalyzeFunCall(id_, args)); } TypePtr IfAST::SemaAnalyze(Analyzer &ana) { auto cond = cond_->SemaAnalyze(ana); if (!cond || cond->IsVoid()) return nullptr; if (!then_->SemaAnalyze(ana)) return nullptr; if (else_then_ && !else_then_->SemaAnalyze(ana)) return nullptr; return set_type(MakeVoidType()); } TypePtr WhileAST::SemaAnalyze(Analyzer &ana) { auto cond = cond_->SemaAnalyze(ana); if (!cond || cond->IsVoid()) return nullptr; auto guard = ana.EnterWhile(); if (!body_->SemaAnalyze(ana)) return nullptr; return set_type(MakeVoidType()); } TypePtr ControlAST::SemaAnalyze(Analyzer &ana) { auto guard = ana.SetLinePos(line_pos()); TypePtr expr; if (expr_) { expr = expr_->SemaAnalyze(ana); if (!expr) return nullptr; } return set_type(ana.AnalyzeControl(type_, expr)); } TypePtr VarElemAST::SemaAnalyze(Analyzer &ana) { auto guard = ana.SetLinePos(line_pos()); TypePtr type, init; if (type_) { type = type_->SemaAnalyze(ana); if (!type) return nullptr; } if (init_) { init = init_->SemaAnalyze(ana); if (!init) return nullptr; } auto ret = ana.AnalyzeVarElem(id_, std::move(type), init); // set type of var element AST to variable's type set_type(ana.env()->GetItem(id_)); return ret; } TypePtr LetElemAST::SemaAnalyze(Analyzer &ana) { auto guard = ana.SetLinePos(line_pos()); TypePtr type; if (type_) { type = type_->SemaAnalyze(ana); if (!type) return nullptr; } auto init = init_->SemaAnalyze(ana); if (!init) return nullptr; auto ret = ana.AnalyzeLetElem(id_, std::move(type), init); // set type of let element AST to variable's type set_type(ana.env()->GetItem(id_)); return ret; } TypePtr TypeAST::SemaAnalyze(Analyzer &ana) { auto guard = ana.SetLinePos(line_pos()); return set_type(ana.AnalyzeType(type_, ptr_)); } TypePtr ArgElemAST::SemaAnalyze(Analyzer &ana) { auto guard = ana.SetLinePos(line_pos()); auto type = type_->SemaAnalyze(ana); if (!type) return nullptr; return set_type(ana.AnalyzeArgElem(id_, std::move(type))); } TypePtr BlockAST::SemaAnalyze(Analyzer &ana) { auto guard = ana.NewEnvironment(); for (const auto &i : stmts_) { if (!i->SemaAnalyze(ana)) return nullptr; } return set_type(MakeVoidType()); } TypePtr BinaryAST::SemaAnalyze(Analyzer &ana) { auto guard = ana.SetLinePos(line_pos()); auto lhs = lhs_->SemaAnalyze(ana); if (!lhs) return nullptr; auto rhs = rhs_->SemaAnalyze(ana); if (!rhs) return nullptr; return set_type(ana.AnalyzeBinary(op_, lhs, rhs)); } TypePtr CastAST::SemaAnalyze(Analyzer &ana) { auto guard = ana.SetLinePos(line_pos()); auto expr = expr_->SemaAnalyze(ana); if (!expr) return nullptr; auto type = type_->SemaAnalyze(ana); if (!type) return nullptr; return set_type(ana.AnalyzeCast(expr, type)); } TypePtr UnaryAST::SemaAnalyze(Analyzer &ana) { auto guard = ana.SetLinePos(line_pos()); auto opr = opr_->SemaAnalyze(ana); if (!opr) return nullptr; return set_type(ana.AnalyzeUnary(op_, opr)); } TypePtr IdAST::SemaAnalyze(Analyzer &ana) { auto guard = ana.SetLinePos(line_pos()); return set_type(ana.AnalyzeId(id_)); } TypePtr NumAST::SemaAnalyze(Analyzer &ana) { return set_type(ana.AnalyzeNum()); } TypePtr StringAST::SemaAnalyze(Analyzer &ana) { return set_type(ana.AnalyzeString()); } TypePtr CharAST::SemaAnalyze(Analyzer &ana) { return set_type(ana.AnalyzeChar()); } TypePtr ArrayAST::SemaAnalyze(Analyzer &ana) { auto guard = ana.SetLinePos(line_pos()); TypePtrList elems; for (const auto &i : elems_) { auto type = i->SemaAnalyze(ana); if (!type) return nullptr; elems.push_back(type); } return set_type(ana.AnalyzeArray(elems)); } TypePtr IndexAST::SemaAnalyze(Analyzer &ana) { auto guard = ana.SetLinePos(line_pos()); auto index = index_->SemaAnalyze(ana); if (!index) return nullptr; return set_type(ana.AnalyzeIndex(id_, index)); }
5,684
C++
.cpp
186
27.602151
70
0.687489
ustb-owl/TinyMIPS
34
6
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,795
lexer.cpp
ustb-owl_TinyMIPS/src/compiler/front/lexer.cpp
#include "front/lexer.h" #include <iostream> #include <cstdlib> #include <cctype> #include <cstring> #include <cstddef> #include "util/style.h" using namespace tinylang::front; namespace { enum class NumberType { Normal, Hex, Bin, }; const char *keywords[] = { "var", "let", "def", "as", "i32", "i8", "u32", "u8", "if", "else", "while", "break", "continue", "return", }; const char *operators[] = { "+", "-", "*", "/", "%", "==", "!=", "<", "<=", ">", ">=", "&&", "||", "!", "&", "|", "~", "^", "<<", ">>", "=", "+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>=", }; // get index of a string in string array template <typename T, std::size_t N> int GetIndex(const char *str, T (&str_array)[N]) { for (std::size_t i = 0; i < N; ++i) { if (!strcmp(str, str_array[i])) return i; } return -1; } bool IsOperatorHeadChar(char c) { const char op_head_chars[] = "+-*/%=!<>&|~^"; for (const auto &i : op_head_chars) { if (i == c) return true; } return false; } bool IsOperatorChar(char c) { const char op_chars[] = "=&|<>"; for (const auto &i : op_chars) { if (i == c) return true; } return false; } } // namespace Token Lexer::PrintError(const char *message) { using namespace tinylang::util; // print error message std::cerr << style("B") << "lexer"; std::cerr << " (line " << line_pos_ << "): " << style("RBr") << "error"; std::cerr << ": " << message << std::endl; // increase error count ++error_num_; return Token::Error; } int Lexer::ReadEscape() { // eat '\' char NextChar(); if (IsEOL()) return -1; switch (last_char_) { case 'a': return '\a'; case 'b': return '\b'; case 'f': return '\f'; case 'n': return '\n'; case 'r': return '\r'; case 't': return '\t'; case 'v': return '\v'; case '\\': return '\\'; case '\'': return '\''; case '"': return '"'; case '0': return '\0'; case 'x': { char hex[3] = {0}; char *end_pos; // read 2 hex digits for (int i = 0; i < 2; ++i) { NextChar(); if (IsEOL()) return -1; hex[i] = last_char_; } // convert to character auto ret = std::strtol(hex, &end_pos, 16); return *end_pos ? -1 : ret; } default: return -1; } } Token Lexer::HandleId() { // read string std::string id; do { id += last_char_; NextChar(); } while (!IsEOL() && (std::isalnum(last_char_) || last_char_ == '_')); // check if string is keyword int index = GetIndex(id.c_str(), keywords); if (index < 0) { id_val_ = id; return Token::Id; } else { key_val_ = static_cast<Keyword>(index); return Token::Keyword; } } Token Lexer::HandleNum() { std::string num; auto num_type = NumberType::Normal; // check if is hexadecimal/binary/floating-point number if (last_char_ == '0') { NextChar(); switch (last_char_) { // hexadecimal case 'x': case 'X': num_type = NumberType::Hex; break; // binary case 'b': case 'B': num_type = NumberType::Bin; break; default: { if (IsEOL() || !std::isdigit(last_char_)) { // just zero num_val_ = 0; return Token::Num; } else { return PrintError("invalid number"); } break; } } NextChar(); } // read number string while (!IsEOL() && std::isxdigit(last_char_)) { num += last_char_; NextChar(); } // convert to number char *end_pos; switch (num_type) { case NumberType::Hex: { num_val_ = std::strtoul(num.c_str(), &end_pos, 16); break; } case NumberType::Bin: { num_val_ = std::strtoul(num.c_str(), &end_pos, 2); break; } case NumberType::Normal: { num_val_ = std::strtoul(num.c_str(), &end_pos, 10); break; } default:; } // check if conversion is valid return *end_pos ? PrintError("invalid number") : Token::Num; } Token Lexer::HandleString() { std::string str; // start with quotes NextChar(); while (last_char_ != '"') { if (last_char_ == '\\') { // read escape char int ret = ReadEscape(); if (ret < 0) return PrintError("invalid escape character"); str += ret; } else { str += last_char_; } NextChar(); if (IsEOL()) return PrintError("expected '\"'"); } // eat right quotation mark NextChar(); str_val_ = str; return Token::String; } Token Lexer::HandleChar() { // start with quotes NextChar(); if (last_char_ == '\\') { // read escape char int ret = ReadEscape(); if (ret < 0) return PrintError("invalid escape character"); char_val_ = ret; } else { char_val_ = last_char_; } NextChar(); // check & eat right quotation mark if (last_char_ != '\'') return PrintError("expected \"'\""); NextChar(); return Token::Char; } Token Lexer::HandleOperator() { std::string op; do { op += last_char_; NextChar(); } while (!IsEOL() && IsOperatorChar(last_char_)); // check if operator is valid int index = GetIndex(op.c_str(), operators); if (index < 0) { return PrintError("unknown operator"); } else { op_val_ = static_cast<Operator>(index); return Token::Operator; } } Token Lexer::HandleComment() { // eat '#' NextChar(); while (!IsEOL()) NextChar(); return NextToken(); } Token Lexer::HandleEOL() { do { ++line_pos_; NextChar(); } while (IsEOL() && !in_.eof()); return NextToken(); } Token Lexer::NextToken() { // end of file if (in_.eof()) return Token::End; // skip spaces while (!IsEOL() && std::isspace(last_char_)) NextChar(); // skip comment if (last_char_ == '#') return HandleComment(); // id or keyword if (std::isalpha(last_char_)) return HandleId(); // number if (std::isdigit(last_char_)) return HandleNum(); // string if (last_char_ == '"') return HandleString(); // character if (last_char_ == '\'') return HandleChar(); // operator if (IsOperatorHeadChar(last_char_)) return HandleOperator(); // end of line if (IsEOL()) return HandleEOL(); // other characters other_val_ = last_char_; NextChar(); return Token::Other; }
6,196
C++
.cpp
252
20.710317
74
0.561371
ustb-owl/TinyMIPS
34
6
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,796
genir.cpp
ustb-owl_TinyMIPS/src/compiler/back/genir.cpp
#include "define/ast.h" using namespace tinylang::front; using namespace tinylang::define; using namespace tinylang::back; IRPtr VarDefAST::GenerateIR(IRBuilder &irb) { for (const auto &i : defs_) i->GenerateIR(irb); return nullptr; } IRPtr LetDefAST::GenerateIR(IRBuilder &irb) { for (const auto &i : defs_) i->GenerateIR(irb); return nullptr; } IRPtr FunDefAST::GenerateIR(IRBuilder &irb) { // NOTE: lhs type is type of current function auto guard_opr = irb.SetOprType(type(), nullptr); if (body_) { // function definition auto guard_func = irb.EnterFunction(id_); for (const auto &i : args_) i->GenerateIR(irb); body_->GenerateIR(irb); } else { // function declaration irb.GenerateFunDecl(id_); } return nullptr; } IRPtr FunCallAST::GenerateIR(IRBuilder &irb) { IRPtrList args; TypePtrList types; for (const auto &i : args_) { args.push_back(i->GenerateIR(irb)); types.push_back(i->type()); } // create a pseudo function type to represent 'types' auto pseudo_func = std::make_shared<FuncType>(std::move(types), nullptr); // NOTE: lhs type is type of arguments auto guard_opr = irb.SetOprType(pseudo_func, nullptr); return irb.GenerateFunCall(id_, std::move(args)); } IRPtr IfAST::GenerateIR(IRBuilder &irb) { irb.GenerateIfCond(cond_->GenerateIR(irb)); { auto guard = irb.EnterIfTrueBody(); then_->GenerateIR(irb); } { auto guard = irb.EnterIfFalseBody(); if (else_then_) else_then_->GenerateIR(irb); } return nullptr; } IRPtr WhileAST::GenerateIR(IRBuilder &irb) { { auto guard = irb.EnterWhileCond(); irb.GenerateWhileCond(cond_->GenerateIR(irb)); } { auto guard = irb.EnterWhileBody(); body_->GenerateIR(irb); } return nullptr; } IRPtr ControlAST::GenerateIR(IRBuilder &irb) { auto guard = irb.SetOprType(expr_ ? expr_->type() : nullptr, nullptr); return irb.GenerateControl(type_, expr_ ? expr_->GenerateIR(irb) : nullptr); } IRPtr VarElemAST::GenerateIR(IRBuilder &irb) { // NOTE: lhs type is variable's type, rhs type is initializer's type auto guard = irb.SetOprType(type(), init_ ? init_->type() : nullptr); return irb.GenerateVarElem(id_, init_ ? init_->GenerateIR(irb) : nullptr); } IRPtr LetElemAST::GenerateIR(IRBuilder &irb) { // NOTE: lhs type is variable's type, rhs type is initializer's type auto guard = irb.SetOprType(type(), init_->type()); return irb.GenerateLetElem(id_, init_->GenerateIR(irb)); } IRPtr TypeAST::GenerateIR(IRBuilder &irb) { return nullptr; } IRPtr ArgElemAST::GenerateIR(IRBuilder &irb) { return irb.GenerateArgElem(id_); } IRPtr BlockAST::GenerateIR(IRBuilder &irb) { for (const auto &i : stmts_) i->GenerateIR(irb); return nullptr; } IRPtr BinaryAST::GenerateIR(IRBuilder &irb) { auto guard = irb.SetOprType(lhs_->type(), rhs_->type()); if (IsOperatorAssign(op_) && lhs_->IsMemAccess()) { // generate rhs first auto value = rhs_->GenerateIR(irb); if (op_ != Operator::Assign) { auto lhs_ir = lhs_->GenerateIR(irb); value = irb.GenerateBinary(GetDeAssignedOp(op_), lhs_ir, value); } // generate memory store auto guard_store = irb.MarkStore(value); return lhs_->GenerateIR(irb); } else if (op_ == Operator::LogicAnd || op_ == Operator::LogicOr) { // generate logical operation irb.GenerateLogicLHS(op_, lhs_->GenerateIR(irb)); auto guard_logic = irb.EnterLogicRHS(op_); return irb.GenerateLogicRHS(rhs_->GenerateIR(irb)); } else { // just binary operation return irb.GenerateBinary(op_, lhs_->GenerateIR(irb), rhs_->GenerateIR(irb)); } } IRPtr CastAST::GenerateIR(IRBuilder &irb) { return expr_->GenerateIR(irb); } IRPtr UnaryAST::GenerateIR(IRBuilder &irb) { auto guard = irb.SetOprType(opr_->type(), nullptr); return irb.GenerateUnary(op_, opr_->GenerateIR(irb)); } IRPtr IdAST::GenerateIR(IRBuilder &irb) { return irb.GenerateId(id_); } IRPtr NumAST::GenerateIR(IRBuilder &irb) { return irb.GenerateNum(num_); } IRPtr StringAST::GenerateIR(IRBuilder &irb) { return irb.GenerateString(str_); } IRPtr CharAST::GenerateIR(IRBuilder &irb) { return irb.GenerateChar(c_); } IRPtr ArrayAST::GenerateIR(IRBuilder &irb) { IRPtrList elems; TypePtrList types; for (const auto &i : elems_) { elems.push_back(i->GenerateIR(irb)); types.push_back(i->type()); } // NOTE: lhs type is array's derefed type, rhs type is elements' type // TODO: a little tricky auto pseudo_func = std::make_shared<FuncType>(std::move(types), nullptr); auto guard = irb.SetOprType(type()->GetDerefedType(), std::move(pseudo_func)); return irb.GenerateArray(std::move(elems)); } IRPtr IndexAST::GenerateIR(IRBuilder &irb) { // NOTE: lhs type is type of current expression, rhs type is type of index auto guard = irb.SetOprType(type(), index_->type()); return irb.GenerateIndex(id_, index_->GenerateIR(irb)); }
5,004
C++
.cpp
151
29.589404
76
0.691575
ustb-owl/TinyMIPS
34
6
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,797
builder.cpp
ustb-owl_TinyMIPS/src/compiler/back/tac/builder.cpp
#include "back/tac/builder.h" #include <cassert> #include <cstdint> using namespace tinylang::front; using namespace tinylang::define; using namespace tinylang::back; using namespace tinylang::back::tac; using namespace tinylang::util; namespace { inline BinaryOp BinaryOperatorCast(Operator op, bool is_unsigned) { switch (op) { case Operator::Add: return BinaryOp::Add; case Operator::Sub: return BinaryOp::Sub; case Operator::Mul: { return is_unsigned ? BinaryOp::UMul : BinaryOp::Mul; } case Operator::Div: { return is_unsigned ? BinaryOp::UDiv : BinaryOp::Div; } case Operator::Mod: { return is_unsigned ? BinaryOp::UMod : BinaryOp::Mod; } case Operator::Equal: return BinaryOp::Equal; case Operator::NotEqual: return BinaryOp::NotEqual; case Operator::Less: { return is_unsigned ? BinaryOp::ULess : BinaryOp::Less; } case Operator::LessEqual: { return is_unsigned ? BinaryOp::ULessEq : BinaryOp::LessEq; } case Operator::Great: { return is_unsigned ? BinaryOp::UGreat : BinaryOp::Great; } case Operator::GreatEqual: { return is_unsigned ? BinaryOp::UGreatEq : BinaryOp::GreatEq; } case Operator::LogicAnd: return BinaryOp::LogicAnd; case Operator::LogicOr: return BinaryOp::LogicOr; case Operator::And: return BinaryOp::And; case Operator::Or: return BinaryOp::Or; case Operator::Xor: return BinaryOp::Xor; case Operator::Shl: return BinaryOp::Shl; case Operator::Shr: { return is_unsigned ? BinaryOp::LShr : BinaryOp::AShr; } default: assert(false); return BinaryOp::Add; } } inline UnaryOp UnaryOperatorCast(Operator op) { switch (op) { case Operator::Sub: return UnaryOp::Negate; case Operator::LogicNot: return UnaryOp::LogicNot; case Operator::Not: return UnaryOp::Not; case Operator::And: return UnaryOp::AddressOf; default: assert(false); return UnaryOp::Negate; } } } // namespace // definition of in-class constant const char *TACBuilder::kEntryFuncId = "__start"; void TACBuilder::NewFuncInfo(const std::string &id) { // insert function info const auto &type = opr_types_.top().lhs; auto result = funcs_.insert({id, {NewLabel(), type, {}, {}}}); assert(result.second); // update current function info cur_func_ = &result.first->second; } TACPtr TACBuilder::NewUnfilledLabel(LabelTag type) { auto label = NewLabel(); unfilled_.top()[type] = label; return label; } const TACPtr &TACBuilder::GetUnfilledLabel(LabelTag type) { auto it = unfilled_.top().find(type); assert(it != unfilled_.top().end()); return it->second; } void TACBuilder::FillLabel(LabelTag type) { AddInst(unfilled_.top()[type]); } void TACBuilder::AddJump(LabelTag type) { AddInst(std::make_shared<JumpTAC>(GetUnfilledLabel(type))); } TACPtr TACBuilder::NewPtrOffset(const TACPtr &offset, const TypePtr &offset_type, const TypePtr &ptr_type) { auto size = ptr_type->GetDerefedType()->GetSize(); return NewPtrOffset(offset, offset_type, size); } TACPtr TACBuilder::NewPtrOffset(const TACPtr &offset, const TypePtr &offset_type, std::size_t size) { auto var = NewTempVar(); auto tac = NewDataCast(offset, offset_type, kTypeSizeWordLength); AddInst(std::make_shared<BinaryTAC>( BinaryOp::Mul, tac, std::make_shared<NumberTAC>(size), var)); return var; } TACPtr TACBuilder::NewDataCast(const TACPtr &data, const TypePtr &src, const TypePtr &dest) { return NewDataCast(data, src, dest->GetSize()); } TACPtr TACBuilder::NewDataCast(const TACPtr &data, const TypePtr &src, std::size_t dest) { auto s_size = src->GetSize(); if (s_size == dest) { return data; } else if (s_size > dest) { auto var = NewTempVar(); AddInst(std::make_shared<UnaryTAC>(UnaryOp::Trunc, data, var)); return var; } else { auto var = NewTempVar(); auto op = src->IsUnsigned() ? UnaryOp::ZExt : UnaryOp::SExt; AddInst(std::make_shared<UnaryTAC>(op, data, var)); return var; } } IRPtr TACBuilder::GenerateFunDecl(const std::string &id) { // insert function info const auto &type = opr_types_.top().lhs; auto result = funcs_.insert({id, {NewLabel(), type, {}, {}}}); assert(result.second); static_cast<void>(result); return nullptr; } IRPtr TACBuilder::GenerateFunCall(const std::string &id, IRPtrList args) { // get type of arguments auto args_type = funcs_[id].type->GetArgsType(); auto types = opr_types_.top().lhs->GetArgsType(); assert(args_type && types); // generate argument setters for (std::size_t i = 0; i < args.size(); ++i) { auto tac = NewDataCast(TACCast(args[i]), (*types)[i], (*args_type)[i]); AddInst(std::make_shared<ArgSetTAC>(i, std::move(tac))); } // create function call auto dest = NewTempVar(); AddInst(std::make_shared<CallTAC>(funcs_[id].label, dest)); return MakeTAC(dest); } IRPtr TACBuilder::GenerateIfCond(const IRPtr &cond) { // create unfilled labels unfilled_.push({}); auto true_branch = NewUnfilledLabel(LabelTag::LabelTrue); auto false_branch = NewUnfilledLabel(LabelTag::LabelFalse); NewUnfilledLabel(LabelTag::LabelEndIf); // generate jump AddInst(std::make_shared<BranchTAC>(TACCast(cond), true_branch)); AddInst(std::make_shared<JumpTAC>(false_branch)); return nullptr; } IRPtr TACBuilder::GenerateWhileCond(const IRPtr &cond) { // generate jump const auto &body = GetUnfilledLabel(LabelTag::LabelBody); AddInst(std::make_shared<BranchTAC>(TACCast(cond), body)); AddJump(LabelTag::LabelEndWhile); return nullptr; } IRPtr TACBuilder::GenerateControl(Keyword type, const IRPtr &expr) { switch (type) { case Keyword::Break: { AddJump(LabelTag::LabelEndWhile); break; } case Keyword::Continue: { AddJump(LabelTag::LabelCond); break; } case Keyword::Return: { TACPtr ret_val; if (expr) { auto func_arg = cur_func_->type->GetArgsType(); auto func_ret = cur_func_->type->GetReturnType(*func_arg); const auto &expr_type = opr_types_.top().lhs; ret_val = NewDataCast(TACCast(expr), expr_type, func_ret); } AddInst(std::make_shared<ReturnTAC>(std::move(ret_val))); break; } default: assert(false); break; } return nullptr; } IRPtr TACBuilder::GenerateVarElem(const std::string &id, const IRPtr &init) { auto var = NewTempVar(); // add variable info vars_->AddItem(id, var); cur_func_->vars.insert(var); // generate initializer if (init) { const auto &cur = opr_types_.top(); auto tac = NewDataCast(TACCast(init), cur.rhs, cur.lhs); AddInst(std::make_shared<AssignTAC>(std::move(tac), var)); } return nullptr; } IRPtr TACBuilder::GenerateLetElem(const std::string &id, const IRPtr &init) { auto var = NewTempVar(); // add variable info vars_->AddItem(id, var); cur_func_->vars.insert(var); // generate initializer assert(init != nullptr); const auto &cur = opr_types_.top(); auto tac = NewDataCast(TACCast(init), cur.rhs, cur.lhs); AddInst(std::make_shared<AssignTAC>(std::move(tac), var)); return nullptr; } IRPtr TACBuilder::GenerateArgElem(const std::string &id) { auto var = NewTempVar(); // add variable info vars_->AddItem(id, var); cur_func_->args.push_back(var); // generate initializer auto arg_get = std::make_shared<ArgGetTAC>(cur_func_->args.size() - 1); AddInst(std::make_shared<AssignTAC>(std::move(arg_get), var)); return nullptr; } IRPtr TACBuilder::GenerateBinary(Operator op, const IRPtr &lhs, const IRPtr &rhs) { // get operand type const auto &lhs_type = opr_types_.top().lhs; const auto &rhs_type = opr_types_.top().rhs; if (op == Operator::Assign) { // generate assign auto tac = NewDataCast(TACCast(rhs), rhs_type, lhs_type); AddInst(std::make_shared<AssignTAC>(std::move(tac), TACCast(lhs))); return nullptr; } else if (IsOperatorAssign(op)) { // generate assign with binary operation auto var = TACCast(GenerateBinary(GetDeAssignedOp(op), lhs, rhs)); if (lhs_type->GetSize() < rhs_type->GetSize()) { // case: i8 += i32 -> i8 = i8 + i32 -> i8 = trunc i32 var = NewDataCast(var, rhs_type, lhs_type); } AddInst(std::make_shared<AssignTAC>(std::move(var), TACCast(lhs))); return nullptr; } else { // create lhs, rhs TAC auto lhs_tac = TACCast(lhs), rhs_tac = TACCast(rhs); // get unsigned flag bool is_unsigned; switch (op) { case Operator::Add: case Operator::Sub: { // check if pointer operation if (lhs_type->IsPointer() || rhs_type->IsPointer()) { is_unsigned = true; // make new operand (times derefed type's size) if (lhs_type->IsPointer()) { rhs_tac = NewPtrOffset(rhs_tac, rhs_type, lhs_type); } else if (rhs_type->IsPointer()) { lhs_tac = NewPtrOffset(lhs_tac, lhs_type, rhs_type); } break; } // fall through } case Operator::Mul: case Operator::Div: case Operator::Mod: case Operator::And: case Operator::Or: case Operator::Xor: case Operator::Shl: case Operator::Less: case Operator::LessEqual: case Operator::Great: case Operator::GreatEqual: case Operator::Equal: case Operator::NotEqual: { lhs_tac = NewDataCast(lhs_tac, lhs_type, kTypeSizeWordLength); rhs_tac = NewDataCast(rhs_tac, rhs_type, kTypeSizeWordLength); if (lhs_type->GetSize() > rhs_type->GetSize()) { is_unsigned = lhs_type->IsUnsigned(); } else if (lhs_type->GetSize() < rhs_type->GetSize()) { is_unsigned = rhs_type->IsUnsigned(); } else { is_unsigned = lhs_type->IsUnsigned() || rhs_type->IsUnsigned(); } break; } case Operator::Shr: { lhs_tac = NewDataCast(lhs_tac, lhs_type, kTypeSizeWordLength); rhs_tac = NewDataCast(rhs_tac, rhs_type, kTypeSizeWordLength); is_unsigned = lhs_type->IsUnsigned(); break; } default: assert(false); return nullptr; } // generate binary operation auto var = NewTempVar(); auto bin_op = BinaryOperatorCast(op, is_unsigned); AddInst(std::make_shared<BinaryTAC>(bin_op, std::move(lhs_tac), std::move(rhs_tac), var)); return MakeTAC(var); } } IRPtr TACBuilder::GenerateLogicLHS(Operator op, const IRPtr &lhs) { unfilled_.push({}); auto lhs_tac = TACCast(lhs); // create return value variable auto ret = NewTempVar(); logics_.push(ret); // check operator if (op == Operator::LogicAnd) { // generate unfilled label auto second = NewUnfilledLabel(LabelTag::LabelSecond); auto end = NewUnfilledLabel(LabelTag::LabelEndLogic); // generate initializer auto init = std::make_shared<NumberTAC>(0); AddInst(std::make_shared<AssignTAC>(std::move(init), ret)); // generate branch & jump AddInst(std::make_shared<BranchTAC>(lhs_tac, std::move(second))); AddJump(LabelTag::LabelEndLogic); } else { // LogicOr // generate unfilled label auto label = NewUnfilledLabel(LabelTag::LabelEndLogic); // generate initializer auto init = std::make_shared<NumberTAC>(1); AddInst(std::make_shared<AssignTAC>(std::move(init), ret)); // generate branch AddInst(std::make_shared<BranchTAC>(lhs_tac, std::move(label))); } return nullptr; } IRPtr TACBuilder::GenerateLogicRHS(const IRPtr &rhs) { // get return value variable auto ret = logics_.top(); logics_.pop(); // generate assign AddInst(std::make_shared<AssignTAC>(TACCast(rhs), ret)); return MakeTAC(ret); } IRPtr TACBuilder::GenerateUnary(Operator op, const IRPtr &opr) { // get operand and type auto tac = TACCast(opr); const auto &type = opr_types_.top().lhs; // pre-handle some case switch (op) { // skip positive operator case Operator::Add: return opr; // memory accessing case Operator::Mul: { auto deref = type->GetDerefedType(); auto size = deref->GetSize(); if (store_) { // handle store AddInst(std::make_shared<StoreTAC>(store_, tac, size)); return nullptr; } else { // just load auto dest = NewTempVar(); auto is_unsigned = deref->IsUnsigned(); AddInst(std::make_shared<LoadTAC>(tac, dest, is_unsigned, size)); return MakeTAC(dest); } } default:; } // generate unary operation auto var = NewTempVar(); auto una_op = UnaryOperatorCast(op); AddInst(std::make_shared<UnaryTAC>(una_op, tac, var)); return MakeTAC(var); } IRPtr TACBuilder::GenerateId(const std::string &id) { return MakeTAC(vars_->GetItem(id)); } IRPtr TACBuilder::GenerateNum(unsigned int num) { return MakeTAC(std::make_shared<NumberTAC>(num)); } IRPtr TACBuilder::GenerateString(const std::string &str) { // create string TACPtrList elems; for (const auto &c : str) { std::uint8_t unsigned_c = c; elems.push_back(std::make_shared<NumberTAC>(unsigned_c)); } elems.push_back(std::make_shared<NumberTAC>(0)); // add data info datas_.push_back({std::move(elems), 1}); return MakeTAC(std::make_shared<DataTAC>(datas_.size() - 1)); } IRPtr TACBuilder::GenerateChar(char c) { std::uint8_t unsigned_c = c; return MakeTAC(std::make_shared<NumberTAC>(unsigned_c)); } IRPtr TACBuilder::GenerateArray(IRPtrList elems) { // create array TACPtrList arr; std::unordered_map<std::size_t, TACPtr> inits; for (std::size_t i = 0; i < elems.size(); ++i) { auto tac = TACCast(elems[i]); if (tac->IsConst()) { arr.push_back(std::move(tac)); } else { arr.push_back(std::make_shared<NumberTAC>(0)); inits.insert({i, std::move(tac)}); } } // add data info auto size = opr_types_.top().lhs->GetSize(); datas_.push_back({arr, size}); auto data = std::make_shared<DataTAC>(datas_.size() - 1); // array initialize if (!inits.empty()) { // create base address variable auto base = NewTempVar(); AddInst(std::make_shared<AssignTAC>(data, base)); // create initializers std::size_t i = 0; for (const auto &it : inits) { // create address variable auto offset = std::make_shared<NumberTAC>(it.first * size); auto addr = NewTempVar(); AddInst(std::make_shared<BinaryTAC>(BinaryOp::Add, base, std::move(offset), addr)); // create initialization data const auto &types = opr_types_.top().rhs->GetArgsType(); assert(types); auto tac = NewDataCast(it.second, (*types)[i++], size); // create store AddInst(std::make_shared<StoreTAC>(std::move(tac), std::move(addr), size)); } } return MakeTAC(data); } IRPtr TACBuilder::GenerateIndex(const std::string &id, const IRPtr &index) { // generate offset auto base = vars_->GetItem(id); auto size = opr_types_.top().lhs->GetSize(); auto offset = NewPtrOffset(TACCast(index), opr_types_.top().rhs, size); // generate address auto addr = NewTempVar(); AddInst(std::make_shared<BinaryTAC>(BinaryOp::Add, base, offset, addr)); if (store_) { // handle store AddInst(std::make_shared<StoreTAC>(store_, addr, size)); return nullptr; } else { // just load auto dest = NewTempVar(); auto is_unsigned = opr_types_.top().lhs->IsUnsigned(); AddInst(std::make_shared<LoadTAC>(addr, dest, is_unsigned, size)); return MakeTAC(dest); } } Guard TACBuilder::EnterFunction(const std::string &id) { NewFuncInfo(id); NewVarMap(); return Guard([this]{ RestoreFuncInfo(); RestoreVarMap(); }); } Guard TACBuilder::EnterIfTrueBody() { FillLabel(LabelTag::LabelTrue); NewVarMap(); return util::Guard([this] { AddJump(LabelTag::LabelEndIf); RestoreVarMap(); }); } Guard TACBuilder::EnterIfFalseBody() { FillLabel(LabelTag::LabelFalse); NewVarMap(); return util::Guard([this] { // fill label FillLabel(LabelTag::LabelEndIf); // remove stack frame unfilled_.pop(); RestoreVarMap(); }); } Guard TACBuilder::EnterWhileCond() { // create unfilled labels unfilled_.push({}); NewUnfilledLabel(LabelTag::LabelCond); NewUnfilledLabel(LabelTag::LabelBody); NewUnfilledLabel(LabelTag::LabelEndWhile); // fill label FillLabel(LabelTag::LabelCond); return Guard(nullptr); } Guard TACBuilder::EnterWhileBody() { FillLabel(LabelTag::LabelBody); NewVarMap(); return Guard([this] { // generate jump AddJump(LabelTag::LabelCond); FillLabel(LabelTag::LabelEndWhile); // remove stack frame unfilled_.pop(); RestoreVarMap(); }); } Guard TACBuilder::EnterLogicRHS(Operator op) { if (op == Operator::LogicAnd) FillLabel(LabelTag::LabelSecond); return Guard([this] { FillLabel(LabelTag::LabelEndLogic); unfilled_.pop(); }); } Guard TACBuilder::MarkStore(const IRPtr &value) { store_ = TACCast(value); return Guard([this] { store_ = nullptr; }); } void TACBuilder::Dump(std::ostream &os) { // print global data if (!datas_.empty()) { os << "data:" << std::endl; for (std::size_t i = 0; i < datas_.size(); ++i) { const auto &info = datas_[i]; os << " " << i << '(' << (info.elem_size * 8) << "): "; os << std::endl << " "; for (std::size_t j = 0; j < info.content.size(); ++j) { if (j) os << ", "; info.content[j]->Dump(os); if (j == info.content.size() - 1) os << std::endl; } } os << std::endl; } // print functions for (const auto &f : funcs_) { const auto &id = f.first; const auto &info = f.second; // print function label os << id << ", "; info.label->Dump(os); // print IRs if (info.irs.empty()) { os << " # function declaration" << std::endl; } else { for (const auto &ir : info.irs) ir->Dump(os); } os << std::endl; } } void TACBuilder::RunOptimization(Optimizer &opt) { opt.set_funcs(&funcs_); opt.set_cur_var_id(&cur_var_id_); opt.set_entry_func(entry_func_); opt.Run(); } void TACBuilder::RunCodeGeneration(CodeGenerator &gen) { gen.set_entry(entry_func_); gen.set_funcs(&funcs_); gen.set_datas(&datas_); gen.Generate(); }
18,596
C++
.cpp
560
28.292857
76
0.649177
ustb-owl/TinyMIPS
34
6
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,798
optimizer.cpp
ustb-owl_TinyMIPS/src/compiler/back/tac/optimizer.cpp
#include "back/tac/optimizer.h" #include <iomanip> using namespace tinylang::back::tac; // definition of static member in optimizer std::list<PassInfo *> Optimizer::passes_; void Optimizer::Run() { if (!funcs_) return; // traverse all functions for (auto &&f : *funcs_) { // run passes on current function bool changed; do { changed = false; // run all passes on current function for (const auto &p : passes_) { if (opt_level_ >= p->min_opt_level()) { auto ret = p->pass()->Run(f.second); if (!changed && ret) changed = true; } } // do until nothing changed } while (changed); } } void Optimizer::ShowInfo(std::ostream &os) { // display optimization os << "current optimization level: " << opt_level_ << std::endl; os << std::endl; // show registed info os << "registed function passes:" << std::endl; if (passes_.empty()) { os << " <none>" << std::endl; return; } for (const auto &i : passes_) { os << " " << std::setw(16) << std::left << i->name(); os << "min_opt_level = " << i->min_opt_level() << std::endl; } os << std::endl; // show enabled passes int count = 0; os << "enabled function passes:" << std::endl; for (const auto &i : passes_) { if (opt_level_ >= i->min_opt_level()) { if (count % 5 == 0) os << " "; os << std::setw(16) << std::left << i->name(); if (count % 5 == 4) os << std::endl; ++count; } } if (!count) { os << " <none>" << std::endl; } else if ((count - 1) % 5 != 4) { os << std::endl; } } void Optimizer::set_cur_var_id(std::size_t *cur_var_id) { // initialize all passes for (const auto &p : passes_) { p->pass()->set_cur_var_id(cur_var_id); } } void Optimizer::set_entry_func(const FuncInfo *entry) { // initialize all passes for (const auto &p : passes_) { p->pass()->set_entry_func(entry); } }
1,940
C++
.cpp
69
24.057971
66
0.568133
ustb-owl/TinyMIPS
34
6
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,799
codegen.cpp
ustb-owl_TinyMIPS/src/compiler/back/tac/codegen.cpp
#include "back/tac/codegen.h" #include <cassert> #include <cstdint> using namespace tinylang::back::tac; /* Stack Organization of TinyLang: frame size: n * 8 +--------------------+ <- last fp | return address | 4 +--------------------+ | last frame pointer | 4 +--------------------+ | | | saved registers | n * 4 | | +--------------------+ | padding | 0/4 +--------------------+ | | | local variables | n * 4 | | +--------------------+ | | | arguments (max) | n * 4 | | +--------------------+ <- sp, fp Standard Functions of TinyLang: mul(lhs, rhs) div(lhs, rhs, is_unsigned) mod(lhs, rhs, is_unsigned) */ namespace { using Asm = TinyMIPSAsm; using Opcode = TinyMIPSOpcode; using Reg = TinyMIPSReg; const char *kIndent = "\t"; const char *kVarLabel = "$_var_"; const char *kDataLabel = "$_data_"; const char *kLabelLabel = "$_label_"; const char *kEpilogueLabel = "$_epilogue_"; const char *kMul = "_std_mul"; const char *kDiv = "_std_div"; const char *kUDiv = "_std_divu"; inline std::size_t RoundUpTo8(std::size_t num) { return ((num + 7) / 8) * 8; } } // namespace void CodeGenerator::GenerateGlobalVars() { code_ << kIndent << ".text" << std::endl; for (const auto &i : entry_->vars) { last_var_ = nullptr; i->GenerateCode(*this); // generate 'local' code_ << kIndent << ".local\t" << GetVarName(last_var_->id()); code_ << std::endl; // generate 'comm' code_ << kIndent << ".comm\t" << GetVarName(last_var_->id()); code_ << ", 4, 4" << std::endl; } code_ << std::endl; } void CodeGenerator::GenerateArrayData() { // put all array to data section code_ << kIndent << ".data" << std::endl; for (std::size_t i = 0; i < datas_->size(); ++i) { auto name = GetDataName(i); // generate 'align' code_ << kIndent << ".align\t2" << std::endl; // generate 'type' code_ << kIndent << ".type\t" << name << ", @object" << std::endl; // generate size info auto arr_size = (*datas_)[i].elem_size * (*datas_)[i].content.size(); code_ << kIndent << ".size\t" << name << ", " << arr_size << std::endl; // generate data label code_ << name << ':' << std::endl; // generate content for (const auto &tac : (*datas_)[i].content) { code_ << kIndent; // generate prefix if ((*datas_)[i].elem_size == 1) { code_ << ".byte\t"; } else if ((*datas_)[i].elem_size == 4) { code_ << ".word\t"; } else { assert(false); } // generate actual data last_data_ = nullptr; last_num_ = nullptr; tac->GenerateCode(*this); if (last_data_) { code_ << GetDataName(last_data_->id()); } else if (last_num_) { code_ << last_num_->num(); } else { assert(false); } code_ << std::endl; } } code_ << std::endl; } void CodeGenerator::GenerateFunc(const std::string &name, const FuncInfo &info) { // generate head code_ << kIndent << ".align\t2" << std::endl; code_ << kIndent << ".globl\t" << name << std::endl; code_ << kIndent << ".ent\t" << name << std::endl; code_ << kIndent << ".type\t" << name << ", @function" << std::endl; // generate labels code_ << name << ':' << std::endl; last_label_ = nullptr; info.label->GenerateCode(*this); code_ << GetLabelName(last_label_->id()) << ':' << std::endl; // generator info GenerateHeaderInfo(); // reset state asm_gen_.Reset(); // generate prologue GeneratePrologue(info); // generate body for (const auto &i : info.irs) { last_label_ = nullptr; i->GenerateCode(*this); // generate labels if (last_label_) { asm_gen_.PushLabel(GetLabelName(last_label_->id())); } } // generate epilogue GenerateEpilogue(); // put assembly code to stream asm_gen_.Dump(code_, kIndent); // generate end code_ << kIndent << ".end\t" << name << std::endl; code_ << std::endl; } void CodeGenerator::GenerateHeaderInfo() { // generate frame info auto frame_size = GetFrameSize(); code_ << kIndent << ".frame\t$fp, " << frame_size << ", $ra" << std::endl; // generate mask info std::uint32_t mask = 0; for (const auto &i : var_alloc_.saved_reg()) { mask |= 1 << static_cast<int>(i); } code_ << kIndent << ".mask\t0x"; code_ << std::hex << mask << ", -4" << std::dec << std::endl; } void CodeGenerator::GeneratePrologue(const FuncInfo &info) { auto frame_size = GetFrameSize(); // initialize stack pointer asm_gen_.PushAsm(Opcode::ADDIU, Reg::SP, Reg::SP, -frame_size); // store all saved registers std::size_t offset = 1; for (const auto &i : var_alloc_.saved_reg()) { asm_gen_.PushAsm(Opcode::SW, i, Reg::SP, frame_size - 4 * offset++); } // set current frame pointer asm_gen_.PushMove(Reg::FP, Reg::SP); // store arguments for (std::size_t i = 0; i < 4 && i < info.args.size(); ++i) { auto arg_reg = static_cast<Reg>(static_cast<int>(Reg::A0) + i); asm_gen_.PushAsm(Opcode::SW, arg_reg, Reg::FP, frame_size + i * 4); } } void CodeGenerator::GenerateEpilogue() { auto frame_size = GetFrameSize(); // generate label asm_gen_.PushLabel(NextEpilogueLabel()); // restore stack pointer asm_gen_.PushMove(Reg::SP, Reg::FP); // restore all saved registers std::size_t offset = 1; for (const auto &i : var_alloc_.saved_reg()) { asm_gen_.PushAsm(Opcode::LW, i, Reg::SP, frame_size - 4 * offset++); } // release current stack frame asm_gen_.PushAsm(Opcode::ADDIU, Reg::SP, Reg::SP, frame_size); // return to last function asm_gen_.PushJump(Reg::RA); } std::string CodeGenerator::GetVarName(std::size_t id) { return kVarLabel + std::to_string(id); } std::string CodeGenerator::GetDataName(std::size_t id) { return kDataLabel + std::to_string(id); } std::string CodeGenerator::GetLabelName(std::size_t id) { return kLabelLabel + std::to_string(id); } std::string CodeGenerator::NextEpilogueLabel() { return kEpilogueLabel + std::to_string(epilogue_id_++); } std::string CodeGenerator::GetEpilogueLabel() { return kEpilogueLabel + std::to_string(epilogue_id_); } std::size_t CodeGenerator::GetFrameSize() { auto save_size = var_alloc_.save_area_size(); auto local_size = var_alloc_.local_area_size(); auto args_size = var_alloc_.arg_area_size(); return RoundUpTo8(save_size + local_size + args_size); } Reg CodeGenerator::GetValue(const TACPtr &tac) { // get pointer of value last_var_ = nullptr; last_data_ = nullptr; last_arg_get_ = nullptr; last_num_ = nullptr; tac->GenerateCode(*this); assert(last_var_ || last_data_ || last_arg_get_ || last_num_); // handle each case if (last_var_) { if (entry_->vars.find(tac) != entry_->vars.end()) { // load global variable auto name = GetVarName(last_var_->id()); asm_gen_.PushAsm(Opcode::LUI, Reg::V1, "%hi(" + name + ")"); asm_gen_.PushAsm(Opcode::LW, Reg::V0, Reg::V1, "%lo(" + name + ")"); return Reg::V0; } else { // get position of variable auto pos = var_alloc_.GetPosition(tac); if (auto slot = std::get_if<std::size_t>(&pos)) { // load from local area auto offset = var_alloc_.arg_area_size() + *slot * 4; asm_gen_.PushAsm(Opcode::LW, Reg::V0, Reg::FP, offset); return Reg::V0; } else { // just return return *std::get_if<Reg>(&pos); } } } else if (last_data_) { // load address of label asm_gen_.PushLoadImm(Reg::V0, GetDataName(last_data_->id())); return Reg::V0; } else if (last_arg_get_) { auto offset = GetFrameSize() + last_arg_get_->pos() * 4; // load argument from argument area asm_gen_.PushAsm(Opcode::LW, Reg::V0, Reg::FP, offset); return Reg::V0; } else { // last_num_ // store number to temporary register asm_gen_.PushLoadImm(Reg::V0, last_num_->num()); return Reg::V0; } } void CodeGenerator::SetValue(const TACPtr &tac, Reg value) { // get pointer of value last_var_ = nullptr; tac->GenerateCode(*this); assert(last_var_); // handle each case if (entry_->vars.find(tac) != entry_->vars.end()) { // store to global variable auto name = GetVarName(last_var_->id()); asm_gen_.PushAsm(Opcode::LUI, Reg::V1, "%hi(" + name + ")"); asm_gen_.PushAsm(Opcode::SW, value, Reg::V1, "%lo(" + name + ")"); } else { // get position of variable auto pos = var_alloc_.GetPosition(tac); if (auto slot = std::get_if<std::size_t>(&pos)) { // store to local area auto offset = var_alloc_.arg_area_size() + *slot * 4; asm_gen_.PushAsm(Opcode::SW, value, Reg::FP, offset); } else { // just move auto dest = *std::get_if<Reg>(&pos); asm_gen_.PushMove(dest, value); } } } CodeGenerator::CodeGenerator() { entry_ = nullptr; funcs_ = nullptr; datas_ = nullptr; epilogue_id_ = 0; } void CodeGenerator::GenerateOn(BinaryTAC &tac) { // get lhs & rhs auto lhs = GetValue(tac.lhs()); if (lhs == Reg::V0) { asm_gen_.PushMove(Reg::V1, lhs); lhs = Reg::V1; } auto rhs = GetValue(tac.rhs()); // generate operation switch (tac.op()) { case BinaryOp::Add: { asm_gen_.PushAsm(Opcode::ADDU, Reg::V0, lhs, rhs); break; } case BinaryOp::Sub: { asm_gen_.PushAsm(Opcode::SUBU, Reg::V0, lhs, rhs); break; } case BinaryOp::Mul: case BinaryOp::UMul: { asm_gen_.PushMove(Reg::A0, lhs); asm_gen_.PushMove(Reg::A1, rhs); asm_gen_.PushJump(kMul); break; } case BinaryOp::Div: { asm_gen_.PushMove(Reg::A0, lhs); asm_gen_.PushMove(Reg::A1, rhs); asm_gen_.PushJump(kDiv); break; } case BinaryOp::UDiv: { asm_gen_.PushMove(Reg::A0, lhs); asm_gen_.PushMove(Reg::A1, rhs); asm_gen_.PushJump(kUDiv); break; } case BinaryOp::Mod: { asm_gen_.PushMove(Reg::A0, lhs); asm_gen_.PushMove(Reg::A1, rhs); asm_gen_.PushJump(kDiv); asm_gen_.PushMove(Reg::V0, Reg::V1); break; } case BinaryOp::UMod: { asm_gen_.PushMove(Reg::A0, lhs); asm_gen_.PushMove(Reg::A1, rhs); asm_gen_.PushJump(kUDiv); asm_gen_.PushMove(Reg::V0, Reg::V1); break; } case BinaryOp::Equal: { asm_gen_.PushAsm(Opcode::XOR, Reg::V0, lhs, rhs); asm_gen_.PushLoadImm(Reg::V1, 1); asm_gen_.PushAsm(Opcode::SLTU, Reg::V0, Reg::V0, Reg::V1); break; } case BinaryOp::NotEqual: { asm_gen_.PushAsm(Opcode::XOR, Reg::V0, lhs, rhs); asm_gen_.PushAsm(Opcode::SLTU, Reg::V0, Reg::Zero, Reg::V0); break; } case BinaryOp::Less: { asm_gen_.PushAsm(Opcode::SLT, Reg::V0, lhs, rhs); break; } case BinaryOp::ULess: { asm_gen_.PushAsm(Opcode::SLTU, Reg::V0, lhs, rhs); break; } case BinaryOp::LessEq: { asm_gen_.PushAsm(Opcode::SLT, Reg::V0, rhs, lhs); asm_gen_.PushLoadImm(Reg::V1, 1); asm_gen_.PushAsm(Opcode::XOR, Reg::V0, Reg::V0, Reg::V1); break; } case BinaryOp::ULessEq: { asm_gen_.PushAsm(Opcode::SLTU, Reg::V0, rhs, lhs); asm_gen_.PushLoadImm(Reg::V1, 1); asm_gen_.PushAsm(Opcode::XOR, Reg::V0, Reg::V0, Reg::V1); break; } case BinaryOp::Great: { asm_gen_.PushAsm(Opcode::SLT, Reg::V0, rhs, lhs); break; } case BinaryOp::UGreat: { asm_gen_.PushAsm(Opcode::SLTU, Reg::V0, rhs, lhs); break; } case BinaryOp::GreatEq: { asm_gen_.PushAsm(Opcode::SLT, Reg::V0, lhs, rhs); asm_gen_.PushLoadImm(Reg::V1, 1); asm_gen_.PushAsm(Opcode::XOR, Reg::V0, Reg::V0, Reg::V1); break; } case BinaryOp::UGreatEq: { asm_gen_.PushAsm(Opcode::SLTU, Reg::V0, lhs, rhs); asm_gen_.PushLoadImm(Reg::V1, 1); asm_gen_.PushAsm(Opcode::XOR, Reg::V0, Reg::V0, Reg::V1); break; } case BinaryOp::And: { asm_gen_.PushAsm(Opcode::AND, Reg::V0, lhs, rhs); break; } case BinaryOp::Or: { asm_gen_.PushAsm(Opcode::OR, Reg::V0, lhs, rhs); break; } case BinaryOp::Xor: { asm_gen_.PushAsm(Opcode::XOR, Reg::V0, lhs, rhs); break; } case BinaryOp::Shl: { asm_gen_.PushAsm(Opcode::SLLV, Reg::V0, lhs, rhs); break; } case BinaryOp::AShr: { asm_gen_.PushAsm(Opcode::SRAV, Reg::V0, lhs, rhs); break; } case BinaryOp::LShr: { asm_gen_.PushAsm(Opcode::SRLV, Reg::V0, lhs, rhs); break; } default: assert(false); } // store to dest SetValue(tac.dest(), Reg::V0); } void CodeGenerator::GenerateOn(UnaryTAC &tac) { if (tac.op() == UnaryOp::AddressOf) { // get variable ref last_var_ = nullptr; tac.opr()->GenerateCode(*this); assert(last_var_); // get address of variable if (entry_->vars.find(tac.opr()) != entry_->vars.end()) { // global variable auto name = GetVarName(last_var_->id()); asm_gen_.PushLoadImm(Reg::V0, name); } else { // get slot position of variable auto pos = var_alloc_.GetPosition(tac.opr()); auto slot = std::get_if<std::size_t>(&pos); assert(slot); // get frame offset auto offset = var_alloc_.arg_area_size() + *slot * 4; asm_gen_.PushLoadImm(Reg::V0, offset); } } else { // get operand auto opr = GetValue(tac.opr()); // generate operation switch (tac.op()) { case UnaryOp::Negate: { asm_gen_.PushAsm(Opcode::SUBU, Reg::V0, Reg::Zero, opr); break; } case UnaryOp::LogicNot: { asm_gen_.PushLoadImm(Reg::V1, 1); asm_gen_.PushAsm(Opcode::SLTU, Reg::V0, opr, Reg::V1); break; } case UnaryOp::Not: { asm_gen_.PushLoadImm(Reg::V1, -1); asm_gen_.PushAsm(Opcode::XOR, Reg::V0, opr, Reg::V1); break; } case UnaryOp::SExt: { asm_gen_.PushAsm(Opcode::SLL, Reg::V0, opr, 24); asm_gen_.PushLoadImm(Reg::V1, 24); asm_gen_.PushAsm(Opcode::SRAV, Reg::V0, Reg::V0, Reg::V1); break; } case UnaryOp::ZExt: case UnaryOp::Trunc: { asm_gen_.PushLoadImm(Reg::V1, 0xff); asm_gen_.PushAsm(Opcode::AND, Reg::V0, opr, Reg::V1); break; } default: assert(false); } } // store to dest SetValue(tac.dest(), Reg::V0); } void CodeGenerator::GenerateOn(LoadTAC &tac) { // get address auto addr = GetValue(tac.addr()); // generate load if (tac.size() == 1) { auto op = tac.is_unsigned() ? Opcode::LBU : Opcode::LB; asm_gen_.PushAsm(op, Reg::V0, addr, 0); } else if (tac.size() == 4) { asm_gen_.PushAsm(Opcode::LW, Reg::V0, addr, 0); } else { assert(false); } // store to dest SetValue(tac.dest(), Reg::V0); } void CodeGenerator::GenerateOn(StoreTAC &tac) { // get address auto addr = GetValue(tac.addr()); asm_gen_.PushMove(Reg::A0, addr); // get value auto value = GetValue(tac.value()); // generate store if (tac.size() == 1) { asm_gen_.PushAsm(Opcode::SB, value, Reg::A0, 0); } else if (tac.size() == 4) { asm_gen_.PushAsm(Opcode::SW, value, Reg::A0, 0); } else { assert(false); } } void CodeGenerator::GenerateOn(ArgSetTAC &tac) { // get value auto value = GetValue(tac.value()); // set argument if (tac.pos() < 4) { // just move auto dest = static_cast<Reg>(static_cast<int>(Reg::A0) + tac.pos()); asm_gen_.PushMove(dest, value); } else { // store to stack auto offset = GetFrameSize() + tac.pos() * 4; asm_gen_.PushAsm(Opcode::SW, value, Reg::FP, offset); } } void CodeGenerator::GenerateOn(JumpTAC &tac) { // generate label last_label_ = nullptr; tac.dest()->GenerateCode(*this); // generate jump asm_gen_.PushJump(GetLabelName(last_label_->id())); last_label_ = nullptr; } void CodeGenerator::GenerateOn(BranchTAC &tac) { // get condition auto cond = GetValue(tac.cond()); // generate label last_label_ = nullptr; tac.dest()->GenerateCode(*this); // generate branch asm_gen_.PushBranch(cond, GetLabelName(last_label_->id())); last_label_ = nullptr; } void CodeGenerator::GenerateOn(CallTAC &tac) { // check if label is an external function auto it = decls_.find(tac.func()); if (it != decls_.end()) { // calling an external function asm_gen_.PushJump(it->second); } else { // generate label last_label_ = nullptr; tac.func()->GenerateCode(*this); // generate function call asm_gen_.PushJump(GetLabelName(last_label_->id())); last_label_ = nullptr; } // set return value SetValue(tac.dest(), Reg::V0); } void CodeGenerator::GenerateOn(ReturnTAC &tac) { // generate return value if (tac.value()) { auto value = GetValue(tac.value()); asm_gen_.PushMove(Reg::V0, value); } // generate return asm_gen_.PushJump(GetEpilogueLabel()); } void CodeGenerator::GenerateOn(AssignTAC &tac) { auto value = GetValue(tac.value()); SetValue(tac.var(), value); } void CodeGenerator::GenerateOn(VarRefTAC &tac) { last_var_ = &tac; } void CodeGenerator::GenerateOn(DataTAC &tac) { last_data_ = &tac; } void CodeGenerator::GenerateOn(LabelTAC &tac) { last_label_ = &tac; } void CodeGenerator::GenerateOn(ArgGetTAC &tac) { last_arg_get_ = &tac; } void CodeGenerator::GenerateOn(NumberTAC &tac) { last_num_ = &tac; } void CodeGenerator::Generate() { code_ << kIndent << ".set\tnoreorder" << std::endl; code_ << kIndent << ".abicalls" << std::endl; // generate global variables & arrays GenerateGlobalVars(); GenerateArrayData(); // store declaration info for (const auto &i : *funcs_) { if (i.second.irs.empty()) { decls_.insert({i.second.label, i.first}); } } // generate each function code_ << kIndent << ".text" << std::endl; for (auto &&i : *funcs_) { if (!i.second.irs.empty()) { // do variable allocation var_alloc_.Run(i.second); // generate current function GenerateFunc(i.first, i.second); } } } void CodeGenerator::Dump(std::ostream &os) { os << code_.str(); }
18,277
C++
.cpp
606
25.674917
76
0.590754
ustb-owl/TinyMIPS
34
6
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,800
tac.cpp
ustb-owl_TinyMIPS/src/compiler/back/tac/ir/tac.cpp
#include "back/tac/ir/tac.h" #include "back/tac/optimizer.h" #include "back/tac/codegen.h" using namespace tinylang::back::tac; namespace { const char *kIndent = " "; const char *bin_ops[] = { "add", "sub", "mul", "umul", "div", "udiv", "mod", "umod", "eql", "neq", "lt", "ult", "le", "ule", "gt", "ugt", "ge", "uge", "land", "lor", "and", "or", "xor", "shl", "ashr", "lshr", }; const char *una_ops[] = { "neg", "lnot", "not", "addr", "sext", "zext", "trunc", }; bool in_expr = false; inline void PrintTypeInfo(std::ostream &os, bool is_unsigned, std::size_t size) { os << '(' << (is_unsigned ? 'u' : 'i') << (size * 8) << ')'; } } // namespace void BinaryTAC::Dump(std::ostream &os) { os << kIndent; dest_->Dump(os); os << " = " << bin_ops[static_cast<int>(op_)]; os << ' '; lhs_->Dump(os); os << ", "; rhs_->Dump(os); os << std::endl; } void UnaryTAC::Dump(std::ostream &os) { os << kIndent; dest_->Dump(os); os << " = " << una_ops[static_cast<int>(op_)]; os << ' '; opr_->Dump(os); os << std::endl; } void LoadTAC::Dump(std::ostream &os) { os << kIndent; dest_->Dump(os); os << " = load"; PrintTypeInfo(os, is_unsigned_, size_); os << ' '; addr_->Dump(os); os << std::endl; } void StoreTAC::Dump(std::ostream &os) { os << kIndent; os << "store"; PrintTypeInfo(os, true, size_); os << ' '; addr_->Dump(os); os << ", "; value_->Dump(os); os << std::endl; } void ArgSetTAC::Dump(std::ostream &os) { os << kIndent; os << "set " << pos_; os << ", "; value_->Dump(os); os << std::endl; } void JumpTAC::Dump(std::ostream &os) { in_expr = true; os << kIndent; os << "jump "; dest_->Dump(os); os << std::endl; in_expr = false; } void BranchTAC::Dump(std::ostream &os) { in_expr = true; os << kIndent; os << "branch "; cond_->Dump(os); os << ", "; dest_->Dump(os); os << std::endl; in_expr = false; } void CallTAC::Dump(std::ostream &os) { in_expr = true; os << kIndent; dest_->Dump(os); os << " = call "; func_->Dump(os); os << std::endl; in_expr = false; } void ReturnTAC::Dump(std::ostream &os) { os << kIndent; os << "ret"; if (value_) { os << ' '; value_->Dump(os); } os << std::endl; } void AssignTAC::Dump(std::ostream &os) { os << kIndent; var_->Dump(os); os << " = "; value_->Dump(os); os << std::endl; } void VarRefTAC::Dump(std::ostream &os) { os << '$' << id_; } void DataTAC::Dump(std::ostream &os) { os << "data " << id_; } void LabelTAC::Dump(std::ostream &os) { if (!in_expr) { os << "label_" << id_ << ':' << std::endl; } else { os << "label_" << id_; } } void ArgGetTAC::Dump(std::ostream &os) { os << "get " << pos_; } void NumberTAC::Dump(std::ostream &os) { os << num_; } void BinaryTAC::RunPass(PassBase &pass) { pass.RunOn(*this); } void UnaryTAC::RunPass(PassBase &pass) { pass.RunOn(*this); } void LoadTAC::RunPass(PassBase &pass) { pass.RunOn(*this); } void StoreTAC::RunPass(PassBase &pass) { pass.RunOn(*this); } void ArgSetTAC::RunPass(PassBase &pass) { pass.RunOn(*this); } void JumpTAC::RunPass(PassBase &pass) { pass.RunOn(*this); } void BranchTAC::RunPass(PassBase &pass) { pass.RunOn(*this); } void CallTAC::RunPass(PassBase &pass) { pass.RunOn(*this); } void ReturnTAC::RunPass(PassBase &pass) { pass.RunOn(*this); } void AssignTAC::RunPass(PassBase &pass) { pass.RunOn(*this); } void VarRefTAC::RunPass(PassBase &pass) { pass.RunOn(*this); } void DataTAC::RunPass(PassBase &pass) { pass.RunOn(*this); } void LabelTAC::RunPass(PassBase &pass) { pass.RunOn(*this); } void ArgGetTAC::RunPass(PassBase &pass) { pass.RunOn(*this); } void NumberTAC::RunPass(PassBase &pass) { pass.RunOn(*this); } void BinaryTAC::GenerateCode(CodeGenerator &gen) { gen.GenerateOn(*this); } void UnaryTAC::GenerateCode(CodeGenerator &gen) { gen.GenerateOn(*this); } void LoadTAC::GenerateCode(CodeGenerator &gen) { gen.GenerateOn(*this); } void StoreTAC::GenerateCode(CodeGenerator &gen) { gen.GenerateOn(*this); } void ArgSetTAC::GenerateCode(CodeGenerator &gen) { gen.GenerateOn(*this); } void JumpTAC::GenerateCode(CodeGenerator &gen) { gen.GenerateOn(*this); } void BranchTAC::GenerateCode(CodeGenerator &gen) { gen.GenerateOn(*this); } void CallTAC::GenerateCode(CodeGenerator &gen) { gen.GenerateOn(*this); } void ReturnTAC::GenerateCode(CodeGenerator &gen) { gen.GenerateOn(*this); } void AssignTAC::GenerateCode(CodeGenerator &gen) { gen.GenerateOn(*this); } void VarRefTAC::GenerateCode(CodeGenerator &gen) { gen.GenerateOn(*this); } void DataTAC::GenerateCode(CodeGenerator &gen) { gen.GenerateOn(*this); } void LabelTAC::GenerateCode(CodeGenerator &gen) { gen.GenerateOn(*this); } void ArgGetTAC::GenerateCode(CodeGenerator &gen) { gen.GenerateOn(*this); } void NumberTAC::GenerateCode(CodeGenerator &gen) { gen.GenerateOn(*this); }
4,881
C++
.cpp
160
28.06875
75
0.631097
ustb-owl/TinyMIPS
34
6
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,801
tmgen.cpp
ustb-owl_TinyMIPS/src/compiler/back/tac/codegen/tmgen.cpp
#include "back/tac/codegen/tmgen.h" #include <algorithm> using namespace tinylang::back::tac; namespace { using Asm = TinyMIPSAsm; using Opcode = TinyMIPSOpcode; using Reg = TinyMIPSReg; const char *opcode_str[] = { "addu", "addiu", "subu", "slt", "sltu", "and", "lui", "or", "xor", "sll", "sllv", "srav", "srlv", "beq", "bne", "jal", "jalr", "lb", "lbu", "lw", "sb", "sw", "nop", "", }; const char *reg_str[] = { "$0", "$at", "$v0", "$v1", "$a0", "$a1", "$a2", "$a3", "$t0", "$t1", "$t2", "$t3", "$t4", "$t5", "$t6", "$t7", "$s0", "$s1", "$s2", "$s3", "$s4", "$s5", "$s6", "$s7", "$t8", "$t9", "$k0", "$k1", "$gp", "$sp", "$fp", "$ra", }; // check if instruction is pseudo instruction inline bool IsPseudo(const Asm &tm) { return static_cast<int>(tm.opcode) >= static_cast<int>(Opcode::NOP); } // check if instruction is just a label inline bool IsLabel(const Asm &tm) { return tm.opcode == Opcode::LABEL; } // check if instruction is jump or branch inline bool IsJump(const Asm &tm) { const auto &op = tm.opcode; return op == Opcode::BEQ || op == Opcode::BNE || op == Opcode::JAL || op == Opcode::JALR; } // check if instruction is store inline bool IsStore(const Asm &tm) { return tm.opcode == Opcode::SB || tm.opcode == Opcode::SW; } // check if current instruction has dest inline bool HasDest(const Asm &tm) { return !IsPseudo(tm) && !IsJump(tm) && !IsStore(tm); } // check if two registers are related inline bool IsRegRelated(Reg r1, Reg r2) { return r1 != Reg::Zero && r1 == r2; } // check if registers and asm are related inline bool IsRelated(const Asm &tm, Reg op, Reg dest) { switch (tm.opcode) { case Opcode::ADDU: case Opcode::SUBU: case Opcode::SLT: case Opcode::SLTU: case Opcode::AND: case Opcode::OR: case Opcode::XOR: case Opcode::SLLV: case Opcode::SRAV: case Opcode::SRLV: { return IsRegRelated(tm.dest, op) || IsRegRelated(dest, tm.opr1) || IsRegRelated(dest, tm.opr2); } case Opcode::ADDIU: case Opcode::SLL: { return IsRegRelated(tm.dest, op) || IsRegRelated(dest, tm.opr1); } case Opcode::BEQ: case Opcode::BNE: { return IsRegRelated(dest, tm.opr1) || IsRegRelated(dest, tm.opr2); } case Opcode::LUI: { return IsRegRelated(tm.dest, op); } case Opcode::JAL: { return IsRegRelated(Reg::RA, op); } case Opcode::JALR: { return IsRegRelated(Reg::RA, op) || IsRegRelated(dest, tm.dest); } case Opcode::LB: case Opcode::LBU: case Opcode::LW: { return IsRegRelated(tm.dest, op) || IsRegRelated(dest, tm.opr1); } case Opcode::SB: case Opcode::SW: { return IsRegRelated(dest, tm.dest) || IsRegRelated(dest, tm.opr1); } default:; } return false; } // check if registers and asm are related inline bool IsRelated(const Asm &tm, Reg op) { return IsRelated(tm, op, Reg::Zero); } // check if instruction and branch are related inline bool IsBranchRelated(const Asm &tm, const Asm &branch) { return IsRelated(tm, branch.dest) || IsRelated(tm, branch.opr1); } // dump content of asm to stream void DumpAsm(std::ostream &os, const Asm &tm) { os << opcode_str[static_cast<int>(tm.opcode)]; if (!IsPseudo(tm)) os << '\t'; switch (tm.opcode) { case Opcode::ADDU: case Opcode::SUBU: case Opcode::SLT: case Opcode::SLTU: case Opcode::AND: case Opcode::OR: case Opcode::XOR: case Opcode::SLLV: case Opcode::SRAV: case Opcode::SRLV: { os << reg_str[static_cast<int>(tm.dest)] << ", "; os << reg_str[static_cast<int>(tm.opr1)] << ", "; os << reg_str[static_cast<int>(tm.opr2)]; break; } case Opcode::ADDIU: case Opcode::BEQ: case Opcode::BNE: case Opcode::SLL: { os << reg_str[static_cast<int>(tm.dest)] << ", "; os << reg_str[static_cast<int>(tm.opr1)] << ", "; if (!tm.imm_str.empty()) { os << tm.imm_str; } else { os << tm.imm; } break; } case Opcode::LUI: { os << reg_str[static_cast<int>(tm.dest)] << ", "; if (!tm.imm_str.empty()) { os << tm.imm_str; } else { os << tm.imm; } break; } case Opcode::JAL: { if (!tm.imm_str.empty()) { os << tm.imm_str; } else { os << tm.index; } break; } case Opcode::JALR: { os << "$0, " << reg_str[static_cast<int>(tm.dest)]; break; } case Opcode::LB: case Opcode::LBU: case Opcode::LW: case Opcode::SB: case Opcode::SW: { os << reg_str[static_cast<int>(tm.dest)] << ", "; if (!tm.imm_str.empty()) { os << tm.imm_str; } else { os << tm.imm; } os << '(' << reg_str[static_cast<int>(tm.opr1)] << ')'; break; } case Opcode::LABEL: { os << tm.imm_str << ':'; break; } default:; } } } // namespace void TinyMIPSAsmGen::ReorderJump() { // check if is already reordered if (is_reordered_) return; is_reordered_ = true; // record position and last elements std::size_t pos = 0; auto last = asms_.end(), last2 = asms_.end(); // traverse all instructions for (auto it = asms_.begin(); it != asms_.end(); ++it, ++pos) { switch (it->opcode) { case Opcode::BEQ: case Opcode::BNE: { // check if is related if (!pos || (pos && (IsBranchRelated(*last, *it) || IsLabel(*last))) || (pos > 1 && IsJump(*last2))) { // insert NOP after branch last = it; it = asms_.insert(++it, {Opcode::NOP}); } else { // just swap std::swap(*last, *it); } break; } case Opcode::JAL: { // check if is related if (!pos || (pos && IsLabel(*last)) || (pos > 1 && IsJump(*last2))) { // insert NOP after jump last = it; it = asms_.insert(++it, {Opcode::NOP}); } else { // just swap std::swap(*last, *it); } break; } case Opcode::JALR: { if (!pos || (pos && (IsRelated(*last, it->dest, Reg::RA) || IsLabel(*last))) || (pos > 1 && IsJump(*last2))) { // insert NOP after jump last = it; it = asms_.insert(++it, {Opcode::NOP}); } else { // just swap std::swap(*last, *it); } break; } default:; } // update iterators last2 = last; last = it; } } void TinyMIPSAsmGen::PushNop() { PushAsm(Opcode::NOP); } void TinyMIPSAsmGen::PushLabel(std::string_view label) { // remove redundant jumps while (asms_.back().opcode == Opcode::JAL && asms_.back().imm_str == label) { asms_.pop_back(); } PushAsm(Opcode::LABEL, label); } void TinyMIPSAsmGen::PushMove(Reg dest, Reg src) { // do not generate redundant move if (dest == src) return; // try to modify the dest of last instruction if (HasDest(asms_.back()) && asms_.back().dest == src) { asms_.back().dest = dest; } else { PushAsm(Opcode::OR, dest, src, Reg::Zero); } } void TinyMIPSAsmGen::PushLoadImm(Reg dest, std::uint32_t imm) { if ((!(imm & 0xffff0000) && !(imm & 0x8000)) || ((imm & 0xffff0000) == 0xffff0000 && (imm & 0x8000))) { PushAsm(Opcode::ADDIU, dest, Reg::Zero, imm); } else if (!(imm & 0x8000)) { PushAsm(Opcode::LUI, dest, imm >> 16); PushAsm(Opcode::ADDIU, dest, dest, imm & 0xffff); } else { PushAsm(Opcode::LUI, dest, (imm >> 16) + 1); PushAsm(Opcode::ADDIU, dest, dest, imm & 0xffff); } } void TinyMIPSAsmGen::PushLoadImm(Reg dest, std::string_view imm_str) { using namespace std::string_literals; PushAsm(Opcode::LUI, dest, "%hi("s + imm_str.data() + ")"); PushAsm(Opcode::ADDIU, dest, dest, "%lo("s + imm_str.data() + ")"); } void TinyMIPSAsmGen::PushBranch(Reg cond, std::string_view label) { PushAsm(Opcode::BNE, cond, Reg::Zero, label); } void TinyMIPSAsmGen::PushJump(std::string_view label) { PushAsm(Opcode::JAL, label); } void TinyMIPSAsmGen::PushJump(Reg dest) { PushAsm(Opcode::JALR, dest); } void TinyMIPSAsmGen::Dump(std::ostream &os, std::string_view indent) { ReorderJump(); for (const auto &i : asms_) { if (i.opcode != Opcode::LABEL) os << indent; DumpAsm(os, i); os << std::endl; } }
8,390
C++
.cpp
282
24.741135
72
0.573568
ustb-owl/TinyMIPS
34
6
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,802
varalloc.cpp
ustb-owl_TinyMIPS/src/compiler/back/tac/codegen/varalloc.cpp
#include "back/tac/codegen/varalloc.h" using namespace tinylang::back::tac; namespace { using VarPos = VarAllocationPass::VarPos; using Reg = TinyMIPSReg; } // namespace void VarAllocationPass::Reset() { live_intervals_.clear(); var_pos_.clear(); cur_pos_ = 0; last_call_pos_ = 0; saved_reg_.clear(); saved_reg_.insert(Reg::RA); saved_reg_.insert(Reg::FP); local_slot_count_ = 0; max_arg_count_ = 0; } void VarAllocationPass::InitFreeReg(bool is_preserved) { free_reg_.clear(); // set range of registers Reg begin, end; if (is_preserved) { begin = Reg::S7; end = Reg::S0; } else { free_reg_.push_back(Reg::T9); free_reg_.push_back(Reg::T8); begin = Reg::T7; end = Reg::T0; } // push to 'free_reg_' for (auto r = static_cast<int>(begin); r >= static_cast<int>(end); --r) { free_reg_.push_back(static_cast<Reg>(r)); } } void VarAllocationPass::LogLiveInterval(const TACPtr &var) { // do not try to allocate register for all global variables if (IsGlobalVar(var)) return; // get live interval info auto it = live_intervals_.find(var); if (it != live_intervals_.end()) { auto &info = it->second; // update end position info.end_pos = cur_pos_; // check if there are function calls in current interval if (last_call_pos_ > info.start_pos && last_call_pos_ < cur_pos_) { info.must_preserve = true; } } else { // add new live interval info live_intervals_.insert({var, {cur_pos_, cur_pos_, true, false}}); } } void VarAllocationPass::RunVarAlloc() { IntervalStartMap start_map; // build map for all normal variables for (const auto &i : live_intervals_) { if (!i.second.can_alloc_reg) { // allocate a new slot now var_pos_.insert({i.first, GetNewSlot()}); } else if (!i.second.must_preserve) { // insert to start map start_map.insert({&i.second, i.first}); } } // run first allocation InitFreeReg(false); LinearScanAlloc(start_map, false); // build map for all preserved variables start_map.clear(); for (const auto &i : live_intervals_) { if (i.second.must_preserve) { // insert to start map start_map.insert({&i.second, i.first}); } } // run second allocation InitFreeReg(true); LinearScanAlloc(start_map, true); } void VarAllocationPass::LinearScanAlloc(const IntervalStartMap &start_map, bool save) { IntervalEndMap active; for (const auto &i : start_map) { ExpireOldIntervals(active, i.first); if (free_reg_.empty()) { // need to spill SpillAtInterval(active, i.first, i.second); } else { // allocate to a free register auto reg = free_reg_.back(); free_reg_.pop_back(); var_pos_[i.second] = reg; // add to saved registers if (save) saved_reg_.insert(reg); // add to active active.insert({i.first, i.second}); } } } void VarAllocationPass::ExpireOldIntervals(IntervalEndMap &active, const LiveInterval *i) { for (auto it = active.begin(); it != active.end();) { if (it->first->end_pos >= i->start_pos) return; // free current element's register const auto &pos = var_pos_[it->second]; if (auto reg = std::get_if<TinyMIPSReg>(&pos)) { free_reg_.push_back(*reg); } // remove current element from active it = active.erase(it); } } void VarAllocationPass::SpillAtInterval(IntervalEndMap &active, const LiveInterval *i, const TACPtr &var) { // get last element of active auto spill = active.end(); --spill; // check if can allocate register to var if (spill->first->end_pos > i->end_pos) { // allocate register of spilled variable to i assert(std::holds_alternative<TinyMIPSReg>(var_pos_[spill->second])); var_pos_[var] = var_pos_[spill->second]; // allocate a slot to spilled variable var_pos_[spill->second] = GetNewSlot(); // remove spill from active active.erase(spill); // add i to active active.insert({i, var}); } else { // just allocate a new slot var_pos_[var] = GetNewSlot(); } } std::size_t VarAllocationPass::GetNewSlot() { return local_slot_count_++; } bool VarAllocationPass::Run(FuncInfo &func) { Reset(); // get live intervals & argument info for (const auto &i : func.irs) { i->RunPass(*this); ++cur_pos_; } // run allocation RunVarAlloc(); return false; } void VarAllocationPass::RunOn(BinaryTAC &tac) { LogLiveInterval(tac.dest()); LogLiveInterval(tac.lhs()); LogLiveInterval(tac.rhs()); } void VarAllocationPass::RunOn(UnaryTAC &tac) { LogLiveInterval(tac.dest()); if (tac.op() == UnaryOp::AddressOf) { live_intervals_[tac.opr()].can_alloc_reg = false; } else { LogLiveInterval(tac.opr()); } } void VarAllocationPass::RunOn(LoadTAC &tac) { LogLiveInterval(tac.addr()); LogLiveInterval(tac.dest()); } void VarAllocationPass::RunOn(StoreTAC &tac) { LogLiveInterval(tac.value()); LogLiveInterval(tac.addr()); } void VarAllocationPass::RunOn(ArgSetTAC &tac) { LogLiveInterval(tac.value()); // get argument position info auto count = tac.pos() + 1; if (count > max_arg_count_) max_arg_count_ = count; } void VarAllocationPass::RunOn(BranchTAC &tac) { LogLiveInterval(tac.cond()); } void VarAllocationPass::RunOn(CallTAC &tac) { // log a function call last_call_pos_ = cur_pos_; LogLiveInterval(tac.dest()); } void VarAllocationPass::RunOn(ReturnTAC &tac) { LogLiveInterval(tac.value()); } void VarAllocationPass::RunOn(AssignTAC &tac) { LogLiveInterval(tac.value()); LogLiveInterval(tac.var()); }
5,761
C++
.cpp
197
24.918782
75
0.650307
ustb-owl/TinyMIPS
34
6
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,803
dce.cpp
ustb-owl_TinyMIPS/src/compiler/back/tac/pass/dce.cpp
#include <unordered_map> #include <cstddef> #include "back/tac/optimizer.h" using namespace tinylang::back::tac; #define ADD_DEST(tac, field, must_remove) \ do { \ auto it = vars_.find(tac.field()); \ if (it == vars_.end()) { \ auto ret = vars_.insert({tac.field(), 0}); \ insts_.insert({&tac, {&ret.first->second, must_remove}}); \ } \ else { \ insts_.insert({&tac, {&it->second, must_remove}}); \ } \ } while (0) #define CHECK_REF_COUNT(tac, field) \ do { \ auto it = vars_.find(tac.field()); \ if (it != vars_.end()) ++it->second; \ } while (0) namespace { // dead code elimination class DeadCodeEliminationPass : public PassBase { public: DeadCodeEliminationPass() {} bool Run(FuncInfo &func) override { vars_.clear(); insts_.clear(); // find and mark all eligible TACs for (auto &&i : func.irs) i->RunPass(*this); // check & remove IRs bool changed = false; for (auto it = func.irs.begin(); it != func.irs.end();) { // find in info map auto inst_it = insts_.find(it->get()); if (inst_it != insts_.end()) { const auto &info = inst_it->second; // check if can be removed if (!*info.ref_count || info.must_remove) { // remove it = func.irs.erase(it); if (!changed) changed = true; continue; } } ++it; } // check & remove LOCAL variables // NOTE: if 'type' is nullptr, all variables in 'var' is global if (func.type) { for (auto it = func.vars.begin(); it != func.vars.end();) { // find in vars auto var_it = vars_.find(*it); if (var_it != vars_.end() && !var_it->second) { // remove it = func.vars.erase(it); if (!changed) changed = true; continue; } ++it; } } return changed; } void RunOn(BinaryTAC &tac) override { ADD_DEST(tac, dest, false); CHECK_REF_COUNT(tac, lhs); CHECK_REF_COUNT(tac, rhs); } void RunOn(UnaryTAC &tac) override { ADD_DEST(tac, dest, false); CHECK_REF_COUNT(tac, opr); } void RunOn(LoadTAC &tac) override { CHECK_REF_COUNT(tac, addr); } void RunOn(StoreTAC &tac) override { CHECK_REF_COUNT(tac, value); CHECK_REF_COUNT(tac, addr); } void RunOn(ArgSetTAC &tac) override { CHECK_REF_COUNT(tac, value); } void RunOn(BranchTAC &tac) override { CHECK_REF_COUNT(tac, cond); } void RunOn(ReturnTAC &tac) override { CHECK_REF_COUNT(tac, value); } void RunOn(AssignTAC &tac) override { // all assignments to global variables will be preserved if (!IsGlobalVar(tac.var()) || tac.var() == tac.value()) { auto must_remove = tac.var() == tac.value(); ADD_DEST(tac, var, must_remove); } CHECK_REF_COUNT(tac, value); } private: struct InstInfo { std::size_t *ref_count; bool must_remove; }; std::unordered_map<TACPtr, std::size_t> vars_; std::unordered_map<TACBase *, InstInfo> insts_; }; } // namespace // register current pass static RegisterPass<DeadCodeEliminationPass> dce("dead_code_elim", 1);
3,530
C++
.cpp
108
27.546296
70
0.531002
ustb-owl/TinyMIPS
34
6
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,804
copyprop.cpp
ustb-owl_TinyMIPS/src/compiler/back/tac/pass/copyprop.cpp
#include <unordered_map> #include <cstddef> #include "back/tac/optimizer.h" using namespace tinylang::back::tac; #define ADD_NEW_INFO(tac, field) \ do { \ auto it = vars_.find(tac.field()); \ if (it == vars_.end()) { \ vars_.insert({tac.field(), {0, &tac, nullptr, nullptr}}); \ } \ } while (0) #define CHECK_REF_COUNT(tac, field) \ do { \ auto it = vars_.find(tac.field()); \ if (it != vars_.end()) { \ ++it->second.ref_count; \ } \ } while (0) namespace { /* copy propagation on TAC IR, handle with TACs like: $0 = add $1, $2 $3 = $0 which variable '$0' has only been used once */ class CopyPropPass : public PassBase { public: CopyPropPass() {} bool Run(FuncInfo &func) override { vars_.clear(); cur_info_ = nullptr; // find and mark all eligible TACs for (auto &&i : func.irs) i->RunPass(*this); // modify TACs bool changed = false; for (const auto &i : vars_) { const auto &info = i.second; if (info.ref_count == 1 && info.assign_tac) { cur_info_ = &info; info.expr_tac->RunPass(*this); info.assign_tac->RunPass(*this); if (!changed) changed = true; } } return changed; } void RunOn(BinaryTAC &tac) override { if (cur_info_) { tac.set_dest(cur_info_->var_ref); } else { ADD_NEW_INFO(tac, dest); CHECK_REF_COUNT(tac, lhs); CHECK_REF_COUNT(tac, rhs); } } void RunOn(UnaryTAC &tac) override { if (cur_info_) { tac.set_dest(cur_info_->var_ref); } else { ADD_NEW_INFO(tac, dest); CHECK_REF_COUNT(tac, opr); } } void RunOn(LoadTAC &tac) override { if (cur_info_) { tac.set_dest(cur_info_->var_ref); } else { ADD_NEW_INFO(tac, dest); CHECK_REF_COUNT(tac, addr); } } void RunOn(StoreTAC &tac) override { CHECK_REF_COUNT(tac, value); CHECK_REF_COUNT(tac, addr); } void RunOn(ArgSetTAC &tac) override { CHECK_REF_COUNT(tac, value); } void RunOn(BranchTAC &tac) override { CHECK_REF_COUNT(tac, cond); } void RunOn(CallTAC &tac) override { if (cur_info_) { tac.set_dest(cur_info_->var_ref); } else { ADD_NEW_INFO(tac, dest); } } void RunOn(ReturnTAC &tac) override { CHECK_REF_COUNT(tac, value); } void RunOn(AssignTAC &tac) override { if (cur_info_) { tac.set_value(cur_info_->var_ref); } else { auto it = vars_.find(tac.value()); if (it != vars_.end()) { ++it->second.ref_count; it->second.assign_tac = &tac; it->second.var_ref = tac.var(); } } } private: struct ExprInfo { std::size_t ref_count; TACBase *expr_tac; TACBase *assign_tac; TACPtr var_ref; }; std::unordered_map<TACPtr, ExprInfo> vars_; const ExprInfo *cur_info_; }; } // namespace // register current pass static RegisterPass<CopyPropPass> copy_prop("copy_prop", 1);
3,270
C++
.cpp
121
22.305785
65
0.534995
ustb-owl/TinyMIPS
34
6
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,805
valprop.cpp
ustb-owl_TinyMIPS/src/compiler/back/tac/pass/valprop.cpp
#include <unordered_map> #include "back/tac/optimizer.h" using namespace tinylang::back::tac; #define CHECK_FIELD(tac, field) \ do { \ auto it = vars_.find(tac.field()); \ if (it != vars_.end()) { \ tac.set_##field(it->second); \ if (!changed_) changed_ = true; \ } \ } while (0) namespace { // value propagation (including constant propagation) class ValuePropPass : public PassBase { public: ValuePropPass() {} bool Run(FuncInfo &func) override { changed_ = false; vars_.clear(); for (auto &&i : func.irs) i->RunPass(*this); return changed_; } void RunOn(BinaryTAC &tac) override { CHECK_FIELD(tac, lhs); CHECK_FIELD(tac, rhs); } void RunOn(UnaryTAC &tac) override { CHECK_FIELD(tac, opr); } void RunOn(LoadTAC &tac) override { CHECK_FIELD(tac, addr); } void RunOn(StoreTAC &tac) override { CHECK_FIELD(tac, value); CHECK_FIELD(tac, addr); } void RunOn(ArgSetTAC &tac) override { CHECK_FIELD(tac, value); } void RunOn(BranchTAC &tac) override { CHECK_FIELD(tac, cond); } void RunOn(ReturnTAC &tac) override { CHECK_FIELD(tac, value); } void RunOn(AssignTAC &tac) override { CHECK_FIELD(tac, value); is_last_var_ref_ = is_last_num_ = false; tac.value()->RunPass(*this); if (is_last_var_ref_ || is_last_num_) { vars_[tac.var()] = tac.value(); } } void RunOn(VarRefTAC &tac) override { is_last_var_ref_ = true; } void RunOn(LabelTAC &tac) override { vars_.clear(); } void RunOn(NumberTAC &tac) override { is_last_num_ = true; } private: // table for variable's value std::unordered_map<TACPtr, TACPtr> vars_; // set to true if function info was changed bool changed_; bool is_last_var_ref_, is_last_num_; }; } // namespace // register current pass static RegisterPass<ValuePropPass> value_prop("value_prop", 1);
1,999
C++
.cpp
72
23.986111
63
0.62087
ustb-owl/TinyMIPS
34
6
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,806
strenredu.cpp
ustb-owl_TinyMIPS/src/compiler/back/tac/pass/strenredu.cpp
#include <bitset> #include <cmath> #include "back/tac/optimizer.h" using namespace tinylang::back::tac; namespace { // strength reduction class StrengthReductionPass : public PassBase { public: StrengthReductionPass() {} bool Run(FuncInfo &func) override { bool changed = false; for (auto it = func.irs.begin(); it != func.irs.end(); ++it) { replace_.clear(); (*it)->RunPass(*this); if (!replace_.empty()) { // replace current TAC for (std::size_t i = 0; i < replace_.size(); ++i) { if (!i) { *it = std::move(replace_[i]); } else { ++it; it = func.irs.insert(it, std::move(replace_[i])); } } if (!changed) changed = true; } } return changed; } void RunOn(BinaryTAC &tac) override { if (tac.lhs()->IsConst() && tac.rhs()->IsConst()) return; if (tac.lhs()->IsConst()) { tac.lhs()->RunPass(*this); ReduceRHS(tac.op(), tac.rhs(), tac.dest()); } else if (tac.rhs()->IsConst()) { tac.rhs()->RunPass(*this); ReduceLHS(tac.op(), tac.lhs(), tac.dest()); } } void RunOn(NumberTAC &tac) override { last_num_ = tac.num(); } private: // do reduction when rhs is constant void ReduceLHS(BinaryOp op, const TACPtr &lhs, const TACPtr &dest) { switch (op) { case BinaryOp::Mul: case BinaryOp::UMul: { // TODO: dynamic programming break; } case BinaryOp::Div: { int num = std::abs(static_cast<int>(last_num_)); if (num == 2) { auto var = NewTempVar(); AddBinaryTAC(BinaryOp::LShr, lhs, 31, var); AddBinaryTAC(BinaryOp::Add, var, lhs, var); AddBinaryTAC(BinaryOp::AShr, var, 1, dest); if (last_num_ & 0x80000000) { AddUnaryTAC(UnaryOp::Negate, dest, dest); } } else if (last_num_ == 0x80000000) { AddBinaryTAC(BinaryOp::LShr, lhs, 31, dest); } else if (num > 1 && (num & (num - 1)) == 0) { auto var = NewTempVar(); auto count = GetPopCount(num - 1); AddBinaryTAC(BinaryOp::AShr, lhs, 31, var); AddBinaryTAC(BinaryOp::LShr, var, 32 - count, var); AddBinaryTAC(BinaryOp::Add, var, lhs, var); AddBinaryTAC(BinaryOp::AShr, var, count, dest); if (last_num_ & 0x80000000) { AddUnaryTAC(UnaryOp::Negate, dest, dest); } } break; } // (unsigned) x / (2 ^ n) = x >> n case BinaryOp::UDiv: { if (last_num_ > 1 && (last_num_ & (last_num_ - 1)) == 0) { auto shift = GetPopCount(last_num_ - 1); AddBinaryTAC(BinaryOp::LShr, lhs, shift, dest); } break; } case BinaryOp::Mod: { auto num = std::abs(static_cast<int>(last_num_)); if (num == 2) { auto var = NewTempVar(); AddBinaryTAC(BinaryOp::LShr, lhs, 31, var); AddBinaryTAC(BinaryOp::Add, var, lhs, var); AddBinaryTAC(BinaryOp::And, var, -2, var); AddBinaryTAC(BinaryOp::Sub, lhs, var, dest); } else if (last_num_ == 0x80000000) { AddBinaryTAC(BinaryOp::And, lhs, last_num_ - 1, dest); } else if (num > 1 && (num & (num - 1)) == 0) { auto var = NewTempVar(); auto count = GetPopCount(num - 1); AddBinaryTAC(BinaryOp::AShr, lhs, 31, var); AddBinaryTAC(BinaryOp::LShr, var, 32 - count, var); AddBinaryTAC(BinaryOp::Add, var, lhs, var); AddBinaryTAC(BinaryOp::And, var, -num, var); AddBinaryTAC(BinaryOp::Sub, lhs, var, dest); } break; } // x % (2 ^ n) = x & (2 ^ n - 1) case BinaryOp::UMod: { if (last_num_ > 1 && (last_num_ & (last_num_ - 1)) == 0) { AddBinaryTAC(BinaryOp::And, lhs, last_num_ - 1, dest); } } default:; } } // do reduction when lhs is constant void ReduceRHS(BinaryOp op, const TACPtr &rhs, const TACPtr &dest) { switch (op) { case BinaryOp::Mul: case BinaryOp::UMul: { ReduceLHS(op, rhs, dest); break; } default:; } } // get population count (count of set bits in 'num') std::size_t GetPopCount(unsigned int num) { std::bitset<32> bit(num); return bit.count(); } void AddBinaryTAC(BinaryOp op, const TACPtr &opr, unsigned int num, const TACPtr &dest) { auto num_tac = std::make_shared<NumberTAC>(num); AddBinaryTAC(op, opr, std::move(num_tac), dest); } void AddBinaryTAC(BinaryOp op, const TACPtr &lhs, const TACPtr &rhs, const TACPtr &dest) { auto tac = std::make_shared<BinaryTAC>(op, lhs, rhs, dest); replace_.push_back(std::move(tac)); } void AddUnaryTAC(UnaryOp op, const TACPtr &opr, const TACPtr &dest) { auto tac = std::make_shared<UnaryTAC>(op, opr, dest); replace_.push_back(std::move(tac)); } TACPtrList replace_; unsigned int last_num_; }; } // namespace // register current pass static RegisterPass<StrengthReductionPass> stren_redu("stren_reduce", 2);
5,183
C++
.cpp
154
26.292208
73
0.558149
ustb-owl/TinyMIPS
34
6
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,807
constfold.cpp
ustb-owl_TinyMIPS/src/compiler/back/tac/pass/constfold.cpp
#include <cassert> #include <cstdint> #include "back/tac/optimizer.h" using namespace tinylang::back::tac; namespace { inline unsigned int DoCalc(BinaryOp op, unsigned int lhs, unsigned int rhs) { int s_lhs = lhs, s_rhs = rhs; switch (op) { case BinaryOp::Add: return lhs + rhs; case BinaryOp::Sub: return lhs - rhs; case BinaryOp::Mul: return s_lhs * s_rhs; case BinaryOp::UMul: return lhs * rhs; case BinaryOp::Div: return s_lhs / s_rhs; case BinaryOp::UDiv: return lhs / rhs; case BinaryOp::Mod: return s_lhs % s_rhs; case BinaryOp::UMod: return lhs % rhs; case BinaryOp::Equal: return lhs == rhs; case BinaryOp::NotEqual: return lhs != rhs; case BinaryOp::Less: return s_lhs < s_rhs; case BinaryOp::ULess: return lhs < rhs; case BinaryOp::LessEq: return s_lhs <= s_rhs; case BinaryOp::ULessEq: return lhs <= rhs; case BinaryOp::Great: return s_lhs > s_rhs; case BinaryOp::UGreat: return lhs > rhs; case BinaryOp::GreatEq: return s_lhs >= s_rhs; case BinaryOp::UGreatEq: return lhs >= rhs; case BinaryOp::LogicAnd: return lhs && rhs; case BinaryOp::LogicOr: return lhs || rhs; case BinaryOp::And: return lhs & rhs; case BinaryOp::Or: return lhs | rhs; case BinaryOp::Xor: return lhs ^ rhs; case BinaryOp::Shl: return lhs << rhs; case BinaryOp::AShr: return s_lhs >> s_rhs; case BinaryOp::LShr: return lhs >> rhs; default: assert(false); return 0; } } inline unsigned int DoCalc(UnaryOp op, unsigned int opr) { switch (op) { case UnaryOp::Negate: return -opr; case UnaryOp::LogicNot: return !opr; case UnaryOp::Not: return ~opr; case UnaryOp::SExt: return static_cast<std::int8_t>(opr); case UnaryOp::ZExt: case UnaryOp::Trunc: return opr & 0xff; default: assert(false); return 0; } } // constant folding on TAC IR class ConstFoldPass : public PassBase { public: ConstFoldPass() {} bool Run(FuncInfo &func) override { bool changed = false; for (auto &&tac : func.irs) { auto new_tac = DoFolding(tac); if (new_tac) { tac = std::move(new_tac); if (!changed) changed = true; } } return changed; } void RunOn(BinaryTAC &tac) override { // get lhs & rhs tac.lhs()->RunPass(*this); auto lhs = last_num_; tac.rhs()->RunPass(*this); auto rhs = last_num_; // do calculation auto ans = DoCalc(tac.op(), lhs, rhs); // create new TAC auto val = std::make_shared<NumberTAC>(ans); last_tac_ = std::make_shared<AssignTAC>(std::move(val), tac.dest()); } void RunOn(UnaryTAC &tac) override { // get operand tac.opr()->RunPass(*this); auto opr = last_num_; // do calculation auto ans = DoCalc(tac.op(), opr); // create new TAC auto val = std::make_shared<NumberTAC>(ans); last_tac_ = std::make_shared<AssignTAC>(std::move(val), tac.dest()); } void RunOn(NumberTAC &tac) override { last_num_ = tac.num(); } private: TACPtr DoFolding(const TACPtr &tac) { if (tac->IsConst()) { last_tac_ = nullptr; tac->RunPass(*this); return last_tac_; } return nullptr; } TACPtr last_tac_; unsigned int last_num_; }; } // namespace // register current pass static RegisterPass<ConstFoldPass> const_fold("const_fold", 1);
3,356
C++
.cpp
103
28.019417
72
0.645261
ustb-owl/TinyMIPS
34
6
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,808
algesimp.cpp
ustb-owl_TinyMIPS/src/compiler/back/tac/pass/algesimp.cpp
#include "back/tac/optimizer.h" #include "define/type.h" using namespace tinylang::back::tac; using namespace tinylang::define; namespace { // algebraic simplification class AlgebraicSimplificationPass : public PassBase { public: AlgebraicSimplificationPass() {} bool Run(FuncInfo &func) override { bool changed = false; for (auto &&i : func.irs) { replace_ = nullptr; i->RunPass(*this); if (replace_) { i = std::move(replace_); if (!changed) changed = true; } } return changed; } void RunOn(BinaryTAC &tac) override { if (tac.lhs()->IsConst() && tac.rhs()->IsConst()) return; if (tac.lhs()->IsConst()) { tac.lhs()->RunPass(*this); SimplifyRHS(tac.op(), tac.rhs(), tac.dest()); } else if (tac.rhs()->IsConst()) { tac.rhs()->RunPass(*this); SimplifyLHS(tac.op(), tac.lhs(), tac.dest()); } else if (tac.lhs() == tac.rhs()) { SimplifyEq(tac.op(), tac.lhs(), tac.dest()); } } void RunOn(NumberTAC &tac) override { last_num_ = tac.num(); } private: // simplify when rhs is constant void SimplifyLHS(BinaryOp op, const TACPtr &lhs, const TACPtr &dest) { switch (op) { // x + 0 = x, x - 0 = x case BinaryOp::Add: case BinaryOp::Sub: { if (!last_num_) MakeAssign(lhs, dest); break; } // x * 0 = 0, x * 1 = x case BinaryOp::Mul: case BinaryOp::UMul: { if (!last_num_) { MakeAssignZero(dest); } else if (last_num_ == 1) { MakeAssign(lhs, dest); } break; } // x / 1 = x, x / 0 = error case BinaryOp::Div: case BinaryOp::UDiv: { if (last_num_ == 1) MakeAssign(lhs, dest); break; } // x % 1 = 0, x % 0 = error case BinaryOp::Mod: case BinaryOp::UMod: { if (last_num_ == 1) MakeAssignZero(dest); break; } // (signed) x < S_MIN = 0, (unsigned) x < 0 = 0 case BinaryOp::Less: case BinaryOp::ULess: { auto val_min = op == BinaryOp::Less ? 0x80000000 : 0; if (last_num_ == val_min) MakeAssignZero(dest); break; } // (signed) x <= S_MAX = 1, (unsigned) x <= U_MAX = 1 case BinaryOp::LessEq: case BinaryOp::ULessEq: { auto val_max = op == BinaryOp::LessEq ? 0x7fffffff : 0xffffffff; if (last_num_ == val_max) MakeAssignOne(dest); break; } // (signed) x > S_MAX = 0, (unsigned) x > U_MAX = 0 case BinaryOp::Great: case BinaryOp::UGreat: { auto val_max = op == BinaryOp::Great ? 0x7fffffff : 0xffffffff; if (last_num_ == val_max) MakeAssignZero(dest); break; } // (signed) x >= S_MIN = 1, (unsigned) x >= 0 = 1 case BinaryOp::GreatEq: case BinaryOp::UGreatEq: { auto val_min = op == BinaryOp::GreatEq ? 0x80000000 : 0; if (last_num_ == val_min) MakeAssignOne(dest); break; } // x && 0 = 0, x && !0 = x case BinaryOp::LogicAnd: { if (!last_num_) { MakeAssignZero(dest); } else { MakeAssign(lhs, dest); } break; } // x || 0 = x, x || !0 = 1 case BinaryOp::LogicOr: { if (!last_num_) { MakeAssign(lhs, dest); } else { MakeAssignOne(dest); } break; } // x & 0 = 0, x & U_MAX = x case BinaryOp::And: { if (!last_num_) { MakeAssignZero(dest); } else if (last_num_ == 0xffffffff) { MakeAssign(lhs, dest); } break; } // x | 0 = x, x & U_MAX = U_MAX case BinaryOp::Or: { if (!last_num_) { MakeAssign(lhs, dest); } else if (last_num_ == 0xffffffff) { MakeAssign(std::make_shared<NumberTAC>(0xffffffff), dest); } break; } // x ^ 0 = x // (signed) x >> 0 = x case BinaryOp::Xor: case BinaryOp::AShr: { if (!last_num_) MakeAssign(lhs, dest); break; } // x << 0 = x, x << (>=WORD_LEN) = 0 // (unsigned) x >> 0 = x, x >> (>=WORD_LEN) = 0 case BinaryOp::Shl: case BinaryOp::LShr: { if (!last_num_) { MakeAssign(lhs, dest); } else if (last_num_ >= kTypeSizeWordLength * 8) { MakeAssignZero(dest); } break; } default:; } } // simplify when lhs is constant void SimplifyRHS(BinaryOp op, const TACPtr &rhs, const TACPtr &dest) { switch (op) { // use exchange law case BinaryOp::Add: case BinaryOp::Mul: case BinaryOp::UMul: case BinaryOp::Equal: case BinaryOp::NotEqual: case BinaryOp::LogicAnd: case BinaryOp::LogicOr: case BinaryOp::And: case BinaryOp::Or: case BinaryOp::Xor: { SimplifyLHS(op, rhs, dest); break; } // 0 / x = 0, 0 % x = 0 // 0 << x = 0, (signed/unsigned) 0 >> x = 0 case BinaryOp::Div: case BinaryOp::UDiv: case BinaryOp::Mod: case BinaryOp::UMod: case BinaryOp::Shl: case BinaryOp::AShr: case BinaryOp::LShr: { if (!last_num_) MakeAssignZero(dest); break; } // (signed) S_MAX < x = 0, (unsigned) U_MAX < x = 0 case BinaryOp::Less: case BinaryOp::ULess: { auto val_max = op == BinaryOp::Less ? 0x7fffffff : 0xffffffff; if (last_num_ == val_max) MakeAssignZero(dest); break; } // (signed) S_MIN <= x = 1, (unsigned) 0 <= x = 1 case BinaryOp::LessEq: case BinaryOp::ULessEq: { auto val_min = op == BinaryOp::LessEq ? 0x80000000 : 0; if (last_num_ == val_min) MakeAssignOne(dest); break; } // (signed) S_MIN > x = 0, (unsigned) 0 > x = 0 case BinaryOp::Great: case BinaryOp::UGreat: { auto val_min = op == BinaryOp::Great ? 0x80000000 : 0; if (last_num_ == val_min) MakeAssignZero(dest); break; } // (signed) S_MAX >= x = 1, (unsigned) U_MAX >= x = 1 case BinaryOp::GreatEq: case BinaryOp::UGreatEq: { auto val_max = op == BinaryOp::GreatEq ? 0x7fffffff : 0xffffffff; if (last_num_ == val_max) MakeAssignOne(dest); break; } default:; } } // simplify when lhs == rhs void SimplifyEq(BinaryOp op, const TACPtr &lhs, const TACPtr &dest) { switch (op) { // x - x = 0, x % x = 0, x != x = 0 // (signed/unsigned) x < x = 0, x > x = 0 // x ^ x = 0 case BinaryOp::Sub: case BinaryOp::Mod: case BinaryOp::UMod: case BinaryOp::NotEqual: case BinaryOp::Less: case BinaryOp::ULess: case BinaryOp::Great: case BinaryOp::UGreat: case BinaryOp::Xor: { MakeAssignZero(dest); break; } // x / x = 1, x == x = 1 // (signed/unsigned) x <= x = 1, x >= x = 1 case BinaryOp::Div: case BinaryOp::UDiv: case BinaryOp::Equal: case BinaryOp::LessEq: case BinaryOp::ULessEq: case BinaryOp::GreatEq: case BinaryOp::UGreatEq: { MakeAssignOne(dest); break; } // x && x = x, x || x = x, x & x = x, x | x = x case BinaryOp::LogicAnd: case BinaryOp::LogicOr: case BinaryOp::And: case BinaryOp::Or: { MakeAssign(lhs, dest); break; } default:; } } void MakeAssign(const TACPtr &value, const TACPtr &dest) { replace_ = std::make_shared<AssignTAC>(value, dest); } void MakeAssignZero(const TACPtr &dest) { auto zero = std::make_shared<NumberTAC>(0); replace_ = std::make_shared<AssignTAC>(std::move(zero), dest); } void MakeAssignOne(const TACPtr &dest) { auto one = std::make_shared<NumberTAC>(1); replace_ = std::make_shared<AssignTAC>(std::move(one), dest); } TACPtr replace_; unsigned int last_num_; }; } // namespace // register current pass static RegisterPass<AlgebraicSimplificationPass> alge_simp("alge_simp", 1);
7,912
C++
.cpp
243
25.588477
75
0.548602
ustb-owl/TinyMIPS
34
6
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,809
usedef.cpp
ustb-owl_TinyMIPS/src/compiler/back/ssa/ir/usedef.cpp
#include "back/ssa/ir/usedef.h" using namespace tinylang::back::ssa; void Value::ReplaceBy(const SSAPtr &value) { // TODO: consider optimizing // copy an use list from current value auto uses = uses_; // reroute all uses to new value for (const auto &use : uses) { use->set_value(value); } } void Use::set_value(const SSAPtr &value) { if (value_) value_->RemoveUse(this); value_ = value; if (value_) value_->AddUse(this); }
449
C++
.cpp
16
25.5
44
0.688372
ustb-owl/TinyMIPS
34
6
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,810
ast.cpp
ustb-owl_TinyMIPS/src/compiler/define/ast.cpp
#include "define/ast.h" #include <iomanip> #include <cassert> #include <cstddef> using namespace tinylang::define; namespace { const char *operators[] = { "+", "-", "*", "/", "%", "==", "!=", "<", "<=", ">", ">=", "&&", "||", "!", "&", "|", "~", "^", "<<", ">>", "=", "+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>=", }; int indent_count = 0, in_expr = 0; const auto indent = [](std::ostream &os) { if (indent_count) { os << std::setw(indent_count * 2) << std::setfill(' ') << ' '; } }; std::ostream &operator<<(std::ostream &os, decltype(indent) func) { func(os); return os; } } // namespace void VarDefAST::Dump(std::ostream &os) { for (const auto &i : defs_) i->Dump(os); } void LetDefAST::Dump(std::ostream &os) { for (const auto &i : defs_) i->Dump(os); } void FunDefAST::Dump(std::ostream &os) { os << indent; if (type_) { type_->Dump(os); } else { os << "void"; } os << ' ' << id_ << '('; for (std::size_t i = 0; i < args_.size(); ++i) { if (i) os << ", "; args_[i]->Dump(os); } os << ')'; if (body_) { os << ' '; body_->Dump(os); } else { os << ';' << std::endl; } } void FunCallAST::Dump(std::ostream &os) { if (!in_expr) os << indent; os << id_ << '('; for (const auto &i : args_) i->Dump(os); os << ')'; if (!in_expr) os << ';' << std::endl; } void IfAST::Dump(std::ostream &os) { os << indent << "if ("; ++in_expr; cond_->Dump(os); --in_expr; os << ") "; then_->Dump(os); if (else_then_) { os << indent << "else "; else_then_->Dump(os); } } void WhileAST::Dump(std::ostream &os) { os << indent << "while ("; ++in_expr; cond_->Dump(os); --in_expr; os << ") "; body_->Dump(os); } void ControlAST::Dump(std::ostream &os) { os << indent; switch (type_) { case front::Keyword::Break: os << "break"; break; case front::Keyword::Continue: os << "continue"; break; case front::Keyword::Return: os << "return"; break; default: assert(false); } if (expr_) { os << ' '; ++in_expr; expr_->Dump(os); --in_expr; } os << ';' << std::endl; } void VarElemAST::Dump(std::ostream &os) { ++in_expr; os << indent; if (type_) { type_->Dump(os); } else { os << "auto"; } os << ' ' << id_; if (init_) { os << " = "; init_->Dump(os); } os << ';' << std::endl; --in_expr; } void LetElemAST::Dump(std::ostream &os) { ++in_expr; os << indent << "const "; if (type_) { type_->Dump(os); } else { os << "auto"; } os << ' ' << id_; if (init_) { os << " = "; init_->Dump(os); } os << ';' << std::endl; --in_expr; } void TypeAST::Dump(std::ostream &os) { switch (type_) { case front::Keyword::Int32: os << "int32_t"; break; case front::Keyword::Int8: os << "int8_t"; break; case front::Keyword::UInt32: os << "uint32_t"; break; case front::Keyword::UInt8: os << "uint8_t"; break; default: assert(false); } if (ptr_) os << std::setw(ptr_) << std::setfill('*') << '*'; } void ArgElemAST::Dump(std::ostream &os) { type_->Dump(os); os << ' ' << id_; } void BlockAST::Dump(std::ostream &os) { os << '{' << std::endl; ++indent_count; for (const auto &i : stmts_) i->Dump(os); --indent_count; os << indent << '}' << std::endl; } void BinaryAST::Dump(std::ostream &os) { if (!in_expr) { os << indent; } else { os << '('; } ++in_expr; lhs_->Dump(os); os << ' ' << operators[static_cast<int>(op_)] << ' '; rhs_->Dump(os); --in_expr; if (!in_expr) { os << ';' << std::endl; } else { os << ')'; } } void CastAST::Dump(std::ostream &os) { ++in_expr; os << '('; type_->Dump(os); os << ") "; expr_->Dump(os); --in_expr; } void UnaryAST::Dump(std::ostream &os) { ++in_expr; os << operators[static_cast<int>(op_)]; opr_->Dump(os); --in_expr; } void IdAST::Dump(std::ostream &os) { os << id_; } void NumAST::Dump(std::ostream &os) { os << num_; } void StringAST::Dump(std::ostream &os) { os << '"' << str_ << '"'; } void CharAST::Dump(std::ostream &os) { os << "'"; switch (c_) { case '\r': os << "\\r"; break; case '\n': os << "\\n"; break; default: os << c_; break; } os << "'"; } void ArrayAST::Dump(std::ostream &os) { ++in_expr; os << "{ "; for (const auto &i : elems_) { i->Dump(os); os << ", "; } os << '}'; --in_expr; } void IndexAST::Dump(std::ostream &os) { ++in_expr; os << id_; os << '['; index_->Dump(os); os << ']'; --in_expr; }
4,552
C++
.cpp
220
17.709091
67
0.501626
ustb-owl/TinyMIPS
34
6
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,811
type.cpp
ustb-owl_TinyMIPS/src/compiler/define/type.cpp
#include "define/type.h" using namespace tinylang::define; bool PlainType::CanAccept(const TypePtr &type) const { if (IsRightValue() || (type->IsVoid() ^ (type_ == Type::Void)) || type->IsFunction() || type->IsPointer()) { return false; } return type->GetSize() <= GetSize(); } bool PlainType::CanCastTo(const TypePtr &type) const { return !type->IsVoid() && !type->IsFunction(); } TypePtr PlainType::GetReturnType(const TypePtrList &args) const { return nullptr; } bool ConstType::CanAccept(const TypePtr &type) const { return false; } bool ConstType::CanCastTo(const TypePtr &type) const { // allow 'const cast' return type_->CanCastTo(type); } TypePtr ConstType::GetReturnType(const TypePtrList &args) const { return type_->GetReturnType(args); } bool PointerType::CanAccept(const TypePtr &type) const { if (IsRightValue() || type->IsVoid() || type->IsFunction()) return false; if (type->IsPointer()) return IsPointerCompatible(*this, *type); return type->GetSize() <= GetSize(); } bool PointerType::CanCastTo(const TypePtr &type) const { return type->GetSize() >= GetSize(); } TypePtr PointerType::GetReturnType(const TypePtrList &args) const { return nullptr; } bool FuncType::CanAccept(const TypePtr &type) const { return false; } bool FuncType::CanCastTo(const TypePtr &type) const { return false; } TypePtr FuncType::GetReturnType(const TypePtrList &args) const { if (args.size() != args_.size()) return nullptr; for (std::size_t i = 0; i < args.size(); ++i) { if (!args_[i]->CanAccept(args[i])) return nullptr; } return ret_; }
1,604
C++
.cpp
49
30.367347
75
0.714656
ustb-owl/TinyMIPS
34
6
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,812
main.cpp
ustb-owl_TinyMIPS/src/utility/elfinfo/main.cpp
#include <fstream> #include <iostream> #include <vector> #include <string_view> #include "elf.h" using namespace std; namespace { inline void PrintHead(std::string_view head) { constexpr int mid_width = 30; int left_half = (mid_width - head.size()) / 2; int right_half = mid_width - left_half - head.size(); cout << " >>>>>>>>>>" << setw(left_half) << ' '; cout << head << setw(right_half) << ' ' << "<<<<<<<<<<" << endl; } inline void PrintTitle(std::string_view title) { cout << setw(30) << left << title; } inline void PrintHex32(std::uint32_t num) { cout << "0x" << hex << setw(8) << setfill('0'); cout << num << dec << setfill(' ') << endl; } Elf32_Ehdr GetELFHeader(std::istream &is) { Elf32_Ehdr ehdr; is.seekg(0, ios::beg); is.read(reinterpret_cast<char *>(&ehdr), sizeof(ehdr)); return ehdr; } bool PrintELFHeader(const Elf32_Ehdr &ehdr) { // check identification auto magic = reinterpret_cast<const char *>(ehdr.e_ident); if (strncmp(magic, elf32_ehdr_magic, EI_MAG3 + 1)) { cout << "invalid ELF file" << endl; return false; } // print identification info PrintTitle("file class:"); cout << elf32_ehdr_class[ehdr.e_ident[EI_CLASS]] << endl; PrintTitle("data encoding:"); cout << elf32_ehdr_data[ehdr.e_ident[EI_DATA]] << endl; PrintTitle("file version:"); cout << elf32_ehdr_version[ehdr.e_ident[EI_VERSION]] << endl; cout << endl; // print other info PrintTitle("object file type:"); cout << elf32_ehdr_type[ehdr.e_type] << endl; PrintTitle("required architecture:"); cout << elf32_ehdr_machine[ehdr.e_machine] << endl; PrintTitle("is version match:"); auto is_match = ehdr.e_version == ehdr.e_ident[EI_VERSION]; cout << boolalpha << is_match << endl; cout << endl; // entry point & offset PrintTitle("entry point:"); PrintHex32(ehdr.e_entry); PrintTitle("program ehdr table offset:"); cout << ehdr.e_phoff << endl; PrintTitle("section ehdr offset:"); cout << ehdr.e_shoff << endl; cout << endl; // flag info PrintTitle("processor-specific flags:"); PrintHex32(ehdr.e_flags); PrintTitle("MIPS noreorder:"); cout << boolalpha << !!(ehdr.e_flags & EF_MIPS_NOREORDER) << endl; PrintTitle("MIPS PIC:"); cout << boolalpha << !!(ehdr.e_flags & EF_MIPS_PIC) << endl; PrintTitle("MIPS calling PIC:"); cout << boolalpha << !!(ehdr.e_flags & EF_MIPS_CPIC) << endl; cout << endl; // size info PrintTitle("ELF ehdr size:"); cout << ehdr.e_ehsize << endl; PrintTitle("program ehdr table size:"); cout << ehdr.e_phentsize << " * " << ehdr.e_phnum; cout << " = " << ehdr.e_phentsize * ehdr.e_phnum << endl; PrintTitle("section ehdr size:"); cout << ehdr.e_shentsize << " * " << ehdr.e_shnum; cout << " = " << ehdr.e_shentsize * ehdr.e_shnum << endl; PrintTitle("string table index:"); cout << ehdr.e_shstrndx << endl; cout << endl; return is_match; } std::vector<Elf32_Shdr> GetSectionHeaders(std::istream &is, const Elf32_Ehdr &ehdr) { std::vector<Elf32_Shdr> shdrs; is.seekg(ehdr.e_shoff, ios::beg); for (Elf32_Half i = 0; i < ehdr.e_shnum; ++i) { Elf32_Shdr shdr; is.read(reinterpret_cast<char *>(&shdr), ehdr.e_shentsize); shdrs.push_back(shdr); } return shdrs; } std::vector<char> GetStringTable(std::istream &is, const Elf32_Ehdr &ehdr, const std::vector<Elf32_Shdr> &shdrs) { std::vector<char> str_table; // get string table section's header const auto &st_header = shdrs[ehdr.e_shstrndx]; // read string table str_table.resize(st_header.sh_size); is.seekg(st_header.sh_offset, ios::beg); is.read(reinterpret_cast<char *>(str_table.data()), str_table.size()); return str_table; } void PrintSectionHeader(const Elf32_Shdr &shdr, const std::vector<char> &str_table) { PrintHead("Section Header"); // print name and type PrintTitle("name:"); cout << str_table.data() + shdr.sh_name << endl;; PrintTitle("type:"); if (shdr.sh_type <= SHT_DYNSYM) { cout << elf32_shdr_type[shdr.sh_type] << endl; } else { switch (shdr.sh_type) { case SHT_MIPS_LIBLIST: cout << "SHT_MIPS_LIBLIST" << endl; break; case SHT_MIPS_CONFLICT: cout << "SHT_MIPS_CONFLICT" << endl; break; case SHT_MIPS_GPTAB: cout << "SHT_MIPS_GPTAB" << endl; break; case SHT_MIPS_UCODE: cout << "SHT_MIPS_UCODE" << endl; break; case SHT_MIPS_REGINFO: cout << "SHT_MIPS_REGINFO" << endl; break; case SHT_MIPS_ABIFLAGS: cout << "SHT_MIPS_ABIFLAGS" << endl; break; default: PrintHex32(shdr.sh_type); break; } } cout << endl; // print attribute flags PrintTitle("flags:"); PrintHex32(shdr.sh_flags); PrintTitle("is writable:"); cout << boolalpha << !!(shdr.sh_flags & SHF_WRITE) << endl; PrintTitle("must allocate:"); cout << boolalpha << !!(shdr.sh_flags & SHF_ALLOC) << endl; PrintTitle("is executable:"); cout << boolalpha << !!(shdr.sh_flags & SHF_EXECINSTR) << endl; cout << endl; // print section's address and position info PrintTitle("address:"); PrintHex32(shdr.sh_addr); PrintTitle("offset:"); cout << shdr.sh_offset << endl; PrintTitle("size:"); cout << shdr.sh_size << endl; cout << endl; // print other info PrintTitle("link:"); PrintHex32(shdr.sh_link); PrintTitle("info:"); PrintHex32(shdr.sh_info); PrintTitle("address alignment:"); cout << shdr.sh_addralign << endl; PrintTitle("fixed entry size:"); cout << shdr.sh_entsize << endl; cout << endl; } std::vector<Elf32_Phdr> GetProgramHeaders(std::istream &is, const Elf32_Ehdr &ehdr) { std::vector<Elf32_Phdr> phdrs; is.seekg(ehdr.e_phoff, ios::beg); for (Elf32_Half i = 0; i < ehdr.e_phnum; ++i) { Elf32_Phdr phdr; is.read(reinterpret_cast<char *>(&phdr), ehdr.e_phentsize); phdrs.push_back(phdr); } return phdrs; } void PrintProgramHeader(const Elf32_Phdr &phdr) { PrintHead("Program Header"); // print type info PrintTitle("type:"); if (phdr.p_type <= PT_PHDR) { cout << elf32_phdr_type[phdr.p_type] << endl; } else { PrintHex32(phdr.p_type); } cout << endl; // print address and size info PrintTitle("offset:"); cout << phdr.p_offset << endl; PrintTitle("virtual address:"); PrintHex32(phdr.p_vaddr); PrintTitle("physical address:"); PrintHex32(phdr.p_paddr); PrintTitle("file size:"); cout << phdr.p_filesz << endl; PrintTitle("memory size:"); cout << phdr.p_memsz << endl; cout << endl; // print other info PrintTitle("flags:"); PrintHex32(phdr.p_flags); PrintTitle("is executable:"); cout << boolalpha << !!(phdr.p_flags & PF_X) << endl; PrintTitle("is writable:"); cout << boolalpha << !!(phdr.p_flags & PF_W) << endl; PrintTitle("is readable:"); cout << boolalpha << !!(phdr.p_flags & PF_R) << endl; PrintTitle("alignment:"); cout << phdr.p_align << endl; cout << endl; } } // namespace int main(int argc, const char *argv[]) { if (argc < 2) { cerr << "invalid argument" << endl; cerr << "usage: " << argv[0] << " <elf_file>" << endl; return 1; } // load input file std::ifstream ifs(argv[1], ios::binary); ifs >> noskipws; // print ELF header auto ehdr = GetELFHeader(ifs); if (!PrintELFHeader(ehdr)) return 1; // print program headers auto phdrs = GetProgramHeaders(ifs, ehdr); for (const auto &i : phdrs) { PrintProgramHeader(i); } // print section headers auto shdrs = GetSectionHeaders(ifs, ehdr); auto str_table = GetStringTable(ifs, ehdr, shdrs); for (const auto &i : shdrs) { PrintSectionHeader(i, str_table); } return 0; }
7,672
C++
.cpp
229
29.838428
74
0.639876
ustb-owl/TinyMIPS
34
6
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,813
version.h
ustb-owl_TinyMIPS/src/compiler/version.h
#ifndef TINYLANG_VERSION_H_ #define TINYLANG_VERSION_H_ // version information of TinyLang #ifndef APP_NAME #define APP_NAME "TinyLang" #endif #ifndef APP_VERSION #define APP_VERSION "0.0.0" #endif #ifndef APP_VERSION_MAJOR #define APP_VERSION_MAJOR 0 #endif #ifndef APP_VERSION_MINOR #define APP_VERSION_MINOR 0 #endif #ifndef APP_VERSION_PATCH #define APP_VERSION_PATCH 0 #endif #endif // TINYLANG_VERSION_H_
444
C++
.h
19
22
38
0.755981
ustb-owl/TinyMIPS
34
6
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,814
argparse.h
ustb-owl_TinyMIPS/src/compiler/util/argparse.h
#ifndef TINYLANG_UTIL_ARGPARSE_H_ #define TINYLANG_UTIL_ARGPARSE_H_ #include <string> #include <vector> #include <map> #include <any> #include <cstddef> namespace tinylang::util { // command line argument parser class ArgParser { public: ArgParser() : program_name_("app"), padding_(kDefaultPadding) {} // add a new argument template <typename T> void AddArgument(const std::string &name, const std::string &help) { // check name CheckArgName(name); // check type CheckArgType(typeid(T)); // update padding width auto txt_width = name.size() + kArgMinWidth; if (txt_width > padding_) padding_ = txt_width; // push into argument list args_.push_back({name, "", help}); vals_.insert({name, T()}); } // add a new option template <typename T> void AddOption(const std::string &name, const std::string &short_name, const std::string &help, const T &default_val) { // check name CheckArgName(name); CheckArgName(short_name); // check type CheckArgType(typeid(T)); // update padding width auto txt_width = name.size() + short_name.size() + kArgMinWidth; if (txt_width > padding_) padding_ = txt_width; // push into option list opts_.push_back({name, short_name, help}); opt_map_.insert({"--" + name, opts_.size() - 1}); opt_map_.insert({"-" + short_name, opts_.size() - 1}); vals_.insert({name, default_val}); } // get parsed value template <typename T> T GetValue(const std::string &name) { return std::any_cast<T>(vals_[name]); } // parse argument bool Parse(int argc, const char *argv[]); // print help message void PrintHelp(); // setter void set_program_name(const char *program_name) { program_name_ = program_name; auto pos = program_name_.rfind('/'); if (pos != std::string::npos) { program_name_ = program_name_.substr(pos + 1); } } // getter const std::string &program_name() const { return program_name_; } private: // default padding width of argument description info static const int kDefaultPadding = 10; // minimum width of argument display in help message static const int kArgMinWidth = sizeof(" -, -- <ARG> ") - 1; struct ArgInfo { std::string name; std::string short_name; std::string help_msg; }; // assert argument/option name is valid void CheckArgName(const std::string &name); // assert argument/option type is valid void CheckArgType(const std::type_info &type); // read argument value bool ReadArgValue(const char *arg, std::any &value); std::string program_name_; std::size_t padding_; std::vector<ArgInfo> args_, opts_; std::map<std::string, std::size_t> opt_map_; std::map<std::string, std::any> vals_; }; } // namespace tinylang::util #endif // TINYLANG_UTIL_ARGPARSE_H_
2,842
C++
.h
87
28.885057
72
0.666058
ustb-owl/TinyMIPS
34
6
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,816
nested.h
ustb-owl_TinyMIPS/src/compiler/util/nested.h
#ifndef TINYLANG_UTIL_NESTED_H_ #define TINYLANG_UTIL_NESTED_H_ #include <unordered_map> #include <memory> #include <type_traits> namespace tinylang::util { template <typename K, typename V> class NestedMap; template <typename K, typename V> using NestedMapPtr = std::shared_ptr<NestedMap<K, V>>; template <typename K, typename V> class NestedMap { public: NestedMap() : outer_(nullptr) { static_cast<void>(PtrChecker<V>{}); } NestedMap(const NestedMapPtr<K, V> &outer) : outer_(outer) { static_cast<void>(PtrChecker<V>{}); } // add item to current map void AddItem(const K &key, const V &value) { map_.insert({key, value}); } // get item V GetItem(const K &key, bool recursive) { auto it = map_.find(key); if (it != map_.end()) { return it->second; } else if (outer_ && recursive) { return outer_->GetItem(key); } else { return nullptr; } } // get item recursively V GetItem(const K &key) { return GetItem(key, true); } // outer map const NestedMapPtr<K, V> &outer() const { return outer_; } // check if current map is root map bool is_root() const { return outer_ == nullptr; } private: // check if type is suitable template <typename Ptr> struct PtrChecker { static_assert(std::is_pointer<Ptr>::value || std::is_assignable<Ptr, std::nullptr_t>::value, "type must be a pointer or can accept nullptr_t"); }; NestedMapPtr<K, V> outer_; std::unordered_map<K, V> map_; }; // create a new nested map template <typename K, typename V> inline NestedMapPtr<K, V> MakeNestedMap() { return std::make_shared<NestedMap<K, V>>(); } // create a new nested map (with outer map) template <typename K, typename V> inline NestedMapPtr<K, V> MakeNestedMap(const NestedMapPtr<K, V> &outer) { return std::make_shared<NestedMap<K, V>>(outer); } } // namespace tinylang::util #endif // TINYLANG_UTIL_NESTED_H_
1,950
C++
.h
63
27.428571
74
0.670758
ustb-owl/TinyMIPS
34
6
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,818
parser.h
ustb-owl_TinyMIPS/src/compiler/front/parser.h
#ifndef TINYLANG_FRONT_PARSER_H_ #define TINYLANG_FRONT_PARSER_H_ #include "front/lexer.h" #include "define/ast.h" namespace tinylang::front { class Parser { public: Parser(Lexer &lexer) : lexer_(lexer) { Reset(); } // reset status of parser void Reset() { lexer_.Reset(); error_num_ = 0; NextToken(); } // get next AST from token stream define::ASTPtr ParseNext() { return cur_token_ == Token::End ? nullptr : ParseStatement(); } // getters unsigned int error_num() const { return error_num_; } private: // get next token from lexer Token NextToken() { return cur_token_ = lexer_.NextToken(); } // check if current token is a character (token type 'Other') bool IsTokenChar(char c) const { return cur_token_ == Token::Other && lexer_.other_val() == c; } // check if current token is a keyword bool IsTokenKeyword(Keyword key) const { return cur_token_ == Token::Keyword && lexer_.key_val() == key; } // check if current token is an operator bool IsTokenOperator(Operator op) const { return cur_token_ == Token::Operator && lexer_.op_val() == op; } // check if current token is an assignment operator bool IsAssign() const { return cur_token_ == Token::Operator && IsOperatorAssign(lexer_.op_val()); } // log error and return null pointer define::ASTPtr LogError(const char *message); define::ASTPtr ParseStatement(); define::ASTPtr ParseVarDef(); define::ASTPtr ParseLetDef(); define::ASTPtr ParseFunDef(); define::ASTPtr ParseIf(); define::ASTPtr ParseWhile(); define::ASTPtr ParseControl(); define::ASTPtr ParseVarElem(); define::ASTPtr ParseLetElem(); define::ASTPtr ParseType(); define::ASTPtr ParseArgElem(); define::ASTPtr ParseBlock(); define::ASTPtr ParseExpression(); define::ASTPtr ParseCast(); define::ASTPtr ParseUnary(); define::ASTPtr ParseFactor(); define::ASTPtr ParseFunCall(); define::ASTPtr ParseIndex(); define::ASTPtr ParseValue(); define::ASTPtr ParseId(); define::ASTPtr ParseNum(); define::ASTPtr ParseString(); define::ASTPtr ParseChar(); define::ASTPtr ParseArray(); // make sure current token is specific character and goto next token bool CheckChar(char c); Lexer &lexer_; unsigned int error_num_; Token cur_token_; }; } // namespace tinylang::front #endif // TINYLANG_FRONT_PARSER_H_
2,389
C++
.h
74
28.945946
70
0.701089
ustb-owl/TinyMIPS
34
6
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,819
analyzer.h
ustb-owl_TinyMIPS/src/compiler/front/analyzer.h
#ifndef TINYLANG_FRONT_ANALYZER_H_ #define TINYLANG_FRONT_ANALYZER_H_ #include <string> #include <stack> #include "define/symbol.h" #include "front/lexer.h" #include "util/guard.h" namespace tinylang::front { class Analyzer { public: Analyzer() : error_num_(0), while_count_(0), env_(define::MakeEnvironment()) {} define::TypePtr AnalyzeFunDef(const std::string &id, define::TypePtrList args, define::TypePtr ret); define::TypePtr AnalyzeFunCall(const std::string &id, const define::TypePtrList &args); define::TypePtr AnalyzeControl(Keyword type, const define::TypePtr &expr); define::TypePtr AnalyzeVarElem(const std::string &id, define::TypePtr type, const define::TypePtr &init); define::TypePtr AnalyzeLetElem(const std::string &id, define::TypePtr type, const define::TypePtr &init); define::TypePtr AnalyzeType(Keyword type, unsigned int ptr); define::TypePtr AnalyzeArgElem(const std::string &id, define::TypePtr type); define::TypePtr AnalyzeBinary(Operator op, const define::TypePtr &lhs, const define::TypePtr &rhs); define::TypePtr AnalyzeCast(const define::TypePtr &expr, const define::TypePtr &type); define::TypePtr AnalyzeUnary(Operator op, const define::TypePtr &opr); define::TypePtr AnalyzeId(const std::string &id); define::TypePtr AnalyzeNum(); define::TypePtr AnalyzeString(); define::TypePtr AnalyzeChar(); define::TypePtr AnalyzeArray(const define::TypePtrList &elems); define::TypePtr AnalyzeIndex(const std::string &id, const define::TypePtr &index); // create a new environment util::Guard NewEnvironment() { env_ = define::MakeEnvironment(env_); return util::Guard([this] { env_ = env_->outer(); }); } // enter a while loop util::Guard EnterWhile() { ++while_count_; return util::Guard([this] { --while_count_; }); } // enter a function util::Guard EnterFunction(const define::TypePtr &ret) { cur_ret_ = ret; return util::Guard([this] { cur_ret_ = nullptr; }); } // set line position util::Guard SetLinePos(unsigned int line_pos) { line_pos_.push(line_pos); return util::Guard([this] { line_pos_.pop(); }); } unsigned int error_num() const { return error_num_; } const define::EnvPtr &env() const { return env_; } private: define::TypePtr LogError(const char *message); define::TypePtr LogError(const char *message, const std::string &id); unsigned int error_num_, while_count_; std::stack<unsigned int> line_pos_; define::EnvPtr env_; define::TypePtr cur_ret_; }; } // namespace tinylang::front #endif // TINYLANG_FRONT_ANALYZER_H_
2,943
C++
.h
71
33.690141
76
0.635093
ustb-owl/TinyMIPS
34
6
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,820
lexer.h
ustb-owl_TinyMIPS/src/compiler/front/lexer.h
#ifndef TINYLANG_FRONT_LEXER_H_ #define TINYLANG_FRONT_LEXER_H_ #include <istream> #include <string> #include <cstdint> #include <cassert> namespace tinylang::front { enum class Token { Error, End, Id, Num, String, Char, Keyword, Operator, Other, }; enum class Keyword { // var, let, def, as Var, Let, Def, As, // i32, i8, u32, u8 Int32, Int8, UInt32, UInt8, // if, else, while If, Else, While, // break, continue, return Break, Continue, Return, }; enum class Operator { // +, -, *, /, % Add, Sub, Mul, Div, Mod, // ==, !=, <, <=, >, >= Equal, NotEqual, Less, LessEqual, Great, GreatEqual, // &&, ||, ! LogicAnd, LogicOr, LogicNot, // &, |, ~, ^, <<, >> And, Or, Not, Xor, Shl, Shr, // =, +=, -=, *=, /=, %= Assign, AssAdd, AssSub, AssMul, AssDiv, AssMod, // &=, |=, ^=, <<=, >>= AssAnd, AssOr, AssXor, AssShl, AssShr, }; class Lexer { public: Lexer(std::istream &in) : in_(in) { Reset(); } // reset status of lexer void Reset() { line_pos_ = 1; error_num_ = 0; last_char_ = ' '; in_ >> std::noskipws; } // get next token from input stream Token NextToken(); // current line position unsigned int line_pos() const { return line_pos_; } // current error count unsigned int error_num() const { return error_num_; } // identifiers const std::string &id_val() const { return id_val_; } // integer values unsigned long long num_val() const { return num_val_; } // string literals const std::string &str_val() const { return str_val_; } // keywords Keyword key_val() const { return key_val_; } // operators Operator op_val() const { return op_val_; } // character literals std::uint8_t char_val() const { return char_val_; } // other characters char other_val() const { return other_val_; } private: void NextChar() { in_ >> last_char_; } bool IsEOL() { return in_.eof() || last_char_ == '\n' || last_char_ == '\r'; } // print error message and return Token::Error Token PrintError(const char *message); // read escape character from stream int ReadEscape(); Token HandleId(); Token HandleNum(); Token HandleString(); Token HandleChar(); Token HandleOperator(); Token HandleComment(); Token HandleEOL(); std::istream &in_; unsigned int line_pos_, error_num_; char last_char_; // value of token std::string id_val_, str_val_; unsigned int num_val_; Keyword key_val_; Operator op_val_; std::uint8_t char_val_; char other_val_; }; // check if operator is assign ('=', '+=', '-=', ...) inline bool IsOperatorAssign(Operator op) { return static_cast<int>(op) >= static_cast<int>(Operator::Assign); } // get de-assigned operator ('+=' -> '+', '-=' -> '-', ...) inline Operator GetDeAssignedOp(Operator op) { switch (op) { case Operator::AssAdd: return Operator::Add; case Operator::AssSub: return Operator::Sub; case Operator::AssMul: return Operator::Mul; case Operator::AssDiv: return Operator::Div; case Operator::AssMod: return Operator::Mod; case Operator::AssAnd: return Operator::And; case Operator::AssOr: return Operator::Or; case Operator::AssXor: return Operator::Xor; case Operator::AssShl: return Operator::Shl; case Operator::AssShr: return Operator::Shr; default: assert(false); return Operator::Assign; } } } // namespace tinylang::front #endif // TINYLANG_FRONT_LEXER_H_
3,413
C++
.h
116
26.405172
68
0.645319
ustb-owl/TinyMIPS
34
6
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,821
irbuilder.h
ustb-owl_TinyMIPS/src/compiler/back/irbuilder.h
#ifndef TINYLANG_BACK_IRBUILDER_H_ #define TINYLANG_BACK_IRBUILDER_H_ #include <string> #include <ostream> #include "back/ir.h" #include "front/lexer.h" #include "define/type.h" #include "util/guard.h" namespace tinylang::back { // interface of all IR builders class IRBuilderInterface { public: virtual ~IRBuilderInterface() = default; virtual IRPtr GenerateFunDecl(const std::string &id) = 0; virtual IRPtr GenerateFunCall(const std::string &id, IRPtrList args) = 0; virtual IRPtr GenerateIfCond(const IRPtr &cond) = 0; virtual IRPtr GenerateWhileCond(const IRPtr &cond) = 0; virtual IRPtr GenerateControl(front::Keyword type, const IRPtr &expr) = 0; virtual IRPtr GenerateVarElem(const std::string &id, const IRPtr &init) = 0; virtual IRPtr GenerateLetElem(const std::string &id, const IRPtr &init) = 0; virtual IRPtr GenerateArgElem(const std::string &id) = 0; virtual IRPtr GenerateBinary(front::Operator op, const IRPtr &lhs, const IRPtr &rhs) = 0; virtual IRPtr GenerateLogicLHS(front::Operator op, const IRPtr &lhs) = 0; virtual IRPtr GenerateLogicRHS(const IRPtr &rhs) = 0; virtual IRPtr GenerateUnary(front::Operator op, const IRPtr &opr) = 0; virtual IRPtr GenerateId(const std::string &id) = 0; virtual IRPtr GenerateNum(unsigned int num) = 0; virtual IRPtr GenerateString(const std::string &str) = 0; virtual IRPtr GenerateChar(char c) = 0; virtual IRPtr GenerateArray(IRPtrList elems) = 0; virtual IRPtr GenerateIndex(const std::string &id, const IRPtr &index) = 0; // set type of current operand virtual util::Guard SetOprType(const define::TypePtr &lhs, const define::TypePtr &rhs) = 0; // mark the entry of a function virtual util::Guard EnterFunction(const std::string &id) = 0; // mark the entry of a true branch of if statement virtual util::Guard EnterIfTrueBody() = 0; // mark the entry of a false branch of if statement virtual util::Guard EnterIfFalseBody() = 0; // mark the entry of a condition checking branch of while statement virtual util::Guard EnterWhileCond() = 0; // mark the entry of a body of while statement virtual util::Guard EnterWhileBody() = 0; // mark the entry of second part of logical expression virtual util::Guard EnterLogicRHS(front::Operator op) = 0; // mark next expression is a memory store virtual util::Guard MarkStore(const IRPtr &value) = 0; // dump IRs in current builder virtual void Dump(std::ostream &os) = 0; }; // alias for 'IRBuilderInterface' using IRBuilder = IRBuilderInterface; } // namespace tinylang::back #endif // TINYLANG_BACK_IRBUILDER_H_
2,756
C++
.h
59
41.59322
76
0.70748
ustb-owl/TinyMIPS
34
6
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,822
ir.h
ustb-owl_TinyMIPS/src/compiler/back/ir.h
#ifndef TINYMIPS_BACK_IR_H_ #define TINYMIPS_BACK_IR_H_ #include <memory> #include <any> #include <vector> #include <cassert> namespace tinylang::back { class IRInterface { public: virtual ~IRInterface() = default; // get the exact value of current IR virtual const std::any value() const = 0; }; using IRPtr = std::shared_ptr<IRInterface>; using IRPtrList = std::vector<IRPtr>; // cast IR pointer to specific type template <typename T> inline T IRCast(const IRPtr &ir) { auto ret = ir->value(); auto value = std::any_cast<T>(&ret); assert(value != nullptr); return *value; } } // namespace tinylang::back #endif // TINYMIPS_BACK_IR_H_
661
C++
.h
25
24.52
43
0.721338
ustb-owl/TinyMIPS
34
6
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,823
builder.h
ustb-owl_TinyMIPS/src/compiler/back/tac/builder.h
#ifndef TINYLANG_BACK_TAC_BUILDER_H_ #define TINYLANG_BACK_TAC_BUILDER_H_ #include <memory> #include <stack> #include <unordered_map> #include <string> #include <vector> #include <cstddef> #include "back/irbuilder.h" #include "back/tac/define.h" #include "back/tac/ir.h" #include "back/tac/optimizer.h" #include "back/tac/codegen.h" #include "util/nested.h" namespace tinylang::back::tac { class TACBuilder : public IRBuilderInterface { public: TACBuilder() : cur_label_id_(0), cur_var_id_(0) { // create entry function auto guard = SetOprType(nullptr, nullptr); NewFuncInfo(kEntryFuncId); entry_func_ = cur_func_; // create variable info map NewVarMap(); } IRPtr GenerateFunDecl(const std::string &id) override; IRPtr GenerateFunCall(const std::string &id, IRPtrList args) override; IRPtr GenerateIfCond(const IRPtr &cond) override; IRPtr GenerateWhileCond(const IRPtr &cond) override; IRPtr GenerateControl(front::Keyword type, const IRPtr &expr) override; IRPtr GenerateVarElem(const std::string &id, const IRPtr &init) override; IRPtr GenerateLetElem(const std::string &id, const IRPtr &init) override; IRPtr GenerateArgElem(const std::string &id) override; IRPtr GenerateBinary(front::Operator op, const IRPtr &lhs, const IRPtr &rhs) override; IRPtr GenerateLogicLHS(front::Operator op, const IRPtr &lhs) override; IRPtr GenerateLogicRHS(const IRPtr &rhs) override; IRPtr GenerateUnary(front::Operator op, const IRPtr &opr) override; IRPtr GenerateId(const std::string &id) override; IRPtr GenerateNum(unsigned int num) override; IRPtr GenerateString(const std::string &str) override; IRPtr GenerateChar(char c) override; IRPtr GenerateArray(IRPtrList elems) override; IRPtr GenerateIndex(const std::string &id, const IRPtr &index) override; util::Guard SetOprType(const define::TypePtr &lhs, const define::TypePtr &rhs) override { opr_types_.push({lhs, rhs}); return util::Guard([this] { opr_types_.pop(); }); } util::Guard EnterFunction(const std::string &id) override; util::Guard EnterIfTrueBody() override; util::Guard EnterIfFalseBody() override; util::Guard EnterWhileCond() override; util::Guard EnterWhileBody() override; util::Guard EnterLogicRHS(front::Operator op) override; util::Guard MarkStore(const IRPtr &value) override; void Dump(std::ostream &os) override; // run TAC optimization void RunOptimization(Optimizer &opt); // run code generation void RunCodeGeneration(CodeGenerator &gen); private: // id of entry function static const char *kEntryFuncId; // label tags enum class LabelTag { // if-statement LabelTrue, LabelFalse, LabelEndIf, // while-statement LabelCond, LabelBody, LabelEndWhile, // logical expression LabelSecond, LabelEndLogic, }; // type info of operands struct OprTypeInfo { define::TypePtr lhs; define::TypePtr rhs; }; // create a new function info void NewFuncInfo(const std::string &id); // restore current function info to entry function void RestoreFuncInfo() { cur_func_ = entry_func_; } // create a new variable info map void NewVarMap() { vars_ = util::MakeNestedMap<std::string, TACPtr>(vars_); } // restore variable info map void RestoreVarMap() { vars_ = vars_->outer(); } // create a new temporary variable TACPtr NewTempVar() { return std::make_shared<VarRefTAC>(cur_var_id_++); } // add new TAC IR to current function void AddInst(TACPtr tac) { cur_func_->irs.push_back(std::move(tac)); } // create a new label TACPtr NewLabel() { return std::make_shared<LabelTAC>(cur_label_id_++); } // create a new unfilled label TACPtr NewUnfilledLabel(LabelTag type); // get an unfilled label const TACPtr &GetUnfilledLabel(LabelTag type); // fill label and insert it to current position void FillLabel(LabelTag type); // add jump TAC to current function void AddJump(LabelTag type); // new pointer offset calculation TACPtr NewPtrOffset(const TACPtr &offset, const define::TypePtr &offset_type, const define::TypePtr &ptr_type); // new pointer offset calculation (with specific size) TACPtr NewPtrOffset(const TACPtr &offset, const define::TypePtr &offset_type, std::size_t ptr_size); // new data casting TACPtr NewDataCast(const TACPtr &data, const define::TypePtr &src, const define::TypePtr &dest); // new data casting (with specific size) TACPtr NewDataCast(const TACPtr &data, const define::TypePtr &src, std::size_t dest); // stack of type of operands std::stack<OprTypeInfo> opr_types_; // hash map of function info FuncInfoMap funcs_; // current function & entry function FuncInfo *cur_func_, *entry_func_; // unfilled labels in current scope std::stack<std::unordered_map<LabelTag, TACPtr>> unfilled_; // current label id std::size_t cur_label_id_; // table of variables util::NestedMapPtr<std::string, TACPtr> vars_; // current variable id std::size_t cur_var_id_; // stack of return value in logical expression std::stack<TACPtr> logics_; // data list DataInfoList datas_; // store value (for memory accessing) TACPtr store_; }; } // namespace tinylang::back::tac #endif // TINYLANG_BACK_TAC_BUILDER_H_
5,418
C++
.h
141
34.198582
75
0.714557
ustb-owl/TinyMIPS
34
6
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,824
define.h
ustb-owl_TinyMIPS/src/compiler/back/tac/define.h
#ifndef TINYLANG_BACK_TAC_DEFINE_H_ #define TINYLANG_BACK_TAC_DEFINE_H_ #include <list> #include <unordered_set> #include <unordered_map> #include <string> #include <vector> #include <cstddef> #include "define/type.h" #include "back/tac/ir/tac.h" namespace tinylang::back::tac { // function info struct FuncInfo { // label of current function TACPtr label; // type of current function, 'nullptr' if is entry function define::TypePtr type; // list of arguments of function TACPtrList args; // list of variables in function std::unordered_set<TACPtr> vars; // list of instructions in function // empty if is just a declaration std::list<TACPtr> irs; }; // function info map using FuncInfoMap = std::unordered_map<std::string, FuncInfo>; // data info struct DataInfo { // content of data TACPtrList content; // size of element std::size_t elem_size; }; // data info list using DataInfoList = std::vector<DataInfo>; } // namespace tinylang::back::tac #endif // TINYLANG_BACK_TAC_DEFINE_H_
1,026
C++
.h
38
24.973684
62
0.742594
ustb-owl/TinyMIPS
34
6
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,825
codegen.h
ustb-owl_TinyMIPS/src/compiler/back/tac/codegen.h
#ifndef TINYLANG_BACK_TAC_CODEGEN_H_ #define TINYLANG_BACK_TAC_CODEGEN_H_ #include <ostream> #include <sstream> #include <string> #include <unordered_map> #include <cstddef> #include "back/tac/ir/tac.h" #include "back/tac/define.h" #include "back/tac/codegen/tmgen.h" #include "back/tac/codegen/varalloc.h" namespace tinylang::back::tac { class CodeGenerator { public: CodeGenerator(); // visitor methods void GenerateOn(BinaryTAC &tac); void GenerateOn(UnaryTAC &tac); void GenerateOn(LoadTAC &tac); void GenerateOn(StoreTAC &tac); void GenerateOn(ArgSetTAC &tac); void GenerateOn(JumpTAC &tac); void GenerateOn(BranchTAC &tac); void GenerateOn(CallTAC &tac); void GenerateOn(ReturnTAC &tac); void GenerateOn(AssignTAC &tac); void GenerateOn(VarRefTAC &tac); void GenerateOn(DataTAC &tac); void GenerateOn(LabelTAC &tac); void GenerateOn(ArgGetTAC &tac); void GenerateOn(NumberTAC &tac); // run code generation void Generate(); // dump generated assembly code void Dump(std::ostream &os); // set entry function's info void set_entry(FuncInfo *entry) { entry_ = entry; var_alloc_.set_entry_func(entry); } // set function info map void set_funcs(FuncInfoMap *funcs) { funcs_ = funcs; } // set data info list void set_datas(DataInfoList *datas) { datas_ = datas; } private: // generate all global variables void GenerateGlobalVars(); // generate all arrays void GenerateArrayData(); // generate a specific function void GenerateFunc(const std::string &name, const FuncInfo &info); // generate info in function's header void GenerateHeaderInfo(); // generate prologue void GeneratePrologue(const FuncInfo &info); // generate epilogue void GenerateEpilogue(); // put variable name to stream std::string GetVarName(std::size_t id); // put data name to stream std::string GetDataName(std::size_t id); // put label name to stream std::string GetLabelName(std::size_t id); // get current epilogue label and switch to next std::string NextEpilogueLabel(); // get current epilogue label std::string GetEpilogueLabel(); // get size of current frame std::size_t GetFrameSize(); // get TAC's value TinyMIPSReg GetValue(const TACPtr &tac); // set register's value to TAC void SetValue(const TACPtr &tac, TinyMIPSReg value); // function info of entry function FuncInfo *entry_; // function info map in TAC builder FuncInfoMap *funcs_; // data info in TAC builder DataInfoList *datas_; // string stream of generated code std::ostringstream code_; // info of all funtion declarations std::unordered_map<TACPtr, std::string> decls_; // assembly code generator of function body TinyMIPSAsmGen asm_gen_; // variable allocator VarAllocationPass var_alloc_; // last TACs VarRefTAC *last_var_; DataTAC *last_data_; LabelTAC *last_label_; ArgGetTAC *last_arg_get_; NumberTAC *last_num_; // id of epilogue label std::size_t epilogue_id_; }; } // namespace tinylang::back::tac #endif // TINYLANG_BACK_TAC_CODEGEN_H_
3,071
C++
.h
98
28.510204
67
0.735473
ustb-owl/TinyMIPS
34
6
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,826
ir.h
ustb-owl_TinyMIPS/src/compiler/back/tac/ir.h
#ifndef TINYLANG_BACK_TAC_IR_H_ #define TINYLANG_BACK_TAC_IR_H_ #include <utility> #include <cassert> #include "back/ir.h" #include "back/tac/ir/tac.h" namespace tinylang::back::tac { class TACIR : public IRInterface { public: TACIR(const TACPtr &value) : value_(value) { assert(value_ != nullptr); } const std::any value() const override { return value_; } private: TACPtr value_; }; // make a new TAC IR pointer by existing TAC IR inline IRPtr MakeTAC(const TACPtr &tac) { return std::make_shared<TACIR>(tac); } // cast IR to TAC IR inline TACPtr TACCast(const IRPtr &ir) { return IRCast<TACPtr>(ir); } } // namespace tinylang::back::tac #endif // TINYLANG_BACK_TAC_IR_H_
698
C++
.h
24
27.166667
75
0.721386
ustb-owl/TinyMIPS
34
6
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,827
optimizer.h
ustb-owl_TinyMIPS/src/compiler/back/tac/optimizer.h
#ifndef TINYLANG_BACK_TAC_OPTIMIZER_H_ #define TINYLANG_BACK_TAC_OPTIMIZER_H_ #include <memory> #include <utility> #include <string_view> #include <list> #include <ostream> #include <cstddef> #include "back/tac/define.h" #include "back/tac/ir/tac.h" namespace tinylang::back::tac { // interface of function pass class PassBase { public: virtual ~PassBase() = default; // run on function, return true if function is modified virtual bool Run(FuncInfo &func) = 0; // visitor methods for running on TAC IRs virtual void RunOn(BinaryTAC &tac) {} virtual void RunOn(UnaryTAC &tac) {} virtual void RunOn(LoadTAC &tac) {} virtual void RunOn(StoreTAC &tac) {} virtual void RunOn(ArgSetTAC &tac) {} virtual void RunOn(JumpTAC &tac) {} virtual void RunOn(BranchTAC &tac) {} virtual void RunOn(CallTAC &tac) {} virtual void RunOn(ReturnTAC &tac) {} virtual void RunOn(AssignTAC &tac) {} virtual void RunOn(VarRefTAC &tac) {} virtual void RunOn(DataTAC &tac) {} virtual void RunOn(LabelTAC &tac) {} virtual void RunOn(ArgGetTAC &tac) {} virtual void RunOn(NumberTAC &tac) {} void set_cur_var_id(std::size_t *cur_var_id) { cur_var_id_ = cur_var_id; } void set_entry_func(const FuncInfo *entry) { entry_ = entry; } protected: // create a new temporary variable TACPtr NewTempVar() { return std::make_shared<VarRefTAC>((*cur_var_id_)++); } // check if variable is a global variable bool IsGlobalVar(const TACPtr &var) { return entry_->vars.find(var) != entry_->vars.end(); } private: std::size_t *cur_var_id_; const FuncInfo *entry_; }; using PassPtr = std::unique_ptr<PassBase>; // pass info class PassInfo { public: PassInfo(std::string_view name, PassPtr pass, unsigned int min_opt_level) : name_(name), pass_(std::move(pass)), min_opt_level_(min_opt_level) {} virtual ~PassInfo() = default; const std::string_view name() const { return name_; } const PassPtr &pass() const { return pass_; } unsigned int min_opt_level() const { return min_opt_level_; } private: std::string_view name_; PassPtr pass_; unsigned int min_opt_level_; }; // TAC IR optimizer class Optimizer { public: Optimizer() : opt_level_(0), funcs_(nullptr) {} // register a new function pass static void RegisterPass(PassInfo *info) { passes_.push_back(info); } // run function passes on function info map void Run(); // show info of optimization void ShowInfo(std::ostream &os); // set optimization level (0-2) void set_opt_level(unsigned int opt_level) { opt_level_ = opt_level; } // set function info map void set_funcs(FuncInfoMap *funcs) { funcs_ = funcs; } // set pointer of current variable ID void set_cur_var_id(std::size_t *cur_var_id); // set pointer of entry function's info void set_entry_func(const FuncInfo *entry); // get optimization level unsigned int opt_level() const { return opt_level_; } private: static std::list<PassInfo *> passes_; unsigned int opt_level_; FuncInfoMap *funcs_; }; // helper class for registering a pass template <typename T> class RegisterPass : public PassInfo { public: RegisterPass(std::string_view name, unsigned int min_opt_level) : PassInfo(name, std::make_unique<T>(), min_opt_level) { Optimizer::RegisterPass(this); } }; } // namespace tinylang::back::tac #endif // TINYLANG_BACK_TAC_OPTIMIZER_H_
3,387
C++
.h
100
31.06
76
0.707721
ustb-owl/TinyMIPS
34
6
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,828
tac.h
ustb-owl_TinyMIPS/src/compiler/back/tac/ir/tac.h
#ifndef TINYLANG_BACK_TAC_IR_TAC_H_ #define TINYLANG_BACK_TAC_IR_TAC_H_ #include <memory> #include <vector> #include <ostream> #include <cstddef> namespace tinylang::back::tac { // forward declaration class TACBase; using TACPtr = std::shared_ptr<TACBase>; using TACPtrList = std::vector<TACPtr>; // forward declaration of pass & code generator class PassBase; class CodeGenerator; // binary operators enum class BinaryOp { Add, Sub, Mul, UMul, Div, UDiv, Mod, UMod, Equal, NotEqual, Less, ULess, LessEq, ULessEq, Great, UGreat, GreatEq, UGreatEq, LogicAnd, LogicOr, And, Or, Xor, Shl, AShr, LShr, }; // unary operators enum class UnaryOp { Negate, LogicNot, Not, AddressOf, SExt, ZExt, Trunc, }; // base class for all tree-address code class TACBase { public: virtual ~TACBase() = default; // dump the content of TAC to output stream virtual void Dump(std::ostream &os) = 0; // run optimization on current TAC virtual void RunPass(PassBase &pass) = 0; // run code generation on current TAC virtual void GenerateCode(CodeGenerator &gen) = 0; // return true if current TAC is constant virtual bool IsConst() const = 0; }; // binary operations class BinaryTAC : public TACBase { public: BinaryTAC(BinaryOp op, const TACPtr &lhs, const TACPtr &rhs, const TACPtr &dest) : op_(op), lhs_(lhs), rhs_(rhs), dest_(dest) {} void Dump(std::ostream &os) override; void RunPass(PassBase &pass) override; void GenerateCode(CodeGenerator &gen) override; bool IsConst() const override { return lhs_->IsConst() && rhs_->IsConst(); } void set_lhs(const TACPtr &lhs) { lhs_ = lhs; } void set_rhs(const TACPtr &rhs) { rhs_ = rhs; } void set_dest(const TACPtr &dest) { dest_ = dest; } BinaryOp op() const { return op_; } const TACPtr &lhs() const { return lhs_; } const TACPtr &rhs() const { return rhs_; } const TACPtr &dest() const { return dest_; } private: BinaryOp op_; TACPtr lhs_, rhs_, dest_; }; // unary operations class UnaryTAC : public TACBase { public: UnaryTAC(UnaryOp op, const TACPtr &opr, const TACPtr &dest) : op_(op), opr_(opr), dest_(dest) {} void Dump(std::ostream &os) override; void RunPass(PassBase &pass) override; void GenerateCode(CodeGenerator &gen) override; bool IsConst() const override { return opr_->IsConst(); } void set_opr(const TACPtr &opr) { opr_ = opr; } void set_dest(const TACPtr &dest) { dest_ = dest; } UnaryOp op() const { return op_; } const TACPtr &opr() const { return opr_; } const TACPtr &dest() const { return dest_; } private: UnaryOp op_; TACPtr opr_, dest_; }; // load from memory class LoadTAC : public TACBase { public: LoadTAC(const TACPtr &addr, const TACPtr &dest, bool is_unsigned, std::size_t size) : addr_(addr), dest_(dest), is_unsigned_(is_unsigned), size_(size) {} void Dump(std::ostream &os) override; void RunPass(PassBase &pass) override; void GenerateCode(CodeGenerator &gen) override; bool IsConst() const override { return false; } void set_addr(const TACPtr &addr) { addr_ = addr; } void set_dest(const TACPtr &dest) { dest_ = dest; } const TACPtr &addr() const { return addr_; } const TACPtr &dest() const { return dest_; } bool is_unsigned() const { return is_unsigned_; } std::size_t size() const { return size_; } private: TACPtr addr_, dest_; bool is_unsigned_; std::size_t size_; }; // store to memory class StoreTAC : public TACBase { public: StoreTAC(const TACPtr &value, const TACPtr &addr, std::size_t size) : value_(value), addr_(addr), size_(size) {} void Dump(std::ostream &os) override; void RunPass(PassBase &pass) override; void GenerateCode(CodeGenerator &gen) override; bool IsConst() const override { return false; } void set_value(const TACPtr &value) { value_ = value; } void set_addr(const TACPtr &addr) { addr_ = addr; } const TACPtr &value() const { return value_; } const TACPtr &addr() const { return addr_; } std::size_t size() const { return size_; } private: TACPtr value_, addr_; std::size_t size_; }; // argument setter class ArgSetTAC : public TACBase { public: ArgSetTAC(std::size_t pos, const TACPtr &value) : pos_(pos), value_(value) {} void Dump(std::ostream &os) override; void RunPass(PassBase &pass) override; void GenerateCode(CodeGenerator &gen) override; bool IsConst() const override { return false; } void set_value(const TACPtr &value) { value_ = value; } std::size_t pos() const { return pos_; } const TACPtr &value() const { return value_; } private: std::size_t pos_; TACPtr value_; }; // jump to label class JumpTAC : public TACBase { public: JumpTAC(const TACPtr &dest) : dest_(dest) {} void Dump(std::ostream &os) override; void RunPass(PassBase &pass) override; void GenerateCode(CodeGenerator &gen) override; bool IsConst() const override { return false; } const TACPtr &dest() const { return dest_; } private: TACPtr dest_; }; // branch to labels class BranchTAC : public TACBase { public: BranchTAC(const TACPtr &cond, const TACPtr &dest) : cond_(cond), dest_(dest) {} void Dump(std::ostream &os) override; void RunPass(PassBase &pass) override; void GenerateCode(CodeGenerator &gen) override; bool IsConst() const override { return cond_->IsConst(); } void set_cond(const TACPtr &cond) { cond_ = cond; } const TACPtr &cond() const { return cond_; } const TACPtr &dest() const { return dest_; } private: TACPtr cond_, dest_; }; // function call class CallTAC : public TACBase { public: CallTAC(const TACPtr &func, const TACPtr &dest) : func_(func), dest_(dest) {} void Dump(std::ostream &os) override; void RunPass(PassBase &pass) override; void GenerateCode(CodeGenerator &gen) override; bool IsConst() const override { return false; } void set_dest(const TACPtr &dest) { dest_ = dest; } const TACPtr &func() const { return func_; } const TACPtr &dest() const { return dest_; } private: TACPtr func_, dest_; }; // return from function class ReturnTAC : public TACBase { public: ReturnTAC(const TACPtr &value) : value_(value) {} void Dump(std::ostream &os) override; void RunPass(PassBase &pass) override; void GenerateCode(CodeGenerator &gen) override; bool IsConst() const override { return false; } void set_value(const TACPtr &value) { value_ = value; } const TACPtr &value() const { return value_; } private: TACPtr value_; }; // variable assign class AssignTAC : public TACBase { public: AssignTAC(const TACPtr &value, const TACPtr &var) : value_(value), var_(var) {} void Dump(std::ostream &os) override; void RunPass(PassBase &pass) override; void GenerateCode(CodeGenerator &gen) override; bool IsConst() const override { return value_->IsConst(); } void set_value(const TACPtr &value) { value_ = value; } const TACPtr &value() const { return value_; } const TACPtr &var() const { return var_; } private: TACPtr value_, var_; }; // variable reference class VarRefTAC : public TACBase { public: VarRefTAC(std::size_t id) : id_(id) {} void Dump(std::ostream &os) override; void RunPass(PassBase &pass) override; void GenerateCode(CodeGenerator &gen) override; bool IsConst() const override { return false; } std::size_t id() const { return id_; } private: std::size_t id_; }; // data reference (from data segment) class DataTAC : public TACBase { public: DataTAC(std::size_t id) : id_(id) {} void Dump(std::ostream &os) override; void RunPass(PassBase &pass) override; void GenerateCode(CodeGenerator &gen) override; bool IsConst() const override { return true; } std::size_t id() const { return id_; } private: std::size_t id_; }; // label class LabelTAC : public TACBase { public: LabelTAC(std::size_t id) : id_(id) {} void Dump(std::ostream &os) override; void RunPass(PassBase &pass) override; void GenerateCode(CodeGenerator &gen) override; bool IsConst() const override { return false; } std::size_t id() const { return id_; } private: std::size_t id_; }; // argument getter class ArgGetTAC : public TACBase { public: ArgGetTAC(std::size_t pos) : pos_(pos) {} void Dump(std::ostream &os) override; void RunPass(PassBase &pass) override; void GenerateCode(CodeGenerator &gen) override; bool IsConst() const override { return false; } std::size_t pos() const { return pos_; } private: std::size_t pos_; }; // number constant class NumberTAC : public TACBase { public: NumberTAC(unsigned int num) : num_(num) {} void Dump(std::ostream &os) override; void RunPass(PassBase &pass) override; void GenerateCode(CodeGenerator &gen) override; bool IsConst() const override { return true; } unsigned int num() const { return num_; } private: unsigned int num_; }; } // namespace tinylang::back::tac #endif // TINYLANG_BACK_TAC_IR_TAC_H_
8,959
C++
.h
268
30.518657
75
0.69986
ustb-owl/TinyMIPS
34
6
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,829
tmgen.h
ustb-owl_TinyMIPS/src/compiler/back/tac/codegen/tmgen.h
#ifndef TINYLANG_BACK_TAC_CODEGEN_TMGEN_H_ #define TINYLANG_BACK_TAC_CODEGEN_TMGEN_H_ #include <ostream> #include <list> #include <utility> #include <string_view> #include "back/tac/codegen/tinymips.h" namespace tinylang::back::tac { class TinyMIPSAsmGen { public: TinyMIPSAsmGen() { Reset(); } // reset internal state void Reset() { asms_.clear(); is_reordered_ = false; } // push a new assembly template <typename... Args> void PushAsm(Args &&... args) { asms_.emplace_back(std::forward<Args>(args)...); } // push 'nop' pseudo instruction void PushNop(); // push a label void PushLabel(std::string_view label); // push 'move' pseudo instruction void PushMove(TinyMIPSReg dest, TinyMIPSReg src); // push 'li' pseudo instruction void PushLoadImm(TinyMIPSReg dest, std::uint32_t imm); // push 'la' pseudo instruction void PushLoadImm(TinyMIPSReg dest, std::string_view imm_str); // push a new branch instruction void PushBranch(TinyMIPSReg cond, std::string_view label); // push a new jump instruction void PushJump(std::string_view label); // push a new jump instruction void PushJump(TinyMIPSReg dest); // dump assembly code to stream void Dump(std::ostream &os, std::string_view indent); private: // reorder all jumps (make delay slots) void ReorderJump(); std::list<TinyMIPSAsm> asms_; bool is_reordered_; }; } // namespace tinylang::back::tac #endif // TINYLANG_BACK_TAC_CODEGEN_TMGEN_H_
1,479
C++
.h
47
28.659574
63
0.721323
ustb-owl/TinyMIPS
34
6
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,830
tinymips.h
ustb-owl_TinyMIPS/src/compiler/back/tac/codegen/tinymips.h
#ifndef TINYLANG_BACK_TAC_CODEGEN_TINYMIPS_H_ #define TINYLANG_BACK_TAC_CODEGEN_TINYMIPS_H_ #include <ostream> #include <string> #include <string_view> #include <cstdint> namespace tinylang::back::tac { enum class TinyMIPSOpcode : std::uint8_t { ADDU, ADDIU, SUBU, SLT, SLTU, AND, LUI, OR, XOR, SLL, SLLV, SRAV, SRLV, BEQ, BNE, JAL, JALR, LB, LBU, LW, SB, SW, NOP, LABEL, }; enum class TinyMIPSReg : std::uint8_t { Zero, AT, V0, V1, A0, A1, A2, A3, T0, T1, T2, T3, T4, T5, T6, T7, S0, S1, S2, S3, S4, S5, S6, S7, T8, T9, K0, K1, GP, SP, FP, RA, }; struct TinyMIPSAsm { TinyMIPSAsm(TinyMIPSOpcode op) : opcode(op) {} TinyMIPSAsm(TinyMIPSOpcode op, TinyMIPSReg dest) : opcode(op), dest(dest) {} TinyMIPSAsm(TinyMIPSOpcode op, TinyMIPSReg dest, TinyMIPSReg opr1, TinyMIPSReg opr2) : opcode(op), dest(dest), opr1(opr1), opr2(opr2) {} TinyMIPSAsm(TinyMIPSOpcode op, TinyMIPSReg dest, std::int16_t imm) : opcode(op), dest(dest), imm(imm) {} TinyMIPSAsm(TinyMIPSOpcode op, TinyMIPSReg dest, std::string_view imm_str) : opcode(op), dest(dest), imm_str(imm_str) {} TinyMIPSAsm(TinyMIPSOpcode op, TinyMIPSReg dest, TinyMIPSReg opr1, std::int16_t imm) : opcode(op), dest(dest), opr1(opr1), imm(imm) {} TinyMIPSAsm(TinyMIPSOpcode op, TinyMIPSReg dest, TinyMIPSReg opr1, std::string_view imm_str) : opcode(op), dest(dest), opr1(opr1), imm_str(imm_str) {} TinyMIPSAsm(TinyMIPSOpcode op, std::uint32_t index) : opcode(op), index(index) {} TinyMIPSAsm(TinyMIPSOpcode op, std::string_view index_str) : opcode(op), imm_str(index_str) {} TinyMIPSOpcode opcode; TinyMIPSReg dest, opr1, opr2; std::int16_t imm; std::string imm_str; std::uint32_t index; }; } // namespace tinylang::back::tac #endif // TINYLANG_BACK_TAC_CODEGEN_TINYMIPS_H_
1,874
C++
.h
54
30.851852
76
0.6766
ustb-owl/TinyMIPS
34
6
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,831
varalloc.h
ustb-owl_TinyMIPS/src/compiler/back/tac/codegen/varalloc.h
#ifndef TINYMIPS_BACK_TAC_CODEGEN_VARALLOC_H_ #define TINYMIPS_BACK_TAC_CODEGEN_VARALLOC_H_ #include <variant> #include <functional> #include <set> #include <map> #include <unordered_map> #include <vector> #include <cstddef> #include <cassert> #include "back/tac/optimizer.h" #include "back/tac/codegen/tinymips.h" namespace tinylang::back::tac { // allocate variables to registers or slots on stack // using linear scan register allocation // reference: M. Poletto, V. Sarkar, Linear Scan Register Allocation class VarAllocationPass : public PassBase { public: // offset relative to local variable area or register using VarPos = std::variant<std::size_t, TinyMIPSReg>; // set of all saved registers using SavedSet = std::set<TinyMIPSReg, std::greater<TinyMIPSReg>>; VarAllocationPass() { set_cur_var_id(nullptr); } bool Run(FuncInfo &func) override; void RunOn(BinaryTAC &tac) override; void RunOn(UnaryTAC &tac) override; void RunOn(LoadTAC &tac) override; void RunOn(StoreTAC &tac) override; void RunOn(ArgSetTAC &tac) override; void RunOn(BranchTAC &tac) override; void RunOn(CallTAC &tac) override; void RunOn(ReturnTAC &tac) override; void RunOn(AssignTAC &tac) override; // get allocated position of local variables const VarPos &GetPosition(const TACPtr &var) const { auto it = var_pos_.find(var); assert(it != var_pos_.end()); return it->second; } // size of save area in stack frame std::size_t save_area_size() const { return saved_reg_.size() * 4; } // return the set of all saved registers const SavedSet &saved_reg() const { return saved_reg_; } // size of local area in stack frame std::size_t local_area_size() const { return local_slot_count_ * 4; } // size of argument area in stack frame std::size_t arg_area_size() const { return max_arg_count_ * 4; } private: struct LiveInterval { std::size_t start_pos; std::size_t end_pos; bool can_alloc_reg; bool must_preserve; }; struct LiveIntervalStartCmp { bool operator()(const LiveInterval *lhs, const LiveInterval *rhs) const { return lhs->start_pos < rhs->start_pos; } }; struct LiveIntervalEndCmp { bool operator()(const LiveInterval *lhs, const LiveInterval *rhs) const { return lhs->end_pos < rhs->end_pos; } }; using IntervalStartMap = std::multimap<const LiveInterval *, TACPtr, LiveIntervalStartCmp>; using IntervalEndMap = std::multimap<const LiveInterval *, TACPtr, LiveIntervalEndCmp>; // reset internal state void Reset(); // initialize free registers void InitFreeReg(bool is_preserved); // log live interval info of specific variable void LogLiveInterval(const TACPtr &var); // run variable allocation void RunVarAlloc(); // run LSRA void LinearScanAlloc(const IntervalStartMap &start_map, bool save); // expire old allocated variables void ExpireOldIntervals(IntervalEndMap &active, const LiveInterval *i); // spill specific variable void SpillAtInterval(IntervalEndMap &active, const LiveInterval *i, const TACPtr &var); // return a new slot index in local area std::size_t GetNewSlot(); // live interval of variables std::unordered_map<TACPtr, LiveInterval> live_intervals_; // allocated position of all variables std::unordered_map<TACPtr, VarPos> var_pos_; // all free registers std::vector<TinyMIPSReg> free_reg_; // current position (used for live interval analysis) std::size_t cur_pos_; // position of last function call (used for live interval analysis) std::size_t last_call_pos_; // set of all saved registers SavedSet saved_reg_; // slot count in local area std::size_t local_slot_count_; // max argument count std::size_t max_arg_count_; }; } // namespace tinylang::back::tac #endif // TINYMIPS_BACK_TAC_CODEGEN_VARALLOC_H_
3,902
C++
.h
106
33.150943
73
0.720296
ustb-owl/TinyMIPS
34
6
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,832
ir.h
ustb-owl_TinyMIPS/src/compiler/back/ssa/ir.h
#ifndef TINYLANG_BACK_SSA_IR_H_ #define TINYLANG_BACK_SSA_IR_H_ #include <utility> #include <cassert> #include "back/ir.h" #include "back/ssa/ir/ssa.h" namespace tinylang::back::ssa { class SSAIR : public IRInterface { public: SSAIR(const SSAPtr &value) : value_(value) { assert(value_ != nullptr); } const std::any value() const override { return value_; } private: SSAPtr value_; }; // make a new SSA IR template <typename T, typename... Args> inline IRPtr MakeSSA(Args &&... args) { auto ssa = std::make_shared<T>(std::forward(args)...); return std::make_shared<SSAIR>(ssa); } // cast IR to SSA IR inline SSAPtr SSACast(const IRPtr &ir) { return IRCast<SSAPtr>(ir); } } // namespace tinylang::back::ssa #endif // TINYLANG_BACK_SSA_IR_H_
766
C++
.h
26
27.538462
75
0.705479
ustb-owl/TinyMIPS
34
6
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,833
usedef.h
ustb-owl_TinyMIPS/src/compiler/back/ssa/ir/usedef.h
#ifndef TINYLANG_BACK_SSA_IR_USEDEF_H_ #define TINYLANG_BACK_SSA_IR_USEDEF_H_ // reference: LLVM version 1.3 #include <memory> #include <vector> #include <ostream> #include <forward_list> #include <cstddef> #include <cassert> namespace tinylang::back::ssa { // interafce of all SSAs class SSAInterface { public: virtual ~SSAInterface() = default; // dump the content of SSA value to output stream virtual void Dump(std::ostream &os) = 0; }; class Value; class User; class Use; using SSAPtr = std::shared_ptr<Value>; using SSAPtrList = std::vector<SSAPtr>; // a SSA value class Value : public SSAInterface { public: Value() {} // add a use reference to current value void AddUse(Use *use) { uses_.push_front(use); } // remove use reference from current value void RemoveUse(Use *use) { uses_.remove(use); } // replace current value by another value void ReplaceBy(const SSAPtr &value); const std::forward_list<Use *> &uses() const { return uses_; } private: // singly-linked list for 'Use' std::forward_list<Use *> uses_; }; // a bidirectional reference between SSA users and values class Use { public: explicit Use(const SSAPtr &value, User *user) : value_(value), user_(user) {} // copy constructor Use(const Use &use) : value_(use.value_), user_(use.user_) { if (value_) value_->AddUse(this); } // move constructor Use(Use &&use) noexcept : value_(std::move(use.value_)), user_(use.user_) { if (value_) { value_->RemoveUse(&use); value_->AddUse(this); } } // destructor ~Use() { if (value_) value_->RemoveUse(this); } void set_value(const SSAPtr &value); const SSAPtr &value() const { return value_; } User *user() const { return user_; } private: SSAPtr value_; User *user_; }; // a SSA user which can use other values class User : public Value { public: User() : Value() {} // preallocate some space for values void reserve(std::size_t size) { operands_.reserve(size); } // add new value to current user void push_back(const SSAPtr &value) { operands_.push_back(Use(value, this)); } // access value in current user Use &operator[](std::size_t pos) { return operands_[pos]; } // access value in current user (const) const Use &operator[](std::size_t pos) const { return operands_[pos]; } // begin iterator auto begin() { return operands_.begin(); } // end iterator auto end() { return operands_.end(); } // count of elements in current user std::size_t size() const { return operands_.size(); } // return true if no value in current user bool empty() const { return operands_.empty(); } private: std::vector<Use> operands_; }; } // namespace tinylang::back::ssa #endif // TINYLANG_BACK_SSA_IR_USEDEF_H_
2,781
C++
.h
93
27.043011
73
0.68192
ustb-owl/TinyMIPS
34
6
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,834
ssa.h
ustb-owl_TinyMIPS/src/compiler/back/ssa/ir/ssa.h
#ifndef TINYLANG_BACK_SSA_IR_SSA_H_ #define TINYLANG_BACK_SSA_IR_SSA_H_ #include <list> #include <cstddef> #include "back/ssa/ir/usedef.h" namespace tinylang::back::ssa { // constant number/pointer value class NumberSSA : public Value { public: NumberSSA(unsigned int num, std::size_t size) : num_(num), size_(size) {} // private: unsigned int num_; std::size_t size_; }; // array (static) class ArraySSA : public User { public: ArraySSA(std::size_t length) { reserve(length); } // private: // }; // variable definition class VariableSSA : public User { public: VariableSSA(const SSAPtr &value) { reserve(1); push_back(value); } // private: // }; // phi node class PhiSSA : public User { public: PhiSSA() {} // TODO // private: // }; // argument getter class ArgGetSSA : public Value { public: ArgGetSSA(std::size_t arg_pos) : arg_pos_(arg_pos) {} // private: std::size_t arg_pos_; }; // argument setter class ArgSetSSA : public User { public: ArgSetSSA(std::size_t arg_pos, const SSAPtr &value) : arg_pos_(arg_pos) { reserve(1); push_back(value); } // private: std::size_t arg_pos_; }; // load from memory class LoadSSA : public User { public: LoadSSA(const SSAPtr &base, const SSAPtr &offset, bool is_unsigned) : is_unsigned_(is_unsigned) { reserve(2); push_back(base); push_back(offset); } // private: bool is_unsigned_; }; // store to memory class StoreSSA : public User { public: StoreSSA(const SSAPtr &base, const SSAPtr &offset) { reserve(2); push_back(base); push_back(offset); } // private: // }; // basic block class BlockSSA : public User { public: BlockSSA() {} // TODO: add instructions // private: std::list<SSAPtr> insts_; }; // function call class CallSSA : public User { public: CallSSA(const SSAPtr &block) { push_back(block); } // TODO: add argument setters // private: // }; // jump to another basic block class JumpSSA : public User { public: JumpSSA(const SSAPtr &block) { reserve(1); push_back(block); } JumpSSA(const SSAPtr &cond, const SSAPtr &true_block, const SSAPtr &false_block) { reserve(3); push_back(cond); push_back(true_block); push_back(false_block); } // private: // }; // return from function (basic block) class ReturnSSA : public User { public: ReturnSSA() {} ReturnSSA(const SSAPtr &value) { reserve(1); push_back(value); } // private: // }; // basic operations class TriSSA : public User { public: enum class Operator { Add, Sub, Mul, Div, Mod, Equal, NotEqual, Less, LessEqual, Great, GreatEqual, LogicAnd, LogicOr, LogicNot, And, Or, Not, Xor, Shl, Shr, }; TriSSA(Operator op, const SSAPtr &opr) : op_(op) { reserve(1); push_back(opr); } TriSSA(Operator op, const SSAPtr &lhs, const SSAPtr &rhs) : op_(op) { reserve(2); push_back(lhs); push_back(rhs); } // private: Operator op_; }; } // namespace tinylang::back::ssa #endif // TINYLANG_BACK_SSA_IR_SSA_H_
3,113
C++
.h
159
16.616352
75
0.661734
ustb-owl/TinyMIPS
34
6
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,835
ast.h
ustb-owl_TinyMIPS/src/compiler/define/ast.h
#ifndef TINYLANG_DEFINE_AST_H_ #define TINYLANG_DEFINE_AST_H_ #include <memory> #include <vector> #include <string> #include <utility> #include <ostream> #include <cstdint> #include "define/type.h" #include "front/lexer.h" #include "front/analyzer.h" #include "back/irbuilder.h" namespace tinylang::define { // definition of base class of all ASTs class BaseAST { public: virtual ~BaseAST() = default; // dump the content of AST to output stream virtual void Dump(std::ostream &os) = 0; // run sematic analysis on current AST virtual TypePtr SemaAnalyze(front::Analyzer &ana) = 0; // build IR by current AST virtual back::IRPtr GenerateIR(back::IRBuilder &irb) = 0; // return true if current AST is a memory access operation virtual bool IsMemAccess() const = 0; void set_line_pos(unsigned int line_pos) { line_pos_ = line_pos; } const TypePtr &set_type(const TypePtr &type) { return type_ = type; } unsigned int line_pos() const { return line_pos_; } const TypePtr &type() const { return type_; } private: unsigned int line_pos_; TypePtr type_; }; using ASTPtr = std::unique_ptr<BaseAST>; using ASTPtrList = std::vector<ASTPtr>; // variable definition class VarDefAST : public BaseAST { public: VarDefAST(ASTPtrList defs) : defs_(std::move(defs)) {} void Dump(std::ostream &os) override; TypePtr SemaAnalyze(front::Analyzer &ana) override; back::IRPtr GenerateIR(back::IRBuilder &irb) override; bool IsMemAccess() const override { return false; } private: ASTPtrList defs_; }; // constant definition class LetDefAST : public BaseAST { public: LetDefAST(ASTPtrList defs) : defs_(std::move(defs)) {} void Dump(std::ostream &os) override; TypePtr SemaAnalyze(front::Analyzer &ana) override; back::IRPtr GenerateIR(back::IRBuilder &irb) override; bool IsMemAccess() const override { return false; } private: ASTPtrList defs_; }; // function definition class FunDefAST : public BaseAST { public: FunDefAST(const std::string &id, ASTPtrList args, ASTPtr type, ASTPtr body) : id_(id), args_(std::move(args)), type_(std::move(type)), body_(std::move(body)) {} void Dump(std::ostream &os) override; TypePtr SemaAnalyze(front::Analyzer &ana) override; back::IRPtr GenerateIR(back::IRBuilder &irb) override; bool IsMemAccess() const override { return false; } private: std::string id_; ASTPtrList args_; ASTPtr type_, body_; }; // function call class FunCallAST : public BaseAST { public: FunCallAST(const std::string &id, ASTPtrList args) : id_(id), args_(std::move(args)) {} void Dump(std::ostream &os) override; TypePtr SemaAnalyze(front::Analyzer &ana) override; back::IRPtr GenerateIR(back::IRBuilder &irb) override; bool IsMemAccess() const override { return false; } private: std::string id_; ASTPtrList args_; }; // if-else statement class IfAST : public BaseAST { public: IfAST(ASTPtr cond, ASTPtr then, ASTPtr else_then) : cond_(std::move(cond)), then_(std::move(then)), else_then_(std::move(else_then)) {} void Dump(std::ostream &os) override; TypePtr SemaAnalyze(front::Analyzer &ana) override; back::IRPtr GenerateIR(back::IRBuilder &irb) override; bool IsMemAccess() const override { return false; } private: ASTPtr cond_, then_, else_then_; }; // while statement class WhileAST : public BaseAST { public: WhileAST(ASTPtr cond, ASTPtr body) : cond_(std::move(cond)), body_(std::move(body)) {} void Dump(std::ostream &os) override; TypePtr SemaAnalyze(front::Analyzer &ana) override; back::IRPtr GenerateIR(back::IRBuilder &irb) override; bool IsMemAccess() const override { return false; } private: ASTPtr cond_, body_; }; // control statements (break, continue, return) class ControlAST : public BaseAST { public: ControlAST(front::Keyword type, ASTPtr expr) : type_(type), expr_(std::move(expr)) {} void Dump(std::ostream &os) override; TypePtr SemaAnalyze(front::Analyzer &ana) override; back::IRPtr GenerateIR(back::IRBuilder &irb) override; bool IsMemAccess() const override { return false; } private: front::Keyword type_; ASTPtr expr_; }; // variable definition element class VarElemAST : public BaseAST { public: VarElemAST(const std::string &id, ASTPtr type, ASTPtr init) : id_(id), type_(std::move(type)), init_(std::move(init)) {} void Dump(std::ostream &os) override; TypePtr SemaAnalyze(front::Analyzer &ana) override; back::IRPtr GenerateIR(back::IRBuilder &irb) override; bool IsMemAccess() const override { return false; } private: std::string id_; ASTPtr type_, init_; }; // constant definition element class LetElemAST : public BaseAST { public: LetElemAST(const std::string &id, ASTPtr type, ASTPtr init) : id_(id), type_(std::move(type)), init_(std::move(init)) {} void Dump(std::ostream &os) override; TypePtr SemaAnalyze(front::Analyzer &ana) override; back::IRPtr GenerateIR(back::IRBuilder &irb) override; bool IsMemAccess() const override { return false; } private: std::string id_; ASTPtr type_, init_; }; // type declaration class TypeAST : public BaseAST { public: TypeAST(front::Keyword type, unsigned int ptr) : type_(type), ptr_(ptr) {} void Dump(std::ostream &os) override; TypePtr SemaAnalyze(front::Analyzer &ana) override; back::IRPtr GenerateIR(back::IRBuilder &irb) override; bool IsMemAccess() const override { return false; } private: front::Keyword type_; unsigned int ptr_; }; // argument definition class ArgElemAST : public BaseAST { public: ArgElemAST(const std::string &id, ASTPtr type) : id_(id), type_(std::move(type)) {} void Dump(std::ostream &os) override; TypePtr SemaAnalyze(front::Analyzer &ana) override; back::IRPtr GenerateIR(back::IRBuilder &irb) override; bool IsMemAccess() const override { return false; } private: std::string id_; ASTPtr type_; }; // statement block class BlockAST : public BaseAST { public: BlockAST(ASTPtrList stmts) : stmts_(std::move(stmts)) {} void Dump(std::ostream &os) override; TypePtr SemaAnalyze(front::Analyzer &ana) override; back::IRPtr GenerateIR(back::IRBuilder &irb) override; bool IsMemAccess() const override { return false; } private: ASTPtrList stmts_; }; // binary expression class BinaryAST : public BaseAST { public: BinaryAST(front::Operator op, ASTPtr lhs, ASTPtr rhs) : op_(op), lhs_(std::move(lhs)), rhs_(std::move(rhs)) {} void Dump(std::ostream &os) override; TypePtr SemaAnalyze(front::Analyzer &ana) override; back::IRPtr GenerateIR(back::IRBuilder &irb) override; bool IsMemAccess() const override { return false; } private: front::Operator op_; ASTPtr lhs_, rhs_; }; // type casting expression class CastAST : public BaseAST { public: CastAST(ASTPtr expr, ASTPtr type) : expr_(std::move(expr)), type_(std::move(type)) {} void Dump(std::ostream &os) override; TypePtr SemaAnalyze(front::Analyzer &ana) override; back::IRPtr GenerateIR(back::IRBuilder &irb) override; bool IsMemAccess() const override { return false; } private: ASTPtr expr_, type_; }; // unary expression class UnaryAST : public BaseAST { public: UnaryAST(front::Operator op, ASTPtr opr) : op_(op), opr_(std::move(opr)) {} void Dump(std::ostream &os) override; TypePtr SemaAnalyze(front::Analyzer &ana) override; back::IRPtr GenerateIR(back::IRBuilder &irb) override; bool IsMemAccess() const override { return op_ == front::Operator::Mul; } private: front::Operator op_; ASTPtr opr_; }; // identifier value class IdAST : public BaseAST { public: IdAST(const std::string &id) : id_(id) {} void Dump(std::ostream &os) override; TypePtr SemaAnalyze(front::Analyzer &ana) override; back::IRPtr GenerateIR(back::IRBuilder &irb) override; bool IsMemAccess() const override { return false; } private: std::string id_; }; // number value class NumAST : public BaseAST { public: NumAST(unsigned int num) : num_(num) {} void Dump(std::ostream &os) override; TypePtr SemaAnalyze(front::Analyzer &ana) override; back::IRPtr GenerateIR(back::IRBuilder &irb) override; bool IsMemAccess() const override { return false; } private: unsigned int num_; }; // string value class StringAST : public BaseAST { public: StringAST(const std::string &str) : str_(str) {} void Dump(std::ostream &os) override; TypePtr SemaAnalyze(front::Analyzer &ana) override; back::IRPtr GenerateIR(back::IRBuilder &irb) override; bool IsMemAccess() const override { return false; } private: std::string str_; }; // character value class CharAST : public BaseAST { public: CharAST(std::uint8_t c) : c_(c) {} void Dump(std::ostream &os) override; TypePtr SemaAnalyze(front::Analyzer &ana) override; back::IRPtr GenerateIR(back::IRBuilder &irb) override; bool IsMemAccess() const override { return false; } private: std::uint8_t c_; }; // array value class ArrayAST : public BaseAST { public: ArrayAST(ASTPtrList elems) : elems_(std::move(elems)) {} void Dump(std::ostream &os) override; TypePtr SemaAnalyze(front::Analyzer &ana) override; back::IRPtr GenerateIR(back::IRBuilder &irb) override; bool IsMemAccess() const override { return false; } private: ASTPtrList elems_; }; // indexing class IndexAST : public BaseAST { public: IndexAST(const std::string &id, ASTPtr index) : id_(id), index_(std::move(index)) {} void Dump(std::ostream &os) override; TypePtr SemaAnalyze(front::Analyzer &ana) override; back::IRPtr GenerateIR(back::IRBuilder &irb) override; bool IsMemAccess() const override { return true; } private: std::string id_; ASTPtr index_; }; } // namespace tinylang::define #endif // TINYLANG_DEFINE_AST_H_
9,787
C++
.h
294
30.513605
76
0.722051
ustb-owl/TinyMIPS
34
6
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,836
symbol.h
ustb-owl_TinyMIPS/src/compiler/define/symbol.h
#ifndef TINYLANG_DEFINE_SYMBOL_H_ #define TINYLANG_DEFINE_SYMBOL_H_ #include <string> #include "define/type.h" #include "util/nested.h" namespace tinylang::define { // scope environment (symbol table) using EnvPtr = util::NestedMapPtr<std::string, TypePtr>; // make a new environment inline EnvPtr MakeEnvironment() { return util::MakeNestedMap<std::string, TypePtr>(); } // make a new environment (with outer environment) inline EnvPtr MakeEnvironment(const EnvPtr &outer) { return util::MakeNestedMap<std::string, TypePtr>(outer); } } // namespace tinylang::define #endif // TINYLANG_DEFINE_SYMBOL_H_
617
C++
.h
18
32.611111
58
0.771574
ustb-owl/TinyMIPS
34
6
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,837
type.h
ustb-owl_TinyMIPS/src/compiler/define/type.h
#ifndef TINYLANG_DEFINE_TYPE_H_ #define TINYLANG_DEFINE_TYPE_H_ #include <memory> #include <vector> #include <optional> #include <cstddef> #include <cassert> #include "front/lexer.h" namespace tinylang::define { // size of machine word length constexpr std::size_t kTypeSizeWordLength = 4; // definition of base class of all types class BaseType; using TypePtr = std::shared_ptr<BaseType>; using TypePtrList = std::vector<TypePtr>; class BaseType { public: virtual ~BaseType() = default; // return true if is right value virtual bool IsRightValue() const = 0; // return true if is void type virtual bool IsVoid() const = 0; // return true if is integer type virtual bool IsInteger() const = 0; // return true if is unsigned type virtual bool IsUnsigned() const = 0; // return true if is constant type virtual bool IsConst() const = 0; // return true if is pointer type virtual bool IsPointer() const = 0; // return true if is function type virtual bool IsFunction() const = 0; // return true if left value which is current type // can accept the right value which is specific type virtual bool CanAccept(const TypePtr &type) const = 0; // return true if current type can be casted to specific type virtual bool CanCastTo(const TypePtr &type) const = 0; // return the size of current type virtual std::size_t GetSize() const = 0; // return the type of arguments of a function call virtual std::optional<TypePtrList> GetArgsType() const = 0; // return the return type of a function call virtual TypePtr GetReturnType(const TypePtrList &args) const = 0; // return the dereferenced type of current type virtual TypePtr GetDerefedType() const = 0; // return the deconsted type of current type virtual TypePtr GetDeconstedType() const = 0; // return a new type with specific value type (left/right) virtual TypePtr GetRightValue(bool is_right) = 0; }; class PlainType : public BaseType { public: enum class Type { Void, Int32, Int8, UInt32, UInt8, }; PlainType(Type type, bool is_right) : type_(type), is_right_(is_right) {} bool IsRightValue() const override { return is_right_; } bool IsVoid() const override { return type_ == Type::Void; } bool IsInteger() const override { return type_ != Type::Void; } bool IsUnsigned() const override { return type_ == Type::UInt32 || type_ == Type::UInt8; } bool IsConst() const override { return false; } bool IsPointer() const override { return false; } bool IsFunction() const override { return false; } std::size_t GetSize() const override { switch (type_) { case Type::Int32: case Type::UInt32: return 4; case Type::Int8: case Type::UInt8: return 1; default: return 0; } } std::optional<TypePtrList> GetArgsType() const override { return {}; } TypePtr GetDerefedType() const override { return nullptr; } TypePtr GetDeconstedType() const override { return nullptr; } TypePtr GetRightValue(bool is_right) override { return std::make_shared<PlainType>(type_, is_right); } bool CanAccept(const TypePtr &type) const override; bool CanCastTo(const TypePtr &type) const override; TypePtr GetReturnType(const TypePtrList &args) const override; private: Type type_; bool is_right_; }; class ConstType : public BaseType { public: ConstType(TypePtr type) : type_(std::move(type)) { assert(!type_->IsConst()); } bool IsRightValue() const override { return type_->IsRightValue(); } bool IsVoid() const override { return type_->IsVoid(); } bool IsInteger() const override { return type_->IsInteger(); } bool IsUnsigned() const override { return type_->IsUnsigned(); } bool IsConst() const override { return true; } bool IsPointer() const override { return type_->IsPointer(); } bool IsFunction() const override { return type_->IsFunction(); } std::size_t GetSize() const override { return type_->GetSize(); } std::optional<TypePtrList> GetArgsType() const override { return {}; } TypePtr GetDerefedType() const override { return type_->GetDerefedType(); } TypePtr GetDeconstedType() const override { return type_; } TypePtr GetRightValue(bool is_right) override { return std::make_shared<ConstType>(type_->GetRightValue(is_right)); } bool CanAccept(const TypePtr &type) const override; bool CanCastTo(const TypePtr &type) const override; TypePtr GetReturnType(const TypePtrList &args) const override; private: TypePtr type_; }; class PointerType : public BaseType { public: PointerType(TypePtr type, unsigned int ptr) : type_(std::move(type)), ptr_(ptr) { assert(ptr > 0); } bool IsRightValue() const override { return type_->IsRightValue(); } bool IsVoid() const override { return false; } bool IsInteger() const override { return false; } bool IsUnsigned() const override { return true; } bool IsConst() const override { return false; } bool IsPointer() const override { return true; } bool IsFunction() const override { return false; } std::size_t GetSize() const override { return kTypeSizeWordLength; } std::optional<TypePtrList> GetArgsType() const override { return {}; } TypePtr GetDerefedType() const override { return ptr_ == 1 ? type_ : std::make_shared<PointerType>(type_, ptr_ - 1); } TypePtr GetDeconstedType() const override { return nullptr; } TypePtr GetRightValue(bool is_right) override { return std::make_shared<PointerType>(type_->GetRightValue(is_right), ptr_); } bool CanAccept(const TypePtr &type) const override; bool CanCastTo(const TypePtr &type) const override; TypePtr GetReturnType(const TypePtrList &args) const override; private: TypePtr type_; unsigned int ptr_; }; class FuncType : public BaseType { public: FuncType(TypePtrList args, TypePtr ret) : args_(std::move(args)), ret_(std::move(ret)) {} bool IsRightValue() const override { return true; } bool IsVoid() const override { return false; } bool IsInteger() const override { return false; } bool IsUnsigned() const override { return false; } bool IsConst() const override { return false; } bool IsPointer() const override { return false; } bool IsFunction() const override { return true; } std::size_t GetSize() const override { return 0; } std::optional<TypePtrList> GetArgsType() const override { return args_; } TypePtr GetDerefedType() const override { return nullptr; } TypePtr GetDeconstedType() const override { return nullptr; } TypePtr GetRightValue(bool is_right) override { return nullptr; } bool CanAccept(const TypePtr &type) const override; bool CanCastTo(const TypePtr &type) const override; TypePtr GetReturnType(const TypePtrList &args) const override; private: TypePtrList args_; TypePtr ret_; }; // create a new plain type by type keyword inline TypePtr MakePlainType(front::Keyword key, bool is_right) { using namespace front; using Type = PlainType::Type; switch (key) { case Keyword::Int32: { return std::make_shared<PlainType>(Type::Int32, is_right); } case Keyword::Int8: { return std::make_shared<PlainType>(Type::Int8, is_right); } case Keyword::UInt32: { return std::make_shared<PlainType>(Type::UInt32, is_right); } case Keyword::UInt8: { return std::make_shared<PlainType>(Type::UInt8, is_right); } default: { assert(false); return nullptr; } } } // create a new void type inline TypePtr MakeVoidType() { return std::make_shared<PlainType>(PlainType::Type::Void, false); } // check if 2 pointers are compatible inline bool IsPointerCompatible(const BaseType &p1, const BaseType &p2) { if (p1.IsPointer() && p2.IsPointer()) { return IsPointerCompatible(*p1.GetDerefedType(), *p2.GetDerefedType()); } else if (!p1.IsPointer() && !p2.IsPointer()) { return p1.IsInteger() && p2.IsInteger() && !(p1.IsUnsigned() ^ p2.IsUnsigned()) && p1.GetSize() == p2.GetSize(); } else { return false; } } } // namespace tinylang::define #endif // TINYLANG_DEFINE_TYPE_H_
8,134
C++
.h
209
35.354067
75
0.710793
ustb-owl/TinyMIPS
34
6
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,838
elf.h
ustb-owl_TinyMIPS/src/utility/elfinfo/elf.h
#ifndef ELFINFO_ELF_H_ #define ELFINFO_ELF_H_ #include <cstdint> // type definitions in ELF using Elf32_Half = std::uint16_t; using Elf32_Word = std::uint32_t; using Elf32_Sword = std::int32_t; using Elf32_Addr = std::uint32_t; using Elf32_Off = std::uint32_t; // index of identification field in ELF header enum Elf32_Ehdr_IdentIndex { EI_MAG0, EI_MAG1, EI_MAG2, EI_MAG3, EI_CLASS, EI_DATA, EI_VERSION, EI_PAD, EI_NIDENT = 16, }; // class field in ELF header enum Elf32_Ehdr_Class { ELFCLASSNONE, ELFCLASS32, ELFCLASS64, }; // data field in ELF header enum Elf32_Ehdr_Data { ELFDATANONE, ELFDATA2LSB, ELFDATA2MSB, }; // type field in ELF header enum Elf32_Ehdr_Type { ET_NONE, ET_REL, ET_EXEC, ET_DYN, ET_CORE, ET_LOPROC = 0xff00, ET_HIPROC = 0xffff, }; // machine field in ELF header enum Elf32_Ehdr_Machine { EM_NONE, EM_M32, EM_SPARC, EM_386, EM_68K, EM_88K, EM_860 = 7, EM_MIPS, }; // version field in ELF header enum Elf32_Ehdr_Version { EV_NONE, EV_CURRENT, }; // flag field in ELF header enum Elf32_Ehdr_Flags { EF_MIPS_NOREORDER = 0x00000001, EF_MIPS_PIC = 0x00000002, EF_MIPS_CPIC = 0x00000004, EF_MIPS_ARCH = 0xf0000000, EF_MIPS_ARCH_2 = 0x10000000, EF_MIPS_ARCH_3 = 0x20000000, }; // ELF magic number const char elf32_ehdr_magic[] = {'\x7f', 'E', 'L', 'F'}; // file class const char *elf32_ehdr_class[] = { "none", "32-bit", "64-bit", }; // data encoding const char *elf32_ehdr_data[] = { "none", "little endian", "big endian", }; // object file type const char *elf32_ehdr_type[] = { "none", "relocatable", "executable", "shared object", "core file", }; // architectures const char *elf32_ehdr_machine[] = { "none", "WE 32100", "SPARC", "80386", "68000", "88000", "", "80860", "MIPS", }; // ELF version const char *elf32_ehdr_version[] = { "none", "current", }; // ELF header #pragma pack(1) struct Elf32_Ehdr { unsigned char e_ident[EI_NIDENT]; Elf32_Half e_type; Elf32_Half e_machine; Elf32_Word e_version; Elf32_Addr e_entry; Elf32_Off e_phoff; Elf32_Off e_shoff; Elf32_Word e_flags; Elf32_Half e_ehsize; Elf32_Half e_phentsize; Elf32_Half e_phnum; Elf32_Half e_shentsize; Elf32_Half e_shnum; Elf32_Half e_shstrndx; }; #pragma pack() // type field in section header enum Elf32_Shdr_Type { SHT_NULL, SHT_PROGBITS, SHT_SYMTAB, SHT_STRTAB, SHT_RELA, SHT_HASH, SHT_DYNAMIC, SHT_NOTE, SHT_NOBITS, SHT_REL, SHT_SHLIB, SHT_DYNSYM, SHT_LOPROC = 0x70000000, SHT_HIPROC = 0x7fffffff, SHT_LOUSER = 0x80000000, SHT_HIUSER = 0xffffffff, SHT_MIPS_LIBLIST = 0x70000000, SHT_MIPS_CONFLICT = 0x70000002, SHT_MIPS_GPTAB = 0x70000003, SHT_MIPS_UCODE = 0x70000004, SHT_MIPS_REGINFO = 0x70000006, SHT_MIPS_ABIFLAGS = 0x7000002a, }; // flags field in section header enum Elf32_Shdr_Flags { SHF_WRITE = 0x1, SHF_ALLOC = 0x2, SHF_EXECINSTR = 0x4, SHF_MASKPROC = 0xf0000000, }; // section header type const char *elf32_shdr_type[] = { "SHT_NULL", "SHT_PROGBITS", "SHT_SYMTAB", "SHT_STRTAB", "SHT_RELA", "SHT_HASH", "SHT_DYNAMIC", "SHT_NOTE", "SHT_NOBITS", "SHT_REL", "SHT_SHLIB", "SHT_DYNSYM", }; // section header #pragma pack(1) struct Elf32_Shdr { Elf32_Word sh_name; Elf32_Word sh_type; Elf32_Word sh_flags; Elf32_Addr sh_addr; Elf32_Off sh_offset; Elf32_Word sh_size; Elf32_Word sh_link; Elf32_Word sh_info; Elf32_Word sh_addralign; Elf32_Word sh_entsize; }; #pragma pack() // type field in program header enum Elf32_Phdr_Type { PT_NULL, PT_LOAD, PT_DYNAMIC, PT_INTERP, PT_NOTE, PT_SHLIB, PT_PHDR, PT_LOPROC = 0x70000000, PT_HIPROC = 0x7fffffff, }; // flags field in program header enum Elf32_Phdr_Flags { PF_X = 0x1, PF_W = 0x2, PF_R = 0x4, PF_MASKOS = 0x0ff00000, PF_MASKPROC = 0xf0000000, }; // segment type const char *elf32_phdr_type[] = { "PT_NULL", "PT_LOAD", "PT_DYNAMIC", "PT_INTERP", "PT_NOTE", "PT_SHLIB", "PT_PHDR", }; // program header #pragma pack(1) struct Elf32_Phdr { Elf32_Word p_type; Elf32_Off p_offset; Elf32_Addr p_vaddr; Elf32_Addr p_paddr; Elf32_Word p_filesz; Elf32_Word p_memsz; Elf32_Word p_flags; Elf32_Word p_align; }; #pragma pack() #endif // ELFINFO_ELF_H_
4,413
C++
.h
179
22.418994
57
0.660489
ustb-owl/TinyMIPS
34
6
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,839
layer.cpp
xuankuzcr_robomaster_mnist/src/layer.cpp
//layer.cpp #include<stdlib.h> #include "layer.h" #include <cstring> #include <time.h> #include <iostream> #include <cmath> using namespace std; Layer::Layer(int numNodes, int numInputNodes,ACTIVATION activa) :mNumNodes(numNodes), mNumInputNodes(numInputNodes), mActivate(activa) { mWeights = new float*[mNumNodes]; mOutputs = new float[mNumNodes]; mDelta = new float[mNumNodes]; init(); } Layer::Layer(Layer &layer) :mNumNodes(layer.mNumNodes), mNumInputNodes(layer.mNumInputNodes), mActivate(layer.mActivate) { int size = mNumNodes * sizeof(float); memcpy(mOutputs, layer.mOutputs, size); memcpy(mDelta, layer.mDelta, size); for (int i = 0; i < mNumNodes; i++) { memcpy(mWeights[i], layer.mWeights[i], layer.mNumInputNodes+1); } } Layer::~Layer() { for (int i = 0; i < mNumNodes; i++) { delete [] mWeights[i]; } delete [] mWeights; delete [] mOutputs; delete [] mDelta; } void Layer::init() { memset(mOutputs, 0, mNumNodes * sizeof(float)); memset(mDelta, 0, mNumNodes * sizeof(float)); srand(time(0)); for (int i = 0; i < mNumNodes; ++i) { float *curWeights = new float[mNumInputNodes + 1]; mWeights[i] = curWeights; for (int w = 0; w < mNumInputNodes + 1; w++) //还有一个 bias 值,所以加 1 { curWeights[w] = rand() % 1000 * 0.001 - 0.5; } } } float Layer::active(float x,ACTIVATION activate) //激活函数 { switch(activate){ case SIGMOID: return (1.0/(1.0+exp(-x))); case RELU: return x*(x>0); case LEAKY: return (x>0)?x:0.1*x; default: cout<<"no activation."<<endl; return x; } } float Layer::gradient(float x,ACTIVATION activate) //激活函数导数 { switch(activate){ case SIGMOID: return x*(1.0-x); case RELU: return (x>0); case LEAKY: return (x>0)?1:0.1; default: cout<<"no activation."<<endl; return 1.0; } } void Layer::forwardLayer(float *inputs) //前向计算 { for (int n = 0; n < mNumNodes; ++n) { float *curWeights = mWeights[n]; float x = 0; int k; for (k = 0; k < mNumInputNodes; ++k) { x += curWeights[k] * inputs[k]; } x += curWeights[k]; mOutputs[n] = active(x,mActivate); } } void Layer::backwardLayer(float *prevOutputs,float *prevDelta,float learningRate) //反向计算 { for (int i = 0; i < mNumNodes; i++) { float* curWeights = mWeights[i]; float delta = mDelta[i] * gradient(mOutputs[i],mActivate); int w; for (w = 0; w < mNumInputNodes; w++) { if (prevDelta) { prevDelta[w] += curWeights[w] * delta; } curWeights[w] += delta * learningRate * prevOutputs[w]; //更新权重 } curWeights[w] += delta * learningRate; //更新 bias } }
3,012
C++
.cpp
117
19.589744
89
0.581644
xuankuzcr/robomaster_mnist
34
6
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,840
network.cpp
xuankuzcr_robomaster_mnist/src/network.cpp
//network.cpp #include "network.h" #include <cstring> #include <stdlib.h> #include <math.h> #include <iostream> using namespace std; Network::Network(int epoches,float learningRate, int numInputs, int numOutputs) :mEpoches(epoches), mNumInputs(numInputs), mNumOutputs(numOutputs), mLearningRate(learningRate) { mNumLayers=0; mErrorSum=0; mInputs=NULL; mOutputs=NULL; } Network::~Network() { for (int i = 0; i < mNumLayers; i++) { if (mLayers[i]) { delete mLayers[i]; } } } void Network::init() //初始化 { for (int i = 0; i < mNumLayers; ++i) { mLayers[i]->init(); } mErrorSum = 0; } void Network::addLayer(int numNodes,ACTIVATION activate) //添加全连接层 { int numInputNodes = (mNumLayers > 0) ? mLayers[mNumLayers-1]->mNumNodes : mNumInputs; mLayers.push_back(new Layer(numNodes,numInputNodes,activate)); mNumLayers++; } void Network::forwardNetwork(float *inputs,int label) //网络前向计算 { for (int i = 0; i < mNumLayers; i++) { mLayers[i]->forwardLayer(inputs); //对每个层计算 inputs = mLayers[i]->mOutputs; } mOutputs=inputs; //注意是指向了最后一层的输出 if(!mTrain) return; float *outputs = mOutputs; float *delta = mLayers[mNumLayers-1]->mDelta; for (int i = 0; i < mNumOutputs; i++) { float err; if(i==label){ err=1-outputs[i]; }else{ err=0-outputs[i]; } delta[i] = err; //计算 delta 和误差 mErrorSum += err * err; } } void Network::backwardNetwork() //网络反向计算并更新权重参数 { float *prevOutputs = NULL; float *prevDelta = NULL; for (int i = mNumLayers-1; i >= 0; i--) { if (i > 0) { Layer &prev = *mLayers[i-1]; prevOutputs = prev.mOutputs; prevDelta = prev.mDelta; memset(prevDelta, 0, prev.mNumNodes * sizeof(float)); } else { prevOutputs = mInputs; prevDelta = NULL; //第一层前是输入,不需计算 delta } mLayers[i]->backwardLayer(prevOutputs, prevDelta,mLearningRate); //反向计算更新权重 } } void Network::compute(float *inputs,int label) //网络计算入口 { mInputs=inputs; forwardNetwork(inputs,label); if(!mTrain){ return; } backwardNetwork(); }
2,574
C++
.cpp
95
18.821053
90
0.576639
xuankuzcr/robomaster_mnist
34
6
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,841
main.cpp
xuankuzcr_robomaster_mnist/src/main.cpp
#include <iostream> #include "opencv2/opencv.hpp" #include <math.h> #include <sstream> #include "network.h" using namespace std; using namespace cv; #define widthThreshold 45 #define heigtThreshold 26 string int_to_str(int i) { stringstream s; s<<i; return s.str(); } int myDiscern(Mat n) { //1的图像,使用穿线会是8。应该从它的尺寸入手,高远大于宽,这里我们选取3倍比. // if(3*n.cols<n.rows) // { // cout<<'1'; // return 1; // } //竖线 int x_half=n.cols/2; //上横线 int y_one_third=n.rows/3; //下横线 int y_two_third=n.rows*2/3; //每段数码管,0灭,1亮 int a=0,b=0,c=0,d=0,e=0,f=0,g=0; //竖线识别a,g,d段 for(int i=0;i<n.rows;i++) { uchar *data=n.ptr<uchar>(i); if(i<y_one_third) { if(data[x_half]==255) a=1; } else if(i>y_one_third&&i<y_two_third) { if(data[x_half]==255) g=1; } else { if(data[x_half]==255) d=1; } } //上横线识别: for(int j=0;j<n.cols;j++) { uchar *data=n.ptr<uchar>(y_one_third); //f if(j<x_half) { if(data[j]==255) f=1; } //b else { if(data[j]==255) b=1; } } //下横线识别: for(int j=0;j<n.cols;j++) { uchar *data=n.ptr<uchar>(y_two_third); //e if(j<x_half) { if(data[j]==255) e=1; } //c else { if(data[j]==255) c=1; } } //七段管组成的数字 if(a==1 && b==1 && c==1 && d==1 && e==1 && f==1 && g==0) { // cout<<"0"; return 0 ; } /* else if(a==0 && b==1 && c==1 && d==0 && e==0 && f==0 && g==0) { cout<<"1"; return 1; } */ else if(a==1 && b==1 && c==0 && d==1 && e==1 && f==0 && g==1) { // cout<<"2"; return 2; } else if(a==1 && b==1 && c==1 && d==1 && e==0 && f==0 && g==1) { // cout<<"3"; return 3; } else if(a==0 && b==1 && c==1 && d==0 && e==0 && f==1 && g==1) { // cout<<"4"; return 4; } else if(a==1 && b==0 && c==1 && d==1 && e==0 && f==1 && g==1) { // cout<<"5"; return 5; } else if(a==1 && b==0 && c==1 && d==1 && e==1 && f==1 && g==1) { // cout<<"6"; return 6; } else if(a==1 && b==1 && c==1 && d==0 && e==0 && f==0 && g==0) { // cout<<"7"; return 7; } else if(a==1 && b==1 && c==1 && d==1 && e==1 && f==1 && g==1) { // cout<<"8"; return 8; } else if(a==1 && b==1 && c==1 && d==1 && e==0 && f==1 && g==1) { // / cout<<"9"; return 9; } else { // / printf("[error_%d_%d_%d_%d_%d_%d_%d]",a,b,c,d,e,f,g); } } //九宫格中的一个小格 struct SudokuGrid { Mat grid; Point2f gridCenter; long evaluation = 0; int lable;//聚类标签 Point2f originSize; }; int main() { int num_jpg=0; int networkInputs=28*28; //网络参数设置 int networkOutputs=10; int epoches=10; float learningRate=0.1; Network *network = new Network(epoches,learningRate,networkInputs,networkOutputs); network->addLayer(256,SIGMOID); //加入全连接层,参数有神经元个数和激活函数类型 256 network->addLayer(128,SIGMOID);//128 network->addLayer(network->mNumOutputs,SIGMOID); ifstream infile("mnist.weight"); if(!infile.is_open()){ cout<<"open weight file failed!"<<endl; exit(-1); } for(int i=0;i<network->mNumLayers;i++){ Layer *layer=network->mLayers[i]; for(int m=0;m<layer->mNumNodes;m++){ for(int n=0;n<layer->mNumInputNodes+1;n++){ infile>>layer->mWeights[m][n]; } } } infile.close(); cout<<"load weight from <"<<"minst.weight"<<"> done."<<endl; //loadWeight("mnist.weight",network); network->mTrain=false; VideoCapture cap("buff1.avi"); Mat src,test,gray,thresh,thresh2,original,src_shuma,shuma,cx_src; vector<Mat>channels; int a = 170;//canny参数170 int b= 11; Mat element1 = getStructuringElement(MORPH_RECT, Size(3, 3)); Mat element2 = getStructuringElement(MORPH_RECT, Size(7, 7)); for(;;) { cap.read(src); original=src.clone(); shuma=src.clone(); Rect rect(100, 113, 450, 350); Rect rect_shuma(0, 0, 500, 113); src = src(rect); src_shuma=shuma(rect_shuma); split(src_shuma,channels); Mat Red =channels.at(2); Mat Blue=channels.at(0); for(int i=0;i<Red.rows;i++) { for(int j=0;j<Red.cols;j++) { if(Red.at<uchar>(i,j)>150)//&&(Red.at<uchar>(i,j)>1.1*Blue.at<uchar>(i,j))) { Red.at<uchar>(i,j)=255; } else Red.at<uchar>(i,j)=0; } } vector<vector<Point> >contours; threshold(Red,cx_src,150,255,THRESH_BINARY); dilate(cx_src, cx_src, element2, Point(-1, -1)); findContours(cx_src,contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE); //src.copyTo(gray); //GaussianBlur(src,src,Size(3,3),0,0); //blur(src,src,Size(1,1),Point(-1,-1)); cvtColor(src, gray, CV_BGR2GRAY); threshold(gray,thresh, 85, 255, THRESH_BINARY_INV); thresh=~thresh; //Canny(gray, thresh, a, 3* a, 3); vector<vector<Point> >contours0; vector<RotatedRect> rectBorder; vector<SudokuGrid> sudoku;//九宫格 // erode(thresh,thresh,element1,Point(-1,-1)); // dilate(thresh, thresh, element2, Point(-1, -1)); findContours(thresh, contours0, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE); //test=thresh.clone(); drawContours(thresh, contours0, -1, Scalar(255, 255, 255)); Rect rect2; Rect rect3; // Rect rect4; if (contours0.size() > 0) { for (size_t j = 0; j < contours.size(); j++) { rect3= boundingRect(Mat(contours[j])); //rect4=Rect(rect3.x-20,rect3.y-20,rect3.width+20,rect3.height+20); if(rect3.height<20||rect3.width<20) continue; rectangle(original, rect3, Scalar(0, 0, 255), 3); Mat roi_shuma(cx_src, rect3); int result_shumaguan ; result_shumaguan = myDiscern(roi_shuma); putText(original,int_to_str(result_shumaguan),Point(rect3.x+10,rect3.y),FONT_HERSHEY_SIMPLEX,1,Scalar(255,255,255),4,8); /* 穿线法识别数码管交点法*/ /* string symbol=".jpg"; string path="/home/chunran/mnist-master/testData/"; if(num_jpg<10) { imwrite(int_to_str(num_jpg)+symbol,roi_shuma); } */// num_jpg++; /* Mat row1,row2,col1; row1 = roi_shuma.rowRange(roi_shuma.rows/3,roi_shuma.rows/3+1); row2 = roi_shuma.rowRange(2*roi_shuma.rows/3,2*roi_shuma.rows/3+1); col1 = roi_shuma.colRange(roi_shuma.cols/2,roi_shuma.cols/2+1); imshow("roi",roi_shuma); //cout<<row1<<endl<<endl; int flag_row1=0; int flag_row2=0; int flag_col1=0; int point_row1[10],point_row2[10],point_col1[10]; for(int i=0;i<row1.cols-1;i++) { if(abs(row1.at<uchar>(0,i)-row1.at<uchar>(0,i+1))==255) { point_row1[flag_row1]=i; flag_row1++; } if(abs(row2.at<uchar>(0,i)-row2.at<uchar>(0,i+1))==255) { point_row2[flag_row2]=i; flag_row2++; } } for(int j=0;j<col1.rows-1;j++) { if(abs(col1.at<uchar>(j,0)-col1.at<uchar>(j+1,0))==255) { point_col1[flag_col1]=j; flag_col1++; } } cout<<flag_row1<<endl; cout<<flag_row2<<endl; cout<<flag_col1<<endl; if(flag_row1==2&&flag_row2==2&&flag_col1==2) { result_shumaguan=1; putText(original,int_to_str(result_shumaguan),Point(rect3.x,rect3.y),FONT_HERSHEY_SIMPLEX,2,Scalar(0,0,255),4,8); } if(flag_row1==2&&flag_row2==2&&flag_col1==6) { if(point_row1[0]>row1.cols/2) { if(point_row2[0]>row2.cols/2) { result_shumaguan=3; putText(original,int_to_str(result_shumaguan),Point(rect3.x,rect3.y),FONT_HERSHEY_SIMPLEX,2,Scalar(0,0,255),4,8); } else { result_shumaguan=2; putText(original,int_to_str(result_shumaguan),Point(rect3.x,rect3.y),FONT_HERSHEY_SIMPLEX,2,Scalar(0,0,255),4,8); } } else { result_shumaguan=5; putText(original,int_to_str(result_shumaguan),Point(rect3.x,rect3.y),FONT_HERSHEY_SIMPLEX,2,Scalar(0,0,255),4,8); } } if(flag_row1==4&&flag_row2==4&&flag_col1==6) { result_shumaguan=8; putText(original,int_to_str(result_shumaguan),Point(rect3.x,rect3.y),FONT_HERSHEY_SIMPLEX,2,Scalar(0,0,255),4,8); } if(flag_row1==2&&flag_row2==4&&flag_col1==6) { result_shumaguan=6; putText(original,int_to_str(result_shumaguan),Point(rect3.x,rect3.y),FONT_HERSHEY_SIMPLEX,2,Scalar(0,0,255),4,8); } if(flag_row1==4&&flag_row2==2&&flag_col1==6) { result_shumaguan=9; putText(original,int_to_str(result_shumaguan),Point(rect3.x,rect3.y),FONT_HERSHEY_SIMPLEX,2,Scalar(0,0,255),4,8); } //if(flag_row1==2&&flag_row2==2&&point_row2[1]>row2.cols/2&&point_row1[1]>row1.cols/2&&flag_col1<6) // { // result_shumaguan=7; // putText(original,int_to_str(result_shumaguan),Point(rect3.x,rect3.y),FONT_HERSHEY_SIMPLEX,2,Scalar(0,0,255),4,8); // } //cout<<result_shumaguan<<endl; */ } vector<Point> poly; for (size_t t = 0; t < contours0.size(); t++) { approxPolyDP(contours0[t], poly, 5, true); // if (poly.size() == 4) //{ rect2= boundingRect(Mat(contours0[t])); rectBorder.push_back(minAreaRect(Mat(contours0[t]))); if(rect2.width<20||rect2.width>200||rect2.height>200||rect2.height<50) { continue; } else { SudokuGrid temp; Rect rect_change=Rect((rect2.x+100),(rect2.y+113),rect2.width,rect2.height); // rectangle(src, rect2, Scalar(0, 255, 0), 3); rectangle(original, rect_change, Scalar(0, 255, 0), 3); temp.originSize = Point2f(rect2.width, rect2.height); Mat roi(thresh, rect2); resize(roi, roi, Size(28, 28));//压缩 temp.grid = roi; // string symbol=".jpg"; // string path="/home/chunran/mnist-master/testData/"; // if(num_jpg<100) // { // imwrite(int_to_str(num_jpg)+symbol,roi); // } temp.gridCenter = Point2f(rect2.x, rect2.y); sudoku.push_back(temp); num_jpg++; float *d=new float[28*28]; for(int i=0;i<28;i++) { for(int j=0;j<28;j++) { float x=(roi.at<uchar>(i,j))/255.0; //将二维像素值转成一维向量,并归一化 d[i*28+j]=x; } } float max=-9999; int idx=10; network->compute(d); //开始预测 float *out=network->mOutputs; //获得网络输出 for(int i=1;i<10;i++) { cout<<out[i]<<","; if(out[i]>max) { //取最大输出为预测值 max=out[i]; idx=i; } } cout<<"the prediction is: "<<idx<<endl; cout<<endl; string result=int_to_str(idx); // putText(src,result,Point(rect2.x,rect2.y),FONT_HERSHEY_SIMPLEX,2,Scalar(0,0,255),4,8); putText(original,result,Point(rect2.x+110,rect2.y+113),FONT_HERSHEY_SIMPLEX,1,Scalar(255,255,255),4,8); } } // } } /* if (sudoku.size() > 9)//检测到大于9个,进行剔除 { vector<Point2f> rectSize;//对矩形尺寸聚类 for (size_t t = 0; t < sudoku.size(); t++) rectSize.push_back(sudoku[t].originSize); const int K = 2;//聚类的类别数量,即Lable的取值 Mat Label, Center; kmeans(rectSize, K, Label, TermCriteria(CV_TERMCRIT_EPS + CV_TERMCRIT_ITER, 10, 1.0), 1, KMEANS_PP_CENTERS, Center);//聚类3次,取结果最好的那次,聚类的初始化采用PP特定的随机算法。 int LableNum[K] = { 0 };//不同类别包含的成员数量,如类别0有8个,类别1有2个。。。。 int sudoLable;//代表九宫格的标签 for (int i = 0; i < rectSize.size(); ++i) { sudoku[i].lable = Label.at<int>(i); cout << rectSize[i] << "\t-->\t" << sudoku[i].lable << endl; for (int j = 0; j < K; ++j) if (sudoku[i].lable == j) { LableNum[j]++; break; } } sudoLable = *max_element(LableNum, LableNum + K); for (int j = 0; j < K; ++j) if (LableNum[j] == sudoLable) { sudoLable = j; break; } vector<SudokuGrid> sudokuTemp;//九宫格 for (int i = 0; i < rectSize.size(); ++i) if (sudoku[i].lable == sudoLable) sudokuTemp.push_back(sudoku[i]); sudoku.swap(sudokuTemp); } for (size_t t = 0; t < sudoku.size(); t++) { rectangle(src,Rect(sudoku[t].gridCenter.x,sudoku[t].gridCenter.y,sudoku[t].originSize.x,sudoku[t].originSize.y),Scalar(0, 255, 0), 3); } */ // namedWindow("src",CV_WINDOW_AUTOSIZE); // namedWindow("thresh",CV_WINDOW_AUTOSIZE); imshow("src",src); imshow("thresh", thresh); imshow("original",original); imshow("src_shuma",src_shuma); imshow("cx_src",cx_src); char c=waitKey(100); if(c==27) { break; } } return 0; }
15,928
C++
.cpp
448
22.571429
146
0.467502
xuankuzcr/robomaster_mnist
34
6
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,842
layer.h
xuankuzcr_robomaster_mnist/src/layer.h
//layer.h #ifndef __LAYER_H__ #define __LAYER_H__ typedef enum{ SIGMOID,RELU,LEAKY } ACTIVATION; class Layer { public: Layer(int numNodes, int numInputNodes,ACTIVATION activate=SIGMOID); Layer(Layer &layer); ~Layer(); void forwardLayer(float *inputs); void backwardLayer(float *prevOutputs,float *prevDelta,float learningRate); void init(); private: inline float active(float x,ACTIVATION activate); inline float gradient(float x,ACTIVATION activate); public: ACTIVATION mActivate; int mNumInputNodes; int mNumNodes; float **mWeights; float *mOutputs; float *mDelta; }; #endif
632
C++
.h
27
20.37037
77
0.74958
xuankuzcr/robomaster_mnist
34
6
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,843
network.h
xuankuzcr_robomaster_mnist/src/network.h
//network.h #ifndef __NETWORK_H__ #define __NETWORK_H__ #include "layer.h" #include <vector> using namespace std; class Network { public: Network(int epoches,float learningRate,int numInputs,int numOutputs); ~Network(); void compute(float *inputs,int label=10); void addLayer(int numNodes,ACTIVATION activate=SIGMOID); private: void init(); void forwardNetwork(float *inputs,int label); void backwardNetwork(); public: bool mTrain; int mEpoches; int mNumInputs; int mNumOutputs; int mNumLayers; float mLearningRate; float mErrorSum; float *mInputs; float *mOutputs; vector<Layer *> mLayers; }; #endif
707
C++
.h
30
19.033333
74
0.689088
xuankuzcr/robomaster_mnist
34
6
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,844
bmdca_sample.cpp
ranganathanlab_bmDCA/src/bmdca_sample.cpp
#include <armadillo> #include <iostream> #include <string> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include "generator.hpp" #include "utils.hpp" void print_usage(void) { std::cout << "bmdca_sample usage:" << std::endl; std::cout << "(e.g. bmdca_sample -p <params h> -P <params|params J> -c " "<config file> \\" << std::endl; std::cout << " -n <# samples per thread> -r <# threads> \\" << std::endl; std::cout << " -d <directory> -o <output flle>)" << std::endl; std::cout << " -p: parameters (txt) _or_ fields h (bin)" << std::endl; std::cout << " -P: couplings J (bin), required if fields h given" << std::endl; std::cout << " -d: destination directory" << std::endl; std::cout << " -o: output file name" << std::endl; std::cout << " -r: # independent sampling runs" << std::endl; std::cout << " -n: # samples obtained per sampling run" << std::endl; std::cout << " -c: config file" << std::endl; std::cout << " -h: print usage (i.e. this message)" << std::endl; }; int main(int argc, char* argv[]) { int num_sequences = 1000; int num_replicates = 10; std::string parameters_file, J_file; std::string dest_dir = "."; std::string config_file; std::string output_file = "MC_samples.fasta"; bool dest_dir_given = false; bool compat_mode = true; // Read command-line parameters. char c; while ((c = getopt(argc, argv, "p:P:d:n:c:o:r:h")) != -1) { switch (c) { case 'p': parameters_file = optarg; break; case 'P': J_file = optarg; compat_mode = false; break; case 'd': dest_dir = optarg; { struct stat st = { 0 }; if (stat(dest_dir.c_str(), &st) == -1) { #if __unix__ mkdir(dest_dir.c_str(), 0700); #elif _WIN32 mkdir(dest_dir.c_str()); #endif } } dest_dir_given = true; break; case 'o': output_file = optarg; break; case 'n': num_sequences = std::stoi(optarg); break; case 'r': num_replicates = std::stoi(optarg); break; case 'c': config_file = optarg; break; case 'h': print_usage(); return 0; break; case '?': std::cerr << "ERROR: Incorrect command line usage." << std::endl; print_usage(); std::exit(EXIT_FAILURE); } } // Check inputs if (compat_mode == true) { if (parameters_file.size() == 0) { std::cerr << "ERROR: Parameters file not given." << std::endl; print_usage(); std::exit(EXIT_FAILURE); } } else { if ((parameters_file.size() == 0) || (J_file.size() == 0)) { std::cerr << "ERROR: Both parameters files not given." << std::endl; print_usage(); std::exit(EXIT_FAILURE); } } // Load Potts model potts_model params; if (compat_mode) { params = loadPottsModelAscii(parameters_file); } else { params = loadPottsModel(parameters_file, J_file); } int N = params.h.n_cols; int Q = params.h.n_rows; Generator generator = Generator(params, N, Q, config_file); if (dest_dir_given == true) { chdir(dest_dir.c_str()); } generator.run(num_replicates, num_sequences, output_file); return 0; };
3,388
C++
.cpp
117
23.444444
79
0.552179
ranganathanlab/bmDCA
33
12
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,845
arma_convert.cpp
ranganathanlab_bmDCA/src/arma_convert.cpp
#include <armadillo> #include <iostream> #include <string> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include "utils.hpp" void print_usage(void) { std::cout << "arma2ascii usage:" << std::endl; std::cout << "(e.g. arma2ascii -p <params h> -P <params J>" << std::endl; std::cout << " -OR- arma2ascii -p <params>" << std::endl; std::cout << " -OR- arma2ascii -s <stats file>)" << std::endl; std::cout << " -p: parameters (txt) _or_ fields h (bin)" << std::endl; std::cout << " -P: couplings J (bin), *required* if fields h given" << std::endl; std::cout << " -s: sequence sample statistics file" << std::endl; std::cout << " -h: print usage (i.e. this message)" << std::endl; }; int main(int argc, char* argv[]) { std::string stat_file; std::string param_h_file; std::string param_J_file; bool valid_input = false; // Read command-line parameters. char c; while ((c = getopt(argc, argv, "P:p:s:h")) != -1) { switch (c) { case 'p': param_h_file = optarg; valid_input = true; break; case 'P': param_J_file = optarg; break; case 's': stat_file = optarg; valid_input = true; break; case 'h': print_usage(); return 0; break; case '?': std::cerr << "ERROR: Incorrect command line usage." << std::endl; print_usage(); std::exit(EXIT_FAILURE); } } if (!valid_input) { std::cerr << "ERROR: Input file not given." << std::endl; print_usage(); std::exit(EXIT_FAILURE); } // Convert 1p and/or 2p statistics from arma binary to ascii. if (stat_file.size() != 0) { std::cout << "converting '" << stat_file << "' to text... " << std::flush; convertFrequencyToAscii(stat_file); std::cout << "done" << std::endl; } // Convert h and J parameters in binary format to one text file. if ((param_h_file.size() != 0) & (param_J_file.size() != 0)) { std::cout << "converting '" << param_h_file << "' and '" << param_J_file << "' to text... " << std::flush; convertParametersToAscii(param_h_file, param_J_file); std::cout << "done" << std::endl; } else if ((param_h_file.size() != 0) || (param_J_file.size() != 0)) { std::cerr << "parameters file missing. exiting..." << std::endl; std::exit(EXIT_FAILURE); } return 0; }
2,402
C++
.cpp
75
27.28
78
0.571182
ranganathanlab/bmDCA
33
12
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,846
mcmc.cpp
ranganathanlab_bmDCA/src/mcmc.cpp
#include "mcmc.hpp" #include <string> #include "graph.hpp" void MCMC::load(potts_model* model) { graph.load(model); }; MCMC::MCMC(size_t N, size_t Q) : graph(N, Q) { n = N; q = Q; }; MCMC::MCMC(size_t N, size_t Q, potts_model* params) : graph(N, Q) { n = N; q = Q; graph.load(params); }; void MCMC::sample(arma::Cube<int>* ptr, int reps, int M, int N, int t_wait, int delta_t, long int seed, double temperature){ #pragma omp parallel { #pragma omp for for (int rep = 0; rep < reps; rep++){ graph.sample_mcmc((arma::Mat<int>*)&((*ptr).slice(rep)), M, t_wait, delta_t, seed + rep, temperature); } } }; void MCMC::sample_zanella(arma::Cube<int>* ptr, int reps, int M, int N, int t_wait, int delta_t, long int seed, std::string mode, double temperature){ #pragma omp parallel { #pragma omp for for (int rep = 0; rep < reps; rep++){ graph.sample_mcmc_zanella((arma::Mat<int>*)&((*ptr).slice(rep)), M, t_wait, delta_t, seed + rep, mode, temperature); } } }; void MCMC::sample_init(arma::Cube<int>* ptr, int reps, int M, int N, int t_wait, int delta_t, arma::Col<int>* init_ptr, long int seed, double temperature){ #pragma omp parallel { #pragma omp for for (int rep = 0; rep < reps; rep++){ graph.sample_mcmc_init((arma::Mat<int>*)&((*ptr).slice(rep)), M, t_wait, delta_t, init_ptr, seed + rep, temperature); } } };
2,404
C++
.cpp
91
13.395604
78
0.367896
ranganathanlab/bmDCA
33
12
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,847
msa.cpp
ranganathanlab_bmDCA/src/msa.cpp
#include "msa.hpp" #include <armadillo> #include <cstdlib> #include <fstream> #include <iostream> #include <string> #include <vector> #ifndef AA_ALPHABET_SIZE #define AA_ALPHABET_SIZE 21 #endif MSA::MSA(std::string msa_file, std::string weight_file, bool reweight, bool is_numeric_msa, double threshold) { if (is_numeric_msa) { readInputNumericMSA(msa_file); } else { readInputMSA(msa_file); M = seq_records.size(); N = getSequenceLength(seq_records.begin()->getSequence()); Q = AA_ALPHABET_SIZE; makeNumericalMatrix(); } if (reweight) { computeSequenceWeights(threshold); } else if (!weight_file.empty()) { readSequenceWeights(weight_file); } else { sequence_weights = arma::Col<double>(M, arma::fill::ones); } }; void MSA::readInputNumericMSA(std::string numeric_msa_file) { std::ifstream input_stream(numeric_msa_file); if (!input_stream) { std::cerr << "ERROR: couldn't open '" << numeric_msa_file << "' for reading." << std::endl; std::exit(EXIT_FAILURE); } input_stream >> M >> N >> Q; alignment = arma::Mat<int>(M, N); int counter = 0; int i = 0; std::string line; std::getline(input_stream, line); while (std::getline(input_stream, line)) { std::istringstream iss(line); int n; i = 0; while (iss >> n) { alignment(counter, i) = n; i++; } counter++; } } void MSA::readSequenceWeights(std::string weights_file) { std::ifstream input_stream(weights_file); if (!input_stream) { std::cerr << "ERROR: couldn't open '" << weights_file << "' for reading." << std::endl; std::exit(EXIT_FAILURE); } sequence_weights = arma::Col<double>(M, arma::fill::zeros); std::string line; int counter = 0; while (std::getline(input_stream, line)) { std::istringstream iss(line); double n; while (iss >> n) { sequence_weights(counter) = n; } counter++; } } void MSA::readInputMSA(std::string msa_file) { std::ifstream input_stream(msa_file); if (!input_stream) { std::cerr << "ERROR: cannot read from '" << msa_file << "'." << std::endl; exit(2); } /* * Read a FASTA-formatted multiple sequence alignment. Each record from the * file is stored as a SeqRecord object and appended to the seq_records * vector. */ std::string header, sequence, line; while (input_stream) { std::getline(input_stream, line); if (line[0] == '>') { if (sequence.length() > 0) { seq_records.push_back(SeqRecord(header, sequence)); sequence.clear(); header.clear(); } header = line; header.erase(0, 1); } else { sequence += line; line.clear(); } }; seq_records.push_back(SeqRecord(header, sequence)); input_stream.close(); }; void MSA::makeNumericalMatrix(void) { alignment = arma::Mat<int>(M, N); int row_idx = 0; for (auto seq = seq_records.begin(); seq != seq_records.end(); seq++) { std::string sequence = seq->getSequence(); int col_idx = 0; for (auto aa = sequence.begin(); aa != sequence.end(); aa++) { switch (*aa) { case '-': case 'B': case 'J': case 'O': case 'U': case 'X': case 'Z': alignment(row_idx, col_idx) = 0; col_idx++; break; case 'A': alignment(row_idx, col_idx) = 1; col_idx++; break; case 'C': alignment(row_idx, col_idx) = 2; col_idx++; break; case 'D': alignment(row_idx, col_idx) = 3; col_idx++; break; case 'E': alignment(row_idx, col_idx) = 4; col_idx++; break; case 'F': alignment(row_idx, col_idx) = 5; col_idx++; break; case 'G': alignment(row_idx, col_idx) = 6; col_idx++; break; case 'H': alignment(row_idx, col_idx) = 7; col_idx++; break; case 'I': alignment(row_idx, col_idx) = 8; col_idx++; break; case 'K': alignment(row_idx, col_idx) = 9; col_idx++; break; case 'L': alignment(row_idx, col_idx) = 10; col_idx++; break; case 'M': alignment(row_idx, col_idx) = 11; col_idx++; break; case 'N': alignment(row_idx, col_idx) = 12; col_idx++; break; case 'P': alignment(row_idx, col_idx) = 13; col_idx++; break; case 'Q': alignment(row_idx, col_idx) = 14; col_idx++; break; case 'R': alignment(row_idx, col_idx) = 15; col_idx++; break; case 'S': alignment(row_idx, col_idx) = 16; col_idx++; break; case 'T': alignment(row_idx, col_idx) = 17; col_idx++; break; case 'V': alignment(row_idx, col_idx) = 18; col_idx++; break; case 'W': alignment(row_idx, col_idx) = 19; col_idx++; break; case 'Y': alignment(row_idx, col_idx) = 20; col_idx++; break; } } row_idx++; } }; void MSA::writeMatrix(std::string output_file) { std::ofstream output_stream(output_file); output_stream << M << " " << N << " " << Q << std::endl; for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { if (j + 1 == N) { output_stream << alignment(i, j) << std::endl; } else { output_stream << alignment(i, j) << " "; } } } }; void MSA::printAlignment(void) { for (std::vector<SeqRecord>::iterator it = seq_records.begin(); it != seq_records.end(); ++it) { it->print(); } }; int MSA::getSequenceLength(std::string sequence) { int valid_aa_count = 0; for (std::string::iterator it = sequence.begin(); it != sequence.end(); ++it) { switch (*it) { case '-': case 'B': case 'J': case 'O': case 'U': case 'X': case 'Z': case 'A': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'K': case 'L': case 'M': case 'N': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'V': case 'W': case 'Y': valid_aa_count += 1; break; } } return valid_aa_count; }; void MSA::computeSequenceWeights(double threshold) { sequence_weights = arma::Col<double>(M, arma::fill::ones); arma::Mat<int> alignment_T = alignment.t(); #pragma omp parallel { #pragma omp for for (int m1 = 0; m1 < M; ++m1) { int* m1_ptr = alignment_T.colptr(m1); for (int m2 = 0; m2 < M; ++m2) { if (m1 != m2) { int* m2_ptr = alignment_T.colptr(m2); double id = 0; for (int i = 0; i < N; ++i) { if (*(m1_ptr + i) == *(m2_ptr + i)) { id += 1; } } if (id > threshold * N) { sequence_weights(m1) += 1; } } } } } sequence_weights = 1. / sequence_weights; }; void MSA::writeSequenceWeights(std::string output_file) { std::ofstream output_stream(output_file); for (int i = 0; i < M; i++) { output_stream << sequence_weights(i) << std::endl; } }; void MSA::computeHammingDistances(void) { hamming_distances = arma::Col<double>(M, arma::fill::zeros); arma::Mat<int> alignment_T = alignment.t(); int* i_ptr = nullptr; int* j_ptr = nullptr; int count = 0; double id = 0; for (int i = 0; i < M; i++) { i_ptr = alignment_T.colptr(i); for (int j = i + 1; j < M; j++) { count = 0; j_ptr = alignment_T.colptr(j); for (int n = 0; n < N; n++) { if (*(i_ptr + n) == *(j_ptr + n)) { count++; } } id = (double)count / N; if (id > hamming_distances(i)) { hamming_distances(i) = id; } } } }; void MSA::writeHammingDistances(std::string output_file) { std::ofstream output_stream(output_file); for (int i = 0; i < M; i++) { output_stream << hamming_distances(i) << std::endl; } };
8,413
C++
.cpp
351
17.792023
78
0.520911
ranganathanlab/bmDCA
33
12
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,848
generator.cpp
ranganathanlab_bmDCA/src/generator.cpp
#include "generator.hpp" #include "mcmc.hpp" #include "mcmc_stats.hpp" #include "pcg_random.hpp" #include "utils.hpp" Generator::Generator(potts_model params, int n, int q, std::string config_file) : N(n) , Q(q) , model(params) { initializeParameters(); if (config_file.length() != 0) { loadParameters(config_file); } }; Generator::~Generator(void) { delete mcmc_stats; }; void Generator::initializeParameters(void) { resample_max = 20; random_seed = 1; adapt_up_time = 1.5; adapt_down_time = 0.600; t_wait_0 = 100000; delta_t_0 = 1000; check_ergo = true; sampler = "mh"; temperature = 1.0; }; void Generator::checkParameters(void) { // Ensure that the set of ergodiciy checks is disabled if M=1 if ((M == 1) && check_ergo) { check_ergo = false; std::cerr << "WARNING: disabling 'check_ergo' when M=1." << std::endl; } } void Generator::loadParameters(std::string file_name) { std::ifstream file(file_name); bool reading_bmdca_section = false; if (file.is_open()) { std::string line; while (std::getline(file, line)) { if (line[0] == '#' || line.empty()) { continue; } else if (line[0] == '[') { if (line == "[sampling]") { reading_bmdca_section = true; continue; } else { reading_bmdca_section = false; continue; } } if (reading_bmdca_section) { auto delim_pos = line.find("="); auto key = line.substr(0, delim_pos); auto value = line.substr(delim_pos + 1); setParameter(key, value); } } } else { std::cerr << "ERROR: " << file_name << " not found." << std::endl; std::exit(EXIT_FAILURE); } }; void Generator::setParameter(std::string key, std::string value) { if (key == "resample_max") { resample_max = std::stoi(value); } else if (key == "random_seed") { random_seed = std::stoi(value); } else if (key == "adapt_up_time") { adapt_up_time = std::stod(value); } else if (key == "adapt_down_time") { adapt_down_time = std::stod(value); } else if (key == "t_wait_0") { t_wait_0 = std::stoi(value); } else if (key == "delta_t_0") { delta_t_0 = std::stoi(value); } else if (key == "check_ergo") { if (value.size() == 1) { check_ergo = (std::stoi(value) == 1); } else { check_ergo = (value == "true"); } } else if (key == "sampler") { sampler = value; } else if (key == "temperature") { temperature = std::stod(value); } }; void Generator::writeAASequences(std::string output_file) { int M = samples.n_rows; int N = samples.n_cols; int reps = samples.n_slices; std::ofstream output_stream(output_file); char aa; for (int rep = 0; rep < reps; rep++) { for (int m = 0; m < M; m++) { output_stream << ">sample" << m * rep + m << std::endl; for (int n = 0; n < N; n++) { aa = convertAA(samples(m, n, rep)); if (aa != '\0') { output_stream << aa; } } output_stream << std::endl << std::endl; } } }; void Generator::writeNumericalSequences(std::string output_file) { int idx = output_file.find_last_of("."); std::string raw_file = output_file.substr(0, idx); mcmc_stats->writeSamples(raw_file + "_numerical.txt"); mcmc_stats->writeSampleEnergies(raw_file + "_energies.txt"); } void Generator::run(int n_indep_runs, int n_per_run, std::string output_file) { std::cout << "initializing sampler... " << std::flush; arma::wall_clock timer; timer.tic(); count_max = n_indep_runs; M = n_per_run; checkParameters(); samples = arma::Cube<int>(M, N, count_max, arma::fill::zeros); mcmc = new MCMC(N, Q, &model); mcmc_stats = new MCMCStats(&samples, &(model)); // Instantiate the PCG random number generator and unifrom random // distribution. pcg32 rng; rng.seed(random_seed); std::uniform_int_distribution<long int> dist(0, RAND_MAX - count_max); std::cout << timer.toc() << " sec" << std::endl << std::endl; int t_wait = t_wait_0; int delta_t = delta_t_0; bool flag_mc = true; int resample_counter = 0; while (flag_mc) { std::cout << "sampling model with mcmc... " << std::flush; timer.tic(); if (sampler == "mh") { mcmc->sample( &samples, count_max, M, N, t_wait, delta_t, dist(rng), temperature); } else if (sampler == "z-sqrt") { mcmc->sample_zanella(&samples, count_max, M, N, t_wait, delta_t, dist(rng), "sqrt", temperature); } else if (sampler == "z-barker") { mcmc->sample_zanella(&samples, count_max, M, N, t_wait, delta_t, dist(rng), "barker", temperature); } else { std::cerr << "ERROR: sampler '" << sampler << "' not recognized." << std::endl; std::exit(EXIT_FAILURE); } std::cout << timer.toc() << " sec" << std::endl; std::cout << "updating mcmc stats with samples... " << std::flush; timer.tic(); mcmc_stats->updateData(&samples, &model); std::cout << timer.toc() << " sec" << std::endl; if (check_ergo) { std::cout << "computing sequence energies and correlations... " << std::flush; timer.tic(); mcmc_stats->computeEnergiesStats(); mcmc_stats->computeCorrelations(); std::cout << timer.toc() << " sec" << std::endl; std::vector<double> energy_stats = mcmc_stats->getEnergiesStats(); std::vector<double> corr_stats = mcmc_stats->getCorrelationsStats(); double auto_corr = corr_stats.at(2); double cross_corr = corr_stats.at(3); double check_corr = corr_stats.at(4); double cross_check_err = corr_stats.at(9); double auto_cross_err = corr_stats.at(8); double e_start = energy_stats.at(0); double e_start_sigma = energy_stats.at(1); double e_end = energy_stats.at(2); double e_end_sigma = energy_stats.at(3); double e_err = energy_stats.at(4); bool flag_deltat_up = true; bool flag_deltat_down = true; bool flag_twaiting_up = true; bool flag_twaiting_down = true; if (check_corr - cross_corr < cross_check_err) { flag_deltat_up = false; } if (auto_corr - cross_corr > auto_cross_err) { flag_deltat_down = false; } if (e_start - e_end < 2 * e_err) { flag_twaiting_up = false; } if (e_start - e_end > -2 * e_err) { flag_twaiting_down = false; } if (flag_deltat_up) { delta_t = (int)(round((double)delta_t * adapt_up_time)); std::cout << "increasing wait time to " << delta_t << std::endl; } else if (flag_deltat_down) { delta_t = Max((int)(round((double)delta_t * adapt_down_time)), 1); std::cout << "decreasing wait time to " << delta_t << std::endl; } if (flag_twaiting_up) { t_wait = (int)(round((double)t_wait * adapt_up_time)); std::cout << "increasing burn-in time to " << t_wait << std::endl; } else if (flag_twaiting_down) { t_wait = Max((int)(round((double)t_wait * adapt_down_time)), 1); std::cout << "decreasing burn-in time to " << t_wait << std::endl; } if (not flag_deltat_up and not flag_twaiting_up) { flag_mc = false; } else { if (resample_counter >= resample_max) { std::cout << "maximum number of resamplings (" << resample_counter << ") reached. stopping..." << std::endl; flag_mc = false; } else { std::cout << "resampling..." << std::endl; resample_counter++; std::cout << "writing temporary files" << std::endl; writeAASequences("temp_" + output_file); writeNumericalSequences("temp_" + output_file); } } } else { flag_mc = false; } } int idx = output_file.find_last_of("."); std::string output_name = output_file.substr(0, idx); if (deleteFile("temp_" + output_file) != 0) std::cerr << "temporary file deletion failed!" << std::endl; else if (deleteFile("temp_" + output_name + "_numerical.txt") != 0) std::cerr << "temporary file deletion failed!" << std::endl; else if (deleteFile("temp_" + output_name + "_energies.txt") != 0) std::cerr << "temporary file deletion failed!" << std::endl; std::cout << "writing final sequences... " << std::flush; writeAASequences(output_file); writeNumericalSequences(output_file); std::cout << "done" << std::endl; return; };
8,884
C++
.cpp
268
26.548507
79
0.561939
ranganathanlab/bmDCA
33
12
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,849
graph.cpp
ranganathanlab_bmDCA/src/graph.cpp
#include <armadillo> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> #include <ctime> #include <fstream> #include <iostream> #include <random> #include "graph.hpp" #include "pcg_random.hpp" using namespace std; std::ostream& log_out = std::cout; void Graph::load(potts_model* model) { params = model; } ostream& Graph::print_distribution(ostream& os) { vector<size_t> conf(n); double norm = 0; while (true) { double x = 0; for (size_t i = 0; i < n; ++i) { x += params->h(conf[i], i); } for (size_t i = 0; i < n; ++i) { for (size_t j = i + 1; j < n; ++j) { x += params->J(i, j)(conf[i], conf[j]); } } norm += exp(x); size_t j = 0; while (j < n && ++conf[j] == q) { conf[j] = 0; j++; } if (j == n) { break; } } while (true) { double x = 0; for (size_t i = 0; i < n; ++i) { x += params->h(conf[i], i); } for (size_t i = 0; i < n; ++i) { for (size_t j = i + 1; j < n; ++j) { x += params->J(i, j)(conf[i], conf[j]); } } os << "G2 " << exp(x) / norm << endl; size_t j = 0; while (j < n && ++conf[j] == q) { conf[j] = 0; j++; } if (j == n) { break; } } return os; }; void Graph::sample_mcmc(arma::Mat<int>* ptr, size_t m, size_t mc_iters0, size_t mc_iters, long int seed, double temperature) { pcg32 rng; rng.seed(seed); std::uniform_real_distribution<double> uniform(0, 1); arma::Col<size_t> conf = arma::Col<size_t>(n); for (size_t i = 0; i < n; ++i) { conf(i) = size_t(q * uniform(rng)); assert(conf(i) < q); } for (size_t k = 0; k < mc_iters0; ++k) { size_t i = size_t(n * uniform(rng)); size_t dq = 1 + size_t((q - 1) * uniform(rng)); size_t q0 = conf(i); size_t q1 = (q0 + dq) % q; double e0 = -params->h(q0, i); double e1 = -params->h(q1, i); for (size_t j = 0; j < n; ++j) { if (i > j) { e0 -= params->J(j, i)(conf(j), q0); e1 -= params->J(j, i)(conf(j), q1); } else if (i < j) { e0 -= params->J(i, j)(q0, conf(j)); e1 -= params->J(i, j)(q1, conf(j)); } } double de = e1 - e0; if ((de < 0) || (uniform(rng) < exp(-de / temperature))) { conf(i) = q1; } } for (size_t s = 0; s < m; ++s) { for (size_t k = 0; k < mc_iters; ++k) { size_t i = size_t(n * uniform(rng)); size_t dq = 1 + size_t((q - 1) * uniform(rng)); size_t q0 = conf(i); size_t q1 = (q0 + dq) % q; double e0 = -params->h(q0, i); double e1 = -params->h(q1, i); for (size_t j = 0; j < n; ++j) { if (i > j) { e0 -= params->J(j, i)(conf(j), q0); e1 -= params->J(j, i)(conf(j), q1); } else if (i < j) { e0 -= params->J(i, j)(q0, conf(j)); e1 -= params->J(i, j)(q1, conf(j)); } } double de = e1 - e0; if ((de < 0) || (uniform(rng) < exp(-de / temperature))) { conf(i) = q1; } } for (size_t i = 0; i < n; ++i) { (*ptr)(s, i) = conf(i); } } return; }; void Graph::sample_mcmc_init(arma::Mat<int>* ptr, size_t m, size_t mc_iters0, size_t mc_iters, arma::Col<int>* init_ptr, long int seed, double temperature) { pcg32 rng; rng.seed(seed); std::uniform_real_distribution<double> uniform(0, 1); arma::Col<size_t> conf = arma::Col<size_t>(n); for (size_t i = 0; i < n; ++i) { conf(i) = (*ptr)(i); assert(conf(i) < q); } for (size_t k = 0; k < mc_iters0; ++k) { size_t i = size_t(n * uniform(rng)); size_t dq = 1 + size_t((q - 1) * uniform(rng)); size_t q0 = conf(i); size_t q1 = (q0 + dq) % q; double e0 = -params->h(q0, i); double e1 = -params->h(q1, i); for (size_t j = 0; j < n; ++j) { if (i > j) { e0 -= params->J(j, i)(conf(j), q0); e1 -= params->J(j, i)(conf(j), q1); } else if (i < j) { e0 -= params->J(i, j)(q0, conf(j)); e1 -= params->J(i, j)(q1, conf(j)); } } double de = e1 - e0; if ((de < 0) || (uniform(rng) < exp(-de / temperature))) { conf(i) = q1; } } for (size_t s = 0; s < m; ++s) { for (size_t k = 0; k < mc_iters; ++k) { size_t i = size_t(n * uniform(rng)); size_t dq = 1 + size_t((q - 1) * uniform(rng)); size_t q0 = conf(i); size_t q1 = (q0 + dq) % q; double e0 = -params->h(q0, i); double e1 = -params->h(q1, i); for (size_t j = 0; j < n; ++j) { if (i > j) { e0 -= params->J(j, i)(conf(j), q0); e1 -= params->J(j, i)(conf(j), q1); } else if (i < j) { e0 -= params->J(i, j)(q0, conf(j)); e1 -= params->J(i, j)(q1, conf(j)); } } double de = e1 - e0; if ((de < 0) || (uniform(rng) < exp(-de / temperature))) { conf(i) = q1; } } for (size_t i = 0; i < n; ++i) { (*ptr)(s, i) = conf(i); } } return; }; void Graph::sample_mcmc_zanella(arma::Mat<int>* ptr, size_t m, size_t mc_iters0, size_t mc_iters, long int seed, std::string mode, double temperature) { pcg32 rng; rng.seed(seed); std::uniform_real_distribution<double> uniform(0, 1); arma::Col<size_t> conf = arma::Col<size_t>(n); for (size_t i = 0; i < n; ++i) { conf(i) = size_t(q * uniform(rng)); assert(conf(i) < q); } arma::Mat<double> de = arma::Mat<double>(n, q, arma::fill::zeros); arma::Mat<double> g = arma::Mat<double>(n, q, arma::fill::zeros); double lambda = 0.0; arma::Mat<double> de_old = arma::Mat<double>(n, q, arma::fill::zeros); arma::Mat<double> g_old = arma::Mat<double>(n, q, arma::fill::zeros); double lambda_old = 0.0; // Compute initial neighborhood. for (size_t i = 0; i < n; i++) { size_t q0 = conf(i); double e0 = -params->h(q0, i); for (size_t j = 0; j < n; ++j) { if (i > j) { e0 -= params->J(j, i)(conf(j), q0); } else if (i < j) { e0 -= params->J(i, j)(q0, conf(j)); } } for (size_t q1 = 0; q1 < q; q1++) { if (q0 == q1) { de(i, q1) = 0.0; } else { double e1 = -params->h(q1, i); for (size_t j = 0; j < n; ++j) { if (i > j) { e1 -= params->J(j, i)(conf(j), q1); } else if (i < j) { e1 -= params->J(i, j)(q1, conf(j)); } } de(i, q1) = e1 - e0; } } } if (mode == "sqrt") { g = arma::exp(de * -0.5 / temperature); lambda = arma::accu(g) - n; // n*exp(0) needs to be subtracted. } else if (mode == "barker") { g = 1.0 / (1.0 + arma::exp(de / temperature)); lambda = arma::accu(g) - .5 * n; } de_old = de; g_old = g; lambda_old = lambda; for (size_t k = 0; k < mc_iters0; ++k) { double rand = uniform(rng) * lambda; double r_sum = 0.0; size_t i = 0; size_t q0 = 0; size_t q1 = 0; bool done = false; for (i = 0; i < n; i++) { for (q1 = 0; q1 < q; q1++) { if (conf(i) == q1) { continue; } else { r_sum += g(i, q1); } if (r_sum > rand) { done = true; break; } } if (done) { break; } } double tmp = de(i, q1); q0 = conf(i); conf(i) = q1; for (size_t pos = 0; pos < n; pos++) { for (size_t aa = 0; aa < q; aa++) { if (pos < i) { de(pos, aa) += params->J(pos, i)(conf(pos), q1) - params->J(pos, i)(conf(pos), q0) - params->J(pos, i)(aa, q1) + params->J(pos, i)(aa, q0); } else if (pos > i) { de(pos, aa) += params->J(i, pos)(q1, conf(pos)) - params->J(i, pos)(q0, conf(pos)) - params->J(i, pos)(q1, aa) + params->J(i, pos)(q0, aa); } else { if (q1 == aa) { de(pos, aa) = 0; } else if (q0 == aa) { de(pos, aa) = -tmp; } else { de(pos, aa) += params->h(q1, pos) - params->h(q0, pos); for (size_t pos2 = 0; pos2 < n; pos2++) { if (pos2 < i) { de(pos, aa) += params->J(pos2, i)(conf(pos2), q1) - params->J(pos2, i)(conf(pos2), q0); } else if (pos2 > i) { de(pos, aa) += params->J(i, pos2)(q1, conf(pos2)) - params->J(i, pos2)(q0, conf(pos2)); } } } } } } if (mode == "sqrt") { g = arma::exp(de * -0.5 / temperature); lambda = arma::accu(g) - n; // n*exp(0) needs to be subtracted. } else if (mode == "barker") { g = 1.0 / (1.0 + arma::exp(de / temperature)); lambda = arma::accu(g) - .5 * n; } if (uniform(rng) < lambda_old / lambda) { conf(i) = q1; de_old = de; g_old = g; lambda_old = lambda; } else { conf(i) = q0; g = g_old; lambda = lambda_old; de = de_old; } } for (size_t s = 0; s < m; ++s) { for (size_t k = 0; k < mc_iters; ++k) { double rand = uniform(rng) * lambda; double r_sum = 0.0; size_t i = 0; size_t q0 = 0; size_t q1 = 0; bool done = false; for (i = 0; i < n; i++) { for (q1 = 0; q1 < q; q1++) { if (conf(i) == q1) { continue; } else { r_sum += g(i, q1); } if (r_sum > rand) { done = true; break; } } if (done) { break; } } double tmp = de(i, q1); q0 = conf(i); conf(i) = q1; for (size_t pos = 0; pos < n; pos++) { for (size_t aa = 0; aa < q; aa++) { if (pos < i) { de(pos, aa) += params->J(pos, i)(conf(pos), q1) - params->J(pos, i)(conf(pos), q0) - params->J(pos, i)(aa, q1) + params->J(pos, i)(aa, q0); } else if (pos > i) { de(pos, aa) += params->J(i, pos)(q1, conf(pos)) - params->J(i, pos)(q0, conf(pos)) - params->J(i, pos)(q1, aa) + params->J(i, pos)(q0, aa); } else { if (q1 == aa) { de(pos, aa) = 0; } else if (q0 == aa) { de(pos, aa) = -tmp; } else { de(pos, aa) += params->h(q1, pos) - params->h(q0, pos); for (size_t pos2 = 0; pos2 < n; pos2++) { if (pos2 < i) { de(pos, aa) += params->J(pos2, i)(conf(pos2), q1) - params->J(pos2, i)(conf(pos2), q0); } else if (pos2 > i) { de(pos, aa) += params->J(i, pos2)(q1, conf(pos2)) - params->J(i, pos2)(q0, conf(pos2)); } } } } } } if (mode == "sqrt") { g = arma::exp(de * -0.5 / temperature); lambda = arma::accu(g) - n; // n*exp(0) needs to be subtracted. } else if (mode == "barker") { g = 1.0 / (1.0 + arma::exp(de / temperature)); lambda = arma::accu(g) - .5 * n; } if (uniform(rng) < lambda_old / lambda) { conf(i) = q1; de_old = de; g_old = g; lambda_old = lambda; } else { conf(i) = q0; de = de_old; g = g_old; lambda = lambda_old; } } for (size_t i = 0; i < n; ++i) { (*ptr)(s, i) = (int)conf(i); } } return; }; ostream& Graph::print_parameters(ostream& os) { log_out << "printing parameters J" << endl; for (size_t i = 0; i < n; ++i) { for (size_t j = i + 1; j < n; ++j) { for (size_t yi = 0; yi < q; ++yi) { for (size_t yj = 0; yj < q; ++yj) { os << "J " << i << " " << j << " " << yi << " " << yj << " " << params->J(i, j)(yi, yj) << endl; } } } } log_out << "printing parameters h" << endl; for (size_t i = 0; i < n; ++i) { for (size_t yi = 0; yi < q; ++yi) { os << "h " << i << " " << yi << " " << params->h(yi, i) << endl; } } log_out << "done" << endl; return os; }; void Graph::print_parameters(FILE* of) { log_out << "printing parameters J" << endl; for (size_t i = 0; i < n; ++i) { for (size_t j = i + 1; j < n; ++j) { for (size_t yi = 0; yi < q; ++yi) { for (size_t yj = 0; yj < q; ++yj) { fprintf(of, "J %lu %lu %lu %lu %g\n", i, j, yi, yj, params->J(i, j)(yi, yj)); } } } } log_out << "printing parameters h" << endl; for (size_t i = 0; i < n; ++i) { for (size_t yi = 0; yi < q; ++yi) { fprintf(of, "h %lu %lu %g\n", i, yi, params->h(yi, i)); } } log_out << "done" << endl; };
13,407
C++
.cpp
465
20.795699
79
0.414509
ranganathanlab/bmDCA
33
12
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,850
model.cpp
ranganathanlab_bmDCA/src/model.cpp
#include "model.hpp" #include <armadillo> #include "utils.hpp" Model::Model(std::string parameters_file, std::string parameters_prev_file, std::string gradient_file, std::string gradient_prev_file, std::string learning_rate_file) { params = loadPottsModelAscii(parameters_file); params_prev = loadPottsModelAscii(parameters_prev_file); gradient = loadPottsModelAscii(gradient_file); gradient_prev = loadPottsModelAscii(gradient_prev_file); learning_rates = loadPottsModelAscii(learning_rate_file); N = params.h.n_cols; Q = params.h.n_rows; } Model::Model(std::string parameters_file_h, std::string parameters_file_J, std::string parameters_prev_file_h, std::string parameters_prev_file_J, std::string gradient_file_h, std::string gradient_file_J, std::string gradient_prev_file_h, std::string gradient_prev_file_J, std::string learning_rate_file_h, std::string learning_rate_file_J) { params = loadPottsModel(parameters_file_h, parameters_file_J); params_prev = loadPottsModel(parameters_prev_file_h, parameters_prev_file_J); gradient = loadPottsModel(gradient_file_h, gradient_file_J); gradient_prev = loadPottsModel(gradient_prev_file_h, gradient_prev_file_J); learning_rates = loadPottsModel(learning_rate_file_h, learning_rate_file_J); N = params.h.n_cols; Q = params.h.n_rows; } Model::Model(MSAStats msa_stats, double epsilon_h, double epsilon_J) { N = msa_stats.getN(); Q = msa_stats.getQ(); double pseudocount = 1. / msa_stats.getEffectiveM(); // Initialize the parameters J and h params.J = arma::field<arma::Mat<double>>(N, N); params_prev.J = arma::field<arma::Mat<double>>(N, N); for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { params.J(i, j) = arma::Mat<double>(Q, Q, arma::fill::zeros); params_prev.J(i, j) = arma::Mat<double>(Q, Q, arma::fill::zeros); } } params.h = arma::Mat<double>(Q, N, arma::fill::zeros); params_prev.h = arma::Mat<double>(Q, N, arma::fill::zeros); double avg; double* freq_ptr = nullptr; for (int i = 0; i < N; i++) { avg = 0; freq_ptr = msa_stats.frequency_1p.colptr(i); for (int aa = 0; aa < Q; aa++) { avg += log((1. - pseudocount) * (*(freq_ptr + aa)) + pseudocount * (1. / Q)); } for (int aa = 0; aa < Q; aa++) { params.h(aa, i) = log((1. - pseudocount) * (*(freq_ptr + aa)) + pseudocount * (1. / Q)) - avg / Q; } } // Initialize the learning rates (epsilon_0_h and epsilon_0_H) learning_rates.h = arma::Mat<double>(Q, N); learning_rates.h.fill(epsilon_h); learning_rates.J = arma::field<arma::Mat<double>>(N, N); for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { learning_rates.J(i, j) = arma::Mat<double>(Q, Q); learning_rates.J(i, j).fill(epsilon_J); } } // Initialize the gradient gradient.J = arma::field<arma::Mat<double>>(N, N); gradient_prev.J = arma::field<arma::Mat<double>>(N, N); for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { gradient.J(i, j) = arma::Mat<double>(Q, Q, arma::fill::zeros); gradient_prev.J(i, j) = arma::Mat<double>(Q, Q, arma::fill::zeros); } } gradient.h = arma::Mat<double>(Q, N, arma::fill::zeros); gradient_prev.h = arma::Mat<double>(Q, N, arma::fill::zeros); }; void Model::writeParams(std::string output_file_h, std::string output_file_J) { params.h.save(output_file_h, arma::arma_binary); params.J.save(output_file_J, arma::arma_binary); }; void Model::writeParamsAscii(std::string output_file) { std::ofstream output_stream(output_file); int N = params.h.n_cols; int Q = params.h.n_rows; // Write J for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { for (int aa1 = 0; aa1 < Q; aa1++) { for (int aa2 = 0; aa2 < Q; aa2++) { output_stream << "J " << i << " " << j << " " << aa1 << " " << aa2 << " " << params.J(i, j)(aa1, aa2) << std::endl; } } } } // Write h for (int i = 0; i < N; i++) { for (int aa = 0; aa < Q; aa++) { output_stream << "h " << i << " " << aa << " " << params.h(aa, i) << std::endl; } } }; void Model::writeParamsPrevious(std::string output_file_h, std::string output_file_J) { params_prev.h.save(output_file_h, arma::arma_binary); params_prev.J.save(output_file_J, arma::arma_binary); }; void Model::writeParamsPreviousAscii(std::string output_file) { std::ofstream output_stream(output_file); int N = params_prev.h.n_cols; int Q = params_prev.h.n_rows; // Write J for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { for (int aa1 = 0; aa1 < Q; aa1++) { for (int aa2 = 0; aa2 < Q; aa2++) { output_stream << "J " << i << " " << j << " " << aa1 << " " << aa2 << " " << params_prev.J(i, j)(aa1, aa2) << std::endl; } } } } // Write h for (int i = 0; i < N; i++) { for (int aa = 0; aa < Q; aa++) { output_stream << "h " << i << " " << aa << " " << params_prev.h(aa, i) << std::endl; } } }; void Model::writeLearningRates(std::string output_file_h, std::string output_file_J) { learning_rates.h.save(output_file_h, arma::arma_binary); learning_rates.J.save(output_file_J, arma::arma_binary); }; void Model::writeLearningRatesAscii(std::string output_file) { std::ofstream output_stream(output_file); int N = learning_rates.h.n_cols; int Q = learning_rates.h.n_rows; // Write J for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { for (int aa1 = 0; aa1 < Q; aa1++) { for (int aa2 = 0; aa2 < Q; aa2++) { output_stream << "J " << i << " " << j << " " << aa1 << " " << aa2 << " " << learning_rates.J(i, j)(aa1, aa2) << std::endl; } } } } // Write h for (int i = 0; i < N; i++) { for (int aa = 0; aa < Q; aa++) { output_stream << "h " << i << " " << aa << " " << learning_rates.h(aa, i) << std::endl; } } }; void Model::writeGradient(std::string output_file_h, std::string output_file_J) { gradient.h.save(output_file_h, arma::arma_binary); gradient.J.save(output_file_J, arma::arma_binary); }; void Model::writeGradientAscii(std::string output_file) { std::ofstream output_stream(output_file); int N = gradient.h.n_cols; int Q = gradient.h.n_rows; // Write J for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { for (int aa1 = 0; aa1 < Q; aa1++) { for (int aa2 = 0; aa2 < Q; aa2++) { output_stream << "J " << i << " " << j << " " << aa1 << " " << aa2 << " " << gradient.J(i, j)(aa1, aa2) << std::endl; } } } } // Write h for (int i = 0; i < N; i++) { for (int aa = 0; aa < Q; aa++) { output_stream << "h " << i << " " << aa << " " << gradient.h(aa, i) << std::endl; } } }; void Model::writeGradientPrevious(std::string output_file_h, std::string output_file_J) { gradient_prev.h.save(output_file_h, arma::arma_binary); gradient_prev.J.save(output_file_J, arma::arma_binary); }; void Model::writeGradientPreviousAscii(std::string output_file) { std::ofstream output_stream(output_file); int N = gradient_prev.h.n_cols; int Q = gradient_prev.h.n_rows; // Write J for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { for (int aa1 = 0; aa1 < Q; aa1++) { for (int aa2 = 0; aa2 < Q; aa2++) { output_stream << "J " << i << " " << j << " " << aa1 << " " << aa2 << " " << gradient_prev.J(i, j)(aa1, aa2) << std::endl; } } } } // Write h for (int i = 0; i < N; i++) { for (int aa = 0; aa < Q; aa++) { output_stream << "h " << i << " " << aa << " " << gradient_prev.h(aa, i) << std::endl; } } };
8,143
C++
.cpp
245
27.885714
80
0.546299
ranganathanlab/bmDCA
33
12
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,851
fasta_convert.cpp
ranganathanlab_bmDCA/src/fasta_convert.cpp
#include <armadillo> #include <iostream> #include <string> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include "utils.hpp" void print_usage(void) { std::cout << "mumeric2fasta usage:" << std::endl; std::cout << "(e.g. numeric2fasta -n <numeric MSA> -o <output FASTA file>" << std::endl; std::cout << " -n: numeric MSA (only 21 states supported)" << std::endl; std::cout << " -o: output FASTA file" << std::endl; std::cout << " -h: print usage (i.e. this message)" << std::endl; }; int main(int argc, char* argv[]) { std::string numeric_file; std::string fasta_file = "output.fasta"; bool valid_input = false; // Read command-line parameters. char c; while ((c = getopt(argc, argv, "n:o:h")) != -1) { switch (c) { case 'n': numeric_file = optarg; valid_input = true; break; case 'o': fasta_file = optarg; break; case 'h': print_usage(); return 0; break; case '?': std::cerr << "ERROR: Incorrect command line usage." << std::endl; print_usage(); std::exit(EXIT_FAILURE); } } if (!valid_input) { std::cerr << "ERROR: Input file not given." << std::endl; print_usage(); std::exit(EXIT_FAILURE); } std::ifstream input_stream(numeric_file); if (!input_stream) { std::cerr << "ERROR: couldn't open '" << numeric_file << "' for reading." << std::endl; std::exit(EXIT_FAILURE); } int N; int M; int Q; input_stream >> M >> N >> Q; if (Q != 21) { std::cerr << "ERROR: only 21 amino acids (states) supported." << std::endl; std::exit(EXIT_FAILURE); } arma::Mat<int> alignment = arma::Mat<int>(M, N); int counter = 0; int i = 0; std::string line; std::getline(input_stream, line); while (std::getline(input_stream, line)) { std::istringstream iss(line); int n; i = 0; while (iss >> n) { alignment(counter, i) = n; i++; } counter++; } std::ofstream output_stream(fasta_file); char aa; for (int m = 0; m < M; m++) { output_stream << ">sample" << m << std::endl; for (int n = 0; n < N; n++) { aa = convertAA(alignment(m, n)); if (aa != '\0') { output_stream << aa; } } output_stream << std::endl << std::endl; } output_stream.close(); return 0; }
2,386
C++
.cpp
92
21.347826
90
0.566784
ranganathanlab/bmDCA
33
12
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,852
bmdca.cpp
ranganathanlab_bmDCA/src/bmdca.cpp
#include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include "msa.hpp" #include "msa_stats.hpp" #include "run.hpp" void print_usage(void) { std::cout << "bmdca usage:" << std::endl; std::cout << "(e.g. bmdca -i <input MSA> -r -d <directory> -c <config file>)" << std::endl; std::cout << " -i: input MSA (FASTA format)" << std::endl; std::cout << " -d: destination directory" << std::endl; std::cout << " -r: re-weighting flag" << std::endl; std::cout << " -n: numerical MSA" << std::endl; std::cout << " -w: sequence weights" << std::endl; std::cout << " -c: config file" << std::endl; std::cout << " -t: sequence similarity threshold for reweighting" << std::endl; std::cout << " -h: print usage (i.e. this message)" << std::endl; std::cout << " -f: force a restart of the inference loop" << std::endl; }; int main(int argc, char* argv[]) { std::string input_file; std::string config_file; std::string weight_file; std::string dest_dir = "."; bool reweight = false; // if true, weight sequences by similarity bool is_numeric = false; bool input_file_given = false; bool force_restart = false; double threshold = 0.8; // Read command-line parameters. char c; while ((c = getopt(argc, argv, "c:d:fhi:n:rt:w:")) != -1) { switch (c) { case 'c': config_file = optarg; break; case 'd': dest_dir = optarg; { struct stat st = { 0 }; if (stat(dest_dir.c_str(), &st) == -1) { #if __unix__ mkdir(dest_dir.c_str(), 0700); #elif _WIN32 mkdir(dest_dir.c_str()); #endif } } break; case 'f': force_restart = true; break; case 'h': print_usage(); return 0; break; case 'i': input_file = optarg; input_file_given = true; break; case 'n': input_file = optarg; input_file_given = true; is_numeric = true; break; case 'r': reweight = true; break; case 't': threshold = std::stod(optarg); break; case 'w': weight_file = optarg; break; case '?': std::cerr << "ERROR: Incorrect command line usage." << std::endl; print_usage(); std::exit(EXIT_FAILURE); } } // Exit if no input file was provided. if (!input_file_given) { std::cerr << "ERROR: Missing MSA input file." << std::endl; print_usage(); std::exit(EXIT_FAILURE); } if (reweight & (!weight_file.empty())) { std::cout << "WARNING: sequence reweighting will ignore weight file." << std::endl; } // Parse the multiple sequence alignment. Reweight sequences if desired. MSA msa = MSA(input_file, weight_file, reweight, is_numeric, threshold); msa.writeSequenceWeights(dest_dir + "/sequence_weights.txt"); msa.writeMatrix(dest_dir + "/msa_numerical.txt"); // Compute the statistics of the MSA. MSAStats msa_stats = MSAStats(msa); msa_stats.writeFrequency1p(dest_dir + "/stat_align_1p.bin"); msa_stats.writeFrequency2p(dest_dir + "/stat_align_2p.bin"); msa_stats.writeRelEntropyGradient(dest_dir + "/rel_ent_grad_align_1p.bin"); // Initialize the MCMC using the statistics of the MSA. Sim sim = Sim(msa_stats, config_file, dest_dir, force_restart); sim.writeParameters("bmdca_params.conf"); sim.run(); return 0; };
3,454
C++
.cpp
111
25.711712
79
0.591236
ranganathanlab/bmDCA
33
12
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,853
run.cpp
ranganathanlab_bmDCA/src/run.cpp
#include "run.hpp" #include <armadillo> #include <cassert> #include <cstdlib> #include <dirent.h> #include <fstream> #include <iostream> #include <random> #include <regex> #include <string> #include <sys/types.h> #include <unistd.h> #include <vector> #define EPSILON 0.00000001 void Sim::initializeParameters(void) { // BM settings lambda_reg1 = 0.01; lambda_reg2 = 0.01; step_max = 2000; error_max = 0.00001; save_parameters = 20; random_seed = 1; use_reparametrization = true; // Learning rate settings epsilon_0_h = 0.01; epsilon_0_J = 0.001; adapt_up = 1.5; adapt_down = 0.6; min_step_h = 0.001; max_step_h = 2.5; min_step_J = 0.00001; max_step_J_N = 2.5; // divide by N later error_min_update = -1; // sampling time settings t_wait_0 = 10000; delta_t_0 = 100; check_ergo = true; adapt_up_time = 1.5; adapt_down_time = 0.600; output_binary = true; // importance sampling settings step_importance_max = 1; coherence_min = 0.9999; // mcmc settings M = 1000; // importance sampling max iterations count_max = 10; // number of independent MCMC runs init_sample = false; // flag to load first position for mcmc seqs }; void Sim::checkParameters(void) { // Ensure that the set of ergodiciy checks is disabled if M=1 if ((M == 1) && check_ergo) { check_ergo = false; std::cerr << "WARNING: disabling 'check_ergo' when M=1." << std::endl; } } void Sim::writeParameters(std::string output_file) { std::ofstream stream(output_file); // Header stream << "[bmDCA]" << std::endl; // BM settings stream << "lambda_reg1=" << lambda_reg1 << std::endl; stream << "lambda_reg2=" << lambda_reg2 << std::endl; stream << "step_max=" << step_max << std::endl; stream << "error_max=" << error_max << std::endl; stream << "save_parameters=" << save_parameters << std::endl; stream << "save_best_steps=" << save_best_steps << std::endl; stream << "random_seed=" << random_seed << std::endl; stream << "use_reparametrization=" << use_reparametrization << std::endl; // Learning rate settings stream << "epsilon_0_h=" << epsilon_0_h << std::endl; stream << "epsilon_0_J=" << epsilon_0_J << std::endl; stream << "adapt_up=" << adapt_up << std::endl; stream << "adapt_down=" << adapt_down << std::endl; stream << "min_step_h=" << min_step_h << std::endl; stream << "max_step_h=" << max_step_h << std::endl; stream << "min_step_J=" << min_step_J << std::endl; stream << "max_step_J_N=" << max_step_J_N << std::endl; stream << "error_min_update=" << error_min_update << std::endl; // sampling time settings stream << "t_wait_0=" << t_wait_0 << std::endl; stream << "delta_t_0=" << delta_t_0 << std::endl; stream << "check_ergo=" << check_ergo << std::endl; stream << "adapt_up_time=" << adapt_up_time << std::endl; stream << "adapt_down_time=" << adapt_down_time << std::endl; // importance sampling settings stream << "step_importance_max=" << step_importance_max << std::endl; stream << "coherence_min=" << coherence_min << std::endl; // mcmc settings stream << "M=" << M << std::endl; stream << "count_max=" << count_max << std::endl; stream << "init_sample=" << init_sample << std::endl; stream << "init_sample_file=" << init_sample_file << std::endl; stream << "sampler=" << sampler << std::endl; stream << "output_binary=" << output_binary << std::endl; }; bool Sim::compareParameters(std::string file_name) { std::ifstream file(file_name); bool reading_bmdca_section = false; bool all_same = true; if (file.is_open()) { std::string line; while (std::getline(file, line)) { if (line[0] == '#' || line.empty()) { continue; } else if (line[0] == '[') { if (line == "[bmDCA]") { reading_bmdca_section = true; continue; } else { reading_bmdca_section = false; continue; } } if (reading_bmdca_section) { auto delim_pos = line.find("="); auto key = line.substr(0, delim_pos); auto value = line.substr(delim_pos + 1); all_same = all_same & compareParameter(key, value); } } } else { std::cerr << "ERROR: " << file_name << " not found." << std::endl; std::exit(EXIT_FAILURE); } return all_same; }; void Sim::loadParameters(std::string file_name) { std::ifstream file(file_name); bool reading_bmdca_section = false; if (file.is_open()) { std::string line; while (std::getline(file, line)) { if (line[0] == '#' || line.empty()) { continue; } else if (line[0] == '[') { if (line == "[bmDCA]") { reading_bmdca_section = true; continue; } else { reading_bmdca_section = false; continue; } } if (reading_bmdca_section) { auto delim_pos = line.find("="); auto key = line.substr(0, delim_pos); auto value = line.substr(delim_pos + 1); setParameter(key, value); } } } else { std::cerr << "ERROR: " << file_name << " not found." << std::endl; std::exit(EXIT_FAILURE); } }; bool Sim::compareParameter(std::string key, std::string value) { bool same = true; // It's not possible to use switch blocks on strings because they are char* // arrays, not actual types. if (key == "lambda_reg1") { same = same & (lambda_reg1 == std::stod(value)); } else if (key == "lambda_reg2") { same = same & (lambda_reg2 == std::stod(value)); } else if (key == "step_max") { } else if (key == "error_max") { } else if (key == "save_parameters") { } else if (key == "save_best_steps") { } else if (key == "random_seed") { same = same & (random_seed == std::stoi(value)); } else if (key == "use_reparametrization") { if (value.size() == 1) { same = same & (use_reparametrization == (std::stoi(value) == 1)); } else { same = same & (use_reparametrization == (value == "true")); } } else if (key == "epsilon_0_h") { same = same & (epsilon_0_h == std::stod(value)); } else if (key == "epsilon_0_J") { same = same & (epsilon_0_J == std::stod(value)); } else if (key == "adapt_up") { same = same & (adapt_up == std::stod(value)); } else if (key == "adapt_down") { same = same & (adapt_down == std::stod(value)); } else if (key == "min_step_h") { same = same & (min_step_h == std::stod(value)); } else if (key == "max_step_h") { same = same & (max_step_h == std::stod(value)); } else if (key == "min_step_J") { same = same & (min_step_J == std::stod(value)); } else if (key == "max_step_J_N") { same = same & (max_step_J_N == std::stod(value)); } else if (key == "error_min_update") { same = same & (error_min_update == std::stod(value)); } else if (key == "t_wait_0") { same = same & (t_wait_0 == std::stoi(value)); } else if (key == "delta_t_0") { same = same & (delta_t_0 == std::stoi(value)); } else if (key == "check_ergo") { if (value.size() == 1) { same = same & (check_ergo == (std::stoi(value) == 1)); } else { same = same & (check_ergo == (value == "true")); } } else if (key == "adapt_up_time") { same = same & (adapt_up_time == std::stod(value)); } else if (key == "adapt_down_time") { same = same & (adapt_down_time == std::stod(value)); } else if (key == "step_importance_max") { same = same & (step_importance_max == std::stoi(value)); } else if (key == "coherence_min") { same = same & (coherence_min == std::stod(value)); } else if (key == "M") { same = same & (M == std::stoi(value)); } else if (key == "count_max") { same = same & (count_max == std::stoi(value)); } else if (key == "init_sample") { if (value.size() == 1) { same = same & (init_sample == (std::stoi(value) == 1)); } else { same = same & (init_sample == (value == "true")); } } else if (key == "init_sample_file") { same = same & (init_sample_file == value); } else if (key == "sampler") { same = same & (sampler == value); } else if (key == "output_binary") { if (value.size() == 1) { same = same & (output_binary == (std::stoi(value) == 1)); } else { same = same & (output_binary == (value == "true")); } } else { std::cerr << "ERROR: unknown parameter '" << key << "'" << std::endl; std::exit(EXIT_FAILURE); } return same; }; void Sim::setParameter(std::string key, std::string value) { // It's not possible to use switch blocks on strings because they are char* // arrays, not actual types. if (key == "lambda_reg1") { lambda_reg1 = std::stod(value); } else if (key == "lambda_reg2") { lambda_reg2 = std::stod(value); } else if (key == "step_max") { step_max = std::stoi(value); } else if (key == "error_max") { error_max = std::stod(value); } else if (key == "save_parameters") { save_parameters = std::stoi(value); } else if (key == "save_best_steps") { if (value.size() == 1) { save_best_steps = (std::stoi(value) == 1); } else { save_best_steps = (value == "true"); } } else if (key == "random_seed") { random_seed = std::stoi(value); } else if (key == "use_reparametrization") { if (value.size() == 1) { use_reparametrization = (std::stoi(value) == 1); } else { use_reparametrization = (value == "true"); } } else if (key == "epsilon_0_h") { epsilon_0_h = std::stod(value); } else if (key == "epsilon_0_J") { epsilon_0_J = std::stod(value); } else if (key == "adapt_up") { adapt_up = std::stod(value); } else if (key == "adapt_down") { adapt_down = std::stod(value); } else if (key == "min_step_h") { min_step_h = std::stod(value); } else if (key == "max_step_h") { max_step_h = std::stod(value); } else if (key == "min_step_J") { min_step_J = std::stod(value); } else if (key == "max_step_J_N") { max_step_J_N = std::stod(value); } else if (key == "error_min_update") { error_min_update = std::stod(value); } else if (key == "t_wait_0") { t_wait_0 = std::stoi(value); } else if (key == "delta_t_0") { delta_t_0 = std::stoi(value); } else if (key == "check_ergo") { if (value.size() == 1) { check_ergo = (std::stoi(value) == 1); } else { check_ergo = (value == "true"); } } else if (key == "adapt_up_time") { adapt_up_time = std::stod(value); } else if (key == "adapt_down_time") { adapt_down_time = std::stod(value); } else if (key == "step_importance_max") { step_importance_max = std::stoi(value); } else if (key == "coherence_min") { coherence_min = std::stod(value); } else if (key == "M") { M = std::stoi(value); } else if (key == "count_max") { count_max = std::stoi(value); } else if (key == "init_sample") { if (value.size() == 1) { init_sample = (std::stoi(value) == 1); } else { init_sample = (value == "true"); } } else if (key == "init_sample_file") { init_sample_file = value; } else if (key == "sampler") { sampler = value; } else if (key == "output_binary") { if (value.size() == 1) { output_binary = (std::stoi(value) == 1); } else { output_binary = (value == "true"); } } else { std::cerr << "ERROR: unknown parameter '" << key << "'" << std::endl; std::exit(EXIT_FAILURE); } }; Sim::Sim(MSAStats msa_stats, std::string config_file, std::string dest_dir, bool force_restart) : msa_stats(msa_stats) { initializeParameters(); if (!config_file.empty()) { std::cout << "loading hyperparameters... " << std::flush; loadParameters(config_file); std::cout << "done." << std::endl; } else if ((!force_restart) & (checkFileExists(dest_dir + "/" + hyperparameter_file))) { std::cout << "loading previously used hyperparameters... " << std::flush; loadParameters(dest_dir + "/" + hyperparameter_file); std::cout << "done." << std::endl; } checkParameters(); if (!dest_dir.empty()) { chdir(dest_dir.c_str()); } if ((!force_restart) & (checkFileExists(hyperparameter_file))) { if (!compareParameters(hyperparameter_file)) { std::cerr << "ERROR: current and previous hyperparameters mismatched. " << std::endl; std::exit(EXIT_FAILURE); } else { setStepOffset(); } } if (step_offset == 0) { model = new Model(msa_stats, epsilon_0_h, epsilon_0_J); } else { if (output_binary) { model = new Model("parameters_h_" + std::to_string(step_offset) + ".bin", "parameters_J_" + std::to_string(step_offset) + ".bin", "parameters_h_" + std::to_string(step_offset - 1) + ".bin", "parameters_J_" + std::to_string(step_offset - 1) + ".bin", "gradients_h_" + std::to_string(step_offset) + ".bin", "gradients_J_" + std::to_string(step_offset) + ".bin", "gradients_h_" + std::to_string(step_offset - 1) + ".bin", "gradients_J_" + std::to_string(step_offset - 1) + ".bin", "learning_rates_h_" + std::to_string(step_offset) + ".bin", "learning_rates_J_" + std::to_string(step_offset) + ".bin"); } else { model = new Model("parameters_" + std::to_string(step_offset) + ".txt", "parameters_" + std::to_string(step_offset - 1) + ".txt", "gradients_" + std::to_string(step_offset) + ".txt", "gradients_" + std::to_string(step_offset - 1) + ".txt", "learning_rates_" + std::to_string(step_offset) + ".txt"); } } mcmc = new MCMC(msa_stats.getN(), msa_stats.getQ()); }; void Sim::clearFiles(std::string dest_dir) { DIR* dp; struct dirent* dirp; std::vector<std::string> files; dp = opendir(dest_dir.c_str()); while ((dirp = readdir(dp)) != NULL) { std::string fname = dirp->d_name; if (fname.find("parameters_")) files.push_back(fname); else if (fname.find("gradients_")) files.push_back(fname); else if (fname.find("bmdca_")) files.push_back(fname); else if (fname.find("learning_rates_")) files.push_back(fname); else if (fname.find("MC_energies_")) files.push_back(fname); else if (fname.find("MC_samples_")) files.push_back(fname); else if (fname.find("msa_numerical")) files.push_back(fname); else if (fname.find("overlap_")) files.push_back(fname); else if (fname.find("ergo_")) files.push_back(fname); else if (fname.find("stat_MC_")) files.push_back(fname); else if (fname.find("stat_align_")) files.push_back(fname); else if (fname.find("rel_ent_grad_")) files.push_back(fname); } closedir(dp); for (auto it = files.begin(); it != files.end(); ++it) { std::remove((*it).c_str()); } }; void Sim::setStepOffset(void) { DIR* dp; struct dirent* dirp; dp = opendir("."); int run_count = 0; std::ifstream stream(run_log_file); if (stream) { std::string line; std::getline(stream, line); // skip the file header while (std::getline(stream, line)) { run_count++; } } stream.close(); std::vector<int> steps; std::vector<int> invalid_steps; while ((dirp = readdir(dp)) != NULL) { std::string fname = dirp->d_name; if (output_binary) { if (fname.find("parameters_h") == std::string::npos) continue; const std::regex re_param_h("parameters_h_([0-9]+)\\.bin"); std::smatch match_param_h; int idx = -1; if (std::regex_match(fname, match_param_h, re_param_h)) { if (match_param_h.size() == 2) { idx = std::stoi(match_param_h[1].str()); } } if (checkFileExists("parameters_J_" + std::to_string(idx) + ".bin") & checkFileExists("parameters_h_" + std::to_string(idx - 1) + ".bin") & checkFileExists("parameters_J_" + std::to_string(idx - 1) + ".bin") & checkFileExists("gradients_h_" + std::to_string(idx) + ".bin") & checkFileExists("gradients_J_" + std::to_string(idx) + ".bin") & checkFileExists("gradients_h_" + std::to_string(idx - 1) + ".bin") & checkFileExists("gradients_J_" + std::to_string(idx - 1) + ".bin") & checkFileExists("learning_rates_h_" + std::to_string(idx) + ".bin") & checkFileExists("learning_rates_J_" + std::to_string(idx) + ".bin")) { steps.push_back(idx); } else { if (idx > -1) { invalid_steps.push_back(idx); } } } else { if (fname.find("parameters") == std::string::npos) continue; const std::regex re_param("parameters_([0-9]+)\\.txt"); std::smatch match_param; int idx = -1; if (std::regex_match(fname, match_param, re_param)) { if (match_param.size() == 2) { idx = std::stoi(match_param[1].str()); } } if (checkFileExists("parameters_" + std::to_string(idx - 1) + ".txt") & checkFileExists("gradients_" + std::to_string(idx) + ".txt") & checkFileExists("gradients_" + std::to_string(idx - 1) + ".txt") & checkFileExists("learning_rates_" + std::to_string(idx) + ".txt")) { steps.push_back(idx); } else { invalid_steps.push_back(idx); } } } closedir(dp); // Clear out steps with missing files. for (auto it_bad = invalid_steps.begin(); it_bad != invalid_steps.end(); ++it_bad) { bool delete_files = true; for (auto it_good = steps.begin(); it_good != steps.end(); ++it_good) { if (*it_good == *it_bad - 1) { delete_files = false; break; } if (*it_good == *it_bad + 1) { delete_files = false; break; } } if (delete_files) { std::cout << "missing data --- clearing step " << *it_bad << std::endl; if (output_binary) { std::string file; file = "parameters_h_" + std::to_string(*it_bad) + ".bin"; if (checkFileExists(file)) deleteFile(file); file = "parameters_J_" + std::to_string(*it_bad) + ".bin"; if (checkFileExists(file)) deleteFile(file); file = "parameters_h_" + std::to_string(*it_bad - 1) + ".bin"; if (checkFileExists(file)) deleteFile(file); file = "parameters_J_" + std::to_string(*it_bad - 1) + ".bin"; if (checkFileExists(file)) deleteFile(file); file = "gradients_h_" + std::to_string(*it_bad) + ".bin"; if (checkFileExists(file)) deleteFile(file); file = "gradients_J_" + std::to_string(*it_bad) + ".bin"; if (checkFileExists(file)) deleteFile(file); file = "gradients_h_" + std::to_string(*it_bad - 1) + ".bin"; if (checkFileExists(file)) deleteFile(file); file = "gradients_J_" + std::to_string(*it_bad - 1) + ".bin"; if (checkFileExists(file)) deleteFile(file); file = "learning_rates_h_" + std::to_string(*it_bad) + ".bin"; if (checkFileExists(file)) deleteFile(file); file = "learning_rates_J_" + std::to_string(*it_bad) + ".bin"; if (checkFileExists(file)) deleteFile(file); } else { std::string file; file = "parameters_" + std::to_string(*it_bad) + ".txt"; if (checkFileExists(file)) deleteFile(file); file = "parameters_" + std::to_string(*it_bad - 1) + ".txt"; if (checkFileExists(file)) deleteFile(file); file = "gradients_" + std::to_string(*it_bad) + ".txt"; if (checkFileExists(file)) deleteFile(file); file = "gradients_" + std::to_string(*it_bad - 1) + ".txt"; if (checkFileExists(file)) deleteFile(file); file = "learning_rates_" + std::to_string(*it_bad) + ".txt"; if (checkFileExists(file)) deleteFile(file); } } } // Pick out the most recent valid step. int max = -1; for (auto it = steps.begin(); it != steps.end(); ++it) { if (*it > max) { max = *it; } } if (max < 0) { step_offset = 0; } else { step_offset = max; } }; Sim::~Sim(void) { delete model; delete mcmc; delete mcmc_stats; }; void Sim::restoreRunState(void) { long int prev_seed = -1; std::ifstream stream(run_log_file); std::string line; std::getline(stream, line); while (!stream.eof()) { std::getline(stream, line); std::stringstream buffer(line); std::string field; std::getline(buffer, field, '\t'); if (step_offset == std::stoi(field)) { std::vector<std::string> fields; std::stringstream ss; ss.str(line); std::string field; while (std::getline(ss, field, '\t')) { fields.push_back(field); } t_wait = std::stoi(fields.at(2)); delta_t = std::stoi(fields.at(3)); // position of some variables depend on whether some flags are set if (check_ergo) { error_tot_min = std::stod(fields.at(17)); prev_seed = std::stol(fields.at(18)); } else { error_tot_min = std::stod(fields.at(7)); prev_seed = std::stol(fields.at(8)); } break; } } std::uniform_int_distribution<long int> dist(0, RAND_MAX - count_max); int counter = 1; while (dist(rng) != prev_seed) { if (counter > 1000 * step_max * step_importance_max) { std::cerr << "WARNING: cannot restore RNG state." << std::endl; break; } counter++; } }; void Sim::readInitialSample(int N, int Q) { std::ifstream input_stream(init_sample_file); if (!input_stream) { std::cerr << "ERROR: cannot read '" << init_sample_file << "'." << std::endl; std::exit(EXIT_FAILURE); } std::string line; int aa; std::getline(input_stream, line); for (int n = 0; n < N; n++) { std::istringstream iss(line); iss >> aa; assert(aa < Q); initial_sample(n) = aa; } input_stream.close(); }; void Sim::run(void) { std::cout << "initializing run... " << std::flush; arma::wall_clock step_timer; arma::wall_clock timer; timer.tic(); int N = model->N; int Q = model->Q; // Initialize sample data structure samples = arma::Cube<int>(M, N, count_max, arma::fill::zeros); mcmc->load(&(model->params)); mcmc_stats = new MCMCStats(&samples, &(model->params)); if (init_sample) { initial_sample = arma::Col<int>(N, arma::fill::zeros); readInitialSample(N, Q); } // Instantiate the PCG random number generator and unifrom random // distribution. rng.seed(random_seed); std::uniform_int_distribution<long int> dist(0, RAND_MAX - count_max); // Initialize the buffer. run_buffer = arma::Mat<double>(save_parameters, 20, arma::fill::zeros); int buffer_offset = 0; if (step_offset == 0) { initializeRunLog(); t_wait = t_wait_0; delta_t = delta_t_0; } else if (step_offset >= step_max) { std::cout << "step " << step_max << " already reached... done." << std::endl; return; } else { restoreRunState(); buffer_offset = (step_offset % save_parameters); } std::cout << timer.toc() << " sec" << std::endl << std::endl; // BM sampling loop for (step = 1 + step_offset; step <= step_max; step++) { step_timer.tic(); std::cout << "Step: " << step << std::endl; // Sampling from MCMC (keep trying until correct properties found) bool flag_mc = true; long int seed; while (flag_mc) { // Draw from MCMC std::cout << "sampling model with mcmc... " << std::flush; timer.tic(); seed = dist(rng); run_buffer((step - 1) % save_parameters, 18) = seed; if (sampler == "mh") { if (init_sample) { mcmc->sample_init( &samples, count_max, M, N, t_wait, delta_t, &initial_sample, seed); } else { mcmc->sample(&samples, count_max, M, N, t_wait, delta_t, seed); } } else if (sampler == "z-sqrt") { mcmc->sample_zanella( &samples, count_max, M, N, t_wait, delta_t, seed, "sqrt"); } else if (sampler == "z-barker") { mcmc->sample_zanella( &samples, count_max, M, N, t_wait, delta_t, seed, "barker"); } else { std::cerr << "ERROR: sampler '" << sampler << "' not recognized." << std::endl; std::exit(EXIT_FAILURE); } std::cout << timer.toc() << " sec" << std::endl; std::cout << "updating mcmc with samples... " << std::flush; timer.tic(); mcmc_stats->updateData(&samples, &(model->params)); std::cout << timer.toc() << " sec" << std::endl; // Run checks and alter burn-in and wait times if (check_ergo) { std::cout << "computing sequence energies and correlations... " << std::flush; timer.tic(); mcmc_stats->computeEnergiesStats(); mcmc_stats->computeCorrelations(); std::cout << timer.toc() << " sec" << std::endl; std::vector<double> energy_stats = mcmc_stats->getEnergiesStats(); std::vector<double> corr_stats = mcmc_stats->getCorrelationsStats(); double auto_corr = corr_stats.at(2); double cross_corr = corr_stats.at(3); double check_corr = corr_stats.at(4); double cross_check_err = corr_stats.at(9); double auto_cross_err = corr_stats.at(8); double e_start = energy_stats.at(0); double e_start_sigma = energy_stats.at(1); double e_end = energy_stats.at(2); double e_end_sigma = energy_stats.at(3); double e_err = energy_stats.at(4); run_buffer((step - 1) % save_parameters, 4) = auto_corr; run_buffer((step - 1) % save_parameters, 5) = cross_corr; run_buffer((step - 1) % save_parameters, 6) = check_corr; run_buffer((step - 1) % save_parameters, 7) = auto_cross_err; run_buffer((step - 1) % save_parameters, 8) = cross_check_err; run_buffer((step - 1) % save_parameters, 9) = e_start; run_buffer((step - 1) % save_parameters, 10) = e_start_sigma; run_buffer((step - 1) % save_parameters, 11) = e_end; run_buffer((step - 1) % save_parameters, 12) = e_end_sigma; run_buffer((step - 1) % save_parameters, 13) = e_err; bool flag_deltat_up = true; bool flag_deltat_down = true; bool flag_twaiting_up = true; bool flag_twaiting_down = true; if (check_corr - cross_corr < cross_check_err) { flag_deltat_up = false; } if (auto_corr - cross_corr > auto_cross_err) { flag_deltat_down = false; } if (e_start - e_end < 2 * e_err) { flag_twaiting_up = false; } if (e_start - e_end > -2 * e_err) { flag_twaiting_down = false; } if (flag_deltat_up) { delta_t = (int)(round((double)delta_t * adapt_up_time)); std::cout << "increasing wait time to " << delta_t << std::endl; } else if (flag_deltat_down) { delta_t = Max((int)(round((double)delta_t * adapt_down_time)), 1); std::cout << "decreasing wait time to " << delta_t << std::endl; } if (flag_twaiting_up) { t_wait = (int)(round((double)t_wait * adapt_up_time)); std::cout << "increasing burn-in time to " << t_wait << std::endl; } else if (flag_twaiting_down) { t_wait = Max((int)(round((double)t_wait * adapt_down_time)), 1); std::cout << "decreasing burn-in time to " << t_wait << std::endl; } if (not flag_deltat_up and not flag_twaiting_up) { flag_mc = false; } else { std::cout << "resampling..." << std::endl; } } else { flag_mc = false; } } run_buffer((step - 1) % save_parameters, 0) = step; run_buffer((step - 1) % save_parameters, 1) = count_max; run_buffer((step - 1) % save_parameters, 2) = t_wait; run_buffer((step - 1) % save_parameters, 3) = delta_t; // Importance sampling loop int step_importance = 0; bool flag_coherence = true; bool new_min_found = false; while (step_importance < step_importance_max and flag_coherence == true) { step_importance++; if (step_importance > 1) { std::cout << "importance sampling step " << step_importance << "... " << std::flush; timer.tic(); mcmc_stats->computeSampleStatsImportance(&(model->params), &(model->params_prev)); std::cout << timer.toc() << " sec" << std::endl; double coherence = mcmc_stats->Z_ratio; if (coherence > coherence_min && 1.0 / coherence > coherence_min) { flag_coherence = true; } else { flag_coherence = false; } } else { std::cout << "computing mcmc 1p and 2p statistics... " << std::flush; timer.tic(); mcmc_stats->computeSampleStats(); std::cout << timer.toc() << " sec" << std::endl; } // Compute error reparametrization model->gradient_prev.h = model->gradient.h; model->gradient_prev.J = model->gradient.J; std::cout << "computing error and updating gradient... " << std::flush; timer.tic(); computeErrorReparametrization(); std::cout << timer.toc() << " sec" << std::endl; run_buffer((step - 1) % save_parameters, 14) = error_1p; run_buffer((step - 1) % save_parameters, 15) = error_2p; run_buffer((step - 1) % save_parameters, 16) = error_tot; if (error_tot < error_tot_min) { error_tot_min = error_tot; error_stat_tot_min = error_stat_tot; new_min_found = true; } run_buffer((step - 1) % save_parameters, 17) = error_tot_min; bool converged = false; if (error_tot < error_max) { converged = true; } if (converged) { run_buffer((step - 1) % save_parameters, 19) = step_timer.toc(); std::cout << "converged! writing final results... " << std::flush; writeRunLog(step % save_parameters, buffer_offset); writeData(step); writeData(std::to_string(step) + "_final"); std::cout << "done" << std::endl; return; } // Update learning rate std::cout << "update learning rate... " << std::flush; timer.tic(); updateLearningRate(); std::cout << timer.toc() << " sec" << std::endl; // Update parameters model->params_prev.h = model->params.h; model->params_prev.J = model->params.J; std::cout << "updating parameters... " << std::flush; timer.tic(); updateReparameterization(); std::cout << timer.toc() << " sec" << std::endl; run_buffer((step - 1) % save_parameters, 19) = step_timer.toc(); // Save parameters if (step % save_parameters == 0 && (step_importance == step_importance_max || flag_coherence == false)) { std::cout << "writing step " << step << "... " << std::flush; timer.tic(); writeRunLog(step % save_parameters, buffer_offset); buffer_offset = 0; writeData(step); std::cout << timer.toc() << " sec" << std::endl; } else if (new_min_found & (step > save_parameters) & save_best_steps) { new_min_found = false; std::cout << "close... writing step... " << std::flush; run_buffer((step - 1) % save_parameters, 19) = step_timer.toc(); writeRunLog(step % save_parameters, buffer_offset, true); buffer_offset = step % save_parameters; writeData(step); std::cout << "done" << std::endl; } } std::cout << std::endl; } if (step_offset != step_max) { std::cout << "writing final results... " << std::flush; if ((step_max % save_parameters) != 0) { writeRunLog(step_max % save_parameters); } writeData(step_max); writeData("final"); } else { std::cout << "all " << step_offset << " steps already... " << std::flush; } std::cout << "done" << std::endl; return; }; void Sim::computeErrorReparametrization(void) { double M_eff = msa_stats.getEffectiveM(); int N = msa_stats.getN(); int Q = msa_stats.getQ(); error_1p = 0; error_2p = 0; error_stat_1p = 0; error_stat_2p = 0; double delta = 0; double delta_stat = 0; double deltamax_1 = 0; double deltamax_2 = 0; double rho = 0, beta = 0, den_beta = 0, num_beta = 0, num_rho = 0, den_stat = 0, den_mc = 0, c_mc_av = 0, c_stat_av = 0, rho_1p = 0, num_rho_1p = 0, den_stat_1p = 0, den_mc_1p = 0; double phi = 0; double lambda_h = lambda_reg1; double lambda_j = lambda_reg2; int count1 = 0; int count2 = 0; // Compute gradient if (use_reparametrization) { for (int i = 0; i < N; i++) { for (int aa = 0; aa < Q; aa++) { phi = 2 * model->params.h(aa, i); for (int j = 0; j < N; j++) { if (i < j) { for (int bb = 0; bb < Q; bb++) { phi += model->params.J(i, j)(aa, bb) * msa_stats.frequency_1p(bb, j); } } else if (i > j) { for (int bb = 0; bb < Q; bb++) { phi += model->params.J(j, i)(bb, aa) * msa_stats.frequency_1p(bb, j); } } } delta = mcmc_stats->frequency_1p(aa, i) - msa_stats.frequency_1p(aa, i) + lambda_h * 0.5 * phi; delta_stat = (mcmc_stats->frequency_1p(aa, i) - msa_stats.frequency_1p(aa, i)) / (pow(msa_stats.frequency_1p(aa, i) * (1. - msa_stats.frequency_1p(aa, i)) / M_eff + pow(mcmc_stats->frequency_1p_sigma(aa, i), 2) + EPSILON, 0.5)); error_1p += pow(delta, 2); error_stat_1p += pow(delta_stat, 2); if (pow(delta, 2) > pow(deltamax_1, 2)) deltamax_1 = sqrt(pow(delta, 2)); if (sqrt(pow(delta_stat, 2)) > error_min_update) { model->gradient.h(aa, i) = -delta; count1++; } } } } else { for (int i = 0; i < N; i++) { for (int aa = 0; aa < Q; aa++) { delta = mcmc_stats->frequency_1p(aa, i) - msa_stats.frequency_1p(aa, i) + lambda_h * model->params.h(aa, i); delta_stat = (mcmc_stats->frequency_1p(aa, i) - msa_stats.frequency_1p(aa, i)) / (pow(msa_stats.frequency_1p(aa, i) * (1. - msa_stats.frequency_1p(aa, i)) / M_eff + pow(mcmc_stats->frequency_1p_sigma(aa, i), 2) + EPSILON, 0.5)); error_1p += pow(delta, 2); error_stat_1p += pow(delta_stat, 2); if (pow(delta, 2) > pow(deltamax_1, 2)) deltamax_1 = sqrt(pow(delta, 2)); if (sqrt(pow(delta_stat, 2)) > error_min_update) { model->gradient.h(aa, i) = -delta; count1++; } } } } double error_c = 0; double c_mc = 0, c_stat = 0; if (use_reparametrization) { for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { for (int aa1 = 0; aa1 < Q; aa1++) { for (int aa2 = 0; aa2 < Q; aa2++) { delta = -(msa_stats.frequency_2p(i, j)(aa1, aa2) - mcmc_stats->frequency_2p(i, j)(aa1, aa2) + (mcmc_stats->frequency_1p(aa1, i) - msa_stats.frequency_1p(aa1, i)) * msa_stats.frequency_1p(aa2, j) + (mcmc_stats->frequency_1p(aa2, j) - msa_stats.frequency_1p(aa2, j)) * msa_stats.frequency_1p(aa1, i) - lambda_j * model->params.J(i, j)(aa1, aa2)); delta_stat = (mcmc_stats->frequency_2p(i, j)(aa1, aa2) - msa_stats.frequency_2p(i, j)(aa1, aa2)) / (pow(msa_stats.frequency_2p(i, j)(aa1, aa2) * (1.0 - msa_stats.frequency_2p(i, j)(aa1, aa2)) / M_eff + pow(mcmc_stats->frequency_2p(i, j)(aa1, aa2), 2) + EPSILON, 0.5)); c_mc = mcmc_stats->frequency_2p(i, j)(aa1, aa2) - mcmc_stats->frequency_1p(aa1, i) * mcmc_stats->frequency_1p(aa2, j); c_stat = msa_stats.frequency_2p(i, j)(aa1, aa2) - msa_stats.frequency_1p(aa1, i) * msa_stats.frequency_1p(aa2, j); c_mc_av += c_mc; c_stat_av += c_stat; error_c += pow(c_mc - c_stat, 2); error_2p += pow(delta, 2); error_stat_2p += pow(delta_stat, 2); if (pow(delta, 2) > pow(deltamax_2, 2)) { deltamax_2 = sqrt(pow(delta, 2)); } if (sqrt(pow(delta_stat, 2)) > error_min_update) { model->gradient.J(i, j)(aa1, aa2) = -delta; count2++; } } } } } } else { for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { for (int aa1 = 0; aa1 < Q; aa1++) { for (int aa2 = 0; aa2 < Q; aa2++) { delta = -(msa_stats.frequency_2p(i, j)(aa1, aa2) - mcmc_stats->frequency_2p(i, j)(aa1, aa2) - lambda_j * model->params.J(i, j)(aa1, aa2)); delta_stat = (mcmc_stats->frequency_2p(i, j)(aa1, aa2) - msa_stats.frequency_2p(i, j)(aa1, aa2)) / (pow(msa_stats.frequency_2p(i, j)(aa1, aa2) * (1.0 - msa_stats.frequency_2p(i, j)(aa1, aa2)) / M_eff + pow(mcmc_stats->frequency_2p(i, j)(aa1, aa2), 2) + EPSILON, 0.5)); c_mc = mcmc_stats->frequency_2p(i, j)(aa1, aa2) - mcmc_stats->frequency_1p(aa1, i) * mcmc_stats->frequency_1p(aa2, j); c_stat = msa_stats.frequency_2p(i, j)(aa1, aa2) - msa_stats.frequency_1p(aa1, i) * msa_stats.frequency_1p(aa2, j); c_mc_av += c_mc; c_stat_av += c_stat; error_c += pow(c_mc - c_stat, 2); error_2p += pow(delta, 2); error_stat_2p += pow(delta_stat, 2); if (pow(delta, 2) > pow(deltamax_2, 2)) { deltamax_2 = sqrt(pow(delta, 2)); } if (sqrt(pow(delta_stat, 2)) > error_min_update) { model->gradient.J(i, j)(aa1, aa2) = -delta; count2++; } } } } } } c_stat_av /= ((N * (N - 1) * Q * Q) / 2); c_mc_av /= ((N * (N - 1) * Q * Q) / 2); num_rho = num_beta = den_stat = den_mc = den_beta = 0; for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { for (int aa1 = 0; aa1 < Q; aa1++) { for (int aa2 = 0; aa2 < Q; aa2++) { c_mc = mcmc_stats->frequency_2p(i, j)(aa1, aa2) - mcmc_stats->frequency_1p(aa1, i) * mcmc_stats->frequency_1p(aa2, j); c_stat = msa_stats.frequency_2p(i, j)(aa1, aa2) - msa_stats.frequency_1p(aa1, i) * msa_stats.frequency_1p(aa2, j); num_rho += (c_mc - c_mc_av) * (c_stat - c_stat_av); num_beta += (c_mc) * (c_stat); den_stat += pow(c_stat - c_stat_av, 2); den_mc += pow(c_mc - c_mc_av, 2); den_beta += pow(c_stat, 2); } } } } num_rho_1p = den_stat_1p = den_mc_1p = 0; for (int i = 0; i < N; i++) { for (int aa = 0; aa < Q; aa++) { num_rho_1p += (mcmc_stats->frequency_1p(aa, i) - 1.0 / Q) * (msa_stats.frequency_1p(aa, i) - 1.0 / Q); den_stat_1p += pow(msa_stats.frequency_1p(aa, i) - 1.0 / Q, 2); den_mc_1p += pow(mcmc_stats->frequency_1p(aa, i) - 1.0 / Q, 2); } } beta = num_beta / den_beta; rho = num_rho / sqrt(den_mc * den_stat); rho_1p = num_rho_1p / sqrt(den_mc_1p * den_stat_1p); error_1p = sqrt(error_1p / (N * Q)); error_2p = sqrt(error_2p / ((N * (N - 1) * Q * Q) / 2)); error_stat_1p = sqrt(error_stat_1p / (N * Q)); error_stat_2p = sqrt(error_stat_2p / (N * (N - 1) * Q * Q) / 2); error_c = sqrt(error_c / (N * (N - 1) * Q * Q) / 2); error_tot = error_1p + error_2p; error_stat_tot = error_stat_1p + error_stat_2p; return; }; void Sim::updateLearningRate(void) { int N = msa_stats.getN(); int Q = msa_stats.getQ(); double max_step_J = max_step_J_N / N; double alfa = 0; for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { for (int a = 0; a < Q; a++) { for (int b = 0; b < Q; b++) { alfa = model->gradient.J(i, j)(a, b) * model->gradient_prev.J(i, j)(a, b); alfa = Theta(alfa) * adapt_up + Theta(-alfa) * adapt_down + Delta(alfa); model->learning_rates.J(i, j)(a, b) = Min(max_step_J, Max(min_step_J, alfa * model->learning_rates.J(i, j)(a, b))); } } } } for (int i = 0; i < N; i++) { for (int a = 0; a < Q; a++) { alfa = model->gradient.h(a, i) * model->gradient_prev.h(a, i); alfa = Theta(alfa) * adapt_up + Theta(-alfa) * adapt_down + Delta(alfa); model->learning_rates.h(a, i) = Min(max_step_h, Max(min_step_h, alfa * model->learning_rates.h(a, i))); } } }; void Sim::updateReparameterization(void) { int N = msa_stats.getN(); int Q = msa_stats.getQ(); for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { for (int a = 0; a < Q; a++) { for (int b = 0; b < Q; b++) { model->params.J(i, j)(a, b) += model->learning_rates.J(i, j)(a, b) * model->gradient.J(i, j)(a, b); } } } } if (use_reparametrization) { arma::Mat<double> Dh = arma::Mat<double>(Q, N, arma::fill::zeros); for (int i = 0; i < N; i++) { for (int a = 0; a < Q; a++) { for (int j = 0; j < N; j++) { if (i < j) { for (int b = 0; b < Q; b++) { Dh(a, i) += msa_stats.frequency_1p(b, j) * model->learning_rates.J(i, j)(a, b) * model->gradient.J(i, j)(a, b); } } if (i > j) { for (int b = 0; b < Q; b++) { Dh(a, i) += msa_stats.frequency_1p(b, j) * model->learning_rates.J(j, i)(b, a) * model->gradient.J(j, i)(b, a); } } } } } for (int i = 0; i < N; i++) { for (int a = 0; a < Q; a++) { model->params.h(a, i) += model->learning_rates.h(a, i) * model->gradient.h(a, i) + 0.5 * Dh(a, i); } } } else { for (int i = 0; i < N; i++) { for (int a = 0; a < Q; a++) { model->params.h(a, i) += model->learning_rates.h(a, i) * model->gradient.h(a, i); } } } }; void Sim::writeData(int step) { if (output_binary) { model->writeParamsPrevious( "parameters_h_" + std::to_string(step - 1) + ".bin", "parameters_J_" + std::to_string(step - 1) + ".bin"); model->writeGradientPrevious( "gradients_h_" + std::to_string(step - 1) + ".bin", "gradients_J_" + std::to_string(step - 1) + ".bin"); model->writeParams("parameters_h_" + std::to_string(step) + ".bin", "parameters_J_" + std::to_string(step) + ".bin"); model->writeGradient("gradients_h_" + std::to_string(step) + ".bin", "gradients_J_" + std::to_string(step) + ".bin"); model->writeLearningRates( "learning_rates_h_" + std::to_string(step) + ".bin", "learning_rates_J_" + std::to_string(step) + ".bin"); mcmc_stats->writeFrequency1p("stat_MC_1p_" + std::to_string(step) + ".bin", "stat_MC_1p_sigma_" + std::to_string(step) + ".bin"); mcmc_stats->writeFrequency2p("stat_MC_2p_" + std::to_string(step) + ".bin", "stat_MC_2p_sigma_" + std::to_string(step) + ".bin"); } else { model->writeParamsPreviousAscii("parameters_" + std::to_string(step - 1) + ".txt"); model->writeGradientPreviousAscii("gradients_" + std::to_string(step - 1) + ".txt"); model->writeParamsAscii("parameters_" + std::to_string(step) + ".txt"); model->writeGradientAscii("gradients_" + std::to_string(step) + ".txt"); model->writeLearningRatesAscii("learning_rates_" + std::to_string(step) + ".txt"); mcmc_stats->writeFrequency1pAscii( "stat_MC_1p_" + std::to_string(step) + ".txt", "stat_MC_1p_sigma_" + std::to_string(step) + ".txt"); mcmc_stats->writeFrequency2pAscii( "stat_MC_2p_" + std::to_string(step) + ".txt", "stat_MC_2p_sigma_" + std::to_string(step) + ".txt"); } mcmc_stats->writeSamples("MC_samples_" + std::to_string(step) + ".txt"); mcmc_stats->writeSampleEnergies("MC_energies_" + std::to_string(step) + ".txt"); if (check_ergo) { mcmc_stats->writeCorrelationsStats( "overlap_" + std::to_string(step) + ".txt", "overlap_inf_" + std::to_string(step) + ".txt", "ergo_" + std::to_string(step) + ".txt"); } }; void Sim::writeData(std::string id) { if (output_binary) { model->writeParams("parameters_h_" + id + ".bin", "parameters_J_" + id + ".bin"); model->writeGradient("gradients_h_" + id + ".bin", "gradients_J_" + id + ".bin"); model->writeLearningRates("learning_rates_h_" + id + ".bin", "learning_rates_J_" + id + ".bin"); mcmc_stats->writeFrequency1p("stat_MC_1p_" + id + ".bin", "stat_MC_1p_sigma_" + id + ".bin"); mcmc_stats->writeFrequency2p("stat_MC_2p_" + id + ".bin", "stat_MC_2p_sigma_" + id + ".bin"); } else { model->writeParamsAscii("parameters_" + id + ".txt"); model->writeGradientAscii("gradients_" + id + ".txt"); model->writeLearningRatesAscii("learning_rates_" + id + ".txt"); mcmc_stats->writeFrequency1pAscii("stat_MC_1p_" + id + ".txt", "stat_MC_1p_sigma_" + id + ".txt"); mcmc_stats->writeFrequency2pAscii("stat_MC_2p_" + id + ".txt", "stat_MC_2p_sigma_" + id + ".txt"); } mcmc_stats->writeSamples("MC_samples_" + id + ".txt"); mcmc_stats->writeSampleEnergies("MC_energies_" + id + ".txt"); if (check_ergo) { mcmc_stats->writeCorrelationsStats("overlap_" + id + ".txt", "overlap_inf_" + id + ".txt", "ergo_" + id + ".txt"); } }; void Sim::initializeRunLog() { std::ofstream stream{ run_log_file, std::ios_base::out }; stream << "step" << "\t" << "reps" << "\t" << "burn-in" << "\t" << "burn-between" << "\t"; if (check_ergo) { stream << "auto-corr" << "\t" << "cross-corr" << "\t" << "check-corr" << "\t" << "auto-cross-err" << "\t" << "cross-check-err" << "\t" << "energy-start-avg" << "\t" << "sigma-energy-start-sigma" << "\t" << "energy-end-avg" << "\t" << "energy-end-sigma" << "\t" << "energy-err" << "\t"; } stream << "error-h" << "\t" << "error-J" << "\t" << "error-tot" << "\t" << "error-tot-min" << "\t" << "seed" << "\t" << "step-time" << std::endl; stream.close(); }; void Sim::writeRunLog(int current_step, int offset, bool keep) { std::ofstream stream{ run_log_file, std::ios_base::app }; int n_entries; if (current_step == 0) { n_entries = save_parameters; } else { n_entries = current_step; } for (int i = 0 + offset; i < n_entries; i++) { stream << (int)run_buffer(i, 0) << "\t"; stream << (int)run_buffer(i, 1) << "\t"; stream << (int)run_buffer(i, 2) << "\t"; stream << (int)run_buffer(i, 3) << "\t"; if (check_ergo) { stream << run_buffer(i, 4) << "\t"; stream << run_buffer(i, 5) << "\t"; stream << run_buffer(i, 6) << "\t"; stream << run_buffer(i, 7) << "\t"; stream << run_buffer(i, 8) << "\t"; stream << run_buffer(i, 9) << "\t"; stream << run_buffer(i, 10) << "\t"; stream << run_buffer(i, 11) << "\t"; stream << run_buffer(i, 12) << "\t"; stream << run_buffer(i, 13) << "\t"; } stream << run_buffer(i, 14) << "\t"; stream << run_buffer(i, 15) << "\t"; stream << run_buffer(i, 16) << "\t"; stream << run_buffer(i, 17) << "\t"; stream << (long int)run_buffer(i, 18) << "\t"; stream << run_buffer(i, 19) << std::endl; } if (!keep) { run_buffer.zeros(); } stream.close(); };
49,342
C++
.cpp
1,356
29.132006
80
0.528828
ranganathanlab/bmDCA
33
12
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,854
msa_stats.cpp
ranganathanlab_bmDCA/src/msa_stats.cpp
#include "msa_stats.hpp" #include <armadillo> #include <cmath> #include <fstream> #include <iostream> MSAStats::MSAStats(MSA msa) { // Initialize N = msa.N; M = msa.M; Q = msa.Q; M_effective = sum(msa.sequence_weights); std::cout << M << " sequences" << std::endl; std::cout << N << " positions" << std::endl; std::cout << Q << " amino acids (including gaps)" << std::endl; std::cout << M_effective << " effective sequences" << std::endl; frequency_1p = arma::Mat<double>(Q, N, arma::fill::zeros); frequency_2p = arma::field<arma::Mat<double>>(N, N); rel_entropy_1p = arma::Mat<double>(Q, N, arma::fill::zeros); rel_entropy_pos_1p = arma::Col<double>(N, arma::fill::zeros); rel_entropy_grad_1p = arma::Mat<double>(Q, N, arma::fill::zeros); aa_background_frequencies = arma::Col<double>(Q, arma::fill::ones); if (Q == 21) { aa_background_frequencies = { 0.000, 0.073, 0.025, 0.050, 0.061, 0.042, 0.072, 0.023, 0.053, 0.064, 0.089, 0.023, 0.043, 0.052, 0.040, 0.052, 0.073, 0.056, 0.063, 0.013, 0.033 }; } else { aa_background_frequencies = aa_background_frequencies / (double)Q; } pseudocount = 0.03; // Compute the frequecies (1p statistics) for amino acids (and gaps) for each // position. Use pointers to make things speedier. #pragma omp parallel { #pragma omp for for (int i = 0; i < N; i++) { int* align_ptr = msa.alignment.colptr(i); double* freq_ptr = frequency_1p.colptr(i); double* weight_ptr = msa.sequence_weights.memptr(); for (int m = 0; m < M; m++) { *(freq_ptr + *(align_ptr + m)) += *(weight_ptr + m); } } } frequency_1p = frequency_1p / M_effective; double mean_1p_var = arma::accu(frequency_1p % (1. - frequency_1p)) / (double)(N*Q); // Compute the 2p statistics arma::Col<double> mean_2p_var_vec = arma::Col<double>(N, arma::fill::zeros); #pragma omp parallel { #pragma omp for schedule(dynamic,1) for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { double* weight_ptr = msa.sequence_weights.memptr(); frequency_2p(i, j) = arma::Mat<double>(Q, Q, arma::fill::zeros); int* align_ptr1 = msa.alignment.colptr(i); int* align_ptr2 = msa.alignment.colptr(j); for (int m = 0; m < M; m++) { frequency_2p(i, j)(*(align_ptr1 + m), *(align_ptr2 + m)) += *(weight_ptr + m); } frequency_2p(i, j) = frequency_2p(i, j) / M_effective; mean_2p_var_vec(i) += arma::accu(frequency_2p(i, j) % (1. - frequency_2p(i, j))); } } } double mean_2p_var = arma::accu(mean_2p_var_vec) / (double)(N * (N - 1) / 2 * Q * Q); freq_rms = sqrt(mean_1p_var) + sqrt(mean_2p_var); // Update the background frequencies based by computing overall gap frequency // theta. double theta = 0; for (int i = 0; i < N; i++) { theta += frequency_1p(0, i); } theta = theta / N; aa_background_frequencies[0] = theta; for (int i = 1; i < Q; i++) { aa_background_frequencies[i] = aa_background_frequencies[i] * (1. - theta); } // Use the positonal and backgrounds frequencies to estimate the relative // entropy gradient for each position. arma::Mat<double> tmp = frequency_1p * (1. - pseudocount); tmp.each_col() += pseudocount * aa_background_frequencies; for (int i = 0; i < N; i++) { for (int aa = 0; aa < Q; aa++) { double pos_freq = tmp(aa, i); double background_freq = aa_background_frequencies(aa); if (pos_freq < 1. && pos_freq > 0.) { rel_entropy_pos_1p(i) += pos_freq * log(pos_freq / background_freq); rel_entropy_1p(aa, i) = pos_freq * log(pos_freq / background_freq) + (1 - pos_freq) * log((1 - pos_freq) / (1 - background_freq)); rel_entropy_grad_1p(aa, i) = log((pos_freq * (1. - background_freq)) / ((1. - pos_freq) * background_freq)); } } } }; double MSAStats::getQ(void) { return Q; }; double MSAStats::getM(void) { return M; }; double MSAStats::getN(void) { return N; }; double MSAStats::getEffectiveM(void) { return M_effective; }; void MSAStats::writeRelEntropyGradient(std::string output_file) { rel_entropy_grad_1p.save(output_file, arma::arma_binary); }; void MSAStats::writeRelEntropyGradientAscii(std::string output_file) { std::ofstream output_stream(output_file); for (int i = 0; i < N; i++) { output_stream << i; for (int aa = 0; aa < Q; aa++) { output_stream << " " << rel_entropy_grad_1p(aa, i); } output_stream << std::endl; } }; // void // MSAStats::writeRelEntropyPos(std::string output_file) // { // rel_entropy_pos_1p.save(output_file, arma::arma_binary); // }; void MSAStats::writeRelEntropyPosAscii(std::string output_file) { std::ofstream output_stream(output_file); for (int i = 0; i < N; i++) { output_stream << " " << rel_entropy_pos_1p(i) << std::endl; } }; void MSAStats::writeRelEntropy(std::string output_file) { rel_entropy_1p.save(output_file, arma::arma_binary); }; void MSAStats::writeRelEntropyAscii(std::string output_file) { std::ofstream output_stream(output_file); for (int i = 0; i < N; i++) { output_stream << i; for (int aa = 0; aa < Q; aa++) { output_stream << " " << rel_entropy_1p(aa, i); } output_stream << std::endl; } }; void MSAStats::writeFrequency1p(std::string output_file) { frequency_1p.save(output_file, arma::arma_binary); }; void MSAStats::writeFrequency1pAscii(std::string output_file) { std::ofstream output_stream(output_file); for (int i = 0; i < N; i++) { output_stream << i; for (int aa = 0; aa < Q; aa++) { output_stream << " " << frequency_1p(aa, i); } output_stream << std::endl; } }; void MSAStats::writeFrequency2p(std::string output_file) { frequency_2p.save(output_file, arma::arma_binary); }; void MSAStats::writeFrequency2pAscii(std::string output_file) { std::ofstream output_stream(output_file); for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { output_stream << i << " " << j; for (int aa1 = 0; aa1 < Q; aa1++) { for (int aa2 = 0; aa2 < Q; aa2++) { output_stream << " " << frequency_2p(i, j)(aa1, aa2); } } output_stream << std::endl; } } };
6,429
C++
.cpp
207
26.681159
79
0.597837
ranganathanlab/bmDCA
33
12
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,855
mcmc_stats.cpp
ranganathanlab_bmDCA/src/mcmc_stats.cpp
#include "mcmc_stats.hpp" #include <armadillo> #include <iostream> #include "utils.hpp" MCMCStats::MCMCStats(arma::Cube<int>* s, potts_model* p) { M = s->n_rows; N = s->n_cols; reps = s->n_slices; Q = p->h.n_rows; samples = s; params = p; computeEnergies(); }; void MCMCStats::updateData(arma::Cube<int>* s, potts_model* p) { samples = s; params = p; computeEnergies(); }; void MCMCStats::computeEnergies(void) { energies = arma::Mat<double>(reps, M, arma::fill::zeros); #pragma omp parallel { #pragma omp for for (int rep = 0; rep < reps; rep++) { for (int seq = 0; seq < M; seq++) { double E = 0; for (int i = 0; i < N; i++) { E -= params->h(samples->at(seq, i, rep), i); for (int j = i + 1; j < N; j++) { E -= params->J(i, j)(samples->at(seq, i, rep), samples->at(seq, j, rep)); } } energies(rep, seq) = E; } } } }; void MCMCStats::computeEnergiesStats(void) { energies_relax = arma::Row<double>(M); energies_relax_sigma = arma::Row<double>(M); energies_start_avg = arma::mean(energies.col(0)); energies_start_sigma = arma::stddev(energies.col(0), 1); energies_end_avg = arma::mean(energies.col(M - 1)); energies_end_sigma = arma::stddev(energies.col(M - 1), 1); energies_err = sqrt((pow(energies_start_sigma, 2) + pow(energies_end_sigma, 2)) / reps); energies_relax = arma::mean(energies, 0); energies_relax_sigma = arma::stddev(energies, 1, 0); }; void MCMCStats::writeEnergyStats(std::string output_file_start, std::string output_file_end, std::string output_file_cfr, std::string output_file_cfr_err) { std::ofstream output_stream_start(output_file_start); std::ofstream output_stream_end(output_file_end); std::ofstream output_stream_cfr(output_file_cfr); std::ofstream output_stream_cfr_err(output_file_cfr_err); for (int rep = 0; rep < reps; rep++) { output_stream_start << energies(rep, 0) << std::endl; output_stream_end << energies(rep, M - 1) << std::endl; } output_stream_cfr << reps << " " << energies_start_avg << " " << energies_start_sigma << " " << reps << " " << energies_end_avg << " " << energies_end_sigma << std::endl; output_stream_cfr_err << energies_start_avg << " " << energies_end_avg << " " << energies_err << std::endl; }; void MCMCStats::computeCorrelations(void) { arma::Col<double> d = arma::Col<double>(M, arma::fill::zeros); arma::Col<double> d2 = arma::Col<double>(M, arma::fill::zeros); arma::Col<int> count = arma::Col<int>(M, arma::fill::zeros); arma::Mat<double> d_mat = arma::Mat<double>(reps, M, arma::fill::zeros); arma::Mat<double> d2_mat = arma::Mat<double>(reps, M, arma::fill::zeros); arma::Mat<int> count_mat = arma::Mat<int>(reps, M, arma::fill::zeros); // Compute distances within replicates #pragma omp parallel { #pragma omp for schedule(dynamic,1) for (int rep = 0; rep < reps; rep++) { arma::Mat<int> slice = (samples->slice(rep)).t(); for (int seq1 = 0; seq1 < M; seq1++) { int* seq1_ptr = slice.colptr(seq1); for (int seq2 = seq1 + 1; seq2 < M; seq2++) { int* seq2_ptr = slice.colptr(seq2); int id = 0; for (int i = 0; i < N; i++) { if (*(seq1_ptr + i) == *(seq2_ptr + i)) { id++; } } d_mat(rep, seq2 - seq1) += (double)id / N; d2_mat(rep, seq2 - seq1) += (double)id * id / (N * N); count_mat(rep, seq2 - seq1)++; } } } } d = arma::sum(d_mat, 0).t(); d2 = arma::sum(d2_mat, 0).t(); count = arma::sum(count_mat, 0).t(); arma::Col<double> dinf_col = arma::Col<double>(M, arma::fill::zeros); arma::Col<double> dinf2_col = arma::Col<double>(M, arma::fill::zeros); // Compute distances between replicates #pragma omp parallel { #pragma omp for schedule(dynamic,1) for (int seq = 0; seq < M; seq++) { for (int rep1 = 0; rep1 < reps; rep1++) { for (int rep2 = rep1 + 1; rep2 < reps; rep2++) { int id = 0; for (int i = 0; i < N; i++) { if (samples->at(seq, i, rep1) == samples->at(seq, i, rep2)) { id++; } } dinf_col(seq) += (double)id / N; dinf2_col(seq) += (double)(id * id) / (N * N); } } } } double dinf = arma::sum(dinf_col); double dinf2 = arma::sum(dinf2_col); overlaps = arma::Col<double>(M - 2, arma::fill::zeros); overlaps_sigma = arma::Col<double>(M - 2, arma::fill::zeros); for (int i = 1; i < M - 1; i++) { overlaps(i - 1) = (double)d(i) / (double)count(i); overlaps_sigma(i - 1) = sqrt(1.0 / count(i)) * sqrt(d2(i) / (double)(count(i)) - pow(d(i) / (double)(count(i)), 2)); } overlap_inf = 2.0 * dinf / (double)(reps * (reps - 1) * M); overlap_inf_sigma = sqrt(2.0 / (reps * (reps - 1) * M)) * sqrt(2.0 * dinf2 / (double)(reps * (reps - 1) * M) - pow(2.0 * dinf / (double)(reps * (reps - 1) * M), 2)); int i_auto = 1; int i_check = Max((double)M / 10.0, 1.0); overlap_cross = (double)2.0 * dinf / (double)(reps * (reps - 1) * M); overlap_auto = d(i_auto) / (double)(count(i_auto)); overlap_check = d(i_check) / (double)(count(i_check)); sigma_cross = sqrt(2.0 * dinf2 / (double)(reps * (reps - 1) * M) - pow(2.0 * dinf / (double)(reps * (reps - 1) * M), 2)); sigma_auto = sqrt(d2(i_auto) / (double)(count(i_auto)) - pow(d(i_auto) / (double)(count(i_auto)), 2)); sigma_check = sqrt(d2(i_check) / (double)(count(i_check)) - pow(d(i_check) / (double)(count(i_check)), 2)); err_cross_auto = sqrt(pow(sigma_cross, 2) + pow(sigma_auto, 2)) / sqrt(reps); err_cross_check = sqrt(pow(sigma_cross, 2) + pow(sigma_check, 2)) / sqrt(reps); err_check_auto = sqrt(pow(sigma_check, 2) + pow(sigma_auto, 2)) / sqrt(reps); }; void MCMCStats::writeCorrelationsStats(std::string overlap_file, std::string overlap_inf_file, std::string ergo_file) { std::ofstream output_stream_overlap(overlap_file); std::ofstream output_stream_overlap_inf(overlap_inf_file); std::ofstream output_stream_ergo(ergo_file); for (int i = 0; i < M - 2; i++) { output_stream_overlap << i << " " << overlaps(i) << " " << overlaps_sigma(i) << std::endl; } output_stream_overlap_inf << "0 " << overlap_inf << " " << overlap_inf_sigma << std::endl; output_stream_overlap_inf << M << " " << overlap_inf << " " << overlap_inf_sigma << std::endl; output_stream_ergo << overlap_auto << " " << overlap_check << " " << overlap_cross << " " << sigma_auto << " " << sigma_check << " " << sigma_cross << " " << err_cross_auto << " " << err_cross_check << " " << err_check_auto << std::endl; }; std::vector<double> MCMCStats::getEnergiesStats(void) { std::vector<double> values = { energies_start_avg, energies_start_sigma, energies_end_avg, energies_end_sigma, energies_err }; return values; }; std::vector<double> MCMCStats::getCorrelationsStats(void) { std::vector<double> values = { overlap_inf, overlap_inf_sigma, overlap_auto, overlap_cross, overlap_check, sigma_auto, sigma_cross, sigma_check, err_cross_auto, err_cross_check, err_check_auto }; return values; }; void MCMCStats::computeSampleStats(void) { frequency_1p = arma::Mat<double>(Q, N, arma::fill::zeros); frequency_1p_sigma = arma::Mat<double>(Q, N, arma::fill::zeros); frequency_2p = arma::field<arma::Mat<double>>(N, N); frequency_2p_sigma = arma::field<arma::Mat<double>>(N, N); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { frequency_2p(i, j) = arma::Mat<double>(Q, Q, arma::fill::zeros); frequency_2p_sigma(i, j) = arma::Mat<double>(Q, Q, arma::fill::zeros); } } #pragma omp parallel { #pragma omp for for (int i = 0; i < N; i++) { arma::Mat<double> n1 = arma::Mat<double>(Q, reps, arma::fill::zeros); arma::Col<double> n1squared = arma::Col<double>(Q, arma::fill::zeros); arma::Col<double> n1av = arma::Col<double>(Q, arma::fill::zeros); for (int rep = 0; rep < reps; rep++) { for (int m = 0; m < M; m++) { n1(samples->at(m, i, rep), rep)++; } } for (int aa = 0; aa < Q; aa++) { for (int rep = 0; rep < reps; rep++) { n1av(aa) += n1(aa, rep); n1squared(aa) += pow(n1(aa, rep), 2); } frequency_1p(aa, i) = n1av(aa) / M / reps; frequency_1p_sigma(aa, i) = Max(sqrt((n1squared(aa) / (M * M * reps) - pow(n1av(aa) / (M * reps), 2)) / sqrt(reps)), 0); } } } #pragma omp parallel { #pragma omp for schedule(dynamic,1) for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { arma::Cube<double> n2 = arma::Cube<double>(reps, Q, Q, arma::fill::zeros); arma::Mat<double> n2av = arma::Mat<double>(Q, Q, arma::fill::zeros); arma::Mat<double> n2squared = arma::Mat<double>(Q, Q, arma::fill::zeros); for (int rep = 0; rep < reps; rep++) for (int m = 0; m < M; m++) { n2(rep, samples->at(m, i, rep), samples->at(m, j, rep))++; } n2av = arma::sum(n2, 0) / (M * reps); n2squared = arma::sum(arma::pow(n2, 2), 0) / (M * reps); frequency_2p(i, j) = n2av; frequency_2p_sigma(i, j) = arma::pow((n2squared / M - arma::pow(n2av, 2)) / sqrt(reps), .5); } } } }; void MCMCStats::computeSampleStatsImportance(potts_model* cur, potts_model* prev) { arma::Mat<double> p = arma::Mat<double>(reps, M, arma::fill::zeros); arma::Mat<double> dE = arma::Mat<double>(reps, M, arma::fill::zeros); arma::Col<double> dE_av = arma::Col<double>(reps, arma::fill::zeros); arma::Col<double> Z = arma::Col<double>(reps, arma::fill::zeros); arma::Col<double> Z_inv = arma::Col<double>(reps, arma::fill::zeros); arma::Col<double> sum = arma::Col<double>(reps, arma::fill::zeros); arma::Col<double> w = arma::Col<double>(reps, arma::fill::zeros); double Z_tot = 0; double Z_inv_tot = 0; double W = 0; double sumw = 0; Z_ratio = 0; sumw_inv = 0; dE_av_tot = 0; for (int rep = 0; rep < reps; rep++) { for (int m = 0; m < M; m++) { for (int i = 0; i < N; i++) { dE(rep, m) += cur->h(samples->at(m, i, rep)) - prev->h(samples->at(m, i, rep)); for (int j = i + 1; j < N; j++) { dE(rep, m) += cur->J(i, j)(samples->at(m, i, rep), samples->at(m, j, rep)) - prev->J(i, j)(samples->at(m, i, rep), samples->at(m, j, rep)); } } dE_av(rep) += dE(rep, m); } dE_av(rep) = dE_av(rep) / M; dE_av_tot += dE_av(rep); } for (int rep = 0; rep < reps; rep++) { for (int m = 0; m < M; m++) { p(rep, m) = exp(dE(rep, m) - dE_av(rep)); Z(rep) += p(rep, m); Z_inv(rep) += 1. / p(rep, m); } for (int m = 0; m < M; m++) { p(rep, m) = p(rep, m) / Z(rep); sum(rep) += pow(p(rep, m), 2); } Z_tot += Z(rep); Z_inv_tot += Z_inv(rep); w(rep) = 1. / sum(rep); W += w(rep); } for (int rep = 0; rep < reps; rep++) { w(rep) = w(rep) / W; sumw += pow(w(rep), 2); } arma::Mat<int> n1 = arma::Mat<int>(Q, reps, arma::fill::zeros); arma::field<arma::Mat<int>> n2 = arma::field<arma::Mat<int>>(reps); for (int rep = 0; rep < reps; rep++) { n2(rep) = arma::Mat<int>(Q, Q, arma::fill::zeros); } Z_ratio = Z_tot / Z_inv_tot; sumw_inv = 1.0 / sumw; arma::Col<int> n1av = arma::Col<int>(Q, arma::fill::zeros); arma::Mat<int> n2av = arma::Mat<int>(Q, Q, arma::fill::zeros); arma::Col<int> n1squared = arma::Col<int>(Q, arma::fill::zeros); arma::Mat<int> n2squared = arma::Mat<int>(Q, Q, arma::fill::zeros); for (int i = 0; i < N; i++) { n1.zeros(); n1av.zeros(); n1squared.zeros(); for (int rep = 0; rep < reps; rep++) { for (int m = 0; m < M; m++) { n1(samples->at(m, i, rep), rep) += p(rep, m); } } for (int aa = 0; aa < Q; aa++) { for (int rep = 0; rep < reps; rep++) { n1av(aa) += w(rep) * n1(aa, rep); n1squared(aa) += w(rep) * pow(n1(aa, rep), 2); } frequency_1p(aa, i) = (double)n1av(aa); frequency_1p_sigma(aa, i) = Max( sqrt(((double)n1squared(aa) - pow((double)n1av(aa), 2)) * sqrt(sumw)), 0); } } for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { for (int rep = 0; rep < reps; rep++) { n2(rep).zeros(); } n2av.zeros(); n2squared.zeros(); for (int rep = 0; rep < reps; rep++) for (int m = 0; m < M; m++) { n2(rep)(samples->at(m, i, rep), samples->at(m, j, rep)) += p(rep, m); } for (int aa1 = 0; aa1 < Q; aa1++) { for (int aa2 = 0; aa2 < Q; aa2++) { for (int rep = 0; rep < reps; rep++) { n2av(aa1, aa2) += w(rep) * n2(rep)(aa1, aa2); n2squared(aa1, aa2) += w(rep) * pow(n2(rep)(aa1, aa2), 2); } frequency_2p(i, j)(aa1, aa2) = (double)n2av(aa1, aa2); frequency_2p_sigma(i, j)(aa1, aa2) = Max(sqrt(((double)n2squared(aa1, aa2) - pow((double)n2av(aa1, aa2), 2)) * sqrt(sumw)), 0); } } } } }; void MCMCStats::writeFrequency1p(std::string output_file, std::string output_file_sigma) { frequency_1p.save(output_file, arma::arma_binary); frequency_1p_sigma.save(output_file_sigma, arma::arma_binary); }; void MCMCStats::writeFrequency1pAscii(std::string output_file, std::string output_file_sigma) { std::ofstream output_stream(output_file); std::ofstream output_stream_sigma(output_file_sigma); for (int i = 0; i < N; i++) { output_stream << i; output_stream_sigma << i; for (int aa = 0; aa < Q; aa++) { output_stream << " " << frequency_1p(aa, i); output_stream_sigma << " " << frequency_1p_sigma(aa, i); } output_stream << std::endl; output_stream_sigma << std::endl; } }; void MCMCStats::writeFrequency2p(std::string output_file, std::string output_file_sigma) { frequency_2p.save(output_file, arma::arma_binary); frequency_2p_sigma.save(output_file_sigma, arma::arma_binary); }; void MCMCStats::writeFrequency2pAscii(std::string output_file, std::string output_file_sigma) { std::ofstream output_stream(output_file); std::ofstream output_stream_sigma(output_file_sigma); for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { output_stream << i << " " << j; output_stream_sigma << i << " " << j; for (int aa1 = 0; aa1 < Q; aa1++) { for (int aa2 = 0; aa2 < Q; aa2++) { output_stream << " " << frequency_2p(i, j)(aa1, aa2); output_stream_sigma << " " << frequency_2p_sigma(i, j)(aa1, aa2); } } output_stream << std::endl; output_stream_sigma << std::endl; } } }; void MCMCStats::writeSamples(std::string output_file) { std::ofstream output_stream(output_file); output_stream << reps * M << " " << N << " " << Q << std::endl; for (int rep = 0; rep < reps; rep++) { for (int m = 0; m < M; m++) { output_stream << samples->at(m, 0, rep); for (int i = 1; i < N; i++) { output_stream << " " << samples->at(m, i, rep); } output_stream << std::endl; } } }; void MCMCStats::writeSampleEnergies(std::string output_file) { std::ofstream output_stream(output_file); for (int rep = 0; rep < reps; rep++) { for (int m = 0; m < M; m++) { output_stream << energies(rep, m) << std::endl; } } }; void MCMCStats::writeSampleEnergiesRelaxation(std::string output_file, int t_wait) { std::ofstream output_stream(output_file); for (int m = 0; m < M; m++) { output_stream << m * t_wait << " " << energies_relax(m) << " " << energies_relax_sigma(m) << std::endl; } };
16,756
C++
.cpp
464
29.385776
80
0.529202
ranganathanlab/bmDCA
33
12
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,856
utils.cpp
ranganathanlab_bmDCA/src/utils.cpp
#include "utils.hpp" #include <cstdio> #include <dirent.h> #include <fstream> #include <iostream> #include <string> #include <sys/types.h> SeqRecord::SeqRecord(std::string h, std::string s) : header(h) , sequence(s){}; void SeqRecord::print(void) { std::cout << ">" << header << std::endl; std::cout << sequence << std::endl; }; std::string SeqRecord::getRecord(void) { std::string record_string = ">" + header + "\n" + sequence + "\n"; return record_string; }; std::string SeqRecord::getHeader(void) { return header; }; std::string SeqRecord::getSequence(void) { return sequence; }; potts_model loadPottsModel(std::string h_file, std::string J_file) { potts_model params; params.h.load(h_file); params.J.load(J_file); return params; }; potts_model loadPottsModelAscii(std::string parameters_file) { std::ifstream input_stream(parameters_file); if (!input_stream) { std::cerr << "ERROR: couldn't open '" << parameters_file << "' for reading." << std::endl; std::exit(EXIT_FAILURE); } int N = 0; int Q = 0; int count = 1; int n1, n2, aa1, aa2; double value; std::string tmp = ""; std::getline(input_stream, tmp); while (std::getline(input_stream, tmp)) { input_stream >> tmp; input_stream >> n1 >> n2 >> aa1 >> aa2; input_stream >> value; count++; if ((n1 == 1) & (N == 0)) { N = count; } if ((aa2 == 0) & (Q == 0)) { Q = count; } if ((N != 0) & (Q != 0)) break; } N = (int)((double)N / (double)Q / double(Q)) + 1; input_stream.clear(); input_stream.seekg(0); potts_model params; params.h = arma::Mat<double>(Q, N, arma::fill::zeros); params.J = arma::field<arma::Mat<double>>(N, N); for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { params.J(i, j) = arma::Mat<double>(Q, Q, arma::fill::zeros); } } for (int count = 0; count < (int)N * (N - 1) / 2 * Q * Q; count++) { input_stream >> tmp; input_stream >> n1 >> n2 >> aa1 >> aa2; input_stream >> value; params.J(n1, n2)(aa1, aa2) = value; } for (int count = 0; count < N * Q; count++) { input_stream >> tmp; input_stream >> n1 >> aa1; input_stream >> value; params.h(aa1, n1) = value; } return params; }; void convertFrequencyToAscii(std::string stats_file) { int idx = stats_file.find_last_of("."); std::string stats_name = stats_file.substr(0, idx); std::string stats_ext = stats_file.substr(idx + 1); if (stats_ext != "bin") { std::cerr << "ERROR: input file does not have 'bin' extension." << std::endl; return; } // Guess if 1p vs 2p statistics bool is_1p = false; bool is_2p = false; if (stats_name.find("_1p") != std::string::npos) { is_1p = true; } else if (stats_name.find("_2p") != std::string::npos) { is_2p = true; } std::string output_file = stats_name + ".txt"; std::ofstream output_stream(output_file); if (is_1p) { arma::Mat<double> frequency_1p; frequency_1p.load(stats_file, arma::arma_binary); int N = frequency_1p.n_cols; int Q = frequency_1p.n_rows; for (int i = 0; i < N; i++) { output_stream << i; for (int aa = 0; aa < Q; aa++) { output_stream << " " << frequency_1p(aa, i); } output_stream << std::endl; } } else if (is_2p) { arma::field<arma::Mat<double>> frequency_2p; frequency_2p.load(stats_file, arma::arma_binary); int N = frequency_2p.n_rows; int Q = frequency_2p(0, 1).n_rows; for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { output_stream << i << " " << j; for (int aa1 = 0; aa1 < Q; aa1++) { for (int aa2 = 0; aa2 < Q; aa2++) { output_stream << " " << frequency_2p(i, j)(aa1, aa2); } } output_stream << std::endl; } } } else { // if name doesn't say if 1p or 2p, load files and guess again arma::Mat<double> frequency_1p; frequency_1p.load(stats_file, arma::arma_binary); int N = frequency_1p.n_cols; int Q = frequency_1p.n_rows; if ((Q != 0) & (N != 0)) { // 1p for (int i = 0; i < N; i++) { output_stream << i; for (int aa = 0; aa < Q; aa++) { output_stream << " " << frequency_1p(aa, i); } output_stream << std::endl; } } else { // 2p arma::field<arma::Mat<double>> frequency_2p; frequency_2p.load(stats_file, arma::arma_binary); int N = frequency_2p.n_rows; int Q = frequency_2p(0, 1).n_rows; for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { output_stream << i << " " << j; for (int aa1 = 0; aa1 < Q; aa1++) { for (int aa2 = 0; aa2 < Q; aa2++) { output_stream << " " << frequency_2p(i, j)(aa1, aa2); } } output_stream << std::endl; } } } } }; void convertParametersToAscii(std::string h_file, std::string J_file) { // Check file extensions and parse out file names. int idx = h_file.find_last_of("."); std::string h_name = h_file.substr(0, idx); std::string h_ext = h_file.substr(idx + 1); idx = J_file.find_last_of("."); std::string J_name = J_file.substr(0, idx); std::string J_ext = J_file.substr(idx + 1); if ((J_ext != "bin") & (h_ext != "bin")) { std::cerr << "ERROR: input parameters do not have 'bin' extension." << std::endl; std::exit(EXIT_FAILURE); } arma::Mat<double> h; h.load(h_file, arma::arma_binary); int N = h.n_cols; int Q = h.n_rows; arma::field<arma::Mat<double>> J(N, N); J.load(J_file, arma::arma_binary); if ((N != (int)J.n_rows) & (N != (int)J.n_cols)) { std::cerr << "ERROR: parameters dimension mismatch." << std::endl; return; } if ((Q != (int)J(0, 1).n_cols) & (Q != (int)J(0, 1).n_rows)) { std::cerr << "ERROR: parameters dimension mismatch." << std::endl; std::exit(EXIT_FAILURE); } // Generate an output file name. std::string output_file; for (int i = 0; i < Min(h_name.size(), J_name.size()); i++) { if (h_name[i] == J_name[i]) { if ((output_file.back() == '_') && (h_name[i] == '_')) continue; output_file += h_name[i]; } } if (output_file.back() == '_') output_file.pop_back(); std::ofstream output_stream(output_file + ".txt"); // Write J for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { for (int aa1 = 0; aa1 < Q; aa1++) { for (int aa2 = 0; aa2 < Q; aa2++) { output_stream << "J " << i << " " << j << " " << aa1 << " " << aa2 << " " << J(i, j)(aa1, aa2) << std::endl; } } } } // Write h for (int i = 0; i < N; i++) { for (int aa = 0; aa < Q; aa++) { output_stream << "h " << i << " " << aa << " " << h(aa, i) << std::endl; } } return; }; int Theta(double x) { if (x > 0) return 1; return 0; }; int Delta(double x) { if (x == 0) return 1; return 0; }; double Max(double a, double b) { if (a > b) return a; return b; }; double Min(double a, double b) { if (a < b) return a; return b; }; int deleteFile(std::string filename) { std::fstream fs; fs.open(filename); if (!fs.fail()) { if (std::remove(filename.c_str()) != 0) { fs.close(); return 1; } } fs.close(); return 0; }; bool checkFileExists(std::string filename) { std::fstream fs; fs.open(filename); if (fs.fail()) { fs.close(); return false; } else { fs.close(); return true; } }; void deleteAllFiles(std::string directory) { DIR* dp; struct dirent* dirp; dp = opendir("."); std::vector<int> steps; while ((dirp = readdir(dp)) != NULL) { std::string fname = dirp->d_name; if (fname == ".") continue; if (fname == "..") continue; if (std::remove(fname.c_str()) != 0) { std::cerr << "ERROR: deletion of '" << fname << "' failed." << std::endl; } } closedir(dp); return; }; char convertAA(int n) { char aa = '\0'; switch (n) { case 0: aa = '-'; break; case 1: aa = 'A'; break; case 2: aa = 'C'; break; case 3: aa = 'D'; break; case 4: aa = 'E'; break; case 5: aa = 'F'; break; case 6: aa = 'G'; break; case 7: aa = 'H'; break; case 8: aa = 'I'; break; case 9: aa = 'K'; break; case 10: aa = 'L'; break; case 11: aa = 'M'; break; case 12: aa = 'N'; break; case 13: aa = 'P'; break; case 14: aa = 'Q'; break; case 15: aa = 'R'; break; case 16: aa = 'S'; break; case 17: aa = 'T'; break; case 18: aa = 'V'; break; case 19: aa = 'W'; break; case 20: aa = 'Y'; break; } return aa; };
8,996
C++
.cpp
382
18.929319
80
0.526912
ranganathanlab/bmDCA
33
12
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,857
utils.hpp
ranganathanlab_bmDCA/src/utils.hpp
#ifndef UTILS_HPP #define UTILS_HPP #include <armadillo> #include <string> class SeqRecord { private: const std::string header; const std::string sequence; public: SeqRecord(std::string, std::string); void print(); std::string getRecord(); std::string getHeader(); std::string getSequence(); }; typedef struct { arma::field<arma::Mat<double>> J; arma::Mat<double> h; } potts_model; potts_model loadPottsModel(std::string, std::string); potts_model loadPottsModelAscii(std::string); void convertFrequencyToAscii(std::string); void convertParametersToAscii(std::string, std::string); int Theta(double); int Delta(double); double Max(double, double); double Min(double, double); int deleteFile(std::string); bool checkFileExists(std::string); void deleteAllFiles(std::string); char convertAA(int); #endif
837
C++
.h
38
20.105263
56
0.777494
ranganathanlab/bmDCA
33
12
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,859
generator.hpp
ranganathanlab_bmDCA/src/generator.hpp
#include "mcmc.hpp" #include "mcmc_stats.hpp" #include "utils.hpp" class Generator { public: Generator(potts_model, int, int, std::string); ~Generator(void); void run(int, int, std::string); void writeAASequences(std::string); void writeNumericalSequences(std::string); private: int N; // number of positions int Q; // number of amino acids int M; // number of independent sampling runs int count_max; // number of sequences sampled from independent runs int resample_max; long int random_seed; double adapt_up_time; double adapt_down_time; int t_wait_0; int delta_t_0; bool check_ergo; std::string sampler = "mh"; // MC sampler type ('mh' or 'z') double temperature; arma::Cube<int> samples; potts_model model; MCMC* mcmc; MCMCStats* mcmc_stats; void loadParameters(std::string); void initializeParameters(void); void checkParameters(void); void setParameter(std::string, std::string); };
972
C++
.h
34
25.882353
69
0.712446
ranganathanlab/bmDCA
33
12
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,860
msa_stats.hpp
ranganathanlab_bmDCA/src/msa_stats.hpp
#ifndef MSA_STATS_HPP #define MSA_STATS_HPP #include "msa.hpp" #include <armadillo> class MSAStats { public: MSAStats(MSA); double getEffectiveM(); double getN(); double getM(); double getQ(); void writeRelEntropy(std::string); void writeRelEntropyAscii(std::string); // void writeRelEntropyPos(std::string); void writeRelEntropyPosAscii(std::string); void writeRelEntropyGradient(std::string); void writeRelEntropyGradientAscii(std::string); void writeFrequency1p(std::string); void writeFrequency2p(std::string); void writeFrequency1pAscii(std::string); void writeFrequency2pAscii(std::string); arma::Mat<double> frequency_1p; arma::field<arma::Mat<double>> frequency_2p; arma::Mat<double> rel_entropy_1p; arma::Col<double> rel_entropy_pos_1p; arma::Mat<double> rel_entropy_grad_1p; double freq_rms; private: double pseudocount; int M; // number of sequences int N; // number of positions int Q; // amino acid alphabet size double M_effective; // effect number of sequences arma::Col<double> aa_background_frequencies; }; #endif
1,132
C++
.h
37
27.918919
51
0.732291
ranganathanlab/bmDCA
33
12
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,861
mcmc.hpp
ranganathanlab_bmDCA/src/mcmc.hpp
#ifndef MCMC_HPP #define MCMC_HPP #include <string> #include <unistd.h> #include "graph.hpp" #include "utils.hpp" class MCMC { public: MCMC(size_t N, size_t Q); MCMC(size_t N, size_t Q, potts_model*); void load(potts_model*); void run(int, int); void sample(arma::Cube<int>*, int, int, int, int, int, long int, double = 1.0); void sample_zanella(arma::Cube<int>*, int, int, int, int, int, long int, std::string, double = 1.0); void sample_init(arma::Cube<int>*, int, int, int, int, int, arma::Col<int>*, long int, double = 1.0); private: size_t n; // number of positions size_t q; // number of amino acids (inc. gaps) Graph graph; }; #endif
998
C++
.h
39
15.435897
76
0.451681
ranganathanlab/bmDCA
33
12
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,862
graph.hpp
ranganathanlab_bmDCA/src/graph.hpp
#ifndef GRAPH_HPP #define GRAPH_HPP #include <armadillo> #include <iostream> #include <string> #include "utils.hpp" class Graph { public: Graph(size_t n, size_t q, potts_model* p) : n(n) , q(q) , params(p){}; Graph(size_t n, size_t q) : n(n) , q(q){}; void load(potts_model*); size_t n, q; potts_model* params; std::ostream& print_distribution(std::ostream& os); std::ostream& print_parameters(std::ostream& os); void sample_mcmc(arma::Mat<int>* ptr, size_t m, size_t mc_iters0, size_t mc_iters, long int seed, double = 1.0); void sample_mcmc_init(arma::Mat<int>* ptr, size_t m, size_t mc_iters0, size_t mc_iters, arma::Col<int>* init_ptr, long int seed, double = 1.0); void sample_mcmc_zanella(arma::Mat<int>* ptr, size_t, size_t, size_t, long int, std::string = "sqrt", double = 1.0); void print_parameters(FILE* of); }; #endif
1,287
C++
.h
44
17.863636
53
0.457282
ranganathanlab/bmDCA
33
12
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,863
msa.hpp
ranganathanlab_bmDCA/src/msa.hpp
#ifndef MSA_HPP #define MSA_HPP #include <armadillo> #include <string> #include <vector> #include "utils.hpp" class MSA { public: arma::Mat<int> alignment; // numerical multiple sequence alignment arma::Col<double> sequence_weights; // weights for each sequence int M; // number of sequences int N; // number of positions int Q; // number of amino acids arma::Col<double> hamming_distances; MSA(std::string, std::string = "", bool = true, bool = false, double = 0.8); void printAlignment(); void writeMatrix(std::string); void writeSequenceWeights(std::string); void writeHammingDistances(std::string); private: std::vector<SeqRecord> seq_records; int getSequenceLength(std::string); void readInputMSA(std::string); void readInputNumericMSA(std::string); void readSequenceWeights(std::string); void makeNumericalMatrix(void); void computeSequenceWeights(double); void computeHammingDistances(void); }; #endif
1,051
C++
.h
31
31.451613
78
0.685094
ranganathanlab/bmDCA
33
12
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,864
model.hpp
ranganathanlab_bmDCA/src/model.hpp
#ifndef MODEL_HPP #define MODEL_HPP #include "msa_stats.hpp" #include "utils.hpp" class Model { public: potts_model params; potts_model params_prev; potts_model learning_rates; potts_model gradient; potts_model gradient_prev; int N; int Q; Model(MSAStats, double, double); Model(std::string, std::string, std::string, std::string, std::string); Model(std::string, std::string, std::string, std::string, std::string, std::string, std::string, std::string, std::string, std::string); void writeParams(std::string, std::string); void writeParamsPrevious(std::string, std::string); void writeLearningRates(std::string, std::string); void writeGradient(std::string, std::string); void writeGradientPrevious(std::string, std::string); void writeParamsAscii(std::string); void writeParamsPreviousAscii(std::string); void writeLearningRatesAscii(std::string); void writeGradientAscii(std::string); void writeGradientPreviousAscii(std::string); }; #endif
1,064
C++
.h
38
23.894737
73
0.708824
ranganathanlab/bmDCA
33
12
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,865
run.hpp
ranganathanlab_bmDCA/src/run.hpp
#ifndef BMDCA_RUN_HPP #define BMDCA_RUN_HPP #include "mcmc.hpp" #include "mcmc_stats.hpp" #include "model.hpp" #include "msa.hpp" #include "msa_stats.hpp" #include "pcg_random.hpp" #include "utils.hpp" class Sim { public: Sim(MSAStats, std::string, std::string, bool); ~Sim(void); void run(void); void loadParameters(std::string); void writeParameters(std::string); private: void initializeParameters(void); bool compareParameters(std::string); void checkParameters(void); void setStepOffset(void); void restoreRunState(void); void readInitialSample(int, int); void computeErrorReparametrization(void); void updateLearningRate(void); void updateReparameterization(void); void writeData(std::string); void writeData(int); void clearFiles(std::string); // BM settings double lambda_reg1; // L2 regularization strength for 1p statistics (fields) double lambda_reg2; // L2 regularization strength for 2p statistics (cpling) int step_max; // max number of BM steps double error_max; // exit error int save_parameters; // multiple of iterations at which to save parameters int save_best_steps; // multiple of iterations at which to save parameters int random_seed; bool use_reparametrization = true; // Learning parameters double epsilon_0_h; // starting learning rate for fields double epsilon_0_J; // starting learning rate for couplings double adapt_up; // positive adaptive step for learning rate double adapt_down; // negative sdaptive step for learning rate double min_step_h; // min learning rate for fields double max_step_h; // maximum learning rate for fields double min_step_J; // minimum learning rate for couplings double max_step_J_N; // maximum learning rate for couplings (to be // divided by N) double error_min_update; // minimal number of standard deviation s of z // variable for having parameter update (if // negative or zero all parameters are updated) // Sampling times int t_wait_0; // staring thermalization time for MCMC int delta_t_0; // starging samplign time for MCMC bool check_ergo; // flag to check if MC is well thermalized and // decorrelated double adapt_up_time; // negative adaptive step for sampling/ // thermalization times double adapt_down_time; // positive adaptive step for sampling/ // thermalization times int t_wait; int delta_t; // Importance sampling settings int step_importance_max; // importance sampling maximum iterations double coherence_min; // coherence importance sampling // MCMC settings int step; // current step number int step_offset = 0; int M; // number of samples for each MCMC run int count_max; // number of independent MCMC runs bool init_sample = false; // flag for loading the first positions when // initializing the mcmc from a file std::string init_sample_file; // name of file with mcmc initial sample std::string sampler = "mh"; // MC sampler type ('mh' or 'z') bool output_binary = true; double error_1p; double error_2p; double error_tot; double error_tot_min = 1; double error_stat_1p; double error_stat_2p; double error_stat_tot; double error_stat_tot_min = 1; std::string hyperparameter_file = "bmdca_params.conf"; std::string run_log_file = "bmdca_run.log"; // Key-value wrapper for loading parameters from a file. void setParameter(std::string, std::string); bool compareParameter(std::string, std::string); // Buffers arma::Mat<double> run_buffer; void initializeRunLog(); void writeRunLog(int = -1, int = 0, bool = false); // Sample data arma::Cube<int> samples; arma::Col<int> initial_sample; // Stats from original MSA MSAStats msa_stats; Model* model; // MCMC MCMC* mcmc; // Stats from MCMC samples MCMCStats* mcmc_stats; // RNG pcg32 rng; }; #endif
4,167
C++
.h
107
34.373832
79
0.681109
ranganathanlab/bmDCA
33
12
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,867
mcmc_stats.hpp
ranganathanlab_bmDCA/src/mcmc_stats.hpp
#ifndef MCMC_STATS_HPP #define MCMC_STATS_HPP #include <armadillo> #include "utils.hpp" class MCMCStats { public: MCMCStats(arma::Cube<int>*, potts_model*); void updateData(arma::Cube<int>*, potts_model*); void computeEnergies(void); void computeEnergiesStats(void); void computeCorrelations(void); void computeSampleStats(void); void computeSampleStatsImportance(potts_model*, potts_model*); std::vector<double> getEnergiesStats(void); std::vector<double> getCorrelationsStats(void); void writeEnergyStats(std::string, std::string, std::string, std::string); void writeCorrelationsStats(std::string, std::string, std::string); void writeFrequency1p(std::string, std::string); void writeFrequency2p(std::string, std::string); void writeFrequency1pAscii(std::string, std::string); void writeFrequency2pAscii(std::string, std::string); void writeSamples(std::string); void writeSampleEnergies(std::string); void writeSampleEnergiesRelaxation(std::string, int = 1); arma::Mat<double> frequency_1p; arma::Mat<double> frequency_1p_sigma; arma::field<arma::Mat<double>> frequency_2p; arma::field<arma::Mat<double>> frequency_2p_sigma; double Z_ratio; double sumw_inv; double dE_av_tot; private: potts_model* params; arma::Cube<int>* samples; arma::Mat<double> energies; double energies_start_avg; double energies_start_sigma; double energies_end_avg; double energies_end_sigma; double energies_err; arma::Row<double> energies_relax; arma::Row<double> energies_relax_sigma; arma::Col<double> overlaps; arma::Col<double> overlaps_sigma; double overlap_inf; double overlap_inf_sigma; double overlap_auto; double overlap_cross; double overlap_check; double sigma_auto; double sigma_cross; double sigma_check; double err_cross_auto; double err_cross_check; double err_check_auto; int reps; int N; int Q; int M; }; #endif
1,929
C++
.h
62
28.193548
76
0.758639
ranganathanlab/bmDCA
33
12
4
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,868
lifx-emulation.h
giantorth_ESPHomeLifx/lifx-emulation.h
#include "esphome.h" #include <ESPAsyncUDP.h> //#define DEBUG //#define MQTT //#define DIYHUE #ifdef DEBUG #define debug_print(x, ...) Serial.print(x, ##__VA_ARGS__) #define debug_println(x, ...) Serial.println(x, ##__VA_ARGS__) #else #define debug_print(x, ...) #define debug_println(x, ...) #endif // this structure doesn't support the response/ack byte properly and needs updated. struct LifxPacket { ////frame uint16_t size; //little endian uint16_t protocol; //little endian byte source[4]; //source ////frame address byte bulbAddress[6]; //device mac uint16_t reserved2; // mac padding byte site[6]; // "reserved" uint8_t res_ack; uint8_t sequence; //message sequence number ////protocol header uint64_t timestamp; uint16_t packet_type; //little endian uint16_t reserved4; byte data[128]; int data_size; }; //need to verify these const unsigned int LifxProtocol_AllBulbsResponse = 21504; // 0x5400 const unsigned int LifxProtocol_AllBulbsRequest = 13312; // 0x3400 const unsigned int LifxProtocol_BulbCommand = 5120; // 0x1400 const unsigned int LifxPacketSize = 36; const unsigned int LifxPort = 56700; // local port to listen on const unsigned int LifxBulbLabelLength = 32; const unsigned int LifxBulbTagsLength = 8; const unsigned int LifxBulbTagLabelsLength = 32; #define LIFX_MAX_PACKET_LENGTH 512 // firmware versions, etc const byte LifxBulbVendor = 1; const byte LifxBulbProduct = 22; const byte LifxBulbVersion = 0; const byte LifxFirmwareVersionMajor = 1; const byte LifxFirmwareVersionMinor = 5; const unsigned int LifxMagicNum = 614500; // still a mystery const byte SERVICE_UDP = 0x01; const byte SERVICE_TCP = 0x02; const byte SERVICE_UDP5 = 0x05; // Real bulbs seem to ofer this service too... // Packet RES/ACK values const byte NO_RESPONSE = 0x00; const byte RES_REQUIRED = 0x01; const byte ACK_REQUIRED = 0x02; const byte RES_ACK_REQUIRED = 0x03; // unknown value, no real packets seem to set both const byte PAN_REQUIRED = 0x04; // Set on GET_PAN_GATEWAY (third bit on only) const byte RES_PAN_REQUIRED = 0x05; // set on multiple packets (first and third bit set) const byte ACK_PAN_REQUIRED = 0x06; // bits 2/3 on const byte RES_ACK_PAN_REQUIRED = 0x07; // All three bits set // Device Messages const byte GET_PAN_GATEWAY = 0x02; const byte PAN_GATEWAY = 0x03; // stateService(3) const byte GET_HOST_INFO = 0x0c; // getHostInfo(12) const byte HOST_INFO = 0x0d; // stateHostInfo(13) const byte GET_MESH_FIRMWARE_STATE = 0x0e; //getHostFirmware(14) const byte MESH_FIRMWARE_STATE = 0x0f; // stateHostFirmware(15) const byte GET_WIFI_INFO = 0x10; // getWifiInfo (16) const byte WIFI_INFO = 0x11; // stateWifiInfo (17) const byte GET_WIFI_FIRMWARE_STATE = 0x12; // getWifiFirmware(18) const byte WIFI_FIRMWARE_STATE = 0x13; // stateWifiFirmware(19) const byte GET_POWER_STATE = 0x14; // getPower(20) const byte SET_POWER_STATE = 0x15; // setPower(21) const byte POWER_STATE = 0x16; // statePower(22) const byte GET_BULB_LABEL = 0x17; // getLabel(23) const byte SET_BULB_LABEL = 0x18; // setLabel(24) const byte BULB_LABEL = 0x19; // stateLabel(25) const byte GET_BULB_TAGS = 0x1a; // unlisted packets const byte SET_BULB_TAGS = 0x1b; // const byte BULB_TAGS = 0x1c; // const byte GET_BULB_TAG_LABELS = 0x1d; // unlisted packets const byte SET_BULB_TAG_LABELS = 0x1e; const byte BULB_TAG_LABELS = 0x1f; const byte GET_VERSION_STATE = 0x20; // getVersion(32) const byte VERSION_STATE = 0x21; // stateVersion(33) const byte GET_INFO = 0x22; // getInfo(34) const byte STATE_INFO = 0x23; // stateInfo(35) const byte RESET_BULB_ANDROID = 0x37; // Sent serval times on reset from android // no documented packets 0x24 thru 0x2c const byte ACKNOWLEDGEMENT = 0x2d; // acknowledgement(45) const byte RESET_BULB = 0x2e; // sent on bulb reset? 24 00 00 14 10 00 7A D8 4C 11 AE 0D 1E 5A 00 00 4C 49 46 58 56 32 06 1E 00 00 00 00 00 00 00 00 2E 00 00 00 const byte GET_LOCATION_STATE = 0x30; // getLocation(48) const byte SET_LOCATION_STATE = 0x31; // setLocation(49) const byte LOCATION_STATE = 0x32; // stateLocation(50) const byte GET_GROUP_STATE = 0x33; // getGroup(51) const byte SET_GROUP_STATE = 0x34; // setGroup(52) const byte GROUP_STATE = 0x35; // stateGroup(53) - res_required // suspect these are FW checksum values const byte GET_AUTH_STATE = 0x36; // getAuth(54) Mystery packets queried first by apps, need to add to wireshark plugin const byte SET_AUTH_STATE = 0x37; // setAuth(55) Sent on bulb cloud join (and reset?) 5C 00 00 14 10 00 7A D8 4C 11 AE 0D 1E 5A 00 00 4C 49 46 58 56 32 06 1A 00 00 00 00 00 00 00 00 37 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 5E 2C B2 27 FA 35 16 const byte AUTH_STATE = 0x38; // stateAuth(56) - should always respond from a SET const byte ECHO_REQUEST = 0x3a; // echoRequest(58) const byte ECHO_RESPONSE = 0x3b; // echoResponse(59) // Light Messages const byte GET_LIGHT_STATE = 0x65; // get(101) const byte SET_LIGHT_STATE = 0x66; // setColor(102) const byte SET_WAVEFORM = 0x67; // setWaveform(103) const byte LIGHT_STATUS = 0x6b; // state(107) - res_required const byte GET_POWER_STATE2 = 0x74; // getPower(116) const byte SET_POWER_STATE2 = 0x75; // setPower(117) const byte POWER_STATE2 = 0x76; // statePower(118) const byte SET_WAVEFORM_OPTIONAL = 0x77; // setWaveformOptional(119) const byte GET_INFARED_STATE = 0x78; // getInfared(120) const byte STATE_INFARED_STATE = 0x79; // stateInfared(121) const byte SET_INFARED_STATE = 0x7A; // setInfrared(122) // Get/State happens during bulb info screens, Set happens during reset // Doesn't cause app to report cloud on but no more dropouts const byte GET_CLOUD_STATE = 0xc9; // getCloud(201) const byte SET_CLOUD_STATE = 0xca; // setCloudState (202) const byte CLOUD_STATE = 0xcb; // stateCloud(203) const byte GET_CLOUD_AUTH = 0xcc; // (204) 24 00 00 14 10 00 2F 7C 4C 11 AE 0D 1E 5A 00 00 4C 49 46 58 56 32 05 31 00 00 00 00 00 00 00 00 CC 00 00 00 const byte SET_CLOUD_AUTH = 0xcd; // (205) 44 00 00 14 10 00 7A D8 4C 11 AE 0D 1E 5A 00 00 4C 49 46 58 56 32 06 1C 00 00 00 00 00 00 00 00 CD 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 const byte CLOUD_AUTH_STATE = 0xce; // (206) app only requests once so difficult to capture. Suspect some kind of cloud-only serial number/guid? App must set a unique value or it does not think bulb is cloud connected. const byte GET_CLOUD_BROKER = 0xd1; // (209) 45 00 00 14 10 00 7A D8 4C 11 AE 0D 1E 5A 00 00 4C 49 46 58 56 32 06 1B 00 00 00 00 00 00 00 00 D1 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 const byte SET_CLOUD_BROKER = 0xd2; // (210) 24 00 00 14 10 00 E5 15 4C 11 AE 0D 1E 5A 00 00 4C 49 46 58 56 32 05 1C 00 00 00 00 00 00 00 00 D2 00 00 00 const byte CLOUD_BROKER_STATE = 0xd3; // (211) 32-bytes of zero response for no cloud bulb, 33 bytes for cloud bulbs "v2.broker.lifx.co" const uint16_t GET_COLOR_ZONE = 502; //{ 0xf6, 0x01 }; // getColorZones(502) const uint16_t STATE_COLOR_ZONE = 503; //{ 0xf7, 0x01 }; // stateColorZone(503) #define SPACE " " #ifdef MQTT_ON class lifxUdp : public Component, public CustomMQTTDevice #else class lifxUdp : public Component #endif { public: // no default MAC address, must be set externally (lifxUdp->mac) byte mac[6] = {}; // Bulb name/locationgroup, lame defaults char bulbLabel[32] = "B"; char bulbLocation[32] = "L"; char bulbLocationGUID[37] = "b49bed4d-77b0-05a3-9ec3-be93d9582f1f"; uint64_t bulbLocationTime = 1553350342028441856; char bulbGroup[32] = "G"; char bulbGroupGUID[37] = "bd93e53d-2014-496f-8cfd-b8886f766d7a"; uint64_t bulbGroupTime = 1600213602318000000; uint8_t cloudStatus = 0x00; byte _cloudBrokerUrl[33] = {0x76, 0x32, 0x2e, 0x62, 0x72, 0x6f, 0x6b, 0x65, 0x72, 0x2e, 0x6c, 0x69, 0x66, 0x78, 0x2e, 0x63, 0x6f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; byte cloudBrokerUrl[33] = {0x00}; // Unclouded response unsigned char cloudAuthResponse[32] = {0x00}; // Unclouded reponse // This is an undocumented packet payload I suspect is a firmware checksum, only checked by official apps byte _authResponse[56] = {0xd1, 0x74, 0xef, 0x20, 0x68, 0x02, 0x4c, 0x3b, 0x94, 0xf7, 0x24, 0x71, 0x33, 0xc2, 0x98, 0x9a, // 16 mystery bytes 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x39, 0x3b, 0x63, 0x31, 0x64, 0x5b, 0x15}; // 8 more mystery bytes byte authResponse[56] = {0x00}; // really another cloud config string // need to change, strcpy will not erase prior string contents void set_bulbLabel(const char *arg) { strcpy(bulbLabel, arg); } void set_bulbLocation(const char *arg) { strcpy(bulbLocation, arg); } void set_bulbLocationGUID(const char *arg) { strcpy(bulbLocationGUID, arg); } void set_bulbLocationTime(uint64_t arg) { bulbLocationTime = arg; } void set_bulbGroup(const char *arg) { strcpy(bulbGroup, arg); } void set_bulbGroupGUID(const char *arg) { strcpy(bulbGroupGUID, arg); } void set_bulbGroupTime(uint64_t arg) { bulbGroupTime = arg; } /****************************************************************************************************************** * beginUDP( char ) * This function creates the UDP listener with inline function called for each packet ******************************************************************************************************************/ void beginUDP() { debug_print(F("Setting Light Name: ")); //strcpy(bulbLabel, bulbLabelToSet); debug_println(bulbLabel); // Convert incoming guids strings to a byte array // Will strip an even number of dashes if included hexCharacterStringToBytes(bulbGroupGUIDb, (const char *)bulbGroupGUID); // strips dashes too hexCharacterStringToBytes(bulbLocationGUIDb, (const char *)bulbLocationGUID); // strips dashes too debug_print("Wifi Signal: "); debug_println(WiFi.RSSI(), DEC); // if( is_connected() ) { // // MQTT is on // char subscription[16] = "lifxlan/"; // //CustomMQTTDevice::subscribe( strcat( subscription, (const char *)mac ), &lifxUdp::on_mqtt_message ); // } // start listening for packets if (Udp.listen(LifxPort)) { ESP_LOGW("LIFXUDP", "Lifx Emulation UDP listerner Enabled"); Udp.onPacket( [&](AsyncUDPPacket &packet) { unsigned long packetTime = millis(); uint32_t packetSize = packet.length(); if (packetSize) { //ignore empty packets incomingUDP(packet); } Serial.print(F("Response: ")); Serial.print(millis() - packetTime); Serial.println("msec"); }); } //TODO: TCP support necessary? //TcpServer.begin(); setLight(); // will (not) turn light on at boot.... why? #ifdef DIYHUE if (HueUdp.listen(2100)) { ESP_LOGD("DiyHueUDP", "Listerner Enabled"); HueUdp.onPacket([&](AsyncUDPPacket &packet) { entertainment(packet); }); } #endif } void on_mqtt_message(const String &payload) { debug_print("MQTT message: "); debug_println(payload); } void setup() override { // moved to beginUDP() } void loop() override { #ifdef DIYHUE //TODO: Need to add bulb state watching here if things are changed outside this protocol if (entertainment_switch->state) { if ((millis() - lastUDPmilsec) >= entertainmentTimeout) { { entertainment_switch->turn_off(); } } } #endif } private: float maxColor = 255; // initial bulb values - warm white! uint16_t power_status = 65535; uint16_t hue = 0; uint16_t sat = 0; uint16_t bri = 65535; uint16_t kel = 2700; uint8_t trans = 0; uint32_t period = 0; float cycles = 0; int skew_ratio = 0; //signed 16 bit int uint8_t waveform = 0; uint8_t set_hue = 1; uint8_t set_sat = 1; uint8_t set_bri = 1; uint8_t set_kel = 1; long dim = 0; uint32_t dur = 0; uint8_t _sequence = 0; unsigned long lastChange = millis(); uint32_t tx_bytes = 0; uint32_t rx_bytes = 0; unsigned long lastUDPmilsec = 0; unsigned int entertainmentTimeout = 1500; byte site_mac[6] = {0x4C, 0x49, 0x46, 0x58, 0x56, 0x32}; // spells out "LIFXV2" - version 2 of the app changes the site address to this...? // tags for this bulb, seemingly unused on current real bulbs char bulbTags[LifxBulbTagsLength] = { 0, 0, 0, 0, 0, 0, 0, 0}; char bulbTagLabels[LifxBulbTagLabelsLength] = ""; // real guids are stored as byte arrays instead of a char string representation byte bulbGroupGUIDb[16] = {}; byte bulbLocationGUIDb[16] = {}; // Guids in packets come in a bizzare mix of big and little endian and treat last two segments as one uint8_t guidSeq[16] = {3, 2, 1, 0, 5, 4, 7, 6, 8, 9, 10, 11, 12, 13, 14, 15}; // Should probably check if wifi is up first before doing this AsyncUDP Udp; #ifdef DIYHUE AsyncUDP HueUdp; // this is a DiyHue entertainment call void entertainment(AsyncUDPPacket &packet) { ESP_LOGD("DiyHueUDP", "Entertainment packet arrived"); auto call = white_led->turn_off(); //turn off white_led when entertainment starts call.set_transition_length(0); call.perform(); if (!entertainment_switch->state) { entertainment_switch->turn_on(); } lastUDPmilsec = millis(); //reset timeout value uint8_t *packetBuffer = packet.data(); uint32_t packetSize = packet.length(); call = color_led->turn_on(); if (((packetBuffer[1]) + (packetBuffer[2]) + (packetBuffer[3])) == 0) { call.set_rgb(0, 0, 0); call.set_brightness(0); call.set_transition_length(0); call.perform(); } else { call.set_rgb(packetBuffer[1] / maxColor, packetBuffer[2] / maxColor, packetBuffer[3] / maxColor); call.set_transition_length(0); call.set_brightness(packetBuffer[4] / maxColor); call.perform(); } } #endif /****************************************************************************************************************** * incomingUDP( AsyncUDPPacket ) * This function is called on all incoming UDP packets ******************************************************************************************************************/ void incomingUDP(AsyncUDPPacket &packet) { int packetSize = packet.length(); rx_bytes += packetSize; // Changed from a pointer to a memcpy when trying to chase down a bug, likely not needed. Was worried about simultanious packets. //uint8_t *packetBuffer = packet.data(); uint8_t packetBuffer[packetSize]; memcpy(packetBuffer, packet.data(), packetSize); ESP_LOGD("LIFXUDP", "Packet arrived"); debug_println(); debug_print(F("Packet Arrived (")); IPAddress remote_addr = (packet.remoteIP()); IPAddress local_addr = packet.localIP(); int remote_port = packet.remotePort(); debug_print(remote_addr); debug_print(F(":")); debug_print(remote_port); debug_print("->"); debug_print(local_addr); debug_print(F(")(")); debug_print(packetSize); debug_print(F(" bytes): ")); for (int i = 0; i < packetSize; i++) { if (packetBuffer[i] <= 0x0F) { debug_print(F("0")); // pad with zeros for proper alignment with web packet decoder tools } debug_print(packetBuffer[i], HEX); debug_print(SPACE); } debug_println(); LifxPacket request; // stuff the packetBuffer into the lifxPacket request struct and return the start of a request object processRequest(packetBuffer, packetSize, request); //respond to the request. handleRequest(request, packet); } /****************************************************************************************************************** * processRequest( byte, float, LifxPacket ) * This function is called on all incoming UDP packets to pack a struct ******************************************************************************************************************/ void processRequest(byte *packetBuffer, float packetSize, LifxPacket &request) { request.size = packetBuffer[0] + (packetBuffer[1] << 8); //little endian request.protocol = packetBuffer[2] + (packetBuffer[3] << 8); //little endian // this is the source of the packet byte sourceID[] = {packetBuffer[4], packetBuffer[5], packetBuffer[6], packetBuffer[7]}; memcpy(request.source, sourceID, 4); byte bulbAddress[] = { packetBuffer[8], packetBuffer[9], packetBuffer[10], packetBuffer[11], packetBuffer[12], packetBuffer[13]}; memcpy(request.bulbAddress, bulbAddress, 6); request.reserved2 = packetBuffer[14] + packetBuffer[15]; byte site[] = { packetBuffer[16], packetBuffer[17], packetBuffer[18], packetBuffer[19], packetBuffer[20], packetBuffer[21]}; memcpy(request.site, site, 6); request.res_ack = packetBuffer[22]; request.sequence = packetBuffer[23]; request.timestamp = packetBuffer[24] + packetBuffer[25] + packetBuffer[26] + packetBuffer[27] + packetBuffer[28] + packetBuffer[29] + packetBuffer[30] + packetBuffer[31]; request.packet_type = packetBuffer[32] + (packetBuffer[33] << 8); //little endian request.reserved4 = packetBuffer[34] + packetBuffer[35]; int j = 0; for (unsigned int i = LifxPacketSize; i < packetSize; i++) { //debug_println(i); request.data[j++] = packetBuffer[i]; } request.data_size = j; } void handleRequest(LifxPacket &request, AsyncUDPPacket &packet) { debug_print(F("-> Packet 0x")); debug_print(request.packet_type, HEX); debug_print(F(" (")); debug_print(request.packet_type, DEC); debug_println(F(")")); LifxPacket response; for (int x = 0; x < 4; x++) { response.source[x] = request.source[x]; } // Bulbs must respond with matching number from request response.sequence = request.sequence; switch (request.packet_type) { // default to no RES/ACK on packet response.res_ack = NO_RESPONSE; case GET_PAN_GATEWAY: { // we are a gateway, so respond to this //debug_println(F(">>GET_PAN_GATEWAY Discovery Packet")); // respond with the UDP port response.packet_type = PAN_GATEWAY; response.protocol = LifxProtocol_AllBulbsResponse; //response.res_ack = RES_REQUIRED; byte UDPdata[] = { SERVICE_UDP, //UDP lowByte(LifxPort), highByte(LifxPort), 0x00, 0x00}; byte UDPdata5[] = { SERVICE_UDP5, //UDP lowByte(LifxPort), highByte(LifxPort), 0x00, 0x00}; // A real bulb seems to respond multiple times, once as service type 5 memcpy(response.data, UDPdata, sizeof(UDPdata)); response.data_size = sizeof(UDPdata); sendPacket(response, packet); memcpy(response.data, UDPdata5, sizeof(UDPdata)); response.data_size = sizeof(UDPdata); sendPacket(response, packet); } break; case SET_LIGHT_STATE: { // set the light colors hue = word(request.data[2], request.data[1]); sat = word(request.data[4], request.data[3]); bri = word(request.data[6], request.data[5]); kel = word(request.data[8], request.data[7]); dur = (uint32_t)request.data[9] << 0 | (uint32_t)request.data[10] << 8 | (uint32_t)request.data[11] << 16 | (uint32_t)request.data[12] << 24; setLight(); if (request.res_ack == RES_REQUIRED) // per spec... TODO: don't just copy-and-paste from other packet case { response.res_ack = NO_RESPONSE; // send the light's state response.packet_type = LIGHT_STATUS; response.protocol = LifxProtocol_AllBulbsResponse; byte StateData[52] = { lowByte(hue), //hue highByte(hue), //hue lowByte(sat), //sat highByte(sat), //sat lowByte(bri), //bri highByte(bri), //bri lowByte(kel), //kel highByte(kel), //kel lowByte(dim), // listed as reserved in protocol highByte(dim), // listed as reserved in protocol lowByte(power_status), //power status highByte(power_status), //power status }; for (int i = 0; i < sizeof(bulbLabel); i++) { StateData[i + 12] = bulbLabel[i]; } for (int j = 0; j < sizeof(bulbTags); j++) { StateData[j + 12 + 32] = bulbTags[j]; } memcpy(response.data, StateData, sizeof(StateData)); response.data_size = sizeof(StateData); sendPacket(response, packet); } } break; case SET_WAVEFORM: { hue = word(request.data[3], request.data[2]); sat = word(request.data[5], request.data[4]); bri = word(request.data[7], request.data[6]); kel = word(request.data[9], request.data[8]); // duration should be multiplied by cycles in theory but ignored for now dur = (uint32_t)request.data[10] << 0 | (uint32_t)request.data[11] << 8 | (uint32_t)request.data[12] << 16 | (uint32_t)request.data[13] << 24; setLight(); } break; case SET_WAVEFORM_OPTIONAL: { if (request.data[21]) { // ignore hue? debug_print(F(" set hue ")); hue = word(request.data[3], request.data[2]); } if (request.data[22]) { // ignore sat? debug_print(F(" set sat ")); sat = word(request.data[5], request.data[4]); } if (request.data[23]) { // ignore bri? debug_print(F(" set bri ")); bri = word(request.data[7], request.data[6]); } if (request.data[24]) { // ignore kel? debug_print(F(" set kel ")); kel = word(request.data[9], request.data[8]); } dur = (uint32_t)request.data[10] << 0 | (uint32_t)request.data[11] << 8 | (uint32_t)request.data[12] << 16 | (uint32_t)request.data[13] << 24; // period uint32_t // cycles float // skew_ratio uint16_t // waveform uint8_t // not supported, all the waveform flags setLight(); } break; case GET_LIGHT_STATE: { response.res_ack = NO_RESPONSE; // send the light's state response.packet_type = LIGHT_STATUS; response.protocol = LifxProtocol_AllBulbsResponse; byte StateData[52] = { lowByte(hue), //hue highByte(hue), //hue lowByte(sat), //sat highByte(sat), //sat lowByte(bri), //bri highByte(bri), //bri lowByte(kel), //kel highByte(kel), //kel lowByte(dim), // listed as reserved in protocol highByte(dim), // listed as reserved in protocol lowByte(power_status), //power status highByte(power_status), //power status }; for (int i = 0; i < sizeof(bulbLabel); i++) { StateData[i + 12] = bulbLabel[i]; } for (int j = 0; j < sizeof(bulbTags); j++) { StateData[j + 12 + 32] = bulbTags[j]; } memcpy(response.data, StateData, sizeof(StateData)); response.data_size = sizeof(StateData); sendPacket(response, packet); } break; // this is a light strip call. Currently hardcoded for single bulb repsonse case GET_COLOR_ZONE: { response.packet_type = STATE_COLOR_ZONE; response.protocol = LifxProtocol_BulbCommand; byte StateData[10] = { 0x01, //count 0x00, //index lowByte(hue), //hue highByte(hue), //hue lowByte(sat), //sat highByte(sat), //sat lowByte(bri), //bri highByte(bri), //bri lowByte(kel), //kel highByte(kel), //kel }; memcpy(response.data, StateData, sizeof(StateData)); response.data_size = sizeof(StateData); sendPacket(response, packet); } break; case SET_POWER_STATE: case SET_POWER_STATE2: { power_status = word(request.data[1], request.data[0]); setLight(); } break; case GET_POWER_STATE: case GET_POWER_STATE2: { response.packet_type = POWER_STATE; response.protocol = LifxProtocol_AllBulbsResponse; byte PowerData[] = { lowByte(power_status), highByte(power_status)}; memcpy(response.data, PowerData, sizeof(PowerData)); response.data_size = sizeof(PowerData); sendPacket(response, packet); } break; case SET_BULB_LABEL: { for (int i = 0; i < LifxBulbLabelLength; i++) { if (bulbLabel[i] != request.data[i]) { bulbLabel[i] = request.data[i]; //EEPROM.write(EEPROM_BULB_LABEL_START + i, request.data[i]); } } } break; case GET_BULB_LABEL: { response.packet_type = BULB_LABEL; response.protocol = LifxProtocol_AllBulbsResponse; memcpy(response.data, bulbLabel, sizeof(bulbLabel)); response.data_size = sizeof(bulbLabel); sendPacket(response, packet); } break; case SET_BULB_TAGS: case GET_BULB_TAGS: { // set if we are setting if (request.packet_type == SET_BULB_TAGS) { for (int i = 0; i < LifxBulbTagsLength; i++) { if (bulbTags[i] != request.data[i]) { bulbTags[i] = lowByte(request.data[i]); //EEPROM.write(EEPROM_BULB_TAGS_START + i, request.data[i]); } } } // respond to both get and set commands response.packet_type = BULB_TAGS; response.protocol = LifxProtocol_AllBulbsResponse; memcpy(response.data, bulbTags, sizeof(bulbTags)); response.data_size = sizeof(bulbTags); sendPacket(response, packet); } break; case SET_BULB_TAG_LABELS: case GET_BULB_TAG_LABELS: { // set if we are setting if (request.packet_type == SET_BULB_TAG_LABELS) { for (int i = 0; i < LifxBulbTagLabelsLength; i++) { if (bulbTagLabels[i] != request.data[i]) { bulbTagLabels[i] = request.data[i]; //EEPROM.write(EEPROM_BULB_TAG_LABELS_START + i, request.data[i]); } } } // respond to both get and set commands response.packet_type = BULB_TAG_LABELS; response.protocol = LifxProtocol_AllBulbsResponse; memcpy(response.data, bulbTagLabels, sizeof(bulbTagLabels)); response.data_size = sizeof(bulbTagLabels); sendPacket(response, packet); } break; case SET_LOCATION_STATE: { // TODO: Actually write out values to somewhere besides memory // this needs constants for (int i = 0; i < 16; i++) { bulbLocationGUIDb[guidSeq[i]] = request.data[i]; // app seems to send in scramble ordering } for (int j = 0; j < 32; j++) { bulbLocation[j] = request.data[j + 16]; } if (request.data[16 + 32] == 0) { // Did they send us no value? use now auto time = ha_time->utcnow(); // generate a msec value from epoch and then stuff 6 more zeros on the end for a magic number bulbLocationTime = (uint64_t)(((uint64_t)time.timestamp * 1000) * 1000000 + LifxMagicNum); } else { uint8_t *p = (uint8_t *)&bulbLocationTime; for (int k = 0; k < 8; k++) { p[k] = request.data[k + 32 + 16]; } } } break; case GET_LOCATION_STATE: { response.packet_type = LOCATION_STATE; response.res_ack = RES_REQUIRED; response.protocol = LifxProtocol_AllBulbsResponse; uint8_t *p = (uint8_t *)&bulbLocationTime; byte LocationStateResponse[56] = {}; for (int i = 0; i < sizeof(bulbLocationGUIDb); i++) { LocationStateResponse[i] = bulbLocationGUIDb[guidSeq[i]]; // special sequence } for (int j = 0; j < sizeof(bulbLocation); j++) { LocationStateResponse[j + 16] = bulbLocation[j]; } for (int k = 0; k < sizeof(bulbLocationTime); k++) { LocationStateResponse[k + 32 + 16] = p[k]; } memcpy(response.data, LocationStateResponse, sizeof(LocationStateResponse)); response.data_size = sizeof(LocationStateResponse); sendPacket(response, packet); } break; case SET_AUTH_STATE: // real bulbs always respond to a SET with a GET case GET_AUTH_STATE: { if (request.packet_type == SET_AUTH_STATE) { for (int i = 0; i < request.data_size; i++) { authResponse[i] = request.data[i]; } } response.packet_type = AUTH_STATE; response.res_ack = RES_REQUIRED; response.protocol = LifxProtocol_AllBulbsResponse; memcpy(response.data, authResponse, sizeof(authResponse)); response.data_size = sizeof(authResponse); sendPacket(response, packet); } break; case SET_GROUP_STATE: { // TODO: Actually write out values to somewhere besides memory // this needs constants for (int i = 0; i < 16; i++) { bulbGroupGUIDb[guidSeq[i]] = request.data[i]; } for (int j = 0; j < 32; j++) { bulbGroup[j] = request.data[j + 16]; } if (request.data[16 + 32] == 0) { // Did they send us no value? use now auto time = ha_time->utcnow(); // generate a msec value from epoch and then stuff 6 more zeros on the end for a magic number bulbGroupTime = (uint64_t)(((uint64_t)time.timestamp * 1000) * 1000000 + LifxMagicNum); } else { uint8_t *p = (uint8_t *)&bulbGroupTime; for (int k = 0; k < 8; k++) { p[k] = request.data[k + 32 + 16]; } } } break; case GET_GROUP_STATE: { response.packet_type = GROUP_STATE; response.res_ack = RES_REQUIRED; response.protocol = LifxProtocol_AllBulbsResponse; uint8_t *p = (uint8_t *)&bulbGroupTime; byte groupStateResponse[56] = {}; for (int i = 0; i < sizeof(bulbGroupGUIDb); i++) { groupStateResponse[i] = bulbGroupGUIDb[guidSeq[i]]; // special sequence } for (int j = 0; j < sizeof(bulbGroup); j++) { groupStateResponse[j + 16] = bulbGroup[j]; } for (int k = 0; k < sizeof(bulbGroupTime); k++) { groupStateResponse[k + 32 + 16] = p[k]; } memcpy(response.data, groupStateResponse, sizeof(groupStateResponse)); response.data_size = sizeof(groupStateResponse); sendPacket(response, packet); } break; case GET_VERSION_STATE: { // respond to get command response.packet_type = VERSION_STATE; response.protocol = LifxProtocol_AllBulbsResponse; response.res_ack = RES_REQUIRED; // matching real bulb response byte VersionData[] = { lowByte(LifxBulbVendor), highByte(LifxBulbVendor), 0x00, 0x00, lowByte(LifxBulbProduct), highByte(LifxBulbProduct), 0x00, 0x00, lowByte(LifxBulbVersion), highByte(LifxBulbVersion), 0x00, 0x00}; memcpy(response.data, VersionData, sizeof(VersionData)); response.data_size = sizeof(VersionData); sendPacket(response, packet); } break; case GET_MESH_FIRMWARE_STATE: { // respond to get command response.packet_type = MESH_FIRMWARE_STATE; response.protocol = LifxProtocol_AllBulbsResponse; response.res_ack = RES_REQUIRED; // timestamp data comes from observed packet from a LIFX v1.5 bulb byte MeshVersionData[] = { 0x00, 0x94, 0x18, 0x58, 0x1c, 0x05, 0xd9, 0x14, // color 1000 build 1502237570000000000 0x00, 0x94, 0x18, 0x58, 0x1c, 0x05, 0xd9, 0x14, // color 1000 reserved 0x14d9051c58189400 0x16, 0x00, 0x01, 0x00 // color 1000 Version 65558 // lowByte(LifxFirmwareVersionMinor), // highByte(LifxFirmwareVersionMinor), // lowByte(LifxFirmwareVersionMajor), // highByte(LifxFirmwareVersionMajor) }; memcpy(response.data, MeshVersionData, sizeof(MeshVersionData)); response.data_size = sizeof(MeshVersionData); sendPacket(response, packet); } break; case GET_WIFI_FIRMWARE_STATE: { // respond to get command response.packet_type = WIFI_FIRMWARE_STATE; response.protocol = LifxProtocol_AllBulbsResponse; response.res_ack = RES_REQUIRED; // timestamp data comes from observed packet from a LIFX v1.5 bulb byte WifiVersionData[] = { // Original 1000 values //0x00, 0xc8, 0x5e, 0x31, 0x99, 0x51, 0x86, 0x13, // Original 1000 (1) bulb build timestamp 1406901652000000000 //0xc0, 0x0c, 0x07, 0x00, 0x48, 0x46, 0xd9, 0x43, // Original 1000 (1) firmware reserved value 0x43d9464800070cc0 //0x05, 0x00, 0x01, 0x00 // Original 1000 (1) Version 65541 0x00, 0x88, 0x82, 0xaa, 0x7d, 0x15, 0x35, 0x14, // color 1000 build 1456093684000000000 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // color 1000 has no install timestamp 0x3e, 0x00, 0x65, 0x00 // color 1000 Version 6619198 //lowByte(LifxFirmwareVersionMinor), //highByte(LifxFirmwareVersionMinor), //lowByte(LifxFirmwareVersionMajor), //highByte(LifxFirmwareVersionMajor) }; memcpy(response.data, WifiVersionData, sizeof(WifiVersionData)); response.data_size = sizeof(WifiVersionData); sendPacket(response, packet); } break; case GET_WIFI_INFO: { // TODO response.packet_type = WIFI_INFO; response.protocol = LifxProtocol_AllBulbsResponse; float rssi = pow(10, (WiFi.RSSI() / 10)); // reverse of math.floor(10 * math.log10(signal) + 0.5) debug_print("RSSI: "); debug_println(rssi, DEC); // fetch some byte pointers byte *rssi_p = (byte *)&rssi; byte *tx_p = (byte *)&tx_bytes; byte *rx_p = (byte *)&rx_bytes; byte wifiInfo[] = { rssi_p[0], rssi_p[1], rssi_p[2], rssi_p[3], tx_p[0], tx_p[1], tx_p[2], tx_p[3], rx_p[0], rx_p[1], rx_p[2], rx_p[3], 0x00, // real bulbs seem to spit mystery values out here 0x00}; memcpy(response.data, wifiInfo, sizeof(wifiInfo)); response.data_size = sizeof(wifiInfo); sendPacket(response, packet); } break; case SET_CLOUD_STATE: { cloudStatus = response.data[0]; // lets do it debug_print("Cloud status changed to: "); debug_println(cloudStatus, DEC); } break; case GET_CLOUD_STATE: { response.res_ack = RES_REQUIRED; // matching real bulb response.packet_type = CLOUD_STATE; response.protocol = LifxProtocol_AllBulbsResponse; response.data[0] = cloudStatus; response.data_size = sizeof(cloudStatus); sendPacket(response, packet); } break; case SET_CLOUD_AUTH: case GET_CLOUD_AUTH: { if (request.packet_type == SET_CLOUD_AUTH) { for (int i = 0; i < request.data_size; i++) { cloudAuthResponse[i] = request.data[i]; } } // suspect this is the crypto checksum response // this repsonse is a unique 32bit number for each bulb that does not change response.res_ack = RES_REQUIRED; // matching real bulb response.packet_type = CLOUD_AUTH_STATE; response.protocol = LifxProtocol_AllBulbsResponse; memcpy(response.data, cloudAuthResponse, sizeof(cloudAuthResponse)); response.data_size = sizeof(cloudAuthResponse); sendPacket(response, packet); } break; case GET_CLOUD_BROKER: case SET_CLOUD_BROKER: { if (request.packet_type == SET_CLOUD_BROKER) { for (int i = 0; i < request.data_size; i++) { cloudBrokerUrl[i] = request.data[i]; } } response.res_ack = RES_REQUIRED; // matching real bulb response.packet_type = CLOUD_BROKER_STATE; response.protocol = LifxProtocol_AllBulbsResponse; //byte cloudBrokerUrl[32] = {0x00}; // Real unclouded bulb returned all 0 here memcpy(response.data, cloudBrokerUrl, sizeof(cloudBrokerUrl)); response.data_size = sizeof(cloudBrokerUrl); sendPacket(response, packet); } break; case ECHO_REQUEST: { response.packet_type = ECHO_RESPONSE; response.protocol = LifxProtocol_AllBulbsResponse; memcpy(response.data, request.data, sizeof(request.data)); response.data_size = request.data_size; sendPacket(response, packet); } break; case PAN_GATEWAY: case STATE_INFO: case LOCATION_STATE: case GROUP_STATE: case LIGHT_STATUS: case AUTH_STATE: case VERSION_STATE: case WIFI_FIRMWARE_STATE: case MESH_FIRMWARE_STATE: case STATE_COLOR_ZONE: case BULB_LABEL: { // TODO: allow bulbs to request location from other bulbs on startup? debug_println("Ignoring bulb repsonse packet"); } break; default: { Serial.print(F("################### Unknown packet type: ")); Serial.print(request.packet_type, HEX); Serial.print(F("/")); Serial.println(request.packet_type, DEC); } break; } // need to break struct up into bits so this section is less hacky // should we RES/ACK? switch (request.res_ack) { case NO_RESPONSE: { // nothing debug_println("No RES_ACK"); } break; case RES_REQUIRED: { debug_println("Response Requested"); // Need to figure out if this matters, not set for standard app 'get' packets } break; // currently only supporting ack, hit on any with that bit set case RES_ACK_PAN_REQUIRED: case ACK_PAN_REQUIRED: case RES_ACK_REQUIRED: case ACK_REQUIRED: { debug_println("Acknowledgement Requested"); // We are supposed to acknoledge the packet response.packet_type = ACKNOWLEDGEMENT; response.res_ack = NO_RESPONSE; response.protocol = LifxProtocol_AllBulbsResponse; memset(response.data, 0, sizeof(response.data)); response.data_size = 0; sendPacket(response, packet); } break; case PAN_REQUIRED: { // what debug_println("PAN Response Requred?"); } break; case RES_PAN_REQUIRED: { // not even sure yet debug_println("RES & PAN Response Requred?"); } break; default: { debug_print("Unknown RES_ACK"); debug_println(request.res_ack, HEX); // unknown packet type } } } unsigned int sendPacket(LifxPacket &pkt, AsyncUDPPacket &Udpi) { int totalSize = LifxPacketSize + pkt.data_size; auto time = ha_time->utcnow(); // generate a msec value from epoch uint64_t packetT = (uint64_t)(((uint64_t)time.timestamp * 1000) * 1000000 + LifxMagicNum); // recast large value for packet handling uint8_t *packetTime = (uint8_t *)&packetT; //debug_println( packetT ); uint8_t _message[totalSize + 1]; int _packetLength = 0; memset(_message, 0, totalSize + 1); // initialize _message with zeroes //// FRAME _message[_packetLength++] = (lowByte(totalSize)); _message[_packetLength++] = (highByte(totalSize)); // protocol uint16_t _message[_packetLength++] = (lowByte(pkt.protocol)); _message[_packetLength++] = (highByte(pkt.protocol)); // source/reserved1 .... real bulbs always include this number _message[_packetLength++] = pkt.source[0]; _message[_packetLength++] = pkt.source[1]; _message[_packetLength++] = pkt.source[2]; _message[_packetLength++] = pkt.source[3]; //// FRAME ADDRESS // bulbAddress mac address (target) for (int i = 0; i < sizeof(mac); i++) { _message[_packetLength++] = mac[i]; } // padding MAC _message[_packetLength++] = 0x00; _message[_packetLength++] = 0x00; // site mac address (LIFXV2) for (int i = 0; i < sizeof(site_mac); i++) { _message[_packetLength++] = site_mac[i]; } // reserved3: Flags - 6 bits reserved, 1bit ack required, 1bit res required _message[_packetLength++] = pkt.res_ack; // Sequence. Real bulbs seem to match the incoming value _message[_packetLength++] = pkt.sequence; //// PROTOCOL HEADER // real bulbs send epoch time in msec plus some strange fixed value (lifxMagicNum?) ... docs say "reserved" _message[_packetLength++] = packetTime[0]; _message[_packetLength++] = packetTime[1]; _message[_packetLength++] = packetTime[2]; _message[_packetLength++] = packetTime[3]; _message[_packetLength++] = packetTime[4]; _message[_packetLength++] = packetTime[5]; _message[_packetLength++] = packetTime[6]; _message[_packetLength++] = packetTime[7]; //packet type _message[_packetLength++] = (lowByte(pkt.packet_type)); _message[_packetLength++] = (highByte(pkt.packet_type)); // reserved4 // This number gets twiddled in the stateService response from a real bulb... sometimes.... other time stays zero // 0 0 0 0 0 8 10 12 12 7 6 6 4 0 _message[_packetLength++] = 0x00; _message[_packetLength++] = 0x00; //data for (int i = 0; i < pkt.data_size; i++) { _message[_packetLength++] = pkt.data[i]; } tx_bytes += _packetLength; IPAddress remote_addr = (Udpi.remoteIP()); // Lets reply to the remote IP of packet which may be different than direct IP (.255) //Udp.writeTo(_message, _packetLength, remote_addr, LifxPort ); // async packets get a free reply without specifying target (unicast to remote ip only) Udpi.write(_message, _packetLength); // debugging output debug_print(F("Sent Packet Type 0x")); debug_print(pkt.packet_type, HEX); debug_print(F(" (")); debug_print(pkt.packet_type, DEC); debug_print(F(", ")); debug_print(_packetLength); debug_print(F(" bytes): ")); for (int j = 0; j < _packetLength; j++) { if (_message[j] <= 0x0F) // pad with zeros for proper alignment { debug_print(F("0")); } debug_print(_message[j], HEX); debug_print(SPACE); } debug_println(); return _packetLength; } // this function sets the lights based on values in the globals // TODO: Allow support for different bulb types ( RGB, RGBW, RGBWW, CWWW ) // Currently supported: CWWW+RGB combo light void setLight() { int maxColor = 255; int loopDuration = 0; unsigned long loopRate = millis() - lastChange; // This value will cycle in 49 days from boot up, do we care? debug_print(F("Packet rate:")); debug_print(loopRate); debug_println(F("msec")); debug_print(F("Set light - ")); debug_print(F("hue: ")); debug_print(hue); debug_print(F(", sat: ")); debug_print(sat); debug_print(F(", bri: ")); debug_print(bri); debug_print(F(", kel: ")); debug_print(kel); debug_print(F(", dur: ")); debug_print(dur); debug_print(F(", power: ")); debug_print(power_status); debug_println(power_status ? " (on)" : "(off)"); if (power_status && bri) { float bright = (float)bri / 65535; // Esphome uses 0-1 float for brighness, protocol is 0-65535 // if we are setting a "white" colour (no saturation) // this doesn't work with homekit bridge on home assistant if (sat < 1) { //debug_println(F("White light enabled")); auto callC = color_led->turn_off(); callC.perform(); auto callW = white_led->turn_on(); uint16_t mireds = 1000000 / kel; // Esphome requires mireds, protocol is kelvin callW.set_color_temperature(mireds); callW.set_brightness(bright); // this is an attempt to deal with the brightness wheel in the app spamming changes with a duration > packet rate if (dur > lastChange) { callW.set_transition_length(0); } else { callW.set_transition_length(dur); } callW.perform(); } else { uint8_t rgbColor[3]; auto callW = white_led->turn_off(); auto callC = color_led->turn_on(); // Remap to smaller range.... should consider a better hsb2rgb that supports higher precision int this_hue = map(hue, 0, 65535, 0, 767); int this_sat = map(sat, 0, 65535, 0, 255); int this_bri = map(bri, 0, 65535, 0, 255); // todo: RGBW(W) math to decide mixing in white light approprately when lowering saturation hsb2rgb(this_hue, this_sat, this_bri, rgbColor); // Remap color to RGB from protocol's HSB float r = (float)rgbColor[0] / maxColor; float g = (float)rgbColor[1] / maxColor; float b = (float)rgbColor[2] / maxColor; callC.set_rgb(r, g, b); callC.set_brightness(bright); callC.set_transition_length(dur); callW.perform(); callC.perform(); } } else { // shit be off, yo auto callC = color_led->turn_off(); callC.set_brightness(0); callC.set_transition_length(dur); callC.perform(); auto callW = white_led->turn_off(); callW.set_brightness(0); // fade to black callW.set_transition_length(dur); callW.perform(); } lastChange = millis(); // throttle transitions based on last change } void hexCharacterStringToBytes(byte *byteArray, const char *hexString) { bool oddLength = strlen(hexString) & 1; byte currentByte = 0; byte byteIndex = 0; byte removed = 0; for (byte charIndex = 0; charIndex < strlen(hexString); charIndex++) { bool oddCharIndex = (charIndex - removed) & 1; if (hexString[charIndex] == '-') { //oddLength = !oddLength; // This didn't work.... not sure what happened if we deduct odd number of dashes however removed++; continue; } if (oddLength) { // If the length is odd if (oddCharIndex) { // odd characters go in high nibble currentByte = nibble(hexString[charIndex]) << 4; } else { // Even characters go into low nibble currentByte |= nibble(hexString[charIndex]); byteArray[byteIndex++] = currentByte; currentByte = 0; } } else { // If the length is even if (!oddCharIndex) { // Odd characters go into the high nibble currentByte = nibble(hexString[charIndex]) << 4; } else { // Odd characters go into low nibble currentByte |= nibble(hexString[charIndex]); byteArray[byteIndex++] = currentByte; currentByte = 0; } } } } void dumpByteArray(const byte *byteArray, const byte arraySize) { for (int i = 0; i < arraySize; i++) { Serial.print("0x"); if (byteArray[i] < 0x10) Serial.print("0"); Serial.print(byteArray[i], HEX); Serial.print(", "); } Serial.println(); } byte nibble(char c) { if (c >= '0' && c <= '9') return c - '0'; if (c >= 'a' && c <= 'f') return c - 'a' + 10; if (c >= 'A' && c <= 'F') return c - 'A' + 10; return 0; // Not a valid hexadecimal character } void hsi2rgbw(float H, float S, float I, int *rgbw) { int r, g, b, w; float cos_h, cos_1047_h; H = fmod(H, 360); // cycle H around to 0-360 degrees H = 3.14159 * H / (float)180; // Convert to radians. S = S > 0 ? (S < 1 ? S : 1) : 0; // clamp S and I to interval [0,1] I = I > 0 ? (I < 1 ? I : 1) : 0; if (H < 2.09439) { cos_h = cos(H); cos_1047_h = cos(1.047196667 - H); r = S * 255 * I / 3 * (1 + cos_h / cos_1047_h); g = S * 255 * I / 3 * (1 + (1 - cos_h / cos_1047_h)); b = 0; w = 255 * (1 - S) * I; } else if (H < 4.188787) { H = H - 2.09439; cos_h = cos(H); cos_1047_h = cos(1.047196667 - H); g = S * 255 * I / 3 * (1 + cos_h / cos_1047_h); b = S * 255 * I / 3 * (1 + (1 - cos_h / cos_1047_h)); r = 0; w = 255 * (1 - S) * I; } else { H = H - 4.188787; cos_h = cos(H); cos_1047_h = cos(1.047196667 - H); b = S * 255 * I / 3 * (1 + cos_h / cos_1047_h); r = S * 255 * I / 3 * (1 + (1 - cos_h / cos_1047_h)); g = 0; w = 255 * (1 - S) * I; } rgbw[0] = r; rgbw[1] = g; rgbw[2] = b; rgbw[3] = w; } /****************************************************************************** * accepts hue, saturation and brightness values and outputs three 8-bit color * values in an array (color[]) * * saturation (sat) and brightness (bright) are 8-bit values. * * hue (index) is a value between 0 and 767. hue values out of range are * rendered as 0. * *****************************************************************************/ void hsb2rgb(uint16_t index, uint8_t sat, uint8_t bright, uint8_t color[3]) { uint16_t r_temp, g_temp, b_temp; uint8_t index_mod; uint8_t inverse_sat = (sat ^ 255); index = index % 768; index_mod = index % 256; if (index < 256) { r_temp = index_mod ^ 255; g_temp = index_mod; b_temp = 0; } else if (index < 512) { r_temp = 0; g_temp = index_mod ^ 255; b_temp = index_mod; } else if (index < 768) { r_temp = index_mod; g_temp = 0; b_temp = index_mod ^ 255; } else { r_temp = 0; g_temp = 0; b_temp = 0; } r_temp = ((r_temp * sat) / 255) + inverse_sat; g_temp = ((g_temp * sat) / 255) + inverse_sat; b_temp = ((b_temp * sat) / 255) + inverse_sat; r_temp = (r_temp * bright) / 255; g_temp = (g_temp * bright) / 255; b_temp = (b_temp * bright) / 255; color[0] = (uint8_t)r_temp; color[1] = (uint8_t)g_temp; color[2] = (uint8_t)b_temp; } };
48,977
C++
.h
1,370
31.00073
362
0.642166
giantorth/ESPHomeLifx
33
2
1
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,869
PluginTranslucentRM.cpp
ozone10_Rainmeter-TranslucentRM/Plugin/PluginTranslucentRM.cpp
/* Copyright (C) 2019-2022 oZone 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 3 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, see <https://www.gnu.org/licenses/>. */ #include "StdAfx.h" #include "PluginTranslucentRM.h" // Note: GetString, ExecuteBang and an unnamed function for use as a section variable // have been commented out. Uncomment any functions as needed. // For more information, see the SDK docs: https://docs.rainmeter.net/developers/plugin/cpp/ static bool validWinVersion = false; static bool isWin11 = false; static bool isWin11Mica = false; static bool isMicaFocus = false; static HMODULE hUser32 = nullptr; static std::vector<ParentMeasure*> g_ParentMeasures; inline bool IsAtLeastWin10Build(DWORD buildNumber) { if (!IsWindows10OrGreater()) { return false; } const auto mask = VerSetConditionMask(0, VER_BUILDNUMBER, VER_GREATER_EQUAL); OSVERSIONINFOEXW osvi{}; osvi.dwOSVersionInfoSize = sizeof(osvi); osvi.dwBuildNumber = buildNumber; return VerifyVersionInfo(&osvi, VER_BUILDNUMBER, mask) != FALSE; } void SetWindowAccent(const struct ChildMeasure* measure, HWND hWnd) { const bool useMica = (measure->mica != DWMSBT_NONE) && isWin11Mica; if (validWinVersion && !measure->parent->errorUser32 && !useMica && (!measure->parent->taskbar || measure->accentState != AccentTypes::ACCENT_DISABLED)) { using SWCA = bool (WINAPI*)(HWND hWnd, WINCOMPATTRDATA* wcaData); const auto _SetWindowCompositionAttribute = reinterpret_cast<SWCA>(GetProcAddress(hUser32, "SetWindowCompositionAttribute")); if (_SetWindowCompositionAttribute != nullptr) { ACCENTPOLICY policy = { measure->accentState, measure->flags, measure->color, 0 }; WINCOMPATTRDATA data = { WCA_ACCENT_POLICY, &policy, sizeof(ACCENTPOLICY) }; _SetWindowCompositionAttribute(hWnd, &data); } } } BOOL CALLBACK MonitorEnumProc(HMONITOR /*hMonitor*/, HDC /*hdcMonitor*/, LPRECT /*lprcMonitor*/, LPARAM dwData) { auto count = reinterpret_cast<int*>(dwData); (*count)++; return TRUE; } int CountMonitor(void* rm) { int count = 0; if (EnumDisplayMonitors(nullptr, nullptr, MonitorEnumProc, reinterpret_cast<LPARAM>(&count)) != FALSE) { return count; } RmLogF(rm, LOG_DEBUG, L"Could not count monitors. Will default to %ld.", DEFAULT_MONITOR_COUNT); return DEFAULT_MONITOR_COUNT; } void EnumTaskbars(struct ParentMeasure* parentMeasure, void* rm) { HWND tmpTaskbar = FindWindow(L"Shell_SecondaryTrayWnd", nullptr); if (tmpTaskbar == nullptr) { return; } parentMeasure->monitorCount = CountMonitor(rm); parentMeasure->taskbars.push_back(tmpTaskbar); int guardCounter = 0; while ((tmpTaskbar = FindWindowEx(nullptr, tmpTaskbar, L"Shell_SecondaryTrayWnd", L"")) != nullptr) { if (guardCounter >= (parentMeasure->monitorCount - 1)) { break; } parentMeasure->taskbars.push_back(tmpTaskbar); guardCounter++; } } void SetTaskbars(struct ParentMeasure* parentMeasure, bool enableAccent) { for (auto taskbar : parentMeasure->taskbars) { if (enableAccent) { SetWindowAccent(parentMeasure->ownerChild, taskbar); } else { SendMessage(taskbar, WM_THEMECHANGED, NULL, NULL); } } } void SetColor(struct Measure* measure, void* rm, bool isBorderColor) { auto* color = isBorderColor ? &measure->colorBorder : &measure->color; *color = MIN_TRANPARENCY; auto optionStr = isBorderColor ? L"BorderColor" : L"Color"; std::wstring colorStr = RmReadString(rm, optionStr, L"00000001", TRUE); if (_wcsnicmp(colorStr.c_str(), L"-", 1) == 0U) { colorStr = colorStr.substr(1, colorStr.size()); } if (_wcsnicmp(colorStr.c_str(), L"0x", 2) == 0U) { colorStr = colorStr.substr(2, colorStr.size()); } constexpr size_t RGBAStrSize = 8; constexpr size_t RGBStrSize = 6; const size_t strSize = colorStr.size(); if (strSize > RGBAStrSize || strSize < RGBStrSize) { measure->warn = true; *color = MIN_TRANPARENCY; return; } try { constexpr int hexBase = 16; *color = std::stoul(colorStr, nullptr, hexBase); } catch (const std::invalid_argument&) { measure->warn = true; *color = MIN_TRANPARENCY; return; } constexpr uint32_t bitwiseShift4 = 4; constexpr uint32_t bitwiseShift8 = 8; constexpr uint32_t bitwiseShift24 = 24; constexpr uint32_t maskAA = 0xFF; constexpr uint32_t maskBB = 0xFF00; constexpr uint32_t maskGG = 0xFF0000; constexpr uint32_t maskRR = 0xFF000000; if (strSize < RGBAStrSize) { *color <<= bitwiseShift4; if (strSize == RGBStrSize) { *color <<= bitwiseShift4; } } measure->accentColor = RmReadInt(rm, L"AccentColor", 0) > 0; if (measure->accentColor && measure->accentState != AccentTypes::ACCENT_ENABLE_BLURBEHIND) { GetAccentColor(measure, isBorderColor); } wchar_t buffer[RGBStrSize + 1]; swprintf_s(buffer, L"%06X", (*color >> bitwiseShift8)); measure->hexColor = buffer; // Transform RRGGBBAA to AABBRRGG *color = (((*color & maskAA) << bitwiseShift24) | ((*color & maskRR) >> bitwiseShift24) | ((*color & maskBB) << bitwiseShift8) | ((*color & maskGG) >> bitwiseShift8)); } void GetAccentColor(struct Measure* measure, bool isBorderColor) { if (!measure->errorDwmapi && validWinVersion) { const HMODULE hDwmapi = LoadLibraryEx(L"dwmapi.dll", nullptr, LOAD_LIBRARY_SEARCH_USER_DIRS | LOAD_LIBRARY_SEARCH_SYSTEM32); if (hDwmapi == nullptr) { measure->errorDwmapi = true; return; } using DGCP = HRESULT (WINAPI*)(DWMCOLORIZATIONPARAMS * colorParams); const auto _DwmGetColorizationParameters = reinterpret_cast<DGCP>(GetProcAddress(hDwmapi, MAKEINTRESOURCEA(127))); if (_DwmGetColorizationParameters != nullptr) { struct DWMCOLORIZATIONPARAMS params; _DwmGetColorizationParameters(&params); constexpr uint32_t bitwiseShift8 = 8; constexpr uint32_t maskAA = 0xFF; constexpr uint32_t maskColor = 0xFFFFFF; constexpr uint32_t maskColor2 = 0xFFFFFF00; auto colorMeasure = isBorderColor ? &measure->colorBorder : &measure->color; //use user defined alpha, ignore it for border color //transform AARRGGBB format to RRGGBBAA auto colorTmp = (*colorMeasure & maskAA) | ((params.dmwColor & maskColor) << bitwiseShift8); *colorMeasure = isBorderColor ? (colorTmp & maskColor2) : colorTmp; } FreeLibrary(hDwmapi); } } void InitColor(struct Measure* measure, void* rm) { SetColor(measure, rm, false); if (RmReadInt(rm, L"DisableColorWarning", 0) > 0) { measure->warn = false; } if (measure->warn) { RmLog(rm, LOG_WARNING, L"Wrong format for option color. Color is in hex format RRGGBBAA or RRGGBB."); } } void SetType(struct Measure* measure, void* rm) { const int type = RmReadInt(rm, L"Type", 0); switch (type) { case 1: measure->accentState = AccentTypes::ACCENT_ENABLE_GRADIENT; break; case 2: measure->accentState = AccentTypes::ACCENT_ENABLE_TRANSPARENTGRADIENT; break; case 3: measure->accentState = AccentTypes::ACCENT_ENABLE_BLURBEHIND; SetMinTransparency(measure); break; case 4: measure->accentState = AccentTypes::ACCENT_ENABLE_ACRYLICBLURBEHIND; SetMinTransparency(measure); break; case 5: measure->accentState = AccentTypes::ACCENT_ENABLE_HOSTBACKDROP; break; case 6: measure->accentState = AccentTypes::ACCENT_ENABLE_TRANSPARENT; break; default: measure->accentState = AccentTypes::ACCENT_DISABLED; } measure->usedState = measure->accentState; } void SetMinTransparency(struct Measure* measure) { constexpr uint32_t onlyColor = 0xFFFFFF; if (measure->color <= onlyColor) { measure->color += MIN_TRANPARENCY; } } void SetBorder(struct Measure* measure) { if ((measure->border && measure->accentState != AccentTypes::ACCENT_ENABLE_TRANSPARENTGRADIENT) || (isWin11 && (measure->corner == DWMWCP_ROUND || measure->corner == DWMWCP_ROUNDSMALL))) { measure->flags = BORDER; } else { measure->flags = 2; } } void SetBorderColor(struct Measure* measure, void* rm) { if (isWin11 && (measure->corner == DWMWCP_ROUND || measure->corner == DWMWCP_ROUNDSMALL)) { SetColor(measure, rm, true); const COLORREF color = measure->colorBorder; DwmSetWindowAttribute(RmGetSkinWindow(rm), DWMWA_BORDER_COLOR, &color, sizeof(color)); } } void SetCorner(struct Measure* measure, void* rm) { const int cornerType = RmReadInt(rm, L"Corner", 1); if (isWin11) { switch (cornerType) { case 0: measure->corner = DWMWCP_DEFAULT; break; case 2: measure->corner = DWMWCP_ROUND; measure->flags = BORDER; break; case 3: measure->corner = DWMWCP_ROUNDSMALL; measure->flags = BORDER; break; default: measure->corner = DWMWCP_DONOTROUND; } DwmSetWindowAttribute(RmGetSkinWindow(rm), DWMWA_WINDOW_CORNER_PREFERENCE, &measure->corner, sizeof(measure->corner)); } } void InitMica(struct Measure* measure, void* rm) { const int type = RmReadInt(rm, L"Mica", 0); if (isWin11Mica) { switch (type) { case 1: measure->mica = DWMSBT_AUTO; measure->accentState = AccentTypes::ACCENT_DISABLED; break; case 2: measure->mica = DWMSBT_MAINWINDOW; measure->accentState = AccentTypes::ACCENT_DISABLED; break; case 3: measure->mica = DWMSBT_TRANSIENTWINDOW; measure->accentState = AccentTypes::ACCENT_DISABLED; break; case 4: measure->mica = DWMSBT_TABBEDWINDOW; measure->accentState = AccentTypes::ACCENT_DISABLED; break; default: measure->mica = DWMSBT_NONE; } if (measure->mica != DWMSBT_NONE) { const auto hwnd = RmGetSkinWindow(rm); if (!isMicaFocus) { SetWindowPos(hwnd, nullptr, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_SHOWWINDOW); } DwmSetWindowAttribute(hwnd, DWMWA_SYSTEMBACKDROP_TYPE, &measure->mica, sizeof(measure->mica)); } } //else if (isWin11) { // const MARGINS margins = { -1 }; // DwmExtendFrameIntoClientArea(RmGetSkinWindow(rm), &margins); // BOOL useMica = type > 0 ? TRUE : FALSE; // DwmSetWindowAttribute(RmGetSkinWindow(rm), DWMWA_MICA_EFFECT, &useMica, sizeof(useMica)); //} } void SetMica(struct Measure* measure, HWND hwnd) { if (isWin11Mica && measure->mica != DWMSBT_NONE) { MARGINS margins = { 0, 0, 1, 0 }; DwmExtendFrameIntoClientArea(hwnd, &margins); margins = { -1 }; DwmExtendFrameIntoClientArea(hwnd, &margins); DwmSetWindowAttribute(hwnd, DWMWA_SYSTEMBACKDROP_TYPE, &measure->mica, sizeof(measure->mica)); } } void InitParentMeasure(struct ParentMeasure* parentMeasure, void* rm) { auto parent = parentMeasure->ownerChild; hUser32 = LoadLibraryEx(L"user32.dll", nullptr, LOAD_LIBRARY_SEARCH_USER_DIRS | LOAD_LIBRARY_SEARCH_SYSTEM32); if (hUser32 == nullptr) { parentMeasure->errorUser32 = true; return; } InitColor(parent, rm); SetType(parent, rm); parentMeasure->taskbar = RmReadInt(rm, L"Taskbar", 0) > 0; if (parentMeasure->taskbar) { parent->altInfo = RmReadInt(rm, L"Info", 0) > 0; parentMeasure->taskbars.push_back(FindWindowW(L"Shell_TrayWnd", nullptr)); parentMeasure->sndMonitor = RmReadInt(rm, L"SecondMonitor", 0) > 0; EnumTaskbars(parentMeasure, rm); parent->flags = 2; } else { parent->handle = RmGetSkinWindow(rm); parent->border = RmReadInt(rm, L"Border", 0) > 0; SetBorder(parent); SetCorner(parent, rm); InitMica(parent, rm); SetWindowAccent(parent, parent->handle); SetBorderColor(parent, rm); } CheckFeaturesSupport(parent, rm); } void InitChildMeasure(struct ChildMeasure* childMeasure, void* rm) { auto parent = childMeasure->parent; if (parent != nullptr && parent->ownerChild != childMeasure && parent->taskbar && parent->sndMonitor) { childMeasure->taskbarIdx = RmReadInt(rm, L"Index", 0); if (childMeasure->taskbarIdx < 0 || childMeasure->taskbarIdx >= childMeasure->parent->monitorCount) { childMeasure->taskbarIdx = 0; RmLogF(rm, LOG_WARNING, L"Could not get taskbar. Index should be in range from 0 to %ld.", (childMeasure->parent->monitorCount - 1)); } if (childMeasure->taskbarIdx == 0) { childMeasure->handle = nullptr; } else { childMeasure->handle = parent->taskbars.at(childMeasure->taskbarIdx); SetType(childMeasure, rm); } } } void CheckFeaturesSupport(struct Measure* measure, void* rm) { const bool useAcrylic = measure->accentState == AccentTypes::ACCENT_ENABLE_ACRYLICBLURBEHIND; if (useAcrylic) { if (IsAtLeastWin10Build(BUILD_1903) && !isWin11) { RmLog(rm, LOG_DEBUG, L"On Windows 10 1903 (May 2019 update, 10.0.18362) and later when using acrylic (Type=4), dragging skin will be slow. Fixed in Windows 11 build 22000?"); } if (!IsAtLeastWin10Build(BUILD_1803)) { measure->accentState = AccentTypes::ACCENT_ENABLE_BLURBEHIND; RmLog(rm, LOG_WARNING, L"Acrylic is not supported, need at least Windows 10 1803 (April 2018 update, 10.0.17134). Will use blur instead."); } } else if (!isWin11Mica) { if (RmReadInt(rm, L"Mica", 0) > 0) { RmLog(rm, LOG_DEBUG, L"Mica effects are properly supported only on Windows 11 build 22621 and later."); } } else if (isWin11) { if (measure->accentState == AccentTypes::ACCENT_ENABLE_BLURBEHIND) { RmLog(rm, LOG_DEBUG, L"On Windows 11 build 22000 when using blur (Type=3), dragging skin can be slow."); } } else { if (measure->corner == DWMWCP_ROUND || measure->corner == DWMWCP_ROUNDSMALL) { RmLog(rm, LOG_DEBUG, L"Rounded corners are supported only on Windows 11 build 22000 and later."); } } } void CheckErrors(const struct ChildMeasure* childMeasure) { if (childMeasure->parent == nullptr) { RmLog(LOG_ERROR, L"Invalid \"ParentName\""); return; } if (childMeasure->parent->errorUser32) { RmLog(LOG_ERROR, L"TranslucentRM plugin could not load library user32.dll."); } if (childMeasure->errorDwmapi) { RmLog(LOG_WARNING, L"TranslucentRM plugin could not load library dwmapi.dll. Accent color and rounded corners will not be applied."); } } PLUGIN_EXPORT void Initialize(void** data, void* rm) { if (!IsWindows10OrGreater()) { return; } validWinVersion = true; isWin11Mica = IsAtLeastWin10Build(BUILD_22H2); isWin11 = isWin11Mica ? true : IsAtLeastWin10Build(BUILD_WIN11); isMicaFocus = isWin11Mica && (RmReadInt(rm, L"MicaOnFocus", 0) > 0); auto child = new ChildMeasure; *data = child; // Initialize Parent measure or Set Child measure void* skin = RmGetSkin(rm); LPCWSTR parentName = RmReadString(rm, L"ParentName", L"", 1); if (*parentName == 0U) { child->parent = new ParentMeasure; child->parent->name = RmGetMeasureName(rm); child->parent->skin = skin; child->parent->ownerChild = child; g_ParentMeasures.push_back(child->parent); InitParentMeasure(child->parent, rm); } else { // Find parent using name AND the skin handle to be sure that it's the right one for (auto parentMeasure : g_ParentMeasures) { if (_wcsicmp(parentMeasure->name, parentName) == 0 && parentMeasure->skin == skin && parentMeasure->taskbar && parentMeasure->sndMonitor) { child->parent = parentMeasure; child->parent->sameStyle = false; child->flags = 2; child->altInfo = RmReadInt(rm, L"Info", 0) > 0; break; } } if (child->parent == nullptr) { RmLog(rm, LOG_ERROR, L"Invalid \"ParentName\""); return; } } InitChildMeasure(child, rm); } PLUGIN_EXPORT void Reload(void* data, void* rm, double* /*maxValue*/) { if (!validWinVersion || hUser32 == nullptr) { return; } auto child = static_cast<ChildMeasure*>(data); auto parent = child->parent; if (parent != nullptr) { if (parent->taskbar) { InitColor(child, rm); } else { SetMica(child, child->handle); } } } PLUGIN_EXPORT double Update(void* data) { if (!validWinVersion) { return -1; } auto child = static_cast<ChildMeasure*>(data); auto parent = child->parent; if (parent == nullptr) { return -1; } if (parent->ownerChild == child) { if (parent->taskbar) { if (parent->sndMonitor && parent->sameStyle) { SetTaskbars(parent, true); } else { SetWindowAccent(child, parent->taskbars.at(0)); } } else if (isMicaFocus) { SetMica(child, child->handle); } } else { if (parent->sndMonitor) { SetWindowAccent(child, child->handle); } } if (child->altInfo) { return static_cast<double>(parent->monitorCount); } return static_cast<double>(child->accentState); } PLUGIN_EXPORT LPCWSTR GetString(void* data) { if (!validWinVersion) { return L"Usupported."; } auto child = static_cast<ChildMeasure*>(data); auto parent = child->parent; if (parent == nullptr) { return L"Error"; } if (parent->ownerChild == child) { if (child->altInfo) { return child->hexColor.c_str(); } if (parent->taskbar) { return L"Taskbar"; } return L"Skin"; } if (child->altInfo) { return child->hexColor.c_str(); } if (parent->sndMonitor) { return L"SecondaryTaskbar"; } return L"SecondaryTaskbar (Disabled)"; } //PLUGIN_EXPORT void ExecuteBang(void* data, LPCWSTR args) //{ // Measure* measure = static_cast<Measure*>(data); //} //PLUGIN_EXPORT LPCWSTR (void* data, const int argc, const WCHAR* argv[]) //{ // Measure* measure = static_cast<Measure*>(data); // return nullptr; //} PLUGIN_EXPORT void Finalize(void* data) { if (!validWinVersion) { RmLog(LOG_WARNING, L"TranslucentRM plugin is supported only on Windows 10 and 11."); return; } auto child = static_cast<ChildMeasure*>(data); auto parent = child->parent; if (parent != nullptr && parent->ownerChild == child) { if (!child->parent->errorUser32) { child->accentState = AccentTypes::ACCENT_DISABLED; child->flags = 0; if (parent->taskbar) { if (parent->sndMonitor) { SetTaskbars(parent, false); } else { SendMessage(parent->taskbars.at(0), WM_THEMECHANGED, NULL, NULL); } std::vector<HWND>().swap(parent->taskbars); } else { SetWindowAccent(child, child->handle); } FreeLibrary(hUser32); } hUser32 = nullptr; std::vector<ParentMeasure*>().swap(g_ParentMeasures); delete parent; } CheckErrors(child); delete child; }
20,993
C++
.cpp
577
29.155979
186
0.631095
ozone10/Rainmeter-TranslucentRM
32
0
2
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,870
version.h
ozone10_Rainmeter-TranslucentRM/Plugin/version.h
#pragma once // Has to be the same as the project name! #define VER_PLUGIN_NAME_STR "TranslucentRM" #define VER_PLUGIN_MAJOR 1 #define VER_PLUGIN_MINOR 2 #define VER_PLUGIN_REVISION 0 #define VER_PLUGIN_BUILD 0 #define VER_PLUGIN_AUTHOR_STR "oZone" #define VER_PLUGIN_YEAR 2022 #define VER_RAINMETER_MAJOR 4 #define VER_RAINMETER_MINOR 5 #define VER_RAINMETER_REVISION 13 #define VER_RAINMETER_BUILD 3632 // This is the path relative to root directory (where build.bat is placed) //#define EXAMPLE_SKIN_PATH "ExampleSkin" //#define EXAMPLE_SKIN_NAME "Example Skin"
617
C++
.h
16
37.5625
74
0.728785
ozone10/Rainmeter-TranslucentRM
32
0
2
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,871
PluginTranslucentRM.h
ozone10_Rainmeter-TranslucentRM/Plugin/PluginTranslucentRM.h
/* Copyright (C) 2019-2022 oZone 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 3 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, see <https://www.gnu.org/licenses/>. */ #pragma once // Won't support outdated insider builds //constexpr DWORD MIN_FLUENT_BUILD = 17063; constexpr DWORD BUILD_1803 = 17134; // Windows 10 1803 (April 2018 Update) constexpr DWORD BUILD_1903 = 18362; // Windows 10 1903 (May 2019 Update) constexpr DWORD BUILD_WIN11 = 22000; // Windows 11 first "stable" build constexpr DWORD BUILD_22H2 = 22621; // Windows 11 22H2 first to support mica properly constexpr uint32_t MIN_TRANPARENCY = 0x01000000; constexpr int32_t BORDER = 0x1E0; //0x20U | 0x40U | 0x80U | 0x100U; constexpr uint32_t WCA_ACCENT_POLICY = 19; constexpr uint32_t DWMWA_MICA_EFFECT = 1029; // Windows 11 Mica constexpr int DEFAULT_MONITOR_COUNT = 5; enum class AccentTypes : int { ACCENT_DISABLED = 0, ACCENT_ENABLE_GRADIENT = 1, ACCENT_ENABLE_TRANSPARENTGRADIENT = 2, ACCENT_ENABLE_BLURBEHIND = 3, ACCENT_ENABLE_ACRYLICBLURBEHIND = 4, ACCENT_ENABLE_HOSTBACKDROP = 5, ACCENT_ENABLE_TRANSPARENT = 6 }; struct ACCENTPOLICY { AccentTypes nAccentState = AccentTypes::ACCENT_DISABLED; int32_t nFlags = 0; uint32_t nColor = 0; int32_t nAnimationId = 0; }; struct WINCOMPATTRDATA { uint32_t nAttribute = 0; void* pData = nullptr; uint32_t ulDataSize = 0; }; struct DWMCOLORIZATIONPARAMS { COLORREF dmwColor = 0; COLORREF dmwAfterglow = 0; DWORD dmwColorBalance = 0; DWORD dmwAfterglowBalance = 0; DWORD dmwBlurBalance = 0; DWORD dmwGlassReflectionIntensity = 0; BOOL dmwOpaqueBlend = FALSE; }; struct Measure { AccentTypes accentState = AccentTypes::ACCENT_DISABLED; AccentTypes usedState = AccentTypes::ACCENT_DISABLED; HWND handle = nullptr; uint32_t color = MIN_TRANPARENCY; std::wstring hexColor = L""; int32_t flags = 0; bool border = false; bool accentColor = false; bool altInfo = false; bool warn = false; bool errorDwmapi = false; DWM_SYSTEMBACKDROP_TYPE mica = DWMSBT_NONE; uint32_t colorBorder = 0x002B2B2B; DWM_WINDOW_CORNER_PREFERENCE corner = DWMWCP_DONOTROUND; }; struct ChildMeasure; struct ParentMeasure { void* skin = nullptr; LPCWSTR name = nullptr; ChildMeasure* ownerChild = nullptr; std::vector<HWND> taskbars; int monitorCount = 0; bool taskbar = false; bool sndMonitor = false; bool sameStyle = true; bool errorUser32 = false; }; struct ChildMeasure : public Measure { ParentMeasure* parent = nullptr; int taskbarIdx = 0; }; inline bool IsAtLeastWin10Build(DWORD buildNumber); void SetWindowAccent(const struct ChildMeasure* measure, HWND hWnd); inline BOOL CALLBACK MonitorEnumProc(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData); inline int CountMonitor(void* rm); void EnumTaskbars(struct ParentMeasure* parentMeasure, void* rm); void SetTaskbars(struct ParentMeasure* parentMeasure, bool enableAccent); void SetColor(struct Measure* measure, void* rm, bool isBorderColor); inline void GetAccentColor(struct Measure* measure, bool isBorderColor); inline void InitColor(struct Measure* measure, void* rm); inline void SetType(struct Measure* measure, void* rm); inline void SetMinTransparency(struct Measure* measure); inline void SetBorder(struct Measure* measure); void SetBorderColor(struct Measure* measure, void* rm); void SetCorner(struct Measure* measure, void* rm); void InitMica(struct Measure* measure, void* rm); void SetMica(struct Measure* measure, HWND hwnd); void InitParentMeasure(struct ParentMeasure* parentMeasure, void* rm); void InitChildMeasure(struct ChildMeasure* childMeasure, void* rm); void CheckFeaturesSupport(struct Measure* measure, void* rm); void CheckErrors(const struct ChildMeasure* childMeasure);
4,373
C++
.h
106
38.04717
107
0.763388
ozone10/Rainmeter-TranslucentRM
32
0
2
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,872
StdAfx.h
ozone10_Rainmeter-TranslucentRM/Plugin/StdAfx.h
/* Copyright (C) 2019-2022 oZone 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 3 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, see <https://www.gnu.org/licenses/>. */ #pragma once // WinAPI #include <Windows.h> #include <dwmapi.h> #include <VersionHelpers.h> // STL #include <stdexcept> #include <string> #include <vector> // Rainmeter API #include "../API/RainmeterAPI.h" #define UNUSED(expr) \ do { \ (void)(expr); \ } while (0)
969
C++
.h
28
31.964286
71
0.738478
ozone10/Rainmeter-TranslucentRM
32
0
2
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,875
SetupController.cpp
KushlaVR_WemosRemote/WemosRemote/WemosRemote/SetupController.cpp
#include "SetupController.h" SetupController::SetupController() { webServer.on("/api/setup", HTTPMethod::HTTP_GET, Setup_Get); webServer.on("/api/setup", HTTPMethod::HTTP_POST, Setup_Post); } SetupController::~SetupController() { } void SetupController::loadConfig() { String s; JsonString cfg = ""; File cfgFile; if (!SPIFFS.exists("/config.json")) { console.println(("Default setting loaded...")); cfg.beginObject(); cfg.AddValue("ssid", "WEMOS"); cfg.AddValue("password", "12345678"); cfg.AddValue("mode", "debug"); cfg.AddValue("center", "90"); cfg.AddValue("max_left", "120"); cfg.AddValue("max_right", "60"); cfg.AddValue("stearing_linearity", "1"); cfg.AddValue("controller_type", "2"); cfg.AddValue("min_speed", "20"); cfg.AddValue("inertion", "800"); cfg.AddValue("potentiometer_linearity", "1"); cfg.AddValue("front_light_on", "40"); cfg.AddValue("high_light_on", "80"); cfg.AddValue("parking_light_on", "10"); cfg.AddValue("turn_light_on", "80"); cfg.AddValue("stop_light_duration", "2000"); cfg.AddValue("back_light_timeout", "500"); cfg.AddValue("back_light_pwm", "70"); cfg.AddValue("beep_freq", "1000"); cfg.AddValue("beep_duration", "150"); cfg.AddValue("beep_interval", "50"); cfg.AddValue("drive_mode", "1"); cfg.endObject(); cfgFile = SPIFFS.open("/config.json", "w"); cfgFile.print(cfg.c_str()); cfgFile.flush(); cfgFile.close(); } else { console.println(("Reading config...")); cfgFile = SPIFFS.open("/config.json", "r"); s = cfgFile.readString(); cfg = JsonString(s.c_str()); cfgFile.close(); } this->cfg->ssid = String(cfg.getValue("ssid")); this->cfg->password = String(cfg.getValue("password")); s = cfg.getValue("mode"); if (s == "debug") this->cfg->debug = true; else this->cfg->debug = false; //Servo config reading this->cfg->center = cfg.getInt("center"); this->cfg->max_left = cfg.getInt("max_left"); this->cfg->max_right = cfg.getInt("max_right"); this->cfg->stearing_linearity = cfg.getInt("stearing_linearity"); //motor config reading this->cfg->controller_type = cfg.getInt("controller_type"); this->cfg->min_speed = cfg.getInt("min_speed"); this->cfg->inertion = cfg.getInt("inertion"); this->cfg->potentiometer_linearity = cfg.getInt("potentiometer_linearity"); this->cfg->front_light_on = cfg.getInt("front_light_on"); this->cfg->high_light_on = cfg.getInt("high_light_on"); this->cfg->parking_light_on = cfg.getInt("parking_light_on"); this->cfg->turn_light_on = cfg.getInt("turn_light_on"); this->cfg->stop_light_duration = cfg.getInt("stop_light_duration"); this->cfg->back_light_timeout = cfg.getInt("back_light_timeout"); this->cfg->back_light_pwm = cfg.getInt("back_light_pwm"); this->cfg->beep_freq = cfg.getInt("beep_freq"); this->cfg->beep_duration = cfg.getInt("beep_duration"); this->cfg->beep_interval = cfg.getInt("beep_interval"); this->cfg->drive_mode = cfg.getInt("drive_mode"); } void SetupController::saveConfig() { JsonString out = JsonString(); printConfig(&out); File cfgFile = SPIFFS.open("/config.json", "w"); cfgFile.print(out.c_str()); cfgFile.flush(); cfgFile.close(); if (setupController.reloadConfig != nullptr) setupController.reloadConfig(); } void SetupController::printConfig(JsonString * out) { out->beginObject(); out->AddValue("ssid", cfg->ssid); out->AddValue("password", cfg->password); out->AddValue("center", String(cfg->center)); out->AddValue("max_left", String(cfg->max_left)); out->AddValue("max_right", String(cfg->max_right)); out->AddValue("stearing_linearity", String(cfg->stearing_linearity)); out->AddValue("controller_type", String(cfg->controller_type)); out->AddValue("min_speed", String(cfg->min_speed)); out->AddValue("inertion", String(cfg->inertion)); out->AddValue("potentiometer_linearity", String(cfg->potentiometer_linearity)); out->AddValue("front_light_on", String(cfg->front_light_on)); out->AddValue("high_light_on", String(cfg->high_light_on)); out->AddValue("parking_light_on", String(cfg->parking_light_on)); out->AddValue("turn_light_on", String(cfg->turn_light_on)); out->AddValue("stop_light_duration", String(cfg->stop_light_duration)); out->AddValue("back_light_timeout", String(cfg->back_light_timeout)); out->AddValue("back_light_pwm", String(cfg->back_light_pwm)); out->AddValue("beep_freq", String(cfg->beep_freq)); out->AddValue("beep_duration", String(cfg->beep_duration)); out->AddValue("beep_interval", String(cfg->beep_interval)); out->AddValue("drive_mode", String(cfg->drive_mode)); out->AddValue("debug", String(cfg->debug)); out->endObject(); } void SetupController::Setup_Get() { JsonString ret = JsonString(); setupController.printConfig(&ret); webServer.jsonOk(&ret); } void SetupController::Setup_Post() { if (webServer.hasArg("ssid")) { setupController.cfg->ssid = webServer.arg("ssid"); } if (webServer.hasArg("password")) { setupController.cfg->password = webServer.arg("password"); } if (webServer.hasArg("center")) { setupController.cfg->center = webServer.arg("center").toInt(); } if (webServer.hasArg("max_left")) { setupController.cfg->max_left = webServer.arg("max_left").toInt(); } if (webServer.hasArg("max_right")) { setupController.cfg->max_right = webServer.arg("max_right").toInt(); } if (webServer.hasArg("stearing_linearity")) { setupController.cfg->stearing_linearity = webServer.arg("stearing_linearity").toInt(); } if (webServer.hasArg("controller_type")) { setupController.cfg->controller_type = webServer.arg("controller_type").toInt(); } if (webServer.hasArg("inertion")) { setupController.cfg->inertion = webServer.arg("inertion").toInt(); } if (webServer.hasArg("min_speed")) { setupController.cfg->min_speed = webServer.arg("min_speed").toInt(); } if (webServer.hasArg("potentiometer_linearity")) { setupController.cfg->potentiometer_linearity = webServer.arg("potentiometer_linearity").toInt(); } if (webServer.hasArg("front_light_on")) { setupController.cfg->front_light_on = webServer.arg("front_light_on").toInt(); } if (webServer.hasArg("high_light_on")) { setupController.cfg->high_light_on = webServer.arg("high_light_on").toInt(); } if (webServer.hasArg("parking_light_on")) { setupController.cfg->parking_light_on = webServer.arg("parking_light_on").toInt(); } if (webServer.hasArg("turn_light_on")) { setupController.cfg->turn_light_on = webServer.arg("turn_light_on").toInt(); } if (webServer.hasArg("stop_light_duration")) { setupController.cfg->stop_light_duration = webServer.arg("stop_light_duration").toInt(); } if (webServer.hasArg("back_light_timeout")) { setupController.cfg->back_light_timeout = webServer.arg("back_light_timeout").toInt(); } if (webServer.hasArg("back_light_pwm")) { setupController.cfg->back_light_pwm = webServer.arg("back_light_pwm").toInt(); } if (webServer.hasArg("beep_freq")) { setupController.cfg->beep_freq = webServer.arg("beep_freq").toInt(); } if (webServer.hasArg("beep_duration")) { setupController.cfg->beep_duration = webServer.arg("beep_duration").toInt(); } if (webServer.hasArg("beep_interval")) { setupController.cfg->beep_interval = webServer.arg("beep_interval").toInt(); } if (webServer.hasArg("drive_mode")) { setupController.cfg->drive_mode = webServer.arg("drive_mode").toInt(); } setupController.saveConfig(); webServer.sendHeader("Location", String("http://") + WebUIController::ipToString(webServer.client().localIP()), true); webServer.send(302, "text/plain", ""); // Empty content inhibits Content-length header so we have to close the socket ourselves. webServer.client().stop(); // Stop is needed because we sent no content length } SetupController setupController;
7,699
C++
.cpp
153
47.973856
150
0.713429
KushlaVR/WemosRemote
32
8
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,876
Console.cpp
KushlaVR_WemosRemote/WemosRemote/WemosRemote/Console.cpp
#include "Console.h" Console console = Console(); Console::Console() { } Console::~Console() { } size_t Console::write(uint8_t b) { if (output != nullptr) return output->write(b); return 1; }
199
C++
.cpp
13
13.769231
48
0.707182
KushlaVR/WemosRemote
32
8
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,879
Stearing.cpp
KushlaVR_WemosRemote/WemosRemote/WemosRemote/Stearing.cpp
#include "Stearing.h" int Stearing::mapPosition(int direction, PotentiometerLinearity stearing_linearity) { int corectedDirection = abs(direction); if (stearing_linearity == PotentiometerLinearity::X2_div_X) { corectedDirection = (direction * direction) / 100; } if (direction >= -5 && direction <= 5) return center; if (direction > 5)//в право return map(corectedDirection, 0, 100, center, max_right); if (direction < -5) return map(corectedDirection, 0, 100, center, max_left); } Stearing::Stearing(int pin) { this->pin = pin; pinMode(pin, OUTPUT); servo = new Servo(); //servo->attach(pin); } Stearing::~Stearing() { } void Stearing::setPosition(int position, PotentiometerLinearity stearing_linearity) { int newPos = mapPosition(position, stearing_linearity); if (newPos != factPosition) { console.printf("Stearing->%i\n", newPos); } factPosition = newPos; } void Stearing::loop() { if (isEnabled) { if (!servo->attached()) servo->attach(pin); servo->write(factPosition); } else { if (servo->attached()) servo->detach(); } }
1,073
C++
.cpp
42
23.52381
83
0.725759
KushlaVR/WemosRemote
32
8
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,882
Console.h
KushlaVR_WemosRemote/WemosRemote/WemosRemote/Console.h
#pragma once #include "Print.h" class Console: public Print { public: Console(); ~Console(); Print * output = nullptr; virtual size_t write(uint8_t b); }; extern Console console;
189
C++
.h
11
15.272727
33
0.744186
KushlaVR/WemosRemote
32
8
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,883
mp3.h
KushlaVR_WemosRemote/WemosRemote/WemosRemote/mp3.h
#pragma once #include <AudioFileSourceSPIFFS.h> #include <AudioFileSourceID3.h> #include <AudioGeneratorMP3.h> #include <AudioOutputI2SNoDAC.h> AudioGeneratorMP3 *mp3; AudioFileSourceSPIFFS *mp3_file; AudioFileSourceID3 *mp3_id3; AudioOutputI2SNoDAC *out; ulong mp3Start; ulong mp3Timeout; void initMP3() { out = new AudioOutputI2SNoDAC(); mp3 = new AudioGeneratorMP3(); } void stopMP3() { mp3->stop(); Serial.println("Stopped mp3"); Serial.flush(); mp3Timeout = 0; } void playMP3(const char* path, ulong timeout = 0) { Serial.print("begin mp3:"); Serial.println(path); Serial.flush(); mp3_file = new AudioFileSourceSPIFFS(path); mp3_id3 = new AudioFileSourceID3(mp3_file); mp3->begin(mp3_id3, out); if (!mp3->loop()) { mp3->stop(); } mp3Timeout = timeout; mp3Start = millis(); } void loopMP3() { if (mp3->isRunning()) { if (!mp3->loop()) { stopMP3(); } else { if (mp3Timeout != 0) { if ((millis() - mp3Start) > mp3Timeout) { stopMP3(); } } } } }
1,005
C++
.h
49
18.326531
49
0.707937
KushlaVR/WemosRemote
32
8
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,888
Stearing.h
KushlaVR_WemosRemote/WemosRemote/WemosRemote/Stearing.h
#pragma once #include <Servo.h> #include "Console.h" #include "RoboconMotor.h" #include "SetupController.h" class Stearing { int pin = 0; int factPosition = 0; int mapPosition(int pos, PotentiometerLinearity stearing_linearity); public: Stearing(int pin); ~Stearing(); Servo * servo = nullptr; int max_left = 60; int max_right = 120; int center = 90; bool isEnabled = false; //positio -100..100 void setPosition(int position, PotentiometerLinearity stearing_linearity); void loop(); };
506
C++
.h
22
21.090909
75
0.75891
KushlaVR/WemosRemote
32
8
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,889
SetupController.h
KushlaVR_WemosRemote/WemosRemote/WemosRemote/SetupController.h
#pragma once #include "WebUIController.h" enum PotentiometerLinearity { Linear,// y=x Лінійний потенціометр X2_div_X// y=X^2 / X }; struct ConfigStruct { public: String ssid; String password; bool debug; int center;//градусів int max_left;//градусів int max_right;//градусів int stearing_linearity;//Тип керування int controller_type; int min_speed;//від 0 до 256 int inertion;//від 0 до 10000 int potentiometer_linearity;//Тип керування int front_light_on;//в процентах int high_light_on;//в процентах int parking_light_on;//в процентах int turn_light_on;//в процентах int stop_light_duration;//в мілісекундах int back_light_timeout;//в мілісекундах int back_light_pwm; int beep_freq; int beep_duration; int beep_interval; int drive_mode;//Режим керування }; typedef void(*myFunctionPointer) (); class SetupController { public: ConfigStruct * cfg; SetupController(); ~SetupController(); void loadConfig(); void saveConfig(); void printConfig(JsonString * out); static void Setup_Get(); static void Setup_Post(); myFunctionPointer reloadConfig = nullptr; }; extern SetupController setupController;
1,149
C++
.h
46
22.869565
44
0.780645
KushlaVR/WemosRemote
32
8
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,890
.WemosRemote.vsarduino.h
KushlaVR_WemosRemote/WemosRemote/WemosRemote/__vm/.WemosRemote.vsarduino.h
/* Editor: https://www.visualmicro.com/ This file is for intellisense purpose only. Visual micro (and the arduino ide) ignore this code during compilation. This code is automatically maintained by visualmicro, manual changes to this file will be overwritten The contents of the _vm sub folder can be deleted prior to publishing a project All non-arduino files created by visual micro and all visual studio project or solution files can be freely deleted and are not required to compile a sketch (do not delete your own code!). Note: debugger breakpoints are stored in '.sln' or '.asln' files, knowledge of last uploaded breakpoints is stored in the upload.vmps.xml file. Both files are required to continue a previous debug session without needing to compile and upload again Hardware: LOLIN(WEMOS) D1 R2 & mini, Platform=esp8266, Package=esp8266 */ #if defined(_VMICRO_INTELLISENSE) #ifndef _VSARDUINO_H_ #define _VSARDUINO_H_ #define __ESP8266_esp8266__ #define __ESP8266_ESP8266__ #define __ets__ #define ICACHE_FLASH #define NONOSDK22x_191024 1 #define F_CPU 160000000L #define LWIP_OPEN_SRC #define TCP_MSS 536 #define LWIP_FEATURES 1 #define LWIP_IPV6 0 #define ARDUINO 108010 #define ARDUINO_ESP8266_WEMOS_D1MINI #define ARDUINO_ARCH_ESP8266 #define FLASHMODE_DIO #define ESP8266 #define __cplusplus 201103L #undef __cplusplus #define __cplusplus 201103L #define __STDC__ #define __ARM__ #define __arm__ #define __inline__ #define __asm__(x) #define __asm__ #define __extension__ #define __ATTR_PURE__ #define __ATTR_CONST__ #define __volatile__ #define __ASM #define __INLINE #define __attribute__(noinline) //#define _STD_BEGIN //#define EMIT #define WARNING #define _Lockit #define __CLR_OR_THIS_CALL #define C4005 #define _NEW //typedef int uint8_t; //#define __ARMCC_VERSION 400678 //#define PROGMEM //#define string_literal // //#define prog_void //#define PGM_VOID_P int // typedef int _read; typedef int _seek; typedef int _write; typedef int _close; typedef int __cleanup; //#define inline #define __builtin_clz #define __builtin_clzl #define __builtin_clzll #define __builtin_labs #define __builtin_va_list typedef int __gnuc_va_list; #define __ATOMIC_ACQ_REL #define __CHAR_BIT__ #define _EXFUN() typedef unsigned char byte; extern "C" void __cxa_pure_virtual() {;} typedef long __INTPTR_TYPE__ ; typedef long __UINTPTR_TYPE__ ; typedef long __SIZE_TYPE__ ; typedef long __PTRDIFF_TYPE__; #include "new" #include "Esp.h" #include "arduino.h" #include <pins_arduino.h> #include "..\generic\Common.h" #include "..\generic\pins_arduino.h" #undef F #define F(string_literal) ((const PROGMEM char *)(string_literal)) #undef PSTR #define PSTR(string_literal) ((const PROGMEM char *)(string_literal)) //current vc++ does not understand this syntax so use older arduino example for intellisense //todo:move to the new clang/gcc project types. #define interrupts() sei() #define noInterrupts() cli() #include "WemosRemote.ino" #endif #endif
2,994
C++
.h
96
29.739583
251
0.763478
KushlaVR/WemosRemote
32
8
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
true
false
false
false
false
false
false
1,534,891
.WemosRemote_mp3.vsarduino.h
KushlaVR_WemosRemote/WemosRemote/WemosRemote_mp3/__vm/.WemosRemote_mp3.vsarduino.h
/* Editor: https://www.visualmicro.com/ This file is for intellisense purpose only. Visual micro (and the arduino ide) ignore this code during compilation. This code is automatically maintained by visualmicro, manual changes to this file will be overwritten The contents of the _vm sub folder can be deleted prior to publishing a project All non-arduino files created by visual micro and all visual studio project or solution files can be freely deleted and are not required to compile a sketch (do not delete your own code!). Note: debugger breakpoints are stored in '.sln' or '.asln' files, knowledge of last uploaded breakpoints is stored in the upload.vmps.xml file. Both files are required to continue a previous debug session without needing to compile and upload again Hardware: LOLIN(WEMOS) D1 R2 & mini, Platform=esp8266, Package=esp8266 */ #if defined(_VMICRO_INTELLISENSE) #ifndef _VSARDUINO_H_ #define _VSARDUINO_H_ #define __ESP8266_esp8266__ #define __ESP8266_ESP8266__ #define __ets__ #define ICACHE_FLASH #define F_CPU 160000000L #define LWIP_OPEN_SRC #define TCP_MSS 536 #define LWIP_FEATURES 1 #define LWIP_IPV6 0 #define ARDUINO 10808 #define ARDUINO_ESP8266_WEMOS_D1MINI #define ARDUINO_ARCH_ESP8266 #define FLASHMODE_DIO #define ESP8266 #define __cplusplus 201103L #undef __cplusplus #define __cplusplus 201103L #define __STDC__ #define __ARM__ #define __arm__ #define __inline__ #define __asm__(x) #define __asm__ #define __extension__ #define __ATTR_PURE__ #define __ATTR_CONST__ #define __volatile__ #define __ASM #define __INLINE #define __attribute__(noinline) //#define _STD_BEGIN //#define EMIT #define WARNING #define _Lockit #define __CLR_OR_THIS_CALL #define C4005 #define _NEW //typedef int uint8_t; //#define __ARMCC_VERSION 400678 //#define PROGMEM //#define string_literal // //#define prog_void //#define PGM_VOID_P int // typedef int _read; typedef int _seek; typedef int _write; typedef int _close; typedef int __cleanup; //#define inline #define __builtin_clz #define __builtin_clzl #define __builtin_clzll #define __builtin_labs #define __builtin_va_list typedef int __gnuc_va_list; #define __ATOMIC_ACQ_REL #define __CHAR_BIT__ #define _EXFUN() typedef unsigned char byte; extern "C" void __cxa_pure_virtual() {;} typedef long __INTPTR_TYPE__ ; typedef long __UINTPTR_TYPE__ ; typedef long __SIZE_TYPE__ ; typedef long __PTRDIFF_TYPE__; #include "new" #include "Esp.h" #include "arduino.h" #include <pins_arduino.h> #include "..\generic\Common.h" #include "..\generic\pins_arduino.h" #undef F #define F(string_literal) ((const PROGMEM char *)(string_literal)) #undef PSTR #define PSTR(string_literal) ((const PROGMEM char *)(string_literal)) //current vc++ does not understand this syntax so use older arduino example for intellisense //todo:move to the new clang/gcc project types. #define interrupts() sei() #define noInterrupts() cli() #include "WemosRemote_mp3.ino" #endif #endif
2,969
C++
.h
95
29.8
251
0.762539
KushlaVR/WemosRemote
32
8
0
GPL-3.0
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
false
true
false
false
false
false
false
false
1,534,892
MuSweep.cpp
dmorse_pscfpp/docs/notes/attic/fd1d/MuSweep.cpp
/* * 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 "MuSweep.h" #include <fd1d/System.h> #include <fd1d/domain/Domain.h> #include <fd1d/solvers/Mixture.h> #include <fd1d/iterator/Iterator.h> #include <util/format/Int.h> #include <util/format/Dbl.h> namespace Pscf { namespace Fd1d { using namespace Util; /* * Constructor. */ MuSweep::MuSweep(System& system) : Sweep(system) { setClassName("MuSweep"); } /* * Destructor. */ MuSweep::~MuSweep() {} /* * Read parameters. */ void MuSweep::readParameters(std::istream& in) { // Read ns, baseFileName and (optionally) homogeneousMode Sweep::readParameters(in); int np = mixture().nPolymer(); dMu_.allocate(np); mu0_.allocate(np); readDArray<double>(in, "dMu", dMu_, np); } /* * Initialization at beginning sweep. Set mu0 to current composition. */ void MuSweep::setup() { Sweep::setup(); int np = mixture().nPolymer(); for (int i = 0; i < np; ++i) { UTIL_CHECK(mixture().polymer(i).ensemble() == Species::Open); mu0_[i] = mixture().polymer(i).mu(); } } /* * Set state for specified value of s. */ void MuSweep::setParameters(double s) { double mu; int np = mixture().nPolymer(); for (int i = 0; i < np; ++i) { mu = mu0_[i] + s*dMu_[i]; mixture().polymer(i).setMu(mu); } } void MuSweep::outputSummary(std::ostream& out) { int i = nAccept() - 1; int np = mixture().nPolymer(); double sNew = s(0); if (homogeneousMode_ == -1) { out << Dbl(sNew) << Dbl(system().fHelmholtz(), 20, 10) << Dbl(system().pressure(), 20, 10); for (i = 0; i < np - 1; ++i) { out << Dbl(mixture().polymer(i).phi(), 20, 10); } out << std::endl; } else { out << Dbl(sNew, 10); if (homogeneousMode_ == 0) { double dF = system().fHelmholtz() - system().homogeneous().fHelmholtz(); out << Dbl(dF, 20, 10); for (int i = 0; i < np - 1; ++i) { out << Dbl(mixture().polymer(i).phi(), 16); } } else { double fEx = system().fHelmholtz() - system().homogeneous().fHelmholtz(); double pEx = system().pressure() - system().homogeneous().pressure(); double V = domain().volume()/mixture().vMonomer(); double fExV = fEx*V; double pExV = pEx*V; out << Dbl(fExV, 20, 10); out << Dbl(pExV, 20, 10); for (int i = 0; i < np; ++i) { out << Dbl(mixture().polymer(i).mu(), 16); } for (int i = 0; i < np - 1; ++i) { out << Dbl(system().homogeneous().phi(i), 16); } double dV; for (int i = 0; i < np - 1; ++i) { dV = mixture().polymer(i).phi() - system().homogeneous().phi(i); dV *= V; out << Dbl(dV, 16); } } out << std::endl; } } } // namespace Fd1d } // namespace Pscf
3,391
C++
.cpp
115
21.678261
71
0.50536
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,534,893
LengthSweep.cpp
dmorse_pscfpp/docs/notes/attic/fd1d/LengthSweep.cpp
/* * 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 "LengthSweep.h" #include <fd1d/System.h> #include <fd1d/domain/Domain.h> #include <fd1d/solvers/Mixture.h> #include <fd1d/iterator/Iterator.h> #include <util/format/Int.h> #include <util/format/Dbl.h> namespace Pscf { namespace Fd1d { using namespace Util; /* * Constructor. */ LengthSweep::LengthSweep(System& system) : Sweep(system) { setClassName("LengthSweep"); } /* * Destructor. */ LengthSweep::~LengthSweep() {} /* * Read parameters. */ void LengthSweep::readParameters(std::istream& in) { // Read ns, baseFileName and (optionally) homogeneousMode Sweep::readParameters(in); read<int>(in,"polymerId",polymerId_); read<int>(in,"blockId",blockId_); read<double>(in, "dLength", dLength_); } /* * Initialization at beginning sweep. Set L0 to current block. */ void LengthSweep::setup() { Sweep::setup(); length0_ = mixture().polymer(polymerId_).block(blockId_).length(); } /* * Set state for specified value of s. */ void LengthSweep::setParameters(double s) { double L = length0_ + s*dLength_; mixture().polymer(polymerId_).block(blockId_).setLength(L); } #if 0 void LengthSweep::outputSummary(std::ostream& out) { #if 0 sNew = s(0); int i = nAccept() - 1; int np = mixture().nPolymer(); if (homogeneousMode_ == -1) { out << Dbl(sNew) << Dbl(system().fHelmholtz(), 20, 10) << Dbl(system().pressure(), 20, 10); for (i = 0; i < np - 1; ++i) { out << Dbl(mixture().polymer(i).phi(), 20, 10); } out << std::endl; } else { out << Dbl(sNew,10); if (homogeneousMode_ == 0) { double dF = system().fHelmholtz() - system().homogeneous().fHelmholtz(); out << Dbl(dF, 20, 10); for (int i = 0; i < np - 1; ++i) { out << Dbl(mixture().polymer(i).phi(), 16); } } else { double fEx = system().fHelmholtz() - system().homogeneous().fHelmholtz(); double pEx = system().pressure() - system().homogeneous().pressure(); double V = domain().volume()/mixture().vMonomer(); double fExV = fEx*V; double pExV = pEx*V; out << Dbl(fExV, 20, 10); out << Dbl(pExV, 20, 10); for (int i = 0; i < np; ++i) { out << Dbl(mixture().polymer(i).mu(), 16); } for (int i = 0; i < np - 1; ++i) { out << Dbl(system().homogeneous().phi(i), 16); } double dV; for (int i = 0; i < np - 1; ++i) { dV = mixture().polymer(i).phi() - system().homogeneous().phi(i); dV *= V; out << Dbl(dV, 16); } } out << std::endl; } #endif } #endif } // namespace Fd1d } // namespace Pscf
3,263
C++
.cpp
110
21.954545
72
0.522915
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,534,894
CompositionSweep.cpp
dmorse_pscfpp/docs/notes/attic/fd1d/CompositionSweep.cpp
/* * 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 "CompositionSweep.h" #include <fd1d/System.h> #include <fd1d/domain/Domain.h> #include <fd1d/solvers/Mixture.h> #include <fd1d/iterator/Iterator.h> #include <util/format/Int.h> #include <util/format/Dbl.h> namespace Pscf { namespace Fd1d { using namespace Util; /* * Constructor. */ CompositionSweep::CompositionSweep(System& system) : Sweep(system) { setClassName("CompositionSweep"); } /* * Destructor. */ CompositionSweep::~CompositionSweep() {} /* * Read parameters. */ void CompositionSweep::readParameters(std::istream& in) { // Read ns, baseFileName and (optionally) homogeneousMode Sweep::readParameters(in); int np = mixture().nPolymer(); int ns = mixture().nSolvent(); dPhi_.allocate(np+ns); phi0_.allocate(np+ns); readDArray<double>(in, "dPhi", dPhi_, np+ns); } /* * Initialization at beginning sweep. Set phi0 to current composition. */ void CompositionSweep::setup() { Sweep::setup(); int np = mixture().nPolymer(); int ns = mixture().nSolvent(); int i, j; for (i = 0; i < np; ++i) { phi0_[i] = mixture().polymer(i).phi(); } if (ns > 0) { for (j = 0; j < ns; ++j) { i = np + j; phi0_[i] = mixture().solvent(j).phi(); } } } /* * Set state for specified value of s. */ void CompositionSweep::setParameters(double s) { double phi; int np = mixture().nPolymer(); int ns = mixture().nSolvent(); int i, j; for (int i = 0; i < np; ++i) { phi = phi0_[i] + s*dPhi_[i]; mixture().polymer(i).setPhi(phi); } if (ns > 0) { for (j = 0; j < ns; ++j) { i = j + np; phi = phi0_[i] + s*dPhi_[i]; mixture().solvent(j).setPhi(phi); } } } void CompositionSweep::outputSummary(std::ostream& out) { double sNew = s(0); int i = nAccept() - 1; int np = mixture().nPolymer(); int ns = mixture().nSolvent(); if (homogeneousMode_ == -1) { out << Int(i) << Dbl(sNew) << Dbl(system().fHelmholtz(), 20, 10) << Dbl(system().pressure(), 20, 10); for (int j = 0; j < np; ++j) { out << Dbl(mixture().polymer(j).phi(), 20, 10); } if (ns > 0) { for (int j = 0; j < ns; ++j) { out << Dbl(mixture().solvent(j).phi(), 20, 10); } } out << std::endl; } else { out << Int(i) << Dbl(sNew, 10); if (homogeneousMode_ == 0) { double dF = system().fHelmholtz() - system().homogeneous().fHelmholtz(); out << Dbl(dF, 20, 10); for (int j = 0; j < np; ++j) { out << Dbl(mixture().polymer(j).phi(), 16); } if (ns > 0) { for (int j = 0; j < ns; ++j) { out << Dbl(mixture().solvent(j).phi(), 16); } } } else { double fEx = system().fHelmholtz() - system().homogeneous().fHelmholtz(); double pEx = system().pressure() - system().homogeneous().pressure(); double V = domain().volume()/mixture().vMonomer(); double fExV = fEx*V; double pExV = pEx*V; out << Dbl(fExV, 20, 10); out << Dbl(pExV, 20, 10); // Output chemical potentials for (int j = 0; j < np; ++j) { out << Dbl(mixture().polymer(j).mu(), 16); } if (ns > 0) { for (int j = 0; j < ns; ++j) { out << Dbl(mixture().solvent(j).mu(), 16); } } // Output volume fractions for (int j = 0; j < np; ++j) { out << Dbl(system().homogeneous().phi(j), 16); } if (ns > 0) { for (int j = 0; j < ns; ++j) { out << Dbl(mixture().solvent(j).phi(), 16); } } double dV; for (int j = 0; j < np; ++j) { dV = mixture().polymer(j).phi() - system().homogeneous().phi(j); dV *= V; out << Dbl(dV, 16); } if (ns > 0) { for (int j = 0; j < ns; ++j) { dV = mixture().solvent(j).phi(); dV *= V; out << Dbl(dV, 16); } } } out << std::endl; } } } // namespace Fd1d } // namespace Pscf
4,905
C++
.cpp
162
21.006173
72
0.460025
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,534,895
Interaction.cpp
dmorse_pscfpp/docs/notes/draft/pscf/Interaction.cpp
/* * 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 "Interaction.h" namespace Pscf { using namespace Util; Interaction::Interaction() : nMonomer_(0) { setClassName("Interaction"); } Interaction::~Interaction() {} void Interaction::setNMonomer(int nMonomer) { nMonomer_ = nMonomer; } } // namespace Pscf
484
C++
.cpp
17
25.411765
67
0.728665
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,534,896
Block.cpp
dmorse_pscfpp/docs/notes/draft/cyln/solvers/Block.cpp
/* * PSCF - Polymer Self-Consistent Field Theory * * Copyright 2016, The Regents of the University of Minnesota * Distributed under the terms of the GNU General Public License. */ #include "Block.h" #include <cyln/misc/Domain.h> namespace Pscf { namespace Cyln { using namespace Util; /* * Constructor. */ Block::Block() : domainPtr_(0), ds_(0.0), ns_(0) { propagator(0).setBlock(*this); propagator(1).setBlock(*this); } /* * Destructor. */ Block::~Block() {} void Block::setDiscretization(Domain const & domain, double ds) { UTIL_CHECK(length() > 0); UTIL_CHECK(domain.nr() > 1); UTIL_CHECK(domain.nz() > 1); UTIL_CHECK(ds > 0.0); // Set association to spatial domain domainPtr_ = &domain; // Set contour length discretization ns_ = floor(length()/ds + 0.5) + 1; if (ns_%2 == 0) { ns_ += 1; } ds_ = length()/double(ns_ - 1); int nr = domain.nr(); int nz = domain.nz(); // Allocate propagators and cField propagator(0).allocate(ns_, nr, nz); propagator(1).allocate(ns_, nr, nz); cField().allocate(nr, nz); // Allocate memory for radial Crank-Nicholson dA_.allocate(nr); dB_.allocate(nr); uA_.allocate(nr - 1); uB_.allocate(nr - 1); lA_.allocate(nr - 1); lB_.allocate(nr - 1); rWork_.allocate(nr); solver_.allocate(nr); // Allocate memory for axial pseudo-spectral nk = nz/2 + 1; // Number of wavevectors expW_.allocate(nr, nz); qk_.allocate(nr, nk); expKsq_.allocate(nk); rWork_.allocate(nr); kWork_.allocate(nk); FFTW_.setup(rWork_, qK.slice(0)); } /* * Setup the Crank-Nicholson work arrays. * * This implementation uses the Crank-Nicholson algorithm for stepping * the modified diffusion equation. One step of this algorithm, which * is implemented by the step() function, solves a matrix equation of * the form * * A q(i) = B q(i-1) * * where A and B are nr x nr symmetric tridiagonal matrices given by * * A = 1 + 0.5*ds_*H * B = 1 - 0.5*ds_*H * * in which ds_ is the contour step and * * H = -(b^2/6)d^2/dr^2 * * is a finite difference representation of the radial part of the * "Hamiltonian" operator, in which b = kuhn() is the statistical * segment length. * * This function sets up arrays containing diagonal and off-diagonal * elements of the matrices A and B, and computes the LU * decomposition of matrix A. Arrays of the nr diagonal elements of * A and B are denoted by dA_ and dB_, respectively, while arrays * of nr - 1 upper and lower off-diagonal elements of A and B are * denoted by uA_, lA_, uB_, and lB_, respectively */ void Block::setupRadialLaplacian(Domain& domain) { // Preconditions UTIL_CHECK(ns_ > 0); UTIL_CHECK(propagator(0).isAllocated()); UTIL_CHECK(propagator(1).isAllocated()); UTIL_CHECK(domainPtr_); UTIL_CHECK(domain.nr() > 0); UTIL_CHECK(domain.nz() > 0); int nr = domain.nr(); double dr = domain.dr(); double radius = domain.radius(); // Check that work arrays are allocated, with correct sizes UTIL_CHECK(dA_.capacity() == nr); UTIL_CHECK(uA_.capacity() == nr - 1); UTIL_CHECK(lA_.capacity() == nr - 1); UTIL_CHECK(dB_.capacity() == nr); UTIL_CHECK(uB_.capacity() == nr - 1); UTIL_CHECK(lB_.capacity() == nr - 1); // Second derivative terms in matrix A double halfDs = 0.5*ds_; double db = kuhn()/dr; double c1 = halfDs*db*db/6.0; //double c2 = 2.0*c1; double halfDr = 0.5*dr; double x, rp, rm; // First row: x = xMin rp = 2.0*c1; dA_[0] += 2.0*rp; uA_[0] = -2.0*rp; // Interior rows for (int i = 1; i < nr - 1; ++i) { x = dr*i; rm = 1.0 - halfDr/x; rp = 1.0 + halfDr/x; rm *= c1; rp *= c1; dA_[i] += rm + rp; uA_[i] = -rp; lA_[i-1] = -rm; } // Last row: x = radius rm = 1.0 - halfDr/radius; rm *= c1; dA_[nr-1] += 2.0*rm; lA_[nr-2] = -2.0*rm; // Construct matrix B for (int i = 0; i < nr; ++i) { dB_[i] = -dA_[i]; } for (int i = 0; i < nr - 1; ++i) { uB_[i] = -uA_[i]; } for (int i = 0; i < nr - 1; ++i) { lB_[i] = -lA_[i]; } // Add diagonal identity terms to matrices A and B for (int i = 0; i < nr; ++i) { dA_[i] += 1.0; dB_[i] += 1.0; } // Compute the LU decomposition of matrix A solver_.computeLU(dA_, uA_, lA_); } void Block::setupAxialLaplacian(Domain& domain) { double length = domain.length(); double b = 2.0 * Constants:Pi * kuhn() / length; double c = 0.5*ds_*b*b/6.0; int nz = domain.nz(); int nk = nz/2 + 1; for (i = 0; i < nk; ++i) { expKSq[i] = exp(-c*i*i); } } /* * Integrate to calculate monomer concentration for this block */ void Block::computeConcentration(double prefactor) { // Preconditions UTIL_CHECK(domain().nr() > 0); UTIL_CHECK(ns_ > 0); UTIL_CHECK(ds_ > 0); UTIL_CHECK(dA_.capacity() == domain().nr()); UTIL_CHECK(dB_.capacity() == domain().nr()); UTIL_CHECK(uA_.capacity() == domain().nr() -1); UTIL_CHECK(uB_.capacity() == domain().nr() -1); UTIL_CHECK(propagator(0).isAllocated()); UTIL_CHECK(propagator(1).isAllocated()); UTIL_CHECK(cField().capacity() == domain().nr()) // Initialize cField to zero at all points int i; int nr = domain().nr(); for (i = 0; i < nr; ++i) { cField()[i] = 0.0; } Propagator const & p0 = propagator(0); Propagator const & p1 = propagator(1); // Evaluate unnormalized integral for (i = 0; i < nr; ++i) { cField()[i] += 0.5*p0.q(0)[i]*p1.q(ns_ - 1)[i]; } for (int j = 1; j < ns_ - 1; ++j) { for (i = 0; i < nr; ++i) { cField()[i] += p0.q(j)[i]*p1.q(ns_ - 1 - j)[i]; } } for (i = 0; i < nr; ++i) { cField()[i] += 0.5*p0.q(ns_ - 1)[i]*p1.q(0)[i]; } // Normalize prefactor *= ds_; for (i = 0; i < nr; ++i) { cField()[i] *= prefactor; } } #if 0 /* * Propagate solution by one step. * * This function implements one step of the Crank-Nicholson algorithm. * To do so, it solves A q(i+1) = B q(i), where A and B are constant * matrices defined in the documentation of the setupStep() function. */ void Block::radialStep(const QField& q, QField& qNew) { int nr = domain().nr(); rWork_[0] = dB_[0]*q[0] + uB_[0]*q[1]; for (int i = 1; i < nr - 1; ++i) { rWork_[i] = dB_[i]*q[i] + lB_[i-1]*q[i-1] + uB_[i]*q[i+1]; } rWork_[nr - 1] = dB_[nr-1]*q[nr-1] + lB_[nr-2]*q[nr-2]; solver_.solve(rWork_, qNew); } #endif } }
7,185
C++
.cpp
234
24.405983
72
0.53686
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,534,897
Mixture.cpp
dmorse_pscfpp/docs/notes/draft/cyln/solvers/Mixture.cpp
/* * 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 "Mixture.h" #include <cyln/domain/Domain.h> #include <cmath> namespace Pscf { namespace Cyln { Mixture::Mixture() : vMonomer_(1.0), ds_(-1.0), domainPtr_(0) { setClassName("Mixture"); } Mixture::~Mixture() {} void Mixture::readParameters(std::istream& in) { MixtureTmpl<Polymer, Solvent>::readParameters(in); vMonomer_ = 1.0; // Default value readOptional(in, "vMonomer", vMonomer_); read(in, "ds", ds_); UTIL_CHECK(nMonomer() > 0); UTIL_CHECK(nPolymer()+ nSolvent() > 0); UTIL_CHECK(ds_ > 0); } void Mixture::setDomain(Domain const& domain) { UTIL_CHECK(nMonomer() > 0); UTIL_CHECK(nPolymer()+ nSolvent() > 0); UTIL_CHECK(ds_ > 0); domainPtr_ = &domain; // 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(domain, ds_); } } } /* * Compute concentrations (but not total free energy). */ void Mixture::compute(DArray<Mixture::WField> const & wFields, DArray<Mixture::CField>& cFields) { UTIL_CHECK(domainPtr_); UTIL_CHECK(domain().nx() > 0); UTIL_CHECK(nMonomer() > 0); UTIL_CHECK(nPolymer() + nSolvent() > 0); UTIL_CHECK(wFields.capacity() == nMonomer()); UTIL_CHECK(cFields.capacity() == nMonomer()); int nx = domain().nx(); int nm = nMonomer(); int i, j, k; // Clear all monomer concentration fields for (i = 0; i < nm; ++i) { UTIL_CHECK(cFields[i].capacity() == nx); UTIL_CHECK(wFields[i].capacity() == nx); for (j = 0; j < nx; ++j) { cFields[i][j] = 0.0; } } // Solve MDE for all polymers for (i = 0; i < nPolymer(); ++i) { polymer(i).compute(wFields); } // Accumulate monomer concentration fields for (i = 0; i < nPolymer(); ++i) { for (j = 0; j < polymer(i).nBlock(); ++j) { int monomerId = polymer(i).block(j).monomerId(); UTIL_CHECK(monomerId >= 0); UTIL_CHECK(monomerId < nm); CField& monomerField = cFields[monomerId]; CField& blockField = polymer(i).block(j).cField(); for (k = 0; k < nx; ++k) { monomerField[k] += blockField[k]; } } } // To do: Add compute functions and accumulation for solvents. } } // namespace Cyln } // namespace Pscf
2,773
C++
.cpp
87
24.908046
68
0.559055
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,534,898
Propagator.cpp
dmorse_pscfpp/docs/notes/draft/cyln/solvers/Propagator.cpp
/* * PSCF - Polymer Self-Consistent Field Theory * * Copyright 2016, The Regents of the University of Minnesota * Distributed under the terms of the GNU General Public License. */ #include "Propagator.h" #include "Block.h" #include <cyln/domain/Domain.h> namespace Pscf { namespace Cyln { using namespace Util; /* * Constructor. */ Propagator::Propagator() : blockPtr_(0), ns_(0), nr_(0), nz_(0), nGrid_(0), isAllocated_(false) {} /* * Destructor. */ Propagator::~Propagator() {} void Propagator::allocate(int ns, int nr, int nz) { ns_ = ns; nr_ = nr; nz_ = nz; nGrid_ = nr*nz; qFields_.allocate(ns); for (int i = 0; i < ns; ++i) { qFields_[i].allocate(nr, nz); } isAllocated_ = true; } bool Propagator::isAllocated() const { return isAllocated_; } /* * Compute initial head QField from final tail QFields of sources. */ void Propagator::computeHead() { // Reference to head of this propagator QField& qh = qFields_[0]; // Initialize qh field to 1.0 at all grid points int ix; for (ix = 0; ix < nGrid_; ++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 < nGrid_; ++ix) { qh[ix] *= qt[ix]; } } } /* * Solve the modified diffusion equation for this block. */ void Propagator::solve() { computeHead(); for (int iStep = 0; iStep < ns_ - 1; ++iStep) { block().step(qFields_[iStep], qFields_[iStep + 1]); } setIsSolved(true); } /* * Solve the modified diffusion equation with specified initial field. */ void Propagator::solve(const Propagator::QField& head) { // Initialize initial (head) field QField& qh = qFields_[0]; for (int i = 0; i < nGrid_; ++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); } /* * Integrate to calculate monomer concentration for this block */ double Propagator::computeQ() { 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(); return block().domain().innerProduct(qh, qt); } } }
2,886
C++
.cpp
113
19.752212
72
0.564019
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,534,899
Polymer.cpp
dmorse_pscfpp/docs/notes/draft/cyln/solvers/Polymer.cpp
/* * PSCF - Polymer Self-Consistent Field Theory * * Copyright 2016, The Regents of the University of Minnesota * Distributed under the terms of the GNU General Public License. */ #include "Polymer.h" namespace Pscf { namespace Cyln { Polymer::Polymer() { setClassName("Polymer"); } Polymer::~Polymer() {} void Polymer::setPhi(double phi) { UTIL_CHECK(ensemble() == Species::Closed); UTIL_CHECK(phi >= 0.0); UTIL_CHECK(phi <= 1.0); phi_ = phi; } void Polymer::setMu(double mu) { UTIL_CHECK(ensemble() == Species::Open); mu_ = mu; } /* * Compute solution to MDE and concentrations. */ void Polymer::compute(const DArray<Block::WField>& wFields) { // Setup solvers for all blocks int monomerId; for (int j = 0; j < nBlock(); ++j) { monomerId = block(j).monomerId(); block(j).setupSolver(wFields[monomerId]); } solve(); } } }
979
C++
.cpp
41
19.097561
64
0.613147
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,534,900
Solvent.cpp
dmorse_pscfpp/docs/notes/draft/cyln/solvers/Solvent.cpp
/* * 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 "Solvent.h" namespace Pscf { namespace Cyln { /* * Constructor */ Solvent::Solvent() { setClassName("Solvent"); } /* * Destructor */ Solvent::~Solvent() {} /* * Compute monomer concentration field and mu or phi. */ void Solvent::compute(WField const & wField) { } } }
514
C++
.cpp
28
15.357143
64
0.672917
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,534,901
Domain.cpp
dmorse_pscfpp/docs/notes/draft/cyln/misc/Domain.cpp
/* * 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 "Domain.h" #include <util/math/Constants.h> namespace Pscf { namespace Cyln { using namespace Util; Domain::Domain() : radius_(0.0), length_(0.0), volume_(0.0), dr_(0.0), dz_(0.0), nr_(0), nz_(0), nGrid_(0), work_() { setClassName("Domain"); } Domain::~Domain() {} void Domain::readParameters(std::istream& in) { read(in, "radius", radius_); read(in, "length", length_); read(in, "nr", nr_); read(in, "nz", nz_); nGrid_ = nr_*nz_; dr_ = radius_/double(nr_ - 1); dz_ = length_/double(nz_ - 1); volume_ = length_*radius_*radius_*Constants::Pi; } void Domain::setParameters(double radius, double length, int nr, int nz) { UTIL_CHECK(radius > 0.0); UTIL_CHECK(length > 0.0); UTIL_CHECK(nr > 1); UTIL_CHECK(nz > 1); radius_ = radius; length_ = length; volume_ = length_*radius_*radius_*Constants::Pi; nr_ = nr; nz_ = nz; nGrid_ = nr_*nz_; dr_ = radius_/double(nr_ - 1); dz_ = length_/double(nz_ - 1); } /* * Compute spatial average of a field. */ double Domain::spatialAverage(Field<double> const & f) const { UTIL_CHECK(nr_ == f.nr()); UTIL_CHECK(nz_ == f.nz()); UTIL_CHECK(nr_ > 1); UTIL_CHECK(nz_ > 1); UTIL_CHECK(dr_ > 0.0); UTIL_CHECK(dz_ > 0.0); UTIL_CHECK(radius_ > dr_); double sum = 0.0; double norm = 0.0; double r; int i, j; int k = 0; // Central axis (r=0) r = 1.0/8.0; for (j = 0; j < nz_; ++j) { sum += f[k]*r; norm += r; ++k; } // Intermediate shells for (i = 1; i < nr_ - 1; ++i) { r = double(i); for (j = 0; j < nz_; ++j) { sum += r*f[0]; norm += r; ++k; } } // Outer shell r = 0.5*double(nr_-1); for (j=0; j < nz_; ++j) { sum += r*f[nr_-1]; norm += r; ++k; } UTIL_CHECK(k == nr_*nz_); return sum/norm; } /* * Compute inner product of two real fields. */ double Domain::innerProduct(Field<double> const & f, Field<double> const & g) const { // Preconditions UTIL_CHECK(nGrid_ > 1); UTIL_CHECK(nGrid_ == f.capacity()); UTIL_CHECK(nGrid_ == g.capacity()); if (!work_.isAllocated()) { work_.allocate(nr_, nz_); } else { UTIL_ASSERT(nGrid_ == work_.capacity()); } // Compute average of f(x)*g(x) for (int i = 0; i < nGrid_; ++i) { work_[i] = f[i]*g[i]; } return spatialAverage(work_); } } }
2,940
C++
.cpp
117
18.57265
86
0.494302
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,534,902
FFT.cpp
dmorse_pscfpp/docs/notes/draft/cyln/field/FFT.cpp
/* * PSCF Package * * Copyright 2016 - 2017, The Regents of the University of Minnesota * Distributed under the terms of the GNU General Public License. */ #include "FFT.h" namespace Pscf { namespace Cyln { using namespace Util; /* * Default constructor. */ FFT::FFT() : work_(), rSize_(0), kSize_(0), fPlan_(0), iPlan_(0), isSetup_(false) {} /* * Destructor. */ FFT::~FFT() { if (fPlan_) { fftw_destroy_plan(fPlan_); } if (iPlan_) { fftw_destroy_plan(iPlan_); } } /* * Check and (if necessary) setup mesh dimensions. */ void FFT::setup(Array<double>& rField, Array<fftw_complex>& kField) { // Preconditions UTIL_CHECK(!isSetup_); rSize_ = rField.capacity(); kSize_ = kField.capacity(); UTIL_CHECK(rSize_ > 0); UTIL_CHECK(kSize_ == rSize_/2 + 1); work_.allocate(rSize_); unsigned int flags = FFTW_ESTIMATE; fPlan_ = fftw_plan_dft_r2c_1d(rSize_, &rField[0], &kField[0], flags); iPlan_ = fftw_plan_dft_c2r_1d(rSize_, &kField[0], &rField[0], flags); isSetup_ = true; } /* * Execute forward transform. */ void FFT::forwardTransform(Array<double>& rField, Array<fftw_complex>& kField) { // Check dimensions or setup if (isSetup_) { UTIL_CHECK(rField.capacity() == rSize_); UTIL_CHECK(kField.capacity() == kSize_); UTIL_CHECK(work_.capacity() == rSize_); } else { setup(rField, kField); } // Copy rescaled input data prior to work array double scale = 1.0/double(rSize_); for (int i = 0; i < rSize_; ++i) { work_[i] = rField[i]*scale; } fftw_execute_dft_r2c(fPlan_, &work_[0], &kField[0]); } /* * Execute inverse (complex-to-real) transform. */ void FFT::inverseTransform(Array<fftw_complex>& kField, Array<double>& rField) { // Check dimensions or setup if (isSetup_) { UTIL_CHECK(work_.capacity() == rSize_); UTIL_CHECK(rField.capacity() == rSize_); UTIL_CHECK(kField.capacity() == kSize_); } else { setup(rField, kField); } fftw_execute_dft_c2r(iPlan_, &kField[0], &rField[0]); } } }
2,356
C++
.cpp
90
19.9
75
0.558418
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,534,903
NanException.cpp
dmorse_pscfpp/src/pscf/iterator/NanException.cpp
/* * 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 "NanException.h" #include <sstream> namespace Pscf { using namespace Util; /* * Constructor, with function name. */ NanException::NanException(const char *function, const char *file, int line, int echo) : Exception(function, "required numerical parameter has value of NaN", file, line, echo) {} /* * Constructor, with no function name. */ NanException::NanException(const char *file, int line, int echo) : Exception("required numerical parameter has value of NaN", file, line, echo) {} /* * Destructor. */ NanException::~NanException() {} }
864
C++
.cpp
32
22.03125
74
0.657385
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,534,904
AmbdInteraction.cpp
dmorse_pscfpp/src/pscf/iterator/AmbdInteraction.cpp
/* * 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 "AmbdInteraction.h" #include <pscf/math/LuSolver.h> namespace Pscf { using namespace Util; /* * Constructor. */ AmbdInteraction::AmbdInteraction() : nMonomer_(0), isAllocated_(false) {} /* * Destructor. */ AmbdInteraction::~AmbdInteraction() {} /* * Set the number of monomer types and allocate memory. */ void AmbdInteraction::setNMonomer(int nMonomer) { UTIL_CHECK(isAllocated_ == false); UTIL_CHECK(nMonomer_ == 0); UTIL_CHECK(nMonomer > 0); nMonomer_ = nMonomer; chi_.allocate(nMonomer, nMonomer); chiInverse_.allocate(nMonomer, nMonomer); p_.allocate(nMonomer, nMonomer); isAllocated_ = true; } void AmbdInteraction::update(Interaction const & interaction) { // Set nMonomer and allocate memory if not done previously if (!isAllocated_) { setNMonomer(interaction.nMonomer()); } UTIL_CHECK(nMonomer_ == interaction.nMonomer()); // Copy all chi and chiInverse matrix values int i, j; for (i = 0; i < nMonomer_; ++i) { for (j = 0; j < nMonomer_; ++j) { chi_(i, j) = interaction.chi(i, j); chiInverse_(i, j) = interaction.chiInverse(i, j); } } // Compute p and sumChiInverse int k; double sum = 0.0; for (i = 0; i < nMonomer_; ++i) { p_(0,i) = 0.0; for (j = 0; j < nMonomer_; ++j) { p_(0,i) -= chiInverse_(j,i); } sum -= p_(0,i); for (k = 0; k < nMonomer_; ++k) { //row p_(k,i) = p_(0,i); } } for (i = 0; i < nMonomer_; ++i) { //row for (j = 0; j < nMonomer_; ++j) { //coloumn p_(i,j) /= sum; } p_(i,i) += 1.0 ; } sumChiInverse_ = sum; } } // namespace Pscf
2,052
C++
.cpp
74
21.364865
67
0.554707
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,534,905
Mesh.cpp
dmorse_pscfpp/src/pscf/mesh/Mesh.cpp
/* * 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.tpp" #include <util/global.h> namespace Pscf { using namespace Util; template class Mesh<1>; template class Mesh<2>; template class Mesh<3>; }
362
C++
.cpp
15
22
67
0.754386
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