hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
884312e6f13d263ffd954e8726ae9fdc13bb86f3
166,749
cpp
C++
nano/core_test/ledger.cpp
Srayman/nano-node
d5fd87c1f73d8e5edac33e7969c1b3d5a04d90f4
[ "BSD-2-Clause" ]
null
null
null
nano/core_test/ledger.cpp
Srayman/nano-node
d5fd87c1f73d8e5edac33e7969c1b3d5a04d90f4
[ "BSD-2-Clause" ]
null
null
null
nano/core_test/ledger.cpp
Srayman/nano-node
d5fd87c1f73d8e5edac33e7969c1b3d5a04d90f4
[ "BSD-2-Clause" ]
null
null
null
#include <nano/core_test/testutil.hpp> #include <nano/lib/stats.hpp> #include <nano/node/testing.hpp> #include <crypto/cryptopp/filters.h> #include <crypto/cryptopp/randpool.h> #include <gtest/gtest.h> using namespace std::chrono_literals; // Init returns an error if it can't open files at the path TEST (ledger, store_error) { nano::logger_mt logger; nano::mdb_store store (logger, boost::filesystem::path ("///")); ASSERT_TRUE (store.init_error ()); nano::stat stats; nano::ledger ledger (store, stats); } // Ledger can be initialized and returns a basic query for an empty account TEST (ledger, empty) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_TRUE (!store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::account account; auto transaction (store->tx_begin_read ()); auto balance (ledger.account_balance (transaction, account)); ASSERT_TRUE (balance.is_zero ()); } // Genesis account should have the max balance on empty initialization TEST (ledger, genesis_balance) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_TRUE (!store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); auto balance (ledger.account_balance (transaction, nano::genesis_account)); ASSERT_EQ (nano::genesis_amount, balance); auto amount (ledger.amount (transaction, nano::genesis_account)); ASSERT_EQ (nano::genesis_amount, amount); nano::account_info info; ASSERT_FALSE (store->account_get (transaction, nano::genesis_account, info)); // Frontier time should have been updated when genesis balance was added ASSERT_GE (nano::seconds_since_epoch (), info.modified); ASSERT_LT (nano::seconds_since_epoch () - info.modified, 10); // Genesis block should be confirmed by default uint64_t confirmation_height; ASSERT_FALSE (store->confirmation_height_get (transaction, nano::genesis_account, confirmation_height)); ASSERT_EQ (confirmation_height, 1); } // All nodes in the system should agree on the genesis balance TEST (system, system_genesis) { nano::system system (24000, 2); for (auto & i : system.nodes) { auto transaction (i->store.tx_begin_read ()); ASSERT_EQ (nano::genesis_amount, i->ledger.account_balance (transaction, nano::genesis_account)); } } // Create a send block and publish it. TEST (ledger, process_send) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_TRUE (!store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); auto transaction (store->tx_begin_write ()); nano::genesis genesis; store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::account_info info1; ASSERT_FALSE (store->account_get (transaction, nano::test_genesis_key.pub, info1)); nano::keypair key2; nano::send_block send (info1.head, key2.pub, 50, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (info1.head)); nano::block_hash hash1 (send.hash ()); ASSERT_EQ (nano::test_genesis_key.pub, store->frontier_get (transaction, info1.head)); ASSERT_EQ (1, info1.block_count); // This was a valid block, it should progress. auto return1 (ledger.process (transaction, send)); ASSERT_EQ (nano::genesis_amount - 50, ledger.amount (transaction, hash1)); ASSERT_TRUE (store->frontier_get (transaction, info1.head).is_zero ()); ASSERT_EQ (nano::test_genesis_key.pub, store->frontier_get (transaction, hash1)); ASSERT_EQ (nano::process_result::progress, return1.code); ASSERT_EQ (nano::test_genesis_key.pub, return1.account); ASSERT_EQ (nano::genesis_amount - 50, return1.amount.number ()); ASSERT_EQ (50, ledger.account_balance (transaction, nano::test_genesis_key.pub)); ASSERT_EQ (nano::genesis_amount - 50, ledger.account_pending (transaction, key2.pub)); nano::account_info info2; ASSERT_FALSE (store->account_get (transaction, nano::test_genesis_key.pub, info2)); ASSERT_EQ (2, info2.block_count); auto latest6 (store->block_get (transaction, info2.head)); ASSERT_NE (nullptr, latest6); auto latest7 (dynamic_cast<nano::send_block *> (latest6.get ())); ASSERT_NE (nullptr, latest7); ASSERT_EQ (send, *latest7); // Create an open block opening an account accepting the send we just created nano::open_block open (hash1, key2.pub, key2.pub, key2.prv, key2.pub, *pool.generate (key2.pub)); nano::block_hash hash2 (open.hash ()); // This was a valid block, it should progress. auto return2 (ledger.process (transaction, open)); ASSERT_EQ (nano::genesis_amount - 50, ledger.amount (transaction, hash2)); ASSERT_EQ (nano::process_result::progress, return2.code); ASSERT_EQ (key2.pub, return2.account); ASSERT_EQ (nano::genesis_amount - 50, return2.amount.number ()); ASSERT_EQ (key2.pub, store->frontier_get (transaction, hash2)); ASSERT_EQ (nano::genesis_amount - 50, ledger.account_balance (transaction, key2.pub)); ASSERT_EQ (0, ledger.account_pending (transaction, key2.pub)); ASSERT_EQ (50, ledger.weight (nano::test_genesis_key.pub)); ASSERT_EQ (nano::genesis_amount - 50, ledger.weight (key2.pub)); nano::account_info info3; ASSERT_FALSE (store->account_get (transaction, nano::test_genesis_key.pub, info3)); auto latest2 (store->block_get (transaction, info3.head)); ASSERT_NE (nullptr, latest2); auto latest3 (dynamic_cast<nano::send_block *> (latest2.get ())); ASSERT_NE (nullptr, latest3); ASSERT_EQ (send, *latest3); nano::account_info info4; ASSERT_FALSE (store->account_get (transaction, key2.pub, info4)); auto latest4 (store->block_get (transaction, info4.head)); ASSERT_NE (nullptr, latest4); auto latest5 (dynamic_cast<nano::open_block *> (latest4.get ())); ASSERT_NE (nullptr, latest5); ASSERT_EQ (open, *latest5); ASSERT_FALSE (ledger.rollback (transaction, hash2)); ASSERT_TRUE (store->frontier_get (transaction, hash2).is_zero ()); nano::account_info info5; ASSERT_TRUE (ledger.store.account_get (transaction, key2.pub, info5)); nano::pending_info pending1; ASSERT_FALSE (ledger.store.pending_get (transaction, nano::pending_key (key2.pub, hash1), pending1)); ASSERT_EQ (nano::test_genesis_key.pub, pending1.source); ASSERT_EQ (nano::genesis_amount - 50, pending1.amount.number ()); ASSERT_EQ (0, ledger.account_balance (transaction, key2.pub)); ASSERT_EQ (nano::genesis_amount - 50, ledger.account_pending (transaction, key2.pub)); ASSERT_EQ (50, ledger.account_balance (transaction, nano::test_genesis_key.pub)); ASSERT_EQ (50, ledger.weight (nano::test_genesis_key.pub)); ASSERT_EQ (0, ledger.weight (key2.pub)); nano::account_info info6; ASSERT_FALSE (ledger.store.account_get (transaction, nano::test_genesis_key.pub, info6)); ASSERT_EQ (hash1, info6.head); ASSERT_FALSE (ledger.rollback (transaction, info6.head)); ASSERT_EQ (nano::genesis_amount, ledger.weight (nano::test_genesis_key.pub)); ASSERT_EQ (nano::test_genesis_key.pub, store->frontier_get (transaction, info1.head)); ASSERT_TRUE (store->frontier_get (transaction, hash1).is_zero ()); nano::account_info info7; ASSERT_FALSE (ledger.store.account_get (transaction, nano::test_genesis_key.pub, info7)); ASSERT_EQ (1, info7.block_count); ASSERT_EQ (info1.head, info7.head); nano::pending_info pending2; ASSERT_TRUE (ledger.store.pending_get (transaction, nano::pending_key (key2.pub, hash1), pending2)); ASSERT_EQ (nano::genesis_amount, ledger.account_balance (transaction, nano::test_genesis_key.pub)); ASSERT_EQ (0, ledger.account_pending (transaction, key2.pub)); } TEST (ledger, process_receive) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_TRUE (!store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::account_info info1; ASSERT_FALSE (store->account_get (transaction, nano::test_genesis_key.pub, info1)); nano::keypair key2; nano::send_block send (info1.head, key2.pub, 50, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (info1.head)); nano::block_hash hash1 (send.hash ()); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, send).code); nano::keypair key3; nano::open_block open (hash1, key3.pub, key2.pub, key2.prv, key2.pub, *pool.generate (key2.pub)); nano::block_hash hash2 (open.hash ()); auto return1 (ledger.process (transaction, open)); ASSERT_EQ (nano::process_result::progress, return1.code); ASSERT_EQ (key2.pub, return1.account); ASSERT_EQ (nano::genesis_amount - 50, return1.amount.number ()); ASSERT_EQ (nano::genesis_amount - 50, ledger.weight (key3.pub)); nano::send_block send2 (hash1, key2.pub, 25, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (hash1)); nano::block_hash hash3 (send2.hash ()); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, send2).code); nano::receive_block receive (hash2, hash3, key2.prv, key2.pub, *pool.generate (hash2)); auto hash4 (receive.hash ()); ASSERT_EQ (key2.pub, store->frontier_get (transaction, hash2)); auto return2 (ledger.process (transaction, receive)); ASSERT_EQ (25, ledger.amount (transaction, hash4)); ASSERT_TRUE (store->frontier_get (transaction, hash2).is_zero ()); ASSERT_EQ (key2.pub, store->frontier_get (transaction, hash4)); ASSERT_EQ (nano::process_result::progress, return2.code); ASSERT_EQ (key2.pub, return2.account); ASSERT_EQ (25, return2.amount.number ()); ASSERT_EQ (hash4, ledger.latest (transaction, key2.pub)); ASSERT_EQ (25, ledger.account_balance (transaction, nano::test_genesis_key.pub)); ASSERT_EQ (0, ledger.account_pending (transaction, key2.pub)); ASSERT_EQ (nano::genesis_amount - 25, ledger.account_balance (transaction, key2.pub)); ASSERT_EQ (nano::genesis_amount - 25, ledger.weight (key3.pub)); ASSERT_FALSE (ledger.rollback (transaction, hash4)); ASSERT_TRUE (store->block_successor (transaction, hash2).is_zero ()); ASSERT_EQ (key2.pub, store->frontier_get (transaction, hash2)); ASSERT_TRUE (store->frontier_get (transaction, hash4).is_zero ()); ASSERT_EQ (25, ledger.account_balance (transaction, nano::test_genesis_key.pub)); ASSERT_EQ (25, ledger.account_pending (transaction, key2.pub)); ASSERT_EQ (nano::genesis_amount - 50, ledger.account_balance (transaction, key2.pub)); ASSERT_EQ (nano::genesis_amount - 50, ledger.weight (key3.pub)); ASSERT_EQ (hash2, ledger.latest (transaction, key2.pub)); nano::pending_info pending1; ASSERT_FALSE (ledger.store.pending_get (transaction, nano::pending_key (key2.pub, hash3), pending1)); ASSERT_EQ (nano::test_genesis_key.pub, pending1.source); ASSERT_EQ (25, pending1.amount.number ()); } TEST (ledger, rollback_receiver) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_TRUE (!store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::account_info info1; ASSERT_FALSE (store->account_get (transaction, nano::test_genesis_key.pub, info1)); nano::keypair key2; nano::send_block send (info1.head, key2.pub, 50, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (info1.head)); nano::block_hash hash1 (send.hash ()); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, send).code); nano::keypair key3; nano::open_block open (hash1, key3.pub, key2.pub, key2.prv, key2.pub, *pool.generate (key2.pub)); nano::block_hash hash2 (open.hash ()); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, open).code); ASSERT_EQ (hash2, ledger.latest (transaction, key2.pub)); ASSERT_EQ (50, ledger.account_balance (transaction, nano::test_genesis_key.pub)); ASSERT_EQ (nano::genesis_amount - 50, ledger.account_balance (transaction, key2.pub)); ASSERT_EQ (50, ledger.weight (nano::test_genesis_key.pub)); ASSERT_EQ (0, ledger.weight (key2.pub)); ASSERT_EQ (nano::genesis_amount - 50, ledger.weight (key3.pub)); ASSERT_FALSE (ledger.rollback (transaction, hash1)); ASSERT_EQ (nano::genesis_amount, ledger.account_balance (transaction, nano::test_genesis_key.pub)); ASSERT_EQ (0, ledger.account_balance (transaction, key2.pub)); ASSERT_EQ (nano::genesis_amount, ledger.weight (nano::test_genesis_key.pub)); ASSERT_EQ (0, ledger.weight (key2.pub)); ASSERT_EQ (0, ledger.weight (key3.pub)); nano::account_info info2; ASSERT_TRUE (ledger.store.account_get (transaction, key2.pub, info2)); nano::pending_info pending1; ASSERT_TRUE (ledger.store.pending_get (transaction, nano::pending_key (key2.pub, info2.head), pending1)); } TEST (ledger, rollback_representation) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_TRUE (!store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::keypair key5; nano::change_block change1 (genesis.hash (), key5.pub, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, change1).code); nano::keypair key3; nano::change_block change2 (change1.hash (), key3.pub, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (change1.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, change2).code); nano::keypair key2; nano::send_block send1 (change2.hash (), key2.pub, 50, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (change2.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, send1).code); nano::keypair key4; nano::open_block open (send1.hash (), key4.pub, key2.pub, key2.prv, key2.pub, *pool.generate (key2.pub)); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, open).code); nano::send_block send2 (send1.hash (), key2.pub, 1, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (send1.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, send2).code); nano::receive_block receive1 (open.hash (), send2.hash (), key2.prv, key2.pub, *pool.generate (open.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, receive1).code); ASSERT_EQ (1, ledger.weight (key3.pub)); ASSERT_EQ (nano::genesis_amount - 1, ledger.weight (key4.pub)); nano::account_info info1; ASSERT_FALSE (store->account_get (transaction, key2.pub, info1)); ASSERT_EQ (key4.pub, info1.representative); ASSERT_FALSE (ledger.rollback (transaction, receive1.hash ())); nano::account_info info2; ASSERT_FALSE (store->account_get (transaction, key2.pub, info2)); ASSERT_EQ (key4.pub, info2.representative); ASSERT_EQ (0, ledger.weight (key2.pub)); ASSERT_EQ (nano::genesis_amount - 50, ledger.weight (key4.pub)); ASSERT_FALSE (ledger.rollback (transaction, open.hash ())); ASSERT_EQ (1, ledger.weight (key3.pub)); ASSERT_EQ (0, ledger.weight (key4.pub)); ledger.rollback (transaction, send1.hash ()); ASSERT_EQ (nano::genesis_amount, ledger.weight (key3.pub)); nano::account_info info3; ASSERT_FALSE (store->account_get (transaction, nano::test_genesis_key.pub, info3)); ASSERT_EQ (key3.pub, info3.representative); ASSERT_FALSE (ledger.rollback (transaction, change2.hash ())); nano::account_info info4; ASSERT_FALSE (store->account_get (transaction, nano::test_genesis_key.pub, info4)); ASSERT_EQ (key5.pub, info4.representative); ASSERT_EQ (nano::genesis_amount, ledger.weight (key5.pub)); ASSERT_EQ (0, ledger.weight (key3.pub)); } TEST (ledger, receive_rollback) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_TRUE (!store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::send_block send (genesis.hash (), nano::test_genesis_key.pub, nano::genesis_amount - nano::Gxrb_ratio, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, send).code); nano::receive_block receive (send.hash (), send.hash (), nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (send.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, receive).code); ASSERT_FALSE (ledger.rollback (transaction, receive.hash ())); } TEST (ledger, process_duplicate) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_TRUE (!store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::account_info info1; ASSERT_FALSE (store->account_get (transaction, nano::test_genesis_key.pub, info1)); nano::keypair key2; nano::send_block send (info1.head, key2.pub, 50, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (info1.head)); nano::block_hash hash1 (send.hash ()); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, send).code); ASSERT_EQ (nano::process_result::old, ledger.process (transaction, send).code); nano::open_block open (hash1, 1, key2.pub, key2.prv, key2.pub, *pool.generate (key2.pub)); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, open).code); ASSERT_EQ (nano::process_result::old, ledger.process (transaction, open).code); } TEST (ledger, representative_genesis) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_TRUE (!store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); auto latest (ledger.latest (transaction, nano::test_genesis_key.pub)); ASSERT_FALSE (latest.is_zero ()); ASSERT_EQ (genesis.open->hash (), ledger.representative (transaction, latest)); } TEST (ledger, weight) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_TRUE (!store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); ASSERT_EQ (nano::genesis_amount, ledger.weight (nano::genesis_account)); } TEST (ledger, representative_change) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_TRUE (!store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::keypair key2; nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); ASSERT_EQ (nano::genesis_amount, ledger.weight (nano::test_genesis_key.pub)); ASSERT_EQ (0, ledger.weight (key2.pub)); nano::account_info info1; ASSERT_FALSE (store->account_get (transaction, nano::test_genesis_key.pub, info1)); nano::change_block block (info1.head, key2.pub, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (info1.head)); ASSERT_EQ (nano::test_genesis_key.pub, store->frontier_get (transaction, info1.head)); auto return1 (ledger.process (transaction, block)); ASSERT_EQ (0, ledger.amount (transaction, block.hash ())); ASSERT_TRUE (store->frontier_get (transaction, info1.head).is_zero ()); ASSERT_EQ (nano::test_genesis_key.pub, store->frontier_get (transaction, block.hash ())); ASSERT_EQ (nano::process_result::progress, return1.code); ASSERT_EQ (nano::test_genesis_key.pub, return1.account); ASSERT_EQ (0, ledger.weight (nano::test_genesis_key.pub)); ASSERT_EQ (nano::genesis_amount, ledger.weight (key2.pub)); nano::account_info info2; ASSERT_FALSE (store->account_get (transaction, nano::test_genesis_key.pub, info2)); ASSERT_EQ (block.hash (), info2.head); ASSERT_FALSE (ledger.rollback (transaction, info2.head)); ASSERT_EQ (nano::test_genesis_key.pub, store->frontier_get (transaction, info1.head)); ASSERT_TRUE (store->frontier_get (transaction, block.hash ()).is_zero ()); nano::account_info info3; ASSERT_FALSE (store->account_get (transaction, nano::test_genesis_key.pub, info3)); ASSERT_EQ (info1.head, info3.head); ASSERT_EQ (nano::genesis_amount, ledger.weight (nano::test_genesis_key.pub)); ASSERT_EQ (0, ledger.weight (key2.pub)); } TEST (ledger, send_fork) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_TRUE (!store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::keypair key2; nano::keypair key3; nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::account_info info1; ASSERT_FALSE (store->account_get (transaction, nano::test_genesis_key.pub, info1)); nano::send_block block (info1.head, key2.pub, 100, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (info1.head)); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, block).code); nano::send_block block2 (info1.head, key3.pub, 0, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (info1.head)); ASSERT_EQ (nano::process_result::fork, ledger.process (transaction, block2).code); } TEST (ledger, receive_fork) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_TRUE (!store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::keypair key2; nano::keypair key3; nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::account_info info1; ASSERT_FALSE (store->account_get (transaction, nano::test_genesis_key.pub, info1)); nano::send_block block (info1.head, key2.pub, 100, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (info1.head)); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, block).code); nano::open_block block2 (block.hash (), key2.pub, key2.pub, key2.prv, key2.pub, *pool.generate (key2.pub)); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, block2).code); nano::change_block block3 (block2.hash (), key3.pub, key2.prv, key2.pub, *pool.generate (block2.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, block3).code); nano::send_block block4 (block.hash (), key2.pub, 0, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (block.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, block4).code); nano::receive_block block5 (block2.hash (), block4.hash (), key2.prv, key2.pub, *pool.generate (block2.hash ())); ASSERT_EQ (nano::process_result::fork, ledger.process (transaction, block5).code); } TEST (ledger, open_fork) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_TRUE (!store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::keypair key2; nano::keypair key3; nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::account_info info1; ASSERT_FALSE (store->account_get (transaction, nano::test_genesis_key.pub, info1)); nano::send_block block (info1.head, key2.pub, 100, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (info1.head)); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, block).code); nano::open_block block2 (block.hash (), key2.pub, key2.pub, key2.prv, key2.pub, *pool.generate (key2.pub)); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, block2).code); nano::open_block block3 (block.hash (), key3.pub, key2.pub, key2.prv, key2.pub, *pool.generate (key2.pub)); ASSERT_EQ (nano::process_result::fork, ledger.process (transaction, block3).code); } TEST (system, DISABLED_generate_send_existing) { nano::system system (24000, 1); nano::thread_runner runner (system.io_ctx, system.nodes[0]->config.io_threads); system.wallet (0)->insert_adhoc (nano::test_genesis_key.prv); nano::keypair stake_preserver; auto send_block (system.wallet (0)->send_action (nano::genesis_account, stake_preserver.pub, nano::genesis_amount / 3 * 2, true)); nano::account_info info1; { auto transaction (system.nodes[0]->store.tx_begin_read ()); ASSERT_FALSE (system.nodes[0]->store.account_get (transaction, nano::test_genesis_key.pub, info1)); } std::vector<nano::account> accounts; accounts.push_back (nano::test_genesis_key.pub); system.generate_send_existing (*system.nodes[0], accounts); // Have stake_preserver receive funds after generate_send_existing so it isn't chosen as the destination { auto transaction (system.nodes[0]->store.tx_begin_write ()); auto open_block (std::make_shared<nano::open_block> (send_block->hash (), nano::genesis_account, stake_preserver.pub, stake_preserver.prv, stake_preserver.pub, 0)); system.nodes[0]->work_generate_blocking (*open_block); ASSERT_EQ (nano::process_result::progress, system.nodes[0]->ledger.process (transaction, *open_block).code); } ASSERT_GT (system.nodes[0]->balance (stake_preserver.pub), system.nodes[0]->balance (nano::genesis_account)); nano::account_info info2; { auto transaction (system.nodes[0]->store.tx_begin_read ()); ASSERT_FALSE (system.nodes[0]->store.account_get (transaction, nano::test_genesis_key.pub, info2)); } ASSERT_NE (info1.head, info2.head); system.deadline_set (15s); while (info2.block_count < info1.block_count + 2) { ASSERT_NO_ERROR (system.poll ()); auto transaction (system.nodes[0]->store.tx_begin_read ()); ASSERT_FALSE (system.nodes[0]->store.account_get (transaction, nano::test_genesis_key.pub, info2)); } ASSERT_EQ (info1.block_count + 2, info2.block_count); ASSERT_EQ (info2.balance, nano::genesis_amount / 3); { auto transaction (system.nodes[0]->store.tx_begin_read ()); ASSERT_NE (system.nodes[0]->ledger.amount (transaction, info2.head), 0); } system.stop (); runner.join (); } TEST (system, generate_send_new) { nano::system system (24000, 1); nano::thread_runner runner (system.io_ctx, system.nodes[0]->config.io_threads); system.wallet (0)->insert_adhoc (nano::test_genesis_key.prv); { auto transaction (system.nodes[0]->store.tx_begin_read ()); auto iterator1 (system.nodes[0]->store.latest_begin (transaction)); ASSERT_NE (system.nodes[0]->store.latest_end (), iterator1); ++iterator1; ASSERT_EQ (system.nodes[0]->store.latest_end (), iterator1); } nano::keypair stake_preserver; auto send_block (system.wallet (0)->send_action (nano::genesis_account, stake_preserver.pub, nano::genesis_amount / 3 * 2, true)); { auto transaction (system.nodes[0]->store.tx_begin_write ()); auto open_block (std::make_shared<nano::open_block> (send_block->hash (), nano::genesis_account, stake_preserver.pub, stake_preserver.prv, stake_preserver.pub, 0)); system.nodes[0]->work_generate_blocking (*open_block); ASSERT_EQ (nano::process_result::progress, system.nodes[0]->ledger.process (transaction, *open_block).code); } ASSERT_GT (system.nodes[0]->balance (stake_preserver.pub), system.nodes[0]->balance (nano::genesis_account)); std::vector<nano::account> accounts; accounts.push_back (nano::test_genesis_key.pub); system.generate_send_new (*system.nodes[0], accounts); nano::account new_account (0); { auto transaction (system.nodes[0]->wallets.tx_begin_read ()); auto iterator2 (system.wallet (0)->store.begin (transaction)); if (iterator2->first != nano::test_genesis_key.pub) { new_account = iterator2->first; } ++iterator2; ASSERT_NE (system.wallet (0)->store.end (), iterator2); if (iterator2->first != nano::test_genesis_key.pub) { new_account = iterator2->first; } ++iterator2; ASSERT_EQ (system.wallet (0)->store.end (), iterator2); ASSERT_FALSE (new_account.is_zero ()); } system.deadline_set (10s); while (system.nodes[0]->balance (new_account) == 0) { ASSERT_NO_ERROR (system.poll ()); } system.stop (); runner.join (); } TEST (ledger, representation_changes) { nano::keypair key1; nano::rep_weights rep_weights; ASSERT_EQ (0, rep_weights.representation_get (key1.pub)); rep_weights.representation_put (key1.pub, 1); ASSERT_EQ (1, rep_weights.representation_get (key1.pub)); rep_weights.representation_put (key1.pub, 2); ASSERT_EQ (2, rep_weights.representation_get (key1.pub)); } TEST (ledger, representation) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_TRUE (!store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); auto & rep_weights = ledger.rep_weights; nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); ASSERT_EQ (nano::genesis_amount, rep_weights.representation_get (nano::test_genesis_key.pub)); nano::keypair key2; nano::send_block block1 (genesis.hash (), key2.pub, nano::genesis_amount - 100, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, block1).code); ASSERT_EQ (nano::genesis_amount - 100, rep_weights.representation_get (nano::test_genesis_key.pub)); nano::keypair key3; nano::open_block block2 (block1.hash (), key3.pub, key2.pub, key2.prv, key2.pub, *pool.generate (key2.pub)); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, block2).code); ASSERT_EQ (nano::genesis_amount - 100, rep_weights.representation_get (nano::test_genesis_key.pub)); ASSERT_EQ (0, rep_weights.representation_get (key2.pub)); ASSERT_EQ (100, rep_weights.representation_get (key3.pub)); nano::send_block block3 (block1.hash (), key2.pub, nano::genesis_amount - 200, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (block1.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, block3).code); ASSERT_EQ (nano::genesis_amount - 200, rep_weights.representation_get (nano::test_genesis_key.pub)); ASSERT_EQ (0, rep_weights.representation_get (key2.pub)); ASSERT_EQ (100, rep_weights.representation_get (key3.pub)); nano::receive_block block4 (block2.hash (), block3.hash (), key2.prv, key2.pub, *pool.generate (block2.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, block4).code); ASSERT_EQ (nano::genesis_amount - 200, rep_weights.representation_get (nano::test_genesis_key.pub)); ASSERT_EQ (0, rep_weights.representation_get (key2.pub)); ASSERT_EQ (200, rep_weights.representation_get (key3.pub)); nano::keypair key4; nano::change_block block5 (block4.hash (), key4.pub, key2.prv, key2.pub, *pool.generate (block4.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, block5).code); ASSERT_EQ (nano::genesis_amount - 200, rep_weights.representation_get (nano::test_genesis_key.pub)); ASSERT_EQ (0, rep_weights.representation_get (key2.pub)); ASSERT_EQ (0, rep_weights.representation_get (key3.pub)); ASSERT_EQ (200, rep_weights.representation_get (key4.pub)); nano::keypair key5; nano::send_block block6 (block5.hash (), key5.pub, 100, key2.prv, key2.pub, *pool.generate (block5.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, block6).code); ASSERT_EQ (nano::genesis_amount - 200, rep_weights.representation_get (nano::test_genesis_key.pub)); ASSERT_EQ (0, rep_weights.representation_get (key2.pub)); ASSERT_EQ (0, rep_weights.representation_get (key3.pub)); ASSERT_EQ (100, rep_weights.representation_get (key4.pub)); ASSERT_EQ (0, rep_weights.representation_get (key5.pub)); nano::keypair key6; nano::open_block block7 (block6.hash (), key6.pub, key5.pub, key5.prv, key5.pub, *pool.generate (key5.pub)); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, block7).code); ASSERT_EQ (nano::genesis_amount - 200, rep_weights.representation_get (nano::test_genesis_key.pub)); ASSERT_EQ (0, rep_weights.representation_get (key2.pub)); ASSERT_EQ (0, rep_weights.representation_get (key3.pub)); ASSERT_EQ (100, rep_weights.representation_get (key4.pub)); ASSERT_EQ (0, rep_weights.representation_get (key5.pub)); ASSERT_EQ (100, rep_weights.representation_get (key6.pub)); nano::send_block block8 (block6.hash (), key5.pub, 0, key2.prv, key2.pub, *pool.generate (block6.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, block8).code); ASSERT_EQ (nano::genesis_amount - 200, rep_weights.representation_get (nano::test_genesis_key.pub)); ASSERT_EQ (0, rep_weights.representation_get (key2.pub)); ASSERT_EQ (0, rep_weights.representation_get (key3.pub)); ASSERT_EQ (0, rep_weights.representation_get (key4.pub)); ASSERT_EQ (0, rep_weights.representation_get (key5.pub)); ASSERT_EQ (100, rep_weights.representation_get (key6.pub)); nano::receive_block block9 (block7.hash (), block8.hash (), key5.prv, key5.pub, *pool.generate (block7.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, block9).code); ASSERT_EQ (nano::genesis_amount - 200, rep_weights.representation_get (nano::test_genesis_key.pub)); ASSERT_EQ (0, rep_weights.representation_get (key2.pub)); ASSERT_EQ (0, rep_weights.representation_get (key3.pub)); ASSERT_EQ (0, rep_weights.representation_get (key4.pub)); ASSERT_EQ (0, rep_weights.representation_get (key5.pub)); ASSERT_EQ (200, rep_weights.representation_get (key6.pub)); } TEST (ledger, double_open) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_TRUE (!store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::keypair key2; nano::send_block send1 (genesis.hash (), key2.pub, 1, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, send1).code); nano::open_block open1 (send1.hash (), key2.pub, key2.pub, key2.prv, key2.pub, *pool.generate (key2.pub)); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, open1).code); nano::open_block open2 (send1.hash (), nano::test_genesis_key.pub, key2.pub, key2.prv, key2.pub, *pool.generate (key2.pub)); ASSERT_EQ (nano::process_result::fork, ledger.process (transaction, open2).code); } TEST (ledger, double_receive) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_TRUE (!store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::keypair key2; nano::send_block send1 (genesis.hash (), key2.pub, 1, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, send1).code); nano::open_block open1 (send1.hash (), key2.pub, key2.pub, key2.prv, key2.pub, *pool.generate (key2.pub)); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, open1).code); nano::receive_block receive1 (open1.hash (), send1.hash (), key2.prv, key2.pub, *pool.generate (open1.hash ())); ASSERT_EQ (nano::process_result::unreceivable, ledger.process (transaction, receive1).code); } TEST (votes, check_signature) { nano::system system; nano::node_config node_config (24000, system.logging); node_config.online_weight_minimum = std::numeric_limits<nano::uint128_t>::max (); auto & node1 = *system.add_node (node_config); nano::genesis genesis; nano::keypair key1; auto send1 (std::make_shared<nano::send_block> (genesis.hash (), key1.pub, nano::genesis_amount - 100, nano::test_genesis_key.prv, nano::test_genesis_key.pub, 0)); node1.work_generate_blocking (*send1); { auto transaction (node1.store.tx_begin_write ()); ASSERT_EQ (nano::process_result::progress, node1.ledger.process (transaction, *send1).code); } node1.active.start (send1); nano::lock_guard<std::mutex> lock (node1.active.mutex); auto votes1 (node1.active.roots.find (send1->qualified_root ())->election); ASSERT_EQ (1, votes1->last_votes.size ()); auto vote1 (std::make_shared<nano::vote> (nano::test_genesis_key.pub, nano::test_genesis_key.prv, 1, send1)); vote1->signature.bytes[0] ^= 1; auto transaction (node1.store.tx_begin_read ()); ASSERT_EQ (nano::vote_code::invalid, node1.vote_processor.vote_blocking (transaction, vote1, std::make_shared<nano::transport::channel_udp> (node1.network.udp_channels, nano::endpoint (boost::asio::ip::address_v6 (), 0), node1.network_params.protocol.protocol_version))); vote1->signature.bytes[0] ^= 1; ASSERT_EQ (nano::vote_code::vote, node1.vote_processor.vote_blocking (transaction, vote1, std::make_shared<nano::transport::channel_udp> (node1.network.udp_channels, nano::endpoint (boost::asio::ip::address_v6 (), 0), node1.network_params.protocol.protocol_version))); ASSERT_EQ (nano::vote_code::replay, node1.vote_processor.vote_blocking (transaction, vote1, std::make_shared<nano::transport::channel_udp> (node1.network.udp_channels, nano::endpoint (boost::asio::ip::address_v6 (), 0), node1.network_params.protocol.protocol_version))); } TEST (votes, add_one) { nano::system system (24000, 1); auto & node1 (*system.nodes[0]); nano::genesis genesis; nano::keypair key1; auto send1 (std::make_shared<nano::send_block> (genesis.hash (), key1.pub, nano::genesis_amount - 100, nano::test_genesis_key.prv, nano::test_genesis_key.pub, 0)); node1.work_generate_blocking (*send1); auto transaction (node1.store.tx_begin_write ()); ASSERT_EQ (nano::process_result::progress, node1.ledger.process (transaction, *send1).code); node1.active.start (send1); nano::unique_lock<std::mutex> lock (node1.active.mutex); auto votes1 (node1.active.roots.find (send1->qualified_root ())->election); ASSERT_EQ (1, votes1->last_votes.size ()); lock.unlock (); auto vote1 (std::make_shared<nano::vote> (nano::test_genesis_key.pub, nano::test_genesis_key.prv, 1, send1)); ASSERT_FALSE (node1.active.vote (vote1)); auto vote2 (std::make_shared<nano::vote> (nano::test_genesis_key.pub, nano::test_genesis_key.prv, 2, send1)); ASSERT_FALSE (node1.active.vote (vote2)); lock.lock (); ASSERT_EQ (2, votes1->last_votes.size ()); auto existing1 (votes1->last_votes.find (nano::test_genesis_key.pub)); ASSERT_NE (votes1->last_votes.end (), existing1); ASSERT_EQ (send1->hash (), existing1->second.hash); auto winner (*votes1->tally ().begin ()); ASSERT_EQ (*send1, *winner.second); ASSERT_EQ (nano::genesis_amount - 100, winner.first); } TEST (votes, add_two) { nano::system system (24000, 1); auto & node1 (*system.nodes[0]); nano::genesis genesis; nano::keypair key1; auto send1 (std::make_shared<nano::send_block> (genesis.hash (), key1.pub, nano::genesis_amount - 100, nano::test_genesis_key.prv, nano::test_genesis_key.pub, 0)); node1.work_generate_blocking (*send1); auto transaction (node1.store.tx_begin_write ()); ASSERT_EQ (nano::process_result::progress, node1.ledger.process (transaction, *send1).code); node1.active.start (send1); nano::unique_lock<std::mutex> lock (node1.active.mutex); auto votes1 (node1.active.roots.find (send1->qualified_root ())->election); lock.unlock (); nano::keypair key2; auto send2 (std::make_shared<nano::send_block> (genesis.hash (), key2.pub, 0, nano::test_genesis_key.prv, nano::test_genesis_key.pub, 0)); auto vote2 (std::make_shared<nano::vote> (key2.pub, key2.prv, 1, send2)); ASSERT_FALSE (node1.active.vote (vote2)); auto vote1 (std::make_shared<nano::vote> (nano::test_genesis_key.pub, nano::test_genesis_key.prv, 1, send1)); ASSERT_FALSE (node1.active.vote (vote1)); lock.lock (); ASSERT_EQ (3, votes1->last_votes.size ()); ASSERT_NE (votes1->last_votes.end (), votes1->last_votes.find (nano::test_genesis_key.pub)); ASSERT_EQ (send1->hash (), votes1->last_votes[nano::test_genesis_key.pub].hash); ASSERT_NE (votes1->last_votes.end (), votes1->last_votes.find (key2.pub)); ASSERT_EQ (send2->hash (), votes1->last_votes[key2.pub].hash); auto winner (*votes1->tally ().begin ()); ASSERT_EQ (*send1, *winner.second); } // Higher sequence numbers change the vote TEST (votes, add_existing) { nano::system system; nano::node_config node_config (24000, system.logging); node_config.online_weight_minimum = std::numeric_limits<nano::uint128_t>::max (); node_config.frontiers_confirmation = nano::frontiers_confirmation_mode::disabled; auto & node1 = *system.add_node (node_config); nano::genesis genesis; nano::keypair key1; auto send1 (std::make_shared<nano::send_block> (genesis.hash (), key1.pub, nano::genesis_amount - nano::Gxrb_ratio, nano::test_genesis_key.prv, nano::test_genesis_key.pub, 0)); node1.work_generate_blocking (*send1); { auto transaction (node1.store.tx_begin_write ()); ASSERT_EQ (nano::process_result::progress, node1.ledger.process (transaction, *send1).code); } node1.active.start (send1); auto vote1 (std::make_shared<nano::vote> (nano::test_genesis_key.pub, nano::test_genesis_key.prv, 1, send1)); ASSERT_FALSE (node1.active.vote (vote1)); // Block is already processed from vote ASSERT_TRUE (node1.active.publish (send1)); nano::unique_lock<std::mutex> lock (node1.active.mutex); auto votes1 (node1.active.roots.find (send1->qualified_root ())->election); ASSERT_EQ (1, votes1->last_votes[nano::test_genesis_key.pub].sequence); nano::keypair key2; auto send2 (std::make_shared<nano::send_block> (genesis.hash (), key2.pub, nano::genesis_amount - nano::Gxrb_ratio, nano::test_genesis_key.prv, nano::test_genesis_key.pub, 0)); node1.work_generate_blocking (*send2); auto vote2 (std::make_shared<nano::vote> (nano::test_genesis_key.pub, nano::test_genesis_key.prv, 2, send2)); // Pretend we've waited the timeout votes1->last_votes[nano::test_genesis_key.pub].time = std::chrono::steady_clock::now () - std::chrono::seconds (20); lock.unlock (); ASSERT_FALSE (node1.active.vote (vote2)); ASSERT_FALSE (node1.active.publish (send2)); lock.lock (); ASSERT_EQ (2, votes1->last_votes[nano::test_genesis_key.pub].sequence); // Also resend the old vote, and see if we respect the sequence number votes1->last_votes[nano::test_genesis_key.pub].time = std::chrono::steady_clock::now () - std::chrono::seconds (20); lock.unlock (); ASSERT_TRUE (node1.active.vote (vote1)); lock.lock (); ASSERT_EQ (2, votes1->last_votes[nano::test_genesis_key.pub].sequence); ASSERT_EQ (2, votes1->last_votes.size ()); ASSERT_NE (votes1->last_votes.end (), votes1->last_votes.find (nano::test_genesis_key.pub)); ASSERT_EQ (send2->hash (), votes1->last_votes[nano::test_genesis_key.pub].hash); { auto transaction (node1.store.tx_begin_read ()); auto winner (*votes1->tally ().begin ()); ASSERT_EQ (*send2, *winner.second); } } // Lower sequence numbers are ignored TEST (votes, add_old) { nano::system system (24000, 1); auto & node1 (*system.nodes[0]); nano::genesis genesis; nano::keypair key1; auto send1 (std::make_shared<nano::send_block> (genesis.hash (), key1.pub, 0, nano::test_genesis_key.prv, nano::test_genesis_key.pub, 0)); node1.work_generate_blocking (*send1); auto transaction (node1.store.tx_begin_write ()); ASSERT_EQ (nano::process_result::progress, node1.ledger.process (transaction, *send1).code); node1.active.start (send1); auto vote1 (std::make_shared<nano::vote> (nano::test_genesis_key.pub, nano::test_genesis_key.prv, 2, send1)); nano::lock_guard<std::mutex> lock (node1.active.mutex); auto votes1 (node1.active.roots.find (send1->qualified_root ())->election); auto channel (std::make_shared<nano::transport::channel_udp> (node1.network.udp_channels, node1.network.endpoint (), node1.network_params.protocol.protocol_version)); node1.vote_processor.vote_blocking (transaction, vote1, channel); nano::keypair key2; auto send2 (std::make_shared<nano::send_block> (genesis.hash (), key2.pub, 0, nano::test_genesis_key.prv, nano::test_genesis_key.pub, 0)); node1.work_generate_blocking (*send2); auto vote2 (std::make_shared<nano::vote> (nano::test_genesis_key.pub, nano::test_genesis_key.prv, 1, send2)); votes1->last_votes[nano::test_genesis_key.pub].time = std::chrono::steady_clock::now () - std::chrono::seconds (20); node1.vote_processor.vote_blocking (transaction, vote2, channel); ASSERT_EQ (2, votes1->last_votes.size ()); ASSERT_NE (votes1->last_votes.end (), votes1->last_votes.find (nano::test_genesis_key.pub)); ASSERT_EQ (send1->hash (), votes1->last_votes[nano::test_genesis_key.pub].hash); auto winner (*votes1->tally ().begin ()); ASSERT_EQ (*send1, *winner.second); } // Lower sequence numbers are accepted for different accounts TEST (votes, add_old_different_account) { nano::system system (24000, 1); auto & node1 (*system.nodes[0]); nano::genesis genesis; nano::keypair key1; auto send1 (std::make_shared<nano::send_block> (genesis.hash (), key1.pub, 0, nano::test_genesis_key.prv, nano::test_genesis_key.pub, 0)); node1.work_generate_blocking (*send1); auto send2 (std::make_shared<nano::send_block> (send1->hash (), key1.pub, 0, nano::test_genesis_key.prv, nano::test_genesis_key.pub, 0)); node1.work_generate_blocking (*send2); auto transaction (node1.store.tx_begin_write ()); ASSERT_EQ (nano::process_result::progress, node1.ledger.process (transaction, *send1).code); ASSERT_EQ (nano::process_result::progress, node1.ledger.process (transaction, *send2).code); node1.active.start (send1); node1.active.start (send2); nano::unique_lock<std::mutex> lock (node1.active.mutex); auto votes1 (node1.active.roots.find (send1->qualified_root ())->election); auto votes2 (node1.active.roots.find (send2->qualified_root ())->election); ASSERT_EQ (1, votes1->last_votes.size ()); ASSERT_EQ (1, votes2->last_votes.size ()); auto vote1 (std::make_shared<nano::vote> (nano::test_genesis_key.pub, nano::test_genesis_key.prv, 2, send1)); auto channel (std::make_shared<nano::transport::channel_udp> (node1.network.udp_channels, node1.network.endpoint (), node1.network_params.protocol.protocol_version)); auto vote_result1 (node1.vote_processor.vote_blocking (transaction, vote1, channel)); ASSERT_EQ (nano::vote_code::vote, vote_result1); ASSERT_EQ (2, votes1->last_votes.size ()); ASSERT_EQ (1, votes2->last_votes.size ()); auto vote2 (std::make_shared<nano::vote> (nano::test_genesis_key.pub, nano::test_genesis_key.prv, 1, send2)); auto vote_result2 (node1.vote_processor.vote_blocking (transaction, vote2, channel)); ASSERT_EQ (nano::vote_code::vote, vote_result2); ASSERT_EQ (2, votes1->last_votes.size ()); ASSERT_EQ (2, votes2->last_votes.size ()); ASSERT_NE (votes1->last_votes.end (), votes1->last_votes.find (nano::test_genesis_key.pub)); ASSERT_NE (votes2->last_votes.end (), votes2->last_votes.find (nano::test_genesis_key.pub)); ASSERT_EQ (send1->hash (), votes1->last_votes[nano::test_genesis_key.pub].hash); ASSERT_EQ (send2->hash (), votes2->last_votes[nano::test_genesis_key.pub].hash); auto winner1 (*votes1->tally ().begin ()); ASSERT_EQ (*send1, *winner1.second); auto winner2 (*votes2->tally ().begin ()); ASSERT_EQ (*send2, *winner2.second); } // The voting cooldown is respected TEST (votes, add_cooldown) { nano::system system (24000, 1); auto & node1 (*system.nodes[0]); nano::genesis genesis; nano::keypair key1; auto send1 (std::make_shared<nano::send_block> (genesis.hash (), key1.pub, 0, nano::test_genesis_key.prv, nano::test_genesis_key.pub, 0)); node1.work_generate_blocking (*send1); auto transaction (node1.store.tx_begin_write ()); ASSERT_EQ (nano::process_result::progress, node1.ledger.process (transaction, *send1).code); node1.active.start (send1); nano::unique_lock<std::mutex> lock (node1.active.mutex); auto votes1 (node1.active.roots.find (send1->qualified_root ())->election); auto vote1 (std::make_shared<nano::vote> (nano::test_genesis_key.pub, nano::test_genesis_key.prv, 1, send1)); auto channel (std::make_shared<nano::transport::channel_udp> (node1.network.udp_channels, node1.network.endpoint (), node1.network_params.protocol.protocol_version)); node1.vote_processor.vote_blocking (transaction, vote1, channel); nano::keypair key2; auto send2 (std::make_shared<nano::send_block> (genesis.hash (), key2.pub, 0, nano::test_genesis_key.prv, nano::test_genesis_key.pub, 0)); node1.work_generate_blocking (*send2); auto vote2 (std::make_shared<nano::vote> (nano::test_genesis_key.pub, nano::test_genesis_key.prv, 2, send2)); node1.vote_processor.vote_blocking (transaction, vote2, channel); ASSERT_EQ (2, votes1->last_votes.size ()); ASSERT_NE (votes1->last_votes.end (), votes1->last_votes.find (nano::test_genesis_key.pub)); ASSERT_EQ (send1->hash (), votes1->last_votes[nano::test_genesis_key.pub].hash); auto winner (*votes1->tally ().begin ()); ASSERT_EQ (*send1, *winner.second); } // Query for block successor TEST (ledger, successor) { nano::system system (24000, 1); nano::keypair key1; nano::genesis genesis; nano::send_block send1 (genesis.hash (), key1.pub, 0, nano::test_genesis_key.prv, nano::test_genesis_key.pub, 0); system.nodes[0]->work_generate_blocking (send1); auto transaction (system.nodes[0]->store.tx_begin_write ()); ASSERT_EQ (nano::process_result::progress, system.nodes[0]->ledger.process (transaction, send1).code); ASSERT_EQ (send1, *system.nodes[0]->ledger.successor (transaction, nano::qualified_root (genesis.hash (), nano::root (0)))); ASSERT_EQ (*genesis.open, *system.nodes[0]->ledger.successor (transaction, genesis.open->qualified_root ())); ASSERT_EQ (nullptr, system.nodes[0]->ledger.successor (transaction, nano::qualified_root (0))); } TEST (ledger, fail_change_old) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_FALSE (store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::keypair key1; nano::change_block block (genesis.hash (), key1.pub, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); auto result1 (ledger.process (transaction, block)); ASSERT_EQ (nano::process_result::progress, result1.code); auto result2 (ledger.process (transaction, block)); ASSERT_EQ (nano::process_result::old, result2.code); } TEST (ledger, fail_change_gap_previous) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_FALSE (store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::keypair key1; nano::change_block block (1, key1.pub, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (nano::root (1))); auto result1 (ledger.process (transaction, block)); ASSERT_EQ (nano::process_result::gap_previous, result1.code); } TEST (ledger, fail_change_bad_signature) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_FALSE (store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::keypair key1; nano::change_block block (genesis.hash (), key1.pub, nano::keypair ().prv, 0, *pool.generate (genesis.hash ())); auto result1 (ledger.process (transaction, block)); ASSERT_EQ (nano::process_result::bad_signature, result1.code); } TEST (ledger, fail_change_fork) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_FALSE (store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::keypair key1; nano::change_block block1 (genesis.hash (), key1.pub, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); auto result1 (ledger.process (transaction, block1)); ASSERT_EQ (nano::process_result::progress, result1.code); nano::keypair key2; nano::change_block block2 (genesis.hash (), key2.pub, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); auto result2 (ledger.process (transaction, block2)); ASSERT_EQ (nano::process_result::fork, result2.code); } TEST (ledger, fail_send_old) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_FALSE (store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::keypair key1; nano::send_block block (genesis.hash (), key1.pub, 1, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); auto result1 (ledger.process (transaction, block)); ASSERT_EQ (nano::process_result::progress, result1.code); auto result2 (ledger.process (transaction, block)); ASSERT_EQ (nano::process_result::old, result2.code); } TEST (ledger, fail_send_gap_previous) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_FALSE (store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::keypair key1; nano::send_block block (1, key1.pub, 1, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (nano::root (1))); auto result1 (ledger.process (transaction, block)); ASSERT_EQ (nano::process_result::gap_previous, result1.code); } TEST (ledger, fail_send_bad_signature) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_FALSE (store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::keypair key1; nano::send_block block (genesis.hash (), key1.pub, 1, nano::keypair ().prv, 0, *pool.generate (genesis.hash ())); auto result1 (ledger.process (transaction, block)); ASSERT_EQ (nano::process_result::bad_signature, result1.code); } TEST (ledger, fail_send_negative_spend) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_FALSE (store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::keypair key1; nano::send_block block1 (genesis.hash (), key1.pub, 1, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, block1).code); nano::keypair key2; nano::send_block block2 (block1.hash (), key2.pub, 2, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (block1.hash ())); ASSERT_EQ (nano::process_result::negative_spend, ledger.process (transaction, block2).code); } TEST (ledger, fail_send_fork) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_FALSE (store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::keypair key1; nano::send_block block1 (genesis.hash (), key1.pub, 1, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, block1).code); nano::keypair key2; nano::send_block block2 (genesis.hash (), key2.pub, 1, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); ASSERT_EQ (nano::process_result::fork, ledger.process (transaction, block2).code); } TEST (ledger, fail_open_old) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_FALSE (store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::keypair key1; nano::send_block block1 (genesis.hash (), key1.pub, 1, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, block1).code); nano::open_block block2 (block1.hash (), 1, key1.pub, key1.prv, key1.pub, *pool.generate (key1.pub)); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, block2).code); ASSERT_EQ (nano::process_result::old, ledger.process (transaction, block2).code); } TEST (ledger, fail_open_gap_source) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_FALSE (store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::keypair key1; nano::open_block block2 (1, 1, key1.pub, key1.prv, key1.pub, *pool.generate (key1.pub)); auto result2 (ledger.process (transaction, block2)); ASSERT_EQ (nano::process_result::gap_source, result2.code); } TEST (ledger, fail_open_bad_signature) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_FALSE (store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::keypair key1; nano::send_block block1 (genesis.hash (), key1.pub, 1, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, block1).code); nano::open_block block2 (block1.hash (), 1, key1.pub, key1.prv, key1.pub, *pool.generate (key1.pub)); block2.signature.clear (); ASSERT_EQ (nano::process_result::bad_signature, ledger.process (transaction, block2).code); } TEST (ledger, fail_open_fork_previous) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_FALSE (store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::keypair key1; nano::send_block block1 (genesis.hash (), key1.pub, 1, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, block1).code); nano::send_block block2 (block1.hash (), key1.pub, 0, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (block1.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, block2).code); nano::open_block block3 (block1.hash (), 1, key1.pub, key1.prv, key1.pub, *pool.generate (key1.pub)); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, block3).code); nano::open_block block4 (block2.hash (), 1, key1.pub, key1.prv, key1.pub, *pool.generate (key1.pub)); ASSERT_EQ (nano::process_result::fork, ledger.process (transaction, block4).code); } TEST (ledger, fail_open_account_mismatch) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_FALSE (store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::keypair key1; nano::send_block block1 (genesis.hash (), key1.pub, 1, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, block1).code); nano::keypair badkey; nano::open_block block2 (block1.hash (), 1, badkey.pub, badkey.prv, badkey.pub, *pool.generate (badkey.pub)); ASSERT_NE (nano::process_result::progress, ledger.process (transaction, block2).code); } TEST (ledger, fail_receive_old) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_FALSE (store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::keypair key1; nano::send_block block1 (genesis.hash (), key1.pub, 1, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, block1).code); nano::send_block block2 (block1.hash (), key1.pub, 0, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (block1.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, block2).code); nano::open_block block3 (block1.hash (), 1, key1.pub, key1.prv, key1.pub, *pool.generate (key1.pub)); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, block3).code); nano::receive_block block4 (block3.hash (), block2.hash (), key1.prv, key1.pub, *pool.generate (block3.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, block4).code); ASSERT_EQ (nano::process_result::old, ledger.process (transaction, block4).code); } TEST (ledger, fail_receive_gap_source) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_FALSE (store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::keypair key1; nano::send_block block1 (genesis.hash (), key1.pub, 1, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); auto result1 (ledger.process (transaction, block1)); ASSERT_EQ (nano::process_result::progress, result1.code); nano::send_block block2 (block1.hash (), key1.pub, 0, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (block1.hash ())); auto result2 (ledger.process (transaction, block2)); ASSERT_EQ (nano::process_result::progress, result2.code); nano::open_block block3 (block1.hash (), 1, key1.pub, key1.prv, key1.pub, *pool.generate (key1.pub)); auto result3 (ledger.process (transaction, block3)); ASSERT_EQ (nano::process_result::progress, result3.code); nano::receive_block block4 (block3.hash (), 1, key1.prv, key1.pub, *pool.generate (block3.hash ())); auto result4 (ledger.process (transaction, block4)); ASSERT_EQ (nano::process_result::gap_source, result4.code); } TEST (ledger, fail_receive_overreceive) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_FALSE (store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::keypair key1; nano::send_block block1 (genesis.hash (), key1.pub, 1, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); auto result1 (ledger.process (transaction, block1)); ASSERT_EQ (nano::process_result::progress, result1.code); nano::open_block block2 (block1.hash (), 1, key1.pub, key1.prv, key1.pub, *pool.generate (key1.pub)); auto result3 (ledger.process (transaction, block2)); ASSERT_EQ (nano::process_result::progress, result3.code); nano::receive_block block3 (block2.hash (), block1.hash (), key1.prv, key1.pub, *pool.generate (block2.hash ())); auto result4 (ledger.process (transaction, block3)); ASSERT_EQ (nano::process_result::unreceivable, result4.code); } TEST (ledger, fail_receive_bad_signature) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_FALSE (store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::keypair key1; nano::send_block block1 (genesis.hash (), key1.pub, 1, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); auto result1 (ledger.process (transaction, block1)); ASSERT_EQ (nano::process_result::progress, result1.code); nano::send_block block2 (block1.hash (), key1.pub, 0, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (block1.hash ())); auto result2 (ledger.process (transaction, block2)); ASSERT_EQ (nano::process_result::progress, result2.code); nano::open_block block3 (block1.hash (), 1, key1.pub, key1.prv, key1.pub, *pool.generate (key1.pub)); auto result3 (ledger.process (transaction, block3)); ASSERT_EQ (nano::process_result::progress, result3.code); nano::receive_block block4 (block3.hash (), block2.hash (), nano::keypair ().prv, 0, *pool.generate (block3.hash ())); auto result4 (ledger.process (transaction, block4)); ASSERT_EQ (nano::process_result::bad_signature, result4.code); } TEST (ledger, fail_receive_gap_previous_opened) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_FALSE (store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::keypair key1; nano::send_block block1 (genesis.hash (), key1.pub, 1, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); auto result1 (ledger.process (transaction, block1)); ASSERT_EQ (nano::process_result::progress, result1.code); nano::send_block block2 (block1.hash (), key1.pub, 0, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (block1.hash ())); auto result2 (ledger.process (transaction, block2)); ASSERT_EQ (nano::process_result::progress, result2.code); nano::open_block block3 (block1.hash (), 1, key1.pub, key1.prv, key1.pub, *pool.generate (key1.pub)); auto result3 (ledger.process (transaction, block3)); ASSERT_EQ (nano::process_result::progress, result3.code); nano::receive_block block4 (1, block2.hash (), key1.prv, key1.pub, *pool.generate (nano::root (1))); auto result4 (ledger.process (transaction, block4)); ASSERT_EQ (nano::process_result::gap_previous, result4.code); } TEST (ledger, fail_receive_gap_previous_unopened) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_FALSE (store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::keypair key1; nano::send_block block1 (genesis.hash (), key1.pub, 1, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); auto result1 (ledger.process (transaction, block1)); ASSERT_EQ (nano::process_result::progress, result1.code); nano::send_block block2 (block1.hash (), key1.pub, 0, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (block1.hash ())); auto result2 (ledger.process (transaction, block2)); ASSERT_EQ (nano::process_result::progress, result2.code); nano::receive_block block3 (1, block2.hash (), key1.prv, key1.pub, *pool.generate (nano::root (1))); auto result3 (ledger.process (transaction, block3)); ASSERT_EQ (nano::process_result::gap_previous, result3.code); } TEST (ledger, fail_receive_fork_previous) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_FALSE (store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::keypair key1; nano::send_block block1 (genesis.hash (), key1.pub, 1, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); auto result1 (ledger.process (transaction, block1)); ASSERT_EQ (nano::process_result::progress, result1.code); nano::send_block block2 (block1.hash (), key1.pub, 0, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (block1.hash ())); auto result2 (ledger.process (transaction, block2)); ASSERT_EQ (nano::process_result::progress, result2.code); nano::open_block block3 (block1.hash (), 1, key1.pub, key1.prv, key1.pub, *pool.generate (key1.pub)); auto result3 (ledger.process (transaction, block3)); ASSERT_EQ (nano::process_result::progress, result3.code); nano::keypair key2; nano::send_block block4 (block3.hash (), key1.pub, 1, key1.prv, key1.pub, *pool.generate (block3.hash ())); auto result4 (ledger.process (transaction, block4)); ASSERT_EQ (nano::process_result::progress, result4.code); nano::receive_block block5 (block3.hash (), block2.hash (), key1.prv, key1.pub, *pool.generate (block3.hash ())); auto result5 (ledger.process (transaction, block5)); ASSERT_EQ (nano::process_result::fork, result5.code); } TEST (ledger, fail_receive_received_source) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_FALSE (store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::keypair key1; nano::send_block block1 (genesis.hash (), key1.pub, 2, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); auto result1 (ledger.process (transaction, block1)); ASSERT_EQ (nano::process_result::progress, result1.code); nano::send_block block2 (block1.hash (), key1.pub, 1, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (block1.hash ())); auto result2 (ledger.process (transaction, block2)); ASSERT_EQ (nano::process_result::progress, result2.code); nano::send_block block6 (block2.hash (), key1.pub, 0, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (block2.hash ())); auto result6 (ledger.process (transaction, block6)); ASSERT_EQ (nano::process_result::progress, result6.code); nano::open_block block3 (block1.hash (), 1, key1.pub, key1.prv, key1.pub, *pool.generate (key1.pub)); auto result3 (ledger.process (transaction, block3)); ASSERT_EQ (nano::process_result::progress, result3.code); nano::keypair key2; nano::send_block block4 (block3.hash (), key1.pub, 1, key1.prv, key1.pub, *pool.generate (block3.hash ())); auto result4 (ledger.process (transaction, block4)); ASSERT_EQ (nano::process_result::progress, result4.code); nano::receive_block block5 (block4.hash (), block2.hash (), key1.prv, key1.pub, *pool.generate (block4.hash ())); auto result5 (ledger.process (transaction, block5)); ASSERT_EQ (nano::process_result::progress, result5.code); nano::receive_block block7 (block3.hash (), block2.hash (), key1.prv, key1.pub, *pool.generate (block3.hash ())); auto result7 (ledger.process (transaction, block7)); ASSERT_EQ (nano::process_result::fork, result7.code); } TEST (ledger, latest_empty) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_FALSE (store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::keypair key; auto transaction (store->tx_begin_read ()); auto latest (ledger.latest (transaction, key.pub)); ASSERT_TRUE (latest.is_zero ()); } TEST (ledger, latest_root) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_FALSE (store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::keypair key; ASSERT_EQ (key.pub, ledger.latest_root (transaction, key.pub)); auto hash1 (ledger.latest (transaction, nano::test_genesis_key.pub)); nano::send_block send (hash1, 0, 1, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (hash1)); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, send).code); ASSERT_EQ (send.hash (), ledger.latest_root (transaction, nano::test_genesis_key.pub)); } TEST (ledger, change_representative_move_representation) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_TRUE (!store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::keypair key1; auto transaction (store->tx_begin_write ()); nano::genesis genesis; store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); auto hash1 (genesis.hash ()); ASSERT_EQ (nano::genesis_amount, ledger.weight (nano::test_genesis_key.pub)); nano::send_block send (hash1, key1.pub, 0, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (hash1)); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, send).code); ASSERT_EQ (0, ledger.weight (nano::test_genesis_key.pub)); nano::keypair key2; nano::change_block change (send.hash (), key2.pub, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (send.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, change).code); nano::keypair key3; nano::open_block open (send.hash (), key3.pub, key1.pub, key1.prv, key1.pub, *pool.generate (key1.pub)); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, open).code); ASSERT_EQ (nano::genesis_amount, ledger.weight (key3.pub)); } TEST (ledger, send_open_receive_rollback) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_TRUE (!store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); auto transaction (store->tx_begin_write ()); nano::genesis genesis; store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::account_info info1; ASSERT_FALSE (store->account_get (transaction, nano::test_genesis_key.pub, info1)); nano::keypair key1; nano::send_block send1 (info1.head, key1.pub, nano::genesis_amount - 50, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (info1.head)); auto return1 (ledger.process (transaction, send1)); ASSERT_EQ (nano::process_result::progress, return1.code); nano::send_block send2 (send1.hash (), key1.pub, nano::genesis_amount - 100, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (send1.hash ())); auto return2 (ledger.process (transaction, send2)); ASSERT_EQ (nano::process_result::progress, return2.code); nano::keypair key2; nano::open_block open (send2.hash (), key2.pub, key1.pub, key1.prv, key1.pub, *pool.generate (key1.pub)); auto return4 (ledger.process (transaction, open)); ASSERT_EQ (nano::process_result::progress, return4.code); nano::receive_block receive (open.hash (), send1.hash (), key1.prv, key1.pub, *pool.generate (open.hash ())); auto return5 (ledger.process (transaction, receive)); ASSERT_EQ (nano::process_result::progress, return5.code); nano::keypair key3; ASSERT_EQ (100, ledger.weight (key2.pub)); ASSERT_EQ (nano::genesis_amount - 100, ledger.weight (nano::test_genesis_key.pub)); ASSERT_EQ (0, ledger.weight (key3.pub)); nano::change_block change1 (send2.hash (), key3.pub, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (send2.hash ())); auto return6 (ledger.process (transaction, change1)); ASSERT_EQ (nano::process_result::progress, return6.code); ASSERT_EQ (100, ledger.weight (key2.pub)); ASSERT_EQ (0, ledger.weight (nano::test_genesis_key.pub)); ASSERT_EQ (nano::genesis_amount - 100, ledger.weight (key3.pub)); ASSERT_FALSE (ledger.rollback (transaction, receive.hash ())); ASSERT_EQ (50, ledger.weight (key2.pub)); ASSERT_EQ (0, ledger.weight (nano::test_genesis_key.pub)); ASSERT_EQ (nano::genesis_amount - 100, ledger.weight (key3.pub)); ASSERT_FALSE (ledger.rollback (transaction, open.hash ())); ASSERT_EQ (0, ledger.weight (key2.pub)); ASSERT_EQ (0, ledger.weight (nano::test_genesis_key.pub)); ASSERT_EQ (nano::genesis_amount - 100, ledger.weight (key3.pub)); ASSERT_FALSE (ledger.rollback (transaction, change1.hash ())); ASSERT_EQ (0, ledger.weight (key2.pub)); ASSERT_EQ (0, ledger.weight (key3.pub)); ASSERT_EQ (nano::genesis_amount - 100, ledger.weight (nano::test_genesis_key.pub)); ASSERT_FALSE (ledger.rollback (transaction, send2.hash ())); ASSERT_EQ (0, ledger.weight (key2.pub)); ASSERT_EQ (0, ledger.weight (key3.pub)); ASSERT_EQ (nano::genesis_amount - 50, ledger.weight (nano::test_genesis_key.pub)); ASSERT_FALSE (ledger.rollback (transaction, send1.hash ())); ASSERT_EQ (0, ledger.weight (key2.pub)); ASSERT_EQ (0, ledger.weight (key3.pub)); ASSERT_EQ (nano::genesis_amount - 0, ledger.weight (nano::test_genesis_key.pub)); } TEST (ledger, bootstrap_rep_weight) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_TRUE (!store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::account_info info1; nano::keypair key2; nano::genesis genesis; nano::work_pool pool (std::numeric_limits<unsigned>::max ()); { auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); ASSERT_FALSE (store->account_get (transaction, nano::test_genesis_key.pub, info1)); nano::send_block send (info1.head, key2.pub, std::numeric_limits<nano::uint128_t>::max () - 50, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (info1.head)); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, send).code); } ASSERT_EQ (2, ledger.block_count_cache); { ledger.bootstrap_weight_max_blocks = 3; ledger.bootstrap_weights[key2.pub] = 1000; ASSERT_EQ (1000, ledger.weight (key2.pub)); } { auto transaction (store->tx_begin_write ()); ASSERT_FALSE (store->account_get (transaction, nano::test_genesis_key.pub, info1)); nano::send_block send (info1.head, key2.pub, std::numeric_limits<nano::uint128_t>::max () - 100, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (info1.head)); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, send).code); } ASSERT_EQ (3, ledger.block_count_cache); { auto transaction (store->tx_begin_read ()); ASSERT_EQ (0, ledger.weight (key2.pub)); } } TEST (ledger, block_destination_source) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_TRUE (!store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::keypair dest; nano::uint128_t balance (nano::genesis_amount); balance -= nano::Gxrb_ratio; nano::send_block block1 (genesis.hash (), dest.pub, balance, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); balance -= nano::Gxrb_ratio; nano::send_block block2 (block1.hash (), nano::genesis_account, balance, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (block1.hash ())); balance += nano::Gxrb_ratio; nano::receive_block block3 (block2.hash (), block2.hash (), nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (block2.hash ())); balance -= nano::Gxrb_ratio; nano::state_block block4 (nano::genesis_account, block3.hash (), nano::genesis_account, balance, dest.pub, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (block3.hash ())); balance -= nano::Gxrb_ratio; nano::state_block block5 (nano::genesis_account, block4.hash (), nano::genesis_account, balance, nano::genesis_account, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (block4.hash ())); balance += nano::Gxrb_ratio; nano::state_block block6 (nano::genesis_account, block5.hash (), nano::genesis_account, balance, block5.hash (), nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (block5.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, block1).code); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, block2).code); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, block3).code); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, block4).code); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, block5).code); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, block6).code); ASSERT_EQ (balance, ledger.balance (transaction, block6.hash ())); ASSERT_EQ (dest.pub, ledger.block_destination (transaction, block1)); ASSERT_TRUE (ledger.block_source (transaction, block1).is_zero ()); ASSERT_EQ (nano::genesis_account, ledger.block_destination (transaction, block2)); ASSERT_TRUE (ledger.block_source (transaction, block2).is_zero ()); ASSERT_TRUE (ledger.block_destination (transaction, block3).is_zero ()); ASSERT_EQ (block2.hash (), ledger.block_source (transaction, block3)); ASSERT_EQ (dest.pub, ledger.block_destination (transaction, block4)); ASSERT_TRUE (ledger.block_source (transaction, block4).is_zero ()); ASSERT_EQ (nano::genesis_account, ledger.block_destination (transaction, block5)); ASSERT_TRUE (ledger.block_source (transaction, block5).is_zero ()); ASSERT_TRUE (ledger.block_destination (transaction, block6).is_zero ()); ASSERT_EQ (block5.hash (), ledger.block_source (transaction, block6)); } TEST (ledger, state_account) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_TRUE (!store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::state_block send1 (nano::genesis_account, genesis.hash (), nano::genesis_account, nano::genesis_amount - nano::Gxrb_ratio, nano::genesis_account, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, send1).code); ASSERT_EQ (nano::genesis_account, ledger.account (transaction, send1.hash ())); } TEST (ledger, state_send_receive) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_TRUE (!store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::state_block send1 (nano::genesis_account, genesis.hash (), nano::genesis_account, nano::genesis_amount - nano::Gxrb_ratio, nano::genesis_account, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, send1).code); ASSERT_TRUE (store->block_exists (transaction, send1.hash ())); auto send2 (store->block_get (transaction, send1.hash ())); ASSERT_NE (nullptr, send2); ASSERT_EQ (send1, *send2); ASSERT_EQ (nano::genesis_amount - nano::Gxrb_ratio, ledger.balance (transaction, send1.hash ())); ASSERT_EQ (nano::Gxrb_ratio, ledger.amount (transaction, send1.hash ())); ASSERT_EQ (nano::genesis_amount - nano::Gxrb_ratio, ledger.weight (nano::genesis_account)); ASSERT_TRUE (store->pending_exists (transaction, nano::pending_key (nano::genesis_account, send1.hash ()))); nano::state_block receive1 (nano::genesis_account, send1.hash (), nano::genesis_account, nano::genesis_amount, send1.hash (), nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (send1.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, receive1).code); ASSERT_TRUE (store->block_exists (transaction, receive1.hash ())); auto receive2 (store->block_get (transaction, receive1.hash ())); ASSERT_NE (nullptr, receive2); ASSERT_EQ (receive1, *receive2); ASSERT_EQ (nano::genesis_amount, ledger.balance (transaction, receive1.hash ())); ASSERT_EQ (nano::Gxrb_ratio, ledger.amount (transaction, receive1.hash ())); ASSERT_EQ (nano::genesis_amount, ledger.weight (nano::genesis_account)); ASSERT_FALSE (store->pending_exists (transaction, nano::pending_key (nano::genesis_account, send1.hash ()))); } TEST (ledger, state_receive) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_TRUE (!store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::send_block send1 (genesis.hash (), nano::genesis_account, nano::genesis_amount - nano::Gxrb_ratio, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, send1).code); ASSERT_TRUE (store->block_exists (transaction, send1.hash ())); auto send2 (store->block_get (transaction, send1.hash ())); ASSERT_NE (nullptr, send2); ASSERT_EQ (send1, *send2); ASSERT_EQ (nano::genesis_amount - nano::Gxrb_ratio, ledger.balance (transaction, send1.hash ())); ASSERT_EQ (nano::Gxrb_ratio, ledger.amount (transaction, send1.hash ())); ASSERT_EQ (nano::genesis_amount - nano::Gxrb_ratio, ledger.weight (nano::genesis_account)); nano::state_block receive1 (nano::genesis_account, send1.hash (), nano::genesis_account, nano::genesis_amount, send1.hash (), nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (send1.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, receive1).code); ASSERT_TRUE (store->block_exists (transaction, receive1.hash ())); auto receive2 (store->block_get (transaction, receive1.hash ())); ASSERT_NE (nullptr, receive2); ASSERT_EQ (receive1, *receive2); ASSERT_EQ (nano::genesis_amount, ledger.balance (transaction, receive1.hash ())); ASSERT_EQ (nano::Gxrb_ratio, ledger.amount (transaction, receive1.hash ())); ASSERT_EQ (nano::genesis_amount, ledger.weight (nano::genesis_account)); } TEST (ledger, state_rep_change) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_TRUE (!store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::keypair rep; nano::state_block change1 (nano::genesis_account, genesis.hash (), rep.pub, nano::genesis_amount, 0, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, change1).code); ASSERT_TRUE (store->block_exists (transaction, change1.hash ())); auto change2 (store->block_get (transaction, change1.hash ())); ASSERT_NE (nullptr, change2); ASSERT_EQ (change1, *change2); ASSERT_EQ (nano::genesis_amount, ledger.balance (transaction, change1.hash ())); ASSERT_EQ (0, ledger.amount (transaction, change1.hash ())); ASSERT_EQ (0, ledger.weight (nano::genesis_account)); ASSERT_EQ (nano::genesis_amount, ledger.weight (rep.pub)); } TEST (ledger, state_open) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_TRUE (!store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::keypair destination; nano::state_block send1 (nano::genesis_account, genesis.hash (), nano::genesis_account, nano::genesis_amount - nano::Gxrb_ratio, destination.pub, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, send1).code); ASSERT_TRUE (store->block_exists (transaction, send1.hash ())); auto send2 (store->block_get (transaction, send1.hash ())); ASSERT_NE (nullptr, send2); ASSERT_EQ (send1, *send2); ASSERT_EQ (nano::genesis_amount - nano::Gxrb_ratio, ledger.balance (transaction, send1.hash ())); ASSERT_EQ (nano::Gxrb_ratio, ledger.amount (transaction, send1.hash ())); ASSERT_EQ (nano::genesis_amount - nano::Gxrb_ratio, ledger.weight (nano::genesis_account)); ASSERT_TRUE (store->pending_exists (transaction, nano::pending_key (destination.pub, send1.hash ()))); nano::state_block open1 (destination.pub, 0, nano::genesis_account, nano::Gxrb_ratio, send1.hash (), destination.prv, destination.pub, *pool.generate (destination.pub)); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, open1).code); ASSERT_FALSE (store->pending_exists (transaction, nano::pending_key (destination.pub, send1.hash ()))); ASSERT_TRUE (store->block_exists (transaction, open1.hash ())); auto open2 (store->block_get (transaction, open1.hash ())); ASSERT_NE (nullptr, open2); ASSERT_EQ (open1, *open2); ASSERT_EQ (nano::Gxrb_ratio, ledger.balance (transaction, open1.hash ())); ASSERT_EQ (nano::Gxrb_ratio, ledger.amount (transaction, open1.hash ())); ASSERT_EQ (nano::genesis_amount, ledger.weight (nano::genesis_account)); } // Make sure old block types can't be inserted after a state block. TEST (ledger, send_after_state_fail) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_TRUE (!store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::state_block send1 (nano::genesis_account, genesis.hash (), nano::genesis_account, nano::genesis_amount - nano::Gxrb_ratio, nano::genesis_account, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, send1).code); nano::send_block send2 (send1.hash (), nano::genesis_account, nano::genesis_amount - (2 * nano::Gxrb_ratio), nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (send1.hash ())); ASSERT_EQ (nano::process_result::block_position, ledger.process (transaction, send2).code); } // Make sure old block types can't be inserted after a state block. TEST (ledger, receive_after_state_fail) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_TRUE (!store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::state_block send1 (nano::genesis_account, genesis.hash (), nano::genesis_account, nano::genesis_amount - nano::Gxrb_ratio, nano::genesis_account, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, send1).code); nano::receive_block receive1 (send1.hash (), send1.hash (), nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (send1.hash ())); ASSERT_EQ (nano::process_result::block_position, ledger.process (transaction, receive1).code); } // Make sure old block types can't be inserted after a state block. TEST (ledger, change_after_state_fail) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_TRUE (!store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::state_block send1 (nano::genesis_account, genesis.hash (), nano::genesis_account, nano::genesis_amount - nano::Gxrb_ratio, nano::genesis_account, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, send1).code); nano::keypair rep; nano::change_block change1 (send1.hash (), rep.pub, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (send1.hash ())); ASSERT_EQ (nano::process_result::block_position, ledger.process (transaction, change1).code); } TEST (ledger, state_unreceivable_fail) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_TRUE (!store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::send_block send1 (genesis.hash (), nano::genesis_account, nano::genesis_amount - nano::Gxrb_ratio, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, send1).code); ASSERT_TRUE (store->block_exists (transaction, send1.hash ())); auto send2 (store->block_get (transaction, send1.hash ())); ASSERT_NE (nullptr, send2); ASSERT_EQ (send1, *send2); ASSERT_EQ (nano::genesis_amount - nano::Gxrb_ratio, ledger.balance (transaction, send1.hash ())); ASSERT_EQ (nano::Gxrb_ratio, ledger.amount (transaction, send1.hash ())); ASSERT_EQ (nano::genesis_amount - nano::Gxrb_ratio, ledger.weight (nano::genesis_account)); nano::state_block receive1 (nano::genesis_account, send1.hash (), nano::genesis_account, nano::genesis_amount, 1, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (send1.hash ())); ASSERT_EQ (nano::process_result::gap_source, ledger.process (transaction, receive1).code); } TEST (ledger, state_receive_bad_amount_fail) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_TRUE (!store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::send_block send1 (genesis.hash (), nano::genesis_account, nano::genesis_amount - nano::Gxrb_ratio, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, send1).code); ASSERT_TRUE (store->block_exists (transaction, send1.hash ())); auto send2 (store->block_get (transaction, send1.hash ())); ASSERT_NE (nullptr, send2); ASSERT_EQ (send1, *send2); ASSERT_EQ (nano::genesis_amount - nano::Gxrb_ratio, ledger.balance (transaction, send1.hash ())); ASSERT_EQ (nano::Gxrb_ratio, ledger.amount (transaction, send1.hash ())); ASSERT_EQ (nano::genesis_amount - nano::Gxrb_ratio, ledger.weight (nano::genesis_account)); nano::state_block receive1 (nano::genesis_account, send1.hash (), nano::genesis_account, nano::genesis_amount - nano::Gxrb_ratio, send1.hash (), nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (send1.hash ())); ASSERT_EQ (nano::process_result::balance_mismatch, ledger.process (transaction, receive1).code); } TEST (ledger, state_no_link_amount_fail) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_TRUE (!store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::state_block send1 (nano::genesis_account, genesis.hash (), nano::genesis_account, nano::genesis_amount - nano::Gxrb_ratio, nano::genesis_account, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, send1).code); nano::keypair rep; nano::state_block change1 (nano::genesis_account, send1.hash (), rep.pub, nano::genesis_amount, 0, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (send1.hash ())); ASSERT_EQ (nano::process_result::balance_mismatch, ledger.process (transaction, change1).code); } TEST (ledger, state_receive_wrong_account_fail) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_TRUE (!store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::state_block send1 (nano::genesis_account, genesis.hash (), nano::genesis_account, nano::genesis_amount - nano::Gxrb_ratio, nano::genesis_account, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, send1).code); ASSERT_TRUE (store->block_exists (transaction, send1.hash ())); auto send2 (store->block_get (transaction, send1.hash ())); ASSERT_NE (nullptr, send2); ASSERT_EQ (send1, *send2); ASSERT_EQ (nano::genesis_amount - nano::Gxrb_ratio, ledger.balance (transaction, send1.hash ())); ASSERT_EQ (nano::Gxrb_ratio, ledger.amount (transaction, send1.hash ())); ASSERT_EQ (nano::genesis_amount - nano::Gxrb_ratio, ledger.weight (nano::genesis_account)); nano::keypair key; nano::state_block receive1 (key.pub, 0, nano::genesis_account, nano::Gxrb_ratio, send1.hash (), key.prv, key.pub, *pool.generate (key.pub)); ASSERT_EQ (nano::process_result::unreceivable, ledger.process (transaction, receive1).code); } TEST (ledger, state_open_state_fork) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_TRUE (!store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::keypair destination; nano::state_block send1 (nano::genesis_account, genesis.hash (), nano::genesis_account, nano::genesis_amount - nano::Gxrb_ratio, destination.pub, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, send1).code); nano::state_block open1 (destination.pub, 0, nano::genesis_account, nano::Gxrb_ratio, send1.hash (), destination.prv, destination.pub, *pool.generate (destination.pub)); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, open1).code); nano::open_block open2 (send1.hash (), nano::genesis_account, destination.pub, destination.prv, destination.pub, *pool.generate (destination.pub)); ASSERT_EQ (nano::process_result::fork, ledger.process (transaction, open2).code); ASSERT_EQ (open1.root (), open2.root ()); } TEST (ledger, state_state_open_fork) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_TRUE (!store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::keypair destination; nano::state_block send1 (nano::genesis_account, genesis.hash (), nano::genesis_account, nano::genesis_amount - nano::Gxrb_ratio, destination.pub, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, send1).code); nano::open_block open1 (send1.hash (), nano::genesis_account, destination.pub, destination.prv, destination.pub, *pool.generate (destination.pub)); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, open1).code); nano::state_block open2 (destination.pub, 0, nano::genesis_account, nano::Gxrb_ratio, send1.hash (), destination.prv, destination.pub, *pool.generate (destination.pub)); ASSERT_EQ (nano::process_result::fork, ledger.process (transaction, open2).code); ASSERT_EQ (open1.root (), open2.root ()); } TEST (ledger, state_open_previous_fail) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_TRUE (!store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::keypair destination; nano::state_block send1 (nano::genesis_account, genesis.hash (), nano::genesis_account, nano::genesis_amount - nano::Gxrb_ratio, destination.pub, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, send1).code); nano::state_block open1 (destination.pub, 1, nano::genesis_account, nano::Gxrb_ratio, send1.hash (), destination.prv, destination.pub, *pool.generate (1)); ASSERT_EQ (nano::process_result::gap_previous, ledger.process (transaction, open1).code); } TEST (ledger, state_open_source_fail) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_TRUE (!store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::keypair destination; nano::state_block send1 (nano::genesis_account, genesis.hash (), nano::genesis_account, nano::genesis_amount - nano::Gxrb_ratio, destination.pub, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, send1).code); nano::state_block open1 (destination.pub, 0, nano::genesis_account, 0, 0, destination.prv, destination.pub, *pool.generate (destination.pub)); ASSERT_EQ (nano::process_result::gap_source, ledger.process (transaction, open1).code); } TEST (ledger, state_send_change) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_TRUE (!store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::keypair rep; nano::state_block send1 (nano::genesis_account, genesis.hash (), rep.pub, nano::genesis_amount - nano::Gxrb_ratio, nano::genesis_account, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, send1).code); ASSERT_TRUE (store->block_exists (transaction, send1.hash ())); auto send2 (store->block_get (transaction, send1.hash ())); ASSERT_NE (nullptr, send2); ASSERT_EQ (send1, *send2); ASSERT_EQ (nano::genesis_amount - nano::Gxrb_ratio, ledger.balance (transaction, send1.hash ())); ASSERT_EQ (nano::Gxrb_ratio, ledger.amount (transaction, send1.hash ())); ASSERT_EQ (0, ledger.weight (nano::genesis_account)); ASSERT_EQ (nano::genesis_amount - nano::Gxrb_ratio, ledger.weight (rep.pub)); } TEST (ledger, state_receive_change) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_TRUE (!store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::state_block send1 (nano::genesis_account, genesis.hash (), nano::genesis_account, nano::genesis_amount - nano::Gxrb_ratio, nano::genesis_account, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, send1).code); ASSERT_TRUE (store->block_exists (transaction, send1.hash ())); auto send2 (store->block_get (transaction, send1.hash ())); ASSERT_NE (nullptr, send2); ASSERT_EQ (send1, *send2); ASSERT_EQ (nano::genesis_amount - nano::Gxrb_ratio, ledger.balance (transaction, send1.hash ())); ASSERT_EQ (nano::Gxrb_ratio, ledger.amount (transaction, send1.hash ())); ASSERT_EQ (nano::genesis_amount - nano::Gxrb_ratio, ledger.weight (nano::genesis_account)); nano::keypair rep; nano::state_block receive1 (nano::genesis_account, send1.hash (), rep.pub, nano::genesis_amount, send1.hash (), nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (send1.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, receive1).code); ASSERT_TRUE (store->block_exists (transaction, receive1.hash ())); auto receive2 (store->block_get (transaction, receive1.hash ())); ASSERT_NE (nullptr, receive2); ASSERT_EQ (receive1, *receive2); ASSERT_EQ (nano::genesis_amount, ledger.balance (transaction, receive1.hash ())); ASSERT_EQ (nano::Gxrb_ratio, ledger.amount (transaction, receive1.hash ())); ASSERT_EQ (0, ledger.weight (nano::genesis_account)); ASSERT_EQ (nano::genesis_amount, ledger.weight (rep.pub)); } TEST (ledger, state_open_old) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_TRUE (!store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::keypair destination; nano::state_block send1 (nano::genesis_account, genesis.hash (), nano::genesis_account, nano::genesis_amount - nano::Gxrb_ratio, destination.pub, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, send1).code); nano::open_block open1 (send1.hash (), nano::genesis_account, destination.pub, destination.prv, destination.pub, *pool.generate (destination.pub)); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, open1).code); ASSERT_EQ (nano::Gxrb_ratio, ledger.balance (transaction, open1.hash ())); ASSERT_EQ (nano::Gxrb_ratio, ledger.amount (transaction, open1.hash ())); ASSERT_EQ (nano::genesis_amount, ledger.weight (nano::genesis_account)); } TEST (ledger, state_receive_old) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_TRUE (!store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::keypair destination; nano::state_block send1 (nano::genesis_account, genesis.hash (), nano::genesis_account, nano::genesis_amount - nano::Gxrb_ratio, destination.pub, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, send1).code); nano::state_block send2 (nano::genesis_account, send1.hash (), nano::genesis_account, nano::genesis_amount - (2 * nano::Gxrb_ratio), destination.pub, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (send1.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, send2).code); nano::open_block open1 (send1.hash (), nano::genesis_account, destination.pub, destination.prv, destination.pub, *pool.generate (destination.pub)); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, open1).code); nano::receive_block receive1 (open1.hash (), send2.hash (), destination.prv, destination.pub, *pool.generate (open1.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, receive1).code); ASSERT_EQ (2 * nano::Gxrb_ratio, ledger.balance (transaction, receive1.hash ())); ASSERT_EQ (nano::Gxrb_ratio, ledger.amount (transaction, receive1.hash ())); ASSERT_EQ (nano::genesis_amount, ledger.weight (nano::genesis_account)); } TEST (ledger, state_rollback_send) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_TRUE (!store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::state_block send1 (nano::genesis_account, genesis.hash (), nano::genesis_account, nano::genesis_amount - nano::Gxrb_ratio, nano::genesis_account, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, send1).code); ASSERT_TRUE (store->block_exists (transaction, send1.hash ())); auto send2 (store->block_get (transaction, send1.hash ())); ASSERT_NE (nullptr, send2); ASSERT_EQ (send1, *send2); ASSERT_EQ (nano::genesis_amount - nano::Gxrb_ratio, ledger.account_balance (transaction, nano::genesis_account)); ASSERT_EQ (nano::genesis_amount - nano::Gxrb_ratio, ledger.weight (nano::genesis_account)); nano::pending_info info; ASSERT_FALSE (store->pending_get (transaction, nano::pending_key (nano::genesis_account, send1.hash ()), info)); ASSERT_EQ (nano::genesis_account, info.source); ASSERT_EQ (nano::Gxrb_ratio, info.amount.number ()); ASSERT_FALSE (ledger.rollback (transaction, send1.hash ())); ASSERT_FALSE (store->block_exists (transaction, send1.hash ())); ASSERT_EQ (nano::genesis_amount, ledger.account_balance (transaction, nano::genesis_account)); ASSERT_EQ (nano::genesis_amount, ledger.weight (nano::genesis_account)); ASSERT_FALSE (store->pending_exists (transaction, nano::pending_key (nano::genesis_account, send1.hash ()))); ASSERT_TRUE (store->block_successor (transaction, genesis.hash ()).is_zero ()); } TEST (ledger, state_rollback_receive) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_TRUE (!store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::state_block send1 (nano::genesis_account, genesis.hash (), nano::genesis_account, nano::genesis_amount - nano::Gxrb_ratio, nano::genesis_account, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, send1).code); nano::state_block receive1 (nano::genesis_account, send1.hash (), nano::genesis_account, nano::genesis_amount, send1.hash (), nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (send1.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, receive1).code); ASSERT_FALSE (store->pending_exists (transaction, nano::pending_key (nano::genesis_account, receive1.hash ()))); ASSERT_FALSE (ledger.rollback (transaction, receive1.hash ())); nano::pending_info info; ASSERT_FALSE (store->pending_get (transaction, nano::pending_key (nano::genesis_account, send1.hash ()), info)); ASSERT_EQ (nano::genesis_account, info.source); ASSERT_EQ (nano::Gxrb_ratio, info.amount.number ()); ASSERT_FALSE (store->block_exists (transaction, receive1.hash ())); ASSERT_EQ (nano::genesis_amount - nano::Gxrb_ratio, ledger.account_balance (transaction, nano::genesis_account)); ASSERT_EQ (nano::genesis_amount - nano::Gxrb_ratio, ledger.weight (nano::genesis_account)); } TEST (ledger, state_rollback_received_send) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_TRUE (!store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::keypair key; nano::state_block send1 (nano::genesis_account, genesis.hash (), nano::genesis_account, nano::genesis_amount - nano::Gxrb_ratio, key.pub, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, send1).code); nano::state_block receive1 (key.pub, 0, key.pub, nano::Gxrb_ratio, send1.hash (), key.prv, key.pub, *pool.generate (key.pub)); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, receive1).code); ASSERT_FALSE (store->pending_exists (transaction, nano::pending_key (nano::genesis_account, receive1.hash ()))); ASSERT_FALSE (ledger.rollback (transaction, send1.hash ())); ASSERT_FALSE (store->pending_exists (transaction, nano::pending_key (nano::genesis_account, send1.hash ()))); ASSERT_FALSE (store->block_exists (transaction, send1.hash ())); ASSERT_FALSE (store->block_exists (transaction, receive1.hash ())); ASSERT_EQ (nano::genesis_amount, ledger.account_balance (transaction, nano::genesis_account)); ASSERT_EQ (nano::genesis_amount, ledger.weight (nano::genesis_account)); ASSERT_EQ (0, ledger.account_balance (transaction, key.pub)); ASSERT_EQ (0, ledger.weight (key.pub)); } TEST (ledger, state_rep_change_rollback) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_TRUE (!store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::keypair rep; nano::state_block change1 (nano::genesis_account, genesis.hash (), rep.pub, nano::genesis_amount, 0, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, change1).code); ASSERT_FALSE (ledger.rollback (transaction, change1.hash ())); ASSERT_FALSE (store->block_exists (transaction, change1.hash ())); ASSERT_EQ (nano::genesis_amount, ledger.account_balance (transaction, nano::genesis_account)); ASSERT_EQ (nano::genesis_amount, ledger.weight (nano::genesis_account)); ASSERT_EQ (0, ledger.weight (rep.pub)); } TEST (ledger, state_open_rollback) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_TRUE (!store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::keypair destination; nano::state_block send1 (nano::genesis_account, genesis.hash (), nano::genesis_account, nano::genesis_amount - nano::Gxrb_ratio, destination.pub, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, send1).code); nano::state_block open1 (destination.pub, 0, nano::genesis_account, nano::Gxrb_ratio, send1.hash (), destination.prv, destination.pub, *pool.generate (destination.pub)); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, open1).code); ASSERT_FALSE (ledger.rollback (transaction, open1.hash ())); ASSERT_FALSE (store->block_exists (transaction, open1.hash ())); ASSERT_EQ (0, ledger.account_balance (transaction, destination.pub)); ASSERT_EQ (nano::genesis_amount - nano::Gxrb_ratio, ledger.weight (nano::genesis_account)); nano::pending_info info; ASSERT_FALSE (store->pending_get (transaction, nano::pending_key (destination.pub, send1.hash ()), info)); ASSERT_EQ (nano::genesis_account, info.source); ASSERT_EQ (nano::Gxrb_ratio, info.amount.number ()); } TEST (ledger, state_send_change_rollback) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_TRUE (!store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::keypair rep; nano::state_block send1 (nano::genesis_account, genesis.hash (), rep.pub, nano::genesis_amount - nano::Gxrb_ratio, nano::genesis_account, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, send1).code); ASSERT_FALSE (ledger.rollback (transaction, send1.hash ())); ASSERT_FALSE (store->block_exists (transaction, send1.hash ())); ASSERT_EQ (nano::genesis_amount, ledger.account_balance (transaction, nano::genesis_account)); ASSERT_EQ (nano::genesis_amount, ledger.weight (nano::genesis_account)); ASSERT_EQ (0, ledger.weight (rep.pub)); } TEST (ledger, state_receive_change_rollback) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_TRUE (!store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::state_block send1 (nano::genesis_account, genesis.hash (), nano::genesis_account, nano::genesis_amount - nano::Gxrb_ratio, nano::genesis_account, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, send1).code); nano::keypair rep; nano::state_block receive1 (nano::genesis_account, send1.hash (), rep.pub, nano::genesis_amount, send1.hash (), nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (send1.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, receive1).code); ASSERT_FALSE (ledger.rollback (transaction, receive1.hash ())); ASSERT_FALSE (store->block_exists (transaction, receive1.hash ())); ASSERT_EQ (nano::genesis_amount - nano::Gxrb_ratio, ledger.account_balance (transaction, nano::genesis_account)); ASSERT_EQ (nano::genesis_amount - nano::Gxrb_ratio, ledger.weight (nano::genesis_account)); ASSERT_EQ (0, ledger.weight (rep.pub)); } TEST (ledger, epoch_blocks_v1_general) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_TRUE (!store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::keypair destination; nano::state_block epoch1 (nano::genesis_account, genesis.hash (), nano::genesis_account, nano::genesis_amount, ledger.link (nano::epoch::epoch_1), nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, epoch1).code); nano::state_block epoch2 (nano::genesis_account, epoch1.hash (), nano::genesis_account, nano::genesis_amount, ledger.link (nano::epoch::epoch_1), nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (epoch1.hash ())); ASSERT_EQ (nano::process_result::block_position, ledger.process (transaction, epoch2).code); nano::account_info genesis_info; ASSERT_FALSE (ledger.store.account_get (transaction, nano::genesis_account, genesis_info)); ASSERT_EQ (genesis_info.epoch (), nano::epoch::epoch_1); ASSERT_FALSE (ledger.rollback (transaction, epoch1.hash ())); ASSERT_FALSE (ledger.store.account_get (transaction, nano::genesis_account, genesis_info)); ASSERT_EQ (genesis_info.epoch (), nano::epoch::epoch_0); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, epoch1).code); ASSERT_FALSE (ledger.store.account_get (transaction, nano::genesis_account, genesis_info)); ASSERT_EQ (genesis_info.epoch (), nano::epoch::epoch_1); nano::change_block change1 (epoch1.hash (), nano::genesis_account, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (epoch1.hash ())); ASSERT_EQ (nano::process_result::block_position, ledger.process (transaction, change1).code); nano::state_block send1 (nano::genesis_account, epoch1.hash (), nano::genesis_account, nano::genesis_amount - nano::Gxrb_ratio, destination.pub, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (epoch1.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, send1).code); nano::open_block open1 (send1.hash (), nano::genesis_account, destination.pub, destination.prv, destination.pub, *pool.generate (destination.pub)); ASSERT_EQ (nano::process_result::unreceivable, ledger.process (transaction, open1).code); nano::state_block epoch3 (destination.pub, 0, nano::genesis_account, 0, ledger.link (nano::epoch::epoch_1), nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (destination.pub)); ASSERT_EQ (nano::process_result::representative_mismatch, ledger.process (transaction, epoch3).code); nano::state_block epoch4 (destination.pub, 0, 0, 0, ledger.link (nano::epoch::epoch_1), nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (destination.pub)); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, epoch4).code); nano::receive_block receive1 (epoch4.hash (), send1.hash (), destination.prv, destination.pub, *pool.generate (epoch4.hash ())); ASSERT_EQ (nano::process_result::block_position, ledger.process (transaction, receive1).code); nano::state_block receive2 (destination.pub, epoch4.hash (), destination.pub, nano::Gxrb_ratio, send1.hash (), destination.prv, destination.pub, *pool.generate (epoch4.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, receive2).code); ASSERT_EQ (0, ledger.balance (transaction, epoch4.hash ())); ASSERT_EQ (nano::Gxrb_ratio, ledger.balance (transaction, receive2.hash ())); ASSERT_EQ (nano::Gxrb_ratio, ledger.amount (transaction, receive2.hash ())); ASSERT_EQ (nano::genesis_amount - nano::Gxrb_ratio, ledger.weight (nano::genesis_account)); ASSERT_EQ (nano::Gxrb_ratio, ledger.weight (destination.pub)); } TEST (ledger, epoch_blocks_v2_general) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_TRUE (!store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::keypair destination; nano::state_block epoch1 (nano::genesis_account, genesis.hash (), nano::genesis_account, nano::genesis_amount, ledger.link (nano::epoch::epoch_2), nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); // Trying to upgrade from epoch 0 to epoch 2. It is a requirement epoch upgrades are sequential unless the account is unopened ASSERT_EQ (nano::process_result::block_position, ledger.process (transaction, epoch1).code); // Set it to the first epoch and it should now succeed epoch1 = nano::state_block (nano::genesis_account, genesis.hash (), nano::genesis_account, nano::genesis_amount, ledger.link (nano::epoch::epoch_1), nano::test_genesis_key.prv, nano::test_genesis_key.pub, epoch1.work); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, epoch1).code); nano::state_block epoch2 (nano::genesis_account, epoch1.hash (), nano::genesis_account, nano::genesis_amount, ledger.link (nano::epoch::epoch_2), nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (epoch1.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, epoch2).code); nano::state_block epoch3 (nano::genesis_account, epoch2.hash (), nano::genesis_account, nano::genesis_amount, ledger.link (nano::epoch::epoch_2), nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (epoch2.hash ())); ASSERT_EQ (nano::process_result::block_position, ledger.process (transaction, epoch3).code); nano::account_info genesis_info; ASSERT_FALSE (ledger.store.account_get (transaction, nano::genesis_account, genesis_info)); ASSERT_EQ (genesis_info.epoch (), nano::epoch::epoch_2); ASSERT_FALSE (ledger.rollback (transaction, epoch1.hash ())); ASSERT_FALSE (ledger.store.account_get (transaction, nano::genesis_account, genesis_info)); ASSERT_EQ (genesis_info.epoch (), nano::epoch::epoch_0); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, epoch1).code); ASSERT_FALSE (ledger.store.account_get (transaction, nano::genesis_account, genesis_info)); ASSERT_EQ (genesis_info.epoch (), nano::epoch::epoch_1); nano::change_block change1 (epoch1.hash (), nano::genesis_account, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (epoch1.hash ())); ASSERT_EQ (nano::process_result::block_position, ledger.process (transaction, change1).code); nano::state_block send1 (nano::genesis_account, epoch1.hash (), nano::genesis_account, nano::genesis_amount - nano::Gxrb_ratio, destination.pub, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (epoch1.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, send1).code); nano::open_block open1 (send1.hash (), nano::genesis_account, destination.pub, destination.prv, destination.pub, *pool.generate (destination.pub)); ASSERT_EQ (nano::process_result::unreceivable, ledger.process (transaction, open1).code); nano::state_block epoch4 (destination.pub, 0, 0, 0, ledger.link (nano::epoch::epoch_1), nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (destination.pub)); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, epoch4).code); nano::state_block epoch5 (destination.pub, epoch4.hash (), nano::genesis_account, 0, ledger.link (nano::epoch::epoch_2), nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (epoch4.hash ())); ASSERT_EQ (nano::process_result::representative_mismatch, ledger.process (transaction, epoch5).code); nano::state_block epoch6 (destination.pub, epoch4.hash (), 0, 0, ledger.link (nano::epoch::epoch_2), nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (epoch4.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, epoch6).code); nano::receive_block receive1 (epoch6.hash (), send1.hash (), destination.prv, destination.pub, *pool.generate (epoch6.hash ())); ASSERT_EQ (nano::process_result::block_position, ledger.process (transaction, receive1).code); nano::state_block receive2 (destination.pub, epoch6.hash (), destination.pub, nano::Gxrb_ratio, send1.hash (), destination.prv, destination.pub, *pool.generate (epoch6.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, receive2).code); ASSERT_EQ (0, ledger.balance (transaction, epoch6.hash ())); ASSERT_EQ (nano::Gxrb_ratio, ledger.balance (transaction, receive2.hash ())); ASSERT_EQ (nano::Gxrb_ratio, ledger.amount (transaction, receive2.hash ())); ASSERT_EQ (nano::genesis_amount - nano::Gxrb_ratio, ledger.weight (nano::genesis_account)); ASSERT_EQ (nano::Gxrb_ratio, ledger.weight (destination.pub)); } TEST (ledger, epoch_blocks_receive_upgrade) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_TRUE (!store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::keypair destination; nano::state_block send1 (nano::genesis_account, genesis.hash (), nano::genesis_account, nano::genesis_amount - nano::Gxrb_ratio, destination.pub, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, send1).code); nano::state_block epoch1 (nano::genesis_account, send1.hash (), nano::genesis_account, nano::genesis_amount - nano::Gxrb_ratio, ledger.link (nano::epoch::epoch_1), nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (send1.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, epoch1).code); nano::state_block send2 (nano::genesis_account, epoch1.hash (), nano::genesis_account, nano::genesis_amount - nano::Gxrb_ratio * 2, destination.pub, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (epoch1.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, send2).code); nano::open_block open1 (send1.hash (), destination.pub, destination.pub, destination.prv, destination.pub, *pool.generate (destination.pub)); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, open1).code); nano::receive_block receive1 (open1.hash (), send2.hash (), destination.prv, destination.pub, *pool.generate (open1.hash ())); ASSERT_EQ (nano::process_result::unreceivable, ledger.process (transaction, receive1).code); nano::state_block receive2 (destination.pub, open1.hash (), destination.pub, nano::Gxrb_ratio * 2, send2.hash (), destination.prv, destination.pub, *pool.generate (open1.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, receive2).code); nano::account_info destination_info; ASSERT_FALSE (ledger.store.account_get (transaction, destination.pub, destination_info)); ASSERT_EQ (destination_info.epoch (), nano::epoch::epoch_1); ASSERT_FALSE (ledger.rollback (transaction, receive2.hash ())); ASSERT_FALSE (ledger.store.account_get (transaction, destination.pub, destination_info)); ASSERT_EQ (destination_info.epoch (), nano::epoch::epoch_0); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, receive2).code); ASSERT_FALSE (ledger.store.account_get (transaction, destination.pub, destination_info)); ASSERT_EQ (destination_info.epoch (), nano::epoch::epoch_1); nano::keypair destination2; nano::state_block send3 (destination.pub, receive2.hash (), destination.pub, nano::Gxrb_ratio, destination2.pub, destination.prv, destination.pub, *pool.generate (receive2.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, send3).code); nano::open_block open2 (send3.hash (), destination2.pub, destination2.pub, destination2.prv, destination2.pub, *pool.generate (destination2.pub)); ASSERT_EQ (nano::process_result::unreceivable, ledger.process (transaction, open2).code); // Upgrade to epoch 2 and send to destination. Try to create an open block from an epoch 2 source block. nano::keypair destination3; nano::state_block epoch2 (nano::genesis_account, send2.hash (), nano::genesis_account, nano::genesis_amount - nano::Gxrb_ratio * 2, ledger.link (nano::epoch::epoch_2), nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (send2.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, epoch2).code); nano::state_block send4 (nano::genesis_account, epoch2.hash (), nano::genesis_account, nano::genesis_amount - nano::Gxrb_ratio * 3, destination3.pub, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (epoch2.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, send4).code); nano::open_block open3 (send4.hash (), destination3.pub, destination3.pub, destination3.prv, destination3.pub, *pool.generate (destination3.pub)); ASSERT_EQ (nano::process_result::unreceivable, ledger.process (transaction, open3).code); // Send it to an epoch 1 account nano::state_block send5 (nano::genesis_account, send4.hash (), nano::genesis_account, nano::genesis_amount - nano::Gxrb_ratio * 4, destination.pub, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (send4.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, send5).code); ASSERT_FALSE (ledger.store.account_get (transaction, destination.pub, destination_info)); ASSERT_EQ (destination_info.epoch (), nano::epoch::epoch_1); nano::state_block receive3 (destination.pub, send3.hash (), destination.pub, nano::Gxrb_ratio * 2, send5.hash (), destination.prv, destination.pub, *pool.generate (send3.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, receive3).code); ASSERT_FALSE (ledger.store.account_get (transaction, destination.pub, destination_info)); ASSERT_EQ (destination_info.epoch (), nano::epoch::epoch_2); // Upgrade an unopened account straight to epoch 2 nano::keypair destination4; nano::state_block send6 (nano::genesis_account, send5.hash (), nano::genesis_account, nano::genesis_amount - nano::Gxrb_ratio * 5, destination4.pub, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (send5.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, send6).code); nano::state_block epoch4 (destination4.pub, 0, 0, 0, ledger.link (nano::epoch::epoch_2), nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (destination4.pub)); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, epoch4).code); } TEST (ledger, epoch_blocks_fork) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_TRUE (!store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::keypair destination; nano::send_block send1 (genesis.hash (), nano::account (0), nano::genesis_amount, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, send1).code); nano::state_block epoch1 (nano::genesis_account, genesis.hash (), nano::genesis_account, nano::genesis_amount, ledger.link (nano::epoch::epoch_1), nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); ASSERT_EQ (nano::process_result::fork, ledger.process (transaction, epoch1).code); nano::state_block epoch2 (nano::genesis_account, genesis.hash (), nano::genesis_account, nano::genesis_amount, ledger.link (nano::epoch::epoch_2), nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); ASSERT_EQ (nano::process_result::fork, ledger.process (transaction, epoch2).code); nano::state_block epoch3 (nano::genesis_account, send1.hash (), nano::genesis_account, nano::genesis_amount, ledger.link (nano::epoch::epoch_1), nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (send1.hash ())); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, epoch3).code); nano::state_block epoch4 (nano::genesis_account, send1.hash (), nano::genesis_account, nano::genesis_amount, ledger.link (nano::epoch::epoch_2), nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (send1.hash ())); ASSERT_EQ (nano::process_result::fork, ledger.process (transaction, epoch2).code); } TEST (ledger, successor_epoch) { nano::system system (24000, 1); nano::keypair key1; nano::genesis genesis; nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::send_block send1 (genesis.hash (), key1.pub, nano::genesis_amount - 1, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); nano::state_block open (key1.pub, 0, key1.pub, 1, send1.hash (), key1.prv, key1.pub, *pool.generate (key1.pub)); nano::state_block change (key1.pub, open.hash (), key1.pub, 1, 0, key1.prv, key1.pub, *pool.generate (open.hash ())); auto open_hash = open.hash (); nano::state_block epoch_open (reinterpret_cast<nano::account const &> (open_hash), 0, 0, 0, system.nodes[0]->ledger.link (nano::epoch::epoch_1), nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (open.hash ())); auto transaction (system.nodes[0]->store.tx_begin_write ()); ASSERT_EQ (nano::process_result::progress, system.nodes[0]->ledger.process (transaction, send1).code); ASSERT_EQ (nano::process_result::progress, system.nodes[0]->ledger.process (transaction, open).code); ASSERT_EQ (nano::process_result::progress, system.nodes[0]->ledger.process (transaction, change).code); ASSERT_EQ (nano::process_result::progress, system.nodes[0]->ledger.process (transaction, epoch_open).code); ASSERT_EQ (change, *system.nodes[0]->ledger.successor (transaction, change.qualified_root ())); ASSERT_EQ (epoch_open, *system.nodes[0]->ledger.successor (transaction, epoch_open.qualified_root ())); } TEST (ledger, block_hash_account_conflict) { nano::block_builder builder; nano::system system (24000, 1); auto & node1 (*system.nodes[0]); nano::genesis genesis; nano::keypair key1; nano::keypair key2; nano::work_pool pool (std::numeric_limits<unsigned>::max ()); /* * Generate a send block whose destination is a block hash already * in the ledger and not an account */ std::shared_ptr<nano::state_block> send1 = builder.state () .account (nano::genesis_account) .previous (genesis.hash ()) .representative (nano::genesis_account) .balance (nano::genesis_amount - 100) .link (key1.pub) .sign (nano::test_genesis_key.prv, nano::test_genesis_key.pub) .work (*pool.generate (genesis.hash ())) .build (); std::shared_ptr<nano::state_block> receive1 = builder.state () .account (key1.pub) .previous (0) .representative (nano::genesis_account) .balance (100) .link (send1->hash ()) .sign (key1.prv, key1.pub) .work (*pool.generate (key1.pub)) .build (); /* * Note that the below link is a block hash when this is intended * to represent a send state block. This can generally never be * received , except by epoch blocks, which can sign an open block * for arbitrary accounts. */ std::shared_ptr<nano::state_block> send2 = builder.state () .account (key1.pub) .previous (receive1->hash ()) .representative (nano::genesis_account) .balance (90) .link (receive1->hash ()) .sign (key1.prv, key1.pub) .work (*pool.generate (receive1->hash ())) .build (); /* * Generate an epoch open for the account with the same value as the block hash */ auto receive1_hash = receive1->hash (); std::shared_ptr<nano::state_block> open_epoch1 = builder.state () .account (reinterpret_cast<nano::account const &> (receive1_hash)) .previous (0) .representative (0) .balance (0) .link (node1.ledger.link (nano::epoch::epoch_1)) .sign (nano::test_genesis_key.prv, nano::test_genesis_key.pub) .work (*pool.generate (receive1->hash ())) .build (); node1.work_generate_blocking (*send1); node1.work_generate_blocking (*receive1); node1.work_generate_blocking (*send2); node1.work_generate_blocking (*open_epoch1); auto transaction (node1.store.tx_begin_write ()); ASSERT_EQ (nano::process_result::progress, node1.ledger.process (transaction, *send1).code); ASSERT_EQ (nano::process_result::progress, node1.ledger.process (transaction, *receive1).code); ASSERT_EQ (nano::process_result::progress, node1.ledger.process (transaction, *send2).code); ASSERT_EQ (nano::process_result::progress, node1.ledger.process (transaction, *open_epoch1).code); node1.active.start (send1); node1.active.start (receive1); node1.active.start (send2); node1.active.start (open_epoch1); auto votes1 (node1.active.roots.find (send1->qualified_root ())->election); auto votes2 (node1.active.roots.find (receive1->qualified_root ())->election); auto votes3 (node1.active.roots.find (send2->qualified_root ())->election); auto votes4 (node1.active.roots.find (open_epoch1->qualified_root ())->election); auto winner1 (*votes1->tally ().begin ()); auto winner2 (*votes2->tally ().begin ()); auto winner3 (*votes3->tally ().begin ()); auto winner4 (*votes4->tally ().begin ()); ASSERT_EQ (*send1, *winner1.second); ASSERT_EQ (*receive1, *winner2.second); ASSERT_EQ (*send2, *winner3.second); ASSERT_EQ (*open_epoch1, *winner4.second); } TEST (ledger, could_fit) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_TRUE (!store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); nano::genesis genesis; auto transaction (store->tx_begin_write ()); store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::keypair destination; // Test legacy and state change blocks could_fit nano::change_block change1 (genesis.hash (), nano::genesis_account, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); nano::state_block change2 (nano::genesis_account, genesis.hash (), nano::genesis_account, nano::genesis_amount, 0, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (genesis.hash ())); ASSERT_TRUE (ledger.could_fit (transaction, change1)); ASSERT_TRUE (ledger.could_fit (transaction, change2)); // Test legacy and state send nano::keypair key1; nano::send_block send1 (change1.hash (), key1.pub, nano::genesis_amount - 1, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (change1.hash ())); nano::state_block send2 (nano::genesis_account, change1.hash (), nano::genesis_account, nano::genesis_amount - 1, key1.pub, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (change1.hash ())); ASSERT_FALSE (ledger.could_fit (transaction, send1)); ASSERT_FALSE (ledger.could_fit (transaction, send2)); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, change1).code); ASSERT_TRUE (ledger.could_fit (transaction, change1)); ASSERT_TRUE (ledger.could_fit (transaction, change2)); ASSERT_TRUE (ledger.could_fit (transaction, send1)); ASSERT_TRUE (ledger.could_fit (transaction, send2)); // Test legacy and state open nano::open_block open1 (send2.hash (), nano::genesis_account, key1.pub, key1.prv, key1.pub, *pool.generate (key1.pub)); nano::state_block open2 (key1.pub, 0, nano::genesis_account, 1, send2.hash (), key1.prv, key1.pub, *pool.generate (key1.pub)); ASSERT_FALSE (ledger.could_fit (transaction, open1)); ASSERT_FALSE (ledger.could_fit (transaction, open2)); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, send2).code); ASSERT_TRUE (ledger.could_fit (transaction, send1)); ASSERT_TRUE (ledger.could_fit (transaction, send2)); ASSERT_TRUE (ledger.could_fit (transaction, open1)); ASSERT_TRUE (ledger.could_fit (transaction, open2)); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, open1).code); ASSERT_TRUE (ledger.could_fit (transaction, open1)); ASSERT_TRUE (ledger.could_fit (transaction, open2)); // Create another send to receive nano::state_block send3 (nano::genesis_account, send2.hash (), nano::genesis_account, nano::genesis_amount - 2, key1.pub, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (send2.hash ())); // Test legacy and state receive nano::receive_block receive1 (open1.hash (), send3.hash (), key1.prv, key1.pub, *pool.generate (open1.hash ())); nano::state_block receive2 (key1.pub, open1.hash (), nano::genesis_account, 2, send3.hash (), key1.prv, key1.pub, *pool.generate (open1.hash ())); ASSERT_FALSE (ledger.could_fit (transaction, receive1)); ASSERT_FALSE (ledger.could_fit (transaction, receive2)); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, send3).code); ASSERT_TRUE (ledger.could_fit (transaction, receive1)); ASSERT_TRUE (ledger.could_fit (transaction, receive2)); // Test epoch (state) nano::state_block epoch1 (key1.pub, receive1.hash (), nano::genesis_account, 2, ledger.link (nano::epoch::epoch_1), nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (receive1.hash ())); ASSERT_FALSE (ledger.could_fit (transaction, epoch1)); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, receive1).code); ASSERT_TRUE (ledger.could_fit (transaction, receive1)); ASSERT_TRUE (ledger.could_fit (transaction, receive2)); ASSERT_TRUE (ledger.could_fit (transaction, epoch1)); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, epoch1).code); ASSERT_TRUE (ledger.could_fit (transaction, epoch1)); } TEST (ledger, unchecked_epoch) { nano::system system (24000, 1); auto & node1 (*system.nodes[0]); nano::genesis genesis; nano::keypair destination; auto send1 (std::make_shared<nano::state_block> (nano::genesis_account, genesis.hash (), nano::genesis_account, nano::genesis_amount - nano::Gxrb_ratio, destination.pub, nano::test_genesis_key.prv, nano::test_genesis_key.pub, 0)); node1.work_generate_blocking (*send1); auto open1 (std::make_shared<nano::state_block> (destination.pub, 0, destination.pub, nano::Gxrb_ratio, send1->hash (), destination.prv, destination.pub, 0)); node1.work_generate_blocking (*open1); auto epoch1 (std::make_shared<nano::state_block> (destination.pub, open1->hash (), destination.pub, nano::Gxrb_ratio, node1.ledger.link (nano::epoch::epoch_1), nano::test_genesis_key.prv, nano::test_genesis_key.pub, 0)); node1.work_generate_blocking (*epoch1); node1.block_processor.add (epoch1); node1.block_processor.flush (); { auto transaction (node1.store.tx_begin_read ()); auto unchecked_count (node1.store.unchecked_count (transaction)); ASSERT_EQ (unchecked_count, 1); auto blocks (node1.store.unchecked_get (transaction, epoch1->previous ())); ASSERT_EQ (blocks.size (), 1); ASSERT_EQ (blocks[0].verified, nano::signature_verification::valid_epoch); } node1.block_processor.add (send1); node1.block_processor.add (open1); node1.block_processor.flush (); { auto transaction (node1.store.tx_begin_read ()); ASSERT_TRUE (node1.store.block_exists (transaction, epoch1->hash ())); auto unchecked_count (node1.store.unchecked_count (transaction)); ASSERT_EQ (unchecked_count, 0); nano::account_info info; ASSERT_FALSE (node1.store.account_get (transaction, destination.pub, info)); ASSERT_EQ (info.epoch (), nano::epoch::epoch_1); } } TEST (ledger, unchecked_epoch_invalid) { nano::system system; nano::node_config node_config (24000, system.logging); node_config.frontiers_confirmation = nano::frontiers_confirmation_mode::disabled; auto & node1 (*system.add_node (node_config)); nano::genesis genesis; nano::keypair destination; auto send1 (std::make_shared<nano::state_block> (nano::genesis_account, genesis.hash (), nano::genesis_account, nano::genesis_amount - nano::Gxrb_ratio, destination.pub, nano::test_genesis_key.prv, nano::test_genesis_key.pub, 0)); node1.work_generate_blocking (*send1); auto open1 (std::make_shared<nano::state_block> (destination.pub, 0, destination.pub, nano::Gxrb_ratio, send1->hash (), destination.prv, destination.pub, 0)); node1.work_generate_blocking (*open1); // Epoch block with account own signature auto epoch1 (std::make_shared<nano::state_block> (destination.pub, open1->hash (), destination.pub, nano::Gxrb_ratio, node1.ledger.link (nano::epoch::epoch_1), destination.prv, destination.pub, 0)); node1.work_generate_blocking (*epoch1); // Pseudo epoch block (send subtype, destination - epoch link) auto epoch2 (std::make_shared<nano::state_block> (destination.pub, open1->hash (), destination.pub, nano::Gxrb_ratio - 1, node1.ledger.link (nano::epoch::epoch_1), destination.prv, destination.pub, 0)); node1.work_generate_blocking (*epoch2); node1.block_processor.add (epoch1); node1.block_processor.add (epoch2); node1.block_processor.flush (); { auto transaction (node1.store.tx_begin_read ()); auto unchecked_count (node1.store.unchecked_count (transaction)); ASSERT_EQ (unchecked_count, 2); auto blocks (node1.store.unchecked_get (transaction, epoch1->previous ())); ASSERT_EQ (blocks.size (), 2); ASSERT_EQ (blocks[0].verified, nano::signature_verification::valid); ASSERT_EQ (blocks[1].verified, nano::signature_verification::valid); } node1.block_processor.add (send1); node1.block_processor.add (open1); node1.block_processor.flush (); { auto transaction (node1.store.tx_begin_read ()); ASSERT_FALSE (node1.store.block_exists (transaction, epoch1->hash ())); ASSERT_TRUE (node1.store.block_exists (transaction, epoch2->hash ())); ASSERT_TRUE (node1.active.empty ()); auto unchecked_count (node1.store.unchecked_count (transaction)); ASSERT_EQ (unchecked_count, 0); nano::account_info info; ASSERT_FALSE (node1.store.account_get (transaction, destination.pub, info)); ASSERT_NE (info.epoch (), nano::epoch::epoch_1); } } TEST (ledger, unchecked_open) { nano::system system (24000, 1); auto & node1 (*system.nodes[0]); nano::genesis genesis; nano::keypair destination; auto send1 (std::make_shared<nano::state_block> (nano::genesis_account, genesis.hash (), nano::genesis_account, nano::genesis_amount - nano::Gxrb_ratio, destination.pub, nano::test_genesis_key.prv, nano::test_genesis_key.pub, 0)); node1.work_generate_blocking (*send1); auto open1 (std::make_shared<nano::open_block> (send1->hash (), destination.pub, destination.pub, destination.prv, destination.pub, 0)); node1.work_generate_blocking (*open1); // Invalid signature for open block auto open2 (std::make_shared<nano::open_block> (send1->hash (), nano::test_genesis_key.pub, destination.pub, destination.prv, destination.pub, 0)); node1.work_generate_blocking (*open2); open2->signature.bytes[0] ^= 1; node1.block_processor.add (open1); node1.block_processor.add (open2); node1.block_processor.flush (); { auto transaction (node1.store.tx_begin_read ()); auto unchecked_count (node1.store.unchecked_count (transaction)); ASSERT_EQ (unchecked_count, 1); auto blocks (node1.store.unchecked_get (transaction, open1->source ())); ASSERT_EQ (blocks.size (), 1); ASSERT_EQ (blocks[0].verified, nano::signature_verification::valid); } node1.block_processor.add (send1); node1.block_processor.flush (); { auto transaction (node1.store.tx_begin_read ()); ASSERT_TRUE (node1.store.block_exists (transaction, open1->hash ())); auto unchecked_count (node1.store.unchecked_count (transaction)); ASSERT_EQ (unchecked_count, 0); } } TEST (ledger, unchecked_receive) { nano::system system (24000, 1); auto & node1 (*system.nodes[0]); nano::genesis genesis; nano::keypair destination; auto send1 (std::make_shared<nano::state_block> (nano::genesis_account, genesis.hash (), nano::genesis_account, nano::genesis_amount - nano::Gxrb_ratio, destination.pub, nano::test_genesis_key.prv, nano::test_genesis_key.pub, 0)); node1.work_generate_blocking (*send1); auto send2 (std::make_shared<nano::state_block> (nano::genesis_account, send1->hash (), nano::genesis_account, nano::genesis_amount - 2 * nano::Gxrb_ratio, destination.pub, nano::test_genesis_key.prv, nano::test_genesis_key.pub, 0)); node1.work_generate_blocking (*send2); auto open1 (std::make_shared<nano::open_block> (send1->hash (), destination.pub, destination.pub, destination.prv, destination.pub, 0)); node1.work_generate_blocking (*open1); auto receive1 (std::make_shared<nano::receive_block> (open1->hash (), send2->hash (), destination.prv, destination.pub, 0)); node1.work_generate_blocking (*receive1); node1.block_processor.add (send1); node1.block_processor.add (receive1); node1.block_processor.flush (); // Previous block for receive1 is unknown, signature cannot be validated { auto transaction (node1.store.tx_begin_read ()); auto unchecked_count (node1.store.unchecked_count (transaction)); ASSERT_EQ (unchecked_count, 1); auto blocks (node1.store.unchecked_get (transaction, receive1->previous ())); ASSERT_EQ (blocks.size (), 1); ASSERT_EQ (blocks[0].verified, nano::signature_verification::unknown); } node1.block_processor.add (open1); node1.block_processor.flush (); // Previous block for receive1 is known, signature was validated { auto transaction (node1.store.tx_begin_read ()); auto unchecked_count (node1.store.unchecked_count (transaction)); ASSERT_EQ (unchecked_count, 1); auto blocks (node1.store.unchecked_get (transaction, receive1->source ())); ASSERT_EQ (blocks.size (), 1); ASSERT_EQ (blocks[0].verified, nano::signature_verification::valid); } node1.block_processor.add (send2); node1.block_processor.flush (); { auto transaction (node1.store.tx_begin_read ()); ASSERT_TRUE (node1.store.block_exists (transaction, receive1->hash ())); auto unchecked_count (node1.store.unchecked_count (transaction)); ASSERT_EQ (unchecked_count, 0); } } TEST (ledger, confirmation_height_not_updated) { nano::logger_mt logger; auto store = nano::make_store (logger, nano::unique_path ()); ASSERT_TRUE (!store->init_error ()); nano::stat stats; nano::ledger ledger (*store, stats); auto transaction (store->tx_begin_write ()); nano::genesis genesis; store->initialize (transaction, genesis, ledger.rep_weights, ledger.cemented_count, ledger.block_count_cache); nano::work_pool pool (std::numeric_limits<unsigned>::max ()); nano::account_info account_info; ASSERT_FALSE (store->account_get (transaction, nano::test_genesis_key.pub, account_info)); nano::keypair key; nano::send_block send1 (account_info.head, key.pub, 50, nano::test_genesis_key.prv, nano::test_genesis_key.pub, *pool.generate (account_info.head)); uint64_t confirmation_height; ASSERT_FALSE (store->confirmation_height_get (transaction, nano::genesis_account, confirmation_height)); ASSERT_EQ (1, confirmation_height); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, send1).code); ASSERT_FALSE (store->confirmation_height_get (transaction, nano::genesis_account, confirmation_height)); ASSERT_EQ (1, confirmation_height); nano::open_block open1 (send1.hash (), nano::genesis_account, key.pub, key.prv, key.pub, *pool.generate (key.pub)); ASSERT_EQ (nano::process_result::progress, ledger.process (transaction, open1).code); ASSERT_FALSE (store->confirmation_height_get (transaction, key.pub, confirmation_height)); ASSERT_EQ (0, confirmation_height); } TEST (ledger, zero_rep) { nano::system system (24000, 1); nano::genesis genesis; nano::block_builder builder; auto block1 = builder.state () .account (nano::test_genesis_key.pub) .previous (genesis.hash ()) .representative (0) .balance (nano::genesis_amount) .link (0) .sign (nano::test_genesis_key.prv, nano::test_genesis_key.pub) .work (*system.work.generate (genesis.hash ())) .build (); auto transaction (system.nodes[0]->store.tx_begin_write ()); ASSERT_EQ (nano::process_result::progress, system.nodes[0]->ledger.process (transaction, *block1).code); ASSERT_EQ (0, system.nodes[0]->ledger.rep_weights.representation_get (nano::test_genesis_key.pub)); ASSERT_EQ (nano::genesis_amount, system.nodes[0]->ledger.rep_weights.representation_get (0)); auto block2 = builder.state () .account (nano::test_genesis_key.pub) .previous (block1->hash ()) .representative (nano::test_genesis_key.pub) .balance (nano::genesis_amount) .link (0) .sign (nano::test_genesis_key.prv, nano::test_genesis_key.pub) .work (*system.work.generate (block1->hash ())) .build (); ASSERT_EQ (nano::process_result::progress, system.nodes[0]->ledger.process (transaction, *block2).code); ASSERT_EQ (nano::genesis_amount, system.nodes[0]->ledger.rep_weights.representation_get (nano::test_genesis_key.pub)); ASSERT_EQ (0, system.nodes[0]->ledger.rep_weights.representation_get (0)); }
58.120948
272
0.743573
[ "vector" ]
884609e0e14f99a85473c3883191c2ddd5fd420d
2,339
cpp
C++
Demos/full_scene/ExampleState.cpp
Odin366/Iceberg3D
f3109e58f3607869b0f28c9d418f2d2b11b3cc72
[ "MIT" ]
null
null
null
Demos/full_scene/ExampleState.cpp
Odin366/Iceberg3D
f3109e58f3607869b0f28c9d418f2d2b11b3cc72
[ "MIT" ]
null
null
null
Demos/full_scene/ExampleState.cpp
Odin366/Iceberg3D
f3109e58f3607869b0f28c9d418f2d2b11b3cc72
[ "MIT" ]
null
null
null
#include "ExampleState.h" #include "GlobalIncludes.h" using namespace iceberg; void ExampleState::pause() {} void ExampleState::resume() {} void ExampleState::finalize() {} void ExampleState::initialize() { // Initialize resources model = std::make_shared<Model>("assets/deadpool/deadpool.obj"); modelProgram = std::make_shared<ShaderProgram>(); modelProgram->create_program(); modelProgram->add_shader_from_file("shaders/modelVert.glsl", GL_VERTEX_SHADER); modelProgram->add_shader_from_file("shaders/modelFrag.glsl", GL_FRAGMENT_SHADER); modelProgram->link_program(); camera = std::make_shared<Camera>(game_, glm::vec3(12.0, 14.0, 30.0), glm::vec3(0), 100.0); camera->enable_input(); SkyboxParameters snowySkybox; snowySkybox.right = "assets/ame_powder/powderpeak_rt.tga"; snowySkybox.left = "assets/ame_powder/powderpeak_lf.tga"; snowySkybox.top = "assets/ame_powder/powderpeak_up.tga"; snowySkybox.bottom = "assets/ame_powder/powderpeak_dn.tga"; snowySkybox.front = "assets/ame_powder/powderpeak_ft.tga"; snowySkybox.back = "assets/ame_powder/powderpeak_bk.tga"; skybox = std::make_shared<Skybox>(snowySkybox); textManager = std::make_shared<TextManager>(game_); textManager->load_font("fonts/inconsolata.ttf", 24); angle = 0.0f; } void ExampleState::update() { angle += game_->delta_time() * float(glm::pi<float>()); camera->update(game_); } void ExampleState::draw() { glEnable(GL_CULL_FACE); glCullFace(GL_BACK); modelProgram->use(); for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { // TODO: Instanced Rendering model->transform()->translate(glm::mat4(1.0f), glm::vec3(8.0f * i, 8.0f * j, 0.0f)); model->transform()->rotate(angle, glm::vec3(0.0f, 1.0f, 0.0f)); model->transform()->scale(glm::vec3(0.02f, 0.02f, 0.02f)); glm::mat4 mvp = camera->make_mvp(model->transform()->model_matrix()); modelProgram->set_uniform("mvpMatrix", &mvp); model->draw(modelProgram.get()); } } glDisable(GL_CULL_FACE); skybox->draw(camera->projection_matrix(), camera->view_matrix()); textManager->render_text("Welcome to the Iceberg3D Game Engine!", 30, 30, 1.0f, glm::vec3(0.0f, 1.0f, 0.0f)); }
33.414286
113
0.659684
[ "model", "transform" ]
88476316fbfac9f92d37ad54cf23884e08f7b815
39,018
cc
C++
src/content/renderer/media/user_media_client_impl_unittest.cc
yang-guangliang/osv-free
b81fee48bc8898fdc641a2e3c227957ed7e6445e
[ "Apache-2.0" ]
2
2021-05-24T13:52:28.000Z
2021-05-24T13:53:10.000Z
src/content/renderer/media/user_media_client_impl_unittest.cc
yang-guangliang/osv-free
b81fee48bc8898fdc641a2e3c227957ed7e6445e
[ "Apache-2.0" ]
null
null
null
src/content/renderer/media/user_media_client_impl_unittest.cc
yang-guangliang/osv-free
b81fee48bc8898fdc641a2e3c227957ed7e6445e
[ "Apache-2.0" ]
3
2018-03-12T07:58:10.000Z
2019-08-31T04:53:58.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/renderer/media/user_media_client_impl.h" #include <stddef.h> #include <memory> #include <utility> #include <vector> #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/strings/utf_string_conversions.h" #include "content/child/child_process.h" #include "content/common/media/media_devices.h" #include "content/renderer/media/media_stream.h" #include "content/renderer/media/media_stream_audio_source.h" #include "content/renderer/media/media_stream_track.h" #include "content/renderer/media/mock_constraint_factory.h" #include "content/renderer/media/mock_media_stream_dispatcher.h" #include "content/renderer/media/mock_media_stream_video_source.h" #include "content/renderer/media/webrtc/mock_peer_connection_dependency_factory.h" #include "mojo/public/cpp/bindings/binding.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/WebKit/public/platform/WebMediaDeviceInfo.h" #include "third_party/WebKit/public/platform/WebMediaStream.h" #include "third_party/WebKit/public/platform/WebMediaStreamSource.h" #include "third_party/WebKit/public/platform/WebMediaStreamTrack.h" #include "third_party/WebKit/public/platform/WebString.h" #include "third_party/WebKit/public/platform/WebVector.h" #include "third_party/WebKit/public/web/WebHeap.h" using testing::_; namespace content { blink::WebMediaConstraints CreateDefaultConstraints() { MockConstraintFactory factory; factory.AddAdvanced(); return factory.CreateWebMediaConstraints(); } blink::WebMediaConstraints CreateDeviceConstraints( const char* basic_exact_value, const char* basic_ideal_value = nullptr, const char* advanced_exact_value = nullptr) { MockConstraintFactory factory; blink::WebMediaTrackConstraintSet basic; if (basic_exact_value) { factory.basic().device_id.SetExact( blink::WebString::FromUTF8(basic_exact_value)); } if (basic_ideal_value) { blink::WebString value = blink::WebString::FromUTF8(basic_ideal_value); factory.basic().device_id.SetIdeal( blink::WebVector<blink::WebString>(&value, 1)); } auto& advanced = factory.AddAdvanced(); if (advanced_exact_value) { blink::WebString value = blink::WebString::FromUTF8(advanced_exact_value); advanced.device_id.SetExact(value); } return factory.CreateWebMediaConstraints(); } blink::WebMediaConstraints CreateFacingModeConstraints( const char* basic_exact_value, const char* basic_ideal_value = nullptr, const char* advanced_exact_value = nullptr) { MockConstraintFactory factory; if (basic_exact_value) { factory.basic().facing_mode.SetExact( blink::WebString::FromUTF8(basic_exact_value)); } if (basic_ideal_value) { blink::WebString value = blink::WebString::FromUTF8(basic_ideal_value); factory.basic().device_id.SetIdeal( blink::WebVector<blink::WebString>(&value, 1)); } auto& advanced = factory.AddAdvanced(); if (advanced_exact_value) { blink::WebString value = blink::WebString::FromUTF8(advanced_exact_value); advanced.device_id.SetExact(value); } return factory.CreateWebMediaConstraints(); } class MockMediaStreamVideoCapturerSource : public MockMediaStreamVideoSource { public: MockMediaStreamVideoCapturerSource( const StreamDeviceInfo& device, const SourceStoppedCallback& stop_callback, PeerConnectionDependencyFactory* factory) : MockMediaStreamVideoSource(false) { SetDeviceInfo(device); SetStopCallback(stop_callback); } }; const char kInvalidDeviceId[] = "invalid"; const char kFakeAudioInputDeviceId1[] = "fake_audio_input 1"; const char kFakeAudioInputDeviceId2[] = "fake_audio_input 2"; const char kFakeVideoInputDeviceId1[] = "fake_video_input 1"; const char kFakeVideoInputDeviceId2[] = "fake_video_input 2"; const char kFakeAudioOutputDeviceId1[] = "fake_audio_output 1"; class MockMediaDevicesDispatcherHost : public ::mojom::MediaDevicesDispatcherHost { public: MockMediaDevicesDispatcherHost() {} void EnumerateDevices(bool request_audio_input, bool request_video_input, bool request_audio_output, EnumerateDevicesCallback callback) override { std::vector<std::vector<MediaDeviceInfo>> result(NUM_MEDIA_DEVICE_TYPES); if (request_audio_input) { result[MEDIA_DEVICE_TYPE_AUDIO_INPUT].push_back(MediaDeviceInfo( kFakeAudioInputDeviceId1, "Fake Audio Input 1", "fake_group 1")); result[MEDIA_DEVICE_TYPE_AUDIO_INPUT].push_back(MediaDeviceInfo( kFakeAudioInputDeviceId2, "Fake Audio Input 2", "fake_group 2")); } if (request_video_input) { result[MEDIA_DEVICE_TYPE_VIDEO_INPUT].push_back( MediaDeviceInfo(kFakeVideoInputDeviceId1, "Fake Video Input 1", "")); result[MEDIA_DEVICE_TYPE_VIDEO_INPUT].push_back( MediaDeviceInfo(kFakeVideoInputDeviceId2, "Fake Video Input 2", "")); } if (request_audio_output) { result[MEDIA_DEVICE_TYPE_AUDIO_OUTPUT].push_back(MediaDeviceInfo( kFakeAudioOutputDeviceId1, "Fake Audio Input 1", "fake_group 1")); } std::move(callback).Run(result); } void GetVideoInputCapabilities( GetVideoInputCapabilitiesCallback client_callback) override { ::mojom::VideoInputDeviceCapabilitiesPtr device = ::mojom::VideoInputDeviceCapabilities::New(); device->device_id = kFakeVideoInputDeviceId1; device->facing_mode = ::mojom::FacingMode::USER; device->formats.push_back(media::VideoCaptureFormat( gfx::Size(640, 480), 30.0f, media::PIXEL_FORMAT_I420)); std::vector<::mojom::VideoInputDeviceCapabilitiesPtr> result; result.push_back(std::move(device)); device = ::mojom::VideoInputDeviceCapabilities::New(); device->device_id = kFakeVideoInputDeviceId2; device->facing_mode = ::mojom::FacingMode::ENVIRONMENT; device->formats.push_back(media::VideoCaptureFormat( gfx::Size(640, 480), 30.0f, media::PIXEL_FORMAT_I420)); result.push_back(std::move(device)); std::move(client_callback).Run(std::move(result)); } void GetAudioInputCapabilities( GetAudioInputCapabilitiesCallback client_callback) override { NOTREACHED(); } MOCK_METHOD2(SubscribeDeviceChangeNotifications, void(MediaDeviceType type, uint32_t subscription_id)); MOCK_METHOD2(UnsubscribeDeviceChangeNotifications, void(MediaDeviceType type, uint32_t subscription_id)); }; class UserMediaClientImplUnderTest : public UserMediaClientImpl { public: enum RequestState { REQUEST_NOT_STARTED, REQUEST_NOT_COMPLETE, REQUEST_SUCCEEDED, REQUEST_FAILED, }; UserMediaClientImplUnderTest( PeerConnectionDependencyFactory* dependency_factory, std::unique_ptr<MediaStreamDispatcher> media_stream_dispatcher) : UserMediaClientImpl(nullptr, dependency_factory, std::move(media_stream_dispatcher), base::ThreadTaskRunnerHandle::Get()), state_(REQUEST_NOT_STARTED), result_(NUM_MEDIA_REQUEST_RESULTS), result_name_(""), factory_(dependency_factory), create_source_that_fails_(false), video_source_(nullptr) {} void RequestUserMediaForTest( const blink::WebUserMediaRequest& user_media_request) { state_ = REQUEST_NOT_COMPLETE; RequestUserMedia(user_media_request); base::RunLoop().RunUntilIdle(); } void RequestUserMediaForTest() { blink::WebUserMediaRequest user_media_request = blink::WebUserMediaRequest::CreateForTesting( CreateDefaultConstraints(), CreateDefaultConstraints()); RequestUserMediaForTest(user_media_request); } void RequestMediaDevicesForTest() { blink::WebMediaDevicesRequest media_devices_request; state_ = REQUEST_NOT_COMPLETE; RequestMediaDevices(media_devices_request); } void GetUserMediaRequestSucceeded( const blink::WebMediaStream& stream, blink::WebUserMediaRequest request_info) override { last_generated_stream_ = stream; state_ = REQUEST_SUCCEEDED; } void GetUserMediaRequestFailed( blink::WebUserMediaRequest request_info, content::MediaStreamRequestResult result, const blink::WebString& result_name) override { last_generated_stream_.Reset(); state_ = REQUEST_FAILED; result_ = result; result_name_ = result_name; } void EnumerateDevicesSucceded( blink::WebMediaDevicesRequest* request, blink::WebVector<blink::WebMediaDeviceInfo>& devices) override { state_ = REQUEST_SUCCEEDED; last_devices_ = devices; } void SetCreateSourceThatFails(bool should_fail) { create_source_that_fails_ = should_fail; } static void SignalSourceReady( const MediaStreamSource::ConstraintsCallback& source_ready, MediaStreamSource* source) { source_ready.Run(source, MEDIA_DEVICE_OK, ""); } MediaStreamAudioSource* CreateAudioSource( const StreamDeviceInfo& device, const blink::WebMediaConstraints& constraints, const MediaStreamSource::ConstraintsCallback& source_ready) override { MediaStreamAudioSource* source; if (create_source_that_fails_) { class FailedAtLifeAudioSource : public MediaStreamAudioSource { public: FailedAtLifeAudioSource() : MediaStreamAudioSource(true) {} ~FailedAtLifeAudioSource() override {} protected: bool EnsureSourceIsStarted() override { return false; } }; source = new FailedAtLifeAudioSource(); } else { source = new MediaStreamAudioSource(true); } source->SetDeviceInfo(device); if (!create_source_that_fails_) { // RunUntilIdle is required for this task to complete. base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&UserMediaClientImplUnderTest::SignalSourceReady, source_ready, source)); } return source; } MediaStreamVideoSource* CreateVideoSource( const StreamDeviceInfo& device, const MediaStreamSource::SourceStoppedCallback& stop_callback) override { video_source_ = new MockMediaStreamVideoCapturerSource(device, stop_callback, factory_); return video_source_; } const blink::WebMediaStream& last_generated_stream() { return last_generated_stream_; } const blink::WebVector<blink::WebMediaDeviceInfo>& last_devices() { return last_devices_; } void ClearLastGeneratedStream() { last_generated_stream_.Reset(); } MockMediaStreamVideoCapturerSource* last_created_video_source() const { return video_source_; } RequestState request_state() const { return state_; } content::MediaStreamRequestResult error_reason() const { return result_; } blink::WebString error_name() const { return result_name_; } // Access to the request queue for testing. bool UserMediaRequestHasAutomaticDeviceSelection() { base::Optional<bool> enabled = AutomaticOutputDeviceSelectionEnabledForCurrentRequest(); EXPECT_TRUE(enabled); return *enabled; } private: blink::WebMediaStream last_generated_stream_; RequestState state_; content::MediaStreamRequestResult result_; blink::WebString result_name_; blink::WebVector<blink::WebMediaDeviceInfo> last_devices_; PeerConnectionDependencyFactory* factory_; bool create_source_that_fails_; MockMediaStreamVideoCapturerSource* video_source_; }; class UserMediaClientImplTest : public ::testing::Test { public: UserMediaClientImplTest() : binding_user_media(&media_devices_dispatcher_), binding_event_dispatcher_(&media_devices_dispatcher_) {} void SetUp() override { // Create our test object. child_process_.reset(new ChildProcess()); dependency_factory_.reset(new MockPeerConnectionDependencyFactory()); ms_dispatcher_ = new MockMediaStreamDispatcher(); user_media_client_impl_.reset(new UserMediaClientImplUnderTest( dependency_factory_.get(), std::unique_ptr<MediaStreamDispatcher>(ms_dispatcher_))); ::mojom::MediaDevicesDispatcherHostPtr user_media_host_proxy; binding_user_media.Bind(mojo::MakeRequest(&user_media_host_proxy)); user_media_client_impl_->SetMediaDevicesDispatcherForTesting( std::move(user_media_host_proxy)); base::WeakPtr<MediaDevicesEventDispatcher> event_dispatcher = MediaDevicesEventDispatcher::GetForRenderFrame(nullptr); ::mojom::MediaDevicesDispatcherHostPtr event_dispatcher_host_proxy; binding_event_dispatcher_.Bind( mojo::MakeRequest(&event_dispatcher_host_proxy)); event_dispatcher->SetMediaDevicesDispatcherForTesting( std::move(event_dispatcher_host_proxy)); } void TearDown() override { MediaDevicesEventDispatcher::GetForRenderFrame(nullptr)->OnDestruct(); user_media_client_impl_.reset(); blink::WebHeap::CollectAllGarbageForTesting(); } void LoadNewDocumentInFrame() { user_media_client_impl_->WillCommitProvisionalLoad(); } blink::WebMediaStream RequestLocalMediaStream() { user_media_client_impl_->RequestUserMediaForTest(); FakeMediaStreamDispatcherRequestUserMediaComplete(); StartMockedVideoSource(); EXPECT_EQ(UserMediaClientImplUnderTest::REQUEST_SUCCEEDED, user_media_client_impl_->request_state()); blink::WebMediaStream desc = user_media_client_impl_->last_generated_stream(); content::MediaStream* native_stream = content::MediaStream::GetMediaStream(desc); if (!native_stream) { ADD_FAILURE(); return desc; } blink::WebVector<blink::WebMediaStreamTrack> audio_tracks; desc.AudioTracks(audio_tracks); blink::WebVector<blink::WebMediaStreamTrack> video_tracks; desc.VideoTracks(video_tracks); EXPECT_EQ(1u, audio_tracks.size()); EXPECT_EQ(1u, video_tracks.size()); EXPECT_NE(audio_tracks[0].Id(), video_tracks[0].Id()); return desc; } void FakeMediaStreamDispatcherRequestUserMediaComplete() { // Audio request ID is used as the shared request ID. user_media_client_impl_->OnStreamGenerated( ms_dispatcher_->audio_input_request_id(), ms_dispatcher_->stream_label(), ms_dispatcher_->audio_input_array(), ms_dispatcher_->video_array()); base::RunLoop().RunUntilIdle(); } void StartMockedVideoSource() { MockMediaStreamVideoCapturerSource* video_source = user_media_client_impl_->last_created_video_source(); if (video_source->SourceHasAttemptedToStart()) video_source->StartMockedSource(); } void FailToStartMockedVideoSource() { MockMediaStreamVideoCapturerSource* video_source = user_media_client_impl_->last_created_video_source(); if (video_source->SourceHasAttemptedToStart()) video_source->FailToStartMockedSource(); blink::WebHeap::CollectGarbageForTesting(); } bool AudioRequestHasAutomaticDeviceSelection( const blink::WebMediaConstraints& audio_constraints) { blink::WebMediaConstraints null_constraints; blink::WebUserMediaRequest request = blink::WebUserMediaRequest::CreateForTesting(audio_constraints, null_constraints); user_media_client_impl_->RequestUserMediaForTest(request); bool result = user_media_client_impl_->UserMediaRequestHasAutomaticDeviceSelection(); user_media_client_impl_->CancelUserMediaRequest(request); return result; } void TestValidRequestWithConstraints( const blink::WebMediaConstraints& audio_constraints, const blink::WebMediaConstraints& video_constraints, const std::string& expected_audio_device_id, const std::string& expected_video_device_id) { DCHECK(!audio_constraints.IsNull()); DCHECK(!video_constraints.IsNull()); blink::WebUserMediaRequest request = blink::WebUserMediaRequest::CreateForTesting(audio_constraints, video_constraints); user_media_client_impl_->RequestUserMediaForTest(request); FakeMediaStreamDispatcherRequestUserMediaComplete(); StartMockedVideoSource(); EXPECT_EQ(UserMediaClientImplUnderTest::REQUEST_SUCCEEDED, user_media_client_impl_->request_state()); EXPECT_EQ(1U, ms_dispatcher_->audio_input_array().size()); EXPECT_EQ(1U, ms_dispatcher_->video_array().size()); // MockMediaStreamDispatcher appends the session ID to its internal device // IDs. EXPECT_EQ(std::string(expected_audio_device_id) + "0", ms_dispatcher_->audio_input_array()[0].device.id); EXPECT_EQ(std::string(expected_video_device_id) + "0", ms_dispatcher_->video_array()[0].device.id); } protected: base::MessageLoop message_loop_; std::unique_ptr<ChildProcess> child_process_; MockMediaStreamDispatcher* ms_dispatcher_; // Owned by |used_media_impl_|. MockMediaDevicesDispatcherHost media_devices_dispatcher_; mojo::Binding<::mojom::MediaDevicesDispatcherHost> binding_user_media; mojo::Binding<::mojom::MediaDevicesDispatcherHost> binding_event_dispatcher_; std::unique_ptr<UserMediaClientImplUnderTest> user_media_client_impl_; std::unique_ptr<MockPeerConnectionDependencyFactory> dependency_factory_; }; TEST_F(UserMediaClientImplTest, GenerateMediaStream) { // Generate a stream with both audio and video. blink::WebMediaStream mixed_desc = RequestLocalMediaStream(); } // Test that the same source object is used if two MediaStreams are generated // using the same source. TEST_F(UserMediaClientImplTest, GenerateTwoMediaStreamsWithSameSource) { blink::WebMediaStream desc1 = RequestLocalMediaStream(); blink::WebMediaStream desc2 = RequestLocalMediaStream(); blink::WebVector<blink::WebMediaStreamTrack> desc1_video_tracks; desc1.VideoTracks(desc1_video_tracks); blink::WebVector<blink::WebMediaStreamTrack> desc2_video_tracks; desc2.VideoTracks(desc2_video_tracks); EXPECT_EQ(desc1_video_tracks[0].Source().Id(), desc2_video_tracks[0].Source().Id()); EXPECT_EQ(desc1_video_tracks[0].Source().GetExtraData(), desc2_video_tracks[0].Source().GetExtraData()); blink::WebVector<blink::WebMediaStreamTrack> desc1_audio_tracks; desc1.AudioTracks(desc1_audio_tracks); blink::WebVector<blink::WebMediaStreamTrack> desc2_audio_tracks; desc2.AudioTracks(desc2_audio_tracks); EXPECT_EQ(desc1_audio_tracks[0].Source().Id(), desc2_audio_tracks[0].Source().Id()); EXPECT_EQ(MediaStreamAudioSource::From(desc1_audio_tracks[0].Source()), MediaStreamAudioSource::From(desc2_audio_tracks[0].Source())); } // Test that the same source object is not used if two MediaStreams are // generated using different sources. TEST_F(UserMediaClientImplTest, GenerateTwoMediaStreamsWithDifferentSources) { blink::WebMediaStream desc1 = RequestLocalMediaStream(); // Make sure another device is selected (another |session_id|) in the next // gUM request. ms_dispatcher_->IncrementSessionId(); blink::WebMediaStream desc2 = RequestLocalMediaStream(); blink::WebVector<blink::WebMediaStreamTrack> desc1_video_tracks; desc1.VideoTracks(desc1_video_tracks); blink::WebVector<blink::WebMediaStreamTrack> desc2_video_tracks; desc2.VideoTracks(desc2_video_tracks); EXPECT_NE(desc1_video_tracks[0].Source().Id(), desc2_video_tracks[0].Source().Id()); EXPECT_NE(desc1_video_tracks[0].Source().GetExtraData(), desc2_video_tracks[0].Source().GetExtraData()); blink::WebVector<blink::WebMediaStreamTrack> desc1_audio_tracks; desc1.AudioTracks(desc1_audio_tracks); blink::WebVector<blink::WebMediaStreamTrack> desc2_audio_tracks; desc2.AudioTracks(desc2_audio_tracks); EXPECT_NE(desc1_audio_tracks[0].Source().Id(), desc2_audio_tracks[0].Source().Id()); EXPECT_NE(MediaStreamAudioSource::From(desc1_audio_tracks[0].Source()), MediaStreamAudioSource::From(desc2_audio_tracks[0].Source())); } TEST_F(UserMediaClientImplTest, StopLocalTracks) { // Generate a stream with both audio and video. blink::WebMediaStream mixed_desc = RequestLocalMediaStream(); blink::WebVector<blink::WebMediaStreamTrack> audio_tracks; mixed_desc.AudioTracks(audio_tracks); MediaStreamTrack* audio_track = MediaStreamTrack::GetTrack(audio_tracks[0]); audio_track->Stop(); EXPECT_EQ(1, ms_dispatcher_->stop_audio_device_counter()); blink::WebVector<blink::WebMediaStreamTrack> video_tracks; mixed_desc.VideoTracks(video_tracks); MediaStreamTrack* video_track = MediaStreamTrack::GetTrack(video_tracks[0]); video_track->Stop(); EXPECT_EQ(1, ms_dispatcher_->stop_video_device_counter()); } // This test that a source is not stopped even if the tracks in a // MediaStream is stopped if there are two MediaStreams with tracks using the // same device. The source is stopped // if there are no more MediaStream tracks using the device. TEST_F(UserMediaClientImplTest, StopLocalTracksWhenTwoStreamUseSameDevices) { // Generate a stream with both audio and video. blink::WebMediaStream desc1 = RequestLocalMediaStream(); blink::WebMediaStream desc2 = RequestLocalMediaStream(); blink::WebVector<blink::WebMediaStreamTrack> audio_tracks1; desc1.AudioTracks(audio_tracks1); MediaStreamTrack* audio_track1 = MediaStreamTrack::GetTrack(audio_tracks1[0]); audio_track1->Stop(); EXPECT_EQ(0, ms_dispatcher_->stop_audio_device_counter()); blink::WebVector<blink::WebMediaStreamTrack> audio_tracks2; desc2.AudioTracks(audio_tracks2); MediaStreamTrack* audio_track2 = MediaStreamTrack::GetTrack(audio_tracks2[0]); audio_track2->Stop(); EXPECT_EQ(1, ms_dispatcher_->stop_audio_device_counter()); blink::WebVector<blink::WebMediaStreamTrack> video_tracks1; desc1.VideoTracks(video_tracks1); MediaStreamTrack* video_track1 = MediaStreamTrack::GetTrack(video_tracks1[0]); video_track1->Stop(); EXPECT_EQ(0, ms_dispatcher_->stop_video_device_counter()); blink::WebVector<blink::WebMediaStreamTrack> video_tracks2; desc2.VideoTracks(video_tracks2); MediaStreamTrack* video_track2 = MediaStreamTrack::GetTrack(video_tracks2[0]); video_track2->Stop(); EXPECT_EQ(1, ms_dispatcher_->stop_video_device_counter()); } TEST_F(UserMediaClientImplTest, StopSourceWhenMediaStreamGoesOutOfScope) { // Generate a stream with both audio and video. RequestLocalMediaStream(); // Makes sure the test itself don't hold a reference to the created // MediaStream. user_media_client_impl_->ClearLastGeneratedStream(); blink::WebHeap::CollectAllGarbageForTesting(); // Expect the sources to be stopped when the MediaStream goes out of scope. EXPECT_EQ(1, ms_dispatcher_->stop_audio_device_counter()); EXPECT_EQ(1, ms_dispatcher_->stop_video_device_counter()); } // Test that the MediaStreams are deleted if a new document is loaded in the // frame. TEST_F(UserMediaClientImplTest, LoadNewDocumentInFrame) { // Test a stream with both audio and video. blink::WebMediaStream mixed_desc = RequestLocalMediaStream(); blink::WebMediaStream desc2 = RequestLocalMediaStream(); LoadNewDocumentInFrame(); blink::WebHeap::CollectAllGarbageForTesting(); EXPECT_EQ(1, ms_dispatcher_->stop_audio_device_counter()); EXPECT_EQ(1, ms_dispatcher_->stop_video_device_counter()); } // This test what happens if a video source to a MediaSteam fails to start. TEST_F(UserMediaClientImplTest, MediaVideoSourceFailToStart) { user_media_client_impl_->RequestUserMediaForTest(); FakeMediaStreamDispatcherRequestUserMediaComplete(); FailToStartMockedVideoSource(); EXPECT_EQ(UserMediaClientImplUnderTest::REQUEST_FAILED, user_media_client_impl_->request_state()); EXPECT_EQ(MEDIA_DEVICE_TRACK_START_FAILURE, user_media_client_impl_->error_reason()); blink::WebHeap::CollectAllGarbageForTesting(); EXPECT_EQ(1, ms_dispatcher_->request_stream_counter()); EXPECT_EQ(1, ms_dispatcher_->stop_audio_device_counter()); EXPECT_EQ(1, ms_dispatcher_->stop_video_device_counter()); } // This test what happens if an audio source fail to initialize. TEST_F(UserMediaClientImplTest, MediaAudioSourceFailToInitialize) { user_media_client_impl_->SetCreateSourceThatFails(true); user_media_client_impl_->RequestUserMediaForTest(); FakeMediaStreamDispatcherRequestUserMediaComplete(); StartMockedVideoSource(); EXPECT_EQ(UserMediaClientImplUnderTest::REQUEST_FAILED, user_media_client_impl_->request_state()); EXPECT_EQ(MEDIA_DEVICE_TRACK_START_FAILURE, user_media_client_impl_->error_reason()); blink::WebHeap::CollectAllGarbageForTesting(); EXPECT_EQ(1, ms_dispatcher_->request_stream_counter()); EXPECT_EQ(1, ms_dispatcher_->stop_audio_device_counter()); EXPECT_EQ(1, ms_dispatcher_->stop_video_device_counter()); } // This test what happens if UserMediaClientImpl is deleted before a source has // started. TEST_F(UserMediaClientImplTest, MediaStreamImplShutDown) { user_media_client_impl_->RequestUserMediaForTest(); FakeMediaStreamDispatcherRequestUserMediaComplete(); EXPECT_EQ(1, ms_dispatcher_->request_stream_counter()); EXPECT_EQ(UserMediaClientImplUnderTest::REQUEST_NOT_COMPLETE, user_media_client_impl_->request_state()); user_media_client_impl_.reset(); } // This test what happens if a new document is loaded in the frame while the // MediaStream is being generated by the MediaStreamDispatcher. TEST_F(UserMediaClientImplTest, ReloadFrameWhileGeneratingStream) { user_media_client_impl_->RequestUserMediaForTest(); LoadNewDocumentInFrame(); EXPECT_EQ(1, ms_dispatcher_->request_stream_counter()); EXPECT_EQ(0, ms_dispatcher_->stop_audio_device_counter()); EXPECT_EQ(0, ms_dispatcher_->stop_video_device_counter()); EXPECT_EQ(UserMediaClientImplUnderTest::REQUEST_NOT_COMPLETE, user_media_client_impl_->request_state()); } // This test what happens if a newdocument is loaded in the frame while the // sources are being started. TEST_F(UserMediaClientImplTest, ReloadFrameWhileGeneratingSources) { user_media_client_impl_->RequestUserMediaForTest(); FakeMediaStreamDispatcherRequestUserMediaComplete(); EXPECT_EQ(1, ms_dispatcher_->request_stream_counter()); LoadNewDocumentInFrame(); EXPECT_EQ(1, ms_dispatcher_->stop_audio_device_counter()); EXPECT_EQ(1, ms_dispatcher_->stop_video_device_counter()); EXPECT_EQ(UserMediaClientImplUnderTest::REQUEST_NOT_COMPLETE, user_media_client_impl_->request_state()); } // This test what happens if stop is called on a track after the frame has // been reloaded. TEST_F(UserMediaClientImplTest, StopTrackAfterReload) { blink::WebMediaStream mixed_desc = RequestLocalMediaStream(); EXPECT_EQ(1, ms_dispatcher_->request_stream_counter()); LoadNewDocumentInFrame(); blink::WebHeap::CollectAllGarbageForTesting(); EXPECT_EQ(1, ms_dispatcher_->stop_audio_device_counter()); EXPECT_EQ(1, ms_dispatcher_->stop_video_device_counter()); blink::WebVector<blink::WebMediaStreamTrack> audio_tracks; mixed_desc.AudioTracks(audio_tracks); MediaStreamTrack* audio_track = MediaStreamTrack::GetTrack(audio_tracks[0]); audio_track->Stop(); EXPECT_EQ(1, ms_dispatcher_->stop_audio_device_counter()); blink::WebVector<blink::WebMediaStreamTrack> video_tracks; mixed_desc.VideoTracks(video_tracks); MediaStreamTrack* video_track = MediaStreamTrack::GetTrack(video_tracks[0]); video_track->Stop(); EXPECT_EQ(1, ms_dispatcher_->stop_video_device_counter()); } TEST_F(UserMediaClientImplTest, EnumerateMediaDevices) { user_media_client_impl_->RequestMediaDevicesForTest(); base::RunLoop().RunUntilIdle(); EXPECT_EQ(UserMediaClientImplUnderTest::REQUEST_SUCCEEDED, user_media_client_impl_->request_state()); EXPECT_EQ(static_cast<size_t>(5), user_media_client_impl_->last_devices().size()); // Audio input device with matched output ID. const blink::WebMediaDeviceInfo* device = &user_media_client_impl_->last_devices()[0]; EXPECT_FALSE(device->DeviceId().IsEmpty()); EXPECT_EQ(blink::WebMediaDeviceInfo::kMediaDeviceKindAudioInput, device->Kind()); EXPECT_FALSE(device->Label().IsEmpty()); EXPECT_FALSE(device->GroupId().IsEmpty()); // Audio input device without matched output ID. device = &user_media_client_impl_->last_devices()[1]; EXPECT_FALSE(device->DeviceId().IsEmpty()); EXPECT_EQ(blink::WebMediaDeviceInfo::kMediaDeviceKindAudioInput, device->Kind()); EXPECT_FALSE(device->Label().IsEmpty()); EXPECT_FALSE(device->GroupId().IsEmpty()); // Video input devices. device = &user_media_client_impl_->last_devices()[2]; EXPECT_FALSE(device->DeviceId().IsEmpty()); EXPECT_EQ(blink::WebMediaDeviceInfo::kMediaDeviceKindVideoInput, device->Kind()); EXPECT_FALSE(device->Label().IsEmpty()); EXPECT_TRUE(device->GroupId().IsEmpty()); device = &user_media_client_impl_->last_devices()[3]; EXPECT_FALSE(device->DeviceId().IsEmpty()); EXPECT_EQ(blink::WebMediaDeviceInfo::kMediaDeviceKindVideoInput, device->Kind()); EXPECT_FALSE(device->Label().IsEmpty()); EXPECT_TRUE(device->GroupId().IsEmpty()); // Audio output device. device = &user_media_client_impl_->last_devices()[4]; EXPECT_FALSE(device->DeviceId().IsEmpty()); EXPECT_EQ(blink::WebMediaDeviceInfo::kMediaDeviceKindAudioOutput, device->Kind()); EXPECT_FALSE(device->Label().IsEmpty()); EXPECT_FALSE(device->GroupId().IsEmpty()); // Verfify group IDs. EXPECT_TRUE(user_media_client_impl_->last_devices()[0].GroupId().Equals( user_media_client_impl_->last_devices()[4].GroupId())); EXPECT_FALSE(user_media_client_impl_->last_devices()[1].GroupId().Equals( user_media_client_impl_->last_devices()[4].GroupId())); } TEST_F(UserMediaClientImplTest, RenderToAssociatedSinkConstraint) { // For a UserMediaRequest without audio, we expect false. blink::WebUserMediaRequest request = blink::WebUserMediaRequest::CreateForTesting(blink::WebMediaConstraints(), CreateDefaultConstraints()); user_media_client_impl_->RequestUserMediaForTest(request); EXPECT_FALSE( user_media_client_impl_->UserMediaRequestHasAutomaticDeviceSelection()); user_media_client_impl_->CancelUserMediaRequest(request); // If audio is requested, but no constraint, it should be true. // Currently we expect it to be false due to a suspected bug in the // device-matching code causing issues with some sound adapters. // See crbug.com/604523 MockConstraintFactory factory; blink::WebMediaConstraints audio_constraints = factory.CreateWebMediaConstraints(); EXPECT_FALSE(AudioRequestHasAutomaticDeviceSelection( factory.CreateWebMediaConstraints())); // If the constraint is present, it should dictate the result. factory.Reset(); factory.AddAdvanced().render_to_associated_sink.SetExact(true); EXPECT_TRUE(AudioRequestHasAutomaticDeviceSelection( factory.CreateWebMediaConstraints())); factory.Reset(); factory.AddAdvanced().render_to_associated_sink.SetExact(false); EXPECT_FALSE(AudioRequestHasAutomaticDeviceSelection( factory.CreateWebMediaConstraints())); factory.Reset(); factory.basic().render_to_associated_sink.SetExact(false); EXPECT_FALSE(AudioRequestHasAutomaticDeviceSelection( factory.CreateWebMediaConstraints())); } TEST_F(UserMediaClientImplTest, ObserveMediaDeviceChanges) { EXPECT_CALL(media_devices_dispatcher_, SubscribeDeviceChangeNotifications( MEDIA_DEVICE_TYPE_AUDIO_INPUT, _)); EXPECT_CALL(media_devices_dispatcher_, SubscribeDeviceChangeNotifications( MEDIA_DEVICE_TYPE_VIDEO_INPUT, _)); EXPECT_CALL( media_devices_dispatcher_, SubscribeDeviceChangeNotifications(MEDIA_DEVICE_TYPE_AUDIO_OUTPUT, _)); user_media_client_impl_->SetMediaDeviceChangeObserver( blink::WebMediaDeviceChangeObserver(true)); base::RunLoop().RunUntilIdle(); base::WeakPtr<MediaDevicesEventDispatcher> event_dispatcher = MediaDevicesEventDispatcher::GetForRenderFrame(nullptr); event_dispatcher->DispatchDevicesChangedEvent(MEDIA_DEVICE_TYPE_AUDIO_INPUT, MediaDeviceInfoArray()); event_dispatcher->DispatchDevicesChangedEvent(MEDIA_DEVICE_TYPE_VIDEO_INPUT, MediaDeviceInfoArray()); event_dispatcher->DispatchDevicesChangedEvent(MEDIA_DEVICE_TYPE_AUDIO_OUTPUT, MediaDeviceInfoArray()); base::RunLoop().RunUntilIdle(); EXPECT_CALL(media_devices_dispatcher_, UnsubscribeDeviceChangeNotifications( MEDIA_DEVICE_TYPE_AUDIO_INPUT, _)); EXPECT_CALL(media_devices_dispatcher_, UnsubscribeDeviceChangeNotifications( MEDIA_DEVICE_TYPE_VIDEO_INPUT, _)); EXPECT_CALL( media_devices_dispatcher_, UnsubscribeDeviceChangeNotifications(MEDIA_DEVICE_TYPE_AUDIO_OUTPUT, _)); user_media_client_impl_->SetMediaDeviceChangeObserver( blink::WebMediaDeviceChangeObserver()); base::RunLoop().RunUntilIdle(); } // This test what happens if the audio stream has same id with video stream. TEST_F(UserMediaClientImplTest, AudioVideoWithSameId) { ms_dispatcher_->TestSameId(); // Generate a stream with both audio and video. blink::WebMediaStream mixed_desc = RequestLocalMediaStream(); // Remove video track. This should trigger // UserMediaClientImpl::OnLocalSourceStopped, and has video track to be // removed from its |local_sources_|. blink::WebVector<blink::WebMediaStreamTrack> video_tracks; mixed_desc.VideoTracks(video_tracks); MediaStreamTrack* video_track = MediaStreamTrack::GetTrack(video_tracks[0]); video_track->Stop(); EXPECT_EQ(1, ms_dispatcher_->stop_video_device_counter()); EXPECT_EQ(0, ms_dispatcher_->stop_audio_device_counter()); // Now we load a new document in the web frame. If in the above Stop() call, // UserMediaClientImpl accidentally removed audio track, then video track will // be removed again here, which is incorrect. LoadNewDocumentInFrame(); blink::WebHeap::CollectAllGarbageForTesting(); EXPECT_EQ(1, ms_dispatcher_->stop_video_device_counter()); EXPECT_EQ(1, ms_dispatcher_->stop_audio_device_counter()); } TEST_F(UserMediaClientImplTest, CreateWithMandatoryInvalidAudioDeviceId) { blink::WebMediaConstraints audio_constraints = CreateDeviceConstraints(kInvalidDeviceId); blink::WebUserMediaRequest request = blink::WebUserMediaRequest::CreateForTesting( audio_constraints, blink::WebMediaConstraints()); user_media_client_impl_->RequestUserMediaForTest(request); EXPECT_EQ(UserMediaClientImplUnderTest::REQUEST_FAILED, user_media_client_impl_->request_state()); } TEST_F(UserMediaClientImplTest, CreateWithMandatoryInvalidVideoDeviceId) { blink::WebMediaConstraints video_constraints = CreateDeviceConstraints(kInvalidDeviceId); blink::WebUserMediaRequest request = blink::WebUserMediaRequest::CreateForTesting(blink::WebMediaConstraints(), video_constraints); user_media_client_impl_->RequestUserMediaForTest(request); EXPECT_EQ(UserMediaClientImplUnderTest::REQUEST_FAILED, user_media_client_impl_->request_state()); } TEST_F(UserMediaClientImplTest, CreateWithMandatoryValidDeviceIds) { blink::WebMediaConstraints audio_constraints = CreateDeviceConstraints(kFakeAudioInputDeviceId1); blink::WebMediaConstraints video_constraints = CreateDeviceConstraints(kFakeVideoInputDeviceId1); TestValidRequestWithConstraints(audio_constraints, video_constraints, kFakeAudioInputDeviceId1, kFakeVideoInputDeviceId1); } TEST_F(UserMediaClientImplTest, CreateWithBasicIdealValidDeviceId) { blink::WebMediaConstraints audio_constraints = CreateDeviceConstraints(nullptr, kFakeAudioInputDeviceId1); blink::WebMediaConstraints video_constraints = CreateDeviceConstraints(nullptr, kFakeVideoInputDeviceId1); TestValidRequestWithConstraints(audio_constraints, video_constraints, kFakeAudioInputDeviceId1, kFakeVideoInputDeviceId1); } TEST_F(UserMediaClientImplTest, CreateWithAdvancedExactValidDeviceId) { blink::WebMediaConstraints audio_constraints = CreateDeviceConstraints(nullptr, nullptr, kFakeAudioInputDeviceId1); blink::WebMediaConstraints video_constraints = CreateDeviceConstraints( nullptr, nullptr, kFakeVideoInputDeviceId1); TestValidRequestWithConstraints(audio_constraints, video_constraints, kFakeAudioInputDeviceId1, kFakeVideoInputDeviceId1); } TEST_F(UserMediaClientImplTest, CreateWithAllOptionalInvalidDeviceId) { blink::WebMediaConstraints audio_constraints = CreateDeviceConstraints(nullptr, kInvalidDeviceId, kInvalidDeviceId); blink::WebMediaConstraints video_constraints = CreateDeviceConstraints(nullptr, kInvalidDeviceId, kInvalidDeviceId); // MockMediaStreamDispatcher uses empty string as default audio device ID. // MockMediaDevicesDispatcher uses the first device in the enumeration as // default video device ID. TestValidRequestWithConstraints(audio_constraints, video_constraints, std::string(), kFakeVideoInputDeviceId1); } TEST_F(UserMediaClientImplTest, CreateWithFacingModeUser) { blink::WebMediaConstraints audio_constraints = CreateDeviceConstraints(kFakeAudioInputDeviceId1); blink::WebMediaConstraints video_constraints = CreateFacingModeConstraints("user"); // kFakeVideoInputDeviceId1 has user facing mode. TestValidRequestWithConstraints(audio_constraints, video_constraints, kFakeAudioInputDeviceId1, kFakeVideoInputDeviceId1); } TEST_F(UserMediaClientImplTest, CreateWithFacingModeEnvironment) { blink::WebMediaConstraints audio_constraints = CreateDeviceConstraints(kFakeAudioInputDeviceId1); blink::WebMediaConstraints video_constraints = CreateFacingModeConstraints("environment"); // kFakeVideoInputDeviceId2 has environment facing mode. TestValidRequestWithConstraints(audio_constraints, video_constraints, kFakeAudioInputDeviceId1, kFakeVideoInputDeviceId2); } } // namespace content
41.641409
82
0.753063
[ "object", "vector" ]
884c7fee99055b47cefce740a5ebe7059817ef82
31,583
cpp
C++
modules/ximgproc/src/structured_edge_detection.cpp
ptelang/opencv_contrib
dd68e396c76f1db4d82e5aa7a6545580939f9b9d
[ "Apache-2.0" ]
35
2021-01-07T11:58:58.000Z
2022-03-25T11:35:25.000Z
modules/ximgproc/src/structured_edge_detection.cpp
ptelang/opencv_contrib
dd68e396c76f1db4d82e5aa7a6545580939f9b9d
[ "Apache-2.0" ]
3
2020-05-22T19:23:38.000Z
2020-06-29T12:32:24.000Z
modules/ximgproc/src/structured_edge_detection.cpp
ptelang/opencv_contrib
dd68e396c76f1db4d82e5aa7a6545580939f9b9d
[ "Apache-2.0" ]
9
2020-12-14T09:13:30.000Z
2021-12-13T07:03:53.000Z
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009-2011, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of Intel Corporation may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) however caused // and on any theory of liability, whether in contract, strict liability, // or tort (including negligence or otherwise) arising in any way out of // the use of this software, even if advised of the possibility of such damage. // //M*/ #include "precomp.hpp" #include <vector> #include <algorithm> #include <iterator> #include <iostream> #include <cmath> #include "advanced_types.hpp" #ifdef CV_CXX11 #define CV_USE_PARALLEL_PREDICT_EDGES_1 1 #define CV_USE_PARALLEL_PREDICT_EDGES_2 0 //1, see https://github.com/opencv/opencv_contrib/issues/2346 #else #define CV_USE_PARALLEL_PREDICT_EDGES_1 0 #define CV_USE_PARALLEL_PREDICT_EDGES_2 0 #endif /********************* Helper functions *********************/ /*! * Lightweight wrapper over cv::resize * * \param src : source image to resize * \param dst : destination image size * \return resized image */ static cv::Mat imresize(const cv::Mat &src, const cv::Size &nSize) { cv::Mat dst; if (nSize.width < src.size().width && nSize.height < src.size().height) cv::resize(src, dst, nSize, 0.0, 0.0, cv::INTER_AREA); else cv::resize(src, dst, nSize, 0.0, 0.0, cv::INTER_LINEAR); return dst; } /*! * The function filters src with triangle filter with radius equal rad * * \param src : source image to filter * \param rad : radius of filtering kernel * \return filtering result */ static cv::Mat imsmooth(const cv::Mat &src, const int rad) { if (rad == 0) return src; else { const float p = 12.0f/rad/(rad + 2) - 2; cv::Mat dst; if (rad <= 1) { CV_INIT_VECTOR(kernelXY, float, {1/(p + 2), p/(p + 2), 1/(p + 2)}); cv::sepFilter2D(src, dst, -1, kernelXY, kernelXY); } else { float nrml = CV_SQR(rad + 1.0f); std::vector <float> kernelXY(2*rad + 1); for (int i = 0; i <= rad; ++i) { kernelXY[2*rad - i] = (i + 1) / nrml; kernelXY[i] = (i + 1) / nrml; } sepFilter2D(src, dst, -1, kernelXY, kernelXY); } return dst; } } /*! * The function implements rgb to luv conversion in a way similar * to UCSD computer vision toolbox * * \param src : source image (RGB, float, in [0;1]) to convert * \return converted image in luv colorspace */ static cv::Mat rgb2luv(const cv::Mat &src) { cv::Mat dst(src.size(), src.type()); const float a = CV_CUBE(29.0f)/27; const float y0 = 8.0f/a; const float mX[] = {0.430574f, 0.341550f, 0.178325f}; const float mY[] = {0.222015f, 0.706655f, 0.071330f}; const float mZ[] = {0.020183f, 0.129553f, 0.939180f}; const float maxi= 1.0f/270; const float minu= -88*maxi; const float minv= -134*maxi; const float un = 0.197833f; const float vn = 0.468331f; // build (padded) lookup table for y->l conversion assuming y in [0,1] std::vector <float> lTable(1024); for (int i = 0; i < 1024; ++i) { float y = i/1024.0f; float l = y > y0 ? 116*powf(y, 1.0f/3.0f) - 16 : y*a; lTable[i] = l*maxi; } for (int i = 0; i < 40; ++i) lTable.push_back(*--lTable.end()); const int nchannels = 3; for (int i = 0; i < src.rows; ++i) { const float *pSrc = src.ptr<float>(i); float *pDst = dst.ptr<float>(i); for (int j = 0; j < src.cols*nchannels; j += nchannels) { const float rgb[] = {pSrc[j + 0], pSrc[j + 1], pSrc[j + 2]}; const float xyz[] = {mX[0]*rgb[0] + mX[1]*rgb[1] + mX[2]*rgb[2], mY[0]*rgb[0] + mY[1]*rgb[1] + mY[2]*rgb[2], mZ[0]*rgb[0] + mZ[1]*rgb[1] + mZ[2]*rgb[2]}; const float nz = 1.0f / float(xyz[0] + 15*xyz[1] + 3*xyz[2] + 1e-35); const float l = pDst[j] = lTable[cvFloor(1024*xyz[1])]; pDst[j + 1] = l * (13*4*xyz[0]*nz - 13*un) - minu;; pDst[j + 2] = l * (13*9*xyz[1]*nz - 13*vn) - minv; } } return dst; } /*! * The function computes gradient magnitude and weighted (with magnitude) * orientation histogram. Magnitude is additionally normalized * by dividing on imsmooth(M, gnrmRad) + 0.01; * * \param src : source image * \param magnitude : gradient magnitude * \param histogram : gradient orientation nBins-channels histogram * \param nBins : number of gradient orientations * \param pSize : factor to downscale histogram * \param gnrmRad : radius for magnitude normalization */ static void gradientHist(const cv::Mat &src, cv::Mat &magnitude, cv::Mat &histogram, const int nBins, const int pSize, const int gnrmRad) { cv::Mat phase, Dx, Dy; magnitude.create( src.size(), cv::DataType<float>::type ); phase.create( src.size(), cv::DataType<float>::type ); histogram.create( cv::Size( cvCeil(src.size().width/float(pSize)), cvCeil(src.size().height/float(pSize)) ), CV_MAKETYPE(cv::DataType<float>::type, nBins) ); histogram.setTo(0); cv::Sobel( src, Dx, cv::DataType<float>::type, 1, 0, 1, 1.0, 0.0, cv::BORDER_REFLECT ); cv::Sobel( src, Dy, cv::DataType<float>::type, 0, 1, 1, 1.0, 0.0, cv::BORDER_REFLECT ); int nchannels = src.channels(); for (int i = 0; i < src.rows; ++i) { const float *pDx = Dx.ptr<float>(i); const float *pDy = Dy.ptr<float>(i); float *pMagnitude = magnitude.ptr<float>(i); float *pPhase = phase.ptr<float>(i); for (int j = 0; j < src.cols*nchannels; j += nchannels) { float fMagn = float(-1e-5), fdx = 0, fdy = 0; for (int k = 0; k < nchannels; ++k) { float cMagn = CV_SQR( pDx[j + k] ) + CV_SQR( pDy[j + k] ); if (cMagn > fMagn) { fMagn = cMagn; fdx = pDx[j + k]; fdy = pDy[j + k]; } } pMagnitude[j/nchannels] = sqrtf(fMagn); float angle = cv::fastAtan2(fdy, fdx) / 180.0f - 1.0f * (fdy < 0); if (std::fabs(fdx) + std::fabs(fdy) < 1e-5) angle = 0.5f; pPhase[j/nchannels] = angle; } } magnitude /= imsmooth( magnitude, gnrmRad ) + 0.01*cv::Mat::ones( magnitude.size(), magnitude.type() ); for (int i = 0; i < phase.rows; ++i) { const float *pPhase = phase.ptr<float>(i); const float *pMagn = magnitude.ptr<float>(i); float *pHist = histogram.ptr<float>(i/pSize); for (int j = 0; j < phase.cols; ++j) { int angle = cvRound(pPhase[j]*nBins); if(angle >= nBins) { angle = 0; } const int index = (j/pSize)*nBins + angle; pHist[index] += pMagn[j] / CV_SQR(pSize); } } } /*! * The class parallelizing the edgenms algorithm. * * \param E : edge image * \param O : orientation image * \param dst : destination image * \param r : radius for NMS suppression * \param s : radius for boundary suppression * \param m : multiplier for conservative suppression */ class NmsInvoker : public cv::ParallelLoopBody { private: const cv::Mat &E; const cv::Mat &O; cv::Mat &dst; const int r; const float m; public: NmsInvoker(const cv::Mat &_E, const cv::Mat &_O, cv::Mat &_dst, const int _r, const float _m) : E(_E), O(_O), dst(_dst), r(_r), m(_m) { } void operator()(const cv::Range &range) const CV_OVERRIDE { for (int x = range.start; x < range.end; x++) { const float *e_ptr = E.ptr<float>(x); const float *o_ptr = O.ptr<float>(x); float *dst_ptr = dst.ptr<float>(x); for (int y=0; y < E.cols; y++) { float e = e_ptr[y]; dst_ptr[y] = e; if (!e) continue; e *= m; float coso = cos(o_ptr[y]); float sino = sin(o_ptr[y]); for (int d=-r; d<=r; d++) { if (d) { float xdcos = x+d*coso; float ydsin = y+d*sino; xdcos = xdcos < 0 ? 0 : (xdcos > E.rows - 1.001f ? E.rows - 1.001f : xdcos); ydsin = ydsin < 0 ? 0 : (ydsin > E.cols - 1.001f ? E.cols - 1.001f : ydsin); int x0 = (int)xdcos; int y0 = (int)ydsin; int x1 = x0 + 1; int y1 = y0 + 1; float dx0 = xdcos - x0; float dy0 = ydsin - y0; float dx1 = 1 - dx0; float dy1 = 1 - dy0; float e0 = E.at<float>(x0, y0) * dx1 * dy1 + E.at<float>(x1, y0) * dx0 * dy1 + E.at<float>(x0, y1) * dx1 * dy0 + E.at<float>(x1, y1) * dx0 * dy0; if(e < e0) { dst_ptr[y] = 0; break; } } } } } } }; /********************* RFFeatureGetter class *********************/ namespace cv { namespace ximgproc { class RFFeatureGetterImpl : public RFFeatureGetter { public: /*! * Default constructor */ RFFeatureGetterImpl() : name("RFFeatureGetter"){} /*! * The method extracts features from img and store them to features. * Extracted features are appropriate for StructuredEdgeDetection::predictEdges. * * \param src : source image (RGB, float, in [0;1]) to extract features * \param features : destination feature image * * \param gnrmRad : __rf.options.gradientNormalizationRadius * \param gsmthRad : __rf.options.gradientSmoothingRadius * \param shrink : __rf.options.shrinkNumber * \param outNum : __rf.options.numberOfOutputChannels * \param gradNum : __rf.options.numberOfGradientOrientations */ virtual void getFeatures(const Mat &src, Mat &features, const int gnrmRad, const int gsmthRad, const int shrink, const int outNum, const int gradNum) const CV_OVERRIDE { cv::Mat luvImg = rgb2luv(src); std::vector <cv::Mat> featureArray; cv::Size nSize = src.size() / float(shrink); split( imresize(luvImg, nSize), featureArray ); CV_INIT_VECTOR(scales, float, {1.0f, 0.5f}); for (size_t i = 0; i < scales.size(); ++i) { int pSize = std::max( 1, int(shrink*scales[i]) ); cv::Mat magnitude, histogram; gradientHist(/**/ imsmooth(imresize(luvImg, scales[i]*src.size()), gsmthRad), magnitude, histogram, gradNum, pSize, gnrmRad /**/); featureArray.push_back(/**/ imresize( magnitude, nSize ).clone() /**/); featureArray.push_back(/**/ imresize( histogram, nSize ).clone() /**/); } // Mixing int resType = CV_MAKETYPE(cv::DataType<float>::type, outNum); features.create(nSize, resType); std::vector <int> fromTo; for (int i = 0; i < 2*outNum; ++i) fromTo.push_back(i/2); mixChannels(featureArray, features, fromTo); } protected: /*! algorithm name */ String name; }; Ptr<RFFeatureGetter> createRFFeatureGetter() { return makePtr<RFFeatureGetterImpl>(); } } } /********************* StructuredEdgeDetection class *********************/ namespace cv { namespace ximgproc { class StructuredEdgeDetectionImpl : public StructuredEdgeDetection { public: /*! * This constructor loads __rf model from filename * * \param filename : name of the file where the model is stored */ StructuredEdgeDetectionImpl(const cv::String &filename, Ptr<const RFFeatureGetter> _howToGetFeatures) : name("StructuredEdgeDetection"), howToGetFeatures( (!_howToGetFeatures.empty()) ? _howToGetFeatures : createRFFeatureGetter().staticCast<const RFFeatureGetter>() ) { cv::FileStorage modelFile(filename, FileStorage::READ); CV_Assert( modelFile.isOpened() ); __rf.options.stride = modelFile["options"]["stride"]; __rf.options.shrinkNumber = modelFile["options"]["shrinkNumber"]; __rf.options.patchSize = modelFile["options"]["patchSize"]; __rf.options.patchInnerSize = modelFile["options"]["patchInnerSize"]; __rf.options.numberOfGradientOrientations = modelFile["options"]["numberOfGradientOrientations"]; __rf.options.gradientSmoothingRadius = modelFile["options"]["gradientSmoothingRadius"]; __rf.options.regFeatureSmoothingRadius = modelFile["options"]["regFeatureSmoothingRadius"]; __rf.options.ssFeatureSmoothingRadius = modelFile["options"]["ssFeatureSmoothingRadius"]; __rf.options.gradientNormalizationRadius = modelFile["options"]["gradientNormalizationRadius"]; __rf.options.selfsimilarityGridSize = modelFile["options"]["selfsimilarityGridSize"]; __rf.options.numberOfTrees = modelFile["options"]["numberOfTrees"]; __rf.options.numberOfTreesToEvaluate = modelFile["options"]["numberOfTreesToEvaluate"]; __rf.options.numberOfOutputChannels = 2*(__rf.options.numberOfGradientOrientations + 1) + 3; //-------------------------------------------- cv::FileNode childs = modelFile["childs"]; cv::FileNode featureIds = modelFile["featureIds"]; std::vector <int> currentTree; for(cv::FileNodeIterator it = childs.begin(); it != childs.end(); ++it) { (*it) >> currentTree; std::copy(currentTree.begin(), currentTree.end(), std::back_inserter(__rf.childs)); } for(cv::FileNodeIterator it = featureIds.begin(); it != featureIds.end(); ++it) { (*it) >> currentTree; std::copy(currentTree.begin(), currentTree.end(), std::back_inserter(__rf.featureIds)); } cv::FileNode thresholds = modelFile["thresholds"]; std::vector <float> fcurrentTree; for(cv::FileNodeIterator it = thresholds.begin(); it != thresholds.end(); ++it) { (*it) >> fcurrentTree; std::copy(fcurrentTree.begin(), fcurrentTree.end(), std::back_inserter(__rf.thresholds)); } cv::FileNode edgeBoundaries = modelFile["edgeBoundaries"]; cv::FileNode edgeBins = modelFile["edgeBins"]; for(cv::FileNodeIterator it = edgeBoundaries.begin(); it != edgeBoundaries.end(); ++it) { (*it) >> currentTree; std::copy(currentTree.begin(), currentTree.end(), std::back_inserter(__rf.edgeBoundaries)); } for(cv::FileNodeIterator it = edgeBins.begin(); it != edgeBins.end(); ++it) { (*it) >> currentTree; std::copy(currentTree.begin(), currentTree.end(), std::back_inserter(__rf.edgeBins)); } __rf.numberOfTreeNodes = int( __rf.childs.size() ) / __rf.options.numberOfTrees; } /*! * The function detects edges in src and draw them to dst * * \param _src : source image (RGB, float, in [0;1]) to detect edges * \param _dst : destination image (grayscale, float, in [0;1]) * where edges are drawn */ void detectEdges(cv::InputArray _src, cv::OutputArray _dst) const CV_OVERRIDE { CV_Assert( _src.type() == CV_32FC3 ); _dst.createSameSize( _src, cv::DataType<float>::type ); _dst.setTo(0); Mat dst = _dst.getMat(); int padding = ( __rf.options.patchSize - __rf.options.patchInnerSize )/2; cv::Mat nSrc; copyMakeBorder( _src, nSrc, padding, padding, padding, padding, BORDER_REFLECT ); NChannelsMat features; createRFFeatureGetter()->getFeatures( nSrc, features, __rf.options.gradientNormalizationRadius, __rf.options.gradientSmoothingRadius, __rf.options.shrinkNumber, __rf.options.numberOfOutputChannels, __rf.options.numberOfGradientOrientations ); predictEdges( features, dst ); } /*! * The function computes orientation from edge image. * * \param src : edge image. * \param dst : orientation image. * \param r : filter radius. */ void computeOrientation(cv::InputArray _src, cv::OutputArray _dst) const CV_OVERRIDE { CV_Assert( _src.type() == CV_32FC1 ); cv::Mat Oxx, Oxy, Oyy; _dst.createSameSize( _src, _src.type() ); _dst.setTo(0); Mat src = _src.getMat(); cv::Mat E_conv = imsmooth(src, __rf.options.gradientNormalizationRadius); Sobel(E_conv, Oxx, -1, 2, 0); Sobel(E_conv, Oxy, -1, 1, 1); Sobel(E_conv, Oyy, -1, 0, 2); Mat dst = _dst.getMat(); float *o = dst.ptr<float>(); float *oxx = Oxx.ptr<float>(); float *oxy = Oxy.ptr<float>(); float *oyy = Oyy.ptr<float>(); for (int i = 0; i < dst.rows * dst.cols; i++) { int xysign = -((oxy[i] > 0) - (oxy[i] < 0)); o[i] = (atan((oyy[i] * xysign / (oxx[i] + 1e-5))) > 0) ? (float) fmod( atan((oyy[i] * xysign / (oxx[i] + 1e-5))), CV_PI) : (float) fmod( atan((oyy[i] * xysign / (oxx[i] + 1e-5))) + CV_PI, CV_PI); } } /*! * The function suppress edges where edge is stronger in orthogonal direction * \param edge_image : edge image from detectEdges function. * \param orientation_image : orientation image from computeOrientation function. * \param _dst : suppressed image (grayscale, float, in [0;1]) * \param r : radius for NMS suppression. * \param s : radius for boundary suppression. * \param m : multiplier for conservative suppression. * \param isParallel: enables/disables parallel computing. */ void edgesNms(cv::InputArray edge_image, cv::InputArray orientation_image, cv::OutputArray _dst, int r, int s, float m, bool isParallel) const CV_OVERRIDE { CV_Assert(edge_image.type() == CV_32FC1); CV_Assert(orientation_image.type() == CV_32FC1); cv::Mat E = edge_image.getMat(); cv::Mat O = orientation_image.getMat(); cv::Mat E_t = E.t(); cv::Mat O_t = O.t(); cv::Mat dst = _dst.getMat(); dst.create(E.cols, E.rows, E.type()); dst.setTo(0); cv::Range sizeRange = cv::Range(0, E_t.rows); NmsInvoker body = NmsInvoker(E_t, O_t, dst, r, m); if (isParallel) { cv::parallel_for_(sizeRange, body); } else { body(sizeRange); } s = s > E_t.rows / 2 ? E_t.rows / 2 : s; s = s > E_t.cols / 2 ? E_t.cols / 2 : s; for (int x=0; x<s; x++) { for (int y=0; y<E_t.cols; y++) { dst.at<float>(x, y) *= x / (float)s; dst.at<float>(E_t.rows-1-x, y) *= x / (float)s; } } for (int x=0; x < E_t.rows; x++) { for (int y=0; y < s; y++) { dst.at<float>(x, y) *= y / (float)s; dst.at<float>(x, E_t.cols-1-y) *= y / (float)s; } } transpose(dst, dst); dst.copyTo(_dst); } protected: /*! * Private method used by process method. The function * predict edges in n-channel feature image and store them to dst. * * \param features : source image (n-channels, float) to detect edges * \param dst : destination image (grayscale, float, in [0;1]) where edges are drawn */ void predictEdges(const NChannelsMat &features, cv::Mat &dst) const { int shrink = __rf.options.shrinkNumber; int rfs = __rf.options.regFeatureSmoothingRadius; int sfs = __rf.options.ssFeatureSmoothingRadius; int nTreesEval = __rf.options.numberOfTreesToEvaluate; int nTrees = __rf.options.numberOfTrees; int nTreesNodes = __rf.numberOfTreeNodes; const int nchannels = features.channels(); int pSize = __rf.options.patchSize; int nFeatures = CV_SQR(pSize/shrink)*nchannels; int outNum = __rf.options.numberOfOutputChannels; int stride = __rf.options.stride; int ipSize = __rf.options.patchInnerSize; int gridSize = __rf.options.selfsimilarityGridSize; const int height = cvCeil( double(features.rows*shrink - pSize) / stride ); const int width = cvCeil( double(features.cols*shrink - pSize) / stride ); // image size in patches with overlapping //------------------------------------------------------------------------- NChannelsMat regFeatures = imsmooth(features, cvRound(rfs / float(shrink))); NChannelsMat ssFeatures = imsmooth(features, cvRound(sfs / float(shrink))); NChannelsMat indexes(height, width, CV_MAKETYPE(DataType<int>::type, nTreesEval)); std::vector <int> offsetI(/**/ CV_SQR(pSize/shrink)*nchannels, 0); for (int i = 0; i < CV_SQR(pSize/shrink)*nchannels; ++i) { int z = i / CV_SQR(pSize/shrink); int y = ( i % CV_SQR(pSize/shrink) )/(pSize/shrink); int x = ( i % CV_SQR(pSize/shrink) )%(pSize/shrink); offsetI[i] = x*features.cols*nchannels + y*nchannels + z; } // lookup table for mapping linear index to offsets std::vector <int> offsetE(/**/ CV_SQR(ipSize)*outNum, 0); for (int i = 0; i < CV_SQR(ipSize)*outNum; ++i) { int z = i / CV_SQR(ipSize); int y = ( i % CV_SQR(ipSize) )/ipSize; int x = ( i % CV_SQR(ipSize) )%ipSize; offsetE[i] = x*dst.cols*outNum + y*outNum + z; } // lookup table for mapping linear index to offsets std::vector <int> offsetX( CV_SQR(gridSize)*(CV_SQR(gridSize) - 1)/2 * nchannels, 0); std::vector <int> offsetY( CV_SQR(gridSize)*(CV_SQR(gridSize) - 1)/2 * nchannels, 0); int hc = cvRound( (pSize/shrink) / (2.0*gridSize) ); // half of cell std::vector <int> gridPositions; for(int i = 0; i < gridSize; i++) gridPositions.push_back( int( (i+1)*(pSize/shrink + 2*hc - 1)/(gridSize + 1.0) - hc + 0.5f ) ); for (int i = 0, n = 0; i < CV_SQR(gridSize)*nchannels; ++i) for (int j = (i%CV_SQR(gridSize)) + 1; j < CV_SQR(gridSize); ++j, ++n) { int z = i / CV_SQR(gridSize); int x1 = gridPositions[i%CV_SQR(gridSize)%gridSize]; int y1 = gridPositions[i%CV_SQR(gridSize)/gridSize]; int x2 = gridPositions[j%gridSize]; int y2 = gridPositions[j/gridSize]; offsetX[n] = x1*features.cols*nchannels + y1*nchannels + z; offsetY[n] = x2*features.cols*nchannels + y2*nchannels + z; } // lookup tables for mapping linear index to offset pairs #if CV_USE_PARALLEL_PREDICT_EDGES_1 parallel_for_(cv::Range(0, height), [&](const cv::Range& range) #else const cv::Range range(0, height); #endif { for(int i = range.start; i < range.end; ++i) { float *regFeaturesPtr = regFeatures.ptr<float>(i*stride/shrink); float *ssFeaturesPtr = ssFeatures.ptr<float>(i*stride/shrink); int *indexPtr = indexes.ptr<int>(i); for (int j = 0, k = 0; j < width; ++k, j += !(k %= nTreesEval)) // for j,k in [0;width)x[0;nTreesEval) { int baseNode = ( ((i + j)%(2*nTreesEval) + k)%nTrees )*nTreesNodes; int currentNode = baseNode; // select root node of the tree to evaluate int offset = (j*stride/shrink)*nchannels; while ( __rf.childs[currentNode] != 0 ) { int currentId = __rf.featureIds[currentNode]; float currentFeature; if (currentId >= nFeatures) { int xIndex = offsetX[currentId - nFeatures]; float A = ssFeaturesPtr[offset + xIndex]; int yIndex = offsetY[currentId - nFeatures]; float B = ssFeaturesPtr[offset + yIndex]; currentFeature = A - B; } else currentFeature = regFeaturesPtr[offset + offsetI[currentId]]; // compare feature to threshold and move left or right accordingly if (currentFeature < __rf.thresholds[currentNode]) currentNode = baseNode + __rf.childs[currentNode] - 1; else currentNode = baseNode + __rf.childs[currentNode]; } indexPtr[j*nTreesEval + k] = currentNode; } } } #if CV_USE_PARALLEL_PREDICT_EDGES_1 ); #endif NChannelsMat dstM(dst.size(), CV_MAKETYPE(DataType<float>::type, outNum)); dstM.setTo(0); float step = 2.0f * CV_SQR(stride) / CV_SQR(ipSize) / nTreesEval; #if CV_USE_PARALLEL_PREDICT_EDGES_2 parallel_for_(cv::Range(0, height), [&](const cv::Range& range) #elif CV_USE_PARALLEL_PREDICT_EDGES_1 const cv::Range range(0, height); #endif { for(int i = range.start; i < range.end; ++i) { int *pIndex = indexes.ptr<int>(i); float *pDst = dstM.ptr<float>(i*stride); for (int j = 0, k = 0; j < width; ++k, j += !(k %= nTreesEval)) {// for j,k in [0;width)x[0;nTreesEval) int currentNode = pIndex[j*nTreesEval + k]; size_t sizeBoundaries = __rf.edgeBoundaries.size(); int convertedBoundaries = static_cast<int>(sizeBoundaries); int nBnds = (convertedBoundaries - 1) / (nTreesNodes * nTrees); int start = __rf.edgeBoundaries[currentNode * nBnds]; int finish = __rf.edgeBoundaries[currentNode * nBnds + 1]; if (start == finish) continue; int offset = j*stride*outNum; for (int p = start; p < finish; ++p) pDst[offset + offsetE[__rf.edgeBins[p]]] += step; } } } #if CV_USE_PARALLEL_PREDICT_EDGES_2 ); #endif cv::reduce( dstM.reshape(1, int( dstM.total() ) ), dstM, 2, CV_REDUCE_SUM); imsmooth( dstM.reshape(1, dst.rows), 1 ).copyTo(dst); } /********************* Members *********************/ protected: /*! algorithm name */ String name; /*! optional feature getter (getFeatures method) */ Ptr<const RFFeatureGetter> howToGetFeatures; /*! random forest used to detect edges */ struct RandomForest { /*! random forest options, e.g. number of trees */ struct RandomForestOptions { // model params int numberOfOutputChannels; /*!< number of edge orientation bins for output */ int patchSize; /*!< width of image patches */ int patchInnerSize; /*!< width of predicted part inside patch*/ // feature params int regFeatureSmoothingRadius; /*!< radius for smoothing of regular features * (using convolution with triangle filter) */ int ssFeatureSmoothingRadius; /*!< radius for smoothing of additional features * (using convolution with triangle filter) */ int shrinkNumber; /*!< amount to shrink channels */ int numberOfGradientOrientations; /*!< number of orientations per gradient scale */ int gradientSmoothingRadius; /*!< radius for smoothing of gradients * (using convolution with triangle filter) */ int gradientNormalizationRadius; /*!< gradient normalization radius */ int selfsimilarityGridSize; /*!< number of self similarity cells */ // detection params int numberOfTrees; /*!< number of trees in forest to train */ int numberOfTreesToEvaluate; /*!< number of trees to evaluate per location */ int stride; /*!< stride at which to compute edges */ } options; int numberOfTreeNodes; std::vector <int> featureIds; /*!< feature coordinate thresholded at k-th node */ std::vector <float> thresholds; /*!< threshold applied to featureIds[k] at k-th node */ std::vector <int> childs; /*!< k --> child[k] - 1, child[k] */ std::vector <int> edgeBoundaries; /*!< ... */ std::vector <int> edgeBins; /*!< ... */ } __rf; }; Ptr<StructuredEdgeDetection> createStructuredEdgeDetection(const String &model, Ptr<const RFFeatureGetter> howToGetFeatures) { return makePtr<StructuredEdgeDetectionImpl>(model, howToGetFeatures); } } }
34.975637
158
0.552829
[ "vector", "model" ]
884c99463a25ee3aefd72f9f03f7f0b000be2fcd
7,946
cc
C++
samples/cl_gpu_metrics/tool.cc
ivorobts/pti-gpu
d846e1b428a5280ab0fd065d5ae68e0a2308fa9b
[ "MIT" ]
1
2021-01-25T10:44:55.000Z
2021-01-25T10:44:55.000Z
samples/cl_gpu_metrics/tool.cc
inteI-cloud/pti-gpu
df968c95687f15f871c9323d9325211669487bd2
[ "MIT" ]
null
null
null
samples/cl_gpu_metrics/tool.cc
inteI-cloud/pti-gpu
df968c95687f15f871c9323d9325211669487bd2
[ "MIT" ]
null
null
null
//============================================================== // Copyright (C) Intel Corporation // // SPDX-License-Identifier: MIT // ============================================================= #include <iomanip> #include <iostream> #include <set> #include "cl_metric_collector.h" #include "cl_kernel_collector.h" struct Kernel { uint64_t total_time; uint64_t call_count; float eu_active; float eu_stall; bool operator>(const Kernel& r) const { if (total_time != r.total_time) { return total_time > r.total_time; } return call_count > r.call_count; } bool operator!=(const Kernel& r) const { if (total_time == r.total_time) { return call_count != r.call_count; } return true; } }; using KernelMap = std::map<std::string, Kernel>; const uint32_t kKernelLength = 10; const uint32_t kCallsLength = 12; const uint32_t kTimeLength = 20; const uint32_t kPercentLength = 16; static ClMetricCollector* metric_collector = nullptr; static ClKernelCollector* kernel_collector = nullptr; static std::chrono::steady_clock::time_point start; // External Tool Interface //////////////////////////////////////////////////// extern "C" #if defined(_WIN32) __declspec(dllexport) #endif void Usage() { std::cout << "Usage: ./cl_gpu_metrics[.exe] <application> <args>" << std::endl; } extern "C" #if defined(_WIN32) __declspec(dllexport) #endif int ParseArgs(int argc, char* argv[]) { return 1; } extern "C" #if defined(_WIN32) __declspec(dllexport) #endif void SetToolEnv() {} // Internal Tool Functionality //////////////////////////////////////////////// static KernelMap GetKernelMap() { PTI_ASSERT(kernel_collector != nullptr); PTI_ASSERT(metric_collector != nullptr); std::vector<md::TTypedValue_1_0> report_list = metric_collector->GetReportList(); if (report_list.size() == 0) { return KernelMap(); } const ClKernelIntervalList& kernel_interval_list = kernel_collector->GetKernelIntervalList(); if (kernel_interval_list.size() == 0) { return KernelMap(); } KernelMap kernel_map; int gpu_timestamp_id = metric_collector->GetMetricId("QueryBeginTime"); PTI_ASSERT(gpu_timestamp_id >= 0); int eu_active_id = metric_collector->GetMetricId("EuActive"); PTI_ASSERT(eu_active_id >= 0); int eu_stall_id = metric_collector->GetMetricId("EuStall"); PTI_ASSERT(eu_stall_id >= 0); uint32_t report_size = metric_collector->GetReportSize(); PTI_ASSERT(report_size > 0); for (auto& kernel : kernel_interval_list) { uint32_t sample_count = 0; float eu_active = 0.0f, eu_stall = 0.0f; const md::TTypedValue_1_0* report = report_list.data(); while (report < report_list.data() + report_list.size()) { PTI_ASSERT(report[gpu_timestamp_id].ValueType == md::VALUE_TYPE_UINT64); uint64_t report_timestamp = metric_collector->GetKernelTimestamp( report[gpu_timestamp_id].ValueUInt64); if (report_timestamp >= kernel.start && report_timestamp <= kernel.end) { PTI_ASSERT(report[eu_active_id].ValueType == md::VALUE_TYPE_FLOAT); eu_active += report[eu_active_id].ValueFloat; PTI_ASSERT(report[eu_stall_id].ValueType == md::VALUE_TYPE_FLOAT); eu_stall += report[eu_stall_id].ValueFloat; ++sample_count; } if (report_timestamp > kernel.end) { break; } report += report_size; } if (sample_count > 0) { eu_active /= sample_count; eu_stall /= sample_count; } else { std::cerr << "[WARNING] No samples found for a kernel instance of " << kernel.name << ", results may be inaccurate" << std::endl; } if (kernel_map.count(kernel.name) == 0) { kernel_map[kernel.name] = {kernel.end - kernel.start, 1, eu_active, eu_stall}; } else { Kernel& kernel_info = kernel_map[kernel.name]; kernel_info.total_time += (kernel.end - kernel.start); kernel_info.eu_active = (kernel_info.eu_active * kernel_info.call_count + eu_active) / (kernel_info.call_count + 1); kernel_info.eu_stall = (kernel_info.eu_stall * kernel_info.call_count + eu_stall) / (kernel_info.call_count + 1); kernel_info.call_count += 1; } } return kernel_map; } static void PrintResults() { std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now(); std::chrono::duration<uint64_t, std::nano> time = end - start; KernelMap kernel_map = GetKernelMap(); if (kernel_map.size() == 0) { return; } std::set< std::pair<std::string, Kernel>, utils::Comparator > sorted_list( kernel_map.begin(), kernel_map.end()); uint64_t total_duration = 0; size_t max_name_length = kKernelLength; for (auto& value : sorted_list) { total_duration += value.second.total_time; if (value.first.size() > max_name_length) { max_name_length = value.first.size(); } } if (total_duration == 0) { return; } std::cerr << std::endl; std::cerr << "=== Device Metrics: ===" << std::endl; std::cerr << std::endl; std::cerr << "Total Execution Time (ns): " << time.count() << std::endl; std::cerr << "Total Kernel Time (ns): " << total_duration << std::endl; std::cerr << std::endl; std::cerr << std::setw(max_name_length) << "Kernel" << "," << std::setw(kCallsLength) << "Calls" << "," << std::setw(kTimeLength) << "Time (ns)" << "," << std::setw(kPercentLength) << "Time (%)" << "," << std::setw(kTimeLength) << "Average (ns)" << "," << std::setw(kPercentLength) << "EU Active (%)" << "," << std::setw(kPercentLength) << "EU Stall (%)" << "," << std::setw(kPercentLength) << "EU Idle (%)" << std::endl; for (auto& value : sorted_list) { const std::string& kernel = value.first; uint64_t call_count = value.second.call_count; uint64_t duration = value.second.total_time; uint64_t avg_duration = duration / call_count; float percent_duration = 100.0f * duration / total_duration; float eu_active = value.second.eu_active; float eu_stall = value.second.eu_stall; float eu_idle = 0.0f; if (eu_active + eu_stall < 100.0f) { eu_idle = 100.f - eu_active - eu_stall; } std::cerr << std::setw(max_name_length) << kernel << "," << std::setw(kCallsLength) << call_count << "," << std::setw(kTimeLength) << duration << "," << std::setw(kPercentLength) << std::setprecision(2) << std::fixed << percent_duration << "," << std::setw(kTimeLength) << avg_duration << "," << std::setw(kPercentLength) << std::setprecision(2) << std::fixed << eu_active << "," << std::setw(kPercentLength) << std::setprecision(2) << std::fixed << eu_stall << "," << std::setw(kPercentLength) << std::setprecision(2) << std::fixed << eu_idle << std::endl; } std::cerr << std::endl; } // Internal Tool Interface //////////////////////////////////////////////////// void EnableProfiling() { cl_device_id device = utils::cl::GetIntelDevice(CL_DEVICE_TYPE_GPU); if (device == nullptr) { std::cerr << "[WARNING] Unable to find target GPU device for tracing" << std::endl; return; } kernel_collector = ClKernelCollector::Create(device); if (kernel_collector == nullptr) { return; } metric_collector = ClMetricCollector::Create(device, "ComputeBasic"); if (metric_collector == nullptr) { kernel_collector->DisableTracing(); delete kernel_collector; kernel_collector = nullptr; return; } start = std::chrono::steady_clock::now(); } void DisableProfiling() { if (kernel_collector != nullptr || metric_collector != nullptr) { PTI_ASSERT(kernel_collector != nullptr); PTI_ASSERT(metric_collector != nullptr); kernel_collector->DisableTracing(); metric_collector->DisableTracing(); PrintResults(); delete kernel_collector; delete metric_collector; } }
30.212928
79
0.630506
[ "vector" ]
884e0044d04140f954a30aecf804920d423a00a3
1,960
cpp
C++
src/python/pml/interpolation_parameter.cpp
s3a-spatialaudio/VISR
55f6289bc5058d4898106f3520e1a60644ffb3ab
[ "ISC" ]
17
2019-03-12T14:52:22.000Z
2021-11-09T01:16:23.000Z
src/python/pml/interpolation_parameter.cpp
s3a-spatialaudio/VISR
55f6289bc5058d4898106f3520e1a60644ffb3ab
[ "ISC" ]
null
null
null
src/python/pml/interpolation_parameter.cpp
s3a-spatialaudio/VISR
55f6289bc5058d4898106f3520e1a60644ffb3ab
[ "ISC" ]
2
2019-08-11T12:53:07.000Z
2021-06-22T10:08:08.000Z
/* Copyright Institute of Sound and Vibration Research - All rights reserved */ #include <libpml/interpolation_parameter.hpp> #include <pybind11/pybind11.h> #include <pybind11/stl.h> #include <ciso646> #include <vector> #include <sstream> namespace visr { using pml::InterpolationParameter; using pml::InterpolationParameterConfig; namespace python { namespace pml { namespace py = pybind11; void exportInterpolationParameter( pybind11::module & m) { py::class_<InterpolationParameterConfig, ParameterConfigBase >( m, "InterpolationParameterConfig" ) .def( py::init<std::size_t>(), pybind11::arg( "numberOfInterpolants" ) ) .def_property_readonly( "numberOfInterpolants", &InterpolationParameterConfig::numberOfInterpolants ) .def( "compare", static_cast<bool(InterpolationParameterConfig::*)(InterpolationParameterConfig const&) const>(&InterpolationParameterConfig::compare), py::arg( "rhs" ) ) .def( "compare", static_cast<bool(InterpolationParameterConfig::*)(ParameterConfigBase const&) const>(&InterpolationParameterConfig::compare), py::arg( "rhs" ) ) ; py::class_<InterpolationParameter, ParameterBase, rbbl::InterpolationParameter>( m, "InterpolationParameter" ) .def_property_readonly_static( "staticType", [](py::object /*self*/) {return InterpolationParameter::staticType(); } ) .def( py::init<ParameterConfigBase const &>(), py::arg( "config" ) ) .def( py::init<InterpolationParameterConfig const &>(), py::arg("config") ) .def( py::init<InterpolationParameter const &>(), py::arg( "rhs" ) ) .def( py::init<InterpolationParameter::IdType, std::size_t>(), py::arg("id"), py::arg( "numberOfInterpolants" ) ) .def( py::init<InterpolationParameter::IdType, InterpolationParameter::IndexContainer const &, InterpolationParameter::WeightContainer const &>(), py::arg( "id" ), py::arg( "indices" ), py::arg( "weights" ) ) ; } } // namespace python } // namepace pml } // namespace visr
40.833333
174
0.728061
[ "object", "vector" ]
71fe3fa8f411eca8a7c1bf02cec95caac005596b
8,225
cc
C++
src/lib/ui/base_view/base_view.cc
liexusong/fuchsia
81897680af92a1848a063e3c20ff3a4892ccff07
[ "BSD-2-Clause" ]
14
2020-10-25T05:48:36.000Z
2021-09-20T02:46:20.000Z
src/lib/ui/base_view/base_view.cc
DamieFC/fuchsia
f78a4a1326f4a4bb5834500918756173c01bab4f
[ "BSD-2-Clause" ]
56
2021-06-03T03:16:25.000Z
2022-03-20T01:07:44.000Z
src/lib/ui/base_view/base_view.cc
DamieFC/fuchsia
f78a4a1326f4a4bb5834500918756173c01bab4f
[ "BSD-2-Clause" ]
2
2020-10-25T01:13:49.000Z
2020-10-26T02:32:13.000Z
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/lib/ui/base_view/base_view.h" #include <lib/fostr/fidl/fuchsia/ui/gfx/formatting.h> #include <lib/syslog/cpp/macros.h> #include <lib/trace/event.h> #include <lib/ui/scenic/cpp/commands.h> #include <lib/ui/scenic/cpp/view_token_pair.h> #include <zircon/status.h> namespace scenic { BaseView::BaseView(ViewContext context, const std::string& debug_name) : component_context_(context.component_context), listener_binding_(this, std::move(context.session_and_listener_request.second)), session_(std::move(context.session_and_listener_request.first)), root_node_(&session_), ime_client_(this), enable_ime_(context.enable_ime) { if (!context.view_ref_pair) { context.view_ref_pair = scenic::ViewRefPair::New(); } view_.emplace(&session_, std::move(context.view_token), std::move(context.view_ref_pair->control_ref), std::move(context.view_ref_pair->view_ref), debug_name); FX_DCHECK(view_); session_.SetDebugName(debug_name); // Listen for metrics events on our top node. root_node_.SetEventMask(fuchsia::ui::gfx::kMetricsEventMask); view_->AddChild(root_node_); if (enable_ime_) { ime_manager_ = component_context_->svc()->Connect<fuchsia::ui::input::ImeService>(); ime_.set_error_handler([](zx_status_t status) { FX_LOGS(ERROR) << "Interface error on: Input Method Editor " << zx_status_get_string(status); }); ime_manager_.set_error_handler([](zx_status_t status) { FX_LOGS(ERROR) << "Interface error on: Text Sync Service " << zx_status_get_string(status); }); } // We must immediately invalidate the scene, otherwise we wouldn't ever hook // the View up to the ViewHolder. An alternative would be to require // subclasses to call an Init() method to set up the initial connection. InvalidateScene(); } void BaseView::SetReleaseHandler(fit::function<void(zx_status_t)> callback) { listener_binding_.set_error_handler(std::move(callback)); } void BaseView::InvalidateScene(PresentCallback present_callback) { TRACE_DURATION("view", "BaseView::InvalidateScene"); if (present_callback) { callbacks_for_next_present_.push_back(std::move(present_callback)); } if (invalidate_pending_) return; invalidate_pending_ = true; // Present the scene ASAP. Pass in the last presentation time; otherwise, if // presentation_time argument is less than the previous time passed to // PresentScene, the Session will be closed. // (We cannot use the current time because the last requested presentation // time, |last_presentation_time_|, could still be in the future. This is // because Session.Present() returns after it _begins_ preparing the given // frame, not after it is presented.) if (!present_pending_) PresentScene(last_presentation_time_); } void BaseView::PresentScene() { PresentScene(last_presentation_time_); } void BaseView::OnScenicEvent(std::vector<fuchsia::ui::scenic::Event> events) { TRACE_DURATION("view", "BaseView::OnScenicEvent"); for (auto& event : events) { switch (event.Which()) { case ::fuchsia::ui::scenic::Event::Tag::kGfx: switch (event.gfx().Which()) { case ::fuchsia::ui::gfx::Event::Tag::kViewPropertiesChanged: { auto& evt = event.gfx().view_properties_changed(); FX_DCHECK(view_->id() == evt.view_id); auto old_props = view_properties_; view_properties_ = evt.properties; ::fuchsia::ui::gfx::BoundingBox layout_box = ViewPropertiesLayoutBox(view_properties_); logical_size_ = scenic::Max(layout_box.max - layout_box.min, 0.f); physical_size_.x = logical_size_.x * metrics_.scale_x; physical_size_.y = logical_size_.y * metrics_.scale_y; physical_size_.z = logical_size_.z * metrics_.scale_z; OnPropertiesChanged(std::move(old_props)); InvalidateScene(); break; } case fuchsia::ui::gfx::Event::Tag::kMetrics: { auto& evt = event.gfx().metrics(); if (evt.node_id == root_node_.id()) { auto old_metrics = metrics_; metrics_ = std::move(evt.metrics); physical_size_.x = logical_size_.x * metrics_.scale_x; physical_size_.y = logical_size_.y * metrics_.scale_y; physical_size_.z = logical_size_.z * metrics_.scale_z; OnMetricsChanged(std::move(old_metrics)); InvalidateScene(); } break; } default: { OnScenicEvent(std::move(event)); } } break; case ::fuchsia::ui::scenic::Event::Tag::kInput: { if (event.input().Which() == fuchsia::ui::input::InputEvent::Tag::kFocus && enable_ime_) { OnHandleFocusEvent(event.input().focus()); } OnInputEvent(std::move(event.input())); break; } case ::fuchsia::ui::scenic::Event::Tag::kUnhandled: { OnUnhandledCommand(std::move(event.unhandled())); break; } default: { OnScenicEvent(std::move(event)); } } } } void BaseView::PresentScene(zx_time_t presentation_time) { TRACE_DURATION("view", "BaseView::PresentScene"); // TODO(fxbug.dev/24406): Remove this when BaseView::PresentScene() is deprecated, // see fxbug.dev/24573. if (present_pending_) return; present_pending_ = true; // Keep track of the most recent presentation time we've passed to // Session.Present(), for use in InvalidateScene(). last_presentation_time_ = presentation_time; TRACE_FLOW_BEGIN("gfx", "Session::Present", session_present_count_); ++session_present_count_; session()->Present( presentation_time, [this, present_callbacks = std::move(callbacks_for_next_present_)]( fuchsia::images::PresentationInfo info) mutable { TRACE_DURATION("view", "BaseView::PresentationCallback"); TRACE_FLOW_END("gfx", "present_callback", info.presentation_time); FX_DCHECK(present_pending_); zx_time_t next_presentation_time = info.presentation_time + info.presentation_interval; bool present_needed = false; if (invalidate_pending_) { invalidate_pending_ = false; OnSceneInvalidated(std::move(info)); present_needed = true; } for (auto& callback : present_callbacks) { callback(info); } present_pending_ = false; if (present_needed) PresentScene(next_presentation_time); }); callbacks_for_next_present_.clear(); } // |fuchsia::ui::input::InputMethodEditorClient| void BaseView::DidUpdateState(fuchsia::ui::input::TextInputState state, std::unique_ptr<fuchsia::ui::input::InputEvent> input_event) { if (input_event) { const fuchsia::ui::input::InputEvent& input = *input_event; fuchsia::ui::input::InputEvent input_event_copy; fidl::Clone(input, &input_event_copy); OnInputEvent(std::move(input_event_copy)); } } // |fuchsia::ui::input::InputMethodEditorClient| void BaseView::OnAction(fuchsia::ui::input::InputMethodAction action) {} bool BaseView::OnHandleFocusEvent(const fuchsia::ui::input::FocusEvent& focus) { if (focus.focused) { ActivateIme(); return true; } else if (!focus.focused) { DeactivateIme(); return true; } return false; } void BaseView::ActivateIme() { ime_manager_->GetInputMethodEditor( fuchsia::ui::input::KeyboardType::TEXT, // keyboard type fuchsia::ui::input::InputMethodAction::DONE, // input method action fuchsia::ui::input::TextInputState{}, // initial state ime_client_.NewBinding(), // client ime_.NewRequest() // editor ); } void BaseView::DeactivateIme() { if (ime_) { ime_manager_->HideKeyboard(); ime_ = nullptr; } if (ime_client_.is_bound()) { ime_client_.Unbind(); } } } // namespace scenic
35.76087
99
0.66383
[ "vector" ]
9c025b9650ebc3d8d810080d207aa26045a76b11
4,530
cpp
C++
src/aten/src/ATen/native/npu/WhereKernelNpu.cpp
Ascend/pytorch
39849cf72dafe8d2fb68bd1679d8fd54ad60fcfc
[ "BSD-3-Clause" ]
1
2021-12-02T03:07:35.000Z
2021-12-02T03:07:35.000Z
src/aten/src/ATen/native/npu/WhereKernelNpu.cpp
Ascend/pytorch
39849cf72dafe8d2fb68bd1679d8fd54ad60fcfc
[ "BSD-3-Clause" ]
1
2021-11-12T07:23:03.000Z
2021-11-12T08:28:13.000Z
src/aten/src/ATen/native/npu/WhereKernelNpu.cpp
Ascend/pytorch
39849cf72dafe8d2fb68bd1679d8fd54ad60fcfc
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2020, Huawei Technologies. // Copyright (c) 2019, Facebook CORPORATION. // All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "ATen/native/npu/utils/OpAdapter.h" namespace at { namespace native { using namespace at::native::npu; std::tuple<Tensor, Tensor, Tensor> npu_expand_outplace( const Tensor &to_expand1, const Tensor &to_expand2, const Tensor &to_expand3, const char *api_name) { for (auto& t : {to_expand1, to_expand2, to_expand3}) { if (!t.defined()) { AT_ERROR(api_name, "(...) called with an undefined Tensor"); } } if (to_expand1.sizes().equals(to_expand2.sizes()) && to_expand1.sizes().equals(to_expand3.sizes())) { return std::make_tuple(to_expand1, to_expand2, to_expand3); } auto expanded_size12 = broadcast_ops_npu_output_size(to_expand1, to_expand2); auto expanded_size = broadcast_ops_npu_output_size(expanded_size12, to_expand3.sizes()); return std::make_tuple( to_expand1.expand(expanded_size, /*implicit=*/true), // see [expand implicit] to_expand2.expand(expanded_size, /*implicit=*/true), to_expand3.expand(expanded_size, /*implicit=*/true)); } Tensor _s_where_npu( const Tensor& condition, const Tensor& self, const Tensor& other) { Tensor result = OpPreparation::ApplyTensor(self); // maskrcnn need dynamicshape function of op "SelectV2" string opName = c10::npu::OptionsManager::CheckDynamicEnable() ? "SelectV2" : "Select"; OpCommand cmd; cmd.Name(opName) .Input(condition) .Input(self) .Input(other) .Output(result) .Run(); return result; } Tensor where_npu( const Tensor& condition, const Tensor& self, const Tensor& other) { TORCH_CHECK(condition.device() == self.device() && self.device() == other.device(), "expected condition, x and y to be on the same device, but condition is on ", condition.device(), " and x and y are on ", self.device(), " and ", other.device(), " respectively"); if (condition.scalar_type() != ScalarType::Byte && condition.scalar_type() != ScalarType::Bool) { AT_ERROR("Expected condition to have ScalarType Byte, but got ScalarType ", toString(condition.scalar_type())); } Tensor b_condition, b_self, b_other; std::tie(b_condition, b_self, b_other) = npu_expand_outplace(condition, self, other, "where_npu"); return at::_s_where(b_condition, b_self, b_other); } SmallVector<int64_t, SIZE> where_npu_output_size(const Tensor& condition){ int64_t dim = condition.dim(); Tensor boolSelf = condition.npu_dtype_cast(ScalarType::Bool); Tensor intSelf = boolSelf.npu_dtype_cast(ScalarType::Int); Tensor coutNonzeroSelf = at::sum(intSelf, ScalarType::Int); int64_t nonzeroNum = coutNonzeroSelf.item().toInt(); SmallVector<int64_t, SIZE> outputSize = {nonzeroNum, dim}; return outputSize; } vector<Tensor> where_npu(const Tensor& condition) { Tensor formatCastOfCondition = condition; if (condition.storage().unsafeGetStorageImpl()->npu_desc_.npu_format_ != ACL_FORMAT_ND) { formatCastOfCondition = formatCastOfCondition.npu_format_cast(ACL_FORMAT_ND); } if (condition.scalar_type() == ScalarType::Half) { formatCastOfCondition = formatCastOfCondition.npu_dtype_cast(ScalarType::Float); } // calculate the output size auto outputSize = where_npu_output_size(formatCastOfCondition); // construct the output tensor of the NPU Tensor result = at::empty_with_format( outputSize, formatCastOfCondition.options().dtype(kLong), ACL_FORMAT_ND); OpCommand cmd; cmd.Name("NonZero") .Input(formatCastOfCondition) .Output(result) .Run(); result = result.transpose(1, 0); std::vector<Tensor> chunkResult = result.chunk(result.size(0), 0); std::vector<Tensor> squeezeResult; for(int64_t i = 0; i < chunkResult.size(); i++){ squeezeResult.push_back(chunkResult[i].squeeze(0)); } return squeezeResult; } } // namespace native } // namespace at
36.24
103
0.710155
[ "vector" ]
9c0c2abffd9fefed9ba0d8849f43226ebcad8657
16,829
cpp
C++
boinc/client/gpu_amd.cpp
tomasbrod/tbboinc
c125cc355b2dc9a1e536b5e5ded028d4e7f4613a
[ "MIT" ]
null
null
null
boinc/client/gpu_amd.cpp
tomasbrod/tbboinc
c125cc355b2dc9a1e536b5e5ded028d4e7f4613a
[ "MIT" ]
4
2020-09-07T15:54:45.000Z
2020-09-27T16:47:16.000Z
boinc_new/client/gpu_amd.cpp
tomasbrod/tbboinc
c125cc355b2dc9a1e536b5e5ded028d4e7f4613a
[ "MIT" ]
null
null
null
// This file is part of BOINC. // http://boinc.berkeley.edu // Copyright (C) 2012 University of California // // BOINC is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License // as published by the Free Software Foundation, // either version 3 of the License, or (at your option) any later version. // // BOINC 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 Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with BOINC. If not, see <http://www.gnu.org/licenses/>. // Detection of AMD/ATI GPUs // // Docs: // http://developer.amd.com/gpu/ATIStreamSDK/assets/ATI_Stream_SDK_CAL_Programming_Guide_v2.0%5B1%5D.pdf // ?? why don't they have HTML docs?? #ifdef _WIN32 #include "boinc_win.h" #ifdef _MSC_VER #define snprintf _snprintf #endif #else #ifdef __APPLE__ // Suppress obsolete warning when building for OS 10.3.9 #define DLOPEN_NO_WARN #include <mach-o/dyld.h> #endif #include "config.h" #include <dlfcn.h> #endif #include <vector> #include <string> using std::vector; using std::string; #include "coproc.h" #include "str_replace.h" #include "util.h" #include "client_msgs.h" #include "gpu_detect.h" static void get_available_ati_ram(COPROC_ATI &cc, vector<string>& warnings); // criteria: // // - double precision support // - local RAM // - speed // int ati_compare(COPROC_ATI& c1, COPROC_ATI& c2, bool loose) { if (c1.attribs.doublePrecision && !c2.attribs.doublePrecision) return 1; if (!c1.attribs.doublePrecision && c2.attribs.doublePrecision) return -1; if (loose) { if (c1.attribs.localRAM> 1.4*c2.attribs.localRAM) return 1; if (c1.attribs.localRAM< .7* c2.attribs.localRAM) return -1; return 0; } if (c1.attribs.localRAM > c2.attribs.localRAM) return 1; if (c1.attribs.localRAM < c2.attribs.localRAM) return -1; double s1 = c1.peak_flops; double s2 = c2.peak_flops; if (s1 > s2) return 1; if (s1 < s2) return -1; return 0; } #ifdef _WIN32 typedef int (__stdcall *ATI_ATTRIBS) (CALdeviceattribs *attribs, CALuint ordinal); typedef int (__stdcall *ATI_CLOSE)(void); typedef int (__stdcall *ATI_GDC)(CALuint *numDevices); typedef int (__stdcall *ATI_GDI)(void); typedef int (__stdcall *ATI_INFO) (CALdeviceinfo *info, CALuint ordinal); typedef int (__stdcall *ATI_VER) (CALuint *cal_major, CALuint *cal_minor, CALuint *cal_imp); typedef int (__stdcall *ATI_STATUS) (CALdevicestatus*, CALdevice); typedef int (__stdcall *ATI_DEVICEOPEN) (CALdevice*, CALuint); typedef int (__stdcall *ATI_DEVICECLOSE) (CALdevice); ATI_ATTRIBS p_calDeviceGetAttribs = NULL; ATI_CLOSE p_calShutdown = NULL; ATI_GDC p_calDeviceGetCount = NULL; ATI_GDI p_calInit = NULL; ATI_INFO p_calDeviceGetInfo = NULL; ATI_VER p_calGetVersion = NULL; ATI_STATUS p_calDeviceGetStatus = NULL; ATI_DEVICEOPEN p_calDeviceOpen = NULL; ATI_DEVICECLOSE p_calDeviceClose = NULL; #else int (*p_calInit)(); int (*p_calGetVersion)(CALuint*, CALuint*, CALuint*); int (*p_calDeviceGetCount)(CALuint*); int (*p_calDeviceGetAttribs)(CALdeviceattribs*, CALuint); int (*p_calShutdown)(); int (*p_calDeviceGetInfo)(CALdeviceinfo*, CALuint); int (*p_calDeviceGetStatus)(CALdevicestatus*, CALdevice); int (*p_calDeviceOpen)(CALdevice*, CALuint); int (*p_calDeviceClose)(CALdevice); #endif void COPROC_ATI::get( vector<string>& warnings ) { CALuint numDevices, cal_major, cal_minor, cal_imp; char buf[256]; int retval; COPROC_ATI cc, cc2; string s, gpu_name; attribs.struct_size = sizeof(CALdeviceattribs); numDevices =0; #ifdef _WIN32 #if defined _M_X64 const char* atilib_name = "aticalrt64.dll"; const char* amdlib_name = "amdcalrt64.dll"; #else const char* atilib_name = "aticalrt.dll"; const char* amdlib_name = "amdcalrt.dll"; #endif HINSTANCE callib = LoadLibrary(atilib_name); if (callib) { atirt_detected = true; } else { callib = LoadLibrary(amdlib_name); if (callib) { amdrt_detected = true; } } if (!callib) { warnings.push_back("No ATI library found."); return; } p_calInit = (ATI_GDI)GetProcAddress(callib, "calInit" ); p_calGetVersion = (ATI_VER)GetProcAddress(callib, "calGetVersion" ); p_calDeviceGetCount = (ATI_GDC)GetProcAddress(callib, "calDeviceGetCount" ); p_calDeviceGetAttribs =(ATI_ATTRIBS)GetProcAddress(callib, "calDeviceGetAttribs" ); p_calShutdown = (ATI_CLOSE)GetProcAddress(callib, "calShutdown" ); p_calDeviceGetInfo = (ATI_INFO)GetProcAddress(callib, "calDeviceGetInfo" ); p_calDeviceGetStatus = (ATI_STATUS)GetProcAddress(callib, "calDeviceGetStatus" ); p_calDeviceOpen = (ATI_DEVICEOPEN)GetProcAddress(callib, "calDeviceOpen" ); p_calDeviceClose = (ATI_DEVICECLOSE)GetProcAddress(callib, "calDeviceClose" ); #else void* callib = dlopen("libaticalrt.so", RTLD_NOW); if (!callib) { snprintf(buf, sizeof(buf), "ATI: %s", dlerror()); warnings.push_back(buf); return; } atirt_detected = true; p_calInit = (int(*)()) dlsym(callib, "calInit"); p_calGetVersion = (int(*)(CALuint*, CALuint*, CALuint*)) dlsym(callib, "calGetVersion"); p_calDeviceGetCount = (int(*)(CALuint*)) dlsym(callib, "calDeviceGetCount"); p_calDeviceGetAttribs = (int(*)(CALdeviceattribs*, CALuint)) dlsym(callib, "calDeviceGetAttribs"); p_calShutdown = (int(*)()) dlsym(callib, "calShutdown"); p_calDeviceGetInfo = (int(*)(CALdeviceinfo*, CALuint)) dlsym(callib, "calDeviceGetInfo"); p_calDeviceGetStatus = (int(*)(CALdevicestatus*, CALdevice)) dlsym(callib, "calDeviceGetStatus"); p_calDeviceOpen = (int(*)(CALdevice*, CALuint)) dlsym(callib, "calDeviceOpen"); p_calDeviceClose = (int(*)(CALdevice)) dlsym(callib, "calDeviceClose"); #endif if (!p_calInit) { warnings.push_back("calInit() missing from CAL library"); goto leave; } if (!p_calGetVersion) { warnings.push_back("calGetVersion() missing from CAL library"); goto leave; } if (!p_calDeviceGetCount) { warnings.push_back("calDeviceGetCount() missing from CAL library"); goto leave; } if (!p_calDeviceGetAttribs) { warnings.push_back("calDeviceGetAttribs() missing from CAL library"); goto leave; } if (!p_calDeviceGetInfo) { warnings.push_back("calDeviceGetInfo() missing from CAL library"); goto leave; } retval = (*p_calInit)(); if (retval != CAL_RESULT_OK) { snprintf(buf, sizeof(buf), "calInit() returned %d", retval); warnings.push_back(buf); goto leave; } retval = (*p_calDeviceGetCount)(&numDevices); if (retval != CAL_RESULT_OK) { snprintf(buf, sizeof(buf), "calDeviceGetCount() returned %d", retval); warnings.push_back(buf); goto leave; } retval = (*p_calGetVersion)(&cal_major, &cal_minor, &cal_imp); if (retval != CAL_RESULT_OK) { snprintf(buf, sizeof(buf), "calGetVersion() returned %d", retval); warnings.push_back(buf); goto leave; } if (!numDevices) { warnings.push_back("No usable CAL devices found"); goto leave; } for (CALuint i=0; i<numDevices; i++) { retval = (*p_calDeviceGetInfo)(&info, i); if (retval != CAL_RESULT_OK) { snprintf(buf, sizeof(buf), "calDeviceGetInfo() returned %d", retval); warnings.push_back(buf); goto leave; } retval = (*p_calDeviceGetAttribs)(&attribs, i); if (retval != CAL_RESULT_OK) { snprintf(buf, sizeof(buf), "calDeviceGetAttribs() returned %d", retval); warnings.push_back(buf); goto leave; } switch ((int)attribs.target) { case CAL_TARGET_600: gpu_name="ATI Radeon HD 2900 (RV600)"; break; case CAL_TARGET_610: gpu_name="ATI Radeon HD 2300/2400/3200/4200 (RV610)"; attribs.numberOfSIMD=1; // set correct values (reported wrong by driver) attribs.wavefrontSize=32; break; case CAL_TARGET_630: gpu_name="ATI Radeon HD 2600/3650 (RV630/RV635)"; // set correct values (reported wrong by driver) attribs.numberOfSIMD=3; attribs.wavefrontSize=32; break; case CAL_TARGET_670: gpu_name="ATI Radeon HD 3800 (RV670)"; break; case CAL_TARGET_710: gpu_name="ATI Radeon HD 4350/4550 (R710)"; break; case CAL_TARGET_730: gpu_name="ATI Radeon HD 4600 series (R730)"; break; case CAL_TARGET_7XX: gpu_name="ATI Radeon (RV700 class)"; break; case CAL_TARGET_770: gpu_name="ATI Radeon HD 4700/4800 (RV740/RV770)"; break; case 8: gpu_name="ATI Radeon HD 5800/5900 series (Cypress/Hemlock)"; break; case 9: gpu_name="ATI Radeon HD 5700/6750/6770 series (Juniper)"; break; case 10: gpu_name="ATI Radeon HD 5500/5600 series (Redwood)"; break; case 11: gpu_name="ATI Radeon HD 5400/R5 210 series (Cedar)"; break; case 12: gpu_name="AMD Radeon HD 6370D/6380G/6410D/6480G (Sumo)"; break; case 13: gpu_name="AMD Radeon HD 6520G/6530D/6550D/6620G (SuperSumo)"; break; case 14: gpu_name="AMD Radeon HD 6200/6300/7200/7300 series (Wrestler)"; break; case 15: gpu_name="AMD Radeon HD 6900 series (Cayman)"; break; case 16: gpu_name="AMD Radeon HD (Kauai)"; break; case 17: gpu_name="AMD Radeon HD 6790/6850/6870 series (Barts)"; break; case 18: gpu_name="AMD Radeon HD 6570/6670/7570/7670 series (Turks)"; break; case 19: gpu_name="AMD Radeon HD 6350/6450/7450/7470/R5 230 series (Caicos)"; break; case 20: gpu_name="AMD Radeon HD 7870/7950/7970/R9 280/R9 280X series (Tahiti)"; break; case 21: gpu_name="AMD Radeon HD 7850/7870 series (Pitcairn)"; break; case 22: gpu_name="AMD Radeon HD 7700/R7 250X/R9 255 series (Capeverde)"; break; case 23: gpu_name="AMD Radeon HD 7500/7600/8500/8600 series (Devastator)"; break; case 24: gpu_name="AMD Radeon HD 7400/7500/8300/8400 series (Scrapper)"; break; case 25: gpu_name="AMD Radeon HD 8600/8790M/R5 330/R5 340/R7 240/R7 250/R7 340/R7 350 (Oland)"; break; case 26: gpu_name="AMD Radeon HD 7790/R7 260/R7 260X/R9 360 (Bonaire)"; break; case 27: gpu_name="AMD Radeon HD (Spectre)"; // Kaveri break; case 28: gpu_name="AMD Radeon HD (Spooky)"; // Kaveri break; case 29: gpu_name="AMD Radeon HD 8200/8300/8400 series (Kalindi)"; // Kabini break; case 30: gpu_name="AMD Radeon HD 8600M (Hainan)"; break; case 31: gpu_name="AMD Radeon R7 265/R9 270/R9 270X/R9 370 (Curacao)"; break; case 32: gpu_name="AMD Radeon R9 290 (Hawaii)"; break; case 33: gpu_name="AMD Radeon R2/R3 (Skunk)"; // Mullins/new FT3 APU break; case 34: gpu_name="AMD Radeon R9 285/R9 380 (Tonga)"; break; case 35: gpu_name="AMD Radeon R9 295X2 (Vesuvius)"; break; case 36: gpu_name="AMD Radeon R7 360 (Tobago)"; break; case 37: gpu_name="AMD Radeon R7 370/R9 370X (Trinidad)"; break; case 38: gpu_name="AMD Radeon R9 390/R9 390X (Grenada)"; break; case 39: gpu_name="AMD Radeon R9 Fury/R9 Nano/R9 Fury X/R9 Fury X2 (Fiji)"; break; default: gpu_name="AMD Radeon HD (unknown)"; break; } have_cal = true; cc.have_cal = true; cc.attribs = attribs; cc.info = info; safe_strcpy(cc.name, gpu_name.c_str()); snprintf(cc.version, sizeof(cc.version), "%d.%d.%d", cal_major, cal_minor, cal_imp); cc.amdrt_detected = amdrt_detected; cc.atirt_detected = atirt_detected; cc.device_num = i; cc.set_peak_flops(); if (cc.bad_gpu_peak_flops("CAL", s)) { warnings.push_back(s); } get_available_ati_ram(cc, warnings); ati_gpus.push_back(cc); } // shut down CAL, otherwise Lenovo won't be able to switch to low-power GPU // retval = (*p_calShutdown)(); if (!ati_gpus.size()) { warnings.push_back("No ATI GPUs found"); } leave: #ifdef _WIN32 if (callib) FreeLibrary(callib); #else if (callib) dlclose(callib); #endif } void COPROC_ATI::correlate( bool use_all, vector<int>& ignore_devs ) { char buf[256]; if (!ati_gpus.size()) return; // find the most capable non-ignored instance // bool first = true; unsigned int i; for (i=0; i<ati_gpus.size(); i++) { if (in_vector(ati_gpus[i].device_num, ignore_devs)) continue; if (first) { *this = ati_gpus[i]; first = false; } else if (ati_compare(ati_gpus[i], *this, false) > 0) { *this = ati_gpus[i]; } } // see which other instances are equivalent, // and set the "count" and "device_nums" fields // count = 0; for (i=0; i<ati_gpus.size(); i++) { ati_gpus[i].description(buf, sizeof(buf)); if (in_vector(ati_gpus[i].device_num, ignore_devs)) { ati_gpus[i].is_used = COPROC_IGNORED; } else if (this->have_opencl && !ati_gpus[i].have_opencl) { ati_gpus[i].is_used = COPROC_UNUSED; } else if (this->have_cal && !ati_gpus[i].have_cal) { ati_gpus[i].is_used = COPROC_UNUSED; } else if (use_all || !ati_compare(ati_gpus[i], *this, true)) { device_nums[count] = ati_gpus[i].device_num; count++; ati_gpus[i].is_used = COPROC_USED; } else { ati_gpus[i].is_used = COPROC_UNUSED; } } } // get available RAM of ATI GPU // // CAUTION: as currently written, this method should be // called only from COPROC_ATI::get(). If in the future // you wish to call it from additional places: // * It must be called from a separate child process on // dual-GPU laptops (e.g., Macbook Pros) with the results // communicated to the main client process via IPC or a // temp file. See the comments about dual-GPU laptops // in gpu_detect.cpp and main.cpp for more details. // * The CAL library must be loaded and calInit() called // first. // * See client/coproc_detect.cpp and cpu_sched.cpp in // BOINC 6.12.36 for an earlier attempt to call this // from the scheduler. Note that it was abandoned // due to repeated calls crashing the driver. // static void get_available_ati_ram(COPROC_ATI &cc, vector<string>& warnings) { CALdevicestatus st; CALdevice dev; char buf[256]; int retval; cc.available_ram = cc.attribs.localRAM*MEGA; st.struct_size = sizeof(CALdevicestatus); if (!p_calDeviceOpen) { warnings.push_back("calDeviceOpen() missing from CAL library"); return; } if (!p_calDeviceGetStatus) { warnings.push_back("calDeviceGetStatus() missing from CAL library"); return; } if (!p_calDeviceClose) { warnings.push_back("calDeviceClose() missing from CAL library"); return; } retval = (*p_calDeviceOpen)(&dev, cc.device_num); if (retval) { snprintf(buf, sizeof(buf), "[coproc] calDeviceOpen(%d) returned %d", cc.device_num, retval ); warnings.push_back(buf); return; } retval = (*p_calDeviceGetStatus)(&st, dev); if (retval) { snprintf(buf, sizeof(buf), "[coproc] calDeviceGetStatus(%d) returned %d", cc.device_num, retval ); warnings.push_back(buf); (*p_calDeviceClose)(dev); return; } cc.available_ram = st.availLocalRAM*MEGA; (*p_calDeviceClose)(dev); }
33.193294
104
0.616436
[ "vector" ]
9c0c36a02c42439024b72644785f10d76e6c8e25
2,481
cpp
C++
test/startup/multiple_spawner/command/initializer_list.cpp
arkantos493/MPICXX
ffbaeaaa3c7248e2087c3716ec71e0612aafe689
[ "MIT" ]
1
2020-10-20T06:53:05.000Z
2020-10-20T06:53:05.000Z
test/startup/multiple_spawner/command/initializer_list.cpp
arkantos493/MPICXX
ffbaeaaa3c7248e2087c3716ec71e0612aafe689
[ "MIT" ]
null
null
null
test/startup/multiple_spawner/command/initializer_list.cpp
arkantos493/MPICXX
ffbaeaaa3c7248e2087c3716ec71e0612aafe689
[ "MIT" ]
1
2020-08-13T17:46:40.000Z
2020-08-13T17:46:40.000Z
/** * @file * @author Marcel Breyer * @date 2020-07-29 * @copyright This file is distributed under the MIT License. * * @brief Test cases for the @ref mpicxx::multiple_spawner::set_command(std::initializer_list<std::string>) member function provided * by the @ref mpicxx::multiple_spawner class. * @details Testsuite: *MultipleSpawnerTest* * | test case name | test case description | * |:------------------------------------------------|:----------------------------------------------------------------------------------------------------------------------| * | SetExecutableNamesViaInitializerList | set new executable names from a [`std::initializer_list`](https://en.cppreference.com/w/cpp/utility/initializer_list) | * | SetExecutableNamesViaInitializerListInvalidSize | [`std::initializer_list`](https://en.cppreference.com/w/cpp/utility/initializer_list) with illegal size (death test) | * | SetExecutableNamesViaInitializerListInvalidName | try to set new executable names with an invalid name (death test) | */ #include <mpicxx/startup/multiple_spawner.hpp> #include <gtest/gtest.h> #include <initializer_list> #include <string> #include <utility> using namespace std::string_literals; TEST(MultipleSpawnerTest, SetExecutableNamesViaInitializerList) { // create new multiple_spawner object mpicxx::multiple_spawner ms({ { "foo", 1 }, { "bar", 1 } }); // set new executable names ms.set_command({ "baz", "qux" }); // check if names were set correctly ASSERT_EQ(ms.command().size(), 2); EXPECT_EQ(ms.command_at(0), "baz"s); EXPECT_EQ(ms.command_at(1), "qux"s); } TEST(MultipleSpawnerDeathTest, SetExecutableNamesViaInitializerListInvalidSize) { // create new multiple_spawner object mpicxx::multiple_spawner ms({ { "foo", 1 }, { "bar", 1 } }); // set new executable names with different size ASSERT_DEATH( ms.set_command({ "baz" }) , ""); ASSERT_DEATH( ms.set_command({ "baz", "qux", "quux" }) , ""); } TEST(MultipleSpawnerDeathTest, SetExecutableNamesViaInitializerListInvalidName) { // create new multiple_spawner object mpicxx::multiple_spawner ms({ { "foo", 1 }, { "bar", 1 } }); // set new executable names with illegal name ASSERT_DEATH( ms.set_command({ "baz", "" }), ""); }
45.109091
174
0.605401
[ "object" ]
9c1f9c6b9eba40b885073638f43b57fc627c9723
22,686
cpp
C++
src/codec/encoder/HoudiniEncoder.cpp
Esri/palladio
d94a93ab79b9c7c77f41fa2f36af8d11cda3d891
[ "Apache-2.0" ]
95
2018-01-27T10:04:30.000Z
2022-03-25T20:59:18.000Z
src/codec/encoder/HoudiniEncoder.cpp
Esri/palladio
d94a93ab79b9c7c77f41fa2f36af8d11cda3d891
[ "Apache-2.0" ]
62
2018-01-27T15:11:23.000Z
2022-01-13T17:17:57.000Z
src/codec/encoder/HoudiniEncoder.cpp
Esri/palladio
d94a93ab79b9c7c77f41fa2f36af8d11cda3d891
[ "Apache-2.0" ]
20
2018-02-14T09:58:11.000Z
2021-08-04T02:16:48.000Z
/* * Copyright 2014-2020 Esri R&D Zurich and VRBN * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "HoudiniEncoder.h" #include "HoudiniCallbacks.h" #include "prtx/Attributable.h" #include "prtx/Exception.h" #include "prtx/ExtensionManager.h" #include "prtx/GenerateContext.h" #include "prtx/Geometry.h" #include "prtx/Log.h" #include "prtx/Material.h" #include "prtx/Mesh.h" #include "prtx/ReportsCollector.h" #include "prtx/Shape.h" #include "prtx/ShapeIterator.h" #include "prtx/URI.h" #include "prt/prt.h" #include <algorithm> #include <iostream> #include <limits> #include <memory> #include <numeric> #include <set> #include <sstream> #include <vector> namespace { constexpr bool DBG = false; constexpr const wchar_t* ENC_NAME = L"SideFX(tm) Houdini(tm) Encoder"; constexpr const wchar_t* ENC_DESCRIPTION = L"Encodes geometry into the Houdini format."; const prtx::EncodePreparator::PreparationFlags PREP_FLAGS = prtx::EncodePreparator::PreparationFlags() .instancing(false) .mergeByMaterial(false) .triangulate(false) .processHoles(prtx::HoleProcessor::TRIANGULATE_FACES_WITH_HOLES) .mergeVertices(true) .cleanupVertexNormals(true) .cleanupUVs(true) .processVertexNormals(prtx::VertexNormalProcessor::SET_MISSING_TO_FACE_NORMALS) .indexSharing(prtx::EncodePreparator::PreparationFlags::INDICES_SAME_FOR_ALL_VERTEX_ATTRIBUTES); std::vector<const wchar_t*> toPtrVec(const prtx::WStringVector& wsv) { std::vector<const wchar_t*> pw(wsv.size()); for (size_t i = 0; i < wsv.size(); i++) pw[i] = wsv[i].c_str(); return pw; } template <typename T> std::pair<std::vector<const T*>, std::vector<size_t>> toPtrVec(const std::vector<std::vector<T>>& v) { std::vector<const T*> pv(v.size()); std::vector<size_t> ps(v.size()); for (size_t i = 0; i < v.size(); i++) { pv[i] = v[i].data(); ps[i] = v[i].size(); } return std::make_pair(pv, ps); } std::wstring uriToPath(const prtx::TexturePtr& t) { return t->getURI()->getPath(); } // we blacklist all CGA-style material attribute keys, see prtx/Material.h const std::set<std::wstring> MATERIAL_ATTRIBUTE_BLACKLIST = { L"ambient.b", L"ambient.g", L"ambient.r", L"bumpmap.rw", L"bumpmap.su", L"bumpmap.sv", L"bumpmap.tu", L"bumpmap.tv", L"color.a", L"color.b", L"color.g", L"color.r", L"color.rgb", L"colormap.rw", L"colormap.su", L"colormap.sv", L"colormap.tu", L"colormap.tv", L"dirtmap.rw", L"dirtmap.su", L"dirtmap.sv", L"dirtmap.tu", L"dirtmap.tv", L"normalmap.rw", L"normalmap.su", L"normalmap.sv", L"normalmap.tu", L"normalmap.tv", L"opacitymap.rw", L"opacitymap.su", L"opacitymap.sv", L"opacitymap.tu", L"opacitymap.tv", L"specular.b", L"specular.g", L"specular.r", L"specularmap.rw", L"specularmap.su", L"specularmap.sv", L"specularmap.tu", L"specularmap.tv", L"bumpmap", L"colormap", L"dirtmap", L"normalmap", L"opacitymap", L"specularmap" #if PRT_VERSION_MAJOR > 1 // also blacklist CGA-style PBR attrs from CE 2019.0, PRT 2.x , L"opacitymap.mode", L"emissive.b", L"emissive.g", L"emissive.r", L"emissivemap.rw", L"emissivemap.su", L"emissivemap.sv", L"emissivemap.tu", L"emissivemap.tv", L"metallicmap.rw", L"metallicmap.su", L"metallicmap.sv", L"metallicmap.tu", L"metallicmap.tv", L"occlusionmap.rw", L"occlusionmap.su", L"occlusionmap.sv", L"occlusionmap.tu", L"occlusionmap.tv", L"roughnessmap.rw", L"roughnessmap.su", L"roughnessmap.sv", L"roughnessmap.tu", L"roughnessmap.tv", L"emissivemap", L"metallicmap", L"occlusionmap", L"roughnessmap" #endif }; void convertMaterialToAttributeMap(prtx::PRTUtils::AttributeMapBuilderPtr& aBuilder, const prtx::Material& prtxAttr, const prtx::WStringVector& keys) { if (DBG) log_debug(L"-- converting material: %1%") % prtxAttr.name(); for (const auto& key : keys) { if (MATERIAL_ATTRIBUTE_BLACKLIST.count(key) > 0) continue; if (DBG) log_debug(L" key: %1%") % key; switch (prtxAttr.getType(key)) { case prt::Attributable::PT_BOOL: aBuilder->setBool(key.c_str(), prtxAttr.getBool(key) == prtx::PRTX_TRUE); break; case prt::Attributable::PT_FLOAT: aBuilder->setFloat(key.c_str(), prtxAttr.getFloat(key)); break; case prt::Attributable::PT_INT: aBuilder->setInt(key.c_str(), prtxAttr.getInt(key)); break; case prt::Attributable::PT_STRING: { const std::wstring& v = prtxAttr.getString(key); // explicit copy aBuilder->setString(key.c_str(), v.c_str()); // also passing on empty strings break; } case prt::Attributable::PT_BOOL_ARRAY: { const std::vector<uint8_t>& ba = prtxAttr.getBoolArray(key); auto boo = std::unique_ptr<bool[]>(new bool[ba.size()]); for (size_t i = 0; i < ba.size(); i++) boo[i] = (ba[i] == prtx::PRTX_TRUE); aBuilder->setBoolArray(key.c_str(), boo.get(), ba.size()); break; } case prt::Attributable::PT_INT_ARRAY: { const std::vector<int32_t>& array = prtxAttr.getIntArray(key); aBuilder->setIntArray(key.c_str(), &array[0], array.size()); break; } case prt::Attributable::PT_FLOAT_ARRAY: { const std::vector<double>& array = prtxAttr.getFloatArray(key); aBuilder->setFloatArray(key.c_str(), array.data(), array.size()); break; } case prt::Attributable::PT_STRING_ARRAY: { const prtx::WStringVector& a = prtxAttr.getStringArray(key); std::vector<const wchar_t*> pw = toPtrVec(a); aBuilder->setStringArray(key.c_str(), pw.data(), pw.size()); break; } case prtx::Material::PT_TEXTURE: { const auto& t = prtxAttr.getTexture(key); const std::wstring p = uriToPath(t); aBuilder->setString(key.c_str(), p.c_str()); break; } case prtx::Material::PT_TEXTURE_ARRAY: { const auto& ta = prtxAttr.getTextureArray(key); prtx::WStringVector pa(ta.size()); std::transform(ta.begin(), ta.end(), pa.begin(), uriToPath); std::vector<const wchar_t*> ppa = toPtrVec(pa); aBuilder->setStringArray(key.c_str(), ppa.data(), ppa.size()); break; } default: if (DBG) log_debug(L"ignored atttribute '%s' with type %d") % key % prtxAttr.getType(key); break; } } } void convertReportsToAttributeMap(prtx::PRTUtils::AttributeMapBuilderPtr& amb, const prtx::ReportsPtr& r) { if (!r) return; for (const auto& b : r->mBools) amb->setBool(b.first->c_str(), b.second); for (const auto& f : r->mFloats) amb->setFloat(f.first->c_str(), f.second); for (const auto& s : r->mStrings) amb->setString(s.first->c_str(), s.second->c_str()); } template <typename F> void forEachKey(prt::Attributable const* a, F f) { if (a == nullptr) return; size_t keyCount = 0; wchar_t const* const* keys = a->getKeys(&keyCount); for (size_t k = 0; k < keyCount; k++) { wchar_t const* const key = keys[k]; f(a, key); } } void forwardGenericAttributes(HoudiniCallbacks* hc, size_t initialShapeIndex, const prtx::InitialShape& initialShape, const prtx::ShapePtr& shape) { forEachKey(initialShape.getAttributeMap(), [&hc, &shape, &initialShapeIndex, &initialShape](prt::Attributable const* a, wchar_t const* key) { assert(key != nullptr); const std::wstring keyStr(key); if (!shape->hasKey(keyStr)) return; switch (shape->getType(keyStr)) { case prtx::Attributable::PT_STRING: { const auto v = shape->getString(keyStr); hc->attrString(initialShapeIndex, shape->getID(), key, v.c_str()); break; } case prtx::Attributable::PT_FLOAT: { const auto v = shape->getFloat(keyStr); hc->attrFloat(initialShapeIndex, shape->getID(), key, v); break; } case prtx::Attributable::PT_BOOL: { const auto v = shape->getBool(keyStr); hc->attrBool(initialShapeIndex, shape->getID(), key, (v == prtx::PRTX_TRUE)); break; } case prtx::Attributable::PT_STRING_ARRAY: { const prtx::WStringVector& v = shape->getStringArray(keyStr); const std::vector<const wchar_t*> vPtrs = toPtrVec(v); hc->attrStringArray(initialShapeIndex, shape->getID(), key, vPtrs.data(), vPtrs.size(), 1); break; } case prtx::Attributable::PT_FLOAT_ARRAY: { const prtx::DoubleVector& v = shape->getFloatArray(keyStr); hc->attrFloatArray(initialShapeIndex, shape->getID(), key, v.data(), v.size(), 1); break; } case prtx::Attributable::PT_BOOL_ARRAY: { const prtx::BoolVector& v = shape->getBoolArray(keyStr); const std::unique_ptr<bool[]> vPtrs(new bool[v.size()]); for (size_t i = 0; i < v.size(); i++) vPtrs[i] = prtx::toPrimitive(v[i]); hc->attrBoolArray(initialShapeIndex, shape->getID(), key, vPtrs.get(), v.size(), 1); break; } default: break; } }); } using AttributeMapNOPtrVector = std::vector<const prt::AttributeMap*>; struct AttributeMapNOPtrVectorOwner { AttributeMapNOPtrVector v; ~AttributeMapNOPtrVectorOwner() { for (const auto& m : v) { if (m) m->destroy(); } } }; struct TextureUVMapping { std::wstring key; uint8_t index; int8_t uvSet; }; const std::vector<TextureUVMapping> TEXTURE_UV_MAPPINGS = []() -> std::vector<TextureUVMapping> { return { // shader key | idx | uv set | CGA key {L"diffuseMap", 0, 0}, // colormap {L"bumpMap", 0, 1}, // bumpmap {L"diffuseMap", 1, 2}, // dirtmap {L"specularMap", 0, 3}, // specularmap {L"opacityMap", 0, 4}, // opacitymap { L"normalMap", 0, 5 } // normalmap #if PRT_VERSION_MAJOR > 1 , {L"emissiveMap", 0, 6}, // emissivemap {L"occlusionMap", 0, 7}, // occlusionmap {L"roughnessMap", 0, 8}, // roughnessmap { L"metallicMap", 0, 9 } // metallicmap #endif }; }(); // return the highest required uv set (where a valid texture is present) uint32_t scanValidTextures(const prtx::MaterialPtr& mat) { int8_t highestUVSet = -1; for (const auto& t : TEXTURE_UV_MAPPINGS) { const auto& ta = mat->getTextureArray(t.key); if (ta.size() > t.index && ta[t.index]->isValid()) highestUVSet = std::max(highestUVSet, t.uvSet); } if (highestUVSet < 0) return 0; else return highestUVSet + 1; } const prtx::DoubleVector EMPTY_UVS; const prtx::IndexVector EMPTY_IDX; } // namespace namespace detail { SerializedGeometry serializeGeometry(const prtx::GeometryPtrVector& geometries, const std::vector<prtx::MaterialPtrVector>& materials) { // PASS 1: scan uint32_t numCoords = 0; uint32_t numNormalCoords = 0; uint32_t numCounts = 0; uint32_t numIndices = 0; uint32_t maxNumUVSets = 0; auto matsIt = materials.cbegin(); for (const auto& geo : geometries) { const prtx::MeshPtrVector& meshes = geo->getMeshes(); const prtx::MaterialPtrVector& mats = *matsIt; auto matIt = mats.cbegin(); for (const auto& mesh : meshes) { numCoords += static_cast<uint32_t>(mesh->getVertexCoords().size()); numNormalCoords += static_cast<uint32_t>(mesh->getVertexNormalsCoords().size()); numCounts += mesh->getFaceCount(); const auto& vtxCnts = mesh->getFaceVertexCounts(); numIndices = std::accumulate(vtxCnts.begin(), vtxCnts.end(), numIndices); const prtx::MaterialPtr& mat = *matIt; const uint32_t requiredUVSetsByMaterial = scanValidTextures(mat); maxNumUVSets = std::max(maxNumUVSets, std::max(mesh->getUVSetsCount(), requiredUVSetsByMaterial)); ++matIt; } ++matsIt; } detail::SerializedGeometry sg(numCoords, numNormalCoords, numCounts, numIndices, maxNumUVSets); // PASS 2: copy uint32_t vertexIndexBase = 0; std::vector<uint32_t> uvIndexBases(maxNumUVSets, 0u); for (const auto& geo : geometries) { const prtx::MeshPtrVector& meshes = geo->getMeshes(); for (const auto& mesh : meshes) { // append points const prtx::DoubleVector& verts = mesh->getVertexCoords(); sg.coords.insert(sg.coords.end(), verts.begin(), verts.end()); // append normals const prtx::DoubleVector& norms = mesh->getVertexNormalsCoords(); sg.normals.insert(sg.normals.end(), norms.begin(), norms.end()); // append uv sets (uv coords, counts, indices) with special cases: // - if mesh has no uv sets but maxNumUVSets is > 0, insert "0" uv face counts to keep in sync // - if mesh has less uv sets than maxNumUVSets, copy uv set 0 to the missing higher sets const uint32_t numUVSets = mesh->getUVSetsCount(); const prtx::DoubleVector& uvs0 = (numUVSets > 0) ? mesh->getUVCoords(0) : EMPTY_UVS; const prtx::IndexVector faceUVCounts0 = (numUVSets > 0) ? mesh->getFaceUVCounts(0) : prtx::IndexVector(mesh->getFaceCount(), 0); if (DBG) log_debug("-- mesh: numUVSets = %1%") % numUVSets; for (uint32_t uvSet = 0; uvSet < sg.uvs.size(); uvSet++) { // append texture coordinates const prtx::DoubleVector& uvs = (uvSet < numUVSets) ? mesh->getUVCoords(uvSet) : EMPTY_UVS; const auto& src = uvs.empty() ? uvs0 : uvs; auto& tgt = sg.uvs[uvSet]; tgt.insert(tgt.end(), src.begin(), src.end()); // append uv face counts const prtx::IndexVector& faceUVCounts = (uvSet < numUVSets && !uvs.empty()) ? mesh->getFaceUVCounts(uvSet) : faceUVCounts0; assert(faceUVCounts.size() == mesh->getFaceCount()); auto& tgtCnts = sg.uvCounts[uvSet]; tgtCnts.insert(tgtCnts.end(), faceUVCounts.begin(), faceUVCounts.end()); if (DBG) log_debug(" -- uvset %1%: face counts size = %2%") % uvSet % faceUVCounts.size(); // append uv vertex indices for (uint32_t fi = 0, faceCount = static_cast<uint32_t>(faceUVCounts.size()); fi < faceCount; ++fi) { const uint32_t* faceUVIdx0 = (numUVSets > 0) ? mesh->getFaceUVIndices(fi, 0) : EMPTY_IDX.data(); const uint32_t* faceUVIdx = (uvSet < numUVSets && !uvs.empty()) ? mesh->getFaceUVIndices(fi, uvSet) : faceUVIdx0; const uint32_t faceUVCnt = faceUVCounts[fi]; if (DBG) log_debug(" fi %1%: faceUVCnt = %2%, faceVtxCnt = %3%") % fi % faceUVCnt % mesh->getFaceVertexCount(fi); for (uint32_t vi = 0; vi < faceUVCnt; vi++) sg.uvIndices[uvSet].push_back(uvIndexBases[uvSet] + faceUVIdx[faceUVCnt - vi - 1]); // reverse winding } uvIndexBases[uvSet] += static_cast<uint32_t>(src.size()) / 2u; } // for all uv sets // append counts and indices for vertices and vertex normals for (uint32_t fi = 0, faceCount = mesh->getFaceCount(); fi < faceCount; ++fi) { const uint32_t* vtxIdx = mesh->getFaceVertexIndices(fi); const uint32_t vtxCnt = mesh->getFaceVertexCount(fi); sg.counts.push_back(vtxCnt); for (uint32_t vi = 0; vi < vtxCnt; vi++) sg.indices.push_back(vertexIndexBase + vtxIdx[vtxCnt - vi - 1]); // reverse winding } vertexIndexBase += (uint32_t)verts.size() / 3u; } // for all meshes } // for all geometries return sg; } } // namespace detail HoudiniEncoder::HoudiniEncoder(const std::wstring& id, const prt::AttributeMap* options, prt::Callbacks* callbacks) : prtx::GeometryEncoder(id, options, callbacks) {} void HoudiniEncoder::init(prtx::GenerateContext&) { prt::Callbacks* cb = getCallbacks(); if (DBG) log_debug("HoudiniEncoder::init: cb = %x") % (size_t)cb; auto* oh = dynamic_cast<HoudiniCallbacks*>(cb); if (DBG) log_debug(" oh = %x") % (size_t)oh; if (oh == nullptr) throw prtx::StatusException(prt::STATUS_ILLEGAL_CALLBACK_OBJECT); } void HoudiniEncoder::encode(prtx::GenerateContext& context, size_t initialShapeIndex) { const prtx::InitialShape& initialShape = *context.getInitialShape(initialShapeIndex); auto* cb = dynamic_cast<HoudiniCallbacks*>(getCallbacks()); const bool emitAttrs = getOptions()->getBool(EO_EMIT_ATTRIBUTES); prtx::DefaultNamePreparator namePrep; prtx::NamePreparator::NamespacePtr nsMesh = namePrep.newNamespace(); prtx::NamePreparator::NamespacePtr nsMaterial = namePrep.newNamespace(); prtx::EncodePreparatorPtr encPrep = prtx::EncodePreparator::create(true, namePrep, nsMesh, nsMaterial); // generate geometry prtx::ReportsAccumulatorPtr reportsAccumulator{prtx::WriteFirstReportsAccumulator::create()}; prtx::ReportingStrategyPtr reportsCollector{ prtx::LeafShapeReportingStrategy::create(context, initialShapeIndex, reportsAccumulator)}; prtx::LeafIteratorPtr li = prtx::LeafIterator::create(context, initialShapeIndex); for (prtx::ShapePtr shape = li->getNext(); shape; shape = li->getNext()) { prtx::ReportsPtr r = reportsCollector->getReports(shape->getID()); encPrep->add(context.getCache(), shape, initialShape.getAttributeMap(), r); // get final values of generic attributes if (emitAttrs) forwardGenericAttributes(cb, initialShapeIndex, initialShape, shape); } prtx::EncodePreparator::InstanceVector instances; encPrep->fetchFinalizedInstances(instances, PREP_FLAGS); convertGeometry(initialShape, instances, cb); } void HoudiniEncoder::convertGeometry(const prtx::InitialShape& initialShape, const prtx::EncodePreparator::InstanceVector& instances, HoudiniCallbacks* cb) { const bool emitMaterials = getOptions()->getBool(EO_EMIT_MATERIALS); const bool emitReports = getOptions()->getBool(EO_EMIT_REPORTS); prtx::GeometryPtrVector geometries; std::vector<prtx::MaterialPtrVector> materials; std::vector<prtx::ReportsPtr> reports; std::vector<int32_t> shapeIDs; geometries.reserve(instances.size()); materials.reserve(instances.size()); reports.reserve(instances.size()); shapeIDs.reserve(instances.size()); for (const auto& inst : instances) { geometries.push_back(inst.getGeometry()); materials.push_back(inst.getMaterials()); reports.push_back(inst.getReports()); shapeIDs.push_back(inst.getShapeId()); } const detail::SerializedGeometry sg = detail::serializeGeometry(geometries, materials); if (DBG) { log_debug("resolvemap: %s") % prtx::PRTUtils::objectToXML(initialShape.getResolveMap()); log_debug("encoder #materials = %s") % materials.size(); } uint32_t faceCount = 0; std::vector<uint32_t> faceRanges; AttributeMapNOPtrVectorOwner matAttrMaps; AttributeMapNOPtrVectorOwner reportAttrMaps; assert(geometries.size() == reports.size()); assert(materials.size() == reports.size()); auto matIt = materials.cbegin(); auto repIt = reports.cbegin(); prtx::PRTUtils::AttributeMapBuilderPtr amb(prt::AttributeMapBuilder::create()); for (const auto& geo : geometries) { const prtx::MeshPtrVector& meshes = geo->getMeshes(); for (size_t mi = 0; mi < meshes.size(); mi++) { const prtx::MeshPtr& m = meshes.at(mi); const prtx::MaterialPtr& mat = matIt->at(mi); faceRanges.push_back(faceCount); if (emitMaterials) { convertMaterialToAttributeMap(amb, *(mat.get()), mat->getKeys()); matAttrMaps.v.push_back(amb->createAttributeMapAndReset()); } if (emitReports) { convertReportsToAttributeMap(amb, *repIt); reportAttrMaps.v.push_back(amb->createAttributeMapAndReset()); if (DBG) log_debug("report attr map: %1%") % prtx::PRTUtils::objectToXML(reportAttrMaps.v.back()); } faceCount += m->getFaceCount(); } ++matIt; ++repIt; } faceRanges.push_back(faceCount); // close last range assert(matAttrMaps.v.empty() || matAttrMaps.v.size() == faceRanges.size() - 1); assert(reportAttrMaps.v.empty() || reportAttrMaps.v.size() == faceRanges.size() - 1); assert(shapeIDs.size() == faceRanges.size() - 1); assert(sg.uvs.size() == sg.uvCounts.size()); assert(sg.uvs.size() == sg.uvIndices.size()); auto puvs = toPtrVec(sg.uvs); auto puvCounts = toPtrVec(sg.uvCounts); auto puvIndices = toPtrVec(sg.uvIndices); assert(sg.uvs.size() == puvCounts.first.size()); assert(sg.uvs.size() == puvCounts.second.size()); cb->add(initialShape.getName(), sg.coords.data(), sg.coords.size(), sg.normals.data(), sg.normals.size(), sg.counts.data(), sg.counts.size(), sg.indices.data(), sg.indices.size(), puvs.first.data(), puvs.second.data(), puvCounts.first.data(), puvCounts.second.data(), puvIndices.first.data(), puvIndices.second.data(), static_cast<uint32_t>(sg.uvs.size()), faceRanges.data(), faceRanges.size(), matAttrMaps.v.empty() ? nullptr : matAttrMaps.v.data(), reportAttrMaps.v.empty() ? nullptr : reportAttrMaps.v.data(), shapeIDs.data()); if (DBG) log_debug("HoudiniEncoder::convertGeometry: end"); } void HoudiniEncoder::finish(prtx::GenerateContext& /*context*/) {} HoudiniEncoderFactory* HoudiniEncoderFactory::createInstance() { prtx::EncoderInfoBuilder encoderInfoBuilder; encoderInfoBuilder.setID(ENCODER_ID_HOUDINI); encoderInfoBuilder.setName(ENC_NAME); encoderInfoBuilder.setDescription(ENC_DESCRIPTION); encoderInfoBuilder.setType(prt::CT_GEOMETRY); prtx::PRTUtils::AttributeMapBuilderPtr amb(prt::AttributeMapBuilder::create()); amb->setBool(EO_EMIT_ATTRIBUTES, prtx::PRTX_FALSE); amb->setBool(EO_EMIT_MATERIALS, prtx::PRTX_FALSE); amb->setBool(EO_EMIT_REPORTS, prtx::PRTX_FALSE); encoderInfoBuilder.setDefaultOptions(amb->createAttributeMap()); return new HoudiniEncoderFactory(encoderInfoBuilder.create()); }
34.741194
117
0.651283
[ "mesh", "geometry", "shape", "vector", "transform" ]
9c20143c3903af4000f214410d5acb721c2d4581
13,839
cc
C++
src/components/application_manager/rpc_plugins/sdl_rpc_plugin/test/commands/mobile/dummy_mobile_commands_test.cc
shoamano83/sdl_core
ea5960280585d11ee02542b0ab183d4400ed691d
[ "BSD-3-Clause" ]
null
null
null
src/components/application_manager/rpc_plugins/sdl_rpc_plugin/test/commands/mobile/dummy_mobile_commands_test.cc
shoamano83/sdl_core
ea5960280585d11ee02542b0ab183d4400ed691d
[ "BSD-3-Clause" ]
null
null
null
src/components/application_manager/rpc_plugins/sdl_rpc_plugin/test/commands/mobile/dummy_mobile_commands_test.cc
shoamano83/sdl_core
ea5960280585d11ee02542b0ab183d4400ed691d
[ "BSD-3-Clause" ]
1
2020-04-22T07:17:49.000Z
2020-04-22T07:17:49.000Z
/* * Copyright (c) 2018, Ford Motor Company * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following * disclaimer in the documentation and/or other materials provided with the * distribution. * * Neither the name of the Ford Motor Company nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "application_manager/commands/command_request_test.h" #include <stdint.h> #include <string> #include <vector> #include "gtest/gtest.h" #include "mobile/add_command_request.h" #include "mobile/add_command_response.h" #include "mobile/add_sub_menu_request.h" #include "mobile/add_sub_menu_response.h" #include "mobile/alert_maneuver_request.h" #include "mobile/alert_maneuver_response.h" #include "mobile/alert_request.h" #include "mobile/alert_response.h" #include "mobile/change_registration_request.h" #include "mobile/change_registration_response.h" #include "mobile/create_interaction_choice_set_request.h" #include "mobile/create_interaction_choice_set_response.h" #include "mobile/delete_command_request.h" #include "mobile/delete_command_response.h" #include "mobile/delete_file_request.h" #include "mobile/delete_file_response.h" #include "mobile/delete_interaction_choice_set_request.h" #include "mobile/delete_interaction_choice_set_response.h" #include "mobile/delete_sub_menu_request.h" #include "mobile/delete_sub_menu_response.h" #include "mobile/dial_number_request.h" #include "mobile/dial_number_response.h" #include "mobile/end_audio_pass_thru_request.h" #include "mobile/end_audio_pass_thru_response.h" #include "mobile/generic_response.h" #include "mobile/get_file_request.h" #include "mobile/get_file_response.h" #include "mobile/get_way_points_request.h" #include "mobile/get_way_points_response.h" #include "mobile/list_files_request.h" #include "mobile/list_files_response.h" #include "mobile/on_app_interface_unregistered_notification.h" #include "mobile/on_audio_pass_thru_notification.h" #include "mobile/on_button_event_notification.h" #include "mobile/on_button_press_notification.h" #include "mobile/on_command_notification.h" #include "mobile/on_driver_distraction_notification.h" #include "mobile/on_hash_change_notification.h" #include "mobile/on_hmi_status_notification.h" #include "mobile/on_hmi_status_notification_from_mobile.h" #include "mobile/on_keyboard_input_notification.h" #include "mobile/on_language_change_notification.h" #include "mobile/on_permissions_change_notification.h" #include "mobile/on_system_capability_updated_notification.h" #include "mobile/on_system_request_notification.h" #include "mobile/on_tbt_client_state_notification.h" #include "mobile/on_touch_event_notification.h" #include "mobile/on_way_point_change_notification.h" #include "mobile/perform_audio_pass_thru_request.h" #include "mobile/perform_audio_pass_thru_response.h" #include "mobile/perform_interaction_request.h" #include "mobile/perform_interaction_response.h" #include "mobile/put_file_request.h" #include "mobile/put_file_response.h" #include "mobile/register_app_interface_request.h" #include "mobile/register_app_interface_response.h" #include "mobile/reset_global_properties_request.h" #include "mobile/reset_global_properties_response.h" #include "mobile/scrollable_message_request.h" #include "mobile/scrollable_message_response.h" #include "mobile/send_location_request.h" #include "mobile/send_location_response.h" #include "mobile/set_app_icon_request.h" #include "mobile/set_app_icon_response.h" #include "mobile/set_display_layout_request.h" #include "mobile/set_display_layout_response.h" #include "mobile/set_global_properties_request.h" #include "mobile/set_global_properties_response.h" #include "mobile/set_media_clock_timer_request.h" #include "mobile/set_media_clock_timer_response.h" #include "mobile/show_constant_tbt_request.h" #include "mobile/show_constant_tbt_response.h" #include "mobile/show_request.h" #include "mobile/show_response.h" #include "mobile/slider_request.h" #include "mobile/slider_response.h" #include "mobile/speak_request.h" #include "mobile/speak_response.h" #include "mobile/subscribe_button_request.h" #include "mobile/subscribe_button_response.h" #include "mobile/subscribe_way_points_request.h" #include "mobile/subscribe_way_points_response.h" #include "mobile/system_response.h" #include "mobile/unregister_app_interface_request.h" #include "mobile/unregister_app_interface_response.h" #include "mobile/unsubscribe_button_request.h" #include "mobile/unsubscribe_button_response.h" #include "mobile/unsubscribe_way_points_request.h" #include "mobile/unsubscribe_way_points_response.h" #include "mobile/update_turn_list_request.h" #include "mobile/update_turn_list_response.h" #include "application_manager/mock_application.h" #include "application_manager/mock_application_manager.h" #include "test/application_manager/mock_application_manager_settings.h" #include "application_manager/mock_event_dispatcher.h" namespace am = application_manager; namespace test { namespace components { namespace commands_test { namespace mobile_commands_test { namespace dummy_mobile_commands_test { namespace commands = sdl_rpc_plugin::commands; using ::testing::_; using ::testing::NotNull; using ::testing::Types; using am::commands::MessageSharedPtr; using ::test::components::event_engine_test::MockEventDispatcher; using ::test::components::application_manager_test::MockApplicationManager; using ::test::components::application_manager_test:: MockApplicationManagerSettings; using ::application_manager::ApplicationSharedPtr; using ::test::components::application_manager_test::MockApplication; namespace { const std::string kEmptyString_ = ""; } // namespace template <class Command> class MobileCommandsTest : public components::commands_test::CommandRequestTest< CommandsTestMocks::kIsNice> { public: typedef Command CommandType; void InitCommand(const uint32_t& timeout) OVERRIDE { EXPECT_CALL(app_mngr_settings_, default_timeout()) .WillOnce(ReturnRef(timeout)); ON_CALL(app_mngr_, event_dispatcher()) .WillByDefault(ReturnRef(event_dispatcher_)); ON_CALL(app_mngr_, get_settings()) .WillByDefault(ReturnRef(app_mngr_settings_)); ON_CALL(app_mngr_settings_, app_icons_folder()) .WillByDefault(ReturnRef(kEmptyString_)); } }; template <class Command> class MobileCommandsTestFirst : public MobileCommandsTest<Command> { public: using typename MobileCommandsTest<Command>::CommandType; }; template <class Command> class MobileCommandsTestSecond : public MobileCommandsTest<Command> { public: using typename MobileCommandsTest<Command>::CommandType; }; template <class Command> class MobileCommandsTestThird : public MobileCommandsTest<Command> { public: using typename MobileCommandsTest<Command>::CommandType; }; /* macro TYPED_TEST_CASE takes max 50 args. That is why there are few * TYPED_TEST_CASE for HMI and mobile commands */ typedef Types<commands::AddCommandRequest, commands::AddCommandResponse, commands::AddSubMenuRequest, commands::AddSubMenuResponse, commands::AlertManeuverRequest, commands::AlertManeuverResponse, commands::AlertRequest, commands::AlertResponse, commands::ChangeRegistrationRequest, commands::ChangeRegistrationResponse, commands::CreateInteractionChoiceSetRequest, commands::CreateInteractionChoiceSetResponse, commands::DeleteCommandRequest, commands::DeleteCommandResponse, commands::DeleteFileRequest, commands::DeleteFileResponse, commands::DeleteInteractionChoiceSetRequest, commands::DeleteInteractionChoiceSetResponse, commands::DeleteSubMenuRequest, commands::DeleteSubMenuResponse, commands::DialNumberRequest, commands::DialNumberResponse, commands::EndAudioPassThruRequest, commands::EndAudioPassThruResponse, commands::GenericResponse, commands::GetFileRequest, commands::GetFileResponse, commands::GetWayPointsRequest, commands::GetWayPointsResponse, commands::ListFilesRequest, commands::ListFilesResponse, commands::OnAppInterfaceUnregisteredNotification, commands::OnAudioPassThruNotification, commands::mobile::OnButtonEventNotification, commands::mobile::OnButtonPressNotification, commands::OnCommandNotification, commands::mobile::OnDriverDistractionNotification, commands::mobile::OnHashChangeNotification, commands::OnHMIStatusNotification, commands::OnHMIStatusNotificationFromMobile, commands::mobile::OnKeyBoardInputNotification, commands::OnLanguageChangeNotification, commands::OnPermissionsChangeNotification, commands::mobile::OnSystemCapabilityUpdatedNotification> MobileCommandsListFirst; typedef Types<commands::mobile::OnSystemRequestNotification, commands::OnTBTClientStateNotification, commands::mobile::OnTouchEventNotification, commands::OnWayPointChangeNotification, commands::PerformAudioPassThruRequest, commands::PerformAudioPassThruResponse, commands::PerformInteractionRequest, commands::PerformInteractionResponse, commands::PutFileRequest, commands::PutFileResponse, commands::RegisterAppInterfaceRequest, commands::RegisterAppInterfaceResponse, commands::ResetGlobalPropertiesRequest, commands::ResetGlobalPropertiesResponse, commands::ScrollableMessageRequest, commands::ScrollableMessageResponse, commands::SendLocationRequest, commands::SendLocationResponse, commands::SetAppIconRequest, commands::SetAppIconResponse, commands::SetDisplayLayoutRequest, commands::SetDisplayLayoutResponse, commands::SetGlobalPropertiesRequest, commands::SetGlobalPropertiesResponse, commands::SetMediaClockRequest, commands::SetMediaClockTimerResponse, commands::ShowConstantTBTRequest, commands::ShowConstantTBTResponse, commands::ShowRequest, commands::ShowResponse, commands::SliderRequest, commands::SliderResponse, commands::SpeakRequest, commands::SpeakResponse, commands::SubscribeButtonRequest, commands::SubscribeButtonResponse, commands::SubscribeWayPointsRequest, commands::SubscribeWayPointsResponse, commands::SystemResponse, commands::UnregisterAppInterfaceRequest> MobileCommandsListSecond; typedef Types<commands::UnregisterAppInterfaceResponse, commands::UnsubscribeButtonRequest, commands::UnsubscribeButtonResponse, commands::UnsubscribeWayPointsRequest, commands::UnsubscribeWayPointsResponse, commands::UpdateTurnListRequest, commands::UpdateTurnListResponse> MobileCommandsListThird; TYPED_TEST_CASE(MobileCommandsTestFirst, MobileCommandsListFirst); TYPED_TEST_CASE(MobileCommandsTestSecond, MobileCommandsListSecond); TYPED_TEST_CASE(MobileCommandsTestThird, MobileCommandsListThird); TYPED_TEST(MobileCommandsTestFirst, CtorAndDtorCall) { std::shared_ptr<typename TestFixture::CommandType> command = this->template CreateCommand<typename TestFixture::CommandType>(); EXPECT_NE(command.use_count(), 0); } TYPED_TEST(MobileCommandsTestSecond, CtorAndDtorCall) { std::shared_ptr<typename TestFixture::CommandType> command = this->template CreateCommand<typename TestFixture::CommandType>(); EXPECT_NE(command.use_count(), 0); } TYPED_TEST(MobileCommandsTestThird, CtorAndDtorCall) { std::shared_ptr<typename TestFixture::CommandType> command = this->template CreateCommand<typename TestFixture::CommandType>(); EXPECT_NE(command.use_count(), 0); } } // namespace dummy_mobile_commands_test } // namespace mobile_commands_test } // namespace commands_test } // namespace components } // namespace test
42.978261
80
0.75728
[ "vector" ]
9c224e2f031c4481bea55c70a274f5b25aa763ae
7,128
cpp
C++
exotica/src/Loaders/XMLLoader.cpp
LongfeiProjects/exotica
206b296edf9bf3b653ca3984b1449151ca17d374
[ "BSD-3-Clause" ]
1
2019-04-12T20:26:59.000Z
2019-04-12T20:26:59.000Z
exotica/src/Loaders/XMLLoader.cpp
LongfeiProjects/exotica
206b296edf9bf3b653ca3984b1449151ca17d374
[ "BSD-3-Clause" ]
null
null
null
exotica/src/Loaders/XMLLoader.cpp
LongfeiProjects/exotica
206b296edf9bf3b653ca3984b1449151ca17d374
[ "BSD-3-Clause" ]
null
null
null
#include <exotica/Loaders/XMLLoader.h> #include <exotica/Setup.h> #include <tinyxml2/tinyxml2.h> namespace exotica { std::shared_ptr<XMLLoader> XMLLoader::instance_ = nullptr; XMLLoader::XMLLoader() { } bool parseXML(tinyxml2::XMLHandle& tag, Initializer& parent, const std::string& prefix); void appendChildXML(Initializer& parent, std::string& name, bool isAttribute, tinyxml2::XMLHandle& tag, const std::string& prefix) { if (isAttribute) { // Attributes are always a regular property std::string value = tag.ToElement()->Attribute(name.c_str()); parent.addProperty(Property(name, true, value)); } else { int count = 0; for (tinyxml2::XMLHandle child = tag.FirstChild(); child.ToNode(); child = child.NextSibling()) if (child.ToElement() != nullptr) count++; if (count == 0) { if (tag.ToElement() == nullptr) return; if (!tag.ToElement()->GetText()) { // No child tags = this is an empty vector of properties return; } std::string value = tag.ToElement()->GetText(); parent.addProperty(Property(name, true, value)); } else { // Child tags found = this is an initializer // All initializers are treated as a vector std::vector<Initializer> ret; tinyxml2::XMLHandle child_tag = tag.FirstChild(); while (child_tag.ToNode()) { if (child_tag.ToElement() == nullptr) { child_tag = child_tag.NextSibling(); continue; } ret.push_back(Initializer("New" + name)); if (!parseXML(child_tag, ret[ret.size() - 1], prefix + "- ")) { ret.pop_back(); } else { //HIGHLIGHT(prefix<<". Adding parsed vector element "<<name<<" to " << parent.getName()); } child_tag = child_tag.NextSibling(); } parent.addProperty(Property(name, true, ret)); } } } // Parses an Initializer parameters from ints attributes and child tags bool parseXML(tinyxml2::XMLHandle& tag, Initializer& parent, const std::string& prefix) { // Get the name std::string name = std::string(tag.ToElement()->Name()); //HIGHLIGHT(prefix<<name<<" added"); parent.setName("exotica/" + name); // Parse values stored in attributes tinyxml2::XMLAttribute* attr = const_cast<tinyxml2::XMLAttribute*>(tag.ToElement()->FirstAttribute()); while (attr) { std::string member_name = attr->Name(); appendChildXML(parent, member_name, true, tag, prefix + "- "); attr = const_cast<tinyxml2::XMLAttribute*>(attr->Next()); } // Parse values stored in tags tinyxml2::XMLHandle member_tag = tag.FirstChild(); while (member_tag.ToNode()) { if (member_tag.ToElement() == nullptr) { member_tag = member_tag.NextSibling(); continue; } std::string member_name = std::string(member_tag.ToElement()->Name()); appendChildXML(parent, member_name, false, member_tag, prefix + "- "); member_tag = member_tag.NextSibling(); } //HIGHLIGHT(prefix<<name<<" finished parsing"); return true; } Initializer XMLLoader::loadXML(std::string file_name, bool parsePathAsXML) { tinyxml2::XMLDocument xml_file; if (parsePathAsXML) { if (xml_file.Parse(file_name.c_str(), file_name.size()) != tinyxml2::XML_SUCCESS) { throw_pretty("Can't load file!\nFile: '" + file_name + "'"); } } else { std::string xml = loadFile(file_name); if (xml_file.Parse(xml.c_str(), xml.size()) != tinyxml2::XML_SUCCESS) { throw_pretty("Can't load file!\nFile: '" + parsePath(file_name) + "'"); } } Initializer ret("TopLevel"); tinyxml2::XMLHandle root_tag(xml_file.RootElement()->FirstChildElement()); if (!parseXML(root_tag, ret, "")) { throw_pretty("Can't parse XML!\nFile: '" + file_name + "'"); } return ret; } void XMLLoader::loadXML(std::string file_name, Initializer& solver, Initializer& problem, const std::string& solver_name, const std::string& problem_name, bool parsePathAsXML) { tinyxml2::XMLDocument xml_file; if (parsePathAsXML) { if (xml_file.Parse(file_name.c_str(), file_name.size()) != tinyxml2::XML_SUCCESS) { throw_pretty("Can't load file!\nFile: '" + file_name + "'"); } } else { std::string xml = loadFile(file_name); if (xml_file.Parse(xml.c_str(), xml.size()) != tinyxml2::XML_SUCCESS) { throw_pretty("Can't load file!\nFile: '" + parsePath(file_name) + "'"); } } std::vector<Initializer> initializers; tinyxml2::XMLHandle root_tag = xml_file.RootElement()->FirstChild(); while (root_tag.ToNode()) { if (root_tag.ToElement() == nullptr) { root_tag = root_tag.NextSibling(); continue; } initializers.push_back(Initializer("TopLevel")); if (!parseXML(root_tag, initializers[initializers.size() - 1], "")) { initializers.pop_back(); } root_tag = root_tag.NextSibling(); } bool foundSolver = false; bool foundProblem = false; if (solver_name == "" || solver_name == "") { for (Initializer& i : initializers) { std::string initializer_type = i.getName(); if (!foundSolver) { for (std::string known_type : Setup::getSolvers()) { if (known_type == initializer_type) { solver = i; foundSolver = true; break; } } } if (!foundProblem) { for (std::string known_type : Setup::getProblems()) { if (known_type == initializer_type) { problem = i; foundProblem = true; break; } } } } } else { for (Initializer& i : initializers) { std::string name = boost::any_cast<std::string>(i.getProperty("Name")); if (name == solver_name) { solver = i; foundSolver = true; } if (name == problem_name) { problem = i; foundProblem = true; } } } if (!foundSolver) throw_pretty("Can't find solver '" + solver_name + "' in '" + file_name + "'!"); if (!foundProblem) throw_pretty("Can't find problem '" + problem_name + "' in '" + file_name + "'!"); } }
32.4
175
0.529882
[ "vector" ]
9c24fd3a3c4482847a04b23bbcca2efe6b6efce3
8,828
cc
C++
core/src/asset.cc
jqly/ppll_rendering
894dbb7a7e1d08f6dc4cd2f02fe6d3ecaaab5ccb
[ "MIT" ]
null
null
null
core/src/asset.cc
jqly/ppll_rendering
894dbb7a7e1d08f6dc4cd2f02fe6d3ecaaab5ccb
[ "MIT" ]
null
null
null
core/src/asset.cc
jqly/ppll_rendering
894dbb7a7e1d08f6dc4cd2f02fe6d3ecaaab5ccb
[ "MIT" ]
null
null
null
#include "asset.h" #include <map> #include "glad/glad.h" #include "tiny_obj_loader.h" #include "stb_image.h" #include "xy_ext.h" #include "gpu_array.h" void ObjAsset::LoadFromFile(std::string obj_path, std::string mtl_dir) { tinyobj::attrib_t attrib; std::vector<tinyobj::shape_t> raw_shapes; std::vector<tinyobj::material_t> materials; std::string errmsg; bool is_success = tinyobj::LoadObj(&attrib, &raw_shapes, &materials, &errmsg, obj_path.c_str(), mtl_dir.c_str(), true); if (!is_success) { XY_Die(errmsg); } if (attrib.vertices.empty()) xy::Print("obj empty vertex list"); if (attrib.normals.empty()) xy::Print("obj empty normal list"); if (attrib.texcoords.empty()) xy::Print("obj empty texcoord list"); shapes.clear(); shapes.resize(raw_shapes.size()); for (int kthshape = 0; kthshape < raw_shapes.size(); ++kthshape) { auto &raw_shape = raw_shapes[kthshape]; auto &shape = shapes[kthshape]; std::vector<int> mtl_ids = raw_shape.mesh.material_ids; { std::sort(mtl_ids.begin(), mtl_ids.end()); auto last = std::unique(mtl_ids.begin(), mtl_ids.end()); mtl_ids.erase(last, mtl_ids.end()); auto num_blobs = mtl_ids.size(); std::vector<ObjShape::Blob>(num_blobs).swap(shape.blobs); std::vector<xy::vec3>(num_blobs).swap(shape.Ka); std::vector<xy::vec3>(num_blobs).swap(shape.Kd); std::vector<xy::vec3>(num_blobs).swap(shape.Ks); std::vector<std::string>(num_blobs, "").swap(shape.map_Ka_image_paths); std::vector<std::string>(num_blobs, "").swap(shape.map_Kd_image_paths); std::vector<std::string>(num_blobs, "").swap(shape.map_Ks_image_paths); std::vector<std::string>(num_blobs, "").swap(shape.map_d_image_paths); std::vector<std::string>(num_blobs, "").swap(shape.mtl_desc); for (int i = 0; i < num_blobs; ++i) { auto &mtl = materials[mtl_ids[i]]; shape.Ka[i] = xy::FloatArrayToVec(mtl.ambient); shape.Kd[i] = xy::FloatArrayToVec(mtl.diffuse); shape.Ks[i] = xy::FloatArrayToVec(mtl.specular); if (mtl.ambient_texname != "") shape.map_Ka_image_paths[i] = mtl_dir + mtl.ambient_texname; if (mtl.diffuse_texname != "") shape.map_Kd_image_paths[i] = mtl_dir + mtl.diffuse_texname; if (mtl.specular_texname != "") shape.map_Ks_image_paths[i] = mtl_dir + mtl.specular_texname; if (mtl.alpha_texname != "") shape.map_d_image_paths[i] = mtl_dir + mtl.alpha_texname; shape.mtl_desc[i] = mtl.name; } std::vector<int> blob_lookup(materials.size(), -1); { for (int i = 0; i < mtl_ids.size(); ++i) blob_lookup[mtl_ids[i]] = i; } auto num_faces = raw_shape.mesh.num_face_vertices.size(); int index_offset = 0; for (int kthface = 0; kthface < num_faces; ++kthface) { auto mtl_id = raw_shape.mesh.material_ids[kthface]; auto &blob = shape.blobs[blob_lookup[mtl_id]]; for (int kthvert = 0; kthvert < 3; ++kthvert) { auto &idxset = raw_shape.mesh.indices[index_offset + kthvert]; if (!attrib.vertices.empty()) { float x = attrib.vertices[3 * idxset.vertex_index + 0]; float y = attrib.vertices[3 * idxset.vertex_index + 1]; float z = attrib.vertices[3 * idxset.vertex_index + 2]; blob.positions.emplace_back(x, y, z); } if (!attrib.normals.empty()) { float nx = attrib.normals[3 * idxset.normal_index + 0]; float ny = attrib.normals[3 * idxset.normal_index + 1]; float nz = attrib.normals[3 * idxset.normal_index + 2]; blob.normals.emplace_back(nx, ny, nz); } if (!attrib.texcoords.empty()) { float tx = attrib.texcoords[2 * idxset.texcoord_index + 0]; float ty = attrib.texcoords[2 * idxset.texcoord_index + 1]; blob.texcoords.emplace_back(tx, ty); } } index_offset += 3; } } } } GLuint LoadTextureFromFile(std::string tex_path) { int width, height, num_channels; stbi_set_flip_vertically_on_load(true); unsigned char *data = stbi_load(tex_path.c_str(), &width, &height, &num_channels, 0); if (data == nullptr) XY_Die(std::string("failed to load texture(") + tex_path + ")"); GLuint tex; glGenTextures(1, &tex); glBindTexture(GL_TEXTURE_2D, tex); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); if (num_channels == 4) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); } else if (num_channels == 3) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); } else XY_Die("Unsupported texture format(#channels not 3 or 4)"); glGenerateMipmap(GL_TEXTURE_2D); stbi_image_free(data); return tex; } void ObjAsset::CreateGpuRes() { std::map<std::string, GLuint> map; map[""] = 0; for (int i = 0; i < shapes.size(); ++i) { for (auto &key : shapes[i].map_d_image_paths) if (map.count(key) == 0) map[key] = LoadTextureFromFile(key); for (auto &key : shapes[i].map_Ka_image_paths) if (map.count(key) == 0) map[key] = LoadTextureFromFile(key); for (auto &key : shapes[i].map_Kd_image_paths) if (map.count(key) == 0) map[key] = LoadTextureFromFile(key); for (auto &key : shapes[i].map_Ks_image_paths) if (map.count(key) == 0) map[key] = LoadTextureFromFile(key); } for (int i = 0; i < shapes.size(); ++i) { for (auto &key : shapes[i].map_d_image_paths) shapes[i].map_d_textures.push_back(map[key]); for (auto &key : shapes[i].map_Ka_image_paths) shapes[i].map_Ka_textures.push_back(map[key]); for (auto &key : shapes[i].map_Kd_image_paths) shapes[i].map_Kd_textures.push_back(map[key]); for (auto &key : shapes[i].map_Ks_image_paths) shapes[i].map_Ks_textures.push_back(map[key]); } for (auto &shape : shapes) { auto num_blobs = shape.blobs.size(); shape.vaos.swap(std::vector<GpuArray>(num_blobs)); for (int i = 0; i < num_blobs; ++i) { shape.vaos[i].SubmitBuf(shape.blobs[i].positions, { 3 }); shape.vaos[i].SubmitBuf(shape.blobs[i].normals, { 3 }); shape.vaos[i].SubmitBuf(shape.blobs[i].texcoords, { 2 }); } } } void FiberAsset::LoadFromFile( std::string model_path, std::string base_color_texture_path, std::string specular_random_offset_texture_path) { map_bc_path = base_color_texture_path; map_sro_path = specular_random_offset_texture_path; std::ifstream fp(model_path, std::ios::binary); char header[9]; fp.read(header, 8); header[8] = '\0'; if (strcmp(header, "IND_HAIR") != 0) XY_Die("Hair file's header not match!\n"); auto read_unsigned = [&fp]()->unsigned { unsigned n; fp.read(reinterpret_cast<char*>(&n), sizeof(n)); return n; }; auto read_float = [&fp]()->float { float n; fp.read(reinterpret_cast<char*>(&n), sizeof(n)); return n; }; unsigned num_fibers = read_unsigned(); unsigned num_total_verts = read_unsigned(); for (unsigned kthfib = 1; kthfib <= num_fibers; ++kthfib) { auto vert_count = read_unsigned(); //if (kthfib % 2 != 0) { // fp.ignore(3 * sizeof(float) * vert_count); // continue; //} num_verts_per_fiber.push_back(vert_count); for (unsigned kthp = 0; kthp < vert_count; ++kthp) { float x = read_float(); float y = read_float(); float z = read_float(); // FLIP positions.emplace_back(x, y, z); } } tangents.resize(positions.size()); for (std::size_t kthvert = 0, kthfib = 0; kthfib < num_verts_per_fiber.size(); ++kthfib) { for (std::size_t i = 0; i < num_verts_per_fiber[kthfib] - 1; ++i) { tangents[kthvert] = xy::Normalize(positions[kthvert + 1] - positions[kthvert]); ++kthvert; } tangents[kthvert] = xy::Normalize(positions[kthvert] - positions[kthvert - 1]); ++kthvert; } scales.reserve(positions.size()); // scale reuse: An integer is attached to each fiber. xy::RandomEngine eng{ 0xc01dbeef }; for (int kthfiber = 0; kthfiber < num_verts_per_fiber.size(); ++kthfiber) { int nvert = num_verts_per_fiber[kthfiber]; int fibrandom = xy::Unif<1, 99>(eng); for (int i = 0; i < nvert; ++i) { //auto dist = static_cast<float>(i) / (nvert - 1.f); //scales.push_back(fibrandom + xy::Lerp(.95f, .05f, 2.f*(abs(.5 - dist)))); if (i < nvert - 1) scales.push_back(fibrandom + .99f); else scales.push_back(fibrandom + .25f); } } vao.SetAsLineStrips(num_verts_per_fiber); } void FiberAsset::CreateGpuRes() { if (positions.size() != tangents.size() || positions.size() != scales.size()) XY_Die("Incomplete fiber asset!"); vao.SubmitBuf(positions, { 3 }); vao.SubmitBuf(tangents, { 3 }); vao.SubmitBuf(scales, { 1 }); // TODO: Add base color & specular random offset texture. map_base_color = LoadTextureFromFile(map_bc_path); map_spec_offset = LoadTextureFromFile(map_sro_path); }
31.641577
120
0.673199
[ "mesh", "shape", "vector" ]
9c27269bebe0ba8fd9cb00144b04655ece80f77f
29,875
cpp
C++
indra/newview/llhudnametag.cpp
SaladDais/LLUDP-Encryption
8a426cd0dd154e1a10903e0e6383f4deb2a6098a
[ "ISC" ]
1
2022-01-29T07:10:03.000Z
2022-01-29T07:10:03.000Z
indra/newview/llhudnametag.cpp
SaladDais/LLUDP-Encryption
8a426cd0dd154e1a10903e0e6383f4deb2a6098a
[ "ISC" ]
null
null
null
indra/newview/llhudnametag.cpp
SaladDais/LLUDP-Encryption
8a426cd0dd154e1a10903e0e6383f4deb2a6098a
[ "ISC" ]
1
2021-10-01T22:22:27.000Z
2021-10-01T22:22:27.000Z
/** * @file llhudnametag.cpp * @brief Name tags for avatars * @author James Cook * * $LicenseInfo:firstyear=2010&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2010, Linden Research, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License only. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" #include "llhudnametag.h" #include "llrender.h" #include "lltracerecording.h" #include "llagent.h" #include "llviewercontrol.h" #include "llcriticaldamp.h" #include "lldrawable.h" #include "llfontgl.h" #include "llglheaders.h" #include "llhudrender.h" #include "llui.h" #include "llviewercamera.h" #include "llviewertexturelist.h" #include "llviewerobject.h" #include "llvovolume.h" #include "llviewerwindow.h" #include "llstatusbar.h" #include "llmenugl.h" #include "pipeline.h" #include <boost/tokenizer.hpp> const F32 SPRING_STRENGTH = 0.7f; const F32 HORIZONTAL_PADDING = 16.f; const F32 VERTICAL_PADDING = 12.f; const F32 LINE_PADDING = 3.f; // aka "leading" const F32 BUFFER_SIZE = 2.f; const F32 HUD_TEXT_MAX_WIDTH = 190.f; const S32 NUM_OVERLAP_ITERATIONS = 10; const F32 POSITION_DAMPING_TC = 0.2f; const F32 MAX_STABLE_CAMERA_VELOCITY = 0.1f; const F32 LOD_0_SCREEN_COVERAGE = 0.15f; const F32 LOD_1_SCREEN_COVERAGE = 0.30f; const F32 LOD_2_SCREEN_COVERAGE = 0.40f; std::set<LLPointer<LLHUDNameTag> > LLHUDNameTag::sTextObjects; std::vector<LLPointer<LLHUDNameTag> > LLHUDNameTag::sVisibleTextObjects; BOOL LLHUDNameTag::sDisplayText = TRUE ; bool llhudnametag_further_away::operator()(const LLPointer<LLHUDNameTag>& lhs, const LLPointer<LLHUDNameTag>& rhs) const { return lhs->getDistance() > rhs->getDistance(); } LLHUDNameTag::LLHUDNameTag(const U8 type) : LLHUDObject(type), mDoFade(TRUE), mFadeDistance(8.f), mFadeRange(4.f), mLastDistance(0.f), mZCompare(TRUE), mVisibleOffScreen(FALSE), mOffscreen(FALSE), mColor(1.f, 1.f, 1.f, 1.f), // mScale(), mWidth(0.f), mHeight(0.f), mFontp(LLFontGL::getFontSansSerifSmall()), mBoldFontp(LLFontGL::getFontSansSerifBold()), mSoftScreenRect(), mPositionAgent(), mPositionOffset(), mMass(10.f), mMaxLines(10), mOffsetY(0), mRadius(0.1f), mTextSegments(), mLabelSegments(), mTextAlignment(ALIGN_TEXT_CENTER), mVertAlignment(ALIGN_VERT_CENTER), mLOD(0), mHidden(FALSE) { LLPointer<LLHUDNameTag> ptr(this); sTextObjects.insert(ptr); // <FS:Ansariel> Performance improvement mRoundedRectImg = LLUI::getUIImage("Rounded_Rect"); mRoundedRectTopImg = LLUI::getUIImage("Rounded_Rect_Top"); // </FS:Ansariel> } LLHUDNameTag::~LLHUDNameTag() { } BOOL LLHUDNameTag::lineSegmentIntersect(const LLVector4a& start, const LLVector4a& end, LLVector4a& intersection, BOOL debug_render) { if (!mVisible || mHidden) { return FALSE; } // don't pick text that isn't bound to a viewerobject if (!mSourceObject || mSourceObject->mDrawable.isNull()) { return FALSE; } F32 alpha_factor = 1.f; LLColor4 text_color = mColor; if (mDoFade) { if (mLastDistance > mFadeDistance) { alpha_factor = llmax(0.f, 1.f - (mLastDistance - mFadeDistance)/mFadeRange); text_color.mV[3] = text_color.mV[3]*alpha_factor; } } if (text_color.mV[3] < 0.01f) { return FALSE; } mOffsetY = lltrunc(mHeight * ((mVertAlignment == ALIGN_VERT_CENTER) ? 0.5f : 1.f)); LLVector3 position = mPositionAgent; if (mSourceObject) { //get intersection of eye through mPositionAgent to plane of source object //using this position keeps the camera from focusing on some seemingly random //point several meters in front of the nametag const LLVector3& p = mSourceObject->getPositionAgent(); const LLVector3& n = LLViewerCamera::getInstance()->getAtAxis(); const LLVector3& eye = LLViewerCamera::getInstance()->getOrigin(); LLVector3 ray = position-eye; ray.normalize(); LLVector3 delta = p-position; F32 dist = delta*n; F32 dt = dist/(ray*n); position += ray*dt; } // scale screen size of borders down LLVector3 x_pixel_vec; LLVector3 y_pixel_vec; LLViewerCamera::getInstance()->getPixelVectors(position, y_pixel_vec, x_pixel_vec); LLVector3 width_vec = mWidth * x_pixel_vec; LLVector3 height_vec = mHeight * y_pixel_vec; LLCoordGL screen_pos; LLViewerCamera::getInstance()->projectPosAgentToScreen(position, screen_pos, FALSE); LLVector2 screen_offset; screen_offset = updateScreenPos(mPositionOffset); LLVector3 render_position = position + (x_pixel_vec * screen_offset.mV[VX]) + (y_pixel_vec * screen_offset.mV[VY]); LLVector3 bg_pos = render_position + (F32)mOffsetY * y_pixel_vec - (width_vec / 2.f) - (height_vec); LLVector3 v[] = { bg_pos, bg_pos + width_vec, bg_pos + width_vec + height_vec, bg_pos + height_vec, }; LLVector4a dir; dir.setSub(end,start); F32 a, b, t; LLVector4a v0,v1,v2,v3; v0.load3(v[0].mV); v1.load3(v[1].mV); v2.load3(v[2].mV); v3.load3(v[3].mV); if (LLTriangleRayIntersect(v0, v1, v2, start, dir, a, b, t) || LLTriangleRayIntersect(v2, v3, v0, start, dir, a, b, t) ) { if (t <= 1.f) { dir.mul(t); intersection.setAdd(start, dir); return TRUE; } } return FALSE; } void LLHUDNameTag::render() { if (sDisplayText) { LLGLDepthTest gls_depth(GL_TRUE, GL_FALSE); LLGLDisable gls_stencil(GL_STENCIL_TEST); renderText(FALSE); } } void LLHUDNameTag::renderText(BOOL for_select) { if (!mVisible || mHidden) { return; } // don't pick text that isn't bound to a viewerobject if (for_select && (!mSourceObject || mSourceObject->mDrawable.isNull())) { return; } if (for_select) { gGL.getTexUnit(0)->disable(); } else { gGL.getTexUnit(0)->enable(LLTexUnit::TT_TEXTURE); } LLGLState gls_blend(GL_BLEND, for_select ? FALSE : TRUE); LLGLState gls_alpha(GL_ALPHA_TEST, for_select ? FALSE : TRUE); LLColor4 shadow_color(0.f, 0.f, 0.f, 1.f); F32 alpha_factor = 1.f; LLColor4 text_color = mColor; if (mDoFade) { if (mLastDistance > mFadeDistance) { alpha_factor = llmax(0.f, 1.f - (mLastDistance - mFadeDistance)/mFadeRange); text_color.mV[3] = text_color.mV[3]*alpha_factor; } } if (text_color.mV[3] < 0.01f) { return; } shadow_color.mV[3] = text_color.mV[3]; mOffsetY = lltrunc(mHeight * ((mVertAlignment == ALIGN_VERT_CENTER) ? 0.5f : 1.f)); // *TODO: cache this image // <FS:Ansariel> Performance improvement //LLUIImagePtr imagep = LLUI::getUIImage("Rounded_Rect"); // *TODO: make this a per-text setting //LLColor4 bg_color = LLUIColorTable::instance().getColor("NameTagBackground"); //bg_color.setAlpha(gSavedSettings.getF32("ChatBubbleOpacity") * alpha_factor); static LLUIColor s_bg_color = LLUIColorTable::instance().getColor("NameTagBackground"); static LLCachedControl<F32> chatBubbleOpacity(gSavedSettings, "ChatBubbleOpacity"); LLColor4 bg_color = s_bg_color.get(); F32 color_alpha = chatBubbleOpacity * alpha_factor; bg_color.setAlpha(color_alpha); // </FS:Ansariel> // scale screen size of borders down //RN: for now, text on hud objects is never occluded LLVector3 x_pixel_vec; LLVector3 y_pixel_vec; LLViewerCamera::getInstance()->getPixelVectors(mPositionAgent, y_pixel_vec, x_pixel_vec); LLVector3 width_vec = mWidth * x_pixel_vec; LLVector3 height_vec = mHeight * y_pixel_vec; mRadius = (width_vec + height_vec).magVec() * 0.5f; LLCoordGL screen_pos; LLViewerCamera::getInstance()->projectPosAgentToScreen(mPositionAgent, screen_pos, FALSE); LLVector2 screen_offset = updateScreenPos(mPositionOffset); LLVector3 render_position = mPositionAgent + (x_pixel_vec * screen_offset.mV[VX]) + (y_pixel_vec * screen_offset.mV[VY]); LLGLDepthTest gls_depth(GL_TRUE, GL_FALSE); LLRect screen_rect; screen_rect.setCenterAndSize(0, static_cast<S32>(lltrunc(-mHeight / 2 + mOffsetY)), static_cast<S32>(lltrunc(mWidth)), static_cast<S32>(lltrunc(mHeight))); // <FS:Ansariel> Performance improvement //imagep->draw3D(render_position, x_pixel_vec, y_pixel_vec, screen_rect, bg_color); mRoundedRectImg->draw3D(render_position, x_pixel_vec, y_pixel_vec, screen_rect, bg_color); // </FS:Ansariel> if (mLabelSegments.size()) { // <FS:Ansariel> Performance improvement //LLUIImagePtr rect_top_image = LLUI::getUIImage("Rounded_Rect_Top"); LLRect label_top_rect = screen_rect; const S32 label_height = ll_round((mFontp->getLineHeight() * (F32)mLabelSegments.size() + (VERTICAL_PADDING / 3.f))); label_top_rect.mBottom = label_top_rect.mTop - label_height; LLColor4 label_top_color = text_color; // <FS:Ansariel> Performance improvement //label_top_color.mV[VALPHA] = gSavedSettings.getF32("ChatBubbleOpacity") * alpha_factor; label_top_color.mV[VALPHA] = color_alpha; // </FS:Ansariel> // <FS:Ansariel> Performance improvement //rect_top_image->draw3D(render_position, x_pixel_vec, y_pixel_vec, label_top_rect, label_top_color); mRoundedRectTopImg->draw3D(render_position, x_pixel_vec, y_pixel_vec, label_top_rect, label_top_color); // </FS:Ansariel> } F32 y_offset = (F32)mOffsetY; // Render label { //gGL.getTexUnit(0)->setTextureBlendType(LLTexUnit::TB_MULT); for(std::vector<LLHUDTextSegment>::iterator segment_iter = mLabelSegments.begin(); segment_iter != mLabelSegments.end(); ++segment_iter ) { // Label segments use default font const LLFontGL* fontp = (segment_iter->mStyle == LLFontGL::BOLD) ? mBoldFontp : mFontp; y_offset -= fontp->getLineHeight(); F32 x_offset; if (mTextAlignment == ALIGN_TEXT_CENTER) { x_offset = -0.5f*segment_iter->getWidth(fontp); } else // ALIGN_LEFT { x_offset = -0.5f * mWidth + (HORIZONTAL_PADDING / 2.f); } LLColor4 label_color(0.f, 0.f, 0.f, 1.f); label_color.mV[VALPHA] = alpha_factor; hud_render_text(segment_iter->getText(), render_position, *fontp, segment_iter->mStyle, LLFontGL::NO_SHADOW, x_offset, y_offset, label_color, FALSE); } } // Render text { // -1 mMaxLines means unlimited lines. S32 start_segment; S32 max_lines = getMaxLines(); if (max_lines < 0) { start_segment = 0; } else { start_segment = llmax((S32)0, (S32)mTextSegments.size() - max_lines); } for (std::vector<LLHUDTextSegment>::iterator segment_iter = mTextSegments.begin() + start_segment; segment_iter != mTextSegments.end(); ++segment_iter ) { const LLFontGL* fontp = segment_iter->mFont; y_offset -= fontp->getLineHeight(); y_offset -= LINE_PADDING; U8 style = segment_iter->mStyle; LLFontGL::ShadowType shadow = LLFontGL::DROP_SHADOW; F32 x_offset; if (mTextAlignment== ALIGN_TEXT_CENTER) { x_offset = -0.5f*segment_iter->getWidth(fontp); } else // ALIGN_LEFT { x_offset = -0.5f * mWidth + (HORIZONTAL_PADDING / 2.f); // *HACK x_offset += 1; } text_color = segment_iter->mColor; text_color.mV[VALPHA] *= alpha_factor; hud_render_text(segment_iter->getText(), render_position, *fontp, style, shadow, x_offset, y_offset, text_color, FALSE); } } /// Reset the default color to white. The renderer expects this to be the default. gGL.color4f(1.0f, 1.0f, 1.0f, 1.0f); if (for_select) { gGL.getTexUnit(0)->enable(LLTexUnit::TT_TEXTURE); } } void LLHUDNameTag::setString(const std::string &text_utf8) { mTextSegments.clear(); addLine(text_utf8, mColor); } void LLHUDNameTag::clearString() { mTextSegments.clear(); } void LLHUDNameTag::addLine(const std::string &text_utf8, const LLColor4& color, const LLFontGL::StyleFlags style, const LLFontGL* font, const bool use_ellipses) { LLWString wline = utf8str_to_wstring(text_utf8); if (!wline.empty()) { // use default font for segment if custom font not specified if (!font) { font = mFontp; } typedef boost::tokenizer<boost::char_separator<llwchar>, LLWString::const_iterator, LLWString > tokenizer; LLWString seps(utf8str_to_wstring("\r\n")); boost::char_separator<llwchar> sep(seps.c_str()); tokenizer tokens(wline, sep); tokenizer::iterator iter = tokens.begin(); const F32 max_pixels = HUD_TEXT_MAX_WIDTH; while (iter != tokens.end()) { U32 line_length = 0; if (use_ellipses) { // "QualityAssuranceAssuresQuality1" will end up like "QualityAssuranceAssuresQual..." // "QualityAssuranceAssuresQuality QualityAssuranceAssuresQuality" will end up like "QualityAssuranceAssuresQual..." // "QualityAssurance AssuresQuality1" will end up as "QualityAssurance AssuresQua..." because we are enforcing single line do { S32 segment_length = font->maxDrawableChars(iter->substr(line_length).c_str(), max_pixels, wline.length(), LLFontGL::ANYWHERE); if (segment_length + line_length < wline.length()) // since we only draw one string, line_length should be 0 { // token does does not fit into signle line, need to draw "...". // Use four dots for ellipsis width to generate padding const LLWString dots_pad(utf8str_to_wstring(std::string("...."))); S32 elipses_width = font->getWidthF32(dots_pad.c_str()); // truncated string length segment_length = font->maxDrawableChars(iter->substr(line_length).c_str(), max_pixels - elipses_width, wline.length(), LLFontGL::ANYWHERE); const LLWString dots(utf8str_to_wstring(std::string("..."))); LLHUDTextSegment segment(iter->substr(line_length, segment_length) + dots, style, color, font); mTextSegments.push_back(segment); break; // consider it to be complete } else { // token fits fully into string LLHUDTextSegment segment(iter->substr(line_length, segment_length), style, color, font); mTextSegments.push_back(segment); line_length += segment_length; } } while (line_length != iter->size()); } else { // "QualityAssuranceAssuresQuality 1" will be split into two lines "QualityAssuranceAssuresQualit" and "y 1" // "QualityAssurance AssuresQuality 1" will be split into two lines "QualityAssurance" and "AssuresQuality" do { S32 segment_length = font->maxDrawableChars(iter->substr(line_length).c_str(), max_pixels, wline.length(), LLFontGL::WORD_BOUNDARY_IF_POSSIBLE); LLHUDTextSegment segment(iter->substr(line_length, segment_length), style, color, font); mTextSegments.push_back(segment); line_length += segment_length; } while (line_length != iter->size()); } ++iter; } } } void LLHUDNameTag::setLabel(const std::string &label_utf8) { mLabelSegments.clear(); addLabel(label_utf8); } void LLHUDNameTag::addLabel(const std::string& label_utf8) { LLWString wstr = utf8string_to_wstring(label_utf8); if (!wstr.empty()) { LLWString seps(utf8str_to_wstring("\r\n")); LLWString empty; typedef boost::tokenizer<boost::char_separator<llwchar>, LLWString::const_iterator, LLWString > tokenizer; boost::char_separator<llwchar> sep(seps.c_str(), empty.c_str(), boost::keep_empty_tokens); tokenizer tokens(wstr, sep); tokenizer::iterator iter = tokens.begin(); while (iter != tokens.end()) { U32 line_length = 0; do { S32 segment_length = mFontp->maxDrawableChars(iter->substr(line_length).c_str(), HUD_TEXT_MAX_WIDTH, wstr.length(), LLFontGL::WORD_BOUNDARY_IF_POSSIBLE); LLHUDTextSegment segment(iter->substr(line_length, segment_length), LLFontGL::NORMAL, mColor, mFontp); mLabelSegments.push_back(segment); line_length += segment_length; } while (line_length != iter->size()); ++iter; } } } void LLHUDNameTag::setZCompare(const BOOL zcompare) { mZCompare = zcompare; } void LLHUDNameTag::setFont(const LLFontGL* font) { mFontp = font; } void LLHUDNameTag::setColor(const LLColor4 &color) { mColor = color; for (std::vector<LLHUDTextSegment>::iterator segment_iter = mTextSegments.begin(); segment_iter != mTextSegments.end(); ++segment_iter ) { segment_iter->mColor = color; } } void LLHUDNameTag::setAlpha(F32 alpha) { mColor.mV[VALPHA] = alpha; for (std::vector<LLHUDTextSegment>::iterator segment_iter = mTextSegments.begin(); segment_iter != mTextSegments.end(); ++segment_iter ) { segment_iter->mColor.mV[VALPHA] = alpha; } } void LLHUDNameTag::setDoFade(const BOOL do_fade) { mDoFade = do_fade; } void LLHUDNameTag::updateVisibility() { if (mSourceObject) { mSourceObject->updateText(); } mPositionAgent = gAgent.getPosAgentFromGlobal(mPositionGlobal); if (!mSourceObject) { //LL_WARNS() << "LLHUDNameTag::updateScreenPos -- mSourceObject is NULL!" << LL_ENDL; mVisible = TRUE; sVisibleTextObjects.push_back(LLPointer<LLHUDNameTag> (this)); return; } // Not visible if parent object is dead if (mSourceObject->isDead()) { mVisible = FALSE; return; } // push text towards camera by radius of object, but not past camera LLVector3 vec_from_camera = mPositionAgent - LLViewerCamera::getInstance()->getOrigin(); LLVector3 dir_from_camera = vec_from_camera; dir_from_camera.normVec(); if (dir_from_camera * LLViewerCamera::getInstance()->getAtAxis() <= 0.f) { //text is behind camera, don't render mVisible = FALSE; return; } if (vec_from_camera * LLViewerCamera::getInstance()->getAtAxis() <= LLViewerCamera::getInstance()->getNear() + 0.1f + mSourceObject->getVObjRadius()) { mPositionAgent = LLViewerCamera::getInstance()->getOrigin() + vec_from_camera * ((LLViewerCamera::getInstance()->getNear() + 0.1f) / (vec_from_camera * LLViewerCamera::getInstance()->getAtAxis())); } else { mPositionAgent -= dir_from_camera * mSourceObject->getVObjRadius(); } mLastDistance = (mPositionAgent - LLViewerCamera::getInstance()->getOrigin()).magVec(); if (mLOD >= 3 || !mTextSegments.size() || (mDoFade && (mLastDistance > mFadeDistance + mFadeRange))) { mVisible = FALSE; return; } LLVector3 x_pixel_vec; LLVector3 y_pixel_vec; LLViewerCamera::getInstance()->getPixelVectors(mPositionAgent, y_pixel_vec, x_pixel_vec); LLVector3 render_position = mPositionAgent + (x_pixel_vec * mPositionOffset.mV[VX]) + (y_pixel_vec * mPositionOffset.mV[VY]); mOffscreen = FALSE; if (!LLViewerCamera::getInstance()->sphereInFrustum(render_position, mRadius)) { if (!mVisibleOffScreen) { mVisible = FALSE; return; } else { mOffscreen = TRUE; } } mVisible = TRUE; sVisibleTextObjects.push_back(LLPointer<LLHUDNameTag> (this)); } LLVector2 LLHUDNameTag::updateScreenPos(LLVector2 &offset) { LLCoordGL screen_pos; LLVector2 screen_pos_vec; LLVector3 x_pixel_vec; LLVector3 y_pixel_vec; LLViewerCamera::getInstance()->getPixelVectors(mPositionAgent, y_pixel_vec, x_pixel_vec); LLVector3 world_pos = mPositionAgent + (offset.mV[VX] * x_pixel_vec) + (offset.mV[VY] * y_pixel_vec); if (!LLViewerCamera::getInstance()->projectPosAgentToScreen(world_pos, screen_pos, FALSE) && mVisibleOffScreen) { // bubble off-screen, so find a spot for it along screen edge LLViewerCamera::getInstance()->projectPosAgentToScreenEdge(world_pos, screen_pos); } screen_pos_vec.setVec((F32)screen_pos.mX, (F32)screen_pos.mY); LLRect world_rect = gViewerWindow->getWorldViewRectScaled(); S32 bottom = world_rect.mBottom + STATUS_BAR_HEIGHT; LLVector2 screen_center; screen_center.mV[VX] = llclamp((F32)screen_pos_vec.mV[VX], (F32)world_rect.mLeft + mWidth * 0.5f, (F32)world_rect.mRight - mWidth * 0.5f); if(mVertAlignment == ALIGN_VERT_TOP) { screen_center.mV[VY] = llclamp((F32)screen_pos_vec.mV[VY], (F32)bottom, (F32)world_rect.mTop - mHeight - (F32)MENU_BAR_HEIGHT); mSoftScreenRect.setLeftTopAndSize(screen_center.mV[VX] - (mWidth + BUFFER_SIZE) * 0.5f, screen_center.mV[VY] + (mHeight + BUFFER_SIZE), mWidth + BUFFER_SIZE, mHeight + BUFFER_SIZE); } else { screen_center.mV[VY] = llclamp((F32)screen_pos_vec.mV[VY], (F32)bottom + mHeight * 0.5f, (F32)world_rect.mTop - mHeight * 0.5f - (F32)MENU_BAR_HEIGHT); mSoftScreenRect.setCenterAndSize(screen_center.mV[VX], screen_center.mV[VY], mWidth + BUFFER_SIZE, mHeight + BUFFER_SIZE); } return offset + (screen_center - LLVector2((F32)screen_pos.mX, (F32)screen_pos.mY)); } void LLHUDNameTag::updateSize() { F32 height = 0.f; F32 width = 0.f; S32 max_lines = getMaxLines(); //S32 lines = (max_lines < 0) ? (S32)mTextSegments.size() : llmin((S32)mTextSegments.size(), max_lines); //F32 height = (F32)mFontp->getLineHeight() * (lines + mLabelSegments.size()); S32 start_segment; if (max_lines < 0) start_segment = 0; else start_segment = llmax((S32)0, (S32)mTextSegments.size() - max_lines); std::vector<LLHUDTextSegment>::iterator iter = mTextSegments.begin() + start_segment; while (iter != mTextSegments.end()) { const LLFontGL* fontp = iter->mFont; height += fontp->getLineHeight(); height += LINE_PADDING; width = llmax(width, llmin(iter->getWidth(fontp), HUD_TEXT_MAX_WIDTH)); ++iter; } // Don't want line spacing under the last line if (height > 0.f) { height -= LINE_PADDING; } iter = mLabelSegments.begin(); while (iter != mLabelSegments.end()) { height += mFontp->getLineHeight(); width = llmax(width, llmin(iter->getWidth(mFontp), HUD_TEXT_MAX_WIDTH)); ++iter; } if (width == 0.f) { return; } width += HORIZONTAL_PADDING; height += VERTICAL_PADDING; // *TODO: Could do a timer-based resize here //mWidth = llmax(width, lerp(mWidth, (F32)width, u)); //mHeight = llmax(height, lerp(mHeight, (F32)height, u)); mWidth = width; mHeight = height; } void LLHUDNameTag::updateAll() { // iterate over all text objects, calculate their restoration forces, // and add them to the visible set if they are on screen and close enough sVisibleTextObjects.clear(); TextObjectIterator text_it; for (text_it = sTextObjects.begin(); text_it != sTextObjects.end(); ++text_it) { LLHUDNameTag* textp = (*text_it); textp->mTargetPositionOffset.clearVec(); textp->updateSize(); textp->updateVisibility(); } // sort back to front for rendering purposes std::sort(sVisibleTextObjects.begin(), sVisibleTextObjects.end(), llhudnametag_further_away()); // iterate from front to back, and set LOD based on current screen coverage F32 screen_area = (F32)(gViewerWindow->getWindowWidthScaled() * gViewerWindow->getWindowHeightScaled()); F32 current_screen_area = 0.f; std::vector<LLPointer<LLHUDNameTag> >::reverse_iterator r_it; for (r_it = sVisibleTextObjects.rbegin(); r_it != sVisibleTextObjects.rend(); ++r_it) { LLHUDNameTag* textp = (*r_it); if (current_screen_area / screen_area > LOD_2_SCREEN_COVERAGE) { textp->setLOD(3); } else if (current_screen_area / screen_area > LOD_1_SCREEN_COVERAGE) { textp->setLOD(2); } else if (current_screen_area / screen_area > LOD_0_SCREEN_COVERAGE) { textp->setLOD(1); } else { textp->setLOD(0); } textp->updateSize(); // find on-screen position and initialize collision rectangle textp->mTargetPositionOffset = textp->updateScreenPos(LLVector2::zero); current_screen_area += (F32)(textp->mSoftScreenRect.getWidth() * textp->mSoftScreenRect.getHeight()); } LLTrace::CountStatHandle<>* camera_vel_stat = LLViewerCamera::getVelocityStat(); F32 camera_vel = LLTrace::get_frame_recording().getLastRecording().getPerSec(*camera_vel_stat); if (camera_vel > MAX_STABLE_CAMERA_VELOCITY) { return; } VisibleTextObjectIterator src_it; for (S32 i = 0; i < NUM_OVERLAP_ITERATIONS; i++) { for (src_it = sVisibleTextObjects.begin(); src_it != sVisibleTextObjects.end(); ++src_it) { LLHUDNameTag* src_textp = (*src_it); VisibleTextObjectIterator dst_it = src_it; ++dst_it; for (; dst_it != sVisibleTextObjects.end(); ++dst_it) { LLHUDNameTag* dst_textp = (*dst_it); if (src_textp->mSoftScreenRect.overlaps(dst_textp->mSoftScreenRect)) { LLRectf intersect_rect = src_textp->mSoftScreenRect; intersect_rect.intersectWith(dst_textp->mSoftScreenRect); intersect_rect.stretch(-BUFFER_SIZE * 0.5f); F32 src_center_x = src_textp->mSoftScreenRect.getCenterX(); F32 src_center_y = src_textp->mSoftScreenRect.getCenterY(); F32 dst_center_x = dst_textp->mSoftScreenRect.getCenterX(); F32 dst_center_y = dst_textp->mSoftScreenRect.getCenterY(); F32 intersect_center_x = intersect_rect.getCenterX(); F32 intersect_center_y = intersect_rect.getCenterY(); LLVector2 force = lerp(LLVector2(dst_center_x - intersect_center_x, dst_center_y - intersect_center_y), LLVector2(intersect_center_x - src_center_x, intersect_center_y - src_center_y), 0.5f); force.setVec(dst_center_x - src_center_x, dst_center_y - src_center_y); force.normVec(); LLVector2 src_force = -1.f * force; LLVector2 dst_force = force; LLVector2 force_strength; F32 src_mult = dst_textp->mMass / (dst_textp->mMass + src_textp->mMass); F32 dst_mult = 1.f - src_mult; F32 src_aspect_ratio = src_textp->mSoftScreenRect.getWidth() / src_textp->mSoftScreenRect.getHeight(); F32 dst_aspect_ratio = dst_textp->mSoftScreenRect.getWidth() / dst_textp->mSoftScreenRect.getHeight(); src_force.mV[VY] *= src_aspect_ratio; src_force.normVec(); dst_force.mV[VY] *= dst_aspect_ratio; dst_force.normVec(); src_force.mV[VX] *= llmin(intersect_rect.getWidth() * src_mult, intersect_rect.getHeight() * SPRING_STRENGTH); src_force.mV[VY] *= llmin(intersect_rect.getHeight() * src_mult, intersect_rect.getWidth() * SPRING_STRENGTH); dst_force.mV[VX] *= llmin(intersect_rect.getWidth() * dst_mult, intersect_rect.getHeight() * SPRING_STRENGTH); dst_force.mV[VY] *= llmin(intersect_rect.getHeight() * dst_mult, intersect_rect.getWidth() * SPRING_STRENGTH); src_textp->mTargetPositionOffset += src_force; dst_textp->mTargetPositionOffset += dst_force; src_textp->mTargetPositionOffset = src_textp->updateScreenPos(src_textp->mTargetPositionOffset); dst_textp->mTargetPositionOffset = dst_textp->updateScreenPos(dst_textp->mTargetPositionOffset); } } } } VisibleTextObjectIterator this_object_it; for (this_object_it = sVisibleTextObjects.begin(); this_object_it != sVisibleTextObjects.end(); ++this_object_it) { (*this_object_it)->mPositionOffset = lerp((*this_object_it)->mPositionOffset, (*this_object_it)->mTargetPositionOffset, LLSmoothInterpolation::getInterpolant(POSITION_DAMPING_TC)); } } void LLHUDNameTag::setLOD(S32 lod) { mLOD = lod; //RN: uncomment this to visualize LOD levels //std::string label = llformat("%d", lod); //setLabel(label); } S32 LLHUDNameTag::getMaxLines() { switch(mLOD) { case 0: return mMaxLines; case 1: return mMaxLines > 0 ? mMaxLines / 2 : 5; case 2: return mMaxLines > 0 ? mMaxLines / 3 : 2; default: // label only return 0; } } void LLHUDNameTag::markDead() { sTextObjects.erase(LLPointer<LLHUDNameTag>(this)); LLHUDObject::markDead(); } void LLHUDNameTag::shiftAll(const LLVector3& offset) { TextObjectIterator text_it; for (text_it = sTextObjects.begin(); text_it != sTextObjects.end(); ++text_it) { LLHUDNameTag *textp = text_it->get(); textp->shift(offset); } } void LLHUDNameTag::shift(const LLVector3& offset) { mPositionAgent += offset; } //static void LLHUDNameTag::addPickable(std::set<LLViewerObject*> &pick_list) { //this might put an object on the pick list a second time, overriding it's mGLName, which is ok // *FIX: we should probably cull against pick frustum VisibleTextObjectIterator text_it; for (text_it = sVisibleTextObjects.begin(); text_it != sVisibleTextObjects.end(); ++text_it) { pick_list.insert((*text_it)->mSourceObject); } } //static // called when UI scale changes, to flush font width caches void LLHUDNameTag::reshape() { TextObjectIterator text_it; for (text_it = sTextObjects.begin(); text_it != sTextObjects.end(); ++text_it) { LLHUDNameTag* textp = (*text_it); std::vector<LLHUDTextSegment>::iterator segment_iter; for (segment_iter = textp->mTextSegments.begin(); segment_iter != textp->mTextSegments.end(); ++segment_iter ) { segment_iter->clearFontWidthMap(); } for(segment_iter = textp->mLabelSegments.begin(); segment_iter != textp->mLabelSegments.end(); ++segment_iter ) { segment_iter->clearFontWidthMap(); } } } //============================================================================ F32 LLHUDNameTag::LLHUDTextSegment::getWidth(const LLFontGL* font) { std::map<const LLFontGL*, F32>::iterator iter = mFontWidthMap.find(font); if (iter != mFontWidthMap.end()) { return iter->second; } else { F32 width = font->getWidthF32(mText.c_str()); mFontWidthMap[font] = width; return width; } }
30.76725
199
0.702862
[ "render", "object", "vector" ]
9c272c5607e494f006404e747a8ebb0e202ae2fe
2,969
cpp
C++
benchmark/benchmark_merge.cpp
AVoytenko/semester-work-fibonacci-heap
afbde338089a45a928dee031a73e7fa4415d7d32
[ "MIT" ]
null
null
null
benchmark/benchmark_merge.cpp
AVoytenko/semester-work-fibonacci-heap
afbde338089a45a928dee031a73e7fa4415d7d32
[ "MIT" ]
null
null
null
benchmark/benchmark_merge.cpp
AVoytenko/semester-work-fibonacci-heap
afbde338089a45a928dee031a73e7fa4415d7d32
[ "MIT" ]
null
null
null
#include <fstream> // ifstream #include <iostream> // cout #include <string> // string, stoi #include <string_view> // string_view #include <chrono> // high_resolution_clock, duration_cast, nanoseconds #include <vector> // подключаем вашу структуру данных #include "data_structure.hpp" using namespace std; using namespace itis; // абсолютный путь до набора данных и папки проекта static constexpr auto kDatasetPath = string_view{PROJECT_DATASET_DIR}; static constexpr auto kProjectPath = string_view{PROJECT_SOURCE_DIR}; int main() { // Tip 1: входные аргументы позволяют более гибко контролировать параметры вашей программы const auto path = string(kDatasetPath); const auto output_path = string(kProjectPath) + "/benchmark/result/benchmark_merge_result.csv"; // работа с набором данных vector <string> folders = {"01", "02", "03", "04", "05", "06", "07", "08", "09", "10"}; vector <string> files = {"100", "500", "1000", "5000", "10000", "50000", "100000", "500000", "1000000", "5000000"}; itis::FibonacciHeap heap1; itis::FibonacciHeap heap2; for (string file : files) { // Проходим по всем 10 .csv файлам for (string folder : folders) { // Проходим по всем 10 папкам с файлами for (int i = 1; i < 11; i++) { // Запускаем замерку времени 10 раз string line = "1"; auto input_file = ifstream(path + "/" + "merge/" + folder + "/" + file + ".csv"); auto time_diff_search = chrono::nanoseconds::zero(); cout << (path + "/" + "merge/" + folder + "/" + file) << endl; if (input_file) { while (line != "") { getline(input_file, line); if (line == "") { break; } heap1.insert(stoi(line)); heap2.insert(stoi(line)); } } input_file.close(); line = "1"; input_file = ifstream(path + "/" + "merge/" + folder + "/" + file + ".csv"); // здесь находится участок кода, время которого необходимо замерить if (input_file) { while (line != "") { getline(input_file, line); if (line == "") { break; } const auto time_point_before_search = chrono::steady_clock::now(); heap1.merge(heap2); const auto time_point_after_search = chrono::steady_clock::now(); time_diff_search += time_point_after_search - time_point_before_search; } } const auto time_elapsed_ns_search = chrono::duration_cast<chrono::nanoseconds>(time_diff_search).count(); cout << time_elapsed_ns_search << endl; //tree.Clear(); input_file.close(); // Открываем файл для записи и вносим полученые данные auto output_file = fstream(output_path, ios::app); output_file << folder << "," << file << "," << time_elapsed_ns_search << endl; output_file.close(); } } } return 0; }
36.207317
117
0.597508
[ "vector" ]
9c2d77d6bc9917c3af32140c8319157a5cda98fe
12,089
cc
C++
src/objects/js-plural-rules.cc
LancerWang001/v8
42ff4531f590b901ade0a18bfd03e56485fe2452
[ "BSD-3-Clause" ]
35
2015-01-22T09:56:20.000Z
2021-09-13T01:11:00.000Z
src/objects/js-plural-rules.cc
Andrea-MariaDB-2/v8
a0f0ebd7a876e8cb2210115adbfcffe900e99540
[ "BSD-3-Clause" ]
11
2019-10-15T23:03:57.000Z
2020-06-14T16:10:12.000Z
src/objects/js-plural-rules.cc
Andrea-MariaDB-2/v8
a0f0ebd7a876e8cb2210115adbfcffe900e99540
[ "BSD-3-Clause" ]
41
2015-01-19T12:30:57.000Z
2021-12-22T19:05:38.000Z
// Copyright 2018 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef V8_INTL_SUPPORT #error Internationalization is expected to be enabled. #endif // V8_INTL_SUPPORT #include "src/objects/js-plural-rules.h" #include "src/execution/isolate-inl.h" #include "src/objects/intl-objects.h" #include "src/objects/js-number-format.h" #include "src/objects/js-plural-rules-inl.h" #include "unicode/locid.h" #include "unicode/numberformatter.h" #include "unicode/plurrule.h" #include "unicode/unumberformatter.h" namespace v8 { namespace internal { namespace { bool CreateICUPluralRules(Isolate* isolate, const icu::Locale& icu_locale, JSPluralRules::Type type, std::unique_ptr<icu::PluralRules>* pl) { // Make formatter from options. Numbering system is added // to the locale as Unicode extension (if it was specified at all). UErrorCode status = U_ZERO_ERROR; UPluralType icu_type = UPLURAL_TYPE_CARDINAL; if (type == JSPluralRules::Type::ORDINAL) { icu_type = UPLURAL_TYPE_ORDINAL; } else { DCHECK_EQ(JSPluralRules::Type::CARDINAL, type); } std::unique_ptr<icu::PluralRules> plural_rules( icu::PluralRules::forLocale(icu_locale, icu_type, status)); if (U_FAILURE(status)) { return false; } DCHECK_NOT_NULL(plural_rules.get()); *pl = std::move(plural_rules); return true; } } // namespace Handle<String> JSPluralRules::TypeAsString() const { switch (type()) { case Type::CARDINAL: return GetReadOnlyRoots().cardinal_string_handle(); case Type::ORDINAL: return GetReadOnlyRoots().ordinal_string_handle(); } UNREACHABLE(); } // static MaybeHandle<JSPluralRules> JSPluralRules::New(Isolate* isolate, Handle<Map> map, Handle<Object> locales, Handle<Object> options_obj) { // 1. Let requestedLocales be ? CanonicalizeLocaleList(locales). Maybe<std::vector<std::string>> maybe_requested_locales = Intl::CanonicalizeLocaleList(isolate, locales); MAYBE_RETURN(maybe_requested_locales, Handle<JSPluralRules>()); std::vector<std::string> requested_locales = maybe_requested_locales.FromJust(); // 2. Set options to ? CoerceOptionsToObject(options). Handle<JSReceiver> options; const char* service = "Intl.PluralRules"; ASSIGN_RETURN_ON_EXCEPTION( isolate, options, Intl::CoerceOptionsToObject(isolate, options_obj, service), JSPluralRules); // 5. Let matcher be ? GetOption(options, "localeMatcher", "string", // « "lookup", "best fit" », "best fit"). // 6. Set opt.[[localeMatcher]] to matcher. Maybe<Intl::MatcherOption> maybe_locale_matcher = Intl::GetLocaleMatcher(isolate, options, service); MAYBE_RETURN(maybe_locale_matcher, MaybeHandle<JSPluralRules>()); Intl::MatcherOption matcher = maybe_locale_matcher.FromJust(); // 7. Let t be ? GetOption(options, "type", "string", « "cardinal", // "ordinal" », "cardinal"). Maybe<Type> maybe_type = Intl::GetStringOption<Type>( isolate, options, "type", service, {"cardinal", "ordinal"}, {Type::CARDINAL, Type::ORDINAL}, Type::CARDINAL); MAYBE_RETURN(maybe_type, MaybeHandle<JSPluralRules>()); Type type = maybe_type.FromJust(); // Note: The spec says we should do ResolveLocale after performing // SetNumberFormatDigitOptions but we need the locale to create all // the ICU data structures. // // This isn't observable so we aren't violating the spec. // 11. Let r be ResolveLocale(%PluralRules%.[[AvailableLocales]], // requestedLocales, opt, %PluralRules%.[[RelevantExtensionKeys]], // localeData). Maybe<Intl::ResolvedLocale> maybe_resolve_locale = Intl::ResolveLocale(isolate, JSPluralRules::GetAvailableLocales(), requested_locales, matcher, {}); if (maybe_resolve_locale.IsNothing()) { THROW_NEW_ERROR(isolate, NewRangeError(MessageTemplate::kIcuError), JSPluralRules); } Intl::ResolvedLocale r = maybe_resolve_locale.FromJust(); Handle<String> locale_str = isolate->factory()->NewStringFromAsciiChecked(r.locale.c_str()); icu::number::LocalizedNumberFormatter icu_number_formatter = icu::number::NumberFormatter::withLocale(r.icu_locale) .roundingMode(UNUM_ROUND_HALFUP); std::unique_ptr<icu::PluralRules> icu_plural_rules; bool success = CreateICUPluralRules(isolate, r.icu_locale, type, &icu_plural_rules); if (!success || icu_plural_rules.get() == nullptr) { // Remove extensions and try again. icu::Locale no_extension_locale(r.icu_locale.getBaseName()); success = CreateICUPluralRules(isolate, no_extension_locale, type, &icu_plural_rules); icu_number_formatter = icu::number::NumberFormatter::withLocale(no_extension_locale) .roundingMode(UNUM_ROUND_HALFUP); if (!success || icu_plural_rules.get() == nullptr) { THROW_NEW_ERROR(isolate, NewRangeError(MessageTemplate::kIcuError), JSPluralRules); } } // 9. Perform ? SetNumberFormatDigitOptions(pluralRules, options, 0, 3). Maybe<Intl::NumberFormatDigitOptions> maybe_digit_options = Intl::SetNumberFormatDigitOptions(isolate, options, 0, 3, false); MAYBE_RETURN(maybe_digit_options, MaybeHandle<JSPluralRules>()); Intl::NumberFormatDigitOptions digit_options = maybe_digit_options.FromJust(); icu_number_formatter = JSNumberFormat::SetDigitOptionsToFormatter( icu_number_formatter, digit_options); Handle<Managed<icu::PluralRules>> managed_plural_rules = Managed<icu::PluralRules>::FromUniquePtr(isolate, 0, std::move(icu_plural_rules)); Handle<Managed<icu::number::LocalizedNumberFormatter>> managed_number_formatter = Managed<icu::number::LocalizedNumberFormatter>::FromRawPtr( isolate, 0, new icu::number::LocalizedNumberFormatter(icu_number_formatter)); // Now all properties are ready, so we can allocate the result object. Handle<JSPluralRules> plural_rules = Handle<JSPluralRules>::cast( isolate->factory()->NewFastOrSlowJSObjectFromMap(map)); DisallowGarbageCollection no_gc; plural_rules->set_flags(0); // 8. Set pluralRules.[[Type]] to t. plural_rules->set_type(type); // 12. Set pluralRules.[[Locale]] to the value of r.[[locale]]. plural_rules->set_locale(*locale_str); plural_rules->set_icu_plural_rules(*managed_plural_rules); plural_rules->set_icu_number_formatter(*managed_number_formatter); // 13. Return pluralRules. return plural_rules; } MaybeHandle<String> JSPluralRules::ResolvePlural( Isolate* isolate, Handle<JSPluralRules> plural_rules, double number) { icu::PluralRules* icu_plural_rules = plural_rules->icu_plural_rules().raw(); DCHECK_NOT_NULL(icu_plural_rules); icu::number::LocalizedNumberFormatter* fmt = plural_rules->icu_number_formatter().raw(); DCHECK_NOT_NULL(fmt); UErrorCode status = U_ZERO_ERROR; icu::number::FormattedNumber formatted_number = fmt->formatDouble(number, status); DCHECK(U_SUCCESS(status)); icu::UnicodeString result = icu_plural_rules->select(formatted_number, status); DCHECK(U_SUCCESS(status)); return Intl::ToString(isolate, result); } namespace { void CreateDataPropertyForOptions(Isolate* isolate, Handle<JSObject> options, Handle<Object> value, const char* key) { Handle<String> key_str = isolate->factory()->NewStringFromAsciiChecked(key); // This is a brand new JSObject that shouldn't already have the same // key so this shouldn't fail. Maybe<bool> maybe = JSReceiver::CreateDataProperty(isolate, options, key_str, value, Just(kDontThrow)); DCHECK(maybe.FromJust()); USE(maybe); } void CreateDataPropertyForOptions(Isolate* isolate, Handle<JSObject> options, int value, const char* key) { Handle<Smi> value_smi(Smi::FromInt(value), isolate); CreateDataPropertyForOptions(isolate, options, value_smi, key); } } // namespace Handle<JSObject> JSPluralRules::ResolvedOptions( Isolate* isolate, Handle<JSPluralRules> plural_rules) { Handle<JSObject> options = isolate->factory()->NewJSObject(isolate->object_function()); Handle<String> locale_value(plural_rules->locale(), isolate); CreateDataPropertyForOptions(isolate, options, locale_value, "locale"); CreateDataPropertyForOptions(isolate, options, plural_rules->TypeAsString(), "type"); UErrorCode status = U_ZERO_ERROR; icu::number::LocalizedNumberFormatter* icu_number_formatter = plural_rules->icu_number_formatter().raw(); icu::UnicodeString skeleton = icu_number_formatter->toSkeleton(status); DCHECK(U_SUCCESS(status)); CreateDataPropertyForOptions( isolate, options, JSNumberFormat::MinimumIntegerDigitsFromSkeleton(skeleton), "minimumIntegerDigits"); int32_t min = 0, max = 0; if (JSNumberFormat::SignificantDigitsFromSkeleton(skeleton, &min, &max)) { CreateDataPropertyForOptions(isolate, options, min, "minimumSignificantDigits"); CreateDataPropertyForOptions(isolate, options, max, "maximumSignificantDigits"); } else { JSNumberFormat::FractionDigitsFromSkeleton(skeleton, &min, &max); CreateDataPropertyForOptions(isolate, options, min, "minimumFractionDigits"); CreateDataPropertyForOptions(isolate, options, max, "maximumFractionDigits"); } // 6. Let pluralCategories be a List of Strings representing the // possible results of PluralRuleSelect for the selected locale pr. icu::PluralRules* icu_plural_rules = plural_rules->icu_plural_rules().raw(); DCHECK_NOT_NULL(icu_plural_rules); std::unique_ptr<icu::StringEnumeration> categories( icu_plural_rules->getKeywords(status)); DCHECK(U_SUCCESS(status)); int32_t count = categories->count(status); DCHECK(U_SUCCESS(status)); Handle<FixedArray> plural_categories = isolate->factory()->NewFixedArray(count); for (int32_t i = 0; i < count; i++) { const icu::UnicodeString* category = categories->snext(status); DCHECK(U_SUCCESS(status)); if (category == nullptr) break; std::string keyword; Handle<String> value = isolate->factory()->NewStringFromAsciiChecked( category->toUTF8String(keyword).data()); plural_categories->set(i, *value); } // 7. Perform ! CreateDataProperty(options, "pluralCategories", // CreateArrayFromList(pluralCategories)). Handle<JSArray> plural_categories_value = isolate->factory()->NewJSArrayWithElements(plural_categories); CreateDataPropertyForOptions(isolate, options, plural_categories_value, "pluralCategories"); return options; } namespace { class PluralRulesAvailableLocales { public: PluralRulesAvailableLocales() { UErrorCode status = U_ZERO_ERROR; std::unique_ptr<icu::StringEnumeration> locales( icu::PluralRules::getAvailableLocales(status)); DCHECK(U_SUCCESS(status)); int32_t len = 0; const char* locale = nullptr; while ((locale = locales->next(&len, status)) != nullptr && U_SUCCESS(status)) { std::string str(locale); if (len > 3) { std::replace(str.begin(), str.end(), '_', '-'); } set_.insert(std::move(str)); } } const std::set<std::string>& Get() const { return set_; } private: std::set<std::string> set_; }; } // namespace const std::set<std::string>& JSPluralRules::GetAvailableLocales() { static base::LazyInstance<PluralRulesAvailableLocales>::type available_locales = LAZY_INSTANCE_INITIALIZER; return available_locales.Pointer()->Get(); } } // namespace internal } // namespace v8
37.196923
80
0.696501
[ "object", "vector" ]
9c2e1714d8510127d78f9d48a17f336a0caa3a03
5,188
hpp
C++
include/Mono/Globalization/Unicode/NormalizationTableUtil.hpp
Fernthedev/BeatSaber-Quest-Codegen
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
[ "Unlicense" ]
null
null
null
include/Mono/Globalization/Unicode/NormalizationTableUtil.hpp
Fernthedev/BeatSaber-Quest-Codegen
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
[ "Unlicense" ]
null
null
null
include/Mono/Globalization/Unicode/NormalizationTableUtil.hpp
Fernthedev/BeatSaber-Quest-Codegen
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" #include "extern/beatsaber-hook/shared/utils/byref.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: Mono::Globalization::Unicode namespace Mono::Globalization::Unicode { // Forward declaring type: CodePointIndexer class CodePointIndexer; } // Completed forward declares // Type namespace: Mono.Globalization.Unicode namespace Mono::Globalization::Unicode { // Size: 0x10 #pragma pack(push, 1) // Autogenerated type: Mono.Globalization.Unicode.NormalizationTableUtil // [TokenAttribute] Offset: FFFFFFFF class NormalizationTableUtil : public ::Il2CppObject { public: // Creating value type constructor for type: NormalizationTableUtil NormalizationTableUtil() noexcept {} // Get static field: static public readonly Mono.Globalization.Unicode.CodePointIndexer Prop static Mono::Globalization::Unicode::CodePointIndexer* _get_Prop(); // Set static field: static public readonly Mono.Globalization.Unicode.CodePointIndexer Prop static void _set_Prop(Mono::Globalization::Unicode::CodePointIndexer* value); // Get static field: static public readonly Mono.Globalization.Unicode.CodePointIndexer Map static Mono::Globalization::Unicode::CodePointIndexer* _get_Map(); // Set static field: static public readonly Mono.Globalization.Unicode.CodePointIndexer Map static void _set_Map(Mono::Globalization::Unicode::CodePointIndexer* value); // Get static field: static public readonly Mono.Globalization.Unicode.CodePointIndexer Combining static Mono::Globalization::Unicode::CodePointIndexer* _get_Combining(); // Set static field: static public readonly Mono.Globalization.Unicode.CodePointIndexer Combining static void _set_Combining(Mono::Globalization::Unicode::CodePointIndexer* value); // Get static field: static public readonly Mono.Globalization.Unicode.CodePointIndexer Composite static Mono::Globalization::Unicode::CodePointIndexer* _get_Composite(); // Set static field: static public readonly Mono.Globalization.Unicode.CodePointIndexer Composite static void _set_Composite(Mono::Globalization::Unicode::CodePointIndexer* value); // Get static field: static public readonly Mono.Globalization.Unicode.CodePointIndexer Helper static Mono::Globalization::Unicode::CodePointIndexer* _get_Helper(); // Set static field: static public readonly Mono.Globalization.Unicode.CodePointIndexer Helper static void _set_Helper(Mono::Globalization::Unicode::CodePointIndexer* value); // static private System.Void .cctor() // Offset: 0x1A6B5E4 static void _cctor(); // static public System.Int32 PropIdx(System.Int32 cp) // Offset: 0x1A6B8A4 static int PropIdx(int cp); // static public System.Int32 MapIdx(System.Int32 cp) // Offset: 0x1A6B91C static int MapIdx(int cp); }; // Mono.Globalization.Unicode.NormalizationTableUtil #pragma pack(pop) } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(Mono::Globalization::Unicode::NormalizationTableUtil*, "Mono.Globalization.Unicode", "NormalizationTableUtil"); #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: Mono::Globalization::Unicode::NormalizationTableUtil::_cctor // Il2CppName: .cctor template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)()>(&Mono::Globalization::Unicode::NormalizationTableUtil::_cctor)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(Mono::Globalization::Unicode::NormalizationTableUtil*), ".cctor", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: Mono::Globalization::Unicode::NormalizationTableUtil::PropIdx // Il2CppName: PropIdx template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (*)(int)>(&Mono::Globalization::Unicode::NormalizationTableUtil::PropIdx)> { static const MethodInfo* get() { static auto* cp = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(Mono::Globalization::Unicode::NormalizationTableUtil*), "PropIdx", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{cp}); } }; // Writing MetadataGetter for method: Mono::Globalization::Unicode::NormalizationTableUtil::MapIdx // Il2CppName: MapIdx template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (*)(int)>(&Mono::Globalization::Unicode::NormalizationTableUtil::MapIdx)> { static const MethodInfo* get() { static auto* cp = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(Mono::Globalization::Unicode::NormalizationTableUtil*), "MapIdx", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{cp}); } };
59.632184
181
0.744796
[ "vector" ]
9c2edf0a14815bca2056587f3ee4f957e49eb027
1,185
cpp
C++
doc/examples/Property/Density.cpp
undisputed-seraphim/TBTK
45a0875a11da951f900b6fd5e0773ccdf8462915
[ "Apache-2.0" ]
96
2016-04-21T16:46:56.000Z
2022-01-15T21:40:25.000Z
doc/examples/Property/Density.cpp
undisputed-seraphim/TBTK
45a0875a11da951f900b6fd5e0773ccdf8462915
[ "Apache-2.0" ]
4
2016-10-19T16:56:20.000Z
2020-04-14T01:31:40.000Z
doc/examples/Property/Density.cpp
undisputed-seraphim/TBTK
45a0875a11da951f900b6fd5e0773ccdf8462915
[ "Apache-2.0" ]
19
2016-10-19T14:21:58.000Z
2021-04-15T13:52:09.000Z
#include "HeaderAndFooter.h" TBTK::DocumentationExamples::HeaderAndFooter headerAndFooter("Density"); //! [Density] #include "TBTK/Models/SquareLattice.h" #include "TBTK/Property/Density.h" #include "TBTK/PropertyExtractor/Diagonalizer.h" #include "TBTK/Solver/Diagonalizer.h" #include "TBTK/Streams.h" #include "TBTK/TBTK.h" #include "TBTK/Visualization/MatPlotLib/Plotter.h" using namespace TBTK; using namespace Visualization::MatPlotLib; int main(){ Initialize(); const unsigned int SIZE_X = 10; const unsigned int SIZE_Y = 10; double t = 1; Model model = Models::SquareLattice({SIZE_X, SIZE_Y}, {0, t}); model.setChemicalPotential(-2); model.construct(); Solver::Diagonalizer solver; solver.setModel(model); solver.run(); PropertyExtractor::Diagonalizer propertyExtractor; propertyExtractor.setSolver(solver); Property::Density density = propertyExtractor.calculateDensity({{_a_, _a_}}); Streams::out << "density({5, 5}) = " << density({5, 5}) << "\n"; Plotter plotter; plotter.plot({_a_, _a_}, density); plotter.save("figures/Density.png"); plotter.clear(); plotter.plot({_a_, 5}, density); plotter.save("figures/DensityCut.png"); } //! [Density]
25.212766
72
0.731646
[ "model" ]
9c3508ff0db55f9a49f23c2e264a1b8fe6d48a89
538
hpp
C++
src/game/PlatformerScene.hpp
RichardMarks/ld41_poker_platform
9c97ec3bdf556bd6228c54681ccb160729c088ff
[ "MIT" ]
null
null
null
src/game/PlatformerScene.hpp
RichardMarks/ld41_poker_platform
9c97ec3bdf556bd6228c54681ccb160729c088ff
[ "MIT" ]
null
null
null
src/game/PlatformerScene.hpp
RichardMarks/ld41_poker_platform
9c97ec3bdf556bd6228c54681ccb160729c088ff
[ "MIT" ]
null
null
null
#ifndef PLATFORMER_SCENE #define PLATFORMER_SCENE #include <vector> #include "SceneInterface.hpp" #include "lib/TileMap.hpp" class PlatformerScene : public SceneInterface { public: PlatformerScene(Game* game) : SceneInterface(game) {} virtual void create(); virtual void destroy(); virtual void enter(); virtual void exit(); virtual void update(sf::Time const& deltaTime); virtual void render(); protected: TileMap tileMap; std::vector<sf::View> viewList; }; #endif // !PLATFORMER_SCENE
20.692308
51
0.697026
[ "render", "vector" ]
9c375c394771b02697f15c4abf28f0c9e46d437a
45,292
cxx
C++
test/multiconvolution/test.cxx
BSeppke/vigra
490213d8954a03bdb985b52cfaafd6389431efd8
[ "MIT" ]
316
2015-01-01T02:06:53.000Z
2022-03-28T08:37:28.000Z
test/multiconvolution/test.cxx
BSeppke/vigra
490213d8954a03bdb985b52cfaafd6389431efd8
[ "MIT" ]
232
2015-01-06T23:51:07.000Z
2022-03-18T13:14:02.000Z
test/multiconvolution/test.cxx
BSeppke/vigra
490213d8954a03bdb985b52cfaafd6389431efd8
[ "MIT" ]
150
2015-01-05T02:11:18.000Z
2022-03-16T09:44:14.000Z
/************************************************************************/ /* */ /* Copyright 2004 by Ullrich Koethe */ /* */ /* This file is part of the VIGRA computer vision library. */ /* The VIGRA Website is */ /* http://hci.iwr.uni-heidelberg.de/vigra/ */ /* Please direct questions, bug reports, and contributions to */ /* ullrich.koethe@iwr.uni-heidelberg.de or */ /* vigra@informatik.uni-hamburg.de */ /* */ /* Permission is hereby granted, free of charge, to any person */ /* obtaining a copy of this software and associated documentation */ /* files (the "Software"), to deal in the Software without */ /* restriction, including without limitation the rights to use, */ /* copy, modify, merge, publish, distribute, sublicense, and/or */ /* sell copies of the Software, and to permit persons to whom the */ /* Software is furnished to do so, subject to the following */ /* conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the */ /* Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES */ /* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND */ /* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT */ /* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, */ /* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING */ /* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR */ /* OTHER DEALINGS IN THE SOFTWARE. */ /* */ /************************************************************************/ // -*- c++ -*- // $Id$ #include <iostream> #include <vector> #include <string> #include <sstream> #include <limits> #include <functional> #include <cmath> #include "vigra/unittest.hxx" #include "vigra/multi_array.hxx" #include "vigra/multi_convolution.hxx" #include "vigra/basicimageview.hxx" #include "vigra/convolution.hxx" #include "vigra/navigator.hxx" #include "vigra/random.hxx" #include "vigra/impex.hxx" #include "vigra/imageinfo.hxx" #include "vigra/basicimage.hxx" #include "vigra/diff2d.hxx" #include "vigra/stdimage.hxx" #include "vigra/multi_resize.hxx" #include "vigra/separableconvolution.hxx" #include "vigra/bordertreatment.hxx" using namespace vigra; using namespace vigra::functor; struct MultiArraySeparableConvolutionTest { typedef float PixelType; typedef TinyVector<PixelType,3> VectorPixelType; typedef MultiArray<3, VectorPixelType> Image3x3; typedef MultiArray<3,PixelType> Image3D; typedef Image3D::difference_type Size3; typedef BasicImage<PixelType> Image2D; typedef Image2D::difference_type Size2; // - - - - - - - - - - - - - - - - - - - - - - - - template<class Image> void makeRandom( Image &image ) { typedef typename Image::value_type T; int size = image.size(); for( int k = 0; k < size; ++k ) { typedef typename NumericTraits<typename Image::value_type>::isIntegral isIntegral; if(isIntegral::value) image[k] = (T)randomMT19937().uniformInt(256); else image[k] = (T)randomMT19937().uniform(); } } void makeWedge( Image3D &image ) { const Size3 shape = image.shape(); const int width = shape[0]; const int height = shape[1]; const int depth = shape[2]; for( int z = 0; z < depth; ++z ) { for( int y = 0; y < height; ++y ) { for( int x = 0; x < width; ++x ) { const Image3D::value_type val = Image3D::value_type(x + y + z); image( x, y, z ) = val; } } } } void makeBox( Image3D &image ) { const int b = 8; const Size3 shape = image.shape(); const int width = shape[0]; const int height = shape[1]; const int depth = shape[2]; for( int z = 0; z < depth; ++z ) { for( int y = 0; y < height; ++y ) { for( int x = 0; x < width; ++x ) { Image3D::value_type val = 80; if( (x > b) && x < (width-b) && (y > b) && y < (height-b) && (z > b) && z < (depth-b) ) { val = 220; } image( x, y, z ) = val; } } } } // - - - - - - - - - - - - - - - - - - - - - - - - void test_1DValidity( const Image3D &src, float ksize ) { Image3D d1( src.shape() ); Image3D dn( src.shape() ); Image3D dest3( src.shape() ); for( int d = 0; d < 3; ++d ) { std::vector<vigra::Kernel1D<float> > kernels( 3 ); kernels[d].initGaussianDerivative( ksize, 1 ); separableConvolveMultiArray( srcMultiArrayRange(src), destMultiArray(dn), kernels.begin() ); convolveMultiArrayOneDimension( srcMultiArrayRange(src), destMultiArray(d1), d, kernels[d] ); shouldEqualSequence( dn.begin(), dn.end(), d1.begin() ); } for( int d = 0; d < 3; ++d ) { std::vector<vigra::Kernel1D<float> > kernels( 3 ); kernels[d].initGaussianDerivative( ksize, 1 ); separableConvolveMultiArray(src, dn, kernels.begin()); convolveMultiArrayOneDimension(src, d1, d, kernels[d] ); shouldEqualSequence( dn.begin(), dn.end(), d1.begin() ); } } // - - - - - - - - - - - - - - - - - - - - - - - - void test_1DValidityB( const Image3D &src, float ksize ) { Image3D dst1( src.shape() ); Image3D dst2( src.shape() ); const int depth = src.shape()[2]; vigra::Kernel1D<float> kernx; vigra::Kernel1D<float> kerny; kernx.initGaussian( ksize ); kerny.initGaussianDerivative( ksize, 1 ); int z; // x convolution convolveMultiArrayOneDimension( srcMultiArrayRange(src), destMultiArray(dst1), 0, kernx ); for( z = 0; z < depth; ++z ) { BasicImageView<Image3D::value_type> sslice = makeBasicImageView( src.bindOuter(z) ); BasicImageView<Image3D::value_type> dslice = makeBasicImageView( dst2.bindOuter(z) ); vigra::separableConvolveX( srcImageRange(sslice), destImage(dslice), vigra::kernel1d(kernx) ); } shouldEqualSequence( dst1.begin(), dst1.end(), dst2.begin() ); // y convolution convolveMultiArrayOneDimension( srcMultiArrayRange(src), destMultiArray(dst1), 1, kerny ); for( z = 0; z < depth; ++z ) { BasicImageView<Image3D::value_type> sslice = makeBasicImageView( src.bindOuter(z) ); BasicImageView<Image3D::value_type> dslice = makeBasicImageView( dst2.bindOuter(z) ); vigra::separableConvolveY( srcImageRange(sslice), destImage(dslice), vigra::kernel1d(kerny) ); } shouldEqualSequence( dst1.begin(), dst1.end(), dst2.begin() ); } void test_2DValidity( const Image3D &src, float ksize ) { Image3D d2( src.shape() ); Image3D dn( src.shape() ); int depth = src.shape()[2]; std::vector<vigra::Kernel1D<float> > kernels( 3 ); kernels[0].initGaussian( ksize ); kernels[1].initGaussianDerivative( ksize, 1 ); for( int z = 0; z < depth; ++z ) { BasicImageView<Image3D::value_type> sslice = makeBasicImageView( src.bindOuter(z) ); BasicImageView<Image3D::value_type> dslice = makeBasicImageView( d2.bindOuter(z) ); vigra::convolveImage( srcImageRange(sslice), destImage(dslice), kernels[0], kernels[1] ); } separableConvolveMultiArray( srcMultiArrayRange(src), destMultiArray(dn), kernels.begin() ); shouldEqualSequence( dn.begin(), dn.end(), d2.begin() ); } // - - - - - - - - - - - - - - - - - - - - - - - - void test_inplacenessN( const Image3D &src, float ksize ) { Image3D da( src.shape() ); Image3D db( src.shape() ); std::vector<vigra::Kernel1D<float> > kernels( 3 ); kernels[0].initGaussian( ksize ); kernels[1].initGaussianDerivative( ksize, 1 ); vigra::separableConvolveMultiArray( srcMultiArrayRange(src), destMultiArray(da), kernels.begin() ); copyMultiArray(srcMultiArrayRange(src), destMultiArray(db)); vigra::separableConvolveMultiArray( srcMultiArrayRange(db), destMultiArray(db), kernels.begin() ); shouldEqualSequenceTolerance( da.begin(), da.end(), db.begin(), 1e-5 ); } // - - - - - - - - - - - - - - - - - - - - - - - - void testSmoothing() { makeRandom(srcImage); ArrayVector<Kernel1D<double> > kernels(3); kernels[0].initGaussian(1.0); kernels[1].initAveraging(1); kernels[2].initGaussian(2.0); //kernels[1].setBorderTreatment(BORDER_TREATMENT_REFLECT); Image3D res(shape); separableConvolveMultiArray(srcMultiArrayRange(srcImage), destMultiArray(res), kernels.begin()); typedef Shape3 S; int w = shape[0], h = shape[1], d = shape[2]; S start[] = { S(0, 0, 25), S(30, 0, 0), S(0, 30, 0), S(2, h-1, 20), S(15, 1, d-2), S(2, 14, 1), S(0,0,0), S(0, 0, 34), S(0, 12, 0) }; S stop[] = { S(w, h, 26), S(31, h, d), S(w, 31, d), S(w-2, h, 30), S(28, h-1, d), S(w-2, 44, d-1), S(w,h,d), S(w, 1, 39), S(w-1, 26, 1) }; for(int k=0; k<9; ++k) { Image3D subarray(stop[k]-start[k]); separableConvolveMultiArray(srcImage, subarray, kernels.begin(), start[k], stop[k]); shouldEqualSequenceTolerance(subarray.begin(), subarray.end(), res.subarray(start[k], stop[k]).begin(), 1e-6); } } void test_inplaceness1( const Image3D &src, float ksize, bool useDerivative ) { Image3D da( src.shape() ); Image3D db( src.shape() ); Kernel1D<float> kernel; if( ! useDerivative ) kernel.initGaussian( ksize ); else kernel.initGaussianDerivative( ksize, 1 ); for( int i = 0; i < 3; ++i ) { const int d = 2-i; convolveMultiArrayOneDimension(src, da, d, kernel ); copyMultiArray(src, db); convolveMultiArrayOneDimension(db, db, d, kernel ); shouldEqualSequence( da.begin(), da.end(), db.begin() ); } } // - - - - - - - - - - - - - - - - - - - - - - - - void test_gradient1( const Image3D &base, bool useGaussian ) { const double sigma = kernelSize/2; const int b = useGaussian ? int( 0.5 + 3*sigma ) : 1; Image3D src( base.shape() ); Image3x3 grad( src.shape() ); makeWedge( src ); if( ! useGaussian ) symmetricGradientMultiArray(src, grad); else gaussianGradientMultiArray(src, grad, sigma ); Image3x3::value_type v; v[0] = 1; v[1] = 1; v[2] = 1; const float v2 = dot(v,v); const Size3 shape = src.shape(); const int width = shape[0]; const int height = shape[1]; const int depth = shape[2]; for( int z = b; z < depth-b; ++z ) { for( int y = b; y < height-b; ++y ) { for( int x = b; x < width-b; ++x ) { shouldEqualTolerance( dot(grad(x,y,z), v), v2, 1e-5 ); } } } } void test_gradient_magnitude() { using namespace functor; MultiArrayShape<2>::type shape(30,40); int size = shape[0]*shape[1]; MultiArray<2, double > src(shape), mgrad(shape), rmgrad(shape); MultiArray<2, TinyVector<double, 2> > grad(shape); makeRandom(src); gaussianGradientMagnitude(src, rmgrad, 1.0); gaussianGradientMultiArray(src, grad, 1.0 ); transformMultiArray(grad, mgrad, norm(Arg1())); shouldEqualSequence(mgrad.data(), mgrad.data()+size, rmgrad.data()); rmgrad.init(0); gaussianGradientMagnitude(src, rmgrad, 1.0); shouldEqualSequence(mgrad.data(), mgrad.data()+size, rmgrad.data()); MultiArray<2, TinyVector<double, 3> > rgb(shape); MultiArrayView<3, Multiband<double> > expanded(rgb.expandElements(2)); makeRandom(expanded); mgrad.init(0); gaussianGradientMagnitude(srcImageRange(rgb), destImage(mgrad), 1.0); rmgrad.init(0); gaussianGradientMagnitude(rgb, rmgrad, 1.0); shouldEqualSequenceTolerance(mgrad.data(), mgrad.data()+size, rmgrad.data(), 1e-14); rmgrad.init(0); gaussianGradientMagnitude<2>(expanded, rmgrad, 1.0); shouldEqualSequenceTolerance(mgrad.data(), mgrad.data()+size, rmgrad.data(), 1e-14); MultiArray<3, Multiband<double> > spectral(Shape3(shape[0], shape[1], 10)); MultiArrayView<3, Multiband<double> > spectral_expanded(spectral); gaussianGradientMagnitude<2>(spectral_expanded, rmgrad, 1.0); } void test_laplacian() { MultiArrayShape<2>::type shape(30,40); int size = shape[0]*shape[1]; MultiArray<2, double > src(shape), laplacian(shape); MultiArray<2, double> rlaplacian(shape[0], shape[1]); makeRandom(src); laplacianOfGaussian(srcImageRange(src), destImage(rlaplacian), 2.0); laplacianOfGaussianMultiArray(srcMultiArrayRange(src), destMultiArray(laplacian), 2.0 ); shouldEqualSequenceTolerance(laplacian.data(), laplacian.data()+size, rlaplacian.data(), 1e-12); laplacian = 0; laplacianOfGaussianMultiArray(src, laplacian, 2.0 ); shouldEqualSequenceTolerance(laplacian.data(), laplacian.data()+size, rlaplacian.data(), 1e-12); } void test_divergence() { // test divergence of gradient - theoretically, it equals the Laplacian, but in practice this requires // large kernel windows, a high tolerance, and doesn't hold near the border MultiArray<2, double> src; importImage("oi_single.gif", src); MultiArray<2, double> laplacian(src.shape()), divergence(src.shape()); MultiArray<2, TinyVector<double, 2> > grad(src.shape()); laplacianOfGaussianMultiArray(src, laplacian, 2.0, ConvolutionOptions<2>().filterWindowSize(5)); gaussianGradientMultiArray(src, grad, sqrt(2.0), ConvolutionOptions<2>().filterWindowSize(5)); gaussianDivergenceMultiArray(grad, divergence, sqrt(2.0), ConvolutionOptions<2>().filterWindowSize(5)); divergence -= laplacian; MultiArrayView <2, double> center(divergence.subarray(Shape2(10,10), Shape2(-10,-10))); using namespace multi_math; should(all(abs(center) < 0.001)); } void test_hessian() { MultiArrayShape<2>::type shape(30,40); int size = shape[0]*shape[1]; MultiArray<2, double > src(shape); MultiArray<2, TinyVector<double, 3> > hessian(shape), hessian1(shape); BasicImage<TinyVector<double, 3> > rhessian(shape[0], shape[1]); makeRandom(src); typedef VectorComponentAccessor<TinyVector<double, 3> > BandAccessor; hessianMatrixOfGaussian(srcImageRange(src), destImage(rhessian, BandAccessor(0)), destImage(rhessian, BandAccessor(1)), destImage(rhessian, BandAccessor(2)), 2.0); hessianOfGaussianMultiArray(srcMultiArrayRange(src), destMultiArray(hessian), 2.0 ); TinyVector<double, 3> epsilon(1e-12, 1e-12, 1e-12); shouldEqualSequenceTolerance(hessian.data(), hessian.data()+size, rhessian.data(), epsilon); hessianOfGaussianMultiArray(src, hessian1, 2.0 ); shouldEqualSequenceTolerance(hessian1.data(), hessian1.data()+size, rhessian.data(), epsilon); } void test_structureTensor() { MultiArrayShape<2>::type shape(30,40); int size = shape[0]*shape[1]; MultiArray<2, double > src(shape); MultiArray<2, TinyVector<double, 3> > st(shape), st1(shape); BasicImage<TinyVector<double, 3> > rst(shape[0], shape[1]); makeRandom(src); typedef VectorComponentAccessor<TinyVector<double, 3> > BandAccessor; structureTensor(srcImageRange(src), destImage(rst, BandAccessor(0)), destImage(rst, BandAccessor(1)), destImage(rst, BandAccessor(2)), 1.5, 3.0); structureTensorMultiArray(srcMultiArrayRange(src), destMultiArray(st), 1.5, 3.0 ); TinyVector<double, 3> epsilon(1e-12, 1e-12, 1e-12); shouldEqualSequenceTolerance(st.data(), st.data()+size, rst.data(), epsilon); structureTensorMultiArray(src, st1, 1.5, 3.0 ); shouldEqualSequenceTolerance(st1.data(), st1.data()+size, rst.data(), epsilon); } //-------------------------------------------- const Size3 shape; Image3D srcImage; const float kernelSize; MultiArraySeparableConvolutionTest() : shape( 60, 70, 50 ), srcImage( shape ), kernelSize( 1.8f ) { makeBox( srcImage ); } void test_Valid1() { test_1DValidity( srcImage, kernelSize ); } void test_Valid3() { test_1DValidityB( srcImage, kernelSize ); } void test_Valid2() { test_2DValidity( srcImage, kernelSize ); } void test_InplaceN() { test_inplacenessN( srcImage, kernelSize ); } void test_Inplace1() { test_inplaceness1( srcImage, kernelSize, false ); test_inplaceness1( srcImage, kernelSize, true ); } void test_gradient1() { test_gradient1( srcImage, false ); test_gradient1( srcImage, true ); } }; //-- struct MultiArraySeparableConvolutionTest //-------------------------------------------------------- struct MultiArraySeparableConvolutionTestSuite : public vigra::test_suite { MultiArraySeparableConvolutionTestSuite() : vigra::test_suite("MultiArraySeparableConvolutionTestSuite") { add( testCase( &MultiArraySeparableConvolutionTest::test_Valid1 ) ); add( testCase( &MultiArraySeparableConvolutionTest::test_Valid2 ) ); add( testCase( &MultiArraySeparableConvolutionTest::test_Valid3 ) ); add( testCase( &MultiArraySeparableConvolutionTest::test_InplaceN ) ); add( testCase( &MultiArraySeparableConvolutionTest::test_Inplace1 ) ); add( testCase( &MultiArraySeparableConvolutionTest::testSmoothing ) ); add( testCase( &MultiArraySeparableConvolutionTest::test_gradient1 ) ); add( testCase( &MultiArraySeparableConvolutionTest::test_laplacian ) ); add( testCase( &MultiArraySeparableConvolutionTest::test_divergence ) ); add( testCase( &MultiArraySeparableConvolutionTest::test_hessian ) ); add( testCase( &MultiArraySeparableConvolutionTest::test_structureTensor ) ); add( testCase( &MultiArraySeparableConvolutionTest::test_gradient_magnitude ) ); } }; // struct MultiArraySeparableConvolutionTestSuite //-------------------------------------------------------- typedef double pixel_type; typedef vigra::MultiArrayShape<2>::type shape_2d; typedef vigra::MultiArray<2, pixel_type> array_2d; typedef vigra::MultiArray<2, vigra::TinyVector<pixel_type, 2> > grad_2d; typedef vigra::MultiArray<2, vigra::TinyVector<pixel_type, 3> > symm_2d; typedef vigra::BasicImageView<pixel_type> image_2d; typedef vigra::ConvolutionOptions<2> options_2d; struct delta_dist { double scale; double offset; delta_dist(double s, double of = 0) : scale(std::abs(s)), offset(of) {} template<class V> double operator()(V a, V b) const { double delta = std::abs(double(a) - double(b)); if (offset == 0) return delta; else return offset - delta; } }; struct rel_dist { double scale; double offset; rel_dist(double s, double of = 0) : scale(std::abs(s)), offset(of) {} template<class V> double operator()(V a, V b) const { double delta = std::abs((double(a) - double(b)) / double(a)); if (offset == 0) return delta; else return offset - delta; } }; struct logger { const bool do_log; std::ostringstream os; logger(bool d = true) : do_log(d) {} operator bool() { return do_log; } void next() { if(os.str().size()) os << ", "; } void operator()(const std::string & msg) { next(); os << msg; } template<class X> void operator()(const std::string & name, const X & value) { next(); os << name << " = " << value; } std::string str() { return os.str(); } }; template<class IM> double min_max_delta(const IM & image) { vigra::FindMinMax<double> minmax; vigra::inspectMultiArray(image, minmax); return minmax.max - minmax.min; } template<class IM> double max(const IM & image) { vigra::FindMinMax<double> minmax; vigra::inspectMultiArray(image, minmax); return minmax.max; } template<class IM> double min(const IM & image) { vigra::FindMinMax<double> minmax; vigra::inspectMultiArray(image, minmax); return minmax.min; } template<class IM> void write_out(const IM & image, const char *const name, bool do_it = true) { if (do_it) { vigra::exportImage(srcImageRange(image), vigra::ImageExportInfo(name)); } } template<class F> double compare(F func, const char *const func_name, const array_2d & image_a, const array_2d & image_b, double sigma_pix = 0, const char* name = 0, bool do_it = true) { array_2d delta_image(image_a); vigra::combineTwoMultiArrays(srcMultiArrayRange(image_a), srcMultiArray(image_b), destMultiArray(delta_image), func); // crop off border artifacts image_2d image_view_delta = vigra::makeBasicImageView(delta_image); // accounting for x step size by using "pixel" counts ... int crop = 1 + int(3 * sigma_pix + 0.5); int wcrop = image_view_delta.width() - 2 * crop; shouldMsg(wcrop > 1, ("no width left after std. dev. crop at" " borders, width = " + asString(wcrop)).c_str()); array_2d delta_cropped(shape_2d(wcrop, image_view_delta.height())); copyImage(srcIterRange( image_view_delta.upperLeft() + vigra::Diff2D(crop, 0), image_view_delta.lowerRight() - vigra::Diff2D(crop, 0)), destImage(delta_cropped)); if (!name) name = func_name; write_out(delta_cropped, name, do_it); return max(delta_cropped); } void resize_0(const array_2d & a, array_2d & b) { vigra::resizeImageNoInterpolation(srcImageRange(a), destImageRange(b)); } template<unsigned order> void resize_n(const array_2d & a, array_2d & b) { typedef typename vigra::BSpline<order, double> my_spline; if(order <=3) // arbitrarily use the different APIs for small and large orders vigra::resizeMultiArraySplineInterpolation(srcMultiArrayRange(a), destMultiArrayRange(b), my_spline()); else vigra::resizeMultiArraySplineInterpolation(a, b, my_spline()); } struct t_func { static const double zeros[2]; // = { 0, 0 }; virtual double operator()(array_2d & image, const options_2d & opt) const = 0; virtual double operator()(array_2d & image, const double sigma_d[2], const double step_size[2]) const { // test various ways to create option setter functions. options_2d opt; opt.resolutionStdDev(sigma_d).stepSize(step_size); std::vector<double> vstep; vstep.push_back(step_size[0]); vstep.push_back(step_size[1]); opt.resolutionStdDev(sigma_d).stepSize((const double *const)step_size); opt.resolutionStdDev(sigma_d).stepSize(vstep); return operator()(image, opt); } virtual double operator()(array_2d & test_image, double im_scale) const { double w[2] = { 1.0 / im_scale, 1 }; return operator()(test_image, zeros, w); } virtual double operator()(array_2d & image) const { return operator()(image, 1); } virtual std::string name() const = 0; virtual void log(logger & log_write) const { log_write("test operator", name()); } virtual ~t_func() {} }; const double t_func::zeros[2] = { 0, 0 }; struct gsmaa_f : public t_func { double sigma; gsmaa_f(double s) : sigma(s) {} std::string name() const { return "gaussianSmoothMultiArray"; } double operator()(array_2d & test_image, const options_2d & opt) const { vigra::gaussianSmoothMultiArray(vigra::srcMultiArrayRange(test_image), vigra::destMultiArray(test_image), sigma, opt); return sigma; } }; struct ggma_f : public t_func { double sigma; int axis; ggma_f(double s, int a) : sigma(s), axis(a) {} std::string name() const { return "gaussianGradientMultiArray, axis " + asString(axis); } double operator()(array_2d & test_image, const options_2d & opt) const { grad_2d grad_data(test_image.shape()); vigra::gaussianGradientMultiArray(vigra::srcMultiArrayRange(test_image), vigra::destMultiArray(grad_data), sigma, opt); // copy gradient #axis to image: typedef grad_2d::value_type value_type; typedef vigra::VectorComponentAccessor<value_type> accessor; vigra::copyMultiArray(vigra::srcMultiArrayRange(grad_data, accessor(axis)), vigra::destMultiArray(test_image)); return sigma; } }; struct sgma_f : public t_func { int axis; sgma_f(int a) : axis(a) {} std::string name() const { return "symmetricGradientMultiArray, axis " + asString(axis); } double operator()(array_2d & test_image, const options_2d & opt) const { grad_2d grad_data(test_image.shape()); vigra::symmetricGradientMultiArray( vigra::srcMultiArrayRange(test_image), vigra::destMultiArray(grad_data), opt); // copy gradient #axis to image: typedef grad_2d::value_type value_type; typedef vigra::VectorComponentAccessor<value_type> accessor; vigra::copyMultiArray(vigra::srcMultiArrayRange(grad_data, accessor(axis)), vigra::destMultiArray(test_image)); return 0; } }; struct lgma_f : public t_func { double sigma; lgma_f(double s) : sigma(s) {} std::string name() const { return "laplacianOfGaussianMultiArray"; } double operator()(array_2d & test_image, const options_2d & opt) const { array_2d dest_image(test_image); vigra::laplacianOfGaussianMultiArray( vigra::srcMultiArrayRange(test_image), vigra::destMultiArray(dest_image), sigma, opt); // copy result to image: vigra::copyMultiArray(vigra::srcMultiArrayRange(dest_image), vigra::destMultiArray(test_image)); return sigma; } }; struct hgma_f : public t_func { double sigma; int entry; hgma_f(double s, int e) : sigma(s), entry(e) {} std::string name() const { return "hessianOfGaussianMultiArray, entry " + asString(entry); } double operator()(array_2d & test_image, const options_2d & opt) const { symm_2d hess_data(test_image.shape()); vigra::hessianOfGaussianMultiArray( vigra::srcMultiArrayRange(test_image), vigra::destMultiArray(hess_data), sigma, opt); // copy hessian entry to image: typedef symm_2d::value_type value_type; typedef vigra::VectorComponentAccessor<value_type> accessor; vigra::copyMultiArray(vigra::srcMultiArrayRange(hess_data, accessor(entry)), vigra::destMultiArray(test_image)); return sigma; } }; struct stma_f : public t_func { double inner; double outer; int entry; stma_f(double in, double out, int e) : inner(in), outer(out), entry(e) {} std::string name() const { return "structureTensorMultiArray, entry " + asString(entry); } double operator()(array_2d & test_image, const options_2d & opt) const { symm_2d st_data(test_image.shape()); vigra::structureTensorMultiArray(vigra::srcMultiArrayRange(test_image), vigra::destMultiArray(st_data), inner, outer, opt); // copy st entry to image: typedef symm_2d::value_type value_type; typedef vigra::VectorComponentAccessor<value_type> accessor; vigra::copyMultiArray(vigra::srcMultiArrayRange(st_data, accessor(entry)), vigra::destMultiArray(test_image)); return std::sqrt(inner * inner + outer * outer); } }; const t_func * new_test_alloc(double sigma, double outer, int test_nr) { switch (test_nr) { case 0: return new gsmaa_f(sigma); case 1: return new ggma_f(sigma, 0); case 2: return new ggma_f(sigma, 1); case 11: return new sgma_f(0); case 12: return new sgma_f(1); case 20: return new lgma_f(sigma); case 21: return new hgma_f(sigma, 0); case 22: return new hgma_f(sigma, 1); case 23: return new hgma_f(sigma, 2); case 31: return new stma_f(sigma, outer, 0); case 32: return new stma_f(sigma, outer, 1); case 33: return new stma_f(sigma, outer, 2); } return 0; } const t_func * new_test(double sigma, double outer, int test_nr, logger & log_name) { const t_func *const test = new_test_alloc(sigma, outer, test_nr); if (test) test->log(log_name); else log_name("[no test operator found in new_test_alloc()]"); return test; } struct cmp_double { double tol; cmp_double(double t) : tol(t) {} void check(double val) const { shouldMsg(!tol || (std::abs(val) <= tol), ("relative difference above tolerance: " "accepted = " + asString(tol) + ", actual = " + asString(val)).c_str()); } }; struct cmp_data { bool write_im; cmp_double global_tol; cmp_double local_tol; cmp_data(bool w, double glob, double loc) : write_im(w), global_tol(glob), local_tol(loc) {} operator bool() const { return write_im; } }; void test_compare(const array_2d & x1_image_b, const array_2d & res_image, double sigma_pix, const cmp_data & cmp, logger & log_write) { double mm_delta = min_max_delta(x1_image_b); double dist = compare(delta_dist(1), "delta_dist", res_image, x1_image_b, sigma_pix, "delta_dist_im.png", cmp); double rel = compare(rel_dist(1), "rel_dist", res_image, x1_image_b, sigma_pix, "rel_dist_im.png", cmp); log_write("globally relative error", dist / mm_delta); log_write("locally relative error", rel); cmp.global_tol.check(dist / mm_delta); cmp.local_tol.check(rel); } unsigned resized(double scale, int size) { return static_cast<unsigned>(std::floor(1 + scale * (size - 1))); } shape_2d resized_shape(const vigra::ImageImportInfo & size_info, double scale_x, double scale_y) { return shape_2d(resized(scale_x, size_info.width()), resized(scale_y, size_info.height())); } void test_upscaled(void (*resize)(const array_2d &, array_2d &), const vigra::ImageImportInfo & size_info, const array_2d & test_image, const t_func & test_f, double im_scale, const cmp_data & cmp, logger & log_write, logger & log_name) { log_name("upscaled test"); if (log_name) return; // image inflated by im_scale in x direction: array_2d x_scaled_image(resized_shape(size_info, im_scale, 1)); (*resize)(test_image, x_scaled_image); write_out(x_scaled_image, "test_any_scaled.png", cmp); double sigma = test_f(x_scaled_image, im_scale); write_out(x_scaled_image, "test_any_scaled_new_f.png", cmp); array_2d x1_image_b(test_image); test_f(x1_image_b); write_out(x1_image_b, "test_any_old_f.png", cmp); // compare with resampled image array_2d res_image(test_image); (*resize)(x_scaled_image, res_image); write_out(res_image, "test_any_res_f.png", cmp); test_compare(x1_image_b, res_image, sigma, cmp, log_write); } void test_downscaled(void (*resize)(const array_2d &, array_2d &), const vigra::ImageImportInfo & size_info, const array_2d & m2_image_old, const t_func & test_f, double im_scale, const cmp_data & cmp, logger & log_write, logger & log_name) { const double y_scale = 3; const double x_scale = im_scale * y_scale; log_name("downscaled test (factor " + asString(y_scale) + ")"); if (log_name) return; int w = (int(size_info.width() - 1) / int(x_scale)) * int(x_scale) + 1; int h = (int(size_info.height() - 1) / int(y_scale)) * int(y_scale) + 1; array_2d test_image(shape_2d(w, h)); (*resize)(m2_image_old, test_image); // pre-sample image with gaussian, std. dev. == scale: const double std_dev_factor = 1; array_2d pre_scale_image(test_image); double sigmas[2] = { 0, 0 }; sigmas[0] = std_dev_factor * x_scale; sigmas[1] = std_dev_factor * y_scale; vigra::gaussianSmoothMultiArray(test_image, pre_scale_image, options_2d().stdDev(sigmas)); // downscale: array_2d downscaled_image(resized_shape(size_info, 1 / x_scale, 1 / y_scale)); (*resize)(pre_scale_image, downscaled_image); write_out(downscaled_image, "test_downscaled.png", cmp); const double step_size[2] = { x_scale, y_scale }; double sigma = test_f(downscaled_image, sigmas, step_size); write_out(downscaled_image, "test_downscaled_new_f.png", cmp); array_2d x1_image_b(test_image); test_f(x1_image_b); write_out(x1_image_b, "test_any_old_f.png", cmp); // compare with resampled image array_2d res_image_b(downscaled_image); (*resize)(x1_image_b, res_image_b); write_out(res_image_b, "test_any_res_b_f.png", cmp); test_compare(res_image_b, downscaled_image, sigma / x_scale, cmp, log_write); } void test_any(void (*resize)(const array_2d &, array_2d &), const vigra::ImageImportInfo & size_info, const array_2d & test_image, const t_func & test_f, double im_scale, const cmp_data & cmp, logger & log_write, logger & log_name, int test_type) { if (test_type == 0) { test_upscaled(resize, size_info, test_image, test_f, im_scale, cmp, log_write, log_name); } else if (test_type == 1) { test_downscaled(resize, size_info, test_image, test_f, im_scale, cmp, log_write, log_name); } } typedef const double test_data[9]; struct args { const int argc; test_data & argv; int pos; args(int a_c, test_data & a_v) : argc(a_c), argv(a_v), pos(-1) {} template<class X> X operator()(X default_value) { ++pos; return static_cast<X>( (argc > pos) ? argv[pos] : static_cast<double>(default_value)); } }; std::string perform_test(int argc, test_data & argv, const vigra::ImageImportInfo & import_info, const array_2d & test_image, bool run_test = true) { logger log_name(!run_test); logger log_write; args cmd_line(argc, argv); const double sigma = cmd_line(2.0); const double im_scale = cmd_line(3.0); const int intp_type = cmd_line(0); const bool write_im = cmd_line(1) == 1; const int test_nr = cmd_line(0); const double outer = cmd_line(sigma); const int test_type = cmd_line(0); const double global_tol = cmd_line(0.0); const double local_tol = cmd_line(0.0); const cmp_data cmp(write_im, global_tol, local_tol); const t_func *const test = new_test(sigma, outer, test_nr, log_name); if (! test) { shouldMsg(!run_test, ("unknown test number " + asString(test_nr) + " for new_test_alloc()").c_str()); return "(unknown test number)"; } log_name("sigma", sigma); log_name("image scaling factor", im_scale); log_name("outer sigma", outer); log_name("global_tol", global_tol); log_name("local_tol", local_tol); if (intp_type == 0) { log_name("resizing without interpolation"); test_any(&resize_0, import_info, test_image, *test, im_scale, cmp, log_write, log_name, test_type); } else if (intp_type == 3) { log_name("resizing with spline3"); test_any(&resize_n<3>, import_info, test_image, *test, im_scale, cmp, log_write, log_name, test_type); } else if (intp_type == 5) { log_name("resizing with spline5"); test_any(&resize_n<5>, import_info, test_image, *test, im_scale, cmp, log_write, log_name, test_type); } if (log_name) return log_name.str(); else return log_name.str() + ":\n" + log_write.str(); } struct scaled_test : public vigra::detail::test_functor<scaled_test> { static const int argc; test_data & argv; const vigra::ImageImportInfo & import_info; const array_2d & test_image; scaled_test(test_data & a, const vigra::ImageImportInfo & ii, const array_2d & t) : argv(a), import_info(ii), test_image(t) {} void operator()() { // std::cout << perform_test(argc, argv, import_info, test_image) // << "\n"; perform_test(argc, argv, import_info, test_image); } std::string str() { return "MultiArraySeparableConvolutionScaledTestSuite [" + perform_test(argc, argv, import_info, test_image, false) + "]"; } }; const int scaled_test::argc = sizeof(test_data) / sizeof(double); test_data tests[] = { /* sigma write_im test_type */ /* im_scale test_nr global_tol */ /* intp_type outer local_tol */ { 2, 3, 5, 0, 0, 0, 0, 0, 0.007 }, { 1, 3, 0, 0, 1, 0, 0, 0.023, 0 }, { 1, 3, 0, 0, 2, 0, 0, 0.011, 0 }, { 4.5, 3, 0, 0, 1, 0, 0, 0.004, 0 }, { 4.5, 3, 0, 0, 2, 0, 0, 0.002, 0 }, { 5, 0.99, 5, 0, 11, 0, 0, 0.065, 0 }, { 5, 0.99, 5, 0, 12, 0, 0, 0.135, 0 }, { 3, 3, 0, 0, 20, 0, 0, 0.014, 0 }, { 3, 3, 0, 0, 21, 0, 0, 0.019, 0 }, { 3, 3, 0, 0, 22, 0, 0, 0.005, 0 }, { 3, 3, 0, 0, 23, 0, 0, 0.001, 0 }, { 4, 3, 0, 0, 31, 2, 0, 0.012, 0 }, { 4, 3, 0, 0, 32, 2, 0, 0.004, 0 }, { 4, 3, 0, 0, 33, 2, 0, 0.001, 0 }, { 15, 3, 0, 0, 0, 0, 1, 0, 0.012 }, { 15, 3, 5, 0, 0, 0, 1, 0, 0.012 }, { 15, 2, 5, 0, 1, 0, 1, 0.005, 0 }, { 15, 2, 5, 0, 2, 0, 1, 0.003, 0 }, { 15, 2, 0, 0, 20, 0, 1, 0.028, 0 }, { 15, 3, 0, 0, 21, 0, 1, 0.045, 0 }, { 15, 3, 0, 0, 22, 0, 1, 0.023, 0 }, { 15, 3, 0, 0, 23, 0, 1, 0.024, 0 }, { 15, 3, 0, 0, 31, 1.1, 1, 0.025, 0 }, { 15, 3, 0, 0, 32, 1.1, 1, 0.035, 0 }, { 15, 3, 0, 0, 33, 1.1, 1, 0.006, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0 } }; //-------------------------------------------------------- struct MultiArraySeparableConvolutionScaledTestSuite : public vigra::test_suite { vigra::ImageImportInfo import_info; array_2d test_image; MultiArraySeparableConvolutionScaledTestSuite() : vigra::test_suite("MultiArraySeparableConvolutionScaledTestSuite"), import_info("oi_single.gif"), test_image(shape_2d(import_info.width(), import_info.height())) { vigra::importImage(import_info, destImage(test_image)); for (test_data* p = tests; (*p)[0]; ++p) { scaled_test* test = new scaled_test(*p, import_info, test_image); add(vigra::create_test_case(*test, test->str().c_str())); } } }; // struct MultiArraySeparableConvolutionScaledTestSuite //-------------------------------------------------------- int main(int argc, char ** argv) { // run the multi-array separable convolution test suite MultiArraySeparableConvolutionTestSuite test1; int failed = test1.run(vigra::testsToBeExecuted(argc, argv)); std::cout << test1.report() << std::endl; // run the multi-array separable scaled-convolution test suite MultiArraySeparableConvolutionScaledTestSuite test2; failed += test2.run(vigra::testsToBeExecuted(argc, argv)); std::cout << test2.report() << std::endl; return (failed != 0); }
34.468798
113
0.544379
[ "shape", "vector" ]
9c37a6fecb4de0947066c8ab09a7cf83465a1f88
14,978
cpp
C++
hphp/runtime/ext/icu/ext_icu_timezone.cpp
atdt/hhvm
63fe59e67d0129090ccb4c096e66dcfc92031f94
[ "PHP-3.01", "Zend-2.0" ]
1
2015-02-12T07:24:28.000Z
2015-02-12T07:24:28.000Z
hphp/runtime/ext/icu/ext_icu_timezone.cpp
atdt/hhvm
63fe59e67d0129090ccb4c096e66dcfc92031f94
[ "PHP-3.01", "Zend-2.0" ]
null
null
null
hphp/runtime/ext/icu/ext_icu_timezone.cpp
atdt/hhvm
63fe59e67d0129090ccb4c096e66dcfc92031f94
[ "PHP-3.01", "Zend-2.0" ]
1
2015-06-16T05:47:12.000Z
2015-06-16T05:47:12.000Z
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-2014 Facebook, Inc. (http://www.facebook.com) | | Copyright (c) 1997-2010 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include "hphp/runtime/ext/icu/ext_icu_timezone.h" #include "hphp/runtime/ext/icu/ext_icu_iterator.h" #include "hphp/runtime/ext/datetime/ext_datetime.h" #include <unicode/locid.h> namespace HPHP { namespace Intl { ///////////////////////////////////////////////////////////////////////////// const StaticString s_IntlTimeZone("IntlTimeZone"); Class* IntlTimeZone::c_IntlTimeZone = nullptr; static bool ustring_from_char(icu::UnicodeString& ret, const String& str, UErrorCode &error) { error = U_ZERO_ERROR; ret = u16(str, error, U_SENTINEL); if (U_FAILURE(error)) { ret.setToBogus(); return false; } return true; } icu::TimeZone* IntlTimeZone::ParseArg(const Variant& arg, const String& funcname, IntlError* err) { String tzstr; if (arg.isNull()) { tzstr = f_date_default_timezone_get(); } else if (arg.isObject()) { auto objarg = arg.toObject(); auto cls = objarg->getVMClass(); auto IntlTimeZone_Class = Unit::lookupClass(s_IntlTimeZone.get()); if (IntlTimeZone_Class && ((cls == IntlTimeZone_Class) || cls->classof(IntlTimeZone_Class))) { return IntlTimeZone::Get(objarg.get())->timezone()->clone(); } if (objarg.instanceof(DateTimeZoneData::getClass())) { auto* dtz = Native::data<DateTimeZoneData>(objarg.get()); tzstr = dtz->getName(); } else { tzstr = arg.toString(); } } else { tzstr = arg.toString(); } UErrorCode error = U_ZERO_ERROR; icu::UnicodeString id; if (!ustring_from_char(id, tzstr, error)) { err->setError(error, "%s: Time zone identifier given is not a " "valid UTF-8 string", funcname.c_str()); return nullptr; } auto ret = icu::TimeZone::createTimeZone(id); if (!ret) { err->setError(U_MEMORY_ALLOCATION_ERROR, "%s: could not create time zone", funcname.c_str()); return nullptr; } icu::UnicodeString gottenId; if (ret->getID(gottenId) != id) { err->setError(U_ILLEGAL_ARGUMENT_ERROR, "%s: no such time zone: '%s'", funcname.c_str(), arg.toString().c_str()); delete ret; return nullptr; } return ret; } #define TZ_GET(dest, src, def) \ auto dest = IntlTimeZone::Get(src); \ if (!dest) { \ return def; \ } #define TZ_CHECK(ov, ec, fail) \ if (U_FAILURE(ec)) { \ ov->setError(ec); \ return fail; \ } ////////////////////////////////////////////////////////////////////////////// // class IntlTimeZone static Variant HHVM_STATIC_METHOD(IntlTimeZone, countEquivalentIDs, const String& zoneId) { UErrorCode error = U_ZERO_ERROR; icu::UnicodeString id; if (!ustring_from_char(id, zoneId, error)) { s_intl_error->setError(error, "intltz_count_equivalent_ids: could not " "convert time zone id to UTF-16"); return false; } return icu::TimeZone::countEquivalentIDs(id); } static Object HHVM_STATIC_METHOD(IntlTimeZone, createDefault) { return IntlTimeZone::newInstance(icu::TimeZone::createDefault()); } static Variant HHVM_STATIC_METHOD(IntlTimeZone, createEnumeration, const Variant& countryRawOffset) { icu::StringEnumeration *se = nullptr; if (countryRawOffset.isNull()) { se = icu::TimeZone::createEnumeration(); } else if (countryRawOffset.isNumeric(true)) { se = icu::TimeZone::createEnumeration((int32_t)countryRawOffset.toInt64()); } else if (countryRawOffset.isString() || countryRawOffset.isObject()) { se = icu::TimeZone::createEnumeration(countryRawOffset.toString().c_str()); } else { s_intl_error->setError(U_ILLEGAL_ARGUMENT_ERROR, "intltz_create_enumeration: invalid argument type"); return false; } return IntlIterator::newInstance(se); } static Object HHVM_STATIC_METHOD(IntlTimeZone, createTimeZone, const String& zoneId) { UErrorCode error = U_ZERO_ERROR; icu::UnicodeString id; if (!ustring_from_char(id, zoneId, error)) { s_intl_error->setError(error, "intltz_count_equivalent_ids: could not " "convert time zone id to UTF-16"); return Object(); } return IntlTimeZone::newInstance(icu::TimeZone::createTimeZone(id)); } static Variant HHVM_STATIC_METHOD(IntlTimeZone, getCanonicalID, const String& zoneId, VRefParam isSystemID) { UErrorCode error = U_ZERO_ERROR; icu::UnicodeString id; if (!ustring_from_char(id, zoneId, error)) { s_intl_error->setError(error, "intltz_get_canonical_id: could not convert " "time zone id to UTF-16"); return false; } icu::UnicodeString result; UBool system; error = U_ZERO_ERROR; icu::TimeZone::getCanonicalID(id, result, system, error); if (U_FAILURE(error)) { s_intl_error->setError(error, "intltz_get_canonical_id: " "error obtaining canonical ID"); return false; } isSystemID = (bool)system; error = U_ZERO_ERROR; String ret(u8(result, error)); if (U_FAILURE(error)) { s_intl_error->setError(error, "intltz_get_canonical_id: could not convert " "time zone id to UTF-8"); return false; } return ret; } static Variant HHVM_METHOD(IntlTimeZone, getDisplayName, bool isDaylight, int64_t style, const String& locale) { if (!IntlTimeZone::isValidStyle(style)) { s_intl_error->setError(U_ILLEGAL_ARGUMENT_ERROR, "intltz_get_display_name: wrong display type"); return false; } TZ_GET(data, this_, false); icu::UnicodeString result; data->timezone()->getDisplayName((UBool)isDaylight, (icu::TimeZone::EDisplayType)style, icu::Locale::createFromName( localeOrDefault(locale).c_str()), result); UErrorCode error = U_ZERO_ERROR; String ret(u8(result, error)); TZ_CHECK(data, error, false); return ret; } static int64_t HHVM_METHOD(IntlTimeZone, getDSTSavings) { TZ_GET(data, this_, -1); return data->timezone()->getDSTSavings(); } static Variant HHVM_STATIC_METHOD(IntlTimeZone, getEquivalentID, const String& zoneId, int64_t index) { UErrorCode error = U_ZERO_ERROR; icu::UnicodeString id; if (!ustring_from_char(id, zoneId, error)) { s_intl_error->setError(error, "intltz_get_canonical_id: could not convert " "time zone id to UTF-16"); return false; } auto result = icu::TimeZone::getEquivalentID(id, (int32_t)index); error = U_ZERO_ERROR; String ret(u8(result, error)); if (U_FAILURE(error)) { s_intl_error->setError(error, "intltz_get_equivalent_id: " "could not convert resulting time zone id " "to UTF-16"); return false; } return ret; } static int64_t HHVM_METHOD(IntlTimeZone, getErrorCode) { TZ_GET(data, this_, 0); return data->getErrorCode(); } static String HHVM_METHOD(IntlTimeZone, getErrorMessage) { TZ_GET(data, this_, String()); return data->getErrorMessage(); } static Object HHVM_STATIC_METHOD(IntlTimeZone, getGMT) { return IntlTimeZone::newInstance( const_cast<icu::TimeZone*>(icu::TimeZone::getGMT()), false); } static Variant HHVM_METHOD(IntlTimeZone, getID) { TZ_GET(data, this_, false); icu::UnicodeString id; data->timezone()->getID(id); UErrorCode error = U_ZERO_ERROR; String ret(u8(id, error)); if (U_FAILURE(error)) { s_intl_error->setError(error, "intltz_get_id: Could not convert id to UTF-8"); return false; } return ret; } static bool HHVM_METHOD(IntlTimeZone, getOffset, double date, bool local, VRefParam rawOffset, VRefParam dstOffset) { TZ_GET(data, this_, false); UErrorCode error = U_ZERO_ERROR; int32_t rawOff, dstOff; data->timezone()->getOffset(date, (UBool)local, rawOff, dstOff, error); if (U_FAILURE(error)) { data->setError(error, "intltz_get_offset: error obtaining offset"); return false; } rawOffset = rawOff; dstOffset = dstOff; return true; } static Variant HHVM_METHOD(IntlTimeZone, getRawOffset) { TZ_GET(data, this_, false); return data->timezone()->getRawOffset(); } static Variant HHVM_STATIC_METHOD(IntlTimeZone, getTZDataVersion) { UErrorCode error = U_ZERO_ERROR; const char *tzdv = icu::TimeZone::getTZDataVersion(error); if (U_FAILURE(error)) { s_intl_error->setError(error, "intltz_get_tz_data_version: " "Error obtaining time zone data version"); return false; } return String(tzdv, CopyString); } static bool HHVM_METHOD(IntlTimeZone, hasSameRules, const Object& otherTimeZone) { TZ_GET(obj1, this_, false); TZ_GET(obj2, otherTimeZone.get(), false); return obj1->timezone()->hasSameRules(*obj2->timezone()); } static bool HHVM_METHOD(IntlTimeZone, useDaylightTime) { TZ_GET(data, this_, false); return data->timezone()->useDaylightTime(); } ////////////////////////////////////////////////////////////////////////////// // ICU >= 4.8 #if U_ICU_VERSION_MAJOR_NUM * 10 + U_ICU_VERSION_MINOR_NUM >= 48 static Variant HHVM_STATIC_METHOD(IntlTimeZone, createTimeZoneIDEnumeration, int64_t zoneType, const String& region, const Variant& offset) { if (zoneType != UCAL_ZONE_TYPE_ANY && zoneType != UCAL_ZONE_TYPE_CANONICAL && zoneType != UCAL_ZONE_TYPE_CANONICAL_LOCATION) { s_intl_error->setError(U_ILLEGAL_ARGUMENT_ERROR, "intltz_create_time_zone_id_enumeration: " "bad zone type"); return false; } int32_t *pofs = nullptr; int32_t ofs = 0; if (offset.isInitialized()) { ofs = offset.toInt64(); pofs = &ofs; } UErrorCode error = U_ZERO_ERROR; auto se = icu::TimeZone::createTimeZoneIDEnumeration( (USystemTimeZoneType)zoneType, region.c_str(), pofs, error); if (U_FAILURE(error)) { s_intl_error->setError(error, "intltz_create_time_zone_id_enumeration: " "Error obtaining time zone id enumeration"); return false; } return IntlIterator::newInstance(se); } static Variant HHVM_STATIC_METHOD(IntlTimeZone, getRegion, const String& str) { UErrorCode error = U_ZERO_ERROR; icu::UnicodeString id; if (!ustring_from_char(id, str, error)) { s_intl_error->setError(error, "intltz_get_region: could not convert " "time zone id to UTF-16"); return false; } char outbuf[3]; error = U_ZERO_ERROR; int32_t len = icu::TimeZone::getRegion(id, outbuf, sizeof(outbuf), error); if (U_FAILURE(error)) { s_intl_error->setError(error, "intltz_get_region: Error obtaining region"); return false; } return String(outbuf, len, CopyString); } #endif // ICU 4.8 ////////////////////////////////////////////////////////////////////////////// // ICU >= 4.9 #if U_ICU_VERSION_MAJOR_NUM * 10 + U_ICU_VERSION_MINOR_NUM >= 49 static Object HHVM_STATIC_METHOD(IntlTimeZone, getUnknown) { return IntlTimeZone::newInstance( const_cast<icu::TimeZone*>(&icu::TimeZone::getUnknown()), false); } #endif // ICU 4.9 ////////////////////////////////////////////////////////////////////////////// #define DISP_CONST(v) Native::registerClassConstant<KindOfInt64>( \ s_IntlTimeZone.get(), makeStaticString("DISPLAY_" #v), \ icu::TimeZone::v) #define CAL_CONST(v) Native::registerClassConstant<KindOfInt64>( \ s_IntlTimeZone.get(), makeStaticString(#v), \ UCAL_ZONE_ ## v) void IntlExtension::initTimeZone() { DISP_CONST(SHORT); DISP_CONST(LONG); #if U_ICU_VERSION_MAJOR_NUM * 10 + U_ICU_VERSION_MINOR_NUM >= 44 DISP_CONST(SHORT_GENERIC); DISP_CONST(LONG_GENERIC); DISP_CONST(SHORT_GMT); DISP_CONST(LONG_GMT); DISP_CONST(SHORT_COMMONLY_USED); DISP_CONST(GENERIC_LOCATION); #endif // ICU 4.4 HHVM_STATIC_ME(IntlTimeZone, countEquivalentIDs); HHVM_STATIC_ME(IntlTimeZone, createDefault); HHVM_STATIC_ME(IntlTimeZone, createEnumeration); HHVM_STATIC_ME(IntlTimeZone, createTimeZone); HHVM_STATIC_ME(IntlTimeZone, getCanonicalID); HHVM_ME(IntlTimeZone, getDisplayName); HHVM_ME(IntlTimeZone, getDSTSavings); HHVM_STATIC_ME(IntlTimeZone, getEquivalentID); HHVM_ME(IntlTimeZone, getErrorCode); HHVM_ME(IntlTimeZone, getErrorMessage); HHVM_STATIC_ME(IntlTimeZone, getGMT); HHVM_ME(IntlTimeZone, getID); HHVM_ME(IntlTimeZone, getOffset); HHVM_ME(IntlTimeZone, getRawOffset); HHVM_STATIC_ME(IntlTimeZone, getTZDataVersion); HHVM_ME(IntlTimeZone, hasSameRules); HHVM_ME(IntlTimeZone, useDaylightTime); #if U_ICU_VERSION_MAJOR_NUM * 10 + U_ICU_VERSION_MINOR_NUM >= 48 CAL_CONST(TYPE_ANY); CAL_CONST(TYPE_CANONICAL); CAL_CONST(TYPE_CANONICAL_LOCATION); HHVM_STATIC_ME(IntlTimeZone, createTimeZoneIDEnumeration); HHVM_STATIC_ME(IntlTimeZone, getRegion); #endif // ICU 4.8 #if U_ICU_VERSION_MAJOR_NUM * 10 + U_ICU_VERSION_MINOR_NUM >= 49 HHVM_STATIC_ME(IntlTimeZone, getUnknown); #endif // ICU 4.9 Native::registerNativeDataInfo<IntlTimeZone>(s_IntlTimeZone.get()); loadSystemlib("icu_timezone"); } ////////////////////////////////////////////////////////////////////////////// }} // namespace HPHP::Intl
34.913753
82
0.60876
[ "object" ]
9c3bd1a17e41e71c4c6e4ab9f31cf69b0d1cafa3
2,678
cpp
C++
logdevice/clients/python/tests/logdevice_test.cpp
mickvav/LogDevice
24a8b6abe4576418eceb72974083aa22d7844705
[ "BSD-3-Clause" ]
null
null
null
logdevice/clients/python/tests/logdevice_test.cpp
mickvav/LogDevice
24a8b6abe4576418eceb72974083aa22d7844705
[ "BSD-3-Clause" ]
null
null
null
logdevice/clients/python/tests/logdevice_test.cpp
mickvav/LogDevice
24a8b6abe4576418eceb72974083aa22d7844705
[ "BSD-3-Clause" ]
null
null
null
/** * Copyright (c) 2017-present, Facebook, Inc. and its affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #include "logdevice/clients/python/util/util.h" #include "logdevice/include/Client.h" #include "logdevice/test/utils/IntegrationTestUtils.h" using namespace boost::python; using namespace facebook::logdevice; using namespace facebook::logdevice::IntegrationTestUtils; namespace { void set_root_path(ClusterFactory* factory, std::string path) { factory->setRootPath(path); } void set_rocks_db_type(ClusterFactory* factory, RocksDBType rocks_db_type) { factory->setRocksDBType(rocks_db_type); } void enable_logsconfig_manager(ClusterFactory* factory) { factory->enableLogsConfigManager(); } boost::shared_ptr<Cluster> create_cluster(ClusterFactory* factory, int nodes) { auto cluster = factory->create(nodes); return boost::shared_ptr<Cluster>(cluster.release()); } boost::shared_ptr<Cluster> create_from_json(ClusterFactory* factory, std::string json) { auto cluster = factory->create( *(Configuration::fromJson(json, nullptr, nullptr, ConfigParserOptions()) .get())); return boost::shared_ptr<Cluster>(cluster.release()); } boost::shared_ptr<Client> create_client(Cluster* cluster) { auto client = cluster->createClient(); return make_boost_shared_ptr_from_std_shared_ptr(client); } list logs_config(Cluster* cluster) { object json = import("json"); return extract<list>(json.attr("loads")( cluster->getConfig()->get()->logsConfig()->toString())); } dict server_config(Cluster* cluster) { object json = import("json"); return extract<dict>(json.attr("loads")( cluster->getConfig()->get()->serverConfig()->toString())); } } // namespace BOOST_PYTHON_MODULE(test) { enum_<RocksDBType>("RocksDBType") .value("SINGLE", RocksDBType::SINGLE) .value("PARTITIONED", RocksDBType::PARTITIONED); class_<ClusterFactory>("ClusterFactory") .def("set_root_path", &set_root_path) .def("set_rocks_db_type", &set_rocks_db_type) .def("enable_logsconfig_manager", &enable_logsconfig_manager) .def("create", &create_cluster) .def("create_from_json", &create_from_json); class_<Cluster, boost::shared_ptr<Cluster>, boost::noncopyable>( "Cluster", no_init) .def("stop", &Cluster::stop) .def("create_client", &create_client) .add_property("logs_config", &logs_config) .add_property("server_config", &server_config) .add_property("config_path", &Cluster::getConfigPath); }
33.061728
79
0.714712
[ "object" ]
9c44e2e255388e80a5e38cd32784d9225d9e94e8
7,237
cpp
C++
qperm.cpp
pujyam/QNC
22fc7d6ad63bef75d2714eebfc386c23476c098c
[ "BSD-3-Clause" ]
null
null
null
qperm.cpp
pujyam/QNC
22fc7d6ad63bef75d2714eebfc386c23476c098c
[ "BSD-3-Clause" ]
null
null
null
qperm.cpp
pujyam/QNC
22fc7d6ad63bef75d2714eebfc386c23476c098c
[ "BSD-3-Clause" ]
null
null
null
/* ############################################################################## # © Copyright 2017-. Triad National Security, LLC. All rights reserved. # # This program was produced under U.S. Government contract 89233218CNA000001 for Los Alamos National Laboratory (LANL), which is operated by Triad National Security, LLC for the U.S. Department of Energy/National Nuclear Security Administration. # # All rights in the program are reserved by Triad National Security, LLC, and the U.S. Department of Energy/National Nuclear Security Administration. The Government is granted for itself and others acting on its behalf a nonexclusive, paid-up, irrevocable worldwide license in this material to reproduce, prepare derivative works, distribute copies to the public, perform publicly and display publicly, and to permit others to do so. # # This is open source software; you can redistribute it and/or modify it under the terms of the BSD 3-clause License. If software is modified to produce derivative works, such modified software should be clearly marked, so as not to confuse it with the version available from LANL. Full text of the BSD 3-clause License can be found in the License file in the main development branch of the repository. # ############################################################################## # BSD 3-clause license: # Copyright 2017- Triad National Security, LLC # # Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ############################################################################## # Author: Nandakishore Santhi # Date: 28 November, 2017 # Copyright: Open source, must acknowledge original author # Purpose: Compile a Quantum Computer Algorithm (as a unitary operator) into a QASM code that can run directly # on IBM-QX physical machines or QISKit simulator. # LACC#: LANL LACC# C18030 - QNC: Quantum Netlist Compiler # ############################################################################## */ #include "qutils.h" #include "qgate.h" #include "qunitary.h" #include "qperm.h" void readPermutation(const string& filename, vector<uint64_t>& P) { if (Verbose) cout << "In function " << __FUNCTION__ << endl; ifstream inFile(filename); uint64_t value; if (!inFile.is_open()) { cerr << "Could not open input file " + filename + "\n"; exit(1); } while (inFile >> value) P.push_back(value); //Read the elements in the file into a vector inFile.close(); if (P.size() == 0) { cerr << "FORMAT ERROR: permutation could not be read: should be in 0-base Cauchy 1-line form\n"; exit(1); } if (Verbose) { cout << "Permutation map from file '" << filename << "': [ "; for (auto i = P.begin(); i != P.end(); i++) cout << *i << ' '; cout << "]\n" << endl; } } uint8_t compilePermutationOp(const string& inFilename, QNet_t& Net, ofstream& outFile) { if (Verbose) cout << "In function " << __FUNCTION__ << endl; vector<uint64_t> P; readPermutation(inFilename, P); const uint64_t N = P.size(); const uint64_t lgN = round(log2(N)); uint64_t QubitSize = lgN; if (Net.useMap && (Net.physMap.size() < QubitSize)) { cerr << "Provided logical to physical qubit mapping is incompatible with the permutation operator\n"; exit(1); } if (Net.useMap && (Net.physMap.size() > QubitSize)) QubitSize = Net.physMap.size(); if (Net.useTop && (Net.topology.n_rows < QubitSize)) { cerr << "Provided topology graph is incompatible with the permutation operator\n"; exit(1); } if (Net.useTop && (Net.topology.n_rows > QubitSize)) QubitSize = Net.topology.n_rows; vector<vector<uint64_t>> VSwaps; swapsDecompose(P, VSwaps); //Decompose P into a sequence of at most N swaps outFile << "\n//Quantum netlist implementing permutation operator '" << inFilename << "' using simple gates:\n"; Net.Gates = vector<vector<QG_t>>(QubitSize); //One vector for each qubit timeline if (Verbose) cout << "\n________________________________\n"; //\Pi_i G_i == P; so apply the G_i in same order to affect P (post-fix) for (int64_t i=0; i<VSwaps.size(); i++) lowerCnG(lgN, X, VSwaps[i], Net, false); if (Verbose) cout << "________________________________\n" << endl; return lgN; } void swapsDecompose(const vector<uint64_t>& P, vector<vector<uint64_t>>& VSwaps) { if (Verbose) cout << "In function " << __FUNCTION__ << endl; //Decompose P into a sequence of at most N swaps vector<bool> done; for (uint64_t i=0; i<P.size(); i++) done.push_back(false); vector<vector<uint64_t>> cycles; for (uint64_t i=0; i<P.size(); i++) { if (!done[i]) { uint64_t j=i, start=i; vector<uint64_t> cycle; while (cycles.size() < P.size()) { //Find cycles in the permutation operator cycle.push_back(j); done[j] = true; j = P[j]; if (j == start) break; } cycles.push_back(cycle); } } if (Verbose) { cout << "CYCLES: [ "; for (auto i = cycles.begin(); i != cycles.end(); i++) { cout << "("; for (auto j = (*i).begin(); j != (*i).end(); j++) cout << " " << (*j); cout << " ) "; } cout << "]\n" << endl; } for (auto i = cycles.begin(); i != cycles.end(); i++) { if ((*i).size() > 1) { uint64_t start=(*i)[0]; for (uint64_t j=1; j<(*i).size(); j++) { vector<uint64_t> s; s.push_back(start); s.push_back((*i)[j]); VSwaps.push_back(s); } } } if (Verbose) { cout << "SWAPS: [ "; for (auto i=VSwaps.begin(); i!=VSwaps.end(); i++) cout << "(" << (*i)[0] << ", " << (*i)[1] << ") "; cout << "]\n" << endl; } }
53.607407
757
0.631615
[ "vector" ]
9c460071699684cdb9db7af1389de92f75f52ccb
2,450
cc
C++
vta/tests/hardware/metal_test/metal_test.cc
peterjc123/tvm
d6dcd6c56febfbb12efe67884c188f045f435893
[ "Apache-2.0" ]
48
2020-07-29T18:09:23.000Z
2021-10-09T01:53:33.000Z
vta/tests/hardware/metal_test/metal_test.cc
peterjc123/tvm
d6dcd6c56febfbb12efe67884c188f045f435893
[ "Apache-2.0" ]
9
2021-04-02T02:28:07.000Z
2022-03-26T18:23:59.000Z
Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/tvm/vta/tests/hardware/metal_test/metal_test.cc
lablup/training_results_v0.7
f5bb59aa0f8b18b602763abe47d1d24d0d54b197
[ "Apache-2.0" ]
42
2020-08-01T06:41:24.000Z
2022-01-20T10:33:08.000Z
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * Copyright (c) 2018 by Contributors * \file metal_test.cpp * \brief Bare-metal test to test driver and VTA design. */ #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <vta/driver.h> #ifdef VTA_TARGET_PYNQ # include "../../../src/pynq/pynq_driver.h" #endif // VTA_TARGET_PYNQ #include "../common/test_lib.h" int main(void) { #if VTA_DEBUG == 1 printParameters(); #endif int status = 0; // Run ALU test (vector-scalar operators) status |= alu_test(VTA_ALU_OPCODE_MAX, true, 16, 128, true); status |= alu_test(VTA_ALU_OPCODE_MAX, true, 16, 128, false); status |= alu_test(VTA_ALU_OPCODE_ADD, true, 16, 128, true); status |= alu_test(VTA_ALU_OPCODE_ADD, true, 16, 128, false); status |= alu_test(VTA_ALU_OPCODE_SHR, true, 16, 128, true); status |= alu_test(VTA_ALU_OPCODE_SHR, true, 16, 128, false); // Run ALU test (vector-vector operators) status |= alu_test(VTA_ALU_OPCODE_MAX, false, 16, 128, true); status |= alu_test(VTA_ALU_OPCODE_MAX, false, 16, 128, false); status |= alu_test(VTA_ALU_OPCODE_ADD, false, 16, 128, true); status |= alu_test(VTA_ALU_OPCODE_ADD, false, 16, 128, false); // Run blocked GEMM test status |= blocked_gemm_test(256, 256, VTA_BLOCK_OUT*4, true, 2); status |= blocked_gemm_test(256, 256, VTA_BLOCK_OUT*4, false, 2); status |= blocked_gemm_test(256, 256, VTA_BLOCK_OUT*4, true, 1); status |= blocked_gemm_test(256, 256, VTA_BLOCK_OUT*4, false, 1); if (status == 0) { printf("\nINFO - Unit tests successful!\n"); } else { printf("\nINTO - Unit tests failed!\n"); } return status; }
34.027778
67
0.708163
[ "vector" ]
9c485998ea87bebda20849eb6fa1c6536c031e69
14,597
cpp
C++
dev/Gems/ScriptCanvasPhysics/Code/Tests/ScriptCanvasPhysicsTest.cpp
brianherrera/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
[ "AML" ]
1,738
2017-09-21T10:59:12.000Z
2022-03-31T21:05:46.000Z
dev/Gems/ScriptCanvasPhysics/Code/Tests/ScriptCanvasPhysicsTest.cpp
ArchitectureStudios/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
[ "AML" ]
427
2017-09-29T22:54:36.000Z
2022-02-15T19:26:50.000Z
dev/Gems/ScriptCanvasPhysics/Code/Tests/ScriptCanvasPhysicsTest.cpp
ArchitectureStudios/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
[ "AML" ]
671
2017-09-21T08:04:01.000Z
2022-03-29T14:30:07.000Z
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #include "ScriptCanvasPhysics_precompiled.h" #include <AzTest/GemTestEnvironment.h> #include <gmock/gmock.h> #include <AzFramework/Physics/Material.h> #include <AzFramework/Physics/Shape.h> #include <AzFramework/Physics/ShapeConfiguration.h> #include <AzFramework/Physics/World.h> #include <AzFramework/Components/TransformComponent.h> namespace ScriptCanvasPhysics { namespace WorldNodes { using Result = AZStd::tuple< bool /*true if an object was hit*/, AZ::Vector3 /*world space position*/, AZ::Vector3 /*surface normal*/, float /*distance to the hit*/, AZ::EntityId /*entity hit, if any*/, AZ::Crc32 /*tag of material surface hit, if any*/ >; using OverlapResult = AZStd::tuple< bool, /*true if the overlap returned hits*/ AZStd::vector<AZ::EntityId> /*list of entityIds*/ >; extern Result RayCastWorldSpaceWithGroup(const AZ::Vector3& start, const AZ::Vector3& direction, float distance, const AZStd::string& collisionGroup, AZ::EntityId ignore); extern Result RayCastLocalSpaceWithGroup(const AZ::EntityId& fromEntityId, const AZ::Vector3& direction, float distance, const AZStd::string& collisionGroup, AZ::EntityId ignore); extern AZStd::vector<Physics::RayCastHit> RayCastMultipleLocalSpaceWithGroup(const AZ::EntityId& fromEntityId, const AZ::Vector3& direction, float distance, const AZStd::string& collisionGroup, AZ::EntityId ignore); extern Result ShapecastQuery(float distance, const AZ::Transform& pose, const AZ::Vector3& direction, Physics::ShapeConfiguration& shape, const AZStd::string& collisionGroup, AZ::EntityId ignore); } } namespace ScriptCanvasPhysicsTests { using namespace ::testing; class MockWorld : public Physics::WorldRequestBus::Handler { public: MockWorld() { Physics::WorldRequestBus::Handler::BusConnect(Physics::DefaultPhysicsWorldId); } ~MockWorld() override { Physics::WorldRequestBus::Handler::BusDisconnect(); } MOCK_METHOD1(Update, void(float deltaTime)); MOCK_METHOD1(StartSimulation, void(float deltaTime)); MOCK_METHOD0(FinishSimulation, void()); MOCK_METHOD1(RayCast, Physics::RayCastHit(const Physics::RayCastRequest& request)); MOCK_METHOD1(RayCastMultiple, AZStd::vector<Physics::RayCastHit>(const Physics::RayCastRequest& request)); MOCK_METHOD1(ShapeCast, Physics::RayCastHit(const Physics::ShapeCastRequest& request)); MOCK_METHOD1(ShapeCastMultiple, AZStd::vector<Physics::RayCastHit>(const Physics::ShapeCastRequest& request)); MOCK_METHOD1(Overlap, AZStd::vector<Physics::OverlapHit>(const Physics::OverlapRequest& request)); MOCK_METHOD2(OverlapUnbounded, void(const Physics::OverlapRequest& request, const Physics::HitCallback<Physics::OverlapHit>& hitCallback)); MOCK_METHOD2(RegisterSuppressedCollision, void(const Physics::WorldBody& body0, const Physics::WorldBody& body1)); MOCK_METHOD2(UnregisterSuppressedCollision, void(const Physics::WorldBody& body0, const Physics::WorldBody& body1)); MOCK_METHOD1(AddBody, void(Physics::WorldBody& body)); MOCK_METHOD1(RemoveBody, void(Physics::WorldBody& body)); MOCK_METHOD1(SetSimFunc, void(std::function<void(void*)> func)); MOCK_METHOD1(SetEventHandler, void(Physics::WorldEventHandler* eventHandler)); MOCK_CONST_METHOD0(GetGravity, AZ::Vector3()); MOCK_METHOD1(SetGravity, void(const AZ::Vector3& gravity)); MOCK_METHOD1(SetMaxDeltaTime, void(float maxDeltaTime)); MOCK_METHOD1(SetFixedDeltaTime, void(float fixedDeltaTime)); MOCK_METHOD1(DeferDelete, void(AZStd::unique_ptr<Physics::WorldBody> worldBody)); MOCK_METHOD1(SetTriggerEventCallback, void(Physics::ITriggerEventCallback* triggerCallback)); MOCK_CONST_METHOD0(GetWorldId, AZ::Crc32()); }; class MockWorldBody : public Physics::WorldBody { public: MOCK_CONST_METHOD0(GetEntityId, AZ::EntityId()); MOCK_CONST_METHOD0(GetWorld, Physics::World*()); MOCK_CONST_METHOD0(GetTransform, AZ::Transform()); MOCK_METHOD1(SetTransform, void(const AZ::Transform& transform)); MOCK_CONST_METHOD0(GetPosition, AZ::Vector3()); MOCK_CONST_METHOD0(GetOrientation, AZ::Quaternion()); MOCK_CONST_METHOD0(GetAabb, AZ::Aabb()); MOCK_METHOD1(RayCast, Physics::RayCastHit(const Physics::RayCastRequest& request)); MOCK_CONST_METHOD0(GetNativeType, AZ::Crc32()); MOCK_CONST_METHOD0(GetNativePointer, void*()); MOCK_METHOD1(AddToWorld, void(Physics::World&)); MOCK_METHOD1(RemoveFromWorld, void(Physics::World&)); }; class MockShape : public Physics::Shape { public: MOCK_METHOD1(SetMaterial, void(const AZStd::shared_ptr<Physics::Material>& material)); MOCK_CONST_METHOD0(GetMaterial, AZStd::shared_ptr<Physics::Material>()); MOCK_METHOD1(SetCollisionLayer, void(const Physics::CollisionLayer& layer)); MOCK_CONST_METHOD0(GetCollisionLayer, Physics::CollisionLayer()); MOCK_METHOD1(SetCollisionGroup, void(const Physics::CollisionGroup& group)); MOCK_CONST_METHOD0(GetCollisionGroup, Physics::CollisionGroup()); MOCK_METHOD1(SetName, void(const char* name)); MOCK_METHOD2(SetLocalPose, void(const AZ::Vector3& offset, const AZ::Quaternion& rotation)); MOCK_CONST_METHOD0(GetLocalPose, AZStd::pair<AZ::Vector3, AZ::Quaternion>()); MOCK_METHOD0(GetNativePointer, void*()); MOCK_CONST_METHOD0(GetTag, AZ::Crc32()); MOCK_METHOD1(AttachedToActor, void(void* actor)); MOCK_METHOD0(DetachedFromActor, void()); MOCK_METHOD2(RayCast, Physics::RayCastHit(const Physics::RayCastRequest& worldSpaceRequest, const AZ::Transform& worldTransform)); MOCK_METHOD1(RayCastLocal, Physics::RayCastHit(const Physics::RayCastRequest& localSpaceRequest)); MOCK_METHOD3(GetGeometry, void(AZStd::vector<AZ::Vector3>&, AZStd::vector<AZ::u32>&, AZ::Aabb*)); MOCK_CONST_METHOD0(GetRestOffset, float()); MOCK_METHOD1(SetRestOffset, void(float)); MOCK_CONST_METHOD0(GetContactOffset, float()); MOCK_METHOD1(SetContactOffset, void(float)); MOCK_CONST_METHOD1(GetAabb, AZ::Aabb(const AZ::Transform& worldTransform)); MOCK_CONST_METHOD0(GetAabbLocal, AZ::Aabb()); }; class MockPhysicsMaterial : public Physics::Material { public: MOCK_CONST_METHOD0(GetSurfaceType, AZ::Crc32()); MOCK_METHOD1(SetSurfaceType, void(AZ::Crc32)); MOCK_CONST_METHOD0(GetSurfaceTypeName, const AZStd::string&()); MOCK_CONST_METHOD0(GetDynamicFriction, float()); MOCK_METHOD1(SetDynamicFriction, void(float)); MOCK_CONST_METHOD0(GetStaticFriction, float()); MOCK_METHOD1(SetStaticFriction, void(float)); MOCK_CONST_METHOD0(GetRestitution, float()); MOCK_METHOD1(SetRestitution, void(float)); MOCK_CONST_METHOD0(GetFrictionCombineMode, CombineMode()); MOCK_METHOD1(SetFrictionCombineMode, void(CombineMode)); MOCK_CONST_METHOD0(GetRestitutionCombineMode, CombineMode()); MOCK_METHOD1(SetRestitutionCombineMode, void(CombineMode)); MOCK_CONST_METHOD0(GetCryEngineSurfaceId, AZ::u32()); MOCK_METHOD0(GetNativePointer, void*()); MOCK_CONST_METHOD0(GetDensity, float()); MOCK_METHOD1(SetDensity, void(float)); }; class ScriptCanvasPhysicsTestEnvironment : public AZ::Test::GemTestEnvironment { void AddGemsAndComponents() override { AddComponentDescriptors({ AzFramework::TransformComponent::CreateDescriptor() }); } }; class ScriptCanvasPhysicsTest : public ::testing::Test { protected: void SetUp() override { ::testing::Test::SetUp(); ON_CALL(m_material, GetSurfaceType()) .WillByDefault(Return(AZ::Crc32("CustomSurface"))); m_hit.m_body = &m_worldBody; m_hit.m_position = AZ::Vector3(1.f, 2.f, 3.f); m_hit.m_distance = 2.5f; m_hit.m_normal = AZ::Vector3(-1.f, 3.5f, 0.5f); m_hit.m_shape = &m_shape; m_hit.m_material = &m_material; } NiceMock<MockWorldBody> m_worldBody; NiceMock<MockShape> m_shape; NiceMock<MockPhysicsMaterial> m_material; NiceMock<MockWorld> m_worldMock; Physics::RayCastHit m_hit; bool ResultIsEqualToHit(const ScriptCanvasPhysics::WorldNodes::Result& result, const Physics::RayCastHit& hit) { return AZStd::get<0>(result) == (hit.m_body != nullptr) && AZStd::get<1>(result) == hit.m_position && AZStd::get<2>(result) == hit.m_normal && AZStd::get<3>(result) == hit.m_distance && AZStd::get<4>(result) == (hit.m_body ? hit.m_body->GetEntityId() : AZ::EntityId()) && AZStd::get<5>(result) == (hit.m_material ? hit.m_material->GetSurfaceType() : AZ::Crc32()) ; } }; TEST_F(ScriptCanvasPhysicsTest, WorldNodes_RayCastWorldSpaceWithGroup_FT) { ON_CALL(m_worldMock, RayCast(_)) .WillByDefault(Return(m_hit)); // given raycast data const AZ::Vector3 start = AZ::Vector3::CreateZero(); const AZ::Vector3 direction = AZ::Vector3(0.f,1.f,0.f); const float distance = 1.f; const AZStd::string collisionGroup = "default"; const AZ::EntityId ignoreEntityId; // when a raycast is performed auto result = ScriptCanvasPhysics::WorldNodes::RayCastWorldSpaceWithGroup( start, direction, distance, collisionGroup, ignoreEntityId ); // expect a valid hit is returned EXPECT_TRUE(ResultIsEqualToHit(result, m_hit)); } TEST_F(ScriptCanvasPhysicsTest, WorldNodes_RayCastLocalSpaceWithGroup_FT) { ON_CALL(m_worldMock, RayCast(_)) .WillByDefault(Return(m_hit)); // given raycast data const AZ::Vector3 start = AZ::Vector3::CreateZero(); const AZ::Vector3 direction = AZ::Vector3(0.f,1.f,0.f); const float distance = 1.f; const AZStd::string collisionGroup = "default"; const AZ::EntityId ignoreEntityId; auto fromEntity = AZStd::make_unique<AZ::Entity>("Entity"); fromEntity->CreateComponent<AzFramework::TransformComponent>()->SetWorldTM(AZ::Transform::Identity()); fromEntity->Init(); fromEntity->Activate(); // when a raycast is performed auto result = ScriptCanvasPhysics::WorldNodes::RayCastLocalSpaceWithGroup( fromEntity->GetId(), direction, distance, collisionGroup, fromEntity->GetId() ); // expect a valid hit is returned EXPECT_TRUE(ResultIsEqualToHit(result, m_hit)); } TEST_F(ScriptCanvasPhysicsTest, WorldNodes_RayCastMultipleLocalSpaceWithGroup_FT) { AZStd::vector<Physics::RayCastHit> hits; hits.push_back(m_hit); ON_CALL(m_worldMock, RayCastMultiple(_)) .WillByDefault(Return(hits)); // given raycast data const AZ::Vector3 start = AZ::Vector3::CreateZero(); const AZ::Vector3 direction = AZ::Vector3(0.f,1.f,0.f); const float distance = 1.f; const AZStd::string collisionGroup = "default"; const AZ::EntityId ignoreEntityId; auto fromEntity = AZStd::make_unique<AZ::Entity>("Entity"); fromEntity->CreateComponent<AzFramework::TransformComponent>()->SetWorldTM(AZ::Transform::Identity()); fromEntity->Init(); fromEntity->Activate(); // when a raycast is performed auto results = ScriptCanvasPhysics::WorldNodes::RayCastMultipleLocalSpaceWithGroup( fromEntity->GetId(), direction, distance, collisionGroup, fromEntity->GetId() ); // expect valid hits are returned EXPECT_FALSE(results.empty()); for (auto result : results) { EXPECT_EQ(result.m_body, m_hit.m_body); EXPECT_EQ(result.m_distance, m_hit.m_distance); EXPECT_EQ(result.m_material, m_hit.m_material); EXPECT_EQ(result.m_normal, m_hit.m_normal); EXPECT_EQ(result.m_position, m_hit.m_position); EXPECT_EQ(result.m_shape, m_hit.m_shape); } } TEST_F(ScriptCanvasPhysicsTest, WorldNodes_ShapecastQuery_FT) { ON_CALL(m_worldMock, ShapeCast(_)) .WillByDefault(Return(m_hit)); // given shapecast data const AZ::Vector3 start = AZ::Vector3::CreateZero(); const AZ::Vector3 direction = AZ::Vector3(0.f,1.f,0.f); const float distance = 1.f; const AZStd::string collisionGroup = "default"; const AZ::EntityId ignoreEntityId; const AZ::Transform pose = AZ::Transform::CreateIdentity(); Physics::BoxShapeConfiguration boxShapeConfiguration = Physics::BoxShapeConfiguration(); // when a shapecast is performed auto result = ScriptCanvasPhysics::WorldNodes::ShapecastQuery( distance, pose, direction, boxShapeConfiguration, collisionGroup, ignoreEntityId ); // expect a valid hit is returned EXPECT_TRUE(ResultIsEqualToHit(result, m_hit)); } AZ_UNIT_TEST_HOOK(new ScriptCanvasPhysicsTestEnvironment); }
41.234463
147
0.653559
[ "object", "shape", "vector", "transform" ]
9c4a5b8a657f054713b645c07528d28ce2a41166
17,343
cpp
C++
profile_indels.cpp
Yichen-Si/vt-topmed
e22e964a68e236b190b3038318ca9799f1922e0e
[ "MIT" ]
null
null
null
profile_indels.cpp
Yichen-Si/vt-topmed
e22e964a68e236b190b3038318ca9799f1922e0e
[ "MIT" ]
1
2019-12-26T09:34:03.000Z
2019-12-26T09:34:03.000Z
profile_indels.cpp
Yichen-Si/vt-topmed
e22e964a68e236b190b3038318ca9799f1922e0e
[ "MIT" ]
1
2021-09-18T18:23:00.000Z
2021-09-18T18:23:00.000Z
/* The MIT License Copyright (c) 2013 Adrian Tan <atks@umich.edu> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "profile_indels.h" namespace { class OverlapStats { public: uint32_t a,ab,b,a_ins,ab_ins,b_ins,a_del,ab_del,b_del; OverlapStats() { a = 0; ab = 0; b = 0; a_ins = 0; a_del = 0; ab_ins = 0; ab_del = 0; b_ins = 0; b_del = 0; }; }; class Igor : Program { public: std::string version; /////////// //options// /////////// std::string input_vcf_file; std::vector<std::string> input_vcf_files; std::string ref_fasta_file; std::string ref_data_sets_list; std::string output_tabulate_dir; std::string output_pdf_file; std::vector<GenomeInterval> intervals; std::string interval_list; ////////////////////////////////////////////// //reference file info : to store in an object? ////////////////////////////////////////////// std::vector<std::string> dataset_labels; std::vector<std::string> dataset_types; std::vector<std::string> dataset_fexps; std::string cds_bed_file; std::string cplx_bed_file; /////// //i/o// /////// BCFSyncedReader *sr; bcf1_t *v; ////////// //filter// ////////// std::string fexp; std::vector<Filter*> filters; std::vector<bool> filter_exists; int32_t no_filters; ///////// //stats// ///////// std::vector<OverlapStats> stats; int32_t no_indels; int32_t nfs; int32_t fs; int32_t lcplx; //////////////// //common tools// //////////////// VariantManip *vm; OrderedRegionOverlapMatcher *orom_lcplx; OrderedRegionOverlapMatcher *orom_gencode_cds; Igor(int argc, char ** argv) { ////////////////////////// //options initialization// ////////////////////////// try { std::string desc = "profile Indels"; version = "0.5"; TCLAP::CmdLine cmd(desc, ' ', version); VTOutput my; cmd.setOutput(&my); TCLAP::ValueArg<std::string> arg_ref_fasta_file("r", "r", "reference sequence fasta file []", true, "", "str", cmd); TCLAP::ValueArg<std::string> arg_intervals("i", "i", "intervals []", false, "", "str", cmd); TCLAP::ValueArg<std::string> arg_interval_list("I", "I", "file containing list of intervals []", false, "", "file", cmd); TCLAP::ValueArg<std::string> arg_fexp("f", "f", "filter expression []", false, "VTYPE==INDEL", "str", cmd); TCLAP::ValueArg<std::string> arg_output_tabulate_dir("x", "x", "output latex directory [tabulate_indels]", false, "", "str", cmd); TCLAP::ValueArg<std::string> arg_output_pdf_file("y", "y", "output pdf file [indels.pdf]", false, "indels.pdf", "str", cmd); TCLAP::ValueArg<std::string> arg_ref_data_sets_list("g", "g", "file containing list of reference datasets []", true, "", "file", cmd); TCLAP::UnlabeledValueArg<std::string> arg_input_vcf_file("<in.vcf>", "input VCF file", true, "","file", cmd); cmd.parse(argc, argv); ref_fasta_file = arg_ref_fasta_file.getValue(); parse_intervals(intervals, arg_interval_list.getValue(), arg_intervals.getValue()); fexp = arg_fexp.getValue(); output_tabulate_dir = arg_output_tabulate_dir.getValue(); output_pdf_file = arg_output_pdf_file.getValue(); ref_data_sets_list = arg_ref_data_sets_list.getValue(); input_vcf_file = arg_input_vcf_file.getValue(); /////////////////////// //parse input VCF files /////////////////////// } catch (TCLAP::ArgException &e) { std::cerr << "error: " << e.error() << " for arg " << e.argId() << "\n"; abort(); } }; void initialize() { ////////////////////// //reference data set// ////////////////////// //# This file contains information on how to process reference data sets. //# //# dataset - name of data set, this label will be printed. //# type - True Positives (TP) and False Positives (FP) //# overlap percentages labeled as (Precision, Sensitivity) and (False Discovery Rate, Type I Error) respectively //# - annotation //# file is used for GENCODE annotation of frame shift and non frame shift Indels //# filter - filter applied to variants for this particular data set //# path - path of indexed BCF file //#dataset type filter path //1000g TP N_ALLELE==2&&VTYPE==INDEL /net/fantasia/home/atks/ref/vt/grch37/1000G.snps_indels.sites.bcf //mills TP N_ALLELE==2&&VTYPE==INDEL /net/fantasia/home/atks/ref/vt/grch37/mills.208620indels.sites.bcf //dbsnp TP N_ALLELE==2&&VTYPE==INDEL /net/fantasia/home/atks/ref/vt/grch37/dbsnp.13147541variants.sites.bcf //GENCODE_V19 cds_annotation . /net/fantasia/home/atks/ref/vt/grch37/gencode.cds.bed.gz //DUST cplx_annotation . /net/fantasia/home/atks/ref/vt/grch37/mdust.bed.gz input_vcf_files.push_back(input_vcf_file); dataset_labels.push_back("data"); dataset_types.push_back("ref"); dataset_fexps.push_back(fexp); htsFile *hts = hts_open(ref_data_sets_list.c_str(), "r"); kstring_t s = {0,0,0}; std::vector<std::string> vec; while (hts_getline(hts, '\n', &s)>=0) { if (s.s[0] == '#') continue; std::string line(s.s); split(vec, " ", line); if (vec[1] == "TP" || vec[1] == "FP") { dataset_labels.push_back(vec[0]); dataset_types.push_back(vec[1]); dataset_fexps.push_back(vec[2]); input_vcf_files.push_back(vec[3]); } else if (vec[1] == "cds_annotation") { cds_bed_file = vec[3]; } else if (vec[1] == "cplx_annotation") { cplx_bed_file = vec[3]; } else { std::cerr << "Reference data set type: \"" << vec[1] << "\" not recognised\n"; exit(1); } } hts_close(hts); if (s.m) free(s.s); ///////////////////////// //filter initialization// ///////////////////////// for (size_t i=0; i<dataset_fexps.size(); ++i) { filters.push_back(new Filter(dataset_fexps[i])); filter_exists.push_back(dataset_fexps[i]!=""); } no_filters = filters.size(); ////////////////////// //i/o initialization// ////////////////////// sr = new BCFSyncedReader(input_vcf_files, intervals, false); /////////////////////// //tool initialization// /////////////////////// vm = new VariantManip(ref_fasta_file); orom_gencode_cds = new OrderedRegionOverlapMatcher(cds_bed_file); orom_lcplx = new OrderedRegionOverlapMatcher(cplx_bed_file); //////////////////////// //stats initialization// //////////////////////// no_indels = 0; lcplx = 0; fs = 0; nfs = 0; } void profile_indels() { //for combining the alleles std::vector<bcfptr*> current_recs; std::vector<Interval*> overlaps; Variant variant; int32_t no_overlap_files = input_vcf_files.size(); std::vector<int32_t> presence(no_overlap_files, 0); stats.resize(no_overlap_files); while(sr->read_next_position(current_recs)) { //check first variant bcf1_t *v = current_recs[0]->v; bcf_hdr_t *h = current_recs[0]->h; int32_t vtype = vm->classify_variant(h, v, variant); std::string chrom = bcf_get_chrom(h,v); int32_t start1 = bcf_get_pos1(v); int32_t end1 = bcf_get_end_pos1(v); for (size_t i=0; i<no_overlap_files; ++i) presence[i]=0; //check existence for (size_t i=0; i<current_recs.size(); ++i) { int32_t index = current_recs[i]->file_index; if (filter_exists[index]) { if (!filters[index]->apply(current_recs[i]->h,current_recs[i]->v,&variant)) { continue; } } ++presence[index]; } //annotate if (presence[0]) { if (orom_lcplx->overlaps_with(chrom, start1, end1)) { ++lcplx; } if (orom_gencode_cds->overlaps_with(chrom, start1, end1)) { if (abs(variant.alleles[0].dlen)%3!=0) { ++fs; } else { ++nfs; } } ++no_indels; } int32_t ins = variant.alleles[0].ins; int32_t del = 1-ins; if (presence[0]) { ++stats[0].a; stats[0].a_ins += ins; stats[0].a_del += del; } //update overlap stats for (size_t i=1; i<no_overlap_files; ++i) { if (presence[0] && !presence[i]) { ++stats[i].a; stats[i].a_ins += ins; stats[i].a_del += del; } else if (presence[0] && presence[i]) { ++stats[i].ab; stats[i].ab_ins += ins; stats[i].ab_del += del; } else if (!presence[0] && presence[i]) { ++stats[i].b; stats[i].b_ins += ins; stats[i].b_del += del; } else { //not in either, do nothing } presence[i]=0; } presence[0] = 0; } }; void print_options() { std::clog << "profile_indels v" << version << "\n\n"; std::clog << "\n"; std::clog << "Options: input VCF File " << input_vcf_file << "\n"; print_str_op(" [f] filter ", fexp); std::clog << " [g] reference data sets list file " << ref_data_sets_list << "\n"; std::clog << " [r] reference FASTA file " << ref_fasta_file << "\n"; print_str_op(" [x] output tabulate directory ", output_tabulate_dir); print_str_op(" [y] output pdf file ", output_pdf_file); print_int_op(" [i] intervals ", intervals); std::clog << "\n"; } void print_pdf() { if (output_tabulate_dir=="") return; append_cwd(output_tabulate_dir); //generate file int32_t ret = mkdir(output_tabulate_dir.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); std::string filepath = output_tabulate_dir + "/tabulate.tex"; FILE *out = fopen(filepath.c_str(), "w"); std::string g2s[3] = {"R/R","R/A","A/A"}; fprintf(out, "\\PassOptionsToPackage{table}{xcolor}\n"); fprintf(out, "\\documentclass{beamer}\n"); fprintf(out, "\\begin{document}\n"); fprintf(out, "\n"); fprintf(out, "\\begin{frame}{Data set summary}\n"); fprintf(out, "\\resizebox{\\linewidth}{!}{\n"); fprintf(out, "\\rowcolors{2}{blue!25}{blue!10}\n"); fprintf(out, "\\begin{tabular}{rrrr}\n"); fprintf(out, "\\rowcolor{blue!50}\n"); fprintf(out, "No. Indels & Ins/Del & Insertions & Deletions \\\\ \n"); fprintf(out, "%d & %.1f & %d & %d \\\\ \n", stats[0].a, (float)stats[0].a_ins/(stats[0].a_del), stats[0].a_ins, stats[0].a_del); fprintf(out, "\\end{tabular}}\n"); fprintf(out, "\\resizebox{\\linewidth}{!}{\n"); fprintf(out, "\\rowcolors{2}{blue!25}{blue!10}\n"); fprintf(out, "\\begin{tabular}{rrr}\n"); fprintf(out, "\\rowcolor{blue!50}\n"); fprintf(out, "Frameshift Indel Proportion (\\%%) & FS & NFS \\\\ \n"); fprintf(out, "%.2f & %d & %d \\\\ \n", (float)fs/(fs+nfs), fs, nfs); fprintf(out, "\\end{tabular}}\n"); fprintf(out, "\\end{frame}\n"); for (int32_t i=1; i<dataset_labels.size(); ++i) { fprintf(out, "\n"); fprintf(out, "\\begin{frame}{Data set summary}\n"); fprintf(out, "\\resizebox{\\linewidth}{!}{\n"); fprintf(out, "\\rowcolors{2}{blue!25}{blue!10}\n"); fprintf(out, "\\begin{tabular}{rrrrr}\n"); fprintf(out, "\\rowcolor{blue!50}\n"); fprintf(out, "%s & no. indels & ins/del & ins & del\\\\ \n", dataset_labels[i].c_str()); fprintf(out, "A-B & %d & %.1f & %d & %d\\\\ \n", stats[i].a, (float)stats[i].a_ins/(stats[i].a_del), stats[i].a_ins, stats[i].a_del); fprintf(out, "A\\&B & %d & %.1f & %d & %d\\\\ \n", stats[i].ab, (float)stats[i].ab_ins/(stats[i].ab_del), stats[i].ab_ins, stats[i].ab_del); fprintf(out, "B-A & %d & %.1f & %d & %d\\\\ \n", stats[i].b, (float)stats[i].b_ins/(stats[i].b_del), stats[i].b_ins, stats[i].b_del); fprintf(out, " & & & & \\\\ \n"); fprintf(out, " Precision & %.2f\\%% & & & \\\\ \n", 100*(float)stats[i].ab/(stats[i].a+stats[i].ab)); fprintf(out, " Sensitivity & %.2f\\%% & & & \\\\ \n", 100*(float)stats[i].ab/(stats[i].b+stats[i].ab)); fprintf(out, "\\end{tabular}}\n"); fprintf(out, "\\end{frame}\n"); } fprintf(out, "\n"); fprintf(out, "\\end{document}\n"); fclose(out); std::string cmd = "cd " + output_tabulate_dir + "; pdflatex tabulate.tex > run.log; mv tabulate.pdf " + output_pdf_file; std::cerr << cmd << "\n"; int32_t sys_ret = system(cmd.c_str()); }; void print_stats() { fprintf(stderr, "\n"); fprintf(stderr, " %s\n", "data set"); fprintf(stderr, " No Indels : %10d [%.2f]\n", no_indels, (float)stats[0].a_ins/(stats[0].a_del)); fprintf(stderr, " FS/NFS : %10.2f (%d/%d)\n", (float)fs/(fs+nfs), fs, nfs); fprintf(stderr, " Low complexity : %10.2f (%d/%d)\n", (float)lcplx/no_indels, lcplx, no_indels); fprintf(stderr, "\n"); for (int32_t i=1; i<dataset_labels.size(); ++i) { fprintf(stderr, " %s\n", dataset_labels[i].c_str()); fprintf(stderr, " A-B %10d [%.2f]\n", stats[i].a, (float)stats[i].a_ins/(stats[i].a_del)); fprintf(stderr, " A&B %10d [%.2f]\n", stats[i].ab, (float)stats[i].ab_ins/stats[i].ab_del); fprintf(stderr, " B-A %10d [%.2f]\n", stats[i].b, (float)stats[i].b_ins/(stats[i].b_del)); if (dataset_types[i]=="TP") { fprintf(stderr, " Precision %4.1f%%\n", 100*(float)stats[i].ab/(stats[i].a+stats[i].ab)); fprintf(stderr, " Sensitivity %4.1f%%\n", 100*(float)stats[i].ab/(stats[i].b+stats[i].ab)); } else { fprintf(stderr, " FDR %4.1f%%\n", 100*(float)stats[i].ab/(stats[i].a+stats[i].ab)); fprintf(stderr, " Type I Error %4.1f%%\n", 100*(float)stats[i].ab/(stats[i].b+stats[i].ab)); } fprintf(stderr, "\n"); } }; ~Igor() { }; private: }; } void profile_indels(int argc, char ** argv) { Igor igor(argc, argv); igor.print_options(); igor.initialize(); igor.profile_indels(); igor.print_stats(); igor.print_pdf(); }
36.665962
153
0.501586
[ "object", "vector" ]
9c4b63d895bc34fe89a2346401a5da1b079c2c9d
3,670
hpp
C++
include/Module/Decoder/Decoder_SIHO.hpp
FredrikBlomgren/aff3ct
fa616bd923b2dcf03a4cf119cceca51cf810d483
[ "MIT" ]
315
2016-06-21T13:32:14.000Z
2022-03-28T09:33:59.000Z
include/Module/Decoder/Decoder_SIHO.hpp
a-panella/aff3ct
61509eb756ae3725b8a67c2d26a5af5ba95186fb
[ "MIT" ]
153
2017-01-17T03:51:06.000Z
2022-03-24T15:39:26.000Z
include/Module/Decoder/Decoder_SIHO.hpp
a-panella/aff3ct
61509eb756ae3725b8a67c2d26a5af5ba95186fb
[ "MIT" ]
119
2017-01-04T14:31:58.000Z
2022-03-21T08:34:16.000Z
/*! * \file * \brief Class module::Decoder_SIHO. */ #ifndef DECODER_SIHO_HPP_ #define DECODER_SIHO_HPP_ #include <memory> #include <vector> #include <cstdint> #include "Module/Task.hpp" #include "Module/Socket.hpp" #include "Module/Decoder/Decoder_HIHO.hpp" namespace aff3ct { namespace module { /*! * \class Decoder_SIHO * * \brief A Decoder is an algorithm dedicated to find the initial sequence of information bits (before the noise). * * \tparam B: type of the bits in the Decoder. * \tparam R: type of the reals (floating-point or fixed-point representation) in the Decoder. * * The Decoder takes a soft input (real numbers) and return a hard output (bits). */ template <typename B = int, typename R = float> class Decoder_SIHO : public Decoder_HIHO<B> { protected: std::vector<R> Y_N; public: inline Task& operator[](const dec::tsk t); inline Socket& operator[](const dec::sck::decode_hiho s); inline Socket& operator[](const dec::sck::decode_hiho_cw s); inline Socket& operator[](const dec::sck::decode_siho s); inline Socket& operator[](const dec::sck::decode_siho_cw s); public: /*! * \brief Constructor. * * \param K: number of information bits in the frame. * \param N: size of one frame. */ Decoder_SIHO(const int K, const int N); /*! * \brief Destructor. */ virtual ~Decoder_SIHO() = default; virtual Decoder_SIHO<B,R>* clone() const; /*! * \brief Decodes the noisy frame. * * \param Y_N: a noisy frame. * \param V_K: a decoded codeword (only the information bits). */ template <class AR = std::allocator<R>, class AB = std::allocator<B>> int decode_siho(const std::vector<R,AR>& Y_N, std::vector<int8_t,AB>& CWD, std::vector<B,AB>& V_K, const int frame_id = -1, const bool managed_memory = true); template <class AR = std::allocator<R>, class AB = std::allocator<B>> int decode_siho(const std::vector<R,AR>& Y_N, std::vector<B,AB>& V_K, const int frame_id = -1, const bool managed_memory = true); int decode_siho(const R *Y_N, int8_t *CWD, B *V_K, const int frame_id = -1, const bool managed_memory = true); int decode_siho(const R *Y_N, B *V_K, const int frame_id = -1, const bool managed_memory = true); template <class AR = std::allocator<R>, class AB = std::allocator<B>> int decode_siho_cw(const std::vector<R,AR>& Y_N, std::vector<int8_t,AB>& CWD, std::vector<B,AB>& V_N, const int frame_id = -1, const bool managed_memory = true); template <class AR = std::allocator<R>, class AB = std::allocator<B>> int decode_siho_cw(const std::vector<R,AR>& Y_N, std::vector<B,AB>& V_N, const int frame_id = -1, const bool managed_memory = true); int decode_siho_cw(const R *Y_N, int8_t *CWD, B *V_N, const int frame_id = -1, const bool managed_memory = true); int decode_siho_cw(const R *Y_N, B *V_N, const int frame_id = -1, const bool managed_memory = true); protected: virtual void set_n_frames_per_wave(const size_t n_frames_per_wave); virtual int _decode_siho(const R *Y_N, int8_t *CWD, B *V_K, const size_t frame_id); virtual int _decode_siho(const R *Y_N, B *V_K, const size_t frame_id); virtual int _decode_siho_cw(const R *Y_N, int8_t *CWD, B *V_N, const size_t frame_id); virtual int _decode_siho_cw(const R *Y_N, B *V_N, const size_t frame_id); virtual int _decode_hiho(const B *Y_N, int8_t *CWD, B *V_K, const size_t frame_id); virtual int _decode_hiho_cw(const B *Y_N, int8_t *CWD, B *V_N, const size_t frame_id); }; } } #ifndef DOXYGEN_SHOULD_SKIP_THIS #include "Module/Decoder/Decoder_SIHO.hxx" #endif #endif /* DECODER_SIHO_HPP_ */
33.363636
114
0.687466
[ "vector" ]
9c4bb105b14ddc8b0d2da641d9b981bdad5c9a78
6,361
hpp
C++
src/modules/sensors/data_validator/DataValidator.hpp
lgarciaos/Firmware
26dba1407bd1fbc65c23870a22fed904afba6347
[ "BSD-3-Clause" ]
4,224
2015-01-02T11:51:02.000Z
2020-10-27T23:42:28.000Z
src/modules/sensors/data_validator/DataValidator.hpp
lgarciaos/Firmware
26dba1407bd1fbc65c23870a22fed904afba6347
[ "BSD-3-Clause" ]
11,736
2015-01-01T11:59:16.000Z
2020-10-28T17:13:38.000Z
src/modules/sensors/data_validator/DataValidator.hpp
lgarciaos/Firmware
26dba1407bd1fbc65c23870a22fed904afba6347
[ "BSD-3-Clause" ]
11,850
2015-01-02T14:54:47.000Z
2020-10-28T16:42:47.000Z
/**************************************************************************** * * Copyright (c) 2015-2020 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file DataValidator.hpp * * A data validation class to identify anomalies in data streams * * @author Lorenz Meier <lorenz@px4.io> */ #pragma once #include <math.h> #include <stdint.h> class DataValidator { public: static const unsigned dimensions = 3; DataValidator() = default; ~DataValidator() = default; /** * Put an item into the validator. * * @param val Item to put */ void put(uint64_t timestamp, float val, uint32_t error_count, uint8_t priority); /** * Put a 3D item into the validator. * * @param val Item to put */ void put(uint64_t timestamp, const float val[dimensions], uint32_t error_count, uint8_t priority); /** * Get the next sibling in the group * * @return the next sibling */ DataValidator *sibling() { return _sibling; } /** * Set the sibling to the next node in the group * */ void setSibling(DataValidator *new_sibling) { _sibling = new_sibling; } /** * Get the confidence of this validator * @return the confidence between 0 and 1 */ float confidence(uint64_t timestamp); /** * Get the error count of this validator * @return the error count */ uint32_t error_count() const { return _error_count; } /** * Get the values of this validator * @return the stored value */ float *value() { return _value; } /** * Get the used status of this validator * @return true if this validator ever saw data */ bool used() const { return (_time_last > 0); } /** * Get the priority of this validator * @return the stored priority */ uint8_t priority() const { return _priority; } /** * Get the error state of this validator * @return the bitmask with the error status */ uint32_t state() const { return _error_mask; } /** * Reset the error state of this validator */ void reset_state() { _error_mask = ERROR_FLAG_NO_ERROR; } /** * Get the RMS values of this validator * @return the stored RMS */ float *rms() { return _rms; } /** * Print the validator value * */ void print(); /** * Set the timeout value * * @param timeout_interval_us The timeout interval in microseconds */ void set_timeout(uint32_t timeout_interval_us) { _timeout_interval = timeout_interval_us; } /** * Set the equal count threshold * * @param threshold The number of equal values before considering the sensor stale */ void set_equal_value_threshold(uint32_t threshold) { _value_equal_count_threshold = threshold; } /** * Get the timeout value * * @return The timeout interval in microseconds */ uint32_t get_timeout() const { return _timeout_interval; } /** * Data validator error states */ static constexpr uint32_t ERROR_FLAG_NO_ERROR = (0x00000000U); static constexpr uint32_t ERROR_FLAG_NO_DATA = (0x00000001U); static constexpr uint32_t ERROR_FLAG_STALE_DATA = (0x00000001U << 1); static constexpr uint32_t ERROR_FLAG_TIMEOUT = (0x00000001U << 2); static constexpr uint32_t ERROR_FLAG_HIGH_ERRCOUNT = (0x00000001U << 3); static constexpr uint32_t ERROR_FLAG_HIGH_ERRDENSITY = (0x00000001U << 4); private: uint32_t _error_mask{ERROR_FLAG_NO_ERROR}; /**< sensor error state */ uint32_t _timeout_interval{40000}; /**< interval in which the datastream times out in us */ uint64_t _time_last{0}; /**< last timestamp */ uint64_t _event_count{0}; /**< total data counter */ uint32_t _error_count{0}; /**< error count */ int _error_density{0}; /**< ratio between successful reads and errors */ uint8_t _priority{0}; /**< sensor nominal priority */ float _mean[dimensions] {}; /**< mean of value */ float _lp[dimensions] {}; /**< low pass value */ float _M2[dimensions] {}; /**< RMS component value */ float _rms[dimensions] {}; /**< root mean square error */ float _value[dimensions] {}; /**< last value */ unsigned _value_equal_count{0}; /**< equal values in a row */ unsigned _value_equal_count_threshold{ VALUE_EQUAL_COUNT_DEFAULT}; /**< when to consider an equal count as a problem */ DataValidator *_sibling{nullptr}; /**< sibling in the group */ static const constexpr unsigned NORETURN_ERRCOUNT = 10000; /**< if the error count reaches this value, return sensor as invalid */ static const constexpr float ERROR_DENSITY_WINDOW = 100.0f; /**< window in measurement counts for errors */ static const constexpr unsigned VALUE_EQUAL_COUNT_DEFAULT = 100; /**< if the sensor value is the same (accumulated also between axes) this many times, flag it */ /* we don't want this class to be copied */ DataValidator(const DataValidator &) = delete; DataValidator operator=(const DataValidator &) = delete; };
31.646766
108
0.697846
[ "3d" ]
9c4ed254782cffa67443915fdff5264d587e333c
87,773
cpp
C++
src/bert/dcfemmodelling.cpp
mjziebarth/gimli
196ac4d6dd67e0326cccc44a87b367f64051e490
[ "Apache-2.0" ]
3
2021-07-10T00:56:59.000Z
2022-02-17T12:43:38.000Z
src/bert/dcfemmodelling.cpp
ivek1312/gimli
5fafebb7c96dd0e04e2616df402fa27a01609d63
[ "Apache-2.0" ]
null
null
null
src/bert/dcfemmodelling.cpp
ivek1312/gimli
5fafebb7c96dd0e04e2616df402fa27a01609d63
[ "Apache-2.0" ]
1
2022-03-29T04:28:40.000Z
2022-03-29T04:28:40.000Z
/****************************************************************************** * Copyright (C) 2006-2019 by the resistivity.net development team * * Carsten Rücker carsten@resistivity.net * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * * ******************************************************************************/ #include "dcfemmodelling.h" #include "bertJacobian.h" #include "bertMisc.h" #include "bertDataContainer.h" #include "datamap.h" #include "electrode.h" #include <datacontainer.h> #include <elementmatrix.h> #include <expressions.h> #include <interpolate.h> #include <linSolver.h> #include <matrix.h> #include <memwatch.h> #include <mesh.h> #include <numericbase.h> #include <regionManager.h> #include <shape.h> #include <sparsematrix.h> #include <stopwatch.h> #include <vectortemplates.h> #undef HAVE_LIBBOOST_THREAD #ifdef HAVE_LIBBOOST_THREAD #include <boost/thread.hpp> #endif namespace GIMLI{ void setComplexResistivities(Mesh & mesh, const std::map < float, Complex > & aMap){ std::map< float, Complex >::const_iterator itm; RVector am(mesh.cellCount()); RVector ph(mesh.cellCount()); if (aMap.size() != 0){ for (Index i = 0, imax = mesh.cellCount(); i < imax; i++){ itm = aMap.find(float(mesh.cell(i).marker())); if (itm != aMap.end()) { am[mesh.cell(i).id()] = std::real((*itm).second); ph[mesh.cell(i).id()] = std::imag((*itm).second); } } } // Assuming aMap is Ohm , phase(rad) setComplexResistivities(mesh, am, ph); } void setComplexResistivities(Mesh & mesh, const RVector & am, const RVector & ph){ setComplexResistivities(mesh, polarToComplex(am, ph, true)); } void setComplexResistivities(Mesh & mesh, const CVector & z){ mesh.addData("AttributeReal", real(z)); mesh.addData("AttributeImag", imag(z)); } CVector getComplexResistivities(const Mesh & mesh){ if (!mesh.haveData("AttributeReal") || !mesh.haveData("AttributeImag")){ throwError(1, WHERE_AM_I + " complex resistivity values expected but non found"); } RVector re(mesh.data("AttributeReal")); RVector im(mesh.data("AttributeImag")); return toComplex(re, im); } void setComplexData(DataContainer & data, const RVector & re, const RVector & im){ setComplexData(data, toComplex(re, -im)); } void setComplexData(DataContainer & data, const CVector & z){ data.set("u", abs(z)); data.set("ip", -angle(z) * 1000); } CVector getComplexData(const DataContainer & data){ if (!data.allNonZero("rhoa") || !data.exists("ip")){ throwError(1, WHERE_AM_I + " We need rhoa and ip to get complex data."); } RVector am(data("rhoa")); RVector ph(data("ip")); return polarToComplex(am, ph, true); } template < class Vec > bool checkIfMapFileExistAndLoadToVector(const std::string & filename, Vec & v){ bool fromOne = true; if (fileExist(filename)){ std::map < float, float > iMap(loadFloatMap(filename)); if ((uint)rint(iMap.begin()->first) == 0){ fromOne = false; } for (std::map <float, float>::iterator it = iMap.begin(); it != iMap.end(); it ++){ if (it->first==-1){ v[v.size() - 1] = it->second; } else { uint idx = (uint)rint(it->first); //std::cout << "idx: " << idx << " " << it->second <<" " << fromOne <<std::endl; if (fromOne){ if (idx <= v.size() && idx > 0) v[idx - 1] = it->second; } else { if (idx < v.size() && idx >= 0) v[idx] = it->second; } } } return true; } return false; } template < class ValueType > void assembleStiffnessMatrixHomogenDirichletBC(SparseMatrix < ValueType > & S, const IndexArray & nodeID, std::vector < Vector < ValueType > > & rhs){ for (Index i = 0; i < nodeID.size(); i ++){ S.cleanRow(nodeID[i]); S.cleanCol(nodeID[i]); S.setVal(nodeID[i], nodeID[i], 1.0); if (rhs.size() == S.rows()){ for (Index j = 0; j < rhs.size(); j ++) rhs[j][nodeID[i]] = ValueType(0.0); } } } template < class ValueType > void assembleStiffnessMatrixHomogenDirichletBC(SparseMatrix < ValueType > & S, const IndexArray & nodeID){ std::vector < Vector < ValueType > > rhs(0); assembleStiffnessMatrixHomogenDirichletBC(S, nodeID, rhs); } template < class ValueType > void dcfemDomainAssembleStiffnessMatrix(SparseMatrix < ValueType > & S, const Mesh & mesh, const Vector < ValueType > & atts, double k, bool fix){ S.clean(); uint countRho0 = 0, countforcedHomDirichlet = 0; if (!S.valid()) S.buildSparsityPattern(mesh); ElementMatrix < double > Se, Stmp; if (atts.size() != mesh.cellCount()){ throwLengthError(1, WHERE_AM_I + " attribute size missmatch" + toStr(atts.size()) + " != " + toStr(mesh.cellCount())); } ValueType rho = 0.0; Stopwatch swatch(true); unsigned long sCount = 0; for (uint i = 0; i < mesh.cellCount(); i++){ rho = atts[mesh.cell(i).id()]; //** rho == 0.0 may happen while secondary field assemblation if (GIMLI::abs(rho) > TOLERANCE){ if (k > 0.0){ // Stmp = Se.u2(mesh.cell(i)); // Stmp *= k * k; // Stmp += Se.ux2uy2uz2(mesh.cell(i)); Stopwatch s(true); Se.u2(mesh.cell(i)); sCount += s.cycleCounter().toc(); Se *= k * k; Se += Stmp.ux2uy2uz2(mesh.cell(i)); } else { Se.ux2uy2uz2(mesh.cell(i)); } S.add(Se, 1./rho); // Se *= 1.0 / rho; // S += Se; } else { //std::cout << WHERE_AM_I << " " << rho << std::endl; } if (rho < ValueType(0.0) && fix) countRho0++; } //std::cout << "assemble time: " << swatch.cycleCounter().toc() << " " << sCount << " " << swatch.duration() << std::endl; if (fix){ IndexArray fixSingNodesID; for (uint i = 0; i < S.size(); i ++){ if (::fabs(S.getVal(i, i) < TOLERANCE)) { fixSingNodesID.push_back(i); countforcedHomDirichlet++; } } assembleStiffnessMatrixHomogenDirichletBC(S, fixSingNodesID); } if (countRho0){ std::cout << WHERE_AM_I << " WARNING! " << countRho0 << " cells with rho <= 0.0 found." << std::endl; } if (countforcedHomDirichlet++){ std::cout << WHERE_AM_I << " WARNING! " << countforcedHomDirichlet << " nodes forced to homogen dirichlet to fix singularity of stiffness matrix" << std::endl; } } void dcfemDomainAssembleStiffnessMatrix(RSparseMatrix & S, const Mesh & mesh, double k, bool fix){ dcfemDomainAssembleStiffnessMatrix(S, mesh, mesh.cellAttributes(), k, fix); } void dcfemDomainAssembleStiffnessMatrix(CSparseMatrix & S, const Mesh & mesh, double k, bool fix){ dcfemDomainAssembleStiffnessMatrix(S, mesh, getComplexResistivities(mesh), k, fix); } template < class ValueType > void dcfemBoundaryAssembleStiffnessMatrix(SparseMatrix < ValueType > & S, const Mesh & mesh, const Vector < ValueType > & atts, const RVector3 & source, double k){ ElementMatrix < double > Se; std::set < Node * > homDirNodes; for (Index i = 0, imax = mesh.boundaryCount(); i < imax; i++){ int marker = mesh.boundary(i).marker(); if (marker < 0){ switch (marker){ case MARKER_BOUND_HOMOGEN_NEUMANN: break; case MARKER_BOUND_MIXED:{ ValueType rho(0.0); Cell * cell = mesh.boundary(i).leftCell(); if (!cell) cell = mesh.boundary(i).rightCell(); if (!cell) cell = findCommonCell(mesh.boundary(i).shape().nodes()); if (cell) { // rho = cell->attribute(); rho = atts[cell->id()]; //rho = 1.0; } else { mesh.exportVTK("FailBC"); mesh.save("FailBC"); throwError(1, " no cell found for boundary. can't determine mixed boundary conditions. See FailBC exports." + str(i)); } if (GIMLI::abs(rho) < TOLERANCE){ std::cerr << WHERE_AM_I << " parameter rho == 0.0 found " << rho << std::endl; } Se.u2(mesh.boundary(i)); S.add(Se, (mixedBoundaryCondition(mesh.boundary(i), source, k) / rho)); //Se *= (mixedBoundaryCondition(mesh.boundary(i), source, k) / rho); // S += Se; } break; case MARKER_BOUND_HOMOGEN_DIRICHLET: for (Index n = 0; n < mesh.boundary(i).nodeCount(); n ++){ homDirNodes.insert(&mesh.boundary(i).node(n)); } break; case MARKER_BOUND_DIRICHLET: THROW_TO_IMPL; break; default: // std::cerr << WHERE_AM_I << " boundary condition for marker " << marker << " not //defined." << std::endl; break; } } } IndexArray vecHomDirNodes; for (std::set< Node * >::iterator it = homDirNodes.begin(); it != homDirNodes.end(); it ++){ vecHomDirNodes.push_back((*it)->id()); } assembleStiffnessMatrixHomogenDirichletBC(S, vecHomDirNodes); } void dcfemBoundaryAssembleStiffnessMatrix(RSparseMatrix & S, const Mesh & mesh, const RVector3 & source, double k){ dcfemBoundaryAssembleStiffnessMatrix(S, mesh, mesh.cellAttributes(), source, k); } void dcfemBoundaryAssembleStiffnessMatrix(CSparseMatrix & S, const Mesh & mesh, const RVector3 & source, double k){ dcfemBoundaryAssembleStiffnessMatrix(S, mesh, getComplexResistivities(mesh), source, k); } void assembleCompleteElectrodeModel_(RSparseMatrix & S, const std::vector < ElectrodeShape * > & elecs, uint oldMatSize, bool lastIsReferenz, const RVector & contactImpedances){ RSparseMapMatrix mapS(S); ElementMatrix < double > Se; uint nElectrodes = elecs.size(); mapS.setRows(oldMatSize + nElectrodes); mapS.setCols(oldMatSize + nElectrodes); // RVector vContactImpedance( nElectrodes, 1.0); // Ohm * m^2 // bool hasImp = checkIfMapFileExistAndLoadToVector("contactImpedance.map", vContactImpedance); bool hasImp = true; RVector vContactResistance(nElectrodes, 1.0); // Ohm bool hasRes = checkIfMapFileExistAndLoadToVector("contactResistance.map", vContactResistance); for (uint elecID = 0; elecID < nElectrodes; elecID ++){ //** some scale value, can used for contact impedance double sumArea = elecs[elecID]->domainSize(); uint mat_ID = oldMatSize + elecID; // __MS(elecID) // __MS(sumArea) // __MS(elecs[elecID]) elecs[elecID]->setMID(mat_ID); double contactResistance = vContactResistance[elecID]; double contactImpedance = contactImpedances[elecID]; std::vector < MeshEntity * > electrodeEnts(elecs[elecID]->entities()); if (hasImp || hasRes){ if (sumArea < TOLERANCE){ //** point electrode contactImpedance = 1.0; sumArea = 1.0; } else { if (hasRes) contactImpedance = contactResistance * sumArea; else if (hasImp) contactResistance = contactImpedance / sumArea; } if (sumArea != 1.0){ std::cout << "Electrode " << elecs[elecID]->id() << " Contact- resistance: "<< contactResistance << " Ohm" << " - impedance: " << contactImpedance << " Ohm m^2" << " - area: " << sumArea << " m^2" << std::endl; } } //std::cout << "electrode facet contact impedance: " << contactImpedance << std::endl; for (uint j = 0; j < electrodeEnts.size(); j ++){ Se.u(*electrodeEnts[j]); if (lastIsReferenz && elecID == nElectrodes - 1){ Se /= contactImpedance; } else { Se /= -contactImpedance; } //** C mapS.addToCol(mat_ID, Se); //** C' mapS.addToRow(mat_ID, Se); // std::cout << Se<< std::endl; //if (::fabs(contactImpedance - 1.0) > TOLERANCE){ //** B += Se.u2(*electrodeEnts[j]); Se /= contactImpedance; mapS += Se; // } else { // std::cout << " cem: without contactImpedance " << std::endl; // } } // for each: electrode entity //** G if (lastIsReferenz){ throwError(1, "CEM with lastIsReferenz is currently not supported. Please add Reference Electrode"); //**!! this leads to nonpositive definite S .. pls check if (elecID != nElectrodes- 1){ std::cout << " cem: last is reference" << std::endl; uint refID = oldMatSize + nElectrodes -1; mapS[refID][mat_ID] = sumArea / contactImpedance; mapS[mat_ID][refID] = sumArea / contactImpedance; mapS[refID][refID] = 2.0 * sumArea / contactImpedance; mapS[mat_ID][mat_ID] = 2.0 * sumArea / contactImpedance; } } else { if (::fabs(sumArea) < TOLERANCE){ //** asuming node electrode mapS[mat_ID][mat_ID] = 1.0; } else { mapS[mat_ID][mat_ID] = sumArea / contactImpedance; } } } // for each: electrode S = mapS; } void assembleCompleteElectrodeModel(RSparseMatrix & S, const std::vector < ElectrodeShape * > & elecs, uint oldMatSize, bool lastIsReferenz, const RVector & contactImpedances){ assembleCompleteElectrodeModel_(S, elecs, oldMatSize, lastIsReferenz, contactImpedances); } void assembleCompleteElectrodeModel(CSparseMatrix & S, const std::vector < ElectrodeShape * > & elecs, uint oldMatSize, bool lastIsReferenz, const RVector & contactImpedances){ THROW_TO_IMPL } double mixedBoundaryCondition(const Boundary & boundary, const RVector3 & source, double k){ if (!source.valid()){ std::cerr << WHERE_AM_I << " no valid source found " << std::endl; return 0.0; } double mirrorPlaneZ = 0.0; RVector3 sourceMir(source); uint dim = 3; if (k > 0) dim = 2; sourceMir[dim - 1] = 2.0 * mirrorPlaneZ - source[dim - 1]; RVector3 facetPos(boundary.center()); RVector3 norm(boundary.norm()); RVector3 r(source - facetPos); RVector3 rMir(sourceMir - facetPos); double rAbs = r.abs(), rMirAbs = rMir.abs(); // std::cout << " S: " << source << " S': " << sourceMir // << " F: " << facetPos << " B: " << boundary.node(0) << " " << boundary.node(1) << " n: " << norm // << " r: " << r<< " r'" << rMir << std::endl; double result = 0.0; enum spaceConfig{HALFSPACE,FULLSPACE,MIRRORSOURCE} config = MIRRORSOURCE; if (k == 0){ // 3D result = ((rMirAbs * rMirAbs) * std::fabs(r.dot(norm)) / rAbs + (rAbs * rAbs) * std::fabs(rMir.dot(norm)) / rMirAbs) / (rMirAbs * rAbs * (rAbs + rMirAbs)); //(|r'|² * |r * n| / |r| + |r|² * |r' * n| / |r'|) / (|r'|*|r|* (|r|+|r'|)) // switch(config){ // case HALFSPACE: // result =::fabs(r.scalar(norm)) / (rAbs * rAbs); // break; // case FULLSPACE: TO_IMPL break; // case MIRRORSOURCE: // nach Bing & Greenhalgh // cout << alpha << std::endl; // break; // default: // std::cerr << WHERE_AM_I << " Warning SpaceConfigEnum = " << config << std::endl; // break; // } } else { // 2.5D switch(config){ case HALFSPACE: if (std::fabs(besselK0(rAbs * k)) < 1e-40) return 0.0; result = k * std::fabs(r.dot(norm)) / rAbs * besselK1(rAbs * k) / besselK0(rAbs * k); break; case FULLSPACE: if (std::fabs(besselK0(rAbs * k)) < 1e-40) return 0.0; //ca: is there missing factor 2?????????? result = k * std::fabs(r.dot(norm)) / rAbs * besselK1(rAbs * k) / besselK0(rAbs * k); break; case MIRRORSOURCE: if ((::fabs(besselK0(rAbs * k)) < TOLERANCE) || (::fabs(besselK0(rMirAbs * k)) < TOLERANCE)) return 0.0; result = k * (::fabs(r.dot(norm)) / rAbs * besselK1(rAbs * k) + ::fabs(rMir.dot(norm)) / rMirAbs * besselK1(rMirAbs * k)) / (besselK0(rAbs * k) + besselK0(rMirAbs * k)); break; } } if (std::isnan(result) || std::isinf(result) || std::fabs(result) < TOLERANCE){ std::cerr << WHERE_AM_I << " Warning " << result << std::endl; std::cerr << "Source: " << source << std::endl; std::cerr << "n: " << norm << std::endl; std::cerr << "r: " << r << " rMir " << rMir << std::endl; std::cerr << "besselK1(rAbs * k) " << besselK1(rAbs * k) << " k " << k << std::endl; std::cerr << "rMirAbs " << rMirAbs << " rAbs " << rAbs << std::endl; } return result; } DCMultiElectrodeModelling::DCMultiElectrodeModelling(bool verbose) : ModellingBase(verbose) { init_(); } DCMultiElectrodeModelling::DCMultiElectrodeModelling(Mesh & mesh, bool verbose) : ModellingBase(verbose) { init_(); setMesh(mesh); } DCMultiElectrodeModelling::DCMultiElectrodeModelling(DataContainerERT & dataContainer, bool verbose) : ModellingBase(dataContainer, verbose){ init_(); } DCMultiElectrodeModelling::DCMultiElectrodeModelling(Mesh & mesh, DataContainerERT & dataContainer, bool verbose) : ModellingBase(dataContainer, verbose){ init_(); setMesh(mesh); } DCMultiElectrodeModelling::~DCMultiElectrodeModelling(){ if (subSolutions_ && subpotOwner_) { delete subSolutions_; } if (electrodeRef_ && electrodeRef_ != electrodes_.back()){ delete electrodeRef_; } if (primDataMap_) delete primDataMap_; for_each(electrodes_.begin(), electrodes_.end(), deletePtr()); } void DCMultiElectrodeModelling::init_(){ analytical_ = false; topography_ = false; neumannDomain_ = true; lastIsReferenz_ = false; complex_ = false; setSingValue_ = true; subpotOwner_ = false; subSolutions_ = NULL; electrodeRef_ = NULL; JIsRMatrix_ = true; buildCompleteElectrodeModel_ = false; dipoleCurrentPattern_ = false; primDataMap_ = new DataMap(); byPassFile_ = "bypass.map"; Index nThreads = getEnvironment("BERTTHREADS", 0, verbose_); nThreads = getEnvironment("BERT_NUM_THREADS", 0, verbose_); if (nThreads > 0) setThreadCount(nThreads); } void DCMultiElectrodeModelling::setComplex(bool c) { if (complex_ != c){ if (subSolutions_ && subpotOwner_) { delete subSolutions_; subSolutions_ = 0; } complex_=c; } } DataContainerERT & DCMultiElectrodeModelling::dataContainer() const{ return dynamic_cast < DataContainerERT & >(*dataContainer_); } void DCMultiElectrodeModelling::deleteMeshDependency_(){ for_each(electrodes_.begin(), electrodes_.end(), deletePtr()); electrodes_.clear(); electrodeRef_ = NULL; } void DCMultiElectrodeModelling::assembleStiffnessMatrixDCFEMByPass(RSparseMatrix & S){ assembleStiffnessMatrixDCFEMByPass_(S); } void DCMultiElectrodeModelling::assembleStiffnessMatrixDCFEMByPass(CSparseMatrix & S){ //assembleStiffnessMatrixDCFEMByPass_(S); } template < class ValueType > void DCMultiElectrodeModelling::assembleStiffnessMatrixDCFEMByPass_(SparseMatrix < ValueType > & _S){ std::vector < std::pair< Index, Index> > byPassPair; std::vector < std::pair< Index, Index> > byPassNodesPair; std::vector < double > resistance; std::vector < double > resistanceNode; std::vector < std::string > row; if (fileExist(byPassFile_)){ if (verbose_) std::cout << byPassFile_ << " found in working path. Applying them." << std::endl; std::fstream file; openInFile(byPassFile_, &file, true); // Check bypass File while(!file.eof()) { row = getNonEmptyRow(file); if (row.size() == 3){ Index eK1idx = toInt(row[0]); Index eK2idx = toInt(row[1]); double resis = toFloat(row[2]); Index a1 = 0, a2 = 0; if (eK1idx < 1){ std::cerr << WHERE_AM_I << " bypass electrode unknown: " << eK1idx << " please choose electrode indices from 1. Ignoring." << std::endl; continue; } if (eK1idx < electrodes_.size()) { a1 = electrodes_[eK1idx - 1]->mID(); } else { std::cerr << WHERE_AM_I << " bypass electrode unknown " << eK1idx << " e-size = " << electrodes_.size() << " Ignoring."<< std::endl; continue; } if (eK1idx < electrodes_.size()) { a2 = electrodes_[eK2idx - 1]->mID(); } else { std::cerr << WHERE_AM_I << " bypass electrode unknown " << eK1idx << " e-size = " << electrodes_.size() << " Ignoring."<< std::endl; continue; } if (a1 < 0 || a2 < 0){ std::cerr << WHERE_AM_I << " bypass dofID unknown " << a1 << " " << a2 << " Ignoring."<< std::endl; continue; } byPassNodesPair.push_back(std::pair< Index, Index>(a1, a2)); resistanceNode.push_back(resis); } else if (row.size() == 2){ int nodeMarker = toInt(row[0]); double resis = toFloat(row[1]); IndexArray nodesIDX(mesh_->findNodesIdxByMarker(nodeMarker)); if (nodesIDX.size()){ for (Index i=0; i < nodesIDX.size()-1; i ++ ){ byPassNodesPair.push_back(std::pair< Index, Index>(nodesIDX[i], nodesIDX[i+1])); resistanceNode.push_back(resis); } } else { std::cerr << WHERE_AM_I << " Warning! cannot requested node marker ("+str(nodeMarker)+") for bypass.map.\n" << "Expect either: \n int(ElectrodeID) int(ElectrodeID) double(resistance)\n or \n"<< "int(NodeMarker) double(resistance)" << row.size() << std::endl; } } else if (row.size() > 0){ std::cerr << WHERE_AM_I << " Warning! Wrong format for bypass.map.\n" << "Expect either: \n int(ElectrodeID) int(ElectrodeID) double(resistance)\n or \n"<< "int(NodeMarker) double(resistance)" << row.size() << std::endl; } } // while file file.close(); } // if file can be read //## looking for CEM nodes if (bypassNodeIdx_.size()){ std::map < float, float > rMap; if (fileExist("electrodeBypassResistances.map")){ rMap = loadFloatMap("electrodeBypassResistances.map"); } for (Index j = 0; j < bypassNodeIdx_.size(); j ++){ int marker = bypassNodeIdx_[j]; IndexArray nodesIDX(mesh_->findNodesIdxByMarker(marker)); for (Index i = 0; i < nodesIDX.size()-1; i ++){ byPassNodesPair.push_back(std::pair< Index, Index>(nodesIDX[i], nodesIDX[i+1])); if (rMap.count(float(marker))){ resistanceNode.push_back(rMap[float(marker)]); } else { resistanceNode.push_back(1e-6); } } } } RSparseMapMatrix S(_S); for (Index i = 0; i < byPassNodesPair.size(); i ++){ Index a1 = byPassNodesPair[i].first; Index a2 = byPassNodesPair[i].second; if (verbose_) std::cout << "Bypass nodes: " << a1 << "-" << a2 << " with resistance: " << resistanceNode[i] << std::endl; double val = 1.0 / resistanceNode[i]; S[a1][a1] += val; S[a2][a2] += val; S[a1][a2] -= val; S[a2][a1] -= val; } _S = S; } void DCMultiElectrodeModelling::updateMeshDependency_(){ if (subSolutions_) subSolutions_->clear(); for_each(electrodes_.begin(), electrodes_.end(), deletePtr()); electrodes_.clear(); electrodeRef_ = NULL; //** Try to analyse the geometrie, check for topography and looking // for surface Z-Koordinate topography_ = false; neumannDomain_ = true; surfaceZ_ = -MAX_DOUBLE; bool init = false; for (Index i = 0; i < mesh_->boundaryCount(); i++){ if (mesh_->boundary(i).marker() == MARKER_BOUND_MIXED || mesh_->boundary(i).marker() == MARKER_BOUND_HOMOGEN_DIRICHLET || mesh_->boundary(i).marker() == MARKER_BOUND_DIRICHLET){ neumannDomain_ = false; } if (mesh_->boundary(i).marker() == MARKER_BOUND_HOMOGEN_NEUMANN && !topography_){ if (init == false) { surfaceZ_ = mesh_->boundary(i).center()[mesh_->dim() -1]; init = true; } else { if (mesh_->boundary(i).center()[mesh_->dim() -1] != surfaceZ_){ if (verbose_) { std::cout << "Found topography for surface=" << surfaceZ_ << " : " << mesh_->boundary(i).center()[mesh_->dim() -1] << std::endl; } topography_ = true; } } } } if (neumannDomain_) { if (verbose_) { std::cout << "Found neumann domain. Setting topography=1." << std::endl; } topography_ = true; } //** when we calculate 2,5D we never have neumannDomain if (mesh_->dim() == 2){ if (neumannDomain_){ neumannDomain_ = false; if (verbose_) { std::cout << "Found neumann domain. but 2.5D -> neumann: false" << std::endl; } } } // mesh_->exportBoundaryVTU("meshBound"); if (mesh_->haveData("AttributeReal") && mesh_->haveData("AttributeImag")){ this->setComplex(true); } //## new mesh but old data .. so we need search electrodes again searchElectrodes_(); } void DCMultiElectrodeModelling::updateDataDependency_(){ if (subSolutions_) subSolutions_->clear(); for_each(electrodes_.begin(), electrodes_.end(), deletePtr()); electrodes_.clear(); electrodeRef_ = NULL; if (mesh_) searchElectrodes_(); } void DCMultiElectrodeModelling::setContactImpedances(const RVector & zi){ vContactImpedance_ = zi; } void DCMultiElectrodeModelling::searchElectrodes_(){ if (!mesh_){ throwError(1, "DCMultiElectrodeModelling::searchElectrodes_() have no mesh defined"); } if (electrodes_.size() > 0) return; passiveCEM_.clear(); //** step 1 search the mesh for signs of electrodes std::vector < Index > sourceIdx = mesh_->findNodesIdxByMarker(MARKER_NODE_ELECTRODE); IndexArray refSourceIdx = mesh_->findNodesIdxByMarker(MARKER_NODE_REFERENCEELECTRODE); calibrationSourceIdx_ = mesh_->findNodesIdxByMarker(MARKER_NODE_CALIBRATION); //** looking for CEM-boundaries std::map< int, std::vector< MeshEntity * > > electrodeFaces; for (Index i = 0, imax = mesh_->boundaryCount(); i < imax; i++){ int marker = mesh_->boundary(i).marker(); if (marker <= MARKER_BOUND_ELECTRODE + 1){ // +1 since -9999 is passive body electrodeFaces[MARKER_BOUND_ELECTRODE - marker].push_back(&mesh_->boundary(i)); } } //** looking for CEM-cells for (Index i = 0, imax = mesh_->cellCount(); i < imax; i++){ int marker = mesh_->cell(i).marker(); if (marker <= MARKER_BOUND_ELECTRODE and marker > MARKER_FIXEDVALUE_REGION){ electrodeFaces[MARKER_BOUND_ELECTRODE - marker].push_back(&mesh_->cell(i)); } } //** looking for CEM-nodes (bypass) std::map< int, std::vector< Node * > > bypassNodes; for (Index i = 0, imax = mesh_->nodeCount(); i < imax; i++){ int marker = mesh_->node(i).marker(); // no nails. either CEM faces OR CEM bypass nodes if (marker <= MARKER_BOUND_ELECTRODE && !electrodeFaces.count(MARKER_BOUND_ELECTRODE - marker)){ if (!bypassNodes.count(MARKER_BOUND_ELECTRODE - marker)) { bypassNodeIdx_.push_back(marker); } bypassNodes[MARKER_BOUND_ELECTRODE - marker].push_back(&mesh_->node(i)); } } std::list < ElectrodeShape * > cemElectrodes; std::list < ElectrodeShape * > passiveCEMBodies; for (std::map< int, std::vector< MeshEntity * > >::iterator it = electrodeFaces.begin(); it != electrodeFaces.end(); it ++){ if (it->first >= 0){ cemElectrodes.push_back(new ElectrodeShapeDomain(it->second)); cemElectrodes.back()->setId(it->first); } else { passiveCEMBodies.push_back(new ElectrodeShapeDomain(it->second)); } //** transform to start with electrode-id == 0; } Index nodeECounter = 0, nodeBCounter = 0, freeECounter = 0; Index cemECounter = 0, passiveCEMbodyCounter = 0; if (dataContainer_){ //!!** match the known electrode to list of electrodes from the datacontainer R3Vector ePos(dataContainer_->sensorPositions()); //!!** For 2d-problems we have to check if xy or xz coordinates are given //!!** only xy is valid so it is necessary to swap the coordinates if (mesh_->dim() == 2){ if ((zVari(ePos) || max(abs(z(ePos))) > 0) && (!yVari(ePos) && max(abs(y(ePos))) < 1e-8)){ if (verbose_) std::cout << "Warning! swap YZ coordinates for sensor positions to meet mesh dimensions." << std::endl; swapYZ(ePos); } } for (uint i = 0; i < ePos.size(); i ++){ bool match = false; //** match the known CEM-electrodes for (std::list< ElectrodeShape * >::iterator it = cemElectrodes.begin(); it != cemElectrodes.end(); it ++){ std::cout << "req.pos:" << ePos[i] << " epos(" << (*it)->id() << "): " << (*it)->pos() << " dist: " << ePos[i].distance((*it)->pos()) << " e-size: " << std::sqrt((*it)->domainSize())*2.0 << std::endl; if (ePos[i].distance((*it)->pos()) < std::sqrt((*it)->domainSize()) * 2.0 || (uint)(*it)->id() == i) { electrodes_.push_back((*it)); electrodes_.back()->setId(i); electrodes_.back()->setPos(ePos[i]); cemElectrodes.erase(it); cemECounter++; match = true; break; } } //** match the known bypass-electrodes if (!match){ for (std::map< int, std::vector< Node * > >::iterator it = bypassNodes.begin(); it != bypassNodes.end(); it ++){ // // std::cout << ePos[i] << " " << mesh_->node(*it).pos() << // // " " << ePos[i].dist(mesh_->node(*it).pos()) << std::endl; if (ePos[i].dist(it->second[0]->pos()) < 0.01){ //CR 1cm?? really?? electrodes_.push_back(new ElectrodeShapeNodesWithBypass(it->second)); electrodes_.back()->setId(i); bypassNodes.erase(it); nodeBCounter++; match = true; break; } } } //** match the known node-electrodes if (!match){ for (std::vector< Index >::iterator it = sourceIdx.begin(); it != sourceIdx.end(); it ++){ // std::cout << ePos[i] << " " << mesh_->node(*it).pos() << // " " << ePos[i].dist(mesh_->node(*it).pos()) << std::endl; if (ePos[i].dist(mesh_->node(*it).pos()) < 0.01){ //CR 1cm?? really?? electrodes_.push_back(new ElectrodeShapeNode(mesh_->node(*it))); electrodes_.back()->setId(i); sourceIdx.erase(it); nodeECounter++; match = true; break; } } } //** fill the missing with node independent electrodes if (!match){ Cell * cell = mesh_->findCell(ePos[i]); if (cell){ electrodes_.push_back(new ElectrodeShapeEntity(*cell, ePos[i])); } else{ electrodes_.push_back(new ElectrodeShape(ePos[i])); std::cerr << WHERE_AM_I << " " << ePos[i] << " mesh " << mesh_->boundingBox() << std::endl; throwError(1, "There is a requested electrode that does not match the given mesh. "); } // std::cout << ePos[i] << std::endl; // std::cout << *cell << std::endl; electrodes_.back()->setId(i); freeECounter++; } } // for all in ePos } else { //** no dataContainer_ //** add all remaining CEM-electrodes for (std::list< ElectrodeShape * >::iterator it = cemElectrodes.begin(); it != cemElectrodes.end(); it ++){ electrodes_.push_back((*it)); //** transform to start with electrode-id == 0; electrodes_.back()->setId(cemECounter); cemECounter++; } //** add all known bypass-electrodes for (std::map< int, std::vector< Node * > >::iterator it = bypassNodes.begin(); it != bypassNodes.end(); it ++){ // // std::cout << ePos[i] << " " << mesh_->node(*it).pos() << // // " " << ePos[i].dist(mesh_->node(*it).pos()) << std::endl; electrodes_.push_back(new ElectrodeShapeNodesWithBypass(it->second)); electrodes_.back()->setId(cemECounter + nodeBCounter); nodeBCounter++; } //** add all remaining electrodes to the calculation for (std::vector < Index >::iterator it = sourceIdx.begin(); it != sourceIdx.end(); it ++){ electrodes_.push_back(new ElectrodeShapeNode(mesh_->node(*it))); electrodes_.back()->setId(nodeECounter + nodeBCounter + cemECounter); nodeECounter++; } } //** add passive cem bodies for (std::list< ElectrodeShape * >::iterator it = passiveCEMBodies.begin(); it != passiveCEMBodies.end(); it ++){ passiveCEM_.push_back((*it)); passiveCEM_.back()->setId(-1); passiveCEMbodyCounter ++; } if (cemECounter > 0 || passiveCEMbodyCounter > 0) buildCompleteElectrodeModel_ = true; if (verbose_) { if (dataContainer_){ std::cout << "Found datafile: " << dataContainer_->sensorCount() << " electrodes" << std::endl; } if (cemECounter) { std::cout << "Found: " << cemECounter << " cem-electrodes" << std::endl; } if (nodeBCounter) { std::cout << "Found: " << nodeBCounter << " bypass-electrodes" << std::endl; } if (nodeECounter) { std::cout << "Found: " << nodeECounter << " node-electrodes" << std::endl; } if (freeECounter) { std::cout << "Found: " << freeECounter << " free-electrodes" << std::endl; } if (passiveCEMbodyCounter) { std::cout << "Found: " << passiveCEMbodyCounter << " passive cem bodies" << std::endl; } } //** Two special cases: //** Just one reference electrode node is possible, if (refSourceIdx.size()) { if (verbose_) std::cout << "Found: " << refSourceIdx.size() << " reference electrode node." << std::endl; electrodeRef_ = new ElectrodeShapeNode(mesh_->node(refSourceIdx[0])); } //** though several calibration point nodes are. if (calibrationSourceIdx_.size()) { if (verbose_) std::cout << "Found: " << calibrationSourceIdx_.size() << " calibration node." << std::endl; } if (electrodes_.size() > 0){ //** looking for source center Position; RVector3 sumPos(0.0, 0.0, 0.0); for (uint i = 0; i < electrodes_.size(); i ++){ if (electrodes_[i]->valid()) sumPos += electrodes_[i]->pos(); } sourceCenterPos_ = sumPos / (double)electrodes_.size(); if (kValues_.empty() || weights_.empty()){ if (dataContainer_){ initKWaveList(*mesh_, kValues_, weights_, dataContainer_->sensorPositions(), verbose_); } else { initKWaveList(*mesh_, kValues_, weights_, verbose_); } } } else { //throwError(1, WHERE_AM_I+ " Warning ! Found neighter electrode nodes nor electrode facets, don't know what to do. "); std::cout << "Warning! Found neighter electrode nodes nor electrode facets, don't know what to do. " << std::endl; } if (neumannDomain_){ if (calibrationSourceIdx_.size() == 0) { std::cout << "Warning! neumann domain without calibration (potential reference) point. " << "This may lead to a non-positive definite matrix. LDL can solve instead of" " CHOLMOD, but better you add VIP with calibration marker " << MARKER_NODE_CALIBRATION << std::endl; std::cout << "Choose first node as calibration node " << std::endl; calibrationSourceIdx_.push_back(0); } if (!electrodeRef_ && !dipoleCurrentPattern_) { if (verbose_) { std::cout << "Found neumann domain without reference electrode. " << std::endl << "Choose last electrode as reference. " << std::endl; } electrodeRef_ = electrodes_.back(); lastIsReferenz_ = true; } } else { // no neumann if (verbose_) std::cout << "Found non-neumann domain" << std::endl; if (calibrationSourceIdx_.size()){ std::cout << "Non-neumann domain conflicts with given calibration point. Ignoring calibration." << std::endl; calibrationSourceIdx_.clear(); } } } RVector DCMultiElectrodeModelling::createDefaultStartModel(){ RVector vec(this->regionManager().parameterCount(), 0.0); if (dataContainer_ != NULL){ vec.fill(median(dataContainer_->get("rhoa"))); } else { std::cerr << WHERE_AM_I << " No datacontainer given. " << std::endl; } return vec; } RVector DCMultiElectrodeModelling::response(const RVector & model, double background){ if (complex()){ // __MS("Pls check response complex scale -1") DataMap dMap(response_(toComplex(model(0, model.size()/2), -model(model.size()/2, model.size())), Complex(background, 0))); RVector respRe(dMap.data(this->dataContainer(), false, false)); RVector respIm(dMap.data(this->dataContainer(), false, true)); CVector resp(toComplex(respRe, respIm) * dataContainer_->get("k")); RVector am(abs(resp)); RVector ph(-angle(resp)); if (verbose_){ std::cout << "Response: min(RE) = " << min(am) << " max(RE) = " << max(am) << " min(IM) = " << min(ph) << " max(IM) = " << max(ph) << std::endl; std::cout << "not yet implemented Reciprocity rms(modelReciprocity) " << std::endl; } return cat(am, ph); } // else no complex here // __MS("nächste Zeile wieder rein TMPHACK**************") if (::fabs(max(model) - min(model)) < TOLERANCE){ return RVector(dataContainer_->size(), min(model)); } DataMap dMap(response_(model, background)); RVector resp(dMap.data(this->dataContainer())); RVector respRez(dMap.data(this->dataContainer(), true)); if (resp.size() != dataContainer_->size() || respRez.size() != dataContainer_->size()){ throwError(1, WHERE_AM_I + " size wrong: " + str(dataContainer_->size()) + " " + str(resp.size()) + " " + str(respRez.size())); } if (std::fabs(min(dataContainer_->get("k"))) < TOLERANCE){ if (!(this->topography() || buildCompleteElectrodeModel_)){ dataContainer_->set("k", this->calcGeometricFactor(this->dataContainer())); if (verbose_) { std::cout << " data contains no K-factors but we find them " " analytical for the response call" << std::endl; } } else { throwError(1, WHERE_AM_I + " data contains no K-factors "); } } resp *= dataContainer_->get("k"); respRez *= dataContainer_->get("k"); RVector modelReciprocity((resp - respRez) / (resp + respRez) * 2.0); if (verbose_){ if (min(resp) < 0 && 1){ std::cout << "Found neg. resp, save and abort." << std::endl; for (uint i = 0; i < resp.size(); i ++){ if (resp[i ] < 0) { int a = (*dataContainer_)("a")[i]; int b = (*dataContainer_)("b")[i]; int m = (*dataContainer_)("m")[i]; int n = (*dataContainer_)("n")[i]; RVector ab(mesh_->nodeCount(), 0.0), mn(mesh_->nodeCount(), 0.0); if (a != -1) ab = solutions_[a]; if (b != -1) ab -= solutions_[b]; if (m != -1) mn = solutions_[m]; if (n != -1) mn -= solutions_[n]; std::cout << i << " " << resp[i] << " " << respRez[i]<< std::endl; std::cout << a << " " << b << " " << m << " " << n << std::endl; mesh_->addExportData("ab-pot", prepExportPotentialData(ab)); mesh_->addExportData("mn-pot", prepExportPotentialData(mn)); //mesh_->addExportData("sens-mn-pot", prepExportSensitivityData(jacobian)); mesh_->exportVTK("negResp"); break; //std::cout << (*dataContainer_)[i] << std::endl; } } //std::cout << find(resp < 0) << std::endl; mesh_->save("negResp"); save(mesh_->cellAttributes(), "negResp-Atts"); save(resp, "resp.vec"); save(respRez, "respRez.vec"); // throwError(1, WHERE_AM_I); } // if found neg. Responses std::cout << "Response: min = " << min(resp) << " max = " << max(resp) << std::endl; std::cout << "Reciprocity rms(modelReciprocity) " << rms(modelReciprocity) * 100.0 << "%, " << "max: " << max(modelReciprocity) * 100.0 << "%" << std::endl; // std::cout << "Reciprocity sum = " << sum(modelReciprocity) << std::endl; // std::cout << 13 << " " << resp[13] << " " << respRez[13] << std::endl; } return sqrt(abs(resp * respRez)); } void DCMultiElectrodeModelling::mapERTModel(const CVector & model, Complex background){ if (model.size() == this->mesh_->cellCount()){ setComplexResistivities(*mesh_, model); } else { mapModel(real(model), real(background)); RVector re(mesh_->cellAttributes()); mapModel(imag(model), imag(background)); RVector im(mesh_->cellAttributes()); setComplexResistivities(*mesh_, toComplex(re, im)); } } void DCMultiElectrodeModelling::mapERTModel(const RVector & model, double background){ if (model.size() == this->mesh_->cellCount()){ this->mesh_->setCellAttributes(model); } else { mapModel(model, background); } } template < class ValueType > DataMap DCMultiElectrodeModelling::response_(const Vector < ValueType > & model, ValueType background){ if (verbose_) std::cout << "Calculating response for model: min = " << min(model) << " max = " << max(model) << std::endl; DataMap dMap; this->mapERTModel(model, background); if (dataContainer_ != NULL){ if (min(model) < TOLERANCE) { model.save("modelFail.vector"); throwError(EXIT_FEM_NO_RHO, WHERE_AM_I + " response for model with negative or zero resistivity is not defined."); } if (GIMLI::abs(max(model)) < TOLERANCE && GIMLI::abs(min(model)) < TOLERANCE) { throwError(EXIT_FEM_NO_RHO, WHERE_AM_I); } if (dipoleCurrentPattern_){ THROW_TO_IMPL calculate(this->dataContainer(), false); // resp = dataContainer_->get("u"); //*** No reciprocity for dipole-current pattern. } else { calculate(dMap); } } else { throwError(1, WHERE_AM_I + " no response without data container"); } return dMap; } template < class ValueType > Matrix < ValueType > * DCMultiElectrodeModelling::prepareJacobianT_(const Vector< ValueType > & model){ //TIC__ this->searchElectrodes_(); if (dataContainer_){ if (!subSolutions_){ if (verbose_) { std::cout << "Creating new subpotentials for createJacobian." << std::endl; } subpotOwner_ = true; subSolutions_ = new Matrix< ValueType >; } else { if (verbose_) { std::cout << "Using existing subpotentials for createJacobian." << std::endl; } } Matrix< ValueType > *u = NULL; u = dynamic_cast< Matrix< ValueType > * >(subSolutions_); if (u->rows() == 0){ if (verbose_) { std::cout << "Subpotentials matrix is empty." << std::endl; } // // std::cout << WHERE_AM_I << " " << mean(model) << " " << model.size() << std::endl; //__MS(toc__) this->mapERTModel(model, ValueType(-1.0)); // very slow //__MS(toc__) bool oldAna = this->analytical(); this->setAnalytical(!(this->topography() || buildCompleteElectrodeModel_ || stdDev(model) > TOLERANCE*1e5)); if (verbose_) { std::cout << "Calculating subpotentials analytical for createJacobian: " << this->analytical() << " (" << "top: " << this->topography() << "|" << "cem: " << buildCompleteElectrodeModel_ << "|" << "het: " << bool(stdDev(model) > TOLERANCE*1e5) << ")" << std::endl; } //__MS(toc__) //** first geometric factors .. since this will overwrite u if (!dataContainer_->allNonZero("k")){ dataContainer_->set("k", this->calcGeometricFactor(this->dataContainer(), model.size())); } DataContainerERT tmp(this->dataContainer()); // __MS(toc__) this->calculate(tmp); // __MS(toc__) /*! We have to scale subSolutions_ for the analytical solution to match the model */ if (this->analytical()){ if (verbose_) std::cout << "Scale subpotentials with " << model[0] << std::endl; for (uint i = 0, imax = u->rows(); i < imax; i ++) { (*u)[i] *= model[0]; } } this->setAnalytical(oldAna); } // if u.rows() return u; } else { throwError(1, WHERE_AM_I + " no data structure given"); } return 0; } RMatrix * DCMultiElectrodeModelling::prepareJacobian_(const RVector & model){ return prepareJacobianT_(model); } CMatrix * DCMultiElectrodeModelling::prepareJacobian_(const CVector & model){ return prepareJacobianT_(model); } void DCMultiElectrodeModelling::createJacobian_(const RVector & model, const RMatrix & u, RMatrix * J){ std::vector < std::pair < Index, Index > > matrixClusterIds; MEMINFO // save(*u, "pots.bmat"); createSensitivityCol(*J, *mesh_, this->dataContainer(), u, weights_, kValues_, matrixClusterIds, nThreads_, verbose_); MEMINFO double sensMatDropTol = getEnvironment("BERT_SENSMATDROPTOL", 0.0, verbose_); RSparseMapMatrix * Jsparse = 0; if (matrixClusterIds.size() > 0){ // just test clustering here Index nData = matrixClusterIds[0].first; Index nModel = matrixClusterIds[0].second; if (sensMatDropTol > 0.0){ // breaks possible blockmatrix sizes if (complex_) {THROW_TO_IMPL } delete jacobian_; MEMINFO jacobian_ = new RSparseMapMatrix(nData, nModel); Jsparse = dynamic_cast< RSparseMapMatrix * >(jacobian_); } else { J->resize(nData, nModel); } for (uint c = 1; c < matrixClusterIds.size(); c ++){ MEMINFO Index start = matrixClusterIds[c].first; Index end = matrixClusterIds[c].second; if (Jsparse){ Jsparse->importCol("sensPart_" + str(start) + "-" + str(end) + ".bmat", sensMatDropTol, start); } else { // no drop tol RMatrix Jcluster("sensPart_" + str(start) + "-" + str(end)); for (Index i = 0; i < J->rows(); i ++){ (*J)[i].setVal(Jcluster[i], start, end); } } MEMINFO } // for each clustering } // if clustering MEMINFO if (!Jsparse){ if (model.size() == J->cols()){ RVector m2(model*model); if (model.size() == J->cols()){ for (uint i = 0; i < J->rows(); i ++) { (*J)[i] /= (m2 / dataContainer_->get("k")[i]); } } } if (verbose_){ RVector sumsens(J->rows()); for (Index i = 0, imax = J->rows(); i < imax; i ++){ sumsens[i] = sum((*J)[i]); } std::cout << "sens sum: median = " << median(sumsens) << " min = " << min(sumsens) << " max = " << max(sumsens) << std::endl; } } else { for (RSparseMapMatrix::iterator it = Jsparse->begin(); it != Jsparse->end(); it ++){ Index row = (*it).first.first; Index col = (*it).first.second; (*it).second /= (model[col] * model[col]) / dataContainer_->get("k")[row]; } if (verbose_){ std::cout << "S sparsity: " << ((double)Jsparse->nVals() / (Jsparse->rows() * Jsparse->cols())) * 100.0 << "% " << std::endl; } } } void DCMultiElectrodeModelling::createJacobian_(const CVector & model, const CMatrix & u, CMatrix * J){ std::vector < std::pair < Index, Index > > matrixClusterIds; createSensitivityCol(*J, *this->mesh_, this->dataContainer(), u, this->weights_, this->kValues_, matrixClusterIds, this->nThreads_, this->verbose_); } void DCMultiElectrodeModelling::createJacobian(const RVector & model){ if (complex_){ CMatrix * u = prepareJacobianT_(toComplex(model(0, model.size()/2), model(model.size()/2, model.size()))); THROW_TO_IMPL } else { RMatrix * u = prepareJacobianT_(model); if (!JIsRMatrix_){ delete jacobian_; jacobian_ = new RMatrix(); JIsRMatrix_ = true; } RMatrix * J = dynamic_cast< RMatrix * >(jacobian_); createJacobian_(model, *u, J); } } void DCMultiElectrodeModelling::createConstraints(){ ModellingBase::createConstraints(); } void DCMultiElectrodeModelling::createCurrentPattern(std::vector < ElectrodeShape * > & eA, std::vector < ElectrodeShape * > & eB, bool reciprocity){ this->searchElectrodes_(); int nElecs = (int)electrodes_.size(); if (dipoleCurrentPattern_){ //** this is only useful for the forward calculation since the reciprocity potentials are needed for sensitivity calculation. if (dataContainer_){ //** reciprocity disabled std::set < Index > inject(this->dataContainer().currentPattern(false)); if (verbose_) std::cout << "Found " << inject.size() << " dipole-current pattern" << std::endl; eA.resize(inject.size(), NULL); eB.resize(inject.size(), NULL); CurrentPattern cp; uint i = 0; for (std::set < Index >::iterator it = inject.begin(); it != inject.end(); it ++, i++){ currentPatternIdxMap_[(*it)] = i; cp = this->dataContainer().currentPatternToElectrode((*it)); if (cp.first < nElecs && cp.second < nElecs){ //std::cout << cp.first << " " << cp.second << std::endl; if (cp.first > -1) eA[i] = electrodes_[cp.first]; if (cp.second > -1) eB[i] = electrodes_[cp.second]; } else { std::cerr << WHERE_AM_I << " requested electrode a = " << cp.first << " or b = " << cp.second << " do not exist." << std::endl; } } } else { std::cerr << WHERE_AM_I << " no data structure given" << std::endl; } } else { // simple pol or dipole with reference node for (int i = 0; i < nElecs; i ++){ if (electrodes_[i] != electrodeRef_ && electrodes_[i]->id() > -1){ eA.push_back(electrodes_[i]); eB.push_back(electrodeRef_); } } } } RVector DCMultiElectrodeModelling::calcGeometricFactor(const DataContainerERT & data, Index nModel){ if (verbose_) std::cout << "Obtaining geometric factors"; if (!this->topography() && !buildCompleteElectrodeModel_) { if (verbose_) std::cout << " (analytical)" << std::endl; return geometricFactors(data, mesh_->dimension(), false); } if (electrodes_.size() == 0){ this->searchElectrodes_(); } if (primDataMap_->electrodes().size() != electrodes_.size()){ if (verbose_) std::cout << " (numerical)" << std::endl; RVector atts(mesh_->cellAttributes()); if (nModel > 0) { this->mapERTModel(RVector(nModel, 1.0), -1.0); } else { mesh_->setCellAttributes(RVector(mesh_->cellCount(), 1.0)); } this->calculate(*primDataMap_); mesh_->setCellAttributes(atts); } else { if (verbose_) std::cout << " (recover)" << std::endl; THROW_TO_IMPL } return 1.0 / (primDataMap_->data(data) + TOLERANCE); } void DCMultiElectrodeModelling::calculate(DataContainerERT & data, bool reciprocity){ if (dipoleCurrentPattern_){ if (complex_) THROW_TO_IMPL std::vector < ElectrodeShape * > eA, eB; //** no reciprocity while using dipole current pattern createCurrentPattern(eA, eB, false); calculate(eA, eB); if (buildCompleteElectrodeModel_ && potentialsCEM_.rows()){ std::cout << "Save cemMatrix.matrix for debugging purposes" << std::endl; saveMatrixRow(potentialsCEM_, "cemMatrix.matrix"); } RVector u(data.size()); uint currentIdx = 0; for (uint i = 0; i < data.size(); i ++){ long abPattern = data.electrodeToCurrentPattern(data("a")[i], data("b")[i]); if (currentPatternIdxMap_.count(abPattern)){ currentIdx = currentPatternIdxMap_[abPattern]; } else { std::cerr << WHERE_AM_I << " cannot find pattern index. " << std::endl; } if (data("m")[i] > -1) { if (buildCompleteElectrodeModel_){ u[i] = potentialsCEM_[currentIdx][data("m")[i]]; } else { u[i] = electrodes_[data("m")[i]]->pot(solutions_[currentIdx]); } } if (data("n")[i] > -1) { if (buildCompleteElectrodeModel_){ u[i] -= potentialsCEM_[currentIdx][data("n")[i]]; } else { u[i] -= electrodes_[data("n")[i]]->pot(solutions_[currentIdx]); } } // if (reciprocity){ // if (currentPatternIdxMap_.count(mnPattern)){ // currentIdx = currentPatternIdxMap_[mnPattern]; // } else { // std::cerr << WHERE_AM_I << " cannot find pattern index. " << std::endl; // } // // uAB_MN = 0.0; // if (data(i).a() > -1) uAB_MN = potentialsCEM_[currentIdx][data(i).a()]; // if (data(i).b() > -1) uAB_MN -= potentialsCEM_[currentIdx][data(i).b()]; // ur[i] = uAB_MN; // } } //** for each in data data.set("u", u); // if (reciprocity) data.add("urez", ur); } else { DataMap dMap; this->calculate(dMap); if (complex_) { setComplexData(data, dMap.data(data), dMap.data(data, false, true)); } else { data.set("u", dMap.data(data)); } } } void DCMultiElectrodeModelling::calculate(DataMap & dMap){ //! create current pattern; if (dipoleCurrentPattern_){ throwError(1, WHERE_AM_I + " Unable to calculate(datamap) using dipoleCurrentPattern. Use calculate(DataContainer) instead "); } std::vector < ElectrodeShape * > eA, eB; createCurrentPattern(eA, eB, true); calculate(eA, eB); if (buildCompleteElectrodeModel_ && potentialsCEM_.rows()) { if (verbose_) std::cout << "Building collectmatrix from CEM matrix appendix." << std::endl; dMap.collect(electrodes_, potentialsCEM_, buildCompleteElectrodeModel_); } else { dMap.collect(electrodes_, solutions_); } } class CalculateMT{ public: CalculateMT(DCMultiElectrodeModelling * fop, const std::vector < ElectrodeShape * > & eA, const std::vector < ElectrodeShape * > & eB, uint kIdx, RMatrix & mat) : fop_(fop), eA_(&eA), eB_(&eB), kIdx_(kIdx), mat_(& mat) { } void operator()(){ fop_->calculateK(*eA_, *eB_, *mat_, kIdx_); } DCMultiElectrodeModelling * fop_; const std::vector < ElectrodeShape * > * eA_; const std::vector < ElectrodeShape * > * eB_; uint kIdx_; RMatrix * mat_; }; void DCMultiElectrodeModelling::calculate(const std::vector < ElectrodeShape * > & eA, const std::vector < ElectrodeShape * > & eB){ if (!subSolutions_) { subpotOwner_ = true; if (complex_){ subSolutions_ = new CMatrix(0); } else { subSolutions_ = new RMatrix(0); } } uint nCurrentPattern = eA.size(); subSolutions_->resize(nCurrentPattern * kValues_.size(), mesh_->nodeCount()); solutions_.clear(); if (complex_){ solutions_.resize(2 * nCurrentPattern, mesh_->nodeCount()); } else { solutions_.resize(nCurrentPattern, mesh_->nodeCount()); } MEMINFO Stopwatch swatch(true); // create or find primary potentials preCalculate(eA, eB); #ifdef HAVE_LIBBOOST_THREAD uint kIdx = 0; while (kIdx < kValues_.size()){ boost::thread_group threads; for (uint thread = 0; thread < nThreads_; thread ++){ if (kIdx < kValues_.size()){ threads.create_thread(CalculateMT(this, eA, eB, kIdx, *subSolutions_)); kIdx ++; } } threads.join_all(); } #else for (Index kIdx = 0; kIdx < kValues_.size(); kIdx ++){ //if (verbose_ && kValues_.size() > 1) std::cout << "\r" << kIdx + 1 << "/" << kValues_.size(); if (complex_){ calculateK(eA, eB, dynamic_cast< CMatrix & > (*subSolutions_), kIdx); } else { calculateK(eA, eB, dynamic_cast< RMatrix & > (*subSolutions_), kIdx); } } #endif for (Index kIdx = 0; kIdx < kValues_.size(); kIdx ++){ for (Index i = 0; i < nCurrentPattern; i ++) { if (kIdx == 0) { if (complex_) { RVector re(real((dynamic_cast< CMatrix & > (*subSolutions_))[i + kIdx * nCurrentPattern])); RVector im(imag((dynamic_cast< CMatrix & > (*subSolutions_))[i + kIdx * nCurrentPattern])); solutions_[i] = re * weights_[kIdx]; solutions_[i+ nCurrentPattern] = im * weights_[kIdx]; } else { solutions_[i] = (dynamic_cast< RMatrix & > (*subSolutions_))[i + kIdx * nCurrentPattern] * weights_[kIdx]; } } else { if (complex_){ RVector re(real((dynamic_cast< CMatrix & > (*subSolutions_))[i + kIdx * nCurrentPattern])); RVector im(imag((dynamic_cast< CMatrix & > (*subSolutions_))[i + kIdx * nCurrentPattern])); solutions_[i] += re * weights_[kIdx]; solutions_[i + nCurrentPattern] += im * weights_[kIdx]; } else { solutions_[i] += (dynamic_cast< RMatrix & > (*subSolutions_))[i + kIdx * nCurrentPattern] * weights_[kIdx]; } } } } if (verbose_) std::cout << "Forward: "; swatch.stop(verbose_); MEMINFO } template < class ValueType > void DCMultiElectrodeModelling::calculateKAnalyt(const std::vector < ElectrodeShape * > & eA, const std::vector < ElectrodeShape * > & eB, Matrix < ValueType > & solutionK, double k, int kIdx) const { uint nCurrentPattern = eA.size(); if (solutionK.rows() < (kIdx + 1) * nCurrentPattern) { throwLengthError(1, WHERE_AM_I + " workspace size insufficient" + toStr(solutionK.rows()) + " " + toStr((kIdx+1)*nCurrentPattern)); } for (uint i = 0; i < nCurrentPattern; i ++) { solutionK[i + kIdx * nCurrentPattern] *= ValueType(0.0); if (eA[i]) solutionK[i + kIdx * nCurrentPattern] = exactDCSolution(*mesh_, eA[i], k, surfaceZ_, setSingValue_); if (eB[i]) solutionK[i + kIdx * nCurrentPattern] -= exactDCSolution(*mesh_, eB[i], k, surfaceZ_, setSingValue_); } } template < class ValueType > void DCMultiElectrodeModelling::calculateK_(const std::vector < ElectrodeShape * > & eA, const std::vector < ElectrodeShape * > & eB, Matrix < ValueType > & solutionK, int kIdx){ bool debug = false; Stopwatch swatch(true); if (debug) std::cout << "Starting calculateK ... " << std::endl; uint nCurrentPattern = eA.size(); double k = kValues_[kIdx]; if (solutionK.rows() < (kIdx+1) * nCurrentPattern) { throwLengthError(1, WHERE_AM_I + " workspace size insufficient" + toStr(solutionK.rows()) + " " + toStr((kIdx+1) * nCurrentPattern)); } if (analytical_) { return calculateKAnalyt(eA, eB, solutionK, k, kIdx); } if (debug) std::cout << "Building sparsity pattern ... " ; SparseMatrix < ValueType > S_; S_.buildSparsityPattern(*mesh_); MEMINFO //** START assemble matrix if (verbose_) std::cout << "Assembling system matrix ... " ; dcfemDomainAssembleStiffnessMatrix(S_, *mesh_, k); dcfemBoundaryAssembleStiffnessMatrix(S_, *mesh_, sourceCenterPos_, k); uint oldMatSize = mesh_->nodeCount(); if (buildCompleteElectrodeModel_){ int lastValidElectrode = electrodes_.size(); // //** check for passive bodies that lay behind valid electrodes // for (uint i = 0; i < electrodes_.size(); i ++){ // if (electrodes_[i]->id() < 0) { // lastValidElectrode = i; // if (verbose_) std::cout << "active electrode count: " << lastValidElectrode << std::endl; // break; // } // } std::vector < ElectrodeShape * > elecs; for (Index i = 0; i < electrodes_.size(); i ++) elecs.push_back(electrodes_[i]); if (electrodeRef_ && electrodeRef_ != electrodes_[lastValidElectrode]) { electrodeRef_->setId(electrodes_.size()); // std::cout << WHERE_AM_I << "//** FIXME this fails with passive bodies " << std::endl; // //** FIXME this fails with passive bodies elecs.push_back(electrodeRef_); } if (verbose_) std::cout << "Assembling complete electrode model ... " << std::endl; for (Index i = 0; i < passiveCEM_.size(); i ++) elecs.push_back(passiveCEM_[i]); if (vContactImpedance_.size() == 0){ vContactImpedance_.resize(elecs.size(), 1.0); // Ohm // RVector vContactResistance(nElectrodes, 1.0); // Ohm // RVector vContactImpedance( nElectrodes, 1.0); // Ohm * m^2 bool hasImp = checkIfMapFileExistAndLoadToVector("contactImpedance.map", vContactImpedance_); if (hasImp){ if (verbose_) std::cout << "Loaded: contactImpedance.map." << std::endl; } } assembleCompleteElectrodeModel(S_, elecs, oldMatSize, lastIsReferenz_, vContactImpedance_); potentialsCEM_.resize(nCurrentPattern, lastValidElectrode); } // end CEM this->assembleStiffnessMatrixDCFEMByPass(S_); assembleStiffnessMatrixHomogenDirichletBC(S_, calibrationSourceIdx_); MEMINFO //** END assemble matrix //** START solving LinSolver solver(verbose_); //solver.setSolverType(LDL); // std::cout << "solver: " << solver.solverName() << std::endl; if (verbose_) std::cout << "Factorizing (" << solver.solverName() << ") system matrix ... "; solver.setMatrix(S_, 1); MEMINFO Vector < ValueType > sol(S_.cols()); for (uint i = 0; i < nCurrentPattern; i ++){ if (verbose_ && k == 0){ std::cout << "\r " << i << " (" << swatch.duration(true) << "s)"; } RVector rTmp(S_.rows(), 0.0); if (eA[i]) eA[i]->assembleRHS(rTmp, 1.0, oldMatSize); if (eB[i]) eB[i]->assembleRHS(rTmp, -1.0, oldMatSize); Vector < ValueType >rhs(rTmp); solver.solve(rhs, sol); // if (i==4){ // S_.save("S-gimli.matrix"); // rhs.save("rhs.vec"); // save(sol, "sol.vec"); // __MS(eA[i]) // __MS(eB[i]) // mesh_->addData("sol" + str((kIdx) * nCurrentPattern + i), sol); // mesh_->addData("rhs", rhs); // mesh_->addData("soll", log(abs(sol))); // mesh_->exportVTK("sol"); // exit(0); // } // mesh_->addData("sol" + str((kIdx) * nCurrentPattern + i), sol); // S_.save("S-gimli.matrix"); // rhs.save("rhs.vec"); // save(rhs[i], "rhs.vec"); // save(sol, "sol.vec"); // __MS(complex_) // __MS(min(sol)<< " " << max(sol)) // __MS(i<< " " << k) if (norml2(S_ * sol - rhs) / norml2(rhs) > 1e-6){ // S_.save("S.matrix"); // save(rhs[i], "rhs.vec"); // save(sol, "sol.vec"); std::cout << " Ooops: Warning!!!! Solver: " << solver.solverName() << " fails with rms(A *x -b)/rms(b) > tol: " << norml2(S_ * sol - rhs)<< std::endl; // S_.save("S-gimli.matrix"); // rhs.save("rhs.vec"); // exit(0); } solutionK[i + kIdx * nCurrentPattern].setVal(sol, 0, oldMatSize); if (buildCompleteElectrodeModel_){ //__MS(sol(oldMatSize, sol.size()- passiveCEM_.size())); potentialsCEM_[i] = TmpToRealHACK(sol(oldMatSize, sol.size() - passiveCEM_.size())); } // no need for setSingValue here .. numerical primpotentials have // some "proper" non singular value // if (setSingValue_){ // if (eA[i]) eA[i]->setSingValue(solutionK[i], mesh_->cellAttributes(), 1.0, k); // if (eB[i]) eB[i]->setSingValue(solutionK[i], mesh_->cellAttributes(), -1.0, k); // } } MEMINFO // we dont need reserve the memory S_.clean(); } void DCMultiElectrodeModelling::calculateK(const std::vector < ElectrodeShape * > & eA, const std::vector < ElectrodeShape * > & eB, RMatrix & solutionK, int kIdx){ calculateK_(eA, eB, solutionK, kIdx); } void DCMultiElectrodeModelling::calculateK(const std::vector < ElectrodeShape * > & eA, const std::vector < ElectrodeShape * > & eB, CMatrix & solutionK, int kIdx){ calculateK_(eA, eB, solutionK, kIdx); } void DCSRMultiElectrodeModelling::updateMeshDependency_(){ DCMultiElectrodeModelling::updateMeshDependency_(); if (primMeshOwner_ && primMesh_) delete primMesh_; if (primPot_) { if (verbose_) std::cout<< " updateMeshDependency:: cleaning primpot" << std::endl; primPot_->clear(); if (primPotOwner_) { delete primPot_; primPot_ = NULL; } } } void DCSRMultiElectrodeModelling::updateDataDependency_(){ DCMultiElectrodeModelling::updateDataDependency_(); if (primPot_) { if (verbose_) std::cout<< " updateDataDependency:: cleaning primpot" << std::endl; primPot_->clear(); if (primPotOwner_) { delete primPot_; primPot_ = NULL; } } } void DCSRMultiElectrodeModelling::setPrimaryMesh(const std::string & meshname){ if (primPotFileBody_.find(NOT_DEFINED) == std::string::npos){ primMesh_ = new Mesh; try { primMesh_->load(meshname); } catch (std::exception & e) { std::cerr << "Cannot load mesh: " << e.what() << std::endl; delete primMesh_; } primMeshOwner_ = true; } } void DCSRMultiElectrodeModelling::checkPrimpotentials_(const std::vector < ElectrodeShape * > & eA, const std::vector < ElectrodeShape * > & eB){ uint nCurrentPattern = eA.size(); Stopwatch swatch(true); if (!primPot_) { //! First check if primPot can be recovered by loading binary matrix if (verbose_) std::cout << "Allocating memory for primary potential..." ; primPot_ = new RMatrix(nCurrentPattern * kValues_.size(), mesh_->nodeCount()); primPot_->rowFlag().fill(0); primPotOwner_ = true; if (verbose_) std::cout << "... " << swatch.duration(true) << std::endl; if (primPotFileBody_.rfind(".bmat") != std::string::npos){ std::cout << std::endl << "No primary potential for secondary field. Recovering " + primPotFileBody_ << std::endl; loadMatrixSingleBin(*primPot_, primPotFileBody_); std::cout << std::endl << " ... done " << std::endl; MEMINFO //! check for sizes here!!! } else { //! no binary matrix so calculate if topography present and no alternativ filename given if (topography() && primPotFileBody_.find(NOT_DEFINED) != std::string::npos){ if (verbose_) { std::cout << std::endl << "No primary potential for secondary field calculation with topography." << std::endl; } if (!primMesh_){ primMesh_ = new Mesh; // dangerous can lead to extremly large meshes *primMesh_ = mesh_->createP2(); // *primMesh_ = *mesh_; primMeshOwner_ = true; if (verbose_) { std::cout<< "Creating P2-Primmesh:\t"; primMesh_->showInfos(); } } primMesh_->setCellAttributes(1.0); DCMultiElectrodeModelling f(this->dataContainer(), verbose_); f.setMesh(*primMesh_); RMatrix primPotentials; f.collectSubPotentials(primPotentials); f.calculate(*primDataMap_); if (verbose_){ std::cout << "Interpolating to secondary mesh" << std::endl; } // for (Index i = 0; i < primPotentials.rows(); i ++ ){ // primMesh_->addData("p"+str(i), log(abs(primPotentials[i]))); // } interpolate(*primMesh_, primPotentials, mesh_->positions(), *primPot_, verbose_); primPot_->rowFlag().fill(1); // for (Index i = 0; i < primPot_->rows(); i ++ ){ // mesh_->addData("s"+str(i), log(abs((*primPot_)[i]))); // } // // primMesh_->exportVTK("prim"); // mesh_->exportVTK("sec"); // save(*primPot_, "primPot"); } } } else {// if (!primPot_) // we assume that given primPotentials are ok if (verbose_){ std::cout << "Using existing primary potentials." << std::endl; } primPot_->rowFlag().fill(1); } //! First check ready! //! now check if all necessary primary potentials loaded or calculated (topography). //! On demand load from single file or calculate analytically if (primPot_->rows() != kValues_.size() * nCurrentPattern || primPot_->cols() != mesh_->nodeCount()){ std::cout << "Warning! primary potential matrix size is invalid for secondary field calculation." << std::endl << "\tMatrix size is " << primPot_->rows() << " x " << primPot_->cols() << "instead of " << kValues_.size() * nCurrentPattern << " x " << mesh_->nodeCount() << std::endl; primPot_->resize(kValues_.size() * nCurrentPattern, mesh_->nodeCount()); primPot_->rowFlag().fill(0); } bool initVerbose = verbose_; //RVector prim(mesh_->nodeCount()); for (uint kIdx = 0; kIdx < kValues_.size(); kIdx ++){ double k = kValues_[kIdx]; for (uint i = 0; i < nCurrentPattern; i ++){ uint potID = (i + kIdx * nCurrentPattern); if (primPot_->rowFlag()[potID] == 0) { //std::cout << "not enough primPot entries " << primPot_->rows() << " " << nCurrentPattern << std::endl; //!** primary potential vector is unknown if (primPotFileBody_.find(NOT_DEFINED) != std::string::npos){ //!** primary potential file body is NOT_DEFINED so we try to determine ourself if (initVerbose){ std::cout << std::endl << "No primary potential for secondary field calculation. " "Calculating analytically..." << std::endl; initVerbose = false; } // PLS CHECK some redundancy here see DCMultiElectrodeModelling::calculateKAnalyt if (eA[i]) (*primPot_)[potID] = exactDCSolution(*mesh_, eA[i], k, surfaceZ_, setSingValue_); if (eB[i]) (*primPot_)[potID] -= exactDCSolution(*mesh_, eB[i], k, surfaceZ_, setSingValue_); } else { if (initVerbose){ std::cout << std::endl << "No primary potential for secondary field calculation. " "Loading potentials." << std::endl; initVerbose = false; } //!** primary potential file body is given so we load it if (k == 0.0){ //!** load 3D potential if (initVerbose) std::cout << std::endl << "Loading primary potential: " << primPotFileBody_ + "." + toStr(i) + ".pot" << std::endl; load((*primPot_)[potID], primPotFileBody_ + "." + toStr(i) + ".pot", Binary); } else { //!** else load 2D potential //!** first try new style "name_Nr.s.pot" if (!load((*primPot_)[potID], primPotFileBody_ + "." + toStr(kIdx * nCurrentPattern + i) + ".s.pot", Binary, false)){ if (!load((*primPot_)[potID], primPotFileBody_ + "." + toStr(i) + "_" + toStr(kIdx) + ".pot", Binary)){ throwError(-1, WHERE_AM_I + " neither new-style potential (" + primPotFileBody_ + ".XX.s.pot nor old-style (" + primPotFileBody_ + ".XX_k.pot) found"); } } } //! else load 2d pot } //! else load pot //** current primary potential is loaded or created, set flag to 1 primPot_->rowFlag()[potID] = 1; } //! if primPot[potID] == 0 } //! for each currentPattern } //** for each k // std::cout << swatch.duration() << std::endl; // exit(0); } void DCSRMultiElectrodeModelling::preCalculate(const std::vector < ElectrodeShape * > & eA, const std::vector < ElectrodeShape * > & eB){ //! check for valid primary potentials, calculate analytical or numerical if nessecary checkPrimpotentials_(eA, eB); mesh1_ = *mesh_; mesh1_.setCellAttributes(1.0); MEMINFO } void DCSRMultiElectrodeModelling::calculateK(const std::vector < ElectrodeShape * > & eA, const std::vector < ElectrodeShape * > & eB, RMatrix & solutionK, int kIdx) { if (complex_){ THROW_TO_IMPL } Stopwatch swatch(true); double k = kValues_[kIdx]; uint nCurrentPattern = eA.size(); if (solutionK.rows() < (kIdx + 1) * nCurrentPattern) { throwLengthError(1, WHERE_AM_I + " workspace size insufficient" + toStr(solutionK.rows()) + " " + toStr((kIdx + 1)*nCurrentPattern)); } if (analytical_){ calculateKAnalyt(eA, eB, solutionK, k, kIdx); return ; } MEMINFO RSparseMatrix S_; S_.buildSparsityPattern(*mesh_); bool singleVerbose = verbose_; MEMINFO dcfemDomainAssembleStiffnessMatrix( S_, *mesh_, k); dcfemBoundaryAssembleStiffnessMatrix( S_, *mesh_, sourceCenterPos_, k); assembleStiffnessMatrixHomogenDirichletBC(S_, calibrationSourceIdx_); // S_.save("S.mat"); // exit(1); RSparseMatrix S1(S_); // RVector tmpRho(mesh_->cellAttributes()); // mesh_->setCellAttributes(1.0); dcfemDomainAssembleStiffnessMatrix( S1, mesh1_, k); dcfemBoundaryAssembleStiffnessMatrix(S1, mesh1_, sourceCenterPos_, k); assembleStiffnessMatrixHomogenDirichletBC(S1, calibrationSourceIdx_); // if (verbose_) std::cout << "Assembling: " << swatch.duration() << std::endl; //mesh_->setCellAttributes(tmpRho); MEMINFO LinSolver solver(false); solver.setMatrix(S_, 1); // if (verbose_) std::cout << "Factorize (" << solver.solverName() << ") matrix ... " << swatch.duration() << std::endl; MEMINFO //std::cout << WHERE_AM_I << std::endl; RVector rhs(S_.rows()), prim(rhs.size()); for (uint i = 0; i < nCurrentPattern; i ++){ if (primPot_->rows() <= (i + kIdx * nCurrentPattern)){ throwError(1, WHERE_AM_I + " this should not happen, pls check primpots "); //** we do not have the primPot; } else { prim = (*primPot_)[i + kIdx * nCurrentPattern]; } //** determine resistivity at the source location double rhoSourceA = 0.0, rhoSourceB = 0.0, rhoSource = 0.0; uint count = 0; if (eA[i]) { rhoSourceA = eA[i]->geomMeanCellAttributes(); if (rhoSourceA > TOLERANCE){ rhoSource += rhoSourceA; count++; } else { std::cout << eA[i]->id() << " "<< eA[i]->pos() << " " << eA[i]->geomMeanCellAttributes() << std::endl; std::cerr << WHERE_AM_I << " WARNING! rhoSourceA < TOLERANCE: " << std::endl; } } if (eB[i]) { rhoSourceB = eB[i]->geomMeanCellAttributes(); if (rhoSourceB > TOLERANCE){ rhoSource += rhoSourceB; count++; } else { std::cout << eB[i]->id() << " "<< eB[i]->pos() << " " << eB[i]->geomMeanCellAttributes() << std::endl; std::cerr << WHERE_AM_I << " WARNING! rhoSourceB < TOLERANCE: " << std::endl; } } //S_sig*u_s = (sig_0 * S1 - S_sig) u_p = sig_0 * S1 * u_p - S_sig * u_p rhoSource = rhoSource / count; prim *= rhoSource; rhs = S1 * prim / rhoSource - S_ * prim; // bool newWay = true; // if (newWay){ // rhs = S1 * prim / rhoSource - S_ * prim; // //rhs = (1.0 / (rhoSource)) * S1 * prim - S_ * prim; // } else { // // RSparseMatrix Stmp(S_); // // RVector tmpRho2(mesh_->cellAttributes()); // // for (uint t = 0; t < mesh_->cellCount(); t ++) { // // if (std::fabs(mesh_->cell(t).attribute() - rhoSource) < 1e-10) { // // //std::cout << "mesh_->cell(t).setAttribute(0.0); " << std::endl; // // mesh_->cell(t).setAttribute(0.0); // // } else { // // mesh_->cell(t).setAttribute(1.0 / // // ( 1.0 / rhoSource - 1.0 / mesh_->cell(t).attribute())) ; // // } // // } // // dcfemDomainAssembleStiffnessMatrix(Stmp, *mesh_, k, false); // // dcfemBoundaryAssembleStiffnessMatrix(Stmp, *mesh_, sourceCenterPos_, k); // // mesh_->setCellAttributes(tmpRho2); // // // // rhs = Stmp * prim; // } //** fill calibration points for (uint j = 0; j < calibrationSourceIdx_.size(); j ++) { rhs[calibrationSourceIdx_[j]] = 0.0; } solutionK[i + (kIdx * nCurrentPattern)] *= 0.0; solver.solve(rhs, solutionK[i + (kIdx * nCurrentPattern)]); solutionK[i + (kIdx * nCurrentPattern)] += prim; if (singleVerbose) singleVerbose = false; } } } // namespace GIMLI{
38.958278
156
0.514623
[ "mesh", "shape", "vector", "model", "transform", "3d" ]
9c4f594a2aa978d5e26a6184181131836f5df8c4
7,482
cpp
C++
src/iptv_in_web_gst.cpp
karimdavoodi/iptv_out
ad1b3282456d42ec0ace4213e98a2014b648cfaf
[ "MIT" ]
3
2020-09-16T01:45:01.000Z
2021-11-02T14:34:45.000Z
src/iptv_in_web_gst.cpp
karimdavoodi/iptv_out
ad1b3282456d42ec0ace4213e98a2014b648cfaf
[ "MIT" ]
null
null
null
src/iptv_in_web_gst.cpp
karimdavoodi/iptv_out
ad1b3282456d42ec0ace4213e98a2014b648cfaf
[ "MIT" ]
null
null
null
/* * Copyright (c) 2020 Karim, karimdavoodi@gmail.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <boost/log/trivial.hpp> #include "gst.hpp" #include <thread> #include <mutex> #include <gtk/gtk.h> #include <webkit2/webkit2.h> #define FPS 2 #define DELAY (1000/FPS) #define WIDTH 1280 #define HEIGHT 720 #define FRAME_SIZE (WIDTH * HEIGHT * 4) #define WAIT_MILISECOND(x) std::this_thread::sleep_for(std::chrono::milliseconds(x)) using namespace std; GstClockTime timestamp = 0; uint8_t* frame = nullptr; cairo_surface_t* surface = nullptr; std::mutex frame_mutex; void init_display(int display_id); void app_need_data (GstElement *appsrc, guint unused_size, gpointer user_data); void get_snapshot(GObject *object, GAsyncResult *result, gpointer data); /* * The Gstreamer main function * Streaming of Web site to udp:://out_multicast:port * * @param web_url: URL of Web site * @param out_multicast : multicast of output stream * @param port: output multicast port numper * * */ void gst_convert_web_to_stream(string web_url, string out_multicast, int port) { //web_url = "http://127.0.0.1/s/?mmk&u=1&p=1"; LOG(info) << "Start " << web_url << " --> udp://" << out_multicast << ":" << port; Gst::Data d; d.loop = g_main_loop_new(nullptr, false); d.pipeline = GST_PIPELINE(gst_element_factory_make("pipeline", nullptr)); frame = (uint8_t* ) malloc(FRAME_SIZE); try{ auto appsrc = Gst::add_element(d.pipeline, "appsrc"), queue_src = Gst::add_element(d.pipeline, "queue", "queue_src"), videoconvert = Gst::add_element(d.pipeline, "videoconvert"), x264enc = Gst::add_element(d.pipeline, "x264enc"), h264parse = Gst::add_element(d.pipeline, "h264parse"), mpegtsmux = Gst::add_element(d.pipeline, "mpegtsmux", "mpegtsmux"), rndbuffersize = Gst::add_element(d.pipeline, "rndbuffersize","queue_sink"), udpsink = Gst::add_element(d.pipeline, "udpsink"); gst_element_link_many( appsrc, queue_src, videoconvert, x264enc, h264parse, mpegtsmux, rndbuffersize, udpsink, nullptr); g_object_set (G_OBJECT (appsrc), "caps", gst_caps_new_simple ("video/x-raw", "format", G_TYPE_STRING, "RGBx", "width", G_TYPE_INT, WIDTH, "height", G_TYPE_INT, HEIGHT, "framerate", GST_TYPE_FRACTION, FPS, 1, NULL), NULL); g_object_set (G_OBJECT (appsrc), "stream-type", 0, "format", GST_FORMAT_TIME, NULL); g_object_set (rndbuffersize, "min", 1316, "max", 1316, nullptr); g_object_set (x264enc, "speed-preset", 1, nullptr); g_signal_connect (appsrc, "need-data", G_CALLBACK (app_need_data), &d); g_object_set(udpsink, "multicast_iface", "lo", "host", out_multicast.c_str() , "port", port, "sync", true, nullptr); Gst::add_bus_watch(d); //Gst::dot_file(d.pipeline, "iptv_archive", 5); /////////////////////////////////////////// GTK GtkWidget *main_window = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_default_size(GTK_WINDOW(main_window), WIDTH, HEIGHT); WebKitWebView *webView = WEBKIT_WEB_VIEW(webkit_web_view_new()); gtk_container_add(GTK_CONTAINER(main_window), GTK_WIDGET(webView)); webkit_web_view_load_uri(webView, web_url.c_str()); bool running = true; std::thread snapshot_thread([&](){ uint32_t n = 0; while(running){ WAIT_MILISECOND(DELAY); if(++n % 10000 == 0){ LOG(debug) << "reload " << web_url; webkit_web_view_reload(webView); } webkit_web_view_get_snapshot(webView, WEBKIT_SNAPSHOT_REGION_VISIBLE, WEBKIT_SNAPSHOT_OPTIONS_NONE, nullptr, get_snapshot, webView); } }); gtk_widget_show_all(main_window); /////////////////////////////////////////// Start Pipline gst_element_set_state(GST_ELEMENT(d.pipeline), GST_STATE_PLAYING); g_main_loop_run(d.loop); running = false; free(frame); }catch(std::exception& e){ LOG(error) << e.what(); } } void init_display(int display_id) { LOG(trace) << "Init display:" << display_id; string display = ":" + to_string(display_id); string cmd = "Xvfb " + display + " -screen scrn 1280x720x24 &"; system(cmd.c_str()); WAIT_MILISECOND(1000); const char* argv_a[] = {"prog", "--display", display.c_str(), nullptr}; int argc = 3; char** argv = (char**) argv_a; gtk_init(&argc, &argv); } void app_need_data (GstElement *appsrc, guint /*unused_size*/, gpointer user_data) { auto* d = (Gst::Data*) user_data; GstBuffer *buffer; GstFlowReturn ret; WAIT_MILISECOND(DELAY); buffer = gst_buffer_new_allocate (nullptr, FRAME_SIZE, nullptr); { std::unique_lock<std::mutex> lock(frame_mutex); gst_buffer_fill(buffer, 0, frame, FRAME_SIZE); } GST_BUFFER_PTS (buffer) = timestamp; GST_BUFFER_DURATION (buffer) = gst_util_uint64_scale_int (1, GST_SECOND, FPS); timestamp += GST_BUFFER_DURATION (buffer); LOG(trace) << "push buffer"; g_signal_emit_by_name (appsrc, "push-buffer", buffer, &ret); gst_buffer_unref (buffer); if (ret != GST_FLOW_OK) { g_main_loop_quit (d->loop); } } void get_snapshot(GObject */*object*/, GAsyncResult *result, gpointer data) { auto * webview = (WebKitWebView*)data; GError* error = nullptr; surface = webkit_web_view_get_snapshot_finish(webview, result, &error); LOG(trace) << "Got frame"; std::unique_lock<std::mutex> lock(frame_mutex); auto* f = (uint8_t*) cairo_image_surface_get_data(surface); memcpy(frame, f, FRAME_SIZE); cairo_surface_destroy(surface); }
36.497561
89
0.605854
[ "object" ]
9c4f5b77acab01f732f569534cbf725ef8af3657
20,460
cpp
C++
src/gopt/impl/global_layout_transform/dynamic_programming_solver.cpp
kxz18/MegEngine
88c1eedbd716805244b35bdda57c3cea5efe734d
[ "Apache-2.0" ]
null
null
null
src/gopt/impl/global_layout_transform/dynamic_programming_solver.cpp
kxz18/MegEngine
88c1eedbd716805244b35bdda57c3cea5efe734d
[ "Apache-2.0" ]
null
null
null
src/gopt/impl/global_layout_transform/dynamic_programming_solver.cpp
kxz18/MegEngine
88c1eedbd716805244b35bdda57c3cea5efe734d
[ "Apache-2.0" ]
null
null
null
/** * \file src/gopt/impl/dynamic_programming_solver.cpp * MegEngine is Licensed under the Apache License, Version 2.0 (the "License") * * Copyright (c) 2014-2021 Megvii Inc. All rights reserved. * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. */ #include <queue> #include "./utils.h" #include "megbrain/gopt/layout_transform_context.h" #include "megbrain/gopt/profiler.h" #include "megbrain/gopt/solver.h" using namespace mgb; using namespace gopt; using namespace cg; /* ================= DynamicProgrammingSolver::Impl ==================*/ class DynamicProgrammingSolver::Impl { public: Impl(size_t max_states) : m_max_states{max_states} {} ~Impl() = default; Solution solve(const ProfilerBase* profiler, const Problem& problem); private: using TensorFormatsBitSet = uint32_t; using State = SmallVector<TensorFormatsBitSet>; /// 1bit represents one kind of tensor formats static constexpr uint32_t BITS_PER_BYTE = 8; static constexpr uint32_t MAX_TENSOR_FORMATS = sizeof(TensorFormatsBitSet) * BITS_PER_BYTE; TensorFormatsBitSet add(TensorFormatsBitSet& set, TensorFormats fmt) { mgb_assert(static_cast<uint32_t>(fmt) < MAX_TENSOR_FORMATS); set |= (1 << static_cast<uint32_t>(fmt)); return set; } bool valid(const TensorFormatsBitSet& set, TensorFormats fmt) { mgb_assert(static_cast<uint32_t>(fmt) < MAX_TENSOR_FORMATS); bool val = set & (1 << static_cast<uint32_t>(fmt)); return val; } struct Value { OperatorNodeBase* opr; const State* prev; OprFormat opr_fmt; float time; ///! index in the topo order of the correspoding operator size_t opr_idx; }; struct StateHash { size_t operator()(const State& key) const { size_t h = 0; for (auto&& v : key) { h = mgb::hash_pair_combine(h, std::hash<TensorFormatsBitSet>{}(v)); } return h; } }; struct StateEqual { size_t operator()(const State& lhs, const State& rhs) const { if (lhs.size() != rhs.size()) return false; for (size_t i = 0; i < lhs.size(); ++i) { if (lhs[i] != rhs[i]) return false; } return true; } }; using StateTable = std::unordered_map<State, Value, StateHash, StateEqual>; struct Cut { StateTable states; }; using ProfilingResult = ProfilerBase::ProfilingResult; using OprConfigTrait = LayoutTransformContext::OprConfigTrait; struct Context { const std::vector<OperatorNodeBase*>& topo; const ProfilingResult& rst; const OprConfigTrait& opr_configs; const SmallVector<TensorFormats>& available_tensor_formats; }; /*! * \brief get the tensor formats configuration for the operator with * particular op format \param[out] var2fmts hashmap that maps varnode to * actual tensor formats of the op format configuration \param[in] opr given * operator \param[in] opr_fmt given op format, an enum type argument which * indicates the op format configuration. \param[in] ctx context */ TensorFormats get_io_formats(ThinHashMap<VarNode*, TensorFormats>& var2fmts, const OperatorNodeBase* opr, OprFormat opr_fmt, const Context& ctx); /*! * \brief compute the distace of two states of the given varnode * \param[in] from the source state * \param[in] to the target state * \param[in] var given varnode * \param[in] ctx context */ float distance(const TensorFormatsBitSet& from, const TensorFormatsBitSet& to, VarNode* var, const Context& ctx); /*! * \brief compute the distace of two states of the given cut edges * \param[in] from the source state * \param[in] to the target state * \param[in] edge a VarNodeArry, the given cut edges * \param[in] ctx context */ float state_distance(const State& from, const State& to, const VarNodeArray& edge, const Context& ctx); /*! * \brief analyze the edges of each cut * \param[out] edges the return edges of the cuts * \param[out] edge2idx hashmaps, that maps edge(varnode) to its index * \param[in] ctx contex */ void analyze_edges(SmallVector<VarNodeArray>& edges, SmallVector<std::unordered_map<VarNode*, int>>& edge2idx, const Context& ctx); /*! * \brief prune states using the distance of states */ void prune(StateTable& states, const VarNodeArray& edge, const Context& ctx); /*! * \brief force prune states, reserve the smallest MAX_STATES states */ void force_prune(StateTable& states); private: size_t m_max_states; }; TensorFormats DynamicProgrammingSolver::Impl::get_io_formats( ThinHashMap<VarNode*, TensorFormats>& var2fmts, const OperatorNodeBase* opr, OprFormat opr_fmt, const Context& ctx) { auto&& rst = ctx.rst; auto&& opr_configs = ctx.opr_configs; auto iter = opr_configs.find(opr->dyn_typeinfo()); Maybe<OprTensorFormatsConfiguration> fmtcfg = None; if (iter != opr_configs.end()) { fmtcfg = (*iter->second.at(opr_fmt))(opr); } TensorFormats out_fmt; if (fmtcfg.valid()) out_fmt = fmtcfg.val().output_tensor_formats[0]; else out_fmt = opr_format_to_tensor_formats(opr_fmt); for (size_t i = 0; i < opr->input().size(); ++i) { auto&& var = opr->input(i); auto iter = rst.var_record.find(var); if (iter != rst.var_record.end()) { if (fmtcfg.valid()) var2fmts[var] = fmtcfg.val().input_tensor_formats[i]; else var2fmts[var] = opr_format_to_tensor_formats(opr_fmt); } } return out_fmt; } float DynamicProgrammingSolver::Impl::distance(const TensorFormatsBitSet& from, const TensorFormatsBitSet& to, VarNode* var, const Context& ctx) { auto&& costs = ctx.rst.var_record.at(var).costs; auto&& available_tensor_formats = ctx.available_tensor_formats; float dist = 0.f; if ((from & to) == to) return dist; auto to_set = ((from | to) ^ from); for (auto o : available_tensor_formats) { if (valid(to_set, o)) { float o_cost = std::numeric_limits<float>::max(); for (auto i : available_tensor_formats) { if (valid(from, i)) { float cost = costs.at({i, o}); o_cost = std::min(o_cost, cost); } } dist += o_cost; } } return dist; } float DynamicProgrammingSolver::Impl::state_distance(const State& from, const State& to, const VarNodeArray& edge, const Context& ctx) { float dist = 0.f; mgb_assert(from.size() == to.size() && from.size() == edge.size()); for (size_t i = 0; i < edge.size(); ++i) { dist += distance(from[i], to[i], edge[i], ctx); } return dist; } void DynamicProgrammingSolver::Impl::analyze_edges( SmallVector<VarNodeArray>& edges, SmallVector<std::unordered_map<VarNode*, int>>& edge2idx, const Context& ctx) { auto&& topo = ctx.topo; auto&& rst = ctx.rst; size_t nr_oprs = topo.size(); edges.resize(nr_oprs); edge2idx.resize(nr_oprs); ThinHashSet<VarNode*> cur_edge; size_t cur = nr_oprs - 1; int idx = 0; for (auto&& ov : topo[cur]->usable_output()) { edges[cur].push_back(ov); edge2idx[cur].emplace(ov, idx++); } cur--; for (const auto& opr : reverse_adaptor(topo)) { for (const auto& i : opr->input()) { if (rst.var_record.count(i) > 0) { cur_edge.insert(i); } } for (auto&& ov : opr->usable_output()) { cur_edge.erase(ov); } edges[cur].insert(edges[cur].begin(), cur_edge.begin(), cur_edge.end()); int i = 0; for (auto&& e : edges[cur]) { edge2idx[cur][e] = i++; } if (cur == 0) break; cur--; } } void DynamicProgrammingSolver::Impl::prune(StateTable& states, const VarNodeArray& edge, const Context& ctx) { struct Item { decltype(states.begin()) iter; }; std::list<Item> list; for (auto it = states.begin(); it != states.end(); ++it) { list.emplace_back(Item{it}); } SmallVector<State> removed_states; for (auto i = list.begin(); i != list.end();) { bool advanced_i = false; for (auto j = std::next(i, 1); j != list.end();) { if (i->iter->second.time > j->iter->second.time && state_distance(j->iter->first, i->iter->first, edge, ctx) < i->iter->second.time - j->iter->second.time) { removed_states.push_back(i->iter->first); i = list.erase(i); advanced_i = true; break; } else if (i->iter->second.time < j->iter->second.time && state_distance(i->iter->first, j->iter->first, edge, ctx) < j->iter->second.time - i->iter->second.time) { removed_states.push_back(j->iter->first); j = list.erase(j); } else { j = std::next(j, 1); } } if (!advanced_i) i = std::next(i, 1); } for (auto&& state : removed_states) states.erase(state); } void DynamicProgrammingSolver::Impl::force_prune(StateTable& states) { if (states.size() < m_max_states) return; struct Item { decltype(states.begin()) iter; }; auto cmp = [](Item lhs, Item rhs) { return lhs.iter->second.time < rhs.iter->second.time; }; std::priority_queue<Item, std::vector<Item>, decltype(cmp)> pq(cmp); for (auto it = states.begin(); it != states.end(); ++it) { if (pq.size() < m_max_states) pq.push(Item{it}); else { auto i = pq.top(); if (it->second.time < i.iter->second.time) { pq.pop(); pq.push(Item{it}); } } } StateTable active_state; while (!pq.empty()) { auto i = pq.top(); active_state.insert(*i.iter); pq.pop(); } states.swap(active_state); } DynamicProgrammingSolver::Solution DynamicProgrammingSolver::Impl::solve( const ProfilerBase* profiler, const Problem& problem) { const auto rst = profiler->profile(problem); const auto& partition = problem.graph_partition(); const auto& opr_configs = problem.opr_configs(); const auto& base_fmt = problem.base_format(); const auto& available_tensor_formats = problem.available_tensor_formats(); const auto& topo = partition.all_oprs(); Context ctx{topo, rst, opr_configs, available_tensor_formats}; SmallVector<VarNodeArray> edges; SmallVector<std::unordered_map<VarNode*, int>> edge2idx; /// analyze edges of each cuts analyze_edges(edges, edge2idx, ctx); SmallVector<Cut> cuts; size_t cur = 0; /// initialize states auto init = [&, this](OperatorNodeBase* opr) { auto it = rst.opr_record.find(opr); if (it == rst.opr_record.end()) return; ThinHashSet<VarNode*> ovar_set; for (auto&& ov : opr->usable_output()) { ovar_set.insert(ov); } const auto& records = it->second.costs; cuts.emplace_back(Cut{}); auto& states = cuts.back().states; for (const auto& record : records) { auto opr_fmt = record.first; float opr_time = record.second; ThinHashMap<VarNode*, TensorFormats> ivar2fmts; auto out_fmt = get_io_formats(ivar2fmts, opr, opr_fmt, ctx); const auto& edge = edges[cur]; State state(edge.size(), 0); Value value{opr, nullptr, opr_fmt, 0.f, cur}; float ovar_time = 0.f; for (size_t i = 0; i < edge.size(); ++i) { auto&& var = edge[i]; auto&& costs = rst.var_record.at(var).costs; if (ovar_set.count(var) > 0) { add(state[i], out_fmt); if (partition.output().count(var) > 0 && out_fmt != base_fmt) { ovar_time += costs.at({out_fmt, base_fmt}); add(state[i], base_fmt); } } else { add(state[i], base_fmt); } } float ivar_time = 0.f; for (const auto& kv : ivar2fmts) { auto&& v = kv.first; auto&& costs = rst.var_record.at(v).costs; auto to = kv.second; float min_time = std::numeric_limits<float>::max(); if (base_fmt == to) { min_time = 0.f; } else { min_time = costs.at({base_fmt, to}); if (edge2idx[cur].count(v) > 0) { add(state[edge2idx[cur][v]], to); } } ivar_time += min_time; } value.time = opr_time + ivar_time + ovar_time; states[state] = value; } }; /// update the states auto body = [&, this](OperatorNodeBase* opr) { auto it = rst.opr_record.find(opr); if (it == rst.opr_record.end()) return; ThinHashSet<VarNode*> ovar_set; for (auto&& ov : opr->usable_output()) { ovar_set.insert(ov); } const auto& records = it->second.costs; StateTable states; for (const auto& record : records) { auto opr_fmt = record.first; float opr_time = record.second; ThinHashMap<VarNode*, TensorFormats> ivar2fmts; auto out_fmt = get_io_formats(ivar2fmts, opr, opr_fmt, ctx); for (const auto& kv : cuts.back().states) { auto&& prev_state = kv.first; float prev_time = kv.second.time; const auto& edge = edges[cur]; State state(edge.size(), 0); Value value{opr, &prev_state, opr_fmt, 0.f, cur}; float ovar_time = 0.f; for (size_t i = 0; i < edge.size(); ++i) { auto&& var = edge[i]; auto&& costs = rst.var_record.at(var).costs; auto iter = edge2idx[cur - 1].find(var); if (iter != edge2idx[cur - 1].end()) { state[i] = prev_state[iter->second]; } else { mgb_assert(ovar_set.count(var) > 0); add(state[i], out_fmt); if (partition.output().count(var) > 0 && out_fmt != base_fmt) { ovar_time += costs.at({out_fmt, base_fmt}); add(state[i], base_fmt); } } } float ivar_time = 0.f; for (const auto& kv : ivar2fmts) { auto&& v = kv.first; auto&& costs = rst.var_record.at(v).costs; auto to = kv.second; auto it1 = edge2idx[cur - 1].find(v); float min_time = std::numeric_limits<float>::max(); if (valid(prev_state[it1->second], to)) { min_time = 0.f; } else { for (auto&& from : available_tensor_formats) { if (valid(prev_state[it1->second], from)) { float cost = costs.at({from, to}); min_time = std::min(min_time, cost); } } } auto it2 = edge2idx[cur].find(v); if (it2 != edge2idx[cur].end()) { add(state[it2->second], to); } ivar_time += min_time; } value.time = prev_time + opr_time + ivar_time + ovar_time; auto iter = states.find(state); if (iter == states.end()) { states[state] = value; } else { float time = iter->second.time; if (value.time < time) { iter->second = value; } } } } cuts.emplace_back(Cut{}); cuts.back().states.swap(states); }; /// forward pass to generate all states for (auto&& opr : topo) { if (cuts.empty()) { init(opr); } else { body(opr); } if (!cuts.empty()) { auto& states = cuts.back().states; prune(states, edges[cur], ctx); force_prune(states); } cur++; } Solution solution; /// backward pass to generate the solution float min_time = std::numeric_limits<float>::max(); OperatorNodeBase* cur_opr = nullptr; OprFormat min_fmt = OprFormat::NCHW; const State* pstate = nullptr; for (auto&& kv : cuts.back().states) { auto&& v = kv.second; if (v.time < min_time) { cur_opr = v.opr; pstate = v.prev; min_time = v.time; min_fmt = v.opr_fmt; ///! just to check the tensor formats of the output varnode auto&& k = kv.first; size_t opr_idx = v.opr_idx; for (size_t i = 0; i < k.size(); ++i) { auto&& fmt_set = k[i]; auto&& var = edges[opr_idx][i]; if (partition.output().count(var)) { mgb_assert(valid(fmt_set, base_fmt)); } } } } mgb_assert(cur_opr != nullptr); mgb_log_debug("opr:%s;format:%s;time:%f", cur_opr->cname(), opr_format_to_string(min_fmt), min_time); solution.insert({cur_opr, min_fmt}); cur = cuts.size() - 2; while (pstate) { auto val = cuts[cur].states[*pstate]; ///! just to check the tensor formats of the output varnode size_t opr_idx = val.opr_idx; for (size_t i = 0; i < pstate->size(); ++i) { auto&& fmt_set = pstate->operator[](i); auto&& var = edges[opr_idx][i]; if (partition.output().count(var)) { mgb_assert(valid(fmt_set, base_fmt)); } } mgb_log_debug("opr:%s;format:%s;time:%f", val.opr->cname(), opr_format_to_string(val.opr_fmt), val.time); solution.insert({val.opr, val.opr_fmt}); pstate = val.prev; cur--; } return solution; } /* =================== DynamicProgrammingSolver ======================*/ DynamicProgrammingSolver::Solution DynamicProgrammingSolver::do_solve( const Problem& problem) const { constexpr size_t MAX_STATES = 1024; Impl impl(MAX_STATES); return impl.solve(m_profiler.get(), problem); } bool DynamicProgrammingSolver::can_solve(const Problem& problem) const { auto&& available_tensor_formats = problem.available_tensor_formats(); for (auto&& tensor_format : available_tensor_formats) { if (static_cast<uint32_t>(tensor_format) >= 32) return false; } return true; } // vim: syntax=cpp.doxygen
36.931408
80
0.524976
[ "vector" ]
9c510c32aaf9485678ed27652c84c8af47ac4d21
162,529
cpp
C++
src/simplex/HSimplex.cpp
ogmundur/HiGHS
ed3a64f589b3a1962783caef793dc20b158210d4
[ "MIT" ]
null
null
null
src/simplex/HSimplex.cpp
ogmundur/HiGHS
ed3a64f589b3a1962783caef793dc20b158210d4
[ "MIT" ]
null
null
null
src/simplex/HSimplex.cpp
ogmundur/HiGHS
ed3a64f589b3a1962783caef793dc20b158210d4
[ "MIT" ]
null
null
null
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* This file is part of the HiGHS linear optimization suite */ /* */ /* Written and engineered 2008-2021 at the University of Edinburgh */ /* */ /* Available as open-source under the MIT License */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /**@file lp_data/HSimplex.cpp * @brief * @author Julian Hall, Ivet Galabova, Qi Huangfu and Michael Feldmeier */ #include "simplex/HSimplex.h" #include "HConfig.h" #include "io/HighsIO.h" #include "lp_data/HighsLpUtils.h" #include "lp_data/HighsModelUtils.h" #include "lp_data/HighsSolution.h" #include "lp_data/HighsSolutionDebug.h" #include "lp_data/HighsStatus.h" #include "simplex/HCrash.h" #include "simplex/HFactorDebug.h" #include "simplex/HSimplexDebug.h" #include "simplex/HVector.h" #include "simplex/HighsSimplexInterface.h" #include "simplex/SimplexConst.h" // For simplex strategy constants #include "simplex/SimplexTimer.h" #include "util/HighsSort.h" #include "util/HighsUtils.h" using std::runtime_error; #include <cassert> #include <vector> #ifdef OPENMP #include "omp.h" #endif void setSimplexOptions(HighsModelObject& highs_model_object) { const HighsOptions& options = highs_model_object.options_; HighsSimplexInfo& simplex_info = highs_model_object.simplex_info_; // Copy values of HighsOptions for the simplex solver // // Currently most of these options are straight copies, but they // will become valuable when "choose" becomes a HiGHS strategy value // that will need converting into a specific simplex strategy value. // simplex_info.simplex_strategy = options.simplex_strategy; simplex_info.dual_edge_weight_strategy = options.simplex_dual_edge_weight_strategy; simplex_info.price_strategy = options.simplex_price_strategy; simplex_info.dual_simplex_cost_perturbation_multiplier = options.dual_simplex_cost_perturbation_multiplier; simplex_info.factor_pivot_threshold = options.factor_pivot_threshold; simplex_info.update_limit = options.simplex_update_limit; // Set values of internal options simplex_info.store_squared_primal_infeasibility = true; // Option for analysing the LP solution #ifdef HiGHSDEV bool useful_analysis = true; // false; // bool full_timing = false; // Options for reporting timing simplex_info.report_simplex_inner_clock = useful_analysis; // true; simplex_info.report_simplex_outer_clock = full_timing; simplex_info.report_simplex_phases_clock = full_timing; simplex_info.report_HFactor_clock = useful_analysis; // full_timing;// // Options for analysing the LP and simplex iterations simplex_info.analyse_lp = useful_analysis; // false; // simplex_info.analyse_iterations = useful_analysis; simplex_info.analyse_invert_form = useful_analysis; // simplex_info.analyse_invert_condition = useful_analysis; simplex_info.analyse_invert_time = full_timing; simplex_info.analyse_rebuild_time = full_timing; #endif } int initialiseSimplexLpBasisAndFactor(HighsModelObject& highs_model_object, const bool only_from_known_basis) { // Perform the transition from whatever information is known about // the LP to a status where the LP is scaled and has the inverse of // a basis. According to only_from_known_basis, this will be // // * Only done for any resident simplex basis or HiGHS basis, with its // rank deficiency returned in the value, or an error return of -1 // inicating there is no resident basis // // * Attempted for any resident simplex basis or HiGHS basis - with // rank deficiency handled - otherwise a logical basis is created // unless crashing is permitted. // // First look at what basis and solution information is known. If a // simplex basis is known, then it's used, and there's no need for // the solution values. This will usually correspond to hot start // when solving MIP problems. Otherwise, generate a simplex basis, // thus: // // If there is a HiGHS basis: use it to determine what's basic and nonbasic // (nonbasicFlag). // // If there's no HiGHS basis: generate nonbasicFlag, possibly by performing a // crash. // // Use nonbasicFlag to generate basicIndex // const HighsOptions& options = highs_model_object.options_; const HighsBasis& basis = highs_model_object.basis_; const HighsSolution& solution = highs_model_object.solution_; const HighsLp& simplex_lp = highs_model_object.simplex_lp_; HighsSimplexInfo& simplex_info = highs_model_object.simplex_info_; HighsSimplexLpStatus& simplex_lp_status = highs_model_object.simplex_lp_status_; SimplexBasis& simplex_basis = highs_model_object.simplex_basis_; HFactor& factor = highs_model_object.factor_; HighsScale& scale = highs_model_object.scale_; HighsSimplexAnalysis& analysis = highs_model_object.simplex_analysis_; if (!simplex_lp_status.valid) { // Simplex LP is not valid so // // Set simplex options from HiGHS options. setSimplexOptions(highs_model_object); // Initialise the simplex LP data initialiseSimplexLpDefinition(highs_model_object); // Initialise the real and integer random vectors initialiseSimplexLpRandomVectors(highs_model_object); } if (simplex_lp_status.has_basis) { // There is a simplex basis: it should be valid - since it's set // internally - but check if (debugSimplexBasisCorrect(highs_model_object) == HighsDebugStatus::LOGICAL_ERROR) { HighsLogMessage(options.logfile, HighsMessageType::ERROR, "Supposed to be a Simplex basis, but incorrect"); return -(int)HighsStatus::Error; } } // Now we know whether the simplex basis at least has the right number // of basic and nonbasic variables if (!simplex_lp_status.has_basis) { // There is no simplex basis so try to identify one if (basis.valid_) { // There is is HiGHS basis: use it to construct nonbasicFlag if (debugBasisConsistent(options, simplex_lp, basis) == HighsDebugStatus::LOGICAL_ERROR) { HighsLogMessage(options.logfile, HighsMessageType::ERROR, "Supposed to be a Highs basis, but not valid"); return -(int)HighsStatus::Error; } // Allocate memory for nonbasicFlag and set it up from the HiGHS basis simplex_basis.nonbasicFlag_.resize(simplex_lp.numCol_ + simplex_lp.numRow_); setNonbasicFlag(simplex_lp, simplex_basis.nonbasicFlag_, &basis.col_status[0], &basis.row_status[0]); } // nonbasicFlag is valid if the HiGHS basis exists and has the correct // number of basic variables bool nonbasicFlag_valid = basis.valid_; // If not valid, and only this basis should be used, then return error if (!nonbasicFlag_valid && only_from_known_basis) { HighsLogMessage(options.logfile, HighsMessageType::ERROR, "Supposed to be a HiGHS basis, but incorrect"); return -(int)HighsStatus::Error; } if (!nonbasicFlag_valid) { // So, nonbasicFlag is not valid - either because there is no // simplex or HiGHS basis, or because what was claimed to be // valid has been found to have the wrong number of basic and // nonbasic variables // // This is taken to imply that this is a "new" LP to be solved, so // // Generate a simplex basis, possibly by performing a crash, // // Possibly permute the columns of the LP to be used by the solver. if (options.simplex_permute_strategy != OPTION_OFF) { permuteSimplexLp(highs_model_object); } // Allocate memory for nonbasicFlag and set it up for a logical basis simplex_basis.nonbasicFlag_.resize(simplex_lp.numCol_ + simplex_lp.numRow_); setNonbasicFlag(simplex_lp, simplex_basis.nonbasicFlag_); // Possibly find a crash basis if (options.simplex_crash_strategy != SIMPLEX_CRASH_STRATEGY_OFF) { HCrash crash(highs_model_object); analysis.simplexTimerStart(CrashClock); crash.crash(options.simplex_crash_strategy); analysis.simplexTimerStop(CrashClock); int num_basic_structurals = 0; for (int iCol = 0; iCol < simplex_lp.numCol_; iCol++) { if (simplex_basis.nonbasicFlag_[iCol] == NONBASIC_FLAG_FALSE) num_basic_structurals++; } HighsLogMessage(options.logfile, HighsMessageType::INFO, "Crash has created a basis with %d/%d structurals", num_basic_structurals, simplex_lp.numRow_); } } // There is now a nonbasicFlag: it should be valid - since it's // just been set but check if (debugNonbasicFlagConsistent(options, simplex_lp, simplex_basis) == HighsDebugStatus::LOGICAL_ERROR) { HighsLogMessage( options.logfile, HighsMessageType::ERROR, "Supposed to be a Simplex basis, but nonbasicFlag not valid"); return -(int)HighsStatus::Error; } // Use nonbasicFlag to form basicIndex // Allocate memory for basicIndex simplex_basis.basicIndex_.resize(simplex_lp.numRow_); int num_basic_variables = 0; simplex_info.num_basic_logicals = 0; for (int iVar = 0; iVar < simplex_lp.numCol_ + simplex_lp.numRow_; iVar++) { if (simplex_basis.nonbasicFlag_[iVar] == NONBASIC_FLAG_FALSE) { simplex_basis.basicIndex_[num_basic_variables] = iVar; if (iVar >= simplex_lp.numCol_) simplex_info.num_basic_logicals++; num_basic_variables++; } } // Double-check that we have the right number of basic variables nonbasicFlag_valid = num_basic_variables == simplex_lp.numRow_; assert(nonbasicFlag_valid); updateSimplexLpStatus(simplex_lp_status, LpAction::NEW_BASIS); } // Execute from here for all calls // // Possibly scale the LP // // If the LP isn't scaled then initialise unit scaling factors, to // simplify things if no scaling is performed. ToDo This is // inefficient if the LP isn't to be scales and is repeatedly // hot-started - but is this really going to happen? if (!simplex_lp_status.scaling_tried) scaleHighsModelInit(highs_model_object); // // Scale the LP to be used by the solver if scaling is to be used and the LP // is not already scaled bool scale_lp = options.simplex_scale_strategy != SIMPLEX_SCALE_STRATEGY_OFF && !simplex_lp_status.scaling_tried; const bool force_no_scaling = false; // true;// if (force_no_scaling) { HighsLogMessage(options.logfile, HighsMessageType::WARNING, "Forcing no scaling"); scale_lp = false; } if (scale_lp) { analysis.simplexTimerStart(ScaleClock); scaleSimplexLp(highs_model_object); analysis.simplexTimerStop(ScaleClock); #ifdef HiGHSDEV // Analyse the scaled LP if (simplex_info.analyse_lp) { analyseLp(simplex_lp, "Unscaled"); HighsScale& scale = highs_model_object.scale_; if (scale.is_scaled_) { analyseVectorValues("Column scaling factors", simplex_lp.numCol_, scale.col_); analyseVectorValues("Row scaling factors", simplex_lp.numRow_, scale.row_); analyseLp(simplex_lp, "Scaled"); } } #endif } // Now there is a valid nonbasicFlag and basicIndex, possibly // reinvert to check for basis condition/singularity // // First setup the factor arrays if they don't exist if (!simplex_lp_status.has_factor_arrays) { assert(simplex_info.factor_pivot_threshold >= options.factor_pivot_threshold); factor.setup(simplex_lp.numCol_, simplex_lp.numRow_, &simplex_lp.Astart_[0], &simplex_lp.Aindex_[0], &simplex_lp.Avalue_[0], &simplex_basis.basicIndex_[0], options.highs_debug_level, options.logfile, options.output, options.message_level, simplex_info.factor_pivot_threshold, options.factor_pivot_tolerance); simplex_lp_status.has_factor_arrays = true; } // Reinvert if there isn't a fresh INVERT. ToDo Override this for MIP hot // start // bool reinvert = !simplex_lp_status.has_fresh_invert; bool reinvert = !simplex_lp_status.has_invert; if (reinvert) { analysis.simplexTimerStart(InvertClock); const int rank_deficiency = computeFactor(highs_model_object); analysis.simplexTimerStop(InvertClock); if (rank_deficiency) { // Basis is rank deficient if (only_from_known_basis) { // If only this basis should be used, then return error HighsLogMessage(options.logfile, HighsMessageType::ERROR, "Supposed to be a full-rank basis, but incorrect"); return rank_deficiency; } else { // Account for rank deficiency by correcing nonbasicFlag simplexHandleRankDeficiency(highs_model_object); updateSimplexLpStatus(simplex_lp_status, LpAction::NEW_BASIS); simplex_lp_status.has_invert = true; simplex_lp_status.has_fresh_invert = true; } } assert(simplex_lp_status.has_invert); } // Possibly check for basis condition. ToDo Override this for MIP hot start bool basis_condition_ok = true; if (options.simplex_initial_condition_check) { const double basis_condition_tolerance = highs_model_object.options_.simplex_initial_condition_tolerance; basis_condition_ok = basisConditionOk(highs_model_object, basis_condition_tolerance); // ToDo Handle ill-conditioned basis with basis crash, in which case // ensure that HiGHS and simplex basis are invalidated and simplex // work and base arrays are re-populated // assert(basis_condition_ok); if (!basis_condition_ok) { // If only this basis should be used, then return error if (only_from_known_basis) { HighsLogMessage( options.logfile, HighsMessageType::ERROR, "Supposed to be a well-conditioned basis, but incorrect"); return -(int)HighsStatus::Error; } // Basis crash really doesn't work, so use logical basis simplex_basis.basicIndex_.resize(simplex_lp.numRow_); for (int iCol = 0; iCol < simplex_lp.numCol_; iCol++) simplex_basis.nonbasicFlag_[iCol] = NONBASIC_FLAG_TRUE; for (int iRow = 0; iRow < simplex_lp.numRow_; iRow++) { int iVar = simplex_lp.numCol_ + iRow; simplex_basis.nonbasicFlag_[iVar] = NONBASIC_FLAG_FALSE; simplex_basis.basicIndex_[iRow] = iVar; } simplex_info.num_basic_logicals = simplex_lp.numRow_; analysis.simplexTimerStart(InvertClock); const int rank_deficiency = computeFactor(highs_model_object); analysis.simplexTimerStop(InvertClock); assert(!rank_deficiency); /* HCrash crash(highs_model_object); analysis.simplexTimerStart(CrashClock); crash.crash(SIMPLEX_CRASH_STRATEGY_BASIC); analysis.simplexTimerStop(CrashClock); HighsLogMessage(options.logfile, HighsMessageType::INFO, "Performed crash to prioritise previously basic variables " "in well-conditioned basis"); // Use nonbasicFlag to form basicIndex // Allocate memory for basicIndex simplex_basis.basicIndex_.resize(simplex_lp.numRow_); int num_basic_variables = 0; simplex_info.num_basic_logicals = 0; for (int iVar = 0; iVar < simplex_lp.numCol_ + simplex_lp.numRow_; iVar++) { if (simplex_basis.nonbasicFlag_[iVar] == NONBASIC_FLAG_FALSE) { simplex_basis.basicIndex_[num_basic_variables] = iVar; if (iVar >= simplex_lp.numCol_) simplex_info.num_basic_logicals++; num_basic_variables++; } } // Double-check that we have the right number of basic variables assert(num_basic_variables == simplex_lp.numRow_); updateSimplexLpStatus(simplex_lp_status, LpAction::NEW_BASIS); // Report on the outcome of crash int num_basic_structurals = simplex_lp.numRow_ - simplex_info.num_basic_logicals; HighsLogMessage(options.logfile, HighsMessageType::INFO, "Crash has created a basis with %d/%d structurals", num_basic_structurals, simplex_lp.numRow_); // Now reinvert int rank_deficiency = computeFactor(highs_model_object); if (rank_deficiency) { // ToDo Handle rank deficiency by replacing singular columns with logicals throw runtime_error("Transition has singular basis matrix"); } // Check the condition after the basis crash basis_condition_ok = basisConditionOk(highs_model_object); */ updateSimplexLpStatus(simplex_lp_status, LpAction::NEW_BASIS); simplex_lp_status.has_invert = true; simplex_lp_status.has_fresh_invert = true; } } // If simplex basis isn't complete, set up nonbasicMove if (!simplex_lp_status.has_basis) { // First determine whether the HiGHS solution space has been // allocated, a necessary condition for its values to be used later const bool have_highs_solution = isSolutionRightSize(highs_model_object.lp_, solution); // Note whether a HiGHS basis can be used to (try to) choose the better // bound for boxed variables const bool have_highs_basis = basis.valid_; simplex_basis.nonbasicMove_.resize(simplex_lp.numCol_ + simplex_lp.numRow_); setNonbasicMove(simplex_lp, scale, have_highs_basis, basis, have_highs_solution, solution, simplex_basis); simplex_lp_status.has_basis = true; } assert(simplex_lp_status.has_basis); return 0; } HighsStatus transition(HighsModelObject& highs_model_object) { // Perform the transition from whatever information is known about // the LP to a status where simplex data are set up for the initial // rebuild() of the chosen solver - primal, scalar dual or parallel // dual. // // First look at what basis and solution information is known. If a // simplex basis is known, then it's used, and there's no need for // the solution values. This will usually correspond to hot start // when solving MIP problems. Otherwise, generate a simplex basis, // thus: // // If there is a HiGHS basis: use it to determine what's basic and nonbasic // (nonbasicFlag). // // If there's no HiGHS basis: generate nonbasicFlag, possibly by dualising and // performing a crash. // // Use nonbasicFlag to generate basicIndex // // Use nonbasicFlag and any HiGHS solution to determine nonbasicMove // HighsStatus return_status = HighsStatus::OK; const HighsSolution& solution = highs_model_object.solution_; HighsLp& simplex_lp = highs_model_object.simplex_lp_; HighsSimplexInfo& simplex_info = highs_model_object.simplex_info_; HighsSimplexLpStatus& simplex_lp_status = highs_model_object.simplex_lp_status_; SimplexBasis& simplex_basis = highs_model_object.simplex_basis_; HMatrix& matrix = highs_model_object.matrix_; HighsSimplexAnalysis& analysis = highs_model_object.simplex_analysis_; int return_code; // Perform the transition from whatever information is known about // the LP to a status where the LP is scaled and has the inverse of // a basis. analysis.simplexTimerStart(initialiseSimplexLpBasisAndFactorClock); return_code = initialiseSimplexLpBasisAndFactor(highs_model_object); analysis.simplexTimerStop(initialiseSimplexLpBasisAndFactorClock); assert(return_code <= 0); if (return_code) { highs_model_object.scaled_model_status_ = HighsModelStatus::SOLVE_ERROR; return HighsStatus::Error; } // Now there is a simplex basis corresponding to a well-conditioned // invertible representation assert(simplex_lp_status.has_basis); assert(simplex_lp_status.has_invert); // Now that the dimensions of the LP to be solved by the simplex // method are known, make sure that there is a postive number of // rows. ToDo: Ensure that LPs with no rows can still be solved assert(simplex_lp.numRow_ > 0); if (simplex_lp.numRow_ == 0) { printf("Solution of LPs with no rows shouldn't reach transition()\n"); highs_model_object.scaled_model_status_ = HighsModelStatus::SOLVE_ERROR; return HighsStatus::Error; } // Possibly set up the HMatrix column-wise and row-wise copies of the matrix if (!simplex_lp_status.has_matrix_col_wise || !simplex_lp_status.has_matrix_row_wise) { analysis.simplexTimerStart(matrixSetupClock); matrix.setup(simplex_lp.numCol_, simplex_lp.numRow_, &simplex_lp.Astart_[0], &simplex_lp.Aindex_[0], &simplex_lp.Avalue_[0], &simplex_basis.nonbasicFlag_[0]); simplex_lp_status.has_matrix_col_wise = true; simplex_lp_status.has_matrix_row_wise = true; analysis.simplexTimerStop(matrixSetupClock); } // Set up the simplex work and base arrays analysis.simplexTimerStart(allocateSimplexArraysClock); allocateWorkAndBaseArrays(highs_model_object); analysis.simplexTimerStop(allocateSimplexArraysClock); analysis.simplexTimerStart(initialiseSimplexCostBoundsClock); initialiseCost(highs_model_object); initialiseBound(highs_model_object); analysis.simplexTimerStop(initialiseSimplexCostBoundsClock); // Possibly solve for the basic primal and nonbasic dual values to determine // which simplex solver to use, unless it's forced // if (simplex_lp_status.has_basic_primal_values) { initialiseNonbasicWorkValue(simplex_lp, simplex_basis, simplex_info); analysis.simplexTimerStart(ComputePrimalClock); computePrimal(highs_model_object); analysis.simplexTimerStop(ComputePrimalClock); simplex_lp_status.has_basic_primal_values = true; //} // if (simplex_lp_status.has_basic_dual_values) { analysis.simplexTimerStart(ComputeDualClock); computeDual(highs_model_object); analysis.simplexTimerStop(ComputeDualClock); simplex_lp_status.has_nonbasic_dual_values = true; //} const bool have_highs_solution = isSolutionRightSize(highs_model_object.lp_, solution); if (have_highs_solution) { // There is a HiGHS solution so possibly determine the changes in // basic and nonbasic values and duals for columns and rows if (debugSimplexHighsSolutionDifferences(highs_model_object) == HighsDebugStatus::LOGICAL_ERROR) return HighsStatus::Error; } // Store, analyse and possibly report the number of primal and dual // infeasiblities and the simplex status computeSimplexInfeasible(highs_model_object); copySimplexInfeasible(highs_model_object); HighsSolutionParams& scaled_solution_params = highs_model_object.scaled_solution_params_; analysis.simplexTimerStart(ComputeDuObjClock); computeDualObjectiveValue(highs_model_object); analysis.simplexTimerStop(ComputeDuObjClock); analysis.simplexTimerStart(ComputePrObjClock); computePrimalObjectiveValue(highs_model_object); analysis.simplexTimerStop(ComputePrObjClock); simplex_lp_status.valid = true; bool primal_feasible = scaled_solution_params.num_primal_infeasibilities == 0; bool dual_feasible = scaled_solution_params.num_dual_infeasibilities == 0; if (primal_feasible && dual_feasible) { highs_model_object.scaled_model_status_ = HighsModelStatus::OPTIMAL; scaled_solution_params.primal_status = PrimalDualStatus::STATUS_FEASIBLE_POINT; scaled_solution_params.dual_status = PrimalDualStatus::STATUS_FEASIBLE_POINT; } scaled_solution_params.objective_function_value = simplex_info.primal_objective_value; if (debugSimplexBasicSolution("After transition", highs_model_object) == HighsDebugStatus::LOGICAL_ERROR) return HighsStatus::Error; return return_status; } void setNonbasicFlag(const HighsLp& simplex_lp, vector<int>& nonbasicFlag, const HighsBasisStatus* col_status, const HighsBasisStatus* row_status) { if (col_status == NULL || row_status == NULL) { // Initialise a logical basis for (int iCol = 0; iCol < simplex_lp.numCol_; iCol++) { int iVar = iCol; nonbasicFlag[iVar] = NONBASIC_FLAG_TRUE; } for (int iRow = 0; iRow < simplex_lp.numRow_; iRow++) { int iVar = simplex_lp.numCol_ + iRow; nonbasicFlag[iVar] = NONBASIC_FLAG_FALSE; } } else { // Initialise from HiGHS basis for (int iCol = 0; iCol < simplex_lp.numCol_; iCol++) { int iVar = iCol; if (col_status[iCol] == HighsBasisStatus::BASIC) { nonbasicFlag[iVar] = NONBASIC_FLAG_FALSE; } else { nonbasicFlag[iVar] = NONBASIC_FLAG_TRUE; } } for (int iRow = 0; iRow < simplex_lp.numRow_; iRow++) { int iVar = simplex_lp.numCol_ + iRow; if (row_status[iRow] == HighsBasisStatus::BASIC) { nonbasicFlag[iVar] = NONBASIC_FLAG_FALSE; } else { nonbasicFlag[iVar] = NONBASIC_FLAG_TRUE; } } } } void setNonbasicMove(const HighsLp& simplex_lp, const HighsScale& scale, const bool have_highs_basis, const HighsBasis& basis, const bool have_highs_solution, const HighsSolution& solution, SimplexBasis& simplex_basis) { // Don't have a simplex basis since nonbasicMove is not set up. const int illegal_move_value = -99; // Assign nonbasicMove using as much information as is available double lower; double upper; const int numTot = simplex_lp.numCol_ + simplex_lp.numRow_; for (int iVar = 0; iVar < numTot; iVar++) { if (!simplex_basis.nonbasicFlag_[iVar]) { // Basic variable simplex_basis.nonbasicMove_[iVar] = 0; continue; } // Nonbasic variable if (iVar < simplex_lp.numCol_) { lower = simplex_lp.colLower_[iVar]; upper = simplex_lp.colUpper_[iVar]; } else { int iRow = iVar - simplex_lp.numCol_; lower = -simplex_lp.rowUpper_[iRow]; upper = -simplex_lp.rowLower_[iRow]; } int move = illegal_move_value; if (lower == upper) { // Fixed move = NONBASIC_MOVE_ZE; } else if (!highs_isInfinity(-lower)) { // Finite lower bound so boxed or lower if (!highs_isInfinity(upper)) { // Finite upper bound so boxed // // Determine the bound to set the value to according to, in order of // priority // // 1. Any valid HiGHS basis status if (have_highs_basis) { if (iVar < simplex_lp.numCol_) { if (basis.col_status[iVar] == HighsBasisStatus::LOWER) { move = NONBASIC_MOVE_UP; } else if (basis.col_status[iVar] == HighsBasisStatus::UPPER) { move = NONBASIC_MOVE_DN; } } else { int iRow = iVar - simplex_lp.numCol_; if (basis.row_status[iRow] == HighsBasisStatus::LOWER) { move = NONBASIC_MOVE_DN; } else if (basis.row_status[iRow] == HighsBasisStatus::UPPER) { move = NONBASIC_MOVE_UP; } } } // 2. Any HiGHS solution value if (move == illegal_move_value && have_highs_solution) { // Reach here if there is no HiGHS basis or the HiGHS // nonbasic status is just NONBASIC. double midpoint = 0.5 * (lower + upper); double value_from_highs_solution; if (iVar < simplex_lp.numCol_) { assert(!have_highs_basis || basis.col_status[iVar] == HighsBasisStatus::NONBASIC); value_from_highs_solution = solution.col_value[iVar] / scale.col_[iVar]; } else { int iRow = iVar - simplex_lp.numCol_; assert(!have_highs_basis || basis.row_status[iRow] == HighsBasisStatus::NONBASIC); value_from_highs_solution = -solution.row_value[iRow] * scale.row_[iRow]; } if (value_from_highs_solution < midpoint) { move = NONBASIC_MOVE_UP; } else { move = NONBASIC_MOVE_DN; } } // 3. Bound of original LP that is closer to zero if (move == illegal_move_value) { if (fabs(lower) < fabs(upper)) { move = NONBASIC_MOVE_UP; } else { move = NONBASIC_MOVE_DN; } } } else { // Lower (since upper bound is infinite) move = NONBASIC_MOVE_UP; } } else if (!highs_isInfinity(upper)) { // Upper move = NONBASIC_MOVE_DN; } else { // FREE move = NONBASIC_MOVE_ZE; } assert(move != illegal_move_value); simplex_basis.nonbasicMove_[iVar] = move; } } void initialiseNonbasicWorkValue(const HighsLp& simplex_lp, const SimplexBasis& simplex_basis, HighsSimplexInfo& simplex_info) { // Assign nonbasic values from bounds and (if necessary) nonbasicMove const int numTot = simplex_lp.numCol_ + simplex_lp.numRow_; for (int iVar = 0; iVar < numTot; iVar++) { if (!simplex_basis.nonbasicFlag_[iVar]) continue; // Nonbasic variable const double lower = simplex_info.workLower_[iVar]; const double upper = simplex_info.workUpper_[iVar]; double value; if (lower == upper) { value = lower; } else if (simplex_basis.nonbasicMove_[iVar] == NONBASIC_MOVE_UP) { value = lower; } else if (simplex_basis.nonbasicMove_[iVar] == NONBASIC_MOVE_DN) { value = upper; } else { assert(simplex_basis.nonbasicMove_[iVar] == NONBASIC_MOVE_ZE); value = 0; } simplex_info.workValue_[iVar] = value; } } bool basisConditionOk(HighsModelObject& highs_model_object, const double tolerance) { HighsSimplexAnalysis& analysis = highs_model_object.simplex_analysis_; bool basis_condition_ok; analysis.simplexTimerStart(BasisConditionClock); double basis_condition = computeBasisCondition(highs_model_object); analysis.simplexTimerStop(BasisConditionClock); basis_condition_ok = basis_condition <= tolerance; HighsMessageType message_type = HighsMessageType::INFO; std::string condition_comment; if (basis_condition_ok) { condition_comment = "is within"; } else { message_type = HighsMessageType::WARNING; condition_comment = "exceeds"; } HighsLogMessage(highs_model_object.options_.logfile, message_type, "Basis condition estimate of %11.4g %s the tolerance of %g", basis_condition, condition_comment.c_str(), tolerance); return basis_condition_ok; } bool dual_infeasible(const double value, const double lower, const double upper, const double dual, const double value_tolerance, const double dual_tolerance) { double midpoint = (lower + upper) * 0.5; double residual = max(lower - value, value - upper); bool infeasible = false; if (highs_isInfinity(-lower)) { // Infinite lower bound if (highs_isInfinity(upper)) { // Infinite upper bound // Free infeasible = fabs(dual) >= dual_tolerance; } else { // Finite upper bound // Upper bounded - and assumed to be nonbasic at that bound if (fabs(residual) >= value_tolerance) { printf("dual_infeasible: %12g %12g %12g %12g %12g\n", value, lower, upper, residual, value_tolerance); } assert(fabs(residual) < value_tolerance); infeasible = dual >= dual_tolerance; } } else { // Finite lower bound if (highs_isInfinity(upper)) { // Infinite upper bound // Lower bounded - and assumed to be nonbasic at that bound assert(fabs(residual) < value_tolerance); infeasible = dual <= -dual_tolerance; } else { // Finite upper bound // Assumed to be nonbasic at that bound assert(fabs(residual) < value_tolerance); if (lower < upper) { if (value < midpoint) { infeasible = dual <= -dual_tolerance; } else { infeasible = dual >= dual_tolerance; } } else { infeasible = false; } } } return infeasible; } void appendNonbasicColsToBasis(HighsLp& lp, HighsBasis& basis, int XnumNewCol) { assert(basis.valid_); if (!basis.valid_) { printf("\n!!Appending columns to invalid basis!!\n\n"); } // Add nonbasic structurals if (XnumNewCol == 0) return; int newNumCol = lp.numCol_ + XnumNewCol; basis.col_status.resize(newNumCol); // Make any new columns nonbasic for (int iCol = lp.numCol_; iCol < newNumCol; iCol++) { if (!highs_isInfinity(-lp.colLower_[iCol])) { basis.col_status[iCol] = HighsBasisStatus::LOWER; } else if (!highs_isInfinity(lp.colUpper_[iCol])) { basis.col_status[iCol] = HighsBasisStatus::UPPER; } else { basis.col_status[iCol] = HighsBasisStatus::ZERO; } } } void appendNonbasicColsToBasis(HighsLp& lp, SimplexBasis& basis, int XnumNewCol) { // Add nonbasic structurals if (XnumNewCol == 0) return; int newNumCol = lp.numCol_ + XnumNewCol; int newNumTot = newNumCol + lp.numRow_; basis.nonbasicFlag_.resize(newNumTot); basis.nonbasicMove_.resize(newNumTot); // Shift the row data in basicIndex, nonbasicFlag and nonbasicMove if // necessary for (int iRow = lp.numRow_ - 1; iRow >= 0; iRow--) { int iCol = basis.basicIndex_[iRow]; if (iCol >= lp.numCol_) { // This basic variable is a row, so shift its index basis.basicIndex_[iRow] += XnumNewCol; } basis.nonbasicFlag_[newNumCol + iRow] = basis.nonbasicFlag_[lp.numCol_ + iRow]; basis.nonbasicMove_[newNumCol + iRow] = basis.nonbasicMove_[lp.numCol_ + iRow]; } // Make any new columns nonbasic const int illegal_move_value = -99; for (int iCol = lp.numCol_; iCol < newNumCol; iCol++) { basis.nonbasicFlag_[iCol] = NONBASIC_FLAG_TRUE; double lower = lp.colLower_[iCol]; double upper = lp.colUpper_[iCol]; int move = illegal_move_value; if (lower == upper) { // Fixed move = NONBASIC_MOVE_ZE; } else if (!highs_isInfinity(-lower)) { // Finite lower bound so boxed or lower if (!highs_isInfinity(upper)) { // Finite upper bound so boxed if (fabs(lower) < fabs(upper)) { move = NONBASIC_MOVE_UP; } else { move = NONBASIC_MOVE_DN; } } else { // Lower (since upper bound is infinite) move = NONBASIC_MOVE_UP; } } else if (!highs_isInfinity(upper)) { // Upper move = NONBASIC_MOVE_DN; } else { // FREE move = NONBASIC_MOVE_ZE; } assert(move != illegal_move_value); basis.nonbasicMove_[iCol] = move; } } void appendBasicRowsToBasis(HighsLp& lp, HighsBasis& basis, int XnumNewRow) { assert(basis.valid_); if (!basis.valid_) { printf("\n!!Appending columns to invalid basis!!\n\n"); } // Add basic logicals if (XnumNewRow == 0) return; int newNumRow = lp.numRow_ + XnumNewRow; basis.row_status.resize(newNumRow); // Make the new rows basic for (int iRow = lp.numRow_; iRow < newNumRow; iRow++) { basis.row_status[iRow] = HighsBasisStatus::BASIC; } } void appendBasicRowsToBasis(HighsLp& lp, SimplexBasis& basis, int XnumNewRow) { // Add basic logicals if (XnumNewRow == 0) return; int newNumRow = lp.numRow_ + XnumNewRow; int newNumTot = lp.numCol_ + newNumRow; basis.nonbasicFlag_.resize(newNumTot); basis.nonbasicMove_.resize(newNumTot); basis.basicIndex_.resize(newNumRow); // Make the new rows basic for (int iRow = lp.numRow_; iRow < newNumRow; iRow++) { basis.nonbasicFlag_[lp.numCol_ + iRow] = NONBASIC_FLAG_FALSE; basis.nonbasicMove_[lp.numCol_ + iRow] = 0; basis.basicIndex_[iRow] = lp.numCol_ + iRow; } } void reportBasis(const HighsOptions options, const HighsLp& lp, const HighsBasis& basis) { if (lp.numCol_ > 0) HighsPrintMessage(options.output, options.message_level, ML_ALWAYS, "HighsBasis\n Col Status\n"); for (int iCol = 0; iCol < lp.numCol_; iCol++) { HighsPrintMessage(options.output, options.message_level, ML_ALWAYS, "%6d %6d\n", iCol, (int)basis.col_status[iCol]); } if (lp.numRow_ > 0) HighsPrintMessage(options.output, options.message_level, ML_ALWAYS, " Row Status\n"); for (int iRow = 0; iRow < lp.numRow_; iRow++) { HighsPrintMessage(options.output, options.message_level, ML_ALWAYS, "%6d %6d\n", iRow, (int)basis.row_status[iRow]); } } void reportBasis(const HighsOptions options, const HighsLp& lp, const SimplexBasis& simplex_basis) { if (lp.numCol_ > 0) HighsPrintMessage(options.output, options.message_level, ML_ALWAYS, "SimplexBasis\n Var Col Flag\n"); for (int iCol = 0; iCol < lp.numCol_; iCol++) { int iVar = iCol; if (simplex_basis.nonbasicFlag_[iVar]) HighsPrintMessage(options.output, options.message_level, ML_ALWAYS, "%6d %6d %6d\n", iVar, iCol, simplex_basis.nonbasicFlag_[iVar]); else HighsPrintMessage(options.output, options.message_level, ML_ALWAYS, "%6d %6d %6d\n", iVar, iCol, simplex_basis.nonbasicFlag_[iVar]); } if (lp.numRow_ > 0) HighsPrintMessage(options.output, options.message_level, ML_ALWAYS, " Var Row Flag Basic\n"); for (int iRow = 0; iRow < lp.numRow_; iRow++) { int iVar = lp.numCol_ + iRow; if (simplex_basis.nonbasicFlag_[iVar]) HighsPrintMessage(options.output, options.message_level, ML_ALWAYS, "%6d %6d %6d %6d\n", iVar, iRow, simplex_basis.nonbasicFlag_[iVar], simplex_basis.basicIndex_[iRow]); else HighsPrintMessage(options.output, options.message_level, ML_ALWAYS, "%6d %6d %6d %6d\n", iVar, iRow, simplex_basis.nonbasicFlag_[iVar], simplex_basis.basicIndex_[iRow]); } } /** * @brief Simplex utilities */ void computeDualObjectiveValue(HighsModelObject& highs_model_object, int phase) { HighsLp& simplex_lp = highs_model_object.simplex_lp_; HighsSimplexInfo& simplex_info = highs_model_object.simplex_info_; HighsSimplexLpStatus& simplex_lp_status = highs_model_object.simplex_lp_status_; simplex_info.dual_objective_value = 0; const int numTot = simplex_lp.numCol_ + simplex_lp.numRow_; for (int i = 0; i < numTot; i++) { if (highs_model_object.simplex_basis_.nonbasicFlag_[i]) { const double term = simplex_info.workValue_[i] * simplex_info.workDual_[i]; if (term) { simplex_info.dual_objective_value += simplex_info.workValue_[i] * simplex_info.workDual_[i]; } } } simplex_info.dual_objective_value *= highs_model_object.scale_.cost_; if (phase != 1) { // In phase 1 the dual objective has no objective // shift. Otherwise, if minimizing the shift is added. If // maximizing, workCost (and hence workDual) are negated, so the // shift is subtracted. Hence the shift is added according to the // sign implied by sense_ simplex_info.dual_objective_value += ((int)simplex_lp.sense_) * simplex_lp.offset_; } // Now have dual objective value simplex_lp_status.has_dual_objective_value = true; } int setSourceOutFmBd(const HighsModelObject& highs_model_object, const int columnOut) { const HighsSimplexInfo& simplex_info = highs_model_object.simplex_info_; int sourceOut = 0; if (simplex_info.workLower_[columnOut] != simplex_info.workUpper_[columnOut]) { if (!highs_isInfinity(-simplex_info.workLower_[columnOut])) { // Finite LB so sourceOut = -1 ensures value set to LB if LB < UB sourceOut = -1; // printf("STRANGE: variable %d leaving the basis is [%11.4g, %11.4g] // so setting sourceOut = -1\n", columnOut, // simplex_info.workLower_[columnOut], // simplex_info.workUpper_[columnOut]); } else { // Infinite LB so sourceOut = 1 ensures value set to UB sourceOut = 1; if (!highs_isInfinity(simplex_info.workUpper_[columnOut])) { // Free variable => trouble! printf("TROUBLE: variable %d leaving the basis is free!\n", columnOut); } } } return sourceOut; } void computePrimalObjectiveValue(HighsModelObject& highs_model_object) { HighsLp& simplex_lp = highs_model_object.simplex_lp_; HighsSimplexInfo& simplex_info = highs_model_object.simplex_info_; SimplexBasis& simplex_basis = highs_model_object.simplex_basis_; HighsSimplexLpStatus& simplex_lp_status = highs_model_object.simplex_lp_status_; simplex_info.primal_objective_value = 0; for (int iRow = 0; iRow < simplex_lp.numRow_; iRow++) { int iVar = simplex_basis.basicIndex_[iRow]; if (iVar < simplex_lp.numCol_) { simplex_info.primal_objective_value += simplex_info.baseValue_[iRow] * simplex_lp.colCost_[iVar]; } } for (int iCol = 0; iCol < simplex_lp.numCol_; iCol++) { if (simplex_basis.nonbasicFlag_[iCol]) simplex_info.primal_objective_value += simplex_info.workValue_[iCol] * simplex_lp.colCost_[iCol]; } simplex_info.primal_objective_value *= highs_model_object.scale_.cost_; // Objective value calculation is done using primal values and // original costs so offset is vanilla simplex_info.primal_objective_value += simplex_lp.offset_; // Now have primal objective value simplex_lp_status.has_primal_objective_value = true; } #ifdef HiGHSDEV void getPrimalValue(const HighsModelObject& highs_model_object, vector<double>& primal_value) { const HighsLp& simplex_lp = highs_model_object.simplex_lp_; const HighsSimplexInfo& simplex_info = highs_model_object.simplex_info_; const SimplexBasis& simplex_basis = highs_model_object.simplex_basis_; // Copy all of workValue to get all the nonbasic values primal_value.resize(simplex_lp.numCol_ + simplex_lp.numRow_); for (int iCol = 0; iCol < simplex_lp.numCol_ + simplex_lp.numRow_; iCol++) primal_value[iCol] = simplex_info.workValue_[iCol]; // Over-write the value of the nonbasic variables for (int iRow = 0; iRow < simplex_lp.numRow_; iRow++) primal_value[simplex_basis.basicIndex_[iRow]] = simplex_info.baseValue_[iRow]; } void analysePrimalObjectiveValue(const HighsModelObject& highs_model_object) { const HighsLp& simplex_lp = highs_model_object.simplex_lp_; const HighsSimplexInfo& simplex_info = highs_model_object.simplex_info_; const SimplexBasis& simplex_basis = highs_model_object.simplex_basis_; HighsValueDistribution objective_value_term_distribution; HighsValueDistribution basic_value_distribution; HighsValueDistribution basic_cost_distribution; initialiseValueDistribution("Nonzero objective terms", "", 1e-16, 1e16, 10.0, objective_value_term_distribution); initialiseValueDistribution("Basic values", "", 1e-16, 1e16, 10.0, basic_value_distribution); initialiseValueDistribution("Nonzero basic costs", "", 1e-16, 1e16, 10.0, basic_cost_distribution); double primal_objective_value = 0; for (int iRow = 0; iRow < simplex_lp.numRow_; iRow++) { int iVar = simplex_basis.basicIndex_[iRow]; const double value = simplex_info.baseValue_[iRow]; updateValueDistribution(value, basic_value_distribution); if (iVar < simplex_lp.numCol_) { const double cost = simplex_lp.colCost_[iVar]; if (cost) { updateValueDistribution(cost, basic_cost_distribution); const double term = value * cost; primal_objective_value += term; const double abs_term = fabs(term); updateValueDistribution(abs_term, objective_value_term_distribution); } } } HighsValueDistribution nonbasic_value_distribution; HighsValueDistribution nonbasic_cost_distribution; initialiseValueDistribution("Nonbasic values", "", 1e-16, 1e16, 10.0, nonbasic_value_distribution); initialiseValueDistribution("Nonzero nonbasic costs", "", 1e-16, 1e16, 10.0, nonbasic_cost_distribution); for (int iCol = 0; iCol < simplex_lp.numCol_; iCol++) { if (simplex_basis.nonbasicFlag_[iCol]) { const double value = simplex_info.workValue_[iCol]; updateValueDistribution(value, nonbasic_value_distribution); const double cost = simplex_lp.colCost_[iCol]; if (cost) { updateValueDistribution(cost, nonbasic_cost_distribution); const double term = value * cost; primal_objective_value += term; const double abs_term = fabs(term); updateValueDistribution(abs_term, objective_value_term_distribution); } } } for (int iCol = simplex_lp.numCol_; iCol < simplex_lp.numCol_ + simplex_lp.numRow_; iCol++) { if (simplex_basis.nonbasicFlag_[iCol]) { const double value = simplex_info.workValue_[iCol]; updateValueDistribution(value, nonbasic_value_distribution); } } printf("\nAnalysis of values, costs and objective terms:\n"); printValueDistribution(nonbasic_value_distribution); printValueDistribution(basic_value_distribution); printValueDistribution(nonbasic_cost_distribution); printValueDistribution(basic_cost_distribution); printValueDistribution(objective_value_term_distribution); printf("Linear objective value: %g\n", primal_objective_value); primal_objective_value *= highs_model_object.scale_.cost_; printf("Scaled objective value: %g\n", primal_objective_value); // Objective value calculation is done using primal values and // original costs so offset is vanilla primal_objective_value -= simplex_lp.offset_; printf("Offset objective value: %g\n", primal_objective_value); } #endif void initialiseSimplexLpDefinition(HighsModelObject& highs_model_object) { HighsSimplexLpStatus& simplex_lp_status = highs_model_object.simplex_lp_status_; // Ensure that the simplex LP is fully invalidated invalidateSimplexLp(simplex_lp_status); // Copy the LP to the structure to be used by the solver highs_model_object.simplex_lp_ = highs_model_object.lp_; } void initialiseSimplexLpRandomVectors(HighsModelObject& highs_model_object) { HighsSimplexInfo& simplex_info = highs_model_object.simplex_info_; const int numCol = highs_model_object.simplex_lp_.numCol_; const int numTot = highs_model_object.simplex_lp_.numCol_ + highs_model_object.simplex_lp_.numRow_; if (!numTot) return; // Instantiate and (re-)initialise the random number generator HighsRandom& random = highs_model_object.random_; random.initialise(); if (numCol) { // Generate a random permutation of the column indices simplex_info.numColPermutation_.resize(numCol); int* numColPermutation = &simplex_info.numColPermutation_[0]; for (int i = 0; i < numCol; i++) numColPermutation[i] = i; for (int i = numCol - 1; i >= 1; i--) { int j = random.integer() % (i + 1); std::swap(numColPermutation[i], numColPermutation[j]); } } // Re-initialise the random number generator and generate the // random vectors in the same order as hsol to maintain repeatable // performance random.initialise(); // // Generate a random permutation of all the indices simplex_info.numTotPermutation_.resize(numTot); int* numTotPermutation = &simplex_info.numTotPermutation_[0]; for (int i = 0; i < numTot; i++) numTotPermutation[i] = i; for (int i = numTot - 1; i >= 1; i--) { int j = random.integer() % (i + 1); std::swap(numTotPermutation[i], numTotPermutation[j]); } // Generate a vector of random reals simplex_info.numTotRandomValue_.resize(numTot); double* numTotRandomValue = &simplex_info.numTotRandomValue_[0]; for (int i = 0; i < numTot; i++) { numTotRandomValue[i] = random.fraction(); } } void extendSimplexLpRandomVectors(HighsModelObject& highs_model_object, const int num_new_col, const int num_new_row) { HighsSimplexInfo& simplex_info = highs_model_object.simplex_info_; const int numCol = highs_model_object.simplex_lp_.numCol_; const int numTot = highs_model_object.simplex_lp_.numCol_ + highs_model_object.simplex_lp_.numRow_; assert(num_new_col >= 0); assert(num_new_row >= 0); if (num_new_col + num_new_row == 0) return; const int new_numCol = numCol + num_new_col; const int new_numTot = numTot + num_new_col + num_new_row; // Instantiate and (re-)initialise the random number generator HighsRandom& random = highs_model_object.random_; random.initialise(); // // Extend a random permutation of the column indices if (num_new_col) { simplex_info.numColPermutation_.resize(new_numCol); int* numColPermutation = &simplex_info.numColPermutation_[0]; for (int i = numCol; i < new_numCol; i++) numColPermutation[i] = i; for (int i = new_numCol - 1; i >= numCol + 1; i--) { int j = random.integer() % (i + 1); std::swap(numColPermutation[i], numColPermutation[j]); } } // Re-initialise the random number generator and generate the // random vectors in the same order as hsol to maintain repeatable // performance random.initialise(); // // Extend a random permutation of all the indices simplex_info.numTotPermutation_.resize(new_numTot); int* numTotPermutation = &simplex_info.numTotPermutation_[0]; for (int i = numTot; i < new_numTot; i++) numTotPermutation[i] = i; for (int i = new_numTot - 1; i >= numTot + 1; i--) { int j = random.integer() % (i + 1); std::swap(numTotPermutation[i], numTotPermutation[j]); } // Extend a vector of random reals simplex_info.numTotRandomValue_.resize(new_numTot); double* numTotRandomValue = &simplex_info.numTotRandomValue_[0]; for (int i = numTot; i < new_numTot; i++) { numTotRandomValue[i] = random.fraction(); } } // SCALING: #ifdef HiGHSDEV // Information on large costs const double tlLargeCo = 1e5; int numLargeCo; vector<int> largeCostFlag; double largeCostScale; #endif void scaleHighsModelInit(HighsModelObject& highs_model_object) { HighsScale& scale = highs_model_object.scale_; scale.is_scaled_ = false; scale.col_.assign(highs_model_object.simplex_lp_.numCol_, 1); scale.row_.assign(highs_model_object.simplex_lp_.numRow_, 1); scale.cost_ = 1; #ifdef HiGHSDEV // largeCostScale = 1; #endif } void scaleCosts(HighsModelObject& highs_model_object) { // Scale the costs by no less than minAlwCostScale double max_allowed_cost_scale = pow(2.0, highs_model_object.options_.allowed_simplex_cost_scale_factor); double cost_scale; double max_nonzero_cost = 0; for (int iCol = 0; iCol < highs_model_object.simplex_lp_.numCol_; iCol++) { if (highs_model_object.simplex_lp_.colCost_[iCol]) { max_nonzero_cost = max(fabs(highs_model_object.simplex_lp_.colCost_[iCol]), max_nonzero_cost); } } // Scaling the costs up effectively increases the dual tolerance to // which the problem is solved - so, if the max cost is small the // scaling factor pushes it up by a power of 2 so it's close to 1 // Scaling the costs down effectively decreases the dual tolerance // to which the problem is solved - so this can't be done too much cost_scale = 1; const double ln2 = log(2.0); // Scale if the max cost is positive and outside the range [1/16, 16] if ((max_nonzero_cost > 0) && ((max_nonzero_cost < (1.0 / 16)) || (max_nonzero_cost > 16))) { cost_scale = max_nonzero_cost; cost_scale = pow(2.0, floor(log(cost_scale) / ln2 + 0.5)); cost_scale = min(cost_scale, max_allowed_cost_scale); } highs_model_object.scale_.cost_ = cost_scale; if (cost_scale == 1) return; // Scale the costs (and record of max_nonzero_cost) by cost_scale, being at // most max_allowed_cost_scale for (int iCol = 0; iCol < highs_model_object.simplex_lp_.numCol_; iCol++) { highs_model_object.simplex_lp_.colCost_[iCol] /= cost_scale; } max_nonzero_cost /= cost_scale; #ifdef HiGHSDEV /* bool alwLargeCostScaling = false; if (alwLargeCostScaling && (numLargeCo > 0)) { // Scale any large costs by largeCostScale, being at most (a further) // max_allowed_cost_scale largeCostScale = max_nonzero_cost; largeCostScale = pow(2.0, floor(log(largeCostScale) / ln2 + 0.5)); largeCostScale = min(largeCostScale, max_allowed_cost_scale); printf( " Scaling all |cost| > %11.4g by %11.4g\ngrep_LargeCostScale,%g,%g\n", tlLargeCo, largeCostScale, tlLargeCo, largeCostScale); for (int iCol = 0; iCol < highs_model_object.simplex_lp_.numCol_; iCol++) { if (largeCostFlag[iCol]) { highs_model_object.simplex_lp_.colCost_[iCol] /= largeCostScale; } } } */ // utils.analyseVectorValues("Column costs", // highs_model_object.simplex_lp_.numCol_, // highs_model_object.simplex_lp_.colCost_); #endif } void scaleFactorRanges(HighsModelObject& highs_model_object, double& min_col_scale, double& max_col_scale, double& min_row_scale, double& max_row_scale) { int numCol = highs_model_object.simplex_lp_.numCol_; int numRow = highs_model_object.simplex_lp_.numRow_; double* colScale = &highs_model_object.scale_.col_[0]; double* rowScale = &highs_model_object.scale_.row_[0]; // Determine the max and min row and column scaling factors min_col_scale = HIGHS_CONST_INF; max_col_scale = 1 / HIGHS_CONST_INF; min_row_scale = HIGHS_CONST_INF; max_row_scale = 1 / HIGHS_CONST_INF; for (int iCol = 0; iCol < numCol; iCol++) { min_col_scale = min(colScale[iCol], min_col_scale); max_col_scale = max(colScale[iCol], max_col_scale); } for (int iRow = 0; iRow < numRow; iRow++) { min_row_scale = min(rowScale[iRow], min_row_scale); max_row_scale = max(rowScale[iRow], max_row_scale); } } void scaleSimplexLp(HighsModelObject& highs_model_object) { // HighsSimplexInfo &simplex_info = highs_model_object.simplex_info_; HighsSimplexLpStatus& simplex_lp_status = highs_model_object.simplex_lp_status_; if (simplex_lp_status.scaling_tried) return; // Scale the LP highs_model_object.simplex_lp_, assuming all data are in place HighsScale& scale = highs_model_object.scale_; // Reset all scaling to 1 scaleHighsModelInit(highs_model_object); int numCol = highs_model_object.simplex_lp_.numCol_; int numRow = highs_model_object.simplex_lp_.numRow_; double* colScale = &highs_model_object.scale_.col_[0]; double* rowScale = &highs_model_object.scale_.row_[0]; int* Astart = &highs_model_object.simplex_lp_.Astart_[0]; double* Avalue = &highs_model_object.simplex_lp_.Avalue_[0]; double* colCost = &highs_model_object.simplex_lp_.colCost_[0]; double* colLower = &highs_model_object.simplex_lp_.colLower_[0]; double* colUpper = &highs_model_object.simplex_lp_.colUpper_[0]; double* rowLower = &highs_model_object.simplex_lp_.rowLower_[0]; double* rowUpper = &highs_model_object.simplex_lp_.rowUpper_[0]; // Allow a switch to/from the original scaling rules int simplex_scale_strategy = highs_model_object.options_.simplex_scale_strategy; bool allow_cost_scaling = highs_model_object.options_.allowed_simplex_cost_scale_factor > 0; // Find out range of matrix values and skip matrix scaling if all // |values| are in [0.2, 5] const double no_scaling_original_matrix_min_value = 0.2; const double no_scaling_original_matrix_max_value = 5.0; double original_matrix_min_value = HIGHS_CONST_INF; double original_matrix_max_value = 0; for (int k = 0, AnX = Astart[numCol]; k < AnX; k++) { double value = fabs(Avalue[k]); original_matrix_min_value = min(original_matrix_min_value, value); original_matrix_max_value = max(original_matrix_max_value, value); } bool no_scaling = (original_matrix_min_value >= no_scaling_original_matrix_min_value) && (original_matrix_max_value <= no_scaling_original_matrix_max_value); const bool force_scaling = false; if (force_scaling) { no_scaling = false; printf("!!!! FORCE SCALING !!!!\n"); } bool scaled_matrix = false; if (no_scaling) { // No matrix scaling, but possible cost scaling HighsLogMessage(highs_model_object.options_.logfile, HighsMessageType::INFO, "Scaling: Matrix has [min, max] values of [%g, %g] within " "[%g, %g] so no scaling performed", original_matrix_min_value, original_matrix_max_value, no_scaling_original_matrix_min_value, no_scaling_original_matrix_max_value); } else { const bool equilibration_scaling = simplex_scale_strategy == SIMPLEX_SCALE_STRATEGY_HIGHS || simplex_scale_strategy == SIMPLEX_SCALE_STRATEGY_HIGHS_FORCED; if (equilibration_scaling) { scaled_matrix = equilibrationScaleMatrix(highs_model_object); } else { scaled_matrix = maxValueScaleMatrix(highs_model_object); } scale.is_scaled_ = scaled_matrix; if (scaled_matrix) { // Matrix is scaled, so scale the bounds and costs for (int iCol = 0; iCol < numCol; iCol++) { colLower[iCol] /= colScale[iCol]; colUpper[iCol] /= colScale[iCol]; colCost[iCol] *= colScale[iCol]; } for (int iRow = 0; iRow < numRow; iRow++) { rowLower[iRow] *= rowScale[iRow]; rowUpper[iRow] *= rowScale[iRow]; } } } // Possibly scale the costs if (allow_cost_scaling) scaleCosts(highs_model_object); // If matrix is unscaled, then LP is only scaled if there is a cost scaling // factor if (!scaled_matrix) scale.is_scaled_ = scale.cost_ != 1; // Deduce the consequences of scaling the LP if (scale.is_scaled_) updateSimplexLpStatus(highs_model_object.simplex_lp_status_, LpAction::SCALE); } bool equilibrationScaleMatrix(HighsModelObject& highs_model_object) { int numCol = highs_model_object.simplex_lp_.numCol_; int numRow = highs_model_object.simplex_lp_.numRow_; double* colScale = &highs_model_object.scale_.col_[0]; double* rowScale = &highs_model_object.scale_.row_[0]; int* Astart = &highs_model_object.simplex_lp_.Astart_[0]; int* Aindex = &highs_model_object.simplex_lp_.Aindex_[0]; double* Avalue = &highs_model_object.simplex_lp_.Avalue_[0]; double* colCost = &highs_model_object.simplex_lp_.colCost_[0]; int simplex_scale_strategy = highs_model_object.options_.simplex_scale_strategy; double original_matrix_min_value = HIGHS_CONST_INF; double original_matrix_max_value = 0; for (int k = 0, AnX = Astart[numCol]; k < AnX; k++) { double value = fabs(Avalue[k]); original_matrix_min_value = min(original_matrix_min_value, value); original_matrix_max_value = max(original_matrix_max_value, value); } // Include cost in scaling if minimum nonzero cost is less than 0.1 double min_nonzero_cost = HIGHS_CONST_INF; for (int i = 0; i < numCol; i++) { if (colCost[i]) min_nonzero_cost = min(fabs(colCost[i]), min_nonzero_cost); } bool include_cost_in_scaling = false; include_cost_in_scaling = min_nonzero_cost < 0.1; // Limits on scaling factors double max_allow_scale; double min_allow_scale; // Now that HIGHS_CONST_INF = // std::numeric_limits<double>::infinity(), this Qi-trick doesn't // work so, in recognition, use the old value of HIGHS_CONST_INF const double finite_infinity = 1e200; max_allow_scale = pow(2.0, highs_model_object.options_.allowed_simplex_matrix_scale_factor); min_allow_scale = 1 / max_allow_scale; double min_allow_col_scale = min_allow_scale; double max_allow_col_scale = max_allow_scale; double min_allow_row_scale = min_allow_scale; double max_allow_row_scale = max_allow_scale; // Search up to 6 times vector<double> row_min_value(numRow, finite_infinity); vector<double> row_max_value(numRow, 1 / finite_infinity); for (int search_count = 0; search_count < 6; search_count++) { // Find column scale, prepare row data for (int iCol = 0; iCol < numCol; iCol++) { // For column scale (find) double col_min_value = finite_infinity; double col_max_value = 1 / finite_infinity; double abs_col_cost = fabs(colCost[iCol]); if (include_cost_in_scaling && abs_col_cost != 0) { col_min_value = min(col_min_value, abs_col_cost); col_max_value = max(col_max_value, abs_col_cost); } for (int k = Astart[iCol]; k < Astart[iCol + 1]; k++) { double value = fabs(Avalue[k]) * rowScale[Aindex[k]]; col_min_value = min(col_min_value, value); col_max_value = max(col_max_value, value); } double col_equilibration = 1 / sqrt(col_min_value * col_max_value); // Ensure that column scale factor is not excessively large or small colScale[iCol] = min(max(min_allow_col_scale, col_equilibration), max_allow_col_scale); // For row scale (only collect) for (int k = Astart[iCol]; k < Astart[iCol + 1]; k++) { int iRow = Aindex[k]; double value = fabs(Avalue[k]) * colScale[iCol]; row_min_value[iRow] = min(row_min_value[iRow], value); row_max_value[iRow] = max(row_max_value[iRow], value); } } // For row scale (find) for (int iRow = 0; iRow < numRow; iRow++) { double row_equilibration = 1 / sqrt(row_min_value[iRow] * row_max_value[iRow]); // Ensure that row scale factor is not excessively large or small rowScale[iRow] = min(max(min_allow_row_scale, row_equilibration), max_allow_row_scale); } row_min_value.assign(numRow, finite_infinity); row_max_value.assign(numRow, 1 / finite_infinity); } // Make it numerically better // Also determine the max and min row and column scaling factors double min_col_scale = finite_infinity; double max_col_scale = 1 / finite_infinity; double min_row_scale = finite_infinity; double max_row_scale = 1 / finite_infinity; const double log2 = log(2.0); for (int iCol = 0; iCol < numCol; iCol++) { colScale[iCol] = pow(2.0, floor(log(colScale[iCol]) / log2 + 0.5)); min_col_scale = min(colScale[iCol], min_col_scale); max_col_scale = max(colScale[iCol], max_col_scale); } for (int iRow = 0; iRow < numRow; iRow++) { rowScale[iRow] = pow(2.0, floor(log(rowScale[iRow]) / log2 + 0.5)); min_row_scale = min(rowScale[iRow], min_row_scale); max_row_scale = max(rowScale[iRow], max_row_scale); } // Apply scaling to matrix and bounds double matrix_min_value = finite_infinity; double matrix_max_value = 0; double min_original_col_equilibration = finite_infinity; double sum_original_log_col_equilibration = 0; double max_original_col_equilibration = 0; double min_original_row_equilibration = finite_infinity; double sum_original_log_row_equilibration = 0; double max_original_row_equilibration = 0; double min_col_equilibration = finite_infinity; double sum_log_col_equilibration = 0; double max_col_equilibration = 0; double min_row_equilibration = finite_infinity; double sum_log_row_equilibration = 0; double max_row_equilibration = 0; vector<double> original_row_min_value(numRow, finite_infinity); vector<double> original_row_max_value(numRow, 1 / finite_infinity); row_min_value.assign(numRow, finite_infinity); row_max_value.assign(numRow, 1 / finite_infinity); for (int iCol = 0; iCol < numCol; iCol++) { double original_col_min_value = finite_infinity; double original_col_max_value = 1 / finite_infinity; double col_min_value = finite_infinity; double col_max_value = 1 / finite_infinity; for (int k = Astart[iCol]; k < Astart[iCol + 1]; k++) { int iRow = Aindex[k]; const double original_value = fabs(Avalue[k]); original_col_min_value = min(original_value, original_col_min_value); original_col_max_value = max(original_value, original_col_max_value); original_row_min_value[iRow] = min(original_row_min_value[iRow], original_value); original_row_max_value[iRow] = max(original_row_max_value[iRow], original_value); Avalue[k] *= (colScale[iCol] * rowScale[iRow]); const double value = fabs(Avalue[k]); col_min_value = min(value, col_min_value); col_max_value = max(value, col_max_value); row_min_value[iRow] = min(row_min_value[iRow], value); row_max_value[iRow] = max(row_max_value[iRow], value); } matrix_min_value = min(matrix_min_value, col_min_value); matrix_max_value = max(matrix_max_value, col_max_value); const double original_col_equilibration = 1 / sqrt(original_col_min_value * original_col_max_value); min_original_col_equilibration = min(original_col_equilibration, min_original_col_equilibration); sum_original_log_col_equilibration += log(original_col_equilibration); max_original_col_equilibration = max(original_col_equilibration, max_original_col_equilibration); const double col_equilibration = 1 / sqrt(col_min_value * col_max_value); min_col_equilibration = min(col_equilibration, min_col_equilibration); sum_log_col_equilibration += log(col_equilibration); max_col_equilibration = max(col_equilibration, max_col_equilibration); } for (int iRow = 0; iRow < numRow; iRow++) { const double original_row_equilibration = 1 / sqrt(original_row_min_value[iRow] * original_row_max_value[iRow]); min_original_row_equilibration = min(original_row_equilibration, min_original_row_equilibration); sum_original_log_row_equilibration += log(original_row_equilibration); max_original_row_equilibration = max(original_row_equilibration, max_original_row_equilibration); const double row_equilibration = 1 / sqrt(row_min_value[iRow] * row_max_value[iRow]); min_row_equilibration = min(row_equilibration, min_row_equilibration); sum_log_row_equilibration += log(row_equilibration); max_row_equilibration = max(row_equilibration, max_row_equilibration); } const double geomean_original_col_equilibration = exp(sum_original_log_col_equilibration / numCol); const double geomean_original_row_equilibration = exp(sum_original_log_row_equilibration / numRow); const double geomean_col_equilibration = exp(sum_log_col_equilibration / numCol); const double geomean_row_equilibration = exp(sum_log_row_equilibration / numRow); #ifdef HiGHSDEV HighsLogMessage( highs_model_object.options_.logfile, HighsMessageType::INFO, "Scaling: Original equilibration: min/mean/max %11.4g/%11.4g/%11.4g " "(cols); min/mean/max %11.4g/%11.4g/%11.4g (rows)", min_original_col_equilibration, geomean_original_col_equilibration, max_original_col_equilibration, min_original_row_equilibration, geomean_original_row_equilibration, max_original_row_equilibration); HighsLogMessage( highs_model_object.options_.logfile, HighsMessageType::INFO, "Scaling: Final equilibration: min/mean/max %11.4g/%11.4g/%11.4g " "(cols); min/mean/max %11.4g/%11.4g/%11.4g (rows)", min_col_equilibration, geomean_col_equilibration, max_col_equilibration, min_row_equilibration, geomean_row_equilibration, max_row_equilibration); #endif // Compute the mean equilibration improvement const double geomean_original_col = max(geomean_original_col_equilibration, 1 / geomean_original_col_equilibration); const double geomean_original_row = max(geomean_original_row_equilibration, 1 / geomean_original_row_equilibration); const double geomean_col = max(geomean_col_equilibration, 1 / geomean_col_equilibration); const double geomean_row = max(geomean_row_equilibration, 1 / geomean_row_equilibration); const double mean_equilibration_improvement = (geomean_original_col * geomean_original_row) / (geomean_col * geomean_row); // Compute the extreme equilibration improvement const double original_col_ratio = max_original_col_equilibration / min_original_col_equilibration; const double original_row_ratio = max_original_row_equilibration / min_original_row_equilibration; const double col_ratio = max_col_equilibration / min_col_equilibration; const double row_ratio = max_row_equilibration / min_row_equilibration; const double extreme_equilibration_improvement = (original_col_ratio + original_row_ratio) / (col_ratio + row_ratio); // Compute the max/min matrix value improvement const double matrix_value_ratio = matrix_max_value / matrix_min_value; const double original_matrix_value_ratio = original_matrix_max_value / original_matrix_min_value; const double matrix_value_ratio_improvement = original_matrix_value_ratio / matrix_value_ratio; #ifdef HiGHSDEV HighsLogMessage(highs_model_object.options_.logfile, HighsMessageType::INFO, "Scaling: Extreme equilibration improvement = ( %11.4g + " "%11.4g) / ( %11.4g + %11.4g) = %11.4g / %11.4g = %11.4g", original_col_ratio, original_row_ratio, col_ratio, row_ratio, (original_col_ratio + original_row_ratio), (col_ratio + row_ratio), extreme_equilibration_improvement); HighsLogMessage(highs_model_object.options_.logfile, HighsMessageType::INFO, "Scaling: Mean equilibration improvement = ( %11.4g * " "%11.4g) / ( %11.4g * %11.4g) = %11.4g / %11.4g = %11.4g", geomean_original_col, geomean_original_row, geomean_col, geomean_row, (geomean_original_col * geomean_original_row), (geomean_col * geomean_row), mean_equilibration_improvement); HighsLogMessage( highs_model_object.options_.logfile, HighsMessageType::INFO, "Scaling: Yields [min, max, ratio] matrix values of [%0.4g, %0.4g, " "%0.4g]; Originally [%0.4g, %0.4g, %0.4g]: Improvement of %0.4g", matrix_min_value, matrix_max_value, matrix_value_ratio, original_matrix_min_value, original_matrix_max_value, original_matrix_value_ratio, matrix_value_ratio_improvement); HighsLogMessage(highs_model_object.options_.logfile, HighsMessageType::INFO, "Scaling: Improves mean equilibration by a factor %0.4g", mean_equilibration_improvement); HighsLogMessage(highs_model_object.options_.logfile, HighsMessageType::INFO, "Scaling: Improves extreme equilibration by a factor %0.4g", extreme_equilibration_improvement); HighsLogMessage(highs_model_object.options_.logfile, HighsMessageType::INFO, "Scaling: Improves max/min matrix values by a factor %0.4g", matrix_value_ratio_improvement); #endif const bool possibly_abandon_scaling = simplex_scale_strategy != SIMPLEX_SCALE_STRATEGY_HIGHS_FORCED; const double improvement_factor = extreme_equilibration_improvement * mean_equilibration_improvement * matrix_value_ratio_improvement; const double improvement_factor_required = 1.0; const bool poor_improvement = improvement_factor < improvement_factor_required; // Possibly abandon scaling if it's not improved equlibration significantly if (possibly_abandon_scaling && poor_improvement) { // Unscale the matrix for (int iCol = 0; iCol < numCol; iCol++) { for (int k = Astart[iCol]; k < Astart[iCol + 1]; k++) { int iRow = Aindex[k]; Avalue[k] /= (colScale[iCol] * rowScale[iRow]); } } HighsLogMessage(highs_model_object.options_.logfile, HighsMessageType::INFO, "Scaling: Improvement factor %0.4g < %0.4g required, so no " "scaling applied", improvement_factor, improvement_factor_required); scaleHighsModelInit(highs_model_object); return false; } else { HighsLogMessage(highs_model_object.options_.logfile, HighsMessageType::INFO, "Scaling: Improvement factor is %0.4g >= %0.4g so scale LP", improvement_factor, improvement_factor_required); #ifdef HiGHSDEV if (extreme_equilibration_improvement < 1.0) { HighsLogMessage( highs_model_object.options_.logfile, HighsMessageType::WARNING, "Scaling: Applying scaling with extreme improvement of %0.4g", extreme_equilibration_improvement); } if (mean_equilibration_improvement < 1.0) { HighsLogMessage( highs_model_object.options_.logfile, HighsMessageType::WARNING, "Scaling: Applying scaling with mean improvement of %0.4g", mean_equilibration_improvement); } if (matrix_value_ratio_improvement < 1.0) { HighsLogMessage(highs_model_object.options_.logfile, HighsMessageType::WARNING, "Scaling: Applying scaling with matrix value ratio " "improvement of %0.4g", matrix_value_ratio_improvement); } if (improvement_factor < 10 * improvement_factor_required) { HighsLogMessage(highs_model_object.options_.logfile, HighsMessageType::WARNING, "Scaling: Applying scaling with improvement factor %0.4g " "< 10*(%0.4g) improvement", improvement_factor, improvement_factor_required); } #endif } return true; } bool maxValueScaleMatrix(HighsModelObject& highs_model_object) { int numCol = highs_model_object.simplex_lp_.numCol_; int numRow = highs_model_object.simplex_lp_.numRow_; vector<double>& colScale = highs_model_object.scale_.col_; vector<double>& rowScale = highs_model_object.scale_.row_; vector<int>& Astart = highs_model_object.simplex_lp_.Astart_; vector<int>& Aindex = highs_model_object.simplex_lp_.Aindex_; vector<double>& Avalue = highs_model_object.simplex_lp_.Avalue_; assert(highs_model_object.options_.simplex_scale_strategy == SIMPLEX_SCALE_STRATEGY_015 || highs_model_object.options_.simplex_scale_strategy == SIMPLEX_SCALE_STRATEGY_0157); const double log2 = log(2.0); const double max_allow_scale = pow(2.0, highs_model_object.options_.allowed_simplex_matrix_scale_factor); const double min_allow_scale = 1 / max_allow_scale; const double min_allow_col_scale = min_allow_scale; const double max_allow_col_scale = max_allow_scale; const double min_allow_row_scale = min_allow_scale; const double max_allow_row_scale = max_allow_scale; double min_row_scale = HIGHS_CONST_INF; double max_row_scale = 0; double original_matrix_min_value = HIGHS_CONST_INF; double original_matrix_max_value = 0; // Determine the row scaling. Also determine the max/min row scaling // factors, and max/min original matrix values vector<double> row_max_value(numRow, 0); for (int iCol = 0; iCol < numCol; iCol++) { for (int k = Astart[iCol]; k < Astart[iCol + 1]; k++) { const int iRow = Aindex[k]; const double value = fabs(Avalue[k]); row_max_value[iRow] = max(row_max_value[iRow], value); original_matrix_min_value = min(original_matrix_min_value, value); original_matrix_max_value = max(original_matrix_max_value, value); } } for (int iRow = 0; iRow < numRow; iRow++) { if (row_max_value[iRow]) { double row_scale_value = 1 / row_max_value[iRow]; // Convert the row scale factor to the nearest power of two, and // ensure that it is not excessively large or small row_scale_value = pow(2.0, floor(log(row_scale_value) / log2 + 0.5)); row_scale_value = min(max(min_allow_row_scale, row_scale_value), max_allow_row_scale); min_row_scale = min(row_scale_value, min_row_scale); max_row_scale = max(row_scale_value, max_row_scale); rowScale[iRow] = row_scale_value; } } // Determine the column scaling, whilst applying the row scaling // Also determine the max/min column scaling factors, and max/min // matrix values double min_col_scale = HIGHS_CONST_INF; double max_col_scale = 0; double matrix_min_value = HIGHS_CONST_INF; double matrix_max_value = 0; for (int iCol = 0; iCol < numCol; iCol++) { double col_max_value = 0; for (int k = Astart[iCol]; k < Astart[iCol + 1]; k++) { const int iRow = Aindex[k]; Avalue[k] *= rowScale[iRow]; const double value = fabs(Avalue[k]); col_max_value = max(col_max_value, value); } if (col_max_value) { double col_scale_value = 1 / col_max_value; // Convert the col scale factor to the nearest power of two, and // ensure that it is not excessively large or small col_scale_value = pow(2.0, floor(log(col_scale_value) / log2 + 0.5)); col_scale_value = min(max(min_allow_col_scale, col_scale_value), max_allow_col_scale); min_col_scale = min(col_scale_value, min_col_scale); max_col_scale = max(col_scale_value, max_col_scale); colScale[iCol] = col_scale_value; for (int k = Astart[iCol]; k < Astart[iCol + 1]; k++) { Avalue[k] *= colScale[iCol]; const double value = fabs(Avalue[k]); matrix_min_value = min(matrix_min_value, value); matrix_max_value = max(matrix_max_value, value); } } } const double matrix_value_ratio = matrix_max_value / matrix_min_value; const double original_matrix_value_ratio = original_matrix_max_value / original_matrix_min_value; const double matrix_value_ratio_improvement = original_matrix_value_ratio / matrix_value_ratio; HighsLogMessage(highs_model_object.options_.logfile, HighsMessageType::INFO, "Scaling: Factors are in [%0.4g, %0.4g] for columns and in " "[%0.4g, %0.4g] for rows", min_col_scale, max_col_scale, min_row_scale, max_row_scale); HighsLogMessage( highs_model_object.options_.logfile, HighsMessageType::INFO, "Scaling: Yields [min, max, ratio] matrix values of [%0.4g, %0.4g, " "%0.4g]; Originally [%0.4g, %0.4g, %0.4g]: Improvement of %0.4g", matrix_min_value, matrix_max_value, matrix_value_ratio, original_matrix_min_value, original_matrix_max_value, original_matrix_value_ratio, matrix_value_ratio_improvement); return true; } HighsStatus deleteScale(const HighsOptions& options, vector<double>& scale, const HighsIndexCollection& index_collection) { HighsStatus return_status = HighsStatus::OK; if (!assessIndexCollection(options, index_collection)) return interpretCallStatus(HighsStatus::Error, return_status, "assessIndexCollection"); int from_k; int to_k; if (!limitsForIndexCollection(options, index_collection, from_k, to_k)) return interpretCallStatus(HighsStatus::Error, return_status, "limitsForIndexCollection"); if (index_collection.is_set_) { // For deletion by set it must be increasing if (!increasingSetOk(index_collection.set_, index_collection.set_num_entries_, 0, index_collection.dimension_ - 1, true)) return HighsStatus::Error; } if (from_k > to_k) return HighsStatus::OK; int delete_from_col; int delete_to_col; int keep_from_col; int keep_to_col = -1; int current_set_entry = 0; int col_dim = index_collection.dimension_; int new_num_col = 0; for (int k = from_k; k <= to_k; k++) { updateIndexCollectionOutInIndex(index_collection, delete_from_col, delete_to_col, keep_from_col, keep_to_col, current_set_entry); // Account for the initial columns being kept if (k == from_k) new_num_col = delete_from_col; if (delete_to_col >= col_dim - 1) break; assert(delete_to_col < col_dim); for (int col = keep_from_col; col <= keep_to_col; col++) { scale[new_num_col] = scale[col]; new_num_col++; } if (keep_to_col >= col_dim - 1) break; } return HighsStatus::OK; } // PERMUTE: void permuteSimplexLp(HighsModelObject& highs_model_object) { HighsSimplexLpStatus& simplex_lp_status = highs_model_object.simplex_lp_status_; #ifdef HiGHSDEV printf("Called permuteSimplexLp: simplex_lp_status.is_permuted = %d\n", simplex_lp_status.is_permuted); #endif if (simplex_lp_status.is_permuted) return; int numCol = highs_model_object.simplex_lp_.numCol_; vector<int>& numColPermutation = highs_model_object.simplex_info_.numColPermutation_; vector<int>& Astart = highs_model_object.simplex_lp_.Astart_; vector<int>& Aindex = highs_model_object.simplex_lp_.Aindex_; vector<double>& Avalue = highs_model_object.simplex_lp_.Avalue_; vector<double>& colCost = highs_model_object.simplex_lp_.colCost_; vector<double>& colLower = highs_model_object.simplex_lp_.colLower_; vector<double>& colUpper = highs_model_object.simplex_lp_.colUpper_; // 2. Duplicate the original data to copy from vector<int> saveAstart = highs_model_object.simplex_lp_.Astart_; vector<int> saveAindex = highs_model_object.simplex_lp_.Aindex_; vector<double> saveAvalue = highs_model_object.simplex_lp_.Avalue_; vector<double> saveColCost = highs_model_object.simplex_lp_.colCost_; vector<double> saveColLower = highs_model_object.simplex_lp_.colLower_; vector<double> saveColUpper = highs_model_object.simplex_lp_.colUpper_; // 3. Generate the permuted matrix and corresponding vectors of column data int countX = 0; for (int i = 0; i < numCol; i++) { int fromCol = numColPermutation[i]; Astart[i] = countX; for (int k = saveAstart[fromCol]; k < saveAstart[fromCol + 1]; k++) { Aindex[countX] = saveAindex[k]; Avalue[countX] = saveAvalue[k]; countX++; } colCost[i] = saveColCost[fromCol]; colLower[i] = saveColLower[fromCol]; colUpper[i] = saveColUpper[fromCol]; } if (highs_model_object.scale_.is_scaled_) { // Permute any columns scaling factors vector<double>& colScale = highs_model_object.scale_.col_; vector<double> saveColScale = highs_model_object.scale_.col_; for (int i = 0; i < numCol; i++) { int fromCol = numColPermutation[i]; colScale[i] = saveColScale[fromCol]; } } assert(Astart[numCol] == countX); // Deduce the consequences of permuting the LP updateSimplexLpStatus(highs_model_object.simplex_lp_status_, LpAction::PERMUTE); } #ifdef HiGHSDEV // Only used to analyse the row and column status after Crash void initialise_basic_index(HighsModelObject& highs_model_object) { HighsLp& simplex_lp = highs_model_object.simplex_lp_; SimplexBasis& simplex_basis = highs_model_object.simplex_basis_; int num_basic_variables = 0; const int numTot = simplex_lp.numCol_ + simplex_lp.numRow_; for (int iVar = 0; iVar < numTot; iVar++) { if (!simplex_basis.nonbasicFlag_[iVar]) { assert(num_basic_variables < simplex_lp.numRow_); simplex_basis.basicIndex_[num_basic_variables] = iVar; num_basic_variables++; } } assert(num_basic_variables == simplex_lp.numRow_); } #endif void allocateWorkAndBaseArrays(HighsModelObject& highs_model_object) { HighsLp& simplex_lp = highs_model_object.simplex_lp_; HighsSimplexInfo& simplex_info = highs_model_object.simplex_info_; // Allocate bounds and solution spaces const int numTot = simplex_lp.numCol_ + simplex_lp.numRow_; simplex_info.workCost_.resize(numTot); simplex_info.workDual_.resize(numTot); simplex_info.workShift_.resize(numTot); simplex_info.workLower_.resize(numTot); simplex_info.workUpper_.resize(numTot); simplex_info.workRange_.resize(numTot); simplex_info.workValue_.resize(numTot); // Feel that it should be possible to resize this with in dual // solver, and only if Devex is being used, but a pointer to it // needs to be set up when constructing HDual simplex_info.devex_index_.resize(numTot); simplex_info.baseLower_.resize(simplex_lp.numRow_); simplex_info.baseUpper_.resize(simplex_lp.numRow_); simplex_info.baseValue_.resize(simplex_lp.numRow_); } void initialiseValueAndNonbasicMove(HighsModelObject& highs_model_object) { // Initialise workValue and nonbasicMove from nonbasicFlag and // bounds, except for boxed variables when nonbasicMove is used to // set workValue=workLower/workUpper SimplexBasis& simplex_basis = highs_model_object.simplex_basis_; HighsSimplexInfo& simplex_info = highs_model_object.simplex_info_; const int numTot = highs_model_object.simplex_lp_.numCol_ + highs_model_object.simplex_lp_.numRow_; for (int iVar = 0; iVar < numTot; iVar++) { if (!simplex_basis.nonbasicFlag_[iVar]) { // Basic variable simplex_basis.nonbasicMove_[iVar] = NONBASIC_MOVE_ZE; } else { // Nonbasic variable if (simplex_info.workLower_[iVar] == simplex_info.workUpper_[iVar]) { // Fixed simplex_info.workValue_[iVar] = simplex_info.workLower_[iVar]; simplex_basis.nonbasicMove_[iVar] = NONBASIC_MOVE_ZE; } else if (!highs_isInfinity(-simplex_info.workLower_[iVar])) { // Finite lower bound so boxed or lower if (!highs_isInfinity(simplex_info.workUpper_[iVar])) { // Finite upper bound so boxed if (simplex_basis.nonbasicMove_[iVar] == NONBASIC_MOVE_UP) { // Set at lower simplex_info.workValue_[iVar] = simplex_info.workLower_[iVar]; } else if (simplex_basis.nonbasicMove_[iVar] == NONBASIC_MOVE_DN) { // Set at upper simplex_info.workValue_[iVar] = simplex_info.workUpper_[iVar]; } else { // Invalid nonbasicMove: correct and set value at lower simplex_basis.nonbasicMove_[iVar] = NONBASIC_MOVE_UP; simplex_info.workValue_[iVar] = simplex_info.workLower_[iVar]; } } else { // Lower simplex_info.workValue_[iVar] = simplex_info.workLower_[iVar]; simplex_basis.nonbasicMove_[iVar] = NONBASIC_MOVE_UP; } } else if (!highs_isInfinity(simplex_info.workUpper_[iVar])) { // Upper simplex_info.workValue_[iVar] = simplex_info.workUpper_[iVar]; simplex_basis.nonbasicMove_[iVar] = NONBASIC_MOVE_DN; } else { // FREE simplex_info.workValue_[iVar] = 0; simplex_basis.nonbasicMove_[iVar] = NONBASIC_MOVE_ZE; } } } } void initialisePhase2ColBound(HighsModelObject& highs_model_object) { // Copy bounds and compute ranges HighsLp& simplex_lp = highs_model_object.simplex_lp_; HighsSimplexInfo& simplex_info = highs_model_object.simplex_info_; for (int iCol = 0; iCol < simplex_lp.numCol_; iCol++) { simplex_info.workLower_[iCol] = simplex_lp.colLower_[iCol]; simplex_info.workUpper_[iCol] = simplex_lp.colUpper_[iCol]; simplex_info.workRange_[iCol] = simplex_info.workUpper_[iCol] - simplex_info.workLower_[iCol]; } } void initialisePhase2RowBound(HighsModelObject& highs_model_object) { // Copy bounds and compute ranges HighsLp& simplex_lp = highs_model_object.simplex_lp_; HighsSimplexInfo& simplex_info = highs_model_object.simplex_info_; for (int row = 0; row < simplex_lp.numRow_; row++) { int var = simplex_lp.numCol_ + row; simplex_info.workLower_[var] = -simplex_lp.rowUpper_[row]; simplex_info.workUpper_[var] = -simplex_lp.rowLower_[row]; simplex_info.workRange_[var] = simplex_info.workUpper_[var] - simplex_info.workLower_[var]; } } void initialiseBound(HighsModelObject& highs_model_object, int phase) { HighsLp& simplex_lp = highs_model_object.simplex_lp_; HighsSimplexInfo& simplex_info = highs_model_object.simplex_info_; // Initialise the Phase 2 bounds (and ranges). NB Phase 2 bounds // necessary to compute Phase 1 bounds initialisePhase2ColBound(highs_model_object); initialisePhase2RowBound(highs_model_object); if (phase == 2) return; // The dual objective is the sum of products of primal and dual // values for nonbasic variables. For dual simplex phase 1, the // primal bounds are set so that when the dual value is feasible, the // primal value is set to zero. Otherwise the value is +1/-1 // according to the required sign of the dual, except for free // variables, where the bounds are [-1000, 1000]. Hence the dual // objective is the negation of the sum of infeasibilities, unless there are // free In Phase 1: change to dual phase 1 bound. const double inf = HIGHS_CONST_INF; const int numTot = simplex_lp.numCol_ + simplex_lp.numRow_; for (int i = 0; i < numTot; i++) { if (simplex_info.workLower_[i] == -inf && simplex_info.workUpper_[i] == inf) { // Don't change for row variables: they should never become // nonbasic when starting from a logical basis, and no crash // should make a free row nonbasic, but could an advanced basis // make a free row nonbasic. // But what it it happened? if (i >= simplex_lp.numCol_) continue; simplex_info.workLower_[i] = -1000, simplex_info.workUpper_[i] = 1000; // FREE } else if (simplex_info.workLower_[i] == -inf) { simplex_info.workLower_[i] = -1, simplex_info.workUpper_[i] = 0; // UPPER } else if (simplex_info.workUpper_[i] == inf) { simplex_info.workLower_[i] = 0, simplex_info.workUpper_[i] = 1; // LOWER } else { simplex_info.workLower_[i] = 0, simplex_info.workUpper_[i] = 0; // BOXED or FIXED } simplex_info.workRange_[i] = simplex_info.workUpper_[i] - simplex_info.workLower_[i]; } } void initialisePhase2ColCost(HighsModelObject& highs_model_object) { // Copy the Phase 2 cost and zero the shift HighsLp& simplex_lp = highs_model_object.simplex_lp_; HighsSimplexInfo& simplex_info = highs_model_object.simplex_info_; for (int col = 0; col < simplex_lp.numCol_; col++) { int var = col; simplex_info.workCost_[var] = (int)simplex_lp.sense_ * simplex_lp.colCost_[col]; simplex_info.workShift_[var] = 0; } } void initialisePhase2RowCost(HighsModelObject& highs_model_object) { // Zero the cost and shift HighsLp& simplex_lp = highs_model_object.simplex_lp_; HighsSimplexInfo& simplex_info = highs_model_object.simplex_info_; for (int iVar = simplex_lp.numCol_; iVar < simplex_lp.numCol_ + simplex_lp.numRow_; iVar++) { simplex_info.workCost_[iVar] = 0; simplex_info.workShift_[iVar] = 0; } } void initialiseCost(HighsModelObject& highs_model_object, int perturb) { HighsLp& simplex_lp = highs_model_object.simplex_lp_; HighsSimplexInfo& simplex_info = highs_model_object.simplex_info_; #ifdef HiGHSDEV HighsSimplexAnalysis* analysis = &highs_model_object.simplex_analysis_; #endif // Copy the cost initialisePhase2ColCost(highs_model_object); initialisePhase2RowCost(highs_model_object); // See if we want to skip perturbation simplex_info.costs_perturbed = 0; if (perturb == 0 || simplex_info.dual_simplex_cost_perturbation_multiplier == 0) return; simplex_info.costs_perturbed = 1; // Perturb the original costs, scale down if is too big #ifdef HiGHSDEV printf("grep_DuPtrb: Cost perturbation for %s\n", highs_model_object.simplex_lp_.model_name_.c_str()); int num_original_nonzero_cost = 0; #endif double bigc = 0; for (int i = 0; i < simplex_lp.numCol_; i++) { const double abs_cost = fabs(simplex_info.workCost_[i]); bigc = max(bigc, abs_cost); #ifdef HiGHSDEV if (abs_cost) num_original_nonzero_cost++; #endif } #ifdef HiGHSDEV const int pct0 = (100 * num_original_nonzero_cost) / simplex_lp.numCol_; double average_cost = 0; if (num_original_nonzero_cost) { average_cost = bigc / num_original_nonzero_cost; } else { printf("grep_DuPtrb: STRANGE initial workCost has non nonzeros\n"); } printf( "grep_DuPtrb: Initially have %d nonzero costs (%3d%%) with bigc = %g " "and average = %g\n", num_original_nonzero_cost, pct0, bigc, average_cost); #endif if (bigc > 100) { bigc = sqrt(sqrt(bigc)); #ifdef HiGHSDEV printf("grep_DuPtrb: Large so set bigc = sqrt(bigc) = %g\n", bigc); #endif } // If there's few boxed variables, we will just use simple perturbation double boxedRate = 0; const int numTot = simplex_lp.numCol_ + simplex_lp.numRow_; for (int i = 0; i < numTot; i++) boxedRate += (simplex_info.workRange_[i] < 1e30); boxedRate /= numTot; if (boxedRate < 0.01) { bigc = min(bigc, 1.0); #ifdef HiGHSDEV printf( "grep_DuPtrb: small boxedRate (%g) so set bigc = min(bigc, 1.0) = " "%g\n", boxedRate, bigc); #endif } // Determine the perturbation base double base = 5e-7 * bigc; #ifdef HiGHSDEV printf("grep_DuPtrb: Perturbation base = %g\n", base); #endif // Now do the perturbation for (int i = 0; i < simplex_lp.numCol_; i++) { double lower = simplex_lp.colLower_[i]; double upper = simplex_lp.colUpper_[i]; double xpert = (fabs(simplex_info.workCost_[i]) + 1) * base * simplex_info.dual_simplex_cost_perturbation_multiplier * (1 + simplex_info.numTotRandomValue_[i]); #ifdef HiGHSDEV const double previous_cost = simplex_info.workCost_[i]; #endif if (lower <= -HIGHS_CONST_INF && upper >= HIGHS_CONST_INF) { // Free - no perturb } else if (upper >= HIGHS_CONST_INF) { // Lower simplex_info.workCost_[i] += xpert; } else if (lower <= -HIGHS_CONST_INF) { // Upper simplex_info.workCost_[i] += -xpert; } else if (lower != upper) { // Boxed simplex_info.workCost_[i] += (simplex_info.workCost_[i] >= 0) ? xpert : -xpert; } else { // Fixed - no perturb } #ifdef HiGHSDEV const double perturbation1 = fabs(simplex_info.workCost_[i] - previous_cost); if (perturbation1) updateValueDistribution(perturbation1, analysis->cost_perturbation1_distribution); #endif } for (int i = simplex_lp.numCol_; i < numTot; i++) { double perturbation2 = (0.5 - simplex_info.numTotRandomValue_[i]) * simplex_info.dual_simplex_cost_perturbation_multiplier * 1e-12; simplex_info.workCost_[i] += perturbation2; #ifdef HiGHSDEV perturbation2 = fabs(perturbation2); updateValueDistribution(perturbation2, analysis->cost_perturbation2_distribution); #endif } } #ifdef HiGHSDEV void reportSimplexProfiling(HighsModelObject& highs_model_object) { HighsTimer& timer = highs_model_object.timer_; HighsSimplexInfo& simplex_info = highs_model_object.simplex_info_; HighsSimplexAnalysis& analysis = highs_model_object.simplex_analysis_; SimplexTimer simplex_timer; int simplex_strategy_for_profiling = simplex_info.simplex_strategy; if (simplex_strategy_for_profiling == SIMPLEX_STRATEGY_CHOOSE) { // Simplex strategy not chosen - probably due to solution after // postsolve being optimal - so profile as if // SIMPLEX_STRATEGY_DUAL_PLAIN has been used simplex_strategy_for_profiling = SIMPLEX_STRATEGY_DUAL_PLAIN; } if (simplex_strategy_for_profiling == SIMPLEX_STRATEGY_PRIMAL) { if (simplex_info.report_simplex_inner_clock) { simplex_timer.reportSimplexInnerClock(analysis.thread_simplex_clocks[0]); } } else if (simplex_strategy_for_profiling == SIMPLEX_STRATEGY_DUAL_PLAIN) { if (simplex_info.report_simplex_inner_clock) { simplex_timer.reportSimplexInnerClock(analysis.thread_simplex_clocks[0]); simplex_timer.reportSimplexChuzc3Clock(analysis.thread_simplex_clocks[0]); } if (simplex_info.report_simplex_outer_clock) { simplex_timer.reportDualSimplexIterateClock( analysis.thread_simplex_clocks[0]); simplex_timer.reportDualSimplexOuterClock( analysis.thread_simplex_clocks[0]); } } if (simplex_strategy_for_profiling == SIMPLEX_STRATEGY_DUAL_MULTI) { if (simplex_info.report_simplex_inner_clock) { simplex_timer.reportSimplexMultiInnerClock( analysis.thread_simplex_clocks[0]); } printf("PAMI %-20s CUTOFF %6g PERSISTENSE %6g\n", highs_model_object.lp_.model_name_.c_str(), simplex_info.pami_cutoff, highs_model_object.iteration_counts_.simplex / (1.0 + simplex_info.multi_iteration)); } if (simplex_info.report_simplex_phases_clock) { simplex_timer.reportSimplexTotalClock(analysis.thread_simplex_clocks[0]); simplex_timer.reportSimplexPhasesClock(analysis.thread_simplex_clocks[0]); } if (simplex_info.analyse_invert_time) { double current_run_highs_time = timer.readRunHighsClock(); simplex_info.total_inverts = analysis.simplexTimerNumCall(InvertClock); simplex_info.total_invert_time = analysis.simplexTimerRead(InvertClock); printf( "Time: Total inverts = %4d; Total invert time = %11.4g of Total time " "= %11.4g", simplex_info.total_inverts, simplex_info.total_invert_time, current_run_highs_time); if (current_run_highs_time > 0.001) { printf(" (%6.2f%%)\n", (100 * simplex_info.total_invert_time) / current_run_highs_time); } else { printf("\n"); } } /* if (simplex_info.analyse_rebuild_time) { double current_run_highs_time = timer.readRunHighsClock(); HighsClockRecord totalRebuildClock; timer.clockInit(totalRebuildClock); timer.clockAdd(totalRebuildClock, simplex_info.clock_[IterateDualRebuildClock]); timer.clockAdd(totalRebuildClock, simplex_info.clock_[IteratePrimalRebuildClock]); int totalRebuilds = 0; double totalRebuildTime = 0; printf("Time: Total rebuild time = %11.4g (%4d) of Total time = %11.4g", totalRebuildTime, totalRebuilds, current_run_highs_time); if (current_run_highs_time > 0.001) { printf(" (%6.2f%%)\n", (100 * totalRebuildTime) / current_run_highs_time); } else { printf("\n"); } } */ } #endif void setRunQuiet(HighsModelObject& highs_model_object) { highs_model_object.simplex_info_.run_quiet = highs_model_object.options_.output == NULL && highs_model_object.options_.logfile == NULL; } double computeBasisCondition(const HighsModelObject& highs_model_object) { int solver_num_row = highs_model_object.simplex_lp_.numRow_; int solver_num_col = highs_model_object.simplex_lp_.numCol_; vector<double> bs_cond_x; vector<double> bs_cond_y; vector<double> bs_cond_z; vector<double> bs_cond_w; HVector row_ep; row_ep.setup(solver_num_row); const HFactor& factor = highs_model_object.factor_; const int* Astart = &highs_model_object.simplex_lp_.Astart_[0]; const double* Avalue = &highs_model_object.simplex_lp_.Avalue_[0]; // Compute the Hager condition number estimate for the basis matrix const double NoDensity = 1; bs_cond_x.resize(solver_num_row); bs_cond_y.resize(solver_num_row); bs_cond_z.resize(solver_num_row); bs_cond_w.resize(solver_num_row); // x = ones(n,1)/n; // y = A\x; double mu = 1.0 / solver_num_row; double norm_Binv; for (int r_n = 0; r_n < solver_num_row; r_n++) bs_cond_x[r_n] = mu; row_ep.clear(); for (int r_n = 0; r_n < solver_num_row; r_n++) { double value = bs_cond_x[r_n]; if (value) { row_ep.index[row_ep.count] = r_n; row_ep.array[r_n] = value; row_ep.count++; } } for (int ps_n = 1; ps_n <= 5; ps_n++) { row_ep.packFlag = false; factor.ftran(row_ep, NoDensity); // zeta = sign(y); for (int r_n = 0; r_n < solver_num_row; r_n++) { bs_cond_y[r_n] = row_ep.array[r_n]; if (bs_cond_y[r_n] > 0) bs_cond_w[r_n] = 1.0; else if (bs_cond_y[r_n] < 0) bs_cond_w[r_n] = -1.0; else bs_cond_w[r_n] = 0.0; } // z=A'\zeta; row_ep.clear(); for (int r_n = 0; r_n < solver_num_row; r_n++) { double value = bs_cond_w[r_n]; if (value) { row_ep.index[row_ep.count] = r_n; row_ep.array[r_n] = value; row_ep.count++; } } row_ep.packFlag = false; factor.btran(row_ep, NoDensity); double norm_z = 0.0; double ztx = 0.0; norm_Binv = 0.0; int argmax_z = -1; for (int r_n = 0; r_n < solver_num_row; r_n++) { bs_cond_z[r_n] = row_ep.array[r_n]; double abs_z_v = fabs(bs_cond_z[r_n]); if (abs_z_v > norm_z) { norm_z = abs_z_v; argmax_z = r_n; } ztx += bs_cond_z[r_n] * bs_cond_x[r_n]; norm_Binv += fabs(bs_cond_y[r_n]); } if (norm_z <= ztx) break; // x = zeros(n,1); // x(fd_i) = 1; for (int r_n = 0; r_n < solver_num_row; r_n++) bs_cond_x[r_n] = 0.0; row_ep.clear(); row_ep.count = 1; row_ep.index[0] = argmax_z; row_ep.array[argmax_z] = 1.0; bs_cond_x[argmax_z] = 1.0; } double norm_B = 0.0; for (int r_n = 0; r_n < solver_num_row; r_n++) { int vr_n = highs_model_object.simplex_basis_.basicIndex_[r_n]; double c_norm = 0.0; if (vr_n < solver_num_col) for (int el_n = Astart[vr_n]; el_n < Astart[vr_n + 1]; el_n++) c_norm += fabs(Avalue[el_n]); else c_norm += 1.0; norm_B = max(c_norm, norm_B); } double cond_B = norm_Binv * norm_B; return cond_B; } void flip_bound(HighsModelObject& highs_model_object, int iCol) { int* nonbasicMove = &highs_model_object.simplex_basis_.nonbasicMove_[0]; HighsSimplexInfo& simplex_info = highs_model_object.simplex_info_; const int move = nonbasicMove[iCol] = -nonbasicMove[iCol]; simplex_info.workValue_[iCol] = move == 1 ? simplex_info.workLower_[iCol] : simplex_info.workUpper_[iCol]; } void simplexHandleRankDeficiency(HighsModelObject& highs_model_object) { HighsLp& simplex_lp = highs_model_object.simplex_lp_; HFactor& factor = highs_model_object.factor_; SimplexBasis& simplex_basis = highs_model_object.simplex_basis_; int rank_deficiency = factor.rank_deficiency; vector<int>& noPvC = factor.noPvC; vector<int>& noPvR = factor.noPvR; for (int k = 0; k < rank_deficiency; k++) { int columnIn = simplex_lp.numCol_ + noPvR[k]; int columnOut = noPvC[k]; simplex_basis.nonbasicFlag_[columnIn] = NONBASIC_FLAG_FALSE; simplex_basis.nonbasicFlag_[columnOut] = NONBASIC_FLAG_TRUE; } highs_model_object.simplex_lp_status_.has_matrix_row_wise = false; } int computeFactor(HighsModelObject& highs_model_object) { HighsSimplexInfo& simplex_info = highs_model_object.simplex_info_; HighsSimplexLpStatus& simplex_lp_status = highs_model_object.simplex_lp_status_; HFactor& factor = highs_model_object.factor_; #ifdef HiGHSDEV HighsSimplexAnalysis& analysis = highs_model_object.simplex_analysis_; double tt0 = 0; if (simplex_info.analyse_invert_time) tt0 = analysis.simplexTimerRead(InvertClock); #endif HighsTimerClock* factor_timer_clock_pointer = NULL; // TODO Understand why handling noPvC and noPvR in what seem to be // different ways ends up equivalent. #ifdef HiGHSDEV int thread_id = 0; #ifdef OPENMP thread_id = omp_get_thread_num(); // printf("Hello world from computeFactor: thread %d\n", thread_id); #endif factor_timer_clock_pointer = highs_model_object.simplex_analysis_.getThreadFactorTimerClockPtr( thread_id); #endif const int rank_deficiency = factor.build(factor_timer_clock_pointer); #ifdef HiGHSDEV if (simplex_info.analyse_invert_form) { const bool report_kernel = false; simplex_info.num_invert++; assert(factor.basis_matrix_num_el); double invert_fill_factor = ((1.0 * factor.invert_num_el) / factor.basis_matrix_num_el); if (report_kernel) printf("INVERT fill = %6.2f", invert_fill_factor); simplex_info.sum_invert_fill_factor += invert_fill_factor; simplex_info.running_average_invert_fill_factor = 0.95 * simplex_info.running_average_invert_fill_factor + 0.05 * invert_fill_factor; double kernel_relative_dim = (1.0 * factor.kernel_dim) / highs_model_object.simplex_lp_.numRow_; if (report_kernel) printf("; kernel dim = %11.4g", kernel_relative_dim); if (factor.kernel_dim) { simplex_info.num_kernel++; simplex_info.max_kernel_dim = max(kernel_relative_dim, simplex_info.max_kernel_dim); simplex_info.sum_kernel_dim += kernel_relative_dim; simplex_info.running_average_kernel_dim = 0.95 * simplex_info.running_average_kernel_dim + 0.05 * kernel_relative_dim; int kernel_invert_num_el = factor.invert_num_el - (factor.basis_matrix_num_el - factor.kernel_num_el); assert(factor.kernel_num_el); double kernel_fill_factor = (1.0 * kernel_invert_num_el) / factor.kernel_num_el; simplex_info.sum_kernel_fill_factor += kernel_fill_factor; simplex_info.running_average_kernel_fill_factor = 0.95 * simplex_info.running_average_kernel_fill_factor + 0.05 * kernel_fill_factor; if (report_kernel) printf("; fill = %6.2f", kernel_fill_factor); if (kernel_relative_dim > simplex_info.major_kernel_relative_dim_threshold) { simplex_info.num_major_kernel++; simplex_info.sum_major_kernel_fill_factor += kernel_fill_factor; simplex_info.running_average_major_kernel_fill_factor = 0.95 * simplex_info.running_average_major_kernel_fill_factor + 0.05 * kernel_fill_factor; } } if (report_kernel) printf("\n"); } if (simplex_info.analyse_invert_condition) { analysis.simplexTimerStart(BasisConditionClock); simplex_info.invert_condition = computeBasisCondition(highs_model_object); analysis.simplexTimerStop(BasisConditionClock); } if (simplex_info.analyse_invert_time) { simplex_info.total_inverts = analysis.simplexTimerNumCall(InvertClock); simplex_info.total_invert_time = analysis.simplexTimerRead(InvertClock); const double invert_time = simplex_info.total_invert_time - tt0; printf( " INVERT %4d on iteration %9d: INVERT time = %11.4g; " "Total INVERT time = %11.4g\n", simplex_info.total_inverts, highs_model_object.iteration_counts_.simplex, invert_time, simplex_info.total_invert_time); } #endif const bool force = rank_deficiency; debugCheckInvert(highs_model_object.options_, highs_model_object.factor_, force); if (rank_deficiency) { // Have an invertible representation, but of B with column(s) // replacements due to singularity. So no (fresh) representation of // B^{-1} simplex_lp_status.has_invert = false; simplex_lp_status.has_fresh_invert = false; } else { // Now have a representation of B^{-1}, and it is fresh! simplex_lp_status.has_invert = true; simplex_lp_status.has_fresh_invert = true; } // Set the update count to zero since the corrected invertible // representation may be used for an initial basis. In any case the // number of updates shouldn't be positive simplex_info.update_count = 0; return rank_deficiency; } // Compute the primal values (in baseValue) and set the lower and upper bounds // of basic variables void computePrimal(HighsModelObject& highs_model_object) { HighsLp& simplex_lp = highs_model_object.simplex_lp_; HighsSimplexInfo& simplex_info = highs_model_object.simplex_info_; HighsSimplexLpStatus& simplex_lp_status = highs_model_object.simplex_lp_status_; SimplexBasis& simplex_basis = highs_model_object.simplex_basis_; HMatrix& matrix = highs_model_object.matrix_; HFactor& factor = highs_model_object.factor_; HighsSimplexAnalysis* analysis = &highs_model_object.simplex_analysis_; // Setup a local buffer for the values of basic variables HVector primal_col; primal_col.setup(simplex_lp.numRow_); primal_col.clear(); for (int i = 0; i < simplex_lp.numCol_ + simplex_lp.numRow_; i++) { if (simplex_basis.nonbasicFlag_[i] && simplex_info.workValue_[i] != 0) { matrix.collect_aj(primal_col, i, simplex_info.workValue_[i]); } } // If debugging, take a copy of the RHS vector<double> debug_primal_rhs; if (highs_model_object.options_.highs_debug_level >= HIGHS_DEBUG_LEVEL_COSTLY) debug_primal_rhs = primal_col.array; // It's possible that the buffer has no nonzeros, so performing // FTRAN is unnecessary. Not much of a saving, but the zero density // looks odd in the analysis! if (primal_col.count) { factor.ftran(primal_col, analysis->primal_col_density, analysis->pointer_serial_factor_clocks); const double local_primal_col_density = (double)primal_col.count / simplex_lp.numRow_; analysis->updateOperationResultDensity(local_primal_col_density, analysis->primal_col_density); } for (int i = 0; i < simplex_lp.numRow_; i++) { int iCol = simplex_basis.basicIndex_[i]; simplex_info.baseValue_[i] = -primal_col.array[i]; simplex_info.baseLower_[i] = simplex_info.workLower_[iCol]; simplex_info.baseUpper_[i] = simplex_info.workUpper_[iCol]; } debugComputePrimal(highs_model_object, debug_primal_rhs); // Now have basic primals simplex_lp_status.has_basic_primal_values = true; } void computeSimplexInfeasible(HighsModelObject& highs_model_object) { HighsSimplexAnalysis& analysis = highs_model_object.simplex_analysis_; analysis.simplexTimerStart(ComputePrIfsClock); computeSimplexPrimalInfeasible(highs_model_object); analysis.simplexTimerStop(ComputePrIfsClock); analysis.simplexTimerStart(ComputeDuIfsClock); computeSimplexDualInfeasible(highs_model_object); analysis.simplexTimerStop(ComputeDuIfsClock); } void computeSimplexPrimalInfeasible(HighsModelObject& highs_model_object) { // Computes num/max/sum of primal infeasibliities according to the // simplex bounds. This is used to determine optimality in dual // phase 1 and dual phase 2, albeit using different bounds in // workLower/Upper. const HighsLp& simplex_lp = highs_model_object.simplex_lp_; const HighsSimplexInfo& simplex_info = highs_model_object.simplex_info_; const SimplexBasis& simplex_basis = highs_model_object.simplex_basis_; const double scaled_primal_feasibility_tolerance = highs_model_object.scaled_solution_params_.primal_feasibility_tolerance; int& num_primal_infeasibilities = highs_model_object.simplex_info_.num_primal_infeasibilities; double& max_primal_infeasibility = highs_model_object.simplex_info_.max_primal_infeasibility; double& sum_primal_infeasibilities = highs_model_object.simplex_info_.sum_primal_infeasibilities; num_primal_infeasibilities = 0; max_primal_infeasibility = 0; sum_primal_infeasibilities = 0; for (int i = 0; i < simplex_lp.numCol_ + simplex_lp.numRow_; i++) { if (simplex_basis.nonbasicFlag_[i]) { // Nonbasic column double value = simplex_info.workValue_[i]; double lower = simplex_info.workLower_[i]; double upper = simplex_info.workUpper_[i]; double primal_infeasibility = max(lower - value, value - upper); if (primal_infeasibility > 0) { if (primal_infeasibility > scaled_primal_feasibility_tolerance) num_primal_infeasibilities++; max_primal_infeasibility = std::max(primal_infeasibility, max_primal_infeasibility); sum_primal_infeasibilities += primal_infeasibility; } } } for (int i = 0; i < simplex_lp.numRow_; i++) { // Basic variable double value = simplex_info.baseValue_[i]; double lower = simplex_info.baseLower_[i]; double upper = simplex_info.baseUpper_[i]; double primal_infeasibility = max(lower - value, value - upper); if (primal_infeasibility > 0) { if (primal_infeasibility > scaled_primal_feasibility_tolerance) num_primal_infeasibilities++; max_primal_infeasibility = std::max(primal_infeasibility, max_primal_infeasibility); sum_primal_infeasibilities += primal_infeasibility; } } } void computeSimplexDualInfeasible(HighsModelObject& highs_model_object) { // Computes num/max/sum of dual infeasibilities in phase 1 and phase // 2 according to nonbasicMove. The bounds are only used to identify // free variables. Fixed variables are assumed to have // nonbasicMove=0 so that no dual infeasibility is counted for them. const HighsLp& simplex_lp = highs_model_object.simplex_lp_; const HighsSimplexInfo& simplex_info = highs_model_object.simplex_info_; const SimplexBasis& simplex_basis = highs_model_object.simplex_basis_; const double scaled_dual_feasibility_tolerance = highs_model_object.scaled_solution_params_.dual_feasibility_tolerance; // Possibly verify that nonbasicMove is correct for fixed variables debugFixedNonbasicMove(highs_model_object); int& num_dual_infeasibilities = highs_model_object.simplex_info_.num_dual_infeasibilities; double& max_dual_infeasibility = highs_model_object.simplex_info_.max_dual_infeasibility; double& sum_dual_infeasibilities = highs_model_object.simplex_info_.sum_dual_infeasibilities; num_dual_infeasibilities = 0; max_dual_infeasibility = 0; sum_dual_infeasibilities = 0; for (int iVar = 0; iVar < simplex_lp.numCol_ + simplex_lp.numRow_; iVar++) { if (!simplex_basis.nonbasicFlag_[iVar]) continue; // Nonbasic column const double dual = simplex_info.workDual_[iVar]; const double lower = simplex_info.workLower_[iVar]; const double upper = simplex_info.workUpper_[iVar]; double dual_infeasibility = 0; if (highs_isInfinity(-lower) && highs_isInfinity(upper)) { // Free: any nonzero dual value is infeasible dual_infeasibility = fabs(dual); } else { // Not free: any dual infeasibility is given by the dual value // signed by nonbasicMove dual_infeasibility = -simplex_basis.nonbasicMove_[iVar] * dual; } if (dual_infeasibility > 0) { if (dual_infeasibility >= scaled_dual_feasibility_tolerance) num_dual_infeasibilities++; max_dual_infeasibility = std::max(dual_infeasibility, max_dual_infeasibility); sum_dual_infeasibilities += dual_infeasibility; } } } void computeSimplexLpDualInfeasible(HighsModelObject& highs_model_object) { // Compute num/max/sum of dual infeasibliities according to the // bounds of the simplex LP. Assumes that boxed variables have // primal variable at the bound corresponding to the sign of the // dual so should only be used in dual phase 1 - where it's only // used for reporting after rebuilds and to determine whether the LP // is dual infeasible and, hence, primal unbounded. const HighsLp& simplex_lp = highs_model_object.simplex_lp_; const HighsSimplexInfo& simplex_info = highs_model_object.simplex_info_; const SimplexBasis& simplex_basis = highs_model_object.simplex_basis_; // Possibly verify that nonbasicMove is correct for fixed variables debugFixedNonbasicMove(highs_model_object); const double scaled_dual_feasibility_tolerance = highs_model_object.scaled_solution_params_.dual_feasibility_tolerance; int& num_dual_infeasibilities = highs_model_object.scaled_solution_params_.num_dual_infeasibilities; double& max_dual_infeasibility = highs_model_object.scaled_solution_params_.max_dual_infeasibility; double& sum_dual_infeasibilities = highs_model_object.scaled_solution_params_.sum_dual_infeasibilities; num_dual_infeasibilities = 0; max_dual_infeasibility = 0; sum_dual_infeasibilities = 0; for (int iCol = 0; iCol < simplex_lp.numCol_; iCol++) { int iVar = iCol; if (!simplex_basis.nonbasicFlag_[iVar]) continue; // Nonbasic column const double dual = simplex_info.workDual_[iVar]; const double lower = simplex_lp.colLower_[iCol]; const double upper = simplex_lp.colUpper_[iCol]; double dual_infeasibility = 0; if (highs_isInfinity(upper)) { if (highs_isInfinity(-lower)) { // Free: any nonzero dual value is infeasible dual_infeasibility = fabs(dual); } else { // Only lower bounded: a negative dual is infeasible dual_infeasibility = -dual; } } else { if (highs_isInfinity(-lower)) { // Only upper bounded: a positive dual is infeasible dual_infeasibility = dual; } else { // Boxed or fixed: any dual value is feasible dual_infeasibility = 0; } } if (dual_infeasibility > 0) { if (dual_infeasibility >= scaled_dual_feasibility_tolerance) num_dual_infeasibilities++; max_dual_infeasibility = std::max(dual_infeasibility, max_dual_infeasibility); sum_dual_infeasibilities += dual_infeasibility; } } for (int iRow = 0; iRow < simplex_lp.numRow_; iRow++) { int iVar = simplex_lp.numCol_ + iRow; if (!simplex_basis.nonbasicFlag_[iVar]) continue; // Nonbasic row const double dual = -simplex_info.workDual_[iVar]; const double lower = simplex_lp.rowLower_[iRow]; const double upper = simplex_lp.rowUpper_[iRow]; double dual_infeasibility = 0; if (highs_isInfinity(upper)) { if (highs_isInfinity(-lower)) { // Free: any nonzero dual value is infeasible dual_infeasibility = fabs(dual); } else { // Only lower bounded: a negative dual is infeasible dual_infeasibility = -dual; } } else { if (highs_isInfinity(-lower)) { // Only upper bounded: a positive dual is infeasible dual_infeasibility = dual; } else { // Boxed or fixed: any dual value is feasible dual_infeasibility = 0; } } if (dual_infeasibility > 0) { if (dual_infeasibility >= scaled_dual_feasibility_tolerance) num_dual_infeasibilities++; max_dual_infeasibility = std::max(dual_infeasibility, max_dual_infeasibility); sum_dual_infeasibilities += dual_infeasibility; } } } void copySimplexInfeasible(HighsModelObject& highs_model_object) { copySimplexPrimalInfeasible(highs_model_object); copySimplexDualInfeasible(highs_model_object); } void copySimplexPrimalInfeasible(HighsModelObject& highs_model_object) { highs_model_object.scaled_solution_params_.num_primal_infeasibilities = highs_model_object.simplex_info_.num_primal_infeasibilities; highs_model_object.scaled_solution_params_.max_primal_infeasibility = highs_model_object.simplex_info_.max_primal_infeasibility; highs_model_object.scaled_solution_params_.sum_primal_infeasibilities = highs_model_object.simplex_info_.sum_primal_infeasibilities; } void copySimplexDualInfeasible(HighsModelObject& highs_model_object) { highs_model_object.scaled_solution_params_.num_dual_infeasibilities = highs_model_object.simplex_info_.num_dual_infeasibilities; highs_model_object.scaled_solution_params_.max_dual_infeasibility = highs_model_object.simplex_info_.max_dual_infeasibility; highs_model_object.scaled_solution_params_.sum_dual_infeasibilities = highs_model_object.simplex_info_.sum_dual_infeasibilities; } void computeDualInfeasibleWithFlips(HighsModelObject& highs_model_object) { // Computes num/max/sum of dual infeasibliities according to // nonbasicMove, using the bounds only to identify free variables // and non-boxed. Fixed variables are assumed to have nonbasicMove=0 // so that no dual infeasibility is counted for them. Indeed, when // called from cleanup() at the end of dual phase 1, nonbasicMove // relates to the phase 1 bounds, but workLower and workUpper will // have been set to phase 2 values! const HighsLp& simplex_lp = highs_model_object.simplex_lp_; const HighsSimplexInfo& simplex_info = highs_model_object.simplex_info_; const SimplexBasis& simplex_basis = highs_model_object.simplex_basis_; HighsSolutionParams& scaled_solution_params = highs_model_object.scaled_solution_params_; const double scaled_dual_feasibility_tolerance = scaled_solution_params.dual_feasibility_tolerance; // Possibly verify that nonbasicMove is correct for fixed variables debugFixedNonbasicMove(highs_model_object); int num_dual_infeasibilities = 0; double max_dual_infeasibility = 0; double sum_dual_infeasibilities = 0; const int numTot = simplex_lp.numCol_ + simplex_lp.numRow_; for (int iVar = 0; iVar < numTot; iVar++) { if (!simplex_basis.nonbasicFlag_[iVar]) continue; // Nonbasic column const double lower = simplex_info.workLower_[iVar]; const double upper = simplex_info.workUpper_[iVar]; const double dual = simplex_info.workDual_[iVar]; double dual_infeasibility = 0; if (highs_isInfinity(-lower) && highs_isInfinity(upper)) { // Free: any nonzero dual value is infeasible dual_infeasibility = fabs(dual); } else if (highs_isInfinity(-lower) || highs_isInfinity(upper)) { // Not free or boxed: any dual infeasibility is given by value // signed by nonbasicMove. // // For boxed variables, nonbasicMove may have the wrong sign for // dual, but nonbasicMove and the primal value can be flipped to // achieve dual feasiblility. dual_infeasibility = -simplex_basis.nonbasicMove_[iVar] * dual; } if (dual_infeasibility > 0) { if (dual_infeasibility >= scaled_dual_feasibility_tolerance) num_dual_infeasibilities++; max_dual_infeasibility = std::max(dual_infeasibility, max_dual_infeasibility); sum_dual_infeasibilities += dual_infeasibility; } } scaled_solution_params.num_dual_infeasibilities = num_dual_infeasibilities; scaled_solution_params.max_dual_infeasibility = max_dual_infeasibility; scaled_solution_params.sum_dual_infeasibilities = sum_dual_infeasibilities; } void choosePriceTechnique(const int price_strategy, const double row_ep_density, bool& use_col_price, bool& use_row_price_w_switch) { // By default switch to column PRICE when pi_p has at least this // density const double density_for_column_price_switch = 0.75; use_col_price = (price_strategy == SIMPLEX_PRICE_STRATEGY_COL) || (price_strategy == SIMPLEX_PRICE_STRATEGY_ROW_SWITCH_COL_SWITCH && row_ep_density > density_for_column_price_switch); use_row_price_w_switch = price_strategy == SIMPLEX_PRICE_STRATEGY_ROW_SWITCH || price_strategy == SIMPLEX_PRICE_STRATEGY_ROW_SWITCH_COL_SWITCH; } void computeTableauRowFromPiP(HighsModelObject& highs_model_object, const HVector& row_ep, HVector& row_ap) { HighsSimplexInfo& simplex_info = highs_model_object.simplex_info_; const HMatrix* matrix = &highs_model_object.matrix_; HighsSimplexAnalysis& analysis = highs_model_object.simplex_analysis_; const int solver_num_row = highs_model_object.simplex_lp_.numRow_; const double local_density = 1.0 * row_ep.count / solver_num_row; bool use_col_price; bool use_row_price_w_switch; choosePriceTechnique(simplex_info.price_strategy, local_density, use_col_price, use_row_price_w_switch); #ifdef HiGHSDEV if (simplex_info.analyse_iterations) { if (use_col_price) { analysis.operationRecordBefore(ANALYSIS_OPERATION_TYPE_PRICE_AP, row_ep, 0.0); analysis.num_col_price++; } else if (use_row_price_w_switch) { analysis.operationRecordBefore(ANALYSIS_OPERATION_TYPE_PRICE_AP, row_ep, analysis.row_ep_density); analysis.num_row_price_with_switch++; } else { analysis.operationRecordBefore(ANALYSIS_OPERATION_TYPE_PRICE_AP, row_ep, analysis.row_ep_density); analysis.num_row_price++; } } #endif analysis.simplexTimerStart(PriceClock); row_ap.clear(); if (use_col_price) { // Perform column-wise PRICE matrix->priceByColumn(row_ap, row_ep); } else if (use_row_price_w_switch) { // Perform hyper-sparse row-wise PRICE, but switch if the density of row_ap // becomes extreme const double switch_density = matrix->hyperPRICE; matrix->priceByRowSparseResultWithSwitch( row_ap, row_ep, analysis.row_ap_density, 0, switch_density); } else { // Perform hyper-sparse row-wise PRICE matrix->priceByRowSparseResult(row_ap, row_ep); } const int solver_num_col = highs_model_object.simplex_lp_.numCol_; if (use_col_price) { // Column-wise PRICE computes components of row_ap corresponding // to basic variables, so zero these by exploiting the fact that, // for basic variables, nonbasicFlag[*]=0 const int* nonbasicFlag = &highs_model_object.simplex_basis_.nonbasicFlag_[0]; for (int col = 0; col < solver_num_col; col++) row_ap.array[col] = nonbasicFlag[col] * row_ap.array[col]; } #ifdef HiGHSDEV // Possibly analyse the error in the result of PRICE const bool analyse_price_error = false; if (analyse_price_error) matrix->debugPriceResult(row_ap, row_ep); #endif // Update the record of average row_ap density const double local_row_ap_density = (double)row_ap.count / solver_num_col; analysis.updateOperationResultDensity(local_row_ap_density, analysis.row_ap_density); #ifdef HiGHSDEV if (simplex_info.analyse_iterations) analysis.operationRecordAfter(ANALYSIS_OPERATION_TYPE_PRICE_AP, row_ap); #endif analysis.simplexTimerStop(PriceClock); } void computeDual(HighsModelObject& highs_model_object) { HighsSimplexAnalysis& analysis = highs_model_object.simplex_analysis_; const HighsLp& simplex_lp = highs_model_object.simplex_lp_; HighsSimplexInfo& simplex_info = highs_model_object.simplex_info_; HighsSimplexLpStatus& simplex_lp_status = highs_model_object.simplex_lp_status_; const SimplexBasis& simplex_basis = highs_model_object.simplex_basis_; HMatrix& matrix = highs_model_object.matrix_; HFactor& factor = highs_model_object.factor_; // Create a local buffer for the pi vector HVector dual_col; dual_col.setup(simplex_lp.numRow_); dual_col.clear(); for (int iRow = 0; iRow < simplex_lp.numRow_; iRow++) { const double value = simplex_info.workCost_[simplex_basis.basicIndex_[iRow]] + simplex_info.workShift_[simplex_basis.basicIndex_[iRow]]; if (value) { dual_col.count++; dual_col.index[iRow] = iRow; dual_col.array[iRow] = value; } } // If debugging, take a copy of the basic costs and any previous duals vector<double> debug_previous_workDual; vector<double> debug_basic_costs; if (highs_model_object.options_.highs_debug_level >= HIGHS_DEBUG_LEVEL_COSTLY) { debug_basic_costs = dual_col.array; if (simplex_lp_status.has_nonbasic_dual_values) debug_previous_workDual = simplex_info.workDual_; } // Copy the costs in case the basic costs are all zero const int numTot = simplex_lp.numCol_ + simplex_lp.numRow_; for (int i = 0; i < numTot; i++) simplex_info.workDual_[i] = simplex_info.workCost_[i]; if (dual_col.count) { // RHS of row dual calculation is nonzero #ifdef HiGHSDEV if (simplex_info.analyse_iterations) analysis.operationRecordBefore(ANALYSIS_OPERATION_TYPE_BTRAN_FULL, dual_col, analysis.dual_col_density); #endif factor.btran(dual_col, analysis.dual_col_density, analysis.pointer_serial_factor_clocks); #ifdef HiGHSDEV if (simplex_info.analyse_iterations) analysis.operationRecordAfter(ANALYSIS_OPERATION_TYPE_BTRAN_FULL, dual_col); #endif const double local_dual_col_density = (double)dual_col.count / simplex_lp.numRow_; analysis.updateOperationResultDensity(local_dual_col_density, analysis.dual_col_density); // Create a local buffer for the values of reduced costs HVector dual_row; dual_row.setup(simplex_lp.numCol_); dual_row.clear(); #ifdef HiGHSDEV double price_full_historical_density = 1; if (simplex_info.analyse_iterations) analysis.operationRecordBefore(ANALYSIS_OPERATION_TYPE_PRICE_FULL, dual_row, price_full_historical_density); #endif matrix.priceByColumn(dual_row, dual_col); #ifdef HiGHSDEV if (simplex_info.analyse_iterations) analysis.operationRecordAfter(ANALYSIS_OPERATION_TYPE_PRICE_FULL, dual_row); #endif for (int i = 0; i < simplex_lp.numCol_; i++) simplex_info.workDual_[i] -= dual_row.array[i]; for (int i = simplex_lp.numCol_; i < numTot; i++) simplex_info.workDual_[i] -= dual_col.array[i - simplex_lp.numCol_]; // Possibly analyse the computed dual values debugComputeDual(highs_model_object, debug_previous_workDual, debug_basic_costs, dual_col.array); } // Now have nonbasic duals simplex_lp_status.has_nonbasic_dual_values = true; } void correctDual(HighsModelObject& highs_model_object, int* free_infeasibility_count) { const HighsLp& simplex_lp = highs_model_object.simplex_lp_; HighsSimplexInfo& simplex_info = highs_model_object.simplex_info_; const SimplexBasis& simplex_basis = highs_model_object.simplex_basis_; HighsRandom& random = highs_model_object.random_; const double tau_d = highs_model_object.scaled_solution_params_.dual_feasibility_tolerance; const double inf = HIGHS_CONST_INF; int workCount = 0; double flip_dual_objective_value_change = 0; double shift_dual_objective_value_change = 0; int num_flip = 0; int num_shift = 0; double sum_flip = 0; double sum_shift = 0; const int numTot = simplex_lp.numCol_ + simplex_lp.numRow_; for (int i = 0; i < numTot; i++) { if (simplex_basis.nonbasicFlag_[i]) { if (simplex_info.workLower_[i] == -inf && simplex_info.workUpper_[i] == inf) { // FREE variable workCount += (fabs(simplex_info.workDual_[i]) >= tau_d); } else if (simplex_basis.nonbasicMove_[i] * simplex_info.workDual_[i] <= -tau_d) { if (simplex_info.workLower_[i] != -inf && simplex_info.workUpper_[i] != inf) { // Boxed variable = flip const int move = simplex_basis.nonbasicMove_[i]; flip_bound(highs_model_object, i); double flip = simplex_info.workUpper_[i] - simplex_info.workLower_[i]; // Negative dual at lower bound (move=1): flip to upper // bound so objective contribution is change in value (flip) // times dual, being move*flip*dual // // Positive dual at upper bound (move=-1): flip to lower // bound so objective contribution is change in value // (-flip) times dual, being move*flip*dual double local_dual_objective_change = move * flip * simplex_info.workDual_[i]; local_dual_objective_change *= highs_model_object.scale_.cost_; flip_dual_objective_value_change += local_dual_objective_change; num_flip++; sum_flip += fabs(flip); } else if (simplex_info.allow_cost_perturbation) { // Other variable = shift // // Before 07/01/20, these shifts were always done, but doing // it after cost perturbation has been removed can lead to // cycling when primal infeasibility has been detecteed in // Phase 2, since the shift below removes dual // infeasibilities, which are then reinstated after the dual // values are recomputed. // // ToDo: Not shifting leads to dual infeasibilities when an // LP is declared to be (primal) infeasible. Should go to // phase 1 primal simplex to "prove" infeasibility. simplex_info.costs_perturbed = 1; std::string direction; double shift; if (simplex_basis.nonbasicMove_[i] == 1) { direction = " up"; double dual = (1 + random.fraction()) * tau_d; shift = dual - simplex_info.workDual_[i]; simplex_info.workDual_[i] = dual; simplex_info.workCost_[i] = simplex_info.workCost_[i] + shift; } else { direction = "down"; double dual = -(1 + random.fraction()) * tau_d; shift = dual - simplex_info.workDual_[i]; simplex_info.workDual_[i] = dual; simplex_info.workCost_[i] = simplex_info.workCost_[i] + shift; } double local_dual_objective_change = shift * simplex_info.workValue_[i]; local_dual_objective_change *= highs_model_object.scale_.cost_; shift_dual_objective_value_change += local_dual_objective_change; num_shift++; sum_shift += fabs(shift); HighsPrintMessage( highs_model_object.options_.output, highs_model_object.options_.message_level, ML_VERBOSE, "Move %s: cost shift = %g; objective change = %g\n", direction.c_str(), shift, local_dual_objective_change); } } } } if (num_flip) HighsPrintMessage( highs_model_object.options_.output, highs_model_object.options_.message_level, ML_VERBOSE, "Performed %d flip(s): total = %g; objective change = %g\n", num_flip, sum_flip, flip_dual_objective_value_change); if (num_shift) HighsPrintMessage( highs_model_object.options_.output, highs_model_object.options_.message_level, ML_DETAILED, "Performed %d cost shift(s): total = %g; objective change = %g\n", num_shift, sum_shift, shift_dual_objective_value_change); *free_infeasibility_count = workCount; } // Record the shift in the cost of a particular column void shift_cost(HighsModelObject& highs_model_object, int iCol, double amount) { HighsSimplexInfo& simplex_info = highs_model_object.simplex_info_; simplex_info.costs_perturbed = 1; if (simplex_info.workShift_[iCol] != 0) { printf("Column %d already has nonzero shift of %g\n", iCol, simplex_info.workShift_[iCol]); } assert(simplex_info.workShift_[iCol] == 0); simplex_info.workShift_[iCol] = amount; } // Undo the shift in the cost of a particular column void shift_back(HighsModelObject& highs_model_object, int iCol) { HighsSimplexInfo& simplex_info = highs_model_object.simplex_info_; simplex_info.workDual_[iCol] -= simplex_info.workShift_[iCol]; /* if (simplex_info.workShift_[iCol]) { printf("shift_back: column %d: shift = %g; value = %g\n", iCol, simplex_info.workShift_[iCol], simplex_info.workValue_[iCol]); simplex_info.updated_dual_objective_value -= simplex_info.workShift_[iCol] * simplex_info.workValue_[iCol]; } */ simplex_info.workShift_[iCol] = 0; } // The major model updates. Factor calls factor.update; Matrix // calls matrix.update; updatePivots does everything---and is // called from the likes of HDual::updatePivots void update_factor(HighsModelObject& highs_model_object, HVector* column, HVector* row_ep, int* iRow, int* hint) { // HighsLp &simplex_lp = highs_model_object.simplex_lp_; HighsSimplexInfo& simplex_info = highs_model_object.simplex_info_; HighsSimplexLpStatus& simplex_lp_status = highs_model_object.simplex_lp_status_; HFactor& factor = highs_model_object.factor_; HighsSimplexAnalysis& analysis = highs_model_object.simplex_analysis_; analysis.simplexTimerStart(UpdateFactorClock); factor.update(column, row_ep, iRow, hint); // Now have a representation of B^{-1}, but it is not fresh simplex_lp_status.has_invert = true; if (simplex_info.update_count >= simplex_info.update_limit) *hint = INVERT_HINT_UPDATE_LIMIT_REACHED; analysis.simplexTimerStop(UpdateFactorClock); } void update_pivots(HighsModelObject& highs_model_object, int columnIn, int rowOut, int sourceOut) { HighsLp& simplex_lp = highs_model_object.simplex_lp_; HighsSimplexInfo& simplex_info = highs_model_object.simplex_info_; HighsSimplexLpStatus& simplex_lp_status = highs_model_object.simplex_lp_status_; SimplexBasis& simplex_basis = highs_model_object.simplex_basis_; HighsSimplexAnalysis& analysis = highs_model_object.simplex_analysis_; analysis.simplexTimerStart(UpdatePivotsClock); int columnOut = simplex_basis.basicIndex_[rowOut]; // Incoming variable simplex_basis.basicIndex_[rowOut] = columnIn; simplex_basis.nonbasicFlag_[columnIn] = 0; simplex_basis.nonbasicMove_[columnIn] = 0; simplex_info.baseLower_[rowOut] = simplex_info.workLower_[columnIn]; simplex_info.baseUpper_[rowOut] = simplex_info.workUpper_[columnIn]; // Outgoing variable simplex_basis.nonbasicFlag_[columnOut] = 1; if (simplex_info.workLower_[columnOut] == simplex_info.workUpper_[columnOut]) { simplex_info.workValue_[columnOut] = simplex_info.workLower_[columnOut]; simplex_basis.nonbasicMove_[columnOut] = 0; } else if (sourceOut == -1) { simplex_info.workValue_[columnOut] = simplex_info.workLower_[columnOut]; simplex_basis.nonbasicMove_[columnOut] = 1; } else { simplex_info.workValue_[columnOut] = simplex_info.workUpper_[columnOut]; simplex_basis.nonbasicMove_[columnOut] = -1; } // Update the dual objective value double nwValue = simplex_info.workValue_[columnOut]; double vrDual = simplex_info.workDual_[columnOut]; double dl_dual_objective_value = nwValue * vrDual; simplex_info.updated_dual_objective_value += dl_dual_objective_value; simplex_info.update_count++; // Update the number of basic logicals if (columnOut < simplex_lp.numCol_) simplex_info.num_basic_logicals -= 1; if (columnIn < simplex_lp.numCol_) simplex_info.num_basic_logicals += 1; // No longer have a representation of B^{-1}, and certainly not // fresh! simplex_lp_status.has_invert = false; simplex_lp_status.has_fresh_invert = false; // Data are no longer fresh from rebuild simplex_lp_status.has_fresh_rebuild = false; analysis.simplexTimerStop(UpdatePivotsClock); } void update_matrix(HighsModelObject& highs_model_object, int columnIn, int columnOut) { HMatrix& matrix = highs_model_object.matrix_; HighsSimplexAnalysis& analysis = highs_model_object.simplex_analysis_; analysis.simplexTimerStart(UpdateMatrixClock); matrix.update(columnIn, columnOut); analysis.simplexTimerStop(UpdateMatrixClock); } bool reinvertOnNumericalTrouble(const std::string method_name, HighsModelObject& highs_model_object, double& numerical_trouble_measure, const double alpha_from_col, const double alpha_from_row, const double numerical_trouble_tolerance) { double abs_alpha_from_col = fabs(alpha_from_col); double abs_alpha_from_row = fabs(alpha_from_row); double min_abs_alpha = min(abs_alpha_from_col, abs_alpha_from_row); double abs_alpha_diff = fabs(abs_alpha_from_col - abs_alpha_from_row); numerical_trouble_measure = abs_alpha_diff / min_abs_alpha; const int update_count = highs_model_object.simplex_info_.update_count; // Reinvert if the relative difference is large enough, and updates have been // performed const bool numerical_trouble = numerical_trouble_measure > numerical_trouble_tolerance; const bool reinvert = numerical_trouble && update_count > 0; debugReportReinvertOnNumericalTrouble( method_name, highs_model_object, numerical_trouble_measure, alpha_from_col, alpha_from_row, numerical_trouble_tolerance, reinvert); if (reinvert) { // Consider increasing the Markowitz multiplier const double current_pivot_threshold = highs_model_object.simplex_info_.factor_pivot_threshold; double new_pivot_threshold = 0; if (current_pivot_threshold < default_pivot_threshold) { // Threshold is below default value, so increase it new_pivot_threshold = min(current_pivot_threshold * pivot_threshold_change_factor, default_pivot_threshold); } else if (current_pivot_threshold < max_pivot_threshold) { // Threshold is below max value, so increase it if few updates have been // performed if (update_count < 10) new_pivot_threshold = min(current_pivot_threshold * pivot_threshold_change_factor, max_pivot_threshold); } if (new_pivot_threshold) { HighsLogMessage( highs_model_object.options_.logfile, HighsMessageType::WARNING, " Increasing Markowitz threshold to %g", new_pivot_threshold); highs_model_object.simplex_info_.factor_pivot_threshold = new_pivot_threshold; highs_model_object.factor_.setPivotThreshold(new_pivot_threshold); } } return reinvert; } // If the scaled LP's model status is optimal, gets suggested // feasibility tolerances for resolving the scaled LP. Assumes that // the unscaled primal and dual infeasibilities are not known in // highs_model_object, so also passes get_unscaled_solution_params as // values to check from HighsStatus getNewInfeasibilityTolerancesFromSimplexBasicSolution( const HighsModelObject& highs_model_object, HighsSolutionParams& get_unscaled_solution_params, double& new_scaled_primal_feasibility_tolerance, double& new_scaled_dual_feasibility_tolerance) { HighsSolutionParams get_scaled_solution_params = highs_model_object.scaled_solution_params_; return getInfeasibilitiesAndNewTolerances( highs_model_object.options_, highs_model_object.lp_, highs_model_object.scale_, highs_model_object.simplex_basis_, highs_model_object.simplex_info_, highs_model_object.scaled_model_status_, get_unscaled_solution_params, highs_model_object.scaled_solution_params_, get_unscaled_solution_params, get_scaled_solution_params, new_scaled_primal_feasibility_tolerance, new_scaled_dual_feasibility_tolerance); } // Gets the unscaled and scaled primal and dual infeasibilities from a // simplex basic solution. The values in unscaled_solution_params and // scaled_solution_params are checked against them. If the scaled LP's // model status is optimal, gets suggested feasibility tolerances for // resolving the scaled LP HighsStatus getInfeasibilitiesAndNewTolerances( const HighsOptions& options, const HighsLp& lp, const HighsScale& scale, const SimplexBasis& basis, const HighsSimplexInfo& simplex_info, const HighsModelStatus scaled_model_status, const HighsSolutionParams& unscaled_solution_params, const HighsSolutionParams& scaled_solution_params, HighsSolutionParams& get_unscaled_solution_params, HighsSolutionParams& get_scaled_solution_params, double& new_scaled_primal_feasibility_tolerance, double& new_scaled_dual_feasibility_tolerance) { const double unscaled_primal_feasibility_tolerance = unscaled_solution_params.primal_feasibility_tolerance; const double unscaled_dual_feasibility_tolerance = unscaled_solution_params.dual_feasibility_tolerance; get_unscaled_solution_params = unscaled_solution_params; get_scaled_solution_params = scaled_solution_params; int& num_unscaled_primal_infeasibilities = get_unscaled_solution_params.num_primal_infeasibilities; double& max_unscaled_primal_infeasibility = get_unscaled_solution_params.max_primal_infeasibility; double& sum_unscaled_primal_infeasibilities = get_unscaled_solution_params.sum_primal_infeasibilities; int& num_unscaled_dual_infeasibilities = get_unscaled_solution_params.num_dual_infeasibilities; double& max_unscaled_dual_infeasibility = get_unscaled_solution_params.max_dual_infeasibility; double& sum_unscaled_dual_infeasibilities = get_unscaled_solution_params.sum_dual_infeasibilities; int& num_scaled_primal_infeasibilities = get_scaled_solution_params.num_primal_infeasibilities; double& max_scaled_primal_infeasibility = get_scaled_solution_params.max_primal_infeasibility; double& sum_scaled_primal_infeasibilities = get_scaled_solution_params.sum_primal_infeasibilities; int& num_scaled_dual_infeasibilities = get_scaled_solution_params.num_dual_infeasibilities; double& max_scaled_dual_infeasibility = get_scaled_solution_params.max_dual_infeasibility; double& sum_scaled_dual_infeasibilities = get_scaled_solution_params.sum_dual_infeasibilities; // Invalidate the unscaled and scaled infeasibility params invalidateSolutionInfeasibilityParams(get_unscaled_solution_params); invalidateSolutionInfeasibilityParams(get_scaled_solution_params); // Zero the counts of unscaled and scaled primal and dual infeasibilities num_unscaled_primal_infeasibilities = 0; num_unscaled_dual_infeasibilities = 0; num_scaled_primal_infeasibilities = 0; num_scaled_dual_infeasibilities = 0; // If the scaled LP has beeen solved to optimality, look at the // scaled solution and, if there are infeasibilities, identify new // feasibility tolerances for the scaled LP const bool get_new_scaled_feasibility_tolerances = scaled_model_status == HighsModelStatus::OPTIMAL; // The scaled infeasibility parameters are not known if the dual // objective upper bound has been reached, the time limit has been // reached, or the iteration limit has been reached, const bool check_scaled_solution_params = scaled_model_status != HighsModelStatus::REACHED_DUAL_OBJECTIVE_VALUE_UPPER_BOUND && scaled_model_status != HighsModelStatus::REACHED_TIME_LIMIT && scaled_model_status != HighsModelStatus::REACHED_ITERATION_LIMIT; const double scaled_primal_feasibility_tolerance = scaled_solution_params.primal_feasibility_tolerance; const double scaled_dual_feasibility_tolerance = scaled_solution_params.dual_feasibility_tolerance; if (get_new_scaled_feasibility_tolerances) { new_scaled_primal_feasibility_tolerance = scaled_primal_feasibility_tolerance; new_scaled_dual_feasibility_tolerance = scaled_dual_feasibility_tolerance; } for (int iVar = 0; iVar < lp.numCol_ + lp.numRow_; iVar++) { // Look at the dual infeasibilities of nonbasic variables if (basis.nonbasicFlag_[iVar] == NONBASIC_FLAG_FALSE) continue; // No dual infeasiblity for fixed rows and columns if (simplex_info.workLower_[iVar] == simplex_info.workUpper_[iVar]) continue; bool col = iVar < lp.numCol_; double scale_mu; int iCol = 0; int iRow = 0; if (col) { iCol = iVar; scale_mu = 1 / (scale.col_[iCol] / scale.cost_); } else { iRow = iVar - lp.numCol_; scale_mu = scale.row_[iRow] * scale.cost_; } const double scaled_dual = simplex_info.workDual_[iVar]; const double unscaled_dual = scaled_dual * scale_mu; const double lower = simplex_info.workLower_[iVar]; const double upper = simplex_info.workUpper_[iVar]; double scaled_dual_infeasibility; double unscaled_dual_infeasibility; if (highs_isInfinity(-lower) && highs_isInfinity(upper)) { // Free: any nonzero dual value is infeasible scaled_dual_infeasibility = fabs(scaled_dual); unscaled_dual_infeasibility = fabs(unscaled_dual); } else { // Not fixed: any dual infeasibility is given by value signed by // nonbasicMove. This assumes that nonbasicMove=0 for fixed // variables scaled_dual_infeasibility = -basis.nonbasicMove_[iVar] * scaled_dual; unscaled_dual_infeasibility = -basis.nonbasicMove_[iVar] * unscaled_dual; } if (scaled_dual_infeasibility > 0) { if (scaled_dual_infeasibility >= scaled_dual_feasibility_tolerance) num_scaled_dual_infeasibilities++; max_scaled_dual_infeasibility = max(scaled_dual_infeasibility, max_scaled_dual_infeasibility); sum_scaled_dual_infeasibilities += scaled_dual_infeasibility; } if (unscaled_dual_infeasibility > 0) { if (unscaled_dual_infeasibility >= unscaled_dual_feasibility_tolerance) { num_unscaled_dual_infeasibilities++; if (get_new_scaled_feasibility_tolerances) { double multiplier = unscaled_dual_feasibility_tolerance / scale_mu; #ifdef HiGHSDEV /* double value = simplex_info.workValue_[iVar]; HighsLogMessage(logfile, HighsMessageType::INFO, "Var %6d (%6d, %6d): [%11.4g, %11.4g, %11.4g] %11.4g s=%11.4g %11.4g: Mu = %g", iVar, iCol, iRow, lower, value, upper, scaled_dual_infeasibility, scale_mu, unscaled_dual_infeasibility, multiplier); */ #endif new_scaled_dual_feasibility_tolerance = min(multiplier, new_scaled_dual_feasibility_tolerance); } } max_unscaled_dual_infeasibility = max(unscaled_dual_infeasibility, max_unscaled_dual_infeasibility); sum_unscaled_dual_infeasibilities += unscaled_dual_infeasibility; } } // Look at the primal infeasibilities of basic variables for (int ix = 0; ix < lp.numRow_; ix++) { int iVar = basis.basicIndex_[ix]; bool col = iVar < lp.numCol_; double scale_mu; int iCol = 0; int iRow = 0; if (col) { iCol = iVar; scale_mu = scale.col_[iCol]; } else { iRow = iVar - lp.numCol_; scale_mu = 1 / scale.row_[iRow]; } // Look at the basic primal infeasibilities double lower = simplex_info.baseLower_[ix]; double upper = simplex_info.baseUpper_[ix]; double value = simplex_info.baseValue_[ix]; double scaled_primal_infeasibility = max(max(lower - value, value - upper), 0.); double unscaled_primal_infeasibility = scaled_primal_infeasibility * scale_mu; if (scaled_primal_infeasibility > scaled_primal_feasibility_tolerance) { num_scaled_primal_infeasibilities++; } max_scaled_primal_infeasibility = max(scaled_primal_infeasibility, max_scaled_primal_infeasibility); sum_scaled_primal_infeasibilities += scaled_primal_infeasibility; if (unscaled_primal_infeasibility > unscaled_primal_feasibility_tolerance) { num_unscaled_primal_infeasibilities++; if (get_new_scaled_feasibility_tolerances) { double multiplier = unscaled_primal_feasibility_tolerance / scale_mu; #ifdef HiGHSDEV /* HighsLogMessage(logfile, HighsMessageType::INFO, "Var %6d (%6d, %6d): [%11.4g, %11.4g, %11.4g] %11.4g s=%11.4g %11.4g: Mu = %g", iVar, iCol, iRow, lower, value, upper, scaled_primal_infeasibility, scale_mu, unscaled_primal_infeasibility, multiplier); */ #endif new_scaled_primal_feasibility_tolerance = min(multiplier, new_scaled_primal_feasibility_tolerance); } } max_unscaled_primal_infeasibility = max(unscaled_primal_infeasibility, max_unscaled_primal_infeasibility); sum_unscaled_primal_infeasibilities += unscaled_primal_infeasibility; } HighsDebugStatus debug_status; debug_status = debugCompareSolutionInfeasibilityParams( options, get_unscaled_solution_params, unscaled_solution_params); if (debug_status != HighsDebugStatus::OK) { HighsLogMessage(options.logfile, HighsMessageType::ERROR, "Unequal unscaled solution infeasibility params in " "getPrimalDualInfeasibilitiesFromSimplexBasicSolution"); assert(debug_status == HighsDebugStatus::OK); return HighsStatus::Error; } if (check_scaled_solution_params) { debug_status = debugCompareSolutionInfeasibilityParams( options, get_scaled_solution_params, scaled_solution_params); if (debug_status != HighsDebugStatus::OK) { HighsLogMessage(options.logfile, HighsMessageType::ERROR, "Unequal scaled solution infeasibility params in " "getPrimalDualInfeasibilitiesFromSimplexBasicSolution"); assert(debug_status == HighsDebugStatus::OK); return HighsStatus::Error; } } return HighsStatus::OK; } void logRebuild(HighsModelObject& highs_model_object, const bool primal, const int solve_phase) { HighsSolutionParams& scaled_solution_params = highs_model_object.scaled_solution_params_; HighsSimplexInfo& simplex_info = highs_model_object.simplex_info_; double objective_value; string simplex_variant; if (primal) { simplex_variant = "Pr"; objective_value = simplex_info.primal_objective_value; } else { simplex_variant = "Du"; objective_value = simplex_info.dual_objective_value; } if (solve_phase < 2) { HighsLogMessage(highs_model_object.options_.logfile, HighsMessageType::INFO, "Iter %10d: %20.10e %sPh%1d", highs_model_object.iteration_counts_.simplex, objective_value, simplex_variant.c_str(), solve_phase); } else if (!primal && scaled_solution_params.sum_dual_infeasibilities == 0) { HighsLogMessage(highs_model_object.options_.logfile, HighsMessageType::INFO, "Iter %10d: %20.10e %sPh%1d Pr: %d(%g)", highs_model_object.iteration_counts_.simplex, objective_value, simplex_variant.c_str(), solve_phase, scaled_solution_params.num_primal_infeasibilities, scaled_solution_params.sum_primal_infeasibilities); } else if (primal && scaled_solution_params.num_primal_infeasibilities) { HighsLogMessage(highs_model_object.options_.logfile, HighsMessageType::INFO, "Iter %10d: %20.10e %sPh%1d Pr: %d(%g); Du: %d(%g)", highs_model_object.iteration_counts_.simplex, objective_value, simplex_variant.c_str(), 1, scaled_solution_params.num_primal_infeasibilities, scaled_solution_params.sum_primal_infeasibilities, scaled_solution_params.num_dual_infeasibilities, scaled_solution_params.sum_dual_infeasibilities); } else { HighsLogMessage(highs_model_object.options_.logfile, HighsMessageType::INFO, "Iter %10d: %20.10e %sPh%1d Pr: %d(%g); Du: %d(%g)", highs_model_object.iteration_counts_.simplex, objective_value, simplex_variant.c_str(), solve_phase, scaled_solution_params.num_primal_infeasibilities, scaled_solution_params.sum_primal_infeasibilities, scaled_solution_params.num_dual_infeasibilities, scaled_solution_params.sum_dual_infeasibilities); } } void reportSimplexLpStatus(HighsSimplexLpStatus& simplex_lp_status, const char* message) { printf("\nReporting solver status and flags: %s\n\n", message); printf(" valid = %d\n", simplex_lp_status.valid); printf(" is_dualised = %d\n", simplex_lp_status.is_dualised); printf(" is_permuted = %d\n", simplex_lp_status.is_permuted); printf(" is_scaled = %d\n", simplex_lp_status.scaling_tried); printf(" has_basis = %d\n", simplex_lp_status.has_basis); printf(" has_matrix_col_wise = %d\n", simplex_lp_status.has_matrix_col_wise); printf(" has_matrix_row_wise = %d\n", simplex_lp_status.has_matrix_row_wise); printf(" has_factor_arrays = %d\n", simplex_lp_status.has_factor_arrays); printf(" has_dual_steepest_edge_weights = %d\n", simplex_lp_status.has_dual_steepest_edge_weights); printf(" has_nonbasic_dual_values = %d\n", simplex_lp_status.has_nonbasic_dual_values); printf(" has_basic_primal_values = %d\n", simplex_lp_status.has_basic_primal_values); printf(" has_invert = %d\n", simplex_lp_status.has_invert); printf(" has_fresh_invert = %d\n", simplex_lp_status.has_fresh_invert); printf(" has_fresh_rebuild = %d\n", simplex_lp_status.has_fresh_rebuild); printf(" has_dual_objective_value = %d\n", simplex_lp_status.has_dual_objective_value); printf(" has_primal_objective_value = %d\n", simplex_lp_status.has_primal_objective_value); } void invalidateSimplexLpBasisArtifacts( HighsSimplexLpStatus& simplex_lp_status) { // Invalidate the artifacts of the basis of the simplex LP simplex_lp_status.has_matrix_col_wise = false; simplex_lp_status.has_matrix_row_wise = false; simplex_lp_status.has_factor_arrays = false; simplex_lp_status.has_dual_steepest_edge_weights = false; simplex_lp_status.has_nonbasic_dual_values = false; simplex_lp_status.has_basic_primal_values = false; simplex_lp_status.has_invert = false; simplex_lp_status.has_fresh_invert = false; simplex_lp_status.has_fresh_rebuild = false; simplex_lp_status.has_dual_objective_value = false; simplex_lp_status.has_primal_objective_value = false; simplex_lp_status.has_dual_ray = false; simplex_lp_status.has_primal_ray = false; } void invalidateSimplexLpBasis(HighsSimplexLpStatus& simplex_lp_status) { // Invalidate the basis of the simplex LP, and all its other // properties - since they are basis-related simplex_lp_status.has_basis = false; invalidateSimplexLpBasisArtifacts(simplex_lp_status); } void invalidateSimplexLp(HighsSimplexLpStatus& simplex_lp_status) { simplex_lp_status.valid = false; simplex_lp_status.is_dualised = false; simplex_lp_status.is_permuted = false; simplex_lp_status.scaling_tried = false; invalidateSimplexLpBasis(simplex_lp_status); } void updateSimplexLpStatus(HighsSimplexLpStatus& simplex_lp_status, LpAction action) { switch (action) { case LpAction::DUALISE: #ifdef HIGHSDEV printf(" LpAction::DUALISE\n"); #endif simplex_lp_status.is_dualised = true; invalidateSimplexLpBasis(simplex_lp_status); break; case LpAction::PERMUTE: #ifdef HIGHSDEV printf(" LpAction::PERMUTE\n"); #endif simplex_lp_status.is_permuted = true; invalidateSimplexLpBasis(simplex_lp_status); break; case LpAction::SCALE: #ifdef HIGHSDEV printf(" LpAction::SCALE\n"); #endif simplex_lp_status.scaling_tried = true; invalidateSimplexLpBasis(simplex_lp_status); break; case LpAction::NEW_COSTS: #ifdef HIGHSDEV printf(" LpAction::NEW_COSTS\n"); #endif simplex_lp_status.has_nonbasic_dual_values = false; simplex_lp_status.has_fresh_rebuild = false; simplex_lp_status.has_dual_objective_value = false; simplex_lp_status.has_primal_objective_value = false; break; case LpAction::NEW_BOUNDS: #ifdef HIGHSDEV printf(" LpAction::NEW_BOUNDS\n"); #endif simplex_lp_status.has_basic_primal_values = false; simplex_lp_status.has_fresh_rebuild = false; simplex_lp_status.has_dual_objective_value = false; simplex_lp_status.has_primal_objective_value = false; break; case LpAction::NEW_BASIS: #ifdef HIGHSDEV printf(" LpAction::NEW_BASIS\n"); #endif invalidateSimplexLpBasis(simplex_lp_status); break; case LpAction::NEW_COLS: #ifdef HIGHSDEV printf(" LpAction::NEW_COLS\n"); #endif invalidateSimplexLpBasisArtifacts(simplex_lp_status); break; case LpAction::NEW_ROWS: #ifdef HIGHSDEV printf(" LpAction::NEW_ROWS\n"); #endif invalidateSimplexLpBasisArtifacts(simplex_lp_status); break; case LpAction::DEL_COLS: #ifdef HIGHSDEV printf(" LpAction::DEL_COLS\n"); #endif invalidateSimplexLpBasis(simplex_lp_status); break; case LpAction::DEL_ROWS: #ifdef HIGHSDEV printf(" LpAction::DEL_ROWS\n"); #endif invalidateSimplexLpBasis(simplex_lp_status); break; case LpAction::DEL_ROWS_BASIS_OK: #ifdef HIGHSDEV printf(" LpAction::DEL_ROWS_BASIS_OK\n"); #endif // simplex_info.simplex_lp_ = true; break; case LpAction::SCALED_COL: #ifdef HIGHSDEV printf(" LpAction::SCALED_COL\n"); #endif invalidateSimplexLpBasisArtifacts(simplex_lp_status); break; case LpAction::SCALED_ROW: #ifdef HIGHSDEV printf(" LpAction::SCALED_ROW\n"); #endif invalidateSimplexLpBasisArtifacts(simplex_lp_status); break; case LpAction::BACKTRACKING: #ifdef HIGHSDEV printf(" LpAction::BACKTRACKING\n"); #endif simplex_lp_status.has_matrix_row_wise = false; simplex_lp_status.has_nonbasic_dual_values = false; simplex_lp_status.has_basic_primal_values = false; simplex_lp_status.has_fresh_rebuild = false; simplex_lp_status.has_dual_objective_value = false; simplex_lp_status.has_primal_objective_value = false; break; default: #ifdef HIGHSDEV printf(" Unrecognised LpAction::%d\n", (int)action); #endif break; } } bool isBasisRightSize(const HighsLp& lp, const SimplexBasis& basis) { bool right_size = true; right_size = (int)basis.nonbasicFlag_.size() == lp.numCol_ + lp.numRow_ && right_size; right_size = (int)basis.nonbasicMove_.size() == lp.numCol_ + lp.numRow_ && right_size; right_size = (int)basis.basicIndex_.size() == lp.numRow_ && right_size; return right_size; }
42.725815
80
0.708194
[ "vector", "model", "3d" ]
9c51888d4f036306c6ea3057814074445f116610
335,734
cc
C++
EnergyPlus/HeatRecovery.cc
yurigabrich/EnergyPlusShadow
396ca83aa82b842e6b177ba35c91b3f481dfbbf9
[ "BSD-3-Clause" ]
null
null
null
EnergyPlus/HeatRecovery.cc
yurigabrich/EnergyPlusShadow
396ca83aa82b842e6b177ba35c91b3f481dfbbf9
[ "BSD-3-Clause" ]
1
2020-07-08T13:32:09.000Z
2020-07-08T13:32:09.000Z
EnergyPlus/HeatRecovery.cc
yurigabrich/EnergyPlusShadow
396ca83aa82b842e6b177ba35c91b3f481dfbbf9
[ "BSD-3-Clause" ]
null
null
null
// EnergyPlus, Copyright (c) 1996-2018, The Board of Trustees of the University of Illinois, // The Regents of the University of California, through Lawrence Berkeley National Laboratory // (subject to receipt of any required approvals from the U.S. Dept. of Energy), Oak Ridge // National Laboratory, managed by UT-Battelle, Alliance for Sustainable Energy, LLC, and other // contributors. All rights reserved. // // NOTICE: This Software was developed under funding from the U.S. Department of Energy and the // U.S. Government consequently retains certain rights. As such, the U.S. Government has been // granted for itself and others acting on its behalf a paid-up, nonexclusive, irrevocable, // worldwide license in the Software to reproduce, distribute copies to the public, prepare // derivative works, and perform publicly and display publicly, and to permit others to do so. // // Redistribution and use in source and binary forms, with or without modification, are permitted // provided that the following conditions are met: // // (1) Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // // (2) Redistributions in binary form must reproduce the above copyright notice, this list of // conditions and the following disclaimer in the documentation and/or other materials // provided with the distribution. // // (3) Neither the name of the University of California, Lawrence Berkeley National Laboratory, // the University of Illinois, U.S. Dept. of Energy nor the names of its contributors may be // used to endorse or promote products derived from this software without specific prior // written permission. // // (4) Use of EnergyPlus(TM) Name. If Licensee (i) distributes the software in stand-alone form // without changes from the version obtained under this License, or (ii) Licensee makes a // reference solely to the software portion of its product, Licensee must refer to the // software as "EnergyPlus version X" software, where "X" is the version number Licensee // obtained under this License and may not use a different name for the software. Except as // specifically required in this Section (4), Licensee shall not use in a company name, a // product name, in advertising, publicity, or other promotional activities any name, trade // name, trademark, logo, or other designation of "EnergyPlus", "E+", "e+" or confusingly // similar designation, without the U.S. Department of Energy's prior written consent. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY // AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // C++ Headers #include <cmath> // ObjexxFCL Headers #include <ObjexxFCL/Fmath.hh> // EnergyPlus Headers #include <BranchNodeConnections.hh> #include <DXCoils.hh> #include <DataContaminantBalance.hh> #include <DataEnvironment.hh> #include <DataHVACGlobals.hh> #include <DataIPShortCuts.hh> #include <DataLoopNode.hh> #include <DataPrecisionGlobals.hh> #include <DataSizing.hh> #include <EMSManager.hh> #include <General.hh> #include <GeneralRoutines.hh> #include <GlobalNames.hh> #include <HeatRecovery.hh> #include <InputProcessing/InputProcessor.hh> #include <NodeInputManager.hh> #include <OutputProcessor.hh> #include <Psychrometrics.hh> #include <ReportSizingManager.hh> #include <ScheduleManager.hh> #include <UtilityRoutines.hh> #include <VariableSpeedCoils.hh> namespace EnergyPlus { namespace HeatRecovery { // Module containing the routines dealing with heat recovery from exhaust or relief air // MODULE INFORMATION: // AUTHOR Michael Wetter // DATE WRITTEN March 1999 // MODIFIED F Buhl Nov 2000, D Shirey Feb 2003, R. Raustad April 2003 // RE-ENGINEERED na // PURPOSE OF THIS MODULE: // To encapsulate the data and routines required to model heat // recovery components in the EnergyPlus HVAC simulation // METHODOLOGY EMPLOYED: // Heat exchanger effectiveness - NTU models are used. // REFERENCES: // M. Wetter, Simulation Model Air-to-Air Plate Heat Exchanger,LBNL Report 42354, 1999. // ARI Standard 1060-2001,Rating Air-to-Air Heat Exchangers for Energy Recovery Ventilation Equipment, www.ari.org // ASHRAE Standard 84, Method of Testing Air-To-Air Heat Exchangers, www.ashrae.org // U.S. Environmental Protection Agency software "SAVES" - // School Advanced Ventilation Engineering Software http://www.epa.gov/iaq/schooldesign/saves.html // OTHER NOTES: none // USE STATEMENTS: // Use statements for data only modules // Using/Aliasing using namespace DataPrecisionGlobals; using namespace DataHVACGlobals; using DataGlobals::BeginEnvrnFlag; using DataGlobals::DisplayExtraWarnings; using DataGlobals::ScheduleAlwaysOn; using DataGlobals::SecInHour; using DataGlobals::SysSizingCalc; using DataGlobals::WarmupFlag; using namespace DataLoopNode; using DataEnvironment::CurMnDy; using DataEnvironment::EnvironmentName; using DataEnvironment::OutBaroPress; using DataEnvironment::StdBaroPress; using DataEnvironment::StdRhoAir; // Use statements for access to subroutines in other modules using namespace ScheduleManager; using General::RoundSigDigits; using General::SolveRoot; using namespace Psychrometrics; // Data // MODULE PARAMETER DEFINITIONS: Real64 const KELVZERO(273.16); Real64 const SMALL(1.e-10); // Heat exchanger performance data type int const BALANCEDHX_PERFDATATYPE1(1); // Heat exchanger configurations int const Counter_Flow(1); int const Parallel_Flow(2); int const Cross_Flow_Both_Unmixed(3); int const Cross_Flow_Other(4); // Heat exchanger configuration types int const Plate(1); int const Rotary(2); // Economizer lockout operation int const EconoLockOut_No(0); int const EconoLockOut_Yes(1); static std::string const BlankString; namespace { bool MyOneTimeAllocate(true); } // DERIVED TYPE DEFINITIONS: // MODULE VARIABLE DECLARATIONS: int NumHeatExchangers(0); // number of heat exchangers int NumAirToAirPlateExchs(0); // number of air to air plate heat exchangers int NumAirToAirGenericExchs(0); // number of air to air generic heat exchangers int NumDesiccantBalancedExchs(0); // number of desiccant balanced heat exchangers int NumDesBalExchsPerfDataType1(0); // number of desiccant balanced heat exchanger performance data maps Real64 FullLoadOutAirTemp(0.0); // Used with desiccant HX empirical model, water coils use inlet node condition // DX coils use DXCoilFullLoadOutAirTemp when coil is ON otherwise inlet node Real64 FullLoadOutAirHumRat(0.0); // Used with desiccant HX empirical model, water coils use inlet node condition // DX coils use DXCoilFullLoadOutAirHumRat when coil is ON otherwise inlet node bool GetInputFlag(true); // First time, input is "gotten" bool CalledFromParentObject(true); // Indicates that HX is called from parent object (this object is not on a branch) Array1D_bool CheckEquipName; // SUBROUTINE SPECIFICATIONS FOR MODULE: // Driver/Manager Routines // Get Input routines for module // Initialization routines for module // Sizing routine for the module // Update routines to check convergence and update nodes // Common routines // External function calls // Object Data Array1D<HeatExchCond> ExchCond; std::unordered_map<std::string, std::string> HeatExchangerUniqueNames; Array1D<BalancedDesDehumPerfData> BalDesDehumPerfData; Array1D<HeatExchCondNumericFieldData> HeatExchCondNumericFields; Array1D<HeatExchCondNumericFieldData> BalDesDehumPerfNumericFields; // Functions void clear_state() { NumHeatExchangers = 0; NumAirToAirPlateExchs = 0; NumAirToAirGenericExchs = 0; NumDesiccantBalancedExchs = 0; NumDesBalExchsPerfDataType1 = 0; FullLoadOutAirTemp = 0.0; FullLoadOutAirHumRat = 0.0; GetInputFlag = true; CalledFromParentObject = true; CheckEquipName.deallocate(); ExchCond.deallocate(); BalDesDehumPerfData.deallocate(); MyOneTimeAllocate = true; HeatExchCondNumericFields.deallocate(); BalDesDehumPerfNumericFields.deallocate(); HeatExchangerUniqueNames.clear(); } void SimHeatRecovery(std::string const &CompName, // name of the heat exchanger unit bool const FirstHVACIteration, // TRUE if 1st HVAC simulation of system timestep int &CompIndex, // Pointer to Component int const FanOpMode, // Supply air fan operating mode Optional<Real64 const> HXPartLoadRatio, // Part load ratio requested of DX compressor Optional_bool_const HXUnitEnable, // Flag to operate heat exchanger Optional_int_const CompanionCoilIndex, // index of companion cooling coil Optional_bool_const RegenInletIsOANode, // flag to determine if supply inlet is OA node, if so air flow cycles Optional_bool_const EconomizerFlag, // economizer operation flag passed by airloop or OA sys Optional_bool_const HighHumCtrlFlag, // high humidity control flag passed by airloop or OA sys Optional_int_const CompanionCoilType_Num // cooling coil type of coil ) { // SUBROUTINE INFORMATION: // AUTHOR Michael Wetter // DATE WRITTEN March 1999 // MODIFIED Fred Buhl November 2000, R. Raustad FSEC - Feb 2009 // RE-ENGINEERED na // PURPOSE OF THIS SUBROUTINE: // Manage the simulation of a heat recovery unit // Using/Aliasing using General::TrimSigDigits; // SUBROUTINE LOCAL VARIABLE DECLARATIONS: int HeatExchNum; // index of unit being simulated bool HXUnitOn; // flag to enable heat exchanger // unused0509 INTEGER :: FanModeOperation ! supply air fan operating mode Real64 PartLoadRatio; // Part load ratio requested of DX compressor bool RegInIsOANode; // local variable to set RegenInletIsOANode optional argument int CompanionCoilNum; // Index to companion cooling coil if (GetInputFlag) { GetHeatRecoveryInput(); GetInputFlag = false; } // Find the correct unit index if (CompIndex == 0) { HeatExchNum = UtilityRoutines::FindItemInList(CompName, ExchCond); if (HeatExchNum == 0) { ShowFatalError("SimHeatRecovery: Unit not found=" + CompName); } CompIndex = HeatExchNum; } else { HeatExchNum = CompIndex; if (HeatExchNum > NumHeatExchangers || HeatExchNum < 1) { ShowFatalError("SimHeatRecovery: Invalid CompIndex passed=" + TrimSigDigits(HeatExchNum) + ", Number of Units=" + TrimSigDigits(NumHeatExchangers) + ", Entered Unit name=" + CompName); } if (CheckEquipName(HeatExchNum)) { if (CompName != ExchCond(HeatExchNum).Name) { ShowFatalError("SimHeatRecovery: Invalid CompIndex passed=" + TrimSigDigits(HeatExchNum) + ", Unit name=" + CompName + ", stored Unit Name for that index=" + ExchCond(HeatExchNum).Name); } CheckEquipName(HeatExchNum) = false; } } if (present(CompanionCoilIndex)) { CompanionCoilNum = CompanionCoilIndex; } else { CompanionCoilNum = 0; } int companionCoilType(0); if (present(CompanionCoilType_Num)) { companionCoilType = CompanionCoilType_Num; } else { companionCoilType = 0; } if (present(HXUnitEnable)) { HXUnitOn = HXUnitEnable; // When CalledFromParentObject is TRUE, this SIM routine was called by a parent object that passed in HXUnitEnable. // HX will use the DX coil part-load ratio (optional CompanionCoilIndex must be present) or PLR passed in if // not used with DX coil (optional CompanionCoilIndex must not be present). CalledFromParentObject = true; } else { // HX is placed on a BRANCH, optional arguments are not passed in from SimAirServingZones. // HX will calculate its own part-load ratio if optional HXUnitEnable flag is not present HXUnitOn = true; CalledFromParentObject = false; } InitHeatRecovery(HeatExchNum, CompanionCoilNum, companionCoilType); // call the correct heat exchanger calculation routine { auto const SELECT_CASE_var(ExchCond(HeatExchNum).ExchTypeNum); if (SELECT_CASE_var == HX_AIRTOAIR_FLATPLATE) { CalcAirToAirPlateHeatExch(HeatExchNum, HXUnitOn, EconomizerFlag, HighHumCtrlFlag); } else if (SELECT_CASE_var == HX_AIRTOAIR_GENERIC) { CalcAirToAirGenericHeatExch(HeatExchNum, HXUnitOn, FirstHVACIteration, FanOpMode, EconomizerFlag, HighHumCtrlFlag, HXPartLoadRatio); } else if (SELECT_CASE_var == HX_DESICCANT_BALANCED) { if (present(HXPartLoadRatio)) { PartLoadRatio = HXPartLoadRatio; } else { PartLoadRatio = 1.0; } if (present(RegenInletIsOANode)) { RegInIsOANode = RegenInletIsOANode; } else { RegInIsOANode = false; } CalcDesiccantBalancedHeatExch(HeatExchNum, HXUnitOn, FirstHVACIteration, FanOpMode, PartLoadRatio, CompanionCoilNum, RegInIsOANode, EconomizerFlag, HighHumCtrlFlag); } } UpdateHeatRecovery(HeatExchNum); ReportHeatRecovery(HeatExchNum); } void GetHeatRecoveryInput() { // SUBROUTINE INFORMATION: // AUTHOR Michael Wetter // DATE WRITTEN March 1999 // MODIFIED F Buhl Nov 2000, D Shirey Feb 2003, R. Raustad FSEC - Feb 2009 (EconoLockout inputs) // RE-ENGINEERED na // PURPOSE OF THIS SUBROUTINE: // Obtains input data for heat recovery units and stores it in // appropriate data structures. // METHODOLOGY EMPLOYED: // Uses InputProcessor "Get" routines to obtain data. // Using/Aliasing using BranchNodeConnections::TestCompSet; using NodeInputManager::GetOnlySingleNode; using namespace DataIPShortCuts; // SUBROUTINE LOCAL VARIABLE DECLARATIONS: int ExchIndex; // loop index int ExchNum; // current heat exchanger number int PerfDataIndex; // desiccant balance heat exchanger performance data loop index int PerfDataNum; // current desiccant balanced heat exchanger performance data set number int NumAlphas; // Number of Alphas for each GetObjectItem call int NumNumbers; // Number of Numbers for each GetObjectItem call int IOStatus; // Used in GetObjectItem static bool ErrorsFound(false); // Set to true if errors in input, fatal at end of routine static std::string HeatExchPerfType; // Desiccant balanced heat exchanger performance data type static std::string const RoutineName("GetHeatRecoveryInput: "); // include trailing blank space NumAirToAirPlateExchs = inputProcessor->getNumObjectsFound("HeatExchanger:AirToAir:FlatPlate"); NumAirToAirGenericExchs = inputProcessor->getNumObjectsFound("HeatExchanger:AirToAir:SensibleAndLatent"); NumDesiccantBalancedExchs = inputProcessor->getNumObjectsFound("HeatExchanger:Desiccant:BalancedFlow"); NumDesBalExchsPerfDataType1 = inputProcessor->getNumObjectsFound("HeatExchanger:Desiccant:BalancedFlow:PerformanceDataType1"); NumHeatExchangers = NumAirToAirPlateExchs + NumAirToAirGenericExchs + NumDesiccantBalancedExchs; // allocate the data array ExchCond.allocate(NumHeatExchangers); HeatExchangerUniqueNames.reserve(NumHeatExchangers); CheckEquipName.dimension(NumHeatExchangers, true); HeatExchCondNumericFields.allocate(NumHeatExchangers); if (NumDesBalExchsPerfDataType1 > 0) { BalDesDehumPerfData.allocate(NumDesBalExchsPerfDataType1); BalDesDehumPerfNumericFields.allocate(NumDesBalExchsPerfDataType1); } // loop over the air to air plate heat exchangers and load their input data for (ExchIndex = 1; ExchIndex <= NumAirToAirPlateExchs; ++ExchIndex) { cCurrentModuleObject = "HeatExchanger:AirToAir:FlatPlate"; inputProcessor->getObjectItem(cCurrentModuleObject, ExchIndex, cAlphaArgs, NumAlphas, rNumericArgs, NumNumbers, IOStatus, lNumericFieldBlanks, lAlphaFieldBlanks, cAlphaFieldNames, cNumericFieldNames); ExchNum = ExchIndex; HeatExchCondNumericFields(ExchNum).NumericFieldNames.allocate(NumNumbers); HeatExchCondNumericFields(ExchNum).NumericFieldNames = ""; HeatExchCondNumericFields(ExchNum).NumericFieldNames = cNumericFieldNames; GlobalNames::VerifyUniqueInterObjectName(HeatExchangerUniqueNames, cAlphaArgs(1), cCurrentModuleObject, cAlphaFieldNames(1), ErrorsFound); ExchCond(ExchNum).Name = cAlphaArgs(1); ExchCond(ExchNum).ExchTypeNum = HX_AIRTOAIR_FLATPLATE; if (lAlphaFieldBlanks(2)) { ExchCond(ExchNum).SchedPtr = ScheduleAlwaysOn; } else { ExchCond(ExchNum).SchedPtr = GetScheduleIndex(cAlphaArgs(2)); if (ExchCond(ExchNum).SchedPtr == 0) { ShowSevereError(RoutineName + cCurrentModuleObject + ": invalid " + cAlphaFieldNames(2) + " entered =" + cAlphaArgs(2) + " for " + cAlphaFieldNames(1) + '=' + cAlphaArgs(1)); ErrorsFound = true; } } { auto const SELECT_CASE_var(cAlphaArgs(3)); if (SELECT_CASE_var == "COUNTERFLOW") { ExchCond(ExchNum).FlowArr = Counter_Flow; } else if (SELECT_CASE_var == "PARALLELFLOW") { ExchCond(ExchNum).FlowArr = Parallel_Flow; } else if (SELECT_CASE_var == "CROSSFLOWBOTHUNMIXED") { ExchCond(ExchNum).FlowArr = Cross_Flow_Both_Unmixed; } else { ShowSevereError(cCurrentModuleObject + ": incorrect flow arrangement: " + cAlphaArgs(3)); ErrorsFound = true; } } { auto const SELECT_CASE_var(cAlphaArgs(4)); if (SELECT_CASE_var == "YES") { ExchCond(ExchNum).EconoLockOut = EconoLockOut_Yes; } else if (SELECT_CASE_var == "NO") { ExchCond(ExchNum).EconoLockOut = EconoLockOut_No; } else { if (lAlphaFieldBlanks(4)) { ExchCond(ExchNum).EconoLockOut = EconoLockOut_Yes; } else { ShowSevereError(cCurrentModuleObject + ": incorrect econo lockout: " + cAlphaArgs(4)); ErrorsFound = true; } } } ExchCond(ExchNum).hARatio = rNumericArgs(1); ExchCond(ExchNum).NomSupAirVolFlow = rNumericArgs(2); ExchCond(ExchNum).NomSupAirInTemp = rNumericArgs(3); ExchCond(ExchNum).NomSupAirOutTemp = rNumericArgs(4); ExchCond(ExchNum).NomSecAirVolFlow = rNumericArgs(5); ExchCond(ExchNum).NomSecAirInTemp = rNumericArgs(6); ExchCond(ExchNum).NomElecPower = rNumericArgs(7); ExchCond(ExchNum).SupInletNode = GetOnlySingleNode( cAlphaArgs(5), ErrorsFound, cCurrentModuleObject, cAlphaArgs(1), NodeType_Air, NodeConnectionType_Inlet, 1, ObjectIsNotParent); ExchCond(ExchNum).SupOutletNode = GetOnlySingleNode( cAlphaArgs(6), ErrorsFound, cCurrentModuleObject, cAlphaArgs(1), NodeType_Air, NodeConnectionType_Outlet, 1, ObjectIsNotParent); ExchCond(ExchNum).SecInletNode = GetOnlySingleNode( cAlphaArgs(7), ErrorsFound, cCurrentModuleObject, cAlphaArgs(1), NodeType_Air, NodeConnectionType_Inlet, 2, ObjectIsNotParent); ExchCond(ExchNum).SecOutletNode = GetOnlySingleNode( cAlphaArgs(8), ErrorsFound, cCurrentModuleObject, cAlphaArgs(1), NodeType_Air, NodeConnectionType_Outlet, 2, ObjectIsNotParent); TestCompSet(cHXTypes(ExchCond(ExchNum).ExchTypeNum), ExchCond(ExchNum).Name, cAlphaArgs(5), cAlphaArgs(6), "Process Air Nodes"); } // end of input loop over air to air plate heat exchangers // loop over the air to air generic heat exchangers and load their input data for (ExchIndex = 1; ExchIndex <= NumAirToAirGenericExchs; ++ExchIndex) { cCurrentModuleObject = "HeatExchanger:AirToAir:SensibleAndLatent"; inputProcessor->getObjectItem(cCurrentModuleObject, ExchIndex, cAlphaArgs, NumAlphas, rNumericArgs, NumNumbers, IOStatus, lNumericFieldBlanks, lAlphaFieldBlanks, cAlphaFieldNames, cNumericFieldNames); ExchNum = ExchIndex + NumAirToAirPlateExchs; HeatExchCondNumericFields(ExchNum).NumericFieldNames.allocate(NumNumbers); HeatExchCondNumericFields(ExchNum).NumericFieldNames = ""; HeatExchCondNumericFields(ExchNum).NumericFieldNames = cNumericFieldNames; GlobalNames::VerifyUniqueInterObjectName(HeatExchangerUniqueNames, cAlphaArgs(1), cCurrentModuleObject, cAlphaFieldNames(1), ErrorsFound); ExchCond(ExchNum).Name = cAlphaArgs(1); ExchCond(ExchNum).ExchTypeNum = HX_AIRTOAIR_GENERIC; if (lAlphaFieldBlanks(2)) { ExchCond(ExchNum).SchedPtr = ScheduleAlwaysOn; } else { ExchCond(ExchNum).SchedPtr = GetScheduleIndex(cAlphaArgs(2)); if (ExchCond(ExchNum).SchedPtr == 0) { ShowSevereError(RoutineName + cCurrentModuleObject + ": invalid " + cAlphaFieldNames(2) + " entered =" + cAlphaArgs(2) + " for " + cAlphaFieldNames(1) + '=' + cAlphaArgs(1)); ErrorsFound = true; } } ExchCond(ExchNum).NomSupAirVolFlow = rNumericArgs(1); ExchCond(ExchNum).HeatEffectSensible100 = rNumericArgs(2); ExchCond(ExchNum).HeatEffectLatent100 = rNumericArgs(3); ExchCond(ExchNum).HeatEffectSensible75 = rNumericArgs(4); ExchCond(ExchNum).HeatEffectLatent75 = rNumericArgs(5); if (ExchCond(ExchNum).HeatEffectSensible75 < ExchCond(ExchNum).HeatEffectSensible100) { ShowWarningError(cCurrentModuleObject + " \"" + ExchCond(ExchNum).Name + "\" sensible heating effectiveness at 75% rated flow is less than at 100% rated flow."); ShowContinueError("Sensible heating effectiveness at 75% rated flow is usually greater than at 100% rated flow."); } if (ExchCond(ExchNum).HeatEffectLatent75 < ExchCond(ExchNum).HeatEffectLatent100) { ShowWarningError(cCurrentModuleObject + " \"" + ExchCond(ExchNum).Name + "\" latent heating effectiveness at 75% rated flow is less than at 100% rated flow."); ShowContinueError("Latent heating effectiveness at 75% rated flow is usually greater than at 100% rated flow."); } ExchCond(ExchNum).CoolEffectSensible100 = rNumericArgs(6); ExchCond(ExchNum).CoolEffectLatent100 = rNumericArgs(7); ExchCond(ExchNum).CoolEffectSensible75 = rNumericArgs(8); ExchCond(ExchNum).CoolEffectLatent75 = rNumericArgs(9); if (ExchCond(ExchNum).CoolEffectSensible75 < ExchCond(ExchNum).CoolEffectSensible100) { ShowWarningError(cCurrentModuleObject + " \"" + ExchCond(ExchNum).Name + "\" sensible cooling effectiveness at 75% rated flow is less than at 100% rated flow."); ShowContinueError("Sensible cooling effectiveness at 75% rated flow is usually greater than at 100% rated flow."); } if (ExchCond(ExchNum).CoolEffectLatent75 < ExchCond(ExchNum).CoolEffectLatent100) { ShowWarningError(cCurrentModuleObject + " \"" + ExchCond(ExchNum).Name + "\" latent cooling effectiveness at 75% rated flow is less than at 100% rated flow."); ShowContinueError("Latent cooling effectiveness at 75% rated flow is usually greater than at 100% rated flow."); } ExchCond(ExchNum).SupInletNode = GetOnlySingleNode( cAlphaArgs(3), ErrorsFound, cCurrentModuleObject, cAlphaArgs(1), NodeType_Air, NodeConnectionType_Inlet, 1, ObjectIsNotParent); ExchCond(ExchNum).SupOutletNode = GetOnlySingleNode( cAlphaArgs(4), ErrorsFound, cCurrentModuleObject, cAlphaArgs(1), NodeType_Air, NodeConnectionType_Outlet, 1, ObjectIsNotParent); ExchCond(ExchNum).SecInletNode = GetOnlySingleNode( cAlphaArgs(5), ErrorsFound, cCurrentModuleObject, cAlphaArgs(1), NodeType_Air, NodeConnectionType_Inlet, 2, ObjectIsNotParent); ExchCond(ExchNum).SecOutletNode = GetOnlySingleNode( cAlphaArgs(6), ErrorsFound, cCurrentModuleObject, cAlphaArgs(1), NodeType_Air, NodeConnectionType_Outlet, 2, ObjectIsNotParent); ExchCond(ExchNum).NomElecPower = rNumericArgs(10); if (UtilityRoutines::SameString(cAlphaArgs(7), "Yes")) { ExchCond(ExchNum).ControlToTemperatureSetPoint = true; } else { if (!UtilityRoutines::SameString(cAlphaArgs(7), "No")) { ShowSevereError("Rotary HX Speed Modulation or Plate Bypass for Temperature Control for "); ShowContinueError(ExchCond(ExchNum).Name + " must be set to Yes or No"); ErrorsFound = true; } } if (UtilityRoutines::SameString(cAlphaArgs(8), "Plate")) { ExchCond(ExchNum).ExchConfigNum = Plate; } else if (UtilityRoutines::SameString(cAlphaArgs(8), "Rotary")) { ExchCond(ExchNum).ExchConfigNum = Rotary; } else { ShowSevereError(cCurrentModuleObject + " configuration not found= " + cAlphaArgs(8)); ShowContinueError("HX configuration must be either Plate or Rotary"); ErrorsFound = true; } // Added additional inputs for frost control ExchCond(ExchNum).FrostControlType = cAlphaArgs(9); if (!UtilityRoutines::SameString(ExchCond(ExchNum).FrostControlType, "None")) { if (!UtilityRoutines::SameString(ExchCond(ExchNum).FrostControlType, "ExhaustOnly")) { if (!UtilityRoutines::SameString(ExchCond(ExchNum).FrostControlType, "ExhaustAirRecirculation")) { if (!UtilityRoutines::SameString(ExchCond(ExchNum).FrostControlType, "MinimumExhaustTemperature")) { ShowSevereError("Invalid Frost Control method for " + ExchCond(ExchNum).Name + " = " + cAlphaArgs(9)); ErrorsFound = true; } } } } if (!UtilityRoutines::SameString(cAlphaArgs(9), "None")) { ExchCond(ExchNum).ThresholdTemperature = rNumericArgs(11); ExchCond(ExchNum).InitialDefrostTime = rNumericArgs(12); ExchCond(ExchNum).RateofDefrostTimeIncrease = rNumericArgs(13); } { auto const SELECT_CASE_var(cAlphaArgs(10)); if (SELECT_CASE_var == "YES") { ExchCond(ExchNum).EconoLockOut = EconoLockOut_Yes; } else if (SELECT_CASE_var == "NO") { ExchCond(ExchNum).EconoLockOut = EconoLockOut_No; } else { if (lAlphaFieldBlanks(10)) { ExchCond(ExchNum).EconoLockOut = EconoLockOut_Yes; } else { ShowSevereError(cCurrentModuleObject + ": incorrect econo lockout: " + cAlphaArgs(10)); ErrorsFound = true; } } } TestCompSet(cHXTypes(ExchCond(ExchNum).ExchTypeNum), ExchCond(ExchNum).Name, cAlphaArgs(3), cAlphaArgs(4), "Process Air Nodes"); } // end of input loop over air to air generic heat exchangers // loop over the desiccant balanced heat exchangers and load their input data for (ExchIndex = 1; ExchIndex <= NumDesiccantBalancedExchs; ++ExchIndex) { cCurrentModuleObject = "HeatExchanger:Desiccant:BalancedFlow"; inputProcessor->getObjectItem(cCurrentModuleObject, ExchIndex, cAlphaArgs, NumAlphas, rNumericArgs, NumNumbers, IOStatus, lNumericFieldBlanks, lAlphaFieldBlanks, cAlphaFieldNames, cNumericFieldNames); ExchNum = ExchIndex + NumAirToAirPlateExchs + NumAirToAirGenericExchs; HeatExchCondNumericFields(ExchNum).NumericFieldNames.allocate(NumNumbers); HeatExchCondNumericFields(ExchNum).NumericFieldNames = ""; HeatExchCondNumericFields(ExchNum).NumericFieldNames = cNumericFieldNames; GlobalNames::VerifyUniqueInterObjectName(HeatExchangerUniqueNames, cAlphaArgs(1), cCurrentModuleObject, cAlphaFieldNames(1), ErrorsFound); ExchCond(ExchNum).Name = cAlphaArgs(1); ExchCond(ExchNum).ExchTypeNum = HX_DESICCANT_BALANCED; if (lAlphaFieldBlanks(2)) { ExchCond(ExchNum).SchedPtr = ScheduleAlwaysOn; } else { ExchCond(ExchNum).SchedPtr = GetScheduleIndex(cAlphaArgs(2)); if (ExchCond(ExchNum).SchedPtr == 0) { ShowSevereError(RoutineName + cCurrentModuleObject + ": invalid " + cAlphaFieldNames(2) + " entered =" + cAlphaArgs(2) + " for " + cAlphaFieldNames(1) + '=' + cAlphaArgs(1)); ErrorsFound = true; } } // desiccant HX's usually refer to process and regeneration air streams // In this module, Sup = Regeneration nodes and Sec = Process nodes // regeneration air inlet and outlet nodes ExchCond(ExchNum).SupInletNode = GetOnlySingleNode( cAlphaArgs(3), ErrorsFound, cCurrentModuleObject, cAlphaArgs(1), NodeType_Air, NodeConnectionType_Inlet, 1, ObjectIsNotParent); ExchCond(ExchNum).SupOutletNode = GetOnlySingleNode( cAlphaArgs(4), ErrorsFound, cCurrentModuleObject, cAlphaArgs(1), NodeType_Air, NodeConnectionType_Outlet, 1, ObjectIsNotParent); // process air inlet and outlet nodes ExchCond(ExchNum).SecInletNode = GetOnlySingleNode( cAlphaArgs(5), ErrorsFound, cCurrentModuleObject, cAlphaArgs(1), NodeType_Air, NodeConnectionType_Inlet, 2, ObjectIsNotParent); ExchCond(ExchNum).SecOutletNode = GetOnlySingleNode( cAlphaArgs(6), ErrorsFound, cCurrentModuleObject, cAlphaArgs(1), NodeType_Air, NodeConnectionType_Outlet, 2, ObjectIsNotParent); // Set up the component set for the process side of the HX (Sec = Process) TestCompSet(cHXTypes(ExchCond(ExchNum).ExchTypeNum), ExchCond(ExchNum).Name, NodeID(ExchCond(ExchNum).SecInletNode), NodeID(ExchCond(ExchNum).SecOutletNode), "Process Air Nodes"); HeatExchPerfType = cAlphaArgs(7); if (UtilityRoutines::SameString(HeatExchPerfType, "HeatExchanger:Desiccant:BalancedFlow:PerformanceDataType1")) { ExchCond(ExchNum).HeatExchPerfTypeNum = BALANCEDHX_PERFDATATYPE1; } else { ShowSevereError(cCurrentModuleObject + " \"" + ExchCond(ExchNum).Name + "\""); ShowContinueError("Invalid performance data type selected."); ShowContinueError("...performance data type selected = " + HeatExchPerfType); ErrorsFound = true; } ExchCond(ExchNum).HeatExchPerfName = cAlphaArgs(8); { auto const SELECT_CASE_var(cAlphaArgs(9)); if (SELECT_CASE_var == "YES") { ExchCond(ExchNum).EconoLockOut = EconoLockOut_Yes; } else if (SELECT_CASE_var == "NO") { ExchCond(ExchNum).EconoLockOut = EconoLockOut_No; } else { if (lAlphaFieldBlanks(9)) { ExchCond(ExchNum).EconoLockOut = EconoLockOut_No; } else { ShowSevereError(cCurrentModuleObject + ": incorrect econo lockout: " + cAlphaArgs(9)); ErrorsFound = true; } } } } // end of input loop over desiccant balanced heat exchangers // get performance data set for balanced desiccant heat exchanger for (PerfDataIndex = 1; PerfDataIndex <= NumDesBalExchsPerfDataType1; ++PerfDataIndex) { cCurrentModuleObject = "HeatExchanger:Desiccant:BalancedFlow:PerformanceDataType1"; inputProcessor->getObjectItem(cCurrentModuleObject, PerfDataIndex, cAlphaArgs, NumAlphas, rNumericArgs, NumNumbers, IOStatus, lNumericFieldBlanks, lAlphaFieldBlanks, cAlphaFieldNames, cNumericFieldNames); PerfDataNum = PerfDataIndex; BalDesDehumPerfNumericFields(PerfDataNum).NumericFieldNames.allocate(NumNumbers); BalDesDehumPerfNumericFields(PerfDataNum).NumericFieldNames = ""; BalDesDehumPerfNumericFields(PerfDataNum).NumericFieldNames = cNumericFieldNames; UtilityRoutines::IsNameEmpty(cAlphaArgs(1), cCurrentModuleObject, ErrorsFound); BalDesDehumPerfData(PerfDataNum).Name = cAlphaArgs(1); BalDesDehumPerfData(PerfDataNum).PerfType = cCurrentModuleObject; BalDesDehumPerfData(PerfDataNum).NomSupAirVolFlow = rNumericArgs(1); // check validity if (BalDesDehumPerfData(PerfDataNum).NomSupAirVolFlow <= 0.0 && BalDesDehumPerfData(PerfDataNum).NomSupAirVolFlow != DataSizing::AutoSize) { ShowSevereError(cCurrentModuleObject + " \"" + BalDesDehumPerfData(PerfDataNum).Name + "\""); ShowContinueError("Nominal air flow rate must be greater than zero."); ShowContinueError("... value entered = " + RoundSigDigits(BalDesDehumPerfData(PerfDataNum).NomSupAirVolFlow, 6)); ErrorsFound = true; } BalDesDehumPerfData(PerfDataNum).NomProcAirFaceVel = rNumericArgs(2); // check validity if ((BalDesDehumPerfData(PerfDataNum).NomProcAirFaceVel <= 0.0 && BalDesDehumPerfData(PerfDataNum).NomProcAirFaceVel != DataSizing::AutoSize) || BalDesDehumPerfData(PerfDataNum).NomProcAirFaceVel > 6.0) { ShowSevereError(cCurrentModuleObject + " \"" + BalDesDehumPerfData(PerfDataNum).Name + "\""); ShowContinueError("Nominal air face velocity cannot be less than or equal to zero or greater than 6 m/s."); ShowContinueError("... value entered = " + RoundSigDigits(BalDesDehumPerfData(PerfDataNum).NomProcAirFaceVel, 6)); ErrorsFound = true; } BalDesDehumPerfData(PerfDataNum).NomElecPower = rNumericArgs(3); // check validity if (BalDesDehumPerfData(PerfDataNum).NomElecPower < 0.0) { ShowSevereError(cCurrentModuleObject + " \"" + BalDesDehumPerfData(PerfDataNum).Name + "\""); ShowContinueError("Nominal electric power cannot be less than zero."); ShowContinueError("... value entered = " + RoundSigDigits(BalDesDehumPerfData(PerfDataNum).NomElecPower, 6)); ErrorsFound = true; } // regen outlet temp variables BalDesDehumPerfData(PerfDataNum).B1 = rNumericArgs(4); BalDesDehumPerfData(PerfDataNum).B2 = rNumericArgs(5); BalDesDehumPerfData(PerfDataNum).B3 = rNumericArgs(6); BalDesDehumPerfData(PerfDataNum).B4 = rNumericArgs(7); BalDesDehumPerfData(PerfDataNum).B5 = rNumericArgs(8); BalDesDehumPerfData(PerfDataNum).B6 = rNumericArgs(9); BalDesDehumPerfData(PerfDataNum).B7 = rNumericArgs(10); BalDesDehumPerfData(PerfDataNum).B8 = rNumericArgs(11); // Check that the minimum is not greater than or equal to the maximum for each of the following model boundaries BalDesDehumPerfData(PerfDataNum).T_MinRegenAirInHumRat = rNumericArgs(12); BalDesDehumPerfData(PerfDataNum).T_MaxRegenAirInHumRat = rNumericArgs(13); if (BalDesDehumPerfData(PerfDataNum).T_MinRegenAirInHumRat >= BalDesDehumPerfData(PerfDataNum).T_MaxRegenAirInHumRat) { ShowSevereError(cCurrentModuleObject + " \"" + BalDesDehumPerfData(PerfDataNum).Name + "\""); ShowContinueError("Error found in min/max boundary for the regen outlet air temperature equation."); ShowContinueError("... the minimum value of regeneration inlet air humidity ratio must be less than the maximum."); ShowContinueError("... minimum value entered by user = " + RoundSigDigits(BalDesDehumPerfData(PerfDataNum).T_MinRegenAirInHumRat, 6)); ShowContinueError("... maximum value entered by user = " + RoundSigDigits(BalDesDehumPerfData(PerfDataNum).T_MaxRegenAirInHumRat, 6)); ErrorsFound = true; } if (BalDesDehumPerfData(PerfDataNum).T_MinRegenAirInHumRat < 0.0) { ShowSevereError(cCurrentModuleObject + " \"" + BalDesDehumPerfData(PerfDataNum).Name + "\""); ShowContinueError("Error found in min boundary for the regen outlet air temperature equation."); ShowContinueError("... the minimum value of regeneration inlet air humidity ratio must be greater than or equal to 0."); ShowContinueError("... minimum value entered by user = " + RoundSigDigits(BalDesDehumPerfData(PerfDataNum).T_MinRegenAirInHumRat, 6)); ErrorsFound = true; } if (BalDesDehumPerfData(PerfDataNum).T_MaxRegenAirInHumRat > 1.0) { ShowSevereError(cCurrentModuleObject + " \"" + BalDesDehumPerfData(PerfDataNum).Name + "\""); ShowContinueError("Error found in max boundary for the regen outlet air temperature equation."); ShowContinueError("... the maximum value of regeneration inlet air humidity ratio must be less than or equal to 1."); ShowContinueError("... maximum value entered by user = " + RoundSigDigits(BalDesDehumPerfData(PerfDataNum).T_MaxRegenAirInHumRat, 6)); ErrorsFound = true; } BalDesDehumPerfData(PerfDataNum).T_MinRegenAirInTemp = rNumericArgs(14); BalDesDehumPerfData(PerfDataNum).T_MaxRegenAirInTemp = rNumericArgs(15); if (BalDesDehumPerfData(PerfDataNum).T_MinRegenAirInTemp >= BalDesDehumPerfData(PerfDataNum).T_MaxRegenAirInTemp) { ShowSevereError(cCurrentModuleObject + " \"" + BalDesDehumPerfData(PerfDataNum).Name + "\""); ShowContinueError("Error found in min/max boundary for the regen outlet air temperature equation."); ShowContinueError("... the minimum value of regeneration inlet air temperature must be less than the maximum."); ShowContinueError("... minimum value entered = " + RoundSigDigits(BalDesDehumPerfData(PerfDataNum).T_MinRegenAirInTemp, 6)); ShowContinueError("... maximum value entered = " + RoundSigDigits(BalDesDehumPerfData(PerfDataNum).T_MaxRegenAirInTemp, 6)); ErrorsFound = true; } BalDesDehumPerfData(PerfDataNum).T_MinProcAirInHumRat = rNumericArgs(16); BalDesDehumPerfData(PerfDataNum).T_MaxProcAirInHumRat = rNumericArgs(17); if (BalDesDehumPerfData(PerfDataNum).T_MinProcAirInHumRat >= BalDesDehumPerfData(PerfDataNum).T_MaxProcAirInHumRat) { ShowSevereError(cCurrentModuleObject + " \"" + BalDesDehumPerfData(PerfDataNum).Name + "\""); ShowContinueError("Error found in min/max boundary for the regen outlet air temperature equation."); ShowContinueError("... the minimum value of process inlet air humidity ratio must be less than the maximum."); ShowContinueError("... minimum value entered by user = " + RoundSigDigits(BalDesDehumPerfData(PerfDataNum).T_MinProcAirInHumRat, 6)); ShowContinueError("... maximum value entered by user = " + RoundSigDigits(BalDesDehumPerfData(PerfDataNum).T_MaxProcAirInHumRat, 6)); ErrorsFound = true; } if (BalDesDehumPerfData(PerfDataNum).T_MinProcAirInHumRat < 0.0) { ShowSevereError(cCurrentModuleObject + " \"" + BalDesDehumPerfData(PerfDataNum).Name + "\""); ShowContinueError("Error found in min boundary for the regen outlet air temperature equation."); ShowContinueError("... the minimum value of process inlet air humidity ratio must be greater than or equal to 0."); ShowContinueError("... minimum value entered by user = " + RoundSigDigits(BalDesDehumPerfData(PerfDataNum).T_MinProcAirInHumRat, 6)); ErrorsFound = true; } if (BalDesDehumPerfData(PerfDataNum).T_MaxProcAirInHumRat > 1.0) { ShowSevereError(cCurrentModuleObject + " \"" + BalDesDehumPerfData(PerfDataNum).Name + "\""); ShowContinueError("Error found in max boundary for the regen outlet air temperature equation."); ShowContinueError("... the maximum value of process inlet air humidity ratio must be less than or equal to 1."); ShowContinueError("... maximum value entered by user = " + RoundSigDigits(BalDesDehumPerfData(PerfDataNum).T_MaxProcAirInHumRat, 6)); ErrorsFound = true; } BalDesDehumPerfData(PerfDataNum).T_MinProcAirInTemp = rNumericArgs(18); BalDesDehumPerfData(PerfDataNum).T_MaxProcAirInTemp = rNumericArgs(19); if (BalDesDehumPerfData(PerfDataNum).T_MinProcAirInTemp >= BalDesDehumPerfData(PerfDataNum).T_MaxProcAirInTemp) { ShowSevereError(cCurrentModuleObject + " \"" + BalDesDehumPerfData(PerfDataNum).Name + "\""); ShowContinueError("Error found in min/max boundary for the regen outlet air temperature equation."); ShowContinueError("... the minimum value of process inlet air temperature must be less than the maximum."); ShowContinueError("... minimum value entered = " + RoundSigDigits(BalDesDehumPerfData(PerfDataNum).T_MinProcAirInTemp, 6)); ShowContinueError("... maximum value entered = " + RoundSigDigits(BalDesDehumPerfData(PerfDataNum).T_MaxProcAirInTemp, 6)); ErrorsFound = true; } BalDesDehumPerfData(PerfDataNum).T_MinFaceVel = rNumericArgs(20); BalDesDehumPerfData(PerfDataNum).T_MaxFaceVel = rNumericArgs(21); if (BalDesDehumPerfData(PerfDataNum).T_MinFaceVel >= BalDesDehumPerfData(PerfDataNum).T_MaxFaceVel) { ShowSevereError(cCurrentModuleObject + " \"" + BalDesDehumPerfData(PerfDataNum).Name + "\""); ShowContinueError("Error found in min/max boundary for the regen outlet air temperature equation."); ShowContinueError("... the minimum value of regen air velocity must be less than the maximum."); ShowContinueError("... minimum value entered = " + RoundSigDigits(BalDesDehumPerfData(PerfDataNum).T_MinFaceVel, 6)); ShowContinueError("... maximum value entered = " + RoundSigDigits(BalDesDehumPerfData(PerfDataNum).T_MaxFaceVel, 6)); ErrorsFound = true; } BalDesDehumPerfData(PerfDataNum).MinRegenAirOutTemp = rNumericArgs(22); BalDesDehumPerfData(PerfDataNum).MaxRegenAirOutTemp = rNumericArgs(23); if (BalDesDehumPerfData(PerfDataNum).MinRegenAirOutTemp >= BalDesDehumPerfData(PerfDataNum).MaxRegenAirOutTemp) { ShowSevereError(cCurrentModuleObject + " \"" + BalDesDehumPerfData(PerfDataNum).Name + "\""); ShowContinueError("Error found in min/max boundary for the regen outlet air temperature equation."); ShowContinueError("... the minimum value of regen outlet air temperature must be less than the maximum."); ShowContinueError("... minimum value entered = " + RoundSigDigits(BalDesDehumPerfData(PerfDataNum).MinRegenAirOutTemp, 6)); ShowContinueError("... maximum value entered = " + RoundSigDigits(BalDesDehumPerfData(PerfDataNum).MaxRegenAirOutTemp, 6)); ErrorsFound = true; } BalDesDehumPerfData(PerfDataNum).T_MinRegenAirInRelHum = rNumericArgs(24) / 100.0; BalDesDehumPerfData(PerfDataNum).T_MaxRegenAirInRelHum = rNumericArgs(25) / 100.0; if (BalDesDehumPerfData(PerfDataNum).T_MinRegenAirInRelHum >= BalDesDehumPerfData(PerfDataNum).T_MaxRegenAirInRelHum) { ShowSevereError(cCurrentModuleObject + " \"" + BalDesDehumPerfData(PerfDataNum).Name + "\""); ShowContinueError("Error found in min/max boundary for the regen outlet air temperature equation."); ShowContinueError("... the minimum value of regen inlet air relative humidity must be less than the maximum."); ShowContinueError("... minimum value entered = " + RoundSigDigits(BalDesDehumPerfData(PerfDataNum).T_MinRegenAirInRelHum * 100.0, 6)); ShowContinueError("... maximum value entered = " + RoundSigDigits(BalDesDehumPerfData(PerfDataNum).T_MaxRegenAirInRelHum * 100.0, 6)); ErrorsFound = true; } if (BalDesDehumPerfData(PerfDataNum).T_MinRegenAirInRelHum < 0.0) { ShowSevereError(cCurrentModuleObject + " \"" + BalDesDehumPerfData(PerfDataNum).Name + "\""); ShowContinueError("Error found in min boundary for the regen outlet air temperature equation."); ShowContinueError("... the minimum value of regen inlet air relative humidity must be greater than or equal to 0."); ShowContinueError("... minimum value entered = " + RoundSigDigits(BalDesDehumPerfData(PerfDataNum).T_MinRegenAirInRelHum * 100.0, 6)); ErrorsFound = true; } if (BalDesDehumPerfData(PerfDataNum).T_MaxRegenAirInRelHum > 1.0) { ShowSevereError(cCurrentModuleObject + " \"" + BalDesDehumPerfData(PerfDataNum).Name + "\""); ShowContinueError("Error found in max boundary for the regen outlet air temperature equation."); ShowContinueError("... the maximum value of regen inlet air relative humidity must be less than or equal to 100."); ShowContinueError("... maximum value entered = " + RoundSigDigits(BalDesDehumPerfData(PerfDataNum).T_MaxRegenAirInRelHum * 100.0, 6)); ErrorsFound = true; } BalDesDehumPerfData(PerfDataNum).T_MinProcAirInRelHum = rNumericArgs(26) / 100.0; BalDesDehumPerfData(PerfDataNum).T_MaxProcAirInRelHum = rNumericArgs(27) / 100.0; if (BalDesDehumPerfData(PerfDataNum).T_MinProcAirInRelHum >= BalDesDehumPerfData(PerfDataNum).T_MaxProcAirInRelHum) { ShowSevereError(cCurrentModuleObject + " \"" + BalDesDehumPerfData(PerfDataNum).Name + "\""); ShowContinueError("Error found in min/max boundary for the regen outlet air temperature equation."); ShowContinueError("... the minimum value of process inlet air relative humidity must be less than the maximum."); ShowContinueError("... minimum value entered = " + RoundSigDigits(BalDesDehumPerfData(PerfDataNum).T_MinProcAirInRelHum * 100.0, 6)); ShowContinueError("... maximum value entered = " + RoundSigDigits(BalDesDehumPerfData(PerfDataNum).T_MaxProcAirInRelHum * 100.0, 6)); ErrorsFound = true; } if (BalDesDehumPerfData(PerfDataNum).T_MinProcAirInRelHum < 0.0) { ShowSevereError(cCurrentModuleObject + " \"" + BalDesDehumPerfData(PerfDataNum).Name + "\""); ShowContinueError("Error found in min boundary for the regen outlet air temperature equation."); ShowContinueError("... the minimum value of process inlet air relative humidity must be greater than or equal to 0."); ShowContinueError("... minimum value entered = " + RoundSigDigits(BalDesDehumPerfData(PerfDataNum).T_MinProcAirInRelHum * 100.0, 6)); ErrorsFound = true; } if (BalDesDehumPerfData(PerfDataNum).T_MaxProcAirInRelHum > 1.0) { ShowSevereError(cCurrentModuleObject + " \"" + BalDesDehumPerfData(PerfDataNum).Name + "\""); ShowContinueError("Error found in max boundary for the regen outlet air temperature equation."); ShowContinueError("... the maximum value of process inlet air relative humidity must be less than or equal to 100."); ShowContinueError("... maximum value entered = " + RoundSigDigits(BalDesDehumPerfData(PerfDataNum).T_MaxProcAirInRelHum * 100.0, 6)); ErrorsFound = true; } // regen outlet humidity ratio variables BalDesDehumPerfData(PerfDataNum).C1 = rNumericArgs(28); BalDesDehumPerfData(PerfDataNum).C2 = rNumericArgs(29); BalDesDehumPerfData(PerfDataNum).C3 = rNumericArgs(30); BalDesDehumPerfData(PerfDataNum).C4 = rNumericArgs(31); BalDesDehumPerfData(PerfDataNum).C5 = rNumericArgs(32); BalDesDehumPerfData(PerfDataNum).C6 = rNumericArgs(33); BalDesDehumPerfData(PerfDataNum).C7 = rNumericArgs(34); BalDesDehumPerfData(PerfDataNum).C8 = rNumericArgs(35); // Check that the minimum is not greater than or equal to the maximum for each of the following model boundaries BalDesDehumPerfData(PerfDataNum).H_MinRegenAirInHumRat = rNumericArgs(36); BalDesDehumPerfData(PerfDataNum).H_MaxRegenAirInHumRat = rNumericArgs(37); if (BalDesDehumPerfData(PerfDataNum).H_MinRegenAirInHumRat >= BalDesDehumPerfData(PerfDataNum).H_MaxRegenAirInHumRat) { ShowSevereError(cCurrentModuleObject + " \"" + BalDesDehumPerfData(PerfDataNum).Name + "\""); ShowContinueError("Error found in min/max boundary for the regen outlet air humidity ratio equation."); ShowContinueError("... the minimum value of regeneration inlet air humidity ratio must be less than the maximum."); ShowContinueError("... minimum value entered by user = " + RoundSigDigits(BalDesDehumPerfData(PerfDataNum).H_MinRegenAirInHumRat, 6)); ShowContinueError("... maximum value entered by user = " + RoundSigDigits(BalDesDehumPerfData(PerfDataNum).H_MaxRegenAirInHumRat, 6)); ErrorsFound = true; } if (BalDesDehumPerfData(PerfDataNum).H_MinRegenAirInHumRat < 0.0) { ShowSevereError(cCurrentModuleObject + " \"" + BalDesDehumPerfData(PerfDataNum).Name + "\""); ShowContinueError("Error found in min boundary for the regen outlet air humidity ratio equation."); ShowContinueError("... the minimum value of regeneration inlet air humidity ratio must be greater than or equal to 0."); ShowContinueError("... minimum value entered by user = " + RoundSigDigits(BalDesDehumPerfData(PerfDataNum).H_MinRegenAirInHumRat, 6)); ErrorsFound = true; } if (BalDesDehumPerfData(PerfDataNum).H_MaxRegenAirInHumRat > 1.0) { ShowSevereError(cCurrentModuleObject + " \"" + BalDesDehumPerfData(PerfDataNum).Name + "\""); ShowContinueError("Error found in max boundary for the regen outlet air humidity ratio equation."); ShowContinueError("... the maximum value of regeneration inlet air humidity ratio must be less than or equal to 1."); ShowContinueError("... maximum value entered by user = " + RoundSigDigits(BalDesDehumPerfData(PerfDataNum).H_MaxRegenAirInHumRat, 6)); ErrorsFound = true; } BalDesDehumPerfData(PerfDataNum).H_MinRegenAirInTemp = rNumericArgs(38); BalDesDehumPerfData(PerfDataNum).H_MaxRegenAirInTemp = rNumericArgs(39); if (BalDesDehumPerfData(PerfDataNum).H_MinRegenAirInTemp >= BalDesDehumPerfData(PerfDataNum).H_MaxRegenAirInTemp) { ShowSevereError(cCurrentModuleObject + " \"" + BalDesDehumPerfData(PerfDataNum).Name + "\""); ShowContinueError("Error found in min/max boundary for the regen outlet air humidity ratio equation."); ShowContinueError("... the minimum value of regeneration inlet air temperature must be less than the maximum."); ShowContinueError("... minimum value entered = " + RoundSigDigits(BalDesDehumPerfData(PerfDataNum).H_MinRegenAirInTemp, 6)); ShowContinueError("... maximum value entered = " + RoundSigDigits(BalDesDehumPerfData(PerfDataNum).H_MaxRegenAirInTemp, 6)); ErrorsFound = true; } BalDesDehumPerfData(PerfDataNum).H_MinProcAirInHumRat = rNumericArgs(40); BalDesDehumPerfData(PerfDataNum).H_MaxProcAirInHumRat = rNumericArgs(41); if (BalDesDehumPerfData(PerfDataNum).H_MinProcAirInHumRat >= BalDesDehumPerfData(PerfDataNum).H_MaxProcAirInHumRat) { ShowSevereError(cCurrentModuleObject + " \"" + BalDesDehumPerfData(PerfDataNum).Name + "\""); ShowContinueError("Error found in min/max boundary for the regen outlet air humidity ratio equation."); ShowContinueError("... the minimum value of process inlet air humidity ratio must be less than the maximum."); ShowContinueError("... minimum value entered by user = " + RoundSigDigits(BalDesDehumPerfData(PerfDataNum).H_MinProcAirInHumRat, 6)); ShowContinueError("... maximum value entered by user = " + RoundSigDigits(BalDesDehumPerfData(PerfDataNum).H_MaxProcAirInHumRat, 6)); ErrorsFound = true; } if (BalDesDehumPerfData(PerfDataNum).H_MinProcAirInHumRat < 0.0) { ShowSevereError(cCurrentModuleObject + " \"" + BalDesDehumPerfData(PerfDataNum).Name + "\""); ShowContinueError("Error found in min boundary for the regen outlet air humidity ratio equation."); ShowContinueError("... the minimum value of process inlet air humidity ratio must be greater than or equal to 0."); ShowContinueError("... minimum value entered by user = " + RoundSigDigits(BalDesDehumPerfData(PerfDataNum).H_MinProcAirInHumRat, 6)); ErrorsFound = true; } if (BalDesDehumPerfData(PerfDataNum).H_MaxProcAirInHumRat > 1.0) { ShowSevereError(cCurrentModuleObject + " \"" + BalDesDehumPerfData(PerfDataNum).Name + "\""); ShowContinueError("Error found in max boundary for the regen outlet air humidity ratio equation."); ShowContinueError("... the maximum value of process inlet air humidity ratio must be less than or equal to 1."); ShowContinueError("... maximum value entered by user = " + RoundSigDigits(BalDesDehumPerfData(PerfDataNum).H_MaxProcAirInHumRat, 6)); ErrorsFound = true; } BalDesDehumPerfData(PerfDataNum).H_MinProcAirInTemp = rNumericArgs(42); BalDesDehumPerfData(PerfDataNum).H_MaxProcAirInTemp = rNumericArgs(43); if (BalDesDehumPerfData(PerfDataNum).H_MinProcAirInTemp >= BalDesDehumPerfData(PerfDataNum).H_MaxProcAirInTemp) { ShowSevereError(cCurrentModuleObject + " \"" + BalDesDehumPerfData(PerfDataNum).Name + "\""); ShowContinueError("Error found in min/max boundary for the regen outlet air humidity ratio equation."); ShowContinueError("... the minimum value of process inlet air temperature must be less than the maximum."); ShowContinueError("... minimum value entered = " + RoundSigDigits(BalDesDehumPerfData(PerfDataNum).H_MinProcAirInTemp, 6)); ShowContinueError("... maximum value entered = " + RoundSigDigits(BalDesDehumPerfData(PerfDataNum).H_MaxProcAirInTemp, 6)); ErrorsFound = true; } BalDesDehumPerfData(PerfDataNum).H_MinFaceVel = rNumericArgs(44); BalDesDehumPerfData(PerfDataNum).H_MaxFaceVel = rNumericArgs(45); if (BalDesDehumPerfData(PerfDataNum).H_MinFaceVel >= BalDesDehumPerfData(PerfDataNum).H_MaxFaceVel) { ShowSevereError(cCurrentModuleObject + " \"" + BalDesDehumPerfData(PerfDataNum).Name + "\""); ShowContinueError("Error found in min/max boundary for the regen outlet air humidity ratio equation."); ShowContinueError("... the minimum value of regen air velocity must be less than the maximum."); ShowContinueError("... minimum value entered = " + RoundSigDigits(BalDesDehumPerfData(PerfDataNum).H_MinFaceVel, 6)); ShowContinueError("... maximum value entered = " + RoundSigDigits(BalDesDehumPerfData(PerfDataNum).H_MaxFaceVel, 6)); ErrorsFound = true; } BalDesDehumPerfData(PerfDataNum).MinRegenAirOutHumRat = rNumericArgs(46); BalDesDehumPerfData(PerfDataNum).MaxRegenAirOutHumRat = rNumericArgs(47); if (BalDesDehumPerfData(PerfDataNum).MinRegenAirOutHumRat >= BalDesDehumPerfData(PerfDataNum).MaxRegenAirOutHumRat) { ShowSevereError(cCurrentModuleObject + " \"" + BalDesDehumPerfData(PerfDataNum).Name + "\""); ShowContinueError("Error found in min/max boundary for the regen outlet air humidity ratio equation."); ShowContinueError("... the minimum value of regen outlet air humidity ratio must be less than the maximum."); ShowContinueError("... minimum value entered = " + RoundSigDigits(BalDesDehumPerfData(PerfDataNum).MinRegenAirOutHumRat, 6)); ShowContinueError("... maximum value entered = " + RoundSigDigits(BalDesDehumPerfData(PerfDataNum).MaxRegenAirOutHumRat, 6)); ErrorsFound = true; } if (BalDesDehumPerfData(PerfDataNum).MinRegenAirOutHumRat < 0.0) { ShowSevereError(cCurrentModuleObject + " \"" + BalDesDehumPerfData(PerfDataNum).Name + "\""); ShowContinueError("Error found in min boundary for the regen outlet air humidity ratio equation."); ShowContinueError("... the minimum value of regen outlet air humidity ratio must be greater than or equal to 0."); ShowContinueError("... minimum value entered = " + RoundSigDigits(BalDesDehumPerfData(PerfDataNum).MinRegenAirOutHumRat, 6)); ErrorsFound = true; } if (BalDesDehumPerfData(PerfDataNum).MaxRegenAirOutHumRat > 1.0) { ShowSevereError(cCurrentModuleObject + " \"" + BalDesDehumPerfData(PerfDataNum).Name + "\""); ShowContinueError("Error found in max boundary for the regen outlet air humidity ratio equation."); ShowContinueError("... the maximum value of regen outlet air humidity ratio must be less or equal to 1."); ShowContinueError("... maximum value entered = " + RoundSigDigits(BalDesDehumPerfData(PerfDataNum).MaxRegenAirOutHumRat, 6)); ErrorsFound = true; } BalDesDehumPerfData(PerfDataNum).H_MinRegenAirInRelHum = rNumericArgs(48) / 100.0; BalDesDehumPerfData(PerfDataNum).H_MaxRegenAirInRelHum = rNumericArgs(49) / 100.0; if (BalDesDehumPerfData(PerfDataNum).H_MinRegenAirInRelHum >= BalDesDehumPerfData(PerfDataNum).H_MaxRegenAirInRelHum) { ShowSevereError(cCurrentModuleObject + " \"" + BalDesDehumPerfData(PerfDataNum).Name + "\""); ShowContinueError("Error found in min/max boundary for the regen outlet air humidity ratio equation."); ShowContinueError("... the minimum value of regen inlet air relative humidity must be less than the maximum."); ShowContinueError("... minimum value entered = " + RoundSigDigits(BalDesDehumPerfData(PerfDataNum).H_MinRegenAirInRelHum * 100.0, 6)); ShowContinueError("... maximum value entered = " + RoundSigDigits(BalDesDehumPerfData(PerfDataNum).H_MaxRegenAirInRelHum * 100.0, 6)); ErrorsFound = true; } if (BalDesDehumPerfData(PerfDataNum).H_MinRegenAirInRelHum < 0.0) { ShowSevereError(cCurrentModuleObject + " \"" + BalDesDehumPerfData(PerfDataNum).Name + "\""); ShowContinueError("Error found in min boundary for the regen outlet air humidity ratio equation."); ShowContinueError("... the minimum value of regen inlet air relative humidity must be greater than or equal to 0."); ShowContinueError("... minimum value entered = " + RoundSigDigits(BalDesDehumPerfData(PerfDataNum).H_MinRegenAirInRelHum * 100.0, 6)); ErrorsFound = true; } if (BalDesDehumPerfData(PerfDataNum).H_MaxRegenAirInRelHum > 1.0) { ShowSevereError(cCurrentModuleObject + " \"" + BalDesDehumPerfData(PerfDataNum).Name + "\""); ShowContinueError("Error found in max boundary for the regen outlet air humidity ratio equation."); ShowContinueError("... the maximum value of regen inlet air relative humidity must be less or equal to 100."); ShowContinueError("... maximum value entered = " + RoundSigDigits(BalDesDehumPerfData(PerfDataNum).H_MaxRegenAirInRelHum * 100.0, 6)); ErrorsFound = true; } BalDesDehumPerfData(PerfDataNum).H_MinProcAirInRelHum = rNumericArgs(50) / 100.0; BalDesDehumPerfData(PerfDataNum).H_MaxProcAirInRelHum = rNumericArgs(51) / 100.0; if (BalDesDehumPerfData(PerfDataNum).H_MinProcAirInRelHum >= BalDesDehumPerfData(PerfDataNum).H_MaxProcAirInRelHum) { ShowSevereError(cCurrentModuleObject + " \"" + BalDesDehumPerfData(PerfDataNum).Name + "\""); ShowContinueError("Error found in min/max boundary for the regen outlet air humidity ratio equation."); ShowContinueError("... the minimum value of process inlet air relative humidity must be less than the maximum."); ShowContinueError("... minimum value entered = " + RoundSigDigits(BalDesDehumPerfData(PerfDataNum).H_MinProcAirInRelHum * 100.0, 6)); ShowContinueError("... maximum value entered = " + RoundSigDigits(BalDesDehumPerfData(PerfDataNum).H_MaxProcAirInRelHum * 100.0, 6)); ErrorsFound = true; } if (BalDesDehumPerfData(PerfDataNum).H_MinProcAirInRelHum < 0.0) { ShowSevereError(cCurrentModuleObject + " \"" + BalDesDehumPerfData(PerfDataNum).Name + "\""); ShowContinueError("Error found in min boundary for the regen outlet air humidity ratio equation."); ShowContinueError("... the minimum value of process inlet air relative humidity must be greater than or equal to 0."); ShowContinueError("... minimum value entered = " + RoundSigDigits(BalDesDehumPerfData(PerfDataNum).H_MinProcAirInRelHum * 100.0, 6)); ErrorsFound = true; } if (BalDesDehumPerfData(PerfDataNum).H_MaxProcAirInRelHum > 1.0) { ShowSevereError(cCurrentModuleObject + " \"" + BalDesDehumPerfData(PerfDataNum).Name + "\""); ShowContinueError("Error found in max boundary for the regen outlet air humidity ratio equation."); ShowContinueError("... the maximum value of process inlet air relative humidity must be less than or equal to 100."); ShowContinueError("... maximum value entered = " + RoundSigDigits(BalDesDehumPerfData(PerfDataNum).H_MaxProcAirInRelHum * 100.0, 6)); ErrorsFound = true; } } // getting performance data set for balanced desiccant heat exchanger ends // match desiccant heat exchanger index to performance data index for (ExchIndex = 1; ExchIndex <= NumDesiccantBalancedExchs; ++ExchIndex) { ExchNum = ExchIndex + NumAirToAirPlateExchs + NumAirToAirGenericExchs; for (PerfDataNum = 1; PerfDataNum <= NumDesBalExchsPerfDataType1; ++PerfDataNum) { if (UtilityRoutines::SameString(ExchCond(ExchNum).HeatExchPerfName, BalDesDehumPerfData(PerfDataNum).Name)) { ExchCond(ExchNum).PerfDataIndex = PerfDataNum; break; } } if (ExchCond(ExchNum).PerfDataIndex == 0) { ShowSevereError(cHXTypes(ExchCond(ExchNum).ExchTypeNum) + " \"" + ExchCond(ExchNum).Name + "\""); ShowContinueError("... Performance data set not found = " + ExchCond(ExchNum).HeatExchPerfName); ErrorsFound = true; } else { if (!ErrorsFound) { ExchCond(ExchNum).FaceArea = BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).NomSupAirVolFlow / (BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).NomProcAirFaceVel); } } } // matching done // setup common report variables for heat exchangers for (ExchIndex = 1; ExchIndex <= NumHeatExchangers; ++ExchIndex) { ExchNum = ExchIndex; // CurrentModuleObject='HeatExchanger:AirToAir:FlatPlate/AirToAir:SensibleAndLatent/Desiccant:BalancedFlow') SetupOutputVariable("Heat Exchanger Sensible Heating Rate", OutputProcessor::Unit::W, ExchCond(ExchNum).SensHeatingRate, "System", "Average", ExchCond(ExchNum).Name); SetupOutputVariable("Heat Exchanger Sensible Heating Energy", OutputProcessor::Unit::J, ExchCond(ExchNum).SensHeatingEnergy, "System", "Sum", ExchCond(ExchNum).Name); SetupOutputVariable("Heat Exchanger Latent Gain Rate", OutputProcessor::Unit::W, ExchCond(ExchNum).LatHeatingRate, "System", "Average", ExchCond(ExchNum).Name); SetupOutputVariable("Heat Exchanger Latent Gain Energy", OutputProcessor::Unit::J, ExchCond(ExchNum).LatHeatingEnergy, "System", "Sum", ExchCond(ExchNum).Name); SetupOutputVariable("Heat Exchanger Total Heating Rate", OutputProcessor::Unit::W, ExchCond(ExchNum).TotHeatingRate, "System", "Average", ExchCond(ExchNum).Name); SetupOutputVariable("Heat Exchanger Total Heating Energy", OutputProcessor::Unit::J, ExchCond(ExchNum).TotHeatingEnergy, "System", "Sum", ExchCond(ExchNum).Name, _, "ENERGYTRANSFER", "HEAT RECOVERY FOR HEATING", _, "System"); SetupOutputVariable("Heat Exchanger Sensible Cooling Rate", OutputProcessor::Unit::W, ExchCond(ExchNum).SensCoolingRate, "System", "Average", ExchCond(ExchNum).Name); SetupOutputVariable("Heat Exchanger Sensible Cooling Energy", OutputProcessor::Unit::J, ExchCond(ExchNum).SensCoolingEnergy, "System", "Sum", ExchCond(ExchNum).Name); SetupOutputVariable("Heat Exchanger Latent Cooling Rate", OutputProcessor::Unit::W, ExchCond(ExchNum).LatCoolingRate, "System", "Average", ExchCond(ExchNum).Name); SetupOutputVariable("Heat Exchanger Latent Cooling Energy", OutputProcessor::Unit::J, ExchCond(ExchNum).LatCoolingEnergy, "System", "Sum", ExchCond(ExchNum).Name); SetupOutputVariable("Heat Exchanger Total Cooling Rate", OutputProcessor::Unit::W, ExchCond(ExchNum).TotCoolingRate, "System", "Average", ExchCond(ExchNum).Name); SetupOutputVariable("Heat Exchanger Total Cooling Energy", OutputProcessor::Unit::J, ExchCond(ExchNum).TotCoolingEnergy, "System", "Sum", ExchCond(ExchNum).Name, _, "ENERGYTRANSFER", "HEAT RECOVERY FOR COOLING", _, "System"); SetupOutputVariable("Heat Exchanger Electric Power", OutputProcessor::Unit::W, ExchCond(ExchNum).ElecUseRate, "System", "Average", ExchCond(ExchNum).Name); SetupOutputVariable("Heat Exchanger Electric Energy", OutputProcessor::Unit::J, ExchCond(ExchNum).ElecUseEnergy, "System", "Sum", ExchCond(ExchNum).Name, _, "ELECTRICITY", "HEATRECOVERY", _, "System"); } // setup additional report variables for generic heat exchangers for (ExchIndex = 1; ExchIndex <= NumAirToAirGenericExchs; ++ExchIndex) { // generic heat exchangers are read in after flat plate heat exchanger objects (index needs to be set correctly) // CurrentModuleObject=HeatExchanger:AirToAir:SensibleAndLatent ExchNum = ExchIndex + NumAirToAirPlateExchs; SetupOutputVariable("Heat Exchanger Sensible Effectiveness", OutputProcessor::Unit::None, ExchCond(ExchNum).SensEffectiveness, "System", "Average", ExchCond(ExchNum).Name); SetupOutputVariable("Heat Exchanger Latent Effectiveness", OutputProcessor::Unit::None, ExchCond(ExchNum).LatEffectiveness, "System", "Average", ExchCond(ExchNum).Name); SetupOutputVariable("Heat Exchanger Supply Air Bypass Mass Flow Rate", OutputProcessor::Unit::kg_s, ExchCond(ExchNum).SupBypassMassFlow, "System", "Average", ExchCond(ExchNum).Name); SetupOutputVariable("Heat Exchanger Exhaust Air Bypass Mass Flow Rate", OutputProcessor::Unit::kg_s, ExchCond(ExchNum).SecBypassMassFlow, "System", "Average", ExchCond(ExchNum).Name); SetupOutputVariable("Heat Exchanger Defrost Time Fraction", OutputProcessor::Unit::None, ExchCond(ExchNum).DefrostFraction, "System", "Average", ExchCond(ExchNum).Name); } if (ErrorsFound) { ShowFatalError(RoutineName + "Errors found in input. Program terminates."); } } void InitHeatRecovery(int const ExchNum, // number of the current heat exchanger being simulated int const CompanionCoilIndex, int const CompanionCoilType_Num) { // SUBROUTINE INFORMATION: // AUTHOR Michael Wetter // DATE WRITTEN March 1999 // MODIFIED F Buhl Nov 2000, D Shirey Feb 2003 // B Griffith May 2009, EMS setpoint check // RE-ENGINEERED na // PURPOSE OF THIS SUBROUTINE: // This subroutine is for initializations of the Heat Recovery Components. // METHODOLOGY EMPLOYED: // Uses the status flags to trigger initializations. // REFERENCES: // na // Using/Aliasing using DXCoils::DXCoilFullLoadOutAirHumRat; using DXCoils::DXCoilFullLoadOutAirTemp; using General::RoundSigDigits; // USE DataZoneEquipment, ONLY: ZoneEquipInputsFilled,CheckZoneEquipmentList using DataGlobals::AnyEnergyManagementSystemInModel; using EMSManager::CheckIfNodeSetPointManagedByEMS; using EMSManager::iHumidityRatioMaxSetPoint; using EMSManager::iTemperatureSetPoint; // Locals // SUBROUTINE ARGUMENT DEFINITIONS: // SUBROUTINE PARAMETER DEFINITIONS: // na // INTERFACE BLOCK SPECIFICATIONS: // na // DERIVED TYPE DEFINITIONS: // na // SUBROUTINE LOCAL VARIABLE DECLARATIONS: int ExIndex; // do loop index int SupInNode; // supply air inlet node number int SecInNode; // secondary air inlet node number Real64 CMin0; // minimum capacity flow Real64 CMax0; // maximum capacity flow Real64 Eps0; // effectiveness at rated conditions Real64 NTU0; // NTU at rated conditions Real64 RhoAir; // air density at outside pressure & standard temperature and humidity Real64 CpAir; // heat capacity of air // of humidity ratio and temperature //////////// hoisted into namespace //////////////////////////////////////////////// // static bool MyOneTimeAllocate( true ); //////////////////////////////////////////////////////////////////////////////////// static Array1D_bool MySetPointTest; static Array1D_bool MySizeFlag; int ErrStat; // error status returned by CalculateNTUfromEpsAndZ bool FatalError; // fatal error flag bool LocalWarningError; // warning error flag Real64 Z; // Min/max flow ratio // LOGICAL,SAVE :: ZoneEquipmentListChecked = .FALSE. ! True after the Zone Equipment List has been checked for items if (MyOneTimeAllocate) { MySetPointTest.allocate(NumHeatExchangers); MySizeFlag.allocate(NumHeatExchangers); MySetPointTest = true; MySizeFlag = true; MyOneTimeAllocate = false; } if (!SysSizingCalc && MySizeFlag(ExchNum)) { SizeHeatRecovery(ExchNum); MySizeFlag(ExchNum) = false; } FatalError = false; LocalWarningError = false; // Do the Begin Environment initializations if (BeginEnvrnFlag && ExchCond(ExchNum).myEnvrnFlag) { // I believe that all of these initializations should be taking place at the SCFM conditions RhoAir = StdRhoAir; // RhoAir = PsyRhoAirFnPbTdbW(101325.0,20.0,0.0) do we want standard air density at sea level for generic ERVs per ARI 1060? CpAir = PsyCpAirFnWTdb(0.0, 20.0); ExIndex = ExchNum; // this replaces the loop that went over multiple at once { auto const SELECT_CASE_var(ExchCond(ExIndex).ExchTypeNum); if (SELECT_CASE_var == HX_AIRTOAIR_FLATPLATE) { ExchCond(ExIndex).NomSupAirMassFlow = RhoAir * ExchCond(ExIndex).NomSupAirVolFlow; ExchCond(ExIndex).NomSecAirMassFlow = RhoAir * ExchCond(ExIndex).NomSecAirVolFlow; // Note: the capacity stream is here simply the mass flow // since the thermal capacity can be assumed to be // equal for both streams if (ExchCond(ExIndex).NomSupAirMassFlow > ExchCond(ExIndex).NomSecAirMassFlow) { CMin0 = ExchCond(ExIndex).NomSecAirMassFlow; CMax0 = ExchCond(ExIndex).NomSupAirMassFlow; } else { CMin0 = ExchCond(ExIndex).NomSupAirMassFlow; CMax0 = ExchCond(ExIndex).NomSecAirMassFlow; } Eps0 = ExchCond(ExIndex).NomSupAirMassFlow * SafeDiv(ExchCond(ExIndex).NomSupAirOutTemp - ExchCond(ExIndex).NomSupAirInTemp, CMin0 * (ExchCond(ExIndex).NomSecAirInTemp - ExchCond(ExIndex).NomSupAirInTemp)); Z = CMin0 / CMax0; ErrStat = 0; CalculateNTUfromEpsAndZ(NTU0, ErrStat, Z, ExchCond(ExIndex).FlowArr, Eps0); if (ErrStat == 1) { FatalError = true; ShowSevereError("In the HeatExchanger:AirToAir:FlatPlate component " + ExchCond(ExIndex).Name); ShowContinueError(" the mass flow ratio is out of bounds"); ShowContinueError("The mass flow ratio is (Min_Mass_Flow_Rate / Max_Mass_Flow_Rate) = " + RoundSigDigits(Z, 2)); ShowContinueError("The mass flow ratio should be >= 0.0 and <= 1.0"); ShowContinueError("Min_Mass_Flow_Rate = " + RoundSigDigits(RhoAir, 2) + " [air density] * " + RoundSigDigits(min(ExchCond(ExIndex).NomSupAirVolFlow, ExchCond(ExIndex).NomSecAirVolFlow), 1) + " [Min_Vol_Flow_Rate]"); ShowContinueError("Max_Mass_Flow_Rate = " + RoundSigDigits(RhoAir, 2) + " [air density] * " + RoundSigDigits(max(ExchCond(ExIndex).NomSupAirVolFlow, ExchCond(ExIndex).NomSecAirVolFlow), 1) + " [Max_Vol_Flow_Rate]"); } else if (ErrStat == 2) { FatalError = true; ShowSevereError("In the HeatExchanger:AirToAir:FlatPlate component " + ExchCond(ExIndex).Name); ShowContinueError(" the calculated nominal effectiveness is out of bounds"); ShowContinueError("The effectiveness is " + RoundSigDigits(Eps0, 3)); ShowContinueError("The effectiveness should be >= 0.0 and <= " + RoundSigDigits(1.0 / (1.0 + Z), 3)); ShowContinueError( "Eff = (Nom_Sup_Mass_Flow_Rate/Min_Mass_Flow_Rate)*(T_nom_sup_out-T_nom_sup_in)/(T_nom_sec_in-T_nom_sup_in)"); ShowContinueError("The temperatures are user inputs. The mass flow rates are user input volume flow rates"); ShowContinueError(" times the density of air [" + RoundSigDigits(RhoAir, 2) + " kg/m3]"); ShowContinueError("Change these inputs to obtain a physically realizable heat exchanger effectiveness"); } else if (ErrStat == 3) { FatalError = true; ShowSevereError("In the HeatExchanger:AirToAir:FlatPlate component " + ExchCond(ExIndex).Name); ShowContinueError(" the calculated nominal effectiveness is out of bounds"); ShowContinueError("The effectiveness is " + RoundSigDigits(Eps0, 3)); ShowContinueError("The effectiveness should be >= 0.0 and <= " + RoundSigDigits((1.0 - std::exp(-Z)) / Z, 3)); ShowContinueError( "Eff = (Nom_Sup_Mass_Flow_Rate/Min_Mass_Flow_Rate)*(T_nom_sup_out-T_nom_sup_in)/(T_nom_sec_in-T_nom_sup_in)"); ShowContinueError("The temperatures are user inputs. The mass flow rates are user input volume flow rates"); ShowContinueError(" times the density of air [" + RoundSigDigits(RhoAir, 2) + " kg/m3]"); ShowContinueError("Change these inputs to obtain a physically realizable heat exchanger effectiveness"); } else if (ErrStat == 4) { FatalError = true; ShowSevereError("In the HeatExchanger:AirToAir:FlatPlate component " + ExchCond(ExIndex).Name); ShowContinueError(" the quantity Eff_nom*(Min_Mass_Flow_Rate / Max_Mass_Flow_Rate) is out of bounds"); ShowContinueError("The value is " + RoundSigDigits(Eps0 * Z, 3)); ShowContinueError("The value should be >= 0.0 and <= " + RoundSigDigits(1.0 - std::exp(Z * (SMALL - 1.0)), 3)); ShowContinueError( "Eff_nom = (Nom_Sup_Mass_Flow_Rate/Min_Mass_Flow_Rate) * (T_nom_sup_out - T_nom_sup_in)/(T_nom_sec_in - T_nom_sup_in)"); ShowContinueError("The temperatures are user inputs. The mass flow rates are user input volume flow rates"); ShowContinueError(" times the density of air [" + RoundSigDigits(RhoAir, 2) + " kg/m3]"); ShowContinueError("Change these inputs to obtain a physically realizable product of effectiveness times min/max mass ratio " "for this heat exchanger"); } else if (ErrStat == 5) { FatalError = true; ShowSevereError("In the HeatExchanger:AirToAir:FlatPlate component " + ExchCond(ExIndex).Name); ShowContinueError(" the calculated nominal effectiveness is out of bounds"); ShowContinueError("The effectiveness is " + RoundSigDigits(Eps0, 3)); ShowContinueError("The effectiveness should be >= 0.0 and <= 1.0"); ShowContinueError( "Eff = (Nom_Sup_Mass_Flow_Rate/Min_Mass_Flow_Rate)*(T_nom_sup_out-T_nom_sup_in)/(T_nom_sec_in-T_nom_sup_in)"); ShowContinueError("The temperatures are user inputs. The mass flow rates are user input volume flow rates"); ShowContinueError(" times the density of air [" + RoundSigDigits(RhoAir, 2) + " kg/m3]"); ShowContinueError("Change these inputs to obtain a physically realizable heat exchanger effectiveness"); } if (FatalError) { ShowFatalError("Heat exchanger design calculation caused fatal error: program terminated."); } ExchCond(ExIndex).UA0 = NTU0 * CMin0 * CpAir; ExchCond(ExIndex).mTSup0 = ExchCond(ExIndex).NomSupAirMassFlow * (ExchCond(ExIndex).NomSupAirInTemp + KELVZERO); ExchCond(ExIndex).mTSec0 = ExchCond(ExIndex).NomSecAirMassFlow * (ExchCond(ExIndex).NomSecAirInTemp + KELVZERO); // check validity if (ExchCond(ExIndex).NomSupAirMassFlow * ExchCond(ExIndex).NomSecAirMassFlow < SmallMassFlow * SmallMassFlow) { ShowFatalError("Mass flow in HeatExchanger:AirToAir:FlatPlate too small in initialization."); } if (ExchCond(ExIndex).mTSup0 < SmallMassFlow) { ShowFatalError("(m*T)Sup,in in HeatExchanger:AirToAir:FlatPlate too small in initialization."); } if (ExchCond(ExIndex).mTSec0 < SmallMassFlow) { ShowFatalError("(m*T)Sec,in in HeatExchanger:AirToAir:FlatPlate too small in initialization."); } if (CMin0 < SmallMassFlow) { ShowFatalError("CMin0 in HeatExchanger:AirToAir:FlatPlate too small in initialization."); } } else if (SELECT_CASE_var == HX_AIRTOAIR_GENERIC) { if (ExchCond(ExIndex).SupOutletNode > 0 && ExchCond(ExIndex).ControlToTemperatureSetPoint) { if (Node(ExchCond(ExIndex).SupOutletNode).TempSetPoint == SensedNodeFlagValue) { if (!AnyEnergyManagementSystemInModel) { ShowSevereError("Missing temperature setpoint for " + cHXTypes(ExchCond(ExIndex).ExchTypeNum) + " \"" + ExchCond(ExIndex).Name + "\" :"); ShowContinueError( " use a Setpoint Manager to establish a setpoint at the supply air outlet node of the Heat Exchanger."); ShowFatalError(" Previous condition causes program termination."); } else { // need call to EMS to check node CheckIfNodeSetPointManagedByEMS(ExchCond(ExIndex).SupOutletNode, iTemperatureSetPoint, FatalError); if (FatalError) { ShowSevereError("Missing temperature setpoint for " + cHXTypes(ExchCond(ExIndex).ExchTypeNum) + " \"" + ExchCond(ExIndex).Name + "\" :"); ShowContinueError( " use a Setpoint Manager to establish a setpoint at the supply air outlet node of the Heat Exchanger."); ShowContinueError( " or use an EMS actuator to establish a setpoint at the supply air outlet node of the Heat Exchanger."); ShowFatalError(" Previous condition causes program termination."); } } } } } else if (SELECT_CASE_var == HX_DESICCANT_BALANCED) { } else { // Will never get here } } ExchCond(ExchNum).myEnvrnFlag = false; } if (!BeginEnvrnFlag) { ExchCond(ExchNum).myEnvrnFlag = true; } // Do these initializations every time step SupInNode = ExchCond(ExchNum).SupInletNode; SecInNode = ExchCond(ExchNum).SecInletNode; // Get information from inlet nodes ExchCond(ExchNum).SupInTemp = Node(SupInNode).Temp; ExchCond(ExchNum).SupInHumRat = Node(SupInNode).HumRat; ExchCond(ExchNum).SupInEnth = Node(SupInNode).Enthalpy; ExchCond(ExchNum).SupInMassFlow = Node(SupInNode).MassFlowRate; ExchCond(ExchNum).SecInTemp = Node(SecInNode).Temp; ExchCond(ExchNum).SecInHumRat = Node(SecInNode).HumRat; ExchCond(ExchNum).SecInEnth = Node(SecInNode).Enthalpy; ExchCond(ExchNum).SecInMassFlow = Node(SecInNode).MassFlowRate; // initialize the output variables ExchCond(ExchNum).SensHeatingRate = 0.0; ExchCond(ExchNum).SensHeatingEnergy = 0.0; ExchCond(ExchNum).LatHeatingRate = 0.0; ExchCond(ExchNum).LatHeatingEnergy = 0.0; ExchCond(ExchNum).TotHeatingRate = 0.0; ExchCond(ExchNum).TotHeatingEnergy = 0.0; ExchCond(ExchNum).SensCoolingRate = 0.0; ExchCond(ExchNum).SensCoolingEnergy = 0.0; ExchCond(ExchNum).LatCoolingRate = 0.0; ExchCond(ExchNum).LatCoolingEnergy = 0.0; ExchCond(ExchNum).TotCoolingRate = 0.0; ExchCond(ExchNum).TotCoolingEnergy = 0.0; ExchCond(ExchNum).ElecUseRate = 0.0; ExchCond(ExchNum).ElecUseEnergy = 0.0; ExchCond(ExchNum).SensEffectiveness = 0.0; ExchCond(ExchNum).LatEffectiveness = 0.0; ExchCond(ExchNum).SupBypassMassFlow = 0.0; ExchCond(ExchNum).SecBypassMassFlow = 0.0; // Initialize inlet conditions { auto const SELECT_CASE_var(ExchCond(ExchNum).ExchTypeNum); if (SELECT_CASE_var == HX_AIRTOAIR_FLATPLATE) { } else if (SELECT_CASE_var == HX_AIRTOAIR_GENERIC) { } else if (SELECT_CASE_var == HX_DESICCANT_BALANCED) { if (MySetPointTest(ExchNum)) { if (!SysSizingCalc && DoSetPointTest) { if (!CalledFromParentObject) { if (Node(ExchCond(ExchNum).SecOutletNode).HumRatMax == SensedNodeFlagValue) { if (!AnyEnergyManagementSystemInModel) { ShowWarningError("Missing optional HumRatMax setpoint for " + cHXTypes(ExchCond(ExchNum).ExchTypeNum) + " \"" + ExchCond(ExchNum).Name + "\""); ShowContinueError("...the simulation will continue without control of the desiccant heat exchanger to a maximum " "humidity ratio setpoint."); ShowContinueError("...use a Setpoint Manager to establish a setpoint at the process air outlet node of the " "desiccant Heat Exchanger if control is desired."); } else { // need call to EMS to check node CheckIfNodeSetPointManagedByEMS(ExchCond(ExchNum).SecOutletNode, iHumidityRatioMaxSetPoint, LocalWarningError); if (LocalWarningError) { ShowWarningError("Missing optional HumRatMax setpoint for " + cHXTypes(ExchCond(ExchNum).ExchTypeNum) + " \"" + ExchCond(ExchNum).Name + "\""); ShowContinueError("...the simulation will continue without control of the desiccant heat exchanger to a " "maximum humidity ratio setpoint."); ShowContinueError("...use a Setpoint Manager to establish a setpoint at the process air outlet node of the " "desiccant Heat Exchanger if control is desired."); ShowContinueError("...or use an EMS Actuator to establish a maximum humidity ratio setpoint at the process " "air outlet node of the desiccant Heat Exchanger if control is desired."); } } } } MySetPointTest(ExchNum) = false; } } if (CompanionCoilIndex > 0) { if (CompanionCoilType_Num == DataHVACGlobals::CoilDX_CoolingSingleSpeed || CompanionCoilType_Num == DataHVACGlobals::CoilDX_CoolingTwoStageWHumControl) { if (DXCoilFullLoadOutAirTemp(CompanionCoilIndex) == 0.0 || DXCoilFullLoadOutAirHumRat(CompanionCoilIndex) == 0.0) { // DX Coil is OFF, read actual inlet conditions FullLoadOutAirTemp = ExchCond(ExchNum).SecInTemp; FullLoadOutAirHumRat = ExchCond(ExchNum).SecInHumRat; } else { // DX Coil is ON, read full load DX coil outlet conditions (conditions HX sees when ON) FullLoadOutAirTemp = DXCoilFullLoadOutAirTemp(CompanionCoilIndex); FullLoadOutAirHumRat = DXCoilFullLoadOutAirHumRat(CompanionCoilIndex); } } else if (CompanionCoilType_Num == DataHVACGlobals::Coil_CoolingAirToAirVariableSpeed) { // how to support VS dx coil here? FullLoadOutAirTemp = VariableSpeedCoils::VarSpeedCoil(CompanionCoilIndex).OutletAirDBTemp; FullLoadOutAirHumRat = VariableSpeedCoils::VarSpeedCoil(CompanionCoilIndex).OutletAirHumRat; } } else { // HX only (not used in conjunction with DX coil), read inlet conditions FullLoadOutAirTemp = ExchCond(ExchNum).SecInTemp; FullLoadOutAirHumRat = ExchCond(ExchNum).SecInHumRat; } } else { // Will never get here } } } void SizeHeatRecovery(int const ExchNum) { // SUBROUTINE INFORMATION: // AUTHOR Richard Raustad // DATE WRITTEN October 2007 // MODIFIED February 2014 Daeho Kang, enable sizing multiple HX types and add additional sizing fields // RE-ENGINEERED na // PURPOSE OF THIS SUBROUTINE: // This subroutine is for sizing Heat Exchanger components for which flow rates have not been // specified in the input. Currently, only nominal supply air flow rate for the generic HX can be autosized. // METHODOLOGY EMPLOYED: // Obtains flow rates from the system or OA system sizing arrays // Using/Aliasing using namespace DataSizing; using ReportSizingManager::ReportSizingOutput; using ReportSizingManager::RequestSizing; // Locals // SUBROUTINE PARAMETER DEFINITIONS: static std::string const RoutineName("SizeHeatRecovery"); // SUBROUTINE LOCAL VARIABLE DECLARATIONS: bool PrintFlag; // true when sizing information is reported in the eio file int BalDesDehumPerfIndex; // index of dehum performance data1 object int SizingMethod; // integer representation of sizing method (e.g., CoolingAirflowSizing, HeatingCapacitySizing, etc.) int FieldNum; // IDD numeric field index where input field description is found Real64 TempSize; // autosized value of coil input field std::string CompName; // component name std::string CompType; // component type std::string SizingString; // input field sizing description HRFlowSizingFlag = true; PrintFlag = true; FieldNum = 0; if (ExchCond(ExchNum).ExchTypeNum == HX_DESICCANT_BALANCED) { PrintFlag = false; } else if (ExchCond(ExchNum).ExchTypeNum == HX_AIRTOAIR_GENERIC) { FieldNum = 1; } else if (ExchCond(ExchNum).ExchTypeNum == HX_AIRTOAIR_FLATPLATE) { FieldNum = 2; } else { assert(0); } CompName = ExchCond(ExchNum).Name; CompType = cHXTypes(ExchCond(ExchNum).ExchTypeNum); if (FieldNum > 0) { SizingString = HeatExchCondNumericFields(ExchNum).NumericFieldNames(FieldNum) + " [m3/s]"; } else { SizingString = "Nominal Supply Air Flow Rate [m3/s]"; // desiccant balanced flow does not have an input for air volume flow rate } SizingMethod = SystemAirflowSizing; if (CurZoneEqNum > 0) { if (ExchCond(ExchNum).NomSupAirVolFlow == AutoSize) { SizingMethod = AutoCalculateSizing; if (ZoneEqSizing(CurZoneEqNum).DesignSizeFromParent) { // Heat recovery heat exchanger in zoneHVAC equipment should have been sized to OA flow in the parent equipment DataConstantUsedForSizing = ZoneEqSizing(CurZoneEqNum).AirVolFlow; } else { DataConstantUsedForSizing = std::max(FinalZoneSizing(CurZoneEqNum).DesCoolVolFlow, FinalZoneSizing(CurZoneEqNum).DesHeatVolFlow); } DataFractionUsedForSizing = 1.0; } else { if (ZoneSizingRunDone) { SizingMethod = AutoCalculateSizing; if (ZoneEqSizing(CurZoneEqNum).DesignSizeFromParent) { // Heat recovery heat exchanger in zoneHVAC equipment should have been sized to OA flow in the parent equipment DataConstantUsedForSizing = ZoneEqSizing(CurZoneEqNum).AirVolFlow; } else { DataConstantUsedForSizing = std::max(FinalZoneSizing(CurZoneEqNum).DesCoolVolFlow, FinalZoneSizing(CurZoneEqNum).DesHeatVolFlow); } DataFractionUsedForSizing = 1.0; } } } TempSize = ExchCond(ExchNum).NomSupAirVolFlow; RequestSizing(CompType, CompName, SizingMethod, SizingString, TempSize, PrintFlag, RoutineName); ExchCond(ExchNum).NomSupAirVolFlow = TempSize; DataConstantUsedForSizing = 0.0; DataFractionUsedForSizing = 0.0; if (ExchCond(ExchNum).ExchTypeNum == HX_AIRTOAIR_FLATPLATE) { PrintFlag = true; FieldNum = 5; CompName = ExchCond(ExchNum).Name; CompType = cHXTypes(ExchCond(ExchNum).ExchTypeNum); SizingString = HeatExchCondNumericFields(ExchNum).NumericFieldNames(FieldNum) + " [m3/s]"; SizingMethod = SystemAirflowSizing; // used if flow is hard sized without sizing run if (ExchCond(ExchNum).NomSecAirVolFlow == AutoSize) { SizingMethod = AutoCalculateSizing; DataConstantUsedForSizing = ExchCond(ExchNum).NomSupAirVolFlow; DataFractionUsedForSizing = 1.0; } else { if (ZoneSizingRunDone || SysSizingRunDone) { SizingMethod = AutoCalculateSizing; DataConstantUsedForSizing = ExchCond(ExchNum).NomSupAirVolFlow; DataFractionUsedForSizing = 1.0; } } TempSize = ExchCond(ExchNum).NomSecAirVolFlow; RequestSizing(CompType, CompName, SizingMethod, SizingString, TempSize, PrintFlag, RoutineName); ExchCond(ExchNum).NomSecAirVolFlow = TempSize; DataConstantUsedForSizing = 0.0; DataFractionUsedForSizing = 0.0; } HRFlowSizingFlag = false; if (ExchCond(ExchNum).ExchTypeNum == HX_DESICCANT_BALANCED && ExchCond(ExchNum).HeatExchPerfTypeNum == BALANCEDHX_PERFDATATYPE1) { BalDesDehumPerfIndex = ExchCond(ExchNum).PerfDataIndex; FieldNum = 1; PrintFlag = true; CompName = BalDesDehumPerfData(BalDesDehumPerfIndex).Name; CompType = BalDesDehumPerfData(BalDesDehumPerfIndex).PerfType; SizingString = BalDesDehumPerfNumericFields(BalDesDehumPerfIndex).NumericFieldNames(FieldNum) + " [m3/s]"; SizingMethod = SystemAirflowSizing; TempSize = BalDesDehumPerfData(BalDesDehumPerfIndex).NomSupAirVolFlow; RequestSizing(CompType, CompName, SizingMethod, SizingString, TempSize, PrintFlag, RoutineName); BalDesDehumPerfData(BalDesDehumPerfIndex).NomSupAirVolFlow = TempSize; FieldNum = 2; SizingString = BalDesDehumPerfNumericFields(BalDesDehumPerfIndex).NumericFieldNames(FieldNum) + " [m/s]"; DataAirFlowUsedForSizing = BalDesDehumPerfData(BalDesDehumPerfIndex).NomSupAirVolFlow; TempSize = BalDesDehumPerfData(BalDesDehumPerfIndex).NomProcAirFaceVel; SizingMethod = DesiccantDehumidifierBFPerfDataFaceVelocitySizing; RequestSizing(CompType, CompName, SizingMethod, SizingString, TempSize, PrintFlag, RoutineName); BalDesDehumPerfData(BalDesDehumPerfIndex).NomProcAirFaceVel = TempSize; DataAirFlowUsedForSizing = 0.0; } } void CalcAirToAirPlateHeatExch(int const ExNum, // number of the current heat exchanger being simulated bool const HXUnitOn, // flag to simulate heat exchager heat recovery Optional_bool_const EconomizerFlag, // economizer flag pass by air loop or OA sys Optional_bool_const HighHumCtrlFlag // high humidity control flag passed by airloop or OA sys ) { // SUBROUTINE INFORMATION: // AUTHOR Michael Wetter // DATE WRITTEN March 1999 // MODIFIED F. Buhl Nov 2000, R. Raustad - FSEC, Feb 2009 - added economizer flags // Both the economizer and high humidity control flags can disable the HX // RE-ENGINEERED na // PURPOSE OF THIS SUBROUTINE: // Calculate the outlet conditions for an air to air plate heat // exchanger given the inlet conditions. // METHODOLOGY EMPLOYED: // This is a static heat exchanger model. No geometrical input data // is needed. No knowledge of h*A values is needed except the ratio // of the primary side to the secondary side convective heat transfer // coefficient times the exchanger surface area. Effectiveness - NTU // heat exchanger formulas are used. // The time varying load is calculated based on the variation of the // convective heat transfer coefficient.The variation is a function of // mass flow rate and inlet temperature. An iterative solution is only // required during initialization in one specific flow arrangement. During // the time steps the solution is explicit. The iteration is done with // the Regula Falsi algorithm. Convergence is always achieved. // REFERENCES: // M. Wetter, Simulation Model Air-to-Air Plate Heat Exchanger // LBNL Report 42354, 1999. // USE STATEMENTS: // na // Locals // SUBROUTINE ARGUMENT DEFINITIONS: // SUBROUTINE PARAMETER DEFINITIONS: // na // INTERFACE BLOCK SPECIFICATIONS: // na // DERIVED TYPE DEFINITIONS: // na // SUBROUTINE LOCAL VARIABLE DECLARATIONS: bool UnitOn; // unit on flag Real64 SupBypassMassFlow; // supply air mass flow rate bypassing unit [kg/s] Real64 UnitSupMassFlow; // supply air mass flow rate passing through the unit [kg/s] Real64 SecBypassMassFlow; // secondary air mass flow rate bypassing unit [kg/s] Real64 UnitSecMassFlow; // secondary air mass flow rate passing through the unit [kg/s] Real64 QuotSup; // ratio of supply nominal m*T to actual m*T Real64 QuotExh; // ratio of secondary nominal m*T to actual m*T Real64 Deno; // denominator of UA calculation Real64 CSup; // supply air capacitance rate [J/C/s] Real64 CSec; // secondary air capacitance rate [J/C/s] Real64 CMin; // minimum air capacitance rate [J/C/s] Real64 Z; // Ratio of minimum air capacitance rate to maximum air capacitance rate Real64 NTU; // Number of heat transfer units Real64 Eps; // epsilon, the unit effectiveness Real64 UA; // present UA Real64 TempSupOut; // unit supply outlet temperature [C] Real64 HumRatSupOut; // unit supply outlet humidity ratio [kg water / kg dry air] Real64 EnthSupOut; // unit supply outlet enthalpy [J/kg] Real64 TempSupOutSat; // unit supply outlet temperature at saturation (at EnthSupOut) [C] Real64 QTrans; // heat transferred in the heat exchanger [W] Real64 ElecCons; // electricity consumption rate [W] Real64 TempSecOut; // unit secondary outlet temperature [C] Real64 HumRatSecOut; // unit secondary outlet humidity ratio [kg water / kg dry air] Real64 EnthSecOut; // unit secondary outlet enthalpy [J/kgC] Real64 TempSecOutSat; // unit secondary outlet temperature at saturation (at EnthsSecOut) [C] Real64 SensHeatRecRate; // sensible heat recovery rate to supply air (heating +, cooling -) Real64 LatHeatRecRate; // latent heat recovery rate to supply air (heating [humidify] +, cooling [dehumidify] -) Real64 TotHeatRecRate; // total heat recovery rate to supply air (heating +, cooling -) bool EconomizerActiveFlag; // local representing the economizer status when PRESENT bool HighHumCtrlActiveFlag; // local representing high humidity control when PRESENT UnitOn = true; QTrans = 0.0; ElecCons = 0.0; if (present(EconomizerFlag)) { EconomizerActiveFlag = EconomizerFlag; } else { EconomizerActiveFlag = false; } if (present(HighHumCtrlFlag)) { HighHumCtrlActiveFlag = HighHumCtrlFlag; } else { HighHumCtrlActiveFlag = false; } if ((EconomizerActiveFlag || HighHumCtrlActiveFlag) && ExchCond(ExNum).EconoLockOut == EconoLockOut_Yes) { UnitSupMassFlow = 0.0; // set HX supply flow to 0, all supply air will go through supply bypass UnitSecMassFlow = 0.0; // set HX secondary flow to 0, all secondary air will got through secondary bypass UnitOn = false; // turn off HX calculations when in economizer mode } else { // if economizer operation is not allowed, air always passes through HX // if CompanionCoilNum > 0, air always passes through HX (no economizer operation allowed) UnitSupMassFlow = min(ExchCond(ExNum).NomSupAirMassFlow, ExchCond(ExNum).SupInMassFlow); UnitSecMassFlow = min(ExchCond(ExNum).NomSecAirMassFlow, ExchCond(ExNum).SecInMassFlow); } SupBypassMassFlow = max(0.0, ExchCond(ExNum).SupInMassFlow - UnitSupMassFlow); SecBypassMassFlow = max(0.0, ExchCond(ExNum).SecInMassFlow - UnitSecMassFlow); if (GetCurrentScheduleValue(ExchCond(ExNum).SchedPtr) <= 0.0) UnitOn = false; if (ExchCond(ExNum).SupInMassFlow <= SmallMassFlow) UnitOn = false; if (ExchCond(ExNum).SecInMassFlow <= SmallMassFlow) UnitOn = false; if (!HXUnitOn) UnitOn = false; if (UnitOn) { // unit is on // calculate the UA for this time step QuotSup = SafeDiv(ExchCond(ExNum).mTSup0, UnitSupMassFlow * (ExchCond(ExNum).SupInTemp + KELVZERO)); QuotExh = SafeDiv(ExchCond(ExNum).mTSec0, UnitSecMassFlow * (ExchCond(ExNum).SecInTemp + KELVZERO)); Deno = std::pow(QuotSup, 0.78) + ExchCond(ExNum).hARatio * std::pow(QuotExh, 0.78); UA = ExchCond(ExNum).UA0 * (ExchCond(ExNum).hARatio + 1.0) / Deno; // calculate the NTU CSup = UnitSupMassFlow * PsyCpAirFnWTdb(ExchCond(ExNum).SupInHumRat, ExchCond(ExNum).SupInTemp); CSec = UnitSecMassFlow * PsyCpAirFnWTdb(ExchCond(ExNum).SecInHumRat, ExchCond(ExNum).SecInTemp); // note: no C can be zero since otherwise we wouldn't be here if (CSup < CSec) { CMin = CSup; Z = CMin / CSec; } else { CMin = CSec; Z = CMin / CSup; } NTU = UA / CMin; // Get the effectiveness CalculateEpsFromNTUandZ(NTU, Z, ExchCond(ExNum).FlowArr, Eps); // use the effectiveness to calculate the unit outlet conditions TempSupOut = ExchCond(ExNum).SupInTemp + Eps * CMin / CSup * (ExchCond(ExNum).SecInTemp - ExchCond(ExNum).SupInTemp); QTrans = CSup * (TempSupOut - ExchCond(ExNum).SupInTemp); TempSecOut = ExchCond(ExNum).SecInTemp - QTrans / CSec; HumRatSupOut = ExchCond(ExNum).SupInHumRat; EnthSupOut = PsyHFnTdbW(TempSupOut, HumRatSupOut); // check for saturation in supply outlet TempSupOutSat = PsyTsatFnHPb(EnthSupOut, OutBaroPress); if (TempSupOutSat > TempSupOut) { TempSupOut = TempSupOutSat; HumRatSupOut = PsyWFnTdbH(TempSupOut, EnthSupOut); } HumRatSecOut = ExchCond(ExNum).SecInHumRat; EnthSecOut = PsyHFnTdbW(TempSecOut, HumRatSecOut); // check for saturation in secondary outlet TempSecOutSat = PsyTsatFnHPb(EnthSecOut, OutBaroPress); if (TempSecOutSat > TempSecOut) { TempSecOut = TempSecOutSat; HumRatSecOut = PsyWFnTdbH(TempSecOut, EnthSecOut); } // calculate outlet conditions by mixing bypass air stream with air that went through the // heat exchanger core. ExchCond(ExNum).SupOutEnth = (UnitSupMassFlow * EnthSupOut + SupBypassMassFlow * ExchCond(ExNum).SupInEnth) / ExchCond(ExNum).SupInMassFlow; ExchCond(ExNum).SupOutHumRat = (UnitSupMassFlow * HumRatSupOut + SupBypassMassFlow * ExchCond(ExNum).SupInHumRat) / ExchCond(ExNum).SupInMassFlow; ExchCond(ExNum).SupOutTemp = PsyTdbFnHW(ExchCond(ExNum).SupOutEnth, ExchCond(ExNum).SupOutHumRat); ExchCond(ExNum).SupOutMassFlow = ExchCond(ExNum).SupInMassFlow; ExchCond(ExNum).SecOutEnth = (UnitSecMassFlow * EnthSecOut + SecBypassMassFlow * ExchCond(ExNum).SecInEnth) / ExchCond(ExNum).SecInMassFlow; ExchCond(ExNum).SecOutHumRat = (UnitSecMassFlow * HumRatSecOut + SecBypassMassFlow * ExchCond(ExNum).SecInHumRat) / ExchCond(ExNum).SecInMassFlow; ExchCond(ExNum).SecOutTemp = PsyTdbFnHW(ExchCond(ExNum).SecOutEnth, ExchCond(ExNum).SecOutHumRat); ExchCond(ExNum).SecOutMassFlow = ExchCond(ExNum).SecInMassFlow; ElecCons = ExchCond(ExNum).NomElecPower; } else { // the unit is off. Pass through the air streams with no change ExchCond(ExNum).SupOutEnth = ExchCond(ExNum).SupInEnth; ExchCond(ExNum).SupOutHumRat = ExchCond(ExNum).SupInHumRat; ExchCond(ExNum).SupOutTemp = ExchCond(ExNum).SupInTemp; ExchCond(ExNum).SupOutMassFlow = ExchCond(ExNum).SupInMassFlow; ExchCond(ExNum).SecOutEnth = ExchCond(ExNum).SecInEnth; ExchCond(ExNum).SecOutHumRat = ExchCond(ExNum).SecInHumRat; ExchCond(ExNum).SecOutTemp = ExchCond(ExNum).SecInTemp; ExchCond(ExNum).SecOutMassFlow = ExchCond(ExNum).SecInMassFlow; } CSup = ExchCond(ExNum).SupInMassFlow * PsyCpAirFnWTdb(ExchCond(ExNum).SupInHumRat, ExchCond(ExNum).SupInTemp); SensHeatRecRate = CSup * (ExchCond(ExNum).SupOutTemp - ExchCond(ExNum).SupInTemp); TotHeatRecRate = ExchCond(ExNum).SupOutMassFlow * (ExchCond(ExNum).SupOutEnth - ExchCond(ExNum).SupInEnth); LatHeatRecRate = TotHeatRecRate - SensHeatRecRate; if (SensHeatRecRate > 0.0) { ExchCond(ExNum).SensHeatingRate = SensHeatRecRate; ExchCond(ExNum).SensCoolingRate = 0.0; } else { ExchCond(ExNum).SensHeatingRate = 0.0; ExchCond(ExNum).SensCoolingRate = std::abs(SensHeatRecRate); } if (LatHeatRecRate > 0.0) { ExchCond(ExNum).LatHeatingRate = LatHeatRecRate; ExchCond(ExNum).LatCoolingRate = 0.0; } else { ExchCond(ExNum).LatHeatingRate = 0.0; ExchCond(ExNum).LatCoolingRate = std::abs(LatHeatRecRate); } if (TotHeatRecRate > 0.0) { ExchCond(ExNum).TotHeatingRate = TotHeatRecRate; ExchCond(ExNum).TotCoolingRate = 0.0; } else { ExchCond(ExNum).TotHeatingRate = 0.0; ExchCond(ExNum).TotCoolingRate = std::abs(TotHeatRecRate); } ExchCond(ExNum).ElecUseRate = ElecCons; } void CalcAirToAirGenericHeatExch(int const ExNum, // number of the current heat exchanger being simulated bool const HXUnitOn, // flag to simulate heat exchanger heat recovery bool const FirstHVACIteration, // first HVAC iteration flag int const FanOpMode, // Supply air fan operating mode (1=cycling, 2=constant) Optional_bool_const EconomizerFlag, // economizer flag pass by air loop or OA sys Optional_bool_const HighHumCtrlFlag, // high humidity control flag passed by airloop or OA sys Optional<Real64 const> HXPartLoadRatio // ) { // SUBROUTINE INFORMATION: // AUTHOR Don Shirey // DATE WRITTEN February 2003 // MODIFIED R. Raustad - FSEC, Feb 2009 - added economizer flags // Both the economizer and high humidity control flags can disable the HX // RE-ENGINEERED Richard Raustad, June 2003 // PURPOSE OF THIS SUBROUTINE: // Calculate the outlet conditions for an air to air generic heat // exchanger given the inlet conditions. // METHODOLOGY EMPLOYED: // This is a standard heat exchanger effectiveness model. No geometrical input data // is needed. The model uses heat exchanger effectiveness performance data // to calculate the air temperature and humidity ratio of the leaving // supply and secondary air streams. Linear interpolation (or extrapolation) // is assumed to obtain heat exchanger effectiveness at off-rated conditions. // Economizer operation is allowed through the use of a Controller: Outside Air // object. // REFERENCES: // ARI Standard 1060-2001,Rating Air-to-Air Heat Exchangers for Energy Recovery Ventilation Equipment, www.ari.org // ASHRAE Standard 84, Method of Testing Air-To-Air Heat Exchangers, www.ashrae.org // U.S. Environmental Protection Agency software "SAVES" - // School Advanced Ventilation Engineering Software http://www.epa.gov/iaq/schooldesign/saves.html // USE STATEMENTS: using DataHVACGlobals::CycFanCycCoil; // Locals // SUBROUTINE ARGUMENT DEFINITIONS: // SUBROUTINE PARAMETER DEFINITIONS: Real64 const ErrorTol(0.001); // error tolerence // INTERFACE BLOCK SPECIFICATIONS: // na // DERIVED TYPE DEFINITIONS: // na // SUBROUTINE LOCAL VARIABLE DECLARATIONS: bool UnitOn; // unit on flag bool FrostControlFlag; // unit is in frost control mode when TRUE int SupOutNode; Real64 Error; // iteration loop error variable Real64 Iter; // iteration counter Real64 ControlFraction; // fraction of effectiveness when rotary HX speed or plate bypass modulation is used for // temperature control Real64 RhoSup; // supply air density at actual pressure, temperature and humidity conditions [kg/m3] Real64 RhoSec; // secondary air density at actual pressure, temperature and humidity conditions [kg/m3] Real64 RhoStd; // standard air density at actual pressure, 20C dry-bulb temp and 0.0 absolute humidity [kg/m3] Real64 CSup; // supply air heat capacity rate [W/K] Real64 CSec; // secondary air heat capacity rate [W/K] Real64 CMin; // minimum air heat capacity rate [W/K] Real64 QSensTrans; // sensible heat transferred by the heat exchanger [W] Real64 QTotTrans; // total heat (sensible + latent) transferred by the heat exchanger [W] Real64 TempSecOutSat; // secondary air outlet temperature at saturation (at EnthsSecOut) [C] Real64 HXSecAirVolFlowRate; // air volume flow rate of the secondary air stream through the heat exchanger [m3/sec] Real64 HXSupAirVolFlowRate; // air volume flow rate of the supply air stream through the heat exchanger [m3/sec] Real64 HXAvgAirVolFlowRate; // average air volume flow rate through the heat exchanger [m3/sec] Real64 HXAirVolFlowRatio; // ratio of avg actual air volume flow through HX to nominal HX air volume flow [-] Real64 HXTempSetPoint; // setpoint temperature at supply outlet node of HX when ControlToTemperatureSetPoint = Yes Real64 MassFlowSecIn; // secondary air mass flow rate at HX inlet // REAL(r64) :: MassFlowSecOut ! secondary air mass flow rate at HX outlet Real64 MassFlowSupIn; // supply air mass flow rate at HX inlet Real64 MassFlowSupOut; // supply air mass flow rate through HX core outlet Real64 MassFlowSupBypass; // supply air bypass mass flow rate around HX core Real64 TempSupIn; // supply side temperature of air entering HX Real64 TempSupOut; // supply side temperature of air leaving HX core Real64 HumRatSupIn; // supply side humidity ratio of air entering HX Real64 TempSecIn; // secondary side temperature of air entering HX Real64 SensHeatRecRate; // sensible heat recovery rate to supply air (heating +, cooling -) Real64 LatHeatRecRate; // latent heat recovery rate to supply air (heating [humidify] +, cooling [dehumidify] -) Real64 TotHeatRecRate; // total heat recovery rate to supply air (heating +, cooling -) bool EconomizerActiveFlag; // local representing the economizer status when PRESENT bool HighHumCtrlActiveFlag; // local representing high humidity control when PRESENT Real64 AirSidePLR; // Initialize local variables UnitOn = true; FrostControlFlag = false; QSensTrans = 0.0; QTotTrans = 0.0; ExchCond(ExNum).DefrostFraction = 0.0; ExchCond(ExNum).SensEffectiveness = 0.0; ExchCond(ExNum).LatEffectiveness = 0.0; ExchCond(ExNum).ElecUseRate = 0.0; ExchCond(ExNum).SupOutTemp = ExchCond(ExNum).SupInTemp; ExchCond(ExNum).SecOutTemp = ExchCond(ExNum).SecInTemp; ExchCond(ExNum).SupOutHumRat = ExchCond(ExNum).SupInHumRat; ExchCond(ExNum).SecOutHumRat = ExchCond(ExNum).SecInHumRat; ExchCond(ExNum).SupOutEnth = ExchCond(ExNum).SupInEnth; ExchCond(ExNum).SecOutEnth = ExchCond(ExNum).SecInEnth; SupOutNode = ExchCond(ExNum).SupOutletNode; HXTempSetPoint = Node(SupOutNode).TempSetPoint; if (present(EconomizerFlag)) { EconomizerActiveFlag = EconomizerFlag; } else { EconomizerActiveFlag = false; } if (present(HighHumCtrlFlag)) { HighHumCtrlActiveFlag = HighHumCtrlFlag; } else { HighHumCtrlActiveFlag = false; } // Determine mass flow through heat exchanger and mass flow being bypassed (only flat plate bypasses flow) if (((EconomizerActiveFlag || HighHumCtrlActiveFlag) && ExchCond(ExNum).EconoLockOut == EconoLockOut_Yes) && ExchCond(ExNum).ExchConfigNum == Plate) { ExchCond(ExNum).SupBypassMassFlow = ExchCond(ExNum).SupInMassFlow; ExchCond(ExNum).SupOutMassFlow = ExchCond(ExNum).SupInMassFlow; ExchCond(ExNum).SecBypassMassFlow = ExchCond(ExNum).SecInMassFlow; ExchCond(ExNum).SecOutMassFlow = ExchCond(ExNum).SecInMassFlow; } else { // No bypass mass flow ExchCond(ExNum).SupOutMassFlow = ExchCond(ExNum).SupInMassFlow; ExchCond(ExNum).SecOutMassFlow = ExchCond(ExNum).SecInMassFlow; ExchCond(ExNum).SupBypassMassFlow = 0.0; ExchCond(ExNum).SecBypassMassFlow = 0.0; } // Unit is scheduled OFF, so bypass heat exchange calcs if (GetCurrentScheduleValue(ExchCond(ExNum).SchedPtr) <= 0.0) UnitOn = false; //! Economizer is active, so bypass heat exchange calcs. This applies to both flat plate and rotary HX's if ((EconomizerActiveFlag || HighHumCtrlActiveFlag) && ExchCond(ExNum).EconoLockOut == EconoLockOut_Yes) { UnitOn = false; } // Determine if unit is ON or OFF based on air mass flow through the supply and secondary airstreams and operation flag if (ExchCond(ExNum).SupInMassFlow <= SmallMassFlow) UnitOn = false; if (ExchCond(ExNum).SecInMassFlow <= SmallMassFlow) UnitOn = false; if (!HXUnitOn) UnitOn = false; if (ExchCond(ExNum).NomSupAirVolFlow == 0.0) UnitOn = false; if (UnitOn) { // Unit is on. if (present(HXPartLoadRatio) && FanOpMode == DataHVACGlobals::CycFanCycCoil) { if (HXPartLoadRatio > 0) { AirSidePLR = HXPartLoadRatio; } else { AirSidePLR = 1.0; } } else { AirSidePLR = 1.0; } if (FanOpMode == DataHVACGlobals::CycFanCycCoil) { ExchCond(ExNum).SupInMassFlow /= AirSidePLR; ExchCond(ExNum).SupOutMassFlow /= AirSidePLR; ExchCond(ExNum).SecInMassFlow /= AirSidePLR; ExchCond(ExNum).SecOutMassFlow /= AirSidePLR; ExchCond(ExNum).SupBypassMassFlow /= AirSidePLR; ExchCond(ExNum).SecBypassMassFlow /= AirSidePLR; } // In the future, use actual node pressures in the following air density calls RhoStd = PsyRhoAirFnPbTdbW(OutBaroPress, 20.0, 0.0); HXSupAirVolFlowRate = ExchCond(ExNum).SupOutMassFlow / RhoStd; // volume flow using standard density HXSecAirVolFlowRate = ExchCond(ExNum).SecOutMassFlow / RhoStd; // Limit unbalanced volumetric flow ratio to 2:1 if (!WarmupFlag && !FirstHVACIteration) { if (HXSupAirVolFlowRate != 0.0 && HXSecAirVolFlowRate != 0.0) { if (((HXSupAirVolFlowRate / HXSecAirVolFlowRate) > 2.0) || ((HXSecAirVolFlowRate / HXSupAirVolFlowRate) > 2.0)) { ++ExchCond(ExNum).UnBalancedErrCount; if (ExchCond(ExNum).UnBalancedErrCount <= 2) { ShowSevereError(cHXTypes(ExchCond(ExNum).ExchTypeNum) + ": \"" + ExchCond(ExNum).Name + "\" unbalanced air volume flow ratio through the heat exchanger is greater than 2:1."); ShowContinueErrorTimeStamp( "...HX Supply air to Exhaust air flow ratio = " + RoundSigDigits(HXSupAirVolFlowRate / HXSecAirVolFlowRate, 5) + '.'); } else { ShowRecurringWarningErrorAtEnd( cHXTypes(ExchCond(ExNum).ExchTypeNum) + " \"" + ExchCond(ExNum).Name + "\": Unbalanced air volume flow ratio exceeds 2:1 warning continues. HX flow ratio statistics follow.", ExchCond(ExNum).UnBalancedErrIndex, HXSupAirVolFlowRate / HXSecAirVolFlowRate, HXSupAirVolFlowRate / HXSecAirVolFlowRate); } } } } // Calculate average volumetric flow rate of the two air streams HXAvgAirVolFlowRate = (HXSecAirVolFlowRate + HXSupAirVolFlowRate) / 2.0; HXAirVolFlowRatio = HXAvgAirVolFlowRate / ExchCond(ExNum).NomSupAirVolFlow; // Average air volume flow rate must be between 50% and 130% of nominal supply air volume flow if (HXAirVolFlowRatio > 1.3 || HXAirVolFlowRatio < 0.5) { if (!WarmupFlag && !FirstHVACIteration) { ++ExchCond(ExNum).LowFlowErrCount; if (ExchCond(ExNum).LowFlowErrCount == 1) { ShowWarningError(cHXTypes(ExchCond(ExNum).ExchTypeNum) + " \"" + ExchCond(ExNum).Name + "\""); ShowContinueError("Average air volume flow rate is <50% or >130% of the nominal HX supply air volume flow rate."); ShowContinueErrorTimeStamp("Air volume flow rate ratio = " + RoundSigDigits(HXAirVolFlowRatio, 3) + '.'); } else { ShowRecurringWarningErrorAtEnd( cHXTypes(ExchCond(ExNum).ExchTypeNum) + " \"" + ExchCond(ExNum).Name + "\": Average air volume flow rate is <50% or >130% warning continues. Air flow rate ratio statistics follow.", ExchCond(ExNum).LowFlowErrIndex, HXAirVolFlowRatio, HXAirVolFlowRatio); } } } // Determine heat exchanger effectiveness using avg air volume flow rate based on actual inlet air density // Linearly interpolate and extrapolate (within limits) from effectiveness input values RhoSup = PsyRhoAirFnPbTdbW(OutBaroPress, ExchCond(ExNum).SupInTemp, ExchCond(ExNum).SupInHumRat); RhoSec = PsyRhoAirFnPbTdbW(OutBaroPress, ExchCond(ExNum).SecInTemp, ExchCond(ExNum).SecInHumRat); HXSupAirVolFlowRate = ExchCond(ExNum).SupOutMassFlow / RhoSup; HXSecAirVolFlowRate = ExchCond(ExNum).SecOutMassFlow / RhoSec; HXAvgAirVolFlowRate = (HXSecAirVolFlowRate + HXSupAirVolFlowRate) / 2.0; HXAirVolFlowRatio = HXAvgAirVolFlowRate / ExchCond(ExNum).NomSupAirVolFlow; if (ExchCond(ExNum).SupInTemp < ExchCond(ExNum).SecInTemp) { // Use heating effectiveness values ExchCond(ExNum).SensEffectiveness = ExchCond(ExNum).HeatEffectSensible75 + (ExchCond(ExNum).HeatEffectSensible100 - ExchCond(ExNum).HeatEffectSensible75) * (HXAirVolFlowRatio - 0.75) / (1.0 - 0.75); ExchCond(ExNum).LatEffectiveness = ExchCond(ExNum).HeatEffectLatent75 + (ExchCond(ExNum).HeatEffectLatent100 - ExchCond(ExNum).HeatEffectLatent75) * (HXAirVolFlowRatio - 0.75) / (1.0 - 0.75); } else { // Use cooling effectiveness values ExchCond(ExNum).SensEffectiveness = ExchCond(ExNum).CoolEffectSensible75 + (ExchCond(ExNum).CoolEffectSensible100 - ExchCond(ExNum).CoolEffectSensible75) * (HXAirVolFlowRatio - 0.75) / (1.0 - 0.75); ExchCond(ExNum).LatEffectiveness = ExchCond(ExNum).CoolEffectLatent75 + (ExchCond(ExNum).CoolEffectLatent100 - ExchCond(ExNum).CoolEffectLatent75) * (HXAirVolFlowRatio - 0.75) / (1.0 - 0.75); } // Keep effectiveness between 0 and 1.0 ?? // HXOpSensEffect = MAX(MIN(HXOpSensEffect,1.0),0.0) // HXOpLatEffect = MAX(MIN(HXOpLatEffect,1.0),0.0) // The model should at least guard against negative numbers ExchCond(ExNum).SensEffectiveness = max(0.0, ExchCond(ExNum).SensEffectiveness); ExchCond(ExNum).LatEffectiveness = max(0.0, ExchCond(ExNum).LatEffectiveness); // Use the effectiveness to calculate the air conditions exiting the heat exchanger (all air flow through the HX) // Include EATR and OACF in the following calculations at some point CSup = ExchCond(ExNum).SupOutMassFlow * PsyCpAirFnWTdb(ExchCond(ExNum).SupInHumRat, ExchCond(ExNum).SupInTemp); CSec = ExchCond(ExNum).SecOutMassFlow * PsyCpAirFnWTdb(ExchCond(ExNum).SecInHumRat, ExchCond(ExNum).SecInTemp); CMin = min(CSup, CSec); ExchCond(ExNum).SupOutTemp = ExchCond(ExNum).SupInTemp + ExchCond(ExNum).SensEffectiveness * CMin / CSup * (ExchCond(ExNum).SecInTemp - ExchCond(ExNum).SupInTemp); ExchCond(ExNum).SupOutHumRat = ExchCond(ExNum).SupInHumRat + ExchCond(ExNum).LatEffectiveness * CMin / CSup * (ExchCond(ExNum).SecInHumRat - ExchCond(ExNum).SupInHumRat); ExchCond(ExNum).SupOutEnth = PsyHFnTdbW(ExchCond(ExNum).SupOutTemp, ExchCond(ExNum).SupOutHumRat); // Check for saturation in supply outlet and reset temp, then humidity ratio at constant enthalpy if (PsyTsatFnHPb(ExchCond(ExNum).SupOutEnth, OutBaroPress) > ExchCond(ExNum).SupOutTemp) { ExchCond(ExNum).SupOutTemp = PsyTsatFnHPb(ExchCond(ExNum).SupOutEnth, OutBaroPress); ExchCond(ExNum).SupOutHumRat = PsyWFnTdbH(ExchCond(ExNum).SupOutTemp, ExchCond(ExNum).SupOutEnth); } QSensTrans = CSup * (ExchCond(ExNum).SupInTemp - ExchCond(ExNum).SupOutTemp); ExchCond(ExNum).SecOutTemp = ExchCond(ExNum).SecInTemp + QSensTrans / CSec; QTotTrans = ExchCond(ExNum).SupOutMassFlow * (ExchCond(ExNum).SupInEnth - ExchCond(ExNum).SupOutEnth); ExchCond(ExNum).SecOutEnth = ExchCond(ExNum).SecInEnth + QTotTrans / ExchCond(ExNum).SecOutMassFlow; ExchCond(ExNum).SecOutHumRat = PsyWFnTdbH(ExchCond(ExNum).SecOutTemp, ExchCond(ExNum).SecOutEnth); // Control the supply air outlet temperature to a setpoint for Heating Mode only // (ControlFraction = 0 HX fully bypassed, ControlFraction = 1 air passed entirely through HX) // (supply air stream bypass mass flow rate proportional to ControlFraction except when frost control is active) if (ExchCond(ExNum).ControlToTemperatureSetPoint) { if ((ExchCond(ExNum).SupInTemp - ExchCond(ExNum).SupOutTemp) != 0.0) { if ((ExchCond(ExNum).SupInTemp < HXTempSetPoint && ExchCond(ExNum).SupOutTemp > HXTempSetPoint) || (ExchCond(ExNum).SupInTemp > HXTempSetPoint && ExchCond(ExNum).SupOutTemp < HXTempSetPoint)) { ControlFraction = max( 0.0, min(1.0, std::abs((ExchCond(ExNum).SupInTemp - HXTempSetPoint) / (ExchCond(ExNum).SupInTemp - ExchCond(ExNum).SupOutTemp)))); } else if ((ExchCond(ExNum).SupInTemp < ExchCond(ExNum).SupOutTemp && ExchCond(ExNum).SupOutTemp < HXTempSetPoint) || (ExchCond(ExNum).SupInTemp > ExchCond(ExNum).SupOutTemp && ExchCond(ExNum).SupOutTemp > HXTempSetPoint)) { ControlFraction = 1.0; } else { ControlFraction = 0.0; } } else { // ELSE fully bypass HX to maintain supply outlet temp as high as possible ControlFraction = 0.0; } if (ExchCond(ExNum).ExchConfigNum == Rotary) { // Rotory HX's never get bypassed, rotational speed is modulated ExchCond(ExNum).SensEffectiveness *= ControlFraction; ExchCond(ExNum).LatEffectiveness *= ControlFraction; } else { // HX is a plate heat exchanger, bypass air to control SA temperature Error = 1.0; Iter = 0.0; MassFlowSupIn = ExchCond(ExNum).SupInMassFlow; MassFlowSupOut = ExchCond(ExNum).SupOutMassFlow; MassFlowSupBypass = ExchCond(ExNum).SupBypassMassFlow; MassFlowSecIn = ExchCond(ExNum).SecInMassFlow; TempSupIn = ExchCond(ExNum).SupInTemp; TempSupOut = ExchCond(ExNum).SupOutTemp; HumRatSupIn = ExchCond(ExNum).SupInHumRat; TempSecIn = ExchCond(ExNum).SecInTemp; while ((std::abs(Error) > ErrorTol && Iter < 10 && ControlFraction < 1.0) || Iter == 1) { MassFlowSupOut = MassFlowSupIn * ControlFraction; MassFlowSupBypass = MassFlowSupIn * (1.0 - ControlFraction); HXSupAirVolFlowRate = MassFlowSupOut / RhoSup; HXAvgAirVolFlowRate = (HXSecAirVolFlowRate + HXSupAirVolFlowRate) / 2.0; HXAirVolFlowRatio = HXAvgAirVolFlowRate / ExchCond(ExNum).NomSupAirVolFlow; CSup = MassFlowSupOut * PsyCpAirFnWTdb(HumRatSupIn, TempSupIn); CMin = min(CSup, CSec); if (TempSupIn < TempSecIn) { // Use heating effectiveness values ExchCond(ExNum).SensEffectiveness = ExchCond(ExNum).HeatEffectSensible75 + (ExchCond(ExNum).HeatEffectSensible100 - ExchCond(ExNum).HeatEffectSensible75) * (HXAirVolFlowRatio - 0.75) / (1.0 - 0.75); ExchCond(ExNum).LatEffectiveness = ExchCond(ExNum).HeatEffectLatent75 + (ExchCond(ExNum).HeatEffectLatent100 - ExchCond(ExNum).HeatEffectLatent75) * (HXAirVolFlowRatio - 0.75) / (1.0 - 0.75); } else { // Use cooling effectiveness values ExchCond(ExNum).SensEffectiveness = ExchCond(ExNum).CoolEffectSensible75 + (ExchCond(ExNum).CoolEffectSensible100 - ExchCond(ExNum).CoolEffectSensible75) * (HXAirVolFlowRatio - 0.75) / (1.0 - 0.75); ExchCond(ExNum).LatEffectiveness = ExchCond(ExNum).CoolEffectLatent75 + (ExchCond(ExNum).CoolEffectLatent100 - ExchCond(ExNum).CoolEffectLatent75) * (HXAirVolFlowRatio - 0.75) / (1.0 - 0.75); } if (CSup == 0.0) { // IF CSup = 0, then supply air mass flow rate = 0 and HX is fully bypassed. Fix divide by 0 error below DO loop. CSup = 1.0; CMin = 0.0; break; } TempSupOut = (MassFlowSupOut * (TempSupIn + ExchCond(ExNum).SensEffectiveness * CMin / CSup * (TempSecIn - TempSupIn)) + MassFlowSupBypass * TempSupIn) / MassFlowSupIn; Error = (TempSupOut - HXTempSetPoint); // IF supply inlet temp = supply outlet temp, fully bypass HX - ELSE control to SP if (TempSupIn != TempSupOut) { ControlFraction = max(0.0, min(1.0, std::abs(ControlFraction * (TempSupIn - HXTempSetPoint) / (TempSupIn - TempSupOut)))); } else if (std::abs(TempSupOut - HXTempSetPoint) < ErrorTol) { // IF TempSupIn = TempSupOut then TempSecIn = TempSupIn (ControlFraction = ?) // Do nothing, variables in ELSE below have already been calculated break; } else { // or HX is fully bypassed (ControlFraction = 0) which actually should be caught in IF(CSup .EQ. 0.0)THEN above. ControlFraction = 0.0; MassFlowSupOut = MassFlowSupIn * ControlFraction; MassFlowSupBypass = MassFlowSupIn * (1.0 - ControlFraction); CSup = 1.0; CMin = 0.0; break; } ++Iter; } ExchCond(ExNum).SupInMassFlow = MassFlowSupIn; ExchCond(ExNum).SupOutMassFlow = MassFlowSupOut; ExchCond(ExNum).SupBypassMassFlow = MassFlowSupBypass; ExchCond(ExNum).SecInMassFlow = MassFlowSecIn; ExchCond(ExNum).SupInTemp = TempSupIn; ExchCond(ExNum).SupOutTemp = TempSupOut; ExchCond(ExNum).SupInHumRat = HumRatSupIn; ExchCond(ExNum).SecInTemp = TempSecIn; } // ENDIF for "IF (ExchCond(ExNum)%ExchConfig == 'ROTARY') THEN" ExchCond(ExNum).SupOutTemp = ExchCond(ExNum).SupInTemp + ExchCond(ExNum).SensEffectiveness * CMin / CSup * (ExchCond(ExNum).SecInTemp - ExchCond(ExNum).SupInTemp); ExchCond(ExNum).SupOutHumRat = ExchCond(ExNum).SupInHumRat + ExchCond(ExNum).LatEffectiveness * CMin / CSup * (ExchCond(ExNum).SecInHumRat - ExchCond(ExNum).SupInHumRat); ExchCond(ExNum).SupOutEnth = PsyHFnTdbW(ExchCond(ExNum).SupOutTemp, ExchCond(ExNum).SupOutHumRat); // Check for saturation in supply outlet and reset temp, then humidity ratio at constant enthalpy if (PsyTsatFnHPb(ExchCond(ExNum).SupOutEnth, OutBaroPress) > ExchCond(ExNum).SupOutTemp) { ExchCond(ExNum).SupOutTemp = PsyTsatFnHPb(ExchCond(ExNum).SupOutEnth, OutBaroPress); ExchCond(ExNum).SupOutHumRat = PsyWFnTdbH(ExchCond(ExNum).SupOutTemp, ExchCond(ExNum).SupOutEnth); } QSensTrans = CSup * (ExchCond(ExNum).SupInTemp - ExchCond(ExNum).SupOutTemp); ExchCond(ExNum).SecOutTemp = ExchCond(ExNum).SecInTemp + QSensTrans / CSec; QTotTrans = ExchCond(ExNum).SupOutMassFlow * (ExchCond(ExNum).SupInEnth - ExchCond(ExNum).SupOutEnth); ExchCond(ExNum).SecOutEnth = ExchCond(ExNum).SecInEnth + QTotTrans / ExchCond(ExNum).SecOutMassFlow; ExchCond(ExNum).SecOutHumRat = PsyWFnTdbH(ExchCond(ExNum).SecOutTemp, ExchCond(ExNum).SecOutEnth); } // ENDIF for "IF(ExchCond(ExNum)%ControlToTemperatureSetPoint .AND... THEN, ELSE" if (FanOpMode == DataHVACGlobals::CycFanCycCoil) { ExchCond(ExNum).SupInMassFlow *= AirSidePLR; ExchCond(ExNum).SupOutMassFlow *= AirSidePLR; ExchCond(ExNum).SecInMassFlow *= AirSidePLR; ExchCond(ExNum).SecOutMassFlow *= AirSidePLR; ExchCond(ExNum).SupBypassMassFlow *= AirSidePLR; ExchCond(ExNum).SecBypassMassFlow *= AirSidePLR; } else if (FanOpMode == DataHVACGlobals::ContFanCycCoil) { ExchCond(ExNum).SupOutTemp = ExchCond(ExNum).SupOutTemp * AirSidePLR + ExchCond(ExNum).SupInTemp * (1.0 - AirSidePLR); ExchCond(ExNum).SupOutHumRat = ExchCond(ExNum).SupOutHumRat * AirSidePLR + ExchCond(ExNum).SupInHumRat * (1.0 - AirSidePLR); ExchCond(ExNum).SupOutEnth = ExchCond(ExNum).SupOutEnth * AirSidePLR + ExchCond(ExNum).SupOutEnth * (1.0 - AirSidePLR); ExchCond(ExNum).SecOutTemp = ExchCond(ExNum).SecOutTemp * AirSidePLR + ExchCond(ExNum).SecInTemp * (1.0 - AirSidePLR); ExchCond(ExNum).SecOutHumRat = ExchCond(ExNum).SecOutHumRat * AirSidePLR + ExchCond(ExNum).SecInHumRat * (1.0 - AirSidePLR); ExchCond(ExNum).SecOutEnth = ExchCond(ExNum).SecOutEnth * AirSidePLR + ExchCond(ExNum).SecOutEnth * (1.0 - AirSidePLR); } if ((ExchCond(ExNum).FrostControlType == "MINIMUMEXHAUSTTEMPERATURE" && ExchCond(ExNum).SecOutTemp < ExchCond(ExNum).ThresholdTemperature) || (ExchCond(ExNum).FrostControlType == "EXHAUSTAIRRECIRCULATION" && ExchCond(ExNum).SupInTemp <= ExchCond(ExNum).ThresholdTemperature) || (ExchCond(ExNum).FrostControlType == "EXHAUSTONLY" && ExchCond(ExNum).SupInTemp <= ExchCond(ExNum).ThresholdTemperature)) { FrostControl(ExNum); FrostControlFlag = true; } // check for saturation in secondary outlet TempSecOutSat = PsyTsatFnHPb(ExchCond(ExNum).SecOutEnth, OutBaroPress); if (TempSecOutSat > ExchCond(ExNum).SecOutTemp) { ExchCond(ExNum).SecOutTemp = TempSecOutSat; ExchCond(ExNum).SecOutHumRat = PsyWFnTdbH(ExchCond(ExNum).SecOutTemp, ExchCond(ExNum).SecOutEnth); } // calculate outlet conditions by mixing bypass air stream with air that went through the // heat exchanger core. Perform this mixing only when no frost control is used or // heat exchanger is not in frost control mode. Mixing similar to this is performed // in the frost control subroutine when in frost control mode. if (!FrostControlFlag) { ExchCond(ExNum).SupOutEnth = (ExchCond(ExNum).SupOutMassFlow * ExchCond(ExNum).SupOutEnth + ExchCond(ExNum).SupBypassMassFlow * ExchCond(ExNum).SupInEnth) / ExchCond(ExNum).SupInMassFlow; ExchCond(ExNum).SupOutHumRat = (ExchCond(ExNum).SupOutMassFlow * ExchCond(ExNum).SupOutHumRat + ExchCond(ExNum).SupBypassMassFlow * ExchCond(ExNum).SupInHumRat) / ExchCond(ExNum).SupInMassFlow; ExchCond(ExNum).SupOutTemp = PsyTdbFnHW(ExchCond(ExNum).SupOutEnth, ExchCond(ExNum).SupOutHumRat); ExchCond(ExNum).SupOutMassFlow = ExchCond(ExNum).SupInMassFlow; ExchCond(ExNum).SecOutEnth = (ExchCond(ExNum).SecOutMassFlow * ExchCond(ExNum).SecOutEnth + ExchCond(ExNum).SecBypassMassFlow * ExchCond(ExNum).SecInEnth) / ExchCond(ExNum).SecInMassFlow; ExchCond(ExNum).SecOutHumRat = (ExchCond(ExNum).SecOutMassFlow * ExchCond(ExNum).SecOutHumRat + ExchCond(ExNum).SecBypassMassFlow * ExchCond(ExNum).SecInHumRat) / ExchCond(ExNum).SecInMassFlow; ExchCond(ExNum).SecOutTemp = PsyTdbFnHW(ExchCond(ExNum).SecOutEnth, ExchCond(ExNum).SecOutHumRat); ExchCond(ExNum).SecOutMassFlow = ExchCond(ExNum).SecInMassFlow; } ExchCond(ExNum).ElecUseRate = ExchCond(ExNum).NomElecPower; } // ENDIF for "IF (UnitOn) THEN" // Calculate heat transfer from the unit using the final supply inlet and supply outlet air conditions CSup = ExchCond(ExNum).SupOutMassFlow * PsyCpAirFnWTdb(ExchCond(ExNum).SupInHumRat, ExchCond(ExNum).SupInTemp); SensHeatRecRate = CSup * (ExchCond(ExNum).SupOutTemp - ExchCond(ExNum).SupInTemp); TotHeatRecRate = ExchCond(ExNum).SupOutMassFlow * (ExchCond(ExNum).SupOutEnth - ExchCond(ExNum).SupInEnth); LatHeatRecRate = TotHeatRecRate - SensHeatRecRate; // Set report variables based on sign of recovery rate if (SensHeatRecRate > 0.0) { ExchCond(ExNum).SensHeatingRate = SensHeatRecRate; ExchCond(ExNum).SensCoolingRate = 0.0; } else { ExchCond(ExNum).SensHeatingRate = 0.0; ExchCond(ExNum).SensCoolingRate = std::abs(SensHeatRecRate); } if (LatHeatRecRate > 0.0) { ExchCond(ExNum).LatHeatingRate = LatHeatRecRate; ExchCond(ExNum).LatCoolingRate = 0.0; } else { ExchCond(ExNum).LatHeatingRate = 0.0; ExchCond(ExNum).LatCoolingRate = std::abs(LatHeatRecRate); } if (TotHeatRecRate > 0.0) { ExchCond(ExNum).TotHeatingRate = TotHeatRecRate; ExchCond(ExNum).TotCoolingRate = 0.0; } else { ExchCond(ExNum).TotHeatingRate = 0.0; ExchCond(ExNum).TotCoolingRate = std::abs(TotHeatRecRate); } } void CalcDesiccantBalancedHeatExch(int const ExNum, // number of the current heat exchanger being simulated bool const HXUnitOn, // flag to simulate heat exchager heat recovery bool const FirstHVACIteration, // First HVAC iteration flag int const FanOpMode, // Supply air fan operating mode (1=cycling, 2=constant) Real64 const PartLoadRatio, // Part load ratio requested of DX compressor int const CompanionCoilIndex, // index of companion cooling coil bool const RegenInletIsOANode, // Flag to determine if regen side inlet is OANode, if so this air stream cycles Optional_bool_const EconomizerFlag, // economizer flag pass by air loop or OA sys Optional_bool_const HighHumCtrlFlag // high humidity control flag passed by airloop or OA sys ) { // SUBROUTINE INFORMATION: // AUTHOR Mangesh Basarkar, FSEC // DATE WRITTEN January 2007 // MODIFIED R. Raustad - FSEC, Feb 2009 - added economizer flags // Both the economizer and high humidity control flags can disable the HX // RE-ENGINEERED na // PURPOSE OF THIS SUBROUTINE: // Calculate the outlet conditions for a balanced air-to-air desiccant heat exchanger // given the inlet conditions and face velocity. Performance map is provided by user. // METHODOLOGY EMPLOYED: // This is an empirical heat exchanger model. The model uses heat exchanger performance data to // calculate the air temperature and humidity ratio of the leaving upply and secondary air streams. // Humidity control can enable/disable heat recovery through the use of the HXUnitOn Subroutine argument. // REFERENCES: // na // Using/Aliasing using DataLoopNode::SensedNodeFlagValue; using DXCoils::DXCoilPartLoadRatio; // Locals // SUBROUTINE ARGUMENT DEFINITIONS: // SUBROUTINE PARAMETER DEFINITIONS: // INTERFACE BLOCK SPECIFICATIONS: // na // DERIVED TYPE DEFINITIONS: // na // SUBROUTINE LOCAL VARIABLE DECLARATIONS: bool UnitOn; // unit on flag Real64 RhoStd; // standard air density at actual pressure, 20C dry-bulb temp and 0.0 absolute humidity [kg/m3] Real64 CSup; // supply air heat capacity rate [W/K] Real64 CSec; // secondary air heat capacity rate [W/K] Real64 TempSecOutSat; // secondary air outlet temperature at saturation (at EnthsSecOut) [C] Real64 SensHeatRecRate; // sensible heat recovery rate to supply air (heating +, cooling -) Real64 TotHeatRecRate; // total heat recovery rate to supply air (heating +, cooling -) Real64 ProcessSensHeatRecRate; // process sensible heat recovery rate (heating +, cooling -) Real64 ProcessTotHeatRecRate; // process total heat recovery rate (heating +, cooling -) Real64 ProcessLatHeatRecRate; // process latent heat recovery rate (heating [humidify] +, cooling [dehumidify] -) Real64 SupInMassFlow; // Supply side HX mass flow rate Real64 SecInMassFlow; // Secondary side HX mass flow rate Real64 Coeff1; // coefficient1 to empirical model (used for both temperature and humidity ratio equations) Real64 Coeff2; // coefficient2 to empirical model (used for both temperature and humidity ratio equations) Real64 Coeff3; // coefficient3 to empirical model (used for both temperature and humidity ratio equations) Real64 Coeff4; // coefficient4 to empirical model (used for both temperature and humidity ratio equations) Real64 Coeff5; // coefficient5 to empirical model (used for both temperature and humidity ratio equations) Real64 Coeff6; // coefficient6 to empirical model (used for both temperature and humidity ratio equations) Real64 Coeff7; // coefficient7 to empirical model (used for both temperature and humidity ratio equations) Real64 Coeff8; // coefficient8 to empirical model (used for both temperature and humidity ratio equations) Real64 BalFaceVelActual; // operating face velocity [m/s] Real64 FullLoadSupOutTemp(0); // empirical model supply outlet temperature [C] Real64 FullLoadSupOutHumRat(0); // empirical model supply outlet humidity ratio [kg/kg] Real64 FullLoadDeltaT; // empirical model heat exchanger delta temperature [C] Real64 FullLoadDeltaW; // empirical model heat exchanger delta humidity ratio [kg/kg] Real64 T_RegenInTemp; // empirical model supply (regen) inlet temperature for temperature equation [C] Real64 T_RegenInHumRat; // empirical model supply (regen) inlet humidity ratio for temperature equation [kg/kg] Real64 T_ProcInTemp; // empirical model secondary (process) inlet temperature for temperature equation [C] Real64 T_ProcInHumRat; // empirical model secondary (process) inlet humidity ratio for temperature equation [kg/kg] Real64 T_FaceVel; // empirical model face velocity for temperature equation [m/s] Real64 H_RegenInTemp; // empirical model supply (regen) inlet temperature for humidity ratio equation [C] Real64 H_RegenInHumRat; // empirical model supply (regen) inlet humidity ratio for humidity ratio equation [kg/kg] Real64 H_ProcInTemp; // empirical model secondary (process) inlet temperature for humidity ratio equation [C] Real64 H_ProcInHumRat; // empirical model secondary (process) inlet humidity ratio for humidity ratio equation [kg/kg] Real64 H_FaceVel; // empirical model face velocity for humidity ratio equation [m/s] Real64 MaxHumRatNeeded; // maximum humidity ratio setpoint for balanced desiccant HX [kg/kg] Real64 MinHumRatNeeded; // minimum humidity ratio setpoint for balanced desiccant HX [kg/kg] Real64 HXPartLoadRatio; // local heat exchanger part-load ratio Real64 TestSaturationEnthalpy; // enthalpy used to test for regeneration outlet condition over saturation curve (J/kg) static std::string const ThisSub("CalcDesiccantBalancedHeatExch: "); // Used to pass to Psyc routines static std::string const ThisSubTSat("CalcDesiccantBalancedHeatExch: TSat"); static std::string const ThisSubTSatFullLoadOutTemp("CalcDesiccantBalancedHeatExch: TSat-FullLoadOutTemp"); static std::string const ThisSubTSatFullLoadOutHumRat("CalcDesiccantBalancedHeatExch: TSat-FullLoadOutHumRat"); static std::string const ThisSubSecOutHumRat("CalcDesiccantBalancedHeatExch: SecOutHumRat"); static std::string const ThisSubTestSatSec("CalcDesiccantBalancedHeatExch: TestSatSec"); static std::string const ThisSubTSatSecOutHumRat("CalcDesiccantBalancedHeatExch: TSat-SecOutHumRat"); Real64 AverageMassFlowRate; // average of supply (regen) and secondary (process) mass flow rates [kg/s] bool EconomizerActiveFlag; // local representing the economizer status when PRESENT bool HighHumCtrlActiveFlag; // local representing high humidity control when PRESENT // Initialize local variables UnitOn = true; SensHeatRecRate = 0.0; TotHeatRecRate = 0.0; HXPartLoadRatio = PartLoadRatio; ExchCond(ExNum).DefrostFraction = 0.0; ExchCond(ExNum).ElecUseRate = 0.0; ExchCond(ExNum).SupOutTemp = ExchCond(ExNum).SupInTemp; ExchCond(ExNum).SecOutTemp = ExchCond(ExNum).SecInTemp; ExchCond(ExNum).SupOutHumRat = ExchCond(ExNum).SupInHumRat; ExchCond(ExNum).SecOutHumRat = ExchCond(ExNum).SecInHumRat; ExchCond(ExNum).SupOutEnth = ExchCond(ExNum).SupInEnth; ExchCond(ExNum).SecOutEnth = ExchCond(ExNum).SecInEnth; ExchCond(ExNum).SupOutMassFlow = ExchCond(ExNum).SupInMassFlow; ExchCond(ExNum).SecOutMassFlow = ExchCond(ExNum).SecInMassFlow; AverageMassFlowRate = (ExchCond(ExNum).SupOutMassFlow + ExchCond(ExNum).SecOutMassFlow) / 2.0; if (present(EconomizerFlag)) { EconomizerActiveFlag = EconomizerFlag; } else { EconomizerActiveFlag = false; } if (present(HighHumCtrlFlag)) { HighHumCtrlActiveFlag = HighHumCtrlFlag; } else { HighHumCtrlActiveFlag = false; } // Unit is scheduled OFF, so bypass heat exchange calcs if (GetCurrentScheduleValue(ExchCond(ExNum).SchedPtr) <= 0.0) UnitOn = false; // Determine if unit is ON or OFF based on air mass flow through the supply and secondary airstreams and operation flag if (ExchCond(ExNum).SupInMassFlow <= SmallMassFlow) UnitOn = false; if (ExchCond(ExNum).SecInMassFlow <= SmallMassFlow) UnitOn = false; if (HXPartLoadRatio == 0.0) UnitOn = false; if (!HXUnitOn) UnitOn = false; if ((EconomizerActiveFlag || HighHumCtrlActiveFlag) && ExchCond(ExNum).EconoLockOut == EconoLockOut_Yes) UnitOn = false; if (UnitOn) { // Use local variables to perform checks SecInMassFlow = ExchCond(ExNum).SecInMassFlow; SupInMassFlow = ExchCond(ExNum).SupInMassFlow; // In constant fan mode, process air mass flow rate is full flow and supply (regen) air cycles based on PLR. // If supply (regen) inlet is OA node, regen mass flow rate is proportional to PLR. // If both of the above is true then boost local variable up to full flow if ((FanOpMode == ContFanCycCoil) && RegenInletIsOANode) { SupInMassFlow /= HXPartLoadRatio; } // for cycling fan case, boost both local variables up to full flow if (FanOpMode == CycFanCycCoil) { SupInMassFlow /= HXPartLoadRatio; // supply = regen SecInMassFlow /= HXPartLoadRatio; // secondary = process } // Check for balanced flow condition CheckForBalancedFlow(ExNum, SecInMassFlow, SupInMassFlow, FirstHVACIteration); { auto const SELECT_CASE_var(ExchCond(ExNum).HeatExchPerfTypeNum); if (SELECT_CASE_var == BALANCEDHX_PERFDATATYPE1) { Coeff1 = BalDesDehumPerfData(ExchCond(ExNum).PerfDataIndex).B1; Coeff2 = BalDesDehumPerfData(ExchCond(ExNum).PerfDataIndex).B2; Coeff3 = BalDesDehumPerfData(ExchCond(ExNum).PerfDataIndex).B3; Coeff4 = BalDesDehumPerfData(ExchCond(ExNum).PerfDataIndex).B4; Coeff5 = BalDesDehumPerfData(ExchCond(ExNum).PerfDataIndex).B5; Coeff6 = BalDesDehumPerfData(ExchCond(ExNum).PerfDataIndex).B6; Coeff7 = BalDesDehumPerfData(ExchCond(ExNum).PerfDataIndex).B7; Coeff8 = BalDesDehumPerfData(ExchCond(ExNum).PerfDataIndex).B8; T_ProcInTemp = FullLoadOutAirTemp; T_ProcInHumRat = FullLoadOutAirHumRat; T_RegenInTemp = ExchCond(ExNum).SupInTemp; T_RegenInHumRat = ExchCond(ExNum).SupInHumRat; // Must use the same density used to convert volumetric flow rate to mass flow rate to get back to velocity RhoStd = StdRhoAir; // PsyRhoAirFnPbTdbW(StdBaroPress,20.0d0, 0.0d0) BalFaceVelActual = SupInMassFlow / (RhoStd * ExchCond(ExNum).FaceArea); T_FaceVel = BalFaceVelActual; // Call model check routines only when HX is active, if coil is off these checks do not apply (no potential for heat transfer) // Check RH limits and warn user if out of bounds (T_* not modified in subroutine) CheckModelBoundsRH_TempEq(ExNum, T_RegenInTemp, T_RegenInHumRat, T_ProcInTemp, T_ProcInHumRat, FirstHVACIteration); // Check model boundaries and cap empirical model independent variables as needed (T_* may be modified on return from sub) CheckModelBoundsTempEq(ExNum, T_RegenInTemp, T_RegenInHumRat, T_ProcInTemp, T_ProcInHumRat, T_FaceVel, FirstHVACIteration); if (T_ProcInTemp != 0.0 && T_RegenInTemp != 0.0) { FullLoadSupOutTemp = Coeff1 + Coeff2 * T_RegenInHumRat + Coeff3 * T_RegenInTemp + Coeff4 * (T_RegenInHumRat / T_RegenInTemp) + Coeff5 * T_ProcInHumRat + Coeff6 * T_ProcInTemp + Coeff7 * (T_ProcInHumRat / T_ProcInTemp) + Coeff8 * T_FaceVel; // Check model boundary for supply (regen) temp and do not cap value if out of bounds, check that supply in temp > out temp CheckModelBoundOutput_Temp(ExNum, ExchCond(ExNum).SupInTemp, FullLoadSupOutTemp, FirstHVACIteration); FullLoadDeltaT = FullLoadSupOutTemp - ExchCond(ExNum).SupInTemp; } else { FullLoadDeltaT = 0.0; } Coeff1 = BalDesDehumPerfData(ExchCond(ExNum).PerfDataIndex).C1; Coeff2 = BalDesDehumPerfData(ExchCond(ExNum).PerfDataIndex).C2; Coeff3 = BalDesDehumPerfData(ExchCond(ExNum).PerfDataIndex).C3; Coeff4 = BalDesDehumPerfData(ExchCond(ExNum).PerfDataIndex).C4; Coeff5 = BalDesDehumPerfData(ExchCond(ExNum).PerfDataIndex).C5; Coeff6 = BalDesDehumPerfData(ExchCond(ExNum).PerfDataIndex).C6; Coeff7 = BalDesDehumPerfData(ExchCond(ExNum).PerfDataIndex).C7; Coeff8 = BalDesDehumPerfData(ExchCond(ExNum).PerfDataIndex).C8; H_ProcInTemp = FullLoadOutAirTemp; H_ProcInHumRat = FullLoadOutAirHumRat; H_RegenInTemp = ExchCond(ExNum).SupInTemp; H_RegenInHumRat = ExchCond(ExNum).SupInHumRat; H_FaceVel = BalFaceVelActual; // Call model check routines only when HX is active, if coil is off these checks do not apply (no potential for heat transfer) // Check RH limits and warn user if out of bounds (H_* not modified in subroutine) CheckModelBoundsRH_HumRatEq(ExNum, H_RegenInTemp, H_RegenInHumRat, H_ProcInTemp, H_ProcInHumRat, FirstHVACIteration); // Check model boundaries and cap empirical model independent variables as needed (H_* may be modified on return from sub) CheckModelBoundsHumRatEq(ExNum, H_RegenInTemp, H_RegenInHumRat, H_ProcInTemp, H_ProcInHumRat, H_FaceVel, FirstHVACIteration); // Calc curve if (H_ProcInTemp != 0.0 && H_RegenInTemp != 0.0) { FullLoadSupOutHumRat = Coeff1 + Coeff2 * H_RegenInHumRat + Coeff3 * H_RegenInTemp + Coeff4 * (H_RegenInHumRat / H_RegenInTemp) + Coeff5 * H_ProcInHumRat + Coeff6 * H_ProcInTemp + Coeff7 * (H_ProcInHumRat / H_ProcInTemp) + Coeff8 * H_FaceVel; // Check model boundary for supply (regen) hum rat and do not cap value if out of bounds, check that supply in HR < out HR CheckModelBoundOutput_HumRat(ExNum, ExchCond(ExNum).SupInHumRat, FullLoadSupOutHumRat, FirstHVACIteration); FullLoadDeltaW = FullLoadSupOutHumRat - ExchCond(ExNum).SupInHumRat; } else { FullLoadDeltaW = 0.0; } // Check for saturation in the model's calculated supply outlet and reset temp, then humidity ratio at constant enthalpy // Reset delta T and delta W such that the model does not allow an outlet condition over saturation TestSaturationEnthalpy = PsyHFnTdbW(FullLoadSupOutTemp, FullLoadSupOutHumRat); if (PsyTsatFnHPb(TestSaturationEnthalpy, OutBaroPress, ThisSubTSat) > FullLoadSupOutTemp) { FullLoadSupOutTemp = PsyTsatFnHPb(TestSaturationEnthalpy, OutBaroPress, ThisSubTSatFullLoadOutTemp); FullLoadSupOutHumRat = PsyWFnTdbH(FullLoadSupOutTemp, TestSaturationEnthalpy, ThisSubTSatFullLoadOutHumRat); FullLoadDeltaT = FullLoadSupOutTemp - ExchCond(ExNum).SupInTemp; FullLoadDeltaW = FullLoadSupOutHumRat - ExchCond(ExNum).SupInHumRat; } if (!CalledFromParentObject) { // calculate part-load ratio for HX MaxHumRatNeeded = Node(ExchCond(ExNum).SecOutletNode).HumRatMax; MinHumRatNeeded = Node(ExchCond(ExNum).SecOutletNode).HumRatMin; // Calculate partload fraction of dehumidification capacity required to meet setpoint // check the model output, if the regen delta W is positive, the process air stream is dehumidified if (FullLoadDeltaW > 0) { // check for a setpoint, if no setpoint then PLR remains at 1 if (MaxHumRatNeeded != SensedNodeFlagValue) { if (ExchCond(ExNum).SecInHumRat > MaxHumRatNeeded && MaxHumRatNeeded > 0.0) { HXPartLoadRatio = (ExchCond(ExNum).SecInHumRat - MaxHumRatNeeded) / FullLoadDeltaW; } else { HXPartLoadRatio = 0.0; } } // check the model output, if the regen delta W is negative, the process air stream is humidified } else if (FullLoadDeltaW < 0) { // check for a setpoint, if no setpoint then PLR remains at 1 if (MinHumRatNeeded != SensedNodeFlagValue) { if (ExchCond(ExNum).SecInHumRat < MinHumRatNeeded && MinHumRatNeeded > 0.0) { HXPartLoadRatio = (ExchCond(ExNum).SecInHumRat - MinHumRatNeeded) / FullLoadDeltaW; } else { HXPartLoadRatio = 0.0; } } } HXPartLoadRatio = max(0.0, HXPartLoadRatio); HXPartLoadRatio = min(1.0, HXPartLoadRatio); } else if (CompanionCoilIndex > 0) { // VS coil issue here? HXPartLoadRatio = DXCoilPartLoadRatio(CompanionCoilIndex); } if (FanOpMode == CycFanCycCoil || RegenInletIsOANode) { // Supply (regen) air stream mass flow rate is cycling and proportional to PLR, outlet conditions are full load // conditions ExchCond(ExNum).SupOutTemp = ExchCond(ExNum).SupInTemp + FullLoadDeltaT; ExchCond(ExNum).SupOutHumRat = min(1.0, max(1.e-5, ExchCond(ExNum).SupInHumRat + FullLoadDeltaW)); } else { // Supply (regen) air stream mass flow rate is constant and outlet conditions are averaged ExchCond(ExNum).SupOutTemp = ExchCond(ExNum).SupInTemp + (FullLoadDeltaT * HXPartLoadRatio); ExchCond(ExNum).SupOutHumRat = min(1.0, max(1.e-5, ExchCond(ExNum).SupInHumRat + (FullLoadDeltaW * HXPartLoadRatio))); } // for a balanced flow HX, use average mass flow rate and actual node conditions to calculate CSup and CSec // the mass flow rate on the process and secondary side of HX may be imbalanced when the HX is used in the OA branch // use the average mass flow rate to avoid psych warnings, mass flow rates will converge at the end of the iteration // if the air mass flow rates do not converge, this model should not be used CSup = AverageMassFlowRate * PsyCpAirFnWTdb(ExchCond(ExNum).SupInHumRat, ExchCond(ExNum).SupInTemp); CSec = AverageMassFlowRate * PsyCpAirFnWTdb(ExchCond(ExNum).SecInHumRat, ExchCond(ExNum).SecInTemp); ExchCond(ExNum).SupOutEnth = PsyHFnTdbW(ExchCond(ExNum).SupOutTemp, ExchCond(ExNum).SupOutHumRat); SensHeatRecRate = CSup * (ExchCond(ExNum).SupOutTemp - ExchCond(ExNum).SupInTemp); TotHeatRecRate = AverageMassFlowRate * (ExchCond(ExNum).SupOutEnth - ExchCond(ExNum).SupInEnth); // now calculate process side heat transfer ExchCond(ExNum).SecOutEnth = ExchCond(ExNum).SecInEnth - TotHeatRecRate / AverageMassFlowRate; ExchCond(ExNum).SecOutTemp = ExchCond(ExNum).SecInTemp - SensHeatRecRate / CSec; ExchCond(ExNum).SecOutHumRat = PsyWFnTdbH(ExchCond(ExNum).SecOutTemp, ExchCond(ExNum).SecOutEnth, ThisSubSecOutHumRat); // check for saturation in process (secondary) outlet // The process outlet conditions should never be over the saturation curve for the balanced desiccant model // although this may occur during warmup. This check is included here for consistency. TempSecOutSat = PsyTsatFnHPb(ExchCond(ExNum).SecOutEnth, OutBaroPress, ThisSubTestSatSec); if (TempSecOutSat > ExchCond(ExNum).SecOutTemp) { ExchCond(ExNum).SecOutTemp = TempSecOutSat; ExchCond(ExNum).SecOutHumRat = PsyWFnTdbH(ExchCond(ExNum).SecOutTemp, ExchCond(ExNum).SecOutEnth, ThisSubTSatSecOutHumRat); } ExchCond(ExNum).ElecUseRate = BalDesDehumPerfData(ExchCond(ExNum).PerfDataIndex).NomElecPower * HXPartLoadRatio; } else { } } } // ENDIF for "IF (UnitOn) THEN" // Report the process side heat transfer CSec = AverageMassFlowRate * PsyCpAirFnWTdb(ExchCond(ExNum).SecInHumRat, ExchCond(ExNum).SecInTemp); ProcessSensHeatRecRate = CSec * (ExchCond(ExNum).SecOutTemp - ExchCond(ExNum).SecInTemp); ProcessTotHeatRecRate = ExchCond(ExNum).SecOutMassFlow * (ExchCond(ExNum).SecOutEnth - ExchCond(ExNum).SecInEnth); ProcessLatHeatRecRate = ProcessTotHeatRecRate - ProcessSensHeatRecRate; // Set report variables based on sign of recovery rate if (ProcessSensHeatRecRate > 0.0) { ExchCond(ExNum).SensHeatingRate = ProcessSensHeatRecRate; ExchCond(ExNum).SensCoolingRate = 0.0; } else { ExchCond(ExNum).SensHeatingRate = 0.0; ExchCond(ExNum).SensCoolingRate = std::abs(ProcessSensHeatRecRate); } if (ProcessLatHeatRecRate > 0.0) { ExchCond(ExNum).LatHeatingRate = ProcessLatHeatRecRate; ExchCond(ExNum).LatCoolingRate = 0.0; } else { ExchCond(ExNum).LatHeatingRate = 0.0; ExchCond(ExNum).LatCoolingRate = std::abs(ProcessLatHeatRecRate); } if (ProcessTotHeatRecRate > 0.0) { ExchCond(ExNum).TotHeatingRate = ProcessTotHeatRecRate; ExchCond(ExNum).TotCoolingRate = 0.0; } else { ExchCond(ExNum).TotHeatingRate = 0.0; ExchCond(ExNum).TotCoolingRate = std::abs(ProcessTotHeatRecRate); } } void FrostControl(int const ExNum) // number of the current heat exchanger being simulated { // SUBROUTINE INFORMATION: // AUTHOR Richard Raustad, FSEC // DATE WRITTEN June 2003 // MODIFIED na // RE-ENGINEERED na // PURPOSE OF THIS SUBROUTINE: // Calculates fraction of timestep necessary to eliminate frost on ERV surface // by comparing secondary outlet or outdoor temperature to a frost control threshold // temperature. Supply air and secondary air outlet conditions are calculated // based on frost control method selected. // METHODOLOGY EMPLOYED: // NA // REFERENCES: // na // USE STATEMENTS: // na // Locals // SUBROUTINE ARGUMENT DEFINITIONS: // SUBROUTINE PARAMETER DEFINITIONS: Real64 const ErrorTol(0.001); // error tolerence for iteration loop // na // INTERFACE BLOCK SPECIFICATIONS: // na // DERIVED TYPE DEFINITIONS: // na // SUBROUTINE LOCAL VARIABLE DECLARATIONS: Real64 DFFraction; // fraction of timestep ERV is in frost control mode Real64 RhoSup; // density of supply air [kg/m3] Real64 RhoSec; // density of secondary air [kg/m3] Real64 Error; // iteration loop error variable Real64 Iter; // iteration counter Real64 CSup; // mdot Cp of supply air [W/K] Real64 CSec; // mdot Cp of secondary air [W/K] Real64 CMin; // minimum mdot Cp of supply or secondary air [W/K] Real64 QTotTrans; // total heat transfer by ERV [W] Real64 QSensTrans; // sensible heat transfer by ERV [W] Real64 HXSecAirVolFlowRate; // air volume flow rate of the secondary air stream through the heat exchanger [m3/sec] Real64 HXSupAirVolFlowRate; // air volume flow rate of the supply air stream through the heat exchanger [m3/sec] Real64 HXAvgAirVolFlowRate; // average air volume flow rate through the heat exchanger [m3/sec] Real64 HXAirVolFlowRatio; // nominal to actual air volume flow ratio Real64 MassFlowSupIn; // supply air mass flow rate at HX inlet Real64 MassFlowSupOut; // supply air mass flow rate through HX core outlet Real64 MassFlowSupBypass; // supply air bypass mass flow rate around HX core Real64 TempSupIn; // supply side temperature of air entering HX Real64 TempSupOut; // supply side temperature of air leaving HX core Real64 HumRatSupIn; // supply side humidity ratio of air entering HX Real64 TempSecIn; // secondary side temperature of air entering HX Real64 TempSecOut; // secondary side temperature of air leaving HX core Real64 TempThreshold; // threshold temperature below which frost control is active ExchCond(ExNum).SupOutMassFlow = ExchCond(ExNum).SupInMassFlow; ExchCond(ExNum).SecOutMassFlow = ExchCond(ExNum).SecInMassFlow; ExchCond(ExNum).SupBypassMassFlow = 0.0; ExchCond(ExNum).SecBypassMassFlow = 0.0; RhoSup = PsyRhoAirFnPbTdbW(OutBaroPress, ExchCond(ExNum).SupInTemp, ExchCond(ExNum).SupInHumRat); RhoSec = PsyRhoAirFnPbTdbW(OutBaroPress, ExchCond(ExNum).SecInTemp, ExchCond(ExNum).SecInHumRat); CSup = ExchCond(ExNum).SupOutMassFlow * PsyCpAirFnWTdb(ExchCond(ExNum).SupInHumRat, ExchCond(ExNum).SupInTemp); CSec = ExchCond(ExNum).SecOutMassFlow * PsyCpAirFnWTdb(ExchCond(ExNum).SecInHumRat, ExchCond(ExNum).SecInTemp); CMin = min(CSup, CSec); TempThreshold = ExchCond(ExNum).ThresholdTemperature; if (ExchCond(ExNum).ControlToTemperatureSetPoint) { // Recalculate HX outlet conditions as if control to temperature setpoint was not activated, // because defrost will override those results HXSupAirVolFlowRate = ExchCond(ExNum).SupOutMassFlow / RhoSup; HXSecAirVolFlowRate = ExchCond(ExNum).SecOutMassFlow / RhoSec; HXAvgAirVolFlowRate = (HXSecAirVolFlowRate + HXSupAirVolFlowRate) / 2.0; HXAirVolFlowRatio = HXAvgAirVolFlowRate / ExchCond(ExNum).NomSupAirVolFlow; ExchCond(ExNum).SensEffectiveness = ExchCond(ExNum).HeatEffectSensible75 + (ExchCond(ExNum).HeatEffectSensible100 - ExchCond(ExNum).HeatEffectSensible75) * (HXAirVolFlowRatio - 0.75) / (1.0 - 0.75); ExchCond(ExNum).LatEffectiveness = ExchCond(ExNum).HeatEffectLatent75 + (ExchCond(ExNum).HeatEffectLatent100 - ExchCond(ExNum).HeatEffectLatent75) * (HXAirVolFlowRatio - 0.75) / (1.0 - 0.75); ExchCond(ExNum).SupOutTemp = ExchCond(ExNum).SupInTemp + ExchCond(ExNum).SensEffectiveness * CMin / CSup * (ExchCond(ExNum).SecInTemp - ExchCond(ExNum).SupInTemp); ExchCond(ExNum).SupOutHumRat = ExchCond(ExNum).SupInHumRat + ExchCond(ExNum).LatEffectiveness * CMin / CSup * (ExchCond(ExNum).SecInHumRat - ExchCond(ExNum).SupInHumRat); ExchCond(ExNum).SupOutEnth = PsyHFnTdbW(ExchCond(ExNum).SupOutTemp, ExchCond(ExNum).SupOutHumRat); // Check for saturation in supply outlet and reset temp, then humidity ratio at constant enthalpy if (PsyTsatFnHPb(ExchCond(ExNum).SupOutEnth, OutBaroPress) > ExchCond(ExNum).SupOutTemp) { ExchCond(ExNum).SupOutTemp = PsyTsatFnHPb(ExchCond(ExNum).SupOutEnth, OutBaroPress); ExchCond(ExNum).SupOutHumRat = PsyWFnTdbH(ExchCond(ExNum).SupOutTemp, ExchCond(ExNum).SupOutEnth); } QSensTrans = CSup * (ExchCond(ExNum).SupInTemp - ExchCond(ExNum).SupOutTemp); ExchCond(ExNum).SecOutTemp = ExchCond(ExNum).SecInTemp + QSensTrans / CSec; QTotTrans = ExchCond(ExNum).SupOutMassFlow * (ExchCond(ExNum).SupInEnth - ExchCond(ExNum).SupOutEnth); ExchCond(ExNum).SecOutEnth = ExchCond(ExNum).SecInEnth + QTotTrans / ExchCond(ExNum).SecOutMassFlow; ExchCond(ExNum).SecOutHumRat = PsyWFnTdbH(ExchCond(ExNum).SecOutTemp, ExchCond(ExNum).SecOutEnth); } // Check frost control by type if (ExchCond(ExNum).FrostControlType == "MINIMUMEXHAUSTTEMPERATURE") { // A plate HX will bypass air on the supply side to keep exhaust temp above a // threshold temperature and requires recalculating effectiveness based on // the reduced air flow rate. A rotary HX modulates rotational speed to try to keep the // exhaust air temperature above the threshold temperature. Assume that // sensible and latent effectiveness decrease proportionally with rotary HX speed. DFFraction = max(0.0, min(1.0, SafeDiv((TempThreshold - ExchCond(ExNum).SecOutTemp), (ExchCond(ExNum).SecInTemp - ExchCond(ExNum).SecOutTemp)))); if (ExchCond(ExNum).ExchConfigNum == Rotary) { ExchCond(ExNum).SensEffectiveness *= (1.0 - DFFraction); ExchCond(ExNum).LatEffectiveness *= (1.0 - DFFraction); } else { // HX is a plate heat exchanger, bypass air to eliminate frost Error = 1.0; Iter = 0.0; MassFlowSupIn = ExchCond(ExNum).SupInMassFlow; MassFlowSupOut = ExchCond(ExNum).SupOutMassFlow; MassFlowSupBypass = ExchCond(ExNum).SupBypassMassFlow; TempSupIn = ExchCond(ExNum).SupInTemp; HumRatSupIn = ExchCond(ExNum).SupInHumRat; TempSecIn = ExchCond(ExNum).SecInTemp; while (std::abs(Error) > ErrorTol && Iter < 10) { MassFlowSupOut = MassFlowSupIn * (1.0 - DFFraction); MassFlowSupBypass = MassFlowSupIn * DFFraction; HXSupAirVolFlowRate = MassFlowSupOut / RhoSup; HXSecAirVolFlowRate = ExchCond(ExNum).SecOutMassFlow / RhoSec; HXAvgAirVolFlowRate = (HXSecAirVolFlowRate + HXSupAirVolFlowRate) / 2.0; HXAirVolFlowRatio = HXAvgAirVolFlowRate / ExchCond(ExNum).NomSupAirVolFlow; CSup = MassFlowSupOut * PsyCpAirFnWTdb(HumRatSupIn, TempSupIn); CMin = min(CSup, CSec); if (TempSupIn < TempSecIn) { // Use heating effectiveness values ExchCond(ExNum).SensEffectiveness = ExchCond(ExNum).HeatEffectSensible75 + (ExchCond(ExNum).HeatEffectSensible100 - ExchCond(ExNum).HeatEffectSensible75) * (HXAirVolFlowRatio - 0.75) / (1.0 - 0.75); ExchCond(ExNum).LatEffectiveness = ExchCond(ExNum).HeatEffectLatent75 + (ExchCond(ExNum).HeatEffectLatent100 - ExchCond(ExNum).HeatEffectLatent75) * (HXAirVolFlowRatio - 0.75) / (1.0 - 0.75); } else { // Use cooling effectiveness values ExchCond(ExNum).SensEffectiveness = ExchCond(ExNum).CoolEffectSensible75 + (ExchCond(ExNum).CoolEffectSensible100 - ExchCond(ExNum).CoolEffectSensible75) * (HXAirVolFlowRatio - 0.75) / (1.0 - 0.75); ExchCond(ExNum).LatEffectiveness = ExchCond(ExNum).CoolEffectLatent75 + (ExchCond(ExNum).CoolEffectLatent100 - ExchCond(ExNum).CoolEffectLatent75) * (HXAirVolFlowRatio - 0.75) / (1.0 - 0.75); } // calculation of local variable Csup can be 0, gaurd against divide by 0. TempSupOut = TempSupIn + ExchCond(ExNum).SensEffectiveness * SafeDiv(CMin, CSup) * (TempSecIn - TempSupIn); QSensTrans = CSup * (TempSupIn - TempSupOut); // Csec cannot be 0 in this subroutine TempSecOut = TempSecIn + QSensTrans / CSec; Error = (TempSecOut - TempThreshold); // recalculate DFFraction until convergence, gaurd against divide by 0 (unlikely). DFFraction = max(0.0, min(1.0, DFFraction * SafeDiv((TempSecIn - TempSecOut), (TempSecIn - TempThreshold)))); ++Iter; } ExchCond(ExNum).SupInMassFlow = MassFlowSupIn; ExchCond(ExNum).SupOutMassFlow = MassFlowSupOut; ExchCond(ExNum).SupBypassMassFlow = MassFlowSupBypass; } ExchCond(ExNum).SupOutTemp = ExchCond(ExNum).SupInTemp + ExchCond(ExNum).SensEffectiveness * SafeDiv(CMin, CSup) * (ExchCond(ExNum).SecInTemp - ExchCond(ExNum).SupInTemp); ExchCond(ExNum).SupOutHumRat = ExchCond(ExNum).SupInHumRat + ExchCond(ExNum).LatEffectiveness * SafeDiv(CMin, CSup) * (ExchCond(ExNum).SecInHumRat - ExchCond(ExNum).SupInHumRat); ExchCond(ExNum).SupOutEnth = PsyHFnTdbW(ExchCond(ExNum).SupOutTemp, ExchCond(ExNum).SupOutHumRat); // Check for saturation in supply outlet and reset temp, then humidity ratio at constant enthalpy if (PsyTsatFnHPb(ExchCond(ExNum).SupOutEnth, OutBaroPress) > ExchCond(ExNum).SupOutTemp) { ExchCond(ExNum).SupOutTemp = PsyTsatFnHPb(ExchCond(ExNum).SupOutEnth, OutBaroPress); ExchCond(ExNum).SupOutHumRat = PsyWFnTdbH(ExchCond(ExNum).SupOutTemp, ExchCond(ExNum).SupOutEnth); } QSensTrans = CSup * (ExchCond(ExNum).SupInTemp - ExchCond(ExNum).SupOutTemp); ExchCond(ExNum).SecOutTemp = ExchCond(ExNum).SecInTemp + QSensTrans / CSec; QTotTrans = ExchCond(ExNum).SupOutMassFlow * (ExchCond(ExNum).SupInEnth - ExchCond(ExNum).SupOutEnth); ExchCond(ExNum).SecOutEnth = ExchCond(ExNum).SecInEnth + QTotTrans / ExchCond(ExNum).SecOutMassFlow; ExchCond(ExNum).SecOutHumRat = PsyWFnTdbH(ExchCond(ExNum).SecOutTemp, ExchCond(ExNum).SecOutEnth); // Perform mixing of core air stream and bypass air stream and set mass flow rates at outlet nodes ExchCond(ExNum).SupOutEnth = (ExchCond(ExNum).SupOutMassFlow * ExchCond(ExNum).SupOutEnth + ExchCond(ExNum).SupBypassMassFlow * ExchCond(ExNum).SupInEnth) / ExchCond(ExNum).SupInMassFlow; ExchCond(ExNum).SupOutHumRat = (ExchCond(ExNum).SupOutMassFlow * ExchCond(ExNum).SupOutHumRat + ExchCond(ExNum).SupBypassMassFlow * ExchCond(ExNum).SupInHumRat) / ExchCond(ExNum).SupInMassFlow; ExchCond(ExNum).SupOutTemp = PsyTdbFnHW(ExchCond(ExNum).SupOutEnth, ExchCond(ExNum).SupOutHumRat); ExchCond(ExNum).SupOutMassFlow = ExchCond(ExNum).SupInMassFlow; ExchCond(ExNum).SecOutEnth = (ExchCond(ExNum).SecOutMassFlow * ExchCond(ExNum).SecOutEnth + ExchCond(ExNum).SecBypassMassFlow * ExchCond(ExNum).SecInEnth) / ExchCond(ExNum).SecInMassFlow; ExchCond(ExNum).SecOutHumRat = (ExchCond(ExNum).SecOutMassFlow * ExchCond(ExNum).SecOutHumRat + ExchCond(ExNum).SecBypassMassFlow * ExchCond(ExNum).SecInHumRat) / ExchCond(ExNum).SecInMassFlow; ExchCond(ExNum).SecOutTemp = PsyTdbFnHW(ExchCond(ExNum).SecOutEnth, ExchCond(ExNum).SecOutHumRat); ExchCond(ExNum).SecOutMassFlow = ExchCond(ExNum).SecInMassFlow; } // End of IF (Minimum Exhaust Temperature) if (ExchCond(ExNum).FrostControlType == "EXHAUSTAIRRECIRCULATION") { // Directing exhaust outlet air back across the HX core on the supply side // Assume no heat exchange when in frost control mode, full heat exchange otherwise DFFraction = max( 0.0, min((ExchCond(ExNum).InitialDefrostTime + ExchCond(ExNum).RateofDefrostTimeIncrease * (TempThreshold - ExchCond(ExNum).SupInTemp)), 1.0)); // Calculate derated heat transfer using outlet air conditions assuming no defrost (calculated earlier) // and (1-DefrostFraction) QSensTrans = (1.0 - DFFraction) * CSup * (ExchCond(ExNum).SupInTemp - ExchCond(ExNum).SupOutTemp); QTotTrans = (1.0 - DFFraction) * ExchCond(ExNum).SupOutMassFlow * (ExchCond(ExNum).SupInEnth - ExchCond(ExNum).SupOutEnth); ExchCond(ExNum).SupOutMassFlow = (1.0 - DFFraction) * ExchCond(ExNum).SupInMassFlow + DFFraction * ExchCond(ExNum).SecInMassFlow; // Blend supply outlet condition of HX core with exhaust air inlet to get final supply air outlet conditions ExchCond(ExNum).SupOutTemp = ((1.0 - DFFraction) * ExchCond(ExNum).SupInMassFlow * ExchCond(ExNum).SupOutTemp + DFFraction * ExchCond(ExNum).SecInMassFlow * ExchCond(ExNum).SecInTemp) / ExchCond(ExNum).SupOutMassFlow; ExchCond(ExNum).SupOutHumRat = ((1.0 - DFFraction) * ExchCond(ExNum).SupInMassFlow * ExchCond(ExNum).SupOutHumRat + DFFraction * ExchCond(ExNum).SecInMassFlow * ExchCond(ExNum).SecInHumRat) / ExchCond(ExNum).SupOutMassFlow; ExchCond(ExNum).SupOutEnth = PsyHFnTdbW(ExchCond(ExNum).SupOutTemp, ExchCond(ExNum).SupOutHumRat); // No need to check for saturation after SA out and EA inlet are blended // Derate effectiveness based on frost control time fraction for reporting purposes ExchCond(ExNum).SensEffectiveness *= (1.0 - DFFraction); ExchCond(ExNum).LatEffectiveness *= (1.0 - DFFraction); // Secondary air outlet conditions are previously calculated as the conditions when not // in defrost, and this is what we want to report so no changes here. // Average SupInMassFlow and SecOutMassFlow rates have been reduced due to frost control // Equipment attached to the supply inlet node may have problems with our setting the // mass flow rate in the next statement. This is done only to simulate exhaust air recirc. Node(ExchCond(ExNum).SupInletNode).MassFlowRate = ExchCond(ExNum).SupInMassFlow * (1.0 - DFFraction); ExchCond(ExNum).SecOutMassFlow *= (1.0 - DFFraction); } // End of IF (Exhaust Air Recirculation) if (ExchCond(ExNum).FrostControlType == "EXHAUSTONLY") { // Perform frost control by bypassing the supply air around the HX core during the defrost // time period. HX heat transfer is reduced proportionally to (1 - defrosttimefraction) DFFraction = max( 0.0, min((ExchCond(ExNum).InitialDefrostTime + ExchCond(ExNum).RateofDefrostTimeIncrease * (TempThreshold - ExchCond(ExNum).SupInTemp)), 1.0)); // Calculate derated heat transfer based on defrost time QSensTrans = (1.0 - DFFraction) * CSup * (ExchCond(ExNum).SupInTemp - ExchCond(ExNum).SupOutTemp); QTotTrans = (1.0 - DFFraction) * ExchCond(ExNum).SupOutMassFlow * (ExchCond(ExNum).SupInEnth - ExchCond(ExNum).SupOutEnth); // Calculate the air conditions leaving heat exchanger unit // Heat exchanger effectiveness is not derated, HX is fully bypassed during frost control ExchCond(ExNum).SupBypassMassFlow = ExchCond(ExNum).SupInMassFlow * DFFraction; ExchCond(ExNum).SupOutTemp = ExchCond(ExNum).SupInTemp - QSensTrans / CSup; ExchCond(ExNum).SupOutEnth = ExchCond(ExNum).SupInEnth - QTotTrans / ExchCond(ExNum).SupOutMassFlow; ExchCond(ExNum).SupOutHumRat = PsyWFnTdbH(ExchCond(ExNum).SupOutTemp, ExchCond(ExNum).SupOutEnth); if (PsyTsatFnHPb(ExchCond(ExNum).SupOutEnth, OutBaroPress) > ExchCond(ExNum).SupOutTemp) { ExchCond(ExNum).SupOutTemp = PsyTsatFnHPb(ExchCond(ExNum).SupOutEnth, OutBaroPress); ExchCond(ExNum).SupOutHumRat = PsyWFnTdbH(ExchCond(ExNum).SupOutTemp, ExchCond(ExNum).SupOutEnth); QSensTrans = CSup * (ExchCond(ExNum).SupInTemp - ExchCond(ExNum).SupOutTemp); // Should we be updating the sensible and latent effectiveness values also? } ExchCond(ExNum).SecOutEnth = ExchCond(ExNum).SecInEnth + QTotTrans / ExchCond(ExNum).SecOutMassFlow; ExchCond(ExNum).SecOutTemp = ExchCond(ExNum).SecInTemp + QSensTrans / CSec; ExchCond(ExNum).SecOutHumRat = PsyWFnTdbH(ExchCond(ExNum).SecOutTemp, ExchCond(ExNum).SecOutEnth); } // End of IF (Exhaust Only) ExchCond(ExNum).DefrostFraction = DFFraction; } void UpdateHeatRecovery(int const ExNum) // number of the current heat exchanger being simulated { // SUBROUTINE INFORMATION: // AUTHOR Michael Wetter // DATE WRITTEN March 1999 // MODIFIED Fred Buhl November 2000 // RE-ENGINEERED na // PURPOSE OF THIS SUBROUTINE: // Moves heat exchanger output to the outlet nodes. // METHODOLOGY EMPLOYED: // NA // REFERENCES: // na // Using/Aliasing using DataContaminantBalance::Contaminant; // Locals // SUBROUTINE ARGUMENT DEFINITIONS: // SUBROUTINE PARAMETER DEFINITIONS: // na // INTERFACE BLOCK SPECIFICATIONS: // na // DERIVED TYPE DEFINITIONS: // na // SUBROUTINE LOCAL VARIABLE DECLARATIONS: int SupInNode; // supply inlet node number int SupOutNode; // supply outlet node number int SecInNode; // secondary inlet node number int SecOutNode; // secondary outlet node number SupInNode = ExchCond(ExNum).SupInletNode; SupOutNode = ExchCond(ExNum).SupOutletNode; SecInNode = ExchCond(ExNum).SecInletNode; SecOutNode = ExchCond(ExNum).SecOutletNode; // Set the outlet air nodes of the heat exchanger Node(SupOutNode).Temp = ExchCond(ExNum).SupOutTemp; Node(SupOutNode).HumRat = ExchCond(ExNum).SupOutHumRat; Node(SupOutNode).Enthalpy = ExchCond(ExNum).SupOutEnth; Node(SupOutNode).MassFlowRate = ExchCond(ExNum).SupOutMassFlow; Node(SecOutNode).Temp = ExchCond(ExNum).SecOutTemp; Node(SecOutNode).HumRat = ExchCond(ExNum).SecOutHumRat; Node(SecOutNode).Enthalpy = ExchCond(ExNum).SecOutEnth; Node(SecOutNode).MassFlowRate = ExchCond(ExNum).SecOutMassFlow; // Set the outlet nodes for properties that just pass through & not used Node(SupOutNode).Quality = Node(SupInNode).Quality; Node(SupOutNode).Press = Node(SupInNode).Press; Node(SupOutNode).MassFlowRateMin = Node(SupInNode).MassFlowRateMin; Node(SupOutNode).MassFlowRateMax = Node(SupInNode).MassFlowRateMax; Node(SupOutNode).MassFlowRateMinAvail = Node(SupInNode).MassFlowRateMinAvail; Node(SupOutNode).MassFlowRateMaxAvail = Node(SupInNode).MassFlowRateMaxAvail; Node(SecOutNode).Quality = Node(SecInNode).Quality; Node(SecOutNode).Press = Node(SecInNode).Press; Node(SecOutNode).MassFlowRateMin = Node(SecInNode).MassFlowRateMin; Node(SecOutNode).MassFlowRateMax = Node(SecInNode).MassFlowRateMax; Node(SecOutNode).MassFlowRateMinAvail = Node(SecInNode).MassFlowRateMinAvail; Node(SecOutNode).MassFlowRateMaxAvail = Node(SecInNode).MassFlowRateMaxAvail; if (Contaminant.CO2Simulation) { Node(SupOutNode).CO2 = Node(SupInNode).CO2; Node(SecOutNode).CO2 = Node(SecInNode).CO2; } if (Contaminant.GenericContamSimulation) { Node(SupOutNode).GenContam = Node(SupInNode).GenContam; Node(SecOutNode).GenContam = Node(SecInNode).GenContam; } } void ReportHeatRecovery(int const ExNum) // number of the current heat exchanger being simulated { // SUBROUTINE INFORMATION: // AUTHOR Michael Wetter // DATE WRITTEN March 1999 // MODIFIED F Buhl Nov 2000, D Shirey Feb/June 2003 // RE-ENGINEERED na // PURPOSE OF THIS SUBROUTINE: // Fill remaining report variables // METHODOLOGY EMPLOYED: // na // REFERENCES: // na // Using/Aliasing using DataHVACGlobals::AirToAirHXElecPower; using DataHVACGlobals::TimeStepSys; // Locals // SUBROUTINE ARGUMENT DEFINITIONS: // SUBROUTINE PARAMETER DEFINITIONS: // na // INTERFACE BLOCK SPECIFICATIONS: // na // DERIVED TYPE DEFINITIONS: // na // SUBROUTINE LOCAL VARIABLE DECLARATIONS: Real64 ReportingConstant; ReportingConstant = TimeStepSys * SecInHour; ExchCond(ExNum).ElecUseEnergy = ExchCond(ExNum).ElecUseRate * ReportingConstant; ExchCond(ExNum).SensHeatingEnergy = ExchCond(ExNum).SensHeatingRate * ReportingConstant; ExchCond(ExNum).LatHeatingEnergy = ExchCond(ExNum).LatHeatingRate * ReportingConstant; ExchCond(ExNum).TotHeatingEnergy = ExchCond(ExNum).TotHeatingRate * ReportingConstant; ExchCond(ExNum).SensCoolingEnergy = ExchCond(ExNum).SensCoolingRate * ReportingConstant; ExchCond(ExNum).LatCoolingEnergy = ExchCond(ExNum).LatCoolingRate * ReportingConstant; ExchCond(ExNum).TotCoolingEnergy = ExchCond(ExNum).TotCoolingRate * ReportingConstant; AirToAirHXElecPower = ExchCond(ExNum).ElecUseRate; } Real64 SafeDiv(Real64 const a, Real64 const b) { // SUBROUTINE INFORMATION: // AUTHOR Michael Wetter // DATE WRITTEN March 1999 // MODIFIED na // RE-ENGINEERED na // PURPOSE OF THIS FUNCTION: // Returns a / b while preventing division by zero // METHODOLOGY EMPLOYED: // Check for small or zero values before performing division // REFERENCES: // na // USE STATEMENTS: // na // Return value Real64 c; // Locals // FUNCTION ARGUMENT DEFINITIONS: // FUNCTION PARAMETER DEFINITIONS: // na // INTERFACE BLOCK SPECIFICATIONS: // na // DERIVED TYPE DEFINITIONS: // na // FUNCTION LOCAL VARIABLE DECLARATIONS: if (std::abs(b) < SMALL) { c = a / sign(SMALL, b); } else { c = a / b; } return c; } void CalculateEpsFromNTUandZ(Real64 const NTU, // number of transfer units Real64 const Z, // capacity rate ratio int const FlowArr, // flow arrangement Real64 &Eps // heat exchanger effectiveness ) { // SUBROUTINE INFORMATION: // AUTHOR Michael Wetter // DATE WRITTEN March 1999 // MODIFIED Fred Buhl November 2000 // RE-ENGINEERED na // PURPOSE OF THIS SUBROUTINE: // Calculates eps, the exchanger effectiveness, // from NTU, the number of transfer units, // from Z, the capacity rate ratio, and // from the flow arrangement // METHODOLOGY EMPLOYED: // Uses the effectiveness - NTU heat exchanger formulas // REFERENCES: // M. Wetter, Simulation Model Air-to-Air Plate Heat Exchanger // LBNL Report 42354, 1999. // Also see: // ASHRAE HVAC 2 Toolkit, pages 4-3 through 4-5 // USE STATEMENTS: // na // Locals // SUBROUTINE ARGUMENT DEFINITIONS: // 1: COUNTER FLOW // 2: PARALLEL FLOW // 3: CROSS FLOW BOTH UNMIXED // 4: CROSS FLOW, Cmax MIXED, Cmin UNMIXED // (coil with one row) // SUBROUTINE PARAMETER DEFINITIONS: // na // INTERFACE BLOCK SPECIFICATIONS: // na // DERIVED TYPE DEFINITIONS: // na // SUBROUTINE LOCAL VARIABLE DECLARATIONS: Real64 Temp; // temporary variable // check input validity if (Z < 0.0 || Z > 1.0) { ShowFatalError("Variable Z (" + RoundSigDigits(Z, 2) + ") out of range [0.0,1.0] in CalculateEpsFromNTUandZ"); } // effectiveness if (NTU < SMALL) { Eps = 0.0; } else if (Z < SMALL) { // Eps independent of flow arrangement Eps = 1.0 - std::exp(-NTU); } else { { auto const SELECT_CASE_var(FlowArr); if (SELECT_CASE_var == Counter_Flow) { // COUNTER FLOW if (std::abs(Z - 1.0) < SMALL) { Eps = NTU / (NTU + 1.0); } else { Temp = std::exp(-NTU * (1.0 - Z)); Eps = (1.0 - Temp) / (1.0 - Z * Temp); } } else if (SELECT_CASE_var == Parallel_Flow) { // PARALLEL FLOW Temp = (1.0 + Z); Eps = (1.0 - std::exp(-NTU * Temp)) / Temp; } else if (SELECT_CASE_var == Cross_Flow_Both_Unmixed) { // CROSS FLOW BOTH UNMIXED Temp = Z * std::pow(NTU, -0.22); Eps = 1.0 - std::exp((std::exp(-NTU * Temp) - 1.0) / Temp); } else if (SELECT_CASE_var == Cross_Flow_Other) { // CROSS FLOW, Cmax MIXED, Cmin UNMIXED Eps = (1.0 - std::exp(-Z * (1.0 - std::exp(-NTU)))) / Z; } else { ShowFatalError("HeatRecovery: Illegal flow arrangement in CalculateEpsFromNTUandZ, Value=" + RoundSigDigits(FlowArr)); } } } } void CalculateNTUfromEpsAndZ(Real64 &NTU, // number of transfer units int &Err, // error indicator Real64 const Z, // capacity rate ratio int const FlowArr, // flow arrangement Real64 const Eps // heat exchanger effectiveness ) { // SUBROUTINE INFORMATION: // AUTHOR Michael Wetter // DATE WRITTEN March 1999 // MODIFIED Fred Buhl November 2000 // RE-ENGINEERED na // PURPOSE OF THIS SUBROUTINE: // Calculates NTU, the number of transfer units, // based on eps, the exchanger effectiveness, // Z, the capacity rate ratio, and // from the flow arrangement // METHODOLOGY EMPLOYED: // Uses the effectiveness - NTU heat exchanger formulas // REFERENCES: // M. Wetter, Simulation Model Air-to-Air Plate Heat Exchanger // LBNL Report 42354, 1999. // Also see: // ASHRAE HVAC 2 Toolkit, pages 4-3 through 4-5 // USE STATEMENTS: // na // Locals // SUBROUTINE ARGUMENT DEFINITIONS: // 1: COUNTER FLOW // 2: PARALLEL FLOW // 3: CROSS FLOW BOTH UNMIXED // 4: CROSS FLOW, Cmax MIXED, Cmin UNMIXED // (coil with one row) // SUBROUTINE PARAMETER DEFINITIONS: // na // INTERFACE BLOCK SPECIFICATIONS: // na // DERIVED TYPE DEFINITIONS: // na // SUBROUTINE LOCAL VARIABLE DECLARATIONS: NTU = 0.0; // check input validity if (Z < 0.0 || Z > 1.0) { Err = 1; return; } if (FlowArr == Parallel_Flow) { if (Eps < 0.0 || Eps > 1.0 / (1.0 + Z)) { Err = 2; return; } } else if (FlowArr == Cross_Flow_Other) { if (Eps < 0.0 || Eps > (1.0 - std::exp(-Z)) / Z) { Err = 3; return; } // check product (Eps*Z) if (Eps * Z < 0.0 || Eps * Z > 1.0 - std::exp(Z * (SMALL - 1.0))) { Err = 4; return; } // check product (Eps*Z) } else { if (Eps < 0.0 || Eps > 1.0) { Err = 5; return; } } if (Eps < SMALL) { // no effectiveness. Set NTU = 0 NTU = 0.0; } else if (Z < SMALL) { // Eps independent of flow arrangement NTU = -std::log(1.0 - Eps); } else { // calculate based on configuration { auto const SELECT_CASE_var(FlowArr); if (SELECT_CASE_var == Counter_Flow) { // COUNTER FLOW if (std::abs(Z - 1.0) < SMALL) { NTU = Eps / (1.0 - Eps); } else { NTU = 1.0 / (Z - 1.0) * std::log((1.0 - Eps) / (1.0 - Eps * Z)); } } else if (SELECT_CASE_var == Parallel_Flow) { // PARALLEL FLOW NTU = -std::log(-Eps - Eps * Z + 1.0) / (Z + 1.0); } else if (SELECT_CASE_var == Cross_Flow_Both_Unmixed) { // CROSS FLOW BOTH UNMIXED NTU = GetNTUforCrossFlowBothUnmixed(Eps, Z); } else if (SELECT_CASE_var == Cross_Flow_Other) { // CROSS FLOW, Cmax MIXED, Cmin UNMIXED NTU = -std::log(1.0 + std::log(1.0 - Eps * Z) / Z); } else { ShowFatalError("HeatRecovery: Illegal flow arrangement in CalculateNTUfromEpsAndZ, Value=" + RoundSigDigits(FlowArr)); } } } } Real64 GetNTUforCrossFlowBothUnmixed(Real64 const Eps, // heat exchanger effectiveness Real64 const Z // capacity rate ratio ) { // FUNCTION INFORMATION: // AUTHOR Michael Wetter // DATE WRITTEN March 1999 // MODIFIED Fred Buhl November 2000 // RE-ENGINEERED na // PURPOSE OF THIS FUNCTION: // Calculates the NTU value based on the exchanger effectiveness // and the capacity ratio for cross flow exchanger, both // streams unmixed // METHODOLOGY EMPLOYED: // Uses a Regula Falsi solver function to numerically invert the formula // giving effectiveness as a function of NTU and Z.. // REFERENCES: // M. Wetter, Simulation Model Air-to-Air Plate Heat Exchanger // LBNL Report 42354, 1999. // Also see: // ASHRAE HVAC 2 Toolkit, pages 4-3 through 4-5 // USE STATEMENTS: // na // Return value Real64 NTU; // result variable; number of transfer units // Locals // FUNCTION ARGUMENT DEFINITIONS: // FUNCTION PARAMETER DEFINITIONS: Real64 const Acc(0.0001); // Accuracy of result int const MaxIte(500); // Maximum number of iterations // INTERFACE BLOCK SPECIFICATIONS: // na // DERIVED TYPE DEFINITIONS: // na // FUNCTION LOCAL VARIABLE DECLARATIONS: int SolFla; // Flag of solver static Real64 NTU0(0.0); // lower bound for NTU static Real64 NTU1(50.0); // upper bound for NTU Array1D<Real64> Par(2); Par(1) = Eps; Par(2) = Z; SolveRoot(Acc, MaxIte, SolFla, NTU, GetResidCrossFlowBothUnmixed, NTU0, NTU1, Par); if (SolFla == -2) { ShowFatalError("HeatRecovery: Bad initial bounds for NTU in GetNTUforCrossFlowBothUnmixed"); } else if (SolFla == -1) { ShowFatalError("HeatRecovery: No convergence in solving for NTU in GetNTUforCrossFlowBothUnmixed"); } return NTU; } Real64 GetResidCrossFlowBothUnmixed(Real64 const NTU, // number of transfer units Array1<Real64> const &Par // par(1) = Eps, par(2) = Z ) { // FUNCTION INFORMATION: // AUTHOR Michael Wetter // DATE WRITTEN March 1999 // MODIFIED Fred Buhl November 2000 // RE-ENGINEERED na // PURPOSE OF THIS FUNCTION: // From the formula Eps = f(NTU,Z) this function finds the // residual of f(NTU,Z) - Eps for a cross flow heat exchanger, // both streams unmixed. // METHODOLOGY EMPLOYED: // Uses the effectiveness - NTU heat exchanger formula for cross // flow, both streams unmixed. // REFERENCES: // M. Wetter, Simulation Model Air-to-Air Plate Heat Exchanger // LBNL Report 42354, 1999. // Also see: // ASHRAE HVAC 2 Toolkit, pages 4-3 through 4-5 // USE STATEMENTS: // na // Return value Real64 Residuum; // residual to be minimized to zero // Argument array dimensioning // Locals // SUBROUTINE ARGUMENT DEFINITIONS: // FUNCTION PARAMETER DEFINITIONS: // na // INTERFACE BLOCK SPECIFICATIONS: // na // DERIVED TYPE DEFINITIONS: // na // FUNCTION LOCAL VARIABLE DECLARATIONS: Residuum = 1.0 - std::exp((std::exp(-std::pow(NTU, 0.78) * Par(2)) - 1.0) / Par(2) * std::pow(NTU, 0.22)) - Par(1); return Residuum; } void CheckModelBoundsTempEq(int const ExchNum, // number of the current heat exchanger being simulated Real64 &T_RegenInTemp, // current regen inlet temperature (C) for regen outlet temp eqn Real64 &T_RegenInHumRat, // current regen inlet hum rat for regen outlet temp eqn Real64 &T_ProcInTemp, // current process inlet temperature (C) for regen outlet temp eqn Real64 &T_ProcInHumRat, // current process inlet hum rat for regen outlet temp eqn Real64 &T_FaceVel, // current process and regen face velocity (m/s) bool const FirstHVACIteration // First HVAC iteration flag ) { // SUBROUTINE INFORMATION: // AUTHOR Mangesh Basarkar, FSEC // DATE WRITTEN January 2007 // MODIFIED na // RE-ENGINEERED na // PURPOSE OF THIS SUBROUTINE: // To verify that the empirical model's independent variables are within the limits used during the // developement of the empirical model. // METHODOLOGY EMPLOYED: // The empirical models used for simulating a desiccant enhanced cooling coil are based on a limited data set. // Extrapolation of empirical models can cause instability and the independent variables may need to be limited. // The range of each independent variable is provided by the user and are based on the limits of the // empirical model. These limits are tested in this subroutine each time step and returned for use by the calling // routine. // REFERENCES: // na // Using/Aliasing using DataGlobals::CurrentTime; using DataHVACGlobals::SysTimeElapsed; using DataHVACGlobals::TimeStepSys; using General::CreateSysTimeIntervalString; using General::RoundSigDigits; // Locals // SUBROUTINE ARGUMENT DEFINITIONS // regen outlet temp equation // SUBROUTINE PARAMETER DEFINITIONS: // CHARACTER(len=*), PARAMETER :: OutputFormat ='(F10.6)' // INTERFACE BLOCK SPECIFICATIONS: // na // DERIVED TYPE DEFINITIONS: // na // SUBROUTINE LOCAL VARIABLE DECLARATIONS: static std::string OutputChar; // character string for warning messages static std::string OutputCharLo; // character string for warning messages static std::string OutputCharHi; // character string for warning messages static std::string CharValue; // character string for warning messages static Real64 TimeStepSysLast(0.0); // last system time step (used to check for downshifting) static Real64 CurrentEndTime(0.0); // end time of time step for current simulation time step static Real64 CurrentEndTimeLast(0.0); // end time of time step for last simulation time step // current end time is compared with last to see if time step changed // calculate end time of current time step CurrentEndTime = CurrentTime + SysTimeElapsed; // Print warning messages only when valid and only for the first ocurrance. Let summary provide statistics. // Wait for next time step to print warnings. If simulation iterates, print out // the warning for the last iteration only. Must wait for next time step to accomplish this. // If a warning occurs and the simulation down shifts, the warning is not valid. if (CurrentEndTime > CurrentEndTimeLast && TimeStepSys >= TimeStepSysLast) { // print error for variables of regeneration outlet temperature equation // Regen inlet temp for temp eqn if (BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintT_RegenInTempMessage) { ++BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_RegenInTempErrorCount; if (BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_RegenInTempErrorCount < 2) { ShowWarningError(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_RegenInTempBuffer1); ShowContinueError(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_RegenInTempBuffer2); ShowContinueError(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_RegenInTempBuffer3); ShowContinueError("...Using regeneration inlet air temperatures that are outside the regeneration outlet air temperature " "equation model boundaries may adversely affect desiccant model performance."); } else { ShowRecurringWarningErrorAtEnd( BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PerfType + " \"" + BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).Name + "\" - Regeneration inlet air temp used in regen outlet air temperature equation is out of range error continues...", BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_RegenInTempErrIndex, BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_RegenInTempLast, BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_RegenInTempLast); } } // Regen inlet humidity ratio for temp eqn if (BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintT_RegenInHumRatMessage) { ++BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_RegenInHumRatErrorCount; if (BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_RegenInHumRatErrorCount < 2) { ShowWarningError(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_RegenInHumRatBuffer1); ShowContinueError(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_RegenInHumRatBuffer2); ShowContinueError(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_RegenInHumRatBuffer3); ShowContinueError("...Using regeneration inlet air humidity ratios that are outside the regeneration outlet air temperature " "equation model boundaries may adversely affect desiccant model performance."); } else { ShowRecurringWarningErrorAtEnd( BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PerfType + " \"" + BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).Name + "\" - Regeneration inlet air humidity ratio used in regen outlet temperature equation is out of range error continues...", BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_RegenInHumRatErrIndex, BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_RegenInHumRatLast, BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_RegenInHumRatLast); } } // Process inlet temp for temp eqn if (BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintT_ProcInTempMessage) { ++BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_ProcInTempErrorCount; if (BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_ProcInTempErrorCount < 2) { ShowWarningError(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_ProcInTempBuffer1); ShowContinueError(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_ProcInTempBuffer2); ShowContinueError(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_ProcInTempBuffer3); ShowContinueError("...Using process inlet air temperatures that are outside the regeneration outlet air temperature equation " "model boundaries may adversely affect desiccant model performance."); } else { ShowRecurringWarningErrorAtEnd( BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PerfType + " \"" + BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).Name + "\" - Process inlet air temperature used in regen outlet temperature equation is out of range error continues...", BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_ProcInTempErrIndex, BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_ProcInTempLast, BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_ProcInTempLast); } } // Process inlet humidity ratio for temp eqn if (BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintT_ProcInHumRatMessage) { ++BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_ProcInHumRatErrorCount; if (BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_ProcInHumRatErrorCount < 2) { ShowWarningError(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_ProcInHumRatBuffer1); ShowContinueError(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_ProcInHumRatBuffer2); ShowContinueError(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_ProcInHumRatBuffer3); ShowContinueError("...Using process inlet air humidity ratios that are outside the regeneratoin outlet air temperature equation " "model boundaries may adversely affect desiccant model performance."); } else { ShowRecurringWarningErrorAtEnd( BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PerfType + " \"" + BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).Name + "\" - Process inlet air humidity ratio used in regen outlet temperature equation is out of range error continues...", BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_ProcInHumRatErrIndex, BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_ProcInHumRatLast, BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_ProcInHumRatLast); } } // Process and regeneration face velocity for temp eqn if (BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintT_FaceVelMessage) { ++BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_FaceVelErrorCount; if (BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_FaceVelErrorCount < 2) { ShowWarningError(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_FaceVelBuffer1); ShowContinueError(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_FaceVelBuffer2); ShowContinueError(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_FaceVelBuffer3); ShowContinueError("...Using process and regeneration face velocities that are outside the regeneration outlet air temperature " "equation model boundaries may adversely affect desiccant model performance."); } else { ShowRecurringWarningErrorAtEnd(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PerfType + " \"" + BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).Name + "\" - Process and regen inlet air face velocity used in regen outlet temperature equation is " "out of range error continues...", BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_FaceVelocityErrIndex, BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_FaceVelLast, BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_FaceVelLast); } } } // IF(CurrentEndTime .GT. CurrentEndTimeLast .AND. TimeStepSys .GE. TimeStepSysLast)THEN // save last system time step and last end time of current time step (used to determine if warning is valid) TimeStepSysLast = TimeStepSys; CurrentEndTimeLast = CurrentEndTime; // If regen and procees inlet temperatures are the same the coil is off, do not print out of bounds warning for this case if (std::abs(T_RegenInTemp - T_ProcInTemp) < SMALL) { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintT_RegenInTempMessage = false; BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintT_RegenInHumRatMessage = false; BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintT_ProcInTempMessage = false; BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintT_ProcInHumRatMessage = false; BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintT_FaceVelMessage = false; return; } // check boundaries of independent variables and post warnings to individual buffers to print at end of time step // checking model bounds for variables of regeneration outlet temperature equation // Regen inlet temp if (T_RegenInTemp < BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_MinRegenAirInTemp || T_RegenInTemp > BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_MaxRegenAirInTemp) { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_RegenInTempLast = T_RegenInTemp; OutputChar = RoundSigDigits(T_RegenInTemp, 2); OutputCharLo = RoundSigDigits(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_MinRegenAirInTemp, 2); OutputCharHi = RoundSigDigits(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_MaxRegenAirInTemp, 2); if (T_RegenInTemp < BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_MinRegenAirInTemp) { T_RegenInTemp = BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_MinRegenAirInTemp; } if (T_RegenInTemp > BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_MaxRegenAirInTemp) { T_RegenInTemp = BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_MaxRegenAirInTemp; } if (!WarmupFlag && !FirstHVACIteration) { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintT_RegenInTempMessage = true; BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_RegenInTempBuffer1 = BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PerfType + " \"" + BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).Name + "\" - Regeneration inlet air temperature used in regen outlet air temperature equation is outside model boundaries at " + OutputChar + '.'; BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_RegenInTempBuffer2 = "...Valid range = " + OutputCharLo + " to " + OutputCharHi + ". Occurrence info = " + EnvironmentName + ", " + CurMnDy + ' ' + CreateSysTimeIntervalString(); CharValue = RoundSigDigits(T_RegenInTemp, 6); BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_RegenInTempBuffer3 = "...Regeneration outlet air temperature equation: regeneration inlet air temperature passed to the model = " + CharValue; } else { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintT_RegenInTempMessage = false; } } else { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintT_RegenInTempMessage = false; } // regen inlet humidity ratio if (T_RegenInHumRat < BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_MinRegenAirInHumRat || T_RegenInHumRat > BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_MaxRegenAirInHumRat) { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_RegenInHumRatLast = T_RegenInHumRat; OutputChar = RoundSigDigits(T_RegenInHumRat, 6); OutputCharLo = RoundSigDigits(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_MinRegenAirInHumRat, 6); OutputCharHi = RoundSigDigits(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_MaxRegenAirInHumRat, 6); if (T_RegenInHumRat < BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_MinRegenAirInHumRat) { T_RegenInHumRat = BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_MinRegenAirInHumRat; } if (T_RegenInHumRat > BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_MaxRegenAirInHumRat) { T_RegenInHumRat = BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_MaxRegenAirInHumRat; } if (!WarmupFlag && !FirstHVACIteration) { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintT_RegenInHumRatMessage = true; BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_RegenInHumRatBuffer1 = BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PerfType + " \"" + BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).Name + "\" - Regeneration inlet air humidity ratio used in regen outlet air temperature equation is outside model boundaries at " + OutputChar + '.'; BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_RegenInHumRatBuffer2 = "...Valid range = " + OutputCharLo + " to " + OutputCharHi + ". Occurrence info = " + EnvironmentName + ", " + CurMnDy + ' ' + CreateSysTimeIntervalString(); CharValue = RoundSigDigits(T_RegenInHumRat, 6); BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_RegenInHumRatBuffer3 = "...Regeneration outlet air temperature equation: regeneration inlet air humidity ratio passed to the model = " + CharValue; } else { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintT_RegenInHumRatMessage = false; } } else { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintT_RegenInHumRatMessage = false; } // process inlet temp if (T_ProcInTemp < BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_MinProcAirInTemp || T_ProcInTemp > BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_MaxProcAirInTemp) { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_ProcInTempLast = T_ProcInTemp; OutputChar = RoundSigDigits(T_ProcInTemp, 2); OutputCharLo = RoundSigDigits(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_MinProcAirInTemp, 2); OutputCharHi = RoundSigDigits(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_MaxProcAirInTemp, 2); if (T_ProcInTemp < BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_MinProcAirInTemp) { T_ProcInTemp = BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_MinProcAirInTemp; } if (T_ProcInTemp > BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_MaxProcAirInTemp) { T_ProcInTemp = BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_MaxProcAirInTemp; } if (!WarmupFlag && !FirstHVACIteration) { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintT_ProcInTempMessage = true; // Suppress warning message when process inlet temperature = 0 (DX coil is off) if (BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_ProcInTempLast == 0.0) BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintT_ProcInTempMessage = false; BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_ProcInTempBuffer1 = BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PerfType + " \"" + BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).Name + "\" - Process inlet air temperature used in regen outlet air temperature equation is outside model boundaries at " + OutputChar + '.'; BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_ProcInTempBuffer2 = "...Valid range = " + OutputCharLo + " to " + OutputCharHi + ". Occurrence info = " + EnvironmentName + ',' + CurMnDy + ' ' + CreateSysTimeIntervalString(); CharValue = RoundSigDigits(T_ProcInTemp, 6); BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_ProcInTempBuffer3 = "...Regeneration outlet air temperature equation: process inlet air temperature passed to the model = " + CharValue; } else { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintT_ProcInTempMessage = false; } } else { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintT_ProcInTempMessage = false; } // process inlet humidity ratio if (T_ProcInHumRat < BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_MinProcAirInHumRat || T_ProcInHumRat > BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_MaxProcAirInHumRat) { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_ProcInHumRatLast = T_ProcInHumRat; OutputChar = RoundSigDigits(T_ProcInHumRat, 6); OutputCharLo = RoundSigDigits(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_MinProcAirInHumRat, 6); OutputCharHi = RoundSigDigits(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_MaxProcAirInHumRat, 6); if (T_ProcInHumRat < BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_MinProcAirInHumRat) { T_ProcInHumRat = BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_MinProcAirInHumRat; } if (T_ProcInHumRat > BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_MaxProcAirInHumRat) { T_ProcInHumRat = BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_MaxProcAirInHumRat; } if (!WarmupFlag && !FirstHVACIteration) { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintT_ProcInHumRatMessage = true; // Suppress warning message when process inlet humrat = 0 (DX coil is off) if (BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_ProcInHumRatLast == 0.0) BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintT_ProcInHumRatMessage = false; BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_ProcInHumRatBuffer1 = BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PerfType + " \"" + BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).Name + "\" - Process inlet air humidity ratio used in regen outlet air temperature equation is outside model boundaries at " + OutputChar + '.'; BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_ProcInHumRatBuffer2 = "...Valid range = " + OutputCharLo + " to " + OutputCharHi + ". Occurrence info = " + EnvironmentName + ", " + CurMnDy + ' ' + CreateSysTimeIntervalString(); CharValue = RoundSigDigits(T_ProcInHumRat, 6); BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_ProcInHumRatBuffer3 = "...Regeneration outlet air temperature equation: process inlet air humidity ratio passed to the model = " + CharValue; } else { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintT_ProcInHumRatMessage = false; } } else { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintT_ProcInHumRatMessage = false; } // regeneration and process face velocity if (T_FaceVel < BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_MinFaceVel || T_FaceVel > BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_MaxFaceVel) { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_FaceVelLast = T_FaceVel; OutputChar = RoundSigDigits(T_FaceVel, 6); OutputCharLo = RoundSigDigits(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_MinFaceVel, 6); OutputCharHi = RoundSigDigits(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_MaxFaceVel, 6); if (T_FaceVel < BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_MinFaceVel) { T_FaceVel = BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_MinFaceVel; } if (T_FaceVel > BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_MaxFaceVel) { T_FaceVel = BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_MaxFaceVel; } if (!WarmupFlag && !FirstHVACIteration) { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintT_FaceVelMessage = true; BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_FaceVelBuffer1 = BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PerfType + " \"" + BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).Name + "\" - Process and regen inlet air face velocity used in regen outlet air temperature equation is outside model boundaries at " + OutputChar + '.'; BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_FaceVelBuffer2 = "...Valid range = " + OutputCharLo + " to " + OutputCharHi + ". Occurrence info = " + EnvironmentName + ", " + CurMnDy + ' ' + CreateSysTimeIntervalString(); CharValue = RoundSigDigits(T_FaceVel, 6); BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_FaceVelBuffer3 = "...Regeneration outlet air temperature equation: process and regen face velocity passed to the model = " + CharValue; } else { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintT_FaceVelMessage = false; } } else { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintT_FaceVelMessage = false; } } void CheckModelBoundsHumRatEq(int const ExchNum, // number of the current heat exchanger being simulated Real64 &H_RegenInTemp, // current regen inlet temperature (C) for regen outlet hum rat eqn Real64 &H_RegenInHumRat, // current regen inlet hum rat for regen outlet hum rat eqn Real64 &H_ProcInTemp, // current process inlet temperature (C) for regen outlet hum rat eqn Real64 &H_ProcInHumRat, // current process inlet hum rat for regen outlet hum rat eqn Real64 &H_FaceVel, // current process and regen face velocity (m/s) bool const FirstHVACIteration // First HVAC iteration flag ) { // SUBROUTINE INFORMATION: // AUTHOR Mangesh Basarkar, FSEC // DATE WRITTEN January 2007 // MODIFIED na // RE-ENGINEERED na // PURPOSE OF THIS SUBROUTINE: // To verify that the empirical model's independent variables are within the limits used during the // developement of the empirical model. // METHODOLOGY EMPLOYED: // The empirical models used for simulating a desiccant enhanced cooling coil are based on a limited data set. // Extrapolation of empirical models can cause instability and the independent variables may need to be limited. // The range of each independent variable is provided by the user and are based on the limits of the // empirical model. These limits are tested in this subroutine each time step and returned for use by the calling // routine. // REFERENCES: // na // Using/Aliasing using DataGlobals::CurrentTime; using DataHVACGlobals::SysTimeElapsed; using DataHVACGlobals::TimeStepSys; using General::CreateSysTimeIntervalString; using General::RoundSigDigits; // Locals // SUBROUTINE ARGUMENT DEFINITIONS: // regen outlet humidity ratio equation // SUBROUTINE PARAMETER DEFINITIONS: // CHARACTER(len=*), PARAMETER :: OutputFormat ='(F10.6)' // INTERFACE BLOCK SPECIFICATIONS: // na // DERIVED TYPE DEFINITIONS: // na // SUBROUTINE LOCAL VARIABLE DECLARATIONS: static std::string OutputChar; // character string for warning messages static std::string OutputCharLo; // character string for warning messages static std::string OutputCharHi; // character string for warning messages static std::string CharValue; // character string for warning messages static Real64 TimeStepSysLast(0.0); // last system time step (used to check for downshifting) static Real64 CurrentEndTime(0.0); // end time of time step for current simulation time step static Real64 CurrentEndTimeLast(0.0); // end time of time step for last simulation time step // current end time is compared with last to see if time step changed // calculate end time of current time step CurrentEndTime = CurrentTime + SysTimeElapsed; // Print warning messages only when valid and only for the first ocurrance. Let summary provide statistics. // Wait for next time step to print warnings. If simulation iterates, print out // the warning for the last iteration only. Must wait for next time step to accomplish this. // If a warning occurs and the simulation down shifts, the warning is not valid. if (CurrentEndTime > CurrentEndTimeLast && TimeStepSys >= TimeStepSysLast) { // print error for variables of regeneration outlet humidity ratio equation // Regen inlet temp for humidity ratio eqn if (BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintH_RegenInTempMessage) { ++BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_RegenInTempErrorCount; if (BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_RegenInTempErrorCount < 2) { ShowWarningError(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_RegenInTempBuffer1); ShowContinueError(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_RegenInTempBuffer2); ShowContinueError(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_RegenInTempBuffer3); ShowContinueError("...Using regeneration inlet air temperatures that are outside the regeneration inlet air temperature equation " "model boundaries may adversely affect desiccant model performance."); } else { ShowRecurringWarningErrorAtEnd(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PerfType + " \"" + BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).Name + "\" - Regeneration inlet air temperature used in regen outlet air humidity ratio equation is " "out of range error continues...", BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_RegenInTempErrIndex, BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_RegenInTempLast, BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_RegenInTempLast); } } // Regen inlet humidity ratio for humidity ratio eqn if (BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintH_RegenInHumRatMessage) { ++BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_RegenInHumRatErrorCount; if (BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_RegenInHumRatErrorCount < 2) { ShowWarningError(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_RegenInHumRatBuffer1); ShowContinueError(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_RegenInHumRatBuffer2); ShowContinueError(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_RegenInHumRatBuffer3); ShowContinueError("...Using regeneration inlet air humidity ratios that are outside the regeneration outlet air humidity ratio " "equation model boundaries may adversely affect desiccant model performance."); } else { ShowRecurringWarningErrorAtEnd(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PerfType + " \"" + BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).Name + "\" - Regeneration inlet air humidity ratio used in regen outlet air humidity ratio equation " "is out of range error continues...", BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_RegenInHumRatErrIndex, BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_RegenInHumRatLast, BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_RegenInHumRatLast); } } // Process inlet temp for humidity ratio eqn if (BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintH_ProcInTempMessage) { ++BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_ProcInTempErrorCount; if (BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_ProcInTempErrorCount < 2) { ShowWarningError(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_ProcInTempBuffer1); ShowContinueError(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_ProcInTempBuffer2); ShowContinueError(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_ProcInTempBuffer3); ShowContinueError("...Using process inlet air temperatures that are outside the regeneration outlet air humidity ratio equation " "model may adversely affect desiccant model performance."); } else { ShowRecurringWarningErrorAtEnd( BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PerfType + " \"" + BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).Name + "\" - Process inlet air temperature used in regen outlet air humidity ratio equation is out of range error continues...", BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_ProcInTempErrIndex, BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_ProcInTempLast, BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_ProcInTempLast); } } // Process inlet humidity ratio for humidity ratio eqn if (BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintH_ProcInHumRatMessage) { ++BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_ProcInHumRatErrorCount; if (BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_ProcInHumRatErrorCount < 2) { ShowWarningError(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_ProcInHumRatBuffer1); ShowContinueError(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_ProcInHumRatBuffer2); ShowContinueError(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_ProcInHumRatBuffer3); ShowContinueError("...Using process inlet air humidity ratios that are outside the regeneration outlet humidity ratio equation " "model boundaries may adversely affect desiccant model performance."); } else { ShowRecurringWarningErrorAtEnd(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PerfType + " \"" + BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).Name + "\" - Process inlet air humidity ratio used in regen outlet air humidity ratio equation is " "out of range error continues...", BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_ProcInHumRatErrIndex, BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_ProcInHumRatLast, BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_ProcInHumRatLast); } } // Process and regeneration face velocity for humidity ratio eqn if (BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintH_FaceVelMessage) { ++BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_FaceVelErrorCount; if (BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_FaceVelErrorCount < 2) { ShowWarningError(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_FaceVelBuffer1); ShowContinueError(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_FaceVelBuffer2); ShowContinueError(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_FaceVelBuffer3); ShowContinueError("...Using process and regeneration face velocities that are outside the regeneration outlet air humidity ratio " "equation model boundaries may adversely affect desiccant model performance."); } else { ShowRecurringWarningErrorAtEnd(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PerfType + " \"" + BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).Name + "\" - Process and regen face velocity used in regen outlet air humidity ratio equation is out " "of range error continues...", BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_FaceVelocityErrIndex, BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_FaceVelLast, BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_FaceVelLast); } } } // IF(CurrentEndTime .GT. CurrentEndTimeLast .AND. TimeStepSys .GE. TimeStepSysLast)THEN // save last system time step and last end time of current time step (used to determine if warning is valid) TimeStepSysLast = TimeStepSys; CurrentEndTimeLast = CurrentEndTime; // If regen and procees inlet temperatures are the same the coil is off, do not print out of bounds warning for this case if (std::abs(H_RegenInTemp - H_ProcInTemp) < SMALL) { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintH_RegenInTempMessage = false; BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintH_RegenInHumRatMessage = false; BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintH_ProcInTempMessage = false; BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintH_ProcInHumRatMessage = false; BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintH_FaceVelMessage = false; return; } // check boundaries of independent variables and post warnings to individual buffers to print at end of time step // checking model bounds for variables of regeneration outlet humidity ratio equation // Regen inlet temp if (H_RegenInTemp < BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_MinRegenAirInTemp || H_RegenInTemp > BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_MaxRegenAirInTemp) { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_RegenInTempLast = H_RegenInTemp; OutputChar = RoundSigDigits(H_RegenInTemp, 2); OutputCharLo = RoundSigDigits(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_MinRegenAirInTemp, 2); OutputCharHi = RoundSigDigits(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_MaxRegenAirInTemp, 2); if (H_RegenInTemp < BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_MinRegenAirInTemp) { H_RegenInTemp = BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_MinRegenAirInTemp; } if (H_RegenInTemp > BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_MaxRegenAirInTemp) { H_RegenInTemp = BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_MaxRegenAirInTemp; } if (!WarmupFlag && !FirstHVACIteration) { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintH_RegenInTempMessage = true; BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_RegenInTempBuffer1 = BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PerfType + " \"" + BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).Name + "\" - Regeneration inlet air temperature used in regen outlet air humidity ratio equation is outside model boundaries at " + OutputChar + '.'; BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_RegenInTempBuffer2 = "...Valid range = " + OutputCharLo + " to " + OutputCharHi + ". Occurrence info = " + EnvironmentName + ", " + CurMnDy + " , " + CreateSysTimeIntervalString(); CharValue = RoundSigDigits(H_RegenInTemp, 2); BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_RegenInTempBuffer3 = "...Regeneration outlet air humidity ratio equation: regeneration inlet air temperature passed to the model = " + CharValue; } else { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintH_RegenInTempMessage = false; } } else { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintH_RegenInTempMessage = false; } // regen inlet humidity ratio if (H_RegenInHumRat < BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_MinRegenAirInHumRat || H_RegenInHumRat > BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_MaxRegenAirInHumRat) { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_RegenInHumRatLast = H_RegenInHumRat; OutputChar = RoundSigDigits(H_RegenInHumRat, 6); OutputCharLo = RoundSigDigits(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_MinRegenAirInHumRat, 6); OutputCharHi = RoundSigDigits(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_MaxRegenAirInHumRat, 6); if (H_RegenInHumRat < BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_MinRegenAirInHumRat) { H_RegenInHumRat = BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_MinRegenAirInHumRat; } if (H_RegenInHumRat > BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_MaxRegenAirInHumRat) { H_RegenInHumRat = BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_MaxRegenAirInHumRat; } if (!WarmupFlag && !FirstHVACIteration) { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintH_RegenInHumRatMessage = true; BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_RegenInHumRatBuffer1 = BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PerfType + " \"" + BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).Name + "\" - Regeneration inlet air humidity ratio used in regen outlet air humidity ratio equation is outside model boundaries at " + OutputChar + '.'; BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_RegenInHumRatBuffer2 = "...Valid range = " + OutputCharLo + " to " + OutputCharHi + ". Occurrence info = " + EnvironmentName + ", " + CurMnDy + ' ' + CreateSysTimeIntervalString(); CharValue = RoundSigDigits(H_RegenInHumRat, 6); BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_RegenInHumRatBuffer3 = "...Regeneration outlet air humidity ratio equation: regeneration inlet air humidity ratio passed to the model = " + CharValue; } else { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintH_RegenInHumRatMessage = false; } } else { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintH_RegenInHumRatMessage = false; } // process inlet temp if (H_ProcInTemp < BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_MinProcAirInTemp || H_ProcInTemp > BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_MaxProcAirInTemp) { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_ProcInTempLast = H_ProcInTemp; OutputChar = RoundSigDigits(H_ProcInTemp, 2); OutputCharLo = RoundSigDigits(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_MinProcAirInTemp, 2); OutputCharHi = RoundSigDigits(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_MaxProcAirInTemp, 2); if (H_ProcInTemp < BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_MinProcAirInTemp) { H_ProcInTemp = BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_MinProcAirInTemp; } if (H_ProcInTemp > BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_MaxProcAirInTemp) { H_ProcInTemp = BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_MaxProcAirInTemp; } if (!WarmupFlag && !FirstHVACIteration) { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintH_ProcInTempMessage = true; // Suppress warning message when process inlet temperature = 0 (DX coil is off) if (BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_ProcInTempLast == 0.0) BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintH_ProcInTempMessage = false; BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_ProcInTempBuffer1 = BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PerfType + " \"" + BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).Name + "\" - Process inlet air temperature used in regen outlet air humidity ratio equation is outside model boundaries at " + OutputChar + '.'; BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_ProcInTempBuffer2 = "...Valid range = " + OutputCharLo + " to " + OutputCharHi + ". Occurrence info = " + EnvironmentName + ", " + CurMnDy + ' ' + CreateSysTimeIntervalString(); CharValue = RoundSigDigits(H_ProcInTemp, 6); BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_ProcInTempBuffer3 = "...Regeneration outlet air humidity ratio equation: process inlet air temperature passed to the model = " + CharValue; } else { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintH_ProcInTempMessage = false; } } else { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintH_ProcInTempMessage = false; } // process inlet humidity ratio if (H_ProcInHumRat < BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_MinProcAirInHumRat || H_ProcInHumRat > BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_MaxProcAirInHumRat) { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_ProcInHumRatLast = H_ProcInHumRat; OutputChar = RoundSigDigits(H_ProcInHumRat, 6); OutputCharLo = RoundSigDigits(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_MinProcAirInHumRat, 6); OutputCharHi = RoundSigDigits(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_MaxProcAirInHumRat, 6); if (H_ProcInHumRat < BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_MinProcAirInHumRat) { H_ProcInHumRat = BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_MinProcAirInHumRat; } if (H_ProcInHumRat > BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_MaxProcAirInHumRat) { H_ProcInHumRat = BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_MaxProcAirInHumRat; } if (!WarmupFlag && !FirstHVACIteration) { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintH_ProcInHumRatMessage = true; // Suppress warning message when process inlet humrat = 0 (DX coil is off) if (BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_ProcInHumRatLast == 0.0) BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintH_ProcInHumRatMessage = false; BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_ProcInHumRatBuffer1 = BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PerfType + " \"" + BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).Name + "\" - Process inlet air humidity ratio used in regen outlet air humidity ratio equation is outside model boundaries at " + OutputChar + '.'; BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_ProcInHumRatBuffer2 = "...Valid range = " + OutputCharLo + " to " + OutputCharHi + ". Occurrence info = " + EnvironmentName + ", " + CurMnDy + ", " + CreateSysTimeIntervalString(); CharValue = RoundSigDigits(H_ProcInHumRat, 6); BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_ProcInHumRatBuffer3 = "...Regeneration outlet air humidity ratio equation: process inlet air humidity ratio passed to the model = " + CharValue; } else { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintH_ProcInHumRatMessage = false; } } else { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintH_ProcInHumRatMessage = false; } // regeneration and process face velocity if (H_FaceVel < BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_MinFaceVel || H_FaceVel > BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_MaxFaceVel) { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_FaceVelLast = H_FaceVel; OutputChar = RoundSigDigits(H_FaceVel, 6); OutputCharLo = RoundSigDigits(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_MinFaceVel, 6); OutputCharHi = RoundSigDigits(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_MaxFaceVel, 6); if (H_FaceVel < BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_MinFaceVel) { H_FaceVel = BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_MinFaceVel; } if (H_FaceVel > BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_MaxFaceVel) { H_FaceVel = BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_MaxFaceVel; } if (!WarmupFlag && !FirstHVACIteration) { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintH_FaceVelMessage = true; BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_FaceVelBuffer1 = BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PerfType + " \"" + BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).Name + "\" - Process and regen inlet air face velocity used in regen outlet air humidity ratio equation is outside model boundaries " "at " + OutputChar + '.'; BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_FaceVelBuffer2 = "...Valid range = " + OutputCharLo + " to " + OutputCharHi + ". Occurrence info = " + EnvironmentName + ", " + CurMnDy + ", " + CreateSysTimeIntervalString(); CharValue = RoundSigDigits(H_FaceVel, 6); BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_FaceVelBuffer3 = "...Regeneration outlet air humidity ratio equation: process and regeneration face velocity passed to the model = " + CharValue; } else { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintH_FaceVelMessage = false; } } else { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintH_FaceVelMessage = false; } } void CheckModelBoundOutput_Temp(int const ExchNum, // number of the current heat exchanger being simulated Real64 const RegenInTemp, // current regen inlet temp passed to eqn Real64 &RegenOutTemp, // current regen outlet temp from eqn bool const FirstHVACIteration // First HVAC iteration flag ) { // SUBROUTINE INFORMATION: // AUTHOR Mangesh Basarkar, FSEC // DATE WRITTEN January 2007 // MODIFIED June 2007, R. Raustad, changed requirement that regen outlet temp be less than inlet temp // RE-ENGINEERED na // PURPOSE OF THIS SUBROUTINE: // To verify that the empirical model's independent variables are within the limits used during the // developement of the empirical model. // METHODOLOGY EMPLOYED: // The empirical models used for simulating a desiccant enhanced cooling coil are based on a limited data set. // Extrapolation of empirical models can cause instability and the independent variables may need to be limited. // The range of each independent variable is provided by the user and are based on the limits of the // empirical model. These limits are tested in this subroutine each time step and returned for use by the calling // routine. // REFERENCES: // na // Using/Aliasing using DataGlobals::CurrentTime; using DataHVACGlobals::SysTimeElapsed; using DataHVACGlobals::TimeStepSys; using General::CreateSysTimeIntervalString; using General::RoundSigDigits; // Locals // SUBROUTINE ARGUMENT DEFINITIONS: // SUBROUTINE PARAMETER DEFINITIONS: // CHARACTER(len=*), PARAMETER :: OutputFormat ='(F10.6)' // INTERFACE BLOCK SPECIFICATIONS: // na // DERIVED TYPE DEFINITIONS: // na // SUBROUTINE LOCAL VARIABLE DECLARATIONS: static std::string OutputChar; // character string for warning messages static std::string OutputCharLo; // character string for warning messages static std::string OutputCharHi; // character string for warning messages static std::string CharValue; // character string for warning messages static Real64 TimeStepSysLast(0.0); // last system time step (used to check for downshifting) static Real64 CurrentEndTime(0.0); // end time of time step for current simulation time step static Real64 CurrentEndTimeLast(0.0); // end time of time step for last simulation time step // current end time is compared with last to see if time step changed // calculate end time of current time step CurrentEndTime = CurrentTime + SysTimeElapsed; // Print warning messages only when valid and only for the first ocurrance. Let summary provide statistics. // Wait for next time step to print warnings. If simulation iterates, print out // the warning for the last iteration only. Must wait for next time step to accomplish this. // If a warning occurs and the simulation down shifts, the warning is not valid. if (CurrentEndTime > CurrentEndTimeLast && TimeStepSys >= TimeStepSysLast) { // print error when regeneration outlet temperature is greater than regen inlet temperature if (BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintRegenOutTempFailedMessage) { ++BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenOutTempFailedErrorCount; if (BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenOutTempFailedErrorCount < 2) { ShowWarningError(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenOutTempFailedBuffer1); ShowContinueError(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenOutTempFailedBuffer2); ShowContinueError("...Regeneration outlet air temperature should always be less than or equal to regen inlet air temperature. " "Verify correct model coefficients."); } else { ShowRecurringWarningErrorAtEnd( BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PerfType + " \"" + BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).Name + "\" - Regeneration outlet air temperature above regen inlet air temperature error continues...", BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenOutTempFailedErrIndex, BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenOutTempFailedLast, BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenOutTempFailedLast); } } // print error for variables of regeneration outlet temperature if (BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintRegenOutTempMessage) { ++BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenOutTempErrorCount; if (BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenOutTempErrorCount < 2) { ShowWarningError(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenOutTempBuffer1); ShowContinueError(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenOutTempBuffer2); ShowContinueError(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenOutTempBuffer3); ShowContinueError("...Regeneration outlet air temperature should always be less than or equal to regen inlet air temperature. " "Verify correct model coefficients."); } else { ShowRecurringWarningErrorAtEnd( BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PerfType + " \"" + BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).Name + "\" - Regeneration outlet air temperature should be less than regen inlet air temperature error continues...", BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenOutTempErrIndex, BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenOutTempLast, BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenOutTempLast); } } } // IF(CurrentEndTime .GT. CurrentEndTimeLast .AND. TimeStepSys .GE. TimeStepSysLast)THEN // save last system time step and last end time of current time step (used to determine if warning is valid) TimeStepSysLast = TimeStepSys; CurrentEndTimeLast = CurrentEndTime; // checking model regeneration outlet temperature to always be less than or equal to regeneration inlet temperature if (RegenOutTemp > RegenInTemp) { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenOutTempFailedLast = RegenOutTemp; OutputChar = RoundSigDigits(RegenOutTemp, 2); OutputCharHi = RoundSigDigits(RegenInTemp, 2); // IF(RegenOutTemp .GT. RegenInTemp)THEN // RegenOutTemp = RegenInTemp // END IF if (!WarmupFlag && !FirstHVACIteration) { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintRegenOutTempFailedMessage = true; BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenOutTempFailedBuffer1 = BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PerfType + " \"" + BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).Name + "\" - Regeneration outlet air temperature is greater than inlet temperature at " + OutputChar + '.'; BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenOutTempFailedBuffer2 = "...Regen inlet air temperature = " + OutputCharHi + ". Occurrence info = " + EnvironmentName + ", " + CurMnDy + ", " + CreateSysTimeIntervalString(); CharValue = RoundSigDigits(RegenOutTemp, 6); BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenOutTempFailedBuffer3 = "...Regen outlet air temperature equation: regeneration outlet air temperature allowed from the model = " + CharValue; } else { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintRegenOutTempMessage = false; } } else { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintRegenOutTempMessage = false; } // check boundaries of regen outlet temperature and post warnings to individual buffers to print at end of time step // checking model bounds for regeneration outlet temperature if (RegenOutTemp < BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).MinRegenAirOutTemp || RegenOutTemp > BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).MaxRegenAirOutTemp) { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenOutTempLast = RegenOutTemp; OutputChar = RoundSigDigits(RegenOutTemp, 2); OutputCharLo = RoundSigDigits(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).MinRegenAirOutTemp, 2); OutputCharHi = RoundSigDigits(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).MaxRegenAirOutTemp, 2); if (RegenOutTemp < BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).MinRegenAirOutTemp) { RegenOutTemp = BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).MinRegenAirOutTemp; } if (RegenOutTemp > BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).MaxRegenAirOutTemp) { RegenOutTemp = BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).MaxRegenAirOutTemp; } if (!WarmupFlag && !FirstHVACIteration) { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintRegenOutTempMessage = true; BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenOutTempBuffer1 = BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PerfType + " \"" + BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).Name + "\" - Regeneration outlet air temperature equation is outside model boundaries at " + OutputChar + '.'; BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenOutTempBuffer2 = "...Valid range = " + OutputCharLo + " to " + OutputCharHi + ". Occurrence info = " + EnvironmentName + ", " + CurMnDy + ", " + CreateSysTimeIntervalString(); CharValue = RoundSigDigits(RegenOutTemp, 6); BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenOutTempBuffer3 = "...Regen outlet air temperature equation: regeneration outlet air temperature allowed from the model = " + CharValue; } else { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintRegenOutTempMessage = false; } } else { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintRegenOutTempMessage = false; } } void CheckModelBoundOutput_HumRat(int const ExchNum, // number of the current heat exchanger being simulated Real64 const RegenInHumRat, // current regen inlet hum rat passed to eqn Real64 &RegenOutHumRat, // current regen outlet hum rat from eqn bool const FirstHVACIteration // First HVAC iteration flag ) { // SUBROUTINE INFORMATION: // AUTHOR Mangesh Basarkar, FSEC // DATE WRITTEN January 2007 // MODIFIED June 2007, R. Raustad, changed requirement that regen outlet temp be less than inlet temp // RE-ENGINEERED na // PURPOSE OF THIS SUBROUTINE: // To verify that the empirical model's independent variables are within the limits used during the // developement of the empirical model. // METHODOLOGY EMPLOYED: // The empirical models used for simulating a desiccant enhanced cooling coil are based on a limited data set. // Extrapolation of empirical models can cause instability and the independent variables may need to be limited. // The range of each independent variable is provided by the user and are based on the limits of the // empirical model. These limits are tested in this subroutine each time step and returned for use by the calling // routine. // REFERENCES: // na // Using/Aliasing using DataGlobals::CurrentTime; using DataHVACGlobals::SysTimeElapsed; using DataHVACGlobals::TimeStepSys; using General::CreateSysTimeIntervalString; using General::RoundSigDigits; // Locals // SUBROUTINE ARGUMENT DEFINITIONS // SUBROUTINE PARAMETER DEFINITIONS: // CHARACTER(len=*), PARAMETER :: OutputFormat ='(F10.6)' // INTERFACE BLOCK SPECIFICATIONS: // na // DERIVED TYPE DEFINITIONS: // na // SUBROUTINE LOCAL VARIABLE DECLARATIONS: static std::string OutputChar; // character string for warning messages static std::string OutputCharLo; // character string for warning messages static std::string OutputCharHi; // character string for warning messages static std::string CharValue; // character string for warning messages static Real64 TimeStepSysLast(0.0); // last system time step (used to check for downshifting) static Real64 CurrentEndTime(0.0); // end time of time step for current simulation time step static Real64 CurrentEndTimeLast(0.0); // end time of time step for last simulation time step // current end time is compared with last to see if time step changed // calculate end time of current time step CurrentEndTime = CurrentTime + SysTimeElapsed; // Print warning messages only when valid and only for the first ocurrance. Let summary provide statistics. // Wait for next time step to print warnings. If simulation iterates, print out // the warning for the last iteration only. Must wait for next time step to accomplish this. // If a warning occurs and the simulation down shifts, the warning is not valid. if (CurrentEndTime > CurrentEndTimeLast && TimeStepSys >= TimeStepSysLast) { // print error when regeneration outlet humidity ratio is less than regeneration inlet humidity ratio if (BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintRegenOutHumRatFailedMess) { ++BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenOutHumRatFailedErrorCount; if (BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenOutHumRatFailedErrorCount < 2) { ShowWarningError(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenOutHumRatFailedBuffer1); ShowContinueError(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenOutHumRatFailedBuffer2); ShowContinueError("...Regeneration outlet air humidity ratio should always be greater than or equal to regen inlet air humidity " "ratio. Verify correct model coefficients."); } else { ShowRecurringWarningErrorAtEnd( BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PerfType + " \"" + BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).Name + "\" - Regeneration outlet air humidity ratio should be greater than regen inlet air humidity ratio error continues...", BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenOutHumRatFailedErrIndex, BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenOutHumRatFailedLast, BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenOutHumRatFailedLast); } } // print error for regeneration outlet humidity ratio if (BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintRegenOutHumRatMessage) { ++BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenOutHumRatErrorCount; if (BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenOutHumRatErrorCount < 2) { ShowWarningError(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenOutHumRatBuffer1); ShowContinueError(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenOutHumRatBuffer2); ShowContinueError(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenOutHumRatBuffer3); ShowContinueError( "...Regeneration outlet air humidity ratio outside model boundaries may adversely affect desiccant model performance."); } else { ShowRecurringWarningErrorAtEnd(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PerfType + " \"" + BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).Name + "\" - Regeneration outlet air humidity ratio is out of range error continues...", BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenOutHumRatErrIndex, BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenOutHumRatLast, BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenOutHumRatLast); } } } // IF(CurrentEndTime .GT. CurrentEndTimeLast .AND. TimeStepSys .GE. TimeStepSysLast)THEN // save last system time step and last end time of current time step (used to determine if warning is valid) TimeStepSysLast = TimeStepSys; CurrentEndTimeLast = CurrentEndTime; // checking for regeneration outlet humidity ratio less than or equal to regeneration inlet humidity ratio if (RegenOutHumRat < RegenInHumRat) { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenOutHumRatFailedLast = RegenOutHumRat; OutputChar = RoundSigDigits(RegenOutHumRat, 6); OutputCharHi = RoundSigDigits(RegenInHumRat, 6); // IF(RegenOutHumRat .LT. RegenInHumRat)THEN // RegenOutHumRat = RegenInHumRat // END IF if (!WarmupFlag && !FirstHVACIteration) { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintRegenOutHumRatFailedMess = true; BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenOutHumRatFailedBuffer1 = BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PerfType + " \"" + BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).Name + "\" - Regeneration outlet air humidity ratio is less than the inlet air humidity ratio at " + OutputChar + '.'; BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenOutHumRatFailedBuffer2 = "...Regen inlet air humidity ratio = " + OutputCharHi + ". Occurrence info = " + EnvironmentName + ", " + CurMnDy + ", " + CreateSysTimeIntervalString(); CharValue = RoundSigDigits(RegenOutHumRat, 6); BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenOutHumRatFailedBuffer3 = "...Regen outlet air humidity ratio equation: regeneration outlet air humidity ratio allowed from the model = " + CharValue; } else { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintRegenOutHumRatFailedMess = false; } } else { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintRegenOutHumRatFailedMess = false; } // check boundaries of regen outlet humrat and post warnings to individual buffers to print at end of time step // checking model bounds for regeneration outlet humidity ratio if (RegenOutHumRat < BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).MinRegenAirOutHumRat || RegenOutHumRat > BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).MaxRegenAirOutHumRat) { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenOutHumRatLast = RegenOutHumRat; OutputChar = RoundSigDigits(RegenOutHumRat, 6); OutputCharLo = RoundSigDigits(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).MinRegenAirOutHumRat, 6); OutputCharHi = RoundSigDigits(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).MaxRegenAirOutHumRat, 6); if (RegenOutHumRat < BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).MinRegenAirOutHumRat) { RegenOutHumRat = BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).MinRegenAirOutHumRat; } if (RegenOutHumRat > BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).MaxRegenAirOutHumRat) { RegenOutHumRat = BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).MaxRegenAirOutHumRat; } if (!WarmupFlag && !FirstHVACIteration) { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintRegenOutHumRatMessage = true; BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenOutHumRatBuffer1 = BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PerfType + " \"" + BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).Name + "\" - Regeneration outlet air humidity ratio is outside model boundaries at " + OutputChar + '.'; BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenOutHumRatBuffer2 = "...Valid range = " + OutputCharLo + " to " + OutputCharHi + ". Occurrence info = " + EnvironmentName + ", " + CurMnDy + ", " + CreateSysTimeIntervalString(); CharValue = RoundSigDigits(RegenOutHumRat, 6); BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenOutHumRatBuffer3 = "...Regen outlet air humidity ratio equation: regeneration outlet air humidity ratio allowed from the model = " + CharValue; } else { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintRegenOutHumRatMessage = false; } } else { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintRegenOutHumRatMessage = false; } } void CheckModelBoundsRH_TempEq(int const ExchNum, // number of the current heat exchanger being simulated Real64 const T_RegenInTemp, // current regen inlet temperature passed to eqn Real64 const T_RegenInHumRat, // current regen inlet hum rat passed to eqn Real64 const T_ProcInTemp, // current process inlet temperature passed to eqn Real64 const T_ProcInHumRat, // current regen outlet hum rat from eqn bool const FirstHVACIteration // first HVAC iteration flag ) { // SUBROUTINE INFORMATION: // AUTHOR Richard Raustad, FSEC // DATE WRITTEN January 2007 // MODIFIED na // RE-ENGINEERED na // PURPOSE OF THIS SUBROUTINE: // To verify that the empirical model's independent variables result in a relative humidity that is within the range // of relative humidities used when creating the empirical model. Both the regeneration and process inlet are tested. // METHODOLOGY EMPLOYED: // The empirical models used for simulating a desiccant enhanced cooling coil are based on a limited data set. // Extrapolation of empirical models can cause instability and the independent variables may need to be limited. // In addition, the range of relative humidities in the original data set may influence the output of the // empirical model. This subroutine tests the relative humidities passed to the empirical model and warns the // user if these relative humidities are out of bounds based on the limits set by the user. // REFERENCES: // na // Using/Aliasing using DataGlobals::CurrentTime; using DataHVACGlobals::SysTimeElapsed; using DataHVACGlobals::TimeStepSys; using General::CreateSysTimeIntervalString; using General::RoundSigDigits; using Psychrometrics::PsyRhFnTdbWPb; // Locals // SUBROUTINE ARGUMENT DEFINITIONS // SUBROUTINE PARAMETER DEFINITIONS: // CHARACTER(len=*), PARAMETER :: OutputFormat ='(F10.6)' // INTERFACE BLOCK SPECIFICATIONS: // na // DERIVED TYPE DEFINITIONS: // na // SUBROUTINE LOCAL VARIABLE DECLARATIONS: static Real64 RegenInletRH(0.0); // Regeneration inlet air relative humidity static Real64 ProcInletRH(0.0); // Process inlet air relative humidity static std::string OutputChar; // character string for warning messages static std::string OutputCharLo; // character string for warning messages static std::string OutputCharHi; // character string for warning messages static Real64 TimeStepSysLast(0.0); // last system time step (used to check for downshifting) static Real64 CurrentEndTime(0.0); // end time of time step for current simulation time step static Real64 CurrentEndTimeLast(0.0); // end time of time step for last simulation time step // current end time is compared with last to see if time step changed if (WarmupFlag || FirstHVACIteration) return; // calculate end time of current time step CurrentEndTime = CurrentTime + SysTimeElapsed; // Print warning messages only when valid and only for the first ocurrance. Let summary provide statistics. // Wait for next time step to print warnings. If simulation iterates, print out // the warning for the last iteration only. Must wait for next time step to accomplish this. // If a warning occurs and the simulation down shifts, the warning is not valid. if (CurrentEndTime > CurrentEndTimeLast && TimeStepSys >= TimeStepSysLast) { // print error when regeneration inlet relative humidity is outside model boundaries if (BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintRegenInRelHumTempMess) { ++BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenInRelHumTempErrorCount; if (BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenInRelHumTempErrorCount < 2) { ShowWarningError(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenInRelHumTempBuffer1); ShowContinueError(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenInRelHumTempBuffer2); ShowContinueError(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenInRelHumTempBuffer3); ShowContinueError("...Using regeneration inlet air relative humidities that are outside the regeneration outlet temperature " "equation model boundaries may adversely affect desiccant model performance. Verify correct model " "coefficients."); } else { ShowRecurringWarningErrorAtEnd(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PerfType + " \"" + BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).Name + "\" - Regeneration inlet air relative humidity related to regen outlet air temperature " "equation is outside model boundaries error continues...", BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenInRelHumTempErrIndex, BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenInRelHumTempLast, BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenInRelHumTempLast); } } // print error when process inlet relative humidity is outside model boundaries if (BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintProcInRelHumTempMess) { ++BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).ProcInRelHumTempErrorCount; if (BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).ProcInRelHumTempErrorCount < 2) { ShowWarningError(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).ProcInRelHumTempBuffer1); ShowContinueError(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).ProcInRelHumTempBuffer2); ShowContinueError(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).ProcInRelHumTempBuffer3); ShowContinueError("...Using process inlet air relative humidities that are outside the regeneration outlet temperature equation " "model boundaries may adversely affect desiccant model performance. Verify correct model coefficients."); } else { ShowRecurringWarningErrorAtEnd(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PerfType + " \"" + BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).Name + "\" - Process inlet air relative humidity related to regen outlet air temperature equation is " "outside model boundaries error continues...", BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).ProcInRelHumTempErrIndex, BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).ProcInRelHumTempLast, BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).ProcInRelHumTempLast); } } } // IF(CurrentEndTime .GT. CurrentEndTimeLast .AND. TimeStepSys .GE. TimeStepSysLast)THEN // save last system time step and last end time of current time step (used to determine if warning is valid) TimeStepSysLast = TimeStepSys; CurrentEndTimeLast = CurrentEndTime; // Check that condition is not above saturation curve prior to next calc (PsyRhFnTdbWPb) to avoid psyc routine errors // * // * // x------*---------- T_HumRat // | * // | * // *----------------- PsyWFnTdpPb(Tdp,Pb) // * | // | // T_Temp if (T_RegenInHumRat > PsyWFnTdpPb(T_RegenInTemp, OutBaroPress) || T_ProcInHumRat > PsyWFnTdpPb(T_ProcInTemp, OutBaroPress)) { // reset RH print flags just in case BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintRegenInRelHumTempMess = false; BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintProcInRelHumTempMess = false; return; } // If regen and procees inlet temperatures are the same the coil is off, do not print out of bounds warning for this case if (std::abs(T_RegenInTemp - T_ProcInTemp) < SMALL) { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintRegenInRelHumTempMess = false; BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintProcInRelHumTempMess = false; return; } RegenInletRH = PsyRhFnTdbWPb(T_RegenInTemp, T_RegenInHumRat, OutBaroPress); ProcInletRH = min(1.0, PsyRhFnTdbWPb(T_ProcInTemp, T_ProcInHumRat, OutBaroPress)); // checking if regeneration inlet relative humidity is within model boundaries if (RegenInletRH < BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_MinRegenAirInRelHum || RegenInletRH > BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_MaxRegenAirInRelHum) { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenInRelHumTempLast = RegenInletRH * 100.0; OutputChar = RoundSigDigits(RegenInletRH * 100.0, 1); OutputCharLo = RoundSigDigits(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_MinRegenAirInRelHum * 100.0, 1); OutputCharHi = RoundSigDigits(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_MaxRegenAirInRelHum * 100.0, 1); BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintRegenInRelHumTempMess = true; BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenInRelHumTempBuffer1 = BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PerfType + " \"" + BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).Name + "\" - Regeneration inlet air relative humidity related to regen outlet air temperature equation is outside model boundaries at " + OutputChar + '.'; BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenInRelHumTempBuffer2 = "...Model limit on regeneration inlet air relative humidity is " + OutputCharLo + " to " + OutputCharHi + '.'; BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenInRelHumTempBuffer3 = "...Occurrence info = " + EnvironmentName + ", " + CurMnDy + ", " + CreateSysTimeIntervalString(); } else { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintRegenInRelHumTempMess = false; } // checking if process inlet relative humidity is within model boundaries if (ProcInletRH < BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_MinProcAirInRelHum || ProcInletRH > BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_MaxProcAirInRelHum) { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).ProcInRelHumTempLast = ProcInletRH * 100.0; OutputChar = RoundSigDigits(ProcInletRH * 100.0, 1); OutputCharLo = RoundSigDigits(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_MinProcAirInRelHum * 100.0, 1); OutputCharHi = RoundSigDigits(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).T_MaxProcAirInRelHum * 100.0, 1); BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintProcInRelHumTempMess = true; BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).ProcInRelHumTempBuffer1 = BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PerfType + " \"" + BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).Name + "\" - Process inlet air relative humidity related to regen outlet air temperature equation is outside model boundaries at " + OutputChar + '.'; BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).ProcInRelHumTempBuffer2 = "...Model limit on process inlet air relative humidity is " + OutputCharLo + " to " + OutputCharHi + '.'; BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).ProcInRelHumTempBuffer3 = "...Occurrence info = " + EnvironmentName + ", " + CurMnDy + ", " + CreateSysTimeIntervalString(); } else { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintProcInRelHumTempMess = false; } } void CheckModelBoundsRH_HumRatEq(int const ExchNum, // number of the current heat exchanger being simulated Real64 const H_RegenInTemp, // current regen inlet temperature passed to eqn Real64 const H_RegenInHumRat, // current regen inlet hum rat passed to eqn Real64 const H_ProcInTemp, // current process inlet temperature passed to eqn Real64 const H_ProcInHumRat, // current process inlet hum rat passed to eqn bool const FirstHVACIteration // first HVAC iteration flag ) { // SUBROUTINE INFORMATION: // AUTHOR Richard Raustad, FSEC // DATE WRITTEN January 2007 // MODIFIED na // RE-ENGINEERED na // PURPOSE OF THIS SUBROUTINE: // To verify that the empirical model's independent variables result in a relative humidity that is within the range // of relative humidities used when creating the empirical model. Both the regeneration and process inlet are tested. // METHODOLOGY EMPLOYED: // The empirical models used for simulating a desiccant enhanced cooling coil are based on a limited data set. // Extrapolation of empirical models can cause instability and the independent variables may need to be limited. // In addition, the range of relative humidities in the original data set may influence the output of the // empirical model. This subroutine tests the relative humidities passed to the empirical model and warns the // user if these relative humidities are out of bounds based on the limits set by the user. // REFERENCES: // na // Using/Aliasing using DataGlobals::CurrentTime; using DataHVACGlobals::SysTimeElapsed; using DataHVACGlobals::TimeStepSys; using General::CreateSysTimeIntervalString; using General::RoundSigDigits; using Psychrometrics::PsyRhFnTdbWPb; // Locals // SUBROUTINE ARGUMENT DEFINITIONS // SUBROUTINE PARAMETER DEFINITIONS: // CHARACTER(len=*), PARAMETER :: OutputFormat ='(F10.6)' // INTERFACE BLOCK SPECIFICATIONS: // na // DERIVED TYPE DEFINITIONS: // na // SUBROUTINE LOCAL VARIABLE DECLARATIONS: static Real64 RegenInletRH(0.0); // Regeneration inlet air relative humidity static Real64 ProcInletRH(0.0); // Process inlet air relative humidity static std::string OutputChar; // character string for warning messages static std::string OutputCharLo; // character string for warning messages static std::string OutputCharHi; // character string for warning messages static Real64 TimeStepSysLast(0.0); // last system time step (used to check for downshifting) static Real64 CurrentEndTime(0.0); // end time of time step for current simulation time step static Real64 CurrentEndTimeLast(0.0); // end time of time step for last simulation time step // current end time is compared with last to see if time step changed if (WarmupFlag || FirstHVACIteration) return; // calculate end time of current time step CurrentEndTime = CurrentTime + SysTimeElapsed; // Print warning messages only when valid and only for the first ocurrance. Let summary provide statistics. // Wait for next time step to print warnings. If simulation iterates, print out // the warning for the last iteration only. Must wait for next time step to accomplish this. // If a warning occurs and the simulation down shifts, the warning is not valid. if (CurrentEndTime > CurrentEndTimeLast && TimeStepSys >= TimeStepSysLast) { // print error when regeneration inlet relative humidity is outside model boundaries if (BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintRegenInRelHumHumRatMess) { ++BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenInRelHumHumRatErrorCount; if (BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenInRelHumHumRatErrorCount < 2) { ShowWarningError(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenInRelHumHumRatBuffer1); ShowContinueError(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenInRelHumHumRatBuffer2); ShowContinueError(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenInRelHumHumRatBuffer3); ShowContinueError("...Using regeneration inlet air relative humidities that are outside the regeneration outlet humidity ratio " "equation model boundaries may adversely affect desiccant model performance. Verify correct model " "coefficients."); } else { ShowRecurringWarningErrorAtEnd(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PerfType + " \"" + BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).Name + "\" - Regeneration inlet air relative humidity related to regen outlet air humidity ratio " "equation is outside model boundaries error continues...", BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenInRelHumHumRatErrIndex, BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenInRelHumHumRatLast, BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenInRelHumHumRatLast); } } // print error when process inlet relative humidity is outside model boundaries if (BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintProcInRelHumHumRatMess) { ++BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).ProcInRelHumHumRatErrorCount; if (BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).ProcInRelHumHumRatErrorCount < 2) { ShowWarningError(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).ProcInRelHumHumRatBuffer1); ShowContinueError(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).ProcInRelHumHumRatBuffer2); ShowContinueError(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).ProcInRelHumHumRatBuffer3); ShowContinueError("...Using process inlet air relative humidities that are outside the regeneration outlet humidity ratio " "equation model boundaries may adversely affect desiccant model performance. Verify correct model " "coefficients."); } else { ShowRecurringWarningErrorAtEnd(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PerfType + " \"" + BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).Name + "\" - Process inlet air relative humidity related to regen outlet air humidity ratio equation " "is outside model boundaries error continues...", BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).ProcInRelHumHumRatErrIndex, BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).ProcInRelHumHumRatLast, BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).ProcInRelHumHumRatLast); } } } // IF(CurrentEndTime .GT. CurrentEndTimeLast .AND. TimeStepSys .GE. TimeStepSysLast)THEN // save last system time step and last end time of current time step (used to determine if warning is valid) TimeStepSysLast = TimeStepSys; CurrentEndTimeLast = CurrentEndTime; // Check that condition is not above saturation curve prior to next calc (PsyRhFnTdbWPb) to avoid psyc routine errors // * // * // x------*---------- H_HumRat // | * // | * // *----------------- PsyWFnTdpPb(Tdp,Pb) // * | // | // H_Temp if (H_RegenInHumRat > PsyWFnTdpPb(H_RegenInTemp, OutBaroPress) || H_ProcInHumRat > PsyWFnTdpPb(H_ProcInTemp, OutBaroPress)) { // reset RH print flags just in case BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintRegenInRelHumHumRatMess = false; BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintProcInRelHumHumRatMess = false; return; } // If regen and procees inlet temperatures are the same the coil is off, do not print out of bounds warning for this case if (std::abs(H_RegenInTemp - H_ProcInTemp) < SMALL) { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintRegenInRelHumHumRatMess = false; BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintProcInRelHumHumRatMess = false; return; } RegenInletRH = PsyRhFnTdbWPb(H_RegenInTemp, H_RegenInHumRat, OutBaroPress); ProcInletRH = min(1.0, PsyRhFnTdbWPb(H_ProcInTemp, H_ProcInHumRat, OutBaroPress)); // checking if regeneration inlet relative humidity is within model boundaries if (RegenInletRH < BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_MinRegenAirInRelHum || RegenInletRH > BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_MaxRegenAirInRelHum) { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenInRelHumHumRatLast = RegenInletRH * 100.0; OutputChar = RoundSigDigits(RegenInletRH * 100.0, 1); OutputCharLo = RoundSigDigits(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_MinRegenAirInRelHum * 100.0, 1); OutputCharHi = RoundSigDigits(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_MaxRegenAirInRelHum * 100.0, 1); BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintRegenInRelHumHumRatMess = true; BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenInRelHumHumRatBuffer1 = BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PerfType + " \"" + BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).Name + "\" - Regeneration inlet air relative humidity related to regen outlet air humidity ratio equation is outside model boundaries at " + OutputChar + '.'; BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenInRelHumHumRatBuffer2 = "...Model limit on regeneration inlet air relative humidity is " + OutputCharLo + " to " + OutputCharHi + '.'; BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).RegenInRelHumHumRatBuffer3 = "...Occurrence info = " + EnvironmentName + ", " + CurMnDy + ", " + CreateSysTimeIntervalString(); } else { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintRegenInRelHumHumRatMess = false; } // checking if process inlet relative humidity is within model boundaries if (ProcInletRH < BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_MinProcAirInRelHum || ProcInletRH > BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_MaxProcAirInRelHum) { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).ProcInRelHumHumRatLast = ProcInletRH * 100.0; OutputChar = RoundSigDigits(ProcInletRH * 100.0, 1); OutputCharLo = RoundSigDigits(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_MinProcAirInRelHum * 100.0, 1); OutputCharHi = RoundSigDigits(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).H_MaxProcAirInRelHum * 100.0, 1); BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintProcInRelHumHumRatMess = true; BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).ProcInRelHumHumRatBuffer1 = BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PerfType + " \"" + BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).Name + "\" - Process inlet air relative humidity related to regen outlet air humidity ratio equation is outside model boundaries at " + OutputChar + '.'; BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).ProcInRelHumHumRatBuffer2 = "...Model limit on process inlet air relative humidity is " + OutputCharLo + " to " + OutputCharHi + '.'; BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).ProcInRelHumHumRatBuffer3 = "...Occurrence info = " + EnvironmentName + ", " + CurMnDy + ", " + CreateSysTimeIntervalString(); } else { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintProcInRelHumHumRatMess = false; } } void CheckForBalancedFlow(int const ExchNum, // number of the current heat exchanger being simulated Real64 const ProcessInMassFlow, // current process inlet air mass flow rate (m3/s) Real64 const RegenInMassFlow, // current regeneration inlet air mass flow rate (m3/s) bool const FirstHVACIteration // first HVAC iteration flag ) { // SUBROUTINE INFORMATION: // AUTHOR Richard Raustad, FSEC // DATE WRITTEN June 2007 // MODIFIED na // RE-ENGINEERED na // PURPOSE OF THIS SUBROUTINE: // To verify that the balanced flow desiccant heat exchanger has the same regeneration and process air flow rates. // METHODOLOGY EMPLOYED: // Check that the regeneration and process air mass flow rates are within 2%. // REFERENCES: // na // Using/Aliasing using DataGlobals::CurrentTime; using DataHVACGlobals::SysTimeElapsed; using DataHVACGlobals::TimeStepSys; using General::CreateSysTimeIntervalString; using General::RoundSigDigits; // Locals // SUBROUTINE ARGUMENT DEFINITIONS // SUBROUTINE PARAMETER DEFINITIONS: // CHARACTER(len=*), PARAMETER :: OutputFormat ='(F10.6)' // INTERFACE BLOCK SPECIFICATIONS: // na // DERIVED TYPE DEFINITIONS: // na // SUBROUTINE LOCAL VARIABLE DECLARATIONS: static std::string OutputCharProc; // character string for warning messages static std::string OutputCharRegen; // character string for warning messages static Real64 TimeStepSysLast(0.0); // last system time step (used to check for downshifting) static Real64 CurrentEndTime(0.0); // end time of time step for current simulation time step static Real64 CurrentEndTimeLast(0.0); // end time of time step for last simulation time step // current end time is compared with last to see if time step changed Real64 ABSImbalancedFlow; // absolute value of process and regeneration air flow imbalance fraction if (WarmupFlag || FirstHVACIteration) return; // calculate end time of current time step CurrentEndTime = CurrentTime + SysTimeElapsed; // Print warning messages only when valid and only for the first ocurrance. Let summary provide statistics. // Wait for next time step to print warnings. If simulation iterates, print out // the warning for the last iteration only. Must wait for next time step to accomplish this. // If a warning occurs and the simulation down shifts, the warning is not valid. if (CurrentEndTime > CurrentEndTimeLast && TimeStepSys >= TimeStepSysLast) { // print error when regeneration inlet relative humidity is outside model boundaries if (BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintImbalancedMassFlowMess) { ++BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).ImbalancedMassFlowErrorCount; if (BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).ImbalancedMassFlowErrorCount < 2) { ShowWarningError(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).ImbalancedMassFlowBuffer1); ShowContinueError(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).ImbalancedMassFlowBuffer2); ShowContinueError(BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).ImbalancedMassFlowBuffer3); // CALL ShowContinueError('...Using regeneration inlet air relative humidities that are outside the regeneration '& // //'outlet humidity ratio equation model boundaries may adversely affect desiccant model performance. '& // //'Verify correct model coefficients.') } else { ShowRecurringWarningErrorAtEnd( cHXTypes(ExchCond(ExchNum).ExchTypeNum) + " \"" + ExchCond(ExchNum).Name + "\" - unbalanced air flow rate is limited to 2% error continues with the imbalanced fraction statistics reported...", BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).ImbalancedFlowErrIndex, BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).ABSImbalancedFlow, BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).ABSImbalancedFlow); } } } // IF(CurrentEndTime .GT. CurrentEndTimeLast .AND. TimeStepSys .GE. TimeStepSysLast)THEN // save last system time step and last end time of current time step (used to determine if warning is valid) TimeStepSysLast = TimeStepSys; CurrentEndTimeLast = CurrentEndTime; // checking if regeneration inlet relative humidity is within model boundaries ABSImbalancedFlow = std::abs(RegenInMassFlow - ProcessInMassFlow) / RegenInMassFlow; if (ABSImbalancedFlow > 0.02) { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).ABSImbalancedFlow = ABSImbalancedFlow; OutputCharRegen = RoundSigDigits(RegenInMassFlow, 6); OutputCharProc = RoundSigDigits(ProcessInMassFlow, 6); BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintImbalancedMassFlowMess = true; BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).ImbalancedMassFlowBuffer1 = cHXTypes(ExchCond(ExchNum).ExchTypeNum) + " \"" + ExchCond(ExchNum).Name + "\" - unbalanced air flow rate is limited to 2%."; BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).ImbalancedMassFlowBuffer2 = "...Regeneration air mass flow rate is " + OutputCharRegen + " and process air mass flow rate is " + OutputCharProc + '.'; BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).ImbalancedMassFlowBuffer3 = "...Occurrence info = " + EnvironmentName + ", " + CurMnDy + ", " + CreateSysTimeIntervalString(); } else { BalDesDehumPerfData(ExchCond(ExchNum).PerfDataIndex).PrintImbalancedMassFlowMess = false; } } int GetSupplyInletNode(std::string const &HXName, // must match HX names for the ExchCond type bool &ErrorsFound // set to true if problem ) { // FUNCTION INFORMATION: // AUTHOR Richard Raustad // DATE WRITTEN February 2007 // MODIFIED na // RE-ENGINEERED na // PURPOSE OF THIS FUNCTION: // This function looks up the given HX and returns the supply air inlet node number. // If incorrect HX name is given, ErrorsFound is returned as true and node number as zero. // Return value int GetSupplyInletNode; // node number returned // FUNCTION LOCAL VARIABLE DECLARATIONS: int WhichHX; // Obtains and Allocates heat exchanger related parameters from input file if (GetInputFlag) { // First time subroutine has been entered GetHeatRecoveryInput(); GetInputFlag = false; } WhichHX = UtilityRoutines::FindItemInList(HXName, ExchCond); if (WhichHX != 0) { GetSupplyInletNode = ExchCond(WhichHX).SupInletNode; } else { ShowSevereError("GetSupplyInletNode: Could not find heat exchanger = \"" + HXName + "\""); ErrorsFound = true; GetSupplyInletNode = 0; } return GetSupplyInletNode; } int GetSupplyOutletNode(std::string const &HXName, // must match HX names for the ExchCond type bool &ErrorsFound // set to true if problem ) { // FUNCTION INFORMATION: // AUTHOR Richard Raustad // DATE WRITTEN February 2007 // MODIFIED na // RE-ENGINEERED na // PURPOSE OF THIS FUNCTION: // This function looks up the given HX and returns the supply air outlet node number. // If incorrect HX name is given, ErrorsFound is returned as true and node number as zero. // Return value int GetSupplyOutletNode; // node number returned // FUNCTION LOCAL VARIABLE DECLARATIONS: int WhichHX; // Obtains and Allocates heat exchanger related parameters from input file if (GetInputFlag) { // First time subroutine has been entered GetHeatRecoveryInput(); GetInputFlag = false; } WhichHX = UtilityRoutines::FindItemInList(HXName, ExchCond); if (WhichHX != 0) { GetSupplyOutletNode = ExchCond(WhichHX).SupOutletNode; } else { ShowSevereError("GetSupplyOutletNode: Could not find heat exchanger = \"" + HXName + "\""); ErrorsFound = true; GetSupplyOutletNode = 0; } return GetSupplyOutletNode; } int GetSecondaryInletNode(std::string const &HXName, // must match HX names for the ExchCond type bool &ErrorsFound // set to true if problem ) { // FUNCTION INFORMATION: // AUTHOR Richard Raustad // DATE WRITTEN February 2007 // MODIFIED na // RE-ENGINEERED na // PURPOSE OF THIS FUNCTION: // This function looks up the given HX and returns the secondary air inlet node number. // If incorrect HX name is given, ErrorsFound is returned as true and node number as zero. // Return value int GetSecondaryInletNode; // node number returned // FUNCTION LOCAL VARIABLE DECLARATIONS: int WhichHX; // Obtains and Allocates heat exchanger related parameters from input file if (GetInputFlag) { // First time subroutine has been entered GetHeatRecoveryInput(); GetInputFlag = false; } WhichHX = UtilityRoutines::FindItemInList(HXName, ExchCond); if (WhichHX != 0) { GetSecondaryInletNode = ExchCond(WhichHX).SecInletNode; } else { ShowSevereError("GetSecondaryInletNode: Could not find heat exchanger = \"" + HXName + "\""); ErrorsFound = true; GetSecondaryInletNode = 0; } return GetSecondaryInletNode; } int GetSecondaryOutletNode(std::string const &HXName, // must match HX names for the ExchCond type bool &ErrorsFound // set to true if problem ) { // FUNCTION INFORMATION: // AUTHOR Richard Raustad // DATE WRITTEN February 2007 // MODIFIED na // RE-ENGINEERED na // PURPOSE OF THIS FUNCTION: // This function looks up the given HX assisted cooling coil and returns the secondary air outlet node number. // If incorrect HX name is given, ErrorsFound is returned as true and node number as zero. // Return value int GetSecondaryOutletNode; // node number returned // FUNCTION LOCAL VARIABLE DECLARATIONS: int WhichHX; // Obtains and Allocates heat exchanger related parameters from input file if (GetInputFlag) { // First time subroutine has been entered GetHeatRecoveryInput(); GetInputFlag = false; } WhichHX = UtilityRoutines::FindItemInList(HXName, ExchCond); if (WhichHX != 0) { GetSecondaryOutletNode = ExchCond(WhichHX).SecOutletNode; } else { ShowSevereError("GetSecondaryOutletNode: Could not find heat exchanger = \"" + HXName + "\""); ErrorsFound = true; GetSecondaryOutletNode = 0; } return GetSecondaryOutletNode; } Real64 GetSupplyAirFlowRate(std::string const &HXName, // must match HX names for the ExchCond type bool &ErrorsFound // set to true if problem ) { // FUNCTION INFORMATION: // AUTHOR Richard Raustad // DATE WRITTEN October 2007 // MODIFIED na // RE-ENGINEERED na // PURPOSE OF THIS FUNCTION: // This function looks up the given Generic HX and the voluetric air flow rate. // If incorrect HX name is given, ErrorsFound is returned as true and air flow rate as zero. // Return value Real64 GetSupplyAirFlowRate; // air flow rate returned // FUNCTION LOCAL VARIABLE DECLARATIONS: int WhichHX; // Obtains and Allocates heat exchanger related parameters from input file if (GetInputFlag) { // First time subroutine has been entered GetHeatRecoveryInput(); GetInputFlag = false; } WhichHX = UtilityRoutines::FindItemInList(HXName, ExchCond); if (WhichHX != 0) { GetSupplyAirFlowRate = ExchCond(WhichHX).NomSupAirVolFlow; } else { ShowSevereError("GetSupplyAirFlowRate: Could not find heat exchanger = \"" + HXName + "\""); ShowContinueError("... Supply Air Flow Rate returned as 0."); ErrorsFound = true; GetSupplyAirFlowRate = 0.0; } return GetSupplyAirFlowRate; } int GetHeatExchangerObjectTypeNum(std::string const &HXName, // must match HX names for the ExchCond type bool &ErrorsFound // set to true if problem ) { // FUNCTION INFORMATION: // AUTHOR Richard Raustad // DATE WRITTEN October 2007 // MODIFIED na // RE-ENGINEERED na // PURPOSE OF THIS FUNCTION: // This function looks up the given Generic HX and the voluetric air flow rate. // If incorrect HX name is given, ErrorsFound is returned as true and air flow rate as zero. // Return value int GetHeatExchangerObjectTypeNum; // object type parameter returned // FUNCTION LOCAL VARIABLE DECLARATIONS: int WhichHX; // Obtains and Allocates heat exchanger related parameters from input file if (GetInputFlag) { // First time subroutine has been entered GetHeatRecoveryInput(); GetInputFlag = false; } WhichHX = UtilityRoutines::FindItemInList(HXName, ExchCond); if (WhichHX != 0) { GetHeatExchangerObjectTypeNum = ExchCond(WhichHX).ExchTypeNum; } else { ShowSevereError("GetHeatExchangerObjectTypeNum: Could not find heat exchanger = \"" + HXName + "\""); ErrorsFound = true; GetHeatExchangerObjectTypeNum = 0; } return GetHeatExchangerObjectTypeNum; } void SetHeatExchangerData(int const HXNum, // Index of HX bool &ErrorsFound, // Set to true if certain errors found std::string const &HXName, // Name of HX Optional<Real64> SupplyAirVolFlow, // HX supply air flow rate [m3/s] Optional<Real64> SecondaryAirVolFlow // HX secondary air flow rate [m3/s] ) { // SUBROUTINE INFORMATION: // AUTHOR Richard Raustad // DATE WRITTEN October 2007 // MODIFIED na // RE-ENGINEERED na // PURPOSE OF THIS SUBROUTINE: // This routine was designed for to autosize the HeatExchanger:AirToAir:SensibleAndLatent using // information from the ZoneHVAC:EnergyRecoveryVentilator object. // This is an illustration of setting data from an outside source. // METHODOLOGY EMPLOYED: // na // REFERENCES: // na // Using/Aliasing using General::TrimSigDigits; // Locals // SUBROUTINE ARGUMENT DEFINITIONS: // SUBROUTINE PARAMETER DEFINITIONS: // na // INTERFACE BLOCK SPECIFICATIONS: // na // DERIVED TYPE DEFINITIONS: // na // SUBROUTINE LOCAL VARIABLE DECLARATIONS: int WhichHX; // index to generic HX // Obtains and Allocates heat exchanger related parameters from input file if (GetInputFlag) { // First time subroutine has been entered GetHeatRecoveryInput(); GetInputFlag = false; } if (HXNum == 0) { WhichHX = UtilityRoutines::FindItemInList(HXName, ExchCond); } else { WhichHX = HXNum; } if (WhichHX <= 0 || WhichHX > NumHeatExchangers) { ShowSevereError("SetHeatExchangerData: Could not find heat exchanger = \"" + HXName + "\""); ErrorsFound = true; return; } if (present(SupplyAirVolFlow)) { ExchCond(WhichHX).NomSupAirVolFlow = SupplyAirVolFlow; } if (present(SecondaryAirVolFlow)) { ExchCond(WhichHX).NomSecAirVolFlow = SecondaryAirVolFlow; } } } // namespace HeatRecovery } // namespace EnergyPlus
62.265208
150
0.612649
[ "object", "model" ]
9c55273564eea72f698869c44dc5dcfeba1b13d5
14,579
cxx
C++
Modules/Numerics/Optimizersv4/test/itkLBFGSBOptimizerv4Test.cxx
fbudin69500/ITK-manually-forked
b8b2b0ba82b8129d121f422e3ce871f41d301bfd
[ "Apache-2.0" ]
1
2021-11-29T14:41:43.000Z
2021-11-29T14:41:43.000Z
Modules/Numerics/Optimizersv4/test/itkLBFGSBOptimizerv4Test.cxx
fbudin69500/ITK-manually-forked
b8b2b0ba82b8129d121f422e3ce871f41d301bfd
[ "Apache-2.0" ]
1
2018-10-18T18:49:19.000Z
2018-10-18T18:49:19.000Z
Modules/Numerics/Optimizersv4/test/itkLBFGSBOptimizerv4Test.cxx
fbudin69500/ITK-manually-forked
b8b2b0ba82b8129d121f422e3ce871f41d301bfd
[ "Apache-2.0" ]
null
null
null
/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include "itkLBFGSBOptimizerv4.h" #include "itkTextOutput.h" #include "itkMath.h" #include "itkTestingMacros.h" #include "itkMath.h" #include <iostream> /** * LBFGSBOptimizerv4TestMetric * * The objective function is the quadratic form: * * f(x) = 1/2 x^T A x - b^T x subject to -1 <= x <= 10 * * Where A is represented as an itkMatrix and * b is represented as a itkVector * * The system in this example is: * * | 3 2 | | 2| * A= | 2 6 | b = |-8| * * the solution is the vector | 4/3 -1 | * * \class LBFGSBOptimizerv4TestMetric */ class LBFGSBOptimizerv4TestMetric : public itk::ObjectToObjectMetricBase { public: using Self = LBFGSBOptimizerv4TestMetric; using Superclass = itk::ObjectToObjectMetricBase; using Pointer = itk::SmartPointer<Self>; using ConstPointer = itk::SmartPointer<const Self>; itkNewMacro( Self ); itkTypeMacro( LBFGSBOptimizerv4TestMetric, ObjectToObjectMetricBase ); enum { SpaceDimension=2 }; using ParametersType = Superclass::ParametersType; using DerivativeType = Superclass::DerivativeType; using MeasureType = Superclass::MeasureType; using VectorType = vnl_vector<double>; using MatrixType = vnl_matrix<double>; LBFGSBOptimizerv4TestMetric(): m_Parameters(0) { m_HasLocalSupport = false; } void Initialize() throw ( itk::ExceptionObject ) override { m_Parameters.SetSize( SpaceDimension ); } Superclass::NumberOfParametersType GetNumberOfLocalParameters() const override { return SpaceDimension; } Superclass::NumberOfParametersType GetNumberOfParameters() const override { return SpaceDimension; } void SetParameters( ParametersType & params ) override { this->m_Parameters = params; } const ParametersType & GetParameters() const override { return this->m_Parameters; } bool HasLocalSupport() const override { return m_HasLocalSupport; } void SetHasLocalSupport(bool hls) { m_HasLocalSupport = hls; } void UpdateTransformParameters( const DerivativeType &, ParametersValueType ) override { } MeasureType GetValue() const override { double x = m_Parameters[0]; double y = m_Parameters[1]; double val = 0.5*(3*x*x+4*x*y+6*y*y) - 2*x + 8*y; std::cout << "GetValue ( " << x << " , " << y << ") = " << val << std::endl; return val; } void GetDerivative( DerivativeType & derivative ) const override { double x = m_Parameters[0]; double y = m_Parameters[1]; derivative = DerivativeType(SpaceDimension); derivative[0] = -(3*x + 2*y -2); derivative[1] = -(2*x + 6*y +8); std::cout << "GetDerivative ( " << x << " , " << y << ") = " << "(" << -derivative[0] << " , " << -derivative[1] << ")" << std::endl; } void GetValueAndDerivative( MeasureType & value, DerivativeType & derivative ) const override { value = GetValue(); GetDerivative( derivative ); } private: ParametersType m_Parameters; bool m_HasLocalSupport; }; /** To ensure the events get fired. */ class EventChecker: public itk::Command { public: using Self = EventChecker; using Superclass = itk::Command; using Pointer = itk::SmartPointer<Self>; itkNewMacro( Self ); bool GetHadStartEvent() { return m_HadStartEvent; } bool GetHadIterationEvent() { return m_HadIterationEvent; } bool GetHadEndEvent() { return m_HadEndEvent; } void Execute( itk::Object *caller, const itk::EventObject & event ) override { Execute( (const itk::Object *)caller, event); } void Execute( const itk::Object *caller, const itk::EventObject & event) override { if( itk::StartEvent().CheckEvent( &event )) { std::cout << "Received StartEvent." << std::endl; m_HadStartEvent = true; } if( itk::IterationEvent().CheckEvent( &event )) { std::cout << "Received IterationEvent." << std::endl; const auto * opt = dynamic_cast<const itk::ObjectToObjectOptimizerBaseTemplate<double> *>(caller); if (opt) { std::cout << " iteration = " << opt->GetCurrentIteration() << std::endl; } m_HadIterationEvent = true; } if( itk::EndEvent().CheckEvent( &event )) { std::cout << "Received EndEvent." << std::endl; m_HadEndEvent = true; } } protected: EventChecker(): m_HadStartEvent( false ), m_HadIterationEvent( false ), m_HadEndEvent( false ) {} private: bool m_HadStartEvent; bool m_HadIterationEvent; bool m_HadEndEvent; }; int itkLBFGSBOptimizerv4Test(int, char *[]) { itk::OutputWindow::SetInstance(itk::TextOutput::New().GetPointer()); std::cout << "L-BFGS-B Optimizerv4 Test \n \n"; using OptimizerType = itk::LBFGSBOptimizerv4; // Declaration of a itkOptimizer OptimizerType::Pointer itkOptimizer = OptimizerType::New(); // Declaration of the metric LBFGSBOptimizerv4TestMetric::Pointer metric = LBFGSBOptimizerv4TestMetric::New(); itkOptimizer->SetMetric( metric ); const double F_Convergence_Factor = 1e+7; // Function value tolerance const double Projected_G_Tolerance = 1e-5; // Proj gradient tolerance constexpr int Max_Iterations = 25; // Maximum number of iterations itkOptimizer->SetCostFunctionConvergenceFactor( F_Convergence_Factor ); itkOptimizer->SetGradientConvergenceTolerance( Projected_G_Tolerance ); itkOptimizer->SetNumberOfIterations( Max_Iterations ); itkOptimizer->SetMaximumNumberOfFunctionEvaluations( 100 ); constexpr unsigned int SpaceDimension = 2; OptimizerType::ParametersType initialValue(SpaceDimension); // Starting point initialValue[0] = 10; initialValue[1] = 10; // Set the initial position by setting the metric parameters. std::cout << "Set metric parameters." << std::endl; metric->SetParameters( initialValue ); OptimizerType::ParametersType currentValue(2); currentValue = initialValue; itkOptimizer->SetInitialPosition( currentValue ); /** * Set the boundary condition for each variable, where * select[i] = 0 if x[i] is unbounded, * = 1 if x[i] has only a lower bound, * = 2 if x[i] has both lower and upper bounds, and * = 3 if x[1] has only an upper bound */ OptimizerType::BoundValueType lower(SpaceDimension); OptimizerType::BoundValueType upper(SpaceDimension); OptimizerType::BoundSelectionType select(SpaceDimension); lower.Fill( -1 ); upper.Fill( 10 ); select.Fill( itk::LBFGSBOptimizerv4::BOTHBOUNDED ); itkOptimizer->SetLowerBound( lower ); itkOptimizer->SetUpperBound( upper ); itkOptimizer->SetBoundSelection( select ); itkOptimizer->Print( std::cout ); EventChecker::Pointer eventChecker = EventChecker::New(); itkOptimizer->AddObserver( itk::StartEvent(), eventChecker ); itkOptimizer->AddObserver( itk::IterationEvent(), eventChecker ); itkOptimizer->AddObserver( itk::EndEvent(), eventChecker ); try { itkOptimizer->StartOptimization(); } catch( itk::ExceptionObject & e ) { std::cerr << "Exception thrown ! " << std::endl; std::cerr << "An error occurred during Optimization" << std::endl; std::cerr << "Location = " << e.GetLocation() << std::endl; std::cerr << "Description = " << e.GetDescription() << std::endl; return EXIT_FAILURE; } const OptimizerType::ParametersType & finalPosition = itkOptimizer->GetCurrentPosition(); std::cout << "Solution = (" << finalPosition[0] << "," << finalPosition[1] << ")" << std::endl; std::cout << "Final Function Value = " << itkOptimizer->GetValue() << std::endl; std::cout << "Infinity Norm of Projected Gradient = " << itkOptimizer->GetInfinityNormOfProjectedGradient() << std::endl; std::cout << "End condition = " << itkOptimizer->GetStopConditionDescription() << std::endl; std::cout << "Trace = " << itkOptimizer->GetTrace() << std::endl; std::cout << "metricConvergenceFactor = " << itkOptimizer->GetCostFunctionConvergenceFactor() << std::endl; std::cout << "ProjectedGradientTolerance = " << itkOptimizer->GetGradientConvergenceTolerance() << std::endl; std::cout << "NumberOfIterations = " << itkOptimizer->GetNumberOfIterations() << std::endl; std::cout << "MaximumNumberOfEvaluations = " << itkOptimizer->GetMaximumNumberOfFunctionEvaluations() << std::endl; std::cout << "MaximumNumberOfCorrections = " << itkOptimizer->GetMaximumNumberOfCorrections() << std::endl; std::cout << "CurrentOfIterations = " << itkOptimizer->GetCurrentIteration() << std::endl; if( !eventChecker->GetHadStartEvent() ) { std::cerr << "Did not have StartEvent!" << std::endl; return EXIT_FAILURE; } if( !eventChecker->GetHadIterationEvent() ) { std::cerr << "Did not have IterationEvent!" << std::endl; return EXIT_FAILURE; } if( !eventChecker->GetHadEndEvent() ) { std::cerr << "Did not have EndEvent!" << std::endl; return EXIT_FAILURE; } // // check results to see if it is within range // bool pass = true; std::string errorIn; // true parameters considering bounding constrains -1 <= x <= 10 double trueParameters[2] = { 4.0/3.0, -1.0 }; for( unsigned int j = 0; j < 2; ++j ) { if( ! itk::Math::FloatAlmostEqual( finalPosition[j], trueParameters[j] ) ) { pass = false; errorIn = "solution"; } } if( ! itk::Math::FloatAlmostEqual( itkOptimizer->GetValue(), -7.66667, 4, 0.01 ) ) { pass = false; errorIn = "final function value"; } if( ! itk::Math::FloatAlmostEqual( itkOptimizer->GetInfinityNormOfProjectedGradient(), 1.77636e-15, 4, 0.01 ) ) { pass = false; errorIn = "infinity norm of projected gradient"; } if( !pass ) { std::cerr << "\nError in " << errorIn << ".\n"; std::cerr << "Test failed." << std::endl; return EXIT_FAILURE; } // // Test stopping when number of iterations reached // std::cout << "-------------------------------" << std::endl; // Testing number of iterations for stopping metric->SetParameters( initialValue ); itkOptimizer->SetNumberOfIterations( 1 ); try { itkOptimizer->StartOptimization(); } catch( itk::ExceptionObject & e ) { std::cerr << "Exception thrown ! " << std::endl; std::cerr << "An error occurred during Optimization" << std::endl; std::cerr << "Location = " << e.GetLocation() << std::endl; std::cerr << "Description = " << e.GetDescription() << std::endl; return EXIT_FAILURE; } std::cout << "Solution = (" << finalPosition[0] << "," << finalPosition[1] << ")" << std::endl; std::cout << "NumberOfIterations = " << itkOptimizer->GetCurrentIteration() << std::endl; if ( itkOptimizer->GetCurrentIteration() != 1 ) { std::cout << "[FAILURE]" << std::endl; return EXIT_FAILURE; } // // Test with local-support transform. Should FAIL. // Such transforms are not yet supported. // std::cout << "-------------------------------" << std::endl; metric->SetHasLocalSupport( true ); TRY_EXPECT_EXCEPTION( itkOptimizer->StartOptimization() ); // // Test in unbounded mode // std::cout << std::endl << "Test in unbounded mode:" << std::endl; OptimizerType::Pointer itkOptimizer2 = OptimizerType::New(); // Set up boundary conditions select.Fill( 0 ); itkOptimizer2->SetBoundSelection( select ); std::cout << "Set metric parameters." << std::endl; metric->SetParameters( initialValue ); metric->SetHasLocalSupport( false ); itkOptimizer2->SetMetric( metric ); itkOptimizer2->SetInitialPosition( currentValue ); itkOptimizer2->SetCostFunctionConvergenceFactor( F_Convergence_Factor ); itkOptimizer2->SetGradientConvergenceTolerance( Projected_G_Tolerance ); itkOptimizer2->SetNumberOfIterations( Max_Iterations ); itkOptimizer2->SetMaximumNumberOfFunctionEvaluations( Max_Iterations ); itkOptimizer2->AddObserver( itk::StartEvent(), eventChecker ); itkOptimizer2->AddObserver( itk::IterationEvent(), eventChecker ); itkOptimizer2->AddObserver( itk::EndEvent(), eventChecker ); try { itkOptimizer2->StartOptimization(); } catch( itk::ExceptionObject & e ) { std::cerr << "Exception thrown ! " << std::endl; std::cerr << "An error occurred during Optimization" << std::endl; std::cerr << "Location = " << e.GetLocation() << std::endl; std::cerr << "Description = " << e.GetDescription() << std::endl; return EXIT_FAILURE; } std::cout << "Boundaries after optimization: " << std::endl; std::cout << "Upper bound size: " << itkOptimizer2->GetUpperBound().size() << std::endl; std::cout << "Lower bound size: " << itkOptimizer2->GetLowerBound().size() << std::endl; const OptimizerType::ParametersType & finalPosition2 = itkOptimizer2->GetCurrentPosition(); std::cout << "Solution = (" << finalPosition2[0] << "," << finalPosition2[1] << ")" << std::endl; std::cout << "Final Function Value = " << itkOptimizer2->GetValue() << std::endl; // check results pass = true; // true parameters when there is no constrain trueParameters[0] = 2.0; trueParameters[1] = -2.0; for( unsigned int j = 0; j < 2; ++j ) { if( ! itk::Math::FloatAlmostEqual( finalPosition2[j], trueParameters[j], 4, 0.01 ) ) { pass = false; errorIn = "solution"; } } if( ! itk::Math::FloatAlmostEqual( itkOptimizer2->GetValue(), -10.0, 4, 0.01 ) ) { pass = false; errorIn = "final function value"; } if( !pass ) { std::cerr << "\nError in " << errorIn << ".\n"; std::cerr << "Test failed." << std::endl; return EXIT_FAILURE; } std::cout << "Test passed." << std::endl; return EXIT_SUCCESS; }
30.059794
137
0.646341
[ "object", "vector", "transform" ]
9c5fd7d02ac537f8f5069dc1f5782108decc1c8b
63,466
cpp
C++
test/TestDynamicMeasurementVector.cpp
rafaelrietmann/ukf
bf53dacafbfee8c7591c48a66b50229f82afe4b4
[ "MIT" ]
320
2015-01-07T05:49:59.000Z
2022-03-31T01:52:15.000Z
test/TestDynamicMeasurementVector.cpp
msnh2012/ukf
04f0a996fee1f49699142bf5b149548a8d3a4ad1
[ "MIT" ]
22
2015-03-03T17:28:32.000Z
2022-02-16T14:46:54.000Z
test/TestDynamicMeasurementVector.cpp
msnh2012/ukf
04f0a996fee1f49699142bf5b149548a8d3a4ad1
[ "MIT" ]
155
2015-02-20T01:18:06.000Z
2022-02-22T01:58:53.000Z
#include <gtest/gtest.h> #include <Eigen/Core> #include <Eigen/Geometry> #include "UKF/Types.h" #include "UKF/StateVector.h" #include "UKF/MeasurementVector.h" #include "comparisons.h" enum MyFields { StaticPressure, DynamicPressure, Accelerometer, Gyroscope, Magnetometer }; using MyMeasurementVector = UKF::DynamicMeasurementVector< UKF::Field<StaticPressure, real_t>, UKF::Field<DynamicPressure, real_t>, UKF::Field<Magnetometer, UKF::FieldVector>, UKF::Field<Accelerometer, UKF::Vector<3>>, UKF::Field<Gyroscope, UKF::Vector<3>> >; TEST(DynamicMeasurementVectorTest, Instantiation) { MyMeasurementVector test_measurement; EXPECT_EQ(11, MyMeasurementVector::MaxRowsAtCompileTime); EXPECT_EQ(11, test_measurement.max_size()); } TEST(DynamicMeasurementVectorTest, Assignment) { MyMeasurementVector test_measurement; test_measurement.set_field<Gyroscope>(UKF::Vector<3>(1, 2, 3)); EXPECT_EQ(3, test_measurement.size()); EXPECT_VECTOR_EQ(UKF::Vector<3>(1, 2, 3), test_measurement.get_field<Gyroscope>()); test_measurement.set_field<DynamicPressure>(4); EXPECT_EQ(4, test_measurement.size()); EXPECT_EQ(4, test_measurement.get_field<DynamicPressure>()); test_measurement.set_field<Accelerometer>(UKF::Vector<3>(5, 6, 7)); EXPECT_EQ(7, test_measurement.size()); EXPECT_VECTOR_EQ(UKF::Vector<3>(5, 6, 7), test_measurement.get_field<Accelerometer>()); test_measurement.set_field<StaticPressure>(8); EXPECT_EQ(8, test_measurement.size()); EXPECT_EQ(8, test_measurement.get_field<StaticPressure>()); test_measurement.set_field<Magnetometer>(UKF::FieldVector(9, 10, 11)); EXPECT_EQ(11, test_measurement.size()); EXPECT_VECTOR_EQ(UKF::FieldVector(9, 10, 11), test_measurement.get_field<Magnetometer>()); UKF::Vector<11> expected; expected << 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11; EXPECT_VECTOR_EQ(expected, test_measurement); } TEST(DynamicMeasurementVectorTest, Reassignment) { MyMeasurementVector test_measurement; test_measurement.set_field<Gyroscope>(UKF::Vector<3>(1, 2, 3)); EXPECT_EQ(3, test_measurement.size()); EXPECT_VECTOR_EQ(UKF::Vector<3>(1, 2, 3), test_measurement); EXPECT_VECTOR_EQ(UKF::Vector<3>(1, 2, 3), test_measurement.get_field<Gyroscope>()); test_measurement.set_field<Gyroscope>(UKF::Vector<3>(4, 5, 6)); EXPECT_EQ(3, test_measurement.size()); EXPECT_VECTOR_EQ(UKF::Vector<3>(4, 5, 6), test_measurement); EXPECT_VECTOR_EQ(UKF::Vector<3>(4, 5, 6), test_measurement.get_field<Gyroscope>()); } TEST(DynamicMeasurementVectorTest, MultipleReassignment) { MyMeasurementVector test_measurement; test_measurement.set_field<Gyroscope>(UKF::Vector<3>(1, 2, 3)); test_measurement.set_field<DynamicPressure>(4); test_measurement.set_field<Accelerometer>(UKF::Vector<3>(5, 6, 7)); test_measurement.set_field<StaticPressure>(8); test_measurement.set_field<Magnetometer>(UKF::FieldVector(9, 10, 11)); EXPECT_EQ(11, test_measurement.size()); UKF::Vector<11> expected; expected << 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11; EXPECT_VECTOR_EQ(expected, test_measurement); test_measurement.set_field<Gyroscope>(UKF::Vector<3>(4, 5, 6)); EXPECT_EQ(11, test_measurement.size()); EXPECT_VECTOR_EQ(UKF::Vector<3>(4, 5, 6), test_measurement.get_field<Gyroscope>()); expected << 4, 5, 6, 4, 5, 6, 7, 8, 9, 10, 11; EXPECT_VECTOR_EQ(expected, test_measurement); test_measurement.set_field<Accelerometer>(UKF::Vector<3>(7, 8, 9)); EXPECT_EQ(11, test_measurement.size()); EXPECT_VECTOR_EQ(UKF::Vector<3>(7, 8, 9), test_measurement.get_field<Accelerometer>()); expected << 4, 5, 6, 4, 7, 8, 9, 8, 9, 10, 11; EXPECT_VECTOR_EQ(expected, test_measurement); test_measurement.set_field<DynamicPressure>(1); EXPECT_EQ(11, test_measurement.size()); EXPECT_EQ(1, test_measurement.get_field<DynamicPressure>()); expected << 4, 5, 6, 1, 7, 8, 9, 8, 9, 10, 11; EXPECT_VECTOR_EQ(expected, test_measurement); test_measurement.set_field<StaticPressure>(3); EXPECT_EQ(11, test_measurement.size()); EXPECT_EQ(3, test_measurement.get_field<StaticPressure>()); expected << 4, 5, 6, 1, 7, 8, 9, 3, 9, 10, 11; EXPECT_VECTOR_EQ(expected, test_measurement); test_measurement.set_field<Magnetometer>(UKF::FieldVector(4, 5, 6)); EXPECT_EQ(11, test_measurement.size()); EXPECT_VECTOR_EQ(UKF::FieldVector(4, 5, 6), test_measurement.get_field<Magnetometer>()); expected << 4, 5, 6, 1, 7, 8, 9, 3, 4, 5, 6; EXPECT_VECTOR_EQ(expected, test_measurement); } TEST(DynamicMeasurementVectorTest, CopyConstructor) { MyMeasurementVector test_measurement_1, test_measurement_2; test_measurement_1.set_field<Gyroscope>(UKF::Vector<3>(1, 2, 3)); test_measurement_1.set_field<DynamicPressure>(4); test_measurement_1.set_field<Accelerometer>(UKF::Vector<3>(5, 6, 7)); test_measurement_1.set_field<StaticPressure>(8); test_measurement_1.set_field<Magnetometer>(UKF::FieldVector(9, 10, 11)); test_measurement_2 = test_measurement_1; EXPECT_EQ(test_measurement_1.size(), test_measurement_2.size()); EXPECT_VECTOR_EQ(test_measurement_1, test_measurement_2); EXPECT_VECTOR_EQ(UKF::Vector<3>(1, 2, 3), test_measurement_2.get_field<Gyroscope>()); EXPECT_EQ(4, test_measurement_2.get_field<DynamicPressure>()); EXPECT_VECTOR_EQ(UKF::Vector<3>(5, 6, 7), test_measurement_2.get_field<Accelerometer>()); EXPECT_EQ(8, test_measurement_2.get_field<StaticPressure>()); EXPECT_VECTOR_EQ(UKF::FieldVector(9, 10, 11), test_measurement_2.get_field<Magnetometer>()); } enum MyStateVectorFields { AngularVelocity, Altitude, Velocity, Attitude }; using MyStateVector = UKF::StateVector< UKF::Field<Velocity, UKF::Vector<3>>, UKF::Field<AngularVelocity, UKF::Vector<3>>, UKF::Field<Attitude, UKF::Quaternion>, UKF::Field<Altitude, real_t> >; namespace UKF { /* Define measurement model to be used in tests. NOTE: These are just for testing, don't expect them to make any physical sense whatsoever. */ template <> template <> UKF::Vector<3> MyMeasurementVector::expected_measurement <MyStateVector, Accelerometer>(const MyStateVector& state) { return state.get_field<Attitude>() * UKF::Vector<3>(0, 0, -9.8); } template <> template <> UKF::Vector<3> MyMeasurementVector::expected_measurement <MyStateVector, Gyroscope>(const MyStateVector& state) { return state.get_field<AngularVelocity>(); } template <> template <> real_t MyMeasurementVector::expected_measurement <MyStateVector, StaticPressure>(const MyStateVector& state) { return 101.3 - 1.2*(state.get_field<Altitude>() / 100.0); } template <> template <> real_t MyMeasurementVector::expected_measurement <MyStateVector, DynamicPressure>(const MyStateVector& state) { return 0.5 * 1.225 * state.get_field<Velocity>().squaredNorm(); } template <> template <> UKF::FieldVector MyMeasurementVector::expected_measurement <MyStateVector, Magnetometer>(const MyStateVector& state) { return state.get_field<Attitude>() * UKF::FieldVector(0.45, 0, 0); } /* These versions of the predicted measurement functions have non-state inputs. This could be used to add predicted kinematic acceleration by feeding control inputs into a dynamics model, for example. */ template <> template <> UKF::Vector<3> MyMeasurementVector::expected_measurement <MyStateVector, Accelerometer, UKF::Vector<3>>(const MyStateVector& state, const UKF::Vector<3>& input) { return state.get_field<Attitude>() * UKF::Vector<3>(0, 0, -9.8) + input; } template <> template <> UKF::Vector<3> MyMeasurementVector::expected_measurement <MyStateVector, Gyroscope, UKF::Vector<3>>(const MyStateVector& state, const UKF::Vector<3>& input) { return state.get_field<AngularVelocity>(); } template <> template <> real_t MyMeasurementVector::expected_measurement <MyStateVector, StaticPressure, UKF::Vector<3>>(const MyStateVector& state, const UKF::Vector<3>& input) { return 101.3 - 1.2*(state.get_field<Altitude>() / 100.0); } template <> template <> real_t MyMeasurementVector::expected_measurement <MyStateVector, DynamicPressure, UKF::Vector<3>>(const MyStateVector& state, const UKF::Vector<3>& input) { return 0.5 * 1.225 * state.get_field<Velocity>().squaredNorm(); } template <> template <> UKF::FieldVector MyMeasurementVector::expected_measurement <MyStateVector, Magnetometer, UKF::Vector<3>>(const MyStateVector& state, const UKF::Vector<3>& input) { return state.get_field<Attitude>() * UKF::FieldVector(0.45, 0, 0) + input; } } TEST(DynamicMeasurementVectorTest, SigmaPointGeneration) { MyStateVector test_state; MyMeasurementVector test_measurement; test_measurement.set_field<Accelerometer>(UKF::Vector<3>(0, 0, 0)); test_measurement.set_field<Gyroscope>(UKF::Vector<3>(0, 0, 0)); test_measurement.set_field<Magnetometer>(UKF::FieldVector(0, 0, 0)); test_measurement.set_field<StaticPressure>(0); test_measurement.set_field<DynamicPressure>(0); test_state.set_field<Velocity>(UKF::Vector<3>(1, 2, 3)); test_state.set_field<AngularVelocity>(UKF::Vector<3>(1, 0, 0)); test_state.set_field<Attitude>(UKF::Quaternion(1, 0, 0, 0)); test_state.set_field<Altitude>(1000); MyStateVector::CovarianceMatrix covariance = MyStateVector::CovarianceMatrix::Zero(); covariance.diagonal() << 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0; MyStateVector::SigmaPointDistribution sigma_points = test_state.calculate_sigma_point_distribution((covariance * (MyStateVector::covariance_size() + UKF::Parameters::Lambda<MyStateVector>)).llt().matrixL()); MyMeasurementVector::SigmaPointDistribution<MyStateVector> target_sigma_points( test_measurement.size(), MyStateVector::num_sigma()); target_sigma_points << 0, 0, 0, 0, 0, 0, 0, 0, -8.314, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8.314, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8.314, 0, 0, 0, 0, 0, 0, 0, 0, 0, -8.314, 0, 0, 0, -9.8, -9.8, -9.8, -9.8, -9.8, -9.8, -9.8, 5.188, 5.188, -9.8, -9.8, -9.8, -9.8, -9.8, -9.8, -9.8, -9.8, 5.188, 5.188, -9.8, -9.8, 1, 1, 1, 1, 4.606, 1, 1, 1, 1, 1, 1, 1, 1, 1, -2.606, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 3.606, 0, 0, 0, 0, 0, 0, 0, 0, 0, -3.606, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3.606, 0, 0, 0, 0, 0, 0, 0, 0, 0, -3.606, 0, 0, 0, 0, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, -0.238, -0.238, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, -0.238, -0.238, 0.45, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.382, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.382, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.382, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.382, 0, 0, 89.3, 89.3, 89.3, 89.3, 89.3, 89.3, 89.3, 89.3, 89.3, 89.3, 89.257, 89.3, 89.3, 89.3, 89.3, 89.3, 89.3, 89.3, 89.3, 89.3, 89.343, 8.575, 20.954, 25.371, 29.788, 8.575, 8.575, 8.575, 8.575, 8.575, 8.575, 8.575, 12.121, 7.704, 3.287, 8.575, 8.575, 8.575, 8.575, 8.575, 8.575, 8.575; MyMeasurementVector::SigmaPointDistribution<MyStateVector> measurement_sigma_points; measurement_sigma_points = test_measurement.calculate_sigma_point_distribution<MyStateVector>(sigma_points); EXPECT_VECTOR_EQ(target_sigma_points.col(0), measurement_sigma_points.col(0)); EXPECT_VECTOR_EQ(target_sigma_points.col(1), measurement_sigma_points.col(1)); EXPECT_VECTOR_EQ(target_sigma_points.col(2), measurement_sigma_points.col(2)); EXPECT_VECTOR_EQ(target_sigma_points.col(3), measurement_sigma_points.col(3)); EXPECT_VECTOR_EQ(target_sigma_points.col(4), measurement_sigma_points.col(4)); EXPECT_VECTOR_EQ(target_sigma_points.col(5), measurement_sigma_points.col(5)); EXPECT_VECTOR_EQ(target_sigma_points.col(6), measurement_sigma_points.col(6)); EXPECT_VECTOR_EQ(target_sigma_points.col(7), measurement_sigma_points.col(7)); EXPECT_VECTOR_EQ(target_sigma_points.col(8), measurement_sigma_points.col(8)); EXPECT_VECTOR_EQ(target_sigma_points.col(9), measurement_sigma_points.col(9)); EXPECT_VECTOR_EQ(target_sigma_points.col(10), measurement_sigma_points.col(10)); EXPECT_VECTOR_EQ(target_sigma_points.col(11), measurement_sigma_points.col(11)); EXPECT_VECTOR_EQ(target_sigma_points.col(12), measurement_sigma_points.col(12)); EXPECT_VECTOR_EQ(target_sigma_points.col(13), measurement_sigma_points.col(13)); EXPECT_VECTOR_EQ(target_sigma_points.col(14), measurement_sigma_points.col(14)); EXPECT_VECTOR_EQ(target_sigma_points.col(15), measurement_sigma_points.col(15)); EXPECT_VECTOR_EQ(target_sigma_points.col(16), measurement_sigma_points.col(16)); EXPECT_VECTOR_EQ(target_sigma_points.col(17), measurement_sigma_points.col(17)); EXPECT_VECTOR_EQ(target_sigma_points.col(18), measurement_sigma_points.col(18)); EXPECT_VECTOR_EQ(target_sigma_points.col(19), measurement_sigma_points.col(19)); EXPECT_VECTOR_EQ(target_sigma_points.col(20), measurement_sigma_points.col(20)); } TEST(DynamicMeasurementVectorTest, SigmaPointGenerationWithInput) { MyStateVector test_state; MyMeasurementVector test_measurement; test_measurement.set_field<Accelerometer>(UKF::Vector<3>(0, 0, 0)); test_measurement.set_field<Gyroscope>(UKF::Vector<3>(0, 0, 0)); test_measurement.set_field<Magnetometer>(UKF::FieldVector(0, 0, 0)); test_measurement.set_field<StaticPressure>(0); test_measurement.set_field<DynamicPressure>(0); test_state.set_field<Velocity>(UKF::Vector<3>(1, 2, 3)); test_state.set_field<AngularVelocity>(UKF::Vector<3>(1, 0, 0)); test_state.set_field<Attitude>(UKF::Quaternion(1, 0, 0, 0)); test_state.set_field<Altitude>(1000); MyStateVector::CovarianceMatrix covariance = MyStateVector::CovarianceMatrix::Zero(); covariance.diagonal() << 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0; MyStateVector::SigmaPointDistribution sigma_points = test_state.calculate_sigma_point_distribution((covariance * (MyStateVector::covariance_size() + UKF::Parameters::Lambda<MyStateVector>)).llt().matrixL()); MyMeasurementVector::SigmaPointDistribution<MyStateVector> target_sigma_points( test_measurement.size(), MyStateVector::num_sigma()); target_sigma_points << 1, 1, 1, 1, 1, 1, 1, 1, -7.313, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9.313, 1, 1, 2, 2, 2, 2, 2, 2, 2, 10.313, 2, 2, 2, 2, 2, 2, 2, 2, 2, -6.313, 2, 2, 2, -6.8, -6.8, -6.8, -6.8, -6.8, -6.8, -6.8, 8.188, 8.188, -6.8, -6.8, -6.8, -6.8, -6.8, -6.8, -6.8, -6.8, 8.188, 8.188, -6.8, -6.8, 1, 1, 1, 1, 4.606, 1, 1, 1, 1, 1, 1, 1, 1, 1, -2.606, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 3.606, 0, 0, 0, 0, 0, 0, 0, 0, 0, -3.606, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3.606, 0, 0, 0, 0, 0, 0, 0, 0, 0, -3.606, 0, 0, 0, 0, 1.45, 1.45, 1.45, 1.45, 1.45, 1.45, 1.45, 1.45, 0.762, 0.762, 1.45, 1.45, 1.45, 1.45, 1.45, 1.45, 1.45, 1.45, 0.762, 0.762, 1.45, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2.382, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1.618, 2, 3, 3, 3, 3, 3, 3, 3, 3, 2.618, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3.382, 3, 3, 89.3, 89.3, 89.3, 89.3, 89.3, 89.3, 89.3, 89.3, 89.3, 89.3, 89.257, 89.3, 89.3, 89.3, 89.3, 89.3, 89.3, 89.3, 89.3, 89.3, 89.343, 8.575, 20.954, 25.371, 29.788, 8.575, 8.575, 8.575, 8.575, 8.575, 8.575, 8.575, 12.121, 7.704, 3.287, 8.575, 8.575, 8.575, 8.575, 8.575, 8.575, 8.575; MyMeasurementVector::SigmaPointDistribution<MyStateVector> measurement_sigma_points; measurement_sigma_points = test_measurement.calculate_sigma_point_distribution<MyStateVector>( sigma_points, UKF::Vector<3>(1, 2, 3)); EXPECT_VECTOR_EQ(target_sigma_points.col(0), measurement_sigma_points.col(0)); EXPECT_VECTOR_EQ(target_sigma_points.col(1), measurement_sigma_points.col(1)); EXPECT_VECTOR_EQ(target_sigma_points.col(2), measurement_sigma_points.col(2)); EXPECT_VECTOR_EQ(target_sigma_points.col(3), measurement_sigma_points.col(3)); EXPECT_VECTOR_EQ(target_sigma_points.col(4), measurement_sigma_points.col(4)); EXPECT_VECTOR_EQ(target_sigma_points.col(5), measurement_sigma_points.col(5)); EXPECT_VECTOR_EQ(target_sigma_points.col(6), measurement_sigma_points.col(6)); EXPECT_VECTOR_EQ(target_sigma_points.col(7), measurement_sigma_points.col(7)); EXPECT_VECTOR_EQ(target_sigma_points.col(8), measurement_sigma_points.col(8)); EXPECT_VECTOR_EQ(target_sigma_points.col(9), measurement_sigma_points.col(9)); EXPECT_VECTOR_EQ(target_sigma_points.col(10), measurement_sigma_points.col(10)); EXPECT_VECTOR_EQ(target_sigma_points.col(11), measurement_sigma_points.col(11)); EXPECT_VECTOR_EQ(target_sigma_points.col(12), measurement_sigma_points.col(12)); EXPECT_VECTOR_EQ(target_sigma_points.col(13), measurement_sigma_points.col(13)); EXPECT_VECTOR_EQ(target_sigma_points.col(14), measurement_sigma_points.col(14)); EXPECT_VECTOR_EQ(target_sigma_points.col(15), measurement_sigma_points.col(15)); EXPECT_VECTOR_EQ(target_sigma_points.col(16), measurement_sigma_points.col(16)); EXPECT_VECTOR_EQ(target_sigma_points.col(17), measurement_sigma_points.col(17)); EXPECT_VECTOR_EQ(target_sigma_points.col(18), measurement_sigma_points.col(18)); EXPECT_VECTOR_EQ(target_sigma_points.col(19), measurement_sigma_points.col(19)); EXPECT_VECTOR_EQ(target_sigma_points.col(20), measurement_sigma_points.col(20)); } TEST(DynamicMeasurementVectorTest, PartialSigmaPointGeneration) { MyStateVector test_state; MyMeasurementVector test_measurement; test_measurement.set_field<Accelerometer>(UKF::Vector<3>(0, 0, 0)); test_state.set_field<Velocity>(UKF::Vector<3>(1, 2, 3)); test_state.set_field<AngularVelocity>(UKF::Vector<3>(1, 0, 0)); test_state.set_field<Attitude>(UKF::Quaternion(1, 0, 0, 0)); test_state.set_field<Altitude>(1000); MyStateVector::CovarianceMatrix covariance = MyStateVector::CovarianceMatrix::Zero(); covariance.diagonal() << 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0; MyStateVector::SigmaPointDistribution sigma_points = test_state.calculate_sigma_point_distribution((covariance * (MyStateVector::covariance_size() + UKF::Parameters::Lambda<MyStateVector>)).llt().matrixL()); MyMeasurementVector::SigmaPointDistribution<MyStateVector> target_sigma_points( test_measurement.size(), MyStateVector::num_sigma()); target_sigma_points << 0, 0, 0, 0, 0, 0, 0, 0, -8.314, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8.314, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8.314, 0, 0, 0, 0, 0, 0, 0, 0, 0, -8.314, 0, 0, 0, -9.8, -9.8, -9.8, -9.8, -9.8, -9.8, -9.8, 5.188, 5.188, -9.8, -9.8, -9.8, -9.8, -9.8, -9.8, -9.8, -9.8, 5.188, 5.188, -9.8, -9.8; MyMeasurementVector::SigmaPointDistribution<MyStateVector> measurement_sigma_points; measurement_sigma_points = test_measurement.calculate_sigma_point_distribution<MyStateVector>(sigma_points); EXPECT_VECTOR_EQ(target_sigma_points.col(0), measurement_sigma_points.col(0)); EXPECT_VECTOR_EQ(target_sigma_points.col(1), measurement_sigma_points.col(1)); EXPECT_VECTOR_EQ(target_sigma_points.col(2), measurement_sigma_points.col(2)); EXPECT_VECTOR_EQ(target_sigma_points.col(3), measurement_sigma_points.col(3)); EXPECT_VECTOR_EQ(target_sigma_points.col(4), measurement_sigma_points.col(4)); EXPECT_VECTOR_EQ(target_sigma_points.col(5), measurement_sigma_points.col(5)); EXPECT_VECTOR_EQ(target_sigma_points.col(6), measurement_sigma_points.col(6)); EXPECT_VECTOR_EQ(target_sigma_points.col(7), measurement_sigma_points.col(7)); EXPECT_VECTOR_EQ(target_sigma_points.col(8), measurement_sigma_points.col(8)); EXPECT_VECTOR_EQ(target_sigma_points.col(9), measurement_sigma_points.col(9)); EXPECT_VECTOR_EQ(target_sigma_points.col(10), measurement_sigma_points.col(10)); EXPECT_VECTOR_EQ(target_sigma_points.col(11), measurement_sigma_points.col(11)); EXPECT_VECTOR_EQ(target_sigma_points.col(12), measurement_sigma_points.col(12)); EXPECT_VECTOR_EQ(target_sigma_points.col(13), measurement_sigma_points.col(13)); EXPECT_VECTOR_EQ(target_sigma_points.col(14), measurement_sigma_points.col(14)); EXPECT_VECTOR_EQ(target_sigma_points.col(15), measurement_sigma_points.col(15)); EXPECT_VECTOR_EQ(target_sigma_points.col(16), measurement_sigma_points.col(16)); EXPECT_VECTOR_EQ(target_sigma_points.col(17), measurement_sigma_points.col(17)); EXPECT_VECTOR_EQ(target_sigma_points.col(18), measurement_sigma_points.col(18)); EXPECT_VECTOR_EQ(target_sigma_points.col(19), measurement_sigma_points.col(19)); EXPECT_VECTOR_EQ(target_sigma_points.col(20), measurement_sigma_points.col(20)); } TEST(DynamicMeasurementVectorTest, SigmaPointMean) { MyMeasurementVector::SigmaPointDistribution<MyStateVector> measurement_sigma_points( MyMeasurementVector::max_size(), MyStateVector::num_sigma()); MyMeasurementVector test_measurement; test_measurement.set_field<Accelerometer>(UKF::Vector<3>(0, 0, 0)); test_measurement.set_field<Gyroscope>(UKF::Vector<3>(0, 0, 0)); test_measurement.set_field<Magnetometer>(UKF::FieldVector(0, 0, 0)); test_measurement.set_field<StaticPressure>(0); test_measurement.set_field<DynamicPressure>(0); measurement_sigma_points << 0, 0, 0, 0, 0, 0, 0, 0, -8.314, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8.314, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8.314, 0, 0, 0, 0, 0, 0, 0, 0, 0, -8.314, 0, 0, 0, -9.8, -9.8, -9.8, -9.8, -9.8, -9.8, -9.8, 5.188, 5.188, -9.8, -9.8, -9.8, -9.8, -9.8, -9.8, -9.8, -9.8, 5.188, 5.188, -9.8, -9.8, 1, 1, 1, 1, 4.606, 1, 1, 1, 1, 1, 1, 1, 1, 1, -2.606, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 3.606, 0, 0, 0, 0, 0, 0, 0, 0, 0, -3.606, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3.606, 0, 0, 0, 0, 0, 0, 0, 0, 0, -3.606, 0, 0, 0, 0, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, -0.238, -0.238, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, -0.238, -0.238, 0.45, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.382, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.382, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.382, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.382, 0, 0, 89.3, 89.3, 89.3, 89.3, 89.3, 89.3, 89.3, 89.3, 89.3, 89.3, 89.257, 89.3, 89.3, 89.3, 89.3, 89.3, 89.3, 89.3, 89.3, 89.3, 89.343, 8.575, 20.954, 25.371, 29.788, 8.575, 8.575, 8.575, 8.575, 8.575, 8.575, 8.575, 12.121, 7.704, 3.287, 8.575, 8.575, 8.575, 8.575, 8.575, 8.575, 8.575; MyMeasurementVector expected_mean; expected_mean.set_field<Accelerometer>(UKF::Vector<3>(0.0, 0.0, -7.494)); expected_mean.set_field<Gyroscope>(UKF::Vector<3>(1.0, 0.0, 0.0)); expected_mean.set_field<Magnetometer>(UKF::FieldVector(0.45, 0, 0)); expected_mean.set_field<StaticPressure>(89.3); expected_mean.set_field<DynamicPressure>(10.4125); EXPECT_VECTOR_EQ(expected_mean, test_measurement.calculate_sigma_point_mean<MyStateVector>(measurement_sigma_points)); } TEST(DynamicMeasurementVectorTest, PartialSigmaPointMean) { MyMeasurementVector::SigmaPointDistribution<MyStateVector> measurement_sigma_points( 3, MyStateVector::num_sigma()); MyMeasurementVector test_measurement; test_measurement.set_field<Accelerometer>(UKF::Vector<3>(0, 0, 0)); measurement_sigma_points << 0, 0, 0, 0, 0, 0, 0, 0, -8.314, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8.314, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8.314, 0, 0, 0, 0, 0, 0, 0, 0, 0, -8.314, 0, 0, 0, -9.8, -9.8, -9.8, -9.8, -9.8, -9.8, -9.8, 5.188, 5.188, -9.8, -9.8, -9.8, -9.8, -9.8, -9.8, -9.8, -9.8, 5.188, 5.188, -9.8, -9.8; MyMeasurementVector expected_mean; expected_mean.set_field<Accelerometer>(UKF::Vector<3>(0.0, 0.0, -7.494)); EXPECT_VECTOR_EQ(expected_mean, test_measurement.calculate_sigma_point_mean<MyStateVector>(measurement_sigma_points)); } TEST(DynamicMeasurementVectorTest, SigmaPointDeltas) { MyStateVector test_state; MyMeasurementVector test_measurement; test_measurement.set_field<Accelerometer>(UKF::Vector<3>(0, 0, 0)); test_measurement.set_field<Gyroscope>(UKF::Vector<3>(0, 0, 0)); test_measurement.set_field<Magnetometer>(UKF::FieldVector(1, 0, 0)); test_measurement.set_field<StaticPressure>(0); test_measurement.set_field<DynamicPressure>(0); test_state.set_field<Velocity>(UKF::Vector<3>(1, 2, 3)); test_state.set_field<AngularVelocity>(UKF::Vector<3>(1, 0, 0)); test_state.set_field<Attitude>(UKF::Quaternion(1, 0, 0, 0)); test_state.set_field<Altitude>(1000); MyStateVector::CovarianceMatrix covariance = MyStateVector::CovarianceMatrix::Zero(); covariance.diagonal() << 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0; MyStateVector::SigmaPointDistribution sigma_points = test_state.calculate_sigma_point_distribution((covariance * (MyStateVector::covariance_size() + UKF::Parameters::Lambda<MyStateVector>)).llt().matrixL()); MyMeasurementVector::SigmaPointDistribution<MyStateVector> measurement_sigma_points = test_measurement.calculate_sigma_point_distribution<MyStateVector>(sigma_points); MyMeasurementVector mean_measurement = test_measurement.calculate_sigma_point_mean<MyStateVector>(measurement_sigma_points); MyMeasurementVector::SigmaPointDeltas<MyStateVector> sigma_point_deltas(mean_measurement.size(), MyStateVector::num_sigma()); MyMeasurementVector::SigmaPointDeltas<MyStateVector> target_sigma_point_deltas(mean_measurement.size(), MyStateVector::num_sigma()); target_sigma_point_deltas << 0, 0, 0, 0, 0, 0, 0, 0, -8.314, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8.314, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8.314, 0, 0, 0, 0, 0, 0, 0, 0, 0, -8.314, 0, 0, 0, -2.306, -2.306, -2.306, -2.306, -2.306, -2.306, -2.306, 12.682, 12.682, -2.306, -2.306, -2.306, -2.306, -2.306, -2.306, -2.306, -2.306, 12.682, 12.682, -2.306, -2.306, 0, 0, 0, 0, 3.606, 0, 0, 0, 0, 0, 0, 0, 0, 0, -3.606, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3.606, 0, 0, 0, 0, 0, 0, 0, 0, 0, -3.606, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3.606, 0, 0, 0, 0, 0, 0, 0, 0, 0, -3.606, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3.606, 0, 0, 0, 0, 0, 0, 0, 0, 0, -3.606, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3.606, 0, 0, 0, 0, 0, 0, 0, 0, 0, -3.606, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.043, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.043, -1.8375, 10.542, 14.959, 19.376, -1.8375, -1.8375, -1.8375, -1.8375, -1.8375, -1.8375, -1.8375, 1.7082, -2.7086, -7.126, -1.8375, -1.8375, -1.8375, -1.8375, -1.8375, -1.8375, -1.8375; sigma_point_deltas = mean_measurement.calculate_sigma_point_deltas<MyStateVector>(measurement_sigma_points); EXPECT_VECTOR_EQ(target_sigma_point_deltas.col(0), sigma_point_deltas.col(0)); EXPECT_VECTOR_EQ(target_sigma_point_deltas.col(1), sigma_point_deltas.col(1)); EXPECT_VECTOR_EQ(target_sigma_point_deltas.col(2), sigma_point_deltas.col(2)); EXPECT_VECTOR_EQ(target_sigma_point_deltas.col(3), sigma_point_deltas.col(3)); EXPECT_VECTOR_EQ(target_sigma_point_deltas.col(4), sigma_point_deltas.col(4)); EXPECT_VECTOR_EQ(target_sigma_point_deltas.col(5), sigma_point_deltas.col(5)); EXPECT_VECTOR_EQ(target_sigma_point_deltas.col(6), sigma_point_deltas.col(6)); EXPECT_VECTOR_EQ(target_sigma_point_deltas.col(7), sigma_point_deltas.col(7)); EXPECT_VECTOR_EQ(target_sigma_point_deltas.col(8), sigma_point_deltas.col(8)); EXPECT_VECTOR_EQ(target_sigma_point_deltas.col(9), sigma_point_deltas.col(9)); EXPECT_VECTOR_EQ(target_sigma_point_deltas.col(10), sigma_point_deltas.col(10)); EXPECT_VECTOR_EQ(target_sigma_point_deltas.col(11), sigma_point_deltas.col(11)); EXPECT_VECTOR_EQ(target_sigma_point_deltas.col(12), sigma_point_deltas.col(12)); EXPECT_VECTOR_EQ(target_sigma_point_deltas.col(13), sigma_point_deltas.col(13)); EXPECT_VECTOR_EQ(target_sigma_point_deltas.col(14), sigma_point_deltas.col(14)); EXPECT_VECTOR_EQ(target_sigma_point_deltas.col(15), sigma_point_deltas.col(15)); EXPECT_VECTOR_EQ(target_sigma_point_deltas.col(16), sigma_point_deltas.col(16)); EXPECT_VECTOR_EQ(target_sigma_point_deltas.col(17), sigma_point_deltas.col(17)); EXPECT_VECTOR_EQ(target_sigma_point_deltas.col(18), sigma_point_deltas.col(18)); EXPECT_VECTOR_EQ(target_sigma_point_deltas.col(19), sigma_point_deltas.col(19)); EXPECT_VECTOR_EQ(target_sigma_point_deltas.col(20), sigma_point_deltas.col(20)); } TEST(DynamicMeasurementVectorTest, PartialSigmaPointDeltas) { MyStateVector test_state; MyMeasurementVector test_measurement; test_measurement.set_field<Accelerometer>(UKF::Vector<3>(0, 0, 0)); test_state.set_field<Velocity>(UKF::Vector<3>(1, 2, 3)); test_state.set_field<AngularVelocity>(UKF::Vector<3>(1, 0, 0)); test_state.set_field<Attitude>(UKF::Quaternion(1, 0, 0, 0)); test_state.set_field<Altitude>(1000); MyStateVector::CovarianceMatrix covariance = MyStateVector::CovarianceMatrix::Zero(); covariance.diagonal() << 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0; MyStateVector::SigmaPointDistribution sigma_points = test_state.calculate_sigma_point_distribution((covariance * (MyStateVector::covariance_size() + UKF::Parameters::Lambda<MyStateVector>)).llt().matrixL()); MyMeasurementVector::SigmaPointDistribution<MyStateVector> measurement_sigma_points = test_measurement.calculate_sigma_point_distribution<MyStateVector>(sigma_points); MyMeasurementVector mean_measurement = test_measurement.calculate_sigma_point_mean<MyStateVector>(measurement_sigma_points); MyMeasurementVector::SigmaPointDeltas<MyStateVector> sigma_point_deltas(3, MyStateVector::num_sigma()); MyMeasurementVector::SigmaPointDeltas<MyStateVector> target_sigma_point_deltas(3, MyStateVector::num_sigma()); target_sigma_point_deltas << 0, 0, 0, 0, 0, 0, 0, 0, -8.314, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8.314, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8.314, 0, 0, 0, 0, 0, 0, 0, 0, 0, -8.314, 0, 0, 0, -2.306, -2.306, -2.306, -2.306, -2.306, -2.306, -2.306, 12.682, 12.682, -2.306, -2.306, -2.306, -2.306, -2.306, -2.306, -2.306, -2.306, 12.682, 12.682, -2.306, -2.306; sigma_point_deltas = mean_measurement.calculate_sigma_point_deltas<MyStateVector>(measurement_sigma_points); EXPECT_VECTOR_EQ(target_sigma_point_deltas.col(0), sigma_point_deltas.col(0)); EXPECT_VECTOR_EQ(target_sigma_point_deltas.col(1), sigma_point_deltas.col(1)); EXPECT_VECTOR_EQ(target_sigma_point_deltas.col(2), sigma_point_deltas.col(2)); EXPECT_VECTOR_EQ(target_sigma_point_deltas.col(3), sigma_point_deltas.col(3)); EXPECT_VECTOR_EQ(target_sigma_point_deltas.col(4), sigma_point_deltas.col(4)); EXPECT_VECTOR_EQ(target_sigma_point_deltas.col(5), sigma_point_deltas.col(5)); EXPECT_VECTOR_EQ(target_sigma_point_deltas.col(6), sigma_point_deltas.col(6)); EXPECT_VECTOR_EQ(target_sigma_point_deltas.col(7), sigma_point_deltas.col(7)); EXPECT_VECTOR_EQ(target_sigma_point_deltas.col(8), sigma_point_deltas.col(8)); EXPECT_VECTOR_EQ(target_sigma_point_deltas.col(9), sigma_point_deltas.col(9)); EXPECT_VECTOR_EQ(target_sigma_point_deltas.col(10), sigma_point_deltas.col(10)); EXPECT_VECTOR_EQ(target_sigma_point_deltas.col(11), sigma_point_deltas.col(11)); EXPECT_VECTOR_EQ(target_sigma_point_deltas.col(12), sigma_point_deltas.col(12)); EXPECT_VECTOR_EQ(target_sigma_point_deltas.col(13), sigma_point_deltas.col(13)); EXPECT_VECTOR_EQ(target_sigma_point_deltas.col(14), sigma_point_deltas.col(14)); EXPECT_VECTOR_EQ(target_sigma_point_deltas.col(15), sigma_point_deltas.col(15)); EXPECT_VECTOR_EQ(target_sigma_point_deltas.col(16), sigma_point_deltas.col(16)); EXPECT_VECTOR_EQ(target_sigma_point_deltas.col(17), sigma_point_deltas.col(17)); EXPECT_VECTOR_EQ(target_sigma_point_deltas.col(18), sigma_point_deltas.col(18)); EXPECT_VECTOR_EQ(target_sigma_point_deltas.col(19), sigma_point_deltas.col(19)); EXPECT_VECTOR_EQ(target_sigma_point_deltas.col(20), sigma_point_deltas.col(20)); } TEST(DynamicMeasurementVectorTest, Innovation) { MyStateVector test_state; MyMeasurementVector test_measurement, target_innovation; test_state.set_field<Velocity>(UKF::Vector<3>(10, 0, 0)); test_state.set_field<AngularVelocity>(UKF::Vector<3>(0, 0, 1)); test_state.set_field<Attitude>(UKF::Quaternion(1, 0, 0, 0)); test_state.set_field<Altitude>(1000); test_measurement.set_field<Gyroscope>(UKF::Vector<3>(1, 0, 0)); test_measurement.set_field<DynamicPressure>(0.5 * 122.5); test_measurement.set_field<Accelerometer>(UKF::Vector<3>(0, 0, 9.8)); test_measurement.set_field<StaticPressure>(101.3); test_measurement.set_field<Magnetometer>(UKF::FieldVector(0, 0.45, 0)); MyStateVector::CovarianceMatrix covariance = MyStateVector::CovarianceMatrix::Zero(); covariance.diagonal() << 1e-9, 1e-9, 1e-9, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0; MyStateVector::SigmaPointDistribution sigma_points = test_state.calculate_sigma_point_distribution((covariance * (MyStateVector::covariance_size() + UKF::Parameters::Lambda<MyStateVector>)).llt().matrixL()); MyMeasurementVector::SigmaPointDistribution<MyStateVector> measurement_sigma_points = test_measurement.calculate_sigma_point_distribution<MyStateVector>(sigma_points); MyMeasurementVector mean_measurement = test_measurement.calculate_sigma_point_mean<MyStateVector>(measurement_sigma_points); target_innovation.set_field<Gyroscope>(UKF::Vector<3>(1, 0, -1)); target_innovation.set_field<DynamicPressure>(0); target_innovation.set_field<Accelerometer>(UKF::Vector<3>(0, 0, 17.294)); target_innovation.set_field<StaticPressure>(12.0); target_innovation.set_field<Magnetometer>(UKF::FieldVector(0, 0, 2)); EXPECT_VECTOR_EQ(target_innovation, mean_measurement.calculate_innovation(test_measurement)); } TEST(DynamicMeasurementVectorTest, PartialInnovation) { MyStateVector test_state; MyMeasurementVector test_measurement, target_innovation; test_state.set_field<Velocity>(UKF::Vector<3>(10, 0, 0)); test_state.set_field<AngularVelocity>(UKF::Vector<3>(0, 0, 1)); test_state.set_field<Attitude>(UKF::Quaternion(1, 0, 0, 0)); test_state.set_field<Altitude>(1000); test_measurement.set_field<Accelerometer>(UKF::Vector<3>(0, 0, 9.8)); MyStateVector::CovarianceMatrix covariance = MyStateVector::CovarianceMatrix::Zero(); covariance.diagonal() << 1e-9, 1e-9, 1e-9, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0; MyStateVector::SigmaPointDistribution sigma_points = test_state.calculate_sigma_point_distribution((covariance * (MyStateVector::covariance_size() + UKF::Parameters::Lambda<MyStateVector>)).llt().matrixL()); MyMeasurementVector::SigmaPointDistribution<MyStateVector> measurement_sigma_points = test_measurement.calculate_sigma_point_distribution<MyStateVector>(sigma_points); MyMeasurementVector mean_measurement = test_measurement.calculate_sigma_point_mean<MyStateVector>(measurement_sigma_points); target_innovation.set_field<Accelerometer>(UKF::Vector<3>(0, 0, 17.294)); EXPECT_VECTOR_EQ(target_innovation, mean_measurement.calculate_innovation(test_measurement)); } TEST(DynamicMeasurementVectorTest, SigmaPointCovariance) { MyStateVector test_state; MyMeasurementVector test_measurement; test_measurement.set_field<Accelerometer>(UKF::Vector<3>(0, 0, 0)); test_measurement.set_field<Gyroscope>(UKF::Vector<3>(0, 0, 0)); test_measurement.set_field<Magnetometer>(UKF::FieldVector(1, 0, 0)); test_measurement.set_field<StaticPressure>(0); test_measurement.set_field<DynamicPressure>(0); test_state.set_field<Velocity>(UKF::Vector<3>(1, 2, 3)); test_state.set_field<AngularVelocity>(UKF::Vector<3>(1, 0, 0)); test_state.set_field<Attitude>(UKF::Quaternion(1, 0, 0, 0)); test_state.set_field<Altitude>(1000); MyStateVector::CovarianceMatrix covariance = MyStateVector::CovarianceMatrix::Zero(); covariance.diagonal() << 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0; MyStateVector::SigmaPointDistribution sigma_points = test_state.calculate_sigma_point_distribution((covariance * (MyStateVector::covariance_size() + UKF::Parameters::Lambda<MyStateVector>)).llt().matrixL()); MyMeasurementVector::SigmaPointDistribution<MyStateVector> measurement_sigma_points = test_measurement.calculate_sigma_point_distribution<MyStateVector>(sigma_points); MyMeasurementVector mean_measurement = test_measurement.calculate_sigma_point_mean<MyStateVector>(measurement_sigma_points); MyMeasurementVector::SigmaPointDeltas<MyStateVector> sigma_point_deltas = mean_measurement.calculate_sigma_point_deltas<MyStateVector>(measurement_sigma_points); MyMeasurementVector::CovarianceMatrix calculated_covariance = mean_measurement.calculate_sigma_point_covariance<MyStateVector>(sigma_point_deltas); MyMeasurementVector::CovarianceMatrix expected_covariance(mean_measurement.size(), mean_measurement.size()); expected_covariance << 5.31709, 0, 0, 0, 0, 0, 0, -2.3059, 0, 0, 0, 0, 5.31709, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 29.2440, 0, 0, 0, 0, 0, 0, 0, -4.237, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -2.3059, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1.44e-4, 0, 0, 0, -4.237, 0, 0, 0, 0, 0, 0, 0, 32.263; EXPECT_VECTOR_EQ(expected_covariance.col(0), calculated_covariance.col(0)); EXPECT_VECTOR_EQ(expected_covariance.col(1), calculated_covariance.col(1)); EXPECT_VECTOR_EQ(expected_covariance.col(2), calculated_covariance.col(2)); EXPECT_VECTOR_EQ(expected_covariance.col(3), calculated_covariance.col(3)); EXPECT_VECTOR_EQ(expected_covariance.col(4), calculated_covariance.col(4)); EXPECT_VECTOR_EQ(expected_covariance.col(5), calculated_covariance.col(5)); EXPECT_VECTOR_EQ(expected_covariance.col(6), calculated_covariance.col(6)); EXPECT_VECTOR_EQ(expected_covariance.col(7), calculated_covariance.col(7)); EXPECT_VECTOR_EQ(expected_covariance.col(8), calculated_covariance.col(8)); EXPECT_VECTOR_EQ(expected_covariance.col(9), calculated_covariance.col(9)); EXPECT_VECTOR_EQ(expected_covariance.col(10), calculated_covariance.col(10)); } TEST(DynamicMeasurementVectorTest, PartialSigmaPointCovariance) { MyStateVector test_state; MyMeasurementVector test_measurement; test_measurement.set_field<Accelerometer>(UKF::Vector<3>(0, 0, 0)); test_state.set_field<Velocity>(UKF::Vector<3>(1, 2, 3)); test_state.set_field<AngularVelocity>(UKF::Vector<3>(1, 0, 0)); test_state.set_field<Attitude>(UKF::Quaternion(1, 0, 0, 0)); test_state.set_field<Altitude>(1000); MyStateVector::CovarianceMatrix covariance = MyStateVector::CovarianceMatrix::Zero(); covariance.diagonal() << 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0; MyStateVector::SigmaPointDistribution sigma_points = test_state.calculate_sigma_point_distribution((covariance * (MyStateVector::covariance_size() + UKF::Parameters::Lambda<MyStateVector>)).llt().matrixL()); MyMeasurementVector::SigmaPointDistribution<MyStateVector> measurement_sigma_points = test_measurement.calculate_sigma_point_distribution<MyStateVector>(sigma_points); MyMeasurementVector mean_measurement = test_measurement.calculate_sigma_point_mean<MyStateVector>(measurement_sigma_points); MyMeasurementVector::SigmaPointDeltas<MyStateVector> sigma_point_deltas = mean_measurement.calculate_sigma_point_deltas<MyStateVector>(measurement_sigma_points); MyMeasurementVector::CovarianceMatrix calculated_covariance = mean_measurement.calculate_sigma_point_covariance<MyStateVector>(sigma_point_deltas); MyMeasurementVector::CovarianceMatrix expected_covariance(mean_measurement.size(), mean_measurement.size()); expected_covariance << 5.31709, 0, 0, 0, 5.31709, 0, 0, 0, 29.2440; EXPECT_VECTOR_EQ(expected_covariance.col(0), calculated_covariance.col(0)); EXPECT_VECTOR_EQ(expected_covariance.col(1), calculated_covariance.col(1)); EXPECT_VECTOR_EQ(expected_covariance.col(2), calculated_covariance.col(2)); } TEST(DynamicMeasurementVectorTest, MeasurementCovariance) { MyMeasurementVector test_measurement, expected_measurement; MyMeasurementVector::CovarianceVector measurement_covariance; measurement_covariance.set_field<Gyroscope>(UKF::Vector<3>(1, 2, 3)); measurement_covariance.set_field<DynamicPressure>(4); measurement_covariance.set_field<Accelerometer>(UKF::Vector<3>(5, 6, 7)); measurement_covariance.set_field<StaticPressure>(8); measurement_covariance.set_field<Magnetometer>(UKF::FieldVector(1, 2, 3)); test_measurement.set_field<Gyroscope>(UKF::Vector<3>(0, 0, 0)); test_measurement.set_field<DynamicPressure>(0); test_measurement.set_field<Accelerometer>(UKF::Vector<3>(0, 0, -9.8)); test_measurement.set_field<StaticPressure>(101.3); test_measurement.set_field<Magnetometer>(UKF::FieldVector(-1, 0, 1)); expected_measurement.set_field<Gyroscope>(UKF::Vector<3>(0, 0, 0)); expected_measurement.set_field<DynamicPressure>(0); expected_measurement.set_field<Accelerometer>(UKF::Vector<3>(0, 0, -9.8)); expected_measurement.set_field<StaticPressure>(101.3); expected_measurement.set_field<Magnetometer>(UKF::FieldVector(1, 1, 0)); MyMeasurementVector::CovarianceMatrix expected_measurement_covariance = MyMeasurementVector::CovarianceMatrix::Zero(11, 11); expected_measurement_covariance.diagonal() << 1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 0; expected_measurement_covariance.block<3, 3>(8, 8) << 8, -8, 0, -8, 8, 0, 0, 0, 16; MyMeasurementVector::CovarianceMatrix out_measurement_covariance = test_measurement.calculate_measurement_covariance(measurement_covariance, expected_measurement); EXPECT_VECTOR_EQ(expected_measurement_covariance.col(0), out_measurement_covariance.col(0)); EXPECT_VECTOR_EQ(expected_measurement_covariance.col(1), out_measurement_covariance.col(1)); EXPECT_VECTOR_EQ(expected_measurement_covariance.col(2), out_measurement_covariance.col(2)); EXPECT_VECTOR_EQ(expected_measurement_covariance.col(3), out_measurement_covariance.col(3)); EXPECT_VECTOR_EQ(expected_measurement_covariance.col(4), out_measurement_covariance.col(4)); EXPECT_VECTOR_EQ(expected_measurement_covariance.col(5), out_measurement_covariance.col(5)); EXPECT_VECTOR_EQ(expected_measurement_covariance.col(6), out_measurement_covariance.col(6)); EXPECT_VECTOR_EQ(expected_measurement_covariance.col(7), out_measurement_covariance.col(7)); EXPECT_VECTOR_EQ(expected_measurement_covariance.col(8), out_measurement_covariance.col(8)); EXPECT_VECTOR_EQ(expected_measurement_covariance.col(9), out_measurement_covariance.col(9)); EXPECT_VECTOR_EQ(expected_measurement_covariance.col(10), out_measurement_covariance.col(10)); } TEST(DynamicMeasurementVectorTest, PartialMeasurementCovariance) { MyMeasurementVector test_measurement, expected_measurement; MyMeasurementVector::CovarianceVector measurement_covariance; measurement_covariance.set_field<Gyroscope>(UKF::Vector<3>(1, 2, 3)); measurement_covariance.set_field<DynamicPressure>(4); measurement_covariance.set_field<Accelerometer>(UKF::Vector<3>(5, 6, 7)); measurement_covariance.set_field<StaticPressure>(8); measurement_covariance.set_field<Magnetometer>(UKF::FieldVector(1, 2, 3)); test_measurement.set_field<Gyroscope>(UKF::Vector<3>(0, 0, 0)); expected_measurement.set_field<Gyroscope>(UKF::Vector<3>(0, 0, 0)); MyMeasurementVector::CovarianceMatrix expected_measurement_covariance = MyMeasurementVector::CovarianceMatrix::Zero(3, 3); expected_measurement_covariance.diagonal() << 1, 2, 3; MyMeasurementVector::CovarianceMatrix out_measurement_covariance = test_measurement.calculate_measurement_covariance(measurement_covariance, expected_measurement); EXPECT_VECTOR_EQ(expected_measurement_covariance.col(0), out_measurement_covariance.col(0)); EXPECT_VECTOR_EQ(expected_measurement_covariance.col(1), out_measurement_covariance.col(1)); EXPECT_VECTOR_EQ(expected_measurement_covariance.col(2), out_measurement_covariance.col(2)); } TEST(DynamicMeasurementVectorTest, MeasurementRootCovariance) { MyMeasurementVector test_measurement, expected_measurement; MyMeasurementVector::CovarianceVector measurement_root_covariance; measurement_root_covariance.set_field<Gyroscope>(UKF::Vector<3>(1, 2, 3)); measurement_root_covariance.set_field<DynamicPressure>(4); measurement_root_covariance.set_field<Accelerometer>(UKF::Vector<3>(5, 6, 7)); measurement_root_covariance.set_field<StaticPressure>(8); measurement_root_covariance.set_field<Magnetometer>(UKF::FieldVector(1, 2, 3)); test_measurement.set_field<Gyroscope>(UKF::Vector<3>(0, 0, 0)); test_measurement.set_field<DynamicPressure>(0); test_measurement.set_field<Accelerometer>(UKF::Vector<3>(0, 0, 0)); test_measurement.set_field<StaticPressure>(0); test_measurement.set_field<Magnetometer>(UKF::FieldVector(-1, 0, 1)); expected_measurement.set_field<Gyroscope>(UKF::Vector<3>(0, 0, 0)); expected_measurement.set_field<DynamicPressure>(0); expected_measurement.set_field<Accelerometer>(UKF::Vector<3>(0, 0, -9.8)); expected_measurement.set_field<StaticPressure>(101.3); expected_measurement.set_field<Magnetometer>(UKF::FieldVector(1, 1, 0)); MyMeasurementVector::CovarianceMatrix expected_measurement_root_covariance = MyMeasurementVector::CovarianceMatrix::Zero(11, 11); expected_measurement_root_covariance.diagonal() << 1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 0; expected_measurement_root_covariance.block<3, 3>(8, 8) << 0, -4, 0, 0, 4, 0, -2, 0, -6; MyMeasurementVector::CovarianceMatrix out_measurement_root_covariance = test_measurement.calculate_measurement_root_covariance(measurement_root_covariance, expected_measurement); EXPECT_VECTOR_EQ(expected_measurement_root_covariance.col(0), out_measurement_root_covariance.col(0)); EXPECT_VECTOR_EQ(expected_measurement_root_covariance.col(1), out_measurement_root_covariance.col(1)); EXPECT_VECTOR_EQ(expected_measurement_root_covariance.col(2), out_measurement_root_covariance.col(2)); EXPECT_VECTOR_EQ(expected_measurement_root_covariance.col(3), out_measurement_root_covariance.col(3)); EXPECT_VECTOR_EQ(expected_measurement_root_covariance.col(4), out_measurement_root_covariance.col(4)); EXPECT_VECTOR_EQ(expected_measurement_root_covariance.col(5), out_measurement_root_covariance.col(5)); EXPECT_VECTOR_EQ(expected_measurement_root_covariance.col(6), out_measurement_root_covariance.col(6)); EXPECT_VECTOR_EQ(expected_measurement_root_covariance.col(7), out_measurement_root_covariance.col(7)); EXPECT_VECTOR_EQ(expected_measurement_root_covariance.col(8), out_measurement_root_covariance.col(8)); EXPECT_VECTOR_EQ(expected_measurement_root_covariance.col(9), out_measurement_root_covariance.col(9)); EXPECT_VECTOR_EQ(expected_measurement_root_covariance.col(10), out_measurement_root_covariance.col(10)); } TEST(DynamicMeasurementVectorTest, PartialMeasurementRootCovariance) { MyMeasurementVector test_measurement, expected_measurement; MyMeasurementVector::CovarianceVector measurement_root_covariance; measurement_root_covariance.set_field<Gyroscope>(UKF::Vector<3>(1, 2, 3)); measurement_root_covariance.set_field<DynamicPressure>(4); measurement_root_covariance.set_field<Accelerometer>(UKF::Vector<3>(5, 6, 7)); measurement_root_covariance.set_field<StaticPressure>(8); measurement_root_covariance.set_field<Magnetometer>(UKF::FieldVector(1, 2, 3)); test_measurement.set_field<Gyroscope>(UKF::Vector<3>(0, 0, 0)); expected_measurement.set_field<Gyroscope>(UKF::Vector<3>(0, 0, 0)); MyMeasurementVector::CovarianceMatrix expected_measurement_root_covariance = MyMeasurementVector::CovarianceMatrix::Zero(3, 3); expected_measurement_root_covariance.diagonal() << 1, 2, 3; MyMeasurementVector::CovarianceMatrix out_measurement_root_covariance = test_measurement.calculate_measurement_root_covariance(measurement_root_covariance, expected_measurement); EXPECT_VECTOR_EQ(expected_measurement_root_covariance.col(0), out_measurement_root_covariance.col(0)); EXPECT_VECTOR_EQ(expected_measurement_root_covariance.col(1), out_measurement_root_covariance.col(1)); EXPECT_VECTOR_EQ(expected_measurement_root_covariance.col(2), out_measurement_root_covariance.col(2)); } TEST(DynamicMeasurementVectorTest, CalculateRotationVector) { UKF::Vector<3> test; test = UKF::Detail::calculate_rotation_vector<MyMeasurementVector>(UKF::Vector<3>(0, 0, 0), UKF::Vector<3>(0, 0, 0)); EXPECT_VECTOR_EQ(UKF::Vector<3>(0, 0, 0), test); test = UKF::Detail::calculate_rotation_vector<MyMeasurementVector>(UKF::Vector<3>(1, 0, 0), UKF::Vector<3>(0, 0, 0)); EXPECT_VECTOR_EQ(UKF::Vector<3>(0, 0, 0), test); test = UKF::Detail::calculate_rotation_vector<MyMeasurementVector>(UKF::Vector<3>(0, 0, 0), UKF::Vector<3>(1, 0, 0)); EXPECT_VECTOR_EQ(UKF::Vector<3>(0, 0, 0), test); test = UKF::Detail::calculate_rotation_vector<MyMeasurementVector>(UKF::Vector<3>(1, 0, 0), UKF::Vector<3>(1, 0, 0)); EXPECT_VECTOR_EQ(UKF::Vector<3>(0, 0, 0), test); test = UKF::Detail::calculate_rotation_vector<MyMeasurementVector>(UKF::Vector<3>(1, 0, 0), UKF::Vector<3>(-1, 0, 0)); EXPECT_VECTOR_EQ(UKF::Vector<3>(0, 0, -2/std::numeric_limits<real_t>::epsilon()), test); test = UKF::Detail::calculate_rotation_vector<MyMeasurementVector>(UKF::Vector<3>(1, 0, 0), UKF::Vector<3>(0, 1, 0)); EXPECT_VECTOR_EQ(UKF::Vector<3>(0, 0, -2), test); test = UKF::Detail::calculate_rotation_vector<MyMeasurementVector>(UKF::Vector<3>(1, 0, 0), UKF::Vector<3>(0, -1, 0)); EXPECT_VECTOR_EQ(UKF::Vector<3>(0, 0, 2), test); test = UKF::Detail::calculate_rotation_vector<MyMeasurementVector>(UKF::Vector<3>(1, 0, 0), UKF::Vector<3>(0, 0, 1)); EXPECT_VECTOR_EQ(UKF::Vector<3>(0, 2, 0), test); test = UKF::Detail::calculate_rotation_vector<MyMeasurementVector>(UKF::Vector<3>(1, 0, 0), UKF::Vector<3>(0, 0, -1)); EXPECT_VECTOR_EQ(UKF::Vector<3>(0, -2, 0), test); /* Some random vectors, for the a = 0, f = 2 case. */ test = UKF::Detail::calculate_rotation_vector<MyMeasurementVector>( UKF::Vector<3>(5.0746, -2.3911, 1.3564), UKF::Vector<3>(8.3439, -4.2832, 5.1440)); EXPECT_VECTOR_EQ(UKF::Vector<3>(0.1070, 0.2438, 0.0294), test); test = UKF::Detail::calculate_rotation_vector<MyMeasurementVector>( UKF::Vector<3>(5.5833, 8.6802, -7.4019), UKF::Vector<3>(-8.4829, -8.9210, 0.6160)); EXPECT_VECTOR_EQ(UKF::Vector<3>(4.4643, -4.3661, -1.7527), test); test = UKF::Detail::calculate_rotation_vector<MyMeasurementVector>( UKF::Vector<3>(2.0396, -4.7406, 3.0816), UKF::Vector<3>(-3.7757, 0.5707, -6.6870)); EXPECT_VECTOR_EQ(UKF::Vector<3>(-3.9209, -0.2624, 2.1914), test); } TEST(DynamicMeasurementVectorTest, CalculateRotationVectorJacobian) { UKF::Matrix<3, 3> test; test = UKF::Detail::calculate_rotation_vector_jacobian<MyMeasurementVector>(UKF::Vector<3>(0, 0, 0), UKF::Vector<3>(0, 0, 0)); EXPECT_VECTOR_EQ(UKF::Vector<3>(0, 0, 0).transpose(), (test*test.transpose()).row(0)); EXPECT_VECTOR_EQ(UKF::Vector<3>(0, 0, 0).transpose(), (test*test.transpose()).row(1)); EXPECT_VECTOR_EQ(UKF::Vector<3>(0, 0, 0).transpose(), (test*test.transpose()).row(2)); test = UKF::Detail::calculate_rotation_vector_jacobian<MyMeasurementVector>(UKF::Vector<3>(1, 0, 0), UKF::Vector<3>(0, 0, 0)); EXPECT_VECTOR_EQ(UKF::Vector<3>(0, 0, 0).transpose(), (test*test.transpose()).row(0)); EXPECT_VECTOR_EQ(UKF::Vector<3>(0, 0, 0).transpose(), (test*test.transpose()).row(1)); EXPECT_VECTOR_EQ(UKF::Vector<3>(0, 0, 0).transpose(), (test*test.transpose()).row(2)); test = UKF::Detail::calculate_rotation_vector_jacobian<MyMeasurementVector>(UKF::Vector<3>(0, 0, 0), UKF::Vector<3>(1, 0, 0)); EXPECT_VECTOR_EQ(UKF::Vector<3>(0, 0, 0).transpose(), (test*test.transpose()).row(0)); EXPECT_VECTOR_EQ(UKF::Vector<3>(0, 4/(std::numeric_limits<real_t>::epsilon()*std::numeric_limits<real_t>::epsilon()), 0).transpose(), (test*test.transpose()).row(1)); EXPECT_VECTOR_EQ(UKF::Vector<3>(0, 0, 4/(std::numeric_limits<real_t>::epsilon()*std::numeric_limits<real_t>::epsilon())).transpose(), (test*test.transpose()).row(2)); test = UKF::Detail::calculate_rotation_vector_jacobian<MyMeasurementVector>(UKF::Vector<3>(1, 0, 0), UKF::Vector<3>(1, 0, 0)); EXPECT_VECTOR_EQ(UKF::Vector<3>(0, 0, 0).transpose(), (test*test.transpose()).row(0)); EXPECT_VECTOR_EQ(UKF::Vector<3>(0, 1, 0).transpose(), (test*test.transpose()).row(1)); EXPECT_VECTOR_EQ(UKF::Vector<3>(0, 0, 1).transpose(), (test*test.transpose()).row(2)); test = UKF::Detail::calculate_rotation_vector_jacobian<MyMeasurementVector>(UKF::Vector<3>(1, 0, 0), UKF::Vector<3>(-1, 0, 0)); EXPECT_VECTOR_EQ(UKF::Vector<3>(0, 0, 0).transpose(), (test*test.transpose()).row(0)); EXPECT_VECTOR_EQ(UKF::Vector<3>(0, 4/(std::numeric_limits<real_t>::epsilon()*std::numeric_limits<real_t>::epsilon()), 0).transpose(), (test*test.transpose()).row(1)); EXPECT_VECTOR_EQ(UKF::Vector<3>(0, 0, 4/(std::numeric_limits<real_t>::epsilon()*std::numeric_limits<real_t>::epsilon())).transpose(), (test*test.transpose()).row(2)); test = UKF::Detail::calculate_rotation_vector_jacobian<MyMeasurementVector>(UKF::Vector<3>(1, 0, 0), UKF::Vector<3>(0, 1, 0)); EXPECT_VECTOR_EQ(UKF::Vector<3>(4, 0, 0).transpose(), (test*test.transpose()).row(0)); EXPECT_VECTOR_EQ(UKF::Vector<3>(0, 0, 0).transpose(), (test*test.transpose()).row(1)); EXPECT_VECTOR_EQ(UKF::Vector<3>(0, 0, 4).transpose(), (test*test.transpose()).row(2)); test = UKF::Detail::calculate_rotation_vector_jacobian<MyMeasurementVector>(UKF::Vector<3>(1, 0, 0), UKF::Vector<3>(0, -1, 0)); EXPECT_VECTOR_EQ(UKF::Vector<3>(4, 0, 0).transpose(), (test*test.transpose()).row(0)); EXPECT_VECTOR_EQ(UKF::Vector<3>(0, 0, 0).transpose(), (test*test.transpose()).row(1)); EXPECT_VECTOR_EQ(UKF::Vector<3>(0, 0, 4).transpose(), (test*test.transpose()).row(2)); test = UKF::Detail::calculate_rotation_vector_jacobian<MyMeasurementVector>(UKF::Vector<3>(1, 0, 0), UKF::Vector<3>(0, 0, 1)); EXPECT_VECTOR_EQ(UKF::Vector<3>(4, 0, 0).transpose(), (test*test.transpose()).row(0)); EXPECT_VECTOR_EQ(UKF::Vector<3>(0, 4, 0).transpose(), (test*test.transpose()).row(1)); EXPECT_VECTOR_EQ(UKF::Vector<3>(0, 0, 0).transpose(), (test*test.transpose()).row(2)); test = UKF::Detail::calculate_rotation_vector_jacobian<MyMeasurementVector>(UKF::Vector<3>(1, 0, 0), UKF::Vector<3>(0, 0, -1)); EXPECT_VECTOR_EQ(UKF::Vector<3>(4, 0, 0).transpose(), (test*test.transpose()).row(0)); EXPECT_VECTOR_EQ(UKF::Vector<3>(0, 4, 0).transpose(), (test*test.transpose()).row(1)); EXPECT_VECTOR_EQ(UKF::Vector<3>(0, 0, 0).transpose(), (test*test.transpose()).row(2)); /* Some random vectors, for the a = 0, f = 2 case. */ Eigen::DiagonalMatrix<real_t, 3> c(UKF::Vector<3>(1, 2, 3)); test = UKF::Detail::calculate_rotation_vector_jacobian<MyMeasurementVector>( UKF::Vector<3>(5.0746, -2.3911, 1.3564), UKF::Vector<3>(8.3439, -4.2832, 5.1440)); EXPECT_VECTOR_EQ(UKF::Vector<3>( 0.030105, 0.032038, -0.022155).transpose(), (test*c*test.transpose()).row(0)); EXPECT_VECTOR_EQ(UKF::Vector<3>( 0.032038, 0.073227, 0.009005).transpose(), (test*c*test.transpose()).row(1)); EXPECT_VECTOR_EQ(UKF::Vector<3>(-0.022155, 0.009005, 0.043436).transpose(), (test*c*test.transpose()).row(2)); test = UKF::Detail::calculate_rotation_vector_jacobian<MyMeasurementVector>( UKF::Vector<3>(5.5833, 8.6802, -7.4019), UKF::Vector<3>(-8.4829, -8.9210, 0.6160)); EXPECT_VECTOR_EQ(UKF::Vector<3>( 0.790494, -0.776049, -0.353005).transpose(), (test*c*test.transpose()).row(0)); EXPECT_VECTOR_EQ(UKF::Vector<3>(-0.776049, 0.768788, 0.446778).transpose(), (test*c*test.transpose()).row(1)); EXPECT_VECTOR_EQ(UKF::Vector<3>(-0.353005, 0.446778, 1.609094).transpose(), (test*c*test.transpose()).row(2)); test = UKF::Detail::calculate_rotation_vector_jacobian<MyMeasurementVector>( UKF::Vector<3>(2.0396, -4.7406, 3.0816), UKF::Vector<3>(-3.7757, 0.5707, -6.6870)); EXPECT_VECTOR_EQ(UKF::Vector<3>( 1.850606, -0.474603, -1.085418).transpose(), (test*c*test.transpose()).row(0)); EXPECT_VECTOR_EQ(UKF::Vector<3>(-0.474603, 1.420474, 0.389206).transpose(), (test*c*test.transpose()).row(1)); EXPECT_VECTOR_EQ(UKF::Vector<3>(-1.085418, 0.389206, 0.646079).transpose(), (test*c*test.transpose()).row(2)); }
64.301925
221
0.647496
[ "geometry", "vector", "model" ]
9c6490a17554e5284666a33b5d1753bf6b0fab46
18,334
hpp
C++
include/cavc/polylineintersects.hpp
findux/CavalierContours
94d125bbc8b51a8ca8244e75d28aeda1979c2bb3
[ "MIT" ]
221
2020-01-18T01:59:58.000Z
2022-03-29T13:00:14.000Z
include/cavc/polylineintersects.hpp
findux/CavalierContours
94d125bbc8b51a8ca8244e75d28aeda1979c2bb3
[ "MIT" ]
48
2020-01-18T01:12:07.000Z
2022-03-25T15:35:54.000Z
include/cavc/polylineintersects.hpp
findux/CavalierContours
94d125bbc8b51a8ca8244e75d28aeda1979c2bb3
[ "MIT" ]
51
2020-01-22T06:06:02.000Z
2022-03-29T13:00:17.000Z
#ifndef CAVC_POLYLINEINTERSECTS_HPP #define CAVC_POLYLINEINTERSECTS_HPP #include "mathutils.hpp" #include "polyline.hpp" #include "vector2.hpp" #include <unordered_set> #include <vector> // This header has functions for finding and working with polyline intersects (self intersects and // intersects between polylines) namespace cavc { /// Represents a non-coincident polyline intersect. template <typename Real> struct PlineIntersect { /// Index of the start vertex of the first segment std::size_t sIndex1; /// Index of the start vertex of the second segment std::size_t sIndex2; /// Point of intersection Vector2<Real> pos; // type of intersect PlineIntersect() = default; PlineIntersect(std::size_t si1, std::size_t si2, Vector2<Real> p) : sIndex1(si1), sIndex2(si2), pos(p) {} }; /// Represents a coincident polyline intersect (stretch). template <typename Real> struct PlineCoincidentIntersect { /// Index of the start vertex of the first segment std::size_t sIndex1; /// Index of the start vertex of the second segment std::size_t sIndex2; /// One end point of the coincident slice Vector2<Real> point1; /// Other end point of the coincident slice Vector2<Real> point2; PlineCoincidentIntersect() = default; PlineCoincidentIntersect(std::size_t si1, std::size_t si2, Vector2<Real> const &point1, Vector2<Real> const &point2) : sIndex1(si1), sIndex2(si2), point1(point1), point2(point2) {} }; /// Holds a collection of intersects found template <typename Real> struct PlineIntersectsResult { std::vector<PlineIntersect<Real>> intersects; std::vector<PlineCoincidentIntersect<Real>> coincidentIntersects; bool hasIntersects() { return intersects.size() != 0 || coincidentIntersects.size() != 0; } }; template <typename Real> struct CoincidentSlicesResult { std::vector<Polyline<Real>> coincidentSlices; std::vector<PlineIntersect<Real>> sliceStartPoints; std::vector<PlineIntersect<Real>> sliceEndPoints; std::vector<bool> coincidentIsOpposingDirection; }; template <typename Real> CoincidentSlicesResult<Real> sortAndjoinCoincidentSlices(std::vector<PlineCoincidentIntersect<Real>> &coincidentIntrs, Polyline<Real> const &pline1, Polyline<Real> const &pline2) { CoincidentSlicesResult<Real> result; if (coincidentIntrs.size() == 0) { return result; } for (auto &intr : coincidentIntrs) { auto const &sp = pline1[intr.sIndex1].pos(); Real dist1 = distSquared(sp, intr.point1); Real dist2 = distSquared(sp, intr.point2); if (dist1 > dist2) { using namespace std; swap(intr.point1, intr.point2); } } std::sort(coincidentIntrs.begin(), coincidentIntrs.end(), [&](auto const &intr1, auto const &intr2) { if (intr1.sIndex1 != intr2.sIndex1) { return intr1.sIndex1 < intr2.sIndex1; } // equal index so sort distance from start auto const &sp = pline1[intr1.sIndex1].pos(); Real dist1 = distSquared(sp, intr1.point1); Real dist2 = distSquared(sp, intr2.point1); return dist1 < dist2; }); auto &sliceStartPoints = result.sliceStartPoints; auto &sliceEndPoints = result.sliceEndPoints; auto &coincidentSlices = result.coincidentSlices; auto &coincidentIsOpposingDirection = result.coincidentIsOpposingDirection; Polyline<Real> currCoincidentSlice; auto startCoincidentSliceAt = [&](std::size_t intrIndex) { const auto &intr = coincidentIntrs[intrIndex]; const auto &v1 = pline1[intr.sIndex1]; const auto &v2 = pline1[utils::nextWrappingIndex(intr.sIndex1, pline1)]; const auto &u1 = pline2[intr.sIndex2]; const auto &u2 = pline2[utils::nextWrappingIndex(intr.sIndex2, pline2)]; auto const &t1 = segTangentVector(v1, v2, v1.pos()); auto const &t2 = segTangentVector(u1, u2, u1.pos()); // tangent vectors are either going same direction or opposite direction, just test dot product // sign to determine if going same direction auto dotP = dot(t1, t2); bool sameDirection = dotP > Real(0); coincidentIsOpposingDirection.push_back(!sameDirection); auto split1 = splitAtPoint(v1, v2, intr.point1); currCoincidentSlice.addVertex(split1.splitVertex); auto split2 = splitAtPoint(v1, v2, intr.point2); currCoincidentSlice.addVertex(split2.splitVertex); PlineIntersect<Real> sliceStart; sliceStart.pos = split1.splitVertex.pos(); if (fuzzyEqual(v1.pos(), intr.point1, utils::realPrecision<Real>())) { // coincidence starts at beginning of segment, report as starting at end of previous index sliceStart.sIndex1 = utils::prevWrappingIndex(intr.sIndex1, pline1); } else { sliceStart.sIndex1 = intr.sIndex1; } if (fuzzyEqual(u1.pos(), sliceStart.pos, utils::realPrecision<Real>())) { sliceStart.sIndex2 = utils::prevWrappingIndex(intr.sIndex2, pline2); } else { sliceStart.sIndex2 = intr.sIndex2; } sliceStartPoints.push_back(std::move(sliceStart)); }; auto endCoincidentSliceAt = [&](std::size_t intrIndex) { const auto &intr = coincidentIntrs[intrIndex]; const auto &u1 = pline2[intr.sIndex2]; coincidentSlices.emplace_back(); using namespace std; swap(coincidentSlices.back(), currCoincidentSlice); PlineIntersect<Real> sliceEnd; sliceEnd.pos = intr.point2; sliceEnd.sIndex1 = intr.sIndex1; if (fuzzyEqual(u1.pos(), sliceEnd.pos, utils::realPrecision<Real>())) { sliceEnd.sIndex2 = utils::prevWrappingIndex(intr.sIndex2, pline2); } else { sliceEnd.sIndex2 = intr.sIndex2; } sliceEndPoints.push_back(std::move(sliceEnd)); }; startCoincidentSliceAt(0); for (std::size_t i = 1; i < coincidentIntrs.size(); ++i) { const auto &intr = coincidentIntrs[i]; const auto &v1 = pline1[intr.sIndex1]; const auto &v2 = pline1[utils::nextWrappingIndex(intr.sIndex1, pline1)]; if (fuzzyEqual(intr.point1, currCoincidentSlice.lastVertex().pos(), utils::realPrecision<Real>())) { // continue coincident slice currCoincidentSlice.vertexes().pop_back(); auto split1 = splitAtPoint(v1, v2, intr.point1); currCoincidentSlice.addVertex(split1.splitVertex); auto split2 = splitAtPoint(v1, v2, intr.point2); currCoincidentSlice.addVertex(split2.splitVertex); } else { // end coincident slice and start new endCoincidentSliceAt(i - 1); startCoincidentSliceAt(i); } } // cap off last slice endCoincidentSliceAt(coincidentIntrs.size() - 1); if (coincidentSlices.size() > 1) { // check if last coincident slice connects with first const auto &lastSliceEnd = coincidentSlices.back().lastVertex().pos(); const auto &firstSliceBegin = coincidentSlices[0][0].pos(); if (fuzzyEqual(lastSliceEnd, firstSliceBegin, utils::realPrecision<Real>())) { // they do connect, join them together auto &lastSlice = coincidentSlices.back(); lastSlice.vertexes().pop_back(); lastSlice.vertexes().insert(lastSlice.vertexes().end(), coincidentSlices[0].vertexes().begin(), coincidentSlices[0].vertexes().end()); // cleanup sliceEndPoints.back() = sliceEndPoints[0]; sliceEndPoints.erase(sliceEndPoints.begin()); sliceStartPoints.erase(sliceStartPoints.begin()); coincidentSlices.erase(coincidentSlices.begin()); coincidentIsOpposingDirection.erase(coincidentIsOpposingDirection.begin()); } } return result; } /// Finds all local self intersects of the polyline, local self intersects are defined as between /// two polyline segments that share a vertex. NOTES: /// - Singularities (repeating vertexes) are returned as coincident intersects template <typename Real> void localSelfIntersects(Polyline<Real> const &pline, std::vector<PlineIntersect<Real>> &output) { if (pline.size() < 2) { return; } if (pline.size() == 2) { if (pline.isClosed()) { // check if overlaps on itself from vertex 1 to vertex 2 if (utils::fuzzyEqual(pline[0].bulge(), -pline[1].bulge())) { // coincident output.emplace_back(0, 1, pline[1].pos()); output.emplace_back(1, 0, pline[0].pos()); } } return; } auto testAndAddIntersect = [&](std::size_t i, std::size_t j, std::size_t k) { const PlineVertex<Real> &v1 = pline[i]; const PlineVertex<Real> &v2 = pline[j]; const PlineVertex<Real> &v3 = pline[k]; // testing intersection between v1->v2 and v2->v3 segments if (fuzzyEqual(v1.pos(), v2.pos(), utils::realPrecision<Real>())) { // singularity // coincident output.emplace_back(i, j, v1.pos()); } else { IntrPlineSegsResult<Real> intrResult = intrPlineSegs(v1, v2, v2, v3); switch (intrResult.intrType) { case PlineSegIntrType::NoIntersect: break; case PlineSegIntrType::TangentIntersect: case PlineSegIntrType::OneIntersect: if (!fuzzyEqual(intrResult.point1, v2.pos(), utils::realPrecision<Real>())) { output.emplace_back(i, j, intrResult.point1); } break; case PlineSegIntrType::TwoIntersects: if (!fuzzyEqual(intrResult.point1, v2.pos(), utils::realPrecision<Real>())) { output.emplace_back(i, j, intrResult.point1); } if (!fuzzyEqual(intrResult.point2, v2.pos(), utils::realPrecision<Real>())) { output.emplace_back(i, j, intrResult.point2); } break; case PlineSegIntrType::SegmentOverlap: case PlineSegIntrType::ArcOverlap: // coincident output.emplace_back(i, j, intrResult.point1); break; } } }; for (std::size_t i = 2; i < pline.size(); ++i) { testAndAddIntersect(i - 2, i - 1, i); } if (pline.isClosed()) { // we tested for intersect between segments at indexes 0->1, 1->2 and everything up to and // including (count-3)->(count-2), (count-2)->(count-1), polyline is closed so now test // [(count-2)->(count-1), (count-1)->0] and [(count-1)->0, 0->1] testAndAddIntersect(pline.size() - 2, pline.size() - 1, 0); testAndAddIntersect(pline.size() - 1, 0, 1); } } /// Finds all global self intersects of the polyline, global self intersects are defined as all /// intersects between polyline segments that DO NOT share a vertex (use the localSelfIntersects /// function to find those). A spatial index is used to minimize the intersect comparisons required, /// the spatial index should hold bounding boxes for all of the polyline's segments. /// NOTES: /// - We never include intersects at a segment's start point, the matching intersect from the /// previous segment's end point is included (no sense in including both) template <typename Real, std::size_t N> void globalSelfIntersects(Polyline<Real> const &pline, std::vector<PlineIntersect<Real>> &output, StaticSpatialIndex<Real, N> const &spatialIndex) { if (pline.size() < 3) { return; } std::unordered_set<std::pair<std::size_t, std::size_t>, internal::IndexPairHash> visitedSegmentPairs; visitedSegmentPairs.reserve(pline.size()); std::vector<std::size_t> queryStack; queryStack.reserve(8); auto visitor = [&](std::size_t i, Real minX, Real minY, Real maxX, Real maxY) { std::size_t j = utils::nextWrappingIndex(i, pline); const PlineVertex<Real> &v1 = pline[i]; const PlineVertex<Real> &v2 = pline[j]; AABB<Real> envelope{minX, minY, maxX, maxY}; envelope.expand(utils::realThreshold<Real>()); auto indexVisitor = [&](std::size_t hitIndexStart) { std::size_t hitIndexEnd = utils::nextWrappingIndex(hitIndexStart, pline); // skip/filter already visited intersects // skip local segments if (i == hitIndexStart || i == hitIndexEnd || j == hitIndexStart || j == hitIndexEnd) { return true; } // skip reversed segment order (would end up comparing the same segments) if (visitedSegmentPairs.find({hitIndexStart, i}) != visitedSegmentPairs.end()) { return true; } // add the segment pair we're visiting now visitedSegmentPairs.emplace(i, hitIndexStart); const PlineVertex<Real> &u1 = pline[hitIndexStart]; const PlineVertex<Real> &u2 = pline[hitIndexEnd]; auto intrAtStartPt = [&](Vector2<Real> const &intr) { return fuzzyEqual(v1.pos(), intr) || fuzzyEqual(u1.pos(), intr); }; IntrPlineSegsResult<Real> intrResult = intrPlineSegs(v1, v2, u1, u2); switch (intrResult.intrType) { case PlineSegIntrType::NoIntersect: break; case PlineSegIntrType::TangentIntersect: case PlineSegIntrType::OneIntersect: if (!intrAtStartPt(intrResult.point1)) { output.emplace_back(i, hitIndexStart, intrResult.point1); } break; case PlineSegIntrType::TwoIntersects: if (!intrAtStartPt(intrResult.point1)) { output.emplace_back(i, hitIndexStart, intrResult.point1); } if (!intrAtStartPt(intrResult.point2)) { output.emplace_back(i, hitIndexStart, intrResult.point2); } break; case PlineSegIntrType::SegmentOverlap: case PlineSegIntrType::ArcOverlap: if (!intrAtStartPt(intrResult.point1)) { output.emplace_back(i, hitIndexStart, intrResult.point1); } if (!intrAtStartPt(intrResult.point2)) { output.emplace_back(i, hitIndexStart, intrResult.point2); } break; } // visit the entire query return true; }; spatialIndex.visitQuery(envelope.xMin, envelope.yMin, envelope.xMax, envelope.yMax, indexVisitor, queryStack); // visit all pline indexes return true; }; spatialIndex.visitItemBoxes(visitor); } /// Finds all self intersects of the polyline (equivalent to calling localSelfIntersects and /// globalSelfIntersects). template <typename Real, std::size_t N> void allSelfIntersects(Polyline<Real> const &pline, std::vector<PlineIntersect<Real>> &output, StaticSpatialIndex<Real, N> const &spatialIndex) { localSelfIntersects(pline, output); globalSelfIntersects(pline, output, spatialIndex); } /// Finds all intersects between pline1 and pline2. template <typename Real, std::size_t N> void findIntersects(Polyline<Real> const &pline1, Polyline<Real> const &pline2, StaticSpatialIndex<Real, N> const &pline1SpatialIndex, PlineIntersectsResult<Real> &output) { std::vector<std::size_t> queryResults; std::vector<std::size_t> queryStack; queryStack.reserve(8); std::unordered_set<std::pair<std::size_t, std::size_t>, internal::IndexPairHash> possibleDuplicates; auto &intrs = output.intersects; auto &coincidentIntrs = output.coincidentIntersects; auto pline2SegVisitor = [&](std::size_t i2, std::size_t j2) { PlineVertex<Real> const &p2v1 = pline2[i2]; PlineVertex<Real> const &p2v2 = pline2[j2]; queryResults.clear(); AABB<Real> bb = createFastApproxBoundingBox(p2v1, p2v2); // expand bounding box by threshold amount to ensure finding intersects at segment end points Real fuzz = cavc::utils::realPrecision<Real>(); pline1SpatialIndex.query(bb.xMin - fuzz, bb.yMin - fuzz, bb.xMax + fuzz, bb.yMax + fuzz, queryResults, queryStack); for (std::size_t i1 : queryResults) { std::size_t j1 = utils::nextWrappingIndex(i1, pline1); PlineVertex<Real> const &p1v1 = pline1[i1]; PlineVertex<Real> const &p1v2 = pline1[j1]; auto intrAtStartPt = [&](Vector2<Real> const &intr) { return fuzzyEqual(p1v1.pos(), intr) || fuzzyEqual(p2v1.pos(), intr); }; auto intrResult = intrPlineSegs(p1v1, p1v2, p2v1, p2v2); switch (intrResult.intrType) { case PlineSegIntrType::NoIntersect: break; case PlineSegIntrType::TangentIntersect: case PlineSegIntrType::OneIntersect: if (!intrAtStartPt(intrResult.point1)) { intrs.emplace_back(i1, i2, intrResult.point1); } break; case PlineSegIntrType::TwoIntersects: if (!intrAtStartPt(intrResult.point1)) { intrs.emplace_back(i1, i2, intrResult.point1); } if (!intrAtStartPt(intrResult.point2)) { intrs.emplace_back(i1, i2, intrResult.point2); } break; case PlineSegIntrType::SegmentOverlap: case PlineSegIntrType::ArcOverlap: coincidentIntrs.emplace_back(i1, i2, intrResult.point1, intrResult.point2); if (fuzzyEqual(p1v1.pos(), intrResult.point1) || fuzzyEqual(p1v1.pos(), intrResult.point2)) { possibleDuplicates.insert({utils::prevWrappingIndex(i1, pline1), i2}); } if (fuzzyEqual(p2v1.pos(), intrResult.point1) || fuzzyEqual(p2v1.pos(), intrResult.point2)) { possibleDuplicates.insert({i1, utils::prevWrappingIndex(i2, pline2)}); } break; } } // visit all indexes return true; }; pline2.visitSegIndices(pline2SegVisitor); // remove duplicate points caused by the coincident intersect definition intrs.erase(std::remove_if(intrs.begin(), intrs.end(), [&](auto const &intr) { auto found = possibleDuplicates.find({intr.sIndex1, intr.sIndex2}); if (found == possibleDuplicates.end()) { return false; } auto const &endPt1 = pline1[utils::nextWrappingIndex(intr.sIndex1, pline1)].pos(); if (fuzzyEqual(intr.pos, endPt1)) { return true; } auto const &endPt2 = pline2[utils::nextWrappingIndex(intr.sIndex2, pline2)].pos(); return fuzzyEqual(intr.pos, endPt2); }), intrs.end()); } } // namespace cavc #endif // CAVC_POLYLINEINTERSECTS_HPP
38.84322
100
0.65414
[ "vector" ]
9c65705c0f8cbceb6bd85cdddfa0e257b6f222f5
4,138
hpp
C++
ReactNativeFrontend/ios/Pods/boost/boost/gil/extension/io/jpeg/detail/scanline_read.hpp
Harshitha91/Tmdb-react-native-node
e06e3f25a7ee6946ef07a1f524fdf62e48424293
[ "Apache-2.0" ]
12,278
2015-01-29T17:11:33.000Z
2022-03-31T21:12:00.000Z
ReactNativeFrontend/ios/Pods/boost/boost/gil/extension/io/jpeg/detail/scanline_read.hpp
Harshitha91/Tmdb-react-native-node
e06e3f25a7ee6946ef07a1f524fdf62e48424293
[ "Apache-2.0" ]
9,469
2015-01-30T05:33:07.000Z
2022-03-31T16:17:21.000Z
ReactNativeFrontend/ios/Pods/boost/boost/gil/extension/io/jpeg/detail/scanline_read.hpp
Harshitha91/Tmdb-react-native-node
e06e3f25a7ee6946ef07a1f524fdf62e48424293
[ "Apache-2.0" ]
892
2015-01-29T16:26:19.000Z
2022-03-20T07:44:30.000Z
// // Copyright 2007-2012 Christian Henning, Andreas Pokorny, Lubomir Bourdev // // Distributed under the Boost Software License, Version 1.0 // See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt // #ifndef BOOST_GIL_EXTENSION_IO_JPEG_DETAIL_SCANLINE_READ_HPP #define BOOST_GIL_EXTENSION_IO_JPEG_DETAIL_SCANLINE_READ_HPP #include <boost/gil/extension/io/jpeg/detail/base.hpp> #include <boost/gil/extension/io/jpeg/detail/is_allowed.hpp> #include <boost/gil/extension/io/jpeg/detail/reader_backend.hpp> #include <boost/gil/io/base.hpp> #include <boost/gil/io/conversion_policies.hpp> #include <boost/gil/io/device.hpp> #include <boost/gil/io/reader_base.hpp> #include <boost/gil/io/scanline_read_iterator.hpp> #include <boost/gil/io/typedefs.hpp> #include <csetjmp> #include <vector> namespace boost { namespace gil { #if BOOST_WORKAROUND(BOOST_MSVC, >= 1400) #pragma warning(push) #pragma warning(disable:4611) //interaction between '_setjmp' and C++ object destruction is non-portable #endif /// /// JPEG Scanline Reader /// template< typename Device > class scanline_reader< Device , jpeg_tag > : public reader_backend< Device , jpeg_tag > { public: using tag_t = jpeg_tag; using backend_t = reader_backend<Device, tag_t>; using this_t = scanline_reader<Device, tag_t>; using iterator_t = scanline_read_iterator<this_t>; public: scanline_reader( Device& device , const image_read_settings< jpeg_tag >& settings ) : reader_backend< Device , jpeg_tag >( device , settings ) { initialize(); } void read( byte_t* dst , int ) { // Fire exception in case of error. if( setjmp( this->_mark )) { this->raise_error(); } // read data read_scanline( dst ); } /// Skip over a scanline. void skip( byte_t* dst, int ) { // Fire exception in case of error. if( setjmp( this->_mark )) { this->raise_error(); } // read data read_scanline( dst ); } iterator_t begin() { return iterator_t( *this ); } iterator_t end() { return iterator_t( *this, this->_info._height ); } private: void initialize() { this->get()->dct_method = this->_settings._dct_method; io_error_if( jpeg_start_decompress( this->get() ) == false , "Cannot start decompression." ); switch( this->_info._color_space ) { case JCS_GRAYSCALE: { this->_scanline_length = this->_info._width; break; } case JCS_RGB: //!\todo add Y'CbCr? We loose image quality when reading JCS_YCbCr as JCS_RGB case JCS_YCbCr: { this->_scanline_length = this->_info._width * num_channels< rgb8_view_t >::value; break; } case JCS_CMYK: //!\todo add Y'CbCrK? We loose image quality when reading JCS_YCCK as JCS_CMYK case JCS_YCCK: { this->get()->out_color_space = JCS_CMYK; this->_scanline_length = this->_info._width * num_channels< cmyk8_view_t >::value; break; } default: { io_error( "Unsupported jpeg color space." ); } } } void read_scanline( byte_t* dst ) { JSAMPLE *row_adr = reinterpret_cast< JSAMPLE* >( dst ); // Read data. io_error_if( jpeg_read_scanlines( this->get() , &row_adr , 1 ) != 1 , "jpeg_read_scanlines: fail to read JPEG file" ); } }; #if BOOST_WORKAROUND(BOOST_MSVC, >= 1400) #pragma warning(pop) #endif } // namespace gil } // namespace boost #endif
27.045752
104
0.563557
[ "object", "vector" ]
9c68d2346c898a6072d587f7bb15e28964257f8e
13,641
cpp
C++
Laser_watchdog.cpp
GerryZhang7/Laser-Watchdog
29ad99cafc7da80b740b6556bb11834c974236b4
[ "MIT" ]
1
2021-07-13T14:57:43.000Z
2021-07-13T14:57:43.000Z
Laser_watchdog.cpp
GerryZhang7/Laser-Watchdog
29ad99cafc7da80b740b6556bb11834c974236b4
[ "MIT" ]
null
null
null
Laser_watchdog.cpp
GerryZhang7/Laser-Watchdog
29ad99cafc7da80b740b6556bb11834c974236b4
[ "MIT" ]
2
2019-03-14T13:53:57.000Z
2021-07-13T14:57:45.000Z
#include "gpiolib_addr.h" #include "gpiolib_reg.c" #include "gpiolib_reg.h" #include <math.h> #include <stdint.h> #include <stdio.h> //for the printf() function #include <fcntl.h> #include <linux/watchdog.h> //needed for the watchdog specific constants #include <unistd.h> //needed for sleep #include <sys/ioctl.h> //needed for the ioctl function #include <stdlib.h> //for atoi #include <time.h> //for time_t and the time() function #include <sys/time.h> //for gettimeofday() //The #defines found below are macros that are used to structure the different type of log messages that this program prints //The PRINT_MSG macro is used to print messages to a log file where we will keep track of the watchdog and initializations of GPIO pins. #define PRINT_MSG(file, time1, programName, sev, str) \ do{ \ fprintf(logFile, "%s : %s : %s : %s", time1, programName, sev, str); \ fflush(logFile); \ }while(0) //PRINT_MSG1 is used to write the inaugural message to a Stats file in order to know when it is first written to. #define PRINT_MSG1(file, time1, programName, sev, str) \ do{ \ fprintf(statsFile, "%s : %s : %s : %s ", time1, programName, sev, str); \ fflush(statsFile); \ }while(0) //PRINT_MSG2 writes to the Stats file and updates when each laser was broken and then outputs the total amount of times each laser was broken. The amount of times an object "enters" or "exits" is also printed at the end. #define PRINT_MSG2(file, time1, programName, sev, str, point) \ do{ \ fprintf(statsFile, "%s : %s : %s : %s : %d \n\n", time1, programName, sev, str, *point); \ fflush(statsFile); \ }while(0) //HARDWARE DEPENDENT CODE //initializeGPIO is used to initialize all of the GPIO pins on the Raspberry Pi. GPIO_Handle initializeGPIO() { GPIO_Handle gpio; gpio = gpiolib_init_gpio(); if (gpio == NULL) { perror("Could not initialize GPIO"); } return gpio; } //Declaring an enum that will be used to read a config file. enum State { START, EQUALS, NOT_EQUALS, TIMEOUT, LOGFILE, STATSFILE }; //The readConfig function uses a State Machine to read the necessary information (watchdog timer, and directory of the log and stats file that will be later written to) from a config file. void readConfig(FILE* configFile, int* timeout, char* logFileName, char* statsFileName) { int i = 0; int j = 0; int k = 0; int parameter = 0; char buffer[255]; enum State s = START; *timeout = 0; while (fgets(buffer, 255, configFile) != NULL) { i = 0; if (buffer[i] != '#') { while (buffer[i] != 0) { switch (s) { case START: if (buffer[i] == '=') { s = EQUALS; } else if (buffer[i] != '=') { s = NOT_EQUALS; } else { s = START; } ++i; break; case NOT_EQUALS: if (buffer[i] != '=') { s = NOT_EQUALS; } else if (buffer[i] == '=') { s = EQUALS; } ++i; break; case EQUALS: if (parameter == 0) { s = TIMEOUT; } else if (parameter == 1) { s = LOGFILE; } else if (parameter == 2) { s = STATSFILE; } //++i; break; case TIMEOUT: while (buffer[i] != 0) { if (buffer[i] >= '0' && buffer[i] <= '9') { //Move the previous digits up one position and add the //new digit *timeout = (*timeout * 10) + (buffer[i] - '0'); } ++i; } ++parameter; s = NOT_EQUALS; break; case LOGFILE: j = 0; while (buffer[i] != 0 && buffer[i] != '\n') { //If the characters after the equal sign are not spaces or //equal signs, then it will add that character to the string if (buffer[i] != ' ' && buffer[i] != '=') { logFileName[j] = buffer[i]; ++j; } ++i; } //Add a null terminator at the end logFileName[j] = 0; ++parameter; s = NOT_EQUALS; break; case STATSFILE: k = 0; while (buffer[i] != 0 && buffer[i] != '\n') { //If the characters after the equal sign are not spaces or //equal signs, then it will add that character to the string if (buffer[i] != ' ' && buffer[i] != '=') { statsFileName[k] = buffer[i]; ++k; } ++i; } //Add a null terminator at the end statsFileName[k] = 0; ++parameter; s = NOT_EQUALS; break; default: break; } } } } } //Checks the status of each laser by detecting if the corresponding photodiode receives light from the laser. If the photodiode does not receive light // it does not produce a voltage and the input pin from the Raspberry Pi does not detect an input voltage. #define LASER1_PIN_NUM 4 //Left diode #define LASER2_PIN_NUM 6 //Right diode int laserDiodeStatus(GPIO_Handle gpio, int diodeNumber) { if (gpio == NULL) { return -1; } if (diodeNumber == 1) { uint32_t level_reg = gpiolib_read_reg(gpio, GPLEV(0)); if (level_reg & (1 << LASER1_PIN_NUM)) { return 1; } else { return 0; } } else if (diodeNumber == 2) { uint32_t level_reg = gpiolib_read_reg(gpio, GPLEV(0)); if (level_reg & (1 << LASER2_PIN_NUM)) { return 1; } else { return 0; } } } #endif //END OF HARDWARE DEPENDENT CODE //FINAL OUTPUT MESSAGE WITH RESULTS void outputMessage(int laser1Count, int laser2Count, int numberIn, int numberOut) { printf("Laser 1 was broken %d times \n", laser1Count); printf("Laser 2 was broken %d times \n", laser2Count); printf("%d objects entered the room \n", numberIn); printf("%d objexts exitted the room \n", numberOut); } int main(const int argc, const char* const argv[]) { enum State { START, LEFT, LEFT_BOTH, LEFT_RIGHT, OUT, RIGHT, RIGHT_BOTH, RIGHT_LEFT, IN, NONE }; enum State s = START; int laser1Count = 0; int* a = &laser1Count; int laser2Count = 0; int* b = &laser2Count; int numberIn = 0; int* c = &numberIn; int numberOut = 0; int* d = &numberOut; //Create a string that contains the program name const char* argName = argv[0]; //These variables will be used to count how long the name of the program is int i = 0; int namelength = 0; while (argName[i] != 0) { namelength++; i++; } char programName[namelength]; i = 0; //Copy the name of the program without the ./ at the start //of argv[0] while (argName[i + 2] != 0) { programName[i] = argName[i + 2]; i++; } //Create a file pointer named configFile FILE* configFile; //Set configFile to point to the Lab4Sample.cfg file. It is //set to read the file. configFile = fopen("/home/pi/Lab4Sample.cfg", "r"); //Output a warning message if the file cannot be openned if (!configFile) { perror("The config file could not be opened"); return -1; } //Declare the variables that will be passed to the readConfig function int timeout; char logFileName[50]; char statsFileName[50]; //Call the readConfig function to read from the config file readConfig(configFile, &timeout, logFileName, statsFileName); //Close the configFile now that we have finished reading from it fclose(configFile); //Creates a pointer called logFile that points to the logFile. FILE* logFile; logFile = fopen(logFileName, "a"); //Creates a pointer called statsFile that points to the statsFile. FILE* statsFile; statsFile = fopen(statsFileName, "a"); //Check that the file opens properly. if (!configFile) { perror("The log file could not be opened"); return -1; } //Start of writing messages to log file. char time1[30]; getTime(time1); getTime(time1); PRINT_MSG(logFile, time1, programName, "sev = Info ", "The program is running\n\n"); GPIO_Handle gpio = initializeGPIO(); getTime(time1); PRINT_MSG(logFile, time1, programName, "sev = Info ", "The GPIO pins have been initialized\n\n"); uint32_t sel_reg = gpiolib_read_reg(gpio, GPFSEL(1)); sel_reg &= ~(1 << 18); gpiolib_write_reg(gpio, GPFSEL(1), sel_reg); getTime(time1); PRINT_MSG(logFile, time1, programName, "sev = Info ", "Pin 16 has been set as output\n\n"); if (argc != 2) { PRINT_MSG(logFile, time1, programName, "sev = Error ", "Invalid number of arguments\n\n"); errorMessage(-1); return -1; } //End of writing to log file. //Watchdog initialization int watchdog; if ((watchdog = open("/dev/watchdog", O_RDWR | O_NOCTTY)) < 0) { printf("Error: Couldn't open watchdog device! %d\n", watchdog); return -1; } getTime(time1); PRINT_MSG(logFile, time1, programName, "sev = Info ", "The Watchdog file has been opened\n\n"); ioctl(watchdog, WDIOC_SETTIMEOUT, &timeout); getTime(time1); PRINT_MSG(logFile, time1, programName, "sev = Info ", "The Watchdog time limit has been set\n\n"); ioctl(watchdog, WDIOC_GETTIMEOUT, &timeout); printf("The watchdog timeout is %d seconds.\n\n", timeout); // time_t startTime = time(NULL); int timeLimit = atoi(argv[1]); getTime(time1); PRINT_MSG(logFile, time1, programName, "sev = Info ", "User has entered a valid time\n\n"); //State machine that reads the current state of the lasers. Outputs messages in real-time. while ((time(NULL) - startTime) < timeLimit) { int left = laserDiodeStatus(gpio, 1); int right = laserDiodeStatus(gpio, 2); fprintf(stderr, "status %i %i \n", left, right); //Status--> light received/laser unbroken //!Status--> light not received/laser broken //Left == laser1 //Right == laser2 //Left -> Right == out //Right -> Left == in switch (s) { case START: if (left && right) { s = NONE; break; } else if (!left && right) { ++laser1Count; getTime(time1); PRINT_MSG(logFile, time1, programName, "sev = Info ", "Laser 1 has been broken\n\n"); s = LEFT; break; } else if (left && !right) { ++laser2Count; getTime(time1); PRINT_MSG(logFile, time1, programName, "sev = Info ", "Laser 2 has been broken\n\n"); s = RIGHT; break; } else { errorMessage(-1); return -1; break; } break; case LEFT: if (!left && right) { s = LEFT; break; } else if (!left && !right) { ++laser2Count; getTime(time1); PRINT_MSG(logFile, time1, programName, "sev = Info ", "Laser 2 has been broken\n\n"); s = LEFT_BOTH; break; } else if (left && right) { s = NONE; break; } break; case LEFT_BOTH: if (!left && !right) { s = LEFT_BOTH; break; } else if (!left && right) { s = LEFT; break; } else if (left && !right) { s = LEFT_RIGHT; break; } break; case LEFT_RIGHT: if (left && !right) { s = LEFT_RIGHT; break; } else if (!left && !right) { ++laser1Count; getTime(time1); PRINT_MSG(logFile, time1, programName, "sev = Info ", "Laser 1 has been broken\n\n"); s = LEFT_BOTH; break; } else if (left && right) { s = OUT; break; } break; case OUT: ++numberOut; s = NONE; break; case RIGHT: if (left && !right) { s = RIGHT; break; } else if (!left && !right) { ++laser1Count; getTime(time1); PRINT_MSG(logFile, time1, programName, "sev = Info ", "Laser 1 has been broken\n\n"); s = RIGHT_BOTH; break; } else if (left && right) { s = NONE; break; } break; case RIGHT_BOTH: if (!left && !right) { s = RIGHT_BOTH; break; } else if (left && !right) { s = RIGHT; break; } else if (!left && right) { s = RIGHT_LEFT; break; } break; case RIGHT_LEFT: if (!left && right) { s = RIGHT_LEFT; break; } else if (!left && !right) { ++laser2Count; getTime(time1); PRINT_MSG(logFile, time1, programName, "sev = Info ", "Laser 2 has been broken\n\n"); s = RIGHT_BOTH; break; } else if (left && right) { s = IN; break; } break; case IN: ++numberIn; s = NONE; case NONE: if (left && right) { s = NONE; break; } else if (!left && right) { ++laser1Count; getTime(time1); PRINT_MSG(logFile, time1, programName, "sev = Info ", "Laser 1 has been broken\n\n"); s = LEFT; break; } else if (left && !right) { ++laser2Count; getTime(time1); PRINT_MSG(logFile, time1, programName, "sev = Info ", "Laser 2 has been broken\n\n"); s = RIGHT; break; } break; default: errorMessage(-1); return -1; break; } } outputMessage(laser1Count, laser2Count, numberIn, numberOut); getTime(time1); PRINT_MSG1(statsFile, time1, programName, "sev = Info ", "Stats have been updated\n\n"); getTime(time1); PRINT_MSG2(statsFile, time1, programName, "sev = Info ", "Number of times laser 1 was broken: ", a); getTime(time1); PRINT_MSG2(statsFile, time1, programName, "sev = Info ", "Number of times laser 2 was broken: ", b); getTime(time1); PRINT_MSG2(statsFile, time1, programName, "sev = Info ", "Number of objects entered the room: ", c); getTime(time1); PRINT_MSG2(statsFile, time1, programName, "sev = Info ", "Number of objects exitted the room: ", d); write(watchdog, "V", 1); getTime(time1); //Log that the Watchdog was disabled PRINT_MSG(logFile, time1, programName, "sev = Info ", "The Watchdog was disabled\n\n"); //Close the watchdog file so that it is not accidentally tampered with close(watchdog); getTime(time1); //Log that the Watchdog was closed PRINT_MSG(logFile, time1, programName, "sev = Info ", "The Watchdog was closed\n\n"); //Free the gpio pins gpiolib_free_gpio(gpio); getTime(time1); //Log that the GPIO pins were freed PRINT_MSG(logFile, time1, programName, "sev = Info ", "The GPIO pins have been freed\n\n"); return 0; } #endif
24.446237
220
0.622975
[ "object" ]
9c6946e1db7c8fe3bff1cf713e50453526bbff64
30,082
cpp
C++
Base/PLRenderer/src/Renderer/Backend/RendererBackend.cpp
ktotheoz/pixellight
43a661e762034054b47766d7e38d94baf22d2038
[ "MIT" ]
83
2015-01-08T15:06:14.000Z
2021-07-20T17:07:00.000Z
Base/PLRenderer/src/Renderer/Backend/RendererBackend.cpp
PixelLightFoundation/pixellight
43a661e762034054b47766d7e38d94baf22d2038
[ "MIT" ]
19
2018-08-24T08:10:13.000Z
2018-11-29T06:39:08.000Z
Base/PLRenderer/src/Renderer/Backend/RendererBackend.cpp
ktotheoz/pixellight
43a661e762034054b47766d7e38d94baf22d2038
[ "MIT" ]
40
2015-02-25T18:24:34.000Z
2021-03-06T09:01:48.000Z
/*********************************************************\ * File: RendererBackend.cpp * * * Copyright (C) 2002-2013 The PixelLight Team (http://www.pixellight.org/) * * This file is part of PixelLight. * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \*********************************************************/ //[-------------------------------------------------------] //[ Includes ] //[-------------------------------------------------------] #include <PLCore/Log/Log.h> #include <PLCore/Base/Class.h> #include <PLCore/Tools/Tools.h> #include <PLCore/Tools/Profiling.h> #include <PLGraphics/Image/Image.h> #include <PLGraphics/Image/ImageBuffer.h> #include "PLRenderer/RendererContext.h" #include "PLRenderer/Renderer/Surface.h" #include "PLRenderer/Renderer/IndexBuffer.h" #include "PLRenderer/Renderer/VertexBuffer.h" #include "PLRenderer/Renderer/TextureBuffer.h" #include "PLRenderer/Renderer/FixedFunctions.h" #include "PLRenderer/Renderer/Backend/DrawHelpersBackendShaders.h" #include "PLRenderer/Renderer/Backend/DrawHelpersBackendFixedFunctions.h" #include "PLRenderer/Renderer/Backend/RendererBackend.h" //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] using namespace PLCore; using namespace PLMath; using namespace PLGraphics; namespace PLRenderer { //[-------------------------------------------------------] //[ RTTI interface ] //[-------------------------------------------------------] pl_implement_class(RendererBackend) //[-------------------------------------------------------] //[ Internal helper function ] //[-------------------------------------------------------] const char *GetBoolString(bool bValue) { return bValue ? "true" : "false"; } //[-------------------------------------------------------] //[ Public functions ] //[-------------------------------------------------------] /** * @brief * Makes a surface to the renderers current render target */ bool RendererBackend::MakeSurfaceCurrent(Surface &cSurface, uint8 nFace) { return cSurface.MakeCurrent(nFace); } /** * @brief * Unmakes a surface from the renderers current render target */ bool RendererBackend::UnmakeSurfaceCurrent(Surface &cSurface) { return cSurface.UnmakeCurrent(); } /** * @brief * Makes a texture buffer to the renderers current texture buffer */ bool RendererBackend::MakeTextureBufferCurrent(TextureBuffer &cTextureBuffer, uint32 nStage) { return cTextureBuffer.MakeCurrent(nStage); } //[-------------------------------------------------------] //[ Protected functions ] //[-------------------------------------------------------] /** * @brief * Constructor */ RendererBackend::RendererBackend(EMode nMode) : m_pDrawHelpers(nullptr), m_nSwapInterval(1), m_nMode(nMode), m_pRendererContext(nullptr) { // Create the draw helpers instance depending on the renderer mode switch (m_nMode) { case ModeFixedFunctions: m_pDrawHelpers = new DrawHelpersBackendFixedFunctions(*this); break; case ModeShaders: m_pDrawHelpers = new DrawHelpersBackendShaders(*this); break; case ModeBoth: default: // The default is shaders based because it's less painful m_pDrawHelpers = new DrawHelpersBackendShaders(*this); break; } // Create the renderer context this renderer instance is in, the renderer context will take // over the control of everything m_pRendererContext = new RendererContext(*this); // Init data MemoryManager::Set(&m_sCapabilities, 0, sizeof(Capabilities)); MemoryManager::Set(&m_sStatistics, 0, sizeof(Statistics)); m_ppDataBackup = nullptr; // Init color mask m_bColorMask[0] = true; m_bColorMask[1] = true; m_bColorMask[2] = true; m_bColorMask[3] = true; // States m_ppnSamplerState = nullptr; m_ppnInternalSamplerState = nullptr; { // Set default renderer states m_nDefaultRenderState[RenderState::FillMode] = Fill::Solid; m_nDefaultRenderState[RenderState::CullMode] = Cull::CCW; // Z buffer m_nDefaultRenderState[RenderState::ZEnable] = true; m_nDefaultRenderState[RenderState::ZWriteEnable] = true; m_nDefaultRenderState[RenderState::ZFunc] = Compare::LessEqual; m_nDefaultRenderState[RenderState::ZBias] = Tools::FloatToUInt32(0.0f); m_nDefaultRenderState[RenderState::SlopeScaleDepthBias] = Tools::FloatToUInt32(0.0f); m_nDefaultRenderState[RenderState::DepthBias] = Tools::FloatToUInt32(0.0f); // Blend m_nDefaultRenderState[RenderState::BlendEnable] = false; m_nDefaultRenderState[RenderState::SrcBlendFunc] = BlendFunc::SrcAlpha; m_nDefaultRenderState[RenderState::DstBlendFunc] = BlendFunc::InvSrcAlpha; // Stencil m_nDefaultRenderState[RenderState::StencilEnable] = false; m_nDefaultRenderState[RenderState::StencilFunc] = Compare::Always; m_nDefaultRenderState[RenderState::StencilRef] = 0; m_nDefaultRenderState[RenderState::StencilMask] = 0xFFFFFFFF; m_nDefaultRenderState[RenderState::StencilFail] = StencilOp::Keep; m_nDefaultRenderState[RenderState::StencilZFail] = StencilOp::Keep; m_nDefaultRenderState[RenderState::StencilPass] = StencilOp::Keep; m_nDefaultRenderState[RenderState::TwoSidedStencilMode] = false; m_nDefaultRenderState[RenderState::CCWStencilFunc] = Compare::Always; m_nDefaultRenderState[RenderState::CCWStencilFail] = StencilOp::Keep; m_nDefaultRenderState[RenderState::CCWStencilZFail] = StencilOp::Keep; m_nDefaultRenderState[RenderState::CCWStencilPass] = StencilOp::Keep; // Point and line m_nDefaultRenderState[RenderState::PointSize] = Tools::FloatToUInt32(1.0f); m_nDefaultRenderState[RenderState::PointScaleEnable] = false; m_nDefaultRenderState[RenderState::PointSizeMin] = Tools::FloatToUInt32(1.0f); m_nDefaultRenderState[RenderState::PointSizeMax] = Tools::FloatToUInt32(64.0f); m_nDefaultRenderState[RenderState::PointScaleA] = Tools::FloatToUInt32(1.0f); m_nDefaultRenderState[RenderState::PointScaleB] = Tools::FloatToUInt32(0.0f); m_nDefaultRenderState[RenderState::PointScaleC] = Tools::FloatToUInt32(0.0f); m_nDefaultRenderState[RenderState::LineWidth] = Tools::FloatToUInt32(1.0f); // Tessellation m_nDefaultRenderState[RenderState::TessellationFactor] = 1; m_nDefaultRenderState[RenderState::TessellationMode] = TessellationMode::Discrete; // Misc m_nDefaultRenderState[RenderState::PointSpriteEnable] = false; m_nDefaultRenderState[RenderState::DitherEnable] = false; m_nDefaultRenderState[RenderState::ScissorTestEnable] = false; m_nDefaultRenderState[RenderState::MultisampleEnable] = true; m_nDefaultRenderState[RenderState::DepthClamp] = false; m_nDefaultRenderState[RenderState::InvCullMode] = false; m_nDefaultRenderState[RenderState::FixedFillMode] = Fill::Unknown; } MemoryManager::Copy(m_nRenderState, m_nDefaultRenderState, sizeof(uint32)*RenderState::Number); { // Set default sampler states // Address modes m_nDefaultSamplerState[Sampler::AddressU] = TextureAddressing::Wrap; m_nDefaultSamplerState[Sampler::AddressV] = TextureAddressing::Wrap; m_nDefaultSamplerState[Sampler::AddressW] = TextureAddressing::Wrap; // Filter m_nDefaultSamplerState[Sampler::MagFilter] = TextureFiltering::Linear; m_nDefaultSamplerState[Sampler::MinFilter] = TextureFiltering::Linear; m_nDefaultSamplerState[Sampler::MipFilter] = TextureFiltering::Linear; // Misc m_nDefaultSamplerState[Sampler::MipmapLODBias] = 0; m_nDefaultSamplerState[Sampler::MaxMapLevel] = 1000; m_nDefaultSamplerState[Sampler::MaxAnisotropy] = 1; } // Current stuff m_fViewPortMinZ = 0.0f; m_fViewPortMaxZ = 0.0f; m_nCurrentSurfaceFace = 0; m_ppCurrentTextureBuffer = nullptr; m_pCurrentIndexBuffer = nullptr; // The rest is done by the API backends! } /** * @brief * Destructor */ RendererBackend::~RendererBackend() { // Destroy the draw helpers instance (usually already destroyed in a derived class to have a better shut down flow) if (m_pDrawHelpers) delete m_pDrawHelpers; // Destroy all renderer surfaces of this renderer while (m_lstSurfaces.GetNumOfElements()) delete m_lstSurfaces[0]; // Destroy all display modes for (uint32 i=0; i<m_lstDisplayModeList.GetNumOfElements(); i++) delete m_lstDisplayModeList[i]; // Destroy all renderer resources of this renderer while (m_lstResources.GetNumOfElements()) delete m_lstResources[0]; // [NOTE] Index and vertex buffer will be destroyed through the renderer automatically } /** * @brief * Writes the renderer capabilities into the log */ void RendererBackend::ShowRendererCapabilities() const { PL_LOG(Info, " ") PL_LOG(Info, "Renderer capabilities:") PL_LOG(Info, String(" TotalAvailableGPUMemory: ") + m_sCapabilities.nTotalAvailableGPUMemory + " KiB (" + m_sCapabilities.nTotalAvailableGPUMemory/1024 + " MiB)") PL_LOG(Info, String(" MaxColorRenderTargets: ") + m_sCapabilities.nMaxColorRenderTargets) PL_LOG(Info, String(" MaxTextureUnits: ") + m_sCapabilities.nMaxTextureUnits) PL_LOG(Info, String(" MaxAnisotropy: ") + static_cast<uint32>(m_sCapabilities.nMaxAnisotropy)) PL_LOG(Info, String(" MaxTessellationFactor: ") + m_sCapabilities.nMaxTessellationFactor) PL_LOG(Info, String(" MaxTextureBufferSize: ") + static_cast<uint32>(m_sCapabilities.nMaxTextureBufferSize)) PL_LOG(Info, String(" TextureBufferNonPowerOfTwo: ") + GetBoolString(m_sCapabilities.bTextureBufferNonPowerOfTwo)) PL_LOG(Info, String(" TextureBuffer2DArray: ") + GetBoolString(m_sCapabilities.bTextureBuffer2DArray)) PL_LOG(Info, String(" MaxTextureBuffer2DArrayLayers: ") + static_cast<uint32>(m_sCapabilities.nMaxTextureBuffer2DArrayLayers)) PL_LOG(Info, String(" TextureBufferRectangle: ") + GetBoolString(m_sCapabilities.bTextureBufferRectangle)) PL_LOG(Info, String(" MaxRectangleTextureBufferSize: ") + static_cast<uint32>(m_sCapabilities.nMaxRectangleTextureBufferSize)) PL_LOG(Info, String(" TextureBuffer3D: ") + GetBoolString(m_sCapabilities.bTextureBuffer3D)) PL_LOG(Info, String(" Max3DTextureBufferSize: ") + static_cast<uint32>(m_sCapabilities.nMax3DTextureBufferSize)) PL_LOG(Info, String(" TextureBufferCube: ") + GetBoolString(m_sCapabilities.bTextureBufferCube)) PL_LOG(Info, String(" MaxCubeTextureBufferSize: ") + static_cast<uint32>(m_sCapabilities.nMaxCubeTextureBufferSize)) PL_LOG(Info, String(" StencilWrap: ") + GetBoolString(m_sCapabilities.bStencilWrap)) PL_LOG(Info, String(" TwoSidedStencils: ") + GetBoolString(m_sCapabilities.bTwoSidedStencils)) PL_LOG(Info, String(" DepthBoundsTest: ") + GetBoolString(m_sCapabilities.bDepthBoundsTest)) PL_LOG(Info, String(" PointSprite: ") + GetBoolString(m_sCapabilities.bPointSprite)) PL_LOG(Info, String(" PointParameters: ") + GetBoolString(m_sCapabilities.bPointParameters)) PL_LOG(Info, String(" OcclusionQuery: ") + GetBoolString(m_sCapabilities.bOcclusionQuery)) PL_LOG(Info, String(" VertexBufferSecondaryColor: ") + GetBoolString(m_sCapabilities.bVertexBufferSecondaryColor)) PL_LOG(Info, String(" Instancing: ") + GetBoolString(m_sCapabilities.bInstancing)) PL_LOG(Info, " ") // Fixed functions FixedFunctions *pFixedFunctions = GetFixedFunctions(); if (pFixedFunctions) { PL_LOG(Info, "Renderer fixed functions capabilities:") PL_LOG(Info, String(" MaxActiveLights: ") + pFixedFunctions->GetCapabilities().nMaxActiveLights) PL_LOG(Info, String(" MaxClipPlanes: ") + pFixedFunctions->GetCapabilities().nMaxClipPlanes) PL_LOG(Info, String(" VertexBufferFogCoord: ") + GetBoolString(pFixedFunctions->GetCapabilities().bVertexBufferFogCoord)) PL_LOG(Info, String(" MaxVertexBufferStreams: ") + pFixedFunctions->GetCapabilities().nMaxVertexBufferStreams) PL_LOG(Info, " ") } } bool RendererBackend::CheckTextureBuffer1D(Image &cImage, TextureBuffer::EPixelFormat nInternalFormat) const { // Get the first image buffer ImageBuffer *pImageBuffer = cImage.GetBuffer(); if (pImageBuffer) { // Valid dimension? uint32 nSize = pImageBuffer->GetSize().x; if (nSize) { if (nSize == 1) nSize = pImageBuffer->GetSize().y; else { if (pImageBuffer->GetSize().y != 1) return false; // Error! } return IsValidTextureBuffer1DSize(nSize); } } // Error! return false; } bool RendererBackend::CheckTextureBuffer2D(Image &cImage, TextureBuffer::EPixelFormat nInternalFormat) const { // Get the first image buffer const ImageBuffer *pImageBuffer = cImage.GetBuffer(); // Check image buffer dimension return (pImageBuffer && IsValidTextureBuffer2DSize(pImageBuffer->GetSize().x) && IsValidTextureBuffer2DSize(pImageBuffer->GetSize().y)); } bool RendererBackend::CheckTextureBuffer2DArray(Image &cImage, TextureBuffer::EPixelFormat nInternalFormat) const { // Get the first image buffer const ImageBuffer *pImageBuffer = cImage.GetBuffer(); // Check image buffer dimension return (pImageBuffer && IsValidTextureBuffer2DSize(pImageBuffer->GetSize().x) && IsValidTextureBuffer2DSize(pImageBuffer->GetSize().y) && pImageBuffer->GetSize().z <= m_sCapabilities.nMaxTextureBuffer2DArrayLayers && pImageBuffer->GetSize().z > 0); } bool RendererBackend::CheckTextureBufferRectangle(Image &cImage, TextureBuffer::EPixelFormat nInternalFormat) const { // Get the first image buffer const ImageBuffer *pImageBuffer = cImage.GetBuffer(); // Check image buffer dimension return (pImageBuffer && IsValidTextureBufferRectangleSize(pImageBuffer->GetSize().x) && IsValidTextureBufferRectangleSize(pImageBuffer->GetSize().y)); } bool RendererBackend::CheckTextureBuffer3D(Image &cImage, TextureBuffer::EPixelFormat nInternalFormat) const { // Get the first image buffer const ImageBuffer *pImageBuffer = cImage.GetBuffer(); // Check image buffer dimension return (pImageBuffer && IsValidTextureBuffer3DSize(pImageBuffer->GetSize().x) && IsValidTextureBuffer3DSize(pImageBuffer->GetSize().y) && IsValidTextureBuffer3DSize(pImageBuffer->GetSize().z)); } bool RendererBackend::CheckTextureBufferCube(Image &cImage, TextureBuffer::EPixelFormat nInternalFormat) const { // Get the first image buffer const ImageBuffer *pImageBuffer = cImage.GetBuffer(); // Check image buffer dimension return (pImageBuffer && pImageBuffer->GetSize().x == pImageBuffer->GetSize().y && IsValidTextureBufferCubeSize(pImageBuffer->GetSize().x)); } //[-------------------------------------------------------] //[ Public virtual Renderer functions ] //[-------------------------------------------------------] RendererContext &RendererBackend::GetRendererContext() const { return *m_pRendererContext; } RendererBackend::EMode RendererBackend::GetMode() const { return m_nMode; } DrawHelpers &RendererBackend::GetDrawHelpers() const { return *m_pDrawHelpers; } void RendererBackend::BackupDeviceObjects() { // Is there already a backup? if (!m_ppDataBackup) { // Allocate enough backup slots m_ppDataBackup = new uint8*[m_lstResources.GetNumOfElements()]; // Backup all resource device data for (uint32 i=0; i<m_lstResources.GetNumOfElements(); i++) m_lstResources[i]->BackupDeviceData(&m_ppDataBackup[i]); // Backup all surface device data for (uint32 i=0; i<m_lstSurfaces.GetNumOfElements(); i++) m_lstSurfaces[i]->BackupDeviceData(); } } void RendererBackend::RestoreDeviceObjects() { // Is there a backup which can be restored? if (m_ppDataBackup) { // Restore all resource device data for (uint32 i=0; i<m_lstResources.GetNumOfElements(); i++) m_lstResources[i]->RestoreDeviceData(&m_ppDataBackup[i]); // Restore all surface device data for (uint32 i=0; i<m_lstSurfaces.GetNumOfElements(); i++) m_lstSurfaces[i]->RestoreDeviceData(); // Destroy backup slots delete [] m_ppDataBackup; m_ppDataBackup = nullptr; } } uint32 RendererBackend::GetNumOfDisplayModes() const { return m_lstDisplayModeList.GetNumOfElements(); } const DisplayMode *RendererBackend::GetDisplayMode(uint32 nIndex) const { return m_lstDisplayModeList[nIndex]; } const Capabilities &RendererBackend::GetCapabilities() const { return m_sCapabilities; } bool RendererBackend::IsValidTextureBuffer1DSize(int nSize) const { return (nSize <= m_sCapabilities.nMaxTextureBufferSize && nSize > 0 && (GetCapabilities().bTextureBufferNonPowerOfTwo || Math::IsPowerOfTwo(nSize))); } bool RendererBackend::IsValidTextureBuffer2DSize(int nSize) const { return (nSize <= m_sCapabilities.nMaxTextureBufferSize && nSize > 0 && (GetCapabilities().bTextureBufferNonPowerOfTwo || Math::IsPowerOfTwo(nSize))); } bool RendererBackend::IsValidTextureBufferRectangleSize(int nSize) const { return (nSize <= m_sCapabilities.nMaxRectangleTextureBufferSize && nSize > 0); } bool RendererBackend::IsValidTextureBuffer3DSize(int nSize) const { return (nSize <= m_sCapabilities.nMax3DTextureBufferSize && nSize > 0 && (GetCapabilities().bTextureBufferNonPowerOfTwo || Math::IsPowerOfTwo(nSize))); } bool RendererBackend::IsValidTextureBufferCubeSize(int nSize) const { return (nSize <= m_sCapabilities.nMaxCubeTextureBufferSize && nSize > 0 && (GetCapabilities().bTextureBufferNonPowerOfTwo || Math::IsPowerOfTwo(nSize))); } const Statistics &RendererBackend::GetStatistics() const { return m_sStatistics; } const Vector2 &RendererBackend::GetTexelToPixelOffset() const { // It looks like that most renderer APIs don't have a texel offset, so this is probably the most useful default implementation return Vector2::Zero; } void RendererBackend::Update() { // Update profiling Profiling *pProfiling = Profiling::GetInstance(); if (pProfiling->IsActive()) { const String sAPI = GetAPI(); const Statistics &sS = m_sStatistics; pProfiling->Set(sAPI, "Number of surfaces", GetNumOfSurfaces()); pProfiling->Set(sAPI, "Number of resources", GetNumOfResources()); pProfiling->Set(sAPI, "Render state changes", sS.nRenderStateChanges); pProfiling->Set(sAPI, "Sampler state changes", sS.nSamplerStateChanges); pProfiling->Set(sAPI, "Draw primitive calls", sS.nDrawPrimitivCalls); pProfiling->Set(sAPI, "Current triangles", sS.nTriangles); pProfiling->Set(sAPI, "Current vertices", sS.nVertices); pProfiling->Set(sAPI, "Rendering time", String::Format("%.3f ms", sS.fRenderingTime)); // Texture buffers pProfiling->Set(sAPI, "Number of texture buffers", sS.nTextureBuffersNum); const float fTextureBuffersMemKB = static_cast<float>(sS.nTextureBuffersMem)/1024.0f; pProfiling->Set(sAPI, "Texture buffers memory", String::Format("%g KB (%g MB)", fTextureBuffersMemKB, fTextureBuffersMemKB/1024.0f)); pProfiling->Set(sAPI, "Texture buffer binds", sS.nTextureBufferBinds); // Vertex buffers pProfiling->Set(sAPI, "Number of vertex buffers", sS.nVertexBufferNum); const float fVertexBufferMemKB = static_cast<float>(sS.nVertexBufferMem)/1024.0f; pProfiling->Set(sAPI, "Vertex buffers memory", String::Format("%g KB (%g MB)", fVertexBufferMemKB, fVertexBufferMemKB/1024.0f)); pProfiling->Set(sAPI, "Vertex buffers update time", String::Format("%.3f ms (%d locks)", sS.nVertexBuffersSetupTime/1000.0f, sS.nVertexBufferLocks)); // Index buffers pProfiling->Set(sAPI, "Number of index buffers", sS.nIndexBufferNum); const float fIndexBufferMemKB = static_cast<float>(sS.nIndexBufferMem)/1024.0f; pProfiling->Set(sAPI, "Index buffers memory", String::Format("%g KB (%g MB)", fIndexBufferMemKB, fIndexBufferMemKB/1024.0f)); pProfiling->Set(sAPI, "Index buffers update time", String::Format("%.3f ms (%d locks)", sS.nIndexBuffersSetupTime/1000.0f, sS.nIndexBufferLocks)); // Uniform buffers pProfiling->Set(sAPI, "Number of uniform buffers", sS.nUniformBufferNum); const float fUniformBufferMemKB = static_cast<float>(sS.nUniformBufferMem)/1024.0f; pProfiling->Set(sAPI, "Uniform buffers memory", String::Format("%g KB (%g MB)", fUniformBufferMemKB, fUniformBufferMemKB/1024.0f)); pProfiling->Set(sAPI, "Uniform buffers update time", String::Format("%.3f ms (%d locks)", sS.nUniformBuffersSetupTime/1000.0f, sS.nUniformBufferLocks)); } // Reset some statistics m_sStatistics.nRenderStateChanges = 0; m_sStatistics.nSamplerStateChanges = 0; m_sStatistics.nDrawPrimitivCalls = 0; m_sStatistics.nVertices = 0; m_sStatistics.nTriangles = 0; m_sStatistics.fRenderingTime = 0.0f; m_sStatistics.nTextureBufferBinds = 0; m_sStatistics.nVertexBuffersSetupTime = 0; m_sStatistics.nVertexBufferLocks = 0; m_sStatistics.nIndexBuffersSetupTime = 0; m_sStatistics.nIndexBufferLocks = 0; } void RendererBackend::Reset() { ResetRenderStates(); ResetSamplerStates(); SetTextureBuffer(); SetIndexBuffer(); SetViewport(); SetScissorRect(); SetColorMask(); SetProgram(); // Fixed functions FixedFunctions *pFixedFunctions = GetFixedFunctions(); if (pFixedFunctions) pFixedFunctions->Reset(); // Draw helpers GetDrawHelpers().End2DMode(); GetDrawHelpers().Set2DZValue(); } //[-------------------------------------------------------] //[ Surfaces ] //[-------------------------------------------------------] uint32 RendererBackend::GetNumOfSurfaces() const { return m_lstSurfaces.GetNumOfElements(); } Surface *RendererBackend::GetSurface(uint32 nIndex) const { return m_lstSurfaces[nIndex]; } bool RendererBackend::AddSurface(Surface &cSurface) { return (m_lstSurfaces.Add(&cSurface) != nullptr); } bool RendererBackend::RemoveSurface(Surface &cSurface) { // Check whether this surface is the current render target if (GetRenderTarget() == &cSurface) { // Set an alternative surface ('>1' because 0 is the internal surface) SetRenderTarget(m_lstSurfaces.GetNumOfElements() > 1 ? m_lstSurfaces[0] : nullptr); } // Remove the surface return m_lstSurfaces.Remove(&cSurface); } SurfacePainter *RendererBackend::CreateSurfacePainter(const String &sClass) { // Get class and check it const Class *pClass = ClassManager::GetInstance()->GetClass(sClass); if (pClass && pClass->IsDerivedFrom("PLRenderer::SurfacePainter")) { // Create the surface painter and return it return reinterpret_cast<SurfacePainter*>(pClass->Create(Params<Object*, Renderer&>(*this))); } else { // Error! return nullptr; } } //[-------------------------------------------------------] //[ Resources ] //[-------------------------------------------------------] uint32 RendererBackend::GetNumOfResources() const { return m_lstResources.GetNumOfElements(); } Resource *RendererBackend::GetResource(uint32 nIndex) const { return m_lstResources[nIndex]; } bool RendererBackend::AddResource(Resource &cResource) { return (m_lstResources.Add(&cResource) != nullptr); } bool RendererBackend::RemoveResource(Resource &cResource) { return m_lstResources.Remove(&cResource); } //[-------------------------------------------------------] //[ States ] //[-------------------------------------------------------] // Render states uint32 RendererBackend::GetDefaultRenderState(RenderState::Enum nState) const { return (nState < RenderState::Number) ? m_nDefaultRenderState[nState] : 0; } void RendererBackend::ResetRenderStates() { // Set renderer states to this default settings for (uint32 i=0; i<RenderState::Number; i++) SetRenderState(static_cast<RenderState::Enum>(i), m_nDefaultRenderState[i]); } int RendererBackend::GetRenderState(RenderState::Enum nState) const { // Check if the state is a valid render state member return (nState < RenderState::Number) ? m_nRenderState[nState] : -1; } // Sampler states uint32 RendererBackend::GetDefaultSamplerState(Sampler::Enum nState) const { return (nState < Sampler::Number) ? m_nDefaultSamplerState[nState] : 0; } void RendererBackend::ResetSamplerStates() { // Set sampler states to this default settings for (uint32 nStage=0; nStage<m_sCapabilities.nMaxTextureUnits; nStage++) { for (uint32 i=0; i<Sampler::Number; i++) SetSamplerState(nStage, static_cast<Sampler::Enum>(i), m_nDefaultSamplerState[i]); } } int RendererBackend::GetSamplerState(uint32 nStage, Sampler::Enum nState) const { // Check if the stage is correct and check if the state is a valid sampler member return (nStage < m_sCapabilities.nMaxTextureUnits && nState < Sampler::Number) ? m_ppnSamplerState[nStage][nState] : -1; } //[-------------------------------------------------------] //[ Misc ] //[-------------------------------------------------------] uint32 RendererBackend::GetSwapInterval() const { return m_nSwapInterval; } void RendererBackend::SetSwapInterval(uint32 nSwapInterval) { m_nSwapInterval = nSwapInterval; } const Rectangle &RendererBackend::GetViewport(float *pfMinZ, float *pfMaxZ) const { if (pfMinZ) *pfMinZ = m_fViewPortMinZ; if (pfMaxZ) *pfMaxZ = m_fViewPortMaxZ; return m_cViewportRect; } bool RendererBackend::SetViewport(const Rectangle *pRectangle, float fMinZ, float fMaxZ) { // Set data if (pRectangle) { if (pRectangle->vMin.x > 0.0f) m_cViewportRect.vMin.x = pRectangle->vMin.x; else m_cViewportRect.vMin.x = 0.0f; if (pRectangle->vMin.y > 0.0f) m_cViewportRect.vMin.y = pRectangle->vMin.y; else m_cViewportRect.vMin.y = 0.0f; Surface *pSurface = m_cCurrentSurface.GetSurface(); if (pSurface) { if (pRectangle->vMax.x > 0.0f) m_cViewportRect.vMax.x = pRectangle->vMax.x; else m_cViewportRect.vMax.x = m_cViewportRect.vMin.x+pSurface->GetSize().x; if (pRectangle->vMax.y > 0.0f) m_cViewportRect.vMax.y = pRectangle->vMax.y; else m_cViewportRect.vMax.y = m_cViewportRect.vMin.y+pSurface->GetSize().y; } else { if (pRectangle->vMax.x > 0.0f) m_cViewportRect.vMax.x = pRectangle->vMax.x; else m_cViewportRect.vMax.x = m_cViewportRect.vMin.x; if (pRectangle->vMax.y > 0.0f) m_cViewportRect.vMax.y = pRectangle->vMax.y; else m_cViewportRect.vMax.y = m_cViewportRect.vMin.y; } } else { m_cViewportRect.vMin.x = 0; m_cViewportRect.vMin.y = 0; Surface *pSurface = m_cCurrentSurface.GetSurface(); if (pSurface) { m_cViewportRect.vMax.x = static_cast<float>(pSurface->GetSize().x); m_cViewportRect.vMax.y = static_cast<float>(pSurface->GetSize().y); } else { m_cViewportRect.vMax.x = 0; m_cViewportRect.vMax.y = 0; } } m_fViewPortMinZ = fMinZ; m_fViewPortMaxZ = fMaxZ; // Done return true; } const Rectangle &RendererBackend::GetScissorRect() const { return m_cScissorRect; } bool RendererBackend::SetScissorRect(const Rectangle *pRectangle) { // Set data if (pRectangle) { if (pRectangle->vMin.x > 0.0f) m_cScissorRect.vMin.x = pRectangle->vMin.x; else m_cScissorRect.vMin.x = m_cViewportRect.vMin.x; if (pRectangle->vMin.y > 0.0f) m_cScissorRect.vMin.y = pRectangle->vMin.y; else m_cScissorRect.vMin.y = m_cViewportRect.vMin.y; if (pRectangle->vMax.x > 0.0f) m_cScissorRect.vMax.x = pRectangle->vMax.x; else m_cScissorRect.vMax.x = m_cViewportRect.vMax.x; if (pRectangle->vMax.y > 0.0f) m_cScissorRect.vMax.y = pRectangle->vMax.y; else m_cScissorRect.vMax.y = m_cViewportRect.vMax.y; } else { m_cScissorRect = m_cViewportRect; } // Done return true; } //[-------------------------------------------------------] //[ Get/set current resources ] //[-------------------------------------------------------] Surface *RendererBackend::GetRenderTarget(uint8 *pnFace) const { if (pnFace) *pnFace = m_nCurrentSurfaceFace; return m_cCurrentSurface.GetSurface(); } TextureBuffer *RendererBackend::GetColorRenderTarget(uint8 nColorIndex) const { // Check current surface if (!m_cCurrentSurface.GetSurface() || m_cCurrentSurface.GetSurface()->GetType() != Surface::TextureBuffer) return nullptr; // Error! // Return the color render target return reinterpret_cast<TextureBuffer*>(m_cCurrentSurface.GetSurface()); } TextureBuffer *RendererBackend::GetTextureBuffer(uint32 nStage) const { // Check if the stage is correct return (nStage < m_sCapabilities.nMaxTextureUnits) ? m_ppCurrentTextureBuffer[nStage] : nullptr; } IndexBuffer *RendererBackend::GetIndexBuffer() const { return m_pCurrentIndexBuffer; } Program *RendererBackend::GetProgram() const { return reinterpret_cast<Program*>(m_cProgramHandler.GetResource()); } bool RendererBackend::SetProgram(Program *pProgram) { // Not implemented return false; } //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] } // PLRenderer
37.415423
194
0.698723
[ "render", "object", "solid" ]
9c6b87582b41001e96066467c150e28741bdbcbb
7,712
cc
C++
chrome/browser/chromeos/crosapi/screen_manager_ash_browsertest.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/chromeos/crosapi/screen_manager_ash_browsertest.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/chromeos/crosapi/screen_manager_ash_browsertest.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2021-03-07T14:20:02.000Z
2021-03-07T14:20:02.000Z
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <memory> #include "ash/public/cpp/test/shell_test_api.h" #include "base/memory/scoped_refptr.h" #include "base/task/task_traits.h" #include "base/task/thread_pool.h" #include "chrome/browser/chromeos/crosapi/screen_manager_ash.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/test/base/in_process_browser_test.h" #include "chromeos/crosapi/mojom/screen_manager.mojom.h" #include "content/public/test/browser_test.h" #include "mojo/public/cpp/bindings/remote.h" #include "mojo/public/cpp/bindings/sync_call_restrictions.h" #include "ui/aura/window.h" #include "ui/display/test/display_manager_test_api.h" namespace crosapi { namespace { // This class tests that the ash-chrome implementation of the screen manager // crosapi works properly. class ScreenManagerAshBrowserTest : public InProcessBrowserTest { protected: using SMRemote = mojo::Remote<mojom::ScreenManager>; using SMPendingRemote = mojo::PendingRemote<mojom::ScreenManager>; using SMPendingReceiver = mojo::PendingReceiver<mojom::ScreenManager>; ScreenManagerAshBrowserTest() = default; ScreenManagerAshBrowserTest(const ScreenManagerAshBrowserTest&) = delete; ScreenManagerAshBrowserTest& operator=(const ScreenManagerAshBrowserTest&) = delete; ~ScreenManagerAshBrowserTest() override { background_sequence_->DeleteSoon(FROM_HERE, std::move(screen_manager_remote_)); } void SetUpOnMainThread() override { // The implementation of screen manager is affine to this sequence. screen_manager_ = std::make_unique<ScreenManagerAsh>(); SMPendingRemote pending_remote; SMPendingReceiver pending_receiver = pending_remote.InitWithNewPipeAndPassReceiver(); // Bind the implementation of ScreenManager to this sequence. screen_manager_->BindReceiver(std::move(pending_receiver)); // Bind the remote to a background sequence. This is necessary because the // screen manager API is synchronous and blocks the calling sequence. background_sequence_ = base::ThreadPool::CreateSequencedTaskRunner( {base::TaskPriority::USER_BLOCKING, base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}); // We construct the remote on this sequence for simplicity. All subsequent // invocations, including destruction, are from the background sequence. screen_manager_remote_ = std::make_unique<SMRemote>(); auto bind_background = base::BindOnce( [](SMRemote* remote, SMPendingRemote pending_remote) { remote->Bind(std::move(pending_remote)); }, screen_manager_remote_.get(), std::move(pending_remote)); background_sequence_->PostTask(FROM_HERE, std::move(bind_background)); } // Affine to main sequence. std::unique_ptr<ScreenManagerAsh> screen_manager_; // A sequence that is allowed to block. scoped_refptr<base::SequencedTaskRunner> background_sequence_; // Affine to background sequence. std::unique_ptr<SMRemote> screen_manager_remote_; }; IN_PROC_BROWSER_TEST_F(ScreenManagerAshBrowserTest, ScreenCapturer) { base::RunLoop run_loop; bool success; SkBitmap snapshot; // Take a snapshot on a background sequence. The call is blocking, so when it // finishes, we can also unblock the main thread. auto take_snapshot_background = base::BindOnce( [](SMRemote* remote, bool* success, SkBitmap* snapshot) { mojo::Remote<mojom::SnapshotCapturer> capturer; (*remote)->GetScreenCapturer(capturer.BindNewPipeAndPassReceiver()); { mojo::ScopedAllowSyncCallForTesting allow_sync; std::vector<mojom::SnapshotSourcePtr> screens; capturer->ListSources(&screens); // There should be at least one screen! ASSERT_LE(1u, screens.size()); capturer->TakeSnapshot(screens[0]->id, success, snapshot); } }, screen_manager_remote_.get(), &success, &snapshot); background_sequence_->PostTaskAndReply( FROM_HERE, std::move(take_snapshot_background), run_loop.QuitClosure()); run_loop.Run(); // Check that the IPC succeeded. ASSERT_TRUE(success); // Check that the screenshot has the right dimensions. aura::Window* primary_window = browser()->window()->GetNativeWindow()->GetRootWindow(); EXPECT_EQ(int{snapshot.width()}, primary_window->bounds().width()); EXPECT_EQ(int{snapshot.height()}, primary_window->bounds().height()); } IN_PROC_BROWSER_TEST_F(ScreenManagerAshBrowserTest, ScreenCapturer_MultipleDisplays) { base::RunLoop run_loop; bool success[2]; SkBitmap snapshot[2]; display::test::DisplayManagerTestApi(ash::ShellTestApi().display_manager()) .UpdateDisplay("400x300,100x500"); // Take a snapshot on a background sequence. The call is blocking, so when it // finishes, we can also unblock the main thread. auto take_snapshot_background = base::BindOnce( [](SMRemote* remote, bool success[2], SkBitmap snapshot[2]) { mojo::Remote<mojom::SnapshotCapturer> capturer; (*remote)->GetScreenCapturer(capturer.BindNewPipeAndPassReceiver()); { mojo::ScopedAllowSyncCallForTesting allow_sync; std::vector<mojom::SnapshotSourcePtr> screens; capturer->ListSources(&screens); // There should be exactly two screens! ASSERT_EQ(2u, screens.size()); capturer->TakeSnapshot(screens[0]->id, &success[0], &snapshot[0]); capturer->TakeSnapshot(screens[1]->id, &success[1], &snapshot[1]); } }, screen_manager_remote_.get(), success, snapshot); background_sequence_->PostTaskAndReply( FROM_HERE, std::move(take_snapshot_background), run_loop.QuitClosure()); run_loop.Run(); // Check that the IPCs succeeded. ASSERT_TRUE(success[0]); ASSERT_TRUE(success[1]); // Check that the screenshots have the right dimensions. EXPECT_EQ(400, int{snapshot[0].width()}); EXPECT_EQ(300, int{snapshot[0].height()}); EXPECT_EQ(100, int{snapshot[1].width()}); EXPECT_EQ(500, int{snapshot[1].height()}); } IN_PROC_BROWSER_TEST_F(ScreenManagerAshBrowserTest, WindowCapturer) { base::RunLoop run_loop; bool success; SkBitmap snapshot; // Take a snapshot on a background sequence. The call is blocking, so when it // finishes, we can also unblock the main thread. auto take_snapshot_background = base::BindOnce( [](SMRemote* remote, bool* success, SkBitmap* snapshot) { mojo::Remote<mojom::SnapshotCapturer> capturer; (*remote)->GetWindowCapturer(capturer.BindNewPipeAndPassReceiver()); { mojo::ScopedAllowSyncCallForTesting allow_sync; std::vector<mojom::SnapshotSourcePtr> windows; capturer->ListSources(&windows); // There should be at least one window! ASSERT_LE(1u, windows.size()); capturer->TakeSnapshot(windows[0]->id, success, snapshot); } }, screen_manager_remote_.get(), &success, &snapshot); background_sequence_->PostTaskAndReply( FROM_HERE, std::move(take_snapshot_background), run_loop.QuitClosure()); run_loop.Run(); // Check that the IPC succeeded. ASSERT_TRUE(success); // Check that the screenshot has the right dimensions. aura::Window* window = browser()->window()->GetNativeWindow(); EXPECT_EQ(int{snapshot.width()}, window->bounds().width()); EXPECT_EQ(int{snapshot.height()}, window->bounds().height()); } } // namespace } // namespace crosapi
37.436893
79
0.715897
[ "vector" ]
9c6f7960add18d3d7367a12af78d06fb5053bde0
7,105
cpp
C++
scene.cpp
xciollax/VSEL
2c1f151da0682b127732d08b22f637fb883b11ba
[ "MIT" ]
null
null
null
scene.cpp
xciollax/VSEL
2c1f151da0682b127732d08b22f637fb883b11ba
[ "MIT" ]
null
null
null
scene.cpp
xciollax/VSEL
2c1f151da0682b127732d08b22f637fb883b11ba
[ "MIT" ]
null
null
null
#include "scene.h" #include <QDir> #include <QTextStream> #include <iostream> #include <qdebug.h> #include "vsexception.h" #include <QStringBuilder> const QString Scene::VID_DATA_FILE = "video_data.txt"; const QString Scene::PREROLL_FILENAME = "preroll.jpg"; Scene::Scene() {} Scene::Scene(QString path) { qDebug("Creating scene from path %s", path.toLocal8Bit().constData()); this->scenePath = path; loadVideos(); createId(); } void Scene::loadVideos() { this->videos.clear(); QDir sceneDir(this->scenePath); if(sceneDir.exists()) { //set name this->name = sceneDir.dirName(); sceneDir.setFilter(QDir::Files | QDir::NoSymLinks); sceneDir.setSorting(QDir::Name); QFileInfoList list = sceneDir.entryInfoList(); //load videos Video * tmpVideo; for (int i = 0; i < list.size(); ++i) { QFileInfo fileInfo = list.at(i); //exclude video data file and preroll image if(fileInfo.fileName() != Scene::VID_DATA_FILE && fileInfo.fileName() != Scene::PREROLL_FILENAME) { tmpVideo = new Video(); tmpVideo->name = fileInfo.fileName(); this->videos.append(*tmpVideo); } } //load additional video data QFile file(sceneDir.filePath(Scene::VID_DATA_FILE)); //we support non existent video data files for scenes if(file.exists() && file.open(QIODevice::ReadOnly)) { QTextStream in(&file); QString line; bool found = false; while (!in.atEnd()) { found = false; line = in.readLine(); for(int i = 0; i < this->videos.size(); i++) { if(this->videos[i].fromLine(line)) { found = true; break; } } if(!found && line != "") { //we've found the id qDebug() << "old id is " << id.toString(); id = QUuid::fromString(line); qDebug() << "new id is " << id.toString(); } } file.close(); } else { qWarning("No additional video data, will use default values"); } } else { throw VSException("non existent scene directory " + this->scenePath, 9); } verify(); } void Scene::addVideo(Video v) { this->videos.append(v); createId(); } void Scene::addPrerollImage(QString imgPath) { if(imgPath != "") { QFileInfo fi(imgPath); if(!fi.exists()) { throw new VSException("non existent image file, can't add to scene", 667); } removePrerollImage(); if(!QFile::copy(imgPath, prerollImgPath())) { QFileInfo dfi(prerollImgPath()); if(!dfi.exists()) { throw VSException("can't copy image file to scene directory", 667); } } } } QString Scene::prerollImgPath() const { return scenePath % QDir::separator() % PREROLL_FILENAME; } void Scene::removePrerollImage() { QDir sceneDir(scenePath); sceneDir.remove(PREROLL_FILENAME); } bool Scene::hasPrerollImage() const { QFileInfo fi(prerollImgPath()); return fi.exists(); } void Scene::addVideoFile(QString videoPath) { if(videoPath != "") { qDebug() << "Filename:" << videoPath; QFileInfo fi(videoPath); if(!fi.exists()) { throw VSException("non existent video file, can't add to scene", 666); } //add video file to scene QString fileName = fi.fileName(); removeDuplicateVideo(fileName); QString destPath = scenePath % QDir::separator() % fileName; //copia il file nella directory della scena if(!QFile::copy(videoPath, destPath)) { //if scene doesn't contain video file already then we have a problem QFileInfo dfi(destPath); if(!dfi.exists()) { //throw exception throw VSException("can't copy video file to scene directory", 666); } } else { reload(); } createId(); } } void Scene::removeVideo(int i) { if(i >= 0 && i < videos.size()) { //remove video file QDir sceneDir(scenePath); sceneDir.remove(videos[i].name); //remove video object this->videos.removeAt(i); //sync video data saveVideoData(); //verify: maybe note duplicate removed? verify(); createId(); } } void Scene::saveVideoData() { QDir sceneDir(scenePath); if(sceneDir.exists()) { QFile file(sceneDir.filePath(Scene::VID_DATA_FILE)); if(file.exists() && file.open(QIODevice::ReadWrite)) { bool ok = file.remove(); file.close(); if(!ok) { throw VSException("can't remove", 10); } } if(file.open(QIODevice::ReadWrite)) { for(int i = 0 ; i < videos.size(); i++) { file.write(videos[i].toLine().append('\n').toLocal8Bit().constData()); } const char nl = '\n'; //write a blank line file.write(&nl); //wite id file.write(id.toByteArray()); file.close(); } else { throw VSException("can't write video files", 11); } } else { throw VSException("non existent scene dir, can't save videos", 12); qWarning() << "Non existent scene directory"; } } void Scene::reload() { loadVideos(); } void Scene::install(QString destPath) { qDebug() << "installing to " << destPath; } void Scene::verify() { //all video on non unique midi notes are not ok ok = true; for(int i = 0; i < videos.size(); i++) { videos[i].ok = true; } for(int i = 0; i < videos.size(); i++) { if(videos[i].ok) { for(int j = 0; j < videos.size(); j++) { if(i != j && videos[j].ok) { if(videos[i].midiNote == videos[j].midiNote) { videos[i].ok = false; videos[j].ok = false; ok = false; } } } } } } bool Scene::hasVideo(QString n) { bool ret = false; for(Video v: videos) { if(v.name == n) { ret = true; break; } } return ret; } void Scene::removeDuplicateVideo(QString name) { int indx = indexOf(name); if(indx != -1) { removeVideo(indx); } } int Scene::indexOf(QString name) { int ret = -1; for(int i = 0; i < videos.size(); i++) { if(videos[i].name == name) { ret = i; break; } } return ret; } void Scene::createId() { id = QUuid::createUuid(); } bool Scene::operator==(const Scene &other) const { return (name == other.name && id == other.id); }
25.930657
111
0.516397
[ "object" ]
9c7330cc4e977782890d4b9cd4b83074ddf06845
24,624
cpp
C++
test/mobile/test_upgrader_bytecode_table_example.cpp
ljhOfGithub/pytorch
c568f7b16f2a98d72ff5b7c6c6161b67b2c27514
[ "Intel" ]
2
2020-03-13T06:57:49.000Z
2020-05-17T04:18:14.000Z
test/mobile/test_upgrader_bytecode_table_example.cpp
ellhe-blaster/pytorch
e5282c3cb8bf6ad8c5161f9d0cc271edb9abed25
[ "Intel" ]
1
2019-07-23T15:23:32.000Z
2019-07-23T15:32:23.000Z
test/mobile/test_upgrader_bytecode_table_example.cpp
ellhe-blaster/pytorch
e5282c3cb8bf6ad8c5161f9d0cc271edb9abed25
[ "Intel" ]
2
2019-07-23T14:37:31.000Z
2019-07-23T14:47:13.000Z
/** * @generated * This is an auto-generated file. Please do not modify it by hand. * To re-generate, please run: * cd ~/pytorch && python torch/csrc/jit/mobile/upgrader_mobile.cpp */ #include <torch/csrc/jit/mobile/upgrader_mobile.h> #include <ATen/core/ivalue.h> #include <caffe2/serialize/versions.h> #include <torch/csrc/jit/mobile/type_parser.h> namespace c10 { TypePtr parseType(const std::string& pythonStr); } // namespace c10 namespace torch { namespace jit { // clang-format off // From operator_versions_map const std::unordered_map<std::string, std::vector<Upgrader>> getOperatorVersionMapForMobile() { static std::unordered_map<std::string, std::vector<Upgrader>> operatorVersionMapForMobile({ {std::string("aten::div.Scalar"), std::vector<Upgrader>({ Upgrader({0, 3, "div_Scalar_0_3", 0}) })}, {std::string("aten::div.Tensor"), std::vector<Upgrader>({ Upgrader({0, 3, "div_Tensor_0_3", 1}) })}, {std::string("aten::div.out"), std::vector<Upgrader>({ Upgrader({0, 3, "div_out_0_3", 4}) })}, {std::string("aten::div_.Scalar"), std::vector<Upgrader>({ Upgrader({0, 3, "div__Scalar_0_3", 2}) })}, {std::string("aten::div_.Tensor"), std::vector<Upgrader>({ Upgrader({0, 3, "div__Tensor_0_3", 3}) })}, {std::string("aten::linspace"), std::vector<Upgrader>({ Upgrader({0, 7, "linspace_0_7", 7}) })}, {std::string("aten::linspace.out"), std::vector<Upgrader>({ Upgrader({0, 7, "linspace_out_0_7", 8}) })}, }); return operatorVersionMapForMobile; } const std::vector<ByteCodeFunctionWithOperator>& getUpgraderBytecodeList() { auto generate_upgrader_bytecode_list = []() { std::vector<ByteCodeFunctionWithOperator> upgrader_function_list({ ByteCodeFunctionWithOperator({ mobile::Function::registerFunc( "div_Scalar_0_3", std::vector<Instruction>({ Instruction{OpCode::STOREN, 1, 2}, Instruction{OpCode::LOAD, 1, 0}, Instruction{OpCode::OP, 0, 0}, Instruction{OpCode::JF, 3, 0}, Instruction{OpCode::LOADC, 1, 0}, Instruction{OpCode::JMP, 3, 0}, Instruction{OpCode::LOAD, 2, 0}, Instruction{OpCode::ISINSTANCE, 0, 1}, Instruction{OpCode::STORE, 3, 0}, Instruction{OpCode::MOVE, 3, 0}, Instruction{OpCode::JF, 5, 0}, Instruction{OpCode::LOAD, 1, 0}, Instruction{OpCode::LOAD, 2, 0}, Instruction{OpCode::OP, 1, 0}, Instruction{OpCode::JMP, 6, 0}, Instruction{OpCode::LOAD, 1, 0}, Instruction{OpCode::LOAD, 2, 0}, Instruction{OpCode::OP, 2, 0}, Instruction{OpCode::LOADC, 0, 0}, Instruction{OpCode::OP, 3, 0}, Instruction{OpCode::STORE, 4, 0}, Instruction{OpCode::DROPR, 2, 0}, Instruction{OpCode::DROPR, 1, 0}, Instruction{OpCode::MOVE, 4, 0}, Instruction{OpCode::RET, 0, 0}, }), // instructions list, std::vector<c10::IValue>({ c10::IValue("trunc"), c10::IValue(true), }), // constants list, std::vector<c10::TypePtr>({ c10::parseType("float"), }), // types list, 4 ), std::vector<OperatorString>({ OperatorString({"aten::is_floating_point", "", 1}), OperatorString({"aten::div", "Scalar", 2}), OperatorString({"prim::unchecked_cast", "", 1}), OperatorString({"aten::div", "Scalar_mode", 3}), }), // operators list }), ByteCodeFunctionWithOperator({ mobile::Function::registerFunc( "div_Tensor_0_3", std::vector<Instruction>({ Instruction{OpCode::STOREN, 1, 2}, Instruction{OpCode::LOAD, 1, 0}, Instruction{OpCode::OP, 0, 0}, Instruction{OpCode::JF, 3, 0}, Instruction{OpCode::LOADC, 1, 0}, Instruction{OpCode::JMP, 3, 0}, Instruction{OpCode::LOAD, 2, 0}, Instruction{OpCode::OP, 0, 0}, Instruction{OpCode::STORE, 3, 0}, Instruction{OpCode::MOVE, 3, 0}, Instruction{OpCode::JF, 5, 0}, Instruction{OpCode::LOAD, 1, 0}, Instruction{OpCode::LOAD, 2, 0}, Instruction{OpCode::OP, 1, 0}, Instruction{OpCode::JMP, 5, 0}, Instruction{OpCode::LOAD, 1, 0}, Instruction{OpCode::LOAD, 2, 0}, Instruction{OpCode::LOADC, 0, 0}, Instruction{OpCode::OP, 2, 0}, Instruction{OpCode::STORE, 4, 0}, Instruction{OpCode::DROPR, 2, 0}, Instruction{OpCode::DROPR, 1, 0}, Instruction{OpCode::MOVE, 4, 0}, Instruction{OpCode::RET, 0, 0}, }), // instructions list, std::vector<c10::IValue>({ c10::IValue("trunc"), c10::IValue(true), }), // constants list, std::vector<c10::TypePtr>(), // types list, 4 ), std::vector<OperatorString>({ OperatorString({"aten::is_floating_point", "", 1}), OperatorString({"aten::div", "Tensor", 2}), OperatorString({"aten::div", "Tensor_mode", 3}), }), // operators list }), ByteCodeFunctionWithOperator({ mobile::Function::registerFunc( "div__Scalar_0_3", std::vector<Instruction>({ Instruction{OpCode::STOREN, 1, 2}, Instruction{OpCode::LOAD, 1, 0}, Instruction{OpCode::OP, 0, 0}, Instruction{OpCode::JF, 3, 0}, Instruction{OpCode::LOADC, 1, 0}, Instruction{OpCode::JMP, 3, 0}, Instruction{OpCode::LOAD, 2, 0}, Instruction{OpCode::ISINSTANCE, 0, 1}, Instruction{OpCode::STORE, 3, 0}, Instruction{OpCode::MOVE, 3, 0}, Instruction{OpCode::JF, 5, 0}, Instruction{OpCode::LOAD, 1, 0}, Instruction{OpCode::LOAD, 2, 0}, Instruction{OpCode::OP, 1, 0}, Instruction{OpCode::JMP, 6, 0}, Instruction{OpCode::LOAD, 1, 0}, Instruction{OpCode::LOAD, 2, 0}, Instruction{OpCode::OP, 2, 0}, Instruction{OpCode::LOADC, 0, 0}, Instruction{OpCode::OP, 3, 0}, Instruction{OpCode::STORE, 4, 0}, Instruction{OpCode::DROPR, 2, 0}, Instruction{OpCode::DROPR, 1, 0}, Instruction{OpCode::MOVE, 4, 0}, Instruction{OpCode::RET, 0, 0}, }), // instructions list, std::vector<c10::IValue>({ c10::IValue("trunc"), c10::IValue(true), }), // constants list, std::vector<c10::TypePtr>({ c10::parseType("float"), }), // types list, 4 ), std::vector<OperatorString>({ OperatorString({"aten::is_floating_point", "", 1}), OperatorString({"aten::div_", "Scalar", 2}), OperatorString({"prim::unchecked_cast", "", 1}), OperatorString({"aten::div_", "Scalar_mode", 3}), }), // operators list }), ByteCodeFunctionWithOperator({ mobile::Function::registerFunc( "div__Tensor_0_3", std::vector<Instruction>({ Instruction{OpCode::STOREN, 1, 2}, Instruction{OpCode::LOAD, 1, 0}, Instruction{OpCode::OP, 0, 0}, Instruction{OpCode::JF, 3, 0}, Instruction{OpCode::LOADC, 1, 0}, Instruction{OpCode::JMP, 3, 0}, Instruction{OpCode::LOAD, 2, 0}, Instruction{OpCode::OP, 0, 0}, Instruction{OpCode::STORE, 3, 0}, Instruction{OpCode::MOVE, 3, 0}, Instruction{OpCode::JF, 5, 0}, Instruction{OpCode::LOAD, 1, 0}, Instruction{OpCode::LOAD, 2, 0}, Instruction{OpCode::OP, 1, 0}, Instruction{OpCode::JMP, 5, 0}, Instruction{OpCode::LOAD, 1, 0}, Instruction{OpCode::LOAD, 2, 0}, Instruction{OpCode::LOADC, 0, 0}, Instruction{OpCode::OP, 2, 0}, Instruction{OpCode::STORE, 4, 0}, Instruction{OpCode::DROPR, 2, 0}, Instruction{OpCode::DROPR, 1, 0}, Instruction{OpCode::MOVE, 4, 0}, Instruction{OpCode::RET, 0, 0}, }), // instructions list, std::vector<c10::IValue>({ c10::IValue("trunc"), c10::IValue(true), }), // constants list, std::vector<c10::TypePtr>(), // types list, 4 ), std::vector<OperatorString>({ OperatorString({"aten::is_floating_point", "", 1}), OperatorString({"aten::div_", "Tensor", 2}), OperatorString({"aten::div_", "Tensor_mode", 3}), }), // operators list }), ByteCodeFunctionWithOperator({ mobile::Function::registerFunc( "div_out_0_3", std::vector<Instruction>({ Instruction{OpCode::STOREN, 1, 3}, Instruction{OpCode::LOAD, 1, 0}, Instruction{OpCode::OP, 0, 0}, Instruction{OpCode::JF, 3, 0}, Instruction{OpCode::LOADC, 1, 0}, Instruction{OpCode::JMP, 3, 0}, Instruction{OpCode::LOAD, 2, 0}, Instruction{OpCode::OP, 0, 0}, Instruction{OpCode::JF, 3, 0}, Instruction{OpCode::LOADC, 1, 0}, Instruction{OpCode::JMP, 3, 0}, Instruction{OpCode::LOAD, 3, 0}, Instruction{OpCode::OP, 0, 0}, Instruction{OpCode::STORE, 4, 0}, Instruction{OpCode::MOVE, 4, 0}, Instruction{OpCode::JF, 6, 0}, Instruction{OpCode::LOAD, 1, 0}, Instruction{OpCode::LOAD, 2, 0}, Instruction{OpCode::LOAD, 3, 0}, Instruction{OpCode::OP, 1, 0}, Instruction{OpCode::JMP, 6, 0}, Instruction{OpCode::LOAD, 1, 0}, Instruction{OpCode::LOAD, 2, 0}, Instruction{OpCode::LOADC, 0, 0}, Instruction{OpCode::LOAD, 3, 0}, Instruction{OpCode::OP, 2, 0}, Instruction{OpCode::STORE, 5, 0}, Instruction{OpCode::DROPR, 3, 0}, Instruction{OpCode::DROPR, 2, 0}, Instruction{OpCode::DROPR, 1, 0}, Instruction{OpCode::MOVE, 5, 0}, Instruction{OpCode::RET, 0, 0}, }), // instructions list, std::vector<c10::IValue>({ c10::IValue("trunc"), c10::IValue(true), }), // constants list, std::vector<c10::TypePtr>(), // types list, 5 ), std::vector<OperatorString>({ OperatorString({"aten::is_floating_point", "", 1}), OperatorString({"aten::div", "out", 3}), OperatorString({"aten::div", "out_mode", 4}), }), // operators list }), ByteCodeFunctionWithOperator({ mobile::Function::registerFunc( "linspace_0_7", std::vector<Instruction>({ Instruction{OpCode::STOREN, 1, 7}, Instruction{OpCode::LOAD, 3, 0}, Instruction{OpCode::LOADC, 0, 0}, Instruction{OpCode::OP, 0, 0}, Instruction{OpCode::JF, 10, 0}, Instruction{OpCode::LOAD, 1, 0}, Instruction{OpCode::LOAD, 2, 0}, Instruction{OpCode::LOADC, 1, 0}, Instruction{OpCode::LOAD, 4, 0}, Instruction{OpCode::LOAD, 5, 0}, Instruction{OpCode::LOAD, 6, 0}, Instruction{OpCode::LOAD, 7, 0}, Instruction{OpCode::OP, 1, 0}, Instruction{OpCode::JMP, 10, 0}, Instruction{OpCode::LOAD, 1, 0}, Instruction{OpCode::LOAD, 2, 0}, Instruction{OpCode::LOAD, 3, 0}, Instruction{OpCode::OP, 2, 0}, Instruction{OpCode::LOAD, 4, 0}, Instruction{OpCode::LOAD, 5, 0}, Instruction{OpCode::LOAD, 6, 0}, Instruction{OpCode::LOAD, 7, 0}, Instruction{OpCode::OP, 1, 0}, Instruction{OpCode::STORE, 8, 0}, Instruction{OpCode::DROPR, 7, 0}, Instruction{OpCode::DROPR, 6, 0}, Instruction{OpCode::DROPR, 5, 0}, Instruction{OpCode::DROPR, 4, 0}, Instruction{OpCode::DROPR, 2, 0}, Instruction{OpCode::DROPR, 1, 0}, Instruction{OpCode::DROPR, 3, 0}, Instruction{OpCode::MOVE, 8, 0}, Instruction{OpCode::RET, 0, 0}, }), // instructions list, std::vector<c10::IValue>({ c10::IValue(), c10::IValue(100), }), // constants list, std::vector<c10::TypePtr>(), // types list, 8 ), std::vector<OperatorString>({ OperatorString({"aten::__is__", "", 2}), OperatorString({"aten::linspace", "", 7}), OperatorString({"prim::unchecked_cast", "", 1}), }), // operators list }), ByteCodeFunctionWithOperator({ mobile::Function::registerFunc( "linspace_out_0_7", std::vector<Instruction>({ Instruction{OpCode::STOREN, 1, 4}, Instruction{OpCode::LOAD, 3, 0}, Instruction{OpCode::LOADC, 0, 0}, Instruction{OpCode::OP, 0, 0}, Instruction{OpCode::JF, 7, 0}, Instruction{OpCode::LOAD, 1, 0}, Instruction{OpCode::LOAD, 2, 0}, Instruction{OpCode::LOADC, 1, 0}, Instruction{OpCode::LOAD, 4, 0}, Instruction{OpCode::OP, 1, 0}, Instruction{OpCode::JMP, 7, 0}, Instruction{OpCode::LOAD, 1, 0}, Instruction{OpCode::LOAD, 2, 0}, Instruction{OpCode::LOAD, 3, 0}, Instruction{OpCode::OP, 2, 0}, Instruction{OpCode::LOAD, 4, 0}, Instruction{OpCode::OP, 1, 0}, Instruction{OpCode::STORE, 5, 0}, Instruction{OpCode::DROPR, 4, 0}, Instruction{OpCode::DROPR, 2, 0}, Instruction{OpCode::DROPR, 1, 0}, Instruction{OpCode::DROPR, 3, 0}, Instruction{OpCode::MOVE, 5, 0}, Instruction{OpCode::RET, 0, 0}, }), // instructions list, std::vector<c10::IValue>({ c10::IValue(), c10::IValue(100), }), // constants list, std::vector<c10::TypePtr>(), // types list, 5 ), std::vector<OperatorString>({ OperatorString({"aten::__is__", "", 2}), OperatorString({"aten::linspace", "out", 4}), OperatorString({"prim::unchecked_cast", "", 1}), }), // operators list }), }); for (const auto& upgrader_function : upgrader_function_list) { for (const auto& op : upgrader_function.operators) { upgrader_function.function.append_operator( op.name, op.overload_name, op.num_specified_args, caffe2::serialize::kMaxSupportedFileFormatVersion); } } return upgrader_function_list; }; static std::vector<ByteCodeFunctionWithOperator> upgraderBytecodeList = generate_upgrader_bytecode_list(); return upgraderBytecodeList; } // clang-format on } // namespace jit } // namespace torch
60.950495
86
0.332643
[ "vector" ]
9c734019e8979b963e4fa2a5ac7b3643bd5d9415
691
cpp
C++
Game.cpp
mattwrench/paddlistC
42586506a2fe7e176e7e47fa5c5dfdb4de1b4ecf
[ "Unlicense" ]
null
null
null
Game.cpp
mattwrench/paddlistC
42586506a2fe7e176e7e47fa5c5dfdb4de1b4ecf
[ "Unlicense" ]
null
null
null
Game.cpp
mattwrench/paddlistC
42586506a2fe7e176e7e47fa5c5dfdb4de1b4ecf
[ "Unlicense" ]
null
null
null
#include "Game.h" const int WINDOW_WIDTH = 1280; const int WINDOW_HEIGHT = 720; Game::Game() : window(sf::VideoMode(WINDOW_WIDTH, WINDOW_HEIGHT), "Paddlist"), clock(), world(WINDOW_WIDTH, WINDOW_HEIGHT), input(window), playerController(world, input), enemyController(world), ballController(world), renderer(window, world) { } void Game::run() { while (window.isOpen()) { update(); renderer.render(); } } void Game::update() { // Get dt sf::Time time = clock.restart(); float dt = time.asSeconds(); input.update(); playerController.update(dt); enemyController.update(dt); ballController.update(dt); }
17.717949
66
0.632417
[ "render" ]
9c783aab2562f53f1d985e57048af3f56963c92d
1,096
hpp
C++
src/index/api/ISeedMaskGenerator.hpp
nileshpatra/plast-library
7c962282fdb68ac1f48a587e03fbb1a1b70a7a32
[ "Intel", "DOC" ]
9
2016-09-30T05:44:35.000Z
2020-09-03T19:40:06.000Z
src/index/api/ISeedMaskGenerator.hpp
nileshpatra/plast-library
7c962282fdb68ac1f48a587e03fbb1a1b70a7a32
[ "Intel", "DOC" ]
10
2017-05-05T14:55:16.000Z
2022-01-24T18:21:51.000Z
src/index/api/ISeedMaskGenerator.hpp
nileshpatra/plast-library
7c962282fdb68ac1f48a587e03fbb1a1b70a7a32
[ "Intel", "DOC" ]
1
2020-12-05T21:33:27.000Z
2020-12-05T21:33:27.000Z
#ifndef _ISEED_MASK_GENERATOR_HPP #define _ISEED_MASK_GENERATOR_HPP #include <designpattern/api/SmartPointer.hpp> #include <misc/api/types.hpp> /********************************************************************************/ /** \brief Genomic database indexation concepts. */ namespace indexation { /********************************************************************************/ /** * \brief Interface for the generators of seed bitmasks * * Declares the operations for obtaining the result of the generation. */ class ISeedMaskGenerator : virtual public dp::ISmartPointer { public: /** * Returns the underlying bitset * * Note that if the object is destroyed, the underlying bitset will be deleted. */ virtual const u_int8_t* getBitset() = 0; /** * Returns the size in bytes of the underlying bitset */ virtual size_t getBitsetSize() = 0; /** * Compute the number of kmers that are used/present in the bitset. */ virtual u_int64_t getKmersUsedCount() = 0; }; } // indexation #endif /* ISEED_MASK_GENERATOR_HPP */
26.731707
83
0.592153
[ "object" ]
9c7f82ea5a31724177c07914a5e7eb1cf8177264
5,242
hpp
C++
src/systems/physics/wrappers/ode_physics.hpp
vi3itor/Blunted2
318af452e51174a3a4634f3fe19b314385838992
[ "Unlicense" ]
56
2020-07-22T22:11:06.000Z
2022-03-09T08:11:43.000Z
GameplayFootball/src/systems/physics/wrappers/ode_physics.hpp
ElsevierSoftwareX/SOFTX-D-20-00016
48c28adb72aa167a251636bc92111b3c43c0be67
[ "MIT" ]
9
2021-04-22T07:06:25.000Z
2022-01-22T12:54:52.000Z
GameplayFootball/src/systems/physics/wrappers/ode_physics.hpp
ElsevierSoftwareX/SOFTX-D-20-00016
48c28adb72aa167a251636bc92111b3c43c0be67
[ "MIT" ]
20
2017-11-07T16:52:32.000Z
2022-01-25T02:42:48.000Z
// written by bastiaan konings schuiling 2008 - 2014 // this work is public domain. the code is undocumented, scruffy, untested, and should generally not be used for anything important. // i do not offer support, so don't ask. to be used for inspiration :) #ifndef _HPP_PHYSICSWRAPPER_ODE #define _HPP_PHYSICSWRAPPER_ODE #include "interface_physics.hpp" #include <ode/ode.h> namespace blunted { static dJointGroupID collisionGroup; class OdePhysics : public IPhysicsWrapper { public: OdePhysics(); virtual ~OdePhysics(); // the mother of all functions virtual int StepTime(int timediff_ms, int resolution_ms); // spacetime stuff virtual int CreateWorld(); virtual void DeleteWorld(int worldID); virtual int CreateSpace(); virtual void DeleteSpace(int spaceID); virtual void SetGravity(int worldID, const Vector3 &gravity); virtual void SetErrorCorrection(int worldID, float value); virtual void SetConstraintForceMixing(int worldID, float value); // actor functions virtual IPhysicsActor *CreateActor(int worldID); virtual void DeleteActor(IPhysicsActor *actor); virtual void ActorSetMassSphere(IPhysicsActor *actor, float radius, float weight); virtual void ActorSetMassBox(IPhysicsActor *actor, const Vector3 &sides, float weight); virtual void ActorSetMassPosition(IPhysicsActor *actor, const Vector3 &pos); virtual void ActorSetPosition(IPhysicsActor *actor, const Vector3 &pos); virtual void ActorSetRotation(IPhysicsActor *actor, const Quaternion &rot); virtual Vector3 ActorGetPosition(IPhysicsActor *actor); virtual Quaternion ActorGetRotation(IPhysicsActor *actor); virtual float ActorGetVelocity(IPhysicsActor *actor); virtual Vector3 ActorGetMovement(IPhysicsActor *actor); virtual void ActorApplyForceAtRelativePosition(IPhysicsActor *actor, float force, const Vector3 &direction, const Vector3 &position); // collision functions virtual IPhysicsCollisionMesh *CreateCollisionPlane(int spaceID, const Vector3 &normal, float d); virtual IPhysicsCollisionMesh *CreateCollisionSphere(int spaceID, float radius); virtual IPhysicsCollisionMesh *CreateCollisionBox(int spaceID, const Vector3 &sides); virtual IPhysicsCollisionMesh *CreateCollisionTriMesh(int spaceID, const float *vertices, int vertexCount); virtual void DeleteCollisionMesh(IPhysicsCollisionMesh *mesh); virtual void CollisionMeshSetActor(IPhysicsCollisionMesh *mesh, IPhysicsActor *actor); virtual void CollisionMeshSetPosition(IPhysicsCollisionMesh *mesh, const Vector3 &pos); virtual void CollisionMeshSetRotation(IPhysicsCollisionMesh *mesh, const Quaternion &rot); virtual Vector3 CollisionMeshGetPosition(IPhysicsCollisionMesh *mesh); virtual Quaternion CollisionMeshGetRotation(IPhysicsCollisionMesh *mesh); virtual void CollisionMeshSetData(IPhysicsCollisionMesh *mesh, const Properties *data); // joint functions virtual IPhysicsJoint *CreateJoint(int worldID, e_JointType jointType, IPhysicsActor *actor1, IPhysicsActor *actor2, const Vector3 &anchor, const Vector3 &axis1, const Vector3 &axis2); virtual void DeleteJoint(IPhysicsJoint *joint); virtual void JointSetStops(IPhysicsJoint *joint, radian lowStop, radian highStop, int paramNum = 1); virtual void JointSetVelocity(IPhysicsJoint *joint, float velocity, int paramNum = 1); // desired velocity virtual void JointSetMaxForce(IPhysicsJoint *joint, float force, int paramNum = 1); // maximum force to reach the desired velocity virtual void JointSetConstraintForceMixing(IPhysicsJoint *joint, float value, int paramNum = 1); virtual void JointSetErrorCorrection(IPhysicsJoint *joint, float value, int paramNum = 1); virtual void JointSetSuspensionConstraintForceMixing(IPhysicsJoint *joint, float value); // only on hinge2 joints virtual void JointSetSuspensionErrorReduction(IPhysicsJoint *joint, float value); // only on hinge2 joints virtual float JointGetAngleRate(IPhysicsJoint *joint, int paramNum = 1); // utility void JointSetParameter(IPhysicsJoint *joint, int parameter, float value, int paramNum = 1); dSpaceID GetOdeSpaceID(int spaceID); dWorldID GetOdeWorldID(int worldID); protected: boost::mutex mutex; std::map <int, dWorldID> worldMap; std::map <int, dSpaceID> spaceMap; }; class OdePhysicsActor : public IPhysicsActor { public: OdePhysicsActor() {}; virtual ~OdePhysicsActor() {}; dBodyID id; protected: }; class OdePhysicsCollisionMesh : public IPhysicsCollisionMesh { public: OdePhysicsCollisionMesh() : vertices(0), indices(0) {}; virtual ~OdePhysicsCollisionMesh() { if (vertices) delete [] vertices; if (indices) delete [] indices; }; dGeomID id; real *vertices; int *indices; protected: }; class OdePhysicsJoint : public IPhysicsJoint { public: OdePhysicsJoint() {}; virtual ~OdePhysicsJoint() {}; dJointID id; e_JointType jointType; protected: }; } #endif
36.151724
190
0.732545
[ "mesh" ]
9c8488dc91a9db1e859d03335bd001f6b6636307
34,735
cpp
C++
tests/TriangulatingPathRendererTests.cpp
hixio-mh/skia
13fc260c7080d2122a7e7152c9385d914cd20be7
[ "BSD-3-Clause" ]
1
2020-09-15T06:55:34.000Z
2020-09-15T06:55:34.000Z
tests/TriangulatingPathRendererTests.cpp
hixio-mh/skia
13fc260c7080d2122a7e7152c9385d914cd20be7
[ "BSD-3-Clause" ]
3
2021-05-11T22:25:32.000Z
2022-03-02T09:53:47.000Z
tests/TriangulatingPathRendererTests.cpp
hixio-mh/skia
13fc260c7080d2122a7e7152c9385d914cd20be7
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright 2015 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "tests/Test.h" #include "include/core/SkPath.h" #include "include/effects/SkGradientShader.h" #include "include/gpu/GrDirectContext.h" #include "src/gpu/GrContextPriv.h" #include "src/gpu/GrRenderTargetContext.h" #include "src/gpu/GrStyle.h" #include "src/gpu/effects/GrPorterDuffXferProcessor.h" #include "src/gpu/geometry/GrStyledShape.h" #include "src/gpu/ops/GrTriangulatingPathRenderer.h" #include "src/shaders/SkShaderBase.h" /* * These tests pass by not crashing, hanging or asserting in Debug. */ // Tests active edges made inactive by splitting. // Also tests active edge list forced into an invalid ordering by // splitting (mopped up in cleanup_active_edges()). static SkPath create_path_0() { SkPath path; path.moveTo(229.127044677734375f, 67.34100341796875f); path.lineTo(187.8097381591796875f, -6.7729740142822265625f); path.lineTo(171.411407470703125f, 50.94266510009765625f); path.lineTo(245.5253753662109375f, 9.6253643035888671875f); path.moveTo(208.4683990478515625f, 30.284009933471679688f); path.lineTo(171.411407470703125f, 50.94266510009765625f); path.lineTo(187.8097381591796875f, -6.7729740142822265625f); return path; } // Intersections which fall exactly on the current vertex, and require // a restart of the intersection checking. static SkPath create_path_1() { SkPath path; path.moveTo(314.483551025390625f, 486.246002197265625f); path.lineTo(385.41949462890625f, 532.8087158203125f); path.lineTo(373.232879638671875f, 474.05938720703125f); path.lineTo(326.670166015625f, 544.995361328125f); path.moveTo(349.951507568359375f, 509.52734375f); path.lineTo(373.232879638671875f, 474.05938720703125f); path.lineTo(385.41949462890625f, 532.8087158203125f); return path; } // Tests active edges which are removed by splitting. static SkPath create_path_2() { SkPath path; path.moveTo(343.107391357421875f, 613.62176513671875f); path.lineTo(426.632415771484375f, 628.5740966796875f); path.lineTo(392.3460693359375f, 579.33544921875f); path.lineTo(377.39373779296875f, 662.86041259765625f); path.moveTo(384.869873046875f, 621.097900390625f); path.lineTo(392.3460693359375f, 579.33544921875f); path.lineTo(426.632415771484375f, 628.5740966796875f); return path; } // Collinear edges merged in set_top(). // Also, an intersection between left and right enclosing edges which // falls above the current vertex. static SkPath create_path_3() { SkPath path; path.moveTo(545.95751953125f, 791.69854736328125f); path.lineTo(612.05816650390625f, 738.494140625f); path.lineTo(552.4056396484375f, 732.0460205078125f); path.lineTo(605.61004638671875f, 798.14666748046875f); path.moveTo(579.00787353515625f, 765.0963134765625f); path.lineTo(552.4056396484375f, 732.0460205078125f); path.lineTo(612.05816650390625f, 738.494140625f); return path; } // Tests active edges which are made inactive by set_top(). static SkPath create_path_4() { SkPath path; path.moveTo(819.2725830078125f, 751.77447509765625f); path.lineTo(820.70904541015625f, 666.933837890625f); path.lineTo(777.57049560546875f, 708.63592529296875f); path.lineTo(862.4111328125f, 710.0723876953125f); path.moveTo(819.99078369140625f, 709.3541259765625f); path.lineTo(777.57049560546875f, 708.63592529296875f); path.lineTo(820.70904541015625f, 666.933837890625f); return path; } static SkPath create_path_5() { SkPath path; path.moveTo(823.33209228515625f, 749.052734375f); path.lineTo(823.494873046875f, 664.20013427734375f); path.lineTo(780.9871826171875f, 706.5450439453125f); path.lineTo(865.8397216796875f, 706.70782470703125f); path.moveTo(823.4134521484375f, 706.6263427734375f); path.lineTo(780.9871826171875f, 706.5450439453125f); path.lineTo(823.494873046875f, 664.20013427734375f); return path; } static SkPath create_path_6() { SkPath path; path.moveTo(954.862548828125f, 562.8349609375f); path.lineTo(899.32818603515625f, 498.679443359375f); path.lineTo(895.017578125f, 558.52435302734375f); path.lineTo(959.17315673828125f, 502.990081787109375f); path.moveTo(927.0953369140625f, 530.7572021484375f); path.lineTo(895.017578125f, 558.52435302734375f); path.lineTo(899.32818603515625f, 498.679443359375f); return path; } static SkPath create_path_7() { SkPath path; path.moveTo(958.5330810546875f, 547.35516357421875f); path.lineTo(899.93109130859375f, 485.989013671875f); path.lineTo(898.54901123046875f, 545.97308349609375f); path.lineTo(959.9151611328125f, 487.37109375f); path.moveTo(929.2320556640625f, 516.67205810546875f); path.lineTo(898.54901123046875f, 545.97308349609375f); path.lineTo(899.93109130859375f, 485.989013671875f); return path; } static SkPath create_path_8() { SkPath path; path.moveTo(389.8609619140625f, 369.326873779296875f); path.lineTo(470.6290283203125f, 395.33697509765625f); path.lineTo(443.250030517578125f, 341.9478759765625f); path.lineTo(417.239959716796875f, 422.7159423828125f); path.moveTo(430.244964599609375f, 382.3319091796875f); path.lineTo(443.250030517578125f, 341.9478759765625f); path.lineTo(470.6290283203125f, 395.33697509765625f); return path; } static SkPath create_path_9() { SkPath path; path.moveTo(20, 20); path.lineTo(50, 80); path.lineTo(20, 80); path.moveTo(80, 50); path.lineTo(50, 50); path.lineTo(20, 50); return path; } static SkPath create_path_10() { SkPath path; path.moveTo(257.19439697265625f, 320.876617431640625f); path.lineTo(190.113037109375f, 320.58978271484375f); path.lineTo(203.64404296875f, 293.8145751953125f); path.moveTo(203.357177734375f, 360.896026611328125f); path.lineTo(216.88824462890625f, 334.120819091796875f); path.lineTo(230.41925048828125f, 307.345611572265625f); return path; } // A degenerate segments case, where both upper and lower segments of // a split edge must remain active. static SkPath create_path_11() { SkPath path; path.moveTo(231.9331207275390625f, 306.2012939453125f); path.lineTo(191.4859161376953125f, 306.04547119140625f); path.lineTo(231.0659332275390625f, 300.2642822265625f); path.moveTo(189.946807861328125f, 302.072265625f); path.lineTo(179.79705810546875f, 294.859771728515625f); path.lineTo(191.0016021728515625f, 296.165679931640625f); path.moveTo(150.8942108154296875f, 304.900146484375f); path.lineTo(179.708892822265625f, 297.849029541015625f); path.lineTo(190.4742279052734375f, 299.11895751953125f); return path; } // Handle the case where edge.dist(edge.fTop) != 0.0. static SkPath create_path_12() { SkPath path; path.moveTo( 0.0f, 400.0f); path.lineTo( 138.0f, 202.0f); path.lineTo( 0.0f, 202.0f); path.moveTo( 12.62693023681640625f, 250.57464599609375f); path.lineTo( 8.13896942138671875f, 254.556884765625f); path.lineTo(-18.15641021728515625f, 220.40203857421875f); path.lineTo(-15.986493110656738281f, 219.6513519287109375f); path.moveTo( 36.931194305419921875f, 282.485504150390625f); path.lineTo( 15.617521286010742188f, 261.2901611328125f); path.lineTo( 10.3829498291015625f, 252.565765380859375f); path.lineTo(-16.165292739868164062f, 222.646026611328125f); return path; } // A degenerate segments case which exercises inactive edges being // made active by splitting. static SkPath create_path_13() { SkPath path; path.moveTo(690.62127685546875f, 509.25555419921875f); path.lineTo(99.336181640625f, 511.71405029296875f); path.lineTo(708.362548828125f, 512.4349365234375f); path.lineTo(729.9940185546875f, 516.3114013671875f); path.lineTo(738.708984375f, 518.76995849609375f); path.lineTo(678.3463134765625f, 510.0819091796875f); path.lineTo(681.21795654296875f, 504.81378173828125f); path.moveTo(758.52764892578125f, 521.55963134765625f); path.lineTo(719.1549072265625f, 514.50372314453125f); path.lineTo(689.59063720703125f, 512.0628662109375f); path.lineTo(679.78216552734375f, 507.447845458984375f); return path; } // Tests vertices which become "orphaned" (ie., no connected edges) // after simplification. static SkPath create_path_14() { SkPath path; path.moveTo(217.326019287109375f, 166.4752960205078125f); path.lineTo(226.279266357421875f, 170.929473876953125f); path.lineTo(234.3973388671875f, 177.0623626708984375f); path.lineTo(262.0921630859375f, 188.746124267578125f); path.moveTo(196.23638916015625f, 174.0722198486328125f); path.lineTo(416.15277099609375f, 180.138214111328125f); path.lineTo(192.651947021484375f, 304.0228271484375f); return path; } static SkPath create_path_15() { SkPath path; path.moveTo( 0.0f, 0.0f); path.lineTo(10000.0f, 0.0f); path.lineTo( 0.0f, -1.0f); path.lineTo(10000.0f, 0.000001f); path.lineTo( 0.0f, -30.0f); return path; } // Reduction of Nebraska-StateSeal.svg. Floating point error causes the // same edge to be added to more than one poly on the same side. static SkPath create_path_16() { SkPath path; path.moveTo(170.8199920654296875, 491.86700439453125); path.lineTo(173.7649993896484375, 489.7340087890625); path.lineTo(174.1450958251953125, 498.545989990234375); path.lineTo( 171.998992919921875, 500.88201904296875); path.moveTo(168.2922515869140625, 498.66265869140625); path.lineTo(169.8589935302734375, 497.94500732421875); path.lineTo( 172, 500.88299560546875); path.moveTo( 169.555267333984375, 490.70111083984375); path.lineTo(173.7649993896484375, 489.7340087890625); path.lineTo( 170.82000732421875, 491.86700439453125); return path; } // A simple concave path. Test this with a non-invertible matrix. static SkPath create_path_17() { SkPath path; path.moveTo(20, 20); path.lineTo(80, 20); path.lineTo(30, 30); path.lineTo(20, 80); return path; } // A shape with a vertex collinear to the right hand edge. // This messes up find_enclosing_edges. static SkPath create_path_18() { SkPath path; path.moveTo(80, 20); path.lineTo(80, 60); path.lineTo(20, 60); path.moveTo(80, 50); path.lineTo(80, 80); path.lineTo(20, 80); return path; } // Exercises the case where an edge becomes collinear with *two* of its // adjacent neighbour edges after splitting. // This is a reduction from // http://mooooo.ooo/chebyshev-sine-approximation/horner_ulp.svg static SkPath create_path_19() { SkPath path; path.moveTo( 351.99298095703125, 348.23046875); path.lineTo( 351.91876220703125, 347.33984375); path.lineTo( 351.91876220703125, 346.1953125); path.lineTo( 351.90313720703125, 347.734375); path.lineTo( 351.90313720703125, 346.1328125); path.lineTo( 351.87579345703125, 347.93359375); path.lineTo( 351.87579345703125, 345.484375); path.lineTo( 351.86407470703125, 347.7890625); path.lineTo( 351.86407470703125, 346.2109375); path.lineTo( 351.84844970703125, 347.63763427734375); path.lineTo( 351.84454345703125, 344.19232177734375); path.lineTo( 351.78204345703125, 346.9483642578125); path.lineTo( 351.758636474609375, 347.18310546875); path.lineTo( 351.75469970703125, 346.75); path.lineTo( 351.75469970703125, 345.46875); path.lineTo( 352.5546875, 345.46875); path.lineTo( 352.55078125, 347.01953125); path.lineTo( 351.75079345703125, 347.02313232421875); path.lineTo( 351.74688720703125, 346.15203857421875); path.lineTo( 351.74688720703125, 347.646148681640625); path.lineTo( 352.5390625, 346.94140625); path.lineTo( 351.73907470703125, 346.94268798828125); path.lineTo( 351.73516845703125, 344.48565673828125); path.lineTo( 352.484375, 346.73828125); path.lineTo( 351.68438720703125, 346.7401123046875); path.lineTo( 352.4765625, 346.546875); path.lineTo( 351.67657470703125, 346.54937744140625); path.lineTo( 352.47265625, 346.75390625); path.lineTo( 351.67266845703125, 346.756622314453125); path.lineTo( 351.66876220703125, 345.612091064453125); return path; } // An intersection above the first vertex in the mesh. // Reduction from http://crbug.com/730687 static SkPath create_path_20() { SkPath path; path.moveTo( 2822128.5, 235.026336669921875); path.lineTo( 2819349.25, 235.3623504638671875); path.lineTo( -340558688, 23.83478546142578125); path.lineTo( -340558752, 25.510419845581054688); path.lineTo( -340558720, 27.18605804443359375); return path; } // An intersection whose result is NaN (due to rounded-to-inf endpoint). static SkPath create_path_21() { SkPath path; path.moveTo(1.7889142061167663539e+38, 39338463358011572224.0); path.lineTo( 1647.4193115234375, -522.603515625); path.lineTo( 1677.74560546875, -529.0028076171875); path.lineTo( 1678.29541015625, -528.7847900390625); path.lineTo( 1637.5167236328125, -519.79266357421875); path.lineTo( 1647.4193115234375, -522.603515625); return path; } // A path which contains out-of-range colinear intersections. static SkPath create_path_23() { SkPath path; path.moveTo( 0, 63.39080047607421875); path.lineTo(-0.70804601907730102539, 63.14350128173828125); path.lineTo(-7.8608899287380243391e-17, 64.14080047607421875); path.moveTo( 0, 64.14080047607421875); path.lineTo(44.285900115966796875, 64.14080047607421875); path.lineTo( 0, 62.64080047607421875); path.moveTo(21.434900283813476562, -0.24732701480388641357); path.lineTo(-0.70804601907730102539, 63.14350128173828125); path.lineTo(0.70804601907730102539, 63.6381988525390625); return path; } // A path which results in infs and nans when conics are converted to quads. static SkPath create_path_24() { SkPath path; path.moveTo(-2.20883e+37f, -1.02892e+37f); path.conicTo(-2.00958e+38f, -9.36107e+37f, -1.7887e+38f, -8.33215e+37f, 0.707107f); path.conicTo(-1.56782e+38f, -7.30323e+37f, 2.20883e+37f, 1.02892e+37f, 0.707107f); path.conicTo(2.00958e+38f, 9.36107e+37f, 1.7887e+38f, 8.33215e+37f, 0.707107f); path.conicTo(1.56782e+38f, 7.30323e+37f, -2.20883e+37f, -1.02892e+37f, 0.707107f); return path; } // An edge collapse event which also collapses a neighbour, requiring // its event to be removed. static SkPath create_path_25() { SkPath path; path.moveTo( 43.44110107421875, 148.15106201171875); path.lineTo( 44.64471435546875, 148.16748046875); path.lineTo( 46.35009765625, 147.403076171875); path.lineTo( 46.45404052734375, 148.34906005859375); path.lineTo( 45.0400390625, 148.54205322265625); path.lineTo( 44.624053955078125, 148.9810791015625); path.lineTo( 44.59405517578125, 149.16107177734375); path.lineTo( 44.877044677734375, 149.62005615234375); path.lineTo(144.373016357421875, 68.8070068359375); return path; } // An edge collapse event causes an edge to become collinear, requiring // its event to be removed. static SkPath create_path_26() { SkPath path; path.moveTo( 43.44110107421875, 148.15106201171875); path.lineTo( 44.64471435546875, 148.16748046875); path.lineTo( 46.35009765625, 147.403076171875); path.lineTo( 46.45404052734375, 148.34906005859375); path.lineTo( 45.0400390625, 148.54205322265625); path.lineTo( 44.624053955078125, 148.9810791015625); path.lineTo( 44.59405517578125, 149.16107177734375); path.lineTo( 44.877044677734375, 149.62005615234375); path.lineTo(144.373016357421875, 68.8070068359375); return path; } // A path which results in non-finite points when stroked and bevelled for AA. static SkPath create_path_27() { SkPath path; path.moveTo(8.5027233009104409507e+37, 1.7503381025241130639e+37); path.lineTo(7.0923661737711584874e+37, 1.4600074517285415699e+37); path.lineTo(7.0848733446033294691e+37, 1.4584649744781838604e+37); path.lineTo(-2.0473916115129349496e+37, -4.2146796450364162012e+36); path.lineTo(2.0473912312177548811e+37, 4.2146815465123165435e+36); return path; } // AA stroking this path produces intersection failures on bevelling. // This should skip the point, but not assert. static SkPath create_path_28() { SkPath path; path.moveTo(-7.5952312625177475154e+21, -2.6819185100266674911e+24); path.lineTo( 1260.3787841796875, 1727.7947998046875); path.lineTo( 1260.5567626953125, 1728.0386962890625); path.lineTo(1.1482511310557754163e+21, 4.054538502765980051e+23); path.lineTo(-7.5952312625177475154e+21, -2.6819185100266674911e+24); return path; } // A quad which generates a huge number of points (>2B) when uniformly // linearized. This should not hang or OOM. static SkPath create_path_29() { SkPath path; path.moveTo(10, 0); path.lineTo(0, 0); path.quadTo(10, 0, 0, 8315084722602508288); return path; } // A path which hangs during simplification. It produces an edge which is // to the left of its own endpoints, which causes an infinte loop in the // right-enclosing-edge splitting. static SkPath create_path_30() { SkPath path; path.moveTo(0.75001740455627441406, 23.051967620849609375); path.lineTo(5.8471612930297851562, 22.731662750244140625); path.lineTo(10.749670028686523438, 22.253145217895507812); path.lineTo(13.115868568420410156, 22.180681228637695312); path.lineTo(15.418928146362304688, 22.340015411376953125); path.lineTo( 17.654022216796875, 22.82159423828125); path.lineTo(19.81632232666015625, 23.715869903564453125); path.lineTo(40, 0); path.lineTo(5.5635203441547955577e-15, 0); path.lineTo(5.5635203441547955577e-15, 47); path.lineTo(-1.4210854715202003717e-14, 21.713298797607421875); path.lineTo(0.75001740455627441406, 21.694292068481445312); path.lineTo(0.75001740455627441406, 23.051967620849609375); return path; } // A path with vertices which become infinite on AA stroking. Should not crash or assert. static SkPath create_path_31() { SkPath path; path.moveTo(2.0257809259190991347e+36, -1244080640); path.conicTo(2.0257809259190991347e+36, -1244080640, 2.0257809259190991347e+36, 0.10976474732160568237, 0.70710676908493041992); path.lineTo(-10036566016, -1954718402215936); path.conicTo(-1.1375507718551896064e+20, -1954721086570496, 10036566016, -1954721086570496, 0.70710676908493041992); return path; } // Reduction from skbug.com/7911 that causes a crash due to splitting a // zombie edge. static SkPath create_path_32() { SkPath path; path.moveTo( 0, 1.0927740941146660348e+24); path.lineTo(2.9333931225865729333e+32, 16476101); path.lineTo(1.0927731573659435417e+24, 1.0927740941146660348e+24); path.lineTo(1.0927740941146660348e+24, 3.7616281094287041715e-37); path.lineTo(1.0927740941146660348e+24, 1.0927740941146660348e+24); path.lineTo(1.3061803026169399536e-33, 1.0927740941146660348e+24); path.lineTo(4.7195362919941370727e-16, -8.4247545146051822591e+32); return path; } // From crbug.com/844873. Crashes trying to merge a zombie edge. static SkPath create_path_33() { SkPath path; path.moveTo( 316.000579833984375, -4338355948977389568); path.lineTo(1.5069369808623501312e+20, 75180972320904708096.0); path.lineTo(1.5069369808623501312e+20, 75180972320904708096.0); path.lineTo( 771.21014404296875, -4338355948977389568.0); path.lineTo( 316.000579833984375, -4338355948977389568.0); path.moveTo( 354.208984375, -4338355948977389568.0); path.lineTo( 773.00177001953125, -4338355948977389568.0); path.lineTo(1.5069369808623501312e+20, 75180972320904708096.0); path.lineTo(1.5069369808623501312e+20, 75180972320904708096.0); path.lineTo( 354.208984375, -4338355948977389568.0); return path; } // From crbug.com/844873. Hangs repeatedly splitting alternate vertices. static SkPath create_path_34() { SkPath path; path.moveTo(10, -1e+20f); path.lineTo(11, 25000); path.lineTo(10, 25000); path.lineTo(11, 25010); return path; } // Reduction from circular_arcs_stroke_and_fill_round GM which // repeatedly splits on the opposite edge from case 34 above. static SkPath create_path_35() { SkPath path; path.moveTo( 16.25, 26.495191574096679688); path.lineTo(32.420825958251953125, 37.377376556396484375); path.lineTo(25.176382064819335938, 39.31851959228515625); path.moveTo( 20, 20); path.lineTo(28.847436904907226562, 37.940830230712890625); path.lineTo(25.17638397216796875, 39.31851959228515625); return path; } // Reduction from crbug.com/843135 where an intersection is found // below the bottom of both intersected edges. static SkPath create_path_36() { SkPath path; path.moveTo(-2791476679359332352, 2608107002026524672); path.lineTo( 0, 11.95427703857421875); path.lineTo(-2781824066779086848, 2599088532777598976); path.lineTo( -7772.6875, 7274); return path; } // Reduction from crbug.com/843135. Exercises a case where an intersection is missed. // This causes bad ordering in the active edge list. static SkPath create_path_37() { SkPath path; path.moveTo(-1.0662557646016024569e+23, 9.9621425197286319718e+22); path.lineTo( -121806400, 113805032); path.lineTo( -120098872, 112209680); path.lineTo( 6.2832999862817380468e-36, 2.9885697364807128906); return path; } // Reduction from crbug.com/851914. static SkPath create_path_38() { SkPath path; path.moveTo(14.400531768798828125, 17.711114883422851562); path.lineTo(14.621990203857421875, 171563104293879808); path.lineTo(14.027951240539550781, 872585759381520384); path.lineTo( 14.0216827392578125, 872665817571917824); path.lineTo(7.699314117431640625, -3417320793833472); path.moveTo(11.606547355651855469, 17.40966796875); path.lineTo( 7642114886926860288, 21.08358001708984375); path.lineTo(11.606547355651855469, 21.08358001708984375); return path; } // Reduction from crbug.com/851409. Exercises collinear last vertex. static SkPath create_path_39() { SkPath path; path.moveTo(2072553216, 0); path.lineTo(2072553216, 1); path.lineTo(2072553472, -13.5); path.lineTo(2072553216, 0); path.lineTo(2072553472, -6.5); return path; } // Another reduction from crbug.com/851409. Exercises two sequential collinear edges. static SkPath create_path_40() { SkPath path; path.moveTo(2072553216, 0); path.lineTo(2072553216, 1); path.lineTo(2072553472, -13); path.lineTo(2072553216, 0); path.lineTo(2072553472, -6); path.lineTo(2072553472, -13); return path; } // Reduction from crbug.com/860453. Tests a case where a "missing" intersection // requires the active edge list to go out-of-order. static SkPath create_path_41() { SkPath path; path.moveTo(72154931603311689728.0, 330.95965576171875); path.lineTo(24053266013925408768.0, 78.11376953125); path.lineTo(1.2031099003292404941e+20, 387.168731689453125); path.lineTo(68859835992355373056.0, 346.55047607421875); path.lineTo(76451708695451009024.0, 337.780029296875); path.moveTo(-20815817797613387776.0, 18065700622522384384.0); path.lineTo(-72144121204987396096.0, 142.855804443359375); path.lineTo(72144121204987396096.0, 325.184783935546875); path.lineTo(1.2347242901040791552e+20, 18065700622522384384.0); return path; } // Reduction from crbug.com/860655. Cause is three collinear edges discovered during // sanitize_contours pass, before the vertices have been found coincident. static SkPath create_path_42() { SkPath path; path.moveTo( 32572426382475264, -3053391034974208); path.lineTo( 521289856, -48865776); path.lineTo( 130322464, -12215873); path.moveTo( 32572426382475264, -3053391034974208); path.lineTo( 521289856, -48865776); path.lineTo( 130322464, -12215873); path.moveTo( 32572426382475264, -3053391034974208); path.lineTo( 32114477642022912, -3010462031544320); path.lineTo( 32111784697528320, -3010209702215680); return path; } // Reduction from crbug.com/866319. Cause is edges that are collinear when tested from // one side, but non-collinear when tested from the other. static SkPath create_path_43() { SkPath path; path.moveTo( 307316821852160, -28808363114496); path.lineTo( 307165222928384, -28794154909696); path.lineTo( 307013691113472, -28779948802048); path.lineTo( 306862159298560, -28765744791552); path.lineTo( 306870313025536, -28766508154880); path.lineTo( 307049695019008, -28783327313920); path.lineTo( 307408660332544, -28816974020608); return path; } // Reduction from crbug.com/966696 static SkPath create_path_44() { SkPath path; path.moveTo(114.4606170654296875, 186.443878173828125); path.lineTo( 91.5394744873046875, 185.4189453125); path.lineTo(306.45538330078125, 3203.986083984375); path.moveTo(16276206965409972224.0, 815.59393310546875); path.lineTo(-3.541605062372533207e+20, 487.7236328125); path.lineTo(-3.541605062372533207e+20, 168.204071044921875); path.lineTo(16276206965409972224.0, 496.07427978515625); path.moveTo(-3.541605062372533207e+20, 167.00958251953125); path.lineTo(-3.541605062372533207e+20, 488.32086181640625); path.lineTo(16276206965409972224.0, 816.78839111328125); path.lineTo(16276206965409972224.0, 495.47705078125); return path; } // Reduction from crbug.com/966274. static SkPath create_path_45() { SkPath path; path.moveTo( 706471854080, 379003666432); path.lineTo( 706503180288, 379020443648); path.lineTo( 706595717120, 379070087168); path.lineTo( 706626060288, 379086372864); path.lineTo( 706656141312, 379102527488); path.lineTo( 706774171648, 379165835264); path.lineTo( 706803073024, 379181334528); path.lineTo( 706831712256, 379196702720); path.lineTo( 706860154880, 379211939840); path.lineTo( 706888335360, 379227078656); path.lineTo( 706916253696, 379242053632); path.lineTo( 706956820480, 379263811584); path.lineTo( 706929098752, 379248934912); path.lineTo( 706901114880, 379233927168); path.lineTo( 706872934400, 379218821120); path.lineTo( 706844491776, 379203551232); path.lineTo( 706815787008, 379188183040); path.lineTo( 706786885632, 379172651008); path.lineTo( 706757722112, 379156987904); path.lineTo( 706728296448, 379141226496); path.lineTo( 706698608640, 379125301248); path.lineTo( 706668724224, 379109244928); path.lineTo( 706638577664, 379093090304); path.lineTo( 706608168960, 379076771840); path.lineTo( 706484174848, 379010252800); return path; } // Reduction from crbug.com/969359. Inf generated by intersections // causes NaN in subsequent intersections, leading to assert or hang. static SkPath create_path_46() { SkPath path; path.moveTo(1.0321827899075254821e+37, -5.1199920965387697886e+37); path.lineTo(-1.0321827899075254821e+37, 5.1199920965387697886e+37); path.lineTo(-1.0425214946728668754e+37, 4.5731834042267216669e+37); path.moveTo(-9.5077331762291841872e+36, 8.1304868292377430302e+37); path.lineTo(9.5077331762291841872e+36, -8.1304868292377430302e+37); path.lineTo(1.0795449417808426232e+37, 1.2246856113744539311e+37); path.moveTo(-165.8018341064453125, -44.859375); path.lineTo(-9.558702871563160835e+36, -7.9814405281448285475e+37); path.lineTo(-9.4147814283168490381e+36, -8.3935116522790983488e+37); return path; } static std::unique_ptr<GrFragmentProcessor> create_linear_gradient_processor( GrRecordingContext* rContext) { SkPoint pts[2] = { {0, 0}, {1, 1} }; SkColor colors[2] = { SK_ColorGREEN, SK_ColorBLUE }; sk_sp<SkShader> shader = SkGradientShader::MakeLinear( pts, colors, nullptr, SK_ARRAY_COUNT(colors), SkTileMode::kClamp); GrColorInfo colorInfo(GrColorType::kRGBA_8888, kPremul_SkAlphaType, nullptr); SkSimpleMatrixProvider matrixProvider(SkMatrix::I()); GrFPArgs args(rContext, matrixProvider, SkFilterQuality::kLow_SkFilterQuality, &colorInfo); return as_SB(shader)->asFragmentProcessor(args); } static void test_path(GrRecordingContext* rContext, GrRenderTargetContext* renderTargetContext, const SkPath& path, const SkMatrix& matrix = SkMatrix::I(), GrAAType aaType = GrAAType::kNone, std::unique_ptr<GrFragmentProcessor> fp = nullptr) { GrTriangulatingPathRenderer pr; pr.setMaxVerbCount(100); GrPaint paint; paint.setXPFactory(GrPorterDuffXPFactory::Get(SkBlendMode::kSrc)); if (fp) { paint.setColorFragmentProcessor(std::move(fp)); } SkIRect clipConservativeBounds = SkIRect::MakeWH(renderTargetContext->width(), renderTargetContext->height()); GrStyle style(SkStrokeRec::kFill_InitStyle); GrStyledShape shape(path, style); GrPathRenderer::DrawPathArgs args{rContext, std::move(paint), &GrUserStencilSettings::kUnused, renderTargetContext, nullptr, &clipConservativeBounds, &matrix, &shape, aaType, false}; pr.drawPath(args); } DEF_GPUTEST_FOR_ALL_CONTEXTS(TriangulatingPathRendererTests, reporter, ctxInfo) { auto ctx = ctxInfo.directContext(); auto rtc = GrRenderTargetContext::Make( ctx, GrColorType::kRGBA_8888, nullptr, SkBackingFit::kApprox, {800, 800}, 1, GrMipmapped::kNo, GrProtected::kNo, kTopLeft_GrSurfaceOrigin); if (!rtc) { return; } ctx->flushAndSubmit(); // Adding discard to appease vulkan validation warning about loading uninitialized data on draw rtc->discard(); test_path(ctx, rtc.get(), create_path_0()); test_path(ctx, rtc.get(), create_path_1()); test_path(ctx, rtc.get(), create_path_2()); test_path(ctx, rtc.get(), create_path_3()); test_path(ctx, rtc.get(), create_path_4()); test_path(ctx, rtc.get(), create_path_5()); test_path(ctx, rtc.get(), create_path_6()); test_path(ctx, rtc.get(), create_path_7()); test_path(ctx, rtc.get(), create_path_8()); test_path(ctx, rtc.get(), create_path_9()); test_path(ctx, rtc.get(), create_path_10()); test_path(ctx, rtc.get(), create_path_11()); test_path(ctx, rtc.get(), create_path_12()); test_path(ctx, rtc.get(), create_path_13()); test_path(ctx, rtc.get(), create_path_14()); test_path(ctx, rtc.get(), create_path_15()); test_path(ctx, rtc.get(), create_path_16()); SkMatrix nonInvertibleMatrix = SkMatrix::Scale(0, 0); std::unique_ptr<GrFragmentProcessor> fp(create_linear_gradient_processor(ctx)); test_path(ctx, rtc.get(), create_path_17(), nonInvertibleMatrix, GrAAType::kCoverage, std::move(fp)); test_path(ctx, rtc.get(), create_path_18()); test_path(ctx, rtc.get(), create_path_19()); test_path(ctx, rtc.get(), create_path_20(), SkMatrix(), GrAAType::kCoverage); test_path(ctx, rtc.get(), create_path_21(), SkMatrix(), GrAAType::kCoverage); test_path(ctx, rtc.get(), create_path_23()); test_path(ctx, rtc.get(), create_path_24()); test_path(ctx, rtc.get(), create_path_25(), SkMatrix(), GrAAType::kCoverage); test_path(ctx, rtc.get(), create_path_26(), SkMatrix(), GrAAType::kCoverage); test_path(ctx, rtc.get(), create_path_27(), SkMatrix(), GrAAType::kCoverage); test_path(ctx, rtc.get(), create_path_28(), SkMatrix(), GrAAType::kCoverage); test_path(ctx, rtc.get(), create_path_29()); test_path(ctx, rtc.get(), create_path_30()); test_path(ctx, rtc.get(), create_path_31(), SkMatrix(), GrAAType::kCoverage); test_path(ctx, rtc.get(), create_path_32()); test_path(ctx, rtc.get(), create_path_33()); test_path(ctx, rtc.get(), create_path_34()); test_path(ctx, rtc.get(), create_path_35()); test_path(ctx, rtc.get(), create_path_36()); test_path(ctx, rtc.get(), create_path_37()); test_path(ctx, rtc.get(), create_path_38(), SkMatrix(), GrAAType::kCoverage); test_path(ctx, rtc.get(), create_path_39()); test_path(ctx, rtc.get(), create_path_40()); test_path(ctx, rtc.get(), create_path_41(), SkMatrix(), GrAAType::kCoverage); test_path(ctx, rtc.get(), create_path_42()); test_path(ctx, rtc.get(), create_path_43(), SkMatrix(), GrAAType::kCoverage); test_path(ctx, rtc.get(), create_path_44(), SkMatrix(), GrAAType::kCoverage); test_path(ctx, rtc.get(), create_path_45(), SkMatrix(), GrAAType::kCoverage); test_path(ctx, rtc.get(), create_path_46(), SkMatrix(), GrAAType::kCoverage); }
43.527569
99
0.693191
[ "mesh", "geometry", "shape" ]
9c895e4907da00a8721699cc5f379a37b1780bc5
4,422
cpp
C++
QtDash/VolvoDigitalDashModels/tests/ntc_test.cpp
whitfijs-jw/DigitalDash
45ec6fcc9dc71af2dfe3e5dc7623d6d664598746
[ "MIT" ]
7
2022-01-01T23:42:50.000Z
2022-02-04T15:25:45.000Z
QtDash/VolvoDigitalDashModels/tests/ntc_test.cpp
whitfijs-jw/DigitalDash
45ec6fcc9dc71af2dfe3e5dc7623d6d664598746
[ "MIT" ]
2
2022-01-14T21:22:11.000Z
2022-01-15T21:59:24.000Z
QtDash/VolvoDigitalDashModels/tests/ntc_test.cpp
whitfijs-jw/DigitalDash
45ec6fcc9dc71af2dfe3e5dc7623d6d664598746
[ "MIT" ]
3
2021-08-08T21:15:43.000Z
2022-02-06T22:20:15.000Z
#include "ntc_test.h" #include <ntc.h> #include <compare_float.h> void NtcTest::testNtcConstructor() { QFETCH(qreal, t1); QFETCH(qreal, t2); QFETCH(qreal, t3); QFETCH(qreal, r1); QFETCH(qreal, r2); QFETCH(qreal, r3); QFETCH(int, units); QFETCH(int, type); QFETCH(qreal, A); QFETCH(qreal, B); QFETCH(qreal, C); // Assemble the config structure Config::TempSensorConfig config; config.r1 = r1; config.r2 = r2; config.r3 = r3; config.t1 = t1; config.t2 = t2; config.t3 = t3; config.rBalance = rBalance; config.vSupply = vSupply; config.type = static_cast<Config::TemperatureSensorType>(type); config.units = static_cast<Config::TemperatureUnits>(units); // make new object Ntc * testSensor = new Ntc(config); COMPARE_F(testSensor->getCoefficients().A, A, COEFF_DELTA); COMPARE_F(testSensor->getCoefficients().B, B, COEFF_DELTA); COMPARE_F(testSensor->getCoefficients().C, C, COEFF_DELTA); delete testSensor; } void NtcTest::testNtcConstructor_data() { QTest::addColumn<qreal>("t1"); QTest::addColumn<qreal>("r1"); QTest::addColumn<qreal>("t2"); QTest::addColumn<qreal>("r2"); QTest::addColumn<qreal>("t3"); QTest::addColumn<qreal>("r3"); QTest::addColumn<int>("units"); QTest::addColumn<int>("type"); /* coefficients were generated independently using : * https://www.thinksrs.com/downloads/programs/therm%20calc/ntccalibrator/ntccalculator.html **/ QTest::addColumn<qreal>("A"); QTest::addColumn<qreal>("B"); QTest::addColumn<qreal>("C"); // make up some NTCs QTest::newRow("2C-30k|25C-10k|100C-300R") << 2.0 << 30000.0 << 25.0 << 10000.0 << 100.0 << 300.0 << static_cast<int>(Config::TemperatureUnits::CELSIUS) << static_cast<int>(Config::TemperatureSensorType::COOLANT) << 2.007961057e-3 << 1.001723351e-4 << 5.419494308e-7; QTest::newRow("1C-29.5k|25C-10k|37C-6.2k") << 1.0 << 29500.0 << 25.0 << 10000.0 << 37.0 << 6200.0 << static_cast<int>(Config::TemperatureUnits::CELSIUS) << static_cast<int>(Config::TemperatureSensorType::COOLANT) << 0.8521912125e-3 << 2.717226313e-4 << -0.01065764181e-7; QTest::newRow("0C-9.6k|37C-1.6k|100C-185R") << 0.0 << 9600.0 << 37.0 << 1600.0 << 100.0 << 185.0 << static_cast<int>(Config::TemperatureUnits::CELSIUS) << static_cast<int>(Config::TemperatureSensorType::COOLANT) << 1.314314314e-3 << 2.643027107e-4 << -0.9968011359e-7; } void NtcTest::testCalculateTemperature() { QFETCH(qreal, t1); QFETCH(qreal, t2); QFETCH(qreal, t3); QFETCH(qreal, r1); QFETCH(qreal, r2); QFETCH(qreal, r3); QFETCH(int, units); QFETCH(int, type); QFETCH(qreal, test_temp_C); QFETCH(qreal, test_input); // Assemble the config structure Config::TempSensorConfig config; config.r1 = r1; config.r2 = r2; config.r3 = r3; config.t1 = t1; config.t2 = t2; config.t3 = t3; config.rBalance = NtcTest::rBalance; config.vSupply = NtcTest::vSupply; config.type = static_cast<Config::TemperatureSensorType>(type); config.units = static_cast<Config::TemperatureUnits>(units); // make new object Ntc * testSensor = new Ntc(config); COMPARE_F(testSensor->calculateTemp(test_input, Config::TemperatureUnits::CELSIUS), test_temp_C, TEMP_DELTA); delete testSensor; } void NtcTest::testCalculateTemperature_data() { QTest::addColumn<qreal>("t1"); QTest::addColumn<qreal>("r1"); QTest::addColumn<qreal>("t2"); QTest::addColumn<qreal>("r2"); QTest::addColumn<qreal>("t3"); QTest::addColumn<qreal>("r3"); QTest::addColumn<int>("units"); QTest::addColumn<int>("type"); QTest::addColumn<qreal>("test_temp_C"); QTest::addColumn<qreal>("test_input"); // make up some NTCs QTest::newRow("2C-30k|25C-10k|100C-300R") << 2.0 << 30000.0 << 25.0 << 10000.0 << 100.0 << 300.0 << static_cast<int>(Config::TemperatureUnits::CELSIUS) << static_cast<int>(Config::TemperatureSensorType::COOLANT) << 65.5439 << NtcTest::vSupply * (1500 / (NtcTest::rBalance + 1500)); }
30.708333
95
0.607191
[ "object" ]
9c8b0628ec012df4f19da7cfd113978ff4d22a22
10,737
cpp
C++
src/HArea.cpp
tapeguy/heekscad
e5037d15d642551de756f352e4e14505c39ad7cf
[ "BSD-3-Clause" ]
null
null
null
src/HArea.cpp
tapeguy/heekscad
e5037d15d642551de756f352e4e14505c39ad7cf
[ "BSD-3-Clause" ]
null
null
null
src/HArea.cpp
tapeguy/heekscad
e5037d15d642551de756f352e4e14505c39ad7cf
[ "BSD-3-Clause" ]
null
null
null
// HArea.cpp // Copyright (c) 2009, Dan Heeks // This program is released under the BSD license. See the file COPYING for details. #include "stdafx.h" #include "HArea.h" #include "HLine.h" #include "HILine.h" #include "HCircle.h" #include "../interface/MarkedObject.h" #include "../interface/Tool.h" #include "../libarea/Arc.h" #include "../tinyxml/tinyxml.h" #include "Gripper.h" #include "Sketch.h" #include "Drawing.h" #include "DigitizeMode.h" HArea::HArea(const HArea &a) : IdNamedObj(a), m_number_curves(a.m_number_curves) { InitializeProperties(); operator=(a); } HArea::HArea(const CArea &a) : IdNamedObj(ObjType), m_number_curves(a.m_curves.size()), m_area(a) { InitializeProperties(); } HArea::~HArea() { } void HArea::InitializeProperties() { m_number_curves.Initialize(_("number of curves"), this); m_number_curves.SetReadOnly(true); m_number_curves.SetTransient(true); } const wxBitmap &HArea::GetIcon() { static wxBitmap* icon = NULL; if(icon == NULL) icon = new wxBitmap(wxImage(wxGetApp().GetResFolder() + _T("/icons/area.png"))); return *icon; } bool HArea::IsDifferent(HeeksObj* other) { HArea* a = (HArea*)other; // to do return this != a; } const HArea& HArea::operator=(const HArea &b) { m_area = b.m_area; return *this; } static HArea* object_for_tool = NULL; class DeleteCurveTool:public Tool{ public: // Tool's virtual functions void Run(){ for(std::list<CCurve>::iterator It = object_for_tool->m_area.m_curves.begin(); It != object_for_tool->m_area.m_curves.end(); It++) { CCurve& curve = *It; if(&curve == object_for_tool->m_selected_curve) { object_for_tool->m_area.m_curves.erase(It); break; } } } const wxChar* GetTitle(){ return _("Delete Curve");} wxString BitmapPath(){ return wxGetApp().GetResFolder() + _T("/bitmaps/delete.png");} }; static DeleteCurveTool delete_selected_curve; class OffsetAreaTool:public Tool{ public: // Tool's virtual functions void Run(){ double offset_value = 2.0; HeeksConfig& config = wxGetApp().GetConfig(); config.Read(_T("OffsetAreaValue"), &offset_value); if(wxGetApp().InputLength(_("Enter Offset Value, + for making bigger, - for making smaller"), _("Offset value"), offset_value)) { try { CArea area = object_for_tool->m_area; area.Offset(-offset_value); HeeksObj* new_object = new HArea(area); object_for_tool->GetOwner()->Add(new_object); config.Write(_T("OffsetAreaValue"), offset_value); } catch (...) { wxMessageBox(_("Area offset error")); } } } const wxChar* GetTitle(){ return _("Offset Area");} wxString BitmapPath(){ return wxGetApp().GetResFolder() + _T("/bitmaps/offsetarea.png");} }; static OffsetAreaTool offset_area_tool; class ObroundAreaTool:public Tool{ public: // Tool's virtual functions void Run(){ double offset_value = 0.3; HeeksConfig& config = wxGetApp().GetConfig(); config.Read(_T("ObroundAreaValue"), &offset_value); if(wxGetApp().InputLength(_("Enter Offset Value"), _("Offset value"), offset_value)) { try { CArea area = object_for_tool->m_area; area.Thicken(fabs(offset_value)); HeeksObj* new_object = new HArea(area); object_for_tool->GetOwner()->Add(new_object); config.Write(_T("ObroundAreaValue"), fabs(offset_value)); } catch (...) { wxMessageBox(_("Area thicken error")); } } } const wxChar* GetTitle(){ return _("Thicken Area");} wxString BitmapPath(){ return wxGetApp().GetResFolder() + _T("/bitmaps/thickenarea.png");} }; static ObroundAreaTool obround_area_tool; class ReorderAreaTool:public Tool{ public: // Tool's virtual functions void Run(){ object_for_tool->m_area.Reorder(); } const wxChar* GetTitle(){ return _("Reorder Area");} wxString BitmapPath(){ return wxGetApp().GetResFolder() + _T("/bitmaps/reorderarea.png");} }; static ReorderAreaTool reorder_area_tool; class SplitAreaTool:public Tool{ public: // Tool's virtual functions void Run(){ std::list<CArea> areas; object_for_tool->m_area.Split(areas); for(std::list<CArea>::iterator It = areas.begin(); It != areas.end(); It++) { CArea &area = *It; HArea* new_object = new HArea(area); wxGetApp().Add(new_object, NULL); } wxGetApp().Remove(object_for_tool); } const wxChar* GetTitle(){ return _("Split Area");} wxString BitmapPath(){ return wxGetApp().GetResFolder() + _T("/bitmaps/areasplit.png");} }; static SplitAreaTool split_area_tool; void HArea::GetTools(std::list<Tool*>* t_list, const wxPoint* p) { object_for_tool = this; if(this->m_selected_curve)t_list->push_back(&delete_selected_curve); t_list->push_back(&offset_area_tool); t_list->push_back(&obround_area_tool); t_list->push_back(&reorder_area_tool); t_list->push_back(&split_area_tool); } static void glVertexFunction(const double *p){glVertex3d(p[0], p[1], 0.0);} static void render_curve(const CCurve& curve) { glBegin(GL_LINE_STRIP); int i = 0; // for gl name stack, when I get round to being able to select individual vertices const CVertex* prev_vertex = NULL; for(std::list<CVertex>::const_iterator It = curve.m_vertices.begin(); It != curve.m_vertices.end(); It++, i++) { const CVertex& vertex = *It; if(prev_vertex && vertex.m_type) { CArc arc(Point(prev_vertex->m_p), Point(vertex.m_p), Point(vertex.m_c), (vertex.m_type == 1), vertex.m_user_data); arc.GetSegments(glVertexFunction, wxGetApp().GetPixelScale()); } else { glVertex3d(vertex.m_p.x, vertex.m_p.y, 0.0); } prev_vertex = &vertex; } glEnd(); } void HArea::glCommands(bool select, bool marked, bool no_color) { if(!no_color){ wxGetApp().glColorEnsuringContrast(HeeksColor(0)); } GLfloat save_depth_range[2]; if(marked){ glGetFloatv(GL_DEPTH_RANGE, save_depth_range); glDepthRange(0, 0); glLineWidth(2); } unsigned int i = 0; for(std::list<CCurve>::iterator It = m_area.m_curves.begin(); It != m_area.m_curves.end(); It++, i++) { CCurve& curve = *It; if(select)glPushName(i); if(marked && (&curve == m_selected_curve))glColor3ub(0, 255, 0); render_curve(curve); if(marked && (&curve == m_selected_curve))wxGetApp().glColorEnsuringContrast(HeeksColor(0)); if(select)glPopName(); } if(marked){ glLineWidth(1); glDepthRange(save_depth_range[0], save_depth_range[1]); } } void HArea::Draw(wxDC& dc) { } HeeksObj *HArea::MakeACopy(void)const { HArea *new_object = new HArea(*this); return new_object; } void HArea::ModifyByMatrix(const double* m) { gp_Trsf mat = make_matrix(m); for(std::list<CCurve>::iterator It = m_area.m_curves.begin(); It != m_area.m_curves.end(); It++) { CCurve& curve = *It; for(std::list<CVertex>::iterator VIt = curve.m_vertices.begin(); VIt != curve.m_vertices.end(); VIt++) { CVertex &v = *VIt; gp_Pnt p(v.m_p.x, v.m_p.y, 0.0); p.Transform(mat); v.m_p = Point(p.X(), p.Y()); if(v.m_type != 0) { gp_Pnt c(v.m_c.x, v.m_c.y, 0.0); c.Transform(mat); v.m_c = Point(c.X(), c.Y()); } } } } void HArea::GetBox(CBox &box) { CBox2D b2; m_area.GetBox(b2); box.Insert(b2.m_minxy.x, b2.m_minxy.y, 0.0); box.Insert(b2.m_maxxy.x, b2.m_maxxy.y, 0.0); } void HArea::GetGripperPositions(std::list<GripData> *list, bool just_for_endof) { //list->push_back(GripData(GripperTypeStretch,C->m_p.X(),C->m_p.Y(),C->m_p.Z(),C)); } void HArea::GetProperties(std::list<Property *> *list) { m_number_curves = m_area.m_curves.size(); HeeksObj::GetProperties(list); } bool HArea::Stretch(const double *p, const double* shift, void* data) { #if 0 gp_Pnt vp = make_point(p); gp_Vec vshift = make_vector(shift); if(A->m_p.IsEqual(vp, wxGetApp().m_geom_tol)){ gp_Vec direction = -(GetSegmentVector(1.0)); gp_Pnt centre; gp_Dir axis; gp_Pnt new_A = gp_Pnt(A->m_p.XYZ() + vshift.XYZ()); if(HArea::TangentialArc(B->m_p, direction, new_A, centre, axis)) { m_axis = gp_Ax1(centre, -axis); m_radius = new_A.Distance(centre); A->m_p = new_A; } } #endif return false; } // static void HArea::WriteVertex(const CVertex& vertex, TiXmlNode *root) { TiXmlElement* element = new TiXmlElement( "vertex" ); root->LinkEndChild( element ); element->SetAttribute("type", vertex.m_type); element->SetDoubleAttribute("x", vertex.m_p.x); element->SetDoubleAttribute("y", vertex.m_p.y); if(vertex.m_type != 0) { element->SetDoubleAttribute("i", vertex.m_c.x); element->SetDoubleAttribute("j", vertex.m_c.y); } } // static void HArea::ReadVertex(CVertex& vertex, TiXmlElement *root) { root->Attribute("type", &vertex.m_type); root->Attribute("x", &vertex.m_p.x); root->Attribute("y", &vertex.m_p.y); if(vertex.m_type != 0) { root->Attribute("i", &vertex.m_c.x); root->Attribute("j", &vertex.m_c.y); } } // static void HArea::WriteCurve(const CCurve& curve, TiXmlNode *root) { TiXmlElement* element = new TiXmlElement( "curve" ); root->LinkEndChild( element ); for(std::list<CVertex>::const_iterator It = curve.m_vertices.begin(); It != curve.m_vertices.end(); It++) { const CVertex& vertex = *It; WriteVertex(vertex, element); } } // static void HArea::ReadCurve(CCurve& curve, TiXmlElement *root) { for(TiXmlElement *pElem = root->FirstChildElement(); pElem; pElem = pElem->NextSiblingElement()) { CVertex vertex; ReadVertex(vertex, pElem); curve.m_vertices.push_back(vertex); } } // static void HArea::WriteArea(const CArea& area, TiXmlNode *root) { TiXmlElement* element = new TiXmlElement( "area" ); root->LinkEndChild( element ); for(std::list<CCurve>::const_iterator It = area.m_curves.begin(); It != area.m_curves.end(); It++) { const CCurve& curve = *It; WriteCurve(curve, element); } } // static void HArea::ReadArea(CArea& area, TiXmlElement *root) { for(TiXmlElement *pElem = root->FirstChildElement(); pElem; pElem = pElem->NextSiblingElement()) { CCurve curve; ReadCurve(curve, pElem); area.m_curves.push_back(curve); } } void HArea::WriteXML(TiXmlNode *root) { TiXmlElement *element = new TiXmlElement( "Area" ); root->LinkEndChild( element ); WriteArea(m_area, element); WriteBaseXML(element); } // static member function HeeksObj* HArea::ReadFromXMLElement(TiXmlElement* root) { // read area CArea area; ReadArea(area, root->FirstChildElement()); HArea* new_object = new HArea(area); new_object->ReadBaseXML(root); return new_object; } void HArea::SetClickMarkPoint(MarkedObject* marked_object, const double* ray_start, const double* ray_direction) { // set picked curve if(marked_object->GetNumCustomNames()>0) { unsigned int i = 0; for(std::list<CCurve>::iterator It = m_area.m_curves.begin(); It != m_area.m_curves.end(); It++, i++) { CCurve& curve = *It; if(i == marked_object->GetCustomNames()[0]) { m_selected_curve = &curve; break; } } } }
24.969767
132
0.689299
[ "transform" ]
9c8bb9cb7bb7ad21f6070297fef957e956f6892a
2,834
cpp
C++
aws-cpp-sdk-elasticmapreduce/source/model/SpotProvisioningSpecification.cpp
woohoou/aws-sdk-cpp
a42835a8aad2eac1e334d899a3fbfedcaa341d51
[ "Apache-2.0" ]
1
2020-07-16T19:03:13.000Z
2020-07-16T19:03:13.000Z
aws-cpp-sdk-elasticmapreduce/source/model/SpotProvisioningSpecification.cpp
woohoou/aws-sdk-cpp
a42835a8aad2eac1e334d899a3fbfedcaa341d51
[ "Apache-2.0" ]
18
2018-05-15T16:41:07.000Z
2018-05-21T00:46:30.000Z
aws-cpp-sdk-elasticmapreduce/source/model/SpotProvisioningSpecification.cpp
woohoou/aws-sdk-cpp
a42835a8aad2eac1e334d899a3fbfedcaa341d51
[ "Apache-2.0" ]
1
2021-10-01T15:29:44.000Z
2021-10-01T15:29:44.000Z
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <aws/elasticmapreduce/model/SpotProvisioningSpecification.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace EMR { namespace Model { SpotProvisioningSpecification::SpotProvisioningSpecification() : m_timeoutDurationMinutes(0), m_timeoutDurationMinutesHasBeenSet(false), m_timeoutAction(SpotProvisioningTimeoutAction::NOT_SET), m_timeoutActionHasBeenSet(false), m_blockDurationMinutes(0), m_blockDurationMinutesHasBeenSet(false) { } SpotProvisioningSpecification::SpotProvisioningSpecification(const JsonValue& jsonValue) : m_timeoutDurationMinutes(0), m_timeoutDurationMinutesHasBeenSet(false), m_timeoutAction(SpotProvisioningTimeoutAction::NOT_SET), m_timeoutActionHasBeenSet(false), m_blockDurationMinutes(0), m_blockDurationMinutesHasBeenSet(false) { *this = jsonValue; } SpotProvisioningSpecification& SpotProvisioningSpecification::operator =(const JsonValue& jsonValue) { if(jsonValue.ValueExists("TimeoutDurationMinutes")) { m_timeoutDurationMinutes = jsonValue.GetInteger("TimeoutDurationMinutes"); m_timeoutDurationMinutesHasBeenSet = true; } if(jsonValue.ValueExists("TimeoutAction")) { m_timeoutAction = SpotProvisioningTimeoutActionMapper::GetSpotProvisioningTimeoutActionForName(jsonValue.GetString("TimeoutAction")); m_timeoutActionHasBeenSet = true; } if(jsonValue.ValueExists("BlockDurationMinutes")) { m_blockDurationMinutes = jsonValue.GetInteger("BlockDurationMinutes"); m_blockDurationMinutesHasBeenSet = true; } return *this; } JsonValue SpotProvisioningSpecification::Jsonize() const { JsonValue payload; if(m_timeoutDurationMinutesHasBeenSet) { payload.WithInteger("TimeoutDurationMinutes", m_timeoutDurationMinutes); } if(m_timeoutActionHasBeenSet) { payload.WithString("TimeoutAction", SpotProvisioningTimeoutActionMapper::GetNameForSpotProvisioningTimeoutAction(m_timeoutAction)); } if(m_blockDurationMinutesHasBeenSet) { payload.WithInteger("BlockDurationMinutes", m_blockDurationMinutes); } return payload; } } // namespace Model } // namespace EMR } // namespace Aws
26.990476
137
0.781934
[ "model" ]
9c8c52031b1f82a92c793960a0977766d7040f26
63,708
cpp
C++
Libraries/RobsJuceModules/jura_processors/filters/jura_Equalizer.cpp
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
34
2017-04-19T18:26:02.000Z
2022-02-15T17:47:26.000Z
Libraries/RobsJuceModules/jura_processors/filters/jura_Equalizer.cpp
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
307
2017-05-04T21:45:01.000Z
2022-02-03T00:59:01.000Z
Libraries/RobsJuceModules/jura_processors/filters/jura_Equalizer.cpp
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
4
2017-09-05T17:04:31.000Z
2021-12-15T21:24:28.000Z
//----------------------------------------------------------------------------------------------------------------------------------------- // construction/destruction: EqualizerAudioModule::EqualizerAudioModule(CriticalSection *newPlugInLock, rosic::EqualizerStereo *equalizerStereoToWrap) : ModulatableAudioModule(newPlugInLock) { ScopedLock scopedLock(*lock); jassert(equalizerStereoToWrap != NULL); // you must pass a valid rosic-object to the constructor // ---nah, this Module admits NULL pointers for use inside EchoLab ...why? wrappedEqualizerStereo = equalizerStereoToWrap; init(); } EqualizerAudioModule::EqualizerAudioModule(CriticalSection *newPlugInLock) : ModulatableAudioModule(newPlugInLock) { ScopedLock scopedLock(*lock); wrappedEqualizerStereo = new rosic::EqualizerStereo; wrappedEqualizerIsOwned = true; init(); } void EqualizerAudioModule::init() { setModuleTypeName("Equalizer"); selectedChannel = 0; selectedIndex = -1; patchFormatIndex = 2; createStaticParameters(); } EqualizerAudioModule::~EqualizerAudioModule() { if(wrappedEqualizerIsOwned) delete wrappedEqualizerStereo; } AudioModuleEditor* EqualizerAudioModule::createEditor(int type) { return new EqualizerModuleEditor(lock, this); } //------------------------------------------------------------------------------------------------- // automation and state management: void EqualizerAudioModule::createStaticParameters() { ScopedLock scopedLock(*lock); typedef ModulatableParameter Param; Param* p; std::vector<double> defaultValues; addObservedParameter( p = new Param("Bypass", 0.0, 1.0, 0.0, Parameter::BOOLEAN, 1.0) ); p->setValueChangeCallback(wrappedEqualizerStereo, &EqualizerStereo::setBypass); p = new Param("StereoMode", 0.0, 3.0, 0.0, Parameter::STRING, 1.0); p->addStringValue("Stereo Linked"); p->addStringValue("Left/Right"); p->addStringValue("Mid/Side"); p->addStringValue("Mono"); addObservedParameter(p); p->setValueChangeCallback(wrappedEqualizerStereo, &EqualizerStereo::setStereoMode); p = new Param("GainRange", 0.0, 4.0, 3.0, Parameter::STRING, 1.0); p->addStringValue("3 dB"); //p->addStringValue(juce::String(T("\xF1 3 dB"))); // xF1 == hex for 241 -> plusminus in extended ASCII p->addStringValue("6 dB"); p->addStringValue("12 dB"); p->addStringValue("24 dB"); p->addStringValue("48 dB"); addObservedParameter(p); //p->setValueChangeCallback(wrappedEqualizerStereo, &EqualizerStereo::setStereoMode); p = new Param("GlobalGain", -48.0, 48.0, 0.0, Parameter::LINEAR_BIPOLAR, 0.1); defaultValues.clear(); defaultValues.push_back(-24.0); defaultValues.push_back(-18.0); defaultValues.push_back(-12.0); defaultValues.push_back( -6.0); defaultValues.push_back( 0.0); defaultValues.push_back( +6.0); defaultValues.push_back(+12.0); defaultValues.push_back(+18.0); defaultValues.push_back(+24.0); p->setDefaultValues(defaultValues); addObservedParameter(p); p->setValueChangeCallback(wrappedEqualizerStereo, &EqualizerStereo::setGlobalGain); } void EqualizerAudioModule::parameterChanged(Parameter* parameterThatHasChanged) { ScopedLock scopedLock(*lock); if( getIndexOfParameter(parameterThatHasChanged) == 1 ) // StereoMode { if( getNumChannelsToPlot() == 1 ) { selectChannel(0); return; // to avoid sending a change-message twice } } markStateAsDirty(); } XmlElement* EqualizerAudioModule::getStateAsXml(const juce::String& stateName, bool markAsClean) { ScopedLock scopedLock(*lock); XmlElement *xmlState = AudioModule::getStateAsXml(stateName, markAsClean); if( wrappedEqualizerStereo->getStereoMode() == rosic::EqualizerStereo::LEFT_RIGHT || wrappedEqualizerStereo->getStereoMode() == rosic::EqualizerStereo::MID_SIDE ) { for(int c = 0; c < 2; c++) xmlState->addChildElement(getChannelStateAsXml(c)); } else { for(int i = 0; i < filterModeParameters[0].size(); i++) xmlState->addChildElement(getBandStateAsXml(0, i)); } markStateAsClean(); return xmlState; } void EqualizerAudioModule::setStateFromXml(const XmlElement& xmlState, const juce::String& stateName, bool markAsClean) { XmlElement convertedState = convertXmlStateIfNecessary(xmlState); ScopedLock scopedLock(*lock); selectedIndex = -1; AudioModule::setStateFromXml(convertedState, stateName, markAsClean); removeAllBands(); int m = 1; double f, g, b; int c = 0; forEachXmlChildElementWithTagName(convertedState, channelChild, "Channel") { //int i = 0; forEachXmlChildElementWithTagName(*channelChild, bandChild, "Band") { juce::String modeString = bandChild->getStringAttribute("Mode", "Bypass"); f = bandChild->getDoubleAttribute("Frequency", 1000.0); g = bandChild->getDoubleAttribute("Gain", 0.0); b = bandChild->getDoubleAttribute("Bandwidth", 2.0*asinh(1.0/sqrt(2.0))/log(2.0)); if( modeString == juce::String("Peak/Dip") ) m = TwoPoleFilter::PEAK; else if( modeString == juce::String("Low Shelving") ) m = TwoPoleFilter::LOW_SHELF; else if( modeString == juce::String("High Shelving") ) m = TwoPoleFilter::HIGH_SHELF; else if( modeString == juce::String("Lowpass 6 dB/oct") ) m = TwoPoleFilter::LOWPASS6; else if( modeString == juce::String("Lowpass 12 dB/oct") ) m = TwoPoleFilter::LOWPASS12; else if( modeString == juce::String("Highpass 6 dB/oct") ) m = TwoPoleFilter::HIGHPASS6; else if( modeString == juce::String("Highpass 12 dB/oct") ) m = TwoPoleFilter::HIGHPASS12; else if( modeString == juce::String("Notch 2*6 dB/oct") ) m = TwoPoleFilter::BANDREJECT; // this string-to-int conversion should be somehow automated... addBand(c, m, f, g, b, false, true); } c++; } sendParameterSetChangeNotification(this); markStateAsClean(); } XmlElement EqualizerAudioModule::convertXmlStateIfNecessary(const XmlElement& xmlState) { ScopedLock scopedLock(*lock); //int xmlPatchFormatIndex = xmlState.getIntAttribute("PatchFormat", patchFormatIndex); if( xmlState.getChildByName(juce::String("Channel")) == NULL ) { // wrap the band-data into a "Channel" child element: XmlElement convertedState(xmlState); convertedState.deleteAllChildElements(); XmlElement* channelState = new XmlElement(juce::String("Channel")); forEachXmlChildElementWithTagName(xmlState, bandChild, "Band") { XmlElement* newBandChild = new XmlElement("Band"); *newBandChild = *bandChild; channelState->addChildElement(newBandChild); } convertedState.addChildElement(channelState); return convertedState; } else return xmlState; } XmlElement* EqualizerAudioModule::getChannelStateAsXml(int c) { XmlElement* channelState = new XmlElement(juce::String("Channel")); for(int i = 0; i < filterModeParameters[c].size(); i++) channelState->addChildElement(getBandStateAsXml(c, i)); return channelState; } XmlElement* EqualizerAudioModule::getBandStateAsXml(int c, int b) { XmlElement* bandState = new XmlElement(juce::String("Band")); bandState->setAttribute(filterModeParameters[c][b]->getName(), filterModeParameters[c][b]->getStringValue() ); bandState->setAttribute(frequencyParameters [c][b]->getName(), frequencyParameters [c][b]->getValue() ); bandState->setAttribute(gainParameters [c][b]->getName(), gainParameters [c][b]->getValue() ); bandState->setAttribute(bandwidthParameters [c][b]->getName(), bandwidthParameters [c][b]->getValue() ); return bandState; } //----------------------------------------------------------------------------------------------------------------------------------------- // setup: void EqualizerAudioModule::setSampleRate(double newSampleRate) { ScopedLock scopedLock(*lock); wrappedEqualizerStereo->setSampleRate((float)newSampleRate); } void EqualizerAudioModule::selectChannel(int channelToSelect) { ScopedLock scopedLock(*lock); jassert(channelToSelect >= 0 && channelToSelect <= 1); // there are only 2 channels selectedChannel = channelToSelect; deSelectBand(); } int EqualizerAudioModule::selectBand(int channel, int indexToSelect) { ScopedLock scopedLock(*lock); selectedChannel = channel; if( indexToSelect < 0 || indexToSelect >= wrappedEqualizerStereo->getNumBands(channel) ) selectedIndex = -1; else selectedIndex = indexToSelect; sendParameterSetChangeNotification(this); return selectedIndex; } void EqualizerAudioModule::deSelectBand() { ScopedLock scopedLock(*lock); selectedIndex = -1; sendParameterSetChangeNotification(this); } void EqualizerAudioModule::addBand(int channel, int mode, double frequency, double gain, double bandwidth, bool selectNewBand, bool suppressNotification) { ScopedLock scopedLock(*lock); int newIndex = wrappedEqualizerStereo->addBand(channel, mode, frequency, gain, bandwidth); std::vector<double> defaultValues; typedef Parameter Param; //typedef ModulatableParameter Param; // experimental, does not yet work right Param* p; p = new Param("Mode", 0.0, 8.0, 0.0, Parameter::STRING, 1.0); p->setMutexToUse(lock); p->addStringValue("Bypass"); p->addStringValue("Peak/Dip"); p->addStringValue("Low Shelving"); p->addStringValue("High Shelving"); p->addStringValue("Lowpass 6 dB/oct"); p->addStringValue("Lowpass 12 dB/oct"); p->addStringValue("Highpass 6 dB/oct"); p->addStringValue("Highpass 12 dB/oct"); p->addStringValue("Notch 2*6 dB/oct"); p->setValue(mode, false, false); p->registerParameterObserver(this); setupManagers(p); filterModeParameters[channel].add(p); p = new Param("Frequency", 20.0, 20000.0, 1000.0, Parameter::EXPONENTIAL, 0.0); p->setMutexToUse(lock); defaultValues.clear(); defaultValues.push_back( 31.25); defaultValues.push_back( 62.5); defaultValues.push_back( 125.0); defaultValues.push_back( 250.0); defaultValues.push_back( 500.0); defaultValues.push_back( 1000.0); defaultValues.push_back( 2000.0); defaultValues.push_back( 4000.0); defaultValues.push_back( 8000.0); defaultValues.push_back(16000.0); p->setDefaultValues(defaultValues); p->setValue(frequency, false, false); p->registerParameterObserver(this); setupManagers(p); frequencyParameters[channel].add(p); p = new Param("Gain", -48.0, 48.0, 0.0, Parameter::LINEAR_BIPOLAR, 0.1); p->setMutexToUse(lock); defaultValues.clear(); defaultValues.push_back(-24.0); defaultValues.push_back(-18.0); defaultValues.push_back(-12.0); defaultValues.push_back( -6.0); defaultValues.push_back( RAPT::rsAmpToDb(sqrt(0.5))); // -3.01 dB - standard definition for cutoff frequencies defaultValues.push_back( 0.0); defaultValues.push_back( +6.0); defaultValues.push_back(+12.0); defaultValues.push_back(+18.0); defaultValues.push_back(+24.0); p->setDefaultValues(defaultValues); p->setValue(gain, false, false); p->registerParameterObserver(this); setupManagers(p); gainParameters[channel].add(p); double defaultBandwidth = 2.0*asinh(1.0/sqrt(2.0))/log(2.0); // ca. 1.9, Q = sqrt(1/2), maximum steepness without overshoot for shelves p = new Param("Bandwidth", 0.25, 6.0, defaultBandwidth, Parameter::EXPONENTIAL, 0.01); p->setMutexToUse(lock); defaultValues.clear(); defaultValues.push_back(1.0/3.0); defaultValues.push_back(0.5); defaultValues.push_back(1.0); defaultValues.push_back(defaultBandwidth); defaultValues.push_back(2.0); defaultValues.push_back(3.0); defaultValues.push_back(4.0); p->setDefaultValues(defaultValues); p->setValue(bandwidth, false, false); p->registerParameterObserver(this); setupManagers(p); bandwidthParameters[channel].add(p); assignCallbacksForDynamicParameters(); if( selectNewBand == true ) { selectedChannel = channel; selectedIndex = newIndex; } if( suppressNotification != true ) sendParameterSetChangeNotification(this); } bool EqualizerAudioModule::removeBand(int channel, int indexToRemove) { ScopedLock scopedLock(*lock); if( indexToRemove < 0 || indexToRemove >= wrappedEqualizerStereo->getNumBands(channel) ) return false; filterModeParameters[channel][indexToRemove]->deRegisterParameterObserver(this); frequencyParameters[channel][indexToRemove]->deRegisterParameterObserver(this); gainParameters[channel][indexToRemove]->deRegisterParameterObserver(this); bandwidthParameters[channel][indexToRemove]->deRegisterParameterObserver(this); filterModeParameters[channel].remove(indexToRemove, true); frequencyParameters[channel].remove( indexToRemove, true); gainParameters[channel].remove( indexToRemove, true); bandwidthParameters[channel].remove( indexToRemove, true); // we can now safely remove the band from the wrapped Equalizer object because the parameters wich have held the callback pointers have // just been deleted: wrappedEqualizerStereo->removeBand(channel, indexToRemove); assignCallbacksForDynamicParameters(); selectedIndex = -1; sendParameterSetChangeNotification(this); return true; } void EqualizerAudioModule::removeAllBands() { ScopedLock scopedLock(*lock); for(int c=0; c<2; c++) { filterModeParameters[c].clear(true); frequencyParameters[c].clear(true); gainParameters[c].clear(true); bandwidthParameters[c].clear(true); } wrappedEqualizerStereo->removeAllBands(); selectedIndex = -1; sendParameterSetChangeNotification(this); } //----------------------------------------------------------------------------------------------------------------------------------------- // inquiry: int EqualizerAudioModule::getNumChannelsToPlot() { ScopedLock scopedLock(*lock); if( wrappedEqualizerStereo->getStereoMode() == rosic::EqualizerStereo::STEREO_LINKED || wrappedEqualizerStereo->getStereoMode() == rosic::EqualizerStereo::MONO ) { return 1; } else return 2; } int EqualizerAudioModule::getNumBands(int channel) { ScopedLock scopedLock(*lock); int result = wrappedEqualizerStereo->getNumBands(channel); return result; } void EqualizerAudioModule::getMagnitudeResponse(int channel, double *frequencies, double *magnitudes, int numBins) { ScopedLock scopedLock(*lock); wrappedEqualizerStereo->getMagnitudeResponse(channel, frequencies, magnitudes, numBins); } double EqualizerAudioModule::getDecibelsAt(int channel, double frequency) { return 0; // preliminary } //----------------------------------------------------------------------------------------------------------------------------------------- // others: void EqualizerAudioModule::reset() { ScopedLock scopedLock(*lock); wrappedEqualizerStereo->reset(); } void EqualizerAudioModule::assignCallbacksForDynamicParameters() { ScopedLock scopedLock(*lock); int numChannels = 2; for(int c=0; c<numChannels; c++) { int numBands = filterModeParameters[c].size(); for(int i=0; i<numBands; i++) { filterModeParameters[c][i]->clearValueChangeCallbacks(); frequencyParameters[c][i]->clearValueChangeCallbacks(); gainParameters[c][i]->clearValueChangeCallbacks(); bandwidthParameters[c][i]->clearValueChangeCallbacks(); // why do we need these call to clear - check and delete if not needed filterModeParameters[c][i]->setValueChangeCallback(&wrappedEqualizerStereo->equalizers[c].bands[i], &TwoPoleFilter::setMode); frequencyParameters[c][i]->setValueChangeCallback( &wrappedEqualizerStereo->equalizers[c].bands[i], &TwoPoleFilter::setFrequency); gainParameters[c][i]->setValueChangeCallback( &wrappedEqualizerStereo->equalizers[c].bands[i], &TwoPoleFilter::setGain); bandwidthParameters[c][i]->setValueChangeCallback( &wrappedEqualizerStereo->equalizers[c].bands[i], &TwoPoleFilter::setBandwidth); } } } //================================================================================================= EqualizerPlotEditor::EqualizerPlotEditor(CriticalSection *newPlugInLock, EqualizerAudioModule* newEqualizerModuleToEdit) : rsSpectrumPlot(juce::String("EqualizerEditor")) { setDescription("Left: insert or grab band-handle, right: remove band"); ParameterObserver::setIsGuiElement(true); plugInLock = newPlugInLock; equalizerModuleToEdit = NULL; // will be assigned later via call to setEqualizerModuleToEdit // set up the plot range: setAutoReRendering(false); setMaximumRange(15.625, 32000.0, -48.0, 48.0); setCurrentRange(15.625, 32000.0, -24.0, 24.0); setHorizontalCoarseGrid(6.0, true); setHorizontalFineGrid( 1.0, false); setVerticalCoarseGridVisible( true); setVerticalFineGridVisible( false); rsPlot::setAxisValuesPositionX(rsPlotSettings::ABOVE_AXIS); rsPlot::setAxisValuesPositionY(rsPlotSettings::RIGHT_TO_AXIS); setAutoReRendering(true); currentMouseCursor = MouseCursor(MouseCursor::NormalCursor); setMouseCursor(currentMouseCursor); filterModeParameter = NULL; frequencyParameter = NULL; gainParameter = NULL; bandwidthParameter = NULL; globalGainParameter = NULL; // this stuff will be (re-) assigned in resized(): numBins = 0; frequencies = NULL; magnitudes1 = NULL; magnitudes2 = NULL; magnitudes[0] = magnitudes1; magnitudes[1] = magnitudes2; currentlyDraggedHandle = NONE; // activate automation for this ParameterObserver: ParameterObserver::setLocalAutomationSwitch(true); setEqualizerModuleToEdit(newEqualizerModuleToEdit); } EqualizerPlotEditor::~EqualizerPlotEditor(void) { setEqualizerModuleToEdit(NULL); // to remove ourselves as ChangeListener deleteAndZero(frequencies); deleteAndZero(magnitudes1); deleteAndZero(magnitudes2); } //----------------------------------------------------------------------------------------------------------------------------------------- // setup: void EqualizerPlotEditor::setEqualizerModuleToEdit(EqualizerAudioModule* newEqualizerModuleToEdit) { ScopedPointerLock spl(plugInLock); if( newEqualizerModuleToEdit == equalizerModuleToEdit ) return; if( equalizerModuleToEdit != NULL ) equalizerModuleToEdit->deRegisterParameterSetObserver(this); equalizerModuleToEdit = newEqualizerModuleToEdit; if( globalGainParameter != NULL ) globalGainParameter->deRegisterParameterObserver(this); globalGainParameter = NULL; if( equalizerModuleToEdit != NULL ) { equalizerModuleToEdit->registerParameterSetObserver(this); globalGainParameter = equalizerModuleToEdit->getParameterByName("GlobalGain"); globalGainParameter->registerParameterObserver(this); } assignParametersToSelectedBand(); updatePlot(); } void EqualizerPlotEditor::unAssignParameters() { ScopedPointerLock spl(plugInLock); if( filterModeParameter != NULL ) filterModeParameter->deRegisterParameterObserver(this); filterModeParameter = NULL; if( frequencyParameter != NULL ) frequencyParameter->deRegisterParameterObserver(this); frequencyParameter = NULL; if( gainParameter != NULL ) gainParameter->deRegisterParameterObserver(this); gainParameter = NULL; if( bandwidthParameter != NULL ) bandwidthParameter->deRegisterParameterObserver(this); bandwidthParameter = NULL; } void EqualizerPlotEditor::assignParametersToSelectedBand() { ScopedPointerLock spl(plugInLock); unAssignParameters(); if( equalizerModuleToEdit == NULL ) return; int channel = equalizerModuleToEdit->selectedChannel; int index = equalizerModuleToEdit->selectedIndex; if( index > -1 ) { filterModeParameter = equalizerModuleToEdit->filterModeParameters[channel][index]; filterModeParameter->registerParameterObserver(this); frequencyParameter = equalizerModuleToEdit->frequencyParameters[channel][index]; frequencyParameter->registerParameterObserver(this); gainParameter = equalizerModuleToEdit->gainParameters[channel][index]; gainParameter->registerParameterObserver(this); bandwidthParameter = equalizerModuleToEdit->bandwidthParameters[channel][index]; bandwidthParameter->registerParameterObserver(this); } } //----------------------------------------------------------------------------------------------------------------------------------------- // inquiry: int EqualizerPlotEditor::getBandIndexAtPixelPosition(int x, int y) { ScopedPointerLock spl(plugInLock); if( equalizerModuleToEdit == NULL ) return -1; double globalGain = equalizerModuleToEdit->wrappedEqualizerStereo->getGlobalGain(); double dotRadius = 4.0; double xd = (double) x; double yd = (double) y; for(int i=0; i<equalizerModuleToEdit->getNumBands(equalizerModuleToEdit->selectedChannel); i++) { double xi = equalizerModuleToEdit->wrappedEqualizerStereo->getBandFrequency(equalizerModuleToEdit->selectedChannel, i); double yi = equalizerModuleToEdit->wrappedEqualizerStereo->getBandGain(equalizerModuleToEdit->selectedChannel, i); yi += globalGain; toPixelCoordinates(xi, yi); double d = sqrt( (xi-xd)*(xi-xd) + (yi-yd)*(yi-yd) ); if( d <= dotRadius ) return i; if( i == equalizerModuleToEdit->selectedIndex ) { // check if x,y is over the left bandwidth handle of the selected band: double xt = equalizerModuleToEdit->wrappedEqualizerStereo->getLowerBandedgeFrequency( equalizerModuleToEdit->selectedChannel, equalizerModuleToEdit->selectedIndex); double yt = equalizerModuleToEdit->wrappedEqualizerStereo->getBandGain( equalizerModuleToEdit->selectedChannel, equalizerModuleToEdit->selectedIndex); yt += globalGain; toPixelCoordinates(xt, yt); if( RAPT::rsEuclideanDistance(xt, yt, xd, yd) < 3.0 ) return i; // check if x,y is over the right bandwidth handle of the selected band: xt = equalizerModuleToEdit->wrappedEqualizerStereo->getUpperBandedgeFrequency( equalizerModuleToEdit->selectedChannel, equalizerModuleToEdit->selectedIndex); yt = equalizerModuleToEdit->wrappedEqualizerStereo->getBandGain( equalizerModuleToEdit->selectedChannel, equalizerModuleToEdit->selectedIndex); yt += globalGain; toPixelCoordinates(xt, yt); if( RAPT::rsEuclideanDistance(xt, yt, xd, yd) < 3.0 ) return i; } } return -1; } //----------------------------------------------------------------------------------------------------------------------------------------- // callbacks: /* void EqualizerPlotEditor::changeListenerCallback(ChangeBroadcaster *objectThatHasChanged) { ScopedPointerLock spl(plugInLock); assignParametersToSelectedBand(); updatePlot(); } */ void EqualizerPlotEditor::parameterSetChanged(ParameterSetHolder* parameterSetHolderThatHasChanged) { ScopedPointerLock spl(plugInLock); assignParametersToSelectedBand(); updatePlot(); } void EqualizerPlotEditor::parameterChanged(Parameter* parameterThatHasChanged) { ScopedPointerLock spl(plugInLock); updatePlot(); } void EqualizerPlotEditor::parameterWillBeDeleted(Parameter* p) { ScopedPointerLock spl(plugInLock); p->deRegisterParameterObserver(this); if( p == filterModeParameter ) filterModeParameter = NULL; else if( p == frequencyParameter ) frequencyParameter = NULL; else if( p == gainParameter ) gainParameter = NULL; else if( p == bandwidthParameter ) bandwidthParameter = NULL; updatePlot(); } void EqualizerPlotEditor::mouseMove(const MouseEvent &e) { ScopedPointerLock spl(plugInLock); if( equalizerModuleToEdit == NULL ) return; int index = getBandIndexAtPixelPosition(e.x, e.y); if( index != -1 ) { //int m = equalizerModuleToEdit->wrappedEqualizerStereo->getBandMode( equalizerModuleToEdit->selectedChannel, index); double f = equalizerModuleToEdit->wrappedEqualizerStereo->getBandFrequency(equalizerModuleToEdit->selectedChannel, index); double g = equalizerModuleToEdit->wrappedEqualizerStereo->getBandGain( equalizerModuleToEdit->selectedChannel, index); double b = equalizerModuleToEdit->wrappedEqualizerStereo->getBandBandwidth(equalizerModuleToEdit->selectedChannel, index); juce::String mStr; int mode = equalizerModuleToEdit->wrappedEqualizerStereo->getBandMode(equalizerModuleToEdit->selectedChannel, index); switch( mode ) { case rosic::TwoPoleFilter::PEAK: mStr = juce::String("Peak/Dip"); break; case rosic::TwoPoleFilter::LOW_SHELF: mStr = juce::String("Low Shelving"); break; case rosic::TwoPoleFilter::HIGH_SHELF: mStr = juce::String("High Shelving"); break; case rosic::TwoPoleFilter::LOWPASS6: mStr = juce::String("Lowpass 6 dB/oct"); break; case rosic::TwoPoleFilter::LOWPASS12: mStr = juce::String("Lowpass 12 dB/oct"); break; case rosic::TwoPoleFilter::HIGHPASS6: mStr = juce::String("Highpass 6 dB/oct"); break; case rosic::TwoPoleFilter::HIGHPASS12: mStr = juce::String("Highpass 12 dB/oct"); break; case rosic::TwoPoleFilter::BANDREJECT: mStr = juce::String("Notch 2*6 dB/oct"); break; } juce::String fStr = juce::String("Frequency: ") + hertzToStringWithUnitTotal5(f) + juce::String(", "); juce::String gStr = juce::String("Gain: ") + decibelsToStringWithUnit2(g) + juce::String(", "); juce::String bStr = juce::String("Bandwidth: ") + octavesToStringWithUnit2(b); juce::String description = mStr + juce::String(", ") + fStr; if( equalizerModuleToEdit->wrappedEqualizerStereo->doesModeSupportGain(equalizerModuleToEdit->selectedChannel, index) ) description += gStr; if( equalizerModuleToEdit->wrappedEqualizerStereo->doesModeSupportBandwidth(equalizerModuleToEdit->selectedChannel, index) ) description += bStr; setDescription(description); } else setDescription(juce::String("Left: insert or grab band-handle, right: remove band")); int dragHandle = getDragHandleAt(e.x, e.y); if( dragHandle == NONE ) setMouseCursor(MouseCursor::NormalCursor); else if( dragHandle == FREQUENCY_AND_GAIN ) setMouseCursor(MouseCursor::PointingHandCursor); else if( dragHandle == BANDWIDTH_AND_GAIN_LEFT || dragHandle == BANDWIDTH_AND_GAIN_RIGHT || dragHandle == FREQUENCY ) setMouseCursor(MouseCursor::LeftRightResizeCursor); else if( dragHandle == GLOBALGAIN_LINE || dragHandle == GAIN ) setMouseCursor(MouseCursor::UpDownResizeCursor); } void EqualizerPlotEditor::mouseDown(const MouseEvent &e) { ScopedPointerLock spl(plugInLock); if( equalizerModuleToEdit == NULL ) return; currentlyDraggedHandle = getDragHandleAt(e.x, e.y); if( equalizerModuleToEdit->selectedIndex != -1 ) { // check first, if one of the left/right or up/down handles is grabbed: if( currentlyDraggedHandle == BANDWIDTH_AND_GAIN_LEFT || currentlyDraggedHandle == BANDWIDTH_AND_GAIN_RIGHT || currentlyDraggedHandle == FREQUENCY || currentlyDraggedHandle == GAIN ) { //sendChangeMessage(); return; } } int tmpIndex = getBandIndexAtPixelPosition(e.x, e.y); if( tmpIndex == -1 ) { if( e.mods.isLeftButtonDown() ) { if( currentlyDraggedHandle != GLOBALGAIN_LINE ) { // create a new band and mark it selected: double f = e.x; double g = e.y; xyToFrequencyAndGain(f, g); equalizerModuleToEdit->addBand(equalizerModuleToEdit->selectedChannel, rosic::TwoPoleFilter::PEAK, f, g); equalizerModuleToEdit->selectBand(equalizerModuleToEdit->selectedChannel, equalizerModuleToEdit->getNumBands(equalizerModuleToEdit->selectedChannel)-1); currentlyDraggedHandle = FREQUENCY_AND_GAIN; } } // maybe de-select on mouse-click /* else if( e.mods.isRightButtonDown() ) { currentlyDraggedHandle = NONE; openRightClickPopupMenu(e.x, e.y); return; } */ } else { if( e.mods.isRightButtonDown() ) { /* // this stuff should not be necesarry, but let's try for debugging: if( frequencyParameter != NULL ) frequencyParameter->deRegisterParameterObserver(this); frequencyParameter = NULL; if( gainParameter != NULL ) gainParameter->deRegisterParameterObserver(this); gainParameter = NULL; // end debug */ equalizerModuleToEdit->removeBand(equalizerModuleToEdit->selectedChannel, tmpIndex); currentlyDraggedHandle = NONE; } else { equalizerModuleToEdit->selectBand(equalizerModuleToEdit->selectedChannel, tmpIndex); currentlyDraggedHandle = FREQUENCY_AND_GAIN; } } updatePlot(); //sendChangeMessage(); } void EqualizerPlotEditor::mouseDrag(const juce::MouseEvent &e) { if( e.mods.isRightButtonDown() || e.mouseWasClicked() ) return; // ignore right-drags because the band was just removed, alos ignore just-clicks ScopedPointerLock spl(plugInLock); if( equalizerModuleToEdit == NULL ) return; if( frequencyParameter == NULL || gainParameter == NULL || bandwidthParameter == NULL || globalGainParameter == NULL ) { if( currentlyDraggedHandle != GLOBALGAIN_LINE ) return; } double globalGain = equalizerModuleToEdit->wrappedEqualizerStereo->getGlobalGain(); // get the position of the event in components coordinates: double x = e.getMouseDownX() + e.getDistanceFromDragStartX(); double y = e.getMouseDownY() + e.getDistanceFromDragStartY(); x = RAPT::rsClip(x, 0.0, (double) getWidth()); y = RAPT::rsClip(y, 0.0, (double) getHeight()); fromPixelCoordinates(x, y); if( currentlyDraggedHandle == FREQUENCY_AND_GAIN ) { frequencyParameter->setValue(x, true, true); gainParameter->setValue(y-globalGain, true, true); } else if( currentlyDraggedHandle == BANDWIDTH_AND_GAIN_LEFT ) { double bw = rosic::TwoPoleFilter::lowerBandedgeFrequencyToBandwdith(x, frequencyParameter->getValue()); bandwidthParameter->setValue(bw, true, true); gainParameter->setValue(y-globalGain, true, true); } else if( currentlyDraggedHandle == BANDWIDTH_AND_GAIN_RIGHT ) { double bw = rosic::TwoPoleFilter::upperBandedgeFrequencyToBandwdith(x, frequencyParameter->getValue()); bandwidthParameter->setValue(bw, true, true); gainParameter->setValue(y-globalGain, true, true); } else if( currentlyDraggedHandle == FREQUENCY ) { frequencyParameter->setValue(x, true, true); } else if( currentlyDraggedHandle == GAIN ) { gainParameter->setValue(y-globalGain, true, true); } else if( currentlyDraggedHandle == GLOBALGAIN_LINE ) { globalGainParameter->setValue(y, true, true); } mouseMove(e); updatePlot(); } void EqualizerPlotEditor::mouseUp(const juce::MouseEvent &e) { currentlyDraggedHandle = NONE; } void EqualizerPlotEditor::mouseWheelMove(const MouseEvent& e, const MouseWheelDetails& wheel) { ScopedPointerLock spl(plugInLock); if( equalizerModuleToEdit == NULL ) return; int channel = equalizerModuleToEdit->selectedChannel; int index = getBandIndexAtPixelPosition(e.x, e.y); if( index != -1 ) { Parameter *p = equalizerModuleToEdit->bandwidthParameters[channel][index]; double b = p->getValue(); b = RAPT::rsExpToLin(b, 0.25, 4.0, 0.0, 1.0); b += 0.0625*wheel.deltaY; b = RAPT::rsLinToExp(b, 0.0, 1.0, 0.25, 4.0); p->setValue(b, true, true); updatePlot(); } } int EqualizerPlotEditor::getDragHandleAt(int x, int y) { ScopedPointerLock spl(plugInLock); if( equalizerModuleToEdit == NULL ) return NONE; double globalGain = equalizerModuleToEdit->wrappedEqualizerStereo->getGlobalGain(); double xd = (double) x; double yd = (double) y; double xt, yt; // target coordinates for matching if( equalizerModuleToEdit->selectedIndex != -1 ) { // check if x,y is over the left bandwidth handle of the selected band: xt = equalizerModuleToEdit->wrappedEqualizerStereo->getLowerBandedgeFrequency( equalizerModuleToEdit->selectedChannel, equalizerModuleToEdit->selectedIndex); yt = equalizerModuleToEdit->wrappedEqualizerStereo->getBandGain( equalizerModuleToEdit->selectedChannel, equalizerModuleToEdit->selectedIndex) + globalGain; toPixelCoordinates(xt, yt); if( RAPT::rsEuclideanDistance(xt, yt, xd, yd) < 3.0 ) return BANDWIDTH_AND_GAIN_LEFT; // check if x,y is over the right bandwidth handle of the selected band: xt = equalizerModuleToEdit->wrappedEqualizerStereo->getUpperBandedgeFrequency( equalizerModuleToEdit->selectedChannel, equalizerModuleToEdit->selectedIndex); yt = equalizerModuleToEdit->wrappedEqualizerStereo->getBandGain( equalizerModuleToEdit->selectedChannel, equalizerModuleToEdit->selectedIndex) + globalGain; toPixelCoordinates(xt, yt); if( RAPT::rsEuclideanDistance(xt, yt, xd, yd) < 3.0 ) return BANDWIDTH_AND_GAIN_RIGHT; } // check if x,y is over the freq/gain handle of some band: for(int i=0; i<equalizerModuleToEdit->getNumBands(equalizerModuleToEdit->selectedChannel); i++) { xt = equalizerModuleToEdit->wrappedEqualizerStereo->getBandFrequency( equalizerModuleToEdit->selectedChannel, i); yt = equalizerModuleToEdit->wrappedEqualizerStereo->getBandGain( equalizerModuleToEdit->selectedChannel, i) + globalGain; toPixelCoordinates(xt, yt); if( RAPT::rsEuclideanDistance(xt, yt, xd, yd) < 4.0 ) return FREQUENCY_AND_GAIN; } if( equalizerModuleToEdit->selectedIndex != -1 ) { // check if y is over the horizontal gain line for the selected band: xt = equalizerModuleToEdit->wrappedEqualizerStereo->getBandFrequency( equalizerModuleToEdit->selectedChannel, equalizerModuleToEdit->selectedIndex); yt = equalizerModuleToEdit->wrappedEqualizerStereo->getBandGain( equalizerModuleToEdit->selectedChannel, equalizerModuleToEdit->selectedIndex) + globalGain; toPixelCoordinates(xt, yt); if( fabs(yt-yd) <= 2.0 ) return GAIN; // check if x is over the vertical frequency line for the selected band: if( fabs(xt-xd) <= 2.0 ) return FREQUENCY; } // check if y is over the global gain line: xt = 1000.0; // dummy; yt = equalizerModuleToEdit->wrappedEqualizerStereo->getGlobalGain(); toPixelCoordinates(xt, yt); if( fabs(y-yt) < 4.0 ) return GLOBALGAIN_LINE; return NONE; } //------------------------------------------------------------------------------------------------- // drawing: void EqualizerPlotEditor::resized() { rsSpectrumPlot::resized(); // (re) allocate and fill the arrays for the magnitude plot numBins = getWidth(); if( frequencies == NULL ) delete[] frequencies; if( magnitudes1 == NULL ) delete[] magnitudes1; if( magnitudes2 == NULL ) delete[] magnitudes2; frequencies = new double[numBins]; magnitudes1 = new double[numBins]; magnitudes2 = new double[numBins]; magnitudes[0] = magnitudes1; magnitudes[1] = magnitudes2; getDisplayedFrequencies(frequencies, numBins); updatePlot(); } void EqualizerPlotEditor::updatePlot() { ScopedPointerLock spl(plugInLock); if( equalizerModuleToEdit == NULL ) { fillWithZeros(magnitudes1, numBins); fillWithZeros(magnitudes2, numBins); } else { equalizerModuleToEdit->getMagnitudeResponse(0, frequencies, magnitudes1, numBins); equalizerModuleToEdit->getMagnitudeResponse(1, frequencies, magnitudes2, numBins); } setSpectra(numBins, 2, frequencies, magnitudes); } void EqualizerPlotEditor::plotCurveFamily(Graphics &g, juce::Image* targetImage, XmlElement *targetSVG) { ScopedPointerLock spl(plugInLock); if( equalizerModuleToEdit == NULL ) return; rsDataPlot::setNumCurves( equalizerModuleToEdit->getNumChannelsToPlot() ); rsDataPlot::plotCurveFamily(g, targetImage, targetSVG); double x, y; // draw the horizontal line for the reference gain: Colour curveColour = plotColourScheme.getCurveColourUniform(0); g.setColour(curveColour); y = equalizerModuleToEdit->wrappedEqualizerStereo->getGlobalGain(); x = 1000.0; toPixelCoordinates(x, y); const float dashLengths[2] = {4.f, 6.f}; g.drawDashedLine(Line<float>(0.f, (float) y, (float) getWidth(), (float) y), dashLengths, 2, 2.f); int channel = equalizerModuleToEdit->selectedChannel; if( equalizerModuleToEdit->getNumChannelsToPlot() == 1 ) channel = 0; // ignore selection in thsi case curveColour = getCurveColour(channel); g.setColour(curveColour); float dotRadius = 4.f; for(int i=0; i<equalizerModuleToEdit->getNumBands(channel); i++) { double globalGain = equalizerModuleToEdit->wrappedEqualizerStereo->getGlobalGain(); x = equalizerModuleToEdit->wrappedEqualizerStereo->getBandFrequency(channel, i); y = equalizerModuleToEdit->wrappedEqualizerStereo->getBandGain(channel, i) + globalGain; toPixelCoordinates(x, y); g.fillEllipse((float) (x-dotRadius), (float) (y-dotRadius), (float) (2*dotRadius), (float) (2*dotRadius) ); if( i == equalizerModuleToEdit->selectedIndex ) { g.setColour(curveColour.withMultipliedAlpha(0.5f)); //g.setColour(Colour(0xff404090).withMultipliedAlpha(0.5f)); g.drawLine((float) x, 0.f, (float) x, (float) getHeight(), 1.f); g.drawLine( 0.f, (float) y, (float) getWidth(), (float) y , 1.f); g.fillEllipse((float) (x-dotRadius-2), (float) (y-dotRadius-2), (float) (2*dotRadius+4), (float) (2*dotRadius+4) ); g.setColour(curveColour.darker(0.5f)); //g.setColour(Colour(0xff404090)); g.fillEllipse((float) (x-dotRadius), (float) (y-dotRadius), (float) (2*dotRadius), (float) (2*dotRadius) ); if( equalizerModuleToEdit->wrappedEqualizerStereo->doesModeSupportBandwidth(channel, i) ) { double x1 = equalizerModuleToEdit->wrappedEqualizerStereo ->getLowerBandedgeFrequency(channel, i); double y1 = equalizerModuleToEdit->wrappedEqualizerStereo ->getBandGain(channel, i) + globalGain; toPixelCoordinates(x1, y1); double x2 = equalizerModuleToEdit->wrappedEqualizerStereo ->getUpperBandedgeFrequency(channel, i); double y2 = equalizerModuleToEdit->wrappedEqualizerStereo ->getBandGain(channel, i) + globalGain; toPixelCoordinates(x2, y2); g.drawLine((float) x1, (float) y1, (float) x2, (float) y1, 2.0f); g.drawLine((float) x1, (float) (y1-5.0), (float) x1, (float) (y1+5.0), 2.0f); g.drawLine((float) x2, (float) (y1-5.0), (float) x2, (float) (y1+5.0), 2.0f); } g.setColour(curveColour); } } } /* void EqualizerPlotEditor::createRightClickPopupMenu(PopupMenu*& menu) { menu = new PopupMenu(); menu->addItem(1, juce::String(T("Insert node: Peak/Dip")) ); menu->addItem(2, juce::String(T("Insert node: Low Shelving")) ); menu->addItem(3, juce::String(T("Insert node: High Shelving")) ); menu->addItem(4, juce::String(T("Insert node: Lowpass 6 dB/oct")) ); menu->addItem(5, juce::String(T("Insert node: Lowpass 12 dB/oct")) ); menu->addItem(6, juce::String(T("Insert node: Highpass 6 dB/oct")) ); menu->addItem(7, juce::String(T("Insert node: Highpass 12 dB/oct")) ); menu->addItem(8, juce::String(T("Insert node: Notch 2*6 dB/oct")) ); } void EqualizerPlotEditor::handleRightClickPopupMenuResult(int result, int x, int y) { ScopedPointerLock spl(plugInLock); if( equalizerModuleToEdit == NULL ) return; double g = (double) y; double f = (double) x; xyToFrequencyAndGain(f, g); switch( result ) { case 1: equalizerModuleToEdit->addBand(rosic::TwoPoleFilter::PEAK, f, g); break; case 2: equalizerModuleToEdit->addBand(rosic::TwoPoleFilter::LOW_SHELF, f, g); break; case 3: equalizerModuleToEdit->addBand(rosic::TwoPoleFilter::HIGH_SHELF, f, g); break; case 4: equalizerModuleToEdit->addBand(rosic::TwoPoleFilter::LOWPASS6, f, g); break; case 5: equalizerModuleToEdit->addBand(rosic::TwoPoleFilter::LOWPASS12, f, g); break; case 6: equalizerModuleToEdit->addBand(rosic::TwoPoleFilter::HIGHPASS6, f, g); break; case 7: equalizerModuleToEdit->addBand(rosic::TwoPoleFilter::HIGHPASS12, f, g); break; case 8: equalizerModuleToEdit->addBand(rosic::TwoPoleFilter::BANDREJECT, f, g); break; } updatePlot(); } void EqualizerPlotEditor::openRightClickPopupMenu(int x, int y) { PopupMenu* menu = NULL; createRightClickPopupMenu(menu); int result = menu->show(); if( menu != NULL ) delete menu; handleRightClickPopupMenuResult(result, x, y); } */ void EqualizerPlotEditor::xyToFrequencyAndGain(double &x, double &y) { ScopedPointerLock spl(plugInLock); if( equalizerModuleToEdit == NULL ) return; double globalGain = equalizerModuleToEdit->wrappedEqualizerStereo->getGlobalGain(); double f = x; double g = y; fromPixelCoordinates(f, g); g -= globalGain; x = f; y = g; } //================================================================================================= rsEqualizerPlotEditor::rsEqualizerPlotEditor(EqualizerAudioModule* eqModule) : equalizerModule(eqModule) { freqRespPlot = new rsFunctionPlot; freqRespPlot->setupForDecibelsAgainstLogFrequency(15.625, 32000.0, -24.0, 24.0, 6); freqRespPlot->addFunction([this](double f)->double { return equalizerModule->getDecibelsAt(0, f); }); freqRespPlot->addFunction([this](double f)->double { return equalizerModule->getDecibelsAt(1, f); }); addPlot(freqRespPlot); nodeEditor = new rsNodeEditor; addWidget(nodeEditor); } void rsEqualizerPlotEditor::nodeWasAdded(rsNodeEditor* editor, int nodeIndex) { } void rsEqualizerPlotEditor::nodeWillBeRemoved(rsNodeEditor* editor, int nodeIndex) { } void rsEqualizerPlotEditor::nodeWasMoved(rsNodeEditor* editor, int nodeIndex) { } //================================================================================================= // construction/destruction: EqualizerModuleEditor::EqualizerModuleEditor(CriticalSection *newPlugInLock, EqualizerAudioModule* newEqualizerAudioModule) : AudioModuleEditor(newEqualizerAudioModule) { ScopedPointerLock spl(lock); equalizerModule = newEqualizerAudioModule; createWidgets(); layout = SLIDERS_RIGHT; useShortSliderNames = false; useSmallComboBox = false; stateWidgetSet->addChangeListener(this); setEqualizerModuleToEdit(newEqualizerAudioModule); setSize(500, 234); // needs to be called before updateWidgetsAccordingToState or we may call resize during paint or soemthing (hits a jassert) updateWidgetsAccordingToState(); } EqualizerModuleEditor::~EqualizerModuleEditor() { if( plotEditor->equalizerModuleToEdit != NULL ) { plotEditor->equalizerModuleToEdit->deRegisterParameterSetObserver(this); //plotEditor->equalizerModuleToEdit->removeStateWatcher(stateWidgetSet); } } //----------------------------------------------------------------------------------------------------------------------------------------- // setup: void EqualizerModuleEditor::setEqualizerModuleToEdit(EqualizerAudioModule* newEqualizerModuleToEdit) { ScopedPointerLock spl(lock); //if( newEqualizerModuleToEdit == plotEditor->equalizerModuleToEdit ) // return; // unassign widgets from parameters of the old equalizer: bypassButton->assignParameter( NULL); stereoModeComboBox->assignParameter(NULL); gainRangeComboBox->assignParameter( NULL); globalGainSlider->assignParameter( NULL); filterModeComboBox->assignParameter(NULL); frequencySlider->assignParameter( NULL); gainSlider->assignParameter( NULL); bandwidthSlider->assignParameter( NULL); if( plotEditor->equalizerModuleToEdit != NULL ) { plotEditor->equalizerModuleToEdit->deRegisterParameterSetObserver(this); plotEditor->equalizerModuleToEdit->removeStateWatcher(stateWidgetSet); } plotEditor->setEqualizerModuleToEdit(newEqualizerModuleToEdit); if( plotEditor->equalizerModuleToEdit != NULL ) { plotEditor->equalizerModuleToEdit->registerParameterSetObserver(this); plotEditor->equalizerModuleToEdit->addStateWatcher(stateWidgetSet); // assign widgets to parameters of the new equalizer (only static parameters - dynamic parameters will be assigned in updateSliders): bypassButton->assignParameter( plotEditor->equalizerModuleToEdit->getParameterByName("Bypass") ); stereoModeComboBox->assignParameter( plotEditor->equalizerModuleToEdit->getParameterByName("StereoMode") ); gainRangeComboBox->assignParameter( plotEditor->equalizerModuleToEdit->getParameterByName("GainRange") ); globalGainSlider->assignParameter( plotEditor->equalizerModuleToEdit->getParameterByName("GlobalGain") ); } updateWidgetsAccordingToState(); } //----------------------------------------------------------------------------------------------------------------------------------------- // setup: void EqualizerModuleEditor::setUseShortSliderNames(bool shouldBeShort) { useShortSliderNames = shouldBeShort; updateWidgetAppearance(); } void EqualizerModuleEditor::setUseSmallComboBox(bool shouldBeSmall) { useSmallComboBox = shouldBeSmall; updateWidgetAppearance(); } //----------------------------------------------------------------------------------------------------------------------------------------- // callbacks: void EqualizerModuleEditor::rButtonClicked(RButton *buttonThatWasClicked) { ScopedPointerLock spl(lock); if( plotEditor->equalizerModuleToEdit == NULL ) return; if( buttonThatWasClicked == channelSelectButton1 || buttonThatWasClicked == channelSelectButton2 ) plotEditor->equalizerModuleToEdit->selectChannel( (bool) channelSelectButton2->getToggleState() ); else AudioModuleEditor::rButtonClicked(buttonThatWasClicked); } void EqualizerModuleEditor::rComboBoxChanged(RComboBox *rComboBoxThatHasChanged) { ScopedPointerLock spl(lock); updateWidgetVisibility(); updateWidgetAppearance(); updatePlotRange(); } void EqualizerModuleEditor::changeListenerCallback(ChangeBroadcaster *objectThatHasChanged) { ScopedPointerLock spl(lock); if( plotEditor->equalizerModuleToEdit == NULL ) return; // the call must have been due to preset recall - deselect band in this case: plotEditor->equalizerModuleToEdit->deSelectBand(); AudioModuleEditor::changeListenerCallback(objectThatHasChanged); /* if( objectThatHasChanged == plotEditor->equalizerModuleToEdit ) { //plotEditor->equalizerModuleToEdit->markStateAsDirty(); // move this call into EqualizerAudioModule updateWidgetsAccordingToState(); // maybe we can get rid of the branch now that we have parameterSetChanged? } else { // the call must have been due to preset recall - deselect band in this case: plotEditor->equalizerModuleToEdit->deSelectBand(); AudioModuleEditor::changeListenerCallback(objectThatHasChanged); } */ } void EqualizerModuleEditor::parameterSetChanged(ParameterSetHolder* parameterSetHolderThatHasChanged) { ScopedPointerLock spl(lock); if( plotEditor->equalizerModuleToEdit == NULL ) return; if( parameterSetHolderThatHasChanged == plotEditor->equalizerModuleToEdit ) updateWidgetsAccordingToState(); } void EqualizerModuleEditor::updateWidgetsAccordingToState() { ScopedPointerLock spl(lock); AudioModuleEditor::updateWidgetsAccordingToState(); if( plotEditor->equalizerModuleToEdit == NULL ) { updateWidgetVisibility(); updateWidgetAppearance(); return; } // un-assign widgets (maybe we should do this first?): filterModeComboBox->assignParameter(nullptr); frequencySlider->assignParameter(nullptr); gainSlider->assignParameter(nullptr); bandwidthSlider->assignParameter(nullptr); // connect the sliders to the parameters of the band selected channel/band: int channel = plotEditor->equalizerModuleToEdit->selectedChannel; int index = plotEditor->equalizerModuleToEdit->selectedIndex; if( index != -1 ) { filterModeComboBox->assignParameter(plotEditor->equalizerModuleToEdit->filterModeParameters[channel][index]); frequencySlider->assignParameter( plotEditor->equalizerModuleToEdit->frequencyParameters[channel][index]); gainSlider->assignParameter( plotEditor->equalizerModuleToEdit->gainParameters[channel][index]); bandwidthSlider->assignParameter( plotEditor->equalizerModuleToEdit->bandwidthParameters[channel][index]); } if( channel == 0 ) channelSelectButton1->setToggleState(true, false); else channelSelectButton2->setToggleState(true, false); updatePlotRange(); updateWidgetVisibility(); updateWidgetAppearance(); plotEditor->assignParametersToSelectedBand(); plotEditor->updatePlot(); } void EqualizerModuleEditor::paint(Graphics &g) { AudioModuleEditor::paint(g); if(layout != SLIDERS_ABOVE) { fillRectWithBilinearGradient(g, rightSectionRectangle, editorColourScheme.topLeft, editorColourScheme.topRight, editorColourScheme.bottomLeft, editorColourScheme.bottomRight); fillRectWithBilinearGradient(g, bottomSectionRectangle, editorColourScheme.topLeft, editorColourScheme.topRight, editorColourScheme.bottomLeft, editorColourScheme.bottomRight); g.setColour(editorColourScheme.outline); g.drawRect(rightSectionRectangle); g.drawRect(bottomSectionRectangle); } // ...this could actually be done in the baseclass via the guiRectangles array, i think /* // gray out the editor if it's disabled: if( !isEnabled() ) g.fillAll(Colours::lightgrey.withAlpha(0.75f)); */ } void EqualizerModuleEditor::resized() { AudioModuleEditor::resized(); int x = 0; int y = getPresetSectionBottom(); int w = getWidth(); int h = getHeight(); if( layout == SLIDERS_RIGHT ) { // the size/position computations are a mess - improve! bandParametersLabel->setVisible(true); int rightSectionWidth = 128; int bottomSectionHeight = 24; x = w-rightSectionWidth; h = infoField->getY() - y - bottomSectionHeight; rightSectionRectangle.setBounds(x, y+4, rightSectionWidth, h-4); x = rightSectionRectangle.getX(); y = rightSectionRectangle.getY(); w = rightSectionRectangle.getWidth(); y = rightSectionRectangle.getY(); bandParametersLabel->setBounds(x+4, y+4, w-8, 16); y += 24; filterModeComboBox->setNameLabelPosition(RNamedComboBox::ABOVE_BOX); filterModeComboBox->setBounds(x+4, y+4, w-8, 32); y += 40; frequencySlider->setLayout(RSlider::NAME_ABOVE); frequencySlider->setBounds(x+4, y+4, w-8, 32); y += 36; gainSlider->setLayout(RSlider::NAME_ABOVE); gainSlider->setBounds(x+4, y+4, w-8, 32); y += 36; bandwidthSlider->setLayout(RSlider::NAME_ABOVE); bandwidthSlider->setBounds(x+4, y+4, w-8, 32); y = rightSectionRectangle.getBottom()-2*16-8; //globalGainSlider->setLayout(RSlider::NAME_ABOVE); //globalGainSlider->setBounds(x+4, y+4, w-8, 32); x = 0; w = rightSectionRectangle.getX()-x; y = getPresetSectionBottom(); h = infoField->getY() - y - bottomSectionHeight; plotEditor->setBounds(x, y+4, w+2, h-4); // new widgets for v10.04: y = plotEditor->getBottom()-2; bottomSectionRectangle.setBounds(0, y, getWidth(), bottomSectionHeight+4); x = bottomSectionRectangle.getX(); y += 1; bypassButton->setBounds(x+4, y+4, 60, 16); stereoModeComboBox->setBounds(bypassButton->getRight()+4, y+4, 180, 16); channelSelectButton1->setBounds(stereoModeComboBox->getRight()+4, y+4, 16, 16); channelSelectButton2->setBounds(channelSelectButton1->getRight()-2, y+4, 16, 16); x = rightSectionRectangle.getX(); w = rightSectionRectangle.getWidth(); globalGainSlider->setBounds(x+4, y+4, w-8, 16); w = 92; gainRangeComboBox->setBounds(globalGainSlider->getX()-w-4, y+4, w, 16); } if( layout == SLIDERS_BELOW ) { bandParametersLabel->setVisible(false); // correct? x = 0; w = getWidth(); y = getPresetSectionBottom(); h = getHeight()-40-y; plotEditor->setBounds(4, y+4, w-8, h-8); y = plotEditor->getBottom(); w = getWidth()/3; frequencySlider->setBounds(x+4, y+4, w-4, 16); x = frequencySlider->getRight(); gainSlider->setBounds(x+4, y+4, w-4, 16); x = gainSlider->getRight(); w = getWidth()-x; bandwidthSlider->setBounds(x+4, y+4, w-8, 16); y += 20; filterModeComboBox->setNameLabelPosition(RNamedComboBox::LEFT_TO_BOX); filterModeComboBox->setBounds(4, y+4, 120, 16); //modeLabel->setBounds(4, y+4, 40, 16); //filterModeComboBox->setBounds(modeLabel->getRight(), y+4, 120, 16); x = filterModeComboBox->getRight(); w = getWidth()-x; globalGainSlider->setBounds(x+4, y+4, w-8, 16); //useShortSliderNames = true; /* globalGainSlider->setSliderName(juce::String(T("GG"))); frequencySlider->setSliderName(juce::String(T("F"))); gainSlider->setSliderName(juce::String(T("G"))); bandwidthSlider->setSliderName(juce::String(T("B"))); */ } if( layout == SLIDERS_ABOVE ) { bandParametersLabel->setVisible(false); //x = getHeadlineRight()+40; x = getWidth()/2; w = getWidth()-x; //globalGainSlider->setBounds(x+4, y+4, w-8, 16); //stateWidgetSet->stateFileNameLabel->setVisible(false); stateWidgetSet->stateFileNameLabel->setVisible(true); //x = stateWidgetSet->stateSaveButton->getX()-16-80; //x += stateWidgetSet->getX(); //globalGainSlider->setBounds(x, 6, 80, 16); x = getHeadlineRight() + 4; w = stateWidgetSet->getX() - x - 8; globalGainSlider->setBounds(x, 6, w, 16); x = 0; y = getPresetSectionBottom(); filterModeComboBox->setBounds(x+4, y+4, 80, 16); x = filterModeComboBox->getRight(); w = (getWidth()-x) /4; frequencySlider->setBounds(x+4, y+4, w-4, 16); x = frequencySlider->getRight(); gainSlider->setBounds(x+4, y+4, w-4, 16); x = gainSlider->getRight(); bandwidthSlider->setBounds(x+4, y+4, w-4, 16); x = bandwidthSlider->getRight(); w = getWidth() - x; globalGainSlider->setBounds(x+4, y+4, w-8, 16); y = gainSlider->getBottom()+4; w = getWidth(); h = getHeight()-y; plotEditor->setBounds(0, y, w, h); /* globalGainSlider->setSliderName(juce::String(T("GG"))); frequencySlider->setSliderName(juce::String(T("F"))); gainSlider->setSliderName(juce::String(T("G"))); bandwidthSlider->setSliderName(juce::String(T("B"))); filterModeComboBox->setItemText(2, juce::String(T("Low Shelf"))); filterModeComboBox->setItemText(3, juce::String(T("High Shelf"))); filterModeComboBox->setItemText(4, juce::String(T("Lowpass 6"))); filterModeComboBox->setItemText(5, juce::String(T("Lowpass 12"))); filterModeComboBox->setItemText(6, juce::String(T("Highpass 6"))); filterModeComboBox->setItemText(7, juce::String(T("Highpass 12"))); filterModeComboBox->setItemText(8, juce::String(T("Notch"))); */ } updateWidgetVisibility(); updateWidgetAppearance(); } void EqualizerModuleEditor::createWidgets() { typedef rsModulatableSlider Sld; typedef RNamedComboBox Box; typedef rsAutomatableButton Btn; Sld* s; //Box* c; Btn* b; addWidget( bypassButton = b = new Btn("Bypass") ); b->setDescription("Bypass the whole equalizer"); b->setDescriptionField(infoField); b->setClickingTogglesState(true); //...? do we need this ? ...set this active by default in RButton addWidget( channelSelectButton1 = new RRadioButton("L") ); channelSelectButton1->setDescription("Edit left channel curve"); channelSelectButton1->setDescriptionField(infoField); channelSelectButton1->setClickingTogglesState(true); channelSelectButton1->addRButtonListener(this); //channelSelectButton1->setRadioGroupId(1); // \todo: make this work again channelSelectButton1->addToRadioButtonGroup(&channelSelectRadioGroup); channelSelectButton1->setToggleState(true, false); addWidget( channelSelectButton2 = new RRadioButton("R") ); channelSelectButton2->setDescription("Edit right channel curve"); channelSelectButton2->setDescriptionField(infoField); channelSelectButton2->setClickingTogglesState(true); channelSelectButton2->addRButtonListener(this); //channelSelectButton2->setRadioGroupId(1); // \todo: make this work again channelSelectButton2->addToRadioButtonGroup(&channelSelectRadioGroup); channelSelectButton2->setToggleState(false, false); addWidget( stereoModeComboBox = new RNamedComboBox(juce::String("StereoModeComboBox"), juce::String("Stereo Mode:")) ); stereoModeComboBox->setDescription("Select mode for processing stereo signals"); stereoModeComboBox->setDescriptionField(infoField); stereoModeComboBox->registerComboBoxObserver(this); addWidget( gainRangeComboBox = new RNamedComboBox(juce::String("RangeComboBox"), juce::String("Range:")) ); gainRangeComboBox->setDescription("Select the range for the plot"); gainRangeComboBox->setDescriptionField(infoField); gainRangeComboBox->registerComboBoxObserver(this); addWidget( globalGainSlider = s = new Sld ); s->setDescription("Global gain to compensate for loudness change"); s->setDescriptionField(infoField); s->setStringConversionFunction(&decibelsToStringWithUnit1); addWidget( bandParametersLabel = new RTextField("Band Parameters") ); bandParametersLabel->setDescription("Parameters for th selected band"); bandParametersLabel->setDescriptionField(infoField); bandParametersLabel->setJustification(Justification::centred); bandParametersLabel->setNoBackgroundAndOutline(true); addWidget( filterModeComboBox = new RNamedComboBox(juce::String("FilterModeComboBox"), juce::String("Mode:")) ); filterModeComboBox->setDescription("Filter mode of selected band"); filterModeComboBox->setDescriptionField(infoField); filterModeComboBox->registerComboBoxObserver(this); addWidget( frequencySlider = new Sld ); frequencySlider->setSliderName(juce::String("Frequency")); frequencySlider->setDescription(juce::String("Frequency of selected band")); frequencySlider->setDescriptionField(infoField); frequencySlider->setStringConversionFunction(&hertzToStringWithUnitTotal5); addWidget( gainSlider = new Sld ); gainSlider->setSliderName(juce::String("Gain")); gainSlider->setDescription(juce::String("Gain of selected band")); gainSlider->setDescriptionField(infoField); gainSlider->setStringConversionFunction(&decibelsToStringWithUnit1); addWidget( bandwidthSlider = new Sld ); bandwidthSlider->setSliderName(juce::String("Bandwidth")); bandwidthSlider->setDescription(juce::String("Bandwidth of selected band")); bandwidthSlider->setDescriptionField(infoField); bandwidthSlider->setStringConversionFunction(&octavesToStringWithUnit2); plotEditor = new EqualizerPlotEditor(lock, equalizerModule); plotEditor->setDescriptionField(infoField); //plotEditor->addChangeListener(this); //if( equalizerModuleToEdit != NULL ) // plotEditor->setEqualizerToEdit(equalizerModuleToEdit->wrappedEqualizer); addPlot( plotEditor ); } void EqualizerModuleEditor::updateWidgetVisibility() { ScopedPointerLock spl(lock); frequencySlider->setVisible( false); gainSlider->setVisible( false); bandwidthSlider->setVisible( false); filterModeComboBox->setVisible( false); channelSelectButton1->setVisible(false); channelSelectButton2->setVisible(false); globalGainSlider->setVisible( false); stateWidgetSet->setVisible( false); if( plotEditor->equalizerModuleToEdit == NULL ) return; globalGainSlider->setVisible( true); stateWidgetSet->setVisible( true); int channel = plotEditor->equalizerModuleToEdit->selectedChannel; int index = plotEditor->equalizerModuleToEdit->selectedIndex; if( index != -1 ) { filterModeComboBox->setVisible(true); frequencySlider->setVisible(true); if( plotEditor->equalizerModuleToEdit->wrappedEqualizerStereo->doesModeSupportBandwidth(channel, index) ) bandwidthSlider->setVisible(true); if( plotEditor->equalizerModuleToEdit->wrappedEqualizerStereo->doesModeSupportGain(channel, index) ) gainSlider->setVisible(true); } } void EqualizerModuleEditor::updateWidgetAppearance() { ScopedPointerLock spl(lock); if( plotEditor->equalizerModuleToEdit == NULL ) return; if( plotEditor->equalizerModuleToEdit->wrappedEqualizerStereo->getStereoMode() == rosic::EqualizerStereo::LEFT_RIGHT ) { channelSelectButton1->setVisible(true); channelSelectButton2->setVisible(true); channelSelectButton1->setButtonText("L"); channelSelectButton2->setButtonText("R"); channelSelectButton1->setDescription(juce::String("Edit curve for left channel")); channelSelectButton2->setDescription(juce::String("Edit curve for right channel")); } else if( plotEditor->equalizerModuleToEdit->wrappedEqualizerStereo->getStereoMode() == rosic::EqualizerStereo::MID_SIDE ) { channelSelectButton1->setVisible(true); channelSelectButton2->setVisible(true); channelSelectButton1->setButtonText("M"); channelSelectButton2->setButtonText("S"); channelSelectButton1->setDescription(juce::String("Edit curve for mid channel")); channelSelectButton2->setDescription(juce::String("Edit curve for side channel")); } if( useShortSliderNames == true ) { globalGainSlider->setSliderName("GG"); frequencySlider->setSliderName( "F"); gainSlider->setSliderName( "G"); bandwidthSlider->setSliderName( "B"); // currently, when we use short names, we also want the compact layout: globalGainSlider->setLayout(RSlider::NAME_INSIDE); frequencySlider->setLayout( RSlider::NAME_INSIDE); gainSlider->setLayout( RSlider::NAME_INSIDE); bandwidthSlider->setLayout( RSlider::NAME_INSIDE); } if( useSmallComboBox == true ) { filterModeComboBox->setNameLabelWidth(0); // workaround because INVISIBLE doesn't work filterModeComboBox->setNameLabelPosition(RNamedComboBox::LEFT_TO_BOX); filterModeComboBox->setItemText(2, "Low Shelf"); filterModeComboBox->setItemText(3, "High Shelf"); filterModeComboBox->setItemText(4, "Lowpass 6"); filterModeComboBox->setItemText(5, "Lowpass 12"); filterModeComboBox->setItemText(6, "Highpass 6"); filterModeComboBox->setItemText(7, "Highpass 12"); filterModeComboBox->setItemText(8, "Notch"); } } void EqualizerModuleEditor::updatePlotRange() { int rangeIndex = (int) plotEditor->equalizerModuleToEdit->getParameterByName( juce::String("GainRange"))->getValue(); switch( rangeIndex ) { case 0: { plotEditor->setCurrentRangeY( -3.0, +3.0); plotEditor->setHorizontalCoarseGrid(1.0, true); } break; case 1: { plotEditor->setCurrentRangeY( -6.0, +6.0); plotEditor->setHorizontalCoarseGrid(2.0, true); } break; case 2: { plotEditor->setCurrentRangeY(-12.0, +12.0); plotEditor->setHorizontalCoarseGrid(3.0, true); } break; case 3: { plotEditor->setCurrentRangeY(-24.0, +24.0); plotEditor->setHorizontalCoarseGrid(6.0, true); } break; case 4: { plotEditor->setCurrentRangeY(-48.0, +48.0); plotEditor->setHorizontalCoarseGrid(12.0, true); } break; } plotEditor->updatePlot(); } /* maybe parametrize a biquad via: -midFreq, midGain, midWidth (regular bell filter params) -lowGain, highGain (would be 0 dB in bell EQ, -inf in BP, 0,-inf in LP etc) -or maybe instead of lowGain/highGain have meanGain and gainDelta -lowGain/highGain would apply to 0 and infinite freq */
34.985173
144
0.70335
[ "object", "vector" ]
9c8ee01a6da348af807dc0839cf462d9f6523eb3
7,165
cpp
C++
Applications/Utils/MeshEdit/moveMeshNodes.cpp
HaibingShao/ogs6_ufz
d4acfe7132eaa2010157122da67c7a4579b2ebae
[ "BSD-4-Clause" ]
null
null
null
Applications/Utils/MeshEdit/moveMeshNodes.cpp
HaibingShao/ogs6_ufz
d4acfe7132eaa2010157122da67c7a4579b2ebae
[ "BSD-4-Clause" ]
null
null
null
Applications/Utils/MeshEdit/moveMeshNodes.cpp
HaibingShao/ogs6_ufz
d4acfe7132eaa2010157122da67c7a4579b2ebae
[ "BSD-4-Clause" ]
null
null
null
/** * \file moveMeshNodes.cpp * 2012/03/07 KR Initial implementation * * \copyright * Copyright (c) 2012-2017, OpenGeoSys Community (http://www.opengeosys.org) * Distributed under a Modified BSD License. * See accompanying file LICENSE.txt or * http://www.opengeosys.org/LICENSE.txt */ #include <memory> #include <string> #include "Applications/ApplicationsLib/LogogSetup.h" #include "BaseLib/FileTools.h" #include "GeoLib/AABB.h" #include "MeshLib/IO/readMeshFromFile.h" #include "MeshLib/IO/writeMeshToFile.h" #include "MeshLib/Mesh.h" #include "MeshLib/Node.h" #include "MathLib/MathTools.h" int find_closest_point(MeshLib::Node const*const point, std::vector<MeshLib::Node*> const& nodes, double const& max_dist) { const std::size_t nNodes (nodes.size()); double sqr_shortest_dist (max_dist*2); int idx = (sqr_shortest_dist<max_dist) ? 0 : -1; const MeshLib::Node p (*point); for (unsigned i=0; i<nNodes; i++) { double sqr_dist ((p[0]-(*nodes[i])[0])*(p[0]-(*nodes[i])[0])); if (sqr_dist < max_dist) { sqr_dist += ((p[1]-(*nodes[i])[1])*(p[1]-(*nodes[i])[1])); if (sqr_dist < max_dist && sqr_dist < sqr_shortest_dist) { sqr_shortest_dist = sqr_dist; idx = i; } } } return idx; } bool containsPoint(MeshLib::Node const& pnt, MathLib::Point3d const& min, MathLib::Point3d const& max) { if (pnt[0] < min[0] || max[0] < pnt[0]) return false; if (pnt[1] < min[1] || max[1] < pnt[1]) return false; return true; } int main (int argc, char* argv[]) { ApplicationsLib::LogogSetup logog_setup; std::vector<std::string> keywords; keywords.push_back("-ALL"); keywords.push_back("-MESH"); keywords.push_back("-LOWPASS"); if (argc < 3) { INFO( "Moves mesh nodes and connected elements either by a given value " "or based on a list.\n"); INFO("Usage: %s <msh-file.msh> <keyword> [<value1>] [<value2>]", argv[0]); INFO("Available keywords:"); INFO( "\t-ALL <value1> <value2> : changes the elevation of all mesh " "nodes by <value2> in direction <value1> [x,y,z]."); INFO( "\t-MESH <value1> <value2> : changes the elevation of mesh nodes " "based on a second mesh <value1> with a search range of <value2>."); INFO( "\t-LOWPASS : applies a lowpass filter over node elevation using " "directly connected nodes."); return EXIT_FAILURE; } const std::string msh_name(argv[1]); const std::string current_key(argv[2]); std::string const ext (BaseLib::getFileExtension(msh_name)); if (!(ext == "msh" || ext == "vtu")) { ERR("Error: Parameter 1 must be a mesh-file (*.msh / *.vtu)."); INFO("Usage: %s <msh-file.gml> <keyword> <value>", argv[0]); return EXIT_FAILURE; } bool is_keyword(false); for (auto & keyword : keywords) if (current_key.compare(keyword)==0) { is_keyword = true; break; } if (!is_keyword) { ERR("Keyword not recognised. Available keywords:"); for (auto const& keyword : keywords) INFO("\t%s", keyword.c_str()); return EXIT_FAILURE; } std::unique_ptr<MeshLib::Mesh> mesh (MeshLib::IO::readMeshFromFile(msh_name)); if (mesh == nullptr) { ERR ("Error reading mesh file."); return 1; } // Start keyword-specific selection of nodes // moves the elevation of all nodes by value if (current_key.compare("-ALL")==0) { if (argc < 5) { ERR("Missing parameter..."); return EXIT_FAILURE; } const std::string dir(argv[3]); unsigned idx = (dir.compare("x") == 0) ? 0 : (dir.compare("y") == 0) ? 1 : 2; const double value(strtod(argv[4],0)); INFO("Moving all mesh nodes by %g in direction %d (%s)...", value, idx, dir.c_str()); //double value(-10); const std::size_t nNodes(mesh->getNumberOfNodes()); std::vector<MeshLib::Node*> nodes (mesh->getNodes()); for (std::size_t i=0; i<nNodes; i++) { (*nodes[i])[idx] += value; } } // maps the elevation of mesh nodes according to a ground truth mesh whenever nodes exist within max_dist if (current_key.compare("-MESH")==0) { if (argc < 5) { ERR("Missing parameter..."); return EXIT_FAILURE; } const std::string value (argv[3]); double max_dist(pow(strtod(argv[4],0), 2)); double offset (0.0); // additional offset for elevation (should be 0) std::unique_ptr<MeshLib::Mesh> ground_truth (MeshLib::IO::readMeshFromFile(value)); if (ground_truth == nullptr) { ERR ("Error reading mesh file."); return EXIT_FAILURE; } const std::vector<MeshLib::Node*>& ground_truth_nodes (ground_truth->getNodes()); GeoLib::AABB bounding_box(ground_truth_nodes.begin(), ground_truth_nodes.end()); MathLib::Point3d const& min(bounding_box.getMinPoint()); MathLib::Point3d const& max(bounding_box.getMaxPoint()); const std::size_t nNodes(mesh->getNumberOfNodes()); std::vector<MeshLib::Node*> nodes (mesh->getNodes()); for (std::size_t i=0; i<nNodes; i++) { bool is_inside (containsPoint(*nodes[i], min, max)); if (is_inside) { int idx = find_closest_point(nodes[i], ground_truth_nodes, max_dist); if (idx>=0) (*nodes[i])[2] = (*(ground_truth_nodes[idx]))[2]-offset; } } } // a simple lowpass filter for the elevation of mesh nodes using the elevation of each node // weighted by 2 and the elevation of each connected node weighted by 1 if (current_key.compare("-LOWPASS")==0) { const std::size_t nNodes(mesh->getNumberOfNodes()); std::vector<MeshLib::Node*> nodes (mesh->getNodes()); std::vector<double> elevation(nNodes); for (std::size_t i=0; i<nNodes; i++) elevation[i] = (*nodes[i])[2]; for (std::size_t i=0; i<nNodes; i++) { const std::vector<MeshLib::Node*> conn_nodes (nodes[i]->getConnectedNodes()); const unsigned nConnNodes (conn_nodes.size()); elevation[i] = (2*(*nodes[i])[2]); for (std::size_t j=0; j<nConnNodes; ++j) elevation[i] += (*conn_nodes[j])[2]; elevation[i] /= (nConnNodes+2); } for (std::size_t i=0; i<nNodes; i++) (*nodes[i])[2] = elevation[i]; } /**** add other keywords here ****/ std::string const new_mesh_name (msh_name.substr(0, msh_name.length() - 4) + "_new.vtu"); if (MeshLib::IO::writeMeshToFile(*mesh, new_mesh_name) != 0) return EXIT_FAILURE; INFO ("Result successfully written.") return EXIT_SUCCESS; }
33.018433
121
0.568876
[ "mesh", "vector" ]
9c9265223d607d5fad329353a4bd87b8a4af689c
26,112
cpp
C++
src/core/qgsvectorlayereditbuffer.cpp
dyna-mis/Hilabeling
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
[ "MIT" ]
null
null
null
src/core/qgsvectorlayereditbuffer.cpp
dyna-mis/Hilabeling
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
[ "MIT" ]
null
null
null
src/core/qgsvectorlayereditbuffer.cpp
dyna-mis/Hilabeling
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
[ "MIT" ]
1
2021-12-25T08:40:30.000Z
2021-12-25T08:40:30.000Z
/*************************************************************************** qgsvectorlayereditbuffer.cpp --------------------- begin : Dezember 2012 copyright : (C) 2012 by Martin Dobias email : wonder dot sk at gmail dot com *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "qgsvectorlayereditbuffer.h" #include "qgsgeometry.h" #include "qgslogger.h" #include "qgsvectorlayerundocommand.h" #include "qgsvectordataprovider.h" #include "qgsvectorlayer.h" #include "qgsvectorlayerutils.h" //! populate two lists (ks, vs) from map - in reverse order template <class Key, class T> void mapToReversedLists( const QMap< Key, T > &map, QList<Key> &ks, QList<T> &vs ) { ks.reserve( map.size() ); vs.reserve( map.size() ); typename QMap<Key, T>::const_iterator i = map.constEnd(); while ( i-- != map.constBegin() ) { ks.append( i.key() ); vs.append( i.value() ); } } QgsVectorLayerEditBuffer::QgsVectorLayerEditBuffer( QgsVectorLayer *layer ) : L( layer ) { connect( L->undoStack(), &QUndoStack::indexChanged, this, &QgsVectorLayerEditBuffer::undoIndexChanged ); // TODO[MD]: queued? } bool QgsVectorLayerEditBuffer::isModified() const { return !L->undoStack()->isClean(); } void QgsVectorLayerEditBuffer::undoIndexChanged( int index ) { QgsDebugMsgLevel( QStringLiteral( "undo index changed %1" ).arg( index ), 4 ); Q_UNUSED( index ); emit layerModified(); } void QgsVectorLayerEditBuffer::updateFields( QgsFields &fields ) { // delete attributes from the higher indices to lower indices for ( int i = mDeletedAttributeIds.count() - 1; i >= 0; --i ) { fields.remove( mDeletedAttributeIds.at( i ) ); } // rename fields QgsFieldNameMap::const_iterator renameIt = mRenamedAttributes.constBegin(); for ( ; renameIt != mRenamedAttributes.constEnd(); ++renameIt ) { fields.rename( renameIt.key(), renameIt.value() ); } // add new fields for ( int i = 0; i < mAddedAttributes.count(); ++i ) { fields.append( mAddedAttributes.at( i ), QgsFields::OriginEdit, i ); } } void QgsVectorLayerEditBuffer::updateFeatureGeometry( QgsFeature &f ) { if ( mChangedGeometries.contains( f.id() ) ) f.setGeometry( mChangedGeometries[f.id()] ); } void QgsVectorLayerEditBuffer::updateChangedAttributes( QgsFeature &f ) { QgsAttributes attrs = f.attributes(); // remove all attributes that will disappear - from higher indices to lower for ( int idx = mDeletedAttributeIds.count() - 1; idx >= 0; --idx ) { attrs.remove( mDeletedAttributeIds[idx] ); } // adjust size to accommodate added attributes attrs.resize( attrs.count() + mAddedAttributes.count() ); // update changed attributes if ( mChangedAttributeValues.contains( f.id() ) ) { const QgsAttributeMap &map = mChangedAttributeValues[f.id()]; for ( QgsAttributeMap::const_iterator it = map.begin(); it != map.end(); ++it ) attrs[it.key()] = it.value(); } f.setAttributes( attrs ); } bool QgsVectorLayerEditBuffer::addFeature( QgsFeature &f ) { if ( !( L->dataProvider()->capabilities() & QgsVectorDataProvider::AddFeatures ) ) { return false; } if ( L->mFields.count() != f.attributes().count() ) return false; // TODO: check correct geometry type L->undoStack()->push( new QgsVectorLayerUndoCommandAddFeature( this, f ) ); return true; } bool QgsVectorLayerEditBuffer::addFeatures( QgsFeatureList &features ) { if ( !( L->dataProvider()->capabilities() & QgsVectorDataProvider::AddFeatures ) ) return false; bool result = true; for ( QgsFeatureList::iterator iter = features.begin(); iter != features.end(); ++iter ) { result = result && addFeature( *iter ); } L->updateExtents(); return result; } bool QgsVectorLayerEditBuffer::deleteFeature( QgsFeatureId fid ) { if ( !( L->dataProvider()->capabilities() & QgsVectorDataProvider::DeleteFeatures ) ) { QgsDebugMsg( QStringLiteral( "Cannot delete features (missing DeleteFeature capability)" ) ); return false; } if ( FID_IS_NEW( fid ) ) { if ( !mAddedFeatures.contains( fid ) ) { QgsDebugMsg( QStringLiteral( "Cannot delete features (in the list of added features)" ) ); return false; } } else // existing feature { if ( mDeletedFeatureIds.contains( fid ) ) { QgsDebugMsg( QStringLiteral( "Cannot delete features (in the list of deleted features)" ) ); return false; } } L->undoStack()->push( new QgsVectorLayerUndoCommandDeleteFeature( this, fid ) ); return true; } bool QgsVectorLayerEditBuffer::deleteFeatures( const QgsFeatureIds &fids ) { if ( !( L->dataProvider()->capabilities() & QgsVectorDataProvider::DeleteFeatures ) ) { QgsDebugMsg( QStringLiteral( "Cannot delete features (missing DeleteFeatures capability)" ) ); return false; } bool ok = true; const auto constFids = fids; for ( QgsFeatureId fid : constFids ) ok = deleteFeature( fid ) && ok; return ok; } bool QgsVectorLayerEditBuffer::changeGeometry( QgsFeatureId fid, const QgsGeometry &geom ) { if ( !L->isSpatial() ) { return false; } if ( FID_IS_NEW( fid ) ) { if ( !mAddedFeatures.contains( fid ) ) return false; } else if ( !( L->dataProvider()->capabilities() & QgsVectorDataProvider::ChangeGeometries ) ) return false; // TODO: check compatible geometry L->undoStack()->push( new QgsVectorLayerUndoCommandChangeGeometry( this, fid, geom ) ); return true; } bool QgsVectorLayerEditBuffer::changeAttributeValues( QgsFeatureId fid, const QgsAttributeMap &newValues, const QgsAttributeMap &oldValues ) { bool success = true; for ( auto it = newValues.constBegin() ; it != newValues.constEnd(); ++it ) { const int field = it.key(); const QVariant newValue = it.value(); QVariant oldValue; if ( oldValues.contains( field ) ) oldValue = oldValues[field]; success &= changeAttributeValue( fid, field, newValue, oldValue ); } return success; } bool QgsVectorLayerEditBuffer::changeAttributeValue( QgsFeatureId fid, int field, const QVariant &newValue, const QVariant &oldValue ) { if ( FID_IS_NEW( fid ) ) { if ( !mAddedFeatures.contains( fid ) ) return false; } else if ( !( L->dataProvider()->capabilities() & QgsVectorDataProvider::ChangeAttributeValues ) ) { return false; } if ( field < 0 || field >= L->fields().count() || L->fields().fieldOrigin( field ) == QgsFields::OriginJoin || L->fields().fieldOrigin( field ) == QgsFields::OriginExpression ) return false; L->undoStack()->push( new QgsVectorLayerUndoCommandChangeAttribute( this, fid, field, newValue, oldValue ) ); return true; } bool QgsVectorLayerEditBuffer::addAttribute( const QgsField &field ) { if ( !( L->dataProvider()->capabilities() & QgsVectorDataProvider::AddAttributes ) ) return false; if ( field.name().isEmpty() ) return false; const QgsFields fields = L->fields(); for ( const QgsField &updatedField : fields ) { if ( updatedField.name() == field.name() ) return false; } if ( !L->dataProvider()->supportedType( field ) ) return false; L->undoStack()->push( new QgsVectorLayerUndoCommandAddAttribute( this, field ) ); return true; } bool QgsVectorLayerEditBuffer::deleteAttribute( int index ) { if ( !( L->dataProvider()->capabilities() & QgsVectorDataProvider::DeleteAttributes ) ) return false; if ( index < 0 || index >= L->fields().count() ) return false; // find out source of the field QgsFields::FieldOrigin origin = L->fields().fieldOrigin( index ); int originIndex = L->fields().fieldOriginIndex( index ); if ( origin == QgsFields::OriginProvider && mDeletedAttributeIds.contains( originIndex ) ) return false; if ( origin == QgsFields::OriginJoin ) return false; L->undoStack()->push( new QgsVectorLayerUndoCommandDeleteAttribute( this, index ) ); return true; } bool QgsVectorLayerEditBuffer::renameAttribute( int index, const QString &newName ) { if ( !( L->dataProvider()->capabilities() & QgsVectorDataProvider::RenameAttributes ) ) return false; if ( newName.isEmpty() ) return false; if ( index < 0 || index >= L->fields().count() ) return false; const QgsFields fields = L->fields(); for ( const QgsField &updatedField : fields ) { if ( updatedField.name() == newName ) return false; } L->undoStack()->push( new QgsVectorLayerUndoCommandRenameAttribute( this, index, newName ) ); return true; } bool QgsVectorLayerEditBuffer::commitChanges( QStringList &commitErrors ) { QgsVectorDataProvider *provider = L->dataProvider(); commitErrors.clear(); int cap = provider->capabilities(); bool success = true; // geometry updates attribute updates // yes no => changeGeometryValues // no yes => changeAttributeValues // yes yes => changeFeatures // to fix https://issues.qgis.org/issues/15741 // first of all check if feature to add is compatible with provider type // this check have to be done before all checks to avoid to clear internal // buffer if some of next steps success. if ( success && !mAddedFeatures.isEmpty() ) { if ( cap & QgsVectorDataProvider::AddFeatures ) { if ( provider->doesStrictFeatureTypeCheck() ) { for ( const auto &f : qgis::as_const( mAddedFeatures ) ) { if ( ( ! f.hasGeometry() ) || ( f.geometry().wkbType() == provider->wkbType() ) ) continue; if ( provider->convertToProviderType( f.geometry() ).isNull() ) { commitErrors << tr( "ERROR: %n feature(s) not added - geometry type is not compatible with the current layer.", "not added features count", mAddedFeatures.size() ); success = false; break; } } } } else { commitErrors << tr( "ERROR: %n feature(s) not added - provider doesn't support adding features.", "not added features count", mAddedFeatures.size() ); success = false; } } // // update geometries // if ( !mChangedGeometries.isEmpty() && ( ( cap & QgsVectorDataProvider::ChangeFeatures ) == 0 || mChangedAttributeValues.isEmpty() ) ) { if ( provider->changeGeometryValues( mChangedGeometries ) ) { commitErrors << tr( "SUCCESS: %n geometries were changed.", "changed geometries count", mChangedGeometries.size() ); emit committedGeometriesChanges( L->id(), mChangedGeometries ); mChangedGeometries.clear(); } else { commitErrors << tr( "ERROR: %n geometries not changed.", "not changed geometries count", mChangedGeometries.size() ); success = false; } } QgsFields oldFields = L->fields(); // // delete attributes // bool attributesChanged = false; if ( !mDeletedAttributeIds.isEmpty() ) { if ( ( cap & QgsVectorDataProvider::DeleteAttributes ) && provider->deleteAttributes( mDeletedAttributeIds.toSet() ) ) { commitErrors << tr( "SUCCESS: %n attribute(s) deleted.", "deleted attributes count", mDeletedAttributeIds.size() ); emit committedAttributesDeleted( L->id(), mDeletedAttributeIds ); mDeletedAttributeIds.clear(); attributesChanged = true; } else { commitErrors << tr( "ERROR: %n attribute(s) not deleted.", "not deleted attributes count", mDeletedAttributeIds.size() ); #if 0 QString list = "ERROR: Pending attribute deletes:"; const auto constMDeletedAttributeIds = mDeletedAttributeIds; for ( int idx : constMDeletedAttributeIds ) { list.append( ' ' + L->fields().at( idx ).name() ); } commitErrors << list; #endif success = false; } } // rename attributes if ( !mRenamedAttributes.isEmpty() ) { if ( ( cap & QgsVectorDataProvider::RenameAttributes ) && provider->renameAttributes( mRenamedAttributes ) ) { commitErrors << tr( "SUCCESS: %n attribute(s) renamed.", "renamed attributes count", mRenamedAttributes.size() ); emit committedAttributesRenamed( L->id(), mRenamedAttributes ); mRenamedAttributes.clear(); attributesChanged = true; } else { commitErrors << tr( "ERROR: %n attribute(s) not renamed", "not renamed attributes count", mRenamedAttributes.size() ); success = false; } } // // add attributes // if ( !mAddedAttributes.isEmpty() ) { if ( ( cap & QgsVectorDataProvider::AddAttributes ) && provider->addAttributes( mAddedAttributes ) ) { commitErrors << tr( "SUCCESS: %n attribute(s) added.", "added attributes count", mAddedAttributes.size() ); emit committedAttributesAdded( L->id(), mAddedAttributes ); mAddedAttributes.clear(); attributesChanged = true; } else { commitErrors << tr( "ERROR: %n new attribute(s) not added", "not added attributes count", mAddedAttributes.size() ); #if 0 QString list = "ERROR: Pending adds:"; const auto constMAddedAttributes = mAddedAttributes; for ( QgsField f : constMAddedAttributes ) { list.append( ' ' + f.name() ); } commitErrors << list; #endif success = false; } } // // check that addition/removal went as expected // bool attributeChangesOk = true; if ( attributesChanged ) { L->updateFields(); QgsFields newFields = L->fields(); if ( oldFields.count() != newFields.count() ) { commitErrors << tr( "ERROR: the count of fields is incorrect after addition/removal of fields!" ); attributeChangesOk = false; // don't try attribute updates - they'll fail. } for ( int i = 0; i < std::min( oldFields.count(), newFields.count() ); ++i ) { QgsField oldField = oldFields.at( i ); QgsField newField = newFields.at( i ); if ( attributeChangesOk && oldField != newField ) { commitErrors << tr( "ERROR: field with index %1 is not the same!" ).arg( i ) << tr( "Provider: %1" ).arg( L->providerType() ) << tr( "Storage: %1" ).arg( L->storageType() ) << QStringLiteral( "%1: name=%2 type=%3 typeName=%4 len=%5 precision=%6" ) .arg( tr( "expected field" ), oldField.name(), QVariant::typeToName( oldField.type() ), oldField.typeName() ) .arg( oldField.length() ) .arg( oldField.precision() ) << QStringLiteral( "%1: name=%2 type=%3 typeName=%4 len=%5 precision=%6" ) .arg( tr( "retrieved field" ), newField.name(), QVariant::typeToName( newField.type() ), newField.typeName() ) .arg( newField.length() ) .arg( newField.precision() ); attributeChangesOk = false; // don't try attribute updates - they'll fail. } } } if ( attributeChangesOk ) { if ( cap & QgsVectorDataProvider::ChangeFeatures && !mChangedGeometries.isEmpty() && !mChangedAttributeValues.isEmpty() ) { Q_ASSERT( ( cap & ( QgsVectorDataProvider::ChangeAttributeValues | QgsVectorDataProvider::ChangeGeometries ) ) == ( QgsVectorDataProvider::ChangeAttributeValues | QgsVectorDataProvider::ChangeGeometries ) ); if ( provider->changeFeatures( mChangedAttributeValues, mChangedGeometries ) ) { commitErrors << tr( "SUCCESS: %1 attribute value(s) and %2 geometries changed." ).arg( mChangedAttributeValues.size(), mChangedGeometries.size() ); emit committedAttributeValuesChanges( L->id(), mChangedAttributeValues ); mChangedAttributeValues.clear(); emit committedGeometriesChanges( L->id(), mChangedGeometries ); mChangedGeometries.clear(); } else { success = false; } } else { // // change attributes // if ( !mChangedAttributeValues.isEmpty() && ( ( cap & QgsVectorDataProvider::ChangeFeatures ) == 0 || mChangedGeometries.isEmpty() ) ) { if ( ( cap & QgsVectorDataProvider::ChangeAttributeValues ) && provider->changeAttributeValues( mChangedAttributeValues ) ) { commitErrors << tr( "SUCCESS: %n attribute value(s) changed.", "changed attribute values count", mChangedAttributeValues.size() ); emit committedAttributeValuesChanges( L->id(), mChangedAttributeValues ); mChangedAttributeValues.clear(); } else { commitErrors << tr( "ERROR: %n attribute value change(s) not applied.", "not changed attribute values count", mChangedAttributeValues.size() ); #if 0 QString list = "ERROR: pending changes:"; const auto constKeys = mChangedAttributeValues.keys(); for ( QgsFeatureId id : constKeys ) { list.append( "\n " + FID_TO_STRING( id ) + '[' ); const auto constKeys = mChangedAttributeValues[ id ].keys(); for ( int idx : constKeys ) { list.append( QString( " %1:%2" ).arg( L->fields().at( idx ).name() ).arg( mChangedAttributeValues[id][idx].toString() ) ); } list.append( " ]" ); } commitErrors << list; #endif success = false; } } } // // delete features // if ( success && !mDeletedFeatureIds.isEmpty() ) { if ( ( cap & QgsVectorDataProvider::DeleteFeatures ) && provider->deleteFeatures( mDeletedFeatureIds ) ) { commitErrors << tr( "SUCCESS: %n feature(s) deleted.", "deleted features count", mDeletedFeatureIds.size() ); // TODO[MD]: we should not need this here const auto constMDeletedFeatureIds = mDeletedFeatureIds; for ( QgsFeatureId id : constMDeletedFeatureIds ) { mChangedAttributeValues.remove( id ); mChangedGeometries.remove( id ); } emit committedFeaturesRemoved( L->id(), mDeletedFeatureIds ); mDeletedFeatureIds.clear(); } else { commitErrors << tr( "ERROR: %n feature(s) not deleted.", "not deleted features count", mDeletedFeatureIds.size() ); #if 0 QString list = "ERROR: pending deletes:"; const auto constMDeletedFeatureIds = mDeletedFeatureIds; for ( QgsFeatureId id : constMDeletedFeatureIds ) { list.append( ' ' + FID_TO_STRING( id ) ); } commitErrors << list; #endif success = false; } } // // add features // if ( success && !mAddedFeatures.isEmpty() ) { if ( cap & QgsVectorDataProvider::AddFeatures ) { QList<QgsFeatureId> ids; QgsFeatureList featuresToAdd; // get the list of added features in reversed order // this will preserve the order how they have been added e.g. (-1, -2, -3) while in the map they are ordered (-3, -2, -1) mapToReversedLists( mAddedFeatures, ids, featuresToAdd ); // we need to strip any extra attributes here -- e.g. virtual fields, which should // not be sent to the data provider. Refs #18784 for ( int i = 0; i < featuresToAdd.count(); ++i ) { QgsVectorLayerUtils::matchAttributesToFields( featuresToAdd[i], provider->fields() ); } if ( provider->addFeatures( featuresToAdd ) ) { commitErrors << tr( "SUCCESS: %n feature(s) added.", "added features count", featuresToAdd.size() ); emit committedFeaturesAdded( L->id(), featuresToAdd ); // notify everyone that the features with temporary ids were updated with permanent ids for ( int i = 0; i < featuresToAdd.count(); ++i ) { if ( featuresToAdd[i].id() != ids[i] ) { //update selection if ( L->mSelectedFeatureIds.contains( ids[i] ) ) { L->mSelectedFeatureIds.remove( ids[i] ); L->mSelectedFeatureIds.insert( featuresToAdd[i].id() ); } emit featureDeleted( ids[i] ); emit featureAdded( featuresToAdd[i].id() ); } } mAddedFeatures.clear(); } else { commitErrors << tr( "ERROR: %n feature(s) not added.", "not added features count", mAddedFeatures.size() ); #if 0 QString list = "ERROR: pending adds:"; const auto constMAddedFeatures = mAddedFeatures; for ( QgsFeature f : constMAddedFeatures ) { list.append( ' ' + FID_TO_STRING( f.id() ) + '[' ); for ( int i = 0; i < L->fields().size(); i++ ) { list.append( QString( " %1:%2" ).arg( L->fields().at( i ).name() ).arg( f.attributes()[i].toString() ) ); } list.append( " ]" ); } commitErrors << list; #endif success = false; } } else { commitErrors << tr( "ERROR: %n feature(s) not added - provider doesn't support adding features.", "not added features count", mAddedFeatures.size() ); success = false; } } } else { success = false; } if ( !success && provider->hasErrors() ) { commitErrors << tr( "\n Provider errors:" ); const auto constErrors = provider->errors(); for ( QString e : constErrors ) { commitErrors << " " + e.replace( '\n', QLatin1String( "\n " ) ); } provider->clearErrors(); } return success; } void QgsVectorLayerEditBuffer::rollBack() { if ( !isModified() ) return; // limit canvas redraws to one by jumping to beginning of stack // see QgsUndoWidget::indexChanged L->undoStack()->setIndex( 0 ); Q_ASSERT( mAddedAttributes.isEmpty() ); Q_ASSERT( mDeletedAttributeIds.isEmpty() ); Q_ASSERT( mChangedAttributeValues.isEmpty() ); Q_ASSERT( mChangedGeometries.isEmpty() ); Q_ASSERT( mAddedFeatures.isEmpty() ); } #if 0 QString QgsVectorLayerEditBuffer::dumpEditBuffer() { QString msg; if ( !mChangedGeometries.isEmpty() ) { msg += "CHANGED GEOMETRIES:\n"; for ( QgsGeometryMap::const_iterator it = mChangedGeometries.begin(); it != mChangedGeometries.end(); ++it ) { // QgsFeatureId, QgsGeometry msg += QString( "- FID %1: %2" ).arg( it.key() ).arg( it.value().to ); } } return msg; } #endif void QgsVectorLayerEditBuffer::handleAttributeAdded( int index ) { // go through the changed attributes map and adapt indices QgsChangedAttributesMap::iterator it = mChangedAttributeValues.begin(); for ( ; it != mChangedAttributeValues.end(); ++it ) { updateAttributeMapIndex( it.value(), index, + 1 ); } // go through added features and adapt attributes QgsFeatureMap::iterator featureIt = mAddedFeatures.begin(); for ( ; featureIt != mAddedFeatures.end(); ++featureIt ) { QgsAttributes attrs = featureIt->attributes(); attrs.insert( index, QVariant() ); featureIt->setAttributes( attrs ); } // go through renamed attributes and adapt QList< int > sortedRenamedIndices = mRenamedAttributes.keys(); //sort keys std::sort( sortedRenamedIndices.begin(), sortedRenamedIndices.end(), std::greater< int >() ); const auto constSortedRenamedIndices = sortedRenamedIndices; for ( int renameIndex : constSortedRenamedIndices ) { if ( renameIndex >= index ) { mRenamedAttributes[ renameIndex + 1 ] = mRenamedAttributes.value( renameIndex ); } } //remove last mRenamedAttributes.remove( index ); } void QgsVectorLayerEditBuffer::handleAttributeDeleted( int index ) { // go through the changed attributes map and adapt indices QgsChangedAttributesMap::iterator it = mChangedAttributeValues.begin(); for ( ; it != mChangedAttributeValues.end(); ++it ) { QgsAttributeMap &attrMap = it.value(); // remove the attribute if ( attrMap.contains( index ) ) attrMap.remove( index ); // update attribute indices updateAttributeMapIndex( attrMap, index, -1 ); } // go through added features and adapt attributes QgsFeatureMap::iterator featureIt = mAddedFeatures.begin(); for ( ; featureIt != mAddedFeatures.end(); ++featureIt ) { QgsAttributes attrs = featureIt->attributes(); attrs.remove( index ); featureIt->setAttributes( attrs ); } // go through rename attributes and adapt QList< int > sortedRenamedIndices = mRenamedAttributes.keys(); //sort keys std::sort( sortedRenamedIndices.begin(), sortedRenamedIndices.end() ); int last = -1; mRenamedAttributes.remove( index ); const auto constSortedRenamedIndices = sortedRenamedIndices; for ( int renameIndex : constSortedRenamedIndices ) { if ( renameIndex > index ) { mRenamedAttributes.insert( renameIndex - 1, mRenamedAttributes.value( renameIndex ) ); last = renameIndex; } } //remove last if ( last > -1 ) mRenamedAttributes.remove( last ); } void QgsVectorLayerEditBuffer::updateAttributeMapIndex( QgsAttributeMap &map, int index, int offset ) const { QgsAttributeMap updatedMap; for ( QgsAttributeMap::const_iterator it = map.constBegin(); it != map.constEnd(); ++it ) { int attrIndex = it.key(); updatedMap.insert( attrIndex < index ? attrIndex : attrIndex + offset, it.value() ); } map = updatedMap; } void QgsVectorLayerEditBuffer::updateLayerFields() { L->updateFields(); }
31.574365
213
0.621745
[ "geometry" ]
9c92ec4101bb04d935acc55c4b7daef927b7aa19
109,374
cpp
C++
thirdparty/plink-2.0/plink2_bits.cpp
pancong419/GEM
a4271ff7e40c919a0cdfc04f09dca7d1ba43dae0
[ "Intel" ]
4
2020-02-28T22:34:47.000Z
2022-02-18T12:29:15.000Z
thirdparty/plink-2.0/plink2_bits.cpp
pancong419/GEM
a4271ff7e40c919a0cdfc04f09dca7d1ba43dae0
[ "Intel" ]
4
2020-07-22T14:10:08.000Z
2022-03-17T03:14:08.000Z
thirdparty/plink-2.0/plink2_bits.cpp
pancong419/GEM
a4271ff7e40c919a0cdfc04f09dca7d1ba43dae0
[ "Intel" ]
5
2019-11-07T20:17:00.000Z
2022-03-03T05:37:35.000Z
// This library is part of PLINK 2, copyright (C) 2005-2020 Shaun Purcell, // Christopher Chang. // // This library is free software: you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published by the // Free Software Foundation; either version 3 of the License, or (at your // option) any later version. // // This library 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 Lesser General Public License // for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this library. If not, see <http://www.gnu.org/licenses/>. #include "plink2_bits.h" #ifdef __cplusplus namespace plink2 { #endif #if defined(__LP64__) && !defined(USE_AVX2) // No alignment assumptions. void Pack32bTo16bMask(const void* words, uintptr_t ct_32b, void* dest) { // This is also competitive in the AVX2 case, but never quite beats the // simple loop. (We'd want to enable a similar function for Ryzen, // processing one 32-byte vector instead of two 16-byte vectors at a time in // the main loop since _mm256_packus_epi16() doesn't do what we want.) const VecW m1 = VCONST_W(kMask5555); # ifdef USE_SSE42 const VecW swap12 = vecw_setr8( 0, 1, 4, 5, 2, 3, 6, 7, 8, 9, 12, 13, 10, 11, 14, 15); # else const VecW m2 = VCONST_W(kMask3333); # endif const VecW m4 = VCONST_W(kMask0F0F); const VecW m8 = VCONST_W(kMask00FF); const VecW* words_valias = R_CAST(const VecW*, words); __m128i* dest_alias = R_CAST(__m128i*, dest); for (uintptr_t vidx = 0; vidx != ct_32b; ++vidx) { VecW vec_lo = vecw_loadu(&(words_valias[2 * vidx])) & m1; VecW vec_hi = vecw_loadu(&(words_valias[2 * vidx + 1])) & m1; # ifdef USE_SSE42 // this right-shift-3 + shuffle shortcut saves two operations. vec_lo = (vec_lo | vecw_srli(vec_lo, 3)) & m4; vec_hi = (vec_hi | vecw_srli(vec_hi, 3)) & m4; vec_lo = vecw_shuffle8(swap12, vec_lo); vec_hi = vecw_shuffle8(swap12, vec_hi); # else vec_lo = (vec_lo | vecw_srli(vec_lo, 1)) & m2; vec_hi = (vec_hi | vecw_srli(vec_hi, 1)) & m2; vec_lo = (vec_lo | vecw_srli(vec_lo, 2)) & m4; vec_hi = (vec_hi | vecw_srli(vec_hi, 2)) & m4; # endif vec_lo = (vec_lo | vecw_srli(vec_lo, 4)) & m8; vec_hi = (vec_hi | vecw_srli(vec_hi, 4)) & m8; const __m128i vec_packed = _mm_packus_epi16(R_CAST(__m128i, vec_lo), R_CAST(__m128i, vec_hi)); _mm_storeu_si128(&(dest_alias[vidx]), vec_packed); } } #endif void SetAllBits(uintptr_t ct, uintptr_t* bitarr) { // leaves bits beyond the end unset // ok for ct == 0 uintptr_t quotient = ct / kBitsPerWord; uintptr_t remainder = ct % kBitsPerWord; SetAllWArr(quotient, bitarr); if (remainder) { bitarr[quotient] = (k1LU << remainder) - k1LU; } } void BitvecAnd(const uintptr_t* __restrict arg_bitvec, uintptr_t word_ct, uintptr_t* __restrict main_bitvec) { // main_bitvec := main_bitvec AND arg_bitvec #ifdef __LP64__ VecW* main_bitvvec_iter = R_CAST(VecW*, main_bitvec); const VecW* arg_bitvvec_iter = R_CAST(const VecW*, arg_bitvec); const uintptr_t full_vec_ct = word_ct / kWordsPerVec; // ok, retested this explicit unroll (Jun 2018) and it's still noticeably // faster for small cases than the simple loop. sigh. if (full_vec_ct & 1) { *main_bitvvec_iter++ &= *arg_bitvvec_iter++; } if (full_vec_ct & 2) { *main_bitvvec_iter++ &= *arg_bitvvec_iter++; *main_bitvvec_iter++ &= *arg_bitvvec_iter++; } for (uintptr_t ulii = 3; ulii < full_vec_ct; ulii += 4) { *main_bitvvec_iter++ &= *arg_bitvvec_iter++; *main_bitvvec_iter++ &= *arg_bitvvec_iter++; *main_bitvvec_iter++ &= *arg_bitvvec_iter++; *main_bitvvec_iter++ &= *arg_bitvvec_iter++; } # ifdef USE_AVX2 if (word_ct & 2) { const uintptr_t base_idx = full_vec_ct * kWordsPerVec; main_bitvec[base_idx] &= arg_bitvec[base_idx]; main_bitvec[base_idx + 1] &= arg_bitvec[base_idx + 1]; } # endif if (word_ct & 1) { main_bitvec[word_ct - 1] &= arg_bitvec[word_ct - 1]; } #else for (uintptr_t widx = 0; widx != word_ct; ++widx) { main_bitvec[widx] &= arg_bitvec[widx]; } #endif } void BitvecInvmask(const uintptr_t* __restrict exclude_bitvec, uintptr_t word_ct, uintptr_t* __restrict main_bitvec) { // main_bitvec := main_bitvec ANDNOT exclude_bitvec // note that this is the reverse of the _mm_andnot() operand order #ifdef __LP64__ VecW* main_bitvvec_iter = R_CAST(VecW*, main_bitvec); const VecW* exclude_bitvvec_iter = R_CAST(const VecW*, exclude_bitvec); const uintptr_t full_vec_ct = word_ct / kWordsPerVec; if (full_vec_ct & 1) { *main_bitvvec_iter = vecw_and_notfirst(*exclude_bitvvec_iter++, *main_bitvvec_iter); ++main_bitvvec_iter; } if (full_vec_ct & 2) { *main_bitvvec_iter = vecw_and_notfirst(*exclude_bitvvec_iter++, *main_bitvvec_iter); ++main_bitvvec_iter; *main_bitvvec_iter = vecw_and_notfirst(*exclude_bitvvec_iter++, *main_bitvvec_iter); ++main_bitvvec_iter; } for (uintptr_t ulii = 3; ulii < full_vec_ct; ulii += 4) { *main_bitvvec_iter = vecw_and_notfirst(*exclude_bitvvec_iter++, *main_bitvvec_iter); ++main_bitvvec_iter; *main_bitvvec_iter = vecw_and_notfirst(*exclude_bitvvec_iter++, *main_bitvvec_iter); ++main_bitvvec_iter; *main_bitvvec_iter = vecw_and_notfirst(*exclude_bitvvec_iter++, *main_bitvvec_iter); ++main_bitvvec_iter; *main_bitvvec_iter = vecw_and_notfirst(*exclude_bitvvec_iter++, *main_bitvvec_iter); ++main_bitvvec_iter; } # ifdef USE_AVX2 if (word_ct & 2) { const uintptr_t base_idx = full_vec_ct * kWordsPerVec; main_bitvec[base_idx] &= ~exclude_bitvec[base_idx]; main_bitvec[base_idx + 1] &= ~exclude_bitvec[base_idx + 1]; } # endif if (word_ct & 1) { main_bitvec[word_ct - 1] &= ~exclude_bitvec[word_ct - 1]; } #else for (uintptr_t widx = 0; widx != word_ct; ++widx) { main_bitvec[widx] &= ~exclude_bitvec[widx]; } #endif } void BitvecOr(const uintptr_t* __restrict arg_bitvec, uintptr_t word_ct, uintptr_t* main_bitvec) { // main_bitvec := main_bitvec OR arg_bitvec #ifdef __LP64__ VecW* main_bitvvec_iter = R_CAST(VecW*, main_bitvec); const VecW* arg_bitvvec_iter = R_CAST(const VecW*, arg_bitvec); const uintptr_t full_vec_ct = word_ct / kWordsPerVec; if (full_vec_ct & 1) { *main_bitvvec_iter++ |= (*arg_bitvvec_iter++); } if (full_vec_ct & 2) { *main_bitvvec_iter++ |= (*arg_bitvvec_iter++); *main_bitvvec_iter++ |= (*arg_bitvvec_iter++); } for (uintptr_t ulii = 3; ulii < full_vec_ct; ulii += 4) { *main_bitvvec_iter++ |= (*arg_bitvvec_iter++); *main_bitvvec_iter++ |= (*arg_bitvvec_iter++); *main_bitvvec_iter++ |= (*arg_bitvvec_iter++); *main_bitvvec_iter++ |= (*arg_bitvvec_iter++); } # ifdef USE_AVX2 if (word_ct & 2) { const uintptr_t base_idx = full_vec_ct * kWordsPerVec; main_bitvec[base_idx] |= arg_bitvec[base_idx]; main_bitvec[base_idx + 1] |= arg_bitvec[base_idx + 1]; } # endif if (word_ct & 1) { main_bitvec[word_ct - 1] |= arg_bitvec[word_ct - 1]; } #else for (uintptr_t widx = 0; widx != word_ct; ++widx) { main_bitvec[widx] |= arg_bitvec[widx]; } #endif } void BitvecInvert(uintptr_t word_ct, uintptr_t* main_bitvec) { #ifdef __LP64__ VecW* main_bitvvec_iter = R_CAST(VecW*, main_bitvec); const uintptr_t full_vec_ct = word_ct / kWordsPerVec; const VecW all1 = VCONST_W(~k0LU); if (full_vec_ct & 1) { *main_bitvvec_iter++ ^= all1; } if (full_vec_ct & 2) { *main_bitvvec_iter++ ^= all1; *main_bitvvec_iter++ ^= all1; } for (uintptr_t ulii = 3; ulii < full_vec_ct; ulii += 4) { *main_bitvvec_iter++ ^= all1; *main_bitvvec_iter++ ^= all1; *main_bitvvec_iter++ ^= all1; *main_bitvvec_iter++ ^= all1; } # ifdef USE_AVX2 if (word_ct & 2) { const uintptr_t base_idx = full_vec_ct * kWordsPerVec; main_bitvec[base_idx] ^= ~k0LU; main_bitvec[base_idx + 1] ^= ~k0LU; } # endif if (word_ct & 1) { main_bitvec[word_ct - 1] ^= ~k0LU; } #else for (uintptr_t widx = 0; widx != word_ct; ++widx) { main_bitvec[widx] ^= ~k0LU; } #endif } uintptr_t AdvTo1Bit(const uintptr_t* bitarr, uintptr_t loc) { const uintptr_t* bitarr_iter = &(bitarr[loc / kBitsPerWord]); uintptr_t ulii = (*bitarr_iter) >> (loc % kBitsPerWord); if (ulii) { return loc + ctzw(ulii); } do { ulii = *(++bitarr_iter); } while (!ulii); return S_CAST(uintptr_t, bitarr_iter - bitarr) * kBitsPerWord + ctzw(ulii); } uintptr_t AdvTo0Bit(const uintptr_t* bitarr, uintptr_t loc) { const uintptr_t* bitarr_iter = &(bitarr[loc / kBitsPerWord]); uintptr_t ulii = (~(*bitarr_iter)) >> (loc % kBitsPerWord); if (ulii) { return loc + ctzw(ulii); } do { ulii = *(++bitarr_iter); } while (ulii == ~k0LU); return S_CAST(uintptr_t, bitarr_iter - bitarr) * kBitsPerWord + ctzw(~ulii); } /* uintptr_t NextNonmissingUnsafe(const uintptr_t* genoarr, uintptr_t loc) { const uintptr_t* genoarr_iter = &(genoarr[loc / kBitsPerWordD2]); uintptr_t ulii = (~(*genoarr_iter)) >> (2 * (loc % kBitsPerWordD2)); if (ulii) { return loc + (ctzw(ulii) / 2); } do { ulii = *(++genoarr_iter); } while (ulii == ~k0LU); return S_CAST(uintptr_t, genoarr_iter - genoarr) * kBitsPerWordD2 + (ctzw(~ulii) / 2); } */ uint32_t AdvBoundedTo1Bit(const uintptr_t* bitarr, uint32_t loc, uint32_t ceil) { // safe version. const uintptr_t* bitarr_iter = &(bitarr[loc / kBitsPerWord]); uintptr_t ulii = (*bitarr_iter) >> (loc % kBitsPerWord); if (ulii) { const uint32_t rval = loc + ctzw(ulii); return MINV(rval, ceil); } const uintptr_t* bitarr_last = &(bitarr[(ceil - 1) / kBitsPerWord]); do { if (bitarr_iter >= bitarr_last) { return ceil; } ulii = *(++bitarr_iter); } while (!ulii); const uint32_t rval = S_CAST(uintptr_t, bitarr_iter - bitarr) * kBitsPerWord + ctzw(ulii); return MINV(rval, ceil); } uintptr_t AdvBoundedTo0Bit(const uintptr_t* bitarr, uintptr_t loc, uintptr_t ceil) { assert(ceil >= 1); const uintptr_t* bitarr_ptr = &(bitarr[loc / kBitsPerWord]); uintptr_t ulii = (~(*bitarr_ptr)) >> (loc % kBitsPerWord); if (ulii) { loc += ctzw(ulii); return MINV(loc, ceil); } const uintptr_t* bitarr_last = &(bitarr[(ceil - 1) / kBitsPerWord]); do { if (bitarr_ptr >= bitarr_last) { return ceil; } ulii = *(++bitarr_ptr); } while (ulii == ~k0LU); loc = S_CAST(uintptr_t, bitarr_ptr - bitarr) * kBitsPerWord + ctzw(~ulii); return MINV(loc, ceil); } uint32_t FindLast1BitBefore(const uintptr_t* bitarr, uint32_t loc) { // unlike the next_{un}set family, this always returns a STRICTLY earlier // position const uintptr_t* bitarr_iter = &(bitarr[loc / kBitsPerWord]); const uint32_t remainder = loc % kBitsPerWord; uintptr_t ulii; if (remainder) { ulii = bzhi(*bitarr_iter, remainder); if (ulii) { return loc - remainder + bsrw(ulii); } } do { ulii = *(--bitarr_iter); } while (!ulii); return S_CAST(uintptr_t, bitarr_iter - bitarr) * kBitsPerWord + bsrw(ulii); } uint32_t AllBytesAreX(const unsigned char* bytes, unsigned char match, uintptr_t byte_ct) { if (byte_ct < kBytesPerWord) { for (uint32_t uii = 0; uii != byte_ct; ++uii) { if (bytes[uii] != match) { return 0; } } return 1; } const uintptr_t* bytes_alias = R_CAST(const uintptr_t*, bytes); const uintptr_t word_match = S_CAST(uintptr_t, match) * kMask0101; uintptr_t word_ct_m1 = (byte_ct - 1) / kBytesPerWord; // todo: try movemask in AVX2 case for (uintptr_t widx = 0; widx != word_ct_m1; ++widx) { if (bytes_alias[widx] != word_match) { return 0; } } const uintptr_t last_word = *R_CAST(const uintptr_t*, &(bytes[byte_ct - kBytesPerWord])); if (last_word != word_match) { return 0; } return 1; } #ifdef USE_AVX2 // void CopyBitarrSubsetEx(const uintptr_t* __restrict raw_bitarr, const uintptr_t* __restrict subset_mask, uint32_t bit_idx_start, uint32_t output_bit_idx_end, uintptr_t* __restrict output_bitarr) { void CopyBitarrSubset(const uintptr_t* __restrict raw_bitarr, const uintptr_t* __restrict subset_mask, uint32_t output_bit_idx_end, uintptr_t* __restrict output_bitarr) { const uint32_t output_bit_idx_end_lowbits = output_bit_idx_end % kBitsPerWord; uintptr_t* output_bitarr_iter = output_bitarr; uintptr_t* output_bitarr_last = &(output_bitarr[output_bit_idx_end / kBitsPerWord]); uintptr_t cur_output_word = 0; uint32_t read_widx = UINT32_MAX; // deliberate overflow uint32_t write_idx_lowbits = 0; while ((output_bitarr_iter != output_bitarr_last) || (write_idx_lowbits != output_bit_idx_end_lowbits)) { uintptr_t cur_mask_word; // sparse subset_mask optimization // guaranteed to terminate since there's at least one more set bit do { cur_mask_word = subset_mask[++read_widx]; } while (!cur_mask_word); uintptr_t extracted_bits = raw_bitarr[read_widx]; uint32_t set_bit_ct = kBitsPerWord; if (cur_mask_word != ~k0LU) { extracted_bits = _pext_u64(extracted_bits, cur_mask_word); set_bit_ct = PopcountWord(cur_mask_word); } cur_output_word |= extracted_bits << write_idx_lowbits; const uint32_t new_write_idx_lowbits = write_idx_lowbits + set_bit_ct; if (new_write_idx_lowbits >= kBitsPerWord) { *output_bitarr_iter++ = cur_output_word; // ...and these are the bits that fell off // bugfix: unsafe to right-shift 64 if (write_idx_lowbits) { cur_output_word = extracted_bits >> (kBitsPerWord - write_idx_lowbits); } else { cur_output_word = 0; } } write_idx_lowbits = new_write_idx_lowbits % kBitsPerWord; } if (write_idx_lowbits) { *output_bitarr_iter = cur_output_word; } } uintptr_t PopcountVecsAvx2(const VecW* bit_vvec, uintptr_t vec_ct) { // See popcnt_avx2() in libpopcnt. VecW cnt = vecw_setzero(); VecW ones = vecw_setzero(); VecW twos = vecw_setzero(); VecW fours = vecw_setzero(); VecW eights = vecw_setzero(); VecW prev_sad_result = vecw_setzero(); const uintptr_t vec_ct_a16 = RoundDownPow2(vec_ct, 16); for (uintptr_t vec_idx = 0; vec_idx != vec_ct_a16; vec_idx += 16) { VecW twos_a = Csa256(bit_vvec[vec_idx + 0], bit_vvec[vec_idx + 1], &ones); VecW twos_b = Csa256(bit_vvec[vec_idx + 2], bit_vvec[vec_idx + 3], &ones); VecW fours_a = Csa256(twos_a, twos_b, &twos); twos_a = Csa256(bit_vvec[vec_idx + 4], bit_vvec[vec_idx + 5], &ones); twos_b = Csa256(bit_vvec[vec_idx + 6], bit_vvec[vec_idx + 7], &ones); VecW fours_b = Csa256(twos_a, twos_b, &twos); const VecW eights_a = Csa256(fours_a, fours_b, &fours); twos_a = Csa256(bit_vvec[vec_idx + 8], bit_vvec[vec_idx + 9], &ones); twos_b = Csa256(bit_vvec[vec_idx + 10], bit_vvec[vec_idx + 11], &ones); fours_a = Csa256(twos_a, twos_b, &twos); twos_a = Csa256(bit_vvec[vec_idx + 12], bit_vvec[vec_idx + 13], &ones); twos_b = Csa256(bit_vvec[vec_idx + 14], bit_vvec[vec_idx + 15], &ones); fours_b = Csa256(twos_a, twos_b, &twos); const VecW eights_b = Csa256(fours_a, fours_b, &fours); const VecW sixteens = Csa256(eights_a, eights_b, &eights); cnt = cnt + prev_sad_result; // work around high SAD latency prev_sad_result = PopcountVecAvx2(sixteens); } bit_vvec = &(bit_vvec[vec_ct_a16]); const uintptr_t remainder = vec_ct % 16; cnt = cnt + prev_sad_result; if (remainder < 12) { cnt = vecw_slli(cnt, 4); if (remainder) { VecW popcnt1_acc = vecw_setzero(); VecW popcnt2_acc = vecw_setzero(); const VecW lookup1 = vecw_setr8(4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8); const VecW lookup2 = vecw_setr8(4, 3, 3, 2, 3, 2, 2, 1, 3, 2, 2, 1, 2, 1, 1, 0); const VecW m4 = VCONST_W(kMask0F0F); for (uintptr_t vec_idx = 0; vec_idx != remainder; ++vec_idx) { const VecW vv = bit_vvec[vec_idx]; const VecW lo = vv & m4; const VecW hi = vecw_srli(vv, 4) & m4; popcnt1_acc = popcnt1_acc + vecw_shuffle8(lookup1, lo); popcnt2_acc = popcnt2_acc + vecw_shuffle8(lookup2, hi); } cnt = cnt + vecw_sad(popcnt1_acc, popcnt2_acc); } } else { VecW twos_a = Csa256(bit_vvec[0], bit_vvec[1], &ones); VecW twos_b = Csa256(bit_vvec[2], bit_vvec[3], &ones); VecW fours_a = Csa256(twos_a, twos_b, &twos); twos_a = Csa256(bit_vvec[4], bit_vvec[5], &ones); twos_b = Csa256(bit_vvec[6], bit_vvec[7], &ones); VecW fours_b = Csa256(twos_a, twos_b, &twos); const VecW eights_a = Csa256(fours_a, fours_b, &fours); twos_a = Csa256(bit_vvec[8], bit_vvec[9], &ones); twos_b = Csa256(bit_vvec[10], bit_vvec[11], &ones); fours_a = Csa256(twos_a, twos_b, &twos); twos_a = vecw_setzero(); if (remainder & 2) { twos_a = Csa256(bit_vvec[12], bit_vvec[13], &ones); } twos_b = vecw_setzero(); if (remainder & 1) { twos_b = CsaOne256(bit_vvec[remainder - 1], &ones); } fours_b = Csa256(twos_a, twos_b, &twos); const VecW eights_b = Csa256(fours_a, fours_b, &fours); const VecW sixteens = Csa256(eights_a, eights_b, &eights); cnt = cnt + PopcountVecAvx2(sixteens); cnt = vecw_slli(cnt, 4); } // Appears to be counterproductive to put multiple SAD instructions in // flight. // Compiler is smart enough that it's pointless to manually inline // PopcountVecAvx2. (Tried combining the 4 SAD calls into one, didn't help.) cnt = cnt + vecw_slli(PopcountVecAvx2(eights), 3); cnt = cnt + vecw_slli(PopcountVecAvx2(fours), 2); cnt = cnt + vecw_slli(PopcountVecAvx2(twos), 1); cnt = cnt + PopcountVecAvx2(ones); return HsumW(cnt); } uintptr_t PopcountVecsAvx2Intersect(const VecW* __restrict vvec1_iter, const VecW* __restrict vvec2_iter, uintptr_t vec_ct) { // See popcnt_avx2() in libpopcnt. vec_ct must be a multiple of 16. VecW cnt = vecw_setzero(); VecW ones = vecw_setzero(); VecW twos = vecw_setzero(); VecW fours = vecw_setzero(); VecW eights = vecw_setzero(); for (uintptr_t vec_idx = 0; vec_idx < vec_ct; vec_idx += 16) { VecW twos_a = Csa256(vvec1_iter[vec_idx + 0] & vvec2_iter[vec_idx + 0], vvec1_iter[vec_idx + 1] & vvec2_iter[vec_idx + 1], &ones); VecW twos_b = Csa256(vvec1_iter[vec_idx + 2] & vvec2_iter[vec_idx + 2], vvec1_iter[vec_idx + 3] & vvec2_iter[vec_idx + 3], &ones); VecW fours_a = Csa256(twos_a, twos_b, &twos); twos_a = Csa256(vvec1_iter[vec_idx + 4] & vvec2_iter[vec_idx + 4], vvec1_iter[vec_idx + 5] & vvec2_iter[vec_idx + 5], &ones); twos_b = Csa256(vvec1_iter[vec_idx + 6] & vvec2_iter[vec_idx + 6], vvec1_iter[vec_idx + 7] & vvec2_iter[vec_idx + 7], &ones); VecW fours_b = Csa256(twos_a, twos_b, &twos); const VecW eights_a = Csa256(fours_a, fours_b, &fours); twos_a = Csa256(vvec1_iter[vec_idx + 8] & vvec2_iter[vec_idx + 8], vvec1_iter[vec_idx + 9] & vvec2_iter[vec_idx + 9], &ones); twos_b = Csa256(vvec1_iter[vec_idx + 10] & vvec2_iter[vec_idx + 10], vvec1_iter[vec_idx + 11] & vvec2_iter[vec_idx + 11], &ones); fours_a = Csa256(twos_a, twos_b, &twos); twos_a = Csa256(vvec1_iter[vec_idx + 12] & vvec2_iter[vec_idx + 12], vvec1_iter[vec_idx + 13] & vvec2_iter[vec_idx + 13], &ones); twos_b = Csa256(vvec1_iter[vec_idx + 14] & vvec2_iter[vec_idx + 14], vvec1_iter[vec_idx + 15] & vvec2_iter[vec_idx + 15], &ones); fours_b = Csa256(twos_a, twos_b, &twos); const VecW eights_b = Csa256(fours_a, fours_b, &fours); const VecW sixteens = Csa256(eights_a, eights_b, &eights); cnt = cnt + PopcountVecAvx2(sixteens); } cnt = vecw_slli(cnt, 4); cnt = cnt + vecw_slli(PopcountVecAvx2(eights), 3); cnt = cnt + vecw_slli(PopcountVecAvx2(fours), 2); cnt = cnt + vecw_slli(PopcountVecAvx2(twos), 1); cnt = cnt + PopcountVecAvx2(ones); return HsumW(cnt); } uintptr_t PopcountWordsIntersect(const uintptr_t* __restrict bitvec1_iter, const uintptr_t* __restrict bitvec2_iter, uintptr_t word_ct) { const uintptr_t* bitvec1_end = &(bitvec1_iter[word_ct]); const uintptr_t block_ct = word_ct / (16 * kWordsPerVec); uintptr_t tot = 0; if (block_ct) { tot = PopcountVecsAvx2Intersect(R_CAST(const VecW*, bitvec1_iter), R_CAST(const VecW*, bitvec2_iter), block_ct * 16); bitvec1_iter = &(bitvec1_iter[block_ct * (16 * kWordsPerVec)]); bitvec2_iter = &(bitvec2_iter[block_ct * (16 * kWordsPerVec)]); } while (bitvec1_iter < bitvec1_end) { tot += PopcountWord((*bitvec1_iter++) & (*bitvec2_iter++)); } return tot; } void ExpandBytearr(const void* __restrict compact_bitarr, const uintptr_t* __restrict expand_mask, uint32_t word_ct, uint32_t expand_size, uint32_t read_start_bit, uintptr_t* __restrict target) { const uint32_t expand_sizex_m1 = expand_size + read_start_bit - 1; const uint32_t leading_byte_ct = 1 + (expand_sizex_m1 % kBitsPerWord) / CHAR_BIT; uintptr_t compact_word = SubwordLoad(compact_bitarr, leading_byte_ct) >> read_start_bit; const uintptr_t* compact_bitarr_iter = R_CAST(const uintptr_t*, &(S_CAST(const unsigned char*, compact_bitarr)[leading_byte_ct])); uint32_t compact_idx_lowbits = read_start_bit + CHAR_BIT * (sizeof(intptr_t) - leading_byte_ct); for (uint32_t widx = 0; widx != word_ct; ++widx) { const uintptr_t mask_word = expand_mask[widx]; uintptr_t write_word = 0; if (mask_word) { const uint32_t mask_set_ct = PopcountWord(mask_word); uint32_t next_compact_idx_lowbits = compact_idx_lowbits + mask_set_ct; if (next_compact_idx_lowbits <= kBitsPerWord) { write_word = _pdep_u64(compact_word, mask_word); if (mask_set_ct != kBitsPerWord) { compact_word = compact_word >> mask_set_ct; } else { // avoid nasal demons compact_word = 0; } } else { # ifdef __arm__ # error "Unaligned accesses in ExpandBytearr()." # endif uintptr_t next_compact_word = *compact_bitarr_iter++; next_compact_idx_lowbits -= kBitsPerWord; compact_word |= next_compact_word << (kBitsPerWord - compact_idx_lowbits); write_word = _pdep_u64(compact_word, mask_word); if (next_compact_idx_lowbits != kBitsPerWord) { compact_word = next_compact_word >> next_compact_idx_lowbits; } else { compact_word = 0; } } compact_idx_lowbits = next_compact_idx_lowbits; } target[widx] = write_word; } } void ExpandThenSubsetBytearr(const void* __restrict compact_bitarr, const uintptr_t* __restrict expand_mask, const uintptr_t* __restrict subset_mask, uint32_t expand_size, uint32_t subset_size, uint32_t read_start_bit, uintptr_t* __restrict target) { const uint32_t expand_sizex_m1 = expand_size + read_start_bit - 1; const uint32_t leading_byte_ct = 1 + (expand_sizex_m1 % kBitsPerWord) / CHAR_BIT; uintptr_t compact_word = SubwordLoad(compact_bitarr, leading_byte_ct) >> read_start_bit; const uintptr_t* compact_bitarr_alias = R_CAST(const uintptr_t*, &(S_CAST(const unsigned char*, compact_bitarr)[leading_byte_ct])); uint32_t compact_widx = UINT32_MAX; // deliberate overflow uint32_t compact_idx_lowbits = read_start_bit + CHAR_BIT * (sizeof(uintptr_t) - leading_byte_ct); const uint32_t subset_size_lowbits = subset_size % kBitsPerWord; uintptr_t* target_iter = target; uintptr_t* target_last = &(target[subset_size / kBitsPerWord]); uintptr_t cur_output_word = 0; uint32_t read_widx = UINT32_MAX; // deliberate overflow uint32_t write_idx_lowbits = 0; // bugfix (5 Feb 2018): missed a case in sparse subset_mask optimization uint32_t expand_bit_ct_skip = 0; while ((target_iter != target_last) || (write_idx_lowbits != subset_size_lowbits)) { uintptr_t expand_word; uintptr_t subset_word; uint32_t expand_bit_ct; while (1) { ++read_widx; expand_word = expand_mask[read_widx]; subset_word = subset_mask[read_widx]; expand_bit_ct = PopcountWord(expand_word); if (subset_word) { break; } expand_bit_ct_skip += expand_bit_ct; } uintptr_t extracted_bits = 0; const uint32_t set_bit_ct = PopcountWord(subset_word); if (expand_word & subset_word) { // lazy load compact_idx_lowbits += expand_bit_ct_skip; if (compact_idx_lowbits >= kBitsPerWord) { compact_widx += compact_idx_lowbits / kBitsPerWord; compact_idx_lowbits = compact_idx_lowbits % kBitsPerWord; # ifdef __arm__ # error "Unaligned accesses in ExpandThenSubsetBytearr()." # endif compact_word = compact_bitarr_alias[compact_widx] >> compact_idx_lowbits; } else { compact_word = compact_word >> expand_bit_ct_skip; } uint32_t next_compact_idx_lowbits = compact_idx_lowbits + expand_bit_ct; uintptr_t expanded_bits; if (next_compact_idx_lowbits <= kBitsPerWord) { expanded_bits = _pdep_u64(compact_word, expand_word); if (expand_bit_ct != kBitsPerWord) { compact_word = compact_word >> expand_bit_ct; } } else { uintptr_t next_compact_word = compact_bitarr_alias[++compact_widx]; next_compact_idx_lowbits -= kBitsPerWord; compact_word |= next_compact_word << (kBitsPerWord - compact_idx_lowbits); expanded_bits = _pdep_u64(compact_word, expand_word); if (next_compact_idx_lowbits != kBitsPerWord) { compact_word = next_compact_word >> next_compact_idx_lowbits; } } extracted_bits = _pext_u64(expanded_bits, subset_word); compact_idx_lowbits = next_compact_idx_lowbits; cur_output_word |= extracted_bits << write_idx_lowbits; expand_bit_ct_skip = 0; } else { expand_bit_ct_skip += expand_bit_ct; } const uint32_t new_write_idx_lowbits = write_idx_lowbits + set_bit_ct; if (new_write_idx_lowbits >= kBitsPerWord) { *target_iter++ = cur_output_word; // ...and these are the bits that fell off if (write_idx_lowbits) { cur_output_word = extracted_bits >> (kBitsPerWord - write_idx_lowbits); } else { cur_output_word = 0; } } write_idx_lowbits = new_write_idx_lowbits % kBitsPerWord; } if (write_idx_lowbits) { *target_iter = cur_output_word; } } void ExpandBytearrNested(const void* __restrict compact_bitarr, const uintptr_t* __restrict mid_bitarr, const uintptr_t* __restrict top_expand_mask, uint32_t word_ct, uint32_t mid_popcount, uint32_t mid_start_bit, uintptr_t* __restrict mid_target, uintptr_t* __restrict compact_target) { assert(mid_popcount); const uint32_t leading_byte_ct = 1 + ((mid_popcount - 1) % kBitsPerWord) / CHAR_BIT; uintptr_t compact_read_word = SubwordLoad(compact_bitarr, leading_byte_ct); uint32_t compact_idx_lowbits = CHAR_BIT * (sizeof(intptr_t) - leading_byte_ct); const uintptr_t* compact_bitarr_iter = R_CAST(const uintptr_t*, &(S_CAST(const unsigned char*, compact_bitarr)[leading_byte_ct])); const uintptr_t* mid_bitarr_iter = mid_bitarr; uint32_t mid_idx_lowbits = mid_start_bit; uintptr_t mid_read_word = (*mid_bitarr_iter) >> mid_start_bit; for (uint32_t widx = 0; widx != word_ct; ++widx) { const uintptr_t top_word = top_expand_mask[widx]; uintptr_t mid_write_word = 0; uintptr_t compact_write_word = 0; if (top_word) { const uint32_t top_set_ct = PopcountWord(top_word); uint32_t next_mid_idx_lowbits = mid_idx_lowbits + top_set_ct; if (next_mid_idx_lowbits <= kBitsPerWord) { mid_write_word = _pdep_u64(mid_read_word, top_word); if (top_set_ct != kBitsPerWord) { mid_read_word = mid_read_word >> top_set_ct; } else { // avoid nasal demons mid_read_word = 0; } } else { uintptr_t next_mid_read_word = *(++mid_bitarr_iter); next_mid_idx_lowbits -= kBitsPerWord; mid_read_word |= next_mid_read_word << (kBitsPerWord - mid_idx_lowbits); mid_write_word = _pdep_u64(mid_read_word, top_word); if (next_mid_idx_lowbits != kBitsPerWord) { mid_read_word = next_mid_read_word >> next_mid_idx_lowbits; } else { mid_read_word = 0; } } mid_idx_lowbits = next_mid_idx_lowbits; if (mid_write_word) { const uint32_t mid_set_ct = PopcountWord(mid_write_word); uint32_t next_compact_idx_lowbits = compact_idx_lowbits + mid_set_ct; if (next_compact_idx_lowbits <= kBitsPerWord) { compact_write_word = _pdep_u64(compact_read_word, mid_write_word); if (mid_set_ct != kBitsPerWord) { compact_read_word = compact_read_word >> mid_set_ct; } else { compact_read_word = 0; } } else { # ifdef __arm__ # error "Unaligned accesses in ExpandBytearrNested()." # endif uintptr_t next_compact_word = *compact_bitarr_iter++; next_compact_idx_lowbits -= kBitsPerWord; compact_read_word |= next_compact_word << (kBitsPerWord - compact_idx_lowbits); compact_write_word = _pdep_u64(compact_read_word, mid_write_word); if (next_compact_idx_lowbits != kBitsPerWord) { compact_read_word = next_compact_word >> next_compact_idx_lowbits; } else { compact_read_word = 0; } } compact_idx_lowbits = next_compact_idx_lowbits; } } mid_target[widx] = mid_write_word; compact_target[widx] = compact_write_word; } } void ExpandThenSubsetBytearrNested(const void* __restrict compact_bitarr, const uintptr_t* __restrict mid_bitarr, const uintptr_t* __restrict top_expand_mask, const uintptr_t* __restrict subset_mask, uint32_t subset_size, uint32_t mid_popcount, uint32_t mid_start_bit, uintptr_t* __restrict mid_target, uintptr_t* __restrict compact_target) { assert(mid_popcount); const uint32_t leading_byte_ct = 1 + ((mid_popcount - 1) % kBitsPerWord) / CHAR_BIT; uintptr_t compact_read_word = SubwordLoad(compact_bitarr, leading_byte_ct); uint32_t compact_idx_lowbits = CHAR_BIT * (sizeof(intptr_t) - leading_byte_ct); const uintptr_t* compact_bitarr_alias = R_CAST(const uintptr_t*, &(S_CAST(const unsigned char*, compact_bitarr)[leading_byte_ct])); const uintptr_t* mid_bitarr_iter = mid_bitarr; const uint32_t subset_size_lowbits = subset_size % kBitsPerWord; const uint32_t write_widx_last = subset_size / kBitsPerWord; uintptr_t mid_read_word = (*mid_bitarr_iter) >> mid_start_bit; uintptr_t mid_output_word = 0; uintptr_t compact_output_word = 0; uint32_t mid_idx_lowbits = mid_start_bit; uint32_t compact_widx = UINT32_MAX; // deliberate overflow uint32_t read_widx = UINT32_MAX; // deliberate overflow uint32_t write_idx_lowbits = 0; uint32_t write_widx = 0; // bugfix (5 Feb 2018): missed a case in sparse subset_mask optimization uint32_t mid_set_skip = 0; while ((write_widx != write_widx_last) || (write_idx_lowbits != subset_size_lowbits)) { uintptr_t subset_word; uintptr_t mid_expanded_bits; uint32_t mid_set_ct; while (1) { ++read_widx; uintptr_t top_word = top_expand_mask[read_widx]; subset_word = subset_mask[read_widx]; mid_expanded_bits = 0; if (top_word) { uint32_t top_set_ct = PopcountWord(top_word); uint32_t next_mid_idx_lowbits = mid_idx_lowbits + top_set_ct; if (next_mid_idx_lowbits <= kBitsPerWord) { mid_expanded_bits = _pdep_u64(mid_read_word, top_word); if (top_set_ct != kBitsPerWord) { mid_read_word = mid_read_word >> top_set_ct; } else { // avoid nasal demons mid_read_word = 0; } } else { uintptr_t next_mid_read_word = *(++mid_bitarr_iter); next_mid_idx_lowbits -= kBitsPerWord; mid_read_word |= next_mid_read_word << (kBitsPerWord - mid_idx_lowbits); mid_expanded_bits = _pdep_u64(mid_read_word, top_word); if (next_mid_idx_lowbits != kBitsPerWord) { mid_read_word = next_mid_read_word >> next_mid_idx_lowbits; } else { mid_read_word = 0; } } mid_idx_lowbits = next_mid_idx_lowbits; } mid_set_ct = PopcountWord(mid_expanded_bits); if (subset_word) { break; } mid_set_skip += mid_set_ct; } uintptr_t mid_extracted_bits = 0; uintptr_t compact_extracted_bits = 0; uint32_t set_bit_ct = PopcountWord(subset_word); if (mid_expanded_bits & subset_word) { // lazy load compact_idx_lowbits += mid_set_skip; if (compact_idx_lowbits >= kBitsPerWord) { compact_widx += compact_idx_lowbits / kBitsPerWord; compact_idx_lowbits = compact_idx_lowbits % kBitsPerWord; # ifdef __arm__ # error "Unaligned accesses in ExpandThenSubsetBytearrNested()." # endif compact_read_word = compact_bitarr_alias[compact_widx] >> compact_idx_lowbits; } else { compact_read_word = compact_read_word >> mid_set_skip; } uint32_t next_compact_idx_lowbits = compact_idx_lowbits + mid_set_ct; uintptr_t compact_expanded_bits; if (next_compact_idx_lowbits <= kBitsPerWord) { compact_expanded_bits = _pdep_u64(compact_read_word, mid_expanded_bits); if (mid_set_ct != kBitsPerWord) { compact_read_word = compact_read_word >> mid_set_ct; } } else { uintptr_t next_compact_word = compact_bitarr_alias[++compact_widx]; next_compact_idx_lowbits -= kBitsPerWord; compact_read_word |= next_compact_word << (kBitsPerWord - compact_idx_lowbits); compact_expanded_bits = _pdep_u64(compact_read_word, mid_expanded_bits); if (next_compact_idx_lowbits != kBitsPerWord) { compact_read_word = next_compact_word >> next_compact_idx_lowbits; } } compact_extracted_bits = _pext_u64(compact_expanded_bits, subset_word); mid_extracted_bits = _pext_u64(mid_expanded_bits, subset_word); compact_idx_lowbits = next_compact_idx_lowbits; compact_output_word |= compact_extracted_bits << write_idx_lowbits; mid_output_word |= mid_extracted_bits << write_idx_lowbits; mid_set_skip = 0; } else { mid_set_skip += mid_set_ct; } const uint32_t new_write_idx_lowbits = write_idx_lowbits + set_bit_ct; if (new_write_idx_lowbits >= kBitsPerWord) { mid_target[write_widx] = mid_output_word; compact_target[write_widx] = compact_output_word; ++write_widx; if (write_idx_lowbits) { mid_output_word = mid_extracted_bits >> (kBitsPerWord - write_idx_lowbits); compact_output_word = compact_extracted_bits >> (kBitsPerWord - write_idx_lowbits); } else { mid_output_word = 0; compact_output_word = 0; } } write_idx_lowbits = new_write_idx_lowbits % kBitsPerWord; } if (write_idx_lowbits) { mid_target[write_widx] = mid_output_word; compact_target[write_widx] = compact_output_word; } } #else // !USE_AVX2 void CopyBitarrSubset(const uintptr_t* __restrict raw_bitarr, const uintptr_t* __restrict subset_mask, uint32_t output_bit_idx_end, uintptr_t* __restrict output_bitarr) { const uint32_t output_bit_idx_end_lowbits = output_bit_idx_end % kBitsPerWord; uintptr_t* output_bitarr_iter = output_bitarr; uintptr_t* output_bitarr_last = &(output_bitarr[output_bit_idx_end / kBitsPerWord]); uintptr_t cur_output_word = 0; uint32_t read_widx = UINT32_MAX; // deliberate overflow uint32_t write_idx_lowbits = 0; while ((output_bitarr_iter != output_bitarr_last) || (write_idx_lowbits != output_bit_idx_end_lowbits)) { uintptr_t cur_mask_word; // sparse subset_mask optimization // guaranteed to terminate since there's at least one more set bit do { cur_mask_word = subset_mask[++read_widx]; } while (!cur_mask_word); uintptr_t cur_masked_input_word = raw_bitarr[read_widx] & cur_mask_word; const uint32_t cur_mask_popcount = PopcountWord(cur_mask_word); uintptr_t subsetted_input_word = 0; while (cur_masked_input_word) { const uintptr_t mask_word_high = (cur_mask_word | (cur_masked_input_word ^ (cur_masked_input_word - 1))) + 1; if (!mask_word_high) { subsetted_input_word |= cur_masked_input_word >> (kBitsPerWord - cur_mask_popcount); break; } const uint32_t cur_read_end = ctzw(mask_word_high); const uintptr_t bits_to_copy = cur_masked_input_word & (~mask_word_high); cur_masked_input_word ^= bits_to_copy; const uint32_t cur_write_end = PopcountWord(cur_mask_word & (~mask_word_high)); subsetted_input_word |= bits_to_copy >> (cur_read_end - cur_write_end); } cur_output_word |= subsetted_input_word << write_idx_lowbits; const uint32_t new_write_idx_lowbits = write_idx_lowbits + cur_mask_popcount; if (new_write_idx_lowbits >= kBitsPerWord) { *output_bitarr_iter++ = cur_output_word; // ...and these are the bits that fell off // bugfix: unsafe to right-shift 64 if (write_idx_lowbits) { cur_output_word = subsetted_input_word >> (kBitsPerWord - write_idx_lowbits); } else { cur_output_word = 0; } } write_idx_lowbits = new_write_idx_lowbits % kBitsPerWord; } if (write_idx_lowbits) { *output_bitarr_iter = cur_output_word; } } // Basic SSE2 implementation of Lauradoux/Walisch popcount. uintptr_t PopcountVecsNoAvx2(const VecW* bit_vvec, uintptr_t vec_ct) { // popcounts vptr[0..(vec_ct-1)]. Assumes vec_ct is a multiple of 3 (0 ok). assert(!(vec_ct % 3)); const VecW m0 = vecw_setzero(); const VecW m1 = VCONST_W(kMask5555); const VecW m2 = VCONST_W(kMask3333); const VecW m4 = VCONST_W(kMask0F0F); const VecW* bit_vvec_iter = bit_vvec; VecW prev_sad_result = vecw_setzero(); VecW acc = vecw_setzero(); uintptr_t cur_incr = 30; for (; ; vec_ct -= cur_incr) { if (vec_ct < 30) { if (!vec_ct) { acc = acc + prev_sad_result; return HsumW(acc); } cur_incr = vec_ct; } VecW inner_acc = vecw_setzero(); const VecW* bit_vvec_stop = &(bit_vvec_iter[cur_incr]); do { VecW count1 = *bit_vvec_iter++; VecW count2 = *bit_vvec_iter++; VecW half1 = *bit_vvec_iter++; VecW half2 = vecw_srli(half1, 1) & m1; half1 = half1 & m1; // Two bits can represent values from 0-3, so make each pair in count1 // count2 store a partial bitcount covering themselves AND another bit // from elsewhere. count1 = count1 - (vecw_srli(count1, 1) & m1); count2 = count2 - (vecw_srli(count2, 1) & m1); count1 = count1 + half1; count2 = count2 + half2; // Four bits represent 0-15, so we can safely add four 0-3 partial // bitcounts together. count1 = (count1 & m2) + (vecw_srli(count1, 2) & m2); count1 = count1 + (count2 & m2) + (vecw_srli(count2, 2) & m2); // Accumulator stores sixteen 0-255 counts in parallel. // (32 in AVX2 case, 4 in 32-bit case) inner_acc = inner_acc + (count1 & m4) + (vecw_srli(count1, 4) & m4); } while (bit_vvec_iter < bit_vvec_stop); // _mm_sad_epu8() has better throughput than the previous method of // horizontal-summing the bytes in inner_acc, by enough to compensate for // the loop length being reduced from 30 to 15 vectors, but it has high // latency. We work around that by waiting till the end of the next full // loop iteration to actually use the SAD result. acc = acc + prev_sad_result; prev_sad_result = vecw_bytesum(inner_acc, m0); } } static inline uintptr_t PopcountVecsNoAvx2Intersect(const VecW* __restrict vvec1_iter, const VecW* __restrict vvec2_iter, uintptr_t vec_ct) { // popcounts vvec1 AND vvec2[0..(ct-1)]. ct is a multiple of 3. assert(!(vec_ct % 3)); const VecW m0 = vecw_setzero(); const VecW m1 = VCONST_W(kMask5555); const VecW m2 = VCONST_W(kMask3333); const VecW m4 = VCONST_W(kMask0F0F); VecW prev_sad_result = vecw_setzero(); VecW acc = vecw_setzero(); uintptr_t cur_incr = 30; for (; ; vec_ct -= cur_incr) { if (vec_ct < 30) { if (!vec_ct) { acc = acc + prev_sad_result; return HsumW(acc); } cur_incr = vec_ct; } VecW inner_acc = vecw_setzero(); const VecW* vvec1_stop = &(vvec1_iter[cur_incr]); do { VecW count1 = (*vvec1_iter++) & (*vvec2_iter++); VecW count2 = (*vvec1_iter++) & (*vvec2_iter++); VecW half1 = (*vvec1_iter++) & (*vvec2_iter++); const VecW half2 = vecw_srli(half1, 1) & m1; half1 = half1 & m1; count1 = count1 - (vecw_srli(count1, 1) & m1); count2 = count2 - (vecw_srli(count2, 1) & m1); count1 = count1 + half1; count2 = count2 + half2; count1 = (count1 & m2) + (vecw_srli(count1, 2) & m2); count1 = count1 + (count2 & m2) + (vecw_srli(count2, 2) & m2); inner_acc = inner_acc + (count1 & m4) + (vecw_srli(count1, 4) & m4); } while (vvec1_iter < vvec1_stop); acc = acc + prev_sad_result; prev_sad_result = vecw_bytesum(inner_acc, m0); } } uintptr_t PopcountWordsIntersect(const uintptr_t* __restrict bitvec1_iter, const uintptr_t* __restrict bitvec2_iter, uintptr_t word_ct) { uintptr_t tot = 0; const uintptr_t* bitvec1_end = &(bitvec1_iter[word_ct]); const uintptr_t trivec_ct = word_ct / (3 * kWordsPerVec); tot += PopcountVecsNoAvx2Intersect(R_CAST(const VecW*, bitvec1_iter), R_CAST(const VecW*, bitvec2_iter), trivec_ct * 3); bitvec1_iter = &(bitvec1_iter[trivec_ct * (3 * kWordsPerVec)]); bitvec2_iter = &(bitvec2_iter[trivec_ct * (3 * kWordsPerVec)]); while (bitvec1_iter < bitvec1_end) { tot += PopcountWord((*bitvec1_iter++) & (*bitvec2_iter++)); } return tot; } void ExpandBytearr(const void* __restrict compact_bitarr, const uintptr_t* __restrict expand_mask, uint32_t word_ct, uint32_t expand_size, uint32_t read_start_bit, uintptr_t* __restrict target) { ZeroWArr(word_ct, target); const uintptr_t* compact_bitarr_alias = S_CAST(const uintptr_t*, compact_bitarr); const uint32_t expand_sizex_m1 = expand_size + read_start_bit - 1; const uint32_t compact_widx_last = expand_sizex_m1 / kBitsPerWord; uint32_t compact_idx_lowbits = read_start_bit; uint32_t loop_len = kBitsPerWord; uintptr_t write_widx = 0; uintptr_t expand_mask_bits = expand_mask[0]; for (uint32_t compact_widx = 0; ; ++compact_widx) { uintptr_t compact_word; if (compact_widx >= compact_widx_last) { if (compact_widx > compact_widx_last) { return; } loop_len = 1 + (expand_sizex_m1 % kBitsPerWord); // avoid possible segfault compact_word = SubwordLoad(&(compact_bitarr_alias[compact_widx]), DivUp(loop_len, CHAR_BIT)); } else { # ifdef __arm__ # error "Unaligned accesses in ExpandBytearr()." # endif compact_word = compact_bitarr_alias[compact_widx]; } for (; compact_idx_lowbits != loop_len; ++compact_idx_lowbits) { const uintptr_t lowbit = BitIter1y(expand_mask, &write_widx, &expand_mask_bits); // bugfix: can't just use (compact_word & 1) and compact_word >>= 1, // since we may skip the first bit on the first loop iteration if ((compact_word >> compact_idx_lowbits) & 1) { target[write_widx] |= lowbit; } } compact_idx_lowbits = 0; } } void ExpandThenSubsetBytearr(const void* __restrict compact_bitarr, const uintptr_t* __restrict expand_mask, const uintptr_t* __restrict subset_mask, uint32_t expand_size, uint32_t subset_size, uint32_t read_start_bit, uintptr_t* __restrict target) { const uint32_t expand_sizex_m1 = expand_size + read_start_bit - 1; const uint32_t leading_byte_ct = 1 + (expand_sizex_m1 % kBitsPerWord) / CHAR_BIT; uint32_t read_idx_lowbits = CHAR_BIT * (sizeof(intptr_t) - leading_byte_ct); uintptr_t compact_read_word = SubwordLoad(compact_bitarr, leading_byte_ct) << read_idx_lowbits; read_idx_lowbits += read_start_bit; const uintptr_t* compact_bitarr_iter = R_CAST(const uintptr_t*, &(S_CAST(const unsigned char*, compact_bitarr)[leading_byte_ct])); const uint32_t subset_size_lowbits = subset_size % kBitsPerWord; uintptr_t* target_iter = target; uintptr_t* target_last = &(target[subset_size / kBitsPerWord]); uintptr_t compact_write_word = 0; uint32_t read_widx = 0; // further improvement is probably possible (e.g. use AVX2 lazy-load), but // I'll postpone for now uint32_t write_idx_lowbits = 0; while ((target_iter != target_last) || (write_idx_lowbits != subset_size_lowbits)) { const uintptr_t subset_word = subset_mask[read_widx]; const uintptr_t expand_word = expand_mask[read_widx]; ++read_widx; uintptr_t tmp_compact_write_word = 0; if (expand_word) { const uint32_t expand_bit_ct = PopcountWord(expand_word); uint32_t read_idx_lowbits_end = read_idx_lowbits + expand_bit_ct; uintptr_t tmp_compact_read_word = 0; if (read_idx_lowbits != kBitsPerWord) { tmp_compact_read_word = compact_read_word >> read_idx_lowbits; } if (read_idx_lowbits_end > kBitsPerWord) { # ifdef __arm__ # error "Unaligned accesses in ExpandThenSubsetBytearr()." # endif compact_read_word = *compact_bitarr_iter++; tmp_compact_read_word |= compact_read_word << (kBitsPerWord - read_idx_lowbits); read_idx_lowbits_end -= kBitsPerWord; } tmp_compact_read_word = bzhi_max(tmp_compact_read_word, expand_bit_ct); read_idx_lowbits = read_idx_lowbits_end; if (tmp_compact_read_word) { uintptr_t cur_intersect = subset_word & expand_word; while (cur_intersect) { const uintptr_t cur_intersect_and_arg = cur_intersect - k1LU; const uintptr_t lowmask = (cur_intersect ^ cur_intersect_and_arg) >> 1; const uint32_t read_idx_offset = PopcountWord(expand_word & lowmask); uintptr_t shifted_compact_read_word = tmp_compact_read_word >> read_idx_offset; if (shifted_compact_read_word & 1) { tmp_compact_write_word |= (k1LU << PopcountWord(subset_word & lowmask)); if (shifted_compact_read_word == 1) { break; } } cur_intersect &= cur_intersect_and_arg; } } compact_write_word |= tmp_compact_write_word << write_idx_lowbits; } const uint32_t write_idx_lowbits_end = write_idx_lowbits + PopcountWord(subset_word); if (write_idx_lowbits_end >= kBitsPerWord) { *target_iter++ = compact_write_word; if (write_idx_lowbits) { compact_write_word = tmp_compact_write_word >> (kBitsPerWord - write_idx_lowbits); } else { compact_write_word = 0; } } write_idx_lowbits = write_idx_lowbits_end % kBitsPerWord; } if (write_idx_lowbits) { *target_iter = compact_write_word; } } // compact_bitarr := phaseinfo // mid_bitarr := phasepresent, [1 + het_ct] // top_expand_mask := all_hets, [raw_sample_ct] void ExpandBytearrNested(const void* __restrict compact_bitarr, const uintptr_t* __restrict mid_bitarr, const uintptr_t* __restrict top_expand_mask, uint32_t word_ct, uint32_t mid_popcount, uint32_t mid_start_bit, uintptr_t* __restrict mid_target, uintptr_t* __restrict compact_target) { ZeroWArr(word_ct, mid_target); ZeroWArr(word_ct, compact_target); const uintptr_t* compact_bitarr_alias = S_CAST(const uintptr_t*, compact_bitarr); const uint32_t mid_popcount_m1 = mid_popcount - 1; const uint32_t compact_widx_last = mid_popcount_m1 / kBitsPerWord; uint32_t mid_idx = mid_start_bit; // can allow compact_idx_lowbits to be initialized to nonzero uint32_t loop_len = kBitsPerWord; uintptr_t write_widx = 0; uintptr_t top_expand_mask_bits = top_expand_mask[0]; for (uint32_t compact_widx = 0; ; ++compact_widx) { uintptr_t compact_word; if (compact_widx >= compact_widx_last) { if (compact_widx > compact_widx_last) { return; } loop_len = 1 + (mid_popcount_m1 % kBitsPerWord); // avoid possible segfault compact_word = SubwordLoad(&(compact_bitarr_alias[compact_widx]), DivUp(loop_len, CHAR_BIT)); } else { #ifdef __arm__ # error "Unaligned accesses in ExpandBytearrNested()." #endif compact_word = compact_bitarr_alias[compact_widx]; } for (uint32_t compact_idx_lowbits = 0; compact_idx_lowbits != loop_len; ++mid_idx) { const uintptr_t lowbit = BitIter1y(top_expand_mask, &write_widx, &top_expand_mask_bits); if (IsSet(mid_bitarr, mid_idx)) { mid_target[write_widx] |= lowbit; compact_target[write_widx] |= lowbit * (compact_word & 1); compact_word >>= 1; ++compact_idx_lowbits; } } } } void ExpandThenSubsetBytearrNested(const void* __restrict compact_bitarr, const uintptr_t* __restrict mid_bitarr, const uintptr_t* __restrict top_expand_mask, const uintptr_t* __restrict subset_mask, uint32_t subset_size, uint32_t mid_popcount, uint32_t mid_start_bit, uintptr_t* __restrict mid_target, uintptr_t* __restrict compact_target) { assert(mid_popcount); const uint32_t leading_byte_ct = 1 + ((mid_popcount - 1) % kBitsPerWord) / CHAR_BIT; uint32_t compact_idx_lowbits = CHAR_BIT * (sizeof(intptr_t) - leading_byte_ct); uintptr_t compact_read_word = SubwordLoad(compact_bitarr, leading_byte_ct) << compact_idx_lowbits; const uintptr_t* compact_bitarr_iter = R_CAST(const uintptr_t*, &(S_CAST(const unsigned char*, compact_bitarr)[leading_byte_ct])); // bugfix (12 Apr 2018): need to round down here const uint32_t subset_size_dl = subset_size / kBitsPerWord; const uint32_t subset_size_lowbits = subset_size % kBitsPerWord; const uintptr_t* mid_read_iter = mid_bitarr; uintptr_t mid_read_word = *mid_read_iter++; uintptr_t mid_write_word = 0; uintptr_t compact_write_word = 0; uint32_t mid_idx_lowbits = mid_start_bit; uint32_t write_idx_lowbits = 0; uint32_t write_widx = 0; uint32_t read_widx = 0; while ((write_widx != subset_size_dl) || (write_idx_lowbits != subset_size_lowbits)) { const uintptr_t subset_word = subset_mask[read_widx]; const uintptr_t top_word = top_expand_mask[read_widx]; ++read_widx; uintptr_t tmp_mid_write_word = 0; uintptr_t tmp_compact_write_word = 0; if (top_word) { const uint32_t top_set_ct = PopcountWord(top_word); uint32_t mid_idx_lowbits_end = mid_idx_lowbits + top_set_ct; uintptr_t tmp_mid_read_word = 0; if (mid_idx_lowbits != kBitsPerWord) { tmp_mid_read_word = mid_read_word >> mid_idx_lowbits; } if (mid_idx_lowbits_end > kBitsPerWord) { // be paranoid for now re: reading an extra word off the end of // mid_bitarr mid_read_word = *mid_read_iter++; tmp_mid_read_word |= mid_read_word << (kBitsPerWord - mid_idx_lowbits); mid_idx_lowbits_end -= kBitsPerWord; } tmp_mid_read_word = bzhi_max(tmp_mid_read_word, top_set_ct); mid_idx_lowbits = mid_idx_lowbits_end; if (tmp_mid_read_word) { const uint32_t mid_set_ct = PopcountWord(tmp_mid_read_word); uintptr_t tmp_compact_read_word; if (compact_idx_lowbits != kBitsPerWord) { const uint32_t compact_idx_lowbits_end = compact_idx_lowbits + mid_set_ct; tmp_compact_read_word = compact_read_word >> compact_idx_lowbits; // avoid reading off end of compact_bitarr here if (compact_idx_lowbits_end <= kBitsPerWord) { compact_idx_lowbits = compact_idx_lowbits_end; } else { #ifdef __arm__ # error "Unaligned accesses in ExpandThenSubsetBytearrNested()." #endif compact_read_word = *compact_bitarr_iter++; tmp_compact_read_word |= compact_read_word << (kBitsPerWord - compact_idx_lowbits); compact_idx_lowbits = compact_idx_lowbits_end - kBitsPerWord; } } else { // special case, can't right-shift 64 compact_read_word = *compact_bitarr_iter++; compact_idx_lowbits = mid_set_ct; tmp_compact_read_word = compact_read_word; } tmp_compact_read_word = bzhi_max(tmp_compact_read_word, mid_set_ct); uintptr_t cur_masked_top = subset_word & top_word; while (cur_masked_top) { const uintptr_t cur_masked_top_and_arg = cur_masked_top - k1LU; const uintptr_t lowmask = (cur_masked_top ^ cur_masked_top_and_arg) >> 1; const uint32_t read_idx_offset = PopcountWord(top_word & lowmask); uintptr_t shifted_mid_read_word = tmp_mid_read_word >> read_idx_offset; if (shifted_mid_read_word & 1) { // bugfix (7 Sep 2017): forgot the "k1LU << " part of this const uintptr_t cur_bit = k1LU << PopcountWord(subset_word & lowmask); tmp_mid_write_word |= cur_bit; tmp_compact_write_word += cur_bit * ((tmp_compact_read_word >> (mid_set_ct - PopcountWord(shifted_mid_read_word))) & 1); if (shifted_mid_read_word == 1) { break; } } cur_masked_top &= cur_masked_top_and_arg; } } mid_write_word |= tmp_mid_write_word << write_idx_lowbits; compact_write_word |= tmp_compact_write_word << write_idx_lowbits; } const uint32_t write_idx_lowbits_end = write_idx_lowbits + PopcountWord(subset_word); if (write_idx_lowbits_end >= kBitsPerWord) { mid_target[write_widx] = mid_write_word; compact_target[write_widx] = compact_write_word; ++write_widx; if (write_idx_lowbits) { const uint32_t rshift = kBitsPerWord - write_idx_lowbits; mid_write_word = tmp_mid_write_word >> rshift; compact_write_word = tmp_compact_write_word >> rshift; } else { mid_write_word = 0; compact_write_word = 0; } } write_idx_lowbits = write_idx_lowbits_end % kBitsPerWord; } if (write_idx_lowbits) { mid_target[write_widx] = mid_write_word; compact_target[write_widx] = compact_write_word; } } #endif uintptr_t PopcountBytes(const void* bitarr, uintptr_t byte_ct) { const unsigned char* bitarr_uc = S_CAST(const unsigned char*, bitarr); const uint32_t lead_byte_ct = (-R_CAST(uintptr_t, bitarr_uc)) % kBytesPerVec; uintptr_t tot = 0; const uintptr_t* bitarr_iter; uint32_t trail_byte_ct; // bugfix: had wrong condition here if (byte_ct >= lead_byte_ct) { #ifdef __LP64__ const uint32_t word_rem = lead_byte_ct % kBytesPerWord; if (word_rem) { tot = PopcountWord(ProperSubwordLoad(bitarr_uc, word_rem)); } bitarr_iter = R_CAST(const uintptr_t*, &(bitarr_uc[word_rem])); if (lead_byte_ct >= kBytesPerWord) { tot += PopcountWord(*bitarr_iter++); # ifdef USE_AVX2 if (lead_byte_ct >= 2 * kBytesPerWord) { tot += PopcountWord(*bitarr_iter++); if (lead_byte_ct >= 3 * kBytesPerWord) { tot += PopcountWord(*bitarr_iter++); } } # endif } #else if (lead_byte_ct) { tot = PopcountWord(ProperSubwordLoad(bitarr_uc, lead_byte_ct)); } bitarr_iter = R_CAST(const uintptr_t*, &(bitarr_uc[lead_byte_ct])); #endif byte_ct -= lead_byte_ct; const uintptr_t word_ct = byte_ct / kBytesPerWord; // vec-alignment required here tot += PopcountWords(bitarr_iter, word_ct); bitarr_iter = &(bitarr_iter[word_ct]); trail_byte_ct = byte_ct % kBytesPerWord; } else { bitarr_iter = R_CAST(const uintptr_t*, bitarr_uc); // this may still be >= kBytesPerWord, so can't remove loop trail_byte_ct = byte_ct; } for (uint32_t bytes_remaining = trail_byte_ct; ; ) { uintptr_t cur_word; if (bytes_remaining < kBytesPerWord) { if (!bytes_remaining) { return tot; } cur_word = ProperSubwordLoad(bitarr_iter, bytes_remaining); bytes_remaining = 0; } else { cur_word = *bitarr_iter++; bytes_remaining -= kBytesPerWord; } tot += PopcountWord(cur_word); } } uintptr_t PopcountBytesMasked(const void* bitarr, const uintptr_t* mask_arr, uintptr_t byte_ct) { // todo: try modifying PopcountWordsIntersect() to use unaligned load // instructions; then, if there is no performance penalty, try modifying this // main loop to call it. const uintptr_t word_ct = byte_ct / kBytesPerWord; #ifdef USE_SSE42 const uintptr_t* bitarr_w = S_CAST(const uintptr_t*, bitarr); uintptr_t tot = 0; for (uintptr_t widx = 0; widx != word_ct; ++widx) { tot += PopcountWord(bitarr_w[widx] & mask_arr[widx]); } const uint32_t trail_byte_ct = byte_ct % kBytesPerWord; if (trail_byte_ct) { uintptr_t cur_word = ProperSubwordLoad(&(bitarr_w[word_ct]), trail_byte_ct); tot += PopcountWord(cur_word & mask_arr[word_ct]); } return tot; #else const uintptr_t* bitarr_iter = S_CAST(const uintptr_t*, bitarr); const uintptr_t mainblock_word_ct = word_ct - (word_ct % (24 / kBytesPerWord)); const uintptr_t* bitarr_24b_end = &(bitarr_iter[mainblock_word_ct]); const uintptr_t* mask_arr_iter = mask_arr; uintptr_t tot = 0; while (bitarr_iter < bitarr_24b_end) { uintptr_t loader = (*bitarr_iter++) & (*mask_arr_iter++); uintptr_t ulii = loader - ((loader >> 1) & kMask5555); loader = (*bitarr_iter++) & (*mask_arr_iter++); uintptr_t uljj = loader - ((loader >> 1) & kMask5555); loader = (*bitarr_iter++) & (*mask_arr_iter++); ulii += (loader >> 1) & kMask5555; uljj += loader & kMask5555; ulii = (ulii & kMask3333) + ((ulii >> 2) & kMask3333); ulii += (uljj & kMask3333) + ((uljj >> 2) & kMask3333); uintptr_t tmp_stor = (ulii & kMask0F0F) + ((ulii >> 4) & kMask0F0F); # ifndef __LP64__ loader = (*bitarr_iter++) & (*mask_arr_iter++); ulii = loader - ((loader >> 1) & kMask5555); loader = (*bitarr_iter++) & (*mask_arr_iter++); uljj = loader - ((loader >> 1) & kMask5555); loader = (*bitarr_iter++) & (*mask_arr_iter++); ulii += (loader >> 1) & kMask5555; uljj += loader & kMask5555; ulii = (ulii & kMask3333) + ((ulii >> 2) & kMask3333); ulii += (uljj & kMask3333) + ((uljj >> 2) & kMask3333); tmp_stor += (ulii & kMask0F0F) + ((ulii >> 4) & kMask0F0F); # endif // 32-bit case: each 8-bit slot stores a number in 0..48. Multiplying by // 0x01010101 is equivalent to the left-shifts and adds we need to sum // those four 8-bit numbers in the high-order slot. // 64-bit case: each 8-bit slot stores a number in 0..24. tot += (tmp_stor * kMask0101) >> (kBitsPerWord - 8); } for (uint32_t trail_byte_ct = byte_ct - (mainblock_word_ct * kBytesPerWord); ; ) { uintptr_t cur_word; if (trail_byte_ct < kBytesPerWord) { if (!trail_byte_ct) { return tot; } cur_word = ProperSubwordLoad(bitarr_iter, trail_byte_ct); trail_byte_ct = 0; } else { cur_word = *bitarr_iter++; trail_byte_ct -= kBytesPerWord; } tot += PopcountWord(cur_word & (*mask_arr_iter++)); } #endif } void FillCumulativePopcounts(const uintptr_t* subset_mask, uint32_t word_ct, uint32_t* cumulative_popcounts) { assert(word_ct); const uint32_t word_ct_m1 = word_ct - 1; uint32_t cur_sum = 0; for (uint32_t widx = 0; widx != word_ct_m1; ++widx) { cumulative_popcounts[widx] = cur_sum; cur_sum += PopcountWord(subset_mask[widx]); } cumulative_popcounts[word_ct_m1] = cur_sum; } void UidxsToIdxs(const uintptr_t* subset_mask, const uint32_t* subset_cumulative_popcounts, const uintptr_t idx_list_len, uint32_t* idx_list) { uint32_t* idx_list_end = &(idx_list[idx_list_len]); for (uint32_t* idx_list_iter = idx_list; idx_list_iter != idx_list_end; ++idx_list_iter) { *idx_list_iter = RawToSubsettedPos(subset_mask, subset_cumulative_popcounts, *idx_list_iter); } } void Expand1bitTo8(const void* __restrict bytearr, uint32_t input_bit_ct, uint32_t incr, uintptr_t* __restrict dst) { const unsigned char* bytearr_uc = S_CAST(const unsigned char*, bytearr); const uint32_t input_bit_ct_plus = input_bit_ct + kBytesPerWord - 1; #ifdef USE_SSE42 const uint32_t input_byte_ct = input_bit_ct_plus / 8; const uint32_t fullvec_ct = input_byte_ct / (kBytesPerVec / 8); uint32_t byte_idx = 0; if (fullvec_ct) { const Vec8thUint* bytearr_alias = R_CAST(const Vec8thUint*, bytearr); # ifdef USE_AVX2 const VecUc byte_gather = R_CAST(VecUc, _mm256_setr_epi64x(0, kMask0101, 2 * kMask0101, 3 * kMask0101)); const VecUc bit_mask = R_CAST(VecUc, _mm256_set1_epi64x(0x7fbfdfeff7fbfdfeLL)); # else const VecUc byte_gather = R_CAST(VecUc, _mm_setr_epi32(0, 0, 0x01010101, 0x01010101)); const VecUc bit_mask = R_CAST(VecUc, _mm_set1_epi64x(0x7fbfdfeff7fbfdfeLL)); # endif const VecUc all1 = vecuc_set1(255); const VecUc subfrom = vecuc_set1(incr); VecUc* dst_alias = R_CAST(VecUc*, dst); for (uint32_t vec_idx = 0; vec_idx != fullvec_ct; ++vec_idx) { # ifdef USE_AVX2 VecUc vmask = R_CAST(VecUc, _mm256_set1_epi32(bytearr_alias[vec_idx])); # else VecUc vmask = R_CAST(VecUc, _mm_set1_epi16(bytearr_alias[vec_idx])); # endif vmask = vecuc_shuffle8(vmask, byte_gather); vmask = vmask | bit_mask; vmask = (vmask == all1); const VecUc result = subfrom - vmask; vecuc_storeu(&(dst_alias[vec_idx]), result); } byte_idx = fullvec_ct * (kBytesPerVec / 8); } const uintptr_t incr_word = incr * kMask0101; for (; byte_idx != input_byte_ct; ++byte_idx) { const uintptr_t input_byte = bytearr_uc[byte_idx]; # ifdef USE_AVX2 const uintptr_t input_byte_scatter = _pdep_u64(input_byte, kMask0101); # else const uintptr_t input_byte_scatter = (((input_byte & 0xfe) * 0x2040810204080LLU) & kMask0101) | (input_byte & 1); # endif dst[byte_idx] = incr_word + input_byte_scatter; } #else const uintptr_t incr_word = incr * kMask0101; # ifdef __LP64__ const uint32_t input_byte_ct = input_bit_ct_plus / 8; for (uint32_t uii = 0; uii != input_byte_ct; ++uii) { // this operation maps binary hgfedcba to h0000000g0000000f... // ^ ^ ^ // | | | // 56 48 40 // 1. (cur_variant_include_word & 0xfe) gives us hgfedcb0; necessary to // avoid carryover. // 2. multiply by the number with bits 7, 14, 21, ..., 49 set, to get // hgfedcbhgfedcbhgf... // ^ ^ ^ // | | | // 56 48 40 // 3. mask out all but bits 8, 16, 24, ..., 56 // todo: test if this actually beats the per-character loop... const uintptr_t input_byte = bytearr_uc[uii]; const uintptr_t input_byte_scatter = (((input_byte & 0xfe) * 0x2040810204080LLU) & kMask0101) | (input_byte & 1); dst[uii] = incr_word + input_byte_scatter; } # else const uint32_t fullbyte_ct = input_bit_ct_plus / 8; for (uint32_t uii = 0; uii != fullbyte_ct; ++uii) { // dcba -> d0000000c0000000b0000000a const uintptr_t input_byte = bytearr_uc[uii]; uintptr_t input_byte_scatter = ((input_byte & 0xf) * 0x204081) & kMask0101; dst[2 * uii] = incr_word + input_byte_scatter; input_byte_scatter = ((input_byte >> 4) * 0x204081) & kMask0101; dst[2 * uii + 1] = incr_word + input_byte_scatter; } if (input_bit_ct_plus & 4) { uintptr_t input_byte = bytearr_uc[fullbyte_ct]; // input_bit_ct mod 8 in 1..4, so high bits zeroed out uintptr_t input_byte_scatter = (input_byte * 0x204081) & kMask0101; dst[2 * fullbyte_ct] = incr_word + input_byte_scatter; } # endif #endif } void Expand1bitTo16(const void* __restrict bytearr, uint32_t input_bit_ct, uint32_t incr, uintptr_t* __restrict dst) { const unsigned char* bytearr_uc = S_CAST(const unsigned char*, bytearr); #ifdef USE_SSE42 const uint32_t input_nybble_ct = DivUp(input_bit_ct, 4); const uint32_t fullvec_ct = input_nybble_ct / (kBytesPerVec / 8); uint32_t byte_idx = 0; if (fullvec_ct) { const Vec16thUint* bytearr_alias = R_CAST(const Vec16thUint*, bytearr); # ifdef USE_AVX2 const VecU16 byte_gather = R_CAST(VecU16, _mm256_setr_epi64x(0, 0, kMask0101, kMask0101)); const VecU16 bit_mask = R_CAST(VecU16, _mm256_set_epi32(0xff7fffbfU, 0xffdfffefU, 0xfff7fffbU, 0xfffdfffeU, 0xff7fffbfU, 0xffdfffefU, 0xfff7fffbU, 0xfffdfffeU)); # else const VecU16 byte_gather = VCONST_S(0); const VecU16 bit_mask = R_CAST(VecU16, _mm_set_epi32(0xff7fffbfU, 0xffdfffefU, 0xfff7fffbU, 0xfffdfffeU)); # endif const VecU16 all1 = VCONST_S(0xffff); const VecU16 subfrom = vecu16_set1(incr); VecU16* dst_alias = R_CAST(VecU16*, dst); // todo: check whether this is actually any better than the non-vectorized // loop for (uint32_t vec_idx = 0; vec_idx != fullvec_ct; ++vec_idx) { # ifdef USE_AVX2 VecU16 vmask = R_CAST(VecU16, _mm256_set1_epi16(bytearr_alias[vec_idx])); # else VecU16 vmask = R_CAST(VecU16, _mm_set1_epi8(bytearr_alias[vec_idx])); # endif vmask = vecu16_shuffle8(vmask, byte_gather); vmask = vmask | bit_mask; vmask = (vmask == all1); const VecU16 result = subfrom - vmask; vecu16_storeu(&(dst_alias[vec_idx]), result); } byte_idx = fullvec_ct * (kBytesPerVec / 16); } const uintptr_t incr_word = incr * kMask0001; const uint32_t fullbyte_ct = input_nybble_ct / 2; for (; byte_idx != fullbyte_ct; ++byte_idx) { const uintptr_t input_byte = bytearr_uc[byte_idx]; const uintptr_t input_byte_scatter = input_byte * 0x200040008001LLU; const uintptr_t write0 = input_byte_scatter & kMask0001; const uintptr_t write1 = (input_byte_scatter >> 4) & kMask0001; dst[2 * byte_idx] = incr_word + write0; dst[2 * byte_idx + 1] = incr_word + write1; } if (input_nybble_ct % 2) { const uintptr_t input_byte = bytearr_uc[byte_idx]; const uintptr_t write0 = (input_byte * 0x200040008001LLU) & kMask0001; dst[input_nybble_ct - 1] = incr_word + write0; } #else const uintptr_t incr_word = incr * kMask0001; # ifdef __LP64__ const uint32_t input_nybble_ct = DivUp(input_bit_ct, 4); const uint32_t fullbyte_ct = input_nybble_ct / 2; for (uint32_t uii = 0; uii != fullbyte_ct; ++uii) { const uintptr_t input_byte = bytearr_uc[uii]; const uintptr_t input_byte_scatter = input_byte * 0x200040008001LLU; const uintptr_t write0 = input_byte_scatter & kMask0001; const uintptr_t write1 = (input_byte_scatter >> 4) & kMask0001; dst[2 * uii] = incr_word + write0; dst[2 * uii + 1] = incr_word + write1; } if (input_nybble_ct % 2) { const uintptr_t input_byte = bytearr_uc[fullbyte_ct]; const uintptr_t write0 = (input_byte * 0x200040008001LLU) & kMask0001; dst[input_nybble_ct - 1] = incr_word + write0; } # else const uint32_t fullbyte_ct = input_bit_ct / 8; for (uint32_t uii = 0; uii != fullbyte_ct; ++uii) { uintptr_t input_byte = bytearr_uc[uii]; const uintptr_t input_byte_scatter = input_byte * 0x8001; dst[4 * uii] = (input_byte_scatter & kMask0001) + incr_word; dst[4 * uii + 1] = ((input_byte_scatter >> 2) & kMask0001) + incr_word; dst[4 * uii + 2] = ((input_byte_scatter >> 4) & kMask0001) + incr_word; dst[4 * uii + 3] = ((input_byte_scatter >> 6) & kMask0001) + incr_word; } const uint32_t remainder = input_bit_ct % 8; if (remainder) { uintptr_t input_byte = bytearr_uc[fullbyte_ct]; uint16_t* dst_alias = R_CAST(uint16_t*, &(dst[4 * fullbyte_ct])); for (uint32_t uii = 0; uii < remainder; ++uii) { dst_alias[uii] = (input_byte & 1) + incr; input_byte = input_byte >> 1; } } # endif #endif } static_assert(kPglBitTransposeBatch == S_CAST(uint32_t, kBitsPerCacheline), "TransposeBitblock64() needs to be updated."); #ifdef __LP64__ void TransposeBitblock64(const uintptr_t* read_iter, uintptr_t read_ul_stride, uintptr_t write_ul_stride, uint32_t read_row_ct, uint32_t write_row_ct, uintptr_t* write_iter, VecW* __restrict buf0, VecW* __restrict buf1) { // We need to perform the equivalent of 9 shuffles (assuming a full-size // 512x512 bitblock). // The first shuffles are performed by the ingestion loop: we write the first // word from every row to buf0, then the second word from every row, etc., // yielding // (0,0) ... (0,63) (1,0) ... (1,63) (2,0) ... (511,63) // (0,64) ... (0,127) (1,64) ... (1,127) (2,64) ... (511,127) // ... // (0,448) ... (0,511) (1,448) ... (1,511) (2,448) ... (511,511) // in terms of the original bit positions. // Since each input row has 8 words, this amounts to 3 shuffles. // // The second step writes // (0,0) (0,1) ... (0,7) (1,0) (1,1) ... (1,7) ... (511,7) // (0,8) (0,9) ... (0,15) (1,8) (1,9) ... (1,15) ... (511,15) // ... // (0,504) ... (0,511) (1,504) ... (1,511) ... (511,511) // to buf1, performing the equivalent of 3 shuffles, and the third step // finishes the transpose using movemask. // // buf0 and buf1 must both be 32KiB vector-aligned buffers. const uint32_t buf0_row_ct = DivUp(write_row_ct, 64); { uintptr_t* buf0_ul = R_CAST(uintptr_t*, buf0); const uint32_t zfill_ct = (-read_row_ct) & 63; for (uint32_t bidx = 0; bidx != buf0_row_ct; ++bidx) { const uintptr_t* read_iter_tmp = &(read_iter[bidx]); uintptr_t* buf0_row_start = &(buf0_ul[512 * bidx]); for (uint32_t uii = 0; uii != read_row_ct; ++uii) { buf0_row_start[uii] = *read_iter_tmp; read_iter_tmp = &(read_iter_tmp[read_ul_stride]); } // This is a simple way of fulfilling the trailing-zero part of the // function contract. // ( buf0 rows zeroed out to 512 bytes // -> buf1 rows zeroed out to 64 bytes // -> output rows zeroed out to 8 bytes) ZeroWArr(zfill_ct, &(buf0_row_start[read_row_ct])); } } // Each width-unit corresponds to 64 input rows. const uint32_t buf_row_xwidth = DivUp(read_row_ct, 64); { const VecW* buf0_read_iter = buf0; uintptr_t* write_iter0 = R_CAST(uintptr_t*, buf1); # ifdef USE_SSE42 const VecW gather_u16s = vecw_setr8(0, 8, 1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15); # ifdef USE_AVX2 const VecW gather_u32s = vecw_setr8(0, 1, 8, 9, 2, 3, 10, 11, 4, 5, 12, 13, 6, 7, 14, 15); # endif # else const VecW m8 = VCONST_W(kMask00FF); # endif const uint32_t buf0_row_clwidth = buf_row_xwidth * 8; for (uint32_t bidx = 0; bidx != buf0_row_ct; ++bidx) { uintptr_t* write_iter1 = &(write_iter0[64]); uintptr_t* write_iter2 = &(write_iter1[64]); uintptr_t* write_iter3 = &(write_iter2[64]); uintptr_t* write_iter4 = &(write_iter3[64]); uintptr_t* write_iter5 = &(write_iter4[64]); uintptr_t* write_iter6 = &(write_iter5[64]); uintptr_t* write_iter7 = &(write_iter6[64]); for (uint32_t clidx = 0; clidx != buf0_row_clwidth; ++clidx) { # ifdef USE_AVX2 VecW loader0 = buf0_read_iter[clidx * 2]; VecW loader1 = buf0_read_iter[clidx * 2 + 1]; // (0,0) (0,1) ... (0,7) (1,0) (1,1) ... (1,7) (2,0) ... (3,7) // -> (0,0) (1,0) (0,1) (1,1) (0,2) .... (1,7) (2,0) (3,0) (2,1) ... loader0 = vecw_shuffle8(loader0, gather_u16s); loader1 = vecw_shuffle8(loader1, gather_u16s); // -> (0,0) (1,0) (0,1) (1,1) (0,2) (1,2) (0,3) (1,3) (2,0) (3,0) ... VecW vec_lo = vecw_permute0xd8_if_avx2(loader0); VecW vec_hi = vecw_permute0xd8_if_avx2(loader1); // -> (0,0) (1,0) (2,0) (3,0) (0,1) (1,1) (2,1) (3,1) (0,2) ... vec_lo = vecw_shuffle8(vec_lo, gather_u32s); // -> (4,0) (5,0) (6,0) (7,0) (4,1) (5,1) (6,1) (7,1) (4,2) ... vec_hi = vecw_shuffle8(vec_hi, gather_u32s); const VecW final0145 = vecw_unpacklo32(vec_lo, vec_hi); const VecW final2367 = vecw_unpackhi32(vec_lo, vec_hi); write_iter0[clidx] = vecw_extract64_0(final0145); write_iter1[clidx] = vecw_extract64_1(final0145); write_iter2[clidx] = vecw_extract64_0(final2367); write_iter3[clidx] = vecw_extract64_1(final2367); write_iter4[clidx] = vecw_extract64_2(final0145); write_iter5[clidx] = vecw_extract64_3(final0145); write_iter6[clidx] = vecw_extract64_2(final2367); write_iter7[clidx] = vecw_extract64_3(final2367); # else // !USE_AVX2 VecW loader0 = buf0_read_iter[clidx * 4]; VecW loader1 = buf0_read_iter[clidx * 4 + 1]; VecW loader2 = buf0_read_iter[clidx * 4 + 2]; VecW loader3 = buf0_read_iter[clidx * 4 + 3]; // (0,0) (0,1) ... (0,7) (1,0) (1,1) ... (1,7) // -> (0,0) (1,0) (0,1) (1,1) (0,2) ... (1,7) # ifdef USE_SSE42 loader0 = vecw_shuffle8(loader0, gather_u16s); loader1 = vecw_shuffle8(loader1, gather_u16s); loader2 = vecw_shuffle8(loader2, gather_u16s); loader3 = vecw_shuffle8(loader3, gather_u16s); # else VecW tmp_lo = vecw_unpacklo8(loader0, loader1); VecW tmp_hi = vecw_unpackhi8(loader0, loader1); loader0 = vecw_blendv(vecw_slli(tmp_hi, 8), tmp_lo, m8); loader1 = vecw_blendv(tmp_hi, vecw_srli(tmp_lo, 8), m8); tmp_lo = vecw_unpacklo8(loader2, loader3); tmp_hi = vecw_unpackhi8(loader2, loader3); loader2 = vecw_blendv(vecw_slli(tmp_hi, 8), tmp_lo, m8); loader3 = vecw_blendv(tmp_hi, vecw_srli(tmp_lo, 8), m8); # endif // -> (0,0) (1,0) (2,0) (3,0) (0,1) (1,1) (2,1) (3,1) (0,2) ... const VecW lo_0123 = vecw_unpacklo16(loader0, loader1); // -> (0,4) (1,4) (2,4) (3,4) (0,5) (1,5) (2,5) (3,5) (0,6) ... const VecW lo_4567 = vecw_unpackhi16(loader0, loader1); const VecW hi_0123 = vecw_unpacklo16(loader2, loader3); const VecW hi_4567 = vecw_unpackhi16(loader2, loader3); VecW final01 = vecw_unpacklo32(lo_0123, hi_0123); VecW final23 = vecw_unpackhi32(lo_0123, hi_0123); VecW final45 = vecw_unpacklo32(lo_4567, hi_4567); VecW final67 = vecw_unpackhi32(lo_4567, hi_4567); write_iter0[clidx] = vecw_extract64_0(final01); write_iter1[clidx] = vecw_extract64_1(final01); write_iter2[clidx] = vecw_extract64_0(final23); write_iter3[clidx] = vecw_extract64_1(final23); write_iter4[clidx] = vecw_extract64_0(final45); write_iter5[clidx] = vecw_extract64_1(final45); write_iter6[clidx] = vecw_extract64_0(final67); write_iter7[clidx] = vecw_extract64_1(final67); # endif // !USE_AVX2 } buf0_read_iter = &(buf0_read_iter[512 / kWordsPerVec]); write_iter0 = &(write_iter7[64]); } } const VecW* buf1_read_iter = buf1; const uint32_t write_v8ui_stride = kVec8thUintPerWord * write_ul_stride; const uint32_t buf1_fullrow_ct = write_row_ct / 8; const uint32_t buf1_row_vecwidth = buf_row_xwidth * (8 / kWordsPerVec); Vec8thUint* write_iter0 = R_CAST(Vec8thUint*, write_iter); for (uint32_t bidx = 0; bidx != buf1_fullrow_ct; ++bidx) { Vec8thUint* write_iter1 = &(write_iter0[write_v8ui_stride]); Vec8thUint* write_iter2 = &(write_iter1[write_v8ui_stride]); Vec8thUint* write_iter3 = &(write_iter2[write_v8ui_stride]); Vec8thUint* write_iter4 = &(write_iter3[write_v8ui_stride]); Vec8thUint* write_iter5 = &(write_iter4[write_v8ui_stride]); Vec8thUint* write_iter6 = &(write_iter5[write_v8ui_stride]); Vec8thUint* write_iter7 = &(write_iter6[write_v8ui_stride]); for (uint32_t vidx = 0; vidx != buf1_row_vecwidth; ++vidx) { VecW loader = buf1_read_iter[vidx]; write_iter7[vidx] = vecw_movemask(loader); loader = vecw_slli(loader, 1); write_iter6[vidx] = vecw_movemask(loader); loader = vecw_slli(loader, 1); write_iter5[vidx] = vecw_movemask(loader); loader = vecw_slli(loader, 1); write_iter4[vidx] = vecw_movemask(loader); loader = vecw_slli(loader, 1); write_iter3[vidx] = vecw_movemask(loader); loader = vecw_slli(loader, 1); write_iter2[vidx] = vecw_movemask(loader); loader = vecw_slli(loader, 1); write_iter1[vidx] = vecw_movemask(loader); loader = vecw_slli(loader, 1); write_iter0[vidx] = vecw_movemask(loader); } buf1_read_iter = &(buf1_read_iter[64 / kWordsPerVec]); write_iter0 = &(write_iter7[write_v8ui_stride]); } const uint32_t row_ct_rem = write_row_ct % 8; if (!row_ct_rem) { return; } const uint32_t lshift = 8 - row_ct_rem; Vec8thUint* write_iter_last = &(write_iter0[write_v8ui_stride * (row_ct_rem - 1)]); for (uint32_t vidx = 0; vidx != buf1_row_vecwidth; ++vidx) { VecW loader = buf1_read_iter[vidx]; loader = vecw_slli(loader, lshift); Vec8thUint* inner_write_iter = &(write_iter_last[vidx]); for (uint32_t uii = 0; uii != row_ct_rem; ++uii) { *inner_write_iter = vecw_movemask(loader); loader = vecw_slli(loader, 1); inner_write_iter -= write_v8ui_stride; } } } #else // !__LP64__ static_assert(kWordsPerVec == 1, "TransposeBitblock32() needs to be updated."); void TransposeBitblock32(const uintptr_t* read_iter, uintptr_t read_ul_stride, uintptr_t write_ul_stride, uint32_t read_batch_size, uint32_t write_batch_size, uintptr_t* write_iter, VecW* __restrict buf0, VecW* __restrict buf1) { // buf must be vector-aligned and have size 64k const uint32_t initial_read_byte_ct = DivUp(write_batch_size, CHAR_BIT); // fold the first 6 shuffles into the initial ingestion loop const unsigned char* initial_read_iter = R_CAST(const unsigned char*, read_iter); const unsigned char* initial_read_end = &(initial_read_iter[initial_read_byte_ct]); unsigned char* initial_target_iter = R_CAST(unsigned char*, buf0); const uint32_t read_byte_stride = read_ul_stride * kBytesPerWord; const uint32_t read_batch_rem = kBitsPerCacheline - read_batch_size; for (; initial_read_iter != initial_read_end; ++initial_read_iter) { const unsigned char* read_iter_tmp = initial_read_iter; for (uint32_t ujj = 0; ujj != read_batch_size; ++ujj) { *initial_target_iter++ = *read_iter_tmp; read_iter_tmp = &(read_iter_tmp[read_byte_stride]); } initial_target_iter = memsetua(initial_target_iter, 0, read_batch_rem); } // third-to-last shuffle, 8 bit spacing -> 4 const VecW* source_iter = buf0; uintptr_t* target_iter0 = buf1; const uint32_t write_word_ct = BitCtToWordCt(read_batch_size); const uint32_t first_inner_loop_iter_ct = 4 * write_word_ct; uint32_t cur_write_skip = 4 * kWordsPerCacheline - first_inner_loop_iter_ct; // coincidentally, this also needs to run DivUp(write_batch_size, CHAR_BIT) // times for (uint32_t uii = 0; uii != initial_read_byte_ct; ++uii) { uintptr_t* target_iter1 = &(target_iter0[kWordsPerCacheline * 4]); for (uint32_t ujj = 0; ujj != first_inner_loop_iter_ct; ++ujj) { const uintptr_t source_word_lo = *source_iter++; const uintptr_t source_word_hi = *source_iter++; uintptr_t target_word0_lo = source_word_lo & kMask0F0F; uintptr_t target_word1_lo = (source_word_lo >> 4) & kMask0F0F; uintptr_t target_word0_hi = source_word_hi & kMask0F0F; uintptr_t target_word1_hi = (source_word_hi >> 4) & kMask0F0F; target_word0_lo = (target_word0_lo | (target_word0_lo >> 4)) & kMask00FF; target_word1_lo = (target_word1_lo | (target_word1_lo >> 4)) & kMask00FF; target_word0_hi = (target_word0_hi | (target_word0_hi >> 4)) & kMask00FF; target_word1_hi = (target_word1_hi | (target_word1_hi >> 4)) & kMask00FF; target_word0_lo = target_word0_lo | (target_word0_lo >> kBitsPerWordD4); target_word1_lo = target_word1_lo | (target_word1_lo >> kBitsPerWordD4); target_word0_hi = target_word0_hi | (target_word0_hi >> kBitsPerWordD4); target_word1_hi = target_word1_hi | (target_word1_hi >> kBitsPerWordD4); *target_iter0++ = S_CAST(Halfword, target_word0_lo) | (target_word0_hi << kBitsPerWordD2); *target_iter1++ = S_CAST(Halfword, target_word1_lo) | (target_word1_hi << kBitsPerWordD2); } source_iter = &(source_iter[2 * cur_write_skip]); target_iter0 = &(target_iter1[cur_write_skip]); } // second-to-last shuffle, 4 bit spacing -> 2 source_iter = buf1; target_iter0 = buf0; const uint32_t second_outer_loop_iter_ct = DivUp(write_batch_size, 4); const uint32_t second_inner_loop_iter_ct = 2 * write_word_ct; cur_write_skip = 2 * kWordsPerCacheline - second_inner_loop_iter_ct; for (uint32_t uii = 0; uii != second_outer_loop_iter_ct; ++uii) { uintptr_t* target_iter1 = &(target_iter0[kWordsPerCacheline * 2]); for (uint32_t ujj = 0; ujj != second_inner_loop_iter_ct; ++ujj) { const uintptr_t source_word_lo = *source_iter++; const uintptr_t source_word_hi = *source_iter++; uintptr_t target_word0_lo = source_word_lo & kMask3333; uintptr_t target_word1_lo = (source_word_lo >> 2) & kMask3333; uintptr_t target_word0_hi = source_word_hi & kMask3333; uintptr_t target_word1_hi = (source_word_hi >> 2) & kMask3333; target_word0_lo = (target_word0_lo | (target_word0_lo >> 2)) & kMask0F0F; target_word1_lo = (target_word1_lo | (target_word1_lo >> 2)) & kMask0F0F; target_word0_hi = (target_word0_hi | (target_word0_hi >> 2)) & kMask0F0F; target_word1_hi = (target_word1_hi | (target_word1_hi >> 2)) & kMask0F0F; target_word0_lo = (target_word0_lo | (target_word0_lo >> 4)) & kMask00FF; target_word1_lo = (target_word1_lo | (target_word1_lo >> 4)) & kMask00FF; target_word0_hi = (target_word0_hi | (target_word0_hi >> 4)) & kMask00FF; target_word1_hi = (target_word1_hi | (target_word1_hi >> 4)) & kMask00FF; target_word0_lo = target_word0_lo | (target_word0_lo >> kBitsPerWordD4); target_word1_lo = target_word1_lo | (target_word1_lo >> kBitsPerWordD4); target_word0_hi = target_word0_hi | (target_word0_hi >> kBitsPerWordD4); target_word1_hi = target_word1_hi | (target_word1_hi >> kBitsPerWordD4); *target_iter0++ = S_CAST(Halfword, target_word0_lo) | (target_word0_hi << kBitsPerWordD2); *target_iter1++ = S_CAST(Halfword, target_word1_lo) | (target_word1_hi << kBitsPerWordD2); } source_iter = &(source_iter[2 * cur_write_skip]); target_iter0 = &(target_iter1[cur_write_skip]); } // last shuffle, 2 bit spacing -> 1 source_iter = buf0; target_iter0 = write_iter; const uint32_t last_loop_iter_ct = DivUp(write_batch_size, 2); for (uint32_t uii = 0; uii != last_loop_iter_ct; ++uii) { uintptr_t* target_iter1 = &(target_iter0[write_ul_stride]); for (uint32_t ujj = 0; ujj != write_word_ct; ++ujj) { const uintptr_t source_word_lo = S_CAST(uintptr_t, *source_iter++); const uintptr_t source_word_hi = S_CAST(uintptr_t, *source_iter++); uintptr_t target_word0_lo = source_word_lo & kMask5555; uintptr_t target_word1_lo = (source_word_lo >> 1) & kMask5555; uintptr_t target_word0_hi = source_word_hi & kMask5555; uintptr_t target_word1_hi = (source_word_hi >> 1) & kMask5555; target_word0_lo = (target_word0_lo | (target_word0_lo >> 1)) & kMask3333; target_word1_lo = (target_word1_lo | (target_word1_lo >> 1)) & kMask3333; target_word0_hi = (target_word0_hi | (target_word0_hi >> 1)) & kMask3333; target_word1_hi = (target_word1_hi | (target_word1_hi >> 1)) & kMask3333; target_word0_lo = (target_word0_lo | (target_word0_lo >> 2)) & kMask0F0F; target_word1_lo = (target_word1_lo | (target_word1_lo >> 2)) & kMask0F0F; target_word0_hi = (target_word0_hi | (target_word0_hi >> 2)) & kMask0F0F; target_word1_hi = (target_word1_hi | (target_word1_hi >> 2)) & kMask0F0F; target_word0_lo = (target_word0_lo | (target_word0_lo >> 4)) & kMask00FF; target_word1_lo = (target_word1_lo | (target_word1_lo >> 4)) & kMask00FF; target_word0_hi = (target_word0_hi | (target_word0_hi >> 4)) & kMask00FF; target_word1_hi = (target_word1_hi | (target_word1_hi >> 4)) & kMask00FF; target_word0_lo = target_word0_lo | (target_word0_lo >> kBitsPerWordD4); target_word1_lo = target_word1_lo | (target_word1_lo >> kBitsPerWordD4); target_word0_hi = target_word0_hi | (target_word0_hi >> kBitsPerWordD4); target_word1_hi = target_word1_hi | (target_word1_hi >> kBitsPerWordD4); target_iter0[ujj] = S_CAST(Halfword, target_word0_lo) | (target_word0_hi << kBitsPerWordD2); target_iter1[ujj] = S_CAST(Halfword, target_word1_lo) | (target_word1_hi << kBitsPerWordD2); } source_iter = &(source_iter[2 * (kWordsPerCacheline - write_word_ct)]); target_iter0 = &(target_iter1[write_ul_stride]); } } #endif // !__LP64__ #ifdef __LP64__ void TransposeNybbleblock(const uintptr_t* read_iter, uint32_t read_ul_stride, uint32_t write_ul_stride, uint32_t read_batch_size, uint32_t write_batch_size, uintptr_t* __restrict write_iter, VecW* vecaligned_buf) { // Very similar to TransposeNypblock64() in pgenlib_internal. // vecaligned_buf must be vector-aligned and have size 8k const uint32_t buf_row_ct = DivUp(write_batch_size, 8); // fold the first 4 shuffles into the initial ingestion loop const uint32_t* initial_read_iter = R_CAST(const uint32_t*, read_iter); const uint32_t* initial_read_end = &(initial_read_iter[buf_row_ct]); uint32_t* initial_target_iter = R_CAST(uint32_t*, vecaligned_buf); const uint32_t read_u32_stride = read_ul_stride * (kBytesPerWord / 4); const uint32_t read_batch_rem = kNybblesPerCacheline - read_batch_size; for (; initial_read_iter != initial_read_end; ++initial_read_iter) { const uint32_t* read_iter_tmp = initial_read_iter; for (uint32_t ujj = 0; ujj != read_batch_size; ++ujj) { *initial_target_iter++ = *read_iter_tmp; read_iter_tmp = &(read_iter_tmp[read_u32_stride]); } if (!read_batch_rem) { continue; } memset(initial_target_iter, 0, read_batch_rem * 4); initial_target_iter = &(initial_target_iter[read_batch_rem]); } // 32 bit spacing -> 4 const VecW* source_iter = vecaligned_buf; const VecW m4 = VCONST_W(kMask0F0F); const uint32_t buf_fullrow_ct = write_batch_size / 8; const uint32_t eightword_ct = DivUp(read_batch_size, 16); uintptr_t* target_iter0 = write_iter; uint32_t cur_dst_row_ct = 8; # ifdef USE_SSE42 const VecW gather_u16s = vecw_setr8(0, 8, 1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15); # else const VecW m8 = VCONST_W(kMask00FF); # endif # ifdef USE_AVX2 // movemask is slower even in AVX2 case const VecW gather_u32s = vecw_setr8(0, 1, 8, 9, 2, 3, 10, 11, 4, 5, 12, 13, 6, 7, 14, 15); for (uint32_t buf_row_idx = 0; ; ++buf_row_idx) { if (buf_row_idx >= buf_fullrow_ct) { if (buf_row_idx == buf_row_ct) { return; } cur_dst_row_ct = write_batch_size % 8; } uintptr_t* target_iter1 = &(target_iter0[write_ul_stride]); uintptr_t* target_iter2 = &(target_iter1[write_ul_stride]); uintptr_t* target_iter3 = &(target_iter2[write_ul_stride]); uintptr_t* target_iter4 = &(target_iter3[write_ul_stride]); uintptr_t* target_iter5 = &(target_iter4[write_ul_stride]); uintptr_t* target_iter6 = &(target_iter5[write_ul_stride]); uintptr_t* target_iter7 = &(target_iter6[write_ul_stride]); for (uint32_t dvidx = 0; dvidx != eightword_ct; ++dvidx) { const VecW loader0 = source_iter[dvidx * 2]; const VecW loader1 = source_iter[dvidx * 2 + 1]; VecW even_nybbles0 = loader0 & m4; VecW odd_nybbles0 = vecw_and_notfirst(m4, loader0); VecW even_nybbles1 = loader1 & m4; VecW odd_nybbles1 = vecw_and_notfirst(m4, loader1); even_nybbles0 = even_nybbles0 | vecw_srli(even_nybbles0, 28); odd_nybbles0 = vecw_slli(odd_nybbles0, 28) | odd_nybbles0; even_nybbles1 = even_nybbles1 | vecw_srli(even_nybbles1, 28); odd_nybbles1 = vecw_slli(odd_nybbles1, 28) | odd_nybbles1; // Label the bytes in even_nybbles0 (0, 1, 2, ..., 31), and the bytes in // even_nybbles1 (32, 33, ..., 63). We wish to generate the following // lane-and-vector-crossing permutation: // (0, 8, 16, 24, 32, 40, 48, 56, 1, 9, 17, 25, 33, 41, 49, 57) // (2, 10, 18, 26, 34, 42, 50, 58, 3, 11, 19, 27, 35, 43, 51, 59) // first shuffle: // (0, 8, 1, 9, 2, 10, 3, 11, _, _, _, _, _, _, _, _, // 16, 24, 17, 25, 18, 26, 19, 27, _, _, _, _, _, _, _, _) // // (32, 40, 33, 41, 34, 42, 35, 43, _, _, _, _, _, _, _, _, // 48, 56, 49, 57, 50, 58, 51, 59, _, _, _, _, _, _, _, _) // // _mm256_unpacklo_epi16: // (0, 8, 32, 40, 1, 9, 33, 41, 2, 10, 34, 42, 3, 11, 35, 43, // 16, 24, 48, 56, 17, 25, 49, 57, 18, 26, 50, 58, 19, 27, 51, 59) // // {0, 2, 1, 3} permute: // (0, 8, 32, 40, 1, 9, 33, 41, 16, 24, 48, 56, 17, 25, 49, 57, // 2, 10, 34, 42, 3, 11, 35, 43, 18, 26, 50, 58, 19, 27, 51, 59) // // final shuffle gives us what we want. even_nybbles0 = vecw_shuffle8(even_nybbles0, gather_u16s); odd_nybbles0 = vecw_shuffle8(odd_nybbles0, gather_u16s); even_nybbles1 = vecw_shuffle8(even_nybbles1, gather_u16s); odd_nybbles1 = vecw_shuffle8(odd_nybbles1, gather_u16s); VecW target_even = vecw_unpacklo16(even_nybbles0, even_nybbles1); VecW target_odd = vecw_unpackhi16(odd_nybbles0, odd_nybbles1); target_even = vecw_permute0xd8_if_avx2(target_even); target_odd = vecw_permute0xd8_if_avx2(target_odd); target_even = vecw_shuffle8(target_even, gather_u32s); target_odd = vecw_shuffle8(target_odd, gather_u32s); // tried using _mm_stream_si64 here, that totally sucked switch (cur_dst_row_ct) { case 8: target_iter7[dvidx] = vecw_extract64_3(target_odd); // fall through case 7: target_iter6[dvidx] = vecw_extract64_3(target_even); // fall through case 6: target_iter5[dvidx] = vecw_extract64_2(target_odd); // fall through case 5: target_iter4[dvidx] = vecw_extract64_2(target_even); // fall through case 4: target_iter3[dvidx] = vecw_extract64_1(target_odd); // fall through case 3: target_iter2[dvidx] = vecw_extract64_1(target_even); // fall through case 2: target_iter1[dvidx] = vecw_extract64_0(target_odd); // fall through default: target_iter0[dvidx] = vecw_extract64_0(target_even); } } source_iter = &(source_iter[(4 * kPglNybbleTransposeBatch) / kBytesPerVec]); target_iter0 = &(target_iter7[write_ul_stride]); } # else // !USE_AVX2 for (uint32_t buf_row_idx = 0; ; ++buf_row_idx) { if (buf_row_idx >= buf_fullrow_ct) { if (buf_row_idx == buf_row_ct) { return; } cur_dst_row_ct = write_batch_size % 8; } uintptr_t* target_iter1 = &(target_iter0[write_ul_stride]); uintptr_t* target_iter2 = &(target_iter1[write_ul_stride]); uintptr_t* target_iter3 = &(target_iter2[write_ul_stride]); uintptr_t* target_iter4 = &(target_iter3[write_ul_stride]); uintptr_t* target_iter5 = &(target_iter4[write_ul_stride]); uintptr_t* target_iter6 = &(target_iter5[write_ul_stride]); uintptr_t* target_iter7 = &(target_iter6[write_ul_stride]); for (uint32_t qvidx = 0; qvidx != eightword_ct; ++qvidx) { const VecW loader0 = source_iter[qvidx * 4]; const VecW loader1 = source_iter[qvidx * 4 + 1]; const VecW loader2 = source_iter[qvidx * 4 + 2]; const VecW loader3 = source_iter[qvidx * 4 + 3]; VecW even_nybbles0 = loader0 & m4; VecW odd_nybbles0 = vecw_and_notfirst(m4, loader0); VecW even_nybbles1 = loader1 & m4; VecW odd_nybbles1 = vecw_and_notfirst(m4, loader1); VecW even_nybbles2 = loader2 & m4; VecW odd_nybbles2 = vecw_and_notfirst(m4, loader2); VecW even_nybbles3 = loader3 & m4; VecW odd_nybbles3 = vecw_and_notfirst(m4, loader3); even_nybbles0 = even_nybbles0 | vecw_srli(even_nybbles0, 28); odd_nybbles0 = vecw_slli(odd_nybbles0, 28) | odd_nybbles0; even_nybbles1 = even_nybbles1 | vecw_srli(even_nybbles1, 28); odd_nybbles1 = vecw_slli(odd_nybbles1, 28) | odd_nybbles1; even_nybbles2 = even_nybbles2 | vecw_srli(even_nybbles2, 28); odd_nybbles2 = vecw_slli(odd_nybbles2, 28) | odd_nybbles2; even_nybbles3 = even_nybbles3 | vecw_srli(even_nybbles3, 28); odd_nybbles3 = vecw_slli(odd_nybbles3, 28) | odd_nybbles3; // Label the bytes in even_nybbles0 (0, 1, 2, ..., 15), the bytes in // even_nybbles1 (16, 17, ..., 31), ..., up to even_nybbles3 being (48, // 49, ..., 63). We wish to generate the following vector-crossing // permutation: // (0, 8, 16, 24, 32, 40, 48, 56, 1, 9, 17, 25, 33, 41, 49, 57) // (2, 10, 18, 26, 34, 42, 50, 58, 3, 11, 19, 27, 35, 43, 51, 59) // first shuffle: // (0, 8, 1, 9, 2, 10, 3, 11, _, _, _, _, _, _, _, _) // (16, 24, 17, 25, 18, 26, 19, 27, _, _, _, _, _, _, _, _) // (32, 40, 33, 41, 34, 42, 35, 43, _, _, _, _, _, _, _, _) // (48, 56, 49, 57, 50, 58, 51, 59, _, _, _, _, _, _, _, _) // _mm_unpacklo_epi16: // (0, 8, 16, 24, 1, 9, 17, 25, 2, 10, 18, 26, 3, 11, 19, 27) // (32, 40, 48, 56, 33, 41, 49, 57, 34, 42, 50, 58, 35, 43, 51, 59) // // finish with _mm_unpack{lo,hi}_epi32 # ifdef USE_SSE42 even_nybbles0 = vecw_shuffle8(even_nybbles0, gather_u16s); odd_nybbles0 = vecw_shuffle8(odd_nybbles0, gather_u16s); even_nybbles1 = vecw_shuffle8(even_nybbles1, gather_u16s); odd_nybbles1 = vecw_shuffle8(odd_nybbles1, gather_u16s); even_nybbles2 = vecw_shuffle8(even_nybbles2, gather_u16s); odd_nybbles2 = vecw_shuffle8(odd_nybbles2, gather_u16s); even_nybbles3 = vecw_shuffle8(even_nybbles3, gather_u16s); odd_nybbles3 = vecw_shuffle8(odd_nybbles3, gather_u16s); # else VecW tmp_lo = vecw_unpacklo8(even_nybbles0, odd_nybbles0); VecW tmp_hi = vecw_unpackhi8(even_nybbles0, odd_nybbles0); even_nybbles0 = vecw_blendv(vecw_slli(tmp_hi, 8), tmp_lo, m8); odd_nybbles0 = vecw_blendv(tmp_hi, vecw_srli(tmp_lo, 8), m8); tmp_lo = vecw_unpacklo8(even_nybbles1, odd_nybbles1); tmp_hi = vecw_unpackhi8(even_nybbles1, odd_nybbles1); even_nybbles1 = vecw_blendv(vecw_slli(tmp_hi, 8), tmp_lo, m8); odd_nybbles1 = vecw_blendv(tmp_hi, vecw_srli(tmp_lo, 8), m8); tmp_lo = vecw_unpacklo8(even_nybbles2, odd_nybbles2); tmp_hi = vecw_unpackhi8(even_nybbles2, odd_nybbles2); even_nybbles2 = vecw_blendv(vecw_slli(tmp_hi, 8), tmp_lo, m8); odd_nybbles2 = vecw_blendv(tmp_hi, vecw_srli(tmp_lo, 8), m8); tmp_lo = vecw_unpacklo8(even_nybbles3, odd_nybbles3); tmp_hi = vecw_unpackhi8(even_nybbles3, odd_nybbles3); even_nybbles3 = vecw_blendv(vecw_slli(tmp_hi, 8), tmp_lo, m8); odd_nybbles3 = vecw_blendv(tmp_hi, vecw_srli(tmp_lo, 8), m8); # endif const VecW even_lo = vecw_unpacklo16(even_nybbles0, even_nybbles1); const VecW odd_lo = vecw_unpackhi16(odd_nybbles0, odd_nybbles1); const VecW even_hi = vecw_unpacklo16(even_nybbles2, even_nybbles3); const VecW odd_hi = vecw_unpackhi16(odd_nybbles2, odd_nybbles3); const VecW final02 = vecw_unpacklo32(even_lo, even_hi); const VecW final13 = vecw_unpacklo32(odd_lo, odd_hi); const VecW final46 = vecw_unpackhi32(even_lo, even_hi); const VecW final57 = vecw_unpackhi32(odd_lo, odd_hi); switch (cur_dst_row_ct) { case 8: target_iter7[qvidx] = vecw_extract64_1(final57); // fall through case 7: target_iter6[qvidx] = vecw_extract64_1(final46); // fall through case 6: target_iter5[qvidx] = vecw_extract64_0(final57); // fall through case 5: target_iter4[qvidx] = vecw_extract64_0(final46); // fall through case 4: target_iter3[qvidx] = vecw_extract64_1(final13); // fall through case 3: target_iter2[qvidx] = vecw_extract64_1(final02); // fall through case 2: target_iter1[qvidx] = vecw_extract64_0(final13); // fall through default: target_iter0[qvidx] = vecw_extract64_0(final02); } } source_iter = &(source_iter[(4 * kPglNybbleTransposeBatch) / kBytesPerVec]); target_iter0 = &(target_iter7[write_ul_stride]); } # endif // !USE_AVX2 } #else // !__LP64__ static_assert(kWordsPerVec == 1, "TransposeNybbleblock() needs to be updated."); void TransposeNybbleblock(const uintptr_t* read_iter, uint32_t read_ul_stride, uint32_t write_ul_stride, uint32_t read_batch_size, uint32_t write_batch_size, uintptr_t* __restrict write_iter, VecW* vecaligned_buf) { // Very similar to TransposeNypblock32() in pgenlib_internal. // vecaligned_buf must be vector-aligned and have size 8k const uint32_t buf_row_ct = NybbleCtToByteCt(write_batch_size); // fold the first 6 shuffles into the initial ingestion loop const unsigned char* initial_read_iter = R_CAST(const unsigned char*, read_iter); const unsigned char* initial_read_end = &(initial_read_iter[buf_row_ct]); unsigned char* initial_target_iter = R_CAST(unsigned char*, vecaligned_buf); const uint32_t read_byte_stride = read_ul_stride * kBytesPerWord; const uint32_t read_batch_rem = kNybblesPerCacheline - read_batch_size; for (; initial_read_iter != initial_read_end; ++initial_read_iter) { const unsigned char* read_iter_tmp = initial_read_iter; for (uint32_t ujj = 0; ujj != read_batch_size; ++ujj) { *initial_target_iter++ = *read_iter_tmp; read_iter_tmp = &(read_iter_tmp[read_byte_stride]); } initial_target_iter = memsetua(initial_target_iter, 0, read_batch_rem); } // 8 bit spacing -> 4 const VecW* source_iter = vecaligned_buf; uintptr_t* target_iter0 = write_iter; const uint32_t buf_fullrow_ct = write_batch_size / 2; const uint32_t write_word_ct = NybbleCtToWordCt(read_batch_size); for (uint32_t uii = 0; uii != buf_fullrow_ct; ++uii) { uintptr_t* target_iter1 = &(target_iter0[write_ul_stride]); for (uint32_t ujj = 0; ujj != write_word_ct; ++ujj) { const uintptr_t source_word_lo = *source_iter++; const uintptr_t source_word_hi = *source_iter++; uintptr_t target_word0_lo = source_word_lo & kMask0F0F; uintptr_t target_word1_lo = (source_word_lo >> 4) & kMask0F0F; uintptr_t target_word0_hi = source_word_hi & kMask0F0F; uintptr_t target_word1_hi = (source_word_hi >> 4) & kMask0F0F; target_word0_lo = (target_word0_lo | (target_word0_lo >> 4)) & kMask00FF; target_word1_lo = (target_word1_lo | (target_word1_lo >> 4)) & kMask00FF; target_word0_hi = (target_word0_hi | (target_word0_hi >> 4)) & kMask00FF; target_word1_hi = (target_word1_hi | (target_word1_hi >> 4)) & kMask00FF; target_word0_lo = target_word0_lo | (target_word0_lo >> kBitsPerWordD4); target_word1_lo = target_word1_lo | (target_word1_lo >> kBitsPerWordD4); target_word0_hi = target_word0_hi | (target_word0_hi >> kBitsPerWordD4); target_word1_hi = target_word1_hi | (target_word1_hi >> kBitsPerWordD4); target_iter0[ujj] = S_CAST(Halfword, target_word0_lo) | (target_word0_hi << kBitsPerWordD2); target_iter1[ujj] = S_CAST(Halfword, target_word1_lo) | (target_word1_hi << kBitsPerWordD2); } source_iter = &(source_iter[2 * (kWordsPerCacheline - write_word_ct)]); target_iter0 = &(target_iter1[write_ul_stride]); } const uint32_t remainder = write_batch_size % 2; if (!remainder) { return; } for (uint32_t ujj = 0; ujj != write_word_ct; ++ujj) { const uintptr_t source_word_lo = *source_iter++; const uintptr_t source_word_hi = *source_iter++; uintptr_t target_word0_lo = source_word_lo & kMask0F0F; uintptr_t target_word0_hi = source_word_hi & kMask0F0F; target_word0_lo = (target_word0_lo | (target_word0_lo >> 4)) & kMask00FF; target_word0_hi = (target_word0_hi | (target_word0_hi >> 4)) & kMask00FF; target_word0_lo = target_word0_lo | (target_word0_lo >> kBitsPerWordD4); target_word0_hi = target_word0_hi | (target_word0_hi >> kBitsPerWordD4); target_iter0[ujj] = S_CAST(Halfword, target_word0_lo) | (target_word0_hi << kBitsPerWordD2); } } #endif // !__LP64__ #ifdef __LP64__ # ifdef USE_AVX2 const unsigned char kLeadMask[2 * kBytesPerVec] __attribute__ ((aligned (64))) = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}; # else const unsigned char kLeadMask[2 * kBytesPerVec] __attribute__ ((aligned (32))) = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}; # endif uintptr_t BytesumArr(const void* bytearr, uintptr_t byte_ct) { uintptr_t tot = 0; if (byte_ct < kBytesPerVec) { const unsigned char* bytearr_uc = S_CAST(const unsigned char*, bytearr); for (uintptr_t ulii = 0; ulii != byte_ct; ++ulii) { tot += bytearr_uc[ulii]; } return tot; } const unsigned char* bytearr_uc_iter = S_CAST(const unsigned char*, bytearr); const unsigned char* bytearr_uc_final = &(bytearr_uc_iter[byte_ct - kBytesPerVec]); const VecW m0 = vecw_setzero(); VecW acc = vecw_setzero(); while (bytearr_uc_iter < bytearr_uc_final) { const VecW cur_vec = vecw_loadu(bytearr_uc_iter); acc = acc + vecw_sad(cur_vec, m0); bytearr_uc_iter = &(bytearr_uc_iter[kBytesPerVec]); } VecW cur_vec = vecw_loadu(bytearr_uc_final); const uintptr_t overlap_byte_ct = bytearr_uc_iter - bytearr_uc_final; const VecW mask_vec = vecw_loadu(&(kLeadMask[kBytesPerVec - overlap_byte_ct])); cur_vec = cur_vec & mask_vec; acc = acc + vecw_sad(cur_vec, m0); return HsumW(acc); } #else // !__LP64__ uintptr_t BytesumArr(const void* bytearr, uintptr_t byte_ct) { // Assumes sum < 2^32. # ifdef __arm__ # error "Unaligned accesses in BytesumArr()." # endif const uint32_t word_ct = byte_ct / kBytesPerWord; const uintptr_t* bytearr_alias_iter = S_CAST(const uintptr_t*, bytearr); const uint32_t wordblock_idx_trail = word_ct / 256; const uint32_t wordblock_idx_end = DivUp(word_ct, 256); uint32_t wordblock_len = 256; uintptr_t tot = 0; for (uint32_t wordblock_idx = 0; ; ++wordblock_idx) { if (wordblock_idx >= wordblock_idx_trail) { if (wordblock_idx == wordblock_idx_end) { byte_ct = byte_ct % kBytesPerWord; const unsigned char* bytearr_alias_iter2 = R_CAST(const unsigned char*, bytearr_alias_iter); for (uint32_t uii = 0; uii != byte_ct; ++uii) { tot += bytearr_alias_iter2[uii]; } return tot; } wordblock_len = word_ct % 256; } const uintptr_t* bytearr_alias_stop = &(bytearr_alias_iter[wordblock_len]); uintptr_t acc_even = 0; uintptr_t acc_odd = 0; do { uintptr_t cur_word = *bytearr_alias_iter++; acc_even += cur_word & kMask00FF; acc_odd += (cur_word >> 8) & kMask00FF; } while (bytearr_alias_iter < bytearr_alias_stop); acc_even = S_CAST(Halfword, acc_even) + (acc_even >> kBitsPerWordD2); acc_odd = S_CAST(Halfword, acc_odd) + (acc_odd >> kBitsPerWordD2); tot += acc_even + acc_odd; } } #endif // !__LP64__ uintptr_t CountByte(const void* bytearr, unsigned char ucc, uintptr_t byte_ct) { #ifdef __LP64__ if (byte_ct < kBytesPerVec) { #endif const unsigned char* bytearr_uc = S_CAST(const unsigned char*, bytearr); uintptr_t tot = 0; for (uintptr_t ulii = 0; ulii != byte_ct; ++ulii) { tot += (bytearr_uc[ulii] == ucc); } return tot; #ifdef __LP64__ } const unsigned char* bytearr_uc_iter = S_CAST(const unsigned char*, bytearr); const VecW m0 = vecw_setzero(); const VecUc match_vvec = vecuc_set1(ucc); VecW acc = vecw_setzero(); while (byte_ct > 255 * kBytesPerVec) { VecUc inner_acc = vecuc_setzero(); for (uint32_t uii = 0; uii != 255; ++uii) { const VecUc cur_vvec = vecuc_loadu(bytearr_uc_iter); bytearr_uc_iter = &(bytearr_uc_iter[kBytesPerVec]); inner_acc = inner_acc - (cur_vvec == match_vvec); } acc = acc + vecw_sad(R_CAST(VecW, inner_acc), m0); byte_ct -= 255 * kBytesPerVec; } const unsigned char* bytearr_uc_final = &(bytearr_uc_iter[byte_ct - kBytesPerVec]); VecUc inner_acc = vecuc_setzero(); while (bytearr_uc_iter < bytearr_uc_final) { const VecUc cur_vvec = vecuc_loadu(bytearr_uc_iter); bytearr_uc_iter = &(bytearr_uc_iter[kBytesPerVec]); inner_acc = inner_acc - (cur_vvec == match_vvec); } VecUc cur_vvec = vecuc_loadu(bytearr_uc_final); const uintptr_t overlap_byte_ct = bytearr_uc_iter - bytearr_uc_final; const VecUc mask_vvec = vecuc_loadu(&(kLeadMask[kBytesPerVec - overlap_byte_ct])); cur_vvec = (cur_vvec == match_vvec) & mask_vvec; inner_acc = inner_acc - cur_vvec; acc = acc + vecw_sad(R_CAST(VecW, inner_acc), m0); return HsumW(acc); #endif // __LP64__ } uintptr_t CountU16(const void* u16arr, uint16_t usii, uintptr_t u16_ct) { #ifdef __LP64__ if (u16_ct < (kBytesPerVec / 2)) { #endif const uint16_t* u16arr_alias = S_CAST(const uint16_t*, u16arr); uintptr_t tot = 0; for (uintptr_t ulii = 0; ulii != u16_ct; ++ulii) { tot += (u16arr_alias[ulii] == usii); } return tot; #ifdef __LP64__ } const uint16_t* u16arr_iter = S_CAST(const uint16_t*, u16arr); const VecW m0 = vecw_setzero(); const VecU16 match_vvec = vecu16_set1(usii); VecW acc = vecw_setzero(); // can also use larger loop and a slightly different accumulation algorithm, // but it should make practically no difference; lets keep these loops as // similar as possible for now. while (u16_ct > 255 * (kBytesPerVec / 2)) { VecU16 inner_acc = vecu16_setzero(); for (uint32_t uii = 0; uii != 255; ++uii) { const VecU16 cur_vvec = vecu16_loadu(u16arr_iter); u16arr_iter = &(u16arr_iter[kBytesPerVec / 2]); inner_acc = inner_acc - (cur_vvec == match_vvec); } acc = acc + vecw_sad(R_CAST(VecW, inner_acc), m0); u16_ct -= 255 * (kBytesPerVec / 2); } const uint16_t* u16arr_final = &(u16arr_iter[u16_ct - (kBytesPerVec / 2)]); VecU16 inner_acc = vecu16_setzero(); while (u16arr_iter < u16arr_final) { const VecU16 cur_vvec = vecu16_loadu(u16arr_iter); u16arr_iter = &(u16arr_iter[kBytesPerVec / 2]); inner_acc = inner_acc - (cur_vvec == match_vvec); } VecU16 cur_vvec = vecu16_loadu(u16arr_final); const uintptr_t overlap_u16_ct = u16arr_iter - u16arr_final; const VecU16 mask_vvec = vecu16_loadu(&(kLeadMask[kBytesPerVec - 2 * overlap_u16_ct])); cur_vvec = (cur_vvec == match_vvec) & mask_vvec; inner_acc = inner_acc - cur_vvec; acc = acc + vecw_sad(R_CAST(VecW, inner_acc), m0); return HsumW(acc); #endif // __LP64__ } uint32_t Copy1bit8Subset(const uintptr_t* __restrict src_subset, const void* __restrict src_vals, const uintptr_t* __restrict sample_include, uint32_t src_subset_size, uint32_t sample_ct, uintptr_t* __restrict dst_subset, void* __restrict dst_vals) { if (!src_subset_size) { return 0; } CopyBitarrSubset(src_subset, sample_include, sample_ct, dst_subset); const unsigned char* src_vals_uc = S_CAST(const unsigned char*, src_vals); unsigned char* dst_vals_uc = S_CAST(unsigned char*, dst_vals); unsigned char* dst_vals_iter = dst_vals_uc; uintptr_t sample_widx = 0; uintptr_t src_subset_bits = src_subset[0]; for (uint32_t src_idx = 0; src_idx != src_subset_size; ++src_idx) { const uintptr_t lowbit = BitIter1y(src_subset, &sample_widx, &src_subset_bits); if (sample_include[sample_widx] & lowbit) { *dst_vals_iter++ = src_vals_uc[src_idx]; } } return dst_vals_iter - dst_vals_uc; } uint32_t Copy1bit16Subset(const uintptr_t* __restrict src_subset, const void* __restrict src_vals, const uintptr_t* __restrict sample_include, uint32_t src_subset_size, uint32_t sample_ct, uintptr_t* __restrict dst_subset, void* __restrict dst_vals) { if (!src_subset_size) { return 0; } CopyBitarrSubset(src_subset, sample_include, sample_ct, dst_subset); const uint16_t* src_vals_u16 = S_CAST(const uint16_t*, src_vals); uint16_t* dst_vals_u16 = S_CAST(uint16_t*, dst_vals); uint16_t* dst_vals_iter = dst_vals_u16; uintptr_t sample_widx = 0; uintptr_t src_subset_bits = src_subset[0]; for (uint32_t src_idx = 0; src_idx != src_subset_size; ++src_idx) { const uintptr_t lowbit = BitIter1y(src_subset, &sample_widx, &src_subset_bits); if (sample_include[sample_widx] & lowbit) { *dst_vals_iter++ = src_vals_u16[src_idx]; } } return dst_vals_iter - dst_vals_u16; } #ifdef __cplusplus } // namespace plink2 #endif
45.195868
342
0.683636
[ "vector" ]
9c9399ce594894518d6bcec7c271d5d2034d9c19
10,626
cc
C++
chrome/browser/chromeos/extensions/file_system_provider/file_system_provider_api.cc
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2019-11-28T10:46:52.000Z
2019-11-28T10:46:52.000Z
chrome/browser/chromeos/extensions/file_system_provider/file_system_provider_api.cc
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/chromeos/extensions/file_system_provider/file_system_provider_api.cc
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2015-03-27T11:15:39.000Z
2016-08-17T14:19:56.000Z
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/extensions/file_system_provider/file_system_provider_api.h" #include <string> #include <vector> #include "base/debug/trace_event.h" #include "base/memory/linked_ptr.h" #include "base/memory/scoped_ptr.h" #include "base/values.h" #include "chrome/browser/chromeos/file_system_provider/provided_file_system_interface.h" #include "chrome/browser/chromeos/file_system_provider/request_manager.h" #include "chrome/browser/chromeos/file_system_provider/request_value.h" #include "chrome/browser/chromeos/file_system_provider/service.h" #include "chrome/common/extensions/api/file_system_provider.h" #include "chrome/common/extensions/api/file_system_provider_internal.h" #include "storage/browser/fileapi/watcher_manager.h" using chromeos::file_system_provider::MountOptions; using chromeos::file_system_provider::ProvidedFileSystemInfo; using chromeos::file_system_provider::ProvidedFileSystemInterface; using chromeos::file_system_provider::ProvidedFileSystemObserver; using chromeos::file_system_provider::RequestValue; using chromeos::file_system_provider::Service; namespace extensions { namespace { typedef std::vector<linked_ptr<api::file_system_provider::Change>> IDLChanges; // Converts the change type from the IDL type to a native type. |changed_type| // must be specified (not CHANGE_TYPE_NONE). storage::WatcherManager::ChangeType ParseChangeType( const api::file_system_provider::ChangeType& change_type) { switch (change_type) { case api::file_system_provider::CHANGE_TYPE_CHANGED: return storage::WatcherManager::CHANGED; case api::file_system_provider::CHANGE_TYPE_DELETED: return storage::WatcherManager::DELETED; default: break; } NOTREACHED(); return storage::WatcherManager::CHANGED; } // Convert the change from the IDL type to a native type. The reason IDL types // are not used is since they are imperfect, eg. paths are stored as strings. ProvidedFileSystemObserver::Change ParseChange( const api::file_system_provider::Change& change) { ProvidedFileSystemObserver::Change result; result.entry_path = base::FilePath::FromUTF8Unsafe(change.entry_path); result.change_type = ParseChangeType(change.change_type); return result; } // Converts a list of child changes from the IDL type to a native type. scoped_ptr<ProvidedFileSystemObserver::Changes> ParseChanges( const IDLChanges& changes) { scoped_ptr<ProvidedFileSystemObserver::Changes> results( new ProvidedFileSystemObserver::Changes); for (const auto& change : changes) { results->push_back(ParseChange(*change)); } return results; } } // namespace bool FileSystemProviderMountFunction::RunSync() { using api::file_system_provider::Mount::Params; const scoped_ptr<Params> params(Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); // It's an error if the file system Id is empty. if (params->options.file_system_id.empty()) { SetError(FileErrorToString(base::File::FILE_ERROR_INVALID_OPERATION)); return false; } // It's an error if the display name is empty. if (params->options.display_name.empty()) { SetError(FileErrorToString(base::File::FILE_ERROR_INVALID_OPERATION)); return false; } // If the opened files limit is set, then it must be larger or equal than 0. if (params->options.opened_files_limit.get() && *params->options.opened_files_limit.get() < 0) { SetError(FileErrorToString(base::File::FILE_ERROR_INVALID_OPERATION)); return false; } Service* const service = Service::Get(GetProfile()); DCHECK(service); MountOptions options; options.file_system_id = params->options.file_system_id; options.display_name = params->options.display_name; options.writable = params->options.writable; options.opened_files_limit = params->options.opened_files_limit.get() ? *params->options.opened_files_limit.get() : 0; options.supports_notify_tag = params->options.supports_notify_tag; const base::File::Error result = service->MountFileSystem(extension_id(), options); if (result != base::File::FILE_OK) { SetError(FileErrorToString(result)); return false; } return true; } bool FileSystemProviderUnmountFunction::RunSync() { using api::file_system_provider::Unmount::Params; scoped_ptr<Params> params(Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); Service* const service = Service::Get(GetProfile()); DCHECK(service); const base::File::Error result = service->UnmountFileSystem(extension_id(), params->options.file_system_id, Service::UNMOUNT_REASON_USER); if (result != base::File::FILE_OK) { SetError(FileErrorToString(result)); return false; } return true; } bool FileSystemProviderGetAllFunction::RunSync() { using api::file_system_provider::FileSystemInfo; using api::file_system_provider::Watcher; Service* const service = Service::Get(GetProfile()); DCHECK(service); const std::vector<ProvidedFileSystemInfo> file_systems = service->GetProvidedFileSystemInfoList(); std::vector<linked_ptr<FileSystemInfo>> items; for (const auto& file_system_info : file_systems) { if (file_system_info.extension_id() == extension_id()) { const linked_ptr<FileSystemInfo> item(new FileSystemInfo); item->file_system_id = file_system_info.file_system_id(); item->display_name = file_system_info.display_name(); item->writable = file_system_info.writable(); chromeos::file_system_provider::ProvidedFileSystemInterface* const file_system = service->GetProvidedFileSystem(file_system_info.extension_id(), file_system_info.file_system_id()); DCHECK(file_system); std::vector<linked_ptr<Watcher>> watcher_items; chromeos::file_system_provider::Watchers* const watchers = file_system->GetWatchers(); DCHECK(watchers); for (const auto& watcher : *watchers) { const linked_ptr<Watcher> watcher_item(new Watcher); watcher_item->entry_path = watcher.second.entry_path.value(); watcher_item->recursive = watcher.second.recursive; if (!watcher.second.last_tag.empty()) watcher_item->last_tag.reset( new std::string(watcher.second.last_tag)); watcher_items.push_back(watcher_item); } item->watchers = watcher_items; items.push_back(item); } } SetResultList(api::file_system_provider::GetAll::Results::Create(items)); return true; } bool FileSystemProviderNotifyFunction::RunAsync() { using api::file_system_provider::Notify::Params; scoped_ptr<Params> params(Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); Service* const service = Service::Get(GetProfile()); DCHECK(service); ProvidedFileSystemInterface* const file_system = service->GetProvidedFileSystem(extension_id(), params->options.file_system_id); if (!file_system) { SetError(FileErrorToString(base::File::FILE_ERROR_NOT_FOUND)); return false; } file_system->Notify( base::FilePath::FromUTF8Unsafe(params->options.observed_path), params->options.recursive, ParseChangeType(params->options.change_type), params->options.changes.get() ? ParseChanges(*params->options.changes.get()) : make_scoped_ptr(new ProvidedFileSystemObserver::Changes), params->options.tag.get() ? *params->options.tag.get() : "", base::Bind(&FileSystemProviderNotifyFunction::OnNotifyCompleted, this)); return true; } void FileSystemProviderNotifyFunction::OnNotifyCompleted( base::File::Error result) { if (result != base::File::FILE_OK) { SetError(FileErrorToString(result)); SendResponse(false); return; } SendResponse(true); } bool FileSystemProviderInternalUnmountRequestedSuccessFunction::RunWhenValid() { using api::file_system_provider_internal::UnmountRequestedSuccess::Params; scoped_ptr<Params> params(Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); return FulfillRequest(RequestValue::CreateForUnmountSuccess(params.Pass()), false /* has_more */); } bool FileSystemProviderInternalGetMetadataRequestedSuccessFunction::RunWhenValid() { using api::file_system_provider_internal::GetMetadataRequestedSuccess::Params; scoped_ptr<Params> params(Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); return FulfillRequest( RequestValue::CreateForGetMetadataSuccess(params.Pass()), false /* has_more */); } bool FileSystemProviderInternalReadDirectoryRequestedSuccessFunction:: RunWhenValid() { using api::file_system_provider_internal::ReadDirectoryRequestedSuccess:: Params; scoped_ptr<Params> params(Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); const bool has_more = params->has_more; return FulfillRequest( RequestValue::CreateForReadDirectorySuccess(params.Pass()), has_more); } bool FileSystemProviderInternalReadFileRequestedSuccessFunction::RunWhenValid() { TRACE_EVENT0("file_system_provider", "ReadFileRequestedSuccess"); using api::file_system_provider_internal::ReadFileRequestedSuccess::Params; scoped_ptr<Params> params(Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); const bool has_more = params->has_more; return FulfillRequest(RequestValue::CreateForReadFileSuccess(params.Pass()), has_more); } bool FileSystemProviderInternalOperationRequestedSuccessFunction::RunWhenValid() { using api::file_system_provider_internal::OperationRequestedSuccess::Params; scoped_ptr<Params> params(Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); return FulfillRequest( scoped_ptr<RequestValue>( RequestValue::CreateForOperationSuccess(params.Pass())), false /* has_more */); } bool FileSystemProviderInternalOperationRequestedErrorFunction::RunWhenValid() { using api::file_system_provider_internal::OperationRequestedError::Params; scoped_ptr<Params> params(Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); const base::File::Error error = ProviderErrorToFileError(params->error); return RejectRequest(RequestValue::CreateForOperationError(params.Pass()), error); } } // namespace extensions
36.390411
93
0.741577
[ "vector" ]
9c95372e64c2054d789e2e56ba3d254fb4ebbdea
9,269
cpp
C++
GW2Radial/src/CustomWheel.cpp
kilteh/GW2Radial
20c35d097b21299335d4d0f2636e0d5629a022bc
[ "MIT" ]
null
null
null
GW2Radial/src/CustomWheel.cpp
kilteh/GW2Radial
20c35d097b21299335d4d0f2636e0d5629a022bc
[ "MIT" ]
null
null
null
GW2Radial/src/CustomWheel.cpp
kilteh/GW2Radial
20c35d097b21299335d4d0f2636e0d5629a022bc
[ "MIT" ]
null
null
null
#include <CustomWheel.h> #include <Wheel.h> #include "DDSTextureLoader.h" #include "WICTextureLoader.h" #include <filesystem> #include <fstream> #include <imgui/examples/imgui_impl_dx9.h> #include <ImGuiPopup.h> #include <FileSystem.h> namespace GW2Radial { float CalcText(ImFont* font, const std::wstring& text) { cref txt = utf8_encode(text); auto sz = font->CalcTextSizeA(100.f, FLT_MAX, 0.f, txt.c_str()); return sz.x; } IDirect3DTexture9* MakeTextTexture(IDirect3DDevice9* dev, float fontSize) { IDirect3DTexture9* tex = nullptr; dev->CreateTexture(1024, uint(fontSize), 1, D3DUSAGE_RENDERTARGET, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &tex, nullptr); return tex; } void DrawText(IDirect3DDevice9* dev, IDirect3DTexture9* tex, ImFont* font, float fontSize, const std::wstring& text) { const uint fgColor = 0xFFFFFFFF; const uint bgColor = 0x00000000; cref txt = utf8_encode(text); auto sz = font->CalcTextSizeA(fontSize, FLT_MAX, 0.f, txt.c_str()); ImVec2 clip(1024.f, fontSize); float xOff = (clip.x - sz.x) * 0.5f; ImDrawList imDraw(ImGui::GetDrawListSharedData()); imDraw.AddDrawCmd(); imDraw.PushClipRect(ImVec2(0.f, 0.f), clip); imDraw.PushTextureID(font->ContainerAtlas->TexID); imDraw.AddText(font, fontSize, ImVec2(xOff, 0.f), fgColor, txt.c_str()); auto& io = ImGui::GetIO(); auto oldDisplaySize = io.DisplaySize; io.DisplaySize = clip; IDirect3DSurface9* surf; tex->GetSurfaceLevel(0, &surf); IDirect3DSurface9* oldRt; dev->GetRenderTarget(0, &oldRt); dev->SetRenderTarget(0, surf); dev->Clear(1, nullptr, D3DCLEAR_TARGET, bgColor, 0.f, 0); ImDrawList* imDraws[] = { &imDraw }; ImDrawData imData; imData.Valid = true; imData.CmdLists = imDraws; imData.CmdListsCount = 1; imData.TotalIdxCount = imDraw.IdxBuffer.Size; imData.TotalVtxCount = imDraw.VtxBuffer.Size; imData.DisplayPos = ImVec2(0.0f, 0.0f); imData.DisplaySize = io.DisplaySize; ImGui_ImplDX9_RenderDrawData(&imData); dev->SetRenderTarget(0, oldRt); oldRt->Release(); io.DisplaySize = oldDisplaySize; surf->Release(); } IDirect3DTexture9* LoadCustomTexture(IDirect3DDevice9* dev, const std::filesystem::path& path) { cref data = FileSystem::ReadFile(path); if(data.empty()) return nullptr; try { IDirect3DTexture9* tex = nullptr; HRESULT hr = S_OK; if(path.extension() == L".dds") hr = DirectX::CreateDDSTextureFromMemory(dev, data.data(), data.size(), &tex); else hr = DirectX::CreateWICTextureFromMemory(dev, data.data(), data.size(), &tex); if(!SUCCEEDED(hr)) FormattedMessageBox(L"Could not load custom radial menu image '%s': 0x%x.", L"Custom Menu Error", path.wstring().c_str(), hr); return tex; } catch(...) { FormattedMessageBox(L"Could not load custom radial menu image '%s'.", L"Custom Menu Error", path.wstring().c_str()); return nullptr; } } CustomWheelsManager::CustomWheelsManager(std::vector<std::unique_ptr<Wheel>>& wheels, ImFont* font) : wheels_(wheels), font_(font) { } void CustomWheelsManager::DrawOffscreen(IDirect3DDevice9* dev) { if(!loaded_) Reload(dev); else if(!textDraws_.empty()) { cref td = textDraws_.front(); DrawText(dev, td.tex, font_, td.size, td.text); textDraws_.pop_front(); } } void CustomWheelsManager::Draw(IDirect3DDevice9* dev) { if(failedLoads_.empty()) return; cref err = failedLoads_.back(); ImGuiPopup("Custom wheel configuration could not be loaded!") .Position({0.5f, 0.45f}).Size({0.35f, 0.2f}) .Display([err](const ImVec2&) { ImGui::Text("Could not load custom wheel. Error message:"); ImGui::TextWrapped(utf8_encode(err).c_str()); }, [&]() { failedLoads_.pop_back(); }); } std::unique_ptr<Wheel> CustomWheelsManager::BuildWheel(const std::filesystem::path& configPath, IDirect3DDevice9* dev) { cref dataFolder = configPath.parent_path(); auto fail = [&](const wchar_t* error) { failedLoads_.push_back(error + (L": '" + configPath.wstring() + L"'")); return nullptr; }; cref cfgSource = FileSystem::ReadFile(configPath); if(cfgSource.empty()) return nullptr; CSimpleIniA ini(true); cref loadResult = ini.LoadData(reinterpret_cast<const char*>(cfgSource.data()), cfgSource.size()); if(loadResult != SI_OK) return fail(L"Invalid INI file"); cref general = *ini.GetSection("General"); cref wheelDisplayName = general.find("display_name"); cref wheelNickname = general.find("nickname"); if(wheelDisplayName == general.end()) return fail(L"Missing field display_name"); if(wheelNickname == general.end()) return fail(L"Missing field nickname"); if(std::any_of(customWheels_.begin(), customWheels_.end(), [&](cref w) { return w->nickname() == wheelNickname->second; })) return fail((L"Nickname " + utf8_decode(std::string(wheelNickname->second)) + L" already exists").c_str()); auto wheel = std::make_unique<Wheel>(IDR_BG, IDR_WIPEMASK, wheelNickname->second, wheelDisplayName->second, dev); wheel->worksOnlyOutOfCombat_ = ini.GetBoolValue("General", "only_out_of_combat", false); wheel->worksOnlyAboveWater_ = ini.GetBoolValue("General", "only_above_water", false); uint baseId = customWheelNextId_; std::list<CSimpleIniA::Entry> sections; ini.GetAllSections(sections); sections.sort(CSimpleIniA::Entry::LoadOrder()); std::vector<CustomElementSettings> elements; elements.reserve(sections.size()); float maxTextWidth = 0.f; for(cref sec : sections) { if(_stricmp(sec.pItem, "General") == 0) continue; cref element = *ini.GetSection(sec.pItem); cref elementName = element.find("name"); cref elementColor = element.find("color"); cref elementIcon = element.find("icon"); cref elementShadow = element.find("shadow_strength"); cref elementColorize = element.find("colorize_strength"); cref elementPremultipliedAlpha = element.find("premultiply_alpha"); fVector4 color { 1.f, 1.f, 1.f, 1.f }; if(elementColor != element.end()) { std::array<std::string, 3> colorElems; SplitString(elementColor->second, ",", colorElems.begin()); size_t i = 0; for(cref c : colorElems) reinterpret_cast<float*>(&color)[i++] = float(atof(c.c_str()) / 255.f); } CustomElementSettings ces; ces.category = wheel->nickname(); ces.nickname = ToLower(wheel->nickname()) + "_" + ToLower(std::string(sec.pItem)); ces.name = elementName == element.end() ? sec.pItem : elementName->second; ces.color = color; ces.id = baseId++; ces.shadow = elementShadow == element.end() ? 1.f : float(atof(elementShadow->second)); ces.colorize = elementColorize == element.end() ? 1.f : float(atof(elementColorize->second)); ces.premultiply = false; if(elementIcon != element.end()) { ces.texture = LoadCustomTexture(dev, dataFolder / utf8_decode(elementIcon->second)); if(elementPremultipliedAlpha != element.end()) ces.premultiply = ini.GetBoolValue(sec.pItem, "premultiply_alpha", true); } if(!ces.texture) maxTextWidth = std::max(maxTextWidth, CalcText(font_, utf8_decode(ces.name))); elements.push_back(ces); GW2_ASSERT(baseId < customWheelNextId_ + CustomWheelIdStep); } float desiredFontSize = 1024.f / maxTextWidth * 100.f; for(auto& ces : elements) { if(ces.texture == nullptr) { ces.texture = MakeTextTexture(dev, desiredFontSize); textDraws_.push_back({ desiredFontSize, utf8_decode(ces.name), ces.texture }); } wheel->AddElement(std::make_unique<CustomElement>(ces, dev)); } customWheelNextId_ += CustomWheelIdStep; return std::move(wheel); } void CustomWheelsManager::Reload(IDirect3DDevice9* dev) { { APTTYPE a; APTTYPEQUALIFIER b; if(CoGetApartmentType(&a, &b) == CO_E_NOTINITIALIZED) { HRESULT hr = CoInitializeEx(nullptr, COINIT_MULTITHREADED); if (hr != S_FALSE && hr != RPC_E_CHANGED_MODE && FAILED(hr)) CriticalMessageBox(L"Could not initialize COM library: error code 0x%X.", hr); } } failedLoads_.clear(); textDraws_.clear(); customWheelNextId_ = CustomWheelStartId; if(!customWheels_.empty()) { wheels_.erase(std::remove_if(wheels_.begin(), wheels_.end(), [&](cref ptr) { return std::find(customWheels_.begin(), customWheels_.end(), ptr.get()) != customWheels_.end(); }), wheels_.end()); customWheels_.clear(); } cref folderBase = ConfigurationFile::i()->folder() + L"custom\\"; if(std::filesystem::exists(folderBase)) { for(cref entry : std::filesystem::directory_iterator(folderBase)) { if(!entry.is_directory() && entry.path().extension() != L".zip") continue; std::filesystem::path configFile = entry.path() / L"config.ini"; if(!FileSystem::Exists(configFile)) continue; auto wheel = BuildWheel(configFile, dev); if(wheel) { wheels_.push_back(std::move(wheel)); customWheels_.push_back(wheels_.back().get()); } } } loaded_ = true; } CustomElement::CustomElement(const CustomElementSettings& ces, IDirect3DDevice9* dev) : WheelElement(ces.id, ces.nickname, ces.category, ces.name, dev, ces.texture), color_(ces.color) { shadowStrength_ = ces.shadow; colorizeAmount_ = ces.colorize; premultiplyAlpha_ = ces.premultiply; } fVector4 CustomElement::color() { return color_; } }
29.425397
132
0.695005
[ "vector" ]
9c9ccb48da905825f8a3bdffb9f8b5f2331d2a11
2,058
cc
C++
other/other_z3.cc
t-dillon/tdoku
1668b02258c58b0647713d78e09a8ab101e13bd1
[ "BSD-2-Clause" ]
100
2019-07-01T20:16:33.000Z
2022-03-27T10:36:48.000Z
other/other_z3.cc
t-dillon/tdoku
1668b02258c58b0647713d78e09a8ab101e13bd1
[ "BSD-2-Clause" ]
7
2019-12-18T09:07:58.000Z
2022-03-13T19:39:46.000Z
other/other_z3.cc
t-dillon/tdoku
1668b02258c58b0647713d78e09a8ab101e13bd1
[ "BSD-2-Clause" ]
14
2019-06-18T05:47:28.000Z
2022-03-05T08:58:05.000Z
#include "z3++.h" #include <array> #include <cstring> namespace { struct SolverZ3 { z3::context c; z3::solver s{c}; z3::expr_vector cell{c}; SolverZ3() { for (int i = 0; i <= 81; i++) { std::stringstream idx; idx << "c" << i; cell.push_back(c.int_const(idx.str().c_str())); } for (int i = 0; i < 9; i++) { z3::expr_vector row{c}, col{c}, box{c}; for (int j = 0; j < 9; j++) { s.add(cell[i * 9 + j] >= 1 && cell[i * 9 + j] <= 9); row.push_back(cell[i * 9 + j]); col.push_back(cell[j * 9 + i]); box.push_back(cell[((i / 3) * 3 + (j / 3)) * 9 + (i % 3) * 3 + (j % 3)]); } s.add(distinct(row) && distinct(col) && distinct(box)); } } size_t SolveSudoku(const char *input, int limit, bool pencilmark, char *solution, size_t *num_guesses) { *num_guesses = 0; s.push(); for (int i = 0; i < 81; i++) { if (pencilmark) { for (int j = 0; j < 9; j++) { if (input[i * 9 + j] == '.') s.add(cell[i] != (j + 1)); } } else { if (input[i] != '.') s.add(cell[i] == (input[i] - '0')); } } if (s.check() == z3::sat) { z3::model m = s.get_model(); std::stringstream result; for (int i = 0; i < 81; i++) { result << m.eval(cell[i]); } strncpy(solution, result.str().c_str(), 81); s.pop(); return 1; } else { s.pop(); return 0; } } }; } //end anonymous namespace extern "C" size_t OtherSolverZ3(const char *input, size_t limit, uint32_t config, char *solution, size_t *num_guesses) { bool pencilmark = input[81] >= '.'; static SolverZ3 solver{}; return solver.SolveSudoku(input, limit, pencilmark, solution, num_guesses); }
28.583333
89
0.428086
[ "model" ]
9c9d4f19ed7da5b5dd1562cdfd3908acb988af26
32,866
cpp
C++
external/vulkancts/modules/vulkan/rasterization/vktRasterizationFragShaderSideEffectsTests.cpp
samuelig/VK-GL-CTS
483a71c5130edf701b89ce120a01b3b81f87b805
[ "Apache-2.0" ]
null
null
null
external/vulkancts/modules/vulkan/rasterization/vktRasterizationFragShaderSideEffectsTests.cpp
samuelig/VK-GL-CTS
483a71c5130edf701b89ce120a01b3b81f87b805
[ "Apache-2.0" ]
null
null
null
external/vulkancts/modules/vulkan/rasterization/vktRasterizationFragShaderSideEffectsTests.cpp
samuelig/VK-GL-CTS
483a71c5130edf701b89ce120a01b3b81f87b805
[ "Apache-2.0" ]
null
null
null
/*------------------------------------------------------------------------ * Vulkan Conformance Tests * ------------------------ * * Copyright (c) 2020 The Khronos Group Inc. * Copyright (c) 2020 Valve Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *//*! * \file * \brief Test frag shader side effects are not removed by optimizations. *//*--------------------------------------------------------------------*/ #include "vktRasterizationFragShaderSideEffectsTests.hpp" #include "vktTestCase.hpp" #include "vkQueryUtil.hpp" #include "vkObjUtil.hpp" #include "vkBuilderUtil.hpp" #include "vkImageWithMemory.hpp" #include "vkBufferWithMemory.hpp" #include "vkTypeUtil.hpp" #include "vkCmdUtil.hpp" #include "vkBarrierUtil.hpp" #include "vkImageUtil.hpp" #include "tcuVector.hpp" #include "tcuMaybe.hpp" #include "tcuTestLog.hpp" #include "deUniquePtr.hpp" #include <sstream> #include <string> #include <memory> #include <vector> #include <algorithm> namespace vkt { namespace rasterization { namespace { enum class CaseType { KILL, DEMOTE, SAMPLE_MASK_BEFORE, SAMPLE_MASK_AFTER, ALPHA_COVERAGE_BEFORE, ALPHA_COVERAGE_AFTER, DEPTH_BOUNDS, STENCIL_NEVER, DEPTH_NEVER, }; constexpr deUint32 kFramebufferWidth = 32u; constexpr deUint32 kFramebufferHeight = 32u; constexpr deUint32 kTotalPixels = kFramebufferWidth * kFramebufferHeight; constexpr vk::VkFormatFeatureFlags kNeededColorFeatures = (vk::VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT | vk::VK_FORMAT_FEATURE_TRANSFER_SRC_BIT); constexpr vk::VkFormat kColorFormat = vk::VK_FORMAT_R8G8B8A8_UNORM; constexpr vk::VkFormatFeatureFlags kNeededDSFeatures = vk::VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT; // VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT must be supported for one of these two, according to the spec. const vk::VkFormat kDepthStencilFormats[] = { vk::VK_FORMAT_D32_SFLOAT_S8_UINT, vk::VK_FORMAT_D24_UNORM_S8_UINT }; struct DepthBoundsParameters { float minDepthBounds; float maxDepthBounds; float depthValue; }; struct TestParams { CaseType caseType; tcu::Vec4 clearColor; tcu::Vec4 drawColor; bool colorAtEnd; tcu::Maybe<DepthBoundsParameters> depthBoundsParams; TestParams (CaseType type, const tcu::Vec4& clearColor_, const tcu::Vec4& drawColor_, bool colorAtEnd_, const tcu::Maybe<DepthBoundsParameters>& depthBoundsParams_) : caseType (type) , clearColor (clearColor_) , drawColor (drawColor_) , colorAtEnd (colorAtEnd_) , depthBoundsParams (depthBoundsParams_) { if (caseType == CaseType::DEPTH_BOUNDS) DE_ASSERT(static_cast<bool>(depthBoundsParams)); } }; bool expectClearColor (CaseType caseType) { return (caseType != CaseType::ALPHA_COVERAGE_BEFORE && caseType != CaseType::ALPHA_COVERAGE_AFTER); } bool needsDepthStencilAttachment (CaseType caseType) { return (caseType == CaseType::DEPTH_BOUNDS || caseType == CaseType::DEPTH_NEVER || caseType == CaseType::STENCIL_NEVER); } vk::VkBool32 makeVkBool32 (bool value) { return (value ? VK_TRUE : VK_FALSE); } class FragSideEffectsTestCase : public vkt::TestCase { public: FragSideEffectsTestCase (tcu::TestContext& testCtx, const std::string& name, const std::string& description, const TestParams& params); virtual ~FragSideEffectsTestCase (void) {} virtual void checkSupport (Context& context) const; virtual void initPrograms (vk::SourceCollections& programCollection) const; virtual TestInstance* createInstance (Context& context) const; private: TestParams m_params; }; class FragSideEffectsInstance : public vkt::TestInstance { public: FragSideEffectsInstance (Context& context, const TestParams& params); virtual ~FragSideEffectsInstance (void) {} virtual tcu::TestStatus iterate (void); private: TestParams m_params; }; FragSideEffectsTestCase::FragSideEffectsTestCase (tcu::TestContext& testCtx, const std::string& name, const std::string& description, const TestParams& params) : vkt::TestCase (testCtx, name, description) , m_params (params) {} void FragSideEffectsTestCase::checkSupport (Context& context) const { const auto& vki = context.getInstanceInterface(); const auto physicalDevice = context.getPhysicalDevice(); if (m_params.caseType == CaseType::DEPTH_BOUNDS) { const auto features = vk::getPhysicalDeviceFeatures(vki, physicalDevice); if (!features.depthBounds) TCU_THROW(NotSupportedError, "Depth bounds test not supported"); } else if (m_params.caseType == CaseType::DEMOTE) { context.requireDeviceFunctionality("VK_EXT_shader_demote_to_helper_invocation"); } const auto colorFormatProperties = vk::getPhysicalDeviceFormatProperties(vki, physicalDevice, kColorFormat); if ((colorFormatProperties.optimalTilingFeatures & kNeededColorFeatures) != kNeededColorFeatures) TCU_THROW(NotSupportedError, "Color format lacks required features"); } void FragSideEffectsTestCase::initPrograms (vk::SourceCollections& programCollection) const { std::ostringstream headers; std::ostringstream before; std::ostringstream after; std::ostringstream vert; std::ostringstream frag; // Depth should be 0 by default unless provided by the depth bounds parameters. const float meshDepth = (m_params.depthBoundsParams ? m_params.depthBoundsParams.get().depthValue : 0.0f); const auto& drawColor = m_params.drawColor; vert << "#version 450\n" << "\n" << "layout (location=0) in vec2 inPos;\n" << "\n" << "void main() {\n" << " gl_Position = vec4(inPos, " << meshDepth << ", 1.0);\n" << "}\n" ; // Prepare output color statement to be used before or after SSBO write. std::ostringstream colorStatement; if (m_params.caseType == CaseType::ALPHA_COVERAGE_BEFORE || m_params.caseType == CaseType::ALPHA_COVERAGE_AFTER) { // In the alpha coverage cases the alpha color value is supposed to be 0. DE_ASSERT(m_params.drawColor.w() == 0.0f); // Leave out the alpha component for these cases. colorStatement << " outColor.rgb = vec3(" << drawColor.x() << ", " << drawColor.y() << ", " << drawColor.z() << ");\n"; } else { colorStatement << " outColor = vec4(" << drawColor.x() << ", " << drawColor.y() << ", " << drawColor.z() << ", " << drawColor.w() << ");\n"; } switch (m_params.caseType) { case CaseType::KILL: after << " discard;\n"; break; case CaseType::DEMOTE: headers << "#extension GL_EXT_demote_to_helper_invocation : enable\n"; after << " demote;\n"; break; case CaseType::SAMPLE_MASK_BEFORE: before << " gl_SampleMask[0] = 0;\n"; break; case CaseType::SAMPLE_MASK_AFTER: after << " gl_SampleMask[0] = 0;\n"; break; case CaseType::ALPHA_COVERAGE_BEFORE: before << " outColor.a = float(" << drawColor.w() << ");\n"; break; case CaseType::ALPHA_COVERAGE_AFTER: after << " outColor.a = float(" << drawColor.w() << ");\n"; break; case CaseType::DEPTH_BOUNDS: case CaseType::STENCIL_NEVER: case CaseType::DEPTH_NEVER: break; default: DE_ASSERT(false); break; } frag << "#version 450\n" << "layout(set=0, binding=0, std430) buffer OutputBuffer {\n" << " int val[" << kTotalPixels << "];\n" << "} outBuffer;\n" << "layout (location=0) out vec4 outColor;\n" << headers.str() << "\n" << "void main() {\n" << " const ivec2 fragCoord = ivec2(gl_FragCoord);\n" << " const int bufferIndex = (fragCoord.y * " << kFramebufferWidth << ") + fragCoord.x;\n" << (m_params.colorAtEnd ? "" : colorStatement.str()) << before.str() << " outBuffer.val[bufferIndex] = 1;\n" << after.str() << (m_params.colorAtEnd ? colorStatement.str() : "") << "}\n" ; programCollection.glslSources.add("vert") << glu::VertexSource(vert.str()); programCollection.glslSources.add("frag") << glu::FragmentSource(frag.str()); } TestInstance* FragSideEffectsTestCase::createInstance (Context& context) const { return new FragSideEffectsInstance(context, m_params); } FragSideEffectsInstance::FragSideEffectsInstance (Context& context, const TestParams& params) : vkt::TestInstance (context) , m_params (params) {} tcu::TestStatus FragSideEffectsInstance::iterate (void) { const auto& vki = m_context.getInstanceInterface(); const auto physicalDevice = m_context.getPhysicalDevice(); const auto& vkd = m_context.getDeviceInterface(); const auto device = m_context.getDevice(); auto& alloc = m_context.getDefaultAllocator(); const auto queue = m_context.getUniversalQueue(); const auto queueIndex = m_context.getUniversalQueueFamilyIndex(); // Color and depth/stencil images. const vk::VkImageCreateInfo colorCreateInfo = { vk::VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, // VkStructureType sType; nullptr, // const void* pNext; 0u, // VkImageCreateFlags flags; vk::VK_IMAGE_TYPE_2D, // VkImageType imageType; kColorFormat, // VkFormat format; vk::makeExtent3D(kFramebufferWidth, kFramebufferHeight, 1u), // VkExtent3D extent; 1u, // deUint32 mipLevels; 1u, // deUint32 arrayLayers; vk::VK_SAMPLE_COUNT_1_BIT, // VkSampleCountFlagBits samples; vk::VK_IMAGE_TILING_OPTIMAL, // VkImageTiling tiling; (vk::VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | vk::VK_IMAGE_USAGE_TRANSFER_SRC_BIT), // VkImageUsageFlags usage; vk::VK_SHARING_MODE_EXCLUSIVE, // VkSharingMode sharingMode; 0u, // deUint32 queueFamilyIndexCount; nullptr, // const deUint32* pQueueFamilyIndices; vk::VK_IMAGE_LAYOUT_UNDEFINED, // VkImageLayout initialLayout; }; vk::ImageWithMemory colorImage(vkd, device, alloc, colorCreateInfo, vk::MemoryRequirement::Any); std::unique_ptr<vk::ImageWithMemory> depthStencilImage; vk::VkFormat depthStencilFormat = vk::VK_FORMAT_UNDEFINED; if (needsDepthStencilAttachment(m_params.caseType)) { // Find available image format first. for (int i = 0; i < DE_LENGTH_OF_ARRAY(kDepthStencilFormats); ++i) { const auto dsFormatProperties = vk::getPhysicalDeviceFormatProperties(vki, physicalDevice, kDepthStencilFormats[i]); if ((dsFormatProperties.optimalTilingFeatures & kNeededDSFeatures) == kNeededDSFeatures) { depthStencilFormat = kDepthStencilFormats[i]; break; } } if (depthStencilFormat == vk::VK_FORMAT_UNDEFINED) TCU_FAIL("No suitable depth/stencil format found"); const vk::VkImageCreateInfo depthStencilCreateInfo = { vk::VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, // VkStructureType sType; nullptr, // const void* pNext; 0u, // VkImageCreateFlags flags; vk::VK_IMAGE_TYPE_2D, // VkImageType imageType; depthStencilFormat, // VkFormat format; vk::makeExtent3D(kFramebufferWidth, kFramebufferHeight, 1u), // VkExtent3D extent; 1u, // deUint32 mipLevels; 1u, // deUint32 arrayLayers; vk::VK_SAMPLE_COUNT_1_BIT, // VkSampleCountFlagBits samples; vk::VK_IMAGE_TILING_OPTIMAL, // VkImageTiling tiling; vk::VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, // VkImageUsageFlags usage; vk::VK_SHARING_MODE_EXCLUSIVE, // VkSharingMode sharingMode; 0u, // deUint32 queueFamilyIndexCount; nullptr, // const deUint32* pQueueFamilyIndices; vk::VK_IMAGE_LAYOUT_UNDEFINED, // VkImageLayout initialLayout; }; depthStencilImage.reset(new vk::ImageWithMemory(vkd, device, alloc, depthStencilCreateInfo, vk::MemoryRequirement::Any)); } // Image views. const auto colorSubresourceRange = vk::makeImageSubresourceRange(vk::VK_IMAGE_ASPECT_COLOR_BIT, 0u, 1u, 0u, 1u); const auto colorImageView = vk::makeImageView(vkd, device, colorImage.get(), vk::VK_IMAGE_VIEW_TYPE_2D, kColorFormat, colorSubresourceRange); vk::Move<vk::VkImageView> depthStencilImageView; if (depthStencilImage) { const auto depthStencilSubresourceRange = vk::makeImageSubresourceRange((vk::VK_IMAGE_ASPECT_DEPTH_BIT | vk::VK_IMAGE_ASPECT_STENCIL_BIT), 0u, 1u, 0u, 1u); depthStencilImageView = vk::makeImageView(vkd, device, depthStencilImage.get()->get(), vk::VK_IMAGE_VIEW_TYPE_2D, depthStencilFormat, depthStencilSubresourceRange); } // Color image buffer. const auto tcuFormat = vk::mapVkFormat(kColorFormat); const auto colorImageBufferSize = static_cast<vk::VkDeviceSize>(kTotalPixels * tcuFormat.getPixelSize()); const auto colorImageBufferInfo = vk::makeBufferCreateInfo(colorImageBufferSize, vk::VK_BUFFER_USAGE_TRANSFER_DST_BIT); vk::BufferWithMemory colorImageBuffer(vkd, device, alloc, colorImageBufferInfo, vk::MemoryRequirement::HostVisible); // Vertex buffer. const std::vector<tcu::Vec2> fullScreenQuad = { tcu::Vec2(-1.0f, 1.0f), tcu::Vec2( 1.0f, 1.0f), tcu::Vec2( 1.0f, -1.0f), tcu::Vec2(-1.0f, 1.0f), tcu::Vec2( 1.0f, -1.0f), tcu::Vec2(-1.0f, -1.0f), }; const auto vertexBufferSize = static_cast<vk::VkDeviceSize>(fullScreenQuad.size() * sizeof(decltype(fullScreenQuad)::value_type)); const auto vertexBufferInfo = vk::makeBufferCreateInfo(vertexBufferSize, vk::VK_BUFFER_USAGE_VERTEX_BUFFER_BIT); const vk::VkDeviceSize vertexBufferOffset = 0ull; vk::BufferWithMemory vertexBuffer (vkd, device, alloc, vertexBufferInfo, vk::MemoryRequirement::HostVisible); const auto& vertexBufferAlloc = vertexBuffer.getAllocation(); deMemcpy(vertexBufferAlloc.getHostPtr(), fullScreenQuad.data(), static_cast<size_t>(vertexBufferSize)); vk::flushAlloc(vkd, device, vertexBufferAlloc); // Storage buffer. const auto storageBufferSize = static_cast<vk::VkDeviceSize>(kTotalPixels * sizeof(deInt32)); const auto storageBufferInfo = vk::makeBufferCreateInfo(storageBufferSize, (vk::VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | vk::VK_BUFFER_USAGE_TRANSFER_SRC_BIT)); vk::BufferWithMemory storageBuffer (vkd, device, alloc, storageBufferInfo, vk::MemoryRequirement::HostVisible); const auto& storageBufferAlloc = storageBuffer.getAllocation(); deMemset(storageBufferAlloc.getHostPtr(), 0, static_cast<size_t>(storageBufferSize)); vk::flushAlloc(vkd, device, storageBufferAlloc); // Descriptor set layout. vk::DescriptorSetLayoutBuilder layoutBuilder; layoutBuilder.addSingleBinding(vk::VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, vk::VK_SHADER_STAGE_FRAGMENT_BIT); const auto descriptorSetLayout = layoutBuilder.build(vkd, device); // Pipeline layout. const auto pipelineLayout = vk::makePipelineLayout(vkd, device, descriptorSetLayout.get()); // Descriptor pool. vk::DescriptorPoolBuilder poolBuilder; poolBuilder.addType(vk::VK_DESCRIPTOR_TYPE_STORAGE_BUFFER); const auto descriptorPool = poolBuilder.build(vkd, device, vk::VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT, 1u); // Descriptor set. const auto descriptorSet = vk::makeDescriptorSet(vkd, device, descriptorPool.get(), descriptorSetLayout.get()); // Update descriptor set. vk::DescriptorSetUpdateBuilder updateBuilder; const auto descriptorBufferInfo = vk::makeDescriptorBufferInfo(storageBuffer.get(), 0u, storageBufferSize); updateBuilder.writeSingle(descriptorSet.get(), vk::DescriptorSetUpdateBuilder::Location::binding(0), vk::VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, &descriptorBufferInfo); updateBuilder.update(vkd, device); // Render pass. const auto renderPass = vk::makeRenderPass(vkd, device, kColorFormat, depthStencilFormat); // Framebuffer. std::vector<vk::VkImageView> imageViews(1u, colorImageView.get()); if (depthStencilImage) imageViews.push_back(depthStencilImageView.get()); const auto framebuffer = vk::makeFramebuffer(vkd, device, renderPass.get(), static_cast<deUint32>(imageViews.size()), imageViews.data(), kFramebufferWidth, kFramebufferHeight); // Shader modules. const auto vertModule = vk::createShaderModule(vkd, device, m_context.getBinaryCollection().get("vert"), 0u); const auto fragModule = vk::createShaderModule(vkd, device, m_context.getBinaryCollection().get("frag"), 0u); // Vertex input state. const auto vertexBinding = vk::makeVertexInputBindingDescription(0u, static_cast<deUint32>(sizeof(tcu::Vec2)), vk::VK_VERTEX_INPUT_RATE_VERTEX); const auto vertexAttributes = vk::makeVertexInputAttributeDescription(0u, 0u, vk::VK_FORMAT_R32G32_SFLOAT, 0u); const vk::VkPipelineVertexInputStateCreateInfo vertexInputInfo = { vk::VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO, // VkStructureType sType; nullptr, // const void* pNext; 0u, // VkPipelineVertexInputStateCreateFlags flags; 1u, // deUint32 vertexBindingDescriptionCount; &vertexBinding, // const VkVertexInputBindingDescription* pVertexBindingDescriptions; 1u, // deUint32 vertexAttributeDescriptionCount; &vertexAttributes, // const VkVertexInputAttributeDescription* pVertexAttributeDescriptions; }; // Input assembly state. const vk::VkPipelineInputAssemblyStateCreateInfo inputAssemblyInfo = { vk::VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO, // VkStructureType sType; nullptr, // const void* pNext; 0u, // VkPipelineInputAssemblyStateCreateFlags flags; vk::VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, // VkPrimitiveTopology topology; VK_FALSE, // VkBool32 primitiveRestartEnable; }; // Viewport state. const auto viewport = vk::makeViewport(kFramebufferWidth, kFramebufferHeight); const auto scissor = vk::makeRect2D(kFramebufferWidth, kFramebufferHeight); const vk::VkPipelineViewportStateCreateInfo viewportInfo = { vk::VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO, // VkStructureType sType; nullptr, // const void* pNext; 0u, // VkPipelineViewportStateCreateFlags flags; 1u, // deUint32 viewportCount; &viewport, // const VkViewport* pViewports; 1u, // deUint32 scissorCount; &scissor, // const VkRect2D* pScissors; }; // Rasterization state. const vk::VkPipelineRasterizationStateCreateInfo rasterizationInfo = { vk::VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO, // VkStructureType sType; nullptr, // const void* pNext; 0u, // VkPipelineRasterizationStateCreateFlags flags; VK_FALSE, // VkBool32 depthClampEnable; VK_FALSE, // VkBool32 rasterizerDiscardEnable; vk::VK_POLYGON_MODE_FILL, // VkPolygonMode polygonMode; vk::VK_CULL_MODE_NONE, // VkCullModeFlags cullMode; vk::VK_FRONT_FACE_COUNTER_CLOCKWISE, // VkFrontFace frontFace; VK_FALSE, // VkBool32 depthBiasEnable; 0.0f, // float depthBiasConstantFactor; 0.0f, // float depthBiasClamp; 0.0f, // float depthBiasSlopeFactor; 1.0f, // float lineWidth; }; // Multisample state. const bool alphaToCoverageEnable = (m_params.caseType == CaseType::ALPHA_COVERAGE_BEFORE || m_params.caseType == CaseType::ALPHA_COVERAGE_AFTER); const vk::VkPipelineMultisampleStateCreateInfo multisampleInfo = { vk::VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO, // VkStructureType sType; nullptr, // const void* pNext; 0u, // VkPipelineMultisampleStateCreateFlags flags; vk::VK_SAMPLE_COUNT_1_BIT, // VkSampleCountFlagBits rasterizationSamples; VK_FALSE, // VkBool32 sampleShadingEnable; 0.0f, // float minSampleShading; nullptr, // const VkSampleMask* pSampleMask; makeVkBool32(alphaToCoverageEnable), // VkBool32 alphaToCoverageEnable; VK_FALSE, // VkBool32 alphaToOneEnable; }; // Depth/stencil state. const auto enableDepthBounds = makeVkBool32(m_params.caseType == CaseType::DEPTH_BOUNDS); const auto enableDepthStencilTest = static_cast<bool>(depthStencilImage); const auto depthCompareOp = ((m_params.caseType == CaseType::DEPTH_NEVER) ? vk::VK_COMPARE_OP_NEVER : vk::VK_COMPARE_OP_ALWAYS); const auto stencilCompareOp = ((m_params.caseType == CaseType::STENCIL_NEVER) ? vk::VK_COMPARE_OP_NEVER : vk::VK_COMPARE_OP_ALWAYS); const auto stencilOpState = vk::makeStencilOpState(vk::VK_STENCIL_OP_KEEP, vk::VK_STENCIL_OP_KEEP, vk::VK_STENCIL_OP_KEEP, stencilCompareOp, 0xFFu, 0xFFu, 0u); const vk::VkPipelineDepthStencilStateCreateInfo depthStencilInfo = { vk::VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO, // VkStructureType sType; nullptr, // const void* pNext; 0u, // VkPipelineDepthStencilStateCreateFlags flags; enableDepthStencilTest, // VkBool32 depthTestEnable; enableDepthStencilTest, // VkBool32 depthWriteEnable; depthCompareOp, // VkCompareOp depthCompareOp; enableDepthBounds, // VkBool32 depthBoundsTestEnable; enableDepthStencilTest, // VkBool32 stencilTestEnable; stencilOpState, // VkStencilOpState front; stencilOpState, // VkStencilOpState back; (enableDepthBounds ? m_params.depthBoundsParams.get().minDepthBounds : 0.0f), // float minDepthBounds; (enableDepthBounds ? m_params.depthBoundsParams.get().maxDepthBounds : 1.0f), // float maxDepthBounds; }; // Color blend state. const vk::VkPipelineColorBlendAttachmentState colorBlendAttachmentState = { VK_FALSE, // VkBool32 blendEnable vk::VK_BLEND_FACTOR_ZERO, // VkBlendFactor srcColorBlendFactor vk::VK_BLEND_FACTOR_ZERO, // VkBlendFactor dstColorBlendFactor vk::VK_BLEND_OP_ADD, // VkBlendOp colorBlendOp vk::VK_BLEND_FACTOR_ZERO, // VkBlendFactor srcAlphaBlendFactor vk::VK_BLEND_FACTOR_ZERO, // VkBlendFactor dstAlphaBlendFactor vk::VK_BLEND_OP_ADD, // VkBlendOp alphaBlendOp vk::VK_COLOR_COMPONENT_R_BIT // VkColorComponentFlags colorWriteMask | vk::VK_COLOR_COMPONENT_G_BIT | vk::VK_COLOR_COMPONENT_B_BIT | vk::VK_COLOR_COMPONENT_A_BIT }; const vk::VkPipelineColorBlendStateCreateInfo colorBlendInfo = { vk::VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO, // VkStructureType sType; nullptr, // const void* pNext; 0u, // VkPipelineColorBlendStateCreateFlags flags; VK_FALSE, // VkBool32 logicOpEnable; vk::VK_LOGIC_OP_NO_OP, // VkLogicOp logicOp; 1u, // deUint32 attachmentCount; &colorBlendAttachmentState, // const VkPipelineColorBlendAttachmentState* pAttachments; { .0f, .0f, .0f, .0f }, // float blendConstants[4]; }; // Graphics pipeline. const auto graphicsPipeline = vk::makeGraphicsPipeline( vkd, device, pipelineLayout.get(), vertModule.get(), DE_NULL, DE_NULL, DE_NULL, fragModule.get(), renderPass.get(), 0u, &vertexInputInfo, &inputAssemblyInfo, nullptr, &viewportInfo, &rasterizationInfo, &multisampleInfo, &depthStencilInfo, &colorBlendInfo); // Command buffer. const auto cmdPool = vk::makeCommandPool(vkd, device, queueIndex); const auto cmdBufferPtr = vk::allocateCommandBuffer(vkd, device, cmdPool.get(), vk::VK_COMMAND_BUFFER_LEVEL_PRIMARY); const auto cmdBuffer = cmdBufferPtr.get(); // Draw full-screen quad. std::vector<vk::VkClearValue> clearValues; clearValues.push_back(vk::makeClearValueColor(m_params.clearColor)); clearValues.push_back(vk::makeClearValueDepthStencil(1.0f, 0u)); vk::beginCommandBuffer(vkd, cmdBuffer); vk::beginRenderPass(vkd, cmdBuffer, renderPass.get(), framebuffer.get(), vk::makeRect2D(kFramebufferWidth, kFramebufferHeight), static_cast<deUint32>(clearValues.size()), clearValues.data()); vkd.cmdBindPipeline(cmdBuffer, vk::VK_PIPELINE_BIND_POINT_GRAPHICS, graphicsPipeline.get()); vkd.cmdBindDescriptorSets(cmdBuffer, vk::VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout.get(), 0u, 1u, &descriptorSet.get(), 0u, nullptr); vkd.cmdBindVertexBuffers(cmdBuffer, 0u, 1u, &vertexBuffer.get(), &vertexBufferOffset); vkd.cmdDraw(cmdBuffer, static_cast<deUint32>(fullScreenQuad.size()), 1u, 0u, 0u); vk::endRenderPass(vkd, cmdBuffer); // Image and buffer barriers. // Storage buffer frag-write to host-read barrier. const auto storageBufferBarrier = vk::makeBufferMemoryBarrier(vk::VK_ACCESS_SHADER_WRITE_BIT, vk::VK_ACCESS_HOST_READ_BIT, storageBuffer.get(), 0u, VK_WHOLE_SIZE); // Color image frag-write to transfer-read barrier. const auto colorImageBarrier = vk::makeImageMemoryBarrier(vk::VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, vk::VK_ACCESS_TRANSFER_READ_BIT, vk::VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, vk::VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, colorImage.get(), colorSubresourceRange); // Color buffer transfer-write to host-read barrier. const auto colorBufferBarrier = vk::makeBufferMemoryBarrier(vk::VK_ACCESS_TRANSFER_WRITE_BIT, vk::VK_ACCESS_HOST_READ_BIT, colorImageBuffer.get(), 0u, VK_WHOLE_SIZE); vk::cmdPipelineBufferMemoryBarrier(vkd, cmdBuffer, vk::VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, vk::VK_PIPELINE_STAGE_HOST_BIT, &storageBufferBarrier); vk::cmdPipelineImageMemoryBarrier(vkd, cmdBuffer, vk::VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, vk::VK_PIPELINE_STAGE_TRANSFER_BIT, &colorImageBarrier); const auto copyRegion = vk::makeBufferImageCopy(vk::makeExtent3D(kFramebufferWidth, kFramebufferHeight, 1u), vk::makeImageSubresourceLayers(vk::VK_IMAGE_ASPECT_COLOR_BIT, 0u, 0u, 1u)); vkd.cmdCopyImageToBuffer(cmdBuffer, colorImage.get(), vk::VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, colorImageBuffer.get(), 1u, &copyRegion); vk::cmdPipelineBufferMemoryBarrier(vkd, cmdBuffer, vk::VK_PIPELINE_STAGE_TRANSFER_BIT, vk::VK_PIPELINE_STAGE_HOST_BIT, &colorBufferBarrier); vk::endCommandBuffer(vkd, cmdBuffer); vk::submitCommandsAndWait(vkd, device, queue, cmdBuffer); // Check output. { // Check SSBO contents. vk::invalidateAlloc(vkd, device, storageBufferAlloc); const auto bufferElements = reinterpret_cast<const deInt32*>(storageBufferAlloc.getHostPtr()); for (deUint32 i = 0; i < kTotalPixels; ++i) { if (bufferElements[i] != 1) { std::ostringstream msg; msg << "Unexpected value in storage buffer element " << i; return tcu::TestStatus::fail("Fail: " + msg.str()); } } } { // Check color attachment. std::vector<tcu::Vec4> expectedColors(1u, m_params.clearColor); if (!expectClearColor(m_params.caseType)) expectedColors.push_back(m_params.drawColor); const auto& colorImageBufferAlloc = colorImageBuffer.getAllocation(); vk::invalidateAlloc(vkd, device, colorImageBufferAlloc); const auto iWidth = static_cast<int>(kFramebufferWidth); const auto iHeight = static_cast<int>(kFramebufferHeight); tcu::ConstPixelBufferAccess colorPixels (tcuFormat, iWidth, iHeight, 1, colorImageBufferAlloc.getHostPtr()); std::vector<deUint8> errorMaskBuffer (kTotalPixels * tcuFormat.getPixelSize(), 0u); tcu::PixelBufferAccess errorMask (tcuFormat, iWidth, iHeight, 1, errorMaskBuffer.data()); const tcu::Vec4 green (0.0f, 1.0f, 0.0f, 1.0f); const tcu::Vec4 red (1.0f, 0.0f, 0.0f, 1.0f); bool allPixOk = true; for (int i = 0; i < iWidth; ++i) for (int j = 0; j < iHeight; ++j) { const auto pixel = colorPixels.getPixel(i, j); const bool pixOk = std::any_of(begin(expectedColors), end(expectedColors), [&pixel](const tcu::Vec4& expected) -> bool { return (pixel == expected); }); errorMask.setPixel((pixOk ? green : red), i, j); if (!pixOk) allPixOk = false; } if (!allPixOk) { auto& testLog = m_context.getTestContext().getLog(); testLog << tcu::TestLog::Image("ColorBuffer", "Result color buffer", colorPixels); testLog << tcu::TestLog::Image("ErrorMask", "Error mask with errors marked in red", errorMask); return tcu::TestStatus::fail("Fail: color buffer with unexpected values; check logged images"); } } return tcu::TestStatus::pass("Pass"); } } // anonymous tcu::TestCaseGroup* createFragSideEffectsTests (tcu::TestContext& testCtx) { de::MovePtr<tcu::TestCaseGroup> fragSideEffectsGroup(new tcu::TestCaseGroup(testCtx, "frag_side_effects", "Test fragment shader side effects are not removed by optimizations")); const tcu::Vec4 kDefaultClearColor (0.0f, 0.0f, 0.0f, 1.0f); const tcu::Vec4 kDefaultDrawColor (0.0f, 0.0f, 1.0f, 1.0f); const auto kDefaultDepthBoundsParams = tcu::nothing<DepthBoundsParameters>(); static const struct { bool colorAtEnd; std::string name; std::string desc; } kColorOrders[] = { { false, "color_at_beginning", "Fragment shader output assignment at the beginning of the shader" }, { true, "color_at_end", "Fragment shader output assignment at the end of the shader" }, }; for (int i = 0; i < DE_LENGTH_OF_ARRAY(kColorOrders); ++i) { de::MovePtr<tcu::TestCaseGroup> colorOrderGroup(new tcu::TestCaseGroup(testCtx, kColorOrders[i].name.c_str(), kColorOrders[i].desc.c_str())); const bool colorAtEnd = kColorOrders[i].colorAtEnd; { TestParams params(CaseType::KILL, kDefaultClearColor, kDefaultDrawColor, colorAtEnd, kDefaultDepthBoundsParams); colorOrderGroup->addChild(new FragSideEffectsTestCase(testCtx, "kill", "OpKill after SSBO write", params)); } { TestParams params(CaseType::DEMOTE, kDefaultClearColor, kDefaultDrawColor, colorAtEnd, kDefaultDepthBoundsParams); colorOrderGroup->addChild(new FragSideEffectsTestCase(testCtx, "demote", "OpDemoteToHelperInvocation after SSBO write", params)); } { TestParams params(CaseType::SAMPLE_MASK_BEFORE, kDefaultClearColor, kDefaultDrawColor, colorAtEnd, kDefaultDepthBoundsParams); colorOrderGroup->addChild(new FragSideEffectsTestCase(testCtx, "sample_mask_before", "Set sample mask to zero before SSBO write", params)); } { TestParams params(CaseType::SAMPLE_MASK_AFTER, kDefaultClearColor, kDefaultDrawColor, colorAtEnd, kDefaultDepthBoundsParams); colorOrderGroup->addChild(new FragSideEffectsTestCase(testCtx, "sample_mask_after", "Set sample mask to zero after SSBO write", params)); } { TestParams params(CaseType::STENCIL_NEVER, kDefaultClearColor, kDefaultDrawColor, colorAtEnd, kDefaultDepthBoundsParams); colorOrderGroup->addChild(new FragSideEffectsTestCase(testCtx, "stencil_never", "SSBO write with stencil test never passes", params)); } { TestParams params(CaseType::DEPTH_NEVER, kDefaultClearColor, kDefaultDrawColor, colorAtEnd, kDefaultDepthBoundsParams); colorOrderGroup->addChild(new FragSideEffectsTestCase(testCtx, "depth_never", "SSBO write with depth test never passes", params)); } { const tcu::Vec4 drawColor(kDefaultDrawColor.x(), kDefaultDrawColor.y(), kDefaultDrawColor.z(), 0.0f); { TestParams params(CaseType::ALPHA_COVERAGE_BEFORE, kDefaultClearColor, drawColor, colorAtEnd, kDefaultDepthBoundsParams); colorOrderGroup->addChild(new FragSideEffectsTestCase(testCtx, "alpha_coverage_before", "Enable alpha coverage and draw with alpha zero before SSBO write", params)); } { TestParams params(CaseType::ALPHA_COVERAGE_AFTER, kDefaultClearColor, drawColor, colorAtEnd, kDefaultDepthBoundsParams); colorOrderGroup->addChild(new FragSideEffectsTestCase(testCtx, "alpha_coverage_after", "Enable alpha coverage and draw with alpha zero after SSBO write", params)); } } { DepthBoundsParameters depthBoundsParams = {0.25f, 0.5f, 0.75f}; // min, max, draw depth. TestParams params(CaseType::DEPTH_BOUNDS, kDefaultClearColor, kDefaultDrawColor, colorAtEnd, tcu::just(depthBoundsParams)); colorOrderGroup->addChild(new FragSideEffectsTestCase(testCtx, "depth_bounds", "SSBO write with depth bounds test failing", params)); } fragSideEffectsGroup->addChild(colorOrderGroup.release()); } return fragSideEffectsGroup.release(); } } // rasterization } // vkt
44.413514
263
0.717824
[ "render", "vector" ]
9ca78e8cc5d1720fb0d5462f498e43d120f9443d
8,064
hpp
C++
include/khepri/math/vector4.hpp
KhepriEngine/KhepriEngine
6ee25cdb57c8e98ff9a0565ebd3b091eac268143
[ "MIT" ]
2
2021-04-30T12:05:35.000Z
2021-05-11T15:56:39.000Z
include/khepri/math/vector4.hpp
KhepriEngine/KhepriEngine
6ee25cdb57c8e98ff9a0565ebd3b091eac268143
[ "MIT" ]
null
null
null
include/khepri/math/vector4.hpp
KhepriEngine/KhepriEngine
6ee25cdb57c8e98ff9a0565ebd3b091eac268143
[ "MIT" ]
null
null
null
#pragma once #include "math.hpp" #include "vector3.hpp" #include <gsl/gsl> #include <cassert> #include <cmath> namespace khepri { class matrix; /// \brief A 4-component vector #pragma pack(push, 1) class Vector4 final { public: /// The type of the vector's components using component_type = float; component_type x{}; ///< The vector's X element component_type y{}; ///< The vector's Y element component_type z{}; ///< The vector's Z element component_type w{}; ///< The vector's W element /// Constructs an uninitialized vector constexpr Vector4() noexcept = default; /// Constructs the vector from literal floats constexpr Vector4(component_type fx, component_type fy, component_type fz, component_type fw) noexcept : x(fx), y(fy), z(fz), w(fw) {} /// Constructs the vector from a vector2, and floats for Z and W constexpr Vector4(const Vector2& v, component_type fz, component_type fw) noexcept : x(v.x), y(v.y), z(fz), w(fw) {} /// Constructs the vector from a vector3, and a float for W constexpr Vector4(const Vector3& v, component_type fw) noexcept : x(v.x), y(v.y), z(v.z), w(fw) {} /// Adds vector \a v to the vector constexpr Vector4& operator+=(const Vector4& v) noexcept { x += v.x; y += v.y; z += v.z; w += v.w; return *this; } /// Subtracts vector \a v from the vector constexpr Vector4& operator-=(const Vector4& v) noexcept { x -= v.x; y -= v.y; z -= v.z; w -= v.w; return *this; } /// Scales the vector by scalar \a s constexpr Vector4& operator*=(component_type s) noexcept { x *= s; y *= s; z *= s; w *= s; return *this; } /// Scales the vector by scalar 1.0 / \a s constexpr Vector4& operator/=(component_type s) noexcept { x /= s; y /= s; z /= s; w /= s; return *this; } /** * Indexes the vector. * * \param[in] index the component index to return. 0 is X, 1 is Y, etc. */ constexpr const component_type& operator[](std::size_t index) const noexcept { assert(index < 4); return gsl::span<const component_type>(&x, 4)[index]; } /** * Indexes the vector. * * \param[in] index the component index to return. 0 is X, 1 is Y, etc. */ constexpr component_type& operator[](std::size_t index) noexcept { assert(index < 4); return gsl::span<component_type>(&x, 4)[index]; } /// Calculates the length of the vector [[nodiscard]] component_type length() const noexcept { return std::sqrt(length_sq()); } /** * \brief Calculates the squared length of the vector * * Calculating the squared length (length*length) is a considerably faster operation so use it * whenever possible (e.g., when comparing lengths) */ [[nodiscard]] constexpr component_type length_sq() const noexcept { return x * x + y * y + z * z + w * w; } /// Calculates the distance between the vector and vector \a v [[nodiscard]] component_type distance(const Vector4& v) const noexcept { const auto dx = v.x - x; const auto dy = v.y - y; const auto dz = v.z - z; const auto dw = v.w - w; return std::sqrt(dx * dx + dy * dy + dz * dz + dw * dw); } /** * \brief Calculates the squared distance between the vector and vector \a v * * Calculating the squared distance (distance*distance) is a considerably faster operation so * use it whenever possible (e.g., when comparing distances) */ [[nodiscard]] constexpr component_type distance_sq(const Vector4& v) const noexcept { const auto dx = v.x - x; const auto dy = v.y - y; const auto dz = v.z - z; const auto dw = v.w - w; return dx * dx + dy * dy + dz * dz + dw * dw; } /// Calculates the dot product between the vector and vector \a v [[nodiscard]] constexpr component_type dot(const Vector4& v) const noexcept { return x * v.x + y * v.y + z * v.z + w * v.w; } /// Normalizes the vector void normalize() noexcept { const component_type inv_length = 1.0F / length(); x *= inv_length; y *= inv_length; z *= inv_length; w *= inv_length; } /// Checks if the vector is normalized [[nodiscard]] bool normalized() const noexcept { constexpr auto max_normalized_length = 0.000001; return abs(1.0F - length()) < max_normalized_length; } }; #pragma pack(pop) /// Validate that the vector has the expected size, because this type can be directly used in a /// mapping to graphics engine's memory. static_assert(sizeof(Vector4) == 4 * sizeof(Vector4::component_type), "Vector4 does not have the expected size"); /// Negates vector \a v inline constexpr Vector4 operator-(const Vector4& v) noexcept { return Vector4(-v.x, -v.y, -v.z, -v.w); } /// Adds vector \a v2 to vector \a v1 inline constexpr Vector4 operator+(const Vector4& v1, const Vector4& v2) noexcept { return Vector4(v1.x + v2.x, v1.y + v2.y, v1.z + v2.z, v1.w + v2.w); } /// Subtracts vector \a v2 from vector \a v1 inline constexpr Vector4 operator-(const Vector4& v1, const Vector4& v2) noexcept { return Vector4(v1.x - v2.x, v1.y - v2.y, v1.z - v2.z, v1.w - v2.w); } /// Scales vector \a v with scalar \a s inline constexpr Vector4 operator*(const Vector4& v, float s) noexcept { return Vector4(v.x * s, v.y * s, v.z * s, v.w * s); } /// Scales vector \a v with scalar \a s inline constexpr Vector4 operator*(float s, const Vector4& v) noexcept { return Vector4(v.x * s, v.y * s, v.z * s, v.w * s); } /// Scales vector \a v with scalar 1/\a s inline constexpr Vector4 operator/(const Vector4& v, float s) noexcept { return Vector4(v.x / s, v.y / s, v.z / s, v.w / s); } /// Multiplies vector \a v1 with vector \a v2, component-wise inline constexpr Vector4 operator*(const Vector4& v1, const Vector4& v2) noexcept { return Vector4(v1.x * v2.x, v1.y * v2.y, v1.z * v2.z, v1.w * v2.w); } /// Calculates the distance between the points identified by vector \a v1 and vector \a v2 inline float distance(const Vector4& v1, const Vector4& v2) noexcept { return v1.distance(v2); } /** * \brief Calculates the squared distance between the points identified by vector \a v1 and vector * \a v2 * * Calculating the squared distance (distance*distance) is a considerably faster operation so * use it whenever possible (e.g., when comparing distances) */ inline constexpr float distance_sq(const Vector4& v1, const Vector4& v2) noexcept { return v1.distance_sq(v2); } /// Calculates the dot product between vector \a v1 and vector \a v2 inline constexpr float dot(const Vector4& v1, const Vector4& v2) noexcept { return v1.dot(v2); } /// Normalizes vector \a v inline Vector4 normalize(const Vector4& v) noexcept { return v / v.length(); } inline constexpr Vector2::Vector2(const Vector4& v) noexcept : x(v.x), y(v.y) {} inline constexpr Vector3::Vector3(const Vector4& v) noexcept : x(v.x), y(v.y), z(v.z) {} /** * \brief Clamps each component of a vector between two extremes * * Returns \a min if \a val.{x,y,z,w} < \a min. * Returns \a max if \a val.{x,y,z,w} > \a max. * Otherwise, returns \a val.{x,y,z,w}. * * \param[in] val the vector to clamp * \param[in] min the lower boundary to clamp against * \param[in] max the upper boundary to clamp against * * \return \a val, with each component clamped between \a min and \a max. */ constexpr Vector4 clamp(const Vector4& val, Vector4::component_type min, Vector4::component_type max) noexcept { return {clamp(val.x, min, max), clamp(val.y, min, max), clamp(val.z, min, max), clamp(val.w, min, max)}; } } // namespace khepri
29.217391
99
0.614955
[ "vector" ]
9ca8d22b06bdbfd4c82f1eb17f9adfd379065944
18,277
cpp
C++
contrib/RemoteControl.cpp
Opendigitalradio/ODR-AudioEnc
f932f86ec601e250bbdcf2bcf87e4696b9431b50
[ "Apache-2.0" ]
15
2016-10-18T11:46:21.000Z
2022-01-16T10:34:52.000Z
contrib/RemoteControl.cpp
Opendigitalradio/ODR-AudioEnc
f932f86ec601e250bbdcf2bcf87e4696b9431b50
[ "Apache-2.0" ]
14
2016-11-15T21:14:50.000Z
2020-09-15T10:13:23.000Z
contrib/RemoteControl.cpp
Opendigitalradio/ODR-AudioEnc
f932f86ec601e250bbdcf2bcf87e4696b9431b50
[ "Apache-2.0" ]
21
2016-11-15T09:00:30.000Z
2022-03-23T17:54:40.000Z
/* Copyright (C) 2007, 2008, 2009, 2010, 2011, 2012 Her Majesty the Queen in Right of Canada (Communications Research Center Canada) Copyright (C) 2019 Matthias P. Braendli, matthias.braendli@mpb.li http://www.opendigitalradio.org */ /* 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 <list> #include <string> #include <iostream> #include <string> #include <algorithm> #include "RemoteControl.h" #include "zmq.hpp" using namespace std; RemoteControllerTelnet::~RemoteControllerTelnet() { m_active = false; if (m_restarter_thread.joinable()) { m_restarter_thread.join(); } if (m_child_thread.joinable()) { m_child_thread.join(); } } void RemoteControllerTelnet::restart() { if (m_restarter_thread.joinable()) { m_restarter_thread.join(); } m_restarter_thread = std::thread( &RemoteControllerTelnet::restart_thread, this, 0); } RemoteControllable::~RemoteControllable() { rcs.remove_controllable(this); } std::list<std::string> RemoteControllable::get_supported_parameters() const { std::list<std::string> parameterlist; for (const auto& param : m_parameters) { parameterlist.push_back(param[0]); } return parameterlist; } void RemoteControllers::add_controller(std::shared_ptr<BaseRemoteController> rc) { m_controllers.push_back(rc); } void RemoteControllers::enrol(RemoteControllable *rc) { controllables.push_back(rc); } void RemoteControllers::remove_controllable(RemoteControllable *rc) { controllables.remove(rc); } std::list< std::vector<std::string> > RemoteControllers::get_param_list_values(const std::string& name) { RemoteControllable* controllable = get_controllable_(name); std::list< std::vector<std::string> > allparams; for (auto &param : controllable->get_supported_parameters()) { std::vector<std::string> item; item.push_back(param); try { item.push_back(controllable->get_parameter(param)); } catch (const ParameterError &e) { item.push_back(std::string("error: ") + e.what()); } allparams.push_back(item); } return allparams; } std::string RemoteControllers::get_param(const std::string& name, const std::string& param) { RemoteControllable* controllable = get_controllable_(name); return controllable->get_parameter(param); } void RemoteControllers::check_faults() { for (auto &controller : m_controllers) { if (controller->fault_detected()) { etiLog.level(warn) << "Detected Remote Control fault, restarting it"; controller->restart(); } } } RemoteControllable* RemoteControllers::get_controllable_(const std::string& name) { auto rc = std::find_if(controllables.begin(), controllables.end(), [&](RemoteControllable* r) { return r->get_rc_name() == name; }); if (rc == controllables.end()) { throw ParameterError("Module name unknown"); } else { return *rc; } } void RemoteControllers::set_param( const std::string& name, const std::string& param, const std::string& value) { etiLog.level(info) << "RC: Setting " << name << " " << param << " to " << value; RemoteControllable* controllable = get_controllable_(name); try { return controllable->set_parameter(param, value); } catch (const ios_base::failure& e) { etiLog.level(info) << "RC: Failed to set " << name << " " << param << " to " << value << ": " << e.what(); throw ParameterError("Cannot understand value"); } } // This runs in a separate thread, because // it would take too long to be done in the main loop // thread. void RemoteControllerTelnet::restart_thread(long) { m_active = false; if (m_child_thread.joinable()) { m_child_thread.join(); } m_child_thread = std::thread(&RemoteControllerTelnet::process, this, 0); } void RemoteControllerTelnet::handle_accept(Socket::TCPSocket&& socket) { const std::string welcome = PACKAGE_NAME " Remote Control CLI\n" "Write 'help' for help.\n" "**********\n"; const std::string prompt = "> "; std::string in_message; try { etiLog.level(info) << "RC: Accepted"; socket.sendall(welcome.data(), welcome.size()); while (m_active and in_message != "quit") { socket.sendall(prompt.data(), prompt.size()); stringstream in_message_stream; char last_char = '\0'; try { while (last_char != '\n') { try { auto ret = socket.recv(&last_char, 1, 0, 1000); if (ret == 1) { in_message_stream << last_char; } else { break; } } catch (const Socket::TCPSocket::Timeout&) { if (not m_active) { break; } } } } catch (const Socket::TCPSocket::Interrupted&) { in_message_stream.clear(); } if (in_message_stream.str().size() == 0) { etiLog.level(info) << "RC: Connection terminated"; break; } std::getline(in_message_stream, in_message); while (in_message.length() > 0 && (in_message[in_message.length()-1] == '\r' || in_message[in_message.length()-1] == '\n')) { in_message.erase(in_message.length()-1, 1); } if (in_message.length() == 0) { continue; } etiLog.level(info) << "RC: Got message '" << in_message << "'"; dispatch_command(socket, in_message); } etiLog.level(info) << "RC: Closing socket"; socket.close(); } catch (const std::exception& e) { etiLog.level(error) << "Remote control caught exception: " << e.what(); } } void RemoteControllerTelnet::process(long) { try { m_active = true; m_socket.listen(m_port, "localhost"); etiLog.level(info) << "RC: Waiting for connection on port " << m_port; while (m_active) { auto sock = m_socket.accept(1000); if (sock.valid()) { handle_accept(move(sock)); etiLog.level(info) << "RC: Connection closed. Waiting for connection on port " << m_port; } } } catch (const runtime_error& e) { etiLog.level(warn) << "RC: Encountered error: " << e.what(); } etiLog.level(info) << "RC: Leaving"; m_fault = true; } static std::vector<std::string> tokenise(const std::string& message) { stringstream ss(message); std::vector<std::string> all_tokens; std::string item; while (std::getline(ss, item, ' ')) { all_tokens.push_back(move(item)); } return all_tokens; } void RemoteControllerTelnet::dispatch_command(Socket::TCPSocket& socket, string command) { vector<string> cmd = tokenise(command); if (cmd[0] == "help") { reply(socket, "The following commands are supported:\n" " list\n" " * Lists the modules that are loaded and their parameters\n" " show MODULE\n" " * Lists all parameters and their values from module MODULE\n" " get MODULE PARAMETER\n" " * Gets the value for the specified PARAMETER from module MODULE\n" " set MODULE PARAMETER VALUE\n" " * Sets the value for the PARAMETER ofr module MODULE\n" " quit\n" " * Terminate this session\n" "\n"); } else if (cmd[0] == "list") { stringstream ss; if (cmd.size() == 1) { for (auto &controllable : rcs.controllables) { ss << controllable->get_rc_name() << endl; list< vector<string> > params = controllable->get_parameter_descriptions(); for (auto &param : params) { ss << "\t" << param[0] << " : " << param[1] << endl; } } } else { reply(socket, "Too many arguments for command 'list'"); } reply(socket, ss.str()); } else if (cmd[0] == "show") { if (cmd.size() == 2) { try { stringstream ss; list< vector<string> > r = rcs.get_param_list_values(cmd[1]); for (auto &param_val : r) { ss << param_val[0] << ": " << param_val[1] << endl; } reply(socket, ss.str()); } catch (const ParameterError &e) { reply(socket, e.what()); } } else { reply(socket, "Incorrect parameters for command 'show'"); } } else if (cmd[0] == "get") { if (cmd.size() == 3) { try { string r = rcs.get_param(cmd[1], cmd[2]); reply(socket, r); } catch (const ParameterError &e) { reply(socket, e.what()); } } else { reply(socket, "Incorrect parameters for command 'get'"); } } else if (cmd[0] == "set") { if (cmd.size() >= 4) { try { stringstream new_param_value; for (size_t i = 3; i < cmd.size(); i++) { new_param_value << cmd[i]; if (i+1 < cmd.size()) { new_param_value << " "; } } rcs.set_param(cmd[1], cmd[2], new_param_value.str()); reply(socket, "ok"); } catch (const ParameterError &e) { reply(socket, e.what()); } catch (const exception &e) { reply(socket, "Error: Invalid parameter value. "); } } else { reply(socket, "Incorrect parameters for command 'set'"); } } else if (cmd[0] == "quit") { reply(socket, "Goodbye"); } else { reply(socket, "Message not understood"); } } void RemoteControllerTelnet::reply(Socket::TCPSocket& socket, string message) { stringstream ss; ss << message << "\r\n"; socket.sendall(message.data(), message.size()); } #if defined(HAVE_ZEROMQ) RemoteControllerZmq::~RemoteControllerZmq() { m_active = false; m_fault = false; if (m_restarter_thread.joinable()) { m_restarter_thread.join(); } if (m_child_thread.joinable()) { m_child_thread.join(); } } void RemoteControllerZmq::restart() { if (m_restarter_thread.joinable()) { m_restarter_thread.join(); } m_restarter_thread = std::thread(&RemoteControllerZmq::restart_thread, this); } // This runs in a separate thread, because // it would take too long to be done in the main loop // thread. void RemoteControllerZmq::restart_thread() { m_active = false; if (m_child_thread.joinable()) { m_child_thread.join(); } m_child_thread = std::thread(&RemoteControllerZmq::process, this); } void RemoteControllerZmq::recv_all(zmq::socket_t& pSocket, std::vector<std::string> &message) { bool more = true; do { zmq::message_t msg; pSocket.recv(msg); std::string incoming((char*)msg.data(), msg.size()); message.push_back(incoming); more = msg.more(); } while (more); } void RemoteControllerZmq::send_ok_reply(zmq::socket_t &pSocket) { zmq::message_t msg(2); char repCode[2] = {'o', 'k'}; memcpy ((void*) msg.data(), repCode, 2); pSocket.send(msg, zmq::send_flags::none); } void RemoteControllerZmq::send_fail_reply(zmq::socket_t &pSocket, const std::string &error) { zmq::message_t msg1(4); char repCode[4] = {'f', 'a', 'i', 'l'}; memcpy ((void*) msg1.data(), repCode, 4); pSocket.send(msg1, zmq::send_flags::sndmore); zmq::message_t msg2(error.length()); memcpy ((void*) msg2.data(), error.c_str(), error.length()); pSocket.send(msg2, zmq::send_flags::none); } void RemoteControllerZmq::process() { m_fault = false; // create zmq reply socket for receiving ctrl parameters try { zmq::socket_t repSocket(m_zmqContext, ZMQ_REP); // connect the socket int hwm = 100; int linger = 0; repSocket.setsockopt(ZMQ_RCVHWM, &hwm, sizeof(hwm)); repSocket.setsockopt(ZMQ_SNDHWM, &hwm, sizeof(hwm)); repSocket.setsockopt(ZMQ_LINGER, &linger, sizeof(linger)); repSocket.bind(m_endpoint.c_str()); // create pollitem that polls the ZMQ sockets zmq::pollitem_t pollItems[] = { {repSocket, 0, ZMQ_POLLIN, 0} }; while (m_active) { zmq::poll(pollItems, 1, 100); std::vector<std::string> msg; if (pollItems[0].revents & ZMQ_POLLIN) { recv_all(repSocket, msg); std::string command((char*)msg[0].data(), msg[0].size()); if (msg.size() == 1 && command == "ping") { send_ok_reply(repSocket); } else if (msg.size() == 1 && command == "list") { size_t cohort_size = rcs.controllables.size(); for (auto &controllable : rcs.controllables) { std::stringstream ss; ss << "{ \"name\": \"" << controllable->get_rc_name() << "\"," << " \"params\": { "; list< vector<string> > params = controllable->get_parameter_descriptions(); size_t i = 0; for (auto &param : params) { if (i > 0) { ss << ", "; } ss << "\"" << param[0] << "\": " << "\"" << param[1] << "\""; i++; } ss << " } }"; std::string msg_s = ss.str(); zmq::message_t zmsg(ss.str().size()); memcpy ((void*) zmsg.data(), msg_s.data(), msg_s.size()); repSocket.send(zmsg, (--cohort_size > 0) ? zmq::send_flags::sndmore : zmq::send_flags::none); } } else if (msg.size() == 2 && command == "show") { std::string module((char*) msg[1].data(), msg[1].size()); try { list< vector<string> > r = rcs.get_param_list_values(module); size_t r_size = r.size(); for (auto &param_val : r) { std::stringstream ss; ss << param_val[0] << ": " << param_val[1] << endl; zmq::message_t zmsg(ss.str().size()); memcpy(zmsg.data(), ss.str().data(), ss.str().size()); repSocket.send(zmsg, (--r_size > 0) ? zmq::send_flags::sndmore : zmq::send_flags::none); } } catch (const ParameterError &err) { send_fail_reply(repSocket, err.what()); } } else if (msg.size() == 3 && command == "get") { std::string module((char*) msg[1].data(), msg[1].size()); std::string parameter((char*) msg[2].data(), msg[2].size()); try { std::string value = rcs.get_param(module, parameter); zmq::message_t zmsg(value.size()); memcpy ((void*) zmsg.data(), value.data(), value.size()); repSocket.send(zmsg, zmq::send_flags::none); } catch (const ParameterError &err) { send_fail_reply(repSocket, err.what()); } } else if (msg.size() == 4 && command == "set") { std::string module((char*) msg[1].data(), msg[1].size()); std::string parameter((char*) msg[2].data(), msg[2].size()); std::string value((char*) msg[3].data(), msg[3].size()); try { rcs.set_param(module, parameter, value); send_ok_reply(repSocket); } catch (const ParameterError &err) { send_fail_reply(repSocket, err.what()); } } else { send_fail_reply(repSocket, "Unsupported command. commands: list, show, get, set"); } } } repSocket.close(); } catch (const zmq::error_t &e) { etiLog.level(error) << "ZMQ RC error: " << std::string(e.what()); } catch (const std::exception& e) { etiLog.level(error) << "ZMQ RC caught exception: " << e.what(); m_fault = true; } } #endif
31.621107
117
0.515621
[ "vector" ]
9caca0f8f3d061701818f4396d637efa22c22371
3,235
cpp
C++
csapex_vision/src/roi/scale_rois.cpp
AdrianZw/csapex_core_plugins
1b23c90af7e552c3fc37c7dda589d751d2aae97f
[ "BSD-3-Clause" ]
2
2016-09-02T15:33:22.000Z
2019-05-06T22:09:33.000Z
csapex_vision/src/roi/scale_rois.cpp
AdrianZw/csapex_core_plugins
1b23c90af7e552c3fc37c7dda589d751d2aae97f
[ "BSD-3-Clause" ]
1
2021-02-14T19:53:30.000Z
2021-02-14T19:53:30.000Z
csapex_vision/src/roi/scale_rois.cpp
AdrianZw/csapex_core_plugins
1b23c90af7e552c3fc37c7dda589d751d2aae97f
[ "BSD-3-Clause" ]
6
2016-10-12T00:55:23.000Z
2021-02-10T17:49:25.000Z
/// PROJECT #include <csapex/model/node.h> #include <csapex/model/node_modifier.h> #include <csapex/msg/generic_vector_message.hpp> #include <csapex/msg/io.h> #include <csapex/param/parameter_factory.h> #include <csapex/utility/register_apex_plugin.h> #include <csapex_opencv/cv_mat_message.h> #include <csapex_opencv/roi_message.h> /// SYSTEM #include <functional> namespace csapex { enum Modes { CENTERED, LINEAR }; using namespace csapex; using namespace connection_types; class ScaleROIs : public csapex::Node { public: ScaleROIs() : mode_(0) { } virtual void setup(csapex::NodeModifier& node_modifier) override { in_rois_ = node_modifier.addInput<GenericVectorMessage, RoiMessage>("ROIs"); in_img_ = node_modifier.addOptionalInput<CvMatMessage>("Cap to Image"); out_rois_ = node_modifier.addOutput<GenericVectorMessage, RoiMessage>("Scaled ROIs"); } void setupParameters(Parameterizable& parameters) override { std::map<std::string, int> modes = { { "centered", CENTERED }, { "linear", LINEAR } }; parameters.addParameter(csapex::param::factory::declareParameterSet("mode", modes, 0), mode_); parameters.addParameter(csapex::param::factory::declareRange("percent x", 1.0, 400.0, 100.0, 1.0), scales_[0]); parameters.addParameter(csapex::param::factory::declareRange("percent y", 1.0, 400.0, 100.0, 1.0), scales_[1]); } virtual void process() override { std::shared_ptr<std::vector<RoiMessage> const> in_rois = msg::getMessage<GenericVectorMessage, RoiMessage>(in_rois_); std::shared_ptr<std::vector<RoiMessage>> out_rois(new std::vector<RoiMessage>); out_rois->assign(in_rois->begin(), in_rois->end()); if (msg::hasMessage(in_img_)) { CvMatMessage::ConstPtr in_img = msg::getMessage<CvMatMessage>(in_img_); const cv::Rect image_bounds(0, 0, in_img->value.cols, in_img->value.rows); for (RoiMessage& r : *out_rois) { cv::Rect rect = r.value.rect(); scale(rect); r.value.setRect(rect & image_bounds); } } else { for (RoiMessage& r : *out_rois) { cv::Rect rect = r.value.rect(); scale(rect); r.value.setRect(rect); } } msg::publish<GenericVectorMessage, RoiMessage>(out_rois_, out_rois); } private: void scale(cv::Rect& rect) { int height = rect.height * scales_[1] / 100.0; int width = rect.width * scales_[0] / 100.0; switch (mode_) { case CENTERED: rect.x += (rect.width - width) / 2; rect.y += (rect.height - height) / 2; break; case LINEAR: rect.x *= scales_[0] / 100.0; rect.y *= scales_[1] / 100.0; break; default: break; } rect.height = height; rect.width = width; } private: Input* in_img_; Input* in_rois_; Output* out_rois_; int mode_; cv::Vec2d scales_; }; } // namespace csapex CSAPEX_REGISTER_CLASS(csapex::ScaleROIs, csapex::Node)
28.628319
125
0.6034
[ "vector", "model" ]
66d3830cb87e27a52b5da644ecb8066c05a1082f
3,787
cpp
C++
src/libharp/math/harp_math.cpp
tskisner/HARP
e21435511c3dc95ce1318c852002a95ca59634b1
[ "BSD-3-Clause-LBNL" ]
null
null
null
src/libharp/math/harp_math.cpp
tskisner/HARP
e21435511c3dc95ce1318c852002a95ca59634b1
[ "BSD-3-Clause-LBNL" ]
null
null
null
src/libharp/math/harp_math.cpp
tskisner/HARP
e21435511c3dc95ce1318c852002a95ca59634b1
[ "BSD-3-Clause-LBNL" ]
null
null
null
/* High Performance Astrophysical Reconstruction and Processing (HARP) (c) 2014-2015, The Regents of the University of California, through Lawrence Berkeley National Laboratory. See top level LICENSE file for details. */ #include <harp_math_internal.hpp> #include <cstdio> extern "C" { #include <sys/time.h> } #ifdef _OPENMP # include <omp.h> #endif #include <cstdio> using namespace std; using namespace harp; double harp::wtime ( ) { struct timeval now; int ret = gettimeofday ( &now, NULL ); if ( ret != 0 ) { HARP_THROW( "gettimeofday() failed" ); } double nowtime = static_cast < double > ( now.tv_sec ) + 1.0e-6 * static_cast < double > ( now.tv_usec ); return nowtime; } void harp::omp_dist_1D ( int n, int & rank, int & nthreads, int & myn, int & offset ) { #ifdef _OPENMP rank = omp_get_thread_num(); nthreads = omp_get_num_threads(); #else rank = 0; nthreads = 1; #endif myn = (int) ( n / nthreads ); int leftover = n % nthreads; if ( rank < leftover ) { ++myn; offset = myn * rank; } else { offset = ( (myn + 1) * leftover ) + ( myn * (rank - leftover) ); } return; } harp::exception::exception ( char const * msg, char const * file, int line ) { int ret; ret = snprintf ( msg_, BIGSTRLEN, "Exception at line %d of file %s: %s", line, file, msg ); } harp::exception::~exception ( ) throw() { } const char* harp::exception::what() const throw() { return msg_; } #ifdef HAVE_BOOST_PYTHON_HPP #include <boost/python.hpp> #include <Python.h> namespace py = boost::python; // Parses the value of the active python exception // NOTE SHOULD NOT BE CALLED IF NO EXCEPTION std::string harp::parse_python_exception ( ) { PyObject *type_ptr = NULL, *value_ptr = NULL, *traceback_ptr = NULL; // Fetch the exception info from the Python C API PyErr_Fetch ( &type_ptr, &value_ptr, &traceback_ptr ); // Fallback error std::string ret("Unfetchable Python error"); // If the fetch got a type pointer, parse the type into the exception string if ( type_ptr != NULL ) { py::handle<> h_type(type_ptr); py::str type_pstr(h_type); // Extract the string from the boost::python object py::extract<std::string> e_type_pstr(type_pstr); // If a valid string extraction is available, use it // otherwise use fallback if ( e_type_pstr.check() ) { ret = e_type_pstr(); } else { ret = "Unknown exception type"; } } // Do the same for the exception value (the stringification of the exception) if ( value_ptr != NULL ) { py::handle<> h_val(value_ptr); py::str a(h_val); py::extract<std::string> returned(a); if ( returned.check() ) { ret += ": " + returned(); } else { ret += std::string(": Unparseable Python error: "); } } // Parse lines from the traceback using the Python traceback module if ( traceback_ptr != NULL ) { py::handle<> h_tb(traceback_ptr); // Load the traceback module and the format_tb function py::object tb(py::import("traceback")); py::object fmt_tb(tb.attr("format_tb")); // Call format_tb to get a list of traceback strings py::object tb_list(fmt_tb(h_tb)); // Join the traceback strings into a single string py::object tb_str(py::str("\n").join(tb_list)); // Extract the string, check the extraction, and fallback in necessary py::extract<std::string> returned(tb_str); if ( returned.check() ) { ret += ": " + returned(); } else { ret += std::string(": Unparseable Python traceback"); } } return ret; } #else std::string harp::parse_python_exception ( ) { HARP_THROW( "HARP was built without python support" ); return string(); } #endif
22.541667
107
0.636388
[ "object" ]
66d7900690e69fe477d17addbe9421cdc07015c4
8,366
hpp
C++
include/VROSC/TransformDataModel.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
null
null
null
include/VROSC/TransformDataModel.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
null
null
null
include/VROSC/TransformDataModel.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
1
2022-03-30T21:07:35.000Z
2022-03-30T21:07:35.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" #include "beatsaber-hook/shared/utils/typedefs-array.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: UnityEngine namespace UnityEngine { // Forward declaring type: Vector3 struct Vector3; // Forward declaring type: Quaternion struct Quaternion; } // Completed forward declares // Type namespace: VROSC namespace VROSC { // Forward declaring type: TransformDataModel class TransformDataModel; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::VROSC::TransformDataModel); DEFINE_IL2CPP_ARG_TYPE(::VROSC::TransformDataModel*, "VROSC", "TransformDataModel"); // Type namespace: VROSC namespace VROSC { // Size: 0x2A #pragma pack(push, 1) // Autogenerated type: VROSC.TransformDataModel // [TokenAttribute] Offset: FFFFFFFF class TransformDataModel : public ::Il2CppObject { public: public: // public System.Single[] Position // Size: 0x8 // Offset: 0x10 ::ArrayW<float> Position; // Field size check static_assert(sizeof(::ArrayW<float>) == 0x8); // public System.Single[] Rotation // Size: 0x8 // Offset: 0x18 ::ArrayW<float> Rotation; // Field size check static_assert(sizeof(::ArrayW<float>) == 0x8); // public System.Single[] Scale // Size: 0x8 // Offset: 0x20 ::ArrayW<float> Scale; // Field size check static_assert(sizeof(::ArrayW<float>) == 0x8); // public System.Boolean IsOpen // Size: 0x1 // Offset: 0x28 bool IsOpen; // Field size check static_assert(sizeof(bool) == 0x1); // public System.Boolean IsPinned // Size: 0x1 // Offset: 0x29 bool IsPinned; // Field size check static_assert(sizeof(bool) == 0x1); public: // Get instance field reference: public System.Single[] Position [[deprecated("Use field access instead!")]] ::ArrayW<float>& dyn_Position(); // Get instance field reference: public System.Single[] Rotation [[deprecated("Use field access instead!")]] ::ArrayW<float>& dyn_Rotation(); // Get instance field reference: public System.Single[] Scale [[deprecated("Use field access instead!")]] ::ArrayW<float>& dyn_Scale(); // Get instance field reference: public System.Boolean IsOpen [[deprecated("Use field access instead!")]] bool& dyn_IsOpen(); // Get instance field reference: public System.Boolean IsPinned [[deprecated("Use field access instead!")]] bool& dyn_IsPinned(); // public System.Void .ctor() // Offset: 0xA22D0C template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static TransformDataModel* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("::VROSC::TransformDataModel::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<TransformDataModel*, creationType>())); } // public System.Void Reset() // Offset: 0xA226E4 void Reset(); // public UnityEngine.Vector3 GetPosition() // Offset: 0xA2A494 ::UnityEngine::Vector3 GetPosition(); // public UnityEngine.Quaternion GetRotation() // Offset: 0xA2A584 ::UnityEngine::Quaternion GetRotation(); // public UnityEngine.Vector3 GetScale() // Offset: 0xA2A6AC ::UnityEngine::Vector3 GetScale(); // public System.Void SetPosition(UnityEngine.Vector3 position) // Offset: 0xA2A4DC void SetPosition(::UnityEngine::Vector3 position); // public System.Void SetRotation(UnityEngine.Quaternion rotation) // Offset: 0xA2A5F4 void SetRotation(::UnityEngine::Quaternion rotation); // public System.Void SetScale(UnityEngine.Vector3 scale) // Offset: 0xA2A6F4 void SetScale(::UnityEngine::Vector3 scale); }; // VROSC.TransformDataModel #pragma pack(pop) static check_size<sizeof(TransformDataModel), 41 + sizeof(bool)> __VROSC_TransformDataModelSizeCheck; static_assert(sizeof(TransformDataModel) == 0x2A); } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: VROSC::TransformDataModel::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead! // Writing MetadataGetter for method: VROSC::TransformDataModel::Reset // Il2CppName: Reset template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::TransformDataModel::*)()>(&VROSC::TransformDataModel::Reset)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(VROSC::TransformDataModel*), "Reset", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: VROSC::TransformDataModel::GetPosition // Il2CppName: GetPosition template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::UnityEngine::Vector3 (VROSC::TransformDataModel::*)()>(&VROSC::TransformDataModel::GetPosition)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(VROSC::TransformDataModel*), "GetPosition", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: VROSC::TransformDataModel::GetRotation // Il2CppName: GetRotation template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::UnityEngine::Quaternion (VROSC::TransformDataModel::*)()>(&VROSC::TransformDataModel::GetRotation)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(VROSC::TransformDataModel*), "GetRotation", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: VROSC::TransformDataModel::GetScale // Il2CppName: GetScale template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::UnityEngine::Vector3 (VROSC::TransformDataModel::*)()>(&VROSC::TransformDataModel::GetScale)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(VROSC::TransformDataModel*), "GetScale", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: VROSC::TransformDataModel::SetPosition // Il2CppName: SetPosition template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::TransformDataModel::*)(::UnityEngine::Vector3)>(&VROSC::TransformDataModel::SetPosition)> { static const MethodInfo* get() { static auto* position = &::il2cpp_utils::GetClassFromName("UnityEngine", "Vector3")->byval_arg; return ::il2cpp_utils::FindMethod(classof(VROSC::TransformDataModel*), "SetPosition", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{position}); } }; // Writing MetadataGetter for method: VROSC::TransformDataModel::SetRotation // Il2CppName: SetRotation template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::TransformDataModel::*)(::UnityEngine::Quaternion)>(&VROSC::TransformDataModel::SetRotation)> { static const MethodInfo* get() { static auto* rotation = &::il2cpp_utils::GetClassFromName("UnityEngine", "Quaternion")->byval_arg; return ::il2cpp_utils::FindMethod(classof(VROSC::TransformDataModel*), "SetRotation", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{rotation}); } }; // Writing MetadataGetter for method: VROSC::TransformDataModel::SetScale // Il2CppName: SetScale template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::TransformDataModel::*)(::UnityEngine::Vector3)>(&VROSC::TransformDataModel::SetScale)> { static const MethodInfo* get() { static auto* scale = &::il2cpp_utils::GetClassFromName("UnityEngine", "Vector3")->byval_arg; return ::il2cpp_utils::FindMethod(classof(VROSC::TransformDataModel*), "SetScale", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{scale}); } };
47
176
0.723285
[ "vector" ]
66e055043033fbc36a2d74ab71715026e007e1a8
15,762
cc
C++
source/blender/io/alembic/intern/abc_customdata.cc
gunslingster/CSC581-assignement1
39012146e142bf400c7140d90ecfd27c45b589ca
[ "Naumen", "Condor-1.1", "MS-PL" ]
365
2015-02-10T15:10:55.000Z
2022-03-03T15:50:51.000Z
source/blender/io/alembic/intern/abc_customdata.cc
mmtt1998819/blender
c9c3bf983321990a6960c422e002a372c35a6f76
[ "Naumen", "Condor-1.1", "MS-PL" ]
45
2015-01-09T15:34:20.000Z
2021-10-05T14:44:23.000Z
source/blender/io/alembic/intern/abc_customdata.cc
mmtt1998819/blender
c9c3bf983321990a6960c422e002a372c35a6f76
[ "Naumen", "Condor-1.1", "MS-PL" ]
172
2015-01-25T15:16:53.000Z
2022-01-31T08:25:36.000Z
/* * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * The Original Code is Copyright (C) 2016 Kévin Dietrich. * All rights reserved. */ /** \file * \ingroup balembic */ #include "abc_customdata.h" #include <Alembic/AbcGeom/All.h> #include <algorithm> #include <unordered_map> #include "DNA_customdata_types.h" #include "DNA_meshdata_types.h" #include "BLI_math_base.h" #include "BLI_utildefines.h" #include "BKE_customdata.h" /* NOTE: for now only UVs and Vertex Colors are supported for streaming. * Although Alembic only allows for a single UV layer per {I|O}Schema, and does * not have a vertex color concept, there is a convention between DCCs to write * such data in a way that lets other DCC know what they are for. See comments * in the write code for the conventions. */ using Alembic::AbcGeom::kFacevaryingScope; using Alembic::AbcGeom::kVertexScope; using Alembic::Abc::C4fArraySample; using Alembic::Abc::UInt32ArraySample; using Alembic::Abc::V2fArraySample; using Alembic::AbcGeom::OC4fGeomParam; using Alembic::AbcGeom::OV2fGeomParam; namespace blender::io::alembic { static void get_uvs(const CDStreamConfig &config, std::vector<Imath::V2f> &uvs, std::vector<uint32_t> &uvidx, void *cd_data) { MLoopUV *mloopuv_array = static_cast<MLoopUV *>(cd_data); if (!mloopuv_array) { return; } const int num_poly = config.totpoly; MPoly *polygons = config.mpoly; MLoop *mloop = config.mloop; if (!config.pack_uvs) { int cnt = 0; uvidx.resize(config.totloop); uvs.resize(config.totloop); /* Iterate in reverse order to match exported polygons. */ for (int i = 0; i < num_poly; i++) { MPoly &current_poly = polygons[i]; MLoopUV *loopuv = mloopuv_array + current_poly.loopstart + current_poly.totloop; for (int j = 0; j < current_poly.totloop; j++, cnt++) { loopuv--; uvidx[cnt] = cnt; uvs[cnt][0] = loopuv->uv[0]; uvs[cnt][1] = loopuv->uv[1]; } } } else { /* Mapping for indexed UVs, deduplicating UV coordinates at vertices. */ std::vector<std::vector<uint32_t>> idx_map(config.totvert); int idx_count = 0; for (int i = 0; i < num_poly; i++) { MPoly &current_poly = polygons[i]; MLoop *looppoly = mloop + current_poly.loopstart + current_poly.totloop; MLoopUV *loopuv = mloopuv_array + current_poly.loopstart + current_poly.totloop; for (int j = 0; j < current_poly.totloop; j++) { looppoly--; loopuv--; Imath::V2f uv(loopuv->uv[0], loopuv->uv[1]); bool found_same = false; /* Find UV already in uvs array. */ for (uint32_t uv_idx : idx_map[looppoly->v]) { if (uvs[uv_idx] == uv) { found_same = true; uvidx.push_back(uv_idx); break; } } /* UV doesn't exists for this vertex, add it. */ if (!found_same) { uint32_t uv_idx = idx_count++; idx_map[looppoly->v].push_back(uv_idx); uvidx.push_back(uv_idx); uvs.push_back(uv); } } } } } const char *get_uv_sample(UVSample &sample, const CDStreamConfig &config, CustomData *data) { const int active_uvlayer = CustomData_get_active_layer(data, CD_MLOOPUV); if (active_uvlayer < 0) { return ""; } void *cd_data = CustomData_get_layer_n(data, CD_MLOOPUV, active_uvlayer); get_uvs(config, sample.uvs, sample.indices, cd_data); return CustomData_get_layer_name(data, CD_MLOOPUV, active_uvlayer); } /* Convention to write UVs: * - V2fGeomParam on the arbGeomParam * - set scope as face varying * - (optional due to its behavior) tag as UV using Alembic::AbcGeom::SetIsUV */ static void write_uv(const OCompoundProperty &prop, CDStreamConfig &config, void *data, const char *name) { std::vector<uint32_t> indices; std::vector<Imath::V2f> uvs; get_uvs(config, uvs, indices, data); if (indices.empty() || uvs.empty()) { return; } std::string uv_map_name(name); OV2fGeomParam param = config.abc_uv_maps[uv_map_name]; if (!param.valid()) { param = OV2fGeomParam(prop, name, true, kFacevaryingScope, 1); } OV2fGeomParam::Sample sample(V2fArraySample(&uvs.front(), uvs.size()), UInt32ArraySample(&indices.front(), indices.size()), kFacevaryingScope); param.set(sample); config.abc_uv_maps[uv_map_name] = param; } /* Convention to write Vertex Colors: * - C3fGeomParam/C4fGeomParam on the arbGeomParam * - set scope as vertex varying */ static void write_mcol(const OCompoundProperty &prop, const CDStreamConfig &config, void *data, const char *name) { const float cscale = 1.0f / 255.0f; MPoly *polys = config.mpoly; MLoop *mloops = config.mloop; MCol *cfaces = static_cast<MCol *>(data); std::vector<Imath::C4f> buffer; std::vector<uint32_t> indices; buffer.reserve(config.totvert); indices.reserve(config.totvert); Imath::C4f col; for (int i = 0; i < config.totpoly; i++) { MPoly *p = &polys[i]; MCol *cface = &cfaces[p->loopstart + p->totloop]; MLoop *mloop = &mloops[p->loopstart + p->totloop]; for (int j = 0; j < p->totloop; j++) { cface--; mloop--; col[0] = cface->a * cscale; col[1] = cface->r * cscale; col[2] = cface->g * cscale; col[3] = cface->b * cscale; buffer.push_back(col); indices.push_back(buffer.size() - 1); } } OC4fGeomParam param(prop, name, true, kFacevaryingScope, 1); OC4fGeomParam::Sample sample(C4fArraySample(&buffer.front(), buffer.size()), UInt32ArraySample(&indices.front(), indices.size()), kVertexScope); param.set(sample); } void write_custom_data(const OCompoundProperty &prop, CDStreamConfig &config, CustomData *data, int data_type) { CustomDataType cd_data_type = static_cast<CustomDataType>(data_type); if (!CustomData_has_layer(data, cd_data_type)) { return; } const int active_layer = CustomData_get_active_layer(data, cd_data_type); const int tot_layers = CustomData_number_of_layers(data, cd_data_type); for (int i = 0; i < tot_layers; i++) { void *cd_data = CustomData_get_layer_n(data, cd_data_type, i); const char *name = CustomData_get_layer_name(data, cd_data_type, i); if (cd_data_type == CD_MLOOPUV) { /* Already exported. */ if (i == active_layer) { continue; } write_uv(prop, config, cd_data, name); } else if (cd_data_type == CD_MLOOPCOL) { write_mcol(prop, config, cd_data, name); } } } /* ************************************************************************** */ using Alembic::Abc::C3fArraySamplePtr; using Alembic::Abc::C4fArraySamplePtr; using Alembic::Abc::PropertyHeader; using Alembic::AbcGeom::IC3fGeomParam; using Alembic::AbcGeom::IC4fGeomParam; using Alembic::AbcGeom::IV2fGeomParam; static void read_uvs(const CDStreamConfig &config, void *data, const Alembic::AbcGeom::V2fArraySamplePtr &uvs, const Alembic::AbcGeom::UInt32ArraySamplePtr &indices) { MPoly *mpolys = config.mpoly; MLoopUV *mloopuvs = static_cast<MLoopUV *>(data); unsigned int uv_index, loop_index, rev_loop_index; for (int i = 0; i < config.totpoly; i++) { MPoly &poly = mpolys[i]; unsigned int rev_loop_offset = poly.loopstart + poly.totloop - 1; for (int f = 0; f < poly.totloop; f++) { loop_index = poly.loopstart + f; rev_loop_index = rev_loop_offset - f; uv_index = (*indices)[loop_index]; const Imath::V2f &uv = (*uvs)[uv_index]; MLoopUV &loopuv = mloopuvs[rev_loop_index]; loopuv.uv[0] = uv[0]; loopuv.uv[1] = uv[1]; } } } static size_t mcols_out_of_bounds_check(const size_t color_index, const size_t array_size, const std::string &iobject_full_name, const PropertyHeader &prop_header, bool &r_is_out_of_bounds, bool &r_bounds_warning_given) { if (color_index < array_size) { return color_index; } if (!r_bounds_warning_given) { std::cerr << "Alembic: color index out of bounds " "reading face colors for object " << iobject_full_name << ", property " << prop_header.getName() << std::endl; r_bounds_warning_given = true; } r_is_out_of_bounds = true; return 0; } static void read_custom_data_mcols(const std::string &iobject_full_name, const ICompoundProperty &arbGeomParams, const PropertyHeader &prop_header, const CDStreamConfig &config, const Alembic::Abc::ISampleSelector &iss) { C3fArraySamplePtr c3f_ptr = C3fArraySamplePtr(); C4fArraySamplePtr c4f_ptr = C4fArraySamplePtr(); Alembic::Abc::UInt32ArraySamplePtr indices; bool use_c3f_ptr; bool is_facevarying; /* Find the correct interpretation of the data */ if (IC3fGeomParam::matches(prop_header)) { IC3fGeomParam color_param(arbGeomParams, prop_header.getName()); IC3fGeomParam::Sample sample; BLI_assert(STREQ("rgb", color_param.getInterpretation())); color_param.getIndexed(sample, iss); is_facevarying = sample.getScope() == kFacevaryingScope && config.totloop == sample.getIndices()->size(); c3f_ptr = sample.getVals(); indices = sample.getIndices(); use_c3f_ptr = true; } else if (IC4fGeomParam::matches(prop_header)) { IC4fGeomParam color_param(arbGeomParams, prop_header.getName()); IC4fGeomParam::Sample sample; BLI_assert(STREQ("rgba", color_param.getInterpretation())); color_param.getIndexed(sample, iss); is_facevarying = sample.getScope() == kFacevaryingScope && config.totloop == sample.getIndices()->size(); c4f_ptr = sample.getVals(); indices = sample.getIndices(); use_c3f_ptr = false; } else { /* this won't happen due to the checks in read_custom_data() */ return; } BLI_assert(c3f_ptr || c4f_ptr); /* Read the vertex colors */ void *cd_data = config.add_customdata_cb( config.mesh, prop_header.getName().c_str(), CD_MLOOPCOL); MCol *cfaces = static_cast<MCol *>(cd_data); MPoly *mpolys = config.mpoly; MLoop *mloops = config.mloop; size_t face_index = 0; size_t color_index; bool bounds_warning_given = false; /* The colors can go through two layers of indexing. Often the 'indices' * array doesn't do anything (i.e. indices[n] = n), but when it does, it's * important. Blender 2.79 writes indices incorrectly (see T53745), which * is why we have to check for indices->size() > 0 */ bool use_dual_indexing = is_facevarying && indices->size() > 0; for (int i = 0; i < config.totpoly; i++) { MPoly *poly = &mpolys[i]; MCol *cface = &cfaces[poly->loopstart + poly->totloop]; MLoop *mloop = &mloops[poly->loopstart + poly->totloop]; for (int j = 0; j < poly->totloop; j++, face_index++) { cface--; mloop--; color_index = is_facevarying ? face_index : mloop->v; if (use_dual_indexing) { color_index = (*indices)[color_index]; } if (use_c3f_ptr) { bool is_mcols_out_of_bounds = false; color_index = mcols_out_of_bounds_check(color_index, c3f_ptr->size(), iobject_full_name, prop_header, is_mcols_out_of_bounds, bounds_warning_given); if (is_mcols_out_of_bounds) { continue; } const Imath::C3f &color = (*c3f_ptr)[color_index]; cface->a = unit_float_to_uchar_clamp(color[0]); cface->r = unit_float_to_uchar_clamp(color[1]); cface->g = unit_float_to_uchar_clamp(color[2]); cface->b = 255; } else { bool is_mcols_out_of_bounds = false; color_index = mcols_out_of_bounds_check(color_index, c4f_ptr->size(), iobject_full_name, prop_header, is_mcols_out_of_bounds, bounds_warning_given); if (is_mcols_out_of_bounds) { continue; } const Imath::C4f &color = (*c4f_ptr)[color_index]; cface->a = unit_float_to_uchar_clamp(color[0]); cface->r = unit_float_to_uchar_clamp(color[1]); cface->g = unit_float_to_uchar_clamp(color[2]); cface->b = unit_float_to_uchar_clamp(color[3]); } } } } static void read_custom_data_uvs(const ICompoundProperty &prop, const PropertyHeader &prop_header, const CDStreamConfig &config, const Alembic::Abc::ISampleSelector &iss) { IV2fGeomParam uv_param(prop, prop_header.getName()); if (!uv_param.isIndexed()) { return; } IV2fGeomParam::Sample sample; uv_param.getIndexed(sample, iss); if (uv_param.getScope() != kFacevaryingScope) { return; } void *cd_data = config.add_customdata_cb(config.mesh, prop_header.getName().c_str(), CD_MLOOPUV); read_uvs(config, cd_data, sample.getVals(), sample.getIndices()); } void read_custom_data(const std::string &iobject_full_name, const ICompoundProperty &prop, const CDStreamConfig &config, const Alembic::Abc::ISampleSelector &iss) { if (!prop.valid()) { return; } int num_uvs = 0; int num_colors = 0; const size_t num_props = prop.getNumProperties(); for (size_t i = 0; i < num_props; i++) { const Alembic::Abc::PropertyHeader &prop_header = prop.getPropertyHeader(i); /* Read UVs according to convention. */ if (IV2fGeomParam::matches(prop_header) && Alembic::AbcGeom::isUV(prop_header)) { if (++num_uvs > MAX_MTFACE) { continue; } read_custom_data_uvs(prop, prop_header, config, iss); continue; } /* Read vertex colors according to convention. */ if (IC3fGeomParam::matches(prop_header) || IC4fGeomParam::matches(prop_header)) { if (++num_colors > MAX_MCOL) { continue; } read_custom_data_mcols(iobject_full_name, prop, prop_header, config, iss); continue; } } } } // namespace blender::io::alembic
32.101833
99
0.611724
[ "mesh", "object", "vector" ]
66e0b67aa663a80d9d8310a78b1d08b765bd0ac0
4,927
cc
C++
server/modules/filter/cache/cachept.cc
tut-blog/MaxScale
cabd6dba0665cb8025c694acf98cffaa68d10de0
[ "MIT" ]
null
null
null
server/modules/filter/cache/cachept.cc
tut-blog/MaxScale
cabd6dba0665cb8025c694acf98cffaa68d10de0
[ "MIT" ]
1
2019-07-02T09:59:27.000Z
2019-07-02T09:59:49.000Z
server/modules/filter/cache/cachept.cc
tut-blog/MaxScale
cabd6dba0665cb8025c694acf98cffaa68d10de0
[ "MIT" ]
null
null
null
/* * Copyright (c) 2016 MariaDB Corporation Ab * * Use of this software is governed by the Business Source License included * in the LICENSE.TXT file and at www.mariadb.com/bsl11. * * Change Date: 2022-01-01 * * On the date above, in accordance with the Business Source License, use * of this software will be governed by version 2 or later of the General * Public License. */ #define MXS_MODULE_NAME "cache" #include "cachept.hh" #include <maxbase/atomic.h> #include <maxscale/config.h> #include "cachest.hh" #include "storagefactory.hh" using std::shared_ptr; using std::string; namespace { int u_current_thread_id = 0; thread_local int u_thread_id = -1; /** * Get the thread index of the current thread. * * @return The index of the current thread. */ inline int thread_index() { // A value of -1 indicates that the value has not been initialized, if (u_thread_id == -1) { u_thread_id = atomic_add(&u_current_thread_id, 1); } return u_thread_id; } } CachePT::CachePT(const std::string& name, const CACHE_CONFIG* pConfig, const std::vector<SCacheRules>& rules, SStorageFactory sFactory, const Caches& caches) : Cache(name, pConfig, rules, sFactory) , m_caches(caches) { MXS_NOTICE("Created cache per thread."); } CachePT::~CachePT() { } // static CachePT* CachePT::Create(const std::string& name, const CACHE_CONFIG* pConfig) { mxb_assert(pConfig); CachePT* pCache = NULL; std::vector<SCacheRules> rules; StorageFactory* pFactory = NULL; if (Cache::Create(*pConfig, &rules, &pFactory)) { shared_ptr<StorageFactory> sFactory(pFactory); pCache = Create(name, pConfig, rules, sFactory); } return pCache; } bool CachePT::must_refresh(const CACHE_KEY& key, const CacheFilterSession* pSession) { return thread_cache().must_refresh(key, pSession); } void CachePT::refreshed(const CACHE_KEY& key, const CacheFilterSession* pSession) { thread_cache().refreshed(key, pSession); } json_t* CachePT::get_info(uint32_t what) const { json_t* pInfo = Cache::do_get_info(what); if (pInfo) { if (what & (INFO_PENDING | INFO_STORAGE)) { what &= ~INFO_RULES; // The rules are the same, we don't want them duplicated. for (size_t i = 0; i < m_caches.size(); ++i) { char key[20]; // Surely enough. sprintf(key, "thread-%u", (unsigned int)i + 1); SCache sCache = m_caches[i]; json_t* pThreadInfo = sCache->get_info(what); if (pThreadInfo) { json_object_set(pInfo, key, pThreadInfo); json_decref(pThreadInfo); } } } } return pInfo; } cache_result_t CachePT::get_key(const char* zDefault_db, const GWBUF* pQuery, CACHE_KEY* pKey) const { return thread_cache().get_key(zDefault_db, pQuery, pKey); } cache_result_t CachePT::get_value(const CACHE_KEY& key, uint32_t flags, uint32_t soft_ttl, uint32_t hard_ttl, GWBUF** ppValue) const { return thread_cache().get_value(key, flags, soft_ttl, hard_ttl, ppValue); } cache_result_t CachePT::put_value(const CACHE_KEY& key, const GWBUF* pValue) { return thread_cache().put_value(key, pValue); } cache_result_t CachePT::del_value(const CACHE_KEY& key) { return thread_cache().del_value(key); } // static CachePT* CachePT::Create(const std::string& name, const CACHE_CONFIG* pConfig, const std::vector<SCacheRules>& rules, SStorageFactory sFactory) { CachePT* pCache = NULL; try { int n_threads = config_threadcount(); Caches caches; bool error = false; int i = 0; while (!error && (i < n_threads)) { char suffix[12]; // Enough for 99999 threads sprintf(suffix, "%d", i); string namest(name + "-" + suffix); CacheST* pCacheST = 0; MXS_EXCEPTION_GUARD(pCacheST = CacheST::Create(namest, rules, sFactory, pConfig)); if (pCacheST) { shared_ptr<Cache> sCache(pCacheST); caches.push_back(sCache); } else { error = true; } ++i; } if (!error) { pCache = new CachePT(name, pConfig, rules, sFactory, caches); } } catch (const std::exception&) { } return pCache; } Cache& CachePT::thread_cache() { int i = thread_index(); mxb_assert(i < (int)m_caches.size()); return *m_caches[i].get(); }
23.574163
100
0.58291
[ "vector" ]
66e0e2c00f266e0c7a17d80a9f5060f1e2337be4
89,482
cc
C++
CCA/Components/Schedulers/SchedulerCommon.cc
QuocAnh90/Uintah_Aalto
802c236c331b7eb705d408c352969037e4c5b153
[ "MIT" ]
3
2020-06-10T08:21:31.000Z
2020-06-23T18:33:16.000Z
CCA/Components/Schedulers/SchedulerCommon.cc
QuocAnh90/Uintah_Aalto
802c236c331b7eb705d408c352969037e4c5b153
[ "MIT" ]
null
null
null
CCA/Components/Schedulers/SchedulerCommon.cc
QuocAnh90/Uintah_Aalto
802c236c331b7eb705d408c352969037e4c5b153
[ "MIT" ]
2
2019-12-30T05:48:30.000Z
2020-02-12T16:24:16.000Z
/* * The MIT License * * Copyright (c) 1997-2019 The University of Utah * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include <CCA/Components/Schedulers/SchedulerCommon.h> #include <CCA/Components/Schedulers/DetailedTasks.h> #include <CCA/Components/Schedulers/OnDemandDataWarehouse.h> #include <CCA/Components/Schedulers/OnDemandDataWarehouseP.h> #include <CCA/Components/Schedulers/TaskGraph.h> #include <CCA/Ports/ApplicationInterface.h> #include <CCA/Ports/DataWarehouse.h> #include <CCA/Ports/LoadBalancer.h> #include <CCA/Ports/Output.h> #include <Core/Exceptions/ErrnoException.h> #include <Core/Exceptions/InternalError.h> #include <Core/Exceptions/ProblemSetupException.h> #include <Core/Grid/Patch.h> #include <Core/Grid/Task.h> #include <Core/Grid/Variables/LocallyComputedPatchVarMap.h> #include <Core/Grid/Variables/PerPatch.h> #include <Core/Grid/Variables/CellIterator.h> #include <Core/Grid/Variables/CCVariable.h> #include <Core/Grid/Variables/NCVariable.h> #include <Core/Grid/Variables/SFCXVariable.h> #include <Core/Grid/Variables/SFCYVariable.h> #include <Core/Grid/Variables/SFCZVariable.h> #include <Core/Malloc/Allocator.h> #include <Core/Parallel/ProcessorGroup.h> #include <Core/ProblemSpec/ProblemSpec.h> #include <Core/OS/ProcessInfo.h> #include <Core/Util/DOUT.hpp> #include <Core/Util/FancyAssert.h> #include <Core/Util/Timers/Timers.hpp> #include <sci_defs/visit_defs.h> #include <cerrno> #include <cstdlib> #include <fstream> #include <iostream> #include <iomanip> #include <sstream> #include <map> #include <memory> #include <string> #include <vector> #include <unistd.h> using namespace Uintah; namespace { Dout g_schedulercommon_dbg( "SchedulerCommon_DBG", "SchedulerCommon", "general debug information" , false ); Dout g_task_graph_compile( "TaskGraphCompile" , "SchedulerCommon", "task graph compilation info", false ); } // for calculating memory use when sci-malloc is disabled. char* SchedulerCommon::start_addr = nullptr; //______________________________________________________________________ // SchedulerCommon::SchedulerCommon( const ProcessorGroup * myworld ) : UintahParallelComponent( myworld ) { for (int i = 0; i < Task::TotalDWs; i++) { m_dwmap[i] = Task::InvalidDW; } // Default mapping... m_dwmap[Task::OldDW] = 0; m_dwmap[Task::NewDW] = 1; m_locallyComputedPatchVarMap = scinew LocallyComputedPatchVarMap; } //______________________________________________________________________ // SchedulerCommon::~SchedulerCommon() { if (m_mem_logfile) { delete m_mem_logfile; } // list of vars used for AMR regridding for (unsigned i = 0u; i < m_label_matls.size(); i++) for (LabelMatlMap::iterator iter = m_label_matls[i].begin(); iter != m_label_matls[i].end(); iter++) if (iter->second->removeReference()) { delete iter->second; } for (unsigned i = 0u; i < m_task_graphs.size(); i++) { delete m_task_graphs[i]; } m_label_matls.clear(); if (m_locallyComputedPatchVarMap) { delete m_locallyComputedPatchVarMap; } // Task monitoring variables. if (m_monitoring) { if (m_dummy_matl && m_dummy_matl->removeReference()) { delete m_dummy_matl; } // Loop through the global (0) and local (1) tasks for (unsigned int i = 0u; i < 2; ++i) { for (const auto &it : m_monitoring_tasks[i]) { VarLabel::destroy(it.second); } m_monitoring_values[i].clear(); } } } void SchedulerCommon::setComponents( UintahParallelComponent *comp ) { SchedulerCommon *parent = dynamic_cast<SchedulerCommon*>( comp ); attachPort( "load balancer", parent->m_loadBalancer ); attachPort( "output", parent->m_output ); attachPort( "application", parent->m_application ); getComponents(); } void SchedulerCommon::getComponents() { m_loadBalancer = dynamic_cast<LoadBalancer*>( getPort("load balancer") ); if( !m_loadBalancer ) { throw InternalError("dynamic_cast of 'm_loadBalancer' failed!", __FILE__, __LINE__); } m_output = dynamic_cast<Output*>( getPort("output") ); if( !m_output ) { throw InternalError("dynamic_cast of 'm_output' failed!", __FILE__, __LINE__); } m_application = dynamic_cast<ApplicationInterface*>( getPort("application") ); if( !m_application ) { throw InternalError("dynamic_cast of 'm_application' failed!", __FILE__, __LINE__); } } //______________________________________________________________________ // void SchedulerCommon::releaseComponents() { releasePort( "load balancer" ); releasePort( "output" ); releasePort( "application" ); m_loadBalancer = nullptr; m_output = nullptr; m_application = nullptr; m_materialManager = nullptr; } //______________________________________________________________________ // void SchedulerCommon::checkMemoryUse( unsigned long & memUsed , unsigned long & highwater , unsigned long & maxMemUsed ) { highwater = 0; memUsed = 0; #if !defined(DISABLE_SCI_MALLOC) size_t nalloc, sizealloc, nfree, sizefree, nfillbin, nmmap, sizemmap, nmunmap, sizemunmap, highwater_alloc, highwater_mmap, bytes_overhead, bytes_free, bytes_fragmented, bytes_inuse, bytes_inhunks; GetGlobalStats( DefaultAllocator(), nalloc, sizealloc, nfree, sizefree, nfillbin, nmmap, sizemmap, nmunmap, sizemunmap, highwater_alloc, highwater_mmap, bytes_overhead, bytes_free, bytes_fragmented, bytes_inuse, bytes_inhunks ); memUsed = sizealloc - sizefree; highwater = highwater_mmap; #else if ( ProcessInfo::isSupported( ProcessInfo::MEM_SIZE ) ) { memUsed = ProcessInfo::getMemoryResident(); // printf("1) memuse is %ld (on proc %d)\n", memuse, Uintah::Parallel::getMPIRank() ); } else { memUsed = (char*)sbrk(0)-start_addr; // printf("2) memuse is %ld (on proc %d)\n", memuse, Uintah::Parallel::getMPIRank() ); } #endif if( memUsed > m_max_mem_used ) { m_max_mem_used = memUsed; } maxMemUsed = m_max_mem_used; } //______________________________________________________________________ // void SchedulerCommon::resetMaxMemValue() { m_max_mem_used = 0; } //______________________________________________________________________ // void SchedulerCommon::makeTaskGraphDoc( const DetailedTasks * /* dt*/ , int rank ) { // This only happens if "-emit_taskgraphs" is passed to sus if (!m_emit_task_graph) { return; } // ARS NOTE: Outputing and Checkpointing may be done out of snyc // now. I.e. turned on just before it happens rather than turned on // before the task graph execution. As such, one should also be // checking: // m_application->activeReductionVariable( "outputInterval" ); // However, if active the code below would be called regardless if // an output or checkpoint time step or not. That is probably not // desired. However, given this code is for debuging it probably // fine that it does not happen if doing an output of sync. if (!m_output->isOutputTimeStep()) { return; } // make sure to release this DOMDocument after finishing emitting the nodes m_graph_doc = ProblemSpec::createDocument("Uintah_TaskGraph"); ProblemSpecP meta = m_graph_doc->appendChild("Meta"); meta->appendElement("username", getenv("LOGNAME")); time_t t = time(nullptr); meta->appendElement("date", ctime(&t)); m_graph_nodes = m_graph_doc->appendChild("Nodes"); ProblemSpecP edgesElement = m_graph_doc->appendChild("Edges"); for (unsigned i = 0; i < m_task_graphs.size(); i++) { DetailedTasks* dts = m_task_graphs[i]->getDetailedTasks(); if (dts) { dts->emitEdges(edgesElement, rank); } } } //______________________________________________________________________ // bool SchedulerCommon::useInternalDeps() { // Keep track of internal dependencies only if it will emit the taskgraphs (by default). return m_emit_task_graph; } //______________________________________________________________________ // void SchedulerCommon::emitNode( const DetailedTask * dtask , double start , double duration , double execution_duration ) { // This only happens if "-emit_taskgraphs" is passed to sus // See makeTaskGraphDoc if (m_graph_nodes == nullptr) { return; } ProblemSpecP node = m_graph_nodes->appendChild( "node" ); //m_graph_nodes->appendChild( node ); node->appendElement("name", dtask->getName()); node->appendElement("start", start); node->appendElement("duration", duration); if (execution_duration > 0) { node->appendElement("execution_duration", execution_duration); } } //______________________________________________________________________ // void SchedulerCommon::finalizeNodes( int process /* = 0 */ ) { // This only happens if "-emit_taskgraphs" is passed to sus // See makeTaskGraphDoc if (m_graph_doc == nullptr) { return; } std::string timestep_dir(m_output->getLastTimeStepOutputLocation()); std::ostringstream fname; fname << "/taskgraph_" << std::setw(5) << std::setfill('0') << process << ".xml"; std::string file_name(timestep_dir + fname.str()); m_graph_doc->output(file_name.c_str()); // Releasing the document causes a hard crash. All calls // to releaseDocument are commented out. // m_graph_doc->releaseDocument(); m_graph_doc = nullptr; m_graph_nodes = nullptr; } //______________________________________________________________________ // void SchedulerCommon::problemSetup( const ProblemSpecP & prob_spec , const MaterialManagerP & materialManager ) { m_materialManager = materialManager; m_tracking_vars_print_location = PRINT_AFTER_EXEC; ProblemSpecP params = prob_spec->findBlock("Scheduler"); if (params) { params->getWithDefault("small_messages", m_use_small_messages, true); if (m_use_small_messages) { proc0cout << "Using small, individual MPI messages (no message combining)\n"; } else { proc0cout << "Using large, combined MPI messages\n"; } ProblemSpecP track = params->findBlock("VarTracker"); if (track) { track->require("start_time", m_tracking_start_time); track->require("end_time", m_tracking_end_time); track->getWithDefault("level", m_tracking_level, -1); track->getWithDefault("start_index", m_tracking_start_index, IntVector(-9, -9, -9)); track->getWithDefault("end_index", m_tracking_end_index, IntVector(-9, -9, -9)); track->getWithDefault("patchid", m_tracking_patch_id, -1); if (d_myworld->myRank() == 0) { std::cout << "\n"; std::cout << "-----------------------------------------------------------\n"; std::cout << "-- Initializing VarTracker...\n"; std::cout << "-- Running from time " << m_tracking_start_time << " to " << m_tracking_end_time << "\n"; std::cout << "-- for indices: " << m_tracking_start_index << " to " << m_tracking_end_index << "\n"; } ProblemSpecP location = track->findBlock("locations"); if (location) { m_tracking_vars_print_location = 0; std::map<std::string, std::string> attributes; location->getAttributes(attributes); if (attributes["before_comm"] == "true") { m_tracking_vars_print_location |= PRINT_BEFORE_COMM; proc0cout << "-- Printing variable information before communication.\n"; } if (attributes["before_exec"] == "true") { m_tracking_vars_print_location |= PRINT_BEFORE_EXEC; proc0cout << "-- Printing variable information before task execution.\n"; } if (attributes["after_exec"] == "true") { m_tracking_vars_print_location |= PRINT_AFTER_EXEC; proc0cout << "-- Printing variable information after task execution.\n"; } } else { // "locations" not specified proc0cout << "-- Defaulting to printing variable information after task execution.\n"; } for (ProblemSpecP var = track->findBlock("var"); var != nullptr; var = var->findNextBlock("var")) { std::map<std::string, std::string> attributes; var->getAttributes(attributes); std::string name = attributes["label"]; m_tracking_vars.push_back(name); std::string dw = attributes["dw"]; if (dw == "OldDW") { m_tracking_dws.push_back(Task::OldDW); } else if (dw == "NewDW") { m_tracking_dws.push_back(Task::NewDW); } else if (dw == "CoarseNewDW") { m_tracking_dws.push_back(Task::CoarseNewDW); } else if (dw == "CoarseOldDW") { m_tracking_dws.push_back(Task::CoarseOldDW); } else if (dw == "ParentOldDW") { m_tracking_dws.push_back(Task::ParentOldDW); } else if (dw == "ParentOldDW") { m_tracking_dws.push_back(Task::ParentNewDW); } else { // This error message most likely can go away once the .ups validation is put into place: printf("WARNING: Hit switch statement default... using NewDW... (This could possibly be" "an error in input file specification.)\n"); m_tracking_dws.push_back(Task::NewDW); } if (d_myworld->myRank() == 0) { std::cout << "-- Tracking variable '" << name << "' in DataWarehouse '" << dw << "'\n"; } } for (ProblemSpecP task = track->findBlock("task"); task != nullptr; task = task->findNextBlock("task")) { std::map<std::string, std::string> attributes; task->getAttributes(attributes); std::string name = attributes["name"]; m_tracking_tasks.push_back(name); if (d_myworld->myRank() == 0) { std::cout << "-- Tracking variables for specific task: " << name << "\n"; } } if (d_myworld->myRank() == 0) { std::cout << "-----------------------------------------------------------\n\n"; } } else { // Tracking not specified // This 'else' won't be necessary once the .ups files are validated... but for now. if (d_myworld->myRank() == 0) { std::cout << "<VarTracker> not specified in .ups file... no variable tracking will take place.\n"; } } // Task monitoring variables. ProblemSpecP taskMonitoring = params->findBlock("TaskMonitoring"); if (taskMonitoring) { // Record the task runtime attributes on a per cell basis rather // than a per patch basis. Default is per patch. taskMonitoring->getWithDefault("per_cell", m_monitoring_per_cell, false); // Maps for the global tasks to be monitored. for (ProblemSpecP attr = taskMonitoring->findBlock("attribute"); attr != nullptr; attr = attr->findNextBlock("attribute")) { std::string attribute = attr->getNodeValue(); // Set the variable name AllTasks/ plus the attribute name and // store in a map for easy lookup by the attribute name. // Note: this modifided name will be needed for saving. m_monitoring_tasks[0][attribute] = VarLabel::create( "AllTasks/" + attribute, PerPatch<double>::getTypeDescription() ); if (d_myworld->myRank() == 0) std::cout << "-- Monitoring attribute " << attribute << " " << "for all tasks. " << "VarLabel name = 'AllTasks/" << attribute << "'" << std::endl; } // Maps for the specific tasks to be monitored. for (ProblemSpecP task = taskMonitoring->findBlock("task"); task != nullptr; task = task->findNextBlock("task")) { // Get the task and attribute to be monitored. std::map<std::string, std::string> attributes; task->getAttributes(attributes); std::string taskName = attributes["name"]; std::string attribute = attributes["attribute"]; // Strip off the colons and replace with a forward slash so // the tasks are divided by component. std::string varName = taskName; std::size_t found = varName.find("::"); if( found != std::string::npos) varName.replace(found, 2 ,"/"); // Set the variable name to the task name plus the attribute // name and store in a map for easy lookup by the task and // attribute name. // Note: this modifided name will be needed for saving. m_monitoring_tasks[1][taskName + "::" + attribute] = VarLabel::create( varName + "/" + attribute, PerPatch<double>::getTypeDescription() ); if (d_myworld->myRank() == 0) std::cout << "-- Monitoring attribute " << attribute << " " << "for task: " << taskName << ". " << "VarLabel name = '" << varName << "/" << attribute << "'" << std::endl; } } m_monitoring = (m_monitoring_tasks[0].size() || m_monitoring_tasks[1].size() ); if(m_monitoring) { m_dummy_matl = scinew MaterialSubset(); m_dummy_matl->add(0); m_dummy_matl->addReference(); } } // If small_messages not specified in UPS Scheduler block, still report what's used if (m_use_small_messages) { proc0cout << "Using small, individual MPI messages (no message combining)\n"; } else { proc0cout << "Using large, combined MPI messages\n"; } m_no_scrub_vars.insert("refineFlag"); m_no_scrub_vars.insert("refinePatchFlag"); #ifdef HAVE_VISIT static bool initialized = false; // Running with VisIt so add in the variables that the user can // modify. if( m_application->getVisIt() && !initialized ) { // variable 1 - Must start with the component name and have NO // spaces in the var name ApplicationInterface::interactiveVar var; var.component = "LoadBalancer"; var.name = "UseSmallMessages"; var.type = Uintah::TypeDescription::bool_type; var.value = (void *) &m_use_small_messages; var.range[0] = 0; var.range[1] = 1; var.modifiable = true; var.recompile = false; var.modified = false; m_application->getUPSVars().push_back( var ); initialized = true; } #endif } //______________________________________________________________________ // handleError() // // The following routine is designed to only print out a given error // once per error type per variable. handleError is used by // printTrackedVars() with each type of error ('errorPosition') // condition specifically enumerated (by an integer running from 0 to 5). // // Returns true if the error message is displayed. // bool handleError( int errorPosition , const std::string & errorMessage , const std::string & variableName ) { static std::vector<std::map<std::string, bool> *> errorsReported(5); std::map<std::string, bool> * varToReportedMap = errorsReported[errorPosition]; // TODO: this new shouldn't happen - APH 08/06/16 if (varToReportedMap == nullptr) { varToReportedMap = new std::map<std::string, bool>; errorsReported[errorPosition] = varToReportedMap; } bool reported = (*varToReportedMap)[variableName]; if (!reported) { (*varToReportedMap)[variableName] = true; std::cout << errorMessage << "\n"; return true; } return false; } //______________________________________________________________________ // template< class T > void SchedulerCommon::printTrackedValues( GridVariable<T> * var , const IntVector & start , const IntVector & end ) { std::ostringstream message; for (int z = start.z(); z < end.z() + 1; z++) { // add 1 to high to include x+,y+,z+ extraCells for (int y = start.y(); y < end.y() + 1; y++) { message << d_myworld->myRank() << " "; for (int x = start.x(); x < end.x() + 1; x++) { IntVector c(x, y, z); message << " " << c << ": " << (*var)[c]; } message << std::endl; } message << std::endl; } DOUT(true, message.str()); } //______________________________________________________________________ // void SchedulerCommon::printTrackedVars( DetailedTask * dtask , int when ) { bool printedHeader = false; unsigned taskNum; for (taskNum = 0; taskNum < m_tracking_tasks.size(); taskNum++) { if (m_tracking_tasks[taskNum] == dtask->getTask()->getName()) break; } // Print for all tasks unless one is specified (but disclude DataArchiver tasks) if ((taskNum == m_tracking_tasks.size() && m_tracking_tasks.size() != 0) || ((std::string(dtask->getTask()->getName())).substr(0, 12) == "DataArchiver")) { return; } if( m_tracking_start_time > m_application->getSimTime() || m_tracking_end_time < m_application->getSimTime() ) { return; } for (int i = 0; i < static_cast<int>(m_tracking_vars.size()); i++) { bool printedVarName = false; // that DW may not have been mapped.... if (dtask->getTask()->mapDataWarehouse(m_tracking_dws[i]) < 0 || dtask->getTask()->mapDataWarehouse(m_tracking_dws[i]) >= (int)m_dws.size()) { std::ostringstream mesg; mesg << "WARNING: VarTracker: Not printing requested variable (" << m_tracking_vars[i] << ") DW is out of range.\n"; handleError(0, mesg.str(), m_tracking_vars[i]); continue; } OnDemandDataWarehouseP dw = m_dws[dtask->getTask()->mapDataWarehouse(m_tracking_dws[i])]; if (dw == nullptr) { // old on initialization timestep continue; } // Get the level here, as the grid can be different between the old and new DW const Grid* grid = dw->getGrid(); int levelnum; if (m_tracking_level == -1) { levelnum = grid->numLevels() - 1; } else { levelnum = m_tracking_level; if (levelnum >= grid->numLevels()) { continue; } } const LevelP level = grid->getLevel(levelnum); const VarLabel* label = VarLabel::find(m_tracking_vars[i]); std::cout.precision(16); if (!label) { std::ostringstream mesg; mesg << "WARNING: VarTracker: Not printing requested variable (" << m_tracking_vars[i] << ") because the label could not be found.\n"; handleError(1, mesg.str(), m_tracking_vars[i]); continue; } const PatchSubset* patches = dtask->getPatches(); // a once-per-proc task is liable to have multiple levels, and thus calls to getLevel(patches) will fail if (dtask->getTask()->getType() != Task::OncePerProc && dtask->getTask()->getType() != Task::Hypre && (!patches || getLevel(patches)->getIndex() != levelnum)) { std::ostringstream mesg; mesg << "WARNING: VarTracker: Not printing requested variable (" << m_tracking_vars[i] << ") because patch is non-standard.\n"; handleError(2, mesg.str(), m_tracking_vars[i]); continue; } //__________________________________ // for (int p = 0; patches && p < patches->size(); p++) { const Patch* patch = patches->get(p); if (m_tracking_patch_id != -1 && m_tracking_patch_id != patch->getID()) { continue; } // Don't print ghost patches (dw->get will yell at you). if ((m_tracking_dws[i] == Task::OldDW && m_loadBalancer->getOldProcessorAssignment(patch) != d_myworld->myRank()) || (m_tracking_dws[i] == Task::NewDW && m_loadBalancer->getPatchwiseProcessorAssignment(patch) != d_myworld->myRank())) { continue; } const TypeDescription* td = label->typeDescription(); Patch::VariableBasis basis = patch->translateTypeToBasis(td->getType(), false); IntVector start = Max(patch->getExtraLowIndex( basis, IntVector(0, 0, 0)), m_tracking_start_index); IntVector end = Min(patch->getExtraHighIndex(basis, IntVector(0, 0, 0)), m_tracking_end_index); // Loop over matls too... for (unsigned int m = 0; m < m_materialManager->getNumMatls(); m++) { if (!dw->exists(label, m, patch)) { std::ostringstream mesg; mesg << "WARNING: VarTracker: Not printing requested variable (" << m_tracking_vars[i] << ") because it does not exist in DW.\n" << " Patch is: " << *patch << "\n"; if (handleError(3, mesg.str(), m_tracking_vars[i])) { } continue; } if (!(start.x() < end.x() && start.y() < end.y() && start.z() < end.z())) { continue; } const TypeDescription::Type subType = td->getSubType()->getType(); if (subType != TypeDescription::double_type && subType != TypeDescription::int_type && subType != TypeDescription::Vector) { // Only allow *Variable<double>, *Variable<int> and *Variable<Vector> for now. std::ostringstream mesg; mesg << "WARNING: VarTracker: Not printing requested variable (" << m_tracking_vars[i] << ") because its type is not supported:\n" << " " << td->getName() << "\n"; handleError(4, mesg.str(), m_tracking_vars[i]); continue; } // pending the task that allocates the var, we may not have allocated it yet GridVariableBase* v; switch (td->getType()) { case TypeDescription::CCVariable : case TypeDescription::NCVariable : case TypeDescription::SFCXVariable : case TypeDescription::SFCYVariable : case TypeDescription::SFCZVariable : v = dynamic_cast<GridVariableBase*>(dw->m_var_DB.get(label, m, patch)); break; default : throw InternalError("Cannot track var type of non-grid-type", __FILE__, __LINE__); break; } start = Max(start, v->getLow()); end = Min(end, v->getHigh()); if (!(start.x() < end.x() && start.y() < end.y() && start.z() < end.z())) { continue; } if (!printedHeader) { std::string location; switch (when) { case PRINT_BEFORE_COMM : location = " before communication of "; break; case PRINT_BEFORE_EXEC : location = " before execution of "; break; case PRINT_AFTER_EXEC : location = " after execution of "; break; } std::cout << d_myworld->myRank() << location << *dtask << std::endl; printedHeader = true; } if (!printedVarName) { std::cout << d_myworld->myRank() << " Variable: " << m_tracking_vars[i] << ", DW " << dw->getID() << ", Patch " << patch->getID() << ", Matl " << m << std::endl; } switch (subType) { case TypeDescription::double_type : { GridVariable<double>* var = dynamic_cast<GridVariable<double>*>(v); printTrackedValues<double>(var, start, end); } break; case TypeDescription::int_type : { GridVariable<int>* var = dynamic_cast<GridVariable<int>*>(v); printTrackedValues<int>(var, start, end); } break; case TypeDescription::Vector : { GridVariable<Vector>* var = dynamic_cast<GridVariable<Vector>*>(v); printTrackedValues<Vector>(var, start, end); } break; default : break; } // end case variable type } // end for materials loop } // end for patches loop } // end for i : trackingVars.size() } // end printTrackedVars() //______________________________________________________________________ // void SchedulerCommon::addTaskGraph( Scheduler::tgType type , int index ) { TaskGraph* tg = scinew TaskGraph(this, d_myworld, type, index); tg->initialize(); m_task_graphs.push_back(tg); } //______________________________________________________________________ // void SchedulerCommon::addTask( Task * task , const PatchSet * patches , const MaterialSet * matls , const int tg_num /* = -1 */ ) { // Save the DW map task->setMapping(m_dwmap); bool is_init = m_is_init_timestep || m_is_restart_init_timestep; DOUT(g_schedulercommon_dbg, "Rank-" << d_myworld->myRank() << " adding Task: " << task->getName() << ", # patches: " << (patches ? patches->size() : 0) << ", # matls: " << (matls ? matls->size() : 0) << ", task-graph: " << ((tg_num < 0) ? (is_init ? "init-tg" : "all") : std::to_string(tg_num))); // bulletproofing - ignore during initialization, the first and only // task graph is used regardless. if (!is_init && tg_num >= (int) m_task_graphs.size()){ std::ostringstream msg; msg << task->getName() <<"::addTask(), taskgraph index ("<< tg_num << ") >= num_taskgraphs ("<< m_task_graphs.size() << ")"; throw InternalError(msg.str(), __FILE__, __LINE__); } // use std::shared_ptr as task pointers may be added to all task graphs - automagic cleanup std::shared_ptr<Task> task_sp(task); // default case for normal tasks addTask(task_sp, patches, matls, tg_num); // separate out the standard from the distal ghost cell requirements - for loadbalancer // This isn't anything fancy, and could be expanded/modified down the road. // It just gets a max ghost cell extent for anything less than MAX_HALO_DEPTH, and // another max ghost cell extent for anything >= MAX_HALO_DEPTH. The idea is that later // we will create two neighborhoods with max extents for each as determined here. for (auto dep = task->getRequires(); dep != nullptr; dep = dep->m_next) { if (dep->m_num_ghost_cells >= MAX_HALO_DEPTH) { if (dep->m_num_ghost_cells > this->m_max_distal_ghost_cells) { this->m_max_distal_ghost_cells = dep->m_num_ghost_cells; } } else { if (dep->m_num_ghost_cells > this->m_max_ghost_cells) { this->m_max_ghost_cells = dep->m_num_ghost_cells; } } } if (task->m_max_level_offset > this->m_max_level_offset) { this->m_max_level_offset = task->m_max_level_offset; } // add to init-requires. These are the vars which require from the OldDW that we'll // need for checkpointing, switching, and the like. // In the case of treatAsOld Vars, we handle them because something external to the taskgraph // needs it that way (i.e., Regridding on a restart requires checkpointed refineFlags). for (auto dep = task->getRequires(); dep != nullptr; dep = dep->m_next) { if (isOldDW(dep->mapDataWarehouse()) || m_treat_as_old_vars.find(dep->m_var->getName()) != m_treat_as_old_vars.end()) { m_init_requires.push_back(dep); m_init_required_vars.insert(dep->m_var); } } // for the treat-as-old vars, go through the computes and add them. // we can (probably) safely assume that we'll avoid duplicates, since if they were inserted // in the above, they wouldn't need to be marked as such for (auto dep = task->getComputes(); dep != nullptr; dep = dep->m_next) { m_computed_vars.insert(dep->m_var); if (m_treat_as_old_vars.find(dep->m_var->getName()) != m_treat_as_old_vars.end()) { m_init_requires.push_back(dep); m_init_required_vars.insert(dep->m_var); } } //__________________________________ // create reduction task if computes included one or more reduction vars for (auto dep = task->getComputes(); dep != nullptr; dep = dep->m_next) { if (dep->m_var->typeDescription()->isReductionVariable()) { int levelidx = dep->m_reduction_level ? dep->m_reduction_level->getIndex() : -1; int dw = dep->mapDataWarehouse(); if (dep->m_var->allowsMultipleComputes()) { DOUT( g_schedulercommon_dbg, "Rank-" << d_myworld->myRank() << " Skipping Reduction task for multi compute variable: " << dep->m_var->getName() << " on level " << levelidx << ", DW " << dw); continue; } DOUT( g_schedulercommon_dbg, "Rank-" << d_myworld->myRank() << " Creating Reduction task for variable: " << dep->m_var->getName() << " on level " << levelidx << ", DW " << dw); std::ostringstream taskname; taskname << "Reduction: " << dep->m_var->getName() << ", level " << levelidx << ", dw " << dw; Task* reduction_task = scinew Task(taskname.str(), Task::Reduction); int dwmap[Task::TotalDWs]; for (int i = 0; i < Task::TotalDWs; i++) { dwmap[i] = Task::InvalidDW; } dwmap[Task::OldDW] = Task::NoDW; dwmap[Task::NewDW] = dw; reduction_task->setMapping(dwmap); int matlIdx = -1; if (dep->m_matls != nullptr) { reduction_task->modifies(dep->m_var, dep->m_reduction_level, dep->m_matls, Task::OutOfDomain); for (int i = 0; i < dep->m_matls->size(); i++) { matlIdx = dep->m_matls->get(i); const DataWarehouse* const_dw = get_dw(dw); VarLabelMatl<Level,DataWarehouse> key(dep->m_var, matlIdx, dep->m_reduction_level, const_dw); // For reduction variables there may be multiple computes // each of which will create reduction task. The last // reduction task should be kept. This is because the tasks // do not get sorted. if( m_reduction_tasks.find(key) == m_reduction_tasks.end() ) { DOUT( g_schedulercommon_dbg, "Rank-" << d_myworld->myRank() << " Excluding previous reduction task for variable: " << dep->m_var->getName() << " on level " << levelidx << ", DW " << dw << " dep->m_reduction_level " << dep->m_reduction_level << " material index " << matlIdx ); } m_reduction_tasks[key] = reduction_task; } } else { for (int m = 0; m < task->getMaterialSet()->size(); m++) { reduction_task->modifies(dep->m_var, dep->m_reduction_level, task->getMaterialSet()->getSubset(m), Task::OutOfDomain); for (int i = 0; i < task->getMaterialSet()->getSubset(m)->size(); ++i) { matlIdx = task->getMaterialSet()->getSubset(m)->get(i); const DataWarehouse* const_dw = get_dw(dw); VarLabelMatl<Level,DataWarehouse> key(dep->m_var, matlIdx, dep->m_reduction_level, const_dw); // For reduction variables there may be multiple computes // each of which will create reduction task. The last // reduction task should be kept. This is because the // tasks do not get sorted. if( m_reduction_tasks.find(key) == m_reduction_tasks.end() ) { DOUT( g_schedulercommon_dbg, "Rank-" << d_myworld->myRank() << " Excluding previous reduction task for variable: " << dep->m_var->getName() << " on level " << levelidx << ", DW " << dw << " dep->m_reduction_level " << dep->m_reduction_level << " material index " << matlIdx ); } m_reduction_tasks[key] = reduction_task; } } } // use std::shared_ptr as task pointers may be added to all task graphs - automagic cleanup std::shared_ptr<Task> reduction_task_sp(reduction_task); // add reduction task to the task graphs addTask(reduction_task_sp, nullptr, task->getMaterialSet(), tg_num); } } } //______________________________________________________________________ // void SchedulerCommon::addTask( std::shared_ptr<Task> task , const PatchSet * patches , const MaterialSet * matls , const int tg_num ) { // During initialization or restart, there is only one task graph. if (m_is_init_timestep || m_is_restart_init_timestep) { m_task_graphs[m_task_graphs.size() - 1]->addTask(task, patches, matls); m_num_tasks++; } else { // Add it to all "Normal" task graphs (default value == -1, from public addTask() method). if (tg_num < 0) { for (int i = 0; i < m_task_graphs.size(); ++i) { m_task_graphs[i]->addTask(task, patches, matls); m_num_tasks++; } } // Otherwise, add this task to a specific task graph. else { m_task_graphs[tg_num]->addTask(task, patches, matls); m_num_tasks++; } } } //______________________________________________________________________ // void SchedulerCommon::initialize( int numOldDW /* = 1 */ , int numNewDW /* = 1 */ ) { // doesn't really do anything except initialize/clear the taskgraph // if the default parameter values are used int numDW = numOldDW + numNewDW; int oldnum = (int)m_dws.size(); // in AMR cases we will often need to move from many new DWs to one. In those cases, move the last NewDW to be the next new one. if (oldnum - m_num_old_dws > 1) { m_dws[numDW - 1] = m_dws[oldnum - 1]; } // Clear out the data warehouse so that memory will be freed for (int i = numDW; i < oldnum; i++) { m_dws[i] = 0; } m_dws.resize(numDW); for (; oldnum < numDW; oldnum++) { m_dws[oldnum] = 0; } m_num_old_dws = numOldDW; // clear the taskgraphs, and set the first one for (unsigned i = 0; i < m_task_graphs.size(); i++) { delete m_task_graphs[i]; } m_task_graphs.clear(); m_init_requires.clear(); m_init_required_vars.clear(); m_computed_vars.clear(); m_num_tasks = 0; m_max_ghost_cells = 0; m_max_distal_ghost_cells = 0; m_max_level_offset = 0; m_reduction_tasks.clear(); // During initialization or restart, use only one task graph bool is_init = m_is_init_timestep || m_is_restart_init_timestep; size_t num_task_graphs = (is_init) ? 1 : m_num_task_graphs; for (size_t i = 0; i < num_task_graphs; ++i) { addTaskGraph(NormalTaskGraph, i); } } //______________________________________________________________________ // void SchedulerCommon::setParentDWs( DataWarehouse * parent_old_dw , DataWarehouse * parent_new_dw ) { OnDemandDataWarehouse* pold = dynamic_cast<OnDemandDataWarehouse*>(parent_old_dw); OnDemandDataWarehouse* pnew = dynamic_cast<OnDemandDataWarehouse*>(parent_new_dw); if (parent_old_dw && parent_new_dw) { ASSERT(pold != nullptr); ASSERT(pnew != nullptr); ASSERT(m_num_old_dws > 2); m_dws[0] = pold; m_dws[1] = pnew; } } //______________________________________________________________________ // void SchedulerCommon::clearMappings() { for (int i = 0; i < Task::TotalDWs; i++) { m_dwmap[i] = -1; } } //______________________________________________________________________ // void SchedulerCommon::mapDataWarehouse( Task::WhichDW which , int dwTag ) { ASSERTRANGE(which, 0, Task::TotalDWs); ASSERTRANGE(dwTag, 0, static_cast<int>(m_dws.size())); m_dwmap[which] = dwTag; } //______________________________________________________________________ // DataWarehouse* SchedulerCommon::get_dw( int idx ) { ASSERTRANGE(idx, 0, static_cast<int>(m_dws.size())); if( 0 <= idx && idx < static_cast<int>(m_dws.size()) ) return m_dws[idx].get_rep(); else return nullptr; } //______________________________________________________________________ // DataWarehouse* SchedulerCommon::getLastDW() { return get_dw(static_cast<int>(m_dws.size()) - 1); } //______________________________________________________________________ // void SchedulerCommon::advanceDataWarehouse( const GridP & grid , bool initialization /* = false */ ) { DOUT(g_schedulercommon_dbg, "Rank-" << d_myworld->myRank() << " advanceDataWarehouse, numDWs = " << m_dws.size()); ASSERT(m_dws.size() >= 2); // The last becomes last old, and the rest are new m_dws[m_num_old_dws - 1] = m_dws[m_dws.size() - 1]; if( m_dws.size() == 2 && m_dws[0] == nullptr ) { // first datawarehouse -- indicate that it is the "initialization" dw. int generation = m_generation++; m_dws[1] = scinew OnDemandDataWarehouse(d_myworld, this, generation, grid, true /* initialization dw */); } else { for (int i = m_num_old_dws; i < static_cast<int>(m_dws.size()); i++) { // in AMR initial cases, you can still be in initialization when you advance again replaceDataWarehouse(i, grid, initialization); } } } //______________________________________________________________________ // void SchedulerCommon::fillDataWarehouses( const GridP & grid ) { for (int i = m_num_old_dws; i < static_cast<int>(m_dws.size()); i++) { if (!m_dws[i]) { replaceDataWarehouse(i, grid); } } } //______________________________________________________________________ // void SchedulerCommon::replaceDataWarehouse( int index , const GridP & grid , bool initialization /* = false */ ) { m_dws[index] = scinew OnDemandDataWarehouse(d_myworld, this, m_generation++, grid, initialization); if (initialization) { return; } for (unsigned i = 0; i < m_task_graphs.size(); i++) { DetailedTasks* dts = m_task_graphs[i]->getDetailedTasks(); if (dts) { dts->copyoutDWKeyDatabase(m_dws[index]); } } m_dws[index]->doReserve(); } //______________________________________________________________________ // const std::vector<const Patch*>* SchedulerCommon::getSuperPatchExtents( const VarLabel * label , int matlIndex , const Patch * patch , Ghost::GhostType requestedGType , int requestedNumGCells , IntVector & requiredLow , IntVector & requiredHigh , IntVector & requestedLow , IntVector & requestedHigh ) const { const SuperPatch* connectedPatchGroup = m_locallyComputedPatchVarMap->getConnectedPatchGroup(patch); if (connectedPatchGroup == nullptr) { return nullptr; } SuperPatch::Region requestedExtents = connectedPatchGroup->getRegion(); SuperPatch::Region requiredExtents = connectedPatchGroup->getRegion(); // expand to cover the entire connected patch group for (unsigned int i = 0; i < connectedPatchGroup->getBoxes().size(); i++) { // get the minimum extents containing both the expected ghost cells // to be needed and the given ghost cells. const Patch* memberPatch = connectedPatchGroup->getBoxes()[i]; Patch::VariableBasis basis = Patch::translateTypeToBasis(label->typeDescription()->getType(), true); IntVector lowOffset = IntVector(0, 0, 0); IntVector highOffset = IntVector(0, 0, 0); //set requiredLow and requiredHigh as extents without ghost cells memberPatch->computeExtents(basis, label->getBoundaryLayer(), lowOffset, highOffset, requiredLow, requiredHigh); //compute ghost cell offsets Patch::getGhostOffsets(basis, requestedGType, requestedNumGCells, lowOffset, highOffset); //set requestedLow and requestedHigh as extents with ghost cells memberPatch->computeExtents(basis, label->getBoundaryLayer(), lowOffset, highOffset, requestedLow, requestedHigh); SuperPatch::Region requiredRegion = SuperPatch::Region(requiredLow, requiredHigh); requiredExtents = requiredExtents.enclosingRegion(requiredRegion); SuperPatch::Region requestedRegion = SuperPatch::Region(requestedLow, requestedHigh); requestedExtents = requestedExtents.enclosingRegion(requestedRegion); ASSERT(memberPatch == patch); } requiredLow = requiredExtents.low_; requiredHigh = requiredExtents.high_; requestedLow = requestedExtents.low_; requestedHigh = requestedExtents.high_; // requested extents must enclose the required extents at lesst. ASSERTEQ(Min(requiredLow, requestedLow), requestedLow); ASSERTEQ(Max(requiredHigh, requestedHigh), requestedHigh); return &connectedPatchGroup->getBoxes(); } //______________________________________________________________________ // void SchedulerCommon::logMemoryUse() { if (!m_mem_logfile) { std::ostringstream fname; fname << "uintah_memuse.log.p" << std::setw(5) << std::setfill('0') << d_myworld->myRank() << "." << d_myworld->nRanks(); m_mem_logfile = scinew std::ofstream(fname.str().c_str()); if (!m_mem_logfile) { std::cerr << "Error opening file: " << fname.str() << '\n'; } } *m_mem_logfile << '\n'; unsigned long total = 0; for (int i = 0; i < (int)m_dws.size(); i++) { char* name; if (i == 0) { name = const_cast<char*>("OldDW"); } else if (i == (int)m_dws.size() - 1) { name = const_cast<char*>("NewDW"); } else { name = const_cast<char*>("IntermediateDW"); } if (m_dws[i]) { m_dws[i]->logMemoryUse(*m_mem_logfile, total, name); } } for (unsigned i = 0; i < m_task_graphs.size(); i++) { DetailedTasks* dts = m_task_graphs[i]->getDetailedTasks(); if (dts) { dts->logMemoryUse(*m_mem_logfile, total, "Taskgraph"); } } *m_mem_logfile << "Total: " << total << '\n'; m_mem_logfile->flush(); } //______________________________________________________________________ // // Makes and returns a map that maps strings to VarLabels of // that name and a list of material indices for which that // variable is valid (according to d_allcomps in graph). Scheduler::VarLabelMaterialMap* SchedulerCommon::makeVarLabelMaterialMap() { VarLabelMaterialMap* result = scinew VarLabelMaterialMap(); for( unsigned i = 0; i < m_task_graphs.size(); i++ ) { m_task_graphs[ i ]->makeVarLabelMaterialMap( result ); } return result; } //______________________________________________________________________ // void SchedulerCommon::doEmitTaskGraphDocs() { m_emit_task_graph = true; } //______________________________________________________________________ // void SchedulerCommon::compile() { GridP grid = const_cast<Grid*>(getLastDW()->getGrid()); GridP oldGrid = nullptr; if (m_dws[0]) { oldGrid = const_cast<Grid*>(get_dw(0)->getGrid()); } if (m_num_tasks > 0) { DOUT(g_schedulercommon_dbg, "Rank-" << d_myworld->myRank() << " SchedulerCommon starting compile"); const auto num_task_graphs = m_task_graphs.size(); for (auto i = 0u; i < num_task_graphs; i++) { if (num_task_graphs > 1) { DOUT(g_schedulercommon_dbg, "Rank-" << d_myworld->myRank() << " Compiling task graph: " << i+1 << " of " << m_task_graphs.size() << " with " << m_num_tasks << " tasks."); } Timers::Simple tg_compile_timer; tg_compile_timer.start(); // check if this TG has any tasks with halo requirements > MAX_HALO_DEPTH (determined in public SchedulerCommon::addTask()) const bool has_distal_reqs = m_task_graphs[i]->getDistalRequires(); // NOTE: this single call is where all the TG compilation complexity arises (dependency analysis for auto MPI mesgs) m_task_graphs[i]->createDetailedTasks( useInternalDeps(), grid, oldGrid, has_distal_reqs ); double compile_time = tg_compile_timer().seconds(); bool is_init = m_is_init_timestep || m_is_restart_init_timestep; DOUT(g_task_graph_compile, "Rank-" << std::left << std::setw(5) << d_myworld->myRank() << " time to compile TG-" << std::setw(4) << (is_init ? "init-tg" : std::to_string(m_task_graphs[i]->getIndex())) << ": " << compile_time << " (sec)"); } // check scheduler at runtime, that all ranks are executing the same size TG (excluding spatial tasks) verifyChecksum(); DOUT(g_schedulercommon_dbg, "Rank-" << d_myworld->myRank() << " SchedulerCommon finished compile"); } else { return; // no tasks, so nothing to do } m_locallyComputedPatchVarMap->reset(); const int num_levels = grid->numLevels(); for (int i = 0; i < num_levels; ++i) { const PatchSubset* patches = m_loadBalancer->getPerProcessorPatchSet(grid->getLevel(i))->getSubset(d_myworld->myRank()); if (patches->size() > 0) { m_locallyComputedPatchVarMap->addComputedPatchSet(patches); } } const auto num_dws = m_dws.size(); for (auto dw = 0u; dw < num_dws; ++dw) { if (m_dws[dw].get_rep()) { const auto num_task_graphs = m_task_graphs.size(); for (auto i = 0u; i < num_task_graphs; ++i) { DetailedTasks* dts = m_task_graphs[i]->getDetailedTasks(); dts->copyoutDWKeyDatabase(m_dws[dw]); } m_dws[dw]->doReserve(); } } // create SuperPatch groups - only necessary if OnDemandDataWarehouse::s_combine_memory == true, by default it is false m_locallyComputedPatchVarMap->makeGroups(); } //______________________________________________________________________ // bool SchedulerCommon::isOldDW( int idx ) const { ASSERTRANGE(idx, 0, static_cast<int>(m_dws.size())); return idx < m_num_old_dws; } //______________________________________________________________________ // bool SchedulerCommon::isNewDW( int idx ) const { ASSERTRANGE(idx, 0, static_cast<int>(m_dws.size())); return idx >= m_num_old_dws; } //______________________________________________________________________ // void SchedulerCommon::finalizeTimestep() { finalizeNodes(d_myworld->myRank()); for (unsigned int i = m_num_old_dws; i < m_dws.size(); i++) { m_dws[i]->finalize(); } } //______________________________________________________________________ // void SchedulerCommon::scheduleAndDoDataCopy( const GridP & grid ) { Timers::Simple timer; timer.start(); // TODO - use the current initReqs and push them back, instead of doing this... // clear the old list of vars and matls for (unsigned i = 0; i < m_label_matls.size(); i++) { for (LabelMatlMap::iterator iter = m_label_matls[i].begin(); iter != m_label_matls[i].end(); iter++) { if (iter->second->removeReference()) { delete iter->second; } } } m_label_matls.clear(); m_label_matls.resize(grid->numLevels()); // produce a map from all tasks' requires from the Old DW. Store the varlabel and matls // TODO - only do this ONCE. for (unsigned t = 0; t < m_task_graphs.size(); t++) { TaskGraph* tg = m_task_graphs[t]; for (int i = 0; i < tg->getNumTasks(); i++) { Task* task = tg->getTask(i); if (task->getType() == Task::Output) { continue; } for (const Task::Dependency* dep = task->getRequires(); dep != 0; dep = dep->m_next) { bool copyThisVar = (dep->m_whichdw == Task::OldDW); // override to manually copy a var if (!copyThisVar) { if (m_copy_data_vars.find(dep->m_var->getName()) != m_copy_data_vars.end()) { copyThisVar = true; } } // Overide the logic above. There are PerPatch variables that cannot/shouldn't be copied to the new grid, // for example PerPatch<FileInfo>. if (m_no_copy_data_vars.count(dep->m_var->getName()) > 0) { copyThisVar = false; } if (copyThisVar) { // Take care of reduction/sole variables in a different section TypeDescription::Type depType = dep->m_var->typeDescription()->getType(); if ( depType == TypeDescription::ReductionVariable || depType == TypeDescription::SoleVariable) { continue; } // check the level on the case where variables are only computed on certain levels const PatchSet* ps = task->getPatchSet(); int level = -1; if (dep->m_patches) { // just in case the task is over multiple levels... level = getLevel(dep->m_patches)->getIndex(); } else if (ps) { level = getLevel(ps)->getIndex(); } // we don't want data with an invalid level, or requiring from a different level (remember, we are // using an old task graph). That will be copied later (and chances are, it's to modify anyway). if (level == -1 || level > grid->numLevels() - 1 || dep->m_patches_dom == Task::CoarseLevel || dep->m_patches_dom == Task::FineLevel) { continue; } const MaterialSubset * matSubset = (dep->m_matls != 0) ? dep->m_matls : dep->m_task->getMaterialSet()->getUnion(); // if var was already found, make a union of the materials MaterialSubset* matls = scinew MaterialSubset(matSubset->getVector()); matls->addReference(); MaterialSubset* union_matls; union_matls = m_label_matls[level][dep->m_var]; if (union_matls) { for (int i = 0; i < union_matls->size(); i++) { if (!matls->contains(union_matls->get(i))) { matls->add(union_matls->get(i)); } } if (union_matls->removeReference()) { delete union_matls; } } matls->sort(); m_label_matls[level][dep->m_var] = matls; } } } } this->initialize(1, 1); this->advanceDataWarehouse(grid, true); this->clearMappings(); this->mapDataWarehouse(Task::OldDW, 0); this->mapDataWarehouse(Task::NewDW, 1); this->mapDataWarehouse(Task::CoarseOldDW, 0); this->mapDataWarehouse(Task::CoarseNewDW, 1); DataWarehouse* oldDataWarehouse = this->get_dw(0); DataWarehouse* newDataWarehouse = this->getLastDW(); oldDataWarehouse->setScrubbing(DataWarehouse::ScrubNone); newDataWarehouse->setScrubbing(DataWarehouse::ScrubNone); const Grid * oldGrid = oldDataWarehouse->getGrid(); std::vector<Task*> dataTasks; std::vector<Handle<PatchSet> > refinePatchSets(grid->numLevels(), (PatchSet*)0); std::vector<Handle<PatchSet> > copyPatchSets(grid->numLevels(), (PatchSet*)0); SchedulerP sched(dynamic_cast<Scheduler*>(this)); m_is_copy_data_timestep = true; for (int L = 0; L < grid->numLevels(); L++) { LevelP newLevel = grid->getLevel(L); if (L > 0) { if (L >= oldGrid->numLevels()) { // new level - refine everywhere refinePatchSets[L] = const_cast<PatchSet*>(newLevel->eachPatch()); copyPatchSets[L] = scinew PatchSet; } // Find patches with new space - but temporarily, refine everywhere... else if (L < oldGrid->numLevels()) { refinePatchSets[L] = scinew PatchSet; copyPatchSets[L] = scinew PatchSet; std::vector<int> myPatchIDs; LevelP oldLevel = oldDataWarehouse->getGrid()->getLevel(L); // Go through the patches, and find if there are patches that // weren't entirely covered by patches on the old grid, and // interpolate them. then after, copy the data, and if // necessary, overwrite interpolated data const PatchSubset *ps = m_loadBalancer->getPerProcessorPatchSet(newLevel)->getSubset(d_myworld->myRank()); // for each patch I own for (int p = 0; p < ps->size(); p++) { const Patch *newPatch = ps->get(p); // get the low/high for what we'll need to get IntVector lowIndex, highIndex; //newPatch->computeVariableExtents(Patch::CellBased, IntVector(0,0,0), Ghost::None, 0, lowIndex, highIndex); lowIndex = newPatch->getCellLowIndex(); highIndex = newPatch->getCellHighIndex(); // find if area on the new patch was not covered by the old patches IntVector dist = highIndex - lowIndex; int totalCells = dist.x() * dist.y() * dist.z(); int sum = 0; Patch::selectType oldPatches; oldLevel->selectPatches(lowIndex, highIndex, oldPatches); //compute volume of overlapping regions for (unsigned int old = 0; old < oldPatches.size(); old++) { const Patch* oldPatch = oldPatches[old]; IntVector oldLow = oldPatch->getCellLowIndex(); IntVector oldHigh = oldPatch->getCellHighIndex(); IntVector low = Max(oldLow, lowIndex); IntVector high = Min(oldHigh, highIndex); IntVector dist = high - low; sum += dist.x() * dist.y() * dist.z(); } // for oldPatches if (sum != totalCells) { if (Uintah::Parallel::usingMPI()) { myPatchIDs.push_back(newPatch->getID()); } else { refinePatchSets[L]->add(newPatch); } } else { if (!Uintah::Parallel::usingMPI()) { copyPatchSets[L]->add(newPatch); } } } // for patch if (Uintah::Parallel::usingMPI()) { //Gather size from all processors int mycount = myPatchIDs.size(); std::vector<int> counts(d_myworld->nRanks()); Uintah::MPI::Allgather(&mycount, 1, MPI_INT, &counts[0], 1, MPI_INT, d_myworld->getComm()); //compute recieve array offset and size std::vector<int> displs(d_myworld->nRanks()); int pos = 0; for (int p = 0; p < d_myworld->nRanks(); p++) { displs[p] = pos; pos += counts[p]; } std::vector<int> allPatchIDs(pos); //receive array; Uintah::MPI::Allgatherv(&myPatchIDs[0], counts[d_myworld->myRank()], MPI_INT, &allPatchIDs[0], &counts[0], &displs[0], MPI_INT, d_myworld->getComm()); //make refinePatchSets from patch ids std::set<int> allPatchIDset(allPatchIDs.begin(), allPatchIDs.end()); for (Level::patch_iterator iter = newLevel->patchesBegin(); iter != newLevel->patchesEnd(); ++iter) { Patch* newPatch = *iter; if (allPatchIDset.find(newPatch->getID()) != allPatchIDset.end()) { refinePatchSets[L]->add(newPatch); } else { copyPatchSets[L]->add(newPatch); } } } // using MPI } if (refinePatchSets[L]->size() > 0) { DOUT(g_schedulercommon_dbg, "Rank-" << d_myworld->myRank() << " Calling scheduleRefine for patches " << *refinePatchSets[L].get_rep()); m_application->scheduleRefine(refinePatchSets[L].get_rep(), sched); } } else { refinePatchSets[L] = scinew PatchSet; copyPatchSets[L] = const_cast<PatchSet*>(newLevel->eachPatch()); } //__________________________________ // Scheduling for copyDataToNewGrid if (copyPatchSets[L]->size() > 0) { dataTasks.push_back(scinew Task("SchedulerCommon::copyDataToNewGrid", this, &SchedulerCommon::copyDataToNewGrid)); for (LabelMatlMap::iterator iter = m_label_matls[L].begin(); iter != m_label_matls[L].end(); iter++) { const VarLabel* var = iter->first; MaterialSubset* matls = iter->second; dataTasks.back()->requires(Task::OldDW, var, 0, Task::OtherGridDomain, matls, Task::NormalDomain, Ghost::None, 0); DOUT(g_schedulercommon_dbg, " Scheduling copy for var " << *var << " matl " << *matls << " Copies: " << *copyPatchSets[L].get_rep()); dataTasks.back()->computes(var, matls); } addTask(dataTasks.back(), copyPatchSets[L].get_rep(), m_materialManager->allMaterials()); // Monitoring tasks must be scheduled last!! scheduleTaskMonitoring( copyPatchSets[L].get_rep() ); } //__________________________________ // Scheduling for modifyDataOnNewGrid if (refinePatchSets[L]->size() > 0) { dataTasks.push_back(scinew Task("SchedulerCommon::modifyDataOnNewGrid", this, &SchedulerCommon::copyDataToNewGrid)); for (LabelMatlMap::iterator iter = m_label_matls[L].begin(); iter != m_label_matls[L].end(); iter++) { const VarLabel* var = iter->first; MaterialSubset* matls = iter->second; dataTasks.back()->requires(Task::OldDW, var, nullptr, Task::OtherGridDomain, matls, Task::NormalDomain, Ghost::None, 0); DOUT(g_schedulercommon_dbg, " Scheduling modify for var " << *var << " matl " << *matls << " Modifies: " << *refinePatchSets[L].get_rep()); dataTasks.back()->modifies(var, matls); } addTask(dataTasks.back(), refinePatchSets[L].get_rep(), m_materialManager->allMaterials()); // Monitoring tasks must be scheduled last!! scheduleTaskMonitoring( refinePatchSets[L].get_rep()); } //__________________________________ // Component's shedule for refineInterfae if (L > 0) { m_application->scheduleRefineInterface(newLevel, sched, 0, 1); } } // set so the load balancer will make an adequate neighborhood, as // the default neighborhood isn't good enough for the copy data // timestep m_is_copy_data_timestep = true; //-- do we still need this? - BJW #if !defined( DISABLE_SCI_MALLOC ) const char* tag = AllocatorSetDefaultTag("DoDataCopy"); #endif this->compile(); (*m_runtimeStats)[RegriddingCompilationTime] += timer().seconds(); // save these and restore them, since the next execute will append the scheduler's, and we don't want to. double exec_time = (*m_runtimeStats)[TaskExecTime]; double local_time = (*m_runtimeStats)[TaskLocalCommTime]; double wait_time = (*m_runtimeStats)[TaskWaitCommTime]; double reduce_time = (*m_runtimeStats)[TaskReduceCommTime]; double thread_time = (*m_runtimeStats)[TaskWaitThreadTime]; timer.reset( true ); this->execute(); #if !defined( DISABLE_SCI_MALLOC ) AllocatorSetDefaultTag(tag); #endif //__________________________________ // copy reduction and sole variables to the new_dw std::vector<VarLabelMatl<Level> > levelVariableInfo; oldDataWarehouse->getVarLabelMatlLevelTriples(levelVariableInfo); newDataWarehouse->unfinalize(); for (unsigned int i = 0; i < levelVariableInfo.size(); i++) { VarLabelMatl<Level> currentGlobalVar = levelVariableInfo[i]; if (currentGlobalVar.m_label->typeDescription()->getType() == TypeDescription::ReductionVariable || currentGlobalVar.m_label->typeDescription()->getType() == TypeDescription::SoleVariable) { // cout << "Global var: Label(" << setw(15) << currentGlobalVar.m_label->getName() << "): Patch(" << reinterpret_cast<int>(currentGlobalVar.level_) << "): Material(" << currentGlobalVar.matlIndex_ << ")" << endl; const Level* oldLevel = currentGlobalVar.m_domain; const Level* newLevel = nullptr; if (oldLevel && oldLevel->getIndex() < grid->numLevels()) { if (oldLevel->getIndex() >= grid->numLevels()) { // the new grid no longer has this level continue; } newLevel = (newDataWarehouse->getGrid()->getLevel(oldLevel->getIndex())).get_rep(); } // Either both levels need to be null or both need to exist (null levels mean global data) if (!oldLevel || newLevel) { if (currentGlobalVar.m_label->typeDescription()->getType() == TypeDescription::ReductionVariable ) { ReductionVariableBase* v = dynamic_cast<ReductionVariableBase*>(currentGlobalVar.m_label->typeDescription()->createInstance()); oldDataWarehouse->get(*v, currentGlobalVar.m_label, currentGlobalVar.m_domain, currentGlobalVar.m_matl_index); newDataWarehouse->put(*v, currentGlobalVar.m_label, newLevel, currentGlobalVar.m_matl_index); delete v; // copied on the put command } else if (currentGlobalVar.m_label->typeDescription()->getType() == TypeDescription::SoleVariable ) { SoleVariableBase* v = dynamic_cast<SoleVariableBase*>(currentGlobalVar.m_label->typeDescription()->createInstance()); oldDataWarehouse->get(*v, currentGlobalVar.m_label, currentGlobalVar.m_domain, currentGlobalVar.m_matl_index); newDataWarehouse->put(*v, currentGlobalVar.m_label, newLevel, currentGlobalVar.m_matl_index); delete v; // copied on the put command } } } } newDataWarehouse->refinalize(); (*m_runtimeStats)[RegriddingCopyDataTime] += timer().seconds(); // restore values from before the regrid and data copy (*m_runtimeStats)[TaskExecTime] = exec_time; (*m_runtimeStats)[TaskLocalCommTime] = local_time; (*m_runtimeStats)[TaskWaitCommTime] = wait_time; (*m_runtimeStats)[TaskReduceCommTime] = reduce_time; (*m_runtimeStats)[TaskWaitThreadTime] = thread_time; m_is_copy_data_timestep = false; } //______________________________________________________________________ // void SchedulerCommon::copyDataToNewGrid( const ProcessorGroup * /* pg */ , const PatchSubset * patches , const MaterialSubset * matls , DataWarehouse * old_dw , DataWarehouse * new_dw ) { DOUT(g_schedulercommon_dbg, "SchedulerCommon::copyDataToNewGrid() BGN on patches " << *patches); OnDemandDataWarehouse* oldDataWarehouse = dynamic_cast<OnDemandDataWarehouse*>(old_dw); OnDemandDataWarehouse* newDataWarehouse = dynamic_cast<OnDemandDataWarehouse*>(new_dw); // For each patch in the patch subset which contains patches in the new grid for (int p = 0; p < patches->size(); p++) { const Patch* newPatch = patches->get(p); const Level* newLevel = newPatch->getLevel(); // to create once per matl instead of once per matl-var std::vector<ParticleSubset*> oldsubsets(m_materialManager->getNumMatls()), newsubsets(m_materialManager->getNumMatls()); // If there is a level that didn't exist, we don't need to copy it if (newLevel->getIndex() >= oldDataWarehouse->getGrid()->numLevels()) { continue; } // find old patches associated with this patch LevelP oldLevel = oldDataWarehouse->getGrid()->getLevel(newLevel->getIndex()); //__________________________________ // Grid and particle variables // Loop over Var labels for (LabelMatlMap::iterator iter = m_label_matls[oldLevel->getIndex()].begin(); iter != m_label_matls[oldLevel->getIndex()].end(); iter++) { const VarLabel* label = iter->first; MaterialSubset* var_matls = iter->second; // get the low/high for what we'll need to get Patch::VariableBasis basis = Patch::translateTypeToBasis(label->typeDescription()->getType(), true); IntVector newLowIndex, newHighIndex; newPatch->computeVariableExtents(basis, IntVector(0, 0, 0), Ghost::None, 0, newLowIndex, newHighIndex); //__________________________________ // Loop over materials for (int m = 0; m < var_matls->size(); m++) { int matl = var_matls->get(m); if (!matls->contains(matl)) { continue; } switch (label->typeDescription()->getType()) { case TypeDescription::PerPatch : case TypeDescription::NCVariable : case TypeDescription::CCVariable : case TypeDescription::SFCXVariable : case TypeDescription::SFCYVariable : case TypeDescription::SFCZVariable : { Patch::selectType oldPatches; oldLevel->selectPatches(newLowIndex, newHighIndex, oldPatches); for (unsigned int oldIdx = 0; oldIdx < oldPatches.size(); oldIdx++) { const Patch* oldPatch = oldPatches[oldIdx]; if (!oldDataWarehouse->exists(label, matl, oldPatch)) { continue; // see comment about oldPatchToTest in ScheduleAndDoDataCopy } IntVector oldLowIndex; IntVector oldHighIndex; if (newLevel->getIndex() > 0) { oldLowIndex = oldPatch->getLowIndexWithDomainLayer(basis); oldHighIndex = oldPatch->getHighIndexWithDomainLayer(basis); } else { oldLowIndex = oldPatch->getExtraLowIndex(basis, label->getBoundaryLayer()); oldHighIndex = oldPatch->getExtraHighIndex(basis, label->getBoundaryLayer()); } IntVector copyLowIndex = Max(newLowIndex, oldLowIndex); IntVector copyHighIndex = Min(newHighIndex, oldHighIndex); // based on the selectPatches above, we might have patches we don't want to use, so prune them here. if (copyLowIndex.x() >= copyHighIndex.x() || copyLowIndex.y() >= copyHighIndex.y() || copyLowIndex.z() >= copyHighIndex.z()) { continue; } // bulletproofing if (!oldDataWarehouse->exists(label, matl, oldPatch)) { SCI_THROW(UnknownVariable(label->getName(), oldDataWarehouse->getID(), oldPatch, matl, "in copyDataTo GridVariableBase", __FILE__, __LINE__)); } if( label->typeDescription()->getType() == TypeDescription::PerPatch ) { // DOUTALL( true, "copyDataToNewGrid PerPatch vars begin" ); std::vector<Variable *> varlist; oldDataWarehouse->m_var_DB.getlist(label, matl, oldPatch, varlist); PerPatchBase* v = nullptr; for (unsigned int i = 0; i < varlist.size(); ++i) { v = dynamic_cast<PerPatchBase*>(varlist[i]); ASSERT(v->getBasePointer() != nullptr); if (!newDataWarehouse->exists(label, matl, newPatch)) { PerPatchBase* newVariable = v->clone(); newDataWarehouse->m_var_DB.put(label, matl, newPatch, newVariable, copyTimestep(), false); } else { PerPatchBase* newVariable = dynamic_cast<PerPatchBase*>(newDataWarehouse->m_var_DB.get(label, matl, newPatch)); if (oldPatch->isVirtual()) { // it can happen where the old patch was virtual and this is not PerPatchBase* tmpVar = newVariable->clone(); tmpVar->copyPointer(*v); newVariable = tmpVar; delete tmpVar; } else { newVariable = v; } } // DOUTALL( true, "copyDataToNewGrid PerPatch vars end " << label->getName() ); } // DOUTALL( true, "copyDataToNewGrid PerPatch vars end" ); } else { std::vector<Variable *> varlist; oldDataWarehouse->m_var_DB.getlist(label, matl, oldPatch, varlist); GridVariableBase* v = nullptr; IntVector srclow = copyLowIndex; IntVector srchigh = copyHighIndex; for (unsigned int i = 0; i < varlist.size(); ++i) { v = dynamic_cast<GridVariableBase*>(varlist[i]); ASSERT(v->getBasePointer() != nullptr); //restrict copy to data range srclow = Max(copyLowIndex, v->getLow()); srchigh = Min(copyHighIndex, v->getHigh()); if (srclow.x() >= srchigh.x() || srclow.y() >= srchigh.y() || srclow.z() >= srchigh.z()) { continue; } if (!newDataWarehouse->exists(label, matl, newPatch)) { GridVariableBase* newVariable = v->cloneType(); newVariable->rewindow(newLowIndex, newHighIndex); newVariable->copyPatch(v, srclow, srchigh); newDataWarehouse->m_var_DB.put(label, matl, newPatch, newVariable, copyTimestep(), false); } else { GridVariableBase* newVariable = dynamic_cast<GridVariableBase*>(newDataWarehouse->m_var_DB.get(label, matl, newPatch)); // make sure it exists in the right region (it might be ghost data) newVariable->rewindow(newLowIndex, newHighIndex); if (oldPatch->isVirtual()) { // it can happen where the old patch was virtual and this is not GridVariableBase* tmpVar = newVariable->cloneType(); tmpVar->copyPointer(*v); tmpVar->offset(oldPatch->getVirtualOffset()); newVariable->copyPatch(tmpVar, srclow, srchigh); delete tmpVar; } else { newVariable->copyPatch(v, srclow, srchigh); } } } } } // end oldPatches } break; //__________________________________ // Particle Variables case TypeDescription::ParticleVariable: { ParticleSubset* oldsub = oldsubsets[matl]; if (!oldsub) { // collect the particles from the range encompassing this patch. Use interior cells since // extracells aren't collected across processors in the data copy, and they don't matter // for particles anyhow (but we will have to reset the bounds to copy the data) oldsub = oldDataWarehouse->getParticleSubset(matl, newPatch->getLowIndexWithDomainLayer(Patch::CellBased), newPatch->getHighIndexWithDomainLayer(Patch::CellBased), newPatch, m_reloc_new_pos_label, oldLevel.get_rep()); oldsubsets[matl] = oldsub; oldsub->addReference(); } ParticleSubset* newsub = newsubsets[matl]; // it might have been created in Refine if (!newsub) { if (!newDataWarehouse->haveParticleSubset(matl, newPatch)) { newsub = newDataWarehouse->createParticleSubset(oldsub->numParticles(), matl, newPatch); } else { newsub = newDataWarehouse->getParticleSubset(matl, newPatch); ASSERT(newsub->numParticles() == 0); newsub->addParticles(oldsub->numParticles()); } newsubsets[matl] = newsub; } ParticleVariableBase* newv = dynamic_cast<ParticleVariableBase*>(label->typeDescription()->createInstance()); newv->allocate(newsub); // don't get and copy if there were no old patches if (oldsub->getNeighbors().size() > 0) { constParticleVariableBase* var = newv->cloneConstType(); oldDataWarehouse->get(*var, label, oldsub); // reset the bounds of the old var's data so copyData doesn't complain ParticleSubset* tempset = scinew ParticleSubset(oldsub->numParticles(), matl, newPatch, newPatch->getExtraCellLowIndex(), newPatch->getExtraCellHighIndex()); const_cast<ParticleVariableBase*>(&var->getBaseRep())->setParticleSubset(tempset); newv->copyData(&var->getBaseRep()); delete var; //pset and tempset are deleted with it. } newDataWarehouse->put(*newv, label, true); delete newv; // the container is copied } break; default : { SCI_THROW(InternalError("Unknown variable type in copyData: "+label->getName(), __FILE__, __LINE__)); } } // end switch } // end matls } // end label_matls for (unsigned i = 0; i < oldsubsets.size(); i++) { if (oldsubsets[i] && oldsubsets[i]->removeReference()) { delete oldsubsets[i]; } } } // end patches DOUT(g_schedulercommon_dbg, "SchedulerCommon::copyDataToNewGrid() END"); } //______________________________________________________________________ // void SchedulerCommon::scheduleParticleRelocation( const LevelP & level , const VarLabel * old_posLabel , const VarLabelList & old_labels , const VarLabel * new_posLabel , const VarLabelList & new_labels , const VarLabel * particleIDLabel , const MaterialSet * matls , int which ) { if (which == 1) { if (m_reloc_new_pos_label) { ASSERTEQ(m_reloc_new_pos_label, new_posLabel); } m_reloc_new_pos_label = new_posLabel; m_relocate_1.scheduleParticleRelocation(this, d_myworld, m_loadBalancer, level, old_posLabel, old_labels, new_posLabel, new_labels, particleIDLabel, matls); releasePort("load balancer"); } if (which == 2) { if (m_reloc_new_pos_label) { ASSERTEQ(m_reloc_new_pos_label, new_posLabel); } m_reloc_new_pos_label = new_posLabel; m_relocate_2.scheduleParticleRelocation(this, d_myworld, m_loadBalancer, level, old_posLabel, old_labels, new_posLabel, new_labels, particleIDLabel, matls); } } //______________________________________________________________________ // void SchedulerCommon::scheduleParticleRelocation( const LevelP & coarsestLevelwithParticles , const VarLabel * old_posLabel , const VarLabelList & old_labels , const VarLabel * new_posLabel , const VarLabelList & new_labels , const VarLabel * particleIDLabel , const MaterialSet * matls ) { if (m_reloc_new_pos_label) { ASSERTEQ(m_reloc_new_pos_label, new_posLabel); } m_reloc_new_pos_label = new_posLabel; m_relocate_1.scheduleParticleRelocation(this, d_myworld, m_loadBalancer, coarsestLevelwithParticles, old_posLabel, old_labels, new_posLabel, new_labels, particleIDLabel, matls); } //______________________________________________________________________ // void SchedulerCommon::scheduleParticleRelocation( const LevelP & coarsestLevelwithParticles , const VarLabel * posLabel , const VarLabelList & otherLabels , const MaterialSet * matls ) { m_reloc_new_pos_label = posLabel; m_relocate_1.scheduleParticleRelocation(this, d_myworld, m_loadBalancer, coarsestLevelwithParticles, posLabel, otherLabels, matls); } //______________________________________________________________________ // void SchedulerCommon::overrideVariableBehavior( const std::string & var , bool treatAsOld , bool copyData , bool noScrub , bool notCopyData , bool noCheckpoint ) { // treat variable as an "old" var - will be checkpointed, copied, and only scrubbed from an OldDW if (treatAsOld) { m_treat_as_old_vars.insert(var); } // manually copy this variable to the new_dw if regridding occurs if (copyData) { m_copy_data_vars.insert(var); m_no_scrub_vars.insert(var); } // set variable not to scrub (normally when needed between a normal taskgraph // and the regridding phase) if (noScrub) { m_no_scrub_vars.insert(var); } // so not copy this variable to the new_dw if regridding occurs if (notCopyData) { m_no_copy_data_vars.insert(var); } // do not checkpoint this variable. if (noCheckpoint) { m_no_checkpoint_vars.insert(var); } } //______________________________________________________________________ // void SchedulerCommon::clearTaskMonitoring() { // Loop through the global (0) and local (1) tasks for (unsigned int i = 0; i < 2; ++i) { m_monitoring_values[i].clear(); } } //______________________________________________________________________ // Schedule the recording of the task monitoring attribute // values. This task should be the last task so that the writing is // done after all task have been executed. void SchedulerCommon::scheduleTaskMonitoring( const LevelP& level ) { if( !m_monitoring ) { return; } // Create and schedule a task that will record each of the // tasking monitoring attributes. Task* t = scinew Task("SchedulerCommon::recordTaskMonitoring", this, &SchedulerCommon::recordTaskMonitoring); // Ghost::GhostType gn = Ghost::None; for (unsigned int i = 0; i < 2; ++i) { for( const auto &it : m_monitoring_tasks[i] ) { t->computes( it.second, m_dummy_matl, Task::OutOfDomain ); // treatAsOld copyData noScrub notCopyData noCheckpoint overrideVariableBehavior(it.second->getName(), false, false, true, true, true); } } addTask(t, level->eachPatch(), m_materialManager->allMaterials()); } //______________________________________________________________________ // Schedule the recording of the task monitoring attribute // values. This task should be the last task so that the writing is // done after all task have been executed. void SchedulerCommon::scheduleTaskMonitoring( const PatchSet* patches ) { if( !m_monitoring ) { return; } // Create and schedule a task that will record each of the // tasking monitoring attributes. Task* t = scinew Task("SchedulerCommon::recordTaskMonitoring", this, &SchedulerCommon::recordTaskMonitoring); // Ghost::GhostType gn = Ghost::None; for (unsigned int i = 0; i < 2; ++i) { for( const auto &it : m_monitoring_tasks[i] ) { t->computes( it.second, m_dummy_matl, Task::OutOfDomain ); overrideVariableBehavior(it.second->getName(), false, false, true, true, true); // treatAsOld copyData noScrub notCopyData noCheckpoint } } addTask(t, patches, m_materialManager->allMaterials()); } //______________________________________________________________________ // Record the global task monitoring attribute values into the data // warehouse. void SchedulerCommon::recordTaskMonitoring( const ProcessorGroup * /* */ , const PatchSubset * patches , const MaterialSubset * /*matls*/ , DataWarehouse * old_dw , DataWarehouse * new_dw ) { int matlIndex = 0; // For all of the patches record the tasking monitoring attribute value. for (int p = 0; p < patches->size(); p++) { const Patch* patch = patches->get(p); // Loop through the global (0) and local (1) tasks for (unsigned int i = 0; i < 2; ++i) { for (const auto &it : m_monitoring_tasks[i]) { PerPatch<double> value = m_monitoring_values[i][it.first][patch->getID()]; new_dw->put(value, it.second, matlIndex, patch); } } } } //______________________________________________________________________ // Sum the task monitoring attribute values void SchedulerCommon::sumTaskMonitoringValues( DetailedTask * dtask ) { if (!m_monitoring) { return; } const PatchSubset *patches = dtask->getPatches(); if (patches && patches->size()) { // Compute the cost on a per cell basis so the measured value can // be distributed proportionally by cells double num_cells = 0; for (int p = 0; p < patches->size(); p++) { const Patch* patch = patches->get(p); num_cells += patch->getNumExtraCells(); } double weight; // Compute the value on a per cell basis. if (m_monitoring_per_cell) { weight = num_cells; } // Compute the value on a per patch basis. else { weight = 1; } // Loop through the global (0) and local (1) tasks for (auto i = 0; i < 2; ++i) { for (const auto &it : m_monitoring_tasks[i]) { // Strip off the attribute name from the task name. std::string taskName = it.first; // For a local task strip off the attribute name. if (i == 1) { size_t found = taskName.find_last_of("::"); // std::string attribute = taskName.substr(found + 1); taskName = taskName.substr(0, found - 1); } // Is this task being monitored ? if ((i == 0) || // Global monitoring yes, otherwise check. (i == 1 && taskName == dtask->getTask()->getName())) { bool loadBalancerCost = false; double value; // Currently the monitoring is limited to the LoadBalancer cost, task exec time, and task wait time. if (it.first.find("LoadBalancerCost") != std::string::npos) { // The same code is in runTask of the specific scheduler // (MPIScheduler and UnifiedScheduler) to use the task // execution time which is then weighted by the number of // cells in CostModelForecaster::addContribution if (!dtask->getTask()->getHasSubScheduler() && !m_is_copy_data_timestep && dtask->getTask()->getType() != Task::Output) { value = dtask->task_exec_time() / num_cells; loadBalancerCost = true; } else { value = 0.0; } } else if (it.first.find("ExecTime") != std::string::npos) { value = dtask->task_exec_time() / weight; } else if (it.first.find("WaitTime") != std::string::npos) { value = dtask->task_wait_time() / weight; } else { value = 0.0; } if (value != 0.0) { // Loop through patches and add the contribution. for (int p = 0; p < patches->size(); ++p) { const Patch* patch = patches->get(p); if (m_monitoring_per_cell || loadBalancerCost) { m_monitoring_values[i][it.first][patch->getID()] += patch->getNumExtraCells() * value; } else { m_monitoring_values[i][it.first][patch->getID()] += value; } // A cheat ... the only time this task will come here is // after the value has been written (and the task is // completed) so the value can be overwritten. This // allows the monitoring to be monitored. if (dtask->getTask()->getName() == "SchedulerCommon::recordTaskMonitoring") { PerPatch<double> value = m_monitoring_values[i][it.first][patch->getID()]; this->getLastDW()->put(value, it.second, 0, patch); } } } } } } } }
37.660774
290
0.616873
[ "vector" ]
66e3f18f6360d5b43c90e0219f45da59926cff21
1,888
cpp
C++
vector_class_raw.cpp
ishansheth/ModernCpp-Exercises
c33d63ea9e6fe3115fbac51304a75292f32998cd
[ "MIT" ]
null
null
null
vector_class_raw.cpp
ishansheth/ModernCpp-Exercises
c33d63ea9e6fe3115fbac51304a75292f32998cd
[ "MIT" ]
null
null
null
vector_class_raw.cpp
ishansheth/ModernCpp-Exercises
c33d63ea9e6fe3115fbac51304a75292f32998cd
[ "MIT" ]
null
null
null
#include <iostream> #include <exception> #include <initializer_list> #include <algorithm> namespace preh { struct out_of_range : std::runtime_error { out_of_range() : std::runtime_error("Index out of range.") {} }; class vector { void index_check(unsigned i) const { if (i >= my_size) throw out_of_range(); } public: explicit vector(unsigned s) : my_size(s), data(new double[my_size]) { std::cout << "s-ctor\n"; } vector(std::initializer_list<double> il) : my_size(il.size()), data(new double[my_size]) { unsigned i= 0; for (double v : il) data[i++]= v; // *(data + i++)= v; } vector(const vector& that) : my_size(that.my_size), data(new double[my_size]) { using namespace std; copy(that.data, that.data + my_size, data); } ~vector() { delete[] data; } double& operator[](unsigned int i) & { index_check(i); return data[i]; } const double& operator[](unsigned int i) const& { index_check(i); return data[i]; } unsigned size() const { return my_size; } private: unsigned my_size; double* data; }; std::ostream& operator<<(std::ostream& os, const vector& v) { os << '['; if (v.size() > 0) os << v[0]; for (unsigned i= 1; i < v.size(); ++i) os << ',' << v[i]; return os << ']'; } double dot(const vector& v, const vector& w) { double res= 0.0; for (unsigned i= 0; i < v.size(); ++i) res+= v[i] * w[i]; return res; } } using namespace std; int main (int argc, char* argv[]) { preh::vector v(7); v[2]= 9; cout << "v[2] = " << v[2] << endl; cout << "v = " << v << endl; // preh::vector(3)[2]= 11; // Quatsch // cout << "dot(4, 4) = " << preh::dot(4, 4) << endl; // preh::vector w= 9; preh::vector w= {3, 5, 9, 2}, x(w); w[2]= 11; cout << "w = " << w << endl; cout << "x = " << x << endl; }
22.47619
97
0.545551
[ "vector" ]
66e4cef1a3b06c53bfc3bd40912de30d52ad40c2
2,053
cpp
C++
trace_analyzer/src/parser/htrace_parser/htrace_clock_detail_parser.cpp
openharmony-gitee-mirror/developtools_profiler
89bdc094fc84c40accb8c0e82dc8bbc7e85f0387
[ "Apache-2.0" ]
null
null
null
trace_analyzer/src/parser/htrace_parser/htrace_clock_detail_parser.cpp
openharmony-gitee-mirror/developtools_profiler
89bdc094fc84c40accb8c0e82dc8bbc7e85f0387
[ "Apache-2.0" ]
null
null
null
trace_analyzer/src/parser/htrace_parser/htrace_clock_detail_parser.cpp
openharmony-gitee-mirror/developtools_profiler
89bdc094fc84c40accb8c0e82dc8bbc7e85f0387
[ "Apache-2.0" ]
1
2021-09-13T11:17:44.000Z
2021-09-13T11:17:44.000Z
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "htrace_clock_detail_parser.h" #include "clock_filter.h" #include "htrace_event_parser.h" #include "measure_filter.h" #include "process_filter.h" #include "stat_filter.h" #include "symbols_filter.h" namespace SysTuning { namespace TraceStreamer { HtraceClockDetailParser::HtraceClockDetailParser(TraceDataCache* dataCache, const TraceStreamerFilters* ctx) : streamFilters_(ctx), traceDataCache_(dataCache) { for (auto i = 0; i < MEM_MAX; i++) { memNameDictMap_.insert( std::make_pair(static_cast<MemInfoType>(i), traceDataCache_->GetDataIndex(config_.memNameMap_.at(static_cast<MemInfoType>(i))))); } } HtraceClockDetailParser::~HtraceClockDetailParser() = default; void HtraceClockDetailParser::Parse(TracePluginResult& tracePacket) const { if (!tracePacket.clocks_detail_size()) { return; } std::vector<SnapShot> snapShot; for (int i = 0; i < tracePacket.clocks_detail_size(); i++) { auto clockInfo = tracePacket.mutable_clocks_detail(i); snapShot.push_back(SnapShot{static_cast<ClockId>(clockInfo->id()), clockInfo->time().tv_nsec() + clockInfo->time().tv_sec() * SEC_TO_NS}); streamFilters_->clockFilter_->AddClockSnapshot(snapShot); } streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_CLOCK_SYNC, STAT_EVENT_RECEIVED); } } // namespace TraceStreamer } // namespace SysTuning
40.254902
112
0.716025
[ "vector" ]
66ee57abef077b28569c46ca0efa533e97297fe3
2,133
cpp
C++
src/filter_anigif_overlay.cpp
folkertvanheusden/constatus
7b0c42a5017bf96afcb0f34c0d4987bdc40ef2e6
[ "Apache-2.0" ]
5
2021-07-15T11:39:25.000Z
2022-02-25T06:14:58.000Z
src/filter_anigif_overlay.cpp
folkertvanheusden/constatus
7b0c42a5017bf96afcb0f34c0d4987bdc40ef2e6
[ "Apache-2.0" ]
2
2021-09-27T11:13:42.000Z
2021-10-10T01:02:39.000Z
src/filter_anigif_overlay.cpp
folkertvanheusden/constatus
7b0c42a5017bf96afcb0f34c0d4987bdc40ef2e6
[ "Apache-2.0" ]
2
2021-06-11T09:19:47.000Z
2022-02-18T22:22:01.000Z
// (C) 2017-2021 by folkert van heusden, released under Apache License v2.0 #include "config.h" #if HAVE_IMAGICK == 1 #include <stddef.h> #include <stdio.h> #include <string> #include <cstring> #include <Magick++.h> #include "error.h" #include "filter_anigif_overlay.h" #include "picio.h" #include "log.h" filter_anigif_overlay::filter_anigif_overlay(const std::string & file, const pos_t & pos) : pos(pos) { Magick::InitializeMagick(nullptr); std::vector<Magick::Image> tempList; Magick::readImages(&tempList, file.c_str()); Magick::coalesceImages(&imageList, tempList.begin(), tempList.end()); log(LL_INFO, "%zu pages in animation %s", imageList.size(), file.c_str()); } filter_anigif_overlay::~filter_anigif_overlay() { } void filter_anigif_overlay::apply(instance *const i, interface *const specific_int, const uint64_t ts, const int w, const int h, const uint8_t *const prev, uint8_t *const in_out) { Magick::Image & m = imageList.at((ts / 100000) % imageList.size()); int this_w = m.columns(); int this_h = m.rows(); auto p = pos_to_xy(pos, this_w, this_h, w, h); int work_x = std::get<0>(p); int work_y = std::get<1>(p); int cw = std::min(this_w, w); int ch = std::min(this_h, h); if (cw <= 0 || ch <= 0) return; int ex = std::min(w - work_x, cw); int ey = std::min(h - work_y, ch); const Magick::PixelPacket *pixels = m.getConstPixels(0, 0, this_w, this_h); for(int y=0; y<ey; y++) { const int ty = y + work_y; if (ty < 0) continue; if (ty >= h) break; for(int x=0; x<ex; x++) { const int tx = x + work_x; if (tx < 0) continue; if (tx >= w) break; const int in_offset = y * this_w + x; const int out_offset = ty * w * 3 + tx * 3; int opacity = pixels[in_offset].opacity; in_out[out_offset + 0] = (in_out[out_offset + 0] * opacity + pixels[in_offset].red * (65535 - opacity)) / 65536; in_out[out_offset + 1] = (in_out[out_offset + 1] * opacity + pixels[in_offset].green * (65535 - opacity)) / 65536; in_out[out_offset + 2] = (in_out[out_offset + 2] * opacity + pixels[in_offset].blue * (65535 - opacity)) / 65536; } } } #endif
26.333333
178
0.649789
[ "vector" ]
66eea01913f44a034dccca05007798f39b3cae0d
3,017
hpp
C++
code/source/game/worldentity_macros.hpp
crafn/clover
586acdbcdb34c3550858af125e9bb4a6300343fe
[ "MIT" ]
12
2015-01-12T00:19:20.000Z
2021-08-05T10:47:20.000Z
code/source/game/worldentity_macros.hpp
crafn/clover
586acdbcdb34c3550858af125e9bb4a6300343fe
[ "MIT" ]
null
null
null
code/source/game/worldentity_macros.hpp
crafn/clover
586acdbcdb34c3550858af125e9bb4a6300343fe
[ "MIT" ]
null
null
null
#ifndef CLOVER_GAME_WORLDENTITY_MACROS_HPP #define CLOVER_GAME_WORLDENTITY_MACROS_HPP #include "build.hpp" namespace clover { namespace game { /// @todo Remove whole legacy junk file class WEInfo; #define DECLARE_WE(typename_, basename_) \ protected: \ typedef basename_ ## WE BaseClass; \ typedef typename_ ## WE ThisClass; \ virtual void onCreate(const WEInfo& info); \ void create(); \ void destroy(); \ public: \ static WEInfo generateWEInfo(); \ typename_ ## WE(); \ virtual ~typename_ ## WE(); \ void initDataDesc(); \ #define IMPLEMENT_WE(typename_) \ typename_ ## WE::typename_ ## WE(){ \ weType= typename_; \ } \ typename_ ## WE::~typename_ ## WE(){ \ destroy(); \ } \ void typename_ ## WE::onCreate(const WEInfo& i){ \ BaseClass::onCreate(i); \ ensure(info); \ initDataDesc(); \ create(); \ } #define BEGIN_WE_INFO(typename_) \ WEInfo typename_##WE::generateWEInfo(){ \ WEInfo info= BaseClass::generateWEInfo(); #define DEF_WE_DEFAULT_ICON(model) \ info.icon.defaultModel= &global::g_env.resCache->getResource<visual::Model>(model); #define DEF_WE_PICKABLE(is_pickable) \ info.pickable= is_pickable; #define END_WE_INFO() \ return info; } #define BEGIN_WE_DATADESC(typename_) \ void typename_##WE::initDataDesc(){ \ #define DEF_WE_SAVE_FIELD_DYNARRAY( array_name, array_max_size ) \ saveFields.add(array_name, util::Str8(#array_name), array_max_size); #define DEF_WE_SAVE_FIELD( variable_name ) \ saveFields.add(variable_name, util::Str8(#variable_name)); #define DEF_WE_SET_FUNC( variable_name, method ) \ saveFields.getFieldByName( util::Str8(#variable_name) )-> \ setChangeFunc<decltype(variable_name)>(std::bind(&ThisClass::method, this, std::placeholders::_1)); #define DEF_WE_STRICT_DEPENDENCY_DYNARRAY( handle, array_max_size ) \ for (auto &m : handle) m.setStrict(*this); \ saveFields.add( handle, \ util::Str8(#handle), array_max_size); #define DEF_WE_STRICT_DEPENDENCY( handle ) \ handle.setStrict(*this); \ saveFields.add( handle, \ util::Str8(#handle)); #define DEF_WE_LOOSE_DEPENDENCY_DYNARRAY( handle, array_max_size ) \ saveFields.add( handle, \ util::Str8(#handle), array_max_size); \ #define DEF_WE_LOOSE_DEPENDENCY( handle ) \ saveFields.add( handle, \ util::Str8(#handle)); \ #define DEF_WE_SAVE_FIELD_SETM( variable_name, set_method ) \ DEF_WE_SAVE_FIELD( variable_name ) DEF_WE_SET_FUNC( variable_name, set_method ) #define DEF_WE_SAVE_FIELD_DYNARRAY_SETM( array_name, array_size, set_method ) \ DEF_WE_SAVE_FIELD_DYNARRAY( array_name, array_size ) DEF_WE_SET_FUNC( array_name, set_method ) #define END_WE_DATADESC() } } // game } // clover #endif // CLOVER_GAME_WORLDENTITY_MACROS_HPP
28.462264
102
0.657275
[ "model" ]
66f097091e833d4e006ae32bce6d370c0e390cec
9,600
cc
C++
tensorflow/core/kernels/ragged_range_op_test.cc
abhaikollara/tensorflow
4f96df3659696990cb34d0ad07dc67843c4225a9
[ "Apache-2.0" ]
848
2019-12-03T00:16:17.000Z
2022-03-31T22:53:17.000Z
tensorflow/core/kernels/ragged_range_op_test.cc
abhaikollara/tensorflow
4f96df3659696990cb34d0ad07dc67843c4225a9
[ "Apache-2.0" ]
656
2019-12-03T00:48:46.000Z
2022-03-31T18:41:54.000Z
tensorflow/core/kernels/ragged_range_op_test.cc
abhaikollara/tensorflow
4f96df3659696990cb34d0ad07dc67843c4225a9
[ "Apache-2.0" ]
506
2019-12-03T00:46:26.000Z
2022-03-30T10:34:56.000Z
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/framework/fake_input.h" #include "tensorflow/core/framework/node_def_builder.h" #include "tensorflow/core/framework/shape_inference.h" #include "tensorflow/core/framework/shape_inference_testutil.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/framework/tensor_shape.h" #include "tensorflow/core/kernels/ops_testutil.h" #include "tensorflow/core/framework/tensor_testutil.h" #include "tensorflow/core/platform/test.h" namespace tensorflow { namespace { class RaggedRangeOpTest : public ::tensorflow::OpsTestBase { protected: // Indices of output tensors. static constexpr int kSplitsOutput = 0; static constexpr int kValuesOutput = 1; // Builds the tensorflow test graph for the RaggedRange op. template <typename T> void BuildRaggedRangeGraph() { const auto& dtype = DataTypeToEnum<T>::v(); TF_ASSERT_OK(NodeDefBuilder("tested_op", "RaggedRange") .Input(FakeInput(dtype)) // starts .Input(FakeInput(dtype)) // limits .Input(FakeInput(dtype)) // deltas .Attr("T", dtype) .Finalize(node_def())); TF_ASSERT_OK(InitOp()); } }; TEST_F(RaggedRangeOpTest, IntValues) { BuildRaggedRangeGraph<int>(); AddInputFromArray<int>(TensorShape({4}), {0, 5, 8, 5}); // starts AddInputFromArray<int>(TensorShape({4}), {8, 7, 8, 1}); // limits AddInputFromArray<int>(TensorShape({4}), {2, 1, 1, -1}); // deltas TF_ASSERT_OK(RunOpKernel()); // Expected: [[0, 2, 4, 6], [5, 6], [], [5, 4, 3, 2]] test::ExpectTensorEqual<int64>(*GetOutput(kSplitsOutput), test::AsTensor<int64>({0, 4, 6, 6, 10})); test::ExpectTensorEqual<int>( *GetOutput(kValuesOutput), test::AsTensor<int>({0, 2, 4, 6, 5, 6, 5, 4, 3, 2})); } TEST_F(RaggedRangeOpTest, FloatValues) { BuildRaggedRangeGraph<float>(); AddInputFromArray<float>(TensorShape({4}), {0, 5, 8, 5}); // starts AddInputFromArray<float>(TensorShape({4}), {8, 7, 8, 1}); // limits AddInputFromArray<float>(TensorShape({4}), {2, 1, 1, -1}); // deltas TF_ASSERT_OK(RunOpKernel()); // Expected: [[0, 2, 4, 6], [5, 6], [], [5, 4, 3, 2]] test::ExpectTensorEqual<int64>(*GetOutput(kSplitsOutput), test::AsTensor<int64>({0, 4, 6, 6, 10})); test::ExpectTensorNear<float>( *GetOutput(kValuesOutput), test::AsTensor<float>({0, 2, 4, 6, 5, 6, 5, 4, 3, 2}), 0.1); } TEST_F(RaggedRangeOpTest, BroadcastDeltas) { BuildRaggedRangeGraph<int>(); AddInputFromArray<int>(TensorShape({3}), {0, 5, 8}); // starts AddInputFromArray<int>(TensorShape({3}), {8, 7, 8}); // limits AddInputFromArray<int>(TensorShape({}), {1}); // deltas TF_ASSERT_OK(RunOpKernel()); // Expected: [[0, 1, 2, 3, 4, 5, 6, 7], [5, 6], []] test::ExpectTensorEqual<int64>(*GetOutput(kSplitsOutput), test::AsTensor<int64>({0, 8, 10, 10})); test::ExpectTensorEqual<int>( *GetOutput(kValuesOutput), test::AsTensor<int>({0, 1, 2, 3, 4, 5, 6, 7, 5, 6})); } TEST_F(RaggedRangeOpTest, BroadcastLimitsAndDeltas) { BuildRaggedRangeGraph<int>(); AddInputFromArray<int>(TensorShape({}), {0}); // starts AddInputFromArray<int>(TensorShape({3}), {3, 0, 2}); // limits AddInputFromArray<int>(TensorShape({}), {1}); // deltas TF_ASSERT_OK(RunOpKernel()); // Expected: [[0, 1, 2], [], [0, 1]] test::ExpectTensorEqual<int64>(*GetOutput(kSplitsOutput), test::AsTensor<int64>({0, 3, 3, 5})); test::ExpectTensorEqual<int>(*GetOutput(kValuesOutput), test::AsTensor<int>({0, 1, 2, 0, 1})); } TEST_F(RaggedRangeOpTest, BroadcastStartsAndLimits) { BuildRaggedRangeGraph<int>(); AddInputFromArray<int>(TensorShape({}), {0}); // starts AddInputFromArray<int>(TensorShape({}), {12}); // limits AddInputFromArray<int>(TensorShape({3}), {3, 4, 5}); // deltas TF_ASSERT_OK(RunOpKernel()); // Expected: [[0, 3, 6, 9], [0, 4, 8], [0, 5, 10]]] test::ExpectTensorEqual<int64>(*GetOutput(kSplitsOutput), test::AsTensor<int64>({0, 4, 7, 10})); test::ExpectTensorEqual<int>( *GetOutput(kValuesOutput), test::AsTensor<int>({0, 3, 6, 9, 0, 4, 8, 0, 5, 10})); } TEST_F(RaggedRangeOpTest, AllScalarInputs) { BuildRaggedRangeGraph<int>(); AddInputFromArray<int>(TensorShape({}), {0}); // starts AddInputFromArray<int>(TensorShape({}), {5}); // limits AddInputFromArray<int>(TensorShape({}), {1}); // deltas TF_ASSERT_OK(RunOpKernel()); // Expected: [[0, 1, 2, 3, 4] test::ExpectTensorEqual<int64>(*GetOutput(kSplitsOutput), test::AsTensor<int64>({0, 5})); test::ExpectTensorEqual<int>(*GetOutput(kValuesOutput), test::AsTensor<int>({0, 1, 2, 3, 4})); } TEST_F(RaggedRangeOpTest, InvalidArgsStarts) { BuildRaggedRangeGraph<int>(); AddInputFromArray<int>(TensorShape({4, 1}), {0, 5, 8, 5}); // starts AddInputFromArray<int>(TensorShape({4}), {8, 7, 8, 1}); // limits AddInputFromArray<int>(TensorShape({4}), {2, 1, 1, -1}); // deltas EXPECT_EQ("starts must be a scalar or vector", RunOpKernel().error_message()); } TEST_F(RaggedRangeOpTest, InvalidArgsLimits) { BuildRaggedRangeGraph<int>(); AddInputFromArray<int>(TensorShape({4}), {0, 5, 8, 5}); // starts AddInputFromArray<int>(TensorShape({4, 1}), {8, 7, 8, 1}); // limits AddInputFromArray<int>(TensorShape({4}), {2, 1, 1, -1}); // deltas EXPECT_EQ("limits must be a scalar or vector", RunOpKernel().error_message()); } TEST_F(RaggedRangeOpTest, InvalidArgsDeltas) { BuildRaggedRangeGraph<int>(); AddInputFromArray<int>(TensorShape({4}), {0, 5, 8, 5}); // starts AddInputFromArray<int>(TensorShape({4}), {8, 7, 8, 1}); // limits AddInputFromArray<int>(TensorShape({4, 1}), {2, 1, 1, -1}); // deltas EXPECT_EQ("deltas must be a scalar or vector", RunOpKernel().error_message()); } TEST_F(RaggedRangeOpTest, InvalidArgsShapeMismatch) { BuildRaggedRangeGraph<int>(); AddInputFromArray<int>(TensorShape({4}), {0, 5, 8, 5}); // starts AddInputFromArray<int>(TensorShape({3}), {7, 8, 1}); // limits AddInputFromArray<int>(TensorShape({4}), {2, 1, 1, -1}); // deltas EXPECT_EQ("starts, limits, and deltas must have the same shape", RunOpKernel().error_message()); } TEST_F(RaggedRangeOpTest, InvalidArgsZeroDelta) { BuildRaggedRangeGraph<int>(); AddInputFromArray<int>(TensorShape({4}), {0, 5, 8, 5}); // starts AddInputFromArray<int>(TensorShape({4}), {7, 8, 8, 1}); // limits AddInputFromArray<int>(TensorShape({4}), {2, 1, 0, -1}); // deltas EXPECT_EQ("Requires delta != 0", RunOpKernel().error_message()); } TEST_F(RaggedRangeOpTest, EmptyRangePositiveDelta) { BuildRaggedRangeGraph<int>(); AddInputFromArray<int>(TensorShape({2}), {0, 5}); // starts AddInputFromArray<int>(TensorShape({2}), {5, 0}); // limits AddInputFromArray<int>(TensorShape({}), {2}); // deltas TF_ASSERT_OK(RunOpKernel()); // Expected: [[0, 2, 4], []] test::ExpectTensorEqual<int64>(*GetOutput(kSplitsOutput), test::AsTensor<int64>({0, 3, 3})); test::ExpectTensorEqual<int>(*GetOutput(kValuesOutput), test::AsTensor<int>({0, 2, 4})); } TEST_F(RaggedRangeOpTest, EmptyRangeNegativeDelta) { BuildRaggedRangeGraph<int>(); AddInputFromArray<int>(TensorShape({2}), {0, 5}); // starts AddInputFromArray<int>(TensorShape({2}), {5, 0}); // limits AddInputFromArray<int>(TensorShape({}), {-2}); // deltas TF_ASSERT_OK(RunOpKernel()); // Expected: [[], [5, 3, 1]] test::ExpectTensorEqual<int64>(*GetOutput(kSplitsOutput), test::AsTensor<int64>({0, 0, 3})); test::ExpectTensorEqual<int>(*GetOutput(kValuesOutput), test::AsTensor<int>({5, 3, 1})); } TEST_F(RaggedRangeOpTest, ShapeFn) { // RaggedRange(starts, limits, deltas) -> [splits, values] ShapeInferenceTestOp op("RaggedRange"); INFER_OK(op, "?;?;?", "[?];[?]"); INFER_OK(op, "[3];[3];[3]", "[4];[?]"); INFER_OK(op, "[3];[3];[]", "[4];[?]"); // broadcast deltas INFER_OK(op, "[3];[];[3]", "[4];[?]"); // broadcast limits INFER_OK(op, "[];[3];[3]", "[4];[?]"); // broadcast starts INFER_OK(op, "[];[];[]", "[2];[?]"); // degenerate case: all scalar inputs INFER_ERROR("Shape must be at most rank 1 but is rank 2", op, "[5,5];[5];[5]"); INFER_ERROR("Shape must be at most rank 1 but is rank 2", op, "[5];[5,5];[5]"); INFER_ERROR("Shape must be at most rank 1 but is rank 2", op, "[5];[5];[5,5]"); INFER_ERROR("Dimensions must be equal, but are 4 and 3", op, "[3];[4];[3]"); } } // namespace } // namespace tensorflow
42.666667
80
0.619271
[ "shape", "vector" ]
66f5788a858d501aa8d5e32e09a7f10c7d381df8
26,564
cpp
C++
clients/cpp-qt-qhttpengine-server/generated/server/src/models/OAIFreeStyleProject.cpp
cliffano/jenkins-api-clients-generator
522d02b3a130a29471df5ec1d3d22c822b3d0813
[ "MIT" ]
null
null
null
clients/cpp-qt-qhttpengine-server/generated/server/src/models/OAIFreeStyleProject.cpp
cliffano/jenkins-api-clients-generator
522d02b3a130a29471df5ec1d3d22c822b3d0813
[ "MIT" ]
null
null
null
clients/cpp-qt-qhttpengine-server/generated/server/src/models/OAIFreeStyleProject.cpp
cliffano/jenkins-api-clients-generator
522d02b3a130a29471df5ec1d3d22c822b3d0813
[ "MIT" ]
null
null
null
/** * Swaggy Jenkins * Jenkins API clients generated from Swagger / Open API specification * * The version of the OpenAPI document: 1.1.2-pre.0 * Contact: blah@cliffano.com * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ #include "OAIFreeStyleProject.h" #include <QDebug> #include <QJsonArray> #include <QJsonDocument> #include <QObject> #include "OAIHelpers.h" namespace OpenAPI { OAIFreeStyleProject::OAIFreeStyleProject(QString json) { this->initializeModel(); this->fromJson(json); } OAIFreeStyleProject::OAIFreeStyleProject() { this->initializeModel(); } OAIFreeStyleProject::~OAIFreeStyleProject() {} void OAIFreeStyleProject::initializeModel() { m__class_isSet = false; m__class_isValid = false; m_name_isSet = false; m_name_isValid = false; m_url_isSet = false; m_url_isValid = false; m_color_isSet = false; m_color_isValid = false; m_actions_isSet = false; m_actions_isValid = false; m_description_isSet = false; m_description_isValid = false; m_display_name_isSet = false; m_display_name_isValid = false; m_display_name_or_null_isSet = false; m_display_name_or_null_isValid = false; m_full_display_name_isSet = false; m_full_display_name_isValid = false; m_full_name_isSet = false; m_full_name_isValid = false; m_buildable_isSet = false; m_buildable_isValid = false; m_builds_isSet = false; m_builds_isValid = false; m_first_build_isSet = false; m_first_build_isValid = false; m_health_report_isSet = false; m_health_report_isValid = false; m_in_queue_isSet = false; m_in_queue_isValid = false; m_keep_dependencies_isSet = false; m_keep_dependencies_isValid = false; m_last_build_isSet = false; m_last_build_isValid = false; m_last_completed_build_isSet = false; m_last_completed_build_isValid = false; m_last_failed_build_isSet = false; m_last_failed_build_isValid = false; m_last_stable_build_isSet = false; m_last_stable_build_isValid = false; m_last_successful_build_isSet = false; m_last_successful_build_isValid = false; m_last_unstable_build_isSet = false; m_last_unstable_build_isValid = false; m_last_unsuccessful_build_isSet = false; m_last_unsuccessful_build_isValid = false; m_next_build_number_isSet = false; m_next_build_number_isValid = false; m_queue_item_isSet = false; m_queue_item_isValid = false; m_concurrent_build_isSet = false; m_concurrent_build_isValid = false; m_scm_isSet = false; m_scm_isValid = false; } void OAIFreeStyleProject::fromJson(QString jsonString) { QByteArray array(jsonString.toStdString().c_str()); QJsonDocument doc = QJsonDocument::fromJson(array); QJsonObject jsonObject = doc.object(); this->fromJsonObject(jsonObject); } void OAIFreeStyleProject::fromJsonObject(QJsonObject json) { m__class_isValid = ::OpenAPI::fromJsonValue(_class, json[QString("_class")]); m__class_isSet = !json[QString("_class")].isNull() && m__class_isValid; m_name_isValid = ::OpenAPI::fromJsonValue(name, json[QString("name")]); m_name_isSet = !json[QString("name")].isNull() && m_name_isValid; m_url_isValid = ::OpenAPI::fromJsonValue(url, json[QString("url")]); m_url_isSet = !json[QString("url")].isNull() && m_url_isValid; m_color_isValid = ::OpenAPI::fromJsonValue(color, json[QString("color")]); m_color_isSet = !json[QString("color")].isNull() && m_color_isValid; m_actions_isValid = ::OpenAPI::fromJsonValue(actions, json[QString("actions")]); m_actions_isSet = !json[QString("actions")].isNull() && m_actions_isValid; m_description_isValid = ::OpenAPI::fromJsonValue(description, json[QString("description")]); m_description_isSet = !json[QString("description")].isNull() && m_description_isValid; m_display_name_isValid = ::OpenAPI::fromJsonValue(display_name, json[QString("displayName")]); m_display_name_isSet = !json[QString("displayName")].isNull() && m_display_name_isValid; m_display_name_or_null_isValid = ::OpenAPI::fromJsonValue(display_name_or_null, json[QString("displayNameOrNull")]); m_display_name_or_null_isSet = !json[QString("displayNameOrNull")].isNull() && m_display_name_or_null_isValid; m_full_display_name_isValid = ::OpenAPI::fromJsonValue(full_display_name, json[QString("fullDisplayName")]); m_full_display_name_isSet = !json[QString("fullDisplayName")].isNull() && m_full_display_name_isValid; m_full_name_isValid = ::OpenAPI::fromJsonValue(full_name, json[QString("fullName")]); m_full_name_isSet = !json[QString("fullName")].isNull() && m_full_name_isValid; m_buildable_isValid = ::OpenAPI::fromJsonValue(buildable, json[QString("buildable")]); m_buildable_isSet = !json[QString("buildable")].isNull() && m_buildable_isValid; m_builds_isValid = ::OpenAPI::fromJsonValue(builds, json[QString("builds")]); m_builds_isSet = !json[QString("builds")].isNull() && m_builds_isValid; m_first_build_isValid = ::OpenAPI::fromJsonValue(first_build, json[QString("firstBuild")]); m_first_build_isSet = !json[QString("firstBuild")].isNull() && m_first_build_isValid; m_health_report_isValid = ::OpenAPI::fromJsonValue(health_report, json[QString("healthReport")]); m_health_report_isSet = !json[QString("healthReport")].isNull() && m_health_report_isValid; m_in_queue_isValid = ::OpenAPI::fromJsonValue(in_queue, json[QString("inQueue")]); m_in_queue_isSet = !json[QString("inQueue")].isNull() && m_in_queue_isValid; m_keep_dependencies_isValid = ::OpenAPI::fromJsonValue(keep_dependencies, json[QString("keepDependencies")]); m_keep_dependencies_isSet = !json[QString("keepDependencies")].isNull() && m_keep_dependencies_isValid; m_last_build_isValid = ::OpenAPI::fromJsonValue(last_build, json[QString("lastBuild")]); m_last_build_isSet = !json[QString("lastBuild")].isNull() && m_last_build_isValid; m_last_completed_build_isValid = ::OpenAPI::fromJsonValue(last_completed_build, json[QString("lastCompletedBuild")]); m_last_completed_build_isSet = !json[QString("lastCompletedBuild")].isNull() && m_last_completed_build_isValid; m_last_failed_build_isValid = ::OpenAPI::fromJsonValue(last_failed_build, json[QString("lastFailedBuild")]); m_last_failed_build_isSet = !json[QString("lastFailedBuild")].isNull() && m_last_failed_build_isValid; m_last_stable_build_isValid = ::OpenAPI::fromJsonValue(last_stable_build, json[QString("lastStableBuild")]); m_last_stable_build_isSet = !json[QString("lastStableBuild")].isNull() && m_last_stable_build_isValid; m_last_successful_build_isValid = ::OpenAPI::fromJsonValue(last_successful_build, json[QString("lastSuccessfulBuild")]); m_last_successful_build_isSet = !json[QString("lastSuccessfulBuild")].isNull() && m_last_successful_build_isValid; m_last_unstable_build_isValid = ::OpenAPI::fromJsonValue(last_unstable_build, json[QString("lastUnstableBuild")]); m_last_unstable_build_isSet = !json[QString("lastUnstableBuild")].isNull() && m_last_unstable_build_isValid; m_last_unsuccessful_build_isValid = ::OpenAPI::fromJsonValue(last_unsuccessful_build, json[QString("lastUnsuccessfulBuild")]); m_last_unsuccessful_build_isSet = !json[QString("lastUnsuccessfulBuild")].isNull() && m_last_unsuccessful_build_isValid; m_next_build_number_isValid = ::OpenAPI::fromJsonValue(next_build_number, json[QString("nextBuildNumber")]); m_next_build_number_isSet = !json[QString("nextBuildNumber")].isNull() && m_next_build_number_isValid; m_queue_item_isValid = ::OpenAPI::fromJsonValue(queue_item, json[QString("queueItem")]); m_queue_item_isSet = !json[QString("queueItem")].isNull() && m_queue_item_isValid; m_concurrent_build_isValid = ::OpenAPI::fromJsonValue(concurrent_build, json[QString("concurrentBuild")]); m_concurrent_build_isSet = !json[QString("concurrentBuild")].isNull() && m_concurrent_build_isValid; m_scm_isValid = ::OpenAPI::fromJsonValue(scm, json[QString("scm")]); m_scm_isSet = !json[QString("scm")].isNull() && m_scm_isValid; } QString OAIFreeStyleProject::asJson() const { QJsonObject obj = this->asJsonObject(); QJsonDocument doc(obj); QByteArray bytes = doc.toJson(); return QString(bytes); } QJsonObject OAIFreeStyleProject::asJsonObject() const { QJsonObject obj; if (m__class_isSet) { obj.insert(QString("_class"), ::OpenAPI::toJsonValue(_class)); } if (m_name_isSet) { obj.insert(QString("name"), ::OpenAPI::toJsonValue(name)); } if (m_url_isSet) { obj.insert(QString("url"), ::OpenAPI::toJsonValue(url)); } if (m_color_isSet) { obj.insert(QString("color"), ::OpenAPI::toJsonValue(color)); } if (actions.size() > 0) { obj.insert(QString("actions"), ::OpenAPI::toJsonValue(actions)); } if (m_description_isSet) { obj.insert(QString("description"), ::OpenAPI::toJsonValue(description)); } if (m_display_name_isSet) { obj.insert(QString("displayName"), ::OpenAPI::toJsonValue(display_name)); } if (m_display_name_or_null_isSet) { obj.insert(QString("displayNameOrNull"), ::OpenAPI::toJsonValue(display_name_or_null)); } if (m_full_display_name_isSet) { obj.insert(QString("fullDisplayName"), ::OpenAPI::toJsonValue(full_display_name)); } if (m_full_name_isSet) { obj.insert(QString("fullName"), ::OpenAPI::toJsonValue(full_name)); } if (m_buildable_isSet) { obj.insert(QString("buildable"), ::OpenAPI::toJsonValue(buildable)); } if (builds.size() > 0) { obj.insert(QString("builds"), ::OpenAPI::toJsonValue(builds)); } if (first_build.isSet()) { obj.insert(QString("firstBuild"), ::OpenAPI::toJsonValue(first_build)); } if (health_report.size() > 0) { obj.insert(QString("healthReport"), ::OpenAPI::toJsonValue(health_report)); } if (m_in_queue_isSet) { obj.insert(QString("inQueue"), ::OpenAPI::toJsonValue(in_queue)); } if (m_keep_dependencies_isSet) { obj.insert(QString("keepDependencies"), ::OpenAPI::toJsonValue(keep_dependencies)); } if (last_build.isSet()) { obj.insert(QString("lastBuild"), ::OpenAPI::toJsonValue(last_build)); } if (last_completed_build.isSet()) { obj.insert(QString("lastCompletedBuild"), ::OpenAPI::toJsonValue(last_completed_build)); } if (m_last_failed_build_isSet) { obj.insert(QString("lastFailedBuild"), ::OpenAPI::toJsonValue(last_failed_build)); } if (last_stable_build.isSet()) { obj.insert(QString("lastStableBuild"), ::OpenAPI::toJsonValue(last_stable_build)); } if (last_successful_build.isSet()) { obj.insert(QString("lastSuccessfulBuild"), ::OpenAPI::toJsonValue(last_successful_build)); } if (m_last_unstable_build_isSet) { obj.insert(QString("lastUnstableBuild"), ::OpenAPI::toJsonValue(last_unstable_build)); } if (m_last_unsuccessful_build_isSet) { obj.insert(QString("lastUnsuccessfulBuild"), ::OpenAPI::toJsonValue(last_unsuccessful_build)); } if (m_next_build_number_isSet) { obj.insert(QString("nextBuildNumber"), ::OpenAPI::toJsonValue(next_build_number)); } if (m_queue_item_isSet) { obj.insert(QString("queueItem"), ::OpenAPI::toJsonValue(queue_item)); } if (m_concurrent_build_isSet) { obj.insert(QString("concurrentBuild"), ::OpenAPI::toJsonValue(concurrent_build)); } if (scm.isSet()) { obj.insert(QString("scm"), ::OpenAPI::toJsonValue(scm)); } return obj; } QString OAIFreeStyleProject::getClass() const { return _class; } void OAIFreeStyleProject::setClass(const QString &_class) { this->_class = _class; this->m__class_isSet = true; } bool OAIFreeStyleProject::is__class_Set() const{ return m__class_isSet; } bool OAIFreeStyleProject::is__class_Valid() const{ return m__class_isValid; } QString OAIFreeStyleProject::getName() const { return name; } void OAIFreeStyleProject::setName(const QString &name) { this->name = name; this->m_name_isSet = true; } bool OAIFreeStyleProject::is_name_Set() const{ return m_name_isSet; } bool OAIFreeStyleProject::is_name_Valid() const{ return m_name_isValid; } QString OAIFreeStyleProject::getUrl() const { return url; } void OAIFreeStyleProject::setUrl(const QString &url) { this->url = url; this->m_url_isSet = true; } bool OAIFreeStyleProject::is_url_Set() const{ return m_url_isSet; } bool OAIFreeStyleProject::is_url_Valid() const{ return m_url_isValid; } QString OAIFreeStyleProject::getColor() const { return color; } void OAIFreeStyleProject::setColor(const QString &color) { this->color = color; this->m_color_isSet = true; } bool OAIFreeStyleProject::is_color_Set() const{ return m_color_isSet; } bool OAIFreeStyleProject::is_color_Valid() const{ return m_color_isValid; } QList<OAIFreeStyleProjectactions> OAIFreeStyleProject::getActions() const { return actions; } void OAIFreeStyleProject::setActions(const QList<OAIFreeStyleProjectactions> &actions) { this->actions = actions; this->m_actions_isSet = true; } bool OAIFreeStyleProject::is_actions_Set() const{ return m_actions_isSet; } bool OAIFreeStyleProject::is_actions_Valid() const{ return m_actions_isValid; } QString OAIFreeStyleProject::getDescription() const { return description; } void OAIFreeStyleProject::setDescription(const QString &description) { this->description = description; this->m_description_isSet = true; } bool OAIFreeStyleProject::is_description_Set() const{ return m_description_isSet; } bool OAIFreeStyleProject::is_description_Valid() const{ return m_description_isValid; } QString OAIFreeStyleProject::getDisplayName() const { return display_name; } void OAIFreeStyleProject::setDisplayName(const QString &display_name) { this->display_name = display_name; this->m_display_name_isSet = true; } bool OAIFreeStyleProject::is_display_name_Set() const{ return m_display_name_isSet; } bool OAIFreeStyleProject::is_display_name_Valid() const{ return m_display_name_isValid; } QString OAIFreeStyleProject::getDisplayNameOrNull() const { return display_name_or_null; } void OAIFreeStyleProject::setDisplayNameOrNull(const QString &display_name_or_null) { this->display_name_or_null = display_name_or_null; this->m_display_name_or_null_isSet = true; } bool OAIFreeStyleProject::is_display_name_or_null_Set() const{ return m_display_name_or_null_isSet; } bool OAIFreeStyleProject::is_display_name_or_null_Valid() const{ return m_display_name_or_null_isValid; } QString OAIFreeStyleProject::getFullDisplayName() const { return full_display_name; } void OAIFreeStyleProject::setFullDisplayName(const QString &full_display_name) { this->full_display_name = full_display_name; this->m_full_display_name_isSet = true; } bool OAIFreeStyleProject::is_full_display_name_Set() const{ return m_full_display_name_isSet; } bool OAIFreeStyleProject::is_full_display_name_Valid() const{ return m_full_display_name_isValid; } QString OAIFreeStyleProject::getFullName() const { return full_name; } void OAIFreeStyleProject::setFullName(const QString &full_name) { this->full_name = full_name; this->m_full_name_isSet = true; } bool OAIFreeStyleProject::is_full_name_Set() const{ return m_full_name_isSet; } bool OAIFreeStyleProject::is_full_name_Valid() const{ return m_full_name_isValid; } bool OAIFreeStyleProject::isBuildable() const { return buildable; } void OAIFreeStyleProject::setBuildable(const bool &buildable) { this->buildable = buildable; this->m_buildable_isSet = true; } bool OAIFreeStyleProject::is_buildable_Set() const{ return m_buildable_isSet; } bool OAIFreeStyleProject::is_buildable_Valid() const{ return m_buildable_isValid; } QList<OAIFreeStyleBuild> OAIFreeStyleProject::getBuilds() const { return builds; } void OAIFreeStyleProject::setBuilds(const QList<OAIFreeStyleBuild> &builds) { this->builds = builds; this->m_builds_isSet = true; } bool OAIFreeStyleProject::is_builds_Set() const{ return m_builds_isSet; } bool OAIFreeStyleProject::is_builds_Valid() const{ return m_builds_isValid; } OAIFreeStyleBuild OAIFreeStyleProject::getFirstBuild() const { return first_build; } void OAIFreeStyleProject::setFirstBuild(const OAIFreeStyleBuild &first_build) { this->first_build = first_build; this->m_first_build_isSet = true; } bool OAIFreeStyleProject::is_first_build_Set() const{ return m_first_build_isSet; } bool OAIFreeStyleProject::is_first_build_Valid() const{ return m_first_build_isValid; } QList<OAIFreeStyleProjecthealthReport> OAIFreeStyleProject::getHealthReport() const { return health_report; } void OAIFreeStyleProject::setHealthReport(const QList<OAIFreeStyleProjecthealthReport> &health_report) { this->health_report = health_report; this->m_health_report_isSet = true; } bool OAIFreeStyleProject::is_health_report_Set() const{ return m_health_report_isSet; } bool OAIFreeStyleProject::is_health_report_Valid() const{ return m_health_report_isValid; } bool OAIFreeStyleProject::isInQueue() const { return in_queue; } void OAIFreeStyleProject::setInQueue(const bool &in_queue) { this->in_queue = in_queue; this->m_in_queue_isSet = true; } bool OAIFreeStyleProject::is_in_queue_Set() const{ return m_in_queue_isSet; } bool OAIFreeStyleProject::is_in_queue_Valid() const{ return m_in_queue_isValid; } bool OAIFreeStyleProject::isKeepDependencies() const { return keep_dependencies; } void OAIFreeStyleProject::setKeepDependencies(const bool &keep_dependencies) { this->keep_dependencies = keep_dependencies; this->m_keep_dependencies_isSet = true; } bool OAIFreeStyleProject::is_keep_dependencies_Set() const{ return m_keep_dependencies_isSet; } bool OAIFreeStyleProject::is_keep_dependencies_Valid() const{ return m_keep_dependencies_isValid; } OAIFreeStyleBuild OAIFreeStyleProject::getLastBuild() const { return last_build; } void OAIFreeStyleProject::setLastBuild(const OAIFreeStyleBuild &last_build) { this->last_build = last_build; this->m_last_build_isSet = true; } bool OAIFreeStyleProject::is_last_build_Set() const{ return m_last_build_isSet; } bool OAIFreeStyleProject::is_last_build_Valid() const{ return m_last_build_isValid; } OAIFreeStyleBuild OAIFreeStyleProject::getLastCompletedBuild() const { return last_completed_build; } void OAIFreeStyleProject::setLastCompletedBuild(const OAIFreeStyleBuild &last_completed_build) { this->last_completed_build = last_completed_build; this->m_last_completed_build_isSet = true; } bool OAIFreeStyleProject::is_last_completed_build_Set() const{ return m_last_completed_build_isSet; } bool OAIFreeStyleProject::is_last_completed_build_Valid() const{ return m_last_completed_build_isValid; } QString OAIFreeStyleProject::getLastFailedBuild() const { return last_failed_build; } void OAIFreeStyleProject::setLastFailedBuild(const QString &last_failed_build) { this->last_failed_build = last_failed_build; this->m_last_failed_build_isSet = true; } bool OAIFreeStyleProject::is_last_failed_build_Set() const{ return m_last_failed_build_isSet; } bool OAIFreeStyleProject::is_last_failed_build_Valid() const{ return m_last_failed_build_isValid; } OAIFreeStyleBuild OAIFreeStyleProject::getLastStableBuild() const { return last_stable_build; } void OAIFreeStyleProject::setLastStableBuild(const OAIFreeStyleBuild &last_stable_build) { this->last_stable_build = last_stable_build; this->m_last_stable_build_isSet = true; } bool OAIFreeStyleProject::is_last_stable_build_Set() const{ return m_last_stable_build_isSet; } bool OAIFreeStyleProject::is_last_stable_build_Valid() const{ return m_last_stable_build_isValid; } OAIFreeStyleBuild OAIFreeStyleProject::getLastSuccessfulBuild() const { return last_successful_build; } void OAIFreeStyleProject::setLastSuccessfulBuild(const OAIFreeStyleBuild &last_successful_build) { this->last_successful_build = last_successful_build; this->m_last_successful_build_isSet = true; } bool OAIFreeStyleProject::is_last_successful_build_Set() const{ return m_last_successful_build_isSet; } bool OAIFreeStyleProject::is_last_successful_build_Valid() const{ return m_last_successful_build_isValid; } QString OAIFreeStyleProject::getLastUnstableBuild() const { return last_unstable_build; } void OAIFreeStyleProject::setLastUnstableBuild(const QString &last_unstable_build) { this->last_unstable_build = last_unstable_build; this->m_last_unstable_build_isSet = true; } bool OAIFreeStyleProject::is_last_unstable_build_Set() const{ return m_last_unstable_build_isSet; } bool OAIFreeStyleProject::is_last_unstable_build_Valid() const{ return m_last_unstable_build_isValid; } QString OAIFreeStyleProject::getLastUnsuccessfulBuild() const { return last_unsuccessful_build; } void OAIFreeStyleProject::setLastUnsuccessfulBuild(const QString &last_unsuccessful_build) { this->last_unsuccessful_build = last_unsuccessful_build; this->m_last_unsuccessful_build_isSet = true; } bool OAIFreeStyleProject::is_last_unsuccessful_build_Set() const{ return m_last_unsuccessful_build_isSet; } bool OAIFreeStyleProject::is_last_unsuccessful_build_Valid() const{ return m_last_unsuccessful_build_isValid; } qint32 OAIFreeStyleProject::getNextBuildNumber() const { return next_build_number; } void OAIFreeStyleProject::setNextBuildNumber(const qint32 &next_build_number) { this->next_build_number = next_build_number; this->m_next_build_number_isSet = true; } bool OAIFreeStyleProject::is_next_build_number_Set() const{ return m_next_build_number_isSet; } bool OAIFreeStyleProject::is_next_build_number_Valid() const{ return m_next_build_number_isValid; } QString OAIFreeStyleProject::getQueueItem() const { return queue_item; } void OAIFreeStyleProject::setQueueItem(const QString &queue_item) { this->queue_item = queue_item; this->m_queue_item_isSet = true; } bool OAIFreeStyleProject::is_queue_item_Set() const{ return m_queue_item_isSet; } bool OAIFreeStyleProject::is_queue_item_Valid() const{ return m_queue_item_isValid; } bool OAIFreeStyleProject::isConcurrentBuild() const { return concurrent_build; } void OAIFreeStyleProject::setConcurrentBuild(const bool &concurrent_build) { this->concurrent_build = concurrent_build; this->m_concurrent_build_isSet = true; } bool OAIFreeStyleProject::is_concurrent_build_Set() const{ return m_concurrent_build_isSet; } bool OAIFreeStyleProject::is_concurrent_build_Valid() const{ return m_concurrent_build_isValid; } OAINullSCM OAIFreeStyleProject::getScm() const { return scm; } void OAIFreeStyleProject::setScm(const OAINullSCM &scm) { this->scm = scm; this->m_scm_isSet = true; } bool OAIFreeStyleProject::is_scm_Set() const{ return m_scm_isSet; } bool OAIFreeStyleProject::is_scm_Valid() const{ return m_scm_isValid; } bool OAIFreeStyleProject::isSet() const { bool isObjectUpdated = false; do { if (m__class_isSet) { isObjectUpdated = true; break; } if (m_name_isSet) { isObjectUpdated = true; break; } if (m_url_isSet) { isObjectUpdated = true; break; } if (m_color_isSet) { isObjectUpdated = true; break; } if (actions.size() > 0) { isObjectUpdated = true; break; } if (m_description_isSet) { isObjectUpdated = true; break; } if (m_display_name_isSet) { isObjectUpdated = true; break; } if (m_display_name_or_null_isSet) { isObjectUpdated = true; break; } if (m_full_display_name_isSet) { isObjectUpdated = true; break; } if (m_full_name_isSet) { isObjectUpdated = true; break; } if (m_buildable_isSet) { isObjectUpdated = true; break; } if (builds.size() > 0) { isObjectUpdated = true; break; } if (first_build.isSet()) { isObjectUpdated = true; break; } if (health_report.size() > 0) { isObjectUpdated = true; break; } if (m_in_queue_isSet) { isObjectUpdated = true; break; } if (m_keep_dependencies_isSet) { isObjectUpdated = true; break; } if (last_build.isSet()) { isObjectUpdated = true; break; } if (last_completed_build.isSet()) { isObjectUpdated = true; break; } if (m_last_failed_build_isSet) { isObjectUpdated = true; break; } if (last_stable_build.isSet()) { isObjectUpdated = true; break; } if (last_successful_build.isSet()) { isObjectUpdated = true; break; } if (m_last_unstable_build_isSet) { isObjectUpdated = true; break; } if (m_last_unsuccessful_build_isSet) { isObjectUpdated = true; break; } if (m_next_build_number_isSet) { isObjectUpdated = true; break; } if (m_queue_item_isSet) { isObjectUpdated = true; break; } if (m_concurrent_build_isSet) { isObjectUpdated = true; break; } if (scm.isSet()) { isObjectUpdated = true; break; } } while (false); return isObjectUpdated; } bool OAIFreeStyleProject::isValid() const { // only required properties are required for the object to be considered valid return true; } } // namespace OpenAPI
30.117914
130
0.722369
[ "object" ]
66f8cc108b1305761e4de1fca78163997530cc59
1,528
hpp
C++
exp/Common/jcArray.hpp
bheinzelman/JITCalculator
14e221394aa3582ea0b40b48f52d63f7e34e7d2b
[ "Apache-2.0" ]
null
null
null
exp/Common/jcArray.hpp
bheinzelman/JITCalculator
14e221394aa3582ea0b40b48f52d63f7e34e7d2b
[ "Apache-2.0" ]
null
null
null
exp/Common/jcArray.hpp
bheinzelman/JITCalculator
14e221394aa3582ea0b40b48f52d63f7e34e7d2b
[ "Apache-2.0" ]
null
null
null
#pragma once #include <vector> #include <memory> #include <functional> #include "jc.h" #include "jcCollection.h" class jcArray : public jcCollection { public: jcArray(); jcArray(int size); jcArray(const jcArray &other); jcArray(const std::vector<jcVariablePtr> &list); size_t size() const override; /** You own this sucker, be careful */ jcCollection* concat(const jcCollection &other) const override; void forEach(std::function<void(jcVariablePtr&)> callback) const override; bool equal(const jcArray &other) const; jcCollection* slice(int startIdx, int endIdx) const override; jcVariablePtr at(int index) const override; jcVariable::Type getType() const override { return jcVariable::TypeArray; } /// Protected Methods protected: void pushBack(const jcVariablePtr &element); /// Private Methods private: jcArray(const std::shared_ptr<std::vector<jcVariablePtr>> &items, int startIdx, int endIdx); std::vector<jcVariablePtr>::iterator startIt() const; std::vector<jcVariablePtr>::iterator endIt() const; /// Private Properties private: std::shared_ptr<std::vector<jcVariablePtr>> mItems; int mStartIndex=0; int mEndIndex=0; }; class jcMutableArray : public jcArray { public: jcMutableArray(); jcMutableArray(int size); jcMutableArray(const jcArray &other); jcMutableArray(const std::vector<jcVariablePtr> &list); void push(const jcVariablePtr &var); };
22.80597
78
0.685209
[ "vector" ]
66f9fb833a1d393c4b6fb30a858d4b06df416160
25,761
cpp
C++
DeviceCode/Targets/Native/sh7216/DeviceCode/INTC/SH7216_functions_INTC.cpp
Sirokujira/MicroFrameworkPK_v4_3
a0d80b4fd8eeda6dbdb58f6f7beb4f07f7ef563e
[ "Apache-2.0" ]
4
2019-01-21T11:47:53.000Z
2020-06-09T02:14:15.000Z
DeviceCode/Targets/Native/sh7216/DeviceCode/INTC/SH7216_functions_INTC.cpp
yisea123/NetmfSTM32
62ddb8aa0362b83d2e73f3621a56593988e3620f
[ "Apache-2.0" ]
null
null
null
DeviceCode/Targets/Native/sh7216/DeviceCode/INTC/SH7216_functions_INTC.cpp
yisea123/NetmfSTM32
62ddb8aa0362b83d2e73f3621a56593988e3620f
[ "Apache-2.0" ]
6
2017-11-09T11:48:10.000Z
2020-05-24T09:43:07.000Z
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // // This file is part of the Microsoft .NET Micro Framework Porting Kit Code Samples and is unsupported. // Copyright (C) Microsoft Corporation. All rights reserved. Use of this sample source code is subject to // the terms of the Microsoft license agreement under which you licensed this sample source code. // // THIS SAMPLE CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. // // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* * Copyright (C) 2010 Renesas Electronics America Inc. All rights reserved. */ #include <tinyhal.h> #include "vect.h" //--// #pragma section INTTBL void *INT_Vectors[] = { // 4 Illegal code (void*) INT_Illegal_code, // 5 Reserved (void*) Dummy, // 6 Illegal slot (void*) INT_Illegal_slot, // 7 Reserved (void*) Dummy, // 8 Reserved (void*) Dummy, // 9 CPU Address error (void*) INT_CPU_Address, // 10 DMAC Address error (void*) INT_DMAC_Address, // 11 NMI (void*) INT_NMI, // 12 User breakpoint trap (void*) INT_User_Break, // 13 Reserved (void*) Dummy, // 14 H-UDI (void*) INT_HUDI, // 15 Register bank over (void*) INT_Bank_Overflow, // 16 Register bank under (void*) INT_Bank_Underflow, // 17 ZERO_DIV (void*) INT_Divide_by_Zero, // 18 OVER_DIV (void*) INT_Divide_Overflow, // 19 Reserved (void*) Dummy, // 20 Reserved (void*) Dummy, // 21 Reserved (void*) Dummy, // 22 Reserved (void*) Dummy, // 23 Reserved (void*) Dummy, // 24 Reserved (void*) Dummy, // 25 Reserved (void*) Dummy, // 26 Reserved (void*) Dummy, // 27 Reserved (void*) Dummy, // 28 Reserved (void*) Dummy, // 29 Reserved (void*) Dummy, // 30 Reserved (void*) Dummy, // 31 Reserved (void*) Dummy, // 32 TRAPA (User Vecter) (void*) INT_TRAPA32, // 33 TRAPA (User Vecter) (void*) INT_TRAPA33, // 34 TRAPA (User Vecter) (void*) INT_TRAPA34, // 35 TRAPA (User Vecter) (void*) INT_TRAPA35, // 36 TRAPA (User Vecter) (void*) INT_TRAPA36, // 37 TRAPA (User Vecter) (void*) INT_TRAPA37, // 38 TRAPA (User Vecter) (void*) INT_TRAPA38, // 39 TRAPA (User Vecter) (void*) INT_TRAPA39, // 40 TRAPA (User Vecter) (void*) INT_TRAPA40, // 41 TRAPA (User Vecter) (void*) INT_TRAPA41, // 42 TRAPA (User Vecter) (void*) INT_TRAPA42, // 43 TRAPA (User Vecter) (void*) INT_TRAPA43, // 44 TRAPA (User Vecter) (void*) INT_TRAPA44, // 45 TRAPA (User Vecter) (void*) INT_TRAPA45, // 46 TRAPA (User Vecter) (void*) INT_TRAPA46, // 47 TRAPA (User Vecter) (void*) INT_TRAPA47, // 48 TRAPA (User Vecter) (void*) INT_TRAPA48, // 49 TRAPA (User Vecter) (void*) INT_TRAPA49, // 50 TRAPA (User Vecter) (void*) INT_TRAPA50, // 51 TRAPA (User Vecter) (void*) INT_TRAPA51, // 52 TRAPA (User Vecter) (void*) INT_TRAPA52, // 53 TRAPA (User Vecter) (void*) INT_TRAPA53, // 54 TRAPA (User Vecter) (void*) INT_TRAPA54, // 55 TRAPA (User Vecter) (void*) INT_TRAPA55, // 56 TRAPA (User Vecter) (void*) INT_TRAPA56, // 57 TRAPA (User Vecter) (void*) INT_TRAPA57, // 58 TRAPA (User Vecter) (void*) INT_TRAPA58, // 59 TRAPA (User Vecter) (void*) INT_TRAPA59, // 60 TRAPA (User Vecter) (void*) INT_TRAPA60, // 61 TRAPA (User Vecter) (void*) INT_TRAPA61, // 62 TRAPA (User Vecter) (void*) INT_TRAPA62, // 63 TRAPA (User Vecter) (void*) INT_TRAPA63, // 64 Interrupt IRQ0 (void*) INT_IRQ0, // 65 Interrupt IRQ1 (void*) INT_IRQ1, // 66 Interrupt IRQ2 (void*) INT_IRQ2, // 67 Interrupt IRQ3 (void*) INT_IRQ3, // 68 Interrupt IRQ4 (void*) INT_IRQ4, // 69 Interrupt IRQ5 (void*) INT_IRQ5, // 70 Interrupt IRQ6 (void*) INT_IRQ6, // 71 Interrupt IRQ7 (void*) INT_IRQ7, // 72 Reserved (void*) Dummy, // 73 Reserved (void*) Dummy, // 74 Reserved (void*) Dummy, // 75 Reserved (void*) Dummy, // 76 Reserved (void*) Dummy, // 77 Reserved (void*) Dummy, // 78 Reserved (void*) Dummy, // 79 Reserved (void*) Dummy, // 80 Interrupt PINT0 (void*) INT_PINT0, // 81 Interrupt PINT1 (void*) INT_PINT1, // 82 Interrupt PINT2 (void*) INT_PINT2, // 83 Interrupt PINT3 (void*) INT_PINT3, // 84 Interrupt PINT4 (void*) INT_PINT4, // 85 Interrupt PINT5 (void*) INT_PINT5, // 86 Interrupt PINT6 (void*) INT_PINT6, // 87 Interrupt PINT7 (void*) INT_PINT7, // 88 Reserved (void*) Dummy, // 89 Reserved (void*) Dummy, // 90 Reserved (void*) Dummy, // 91 ROM FIFE (void*) INT_ROM_FIFE, // 92 A/D ADI0 (void*) INT_AD_ADI0, // 93 Reserved (void*) Dummy, // 94 Reserved (void*) Dummy, // 95 Reserved (void*) Dummy, // 96 A/D ADI1 (void*) INT_AD_ADI1, // 97 Reserved (void*) Dummy, // 98 Reserved (void*) Dummy, // 99 Reserved (void*) Dummy, // 100 Reserved (void*) Dummy, // 101 Reserved (void*) Dummy, // 102 Reserved (void*) Dummy, // 103 Reserved (void*) Dummy, // 104 RCANET0 ERS_0 (void*) INT_RCANET0_ERS_0, // 105 RCANET0 OVR_0 (void*) INT_RCANET0_OVR_0, // 106 RCANET0 RM01_0 (void*) INT_RCANET0_RM01_0, // 107 RCANET0 SLE_0 (void*) INT_RCANET0_SLE_0, // 108 DMAC0 DEI0 (void*) INT_DMAC0_DEI0, // 109 DMAC0 HEI0 (void*) INT_DMAC0_HEI0, // 110 Reserved (void*) Dummy, // 111 Reserved (void*) Dummy, // 112 DMAC1 DEI1 (void*) INT_DMAC1_DEI1, // 113 DMAC1 HEI1 (void*) INT_DMAC1_HEI1, // 114 Reserved (void*) Dummy, // 115 Reserved (void*) Dummy, // 116 DMAC2 DEI2 (void*) INT_DMAC2_DEI2, // 117 DMAC2 HEI2 (void*) INT_DMAC2_HEI2, // 118 Reserved (void*) Dummy, // 119 Reserved (void*) Dummy, // 120 DMAC3 DEI3 (void*) INT_DMAC3_DEI3, // 121 DMAC3 HEI3 (void*) INT_DMAC3_HEI3, // 122 Reserved (void*) Dummy, // 123 Reserved (void*) Dummy, // 124 DMAC4 DEI4 (void*) INT_DMAC4_DEI4, // 125 DMAC4 HEI4 (void*) INT_DMAC4_HEI4, // 126 Reserved (void*) Dummy, // 127 Reserved (void*) Dummy, // 128 DMAC5 DEI5 (void*) INT_DMAC5_DEI5, // 129 DMAC5 HEI5 (void*) INT_DMAC5_HEI5, // 130 Reserved (void*) Dummy, // 131 Reserved (void*) Dummy, // 132 DMAC6 DEI6 (void*) INT_DMAC6_DEI6, // 133 DMAC6 HEI6 (void*) INT_DMAC6_HEI6, // 134 Reserved (void*) Dummy, // 135 Reserved (void*) Dummy, // 136 DMAC7 DEI7 (void*) INT_DMAC7_DEI7, // 137 DMAC7 HEI7 (void*) INT_DMAC7_HEI7, // 138 Reserved (void*) Dummy, // 139 Reserved (void*) Dummy, // 140 CMT CMI0 (void*) INT_CMT_CMI0, // 141 Reserved (void*) Dummy, // 142 Reserved (void*) Dummy, // 143 Reserved (void*) Dummy, // 144 CMT CMI1 (void*) INT_CMT_CMI1, // 145 Reserved (void*) Dummy, // 146 Reserved (void*) Dummy, // 147 Reserved (void*) Dummy, // 148 BSC CMTI (void*) INT_BSC_CMTI, // 149 Reserved (void*) Dummy, // 150 USB EP4FULL (void*) INT_USB_EP4FULL, // 151 USB EP5EMPTY (void*) INT_USB_EP5EMPTY, // 152 WDT ITI (void*) INT_WDT_ITI, // 153 E-DMAC EINT0 (void*) INT_EDMAC_EINT0, // 154 USB EP1FULL (void*) INT_USB_EP1FULL, // 155 USB EP2EMPTY (void*) INT_USB_EP2EMPTY, // 156 MTU2 MTU0 TGI0A (void*) INT_MTU2_MTU0_TGI0A, // 157 MTU2 MTU0 TGI0B (void*) INT_MTU2_MTU0_TGI0B, // 158 MTU2 MTU0 TGI0C (void*) INT_MTU2_MTU0_TGI0C, // 159 MTU2 MTU0 TGI0D (void*) INT_MTU2_MTU0_TGI0D, // 160 MTU2 MTU0 TGI0V (void*) INT_MTU2_MTU0_TGI0V, // 161 MTU2 MTU0 TGI0E (void*) INT_MTU2_MTU0_TGI0E, // 162 MTU2 MTU0 TGI0F (void*) INT_MTU2_MTU0_TGI0F, // 163 Reserved (void*) Dummy, // 164 MTU2 MTU1 TGI1A (void*) INT_MTU2_MTU1_TGI1A, // 165 MTU2 MTU1 TGI1B (void*) INT_MTU2_MTU1_TGI1B, // 166 Reserved (void*) Dummy, // 167 Reserved (void*) Dummy, // 168 MTU2 MTU1 TGI1V (void*) INT_MTU2_MTU1_TGI1V, // 169 MTU2 MTU1 TGI1U (void*) INT_MTU2_MTU1_TGI1U, // 170 Reserved (void*) Dummy, // 171 Reserved (void*) Dummy, // 172 MTU2 MTU2 TGI2A (void*) INT_MTU2_MTU2_TGI2A, // 173 MTU2 MTU2 TGI2B (void*) INT_MTU2_MTU2_TGI2B, // 174 Reserved (void*) Dummy, // 175 Reserved (void*) Dummy, // 176 MTU2 MTU2 TGI2V (void*) INT_MTU2_MTU2_TGI2V, // 177 MTU2 MTU2 TGI2U (void*) INT_MTU2_MTU2_TGI2U, // 178 Reserved (void*) Dummy, // 179 Reserved (void*) Dummy, // 180 MTU2 MTU3 TGI3A (void*) INT_MTU2_MTU3_TGI3A, // 181 MTU2 MTU3 TGI3B (void*) INT_MTU2_MTU3_TGI3B, // 182 MTU2 MTU3 TGI3C (void*) INT_MTU2_MTU3_TGI3C, // 183 MTU2 MTU3 TGI3D (void*) INT_MTU2_MTU3_TGI3D, // 184 MTU2 MTU3 TGI3V (void*) INT_MTU2_MTU3_TGI3V, // 185 Reserved (void*) Dummy, // 186 Reserved (void*) Dummy, // 187 Reserved (void*) Dummy, // 188 MTU2 MTU4 TGI4A (void*) INT_MTU2_MTU4_TGI4A, // 189 MTU2 MTU4 TGI4B (void*) INT_MTU2_MTU4_TGI4B, // 190 MTU2 MTU4 TGI4C (void*) INT_MTU2_MTU4_TGI4C, // 191 MTU2 MTU4 TGI4D (void*) INT_MTU2_MTU4_TGI4D, // 192 MTU2 MTU4 TGI4V (void*) INT_MTU2_MTU4_TGI4V, // 193 Reserved (void*) Dummy, // 194 Reserved (void*) Dummy, // 195 Reserved (void*) Dummy, // 196 MTU2 MTU5 TGI5U (void*) INT_MTU2_MTU5_TGI5U, // 197 MTU2 MTU5 TGI5V (void*) INT_MTU2_MTU5_TGI5V, // 198 MTU2 MTU5 TGI5W (void*) INT_MTU2_MTU5_TGI5W, // 199 Reserved (void*) Dummy, // 200 POE2 OEI1 (void*) INT_POE2_OEI1, // 201 POE2 OEI2 (void*) INT_POE2_OEI2, // 202 Reserved (void*) Dummy, // 203 Reserved (void*) Dummy, // 204 MTU2S MTU3S TGI3A (void*) INT_MTU2S_MTU3S_TGI3A, // 205 MTU2S MTU3S TGI3B (void*) INT_MTU2S_MTU3S_TGI3B, // 206 MTU2S MTU3S TGI3C (void*) INT_MTU2S_MTU3S_TGI3C, // 207 MTU2S MTU3S TGI3D (void*) INT_MTU2S_MTU3S_TGI3D, // 208 MTU2S MTU3S TGI3V (void*) INT_MTU2S_MTU3S_TGI3V, // 209 Reserved (void*) Dummy, // 210 Reserved (void*) Dummy, // 211 Reserved (void*) Dummy, // 212 MTU2S MTU4S TGI4A (void*) INT_MTU2S_MTU4S_TGI4A, // 213 MTU2S MTU4S TGI4B (void*) INT_MTU2S_MTU4S_TGI4B, // 214 MTU2S MTU4S TGI4C (void*) INT_MTU2S_MTU4S_TGI4C, // 215 MTU2S MTU4S TGI4D (void*) INT_MTU2S_MTU4S_TGI4D, // 216 MTU2S MTU4S TGI4V (void*) INT_MTU2S_MTU4S_TGI4V, // 217 Reserved (void*) Dummy, // 218 Reserved (void*) Dummy, // 219 Reserved (void*) Dummy, // 220 MTU2S MTU5S TGI5U (void*) INT_MTU2S_MTU5S_TGI5U, // 221 MTU2S MTU5S TGI5V (void*) INT_MTU2S_MTU5S_TGI5V, // 222 MTU2S MTU5S TGI5W (void*) INT_MTU2S_MTU5S_TGI5W, // 223 Reserved (void*) Dummy, // 224 POE2 OEI3 (void*) INT_POE2_OEI3, // 225 Reserved (void*) Dummy, // 226 USB USI0 (void*) INT_USB_USI0, // 227 USB USI1 (void*) INT_USB_USI1, // 228 IIC3 STPI (void*) INT_IIC3_STPI, // 229 IIC3 NAKI (void*) INT_IIC3_NAKI, // 230 IIC3 RXI (void*) INT_IIC3_RXI, // 231 IIC3 TXI (void*) INT_IIC3_TXI, // 232 IIC3 TEI (void*) INT_IIC3_TEI, // 233 RSPI SPERI (void*) INT_RSPI_SPERI, // 234 RSPI SPRXI (void*) INT_RSPI_SPRXI, // 235 RSPI SPTXI (void*) INT_RSPI_SPTXI, // 236 SCI SCI4 ERI4 (void*) INT_SCI_SCI4_ERI4, // 237 SCI SCI4 RXI4 (void*) INT_SCI_SCI4_RXI4, // 238 SCI SCI4 TXI4 (void*) INT_SCI_SCI4_TXI4, // 239 SCI SCI4 TEI4 (void*) INT_SCI_SCI4_TEI4, // 240 SCI SCI0 ERI0 (void*) INT_SCI_SCI0_ERI0, // 241 SCI SCI0 RXI0 (void*) INT_SCI_SCI0_RXI0, // 242 SCI SCI0 TXI0 (void*) INT_SCI_SCI0_TXI0, // 243 SCI SCI0 TEI0 (void*) INT_SCI_SCI0_TEI0, // 244 SCI SCI1 ERI1 (void*) INT_SCI_SCI1_ERI1, // 245 SCI SCI1 RXI1 (void*) INT_SCI_SCI1_RXI1, // 246 SCI SCI1 TXI1 (void*) INT_SCI_SCI1_TXI1, // 247 SCI SCI1 TEI1 (void*) INT_SCI_SCI1_TEI1, // 248 SCI SCI2 ERI2 (void*) INT_SCI_SCI2_ERI2, // 249 SCI SCI2 RXI2 (void*) INT_SCI_SCI2_RXI2, // 250 SCI SCI2 TXI2 (void*) INT_SCI_SCI2_TXI2, // 251 SCI SCI2 TEI2 (void*) INT_SCI_SCI2_TEI2, // 252 SCIF SCIF3 BRI3 (void*) INT_SCIF_SCIF3_BRI3, // 253 SCIF SCIF3 ERI3 (void*) INT_SCIF_SCIF3_ERI3, // 254 SCIF SCIF3 RXI3 (void*) INT_SCIF_SCIF3_RXI3, // 255 SCIF SCIF3 TXI3 (void*) INT_SCIF_SCIF3_TXI3, // xx Reserved (void*) Dummy }; #pragma section extern void SH7216_TIMER_ISR( UINT32 timer ); extern void USART_TxISR( UINT32 port ); extern void USART_RxISR( UINT32 port ); extern void USART_RxErrorISR( UINT32 port ); #pragma section IntPRG // 4 Illegal code void INT_Illegal_code(void){/* sleep(); */} // 5 Reserved // 6 Illegal slot void INT_Illegal_slot(void){/* sleep(); */} // 7 Reserved // 8 Reserved // 9 CPU Address error void INT_CPU_Address(void){/* sleep(); */} // 10 DMAC Address error void INT_DMAC_Address(void){/* sleep(); */} // 11 NMI void INT_NMI(void){/* sleep(); */} // 12 User breakpoint trap void INT_User_Break(void){/* sleep(); */} // 13 Reserved // 14 H-UDI void INT_HUDI(void){/* sleep(); */} // 15 Register bank over void INT_Bank_Overflow(void){/* sleep(); */} // 16 Register bank under void INT_Bank_Underflow(void){/* sleep(); */} // 17 ZERO DIV void INT_Divide_by_Zero(void){/* sleep(); */} // 18 OVER DIV void INT_Divide_Overflow(void){/* sleep(); */} // 19 Reserved // 20 Reserved // 21 Reserved // 22 Reserved // 23 Reserved // 24 Reserved // 25 Reserved // 26 Reserved // 27 Reserved // 28 Reserved // 29 Reserved // 30 Reserved // 31 Reserved // 32 TRAPA (User Vecter) void INT_TRAPA32(void){/* sleep(); */} // 33 TRAPA (User Vecter) void INT_TRAPA33(void){/* sleep(); */} // 34 TRAPA (User Vecter) void INT_TRAPA34(void){/* sleep(); */} // 35 TRAPA (User Vecter) void INT_TRAPA35(void){/* sleep(); */} // 36 TRAPA (User Vecter) void INT_TRAPA36(void){/* sleep(); */} // 37 TRAPA (User Vecter) void INT_TRAPA37(void){/* sleep(); */} // 38 TRAPA (User Vecter) void INT_TRAPA38(void){/* sleep(); */} // 39 TRAPA (User Vecter) void INT_TRAPA39(void){/* sleep(); */} // 40 TRAPA (User Vecter) void INT_TRAPA40(void){/* sleep(); */} // 41 TRAPA (User Vecter) void INT_TRAPA41(void){/* sleep(); */} // 42 TRAPA (User Vecter) void INT_TRAPA42(void){/* sleep(); */} // 43 TRAPA (User Vecter) void INT_TRAPA43(void){/* sleep(); */} // 44 TRAPA (User Vecter) void INT_TRAPA44(void){/* sleep(); */} // 45 TRAPA (User Vecter) void INT_TRAPA45(void){/* sleep(); */} // 46 TRAPA (User Vecter) void INT_TRAPA46(void){/* sleep(); */} // 47 TRAPA (User Vecter) void INT_TRAPA47(void){/* sleep(); */} // 48 TRAPA (User Vecter) void INT_TRAPA48(void){/* sleep(); */} // 49 TRAPA (User Vecter) void INT_TRAPA49(void){/* sleep(); */} // 50 TRAPA (User Vecter) void INT_TRAPA50(void){/* sleep(); */} // 51 TRAPA (User Vecter) void INT_TRAPA51(void){/* sleep(); */} // 52 TRAPA (User Vecter) void INT_TRAPA52(void){/* sleep(); */} // 53 TRAPA (User Vecter) void INT_TRAPA53(void){/* sleep(); */} // 54 TRAPA (User Vecter) void INT_TRAPA54(void){/* sleep(); */} // 55 TRAPA (User Vecter) void INT_TRAPA55(void){/* sleep(); */} // 56 TRAPA (User Vecter) void INT_TRAPA56(void){/* sleep(); */} // 57 TRAPA (User Vecter) void INT_TRAPA57(void){/* sleep(); */} // 58 TRAPA (User Vecter) void INT_TRAPA58(void){/* sleep(); */} // 59 TRAPA (User Vecter) void INT_TRAPA59(void){/* sleep(); */} // 60 TRAPA (User Vecter) void INT_TRAPA60(void){/* sleep(); */} // 61 TRAPA (User Vecter) void INT_TRAPA61(void){/* sleep(); */} // 62 TRAPA (User Vecter) void INT_TRAPA62(void){/* sleep(); */} // 63 TRAPA (User Vecter) void INT_TRAPA63(void){/* sleep(); */} // 64 Interrupt IRQ0 void INT_IRQ0(void){/* sleep(); */} // 65 Interrupt IRQ1 void INT_IRQ1(void){/* sleep(); */} // 66 Interrupt IRQ2 void INT_IRQ2(void){/* sleep(); */} // 67 Interrupt IRQ3 void INT_IRQ3(void){/* sleep(); */} // 68 Interrupt IRQ4 void INT_IRQ4(void){/* sleep(); */} // 69 Interrupt IRQ5 void INT_IRQ5(void){/* sleep(); */} // 70 Interrupt IRQ6 void INT_IRQ6(void){/* sleep(); */} // 71 Interrupt IRQ7 void INT_IRQ7(void){/* sleep(); */} // 72 Reserved // 73 Reserved // 74 Reserved // 75 Reserved // 76 Reserved // 77 Reserved // 78 Reserved // 79 Reserved // 80 Interrupt PINT0 void INT_PINT0(void){/* sleep(); */} // 81 Interrupt PINT1 void INT_PINT1(void){/* sleep(); */} // 82 Interrupt PINT2 void INT_PINT2(void){/* sleep(); */} // 83 Interrupt PINT3 void INT_PINT3(void){/* sleep(); */} // 84 Interrupt PINT4 void INT_PINT4(void){/* sleep(); */} // 85 Interrupt PINT5 void INT_PINT5(void){/* sleep(); */} // 86 Interrupt PINT6 void INT_PINT6(void){/* sleep(); */} // 87 Interrupt PINT7 void INT_PINT7(void){/* sleep(); */} // 88 Reserved // 89 Reserved // 90 Reserved // 91 ROM FIFE void INT_ROM_FIFE(void){/* sleep(); */} // 92 A/D ADI0 void INT_AD_ADI0(void){/* sleep(); */} // 93 Reserved // 94 Reserved // 95 Reserved // 96 A/D ADI1 void INT_AD_ADI1(void){/* sleep(); */} // 97 Reserved // 98 Reserved // 99 Reserved // 100 Reserved // 101 Reserved // 102 Reserved // 103 Reserved // 104 RCANET0 ERS_0 void INT_RCANET0_ERS_0(void){/* sleep(); */} // 105 RCANET0 OVR_0 void INT_RCANET0_OVR_0(void){/* sleep(); */} // 106 RCANET0 RM01_0 void INT_RCANET0_RM01_0(void){/* sleep(); */} // 107 RCANET0 SLE_0 void INT_RCANET0_SLE_0(void){/* sleep(); */} // 108 DMAC0 DEI0 void INT_DMAC0_DEI0(void){/* sleep(); */} // 109 DMAC0 HEI0 void INT_DMAC0_HEI0(void){/* sleep(); */} // 110 Reserved // 111 Reserved // 112 DMAC1 DEI1 void INT_DMAC1_DEI1(void){/* sleep(); */} // 113 DMAC1 HEI1 void INT_DMAC1_HEI1(void){/* sleep(); */} // 114 Reserved // 115 Reserved // 116 DMAC2 DEI2 void INT_DMAC2_DEI2(void){/* sleep(); */} // 117 DMAC2 HEI2 void INT_DMAC2_HEI2(void){/* sleep(); */} // 118 Reserved // 119 Reserved // 120 DMAC3 DEI3 void INT_DMAC3_DEI3(void){/* sleep(); */} // 121 DMAC3 HEI3 void INT_DMAC3_HEI3(void){/* sleep(); */} // 122 Reserved // 123 Reserved // 124 DMAC4 DEI4 void INT_DMAC4_DEI4(void){/* sleep(); */} // 125 DMAC4 HEI4 void INT_DMAC4_HEI4(void){/* sleep(); */} // 126 Reserved // 127 Reserved // 128 DMAC5 DEI5 void INT_DMAC5_DEI5(void){/* sleep(); */} // 129 DMAC5 HEI5 void INT_DMAC5_HEI5(void){/* sleep(); */} // 130 Reserved // 131 Reserved // 132 DMAC6 DEI6 void INT_DMAC6_DEI6(void){/* sleep(); */} // 133 DMAC6 HEI6 void INT_DMAC6_HEI6(void){/* sleep(); */} // 134 Reserved // 135 Reserved // 136 DMAC7 DEI7 void INT_DMAC7_DEI7(void){/* sleep(); */} // 137 DMAC7 HEI7 void INT_DMAC7_HEI7(void){/* sleep(); */} // 138 Reserved // 139 Reserved // 140 CMT CMI0 void INT_CMT_CMI0(void) { SH7216_TIMER_ISR(0); } // 141 Reserved // 142 Reserved // 143 Reserved // 144 CMT CMI1 void INT_CMT_CMI1(void) { SH7216_TIMER_ISR(1); } // 145 Reserved // 146 Reserved // 147 Reserved // 148 BSC CMTI void INT_BSC_CMTI(void){/* sleep(); */} // 149 Reserved // 150 USB EP4FULL void INT_USB_EP4FULL(void){/* sleep(); */} // 151 USB EP5EMPTY void INT_USB_EP5EMPTY(void){/* sleep(); */} // 152 WDT ITI void INT_WDT_ITI(void){/* sleep(); */} // 153 E-DMAC EINT0 void INT_EDMAC_EINT0(void){/* sleep(); */} // 154 USB EP1FULL void INT_USB_EP1FULL(void){/* sleep(); */} // 155 USB EP2EMPTY void INT_USB_EP2EMPTY(void){/* sleep(); */} // 156 MTU2 MTU0 TGI0A void INT_MTU2_MTU0_TGI0A(void){/* sleep(); */} // 157 MTU2 MTU0 TGI0B void INT_MTU2_MTU0_TGI0B(void){/* sleep(); */} // 158 MTU2 MTU0 TGI0C void INT_MTU2_MTU0_TGI0C(void){/* sleep(); */} // 159 MTU2 MTU0 TGI0D void INT_MTU2_MTU0_TGI0D(void){/* sleep(); */} // 160 MTU2 MTU0 TGI0V void INT_MTU2_MTU0_TGI0V(void){/* sleep(); */} // 161 MTU2 MTU0 TGI0E void INT_MTU2_MTU0_TGI0E(void){/* sleep(); */} // 162 MTU2 MTU0 TGI0F void INT_MTU2_MTU0_TGI0F(void){/* sleep(); */} // 163 Reserved // 164 MTU2 MTU1 TGI1A void INT_MTU2_MTU1_TGI1A(void){/* sleep(); */} // 165 MTU2 MTU1 TGI1B void INT_MTU2_MTU1_TGI1B(void){/* sleep(); */} // 166 Reserved // 167 Reserved // 168 MTU2 MTU1 TGI1V void INT_MTU2_MTU1_TGI1V(void){/* sleep(); */} // 169 MTU2 MTU1 TGI1U void INT_MTU2_MTU1_TGI1U(void){/* sleep(); */} // 170 Reserved // 171 Reserved // 172 MTU2 MTU2 TGI2A void INT_MTU2_MTU2_TGI2A(void){/* sleep(); */} // 173 MTU2 MTU2 TGI2B void INT_MTU2_MTU2_TGI2B(void){/* sleep(); */} // 174 Reserved // 175 Reserved // 176 MTU2 MTU2 TGI2V void INT_MTU2_MTU2_TGI2V(void){/* sleep(); */} // 177 MTU2 MTU2 TGI2U void INT_MTU2_MTU2_TGI2U(void){/* sleep(); */} // 178 Reserved // 179 Reserved // 180 MTU2 MTU3 TGI3A void INT_MTU2_MTU3_TGI3A(void){/* sleep(); */} // 181 MTU2 MTU3 TGI3B void INT_MTU2_MTU3_TGI3B(void){/* sleep(); */} // 182 MTU2 MTU3 TGI3C void INT_MTU2_MTU3_TGI3C(void){/* sleep(); */} // 183 MTU2 MTU3 TGI3D void INT_MTU2_MTU3_TGI3D(void){/* sleep(); */} // 184 MTU2 MTU3 TGI3V void INT_MTU2_MTU3_TGI3V(void){/* sleep(); */} // 185 Reserved // 186 Reserved // 187 Reserved // 188 MTU2 MTU4 TGI4A void INT_MTU2_MTU4_TGI4A(void){/* sleep(); */} // 189 MTU2 MTU4 TGI4B void INT_MTU2_MTU4_TGI4B(void){/* sleep(); */} // 190 MTU2 MTU4 TGI4C void INT_MTU2_MTU4_TGI4C(void){/* sleep(); */} // 191 MTU2 MTU4 TGI4D void INT_MTU2_MTU4_TGI4D(void){/* sleep(); */} // 192 MTU2 MTU4 TGI4V void INT_MTU2_MTU4_TGI4V(void){/* sleep(); */} // 193 Reserved // 194 Reserved // 195 Reserved // 196 MTU2 MTU5 TGI5U void INT_MTU2_MTU5_TGI5U(void){/* sleep(); */} // 197 MTU2 MTU5 TGI5V void INT_MTU2_MTU5_TGI5V(void){/* sleep(); */} // 198 MTU2 MTU5 TGI5W void INT_MTU2_MTU5_TGI5W(void){/* sleep(); */} // 199 Reserved // 200 POE2 OEI1 void INT_POE2_OEI1(void){/* sleep(); */} // 201 POE2 OEI2 void INT_POE2_OEI2(void){/* sleep(); */} // 202 Reserved // 203 Reserved // 204 MTU2S MTU3S TGI3A void INT_MTU2S_MTU3S_TGI3A(void){/* sleep(); */} // 205 MTU2S MTU3S TGI3B void INT_MTU2S_MTU3S_TGI3B(void){/* sleep(); */} // 206 MTU2S MTU3S TGI3C void INT_MTU2S_MTU3S_TGI3C(void){/* sleep(); */} // 207 MTU2S MTU3S TGI3D void INT_MTU2S_MTU3S_TGI3D(void){/* sleep(); */} // 208 MTU2S MTU3S TGI3V void INT_MTU2S_MTU3S_TGI3V(void){/* sleep(); */} // 209 Reserved // 210 Reserved // 211 Reserved // 212 MTU2S MTU4S TGI4A void INT_MTU2S_MTU4S_TGI4A(void){/* sleep(); */} // 213 MTU2S MTU4S TGI4B void INT_MTU2S_MTU4S_TGI4B(void){/* sleep(); */} // 214 MTU2S MTU4S TGI4C void INT_MTU2S_MTU4S_TGI4C(void){/* sleep(); */} // 215 MTU2S MTU4S TGI4D void INT_MTU2S_MTU4S_TGI4D(void){/* sleep(); */} // 216 MTU2S MTU4S TGI4V void INT_MTU2S_MTU4S_TGI4V(void){/* sleep(); */} // 217 Reserved // 218 Reserved // 219 Reserved // 220 MTU2S MTU5S TGI5U void INT_MTU2S_MTU5S_TGI5U(void){/* sleep(); */} // 221 MTU2S MTU5S TGI5V void INT_MTU2S_MTU5S_TGI5V(void){/* sleep(); */} // 222 MTU2S MTU5S TGI5W void INT_MTU2S_MTU5S_TGI5W(void){/* sleep(); */} // 223 Reserved // 224 POE2 OEI3 void INT_POE2_OEI3(void){/* sleep(); */} // 225 Reserved // 226 USB USI0 void INT_USB_USI0(void){/* sleep(); */} // 227 USB USI1 void INT_USB_USI1(void){/* sleep(); */} // 228 IIC3 STPI void INT_IIC3_STPI(void){/* sleep(); */} // 229 IIC3 NAKI void INT_IIC3_NAKI(void){/* sleep(); */} // 230 IIC3 RXI void INT_IIC3_RXI(void){/* sleep(); */} // 231 IIC3 TXI void INT_IIC3_TXI(void){/* sleep(); */} // 232 IIC3 TEI void INT_IIC3_TEI(void){/* sleep(); */} // 233 RSPI SPERI void INT_RSPI_SPERI(void){/* sleep(); */} // 234 RSPI SPRXI void INT_RSPI_SPRXI(void){/* sleep(); */} // 235 RSPI SPTXI void INT_RSPI_SPTXI(void){/* sleep(); */} // 236 SCI SCI4 ERI4 void INT_SCI_SCI4_ERI4(void){/* sleep(); */} // 237 SCI SCI4 RXI4 void INT_SCI_SCI4_RXI4(void){/* sleep(); */} // 238 SCI SCI4 TXI4 void INT_SCI_SCI4_TXI4(void){/* sleep(); */} // 239 SCI SCI4 TEI4 void INT_SCI_SCI4_TEI4(void){/* sleep(); */} // 240 SCI SCI0 ERI0 void INT_SCI_SCI0_ERI0(void){/* sleep(); */} // 241 SCI SCI0 RXI0 void INT_SCI_SCI0_RXI0(void){/* sleep(); */} // 242 SCI SCI0 TXI0 void INT_SCI_SCI0_TXI0(void){/* sleep(); */} // 243 SCI SCI0 TEI0 void INT_SCI_SCI0_TEI0(void){/* sleep(); */} // 244 SCI SCI1 ERI1 void INT_SCI_SCI1_ERI1(void) { USART_RxErrorISR(1); } // 245 SCI SCI1 RXI1 void INT_SCI_SCI1_RXI1(void) { USART_RxISR(1); } // 246 SCI SCI1 TXI1 void INT_SCI_SCI1_TXI1(void) { USART_TxISR(1); } // 247 SCI SCI1 TEI1 void INT_SCI_SCI1_TEI1(void){/* sleep(); */} // 248 SCI SCI2 ERI2 void INT_SCI_SCI2_ERI2(void){/* sleep(); */} // 249 SCI SCI2 RXI2 void INT_SCI_SCI2_RXI2(void){/* sleep(); */} // 250 SCI SCI2 TXI2 void INT_SCI_SCI2_TXI2(void){/* sleep(); */} // 251 SCI SCI2 TEI2 void INT_SCI_SCI2_TEI2(void){/* sleep(); */} // 252 SCIF SCIF3 BRI3 void INT_SCIF_SCIF3_BRI3(void){/* sleep(); */} // 253 SCIF SCIF3 ERI3 void INT_SCIF_SCIF3_ERI3(void){/* sleep(); */} // 254 SCIF SCIF3 RXI3 void INT_SCIF_SCIF3_RXI3(void){/* sleep(); */} // 255 SCIF SCIF3 TXI3 void INT_SCIF_SCIF3_TXI3(void){/* sleep(); */} // Dummy void Dummy(void){/* sleep(); */} void __irq IRQ_Handler() { } void CPU_INTC_Initialize() { } BOOL CPU_INTC_ActivateInterrupt( UINT32 Irq_Index, HAL_CALLBACK_FPN ISR, void* ISR_Param ) { // figure out the interrupt HAL_CALLBACK* IsrVector; IsrVector = (HAL_CALLBACK *)INT_Vectors[Irq_Index]; if(!IsrVector) return FALSE; { // set the vector IsrVector->Initialize( ISR, ISR_Param ); } return TRUE; } BOOL CPU_INTC_DeactivateInterrupt( UINT32 Irq_Index ) { return FALSE; } BOOL CPU_INTC_InterruptEnable( UINT32 Irq_Index ) { return FALSE; } BOOL CPU_INTC_InterruptDisable( UINT32 Irq_Index ) { return FALSE; } BOOL CPU_INTC_InterruptEnableState( UINT32 Irq_Index ) { return FALSE; } BOOL CPU_INTC_InterruptState( UINT32 Irq_Index ) { return FALSE; }
23.166367
200
0.64062
[ "vector" ]
66fb96a1187b63c303963ae92e0f08e2ee79a02d
1,555
cpp
C++
station/timer.cpp
khantkyawkhaung/robot-monitor
3614dc0cf804138c81f6800fb5ec443bff709dbd
[ "MIT" ]
1
2021-04-06T04:11:58.000Z
2021-04-06T04:11:58.000Z
station/timer.cpp
khantkyawkhaung/robot-monitor
3614dc0cf804138c81f6800fb5ec443bff709dbd
[ "MIT" ]
null
null
null
station/timer.cpp
khantkyawkhaung/robot-monitor
3614dc0cf804138c81f6800fb5ec443bff709dbd
[ "MIT" ]
1
2019-12-26T09:01:16.000Z
2019-12-26T09:01:16.000Z
/** * @file timer.cpp * @brief the wxTimer to handle the idle function of the client * * This is used to replace the default extra thread that runs parallel with the * main thread. wxWidgets require its own type of timer to process the idle * function. If the default multithreading is used, there will be data races * and conflict with data and event systems of wxWidgets. * * @copyright Copyright (c) 2021 Khant Kyaw Khaung * * @license{This project is released under the MIT License.} */ #define RM_WX_EXPORT #include "rm/timer.hpp" long rmTimer::getWxID() { if(wx_id == 0) wx_id = wxNewId(); return wx_id; } /** * @brief Default constructor */ rmTimer::rmTimer() :wxTimer(this, getWxID()) { Connect( wxEVT_TIMER, wxTimerEventHandler(rmTimer::onTimer), NULL, this ); } /** * @brief Starts the timer * * @param ms Time interval in milliseconds */ void rmTimer::start(long ms) { Start(ms); } /** * @brief Stops the timer */ void rmTimer::stop() { Stop(); } /** * @brief Timer function to be executed in each interval * * @param evt Timer event object */ void rmTimer::onTimer(wxTimerEvent& evt) { if(clients.size() == 0) { Stop(); return; } auto vec = clients; for(auto it=vec.begin(); it!=vec.end(); it++) { if((*it)->isConnected() == false) { (*it)->echo("Port disconnected", 1); removeClient(*it); (*it)->onDisconnected(); } (*it)->onIdle(); } }
20.733333
79
0.601286
[ "object" ]
66fc4f5782fbaa1c8820f94574434b2e97912488
16,193
hpp
C++
src/blas/impl/KokkosBlas1_axpby_impl.hpp
purdue-aalp/kokkos-kernels
a86b60232950b62a84514c161b6551e516b6565f
[ "BSD-3-Clause" ]
null
null
null
src/blas/impl/KokkosBlas1_axpby_impl.hpp
purdue-aalp/kokkos-kernels
a86b60232950b62a84514c161b6551e516b6565f
[ "BSD-3-Clause" ]
1
2021-12-08T14:31:15.000Z
2021-12-08T14:31:15.000Z
src/blas/impl/KokkosBlas1_axpby_impl.hpp
purdue-aalp/kokkos-kernels
a86b60232950b62a84514c161b6551e516b6565f
[ "BSD-3-Clause" ]
null
null
null
/* //@HEADER // ************************************************************************ // // KokkosKernels 0.9: Linear Algebra and Graph Kernels // Copyright 2017 Sandia Corporation // // Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, // the U.S. Government retains certain rights in this software. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the Corporation nor the names of the // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SANDIA CORPORATION OR THE // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Questions? Contact Siva Rajamanickam (srajama@sandia.gov) // // ************************************************************************ //@HEADER */ #ifndef KOKKOSBLAS1_AXPBY_IMPL_HPP_ #define KOKKOSBLAS1_AXPBY_IMPL_HPP_ #include "KokkosKernels_config.h" #include "Kokkos_Core.hpp" #include "Kokkos_InnerProductSpaceTraits.hpp" #ifndef KOKKOSBLAS_OPTIMIZATION_LEVEL_AXPBY #define KOKKOSBLAS_OPTIMIZATION_LEVEL_AXPBY 2 #endif // KOKKOSBLAS_OPTIMIZATION_LEVEL_AXPBY namespace KokkosBlas { namespace Impl { // // axpby // // Single-vector version of Axpby_MV_Functor. The definition // immediately below lets a and b both be 1-D Views (and only requires // that each have one entry). Following this is a partial // specialization that lets both of them be scalars. This functor // computes any of the following: // // 1. Y(i) = alpha*X(i) + beta*Y(i) for alpha,beta in -1,0,1 // 2. Y(i) = a(0)*X(i) + beta*Y(i) for beta in -1,0,1 // 3. Y(i) = alpha*X(i) + b(0)*Y(i) for alpha in -1,0,1 // 4. Y(i) = a(0)*X(i) + b(0)*Y(i) // // The template parameters scalar_x and scalar_y correspond to alpha // resp. beta in the operation y = alpha*x + beta*y. The values -1, // 0, and -1 correspond to literal values of those coefficients. The // value 2 tells the functor to use the corresponding vector of // coefficients. Any literal coefficient of zero has BLAS semantics // of ignoring the corresponding (multi)vector entry. This does not // apply to coefficients in the a and b vectors, if they are used. template<class AV, class XV, class BV, class YV, int scalar_x, int scalar_y, class SizeType> struct Axpby_Functor { typedef typename YV::execution_space execution_space; typedef SizeType size_type; typedef Kokkos::Details::ArithTraits<typename YV::non_const_value_type> ATS; XV m_x; YV m_y; AV m_a; BV m_b; Axpby_Functor (const XV& x, const YV& y, const AV& a, const BV& b, const SizeType startingColumn) : m_x (x), m_y (y), m_a (a), m_b (b) { static_assert (Kokkos::Impl::is_view<XV>::value, "KokkosBlas::Impl::" "Axpby_Functor: X is not a Kokkos::View."); static_assert (Kokkos::Impl::is_view<YV>::value, "KokkosBlas::Impl::" "Axpby_Functor: Y is not a Kokkos::View."); static_assert (Kokkos::Impl::is_same<typename YV::value_type, typename YV::non_const_value_type>::value, "KokkosBlas::Impl::Axpby_Functor: Y is const. " "It must be nonconst, because it is an output argument " "(we have to be able to write to its entries)."); static_assert ((int) YV::Rank == (int) XV::Rank, "KokkosBlas::Impl::" "Axpby_Functor: X and Y must have the same rank."); static_assert (YV::Rank == 1, "KokkosBlas::Impl::Axpby_Functor: " "XV and YV must have rank 1."); if (startingColumn != 0) { m_a = Kokkos::subview (a, std::make_pair (startingColumn, SizeType(a.extent(0)))); m_b = Kokkos::subview (b, std::make_pair (startingColumn, SizeType(b.extent(0)))); } } KOKKOS_INLINE_FUNCTION void operator() (const size_type& i) const { // scalar_x and scalar_y are compile-time constants (since they // are template parameters), so the compiler should evaluate these // branches at compile time. #if KOKKOSBLAS_OPTIMIZATION_LEVEL_AXPBY <= 2 if (scalar_x == 0 && scalar_y == 0) { m_y(i) = ATS::zero (); } if (scalar_x == 0 && scalar_y == 2) { m_y(i) = m_b(0)*m_y(i); } if (scalar_x == 2 && scalar_y == 0) { m_y(i) = m_a(0)*m_x(i); } if (scalar_x == 2 && scalar_y == 2) { m_y(i) = m_a(0)*m_x(i) + m_b(0)*m_y(i); } #else // KOKKOSBLAS_OPTIMIZATION_LEVEL_AXPBY > 2 if (scalar_x == 0 && scalar_y == 0) { m_y(i) = ATS::zero (); } if (scalar_x == 0 && scalar_y == -1) { m_y(i) = -m_y(i); } if (scalar_x == 0 && scalar_y == 1) { return; // m_y(i) = m_y(i); } if (scalar_x == 0 && scalar_y == 2) { m_y(i) = m_b(0)*m_y(i); } if (scalar_x == -1 && scalar_y == 0) { m_y(i) = -m_x(i); } if (scalar_x == -1 && scalar_y == -1) { m_y(i) = -m_x(i) - m_y(i); } if (scalar_x == -1 && scalar_y == 1) { m_y(i) = -m_x(i) + m_y(i); } if (scalar_x == -1 && scalar_y == 2) { m_y(i) = -m_x(i) + m_b(0)*m_y(i); } if (scalar_x == 1 && scalar_y == 0) { m_y(i) = m_x(i); } if (scalar_x == 1 && scalar_y == -1) { m_y(i) = m_x(i) - m_y(i); } if (scalar_x == 1 && scalar_y == 1) { m_y(i) = m_x(i) + m_y(i); } if (scalar_x == 1 && scalar_y == 2) { m_y(i) = m_x(i) + m_b(0)*m_y(i); } if (scalar_x == 2 && scalar_y == 0) { m_y(i) = m_a(0)*m_x(i); } if (scalar_x == 2 && scalar_y == -1) { m_y(i) = m_a(0)*m_x(i) - m_y(i); } if (scalar_x == 2 && scalar_y == 1) { m_y(i) = m_a(0)*m_x(i) + m_y(i); } if (scalar_x == 2 && scalar_y == 2) { m_y(i) = m_a(0)*m_x(i) + m_b(0)*m_y(i); } #endif // KOKKOSBLAS_OPTIMIZATION_LEVEL_AXPBY } }; // Partial specialization of Axpby_Functor that lets a and b be // scalars (rather than 1-D Views, as in the most general version // above). This functor computes any of the following: // // 1. Y(i) = alpha*X(i) + beta*Y(i) for alpha,beta in -1,0,1 // 2. Y(i) = a*X(i) + beta*Y(i) for beta in -1,0,1 // 3. Y(i) = alpha*X(i) + b*Y(i) for alpha in -1,0,1 // 4. Y(i) = a*X(i) + b*Y(i) // // The template parameters scalar_x and scalar_y correspond to alpha // resp. beta in the operation y = alpha*x + beta*y. The values -1, // 0, and -1 correspond to literal values of those coefficients. The // value 2 tells the functor to use the corresponding vector of // coefficients. Any literal coefficient of zero has BLAS semantics // of ignoring the corresponding (multi)vector entry. This does not // apply to coefficients in the a and b vectors, if they are used. template<class XV, class YV, int scalar_x, int scalar_y, class SizeType> struct Axpby_Functor<typename XV::non_const_value_type, XV, typename YV::non_const_value_type, YV, scalar_x, scalar_y, SizeType> { typedef typename YV::execution_space execution_space; typedef SizeType size_type; typedef Kokkos::Details::ArithTraits<typename YV::non_const_value_type> ATS; XV m_x; YV m_y; const typename XV::non_const_value_type m_a; const typename YV::non_const_value_type m_b; Axpby_Functor (const XV& x, const YV& y, const typename XV::non_const_value_type& a, const typename YV::non_const_value_type& b, const SizeType /* startingColumn */) : m_x (x), m_y (y), m_a (a), m_b (b) { static_assert (Kokkos::Impl::is_view<XV>::value, "KokkosBlas::Impl::" "Axpby_Functor: X is not a Kokkos::View."); static_assert (Kokkos::Impl::is_view<YV>::value, "KokkosBlas::Impl::" "Axpby_Functor: Y is not a Kokkos::View."); static_assert (Kokkos::Impl::is_same<typename YV::value_type, typename YV::non_const_value_type>::value, "KokkosBlas::Impl::Axpby_Functor: R is const. " "It must be nonconst, because it is an output argument " "(we have to be able to write to its entries)."); static_assert ((int) YV::Rank == (int) XV::Rank, "KokkosBlas::Impl::" "Axpby_Functor: X and Y must have the same rank."); static_assert (YV::Rank == 1, "KokkosBlas::Impl::Axpby_Functor: " "XV and YV must have rank 1."); } KOKKOS_INLINE_FUNCTION void operator() (const size_type& i) const { // scalar_x and scalar_y are compile-time constants (since they // are template parameters), so the compiler should evaluate these // branches at compile time. #if KOKKOSBLAS_OPTIMIZATION_LEVEL_AXPBY <= 2 if (scalar_x == 0 && scalar_y == 0) { m_y(i) = ATS::zero (); } if (scalar_x == 0 && scalar_y == 2) { m_y(i) = m_b*m_y(i); } if (scalar_x == 2 && scalar_y == 0) { m_y(i) = m_a*m_x(i); } if (scalar_x == 2 && scalar_y == 2) { m_y(i) = m_a*m_x(i) + m_b*m_y(i); } #else // KOKKOSBLAS_OPTIMIZATION_LEVEL_AXPBY > 2 if (scalar_x == 0 && scalar_y == 0) { m_y(i) = ATS::zero (); } if (scalar_x == 0 && scalar_y == -1) { m_y(i) = -m_y(i); } if (scalar_x == 0 && scalar_y == 1) { return; // m_y(i) = m_y(i); } if (scalar_x == 0 && scalar_y == 2) { m_y(i) = m_b*m_y(i); } if (scalar_x == -1 && scalar_y == 0) { m_y(i) = -m_x(i); } if (scalar_x == -1 && scalar_y == -1) { m_y(i) = -m_x(i) - m_y(i); } if (scalar_x == -1 && scalar_y == 1) { m_y(i) = -m_x(i) + m_y(i); } if (scalar_x == -1 && scalar_y == 2) { m_y(i) = -m_x(i) + m_b*m_y(i); } if (scalar_x == 1 && scalar_y == 0) { m_y(i) = m_x(i); } if (scalar_x == 1 && scalar_y == -1) { m_y(i) = m_x(i) - m_y(i); } if (scalar_x == 1 && scalar_y == 1) { m_y(i) = m_x(i) + m_y(i); } if (scalar_x == 1 && scalar_y == 2) { m_y(i) = m_x(i) + m_b*m_y(i); } if (scalar_x == 2 && scalar_y == 0) { m_y(i) = m_a*m_x(i); } if (scalar_x == 2 && scalar_y == -1) { m_y(i) = m_a*m_x(i) - m_y(i); } if (scalar_x == 2 && scalar_y == 1) { m_y(i) = m_a*m_x(i) + m_y(i); } if (scalar_x == 2 && scalar_y == 2) { m_y(i) = m_a*m_x(i) + m_b*m_y(i); } #endif // KOKKOSBLAS_OPTIMIZATION_LEVEL_AXPBY } }; // Variant of Axpby_MV_Generic for single vectors (1-D Views) x and y. // As above, either av and bv are both 1-D Views (and only the first // entry of each will be read), or both av and bv are scalars. // // This takes the starting column, so that if av and bv are both 1-D // Views, then the functor can take a subview if appropriate. template<class AV, class XV, class BV, class YV, class SizeType> void Axpby_Generic (const AV& av, const XV& x, const BV& bv, const YV& y, const SizeType startingColumn, int a = 2, int b = 2) { static_assert (Kokkos::Impl::is_view<XV>::value, "KokkosBlas::Impl::" "Axpby_Generic: X is not a Kokkos::View."); static_assert (Kokkos::Impl::is_view<YV>::value, "KokkosBlas::Impl::" "Axpby_Generic: Y is not a Kokkos::View."); static_assert (Kokkos::Impl::is_same<typename YV::value_type, typename YV::non_const_value_type>::value, "KokkosBlas::Impl::Axpby_Generic: Y is const. " "It must be nonconst, because it is an output argument " "(we have to be able to write to its entries)."); static_assert ((int) YV::Rank == (int) XV::Rank, "KokkosBlas::Impl::" "Axpby_Generic: X and Y must have the same rank."); static_assert (YV::Rank == 1, "KokkosBlas::Impl::Axpby_Generic: " "XV and YV must have rank 1."); typedef typename YV::execution_space execution_space; const SizeType numRows = x.extent(0); Kokkos::RangePolicy<execution_space, SizeType> policy (0, numRows); if (a == 0 && b == 0) { Axpby_Functor<AV, XV, BV, YV, 0, 0, SizeType> op (x, y, av, bv, startingColumn); Kokkos::parallel_for (policy, op); return; } #if KOKKOSBLAS_OPTIMIZATION_LEVEL_AXPBY > 2 if (a == 0 && b == -1) { Axpby_Functor<AV, XV, BV, YV, 0, -1, SizeType> op (x, y, av, bv, startingColumn); Kokkos::parallel_for (policy, op); return; } if (a == 0 && b == 1) { Axpby_Functor<AV, XV, BV, YV, 0, 1, SizeType> op (x, y, av, bv, startingColumn); Kokkos::parallel_for (policy, op); return; } #endif // KOKKOSBLAS_OPTIMIZATION_LEVEL_AXPBY > 2 if (a == 0 && b == 2) { Axpby_Functor<AV, XV, BV, YV, 0, 2, SizeType> op (x, y, av, bv, startingColumn); Kokkos::parallel_for (policy, op); return; } #if KOKKOSBLAS_OPTIMIZATION_LEVEL_AXPBY > 2 // a == -1 if (a == -1 && b == 0) { Axpby_Functor<AV, XV, BV, YV, -1, 0, SizeType> op (x, y, av, bv, startingColumn); Kokkos::parallel_for (policy, op); return; } if (a == -1 && b == -1) { Axpby_Functor<AV, XV, BV, YV, -1, -1, SizeType> op (x, y, av, bv, startingColumn); Kokkos::parallel_for (policy, op); return; } if (a == -1 && b == 1) { Axpby_Functor<AV, XV, BV, YV, -1, 1, SizeType> op (x, y, av, bv, startingColumn); Kokkos::parallel_for (policy, op); return; } if (a == -1 && b == 2) { Axpby_Functor<AV, XV, BV, YV, -1, 2, SizeType> op (x, y, av, bv, startingColumn); Kokkos::parallel_for (policy, op); return; } // a == 1 if (a == 1 && b == 0) { Axpby_Functor<AV, XV, BV, YV, 1, 0, SizeType> op (x, y, av, bv, startingColumn); Kokkos::parallel_for (policy, op); return; } if (a == 1 && b == -1) { Axpby_Functor<AV, XV, BV, YV, 1, -1, SizeType> op (x, y, av, bv, startingColumn); Kokkos::parallel_for (policy, op); return; } if (a == 1 && b == 1) { Axpby_Functor<AV, XV, BV, YV, 1, 1, SizeType> op (x, y, av, bv, startingColumn); Kokkos::parallel_for (policy, op); return; } if (a == 1 && b == 2) { Axpby_Functor<AV, XV, BV, YV, 1, 2, SizeType> op (x, y, av, bv, startingColumn); Kokkos::parallel_for (policy, op); return; } #endif // KOKKOSBLAS_OPTIMIZATION_LEVEL_AXPBY > 2 // a == 2 if (a == 2 && b == 0) { Axpby_Functor<AV, XV, BV, YV, 2, 0, SizeType> op (x, y, av, bv, startingColumn); Kokkos::parallel_for (policy, op); return; } #if KOKKOSBLAS_OPTIMIZATION_LEVEL_AXPBY > 2 if (a == 2 && b == -1) { Axpby_Functor<AV, XV, BV, YV, 2, -1, SizeType> op (x, y, av, bv, startingColumn); Kokkos::parallel_for (policy, op); return; } if (a == 2 && b == 1) { Axpby_Functor<AV, XV, BV, YV, 2, 1, SizeType> op (x, y, av, bv, startingColumn); Kokkos::parallel_for (policy, op); return; } #endif // KOKKOSBLAS_OPTIMIZATION_LEVEL_AXPBY > 2 // a and b arbitrary (not -1, 0, or 1) Axpby_Functor<AV, XV, BV, YV, 2, 2, SizeType> op (x, y, av, bv, startingColumn); Kokkos::parallel_for (policy, op); } } } #endif // KOKKOSBLAS1_AXPBY_IMPL_HPP_
35.904656
88
0.595875
[ "vector" ]
66fe7a8a49c3c849c48f5f5b840e693e02f275e5
3,884
cc
C++
mindspore/lite/src/runtime/kernel/arm/fp32/space_to_depth_fp32.cc
Vincent34/mindspore
a39a60878a46e7e9cb02db788c0bca478f2fa6e5
[ "Apache-2.0" ]
null
null
null
mindspore/lite/src/runtime/kernel/arm/fp32/space_to_depth_fp32.cc
Vincent34/mindspore
a39a60878a46e7e9cb02db788c0bca478f2fa6e5
[ "Apache-2.0" ]
null
null
null
mindspore/lite/src/runtime/kernel/arm/fp32/space_to_depth_fp32.cc
Vincent34/mindspore
a39a60878a46e7e9cb02db788c0bca478f2fa6e5
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2020 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "src/runtime/kernel/arm/fp32/space_to_depth_fp32.h" #include <limits> #include <vector> #include "schema/model_generated.h" #include "src/kernel_registry.h" #include "nnacl/space_to_depth_parameter.h" #include "nnacl/base/space_to_depth_base.h" #include "include/errorcode.h" using mindspore::lite::KernelRegistrar; using mindspore::lite::RET_ERROR; using mindspore::lite::RET_FORMAT_ERR; using mindspore::lite::RET_OK; using mindspore::lite::RET_PARAM_INVALID; using mindspore::schema::PrimitiveType_SpaceToDepth; namespace mindspore::kernel { int SpaceToDepthCPUKernel::Init() { SpaceToDepthParameter *param = reinterpret_cast<SpaceToDepthParameter *>(op_parameter_); if (param->block_size_ <= 0) { MS_LOG(ERROR) << "Input block_size should > 0!"; return RET_PARAM_INVALID; } if (!InferShapeDone()) { return RET_OK; } return ReSize(); } int SpaceToDepthCPUKernel::ReSize() { if (in_tensors_.at(0)->format() != mindspore::NHWC) { MS_LOG(ERROR) << "space_to_depth only support NHWC now!"; return RET_FORMAT_ERR; } num_unit_ = static_cast<int>(out_tensors_.at(0)->shape().at(kNHWC_H)); thread_h_num_ = MSMIN(op_parameter_->thread_num_, num_unit_); if (thread_h_num_ == 0) { return RET_ERROR; } thread_h_stride_ = UP_DIV(num_unit_, thread_h_num_); return RET_OK; } int SpaceToDepthCPUKernel::SpaceToDepth(int task_id) { int num_unit_thread = MSMIN(thread_h_stride_, num_unit_ - task_id * thread_h_stride_); if (num_unit_thread <= 0) { return RET_OK; } int thread_offset = task_id * thread_h_stride_; auto in_shape = in_tensors_.at(0)->shape(); auto out_shape = out_tensors_.at(0)->shape(); SpaceToDepthParameter *param = reinterpret_cast<SpaceToDepthParameter *>(op_parameter_); MS_ASSERT(param); MS_ASSERT(input_ptr_); MS_ASSERT(output_ptr_); auto ret = SpaceToDepthForNHWC(input_ptr_, output_ptr_, in_shape.data(), out_shape.data(), in_shape.size(), param->block_size_, thread_offset, thread_offset + num_unit_thread, sizeof(float)); if (ret != RET_OK) { MS_LOG(ERROR) << "SpaceToDepth error task_id[" << task_id << "] error_code[" << ret << "]"; return RET_ERROR; } return RET_OK; } int SpaceToDepthRun(void *cdata, int task_id, float lhs_scale, float rhs_scale) { auto g_kernel = reinterpret_cast<SpaceToDepthCPUKernel *>(cdata); auto ret = g_kernel->SpaceToDepth(task_id); if (ret != RET_OK) { MS_LOG(ERROR) << "SpaceToDepthRun error task_id[" << task_id << "] error_code[" << ret << "]"; return RET_ERROR; } return RET_OK; } int SpaceToDepthCPUKernel::Run() { input_ptr_ = reinterpret_cast<float *>(in_tensors_.at(0)->data_c()); output_ptr_ = reinterpret_cast<float *>(out_tensors_.at(0)->data_c()); if (in_tensors_.at(0)->format() == mindspore::NHWC) { auto ret = ParallelLaunch(this->context_, SpaceToDepthRun, this, thread_h_num_); if (ret != RET_OK) { MS_LOG(ERROR) << "SpaceToDepth error error_code[" << ret << "]"; return ret; } } else { MS_LOG(ERROR) << "Only support NHWC now!"; return RET_ERROR; } return RET_OK; } REG_KERNEL(kCPU, kNumberTypeFloat32, PrimitiveType_SpaceToDepth, LiteKernelCreator<SpaceToDepthCPUKernel>) } // namespace mindspore::kernel
34.990991
116
0.716529
[ "shape", "vector" ]
66ff9b33e09ca1b71d879ad3d68a5c6d36f02a78
3,907
cxx
C++
examples/neural_network/binary_classifier.cxx
mmendez1012/PUJ_ML_APRENDIZAJE_MAQ
d09a8ed7e24d58bc7600d316b032dcd7fb21230b
[ "Unlicense" ]
null
null
null
examples/neural_network/binary_classifier.cxx
mmendez1012/PUJ_ML_APRENDIZAJE_MAQ
d09a8ed7e24d58bc7600d316b032dcd7fb21230b
[ "Unlicense" ]
null
null
null
examples/neural_network/binary_classifier.cxx
mmendez1012/PUJ_ML_APRENDIZAJE_MAQ
d09a8ed7e24d58bc7600d316b032dcd7fb21230b
[ "Unlicense" ]
null
null
null
// ========================================================================= // @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co) // ========================================================================= #include "ActivationFunctions.h" #include "NeuralNetwork.h" #include "CSVReader.h" #include <fstream> #include <iostream> #include <iomanip> #include <limits> #include <sstream> // -- Some typedefs using TPixel = unsigned short; using TScalar = double; // float | double | long double using TAnn = NeuralNetwork< TScalar >; // -- Main function int main( int argc, char** argv ) { // Check inputs and get them if( argc < 5 ) { std::cerr << "Usage: " << argv[ 0 ] << " input_examples.csv y_size alpha lambda" << std::endl; return( 1 ); } // end if std::string input_examples = argv[ 1 ]; std::stringstream args; args << argv[ 2 ] << " " << argv[ 3 ] << " " << argv[ 4 ]; std::istringstream iargs( args.str( ) ); int p; TScalar alpha, lambda; iargs >> p >> alpha >> lambda; // Read data CSVReader reader( input_examples, "," ); reader.read( ); TAnn::TMatrix X, Y; reader.cast( X, Y, p ); // Create an empty artifical neural network TAnn ann( 1e-6 ); /* TODO ann.add( X.cols( ), X.cols( ) * 4, ActivationFunctions::ReLU< TScalar >( ) ); ann.add( X.cols( ) * 3, ActivationFunctions::ReLU< TScalar >( ) ); ann.add( X.cols( ) * 2, ActivationFunctions::ReLU< TScalar >( ) ); ann.add( p, ActivationFunctions::Logistic< TScalar >( ) ); */ ann.add( X.cols( ), p, ActivationFunctions::Logistic< TScalar >( ) ); // Initialize the ANN with random weights and biases ann.init( true ); // Train the neural network ann.train( X, Y, alpha, lambda, &std::cout ); // Evaluate trained results TAnn::TMatrix K = ann.confusion_matrix( X, Y ); std::cout << "*******************" << std::endl << "***** Results *****" << std::endl << "*******************" << std::endl << "* Confusion matrix:" << std::endl << K << std::endl << std::setprecision( 4 ) << "* Sen (0) : " << ( 100.0 * ( K( 0, 0 ) / ( K( 0, 0 ) + K( 1, 0 ) ) ) ) << "%" << std::endl << "* PPV (0) : " << ( 100.0 * ( K( 0, 0 ) / ( K( 0, 0 ) + K( 0, 1 ) ) ) ) << "%" << std::endl << "* Spe (1) : " << ( 100.0 * ( K( 1, 1 ) / ( K( 1, 1 ) + K( 0, 1 ) ) ) ) << "%" << std::endl << "* NPV (1) : " << ( 100.0 * ( K( 1, 1 ) / ( K( 1, 1 ) + K( 1, 0 ) ) ) ) << "%" << std::endl << "* F1 : " << ( ( 2.0 * K( 0, 0 ) ) / ( ( 2.0 * K( 0, 0 ) ) + K( 0, 1 ) + K( 1, 0 ) ) ) << std::endl << "*******************" << std::endl; /* TODO if( X.cols( ) == 2 ) { auto minX = X.colwise( ).minCoeff( ); auto maxX = X.colwise( ).maxCoeff( ); auto difX = maxX - minX; unsigned long samples = 100; std::vector< TPixel > data( 3 * samples * samples ); unsigned long k = 0; for( unsigned long j = 0; j < samples; ++j ) { TScalar dj = difX( 0, 1 ) * TScalar( j ) / TScalar( samples ); dj += minX( 0, 1 ); for( unsigned long i = 0; i < samples; ++i ) { TScalar di = difX( 0, 0 ) * TScalar( i ) / TScalar( samples ); di += minX( 0, 0 ); TAnn::TColVector x( X.cols( ) ); x << di, dj; data[ k ] = TPixel( ann( x )( 0, 0 ) * TScalar( std::numeric_limits< TPixel >::max( ) ) ); data[ k + 1 ] = data[ k + 2 ] = data[ k ]; k += 3; } // end for } // end for // Save a file std::ofstream out( "ann.ppm" ); out << "P6" << std::endl << "# Result of a 2-class ANN" << std::endl << samples << " " << samples << std::endl << std::numeric_limits< TPixel >::max( ) << std::endl; out.write( reinterpret_cast< char* >( data.data( ) ), 3 * samples * samples ); out.close( ); } // end if */ return( 0 ); } // eof
29.824427
83
0.472741
[ "vector" ]
0f00aaaa290002f2595ebb2e0a0ee87ed7d81a36
14,018
cc
C++
src/vw/Cartography/shapeFile.cc
lucasz93/visionworkbench
1784572beda475e6770384f5cf34b578a320da51
[ "Apache-2.0" ]
null
null
null
src/vw/Cartography/shapeFile.cc
lucasz93/visionworkbench
1784572beda475e6770384f5cf34b578a320da51
[ "Apache-2.0" ]
null
null
null
src/vw/Cartography/shapeFile.cc
lucasz93/visionworkbench
1784572beda475e6770384f5cf34b578a320da51
[ "Apache-2.0" ]
null
null
null
// __BEGIN_LICENSE__ // Copyright (c) 2006-2013, United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. All // rights reserved. // // The NASA Vision Workbench is licensed under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // __END_LICENSE__ #include <vw/Cartography/shapeFile.h> #include <vector> #include <algorithm> #include <iostream> #include <cassert> #include <cfloat> #include <cassert> #include <cstring> #include <string> #include <map> #include <boost/filesystem/path.hpp> namespace vw { namespace geometry { // Convert a single polygon in a set of polygons to an ORG ring. void toOGR(const double * xv, const double * yv, int startPos, int numVerts, OGRLinearRing & R){ R = OGRLinearRing(); // init for (int vIter = 0; vIter < numVerts; vIter++){ double x = xv[startPos + vIter], y = yv[startPos + vIter]; R.addPoint(x, y); } // An OGRLinearRing must end with the same point as what it starts with double x = xv[startPos], y = yv[startPos]; if (numVerts >= 2 && x == xv[startPos + numVerts - 1] && y == yv[startPos + numVerts - 1]) { // Do nothing, the polygon already starts and ends with the same point }else{ // Ensure the ring is closed R.addPoint(x, y); } // A ring must have at least 4 points (but the first is same as last) if (R.getNumPoints() <= 3) R = OGRLinearRing(); } // Convert a set of polygons to OGR void toOGR(vw::geometry::dPoly const& poly, OGRPolygon & P){ P = OGRPolygon(); // reset const double * xv = poly.get_xv(); const double * yv = poly.get_yv(); const int * numVerts = poly.get_numVerts(); int numPolys = poly.get_numPolys(); // Iterate over polygon rings, adding them one by one int startPos = 0; for (int pIter = 0; pIter < numPolys; pIter++){ if (pIter > 0) startPos += numVerts[pIter - 1]; int numCurrPolyVerts = numVerts[pIter]; OGRLinearRing R; toOGR(xv, yv, startPos, numCurrPolyVerts, R); if (R.getNumPoints() >= 4 ){ if (P.addRing(&R) != OGRERR_NONE ) vw_throw(ArgumentErr() << "Failed add ring to polygon.\n"); } } return; } // Extract a polygon from OGR void fromOGR(OGRPolygon *poPolygon, std::string const& poly_color, std::string const& layer_str, vw::geometry::dPoly & poly){ bool isPolyClosed = true; // only closed polygons are supported poly.reset(); int numInteriorRings = poPolygon->getNumInteriorRings(); // Read exterior and interior rings int count = -1; while (1){ count++; OGRLinearRing *ring; if (count == 0){ // Exterior ring ring = poPolygon->getExteriorRing(); if (ring == NULL || ring->IsEmpty ()){ // No exterior ring, that means no polygon break; } }else{ // Interior rings int iRing = count - 1; if (iRing >= numInteriorRings) break; // no more rings ring = poPolygon->getInteriorRing(iRing); if (ring == NULL || ring->IsEmpty ()) continue; // go to the next ring } int numPoints = ring->getNumPoints(); std::vector<double> x, y; x.clear(); y.clear(); for (int iPt = 0; iPt < numPoints; iPt++){ OGRPoint poPoint; ring->getPoint(iPt, &poPoint); x.push_back(poPoint.getX()); y.push_back(poPoint.getY()); } // Don't record the last element if the same as the first int len = x.size(); if (len >= 2 && x[0] == x[len-1] && y[0] == y[len-1]){ len--; x.resize(len); y.resize(len); } poly.appendPolygon(len, vw::geometry::vecPtr(x), vw::geometry::vecPtr(y), isPolyClosed, poly_color, layer_str); } } // Extract a polygonal line (line string) from OGR void fromOGR(OGRLineString *poLineString, std::string const& poly_color, std::string const& layer_str, vw::geometry::dPoly & poly){ bool isPolyClosed = false; // polygonal lines are not closed poly.reset(); std::vector<double> x, y; x.clear(); y.clear(); int NumberOfVertices = poLineString ->getNumPoints(); for (int k = 0; k < NumberOfVertices; k++) { OGRPoint P; poLineString ->getPoint(k, &P); x.push_back(P.getX()); y.push_back(P.getY()); } poly.appendPolygon(x.size(), vw::geometry::vecPtr(x), vw::geometry::vecPtr(y), isPolyClosed, poly_color, layer_str); } // Extract a multi-polygon from OGR void fromOGR(OGRMultiPolygon *poMultiPolygon, std::string const& poly_color, std::string const& layer_str, std::vector<vw::geometry::dPoly> & polyVec, bool append){ if (!append) polyVec.clear(); int numGeom = poMultiPolygon->getNumGeometries(); for (int iGeom = 0; iGeom < numGeom; iGeom++){ const OGRGeometry *currPolyGeom = poMultiPolygon->getGeometryRef(iGeom); if (wkbFlatten(currPolyGeom->getGeometryType()) != wkbPolygon) continue; OGRPolygon *poPolygon = (OGRPolygon*) currPolyGeom; vw::geometry::dPoly poly; fromOGR(poPolygon, poly_color, layer_str, poly); polyVec.push_back(poly); } } // Read polygons from OGR geometry void fromOGR(OGRGeometry *poGeometry, std::string const& poly_color, std::string const& layer_str, std::vector<vw::geometry::dPoly> & polyVec, bool append){ if (!append) polyVec.clear(); if( poGeometry == NULL) { // nothing to do } else if (wkbFlatten(poGeometry->getGeometryType()) == wkbPoint ) { // Create a polygon with just one point OGRPoint *poPoint = (OGRPoint*)poGeometry; std::vector<double> x, y; x.push_back(poPoint->getX()); y.push_back(poPoint->getY()); vw::geometry::dPoly poly; bool isPolyClosed = true; // only closed polygons are supported poly.setPolygon(x.size(), vw::geometry::vecPtr(x), vw::geometry::vecPtr(y), isPolyClosed, poly_color, layer_str); polyVec.push_back(poly); } else if (wkbFlatten(poGeometry->getGeometryType()) == wkbMultiPolygon){ bool append = true; OGRMultiPolygon *poMultiPolygon = (OGRMultiPolygon*)poGeometry; fromOGR(poMultiPolygon, poly_color, layer_str, polyVec, append); } else if (wkbFlatten(poGeometry->getGeometryType()) == wkbPolygon){ OGRPolygon *poPolygon = (OGRPolygon*)poGeometry; vw::geometry::dPoly poly; fromOGR(poPolygon, poly_color, layer_str, poly); polyVec.push_back(poly); } else if (wkbFlatten (poGeometry ->getGeometryType() ) == wkbLineString) { OGRLineString *poLineString = (OGRLineString*)poGeometry; vw::geometry::dPoly poly; fromOGR(poLineString, poly_color, layer_str, poly); polyVec.push_back(poly); } } // Read a shapefile void read_shapefile(std::string const& file, std::string const& poly_color, bool & has_geo, vw::cartography::GeoReference & geo, std::vector<vw::geometry::dPoly> & polyVec){ // Make sure the outputs are initialized has_geo = false; geo = vw::cartography::GeoReference(); polyVec.clear(); std::string layer_str = boost::filesystem::path(file).stem().string(); vw_out() << "Reading layer " << layer_str << " from " << file << "\n"; GDALAllRegister(); GDALDataset * poDS; poDS = (GDALDataset*) GDALOpenEx(file.c_str(), GDAL_OF_VECTOR, NULL, NULL, NULL); if (poDS == NULL) vw_throw(ArgumentErr() << "Could not open file: " << file << ".\n"); OGRLayer *poLayer; poLayer = poDS->GetLayerByName( layer_str.c_str() ); if (poLayer == NULL) vw_throw(ArgumentErr() << "Could not find layer " << layer_str << " in file: " << file << ".\n"); // Read the georef int nGeomFieldCount = poLayer->GetLayerDefn()->GetGeomFieldCount(); char *pszWKT = NULL; if (nGeomFieldCount > 1) { for(int iGeom = 0; iGeom < nGeomFieldCount; iGeom ++ ){ OGRGeomFieldDefn* poGFldDefn = poLayer->GetLayerDefn()->GetGeomFieldDefn(iGeom); OGRSpatialReference* poSRS = poGFldDefn->GetSpatialRef(); if( poSRS == NULL ) pszWKT = CPLStrdup( "(unknown)" ); else { has_geo = true; poSRS->exportToPrettyWkt(&pszWKT); // Stop at the first geom break; } } }else{ if( poLayer->GetSpatialRef() == NULL ) pszWKT = CPLStrdup( "(unknown)" ); else{ has_geo = true; poLayer->GetSpatialRef()->exportToPrettyWkt(&pszWKT); } } geo.set_wkt(pszWKT); if (pszWKT != NULL) CPLFree( pszWKT ); // There is no georef per se, as there is no image. The below forces // that the map from projected coordinates to pixel coordinates (point_to_pixel()) // to be the identity. geo.set_pixel_interpretation(vw::cartography::GeoReference::PixelAsPoint); OGRFeature *poFeature; poLayer->ResetReading(); while ( (poFeature = poLayer->GetNextFeature()) != NULL ) { OGRGeometry *poGeometry = poFeature->GetGeometryRef(); bool append = true; fromOGR(poGeometry, poly_color, layer_str, polyVec, append); OGRFeature::DestroyFeature(poFeature); } GDALClose( poDS ); // See if the georef should have lon in [-180, 180], or in [0, 360]. This is fragile. if (!geo.is_projected()) { // Find the bounding box of all polygons BBox2 lon_lat_box; for (int s = 0; s < (int)polyVec.size(); s++) { vw::geometry::dPoly const& poly = polyVec[s]; double xll, yll, xur, yur; poly.bdBox(xll, yll, xur, yur); lon_lat_box.grow(Vector2(xll, yll)); lon_lat_box.grow(Vector2(xur, yur)); } // Change it only if we have to. if (lon_lat_box.min().x() < 0.0) { bool centered_on_lon_zero = true; geo.set_lon_center(centered_on_lon_zero); } if (lon_lat_box.max().x() > 180.0) { bool centered_on_lon_zero = false; geo.set_lon_center(centered_on_lon_zero); } } } // Write a shapefile void write_shapefile(std::string const& file, bool has_geo, vw::cartography::GeoReference const& geo, std::vector<vw::geometry::dPoly> const& polyVec){ std::string layer_str = boost::filesystem::path(file).stem().string(); const char *pszDriverName = "ESRI Shapefile"; GDALDriver *poDriver; GDALAllRegister(); poDriver = GetGDALDriverManager()->GetDriverByName(pszDriverName); if (poDriver == NULL ) vw_throw(ArgumentErr() << "Could not find driver: " << pszDriverName << ".\n"); GDALDataset *poDS; poDS = poDriver->Create(file.c_str(), 0, 0, 0, GDT_Unknown, NULL ); if (poDS == NULL) vw_throw(ArgumentErr() << "Failed writing file: " << file << ".\n"); // Write the georef OGRSpatialReference spatial_ref; OGRSpatialReference * spatial_ref_ptr = NULL; if (has_geo){ std::string srs_string = geo.get_wkt(); if (spatial_ref.SetFromUserInput( srs_string.c_str() )) vw_throw( ArgumentErr() << "Failed to parse: \"" << srs_string << "\"." ); spatial_ref_ptr = &spatial_ref; } OGRLayer *poLayer = poDS->CreateLayer(layer_str.c_str(), spatial_ref_ptr, wkbPolygon, NULL ); if (poLayer == NULL) vw_throw(ArgumentErr() << "Failed creating layer: " << layer_str << ".\n"); #if 0 OGRFieldDefn oField( "Name", OFTString ); oField.SetWidth(32); if( poLayer->CreateField( &oField ) != OGRERR_NONE ) vw_throw(ArgumentErr() << "Failed creating name field for layer: " << layer_str << ".\n"); #endif for (size_t vecIter = 0; vecIter < polyVec.size(); vecIter++){ vw::geometry::dPoly const& poly = polyVec[vecIter]; // alias if (poly.get_totalNumVerts() == 0) continue; OGRFeature *poFeature = OGRFeature::CreateFeature( poLayer->GetLayerDefn() ); #if 0 poFeature->SetField( "Name", "ToBeFilledIn" ); #endif OGRPolygon P; toOGR(poly, P); poFeature->SetGeometry(&P); if (poLayer->CreateFeature( poFeature ) != OGRERR_NONE) vw_throw(ArgumentErr() << "Failed to create feature in shape file.\n"); OGRFeature::DestroyFeature( poFeature ); } GDALClose( poDS ); } // Bounding box of a shapefile void shapefile_bdbox(const std::vector<vw::geometry::dPoly> & polyVec, // outputs double & xll, double & yll, double & xur, double & yur){ double big = std::numeric_limits<double>::max(); xll = big; yll = big; xur = -big; yur = -big; for (size_t p = 0; p < polyVec.size(); p++){ if (polyVec[p].get_totalNumVerts() == 0) continue; double xll0, yll0, xur0, yur0; polyVec[p].bdBox(xll0, yll0, xur0, yur0); xll = std::min(xll, xll0); xur = std::max(xur, xur0); yll = std::min(yll, yll0); yur = std::max(yur, yur0); } return; } }}
32.6
89
0.599943
[ "geometry", "shape", "vector" ]
0f06aec9bbf668ba7ae9d9a3383de57e23b6bf15
3,274
cpp
C++
src/ObjectManipulation.cpp
Charan-Karthikeyan/warehouse_material_handiling_turtlebot
b26bf6d1af866334df45129761bac150569e26fd
[ "MIT" ]
null
null
null
src/ObjectManipulation.cpp
Charan-Karthikeyan/warehouse_material_handiling_turtlebot
b26bf6d1af866334df45129761bac150569e26fd
[ "MIT" ]
3
2019-12-08T22:25:41.000Z
2019-12-10T02:39:55.000Z
src/ObjectManipulation.cpp
Charan-Karthikeyan/warehouse_material_handiling_turtlebot
b26bf6d1af866334df45129761bac150569e26fd
[ "MIT" ]
1
2019-12-11T01:11:27.000Z
2019-12-11T01:11:27.000Z
/** * MIT License * * Copyright (c) 2019 Charan Karthikeyan P V, Nagireddi Jagadesh Nischal * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without * limitation the rights to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of the Software, and to permit persons to * whom the Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ /** * @file ObjectManipulation.cpp * @author Charan Karthikeyan P V (Navigator), Nagireddi Jagadesh Nischal (Driver) * @copyright MIT License. * @date 2/12/2019 * @brief Cpp file for class to manipulate objects when Turtlebot reaches pick up or drop off * locations in the map */ #include "../include/warehouse_material_handling_turtlebot/ObjectManipulation.h" #include "ros/ros.h" /* * @brief The constructor for the ObjectManipulation class. * @param None. * @return None. */ ObjectManipulation::ObjectManipulation() { } /* * @brief The destructor for the ObjectManipulation class. * @param None. * @return None. */ ObjectManipulation::~ObjectManipulation() { } std::string ObjectManipulation::setTargetPoint(double targetPoint) { std::ostringstream conv; // Convert the input to string conv << targetPoint; return conv.str(); } std::string ObjectManipulation::showObject(double x, double y) { // Converting the double values to string std::string g_x = setTargetPoint(x); std::string g_y = setTargetPoint(y); // rosrun file for spawning the object in gazebo. std::string start = "rosrun gazebo_ros spawn_model " "-file src/warehouse_material_handling_turtlebot/" "data/gazebo_models/beer/model.sdf -sdf "; std::string x_vals = "-x "; std::string y_vals = " -y "; std::string end = " -z 0 -model beer"; // Joining all the strings to form the command. std::string cmd = start+x_vals+g_x+y_vals+g_y+end; const char* command = cmd.c_str(); ROS_INFO("Set the objects in the map "); // Sending the command to the system. system(command); return cmd; } std::string ObjectManipulation::disappearObject() { // Rosservice to remove the model from the gazebo environment. std::string destroy = "rosservice call /gazebo/delete_model"; std::string cont = " beer"; // Joining the string to form the command. std::string cmd = destroy+cont; const char* command = cmd.c_str(); ROS_INFO("Removed the Object from the map"); // Send the command to the system to execute. system(command); return cmd; }
35.204301
93
0.724496
[ "object", "model" ]
0f0d6e4a3344dff857c112a1493215725bfbcc97
47,958
cpp
C++
blast/src/objtools/readers/gvf_reader.cpp
mycolab/ncbi-blast
e59746cec78044d2bf6d65de644717c42f80b098
[ "Apache-2.0" ]
null
null
null
blast/src/objtools/readers/gvf_reader.cpp
mycolab/ncbi-blast
e59746cec78044d2bf6d65de644717c42f80b098
[ "Apache-2.0" ]
null
null
null
blast/src/objtools/readers/gvf_reader.cpp
mycolab/ncbi-blast
e59746cec78044d2bf6d65de644717c42f80b098
[ "Apache-2.0" ]
null
null
null
/* $Id: gvf_reader.cpp 632531 2021-06-02 17:25:37Z ivanov $ * =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * * Author: Frank Ludwig * * File Description: * GVF file reader * */ #include <ncbi_pch.hpp> #include <corelib/ncbistd.hpp> #include <util/line_reader.hpp> #include <objects/general/User_object.hpp> #include <objects/general/Dbtag.hpp> #include <objects/seqloc/Seq_interval.hpp> #include <objects/seqloc/Seq_point.hpp> #include <objects/seq/Seq_annot.hpp> #include <objects/seq/Annot_id.hpp> #include <objects/seq/Annot_descr.hpp> #include <objects/seq/Seq_literal.hpp> #include <objects/seqfeat/Variation_ref.hpp> #include <objects/seqfeat/VariantProperties.hpp> #include <objects/seqfeat/Variation_inst.hpp> #include <objtools/readers/gvf_reader.hpp> #include "reader_message_handler.hpp" #include <algorithm> #define NCBI_USE_ERRCODE_X Objtools_Rd_RepMask BEGIN_NCBI_SCOPE BEGIN_objects_SCOPE // namespace ncbi::objects:: typedef map<string, CVariantProperties::EAllele_state> TAlleleStateMap; // ---------------------------------------------------------------------------- const TAlleleStateMap& s_AlleleStateMap() // ---------------------------------------------------------------------------- { static CSafeStatic<TAlleleStateMap> s_Map; TAlleleStateMap& m = *s_Map; if ( m.empty() ) { m["heterozygous"] = CVariantProperties::eAllele_state_heterozygous; m["homozygous"] = CVariantProperties::eAllele_state_homozygous; m["hemizygous"] = CVariantProperties::eAllele_state_hemizygous; } return m; } // ---------------------------------------------------------------------------- bool CGvfReadRecord::AssignFromGff( const string& strGff ) // ---------------------------------------------------------------------------- { if ( ! CGff3ReadRecord::AssignFromGff( strGff ) ) { return false; } // GVF specific fixup goes here ... TAttrIt idIt = m_Attributes.find("ID"); if (idIt == m_Attributes.end()) { CReaderMessage fatal( eDiag_Error, 0, "Mandatory attribute ID missing."); throw fatal; } TAttrIt variantSeqIt = m_Attributes.find("Variant_seq"); TAttrIt referenceSeqIt = m_Attributes.find("Reference_seq"); if (variantSeqIt == m_Attributes.end() || referenceSeqIt == m_Attributes.end()) { CReaderMessage fatal( eDiag_Error, 0, "Mandatory attribute Reference_seq and/or Variant_seq missing."); throw fatal; } return true; } // ---------------------------------------------------------------------------- bool CGvfReadRecord::xAssignAttributesFromGff( const string& strGffType, const string& strRawAttributes ) // ---------------------------------------------------------------------------- { vector< string > attributes; xSplitGffAttributes(strRawAttributes, attributes); for ( size_t u=0; u < attributes.size(); ++u ) { string strKey; string strValue; if ( ! NStr::SplitInTwo( attributes[u], "=", strKey, strValue ) ) { if ( ! NStr::SplitInTwo( attributes[u], " ", strKey, strValue ) ) { return false; } } strKey = x_NormalizedAttributeKey( strKey ); strValue = xNormalizedAttributeValue( strValue ); if ( strKey.empty() && strValue.empty() ) { // Probably due to trailing "; ". Sequence Ontology generates such // things. continue; } if ( strKey == "Dbxref" ) { TAttrIt it = m_Attributes.find( strKey ); if ( it != m_Attributes.end() ) { m_Attributes[ strKey ] += ";"; m_Attributes[ strKey ] += strValue; continue; } } m_Attributes[ strKey ] = strValue; } return true; } // ---------------------------------------------------------------------------- bool CGvfReadRecord::SanityCheck() const // ---------------------------------------------------------------------------- { return true; } // ---------------------------------------------------------------------------- CGvfReader::CGvfReader( unsigned int uFlags, const string& name, const string& title, CReaderListener* pRL): // ---------------------------------------------------------------------------- CGff3Reader(uFlags, name, title, CReadUtil::AsSeqId, pRL) { } // ---------------------------------------------------------------------------- CGvfReader::~CGvfReader() // ---------------------------------------------------------------------------- { } // ---------------------------------------------------------------------------- CRef<CSeq_annot> CGvfReader::ReadSeqAnnot( ILineReader& lineReader, ILineErrorListener* pEC ) // ---------------------------------------------------------------------------- { return CReaderBase::ReadSeqAnnot(lineReader, pEC); } // ---------------------------------------------------------------------------- void CGvfReader::xGetData( ILineReader& lr, TReaderData& readerData) // ---------------------------------------------------------------------------- { return CReaderBase::xGetData(lr, readerData); } // ---------------------------------------------------------------------------- void CGvfReader::xProcessData( const TReaderData& readerData, CSeq_annot& annot) // ---------------------------------------------------------------------------- { for (const auto& lineData: readerData) { const auto& line = lineData.mData; if (xParseStructuredComment(line)) { continue; } if (xParseBrowserLine(line, annot)) { continue; } if (xParseFeature(line, annot, nullptr)) { continue; } } } // ---------------------------------------------------------------------------- bool CGvfReader::xParseFeature( const string& line, CSeq_annot& annot, ILineErrorListener* pEC) // ---------------------------------------------------------------------------- { CGvfReadRecord record(m_uLineNumber); if (!record.AssignFromGff(line)) { return false; } if (!xMergeRecord(record, annot, pEC)) { return false; } ++mCurrentFeatureCount; return true; } // ---------------------------------------------------------------------------- void CGvfReader::xPostProcessAnnot( CSeq_annot& annot) // ---------------------------------------------------------------------------- { xAddConversionInfo(annot, nullptr); xAssignTrackData(annot); xAssignAnnotId(annot); if (m_Pragmas) { annot.SetDesc().Set().push_back(m_Pragmas); } } // ---------------------------------------------------------------------------- CRef<CSeq_annot> CGvfReader::x_GetAnnotById( TAnnots& annots, const string& strId ) // ---------------------------------------------------------------------------- { for ( TAnnotIt it = annots.begin(); it != annots.end(); ++it ) { CSeq_annot& annot = **it; if ( ! annot.CanGetId() || annot.GetId().size() != 1 ) { // internal error return CRef<CSeq_annot>(); } CRef< CAnnot_id > pId = *( annot.GetId().begin() ); if ( ! pId->IsLocal() ) { // internal error return CRef<CSeq_annot>(); } if ( strId == pId->GetLocal().GetStr() ) { return *it; } } CRef<CSeq_annot> pNewAnnot( new CSeq_annot ); annots.insert(annots.begin(), pNewAnnot); CRef< CAnnot_id > pAnnotId( new CAnnot_id ); pAnnotId->SetLocal().SetStr( strId ); pNewAnnot->SetId().push_back( pAnnotId ); pNewAnnot->SetData().SetFtable(); // if available, add current browser information if ( m_CurrentBrowserInfo ) { pNewAnnot->SetDesc().Set().push_back( m_CurrentBrowserInfo ); } // if available, add current track information if (m_pTrackDefaults->ContainsData()) { xAssignTrackData(*pNewAnnot); } if ( !m_AnnotName.empty() ) { pNewAnnot->SetNameDesc(m_AnnotName); } if ( !m_AnnotTitle.empty() ) { pNewAnnot->SetTitleDesc(m_AnnotTitle); } // if available, add gvf pragma information if ( m_Pragmas ) { pNewAnnot->SetDesc().Set().push_back( m_Pragmas ); } return pNewAnnot; } // ---------------------------------------------------------------------------- bool CGvfReader::xMergeRecord( const CGvfReadRecord& record, CSeq_annot& annot, ILineErrorListener* pMessageListener) // ---------------------------------------------------------------------------- { if ( ! record.SanityCheck() ) { return false; } CRef< CSeq_feat > pFeature( new CSeq_feat ); if ( ! xFeatureSetLocation( record, *pFeature ) ) { return false; } if ( ! xFeatureSetVariation( record, *pFeature ) ) { return false; } if ( ! xFeatureSetExt( record, *pFeature, pMessageListener ) ) { return false; } annot.SetData().SetFtable().push_back( pFeature ); return true; } // ---------------------------------------------------------------------------- bool CGvfReader::xFeatureSetLocation( const CGff2Record& record, CSeq_feat& feature ) // ---------------------------------------------------------------------------- { if (record.SeqStart() < record.SeqStop()) { return xFeatureSetLocationInterval(record, feature); } else {// record.SeqStart() == record.SeqStop() return xFeatureSetLocationPoint(record, feature); } } // ---------------------------------------------------------------------------- bool CGvfReader::xSetLocation( const CGff2Record& record, CSeq_loc& location) // ---------------------------------------------------------------------------- { if (record.SeqStart() < record.SeqStop()) { return xSetLocationInterval(record, location); } else { // record.SeqStart() == record.SeqStop() return xSetLocationPoint(record, location); } } // ---------------------------------------------------------------------------- bool CGvfReader::xSetLocationInterval( const CGff2Record& record, CSeq_loc& location) // ---------------------------------------------------------------------------- { CRef< CSeq_id > pId = mSeqIdResolve(record.Id(), m_iFlags, true); location.SetInt().SetId(*pId); location.SetInt().SetFrom(record.SeqStart()); location.SetInt().SetTo(record.SeqStop()); if (record.IsSetStrand()) { location.SetInt().SetStrand( record.Strand() ); } // deal with fuzzy range indicators / lower end: string strRange; list<string> range_borders; TSeqPos lower, upper; if (record.GetAttribute( "Start_range", strRange ) ) { NStr::Split( strRange, ",", range_borders, 0 ); if ( range_borders.size() != 2 ) { CReaderMessage error( eDiag_Error, m_uLineNumber, "Bad Start_range attribute: Start_range=" + strRange + "."); throw error; } try { if ( range_borders.back() == "." ) { lower = upper = NStr::StringToUInt( range_borders.front() ); location.SetInt().SetFuzz_from().SetLim( CInt_fuzz::eLim_gt ); } else if ( range_borders.front() == "." ) { lower = upper = NStr::StringToUInt( range_borders.back() ); location.SetInt().SetFuzz_from().SetLim( CInt_fuzz::eLim_lt ); } else { lower = NStr::StringToUInt( range_borders.front() ); upper = NStr::StringToUInt( range_borders.back() ); location.SetInt().SetFuzz_from().SetRange().SetMin( lower-1 ); location.SetInt().SetFuzz_from().SetRange().SetMax( upper-1 ); } } catch ( std::exception& ) { CReaderMessage error( eDiag_Error, m_uLineNumber, "Bad Start_range attribute: Start_range=" + strRange + "."); throw error; } } // deal with fuzzy range indicators / upper end: range_borders.clear(); if (record.GetAttribute( "End_range", strRange ) ) { NStr::Split( strRange, ",", range_borders, 0 ); if ( range_borders.size() != 2 ) { CReaderMessage error( eDiag_Error, m_uLineNumber, "Bad End_range attribute: End_range=" + strRange + "."); throw error; } try { if ( range_borders.back() == "." ) { lower = upper = NStr::StringToUInt( range_borders.front() ); location.SetInt().SetFuzz_to().SetLim( CInt_fuzz::eLim_gt ); } else if ( range_borders.front() == "." ) { lower = upper = NStr::StringToUInt( range_borders.back() ); location.SetInt().SetFuzz_to().SetLim( CInt_fuzz::eLim_lt ); } else { lower = NStr::StringToUInt( range_borders.front() ); upper = NStr::StringToUInt( range_borders.back() ); location.SetInt().SetFuzz_to().SetRange().SetMin( lower-1 ); location.SetInt().SetFuzz_to().SetRange().SetMax( upper-1 ); } } catch (std::exception&) { CReaderMessage error( eDiag_Error, m_uLineNumber, "Bad End_range attribute: End_range=" + strRange + "."); throw error; } } return true; } // ---------------------------------------------------------------------------- bool CGvfReader::xSetLocationPoint( const CGff2Record& record, CSeq_loc& location) // ---------------------------------------------------------------------------- { CRef< CSeq_id > pId = mSeqIdResolve(record.Id(), m_iFlags, true); location.SetPnt().SetId(*pId); if (record.Type() == "insertion") { //for insertions, GVF uses insert-after logic while NCBI uses insert-before location.SetPnt().SetPoint(record.SeqStart()+1); } else { location.SetPnt().SetPoint(record.SeqStart()); } if (record.IsSetStrand()) { location.SetStrand(record.Strand()); } string strRangeLower, strRangeUpper; bool hasLower = record.GetAttribute("Start_range", strRangeLower); bool hasUpper = record.GetAttribute("End_range", strRangeUpper); if (hasLower && hasUpper && strRangeLower != strRangeUpper) { CReaderMessage error( eDiag_Error, m_uLineNumber, "Bad range attribute: Conflicting fuzz ranges for single point location."); throw error; } if (!hasLower && !hasUpper) { return true; } if (!hasLower) { strRangeLower = strRangeUpper; } list<string> bounds; TSeqPos lower, upper; NStr::Split( strRangeLower, ",", bounds, 0 ); if (bounds.size() != 2) { CReaderMessage error( eDiag_Error, m_uLineNumber, "Bad range attribute: XXX_range=" + strRangeLower + "."); throw error; } try { if (bounds.back() == ".") { lower = upper = NStr::StringToUInt(bounds.front()); location.SetPnt().SetFuzz().SetLim(CInt_fuzz::eLim_gt); } else if (bounds.front() == ".") { lower = upper = NStr::StringToUInt(bounds.back()); location.SetPnt().SetFuzz().SetLim( CInt_fuzz::eLim_lt ); } else { lower = NStr::StringToUInt(bounds.front()); upper = NStr::StringToUInt(bounds.back()); location.SetPnt().SetFuzz().SetRange().SetMin(lower-1); location.SetPnt().SetFuzz().SetRange().SetMax(upper-1); } } catch (std::exception&) { CReaderMessage error( eDiag_Error, m_uLineNumber, "Bad range attribute: XXX_range=" + strRangeLower + "."); throw error; } return true; } // ---------------------------------------------------------------------------- bool CGvfReader::xFeatureSetLocationInterval( const CGff2Record& record, CSeq_feat& feature ) // ---------------------------------------------------------------------------- { CRef< CSeq_id > pId = mSeqIdResolve(record.Id(), m_iFlags, true); CRef< CSeq_loc > pLocation( new CSeq_loc ); pLocation->SetInt().SetId(*pId); pLocation->SetInt().SetFrom(record.SeqStart()); pLocation->SetInt().SetTo(record.SeqStop()); if (record.IsSetStrand()) { pLocation->SetInt().SetStrand( record.Strand() ); } // deal with fuzzy range indicators / lower end: string strRange; list<string> range_borders; TSeqPos lower, upper; if (record.GetAttribute( "Start_range", strRange ) ) { NStr::Split( strRange, ",", range_borders, 0 ); if ( range_borders.size() != 2 ) { CReaderMessage error( eDiag_Error, m_uLineNumber, "Bad Start_range attribute: Start_range=" + strRange + "."); throw error; } try { if ( range_borders.back() == "." ) { lower = upper = NStr::StringToUInt( range_borders.front() ); pLocation->SetInt().SetFuzz_from().SetLim( CInt_fuzz::eLim_gt ); } else if ( range_borders.front() == "." ) { lower = upper = NStr::StringToUInt( range_borders.back() ); pLocation->SetInt().SetFuzz_from().SetLim( CInt_fuzz::eLim_lt ); } else { lower = NStr::StringToUInt( range_borders.front() ); upper = NStr::StringToUInt( range_borders.back() ); pLocation->SetInt().SetFuzz_from().SetRange().SetMin( lower-1 ); pLocation->SetInt().SetFuzz_from().SetRange().SetMax( upper-1 ); } } catch ( std::exception& ) { CReaderMessage error( eDiag_Error, m_uLineNumber, "Bad Start_range attribute: Start_range=" + strRange + "."); throw error; } } // deal with fuzzy range indicators / upper end: range_borders.clear(); if (record.GetAttribute( "End_range", strRange ) ) { NStr::Split( strRange, ",", range_borders, 0 ); if ( range_borders.size() != 2 ) { CReaderMessage error( eDiag_Error, m_uLineNumber, "Bad End_range attribute: End_range=" + strRange + "."); throw error; } try { if ( range_borders.back() == "." ) { lower = upper = NStr::StringToUInt( range_borders.front() ); pLocation->SetInt().SetFuzz_to().SetLim( CInt_fuzz::eLim_gt ); } else if ( range_borders.front() == "." ) { lower = upper = NStr::StringToUInt( range_borders.back() ); pLocation->SetInt().SetFuzz_to().SetLim( CInt_fuzz::eLim_lt ); } else { lower = NStr::StringToUInt( range_borders.front() ); upper = NStr::StringToUInt( range_borders.back() ); pLocation->SetInt().SetFuzz_to().SetRange().SetMin( lower-1 ); pLocation->SetInt().SetFuzz_to().SetRange().SetMax( upper-1 ); } } catch (std::exception&) { CReaderMessage error( eDiag_Error, m_uLineNumber, "Bad End_range attribute: End_range=" + strRange + "."); throw error; } } feature.SetLocation( *pLocation ); return true; } // ---------------------------------------------------------------------------- bool CGvfReader::xFeatureSetLocationPoint( const CGff2Record& record, CSeq_feat& feature ) // ---------------------------------------------------------------------------- { CRef< CSeq_id > pId = mSeqIdResolve(record.Id(), m_iFlags, true); CRef< CSeq_loc > pLocation( new CSeq_loc ); pLocation->SetPnt().SetId(*pId); if (record.Type() == "insertion") { //for insertions, GVF uses insert-after logic while NCBI uses insert-before pLocation->SetPnt().SetPoint(record.SeqStart()+1); } else { pLocation->SetPnt().SetPoint(record.SeqStart()); } if (record.IsSetStrand()) { pLocation->SetStrand(record.Strand()); } string strRangeLower, strRangeUpper; bool hasLower = record.GetAttribute("Start_range", strRangeLower); bool hasUpper = record.GetAttribute("End_range", strRangeUpper); if (hasLower && hasUpper && strRangeLower != strRangeUpper) { CReaderMessage error( eDiag_Error, m_uLineNumber, "Bad range attribute: Conflicting fuzz ranges for single point location."); throw error; } if (!hasLower && !hasUpper) { feature.SetLocation(*pLocation); return true; } if (!hasLower) { strRangeLower = strRangeUpper; } list<string> bounds; TSeqPos lower, upper; NStr::Split( strRangeLower, ",", bounds, 0 ); if (bounds.size() != 2) { CReaderMessage error( eDiag_Error, m_uLineNumber, "Bad range attribute: XXX_range=" + strRangeLower + "."); throw error; } try { if (bounds.back() == ".") { lower = upper = NStr::StringToUInt(bounds.front()); pLocation->SetPnt().SetFuzz().SetLim(CInt_fuzz::eLim_gt); } else if (bounds.front() == ".") { lower = upper = NStr::StringToUInt(bounds.back()); pLocation->SetPnt().SetFuzz().SetLim( CInt_fuzz::eLim_lt ); } else { lower = NStr::StringToUInt(bounds.front()); upper = NStr::StringToUInt(bounds.back()); pLocation->SetPnt().SetFuzz().SetRange().SetMin(lower-1); pLocation->SetPnt().SetFuzz().SetRange().SetMax(upper-1); } } catch (std::exception&) { CReaderMessage error( eDiag_Error, m_uLineNumber, "Bad range attribute: XXX_range=" + strRangeLower + "."); throw error; } feature.SetLocation( *pLocation ); return true; } // ---------------------------------------------------------------------------- bool CGvfReader::xIsDbvarCall(const string& nameAttr) const // ---------------------------------------------------------------------------- { return (nameAttr.find("ssv") != string::npos); } // ---------------------------------------------------------------------------- bool CGvfReader::xGetNameAttribute(const CGvfReadRecord& record, string& name) const // ---------------------------------------------------------------------------- { if ( record.GetAttribute( "Name", name ) ) { return true; } return false; } // ---------------------------------------------------------------------------- bool CGvfReader::xFeatureSetVariation( const CGvfReadRecord& record, CSeq_feat& feature ) // ---------------------------------------------------------------------------- { CRef<CVariation_ref> pVariation(new CVariation_ref); string strType = record.NormalizedType(); string nameAttr; xGetNameAttribute(record, nameAttr); if ( strType == "snv" ) { if (!xVariationMakeSNV( record, *pVariation )) { return false; } } else if (strType == "insertion" || strType == "alu_insertion" || strType == "line1_insertion" || strType == "sva_insertion" || strType == "mobile_element_insertion" || strType == "mobile_sequence_insertion" || strType == "novel_sequence_insertion") { if (!xVariationMakeInsertions( record, *pVariation )) { return false; } } else if (strType == "deletion" || strType == "alu_deletion" || strType == "line1_deletion" || strType == "sva_deletion" || strType == "herv_deletion" || (strType == "mobile_element_deletion" && xIsDbvarCall(nameAttr))) { if (!xVariationMakeDeletions( record, *pVariation )) { return false; } } else if (strType == "indel") { if (!xVariationMakeIndels( record, *pVariation )) { return false; } } else if (strType == "inversion") { if (!xVariationMakeInversions( record, *pVariation )) { return false; } } else if (strType == "tandem_duplication") { if (!xVariationMakeEversions( record, *pVariation )) { return false; } } else if (strType == "translocation" || strType == "interchromosomal_translocation" || strType == "intrachromosomal_translocation") { if (!xVariationMakeTranslocations( record, *pVariation )) { return false; } } else if (strType == "complex" || strType == "complex_substitution" || strType == "complex_chromosomal_rearrangement" || strType == "complex_sequence_alteration") { if (!xVariationMakeComplex( record, *pVariation )){ return false; } } else if (strType == "unknown" || strType == "other" || strType == "sequence_alteration") { if (!xVariationMakeUnknown( record, *pVariation )){ return false; } } else { if (!xVariationMakeCNV( record, *pVariation )) { return false; } } if ( pVariation ) { feature.SetData().SetVariation( *pVariation ); return true; } return false; } // ---------------------------------------------------------------------------- bool CGvfReader::xParseStructuredComment( const string& strLine) // ---------------------------------------------------------------------------- { if ( !CGff2Reader::xParseStructuredComment( strLine) ) { return false; } if ( ! m_Pragmas ) { m_Pragmas.Reset( new CAnnotdesc ); m_Pragmas->SetUser().SetType().SetStr( "gvf-import-pragmas" ); } string key, value; NStr::SplitInTwo(strLine.substr(2), " ", key, value); m_Pragmas->SetUser().AddField(key, value); return true; } // ---------------------------------------------------------------------------- bool CGvfReader::xVariationSetInsertions( const CGvfReadRecord& record, CVariation_ref& variation) // ---------------------------------------------------------------------------- { CRef<CVariation_ref> pReference(new CVariation_ref); pReference->SetData().SetInstance().SetType( CVariation_inst::eType_identity); CRef<CDelta_item> pDelta(new CDelta_item); pDelta->SetSeq().SetThis(); pReference->SetData().SetInstance().SetDelta().push_back(pDelta); pReference->SetData().SetInstance().SetObservation( CVariation_inst::eObservation_asserted); variation.SetData().SetSet().SetVariations().push_back( pReference ); string strAlleles; if ( record.GetAttribute( "Variant_seq", strAlleles ) ) { list<string> alleles; NStr::Split( strAlleles, ",", alleles, 0 ); alleles.sort(); alleles.unique(); for ( list<string>::const_iterator cit = alleles.begin(); cit != alleles.end(); ++cit ) { string allele(*cit); if (allele == "-") { pReference->SetVariant_prop().SetAllele_state( (alleles.size() == 1) ? CVariantProperties::eAllele_state_homozygous : CVariantProperties::eAllele_state_heterozygous); pReference->SetData().SetInstance().SetObservation( CVariation_inst::eObservation_asserted | CVariation_inst::eObservation_variant); continue; } CRef<CVariation_ref> pAllele(new CVariation_ref); //if (allele == strReference) { // continue; //} if (alleles.size() == 1) { pAllele->SetVariant_prop().SetAllele_state( CVariantProperties::eAllele_state_homozygous); } else { pAllele->SetVariant_prop().SetAllele_state( CVariantProperties::eAllele_state_heterozygous); } ///pAllele->SetInsertion(allele, CVariation_ref::eSeqType_na); CRef<CDelta_item> pDelta(new CDelta_item); pDelta->SetSeq().SetLiteral().SetLength( static_cast<TSeqPos>(allele.size())); pDelta->SetSeq().SetLiteral().SetSeq_data().SetIupacna().Set(allele); pDelta->SetAction(CDelta_item::eAction_ins_before); pAllele->SetData().SetInstance().SetDelta().push_back(pDelta); pAllele->SetData().SetInstance().SetType(CVariation_inst::eType_ins); pAllele->SetData().SetInstance().SetObservation( CVariation_inst::eObservation_variant ); variation.SetData().SetSet().SetVariations().push_back( pAllele ); } } return true; } // ---------------------------------------------------------------------------- bool CGvfReader::xVariationMakeCNV( const CGvfReadRecord& record, CVariation_ref& variation ) // ---------------------------------------------------------------------------- { if (!xVariationSetId(record, variation)) { return false; } if (!xVariationSetParent(record, variation)) { return false; } if (!xVariationSetName(record, variation)) { return false; } string nameAttr; xGetNameAttribute(record, nameAttr); string strType = record.NormalizedType(); if ( strType == "cnv" || strType == "copy_number_variation" ) { variation.SetCNV(); return true; } if ( strType == "gain" || strType == "copy_number_gain" || strType == "duplication" ) { variation.SetGain(); return true; } if ( strType == "loss" || strType == "copy_number_loss" || (strType == "mobile_element_deletion" && !xIsDbvarCall(nameAttr)) ) { variation.SetLoss(); return true; } if ( strType == "loss_of_heterozygosity" ) { variation.SetLoss(); CRef<CVariation_ref::C_E_Consequence> pConsequence( new CVariation_ref::C_E_Consequence ); pConsequence->SetLoss_of_heterozygosity(); variation.SetConsequence().push_back( pConsequence ); return true; } CReaderMessage error( eDiag_Error, m_uLineNumber, "Bad data line: Unknown type \"" + strType + "\"."); throw error; } // ---------------------------------------------------------------------------- bool CGvfReader::xVariationSetCommon( const CGvfReadRecord& record, CVariation_ref& variation) // ---------------------------------------------------------------------------- { variation.SetData().SetSet().SetType( CVariation_ref::C_Data::C_Set::eData_set_type_package ); if ( ! xVariationSetId( record, variation ) ) { return false; } if ( ! xVariationSetParent( record, variation ) ) { return false; } if ( ! xVariationSetName( record, variation ) ) { return false; } if ( ! xVariationSetProperties( record, variation ) ) { return false; } return true; } // ---------------------------------------------------------------------------- bool CGvfReader::xVariationMakeInversions( const CGvfReadRecord& record, CVariation_ref& variation) // ---------------------------------------------------------------------------- { if ( ! xVariationSetCommon( record, variation ) ) { return false; } CRef<CSeq_loc> null = Ref(new CSeq_loc()); null->SetNull(); variation.SetInversion(*null); return true; } // ---------------------------------------------------------------------------- bool CGvfReader::xVariationMakeEversions( const CGvfReadRecord& record, CVariation_ref& variation) // ---------------------------------------------------------------------------- { if ( ! xVariationSetCommon( record, variation ) ) { return false; } CRef<CSeq_loc> null = Ref(new CSeq_loc()); null->SetNull(); variation.SetEversion(*null); return true; } // ---------------------------------------------------------------------------- bool CGvfReader::xVariationMakeTranslocations( const CGvfReadRecord& record, CVariation_ref& variation) // ---------------------------------------------------------------------------- { if ( ! xVariationSetCommon( record, variation ) ) { return false; } CRef<CSeq_loc> null = Ref(new CSeq_loc()); null->SetNull(); variation.SetTranslocation(*null); return true; } // ---------------------------------------------------------------------------- bool CGvfReader::xVariationMakeComplex( const CGvfReadRecord& record, CVariation_ref& variation) // ---------------------------------------------------------------------------- { if ( ! xVariationSetCommon( record, variation ) ) { return false; } variation.SetComplex(); return true; } // ---------------------------------------------------------------------------- bool CGvfReader::xVariationMakeUnknown( const CGvfReadRecord& record, CVariation_ref& variation) // ---------------------------------------------------------------------------- { if ( ! xVariationSetCommon( record, variation ) ) { return false; } variation.SetUnknown(); return true; } // ---------------------------------------------------------------------------- bool CGvfReader::xVariationMakeSNV( const CGvfReadRecord& record, CVariation_ref& variation) // ---------------------------------------------------------------------------- { if ( ! xVariationSetCommon( record, variation ) ) { return false; } if ( ! xVariationSetSnvs( record, variation ) ) { return false; } return true; } // ---------------------------------------------------------------------------- bool CGvfReader::xVariationMakeInsertions( const CGvfReadRecord& record, CVariation_ref& variation) // ---------------------------------------------------------------------------- { if ( ! xVariationSetCommon( record, variation ) ) { return false; } if ( ! xVariationSetInsertions( record, variation ) ) { return false; } return true; } // ---------------------------------------------------------------------------- bool CGvfReader::xVariationMakeDeletions( const CGvfReadRecord& record, CVariation_ref& variation) // ---------------------------------------------------------------------------- { if ( ! xVariationSetCommon( record, variation ) ) { return false; } if ( ! xVariationSetDeletions( record, variation ) ) { return false; } return true; } // ---------------------------------------------------------------------------- bool CGvfReader::xVariationMakeIndels( const CGvfReadRecord& record, CVariation_ref& variation) // ---------------------------------------------------------------------------- { if ( ! xVariationSetCommon( record, variation ) ) { return false; } variation.SetDeletionInsertion("", CVariation_ref::eSeqType_na); variation.SetData().SetInstance().SetType(CVariation_inst::eType_delins); return true; } // --------------------------------------------------------------------------- bool CGvfReader::xVariationSetId( const CGvfReadRecord& record, CVariation_ref& variation) // --------------------------------------------------------------------------- { string id; if ( record.GetAttribute( "ID", id ) ) { variation.SetId().SetDb( record.Source() ); variation.SetId().SetTag().SetStr( id ); } return true; } // --------------------------------------------------------------------------- bool CGvfReader::xVariationSetParent( const CGvfReadRecord& record, CVariation_ref& variation) // --------------------------------------------------------------------------- { string id; if ( record.GetAttribute( "Parent", id ) ) { variation.SetParent_id().SetDb( record.Source() ); variation.SetParent_id().SetTag().SetStr( id ); } return true; } // --------------------------------------------------------------------------- bool CGvfReader::xVariationSetName( const CGvfReadRecord& record, CVariation_ref& variation ) // --------------------------------------------------------------------------- { string name; if ( record.GetAttribute( "Name", name ) ) { variation.SetName( name ); } return true; } // --------------------------------------------------------------------------- bool CGvfReader::xVariationSetProperties( const CGvfReadRecord& record, CVariation_ref& variation ) // --------------------------------------------------------------------------- { typedef map<string, CVariantProperties::EAllele_state>::const_iterator ALLIT; string strGenotype; if ( record.GetAttribute( "Genotype", strGenotype ) ) { ALLIT it = s_AlleleStateMap().find( strGenotype ); if ( it != s_AlleleStateMap().end() ) { variation.SetVariant_prop().SetAllele_state( it->second ); } else { variation.SetVariant_prop().SetAllele_state( CVariantProperties::eAllele_state_other ); } } string strValidated; if ( record.GetAttribute( "validated", strValidated ) ) { if ( strValidated == "1" ) { variation.SetVariant_prop().SetOther_validation( true ); } if ( strValidated == "0" ) { variation.SetVariant_prop().SetOther_validation( false ); } } return true; } // --------------------------------------------------------------------------- bool CGvfReader::xVariationSetDeletions( const CGvfReadRecord& record, CVariation_ref& variation ) // --------------------------------------------------------------------------- { string strReference; CRef<CVariation_ref> pReference(new CVariation_ref); if (!record.GetAttribute("Reference_seq", strReference)) { return false; } pReference->SetData().SetInstance().SetType( CVariation_inst::eType_identity); CRef<CDelta_item> pDelta(new CDelta_item); pDelta->SetSeq().SetLiteral().SetLength( static_cast<TSeqPos>(strReference.size())); pDelta->SetSeq().SetLiteral().SetSeq_data().SetIupacna().Set( strReference); pReference->SetData().SetInstance().SetDelta().push_back(pDelta); pReference->SetData().SetInstance().SetObservation( CVariation_inst::eObservation_asserted); variation.SetData().SetSet().SetVariations().push_back( pReference ); string strAlleles; if (!record.GetAttribute( "Variant_seq", strAlleles)) { return false; } list<string> alleles; NStr::Split( strAlleles, ",", alleles, 0 ); alleles.sort(); alleles.unique(); for ( list<string>::const_iterator cit = alleles.begin(); cit != alleles.end(); ++cit ) { string allele(*cit); if (allele == strReference) { pReference->SetVariant_prop().SetAllele_state( (alleles.size() == 1) ? CVariantProperties::eAllele_state_homozygous : CVariantProperties::eAllele_state_heterozygous); pReference->SetData().SetInstance().SetObservation( CVariation_inst::eObservation_asserted | CVariation_inst::eObservation_variant); continue; } CRef<CVariation_ref> pAllele(new CVariation_ref); pAllele->SetVariant_prop().SetAllele_state( (alleles.size() == 1) ? CVariantProperties::eAllele_state_homozygous : CVariantProperties::eAllele_state_heterozygous); CRef<CDelta_item> pDelta(new CDelta_item); pDelta->SetSeq().SetThis(); pDelta->SetAction(CDelta_item::eAction_del_at); pAllele->SetData().SetInstance().SetDelta().push_back(pDelta); pAllele->SetData().SetInstance().SetType(CVariation_inst::eType_del); pAllele->SetData().SetInstance().SetObservation( CVariation_inst::eObservation_variant ); variation.SetData().SetSet().SetVariations().push_back( pAllele ); } return true; } // --------------------------------------------------------------------------- bool CGvfReader::xVariationSetSnvs( const CGvfReadRecord& record, CVariation_ref& variation ) // --------------------------------------------------------------------------- { string strReference; CRef<CVariation_ref> pReference(new CVariation_ref); if (record.GetAttribute("Reference_seq", strReference)) { pReference->SetData().SetInstance().SetType( CVariation_inst::eType_identity); CRef<CDelta_item> pDelta(new CDelta_item); pDelta->SetSeq().SetLiteral().SetLength( static_cast<TSeqPos>(strReference.size())); pDelta->SetSeq().SetLiteral().SetSeq_data().SetIupacna().Set( strReference); pReference->SetData().SetInstance().SetDelta().push_back(pDelta); pReference->SetData().SetInstance().SetObservation( CVariation_inst::eObservation_asserted); variation.SetData().SetSet().SetVariations().push_back( pReference ); } string strAlleles; if ( record.GetAttribute( "Variant_seq", strAlleles ) ) { list<string> alleles; NStr::Split( strAlleles, ",", alleles, 0 ); alleles.sort(); alleles.unique(); for ( list<string>::const_iterator cit = alleles.begin(); cit != alleles.end(); ++cit ) { string allele(*cit); CRef<CVariation_ref> pAllele(new CVariation_ref); if (allele == strReference) { pReference->SetVariant_prop().SetAllele_state( (alleles.size() == 1) ? CVariantProperties::eAllele_state_homozygous : CVariantProperties::eAllele_state_heterozygous); pReference->SetData().SetInstance().SetObservation( CVariation_inst::eObservation_asserted | CVariation_inst::eObservation_variant); continue; } if (alleles.size() == 1) { pAllele->SetVariant_prop().SetAllele_state( CVariantProperties::eAllele_state_homozygous); } else { pAllele->SetVariant_prop().SetAllele_state( CVariantProperties::eAllele_state_heterozygous); } vector<string> replaces; replaces.push_back(*cit); pAllele->SetSNV(replaces, CVariation_ref::eSeqType_na); pAllele->SetData().SetInstance().SetObservation( CVariation_inst::eObservation_variant); pAllele->SetData().SetInstance().SetType( CVariation_inst::eType_snv ); variation.SetData().SetSet().SetVariations().push_back( pAllele ); } } return true; } // --------------------------------------------------------------------------- bool CGvfReader::xFeatureSetExt( const CGvfReadRecord& record, CSeq_feat& feature, ILineErrorListener* pMessageListener) // --------------------------------------------------------------------------- { string strAttribute; CSeq_feat::TExt& ext = feature.SetExt(); ext.SetType().SetStr( "GvfAttributes" ); ext.AddField( "orig-var-type", record.Type() ); if ( record.Source() != "." ) { ext.AddField( "source", record.Source() ); } if ( record.IsSetScore() ) { ext.AddField( "score", record.Score() ); } for ( CGff2Record::TAttrCit cit = record.Attributes().begin(); cit != record.Attributes().end(); ++cit ) { if ( cit->first == "Start_range" ) { continue; } if ( cit->first == "End_range" ) { continue; } if ( cit->first == "validated" ) { continue; } string strAttribute; if ( ! record.GetAttribute( cit->first, strAttribute ) ) { CReaderMessage warning( eDiag_Warning, m_uLineNumber, "Suspicious data line: Funny attribute \"" + cit->first + "\"."); m_pMessageHandler->Report(warning); continue; } if ( cit->first == "ID" ) { ext.AddField( "id", strAttribute ); continue; } if ( cit->first == "Parent" ) { ext.AddField( "parent", strAttribute ); continue; } if ( cit->first == "Variant_reads" ) { ext.AddField( "variant-reads", strAttribute ); // for lack of better idea continue; } if ( cit->first == "Variant_effect" ) { ext.AddField( "variant-effect", strAttribute ); // for lack of better idea continue; } if ( cit->first == "Total_reads" ) { ext.AddField( "total-reads", strAttribute ); continue; } if ( cit->first == "Variant_copy_number" ) { ext.AddField( "variant-copy-number", strAttribute ); continue; } if ( cit->first == "Reference_copy_number" ) { ext.AddField( "reference-copy-number", strAttribute ); continue; } if ( cit->first == "Phased" ) { ext.AddField( "phased", strAttribute ); continue; } if ( cit->first == "Name" ) { ext.AddField( "name", strAttribute ); continue; } ext.AddField( string("custom-") + cit->first, strAttribute ); } return true; } END_objects_SCOPE END_NCBI_SCOPE
34.551873
87
0.504775
[ "vector" ]
0f15dd00bcddf200fe1f8107b552185c8408279b
32,378
cpp
C++
OgreMain/OgreMain/src/OgreInstanceManager.cpp
liang47009/ndk_sources
88155286084d1ebd1c4f34456d84812a46aba212
[ "MIT" ]
null
null
null
OgreMain/OgreMain/src/OgreInstanceManager.cpp
liang47009/ndk_sources
88155286084d1ebd1c4f34456d84812a46aba212
[ "MIT" ]
null
null
null
OgreMain/OgreMain/src/OgreInstanceManager.cpp
liang47009/ndk_sources
88155286084d1ebd1c4f34456d84812a46aba212
[ "MIT" ]
null
null
null
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2014 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "OgreStableHeaders.h" #include "OgreInstanceManager.h" #include "OgreInstanceBatchHW.h" #include "OgreInstanceBatchHW_VTF.h" #include "OgreInstanceBatchShader.h" #include "OgreInstanceBatchVTF.h" #include "OgreMesh.h" #include "OgreSubMesh.h" #include "OgreMeshManager.h" #include "OgreMaterialManager.h" #include "OgreSceneManager.h" #include "OgreHardwareBufferManager.h" #include "OgreSceneNode.h" #include "OgreIteratorWrappers.h" namespace Ogre { InstanceManager::InstanceManager( IdString customName, SceneManager *sceneManager, const String &meshName, const String &groupName, InstancingTechnique instancingTechnique, uint16 instancingFlags, size_t instancesPerBatch, unsigned short subMeshIdx, bool useBoneMatrixLookup ) : mName( customName ), #ifndef NDEBUG mIdCount( 0 ), #endif mInstancesPerBatch( instancesPerBatch ), mInstancingTechnique( instancingTechnique ), mInstancingFlags( instancingFlags ), mSubMeshIdx( subMeshIdx ), mSceneManager( sceneManager ), mMaxLookupTableInstances(16), mNumCustomParams( 0 ) { mMeshReference = MeshManager::getSingleton().load( meshName, groupName ); if(mMeshReference->sharedVertexData) unshareVertices(mMeshReference); if( mMeshReference->hasSkeleton() && !mMeshReference->getSkeleton().isNull() ) mMeshReference->getSubMesh(mSubMeshIdx)->_compileBoneAssignments(); } InstanceManager::~InstanceManager() { //Remove all batches from all materials we created InstanceBatchMap::const_iterator itor = mInstanceBatches.begin(); InstanceBatchMap::const_iterator end = mInstanceBatches.end(); while( itor != end ) { InstanceBatchVec::const_iterator it = itor->second.begin(); InstanceBatchVec::const_iterator en = itor->second.end(); while( it != en ) OGRE_DELETE *it++; ++itor; } } //---------------------------------------------------------------------- void InstanceManager::setInstancesPerBatch( size_t instancesPerBatch ) { if( !mInstanceBatches.empty() ) { OGRE_EXCEPT(Exception::ERR_INVALID_STATE, "Instances per batch can only be changed before" " building the batch.", "InstanceManager::setInstancesPerBatch"); } mInstancesPerBatch = instancesPerBatch; } //---------------------------------------------------------------------- void InstanceManager::setMaxLookupTableInstances( size_t maxLookupTableInstances ) { if( !mInstanceBatches.empty() ) { OGRE_EXCEPT(Exception::ERR_INVALID_STATE, "Instances per batch can only be changed before" " building the batch.", "InstanceManager::setMaxLookupTableInstances"); } mMaxLookupTableInstances = maxLookupTableInstances; } //---------------------------------------------------------------------- void InstanceManager::setNumCustomParams( unsigned char numCustomParams ) { if( !mInstanceBatches.empty() ) { OGRE_EXCEPT(Exception::ERR_INVALID_STATE, "setNumCustomParams can only be changed before" " building the batch.", "InstanceManager::setNumCustomParams"); } mNumCustomParams = numCustomParams; } //---------------------------------------------------------------------- size_t InstanceManager::getMaxOrBestNumInstancesPerBatch( const String &materialName, size_t suggestedSize, uint16 flags ) { //Get the material MaterialPtr mat = MaterialManager::getSingleton().getByName( materialName, mMeshReference->getGroup() ); InstanceBatch *batch = 0; //Base material couldn't be found if( mat.isNull() ) return 0; switch( mInstancingTechnique ) { case ShaderBased: batch = OGRE_NEW InstanceBatchShader( -1, &mSceneManager->_getEntityMemoryManager( SCENE_DYNAMIC ), this, mMeshReference, mat, suggestedSize, 0 ); break; case TextureVTF: batch = OGRE_NEW InstanceBatchVTF( -1, &mSceneManager->_getEntityMemoryManager( SCENE_DYNAMIC ), this, mMeshReference, mat, suggestedSize, 0 ); static_cast<InstanceBatchVTF*>(batch)->setBoneDualQuaternions((mInstancingFlags & IM_USEBONEDUALQUATERNIONS) != 0); static_cast<InstanceBatchVTF*>(batch)->setUseOneWeight((mInstancingFlags & IM_USEONEWEIGHT) != 0); static_cast<InstanceBatchVTF*>(batch)->setForceOneWeight((mInstancingFlags & IM_FORCEONEWEIGHT) != 0); break; case HWInstancingBasic: batch = OGRE_NEW InstanceBatchHW( -1, &mSceneManager->_getEntityMemoryManager( SCENE_DYNAMIC ), this, mMeshReference, mat, suggestedSize, 0 ); break; case HWInstancingVTF: batch = OGRE_NEW InstanceBatchHW_VTF( -1, &mSceneManager->_getEntityMemoryManager( SCENE_DYNAMIC ), this, mMeshReference, mat, suggestedSize, 0 ); static_cast<InstanceBatchHW_VTF*>(batch)->setBoneMatrixLookup((mInstancingFlags & IM_VTFBONEMATRIXLOOKUP) != 0, mMaxLookupTableInstances); static_cast<InstanceBatchHW_VTF*>(batch)->setBoneDualQuaternions((mInstancingFlags & IM_USEBONEDUALQUATERNIONS) != 0); static_cast<InstanceBatchHW_VTF*>(batch)->setUseOneWeight((mInstancingFlags & IM_USEONEWEIGHT) != 0); static_cast<InstanceBatchHW_VTF*>(batch)->setForceOneWeight((mInstancingFlags & IM_FORCEONEWEIGHT) != 0); break; default: OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "Unimplemented instancing technique: " + StringConverter::toString(mInstancingTechnique), "InstanceBatch::getMaxOrBestNumInstancesPerBatches()"); } const size_t retVal = batch->calculateMaxNumInstances( mMeshReference->getSubMesh(mSubMeshIdx), flags ); OGRE_DELETE batch; return retVal; } //---------------------------------------------------------------------- InstancedEntity* InstanceManager::createInstancedEntity( const String &materialName, SceneMemoryMgrTypes sceneType ) { InstanceBatch *instanceBatch; if( mInstanceBatches.empty() ) instanceBatch = buildNewBatch( materialName, sceneType, true ); else instanceBatch = getFreeBatch( materialName, sceneType ); return instanceBatch->createInstancedEntity(); } //----------------------------------------------------------------------- inline InstanceBatch* InstanceManager::getFreeBatch( const String &materialName, SceneMemoryMgrTypes sceneType ) { IdString materialHash( materialName + StringConverter::toString( sceneType ) ); InstanceBatchVec &batchVec = mInstanceBatches[materialHash]; InstanceBatchVec::const_reverse_iterator itor = batchVec.rbegin(); InstanceBatchVec::const_reverse_iterator end = batchVec.rend(); while( itor != end ) { if( !(*itor)->isBatchFull() ) return *itor; ++itor; } //None found, or they're all full return buildNewBatch( materialName, sceneType, false ); } //----------------------------------------------------------------------- InstanceBatch* InstanceManager::buildNewBatch( const String &materialName, SceneMemoryMgrTypes sceneType, bool firstTime ) { IdString materialHashGeneric( materialName ); IdString materialHash( materialName + StringConverter::toString( sceneType ) ); //Get the bone to index map for the batches Mesh::IndexMap &idxMap = mMeshReference->getSubMesh(mSubMeshIdx)->blendIndexToBoneIndexMap; idxMap = idxMap.empty() ? mMeshReference->sharedBlendIndexToBoneIndexMap : idxMap; //Get the material MaterialPtr mat = MaterialManager::getSingleton().getByName( materialName, mMeshReference->getGroup() ); //Get the array of batches grouped by this material InstanceBatchVec &materialInstanceBatch = mInstanceBatches[materialHash]; InstanceBatch *batch = 0; switch( mInstancingTechnique ) { case ShaderBased: batch = OGRE_NEW InstanceBatchShader( Id::generateNewId<InstanceBatch>(), &mSceneManager->_getEntityMemoryManager(sceneType), this, mMeshReference, mat, mInstancesPerBatch, &idxMap ); break; case TextureVTF: batch = OGRE_NEW InstanceBatchVTF( Id::generateNewId<InstanceBatch>(), &mSceneManager->_getEntityMemoryManager(sceneType), this, mMeshReference, mat, mInstancesPerBatch, &idxMap ); static_cast<InstanceBatchVTF*>(batch)->setBoneDualQuaternions((mInstancingFlags & IM_USEBONEDUALQUATERNIONS) != 0); static_cast<InstanceBatchVTF*>(batch)->setUseOneWeight((mInstancingFlags & IM_USEONEWEIGHT) != 0); static_cast<InstanceBatchVTF*>(batch)->setForceOneWeight((mInstancingFlags & IM_FORCEONEWEIGHT) != 0); break; case HWInstancingBasic: batch = OGRE_NEW InstanceBatchHW( Id::generateNewId<InstanceBatch>(), &mSceneManager->_getEntityMemoryManager(sceneType), this, mMeshReference, mat, mInstancesPerBatch, &idxMap ); break; case HWInstancingVTF: batch = OGRE_NEW InstanceBatchHW_VTF( Id::generateNewId<InstanceBatch>(), &mSceneManager->_getEntityMemoryManager(sceneType), this, mMeshReference, mat, mInstancesPerBatch, &idxMap ); static_cast<InstanceBatchHW_VTF*>(batch)->setBoneMatrixLookup((mInstancingFlags & IM_VTFBONEMATRIXLOOKUP) != 0, mMaxLookupTableInstances); static_cast<InstanceBatchHW_VTF*>(batch)->setBoneDualQuaternions((mInstancingFlags & IM_USEBONEDUALQUATERNIONS) != 0); static_cast<InstanceBatchHW_VTF*>(batch)->setUseOneWeight((mInstancingFlags & IM_USEONEWEIGHT) != 0); static_cast<InstanceBatchHW_VTF*>(batch)->setForceOneWeight((mInstancingFlags & IM_FORCEONEWEIGHT) != 0); break; default: OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "Unimplemented instancing technique: " + StringConverter::toString(mInstancingTechnique), "InstanceBatch::buildNewBatch()"); } #ifndef NDEBUG batch->setName( mName.getFriendlyText() + "/InstanceBatch_" + StringConverter::toString(mIdCount++) ); #endif batch->_notifyManager( mSceneManager ); if( !firstTime ) { //TODO: Check different materials have the same mInstancesPerBatch upper limit //otherwise we can't share batch->buildFrom( mMeshReference->getSubMesh(mSubMeshIdx), mSharedRenderOperation ); } else { //Ensure we don't request more than we can const size_t maxInstPerBatch = batch->calculateMaxNumInstances( mMeshReference-> getSubMesh(mSubMeshIdx), mInstancingFlags ); mInstancesPerBatch = std::min( maxInstPerBatch, mInstancesPerBatch ); batch->_setInstancesPerBatch( mInstancesPerBatch ); //TODO: Create a "merge" function that merges all submeshes into one big submesh //instead of just sending submesh #0 //Get the RenderOperation to be shared with further instances. mSharedRenderOperation = batch->build( mMeshReference->getSubMesh(mSubMeshIdx) ); } const BatchSettings &batchSettings = mBatchSettings[materialHashGeneric]; batch->setCastShadows( batchSettings.setting[CAST_SHADOWS] ); batch->setStatic( sceneType == SCENE_STATIC ); materialInstanceBatch.push_back( batch ); return batch; } //----------------------------------------------------------------------- void InstanceManager::cleanupEmptyBatches(void) { //Do this now to avoid any dangling pointer inside mDirtyBatches _updateDirtyBatches(); InstanceBatchMap::iterator itor = mInstanceBatches.begin(); InstanceBatchMap::iterator end = mInstanceBatches.end(); while( itor != end ) { InstanceBatchVec::iterator it = itor->second.begin(); InstanceBatchVec::iterator en = itor->second.end(); while( it != en ) { if( (*it)->isBatchUnused() ) { OGRE_DELETE *it; //Remove it from the list swapping with the last element and popping back size_t idx = it - itor->second.begin(); *it = itor->second.back(); itor->second.pop_back(); //Restore invalidated iterators it = itor->second.begin() + idx; en = itor->second.end(); } else ++it; } ++itor; } //By this point it may happen that all mInstanceBatches' objects are also empty //however if we call mInstanceBatches.clear(), next time we'll create an InstancedObject //we'll end up calling buildFirstTime() instead of buildNewBatch(), which is not the idea //(takes more time and will leak the shared render operation) } //----------------------------------------------------------------------- void InstanceManager::defragmentBatches( bool optimizeCull, InstanceBatch::InstancedEntityVec &usedEntities, InstanceBatch::CustomParamsVec &usedParams, InstanceBatchVec &fragmentedBatches ) { InstanceBatchVec::iterator itor = fragmentedBatches.begin(); InstanceBatchVec::iterator end = fragmentedBatches.end(); while( itor != end && !usedEntities.empty() ) { if( !(*itor)->isStatic() ) (*itor)->_defragmentBatch( optimizeCull, usedEntities, usedParams ); ++itor; } InstanceBatchVec::iterator lastImportantBatch = itor; while( itor != end ) { if( !(*itor)->isStatic() ) { //If we get here, this means we hit remaining batches which will be unused. //Destroy them //Call this to avoid freeing InstancedEntities that were just reparented (*itor)->_defragmentBatchDiscard(); OGRE_DELETE *itor; } else { //This isn't a meaningless batch, move it forward so it doesn't get wipe //when we resize the container (faster than removing element by element) *lastImportantBatch++ = *itor; } ++itor; } //Remove remaining batches all at once from the vector const size_t remainingBatches = end - lastImportantBatch; fragmentedBatches.resize( fragmentedBatches.size() - remainingBatches ); } //----------------------------------------------------------------------- void InstanceManager::defragmentBatches( bool optimizeCulling ) { //Do this now to avoid any dangling pointer inside mDirtyBatches _updateDirtyBatches(); //Do this for every material InstanceBatchMap::iterator itor = mInstanceBatches.begin(); InstanceBatchMap::iterator end = mInstanceBatches.end(); while( itor != end ) { InstanceBatch::InstancedEntityVec usedEntities; InstanceBatch::CustomParamsVec usedParams; usedEntities.reserve( itor->second.size() * mInstancesPerBatch ); //Collect all Instanced Entities being used by _all_ batches from this material InstanceBatchVec::iterator it = itor->second.begin(); InstanceBatchVec::iterator en = itor->second.end(); while( it != en ) { //Don't collect instances from static batches, we assume they're correctly set //Plus, we don't want to put InstancedEntities from non-static into static batches if( !(*it)->isStatic() ) (*it)->getInstancedEntitiesInUse( usedEntities, usedParams ); ++it; } defragmentBatches( optimizeCulling, usedEntities, usedParams, itor->second ); ++itor; } } //----------------------------------------------------------------------- void InstanceManager::setSetting( BatchSettingId id, bool value, IdString materialName ) { assert( id < NUM_SETTINGS ); if( materialName == IdString() ) { //Setup all existing materials InstanceBatchMap::iterator itor = mInstanceBatches.begin(); InstanceBatchMap::iterator end = mInstanceBatches.end(); while( itor != end ) { mBatchSettings[itor->first].setting[id] = value; applySettingToBatches( id, value, itor->second ); ++itor; } } else { //Setup a given material mBatchSettings[materialName].setting[id] = value; InstanceBatchMap::const_iterator itor = mInstanceBatches.find( materialName ); //Don't crash or throw if the batch with that material hasn't been created yet if( itor != mInstanceBatches.end() ) applySettingToBatches( id, value, itor->second ); } } //----------------------------------------------------------------------- bool InstanceManager::getSetting( BatchSettingId id, IdString materialName ) const { assert( id < NUM_SETTINGS ); BatchSettingsMap::const_iterator itor = mBatchSettings.find( materialName ); if( itor != mBatchSettings.end() ) return itor->second.setting[id]; //Return current setting //Return default return BatchSettings().setting[id]; } //----------------------------------------------------------------------- void InstanceManager::applySettingToBatches( BatchSettingId id, bool value, const InstanceBatchVec &container ) { InstanceBatchVec::const_iterator itor = container.begin(); InstanceBatchVec::const_iterator end = container.end(); while( itor != end ) { switch( id ) { case CAST_SHADOWS: (*itor)->setCastShadows( value ); break; case SHOW_BOUNDINGBOX: //(*itor)->getParentSceneNode()->showBoundingBox( value ); break; default: break; } ++itor; } } //----------------------------------------------------------------------- void InstanceManager::setBatchesAsStatic( bool bStatic ) { InstanceBatchMap::iterator itor = mInstanceBatches.begin(); InstanceBatchMap::iterator end = mInstanceBatches.end(); while( itor != end ) { InstanceBatchVec::iterator it = itor->second.begin(); InstanceBatchVec::iterator en = itor->second.end(); while( it != en ) { (*it)->setStatic( bStatic ); ++it; } ++itor; } } //----------------------------------------------------------------------- void InstanceManager::_addToDynamicBatchList( InstanceBatch *dynamicBatch ) { InstanceBatchVec::iterator itor = std::find( mDynamicBatches.begin(), mDynamicBatches.end(), dynamicBatch ); if( itor == mDynamicBatches.end() ) mDynamicBatches.push_back( dynamicBatch ); } //----------------------------------------------------------------------- void InstanceManager::_removeFromDynamicBatchList( InstanceBatch *batch ) { InstanceBatchVec::iterator itor = std::find( mDynamicBatches.begin(), mDynamicBatches.end(), batch ); if( itor != mDynamicBatches.end() ) efficientVectorRemove( mDynamicBatches, itor ); } //----------------------------------------------------------------------- void InstanceManager::_addDirtyStaticBatch( InstanceBatch *dirtyBatch ) { //If he needs to this very often, they're probably not static... //Note: Calling this more often will only affect performance for the next frame. //It won't crash and can be ignored assert( std::find( mDirtyStaticBatches.begin(), mDirtyStaticBatches.end(), dirtyBatch ) == mDirtyStaticBatches.end() && "Only flag as dirty static batches once!" ); mDirtyStaticBatches.push_back( dirtyBatch ); } //----------------------------------------------------------------------- #ifdef OGRE_LEGACY_ANIMATIONS void InstanceManager::_updateAnimations(void) { InstanceBatchVec::const_iterator itor = mDynamicBatches.begin(); InstanceBatchVec::const_iterator end = mDynamicBatches.end(); while( itor != end ) { (*itor)->_updateAnimations(); ++itor; } itor = mDirtyStaticBatches.begin(); end = mDirtyStaticBatches.end(); while( itor != end ) { (*itor)->_updateAnimations(); ++itor; } //_updateDirtyBatches will be called after us, and will do that job. //mDirtyStaticBatches.clear(); } #endif //----------------------------------------------------------------------- void InstanceManager::_updateDirtyBatchesThread( size_t threadIdx ) { InstanceBatchVec::const_iterator itor = mDynamicBatches.begin(); InstanceBatchVec::const_iterator end = mDynamicBatches.end(); while( itor != end ) { (*itor)->_updateEntitiesBoundsThread( threadIdx ); ++itor; } itor = mDirtyStaticBatches.begin(); end = mDirtyStaticBatches.end(); while( itor != end ) { (*itor)->_updateEntitiesBoundsThread( threadIdx ); ++itor; } } //----------------------------------------------------------------------- void InstanceManager::_updateDirtyBatches(void) { InstanceBatchVec::const_iterator itor = mDynamicBatches.begin(); InstanceBatchVec::const_iterator end = mDynamicBatches.end(); while( itor != end ) { (*itor)->_updateBounds(); ++itor; } itor = mDirtyStaticBatches.begin(); end = mDirtyStaticBatches.end(); while( itor != end ) { (*itor)->_updateBounds(); ++itor; } mDirtyStaticBatches.clear(); } //----------------------------------------------------------------------- InstanceManager::InstanceBatchIterator InstanceManager::getInstanceBatchIterator( const String &materialName, SceneMemoryMgrTypes sceneType ) const { IdString materialHash( materialName + StringConverter::toString( sceneType ) ); InstanceBatchMap::const_iterator it = mInstanceBatches.find( materialHash ); if( it == mInstanceBatches.end() ) { OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Can't find instance batches with material '" + materialName + "'", "InstanceManager::getInstanceBatchIterator"); } return InstanceBatchIterator( it->second.begin(), it->second.end() ); } //----------------------------------------------------------------------- // Helper functions to unshare the vertices //----------------------------------------------------------------------- typedef map<uint32, uint32>::type IndicesMap; template< typename TIndexType > IndicesMap getUsedIndices(IndexData* idxData) { TIndexType *data = (TIndexType*)idxData->indexBuffer->lock(idxData->indexStart * sizeof(TIndexType), idxData->indexCount * sizeof(TIndexType), HardwareBuffer::HBL_READ_ONLY); IndicesMap indicesMap; for (size_t i = 0; i < idxData->indexCount; i++) { TIndexType index = data[i]; if (indicesMap.find(index) == indicesMap.end()) { indicesMap[index] = (uint32)(indicesMap.size()); } } idxData->indexBuffer->unlock(); return indicesMap; } //----------------------------------------------------------------------- template< typename TIndexType > void copyIndexBuffer(IndexData* idxData, IndicesMap& indicesMap) { TIndexType *data = (TIndexType*)idxData->indexBuffer->lock(idxData->indexStart * sizeof(TIndexType), idxData->indexCount * sizeof(TIndexType), HardwareBuffer::HBL_NORMAL); for (uint32 i = 0; i < idxData->indexCount; i++) { data[i] = (TIndexType)indicesMap[data[i]]; } idxData->indexBuffer->unlock(); } //----------------------------------------------------------------------- void InstanceManager::unshareVertices(const Ogre::MeshPtr &mesh) { // Retrieve data to copy bone assignments const Mesh::VertexBoneAssignmentList& boneAssignments = mesh->getBoneAssignments(); Mesh::VertexBoneAssignmentList::const_iterator it = boneAssignments.begin(); Mesh::VertexBoneAssignmentList::const_iterator end = boneAssignments.end(); size_t curVertexOffset = 0; // Access shared vertices VertexData* sharedVertexData = mesh->sharedVertexData; for (size_t subMeshIdx = 0; subMeshIdx < mesh->getNumSubMeshes(); subMeshIdx++) { SubMesh *subMesh = mesh->getSubMesh(subMeshIdx); IndexData *indexData = subMesh->indexData; HardwareIndexBuffer::IndexType idxType = indexData->indexBuffer->getType(); IndicesMap indicesMap = (idxType == HardwareIndexBuffer::IT_16BIT) ? getUsedIndices<uint16>(indexData) : getUsedIndices<uint32>(indexData); VertexData *newVertexData = new VertexData(); newVertexData->vertexCount = indicesMap.size(); newVertexData->vertexDeclaration = sharedVertexData->vertexDeclaration->clone(); for (size_t bufIdx = 0; bufIdx < sharedVertexData->vertexBufferBinding->getBufferCount(); bufIdx++) { HardwareVertexBufferSharedPtr sharedVertexBuffer = sharedVertexData->vertexBufferBinding->getBuffer(bufIdx); size_t vertexSize = sharedVertexBuffer->getVertexSize(); HardwareVertexBufferSharedPtr newVertexBuffer = HardwareBufferManager::getSingleton().createVertexBuffer (vertexSize, newVertexData->vertexCount, sharedVertexBuffer->getUsage(), sharedVertexBuffer->hasShadowBuffer()); uint8 *oldLock = (uint8*)sharedVertexBuffer->lock(0, sharedVertexData->vertexCount * vertexSize, HardwareBuffer::HBL_READ_ONLY); uint8 *newLock = (uint8*)newVertexBuffer->lock(0, newVertexData->vertexCount * vertexSize, HardwareBuffer::HBL_NORMAL); IndicesMap::iterator indIt = indicesMap.begin(); IndicesMap::iterator endIndIt = indicesMap.end(); for (; indIt != endIndIt; ++indIt) { memcpy(newLock + vertexSize * indIt->second, oldLock + vertexSize * indIt->first, vertexSize); } sharedVertexBuffer->unlock(); newVertexBuffer->unlock(); newVertexData->vertexBufferBinding->setBinding(bufIdx, newVertexBuffer); } if (idxType == HardwareIndexBuffer::IT_16BIT) { copyIndexBuffer<uint16>(indexData, indicesMap); } else { copyIndexBuffer<uint32>(indexData, indicesMap); } // Store new attributes subMesh->useSharedVertices = false; subMesh->vertexData = newVertexData; // Transfer bone assignments to the submesh size_t offset = curVertexOffset + newVertexData->vertexCount; for (; it != end; ++it) { size_t vertexIdx = (*it).first; if (vertexIdx > offset) break; VertexBoneAssignment boneAssignment = (*it).second; boneAssignment.vertexIndex = static_cast<unsigned int>(boneAssignment.vertexIndex - curVertexOffset); subMesh->addBoneAssignment(boneAssignment); } curVertexOffset = newVertexData->vertexCount + 1; } // Release shared vertex data delete mesh->sharedVertexData; mesh->sharedVertexData = NULL; mesh->clearBoneAssignments(); } //----------------------------------------------------------------------- }
43.754054
150
0.553802
[ "mesh", "render", "object", "vector" ]
0f168fb627c34b9e72b72fde6ff638fc975caa83
1,832
cpp
C++
Algorithms/sort/counting_sort.cpp
Divide-et-impera-11/AlgorithmWord
a78bb9272b59df5d16fdc0af565391ef2ac20117
[ "MIT" ]
null
null
null
Algorithms/sort/counting_sort.cpp
Divide-et-impera-11/AlgorithmWord
a78bb9272b59df5d16fdc0af565391ef2ac20117
[ "MIT" ]
null
null
null
Algorithms/sort/counting_sort.cpp
Divide-et-impera-11/AlgorithmWord
a78bb9272b59df5d16fdc0af565391ef2ac20117
[ "MIT" ]
null
null
null
#include <iostream> #include <algorithm> #include <vector> #include <map> using namespace std; //---------------------Counting Sort Algorithm--------------------- // Analysis // Time Complexity O(n+k) // Worst Time Complexity O(n+k) // Avarage Time Complexity O(n+k) // Best Time Complexity O(n+k) // Space Complexity O(n+k) // Auxiliary Space Complexity O(n+k) int* counting_sort(int* array, size_t size) { if (size <= 1) return array; map<int, uint16_t> hash; uint32_t offset(0); for (; offset < size; ++offset) { auto iter = find_if(hash.begin(), hash.end(), [&](pair<const int, uint16_t>& pair_) -> bool { return pair_.first >= *(array + offset) ? true : false;}); if (iter == hash.end()) { hash.insert(hash.end(),pair<const int, uint16_t>(*(array + offset), 1)); continue; } if ((*iter).first == *(array + offset)) { iter->second++; } else { hash.insert(iter,pair<int, uint16_t>(*(array + offset), 1)); } } auto iter_f = hash.begin(); auto iter_l = ++iter_f; iter_f--; while (iter_l != hash.end()) { iter_l->second += iter_f->second; iter_f++; iter_l++; } int*result = new int[size]; for (uint32_t offset(0); offset < size; ++offset) { *(result + --hash.at(*(array + offset))) = *(array + offset); } return result; } // Parameter List: // Type* array = pointer to an array // size_t size = size of elements in array // Return Value Cases: // pointer to sorted array // Function Call Example // counting_sort<int>(new int[2]{2,1},2);
33.309091
168
0.502183
[ "vector" ]
0f1a8e2a9ed5f0e711e9cd70dca73f83deba9833
14,219
cc
C++
paddle/fluid/framework/save_load_util.cc
zmxdream/Paddle
04f042a5d507ad98f7f2cfc3cbc44b06d7a7f45c
[ "Apache-2.0" ]
2
2021-11-12T11:31:12.000Z
2021-12-05T10:30:28.000Z
paddle/fluid/framework/save_load_util.cc
zmxdream/Paddle
04f042a5d507ad98f7f2cfc3cbc44b06d7a7f45c
[ "Apache-2.0" ]
null
null
null
paddle/fluid/framework/save_load_util.cc
zmxdream/Paddle
04f042a5d507ad98f7f2cfc3cbc44b06d7a7f45c
[ "Apache-2.0" ]
1
2021-08-21T06:57:20.000Z
2021-08-21T06:57:20.000Z
// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "paddle/fluid/framework/save_load_util.h" #include <fstream> #include "paddle/fluid/imperative/layer.h" namespace paddle { namespace framework { const int model_file_reserve_size = 256; const std::string tensor_number_mark = "TNUM"; // NOLINT const std::string tensor_name_mark = "NAME"; // NOLINT void CheckInStreamState(std::istream& istre, size_t length) { if (!istre) { VLOG(5) << "Can't read [" << length << "] from file" << "file seems breakem"; PADDLE_THROW(platform::errors::Unavailable( "Model load failed, istream state error.")); } } struct DeserializedDataFunctor { DeserializedDataFunctor(void** buf, Tensor* tensor, const platform::Place& place) : buf_(buf), tensor_(tensor), place_(place) {} template <typename T> void apply() { *buf_ = tensor_->mutable_data<T>(place_); } void** buf_; Tensor* tensor_; platform::Place place_; }; size_t ReadTensorNumber(std::istream& istre) { char* tensor_number_mark_buffer = new char[tensor_number_mark.size()]; istre.read(tensor_number_mark_buffer, sizeof(char) * tensor_number_mark.size()); std::string str_read_tensor_number_mark(tensor_number_mark_buffer, tensor_number_mark.size()); PADDLE_ENFORCE_EQ(tensor_number_mark, str_read_tensor_number_mark, platform::errors::InvalidArgument( "Tensor number mark does not match, expect mark is " "[%s], but the mark read from file is [%s].", tensor_number_mark, str_read_tensor_number_mark)); size_t tensor_number = 0; istre.read(reinterpret_cast<char*>(&tensor_number), sizeof(tensor_number)); CheckInStreamState(istre, sizeof(tensor_number)); delete[] tensor_number_mark_buffer; return tensor_number; } std::string ReadTensorName(std::istream& istre) { char* name_mark_buffer = new char[tensor_name_mark.size()]; istre.read(name_mark_buffer, sizeof(char) * tensor_name_mark.size()); CheckInStreamState(istre, sizeof(char) * tensor_name_mark.size()); std::string str_read_tensor_name_mark(name_mark_buffer, tensor_name_mark.size()); PADDLE_ENFORCE_EQ(tensor_name_mark, str_read_tensor_name_mark, platform::errors::InvalidArgument( "Tensor name mark does not match, expect mark is [%s], " "but the mark read from file is [%s].", tensor_name_mark, str_read_tensor_name_mark)); size_t tensor_name_length = 0; istre.read(reinterpret_cast<char*>(&tensor_name_length), sizeof(tensor_name_length)); CheckInStreamState(istre, sizeof(tensor_name_length)); char* tensor_name_buffer = new char[tensor_name_length]; istre.read(tensor_name_buffer, sizeof(char) * tensor_name_length); CheckInStreamState(istre, sizeof(char) * tensor_name_length); std::string str_tensor_name(tensor_name_buffer, tensor_name_length); delete[] name_mark_buffer; delete[] tensor_name_buffer; return str_tensor_name; } void ReadReserveBuffer(std::istream& istre) { char* reserve_buffer = new char[model_file_reserve_size]; istre.read(reserve_buffer, sizeof(char) * model_file_reserve_size); CheckInStreamState(istre, model_file_reserve_size); delete[] reserve_buffer; } bool SaveStaticNameListToDisk( const std::string& file_name, const std::vector<std::string>& vec_tensor_name_list, const Scope& scope) { std::map<std::string, Tensor*> map_tensor; for (size_t i = 0; i < vec_tensor_name_list.size(); ++i) { auto var_ptr = scope.FindVar(vec_tensor_name_list[i]); PADDLE_ENFORCE_NOT_NULL( var_ptr, platform::errors::NotFound("Variable (%s) is not found when " "saving model, please make sure " "that exe.run(startup_program) has " "been executed.", vec_tensor_name_list[i])); Tensor* tensor = var_ptr->GetMutable<LoDTensor>(); PADDLE_ENFORCE_EQ(tensor->IsInitialized(), true, platform::errors::PreconditionNotMet( "Paramter [%s] is not initialzed, please make sure " "that exe.run(startup_program) has been executed.", vec_tensor_name_list[i])); map_tensor[vec_tensor_name_list[i]] = tensor; } return SaveTensorToDisk(file_name, map_tensor); } bool SaveDygraphVarBaseListToDisk( const std::string& file_name, const std::vector<std::shared_ptr<imperative::VarBase>>& vec_var_base_list) { std::map<std::string, Tensor*> map_tensor; for (size_t i = 0; i < vec_var_base_list.size(); ++i) { auto var_ptr = vec_var_base_list[i]->MutableVar(); Tensor* tensor = var_ptr->GetMutable<LoDTensor>(); PADDLE_ENFORCE_EQ(tensor->IsInitialized(), true, platform::errors::PreconditionNotMet( "Paramter [%s] is not initialzed, please make sure " "that exe.run(startup_program) has been executed.", vec_var_base_list[i]->Name())); map_tensor[vec_var_base_list[i]->Name()] = tensor; } return SaveTensorToDisk(file_name, map_tensor); } const std::vector<std::shared_ptr<imperative::VarBase>> LoadDygraphVarBaseListFromDisk(const std::string& file_name) { std::map<std::string, std::shared_ptr<Tensor>> map_load_tensor; LoadTensorFromDisk(file_name, &map_load_tensor); std::vector<std::shared_ptr<imperative::VarBase>> vec_res; vec_res.reserve(map_load_tensor.size()); for (auto& load_tensor : map_load_tensor) { std::shared_ptr<imperative::VarBase> var( new imperative::VarBase(load_tensor.first)); auto* tensor = var->MutableVar()->GetMutable<framework::LoDTensor>(); TensorCopySync(*(load_tensor.second.get()), load_tensor.second->place(), tensor); vec_res.emplace_back(var); } return vec_res; } bool LoadStaticNameListFromDisk( const std::string& file_name, const std::vector<std::string>& vec_tensor_name_list, const Scope& scope) { std::map<std::string, std::shared_ptr<Tensor>> map_load_tensor; LoadTensorFromDisk(file_name, &map_load_tensor); for (size_t i = 0; i < vec_tensor_name_list.size(); ++i) { auto it = map_load_tensor.find(vec_tensor_name_list[i]); PADDLE_ENFORCE_NE(it, map_load_tensor.end(), platform::errors::NotFound( "Parameter (%s) not found in model file (%s).", vec_tensor_name_list[i], file_name)); auto var_ptr = scope.FindVar(vec_tensor_name_list[i]); PADDLE_ENFORCE_NOT_NULL( var_ptr, platform::errors::PreconditionNotMet( "Parameter (%s) is not created when loading model, " "please make sure that exe.run(startup_program) has been executed.", vec_tensor_name_list[i])); Tensor* tensor = var_ptr->GetMutable<LoDTensor>(); PADDLE_ENFORCE_NOT_NULL( tensor, platform::errors::PreconditionNotMet( "Paramter [%s] is not initialzed, " "please make sure that exe.run(startup_program) has been executed.", vec_tensor_name_list[i])); PADDLE_ENFORCE_EQ(tensor->IsInitialized(), true, platform::errors::PreconditionNotMet( "Paramter [%s] is not initialzed, " "please make sure that exe.run(startup_program) has " "been executed.v", vec_tensor_name_list[i])); PADDLE_ENFORCE_EQ( tensor->dims(), it->second->dims(), platform::errors::InvalidArgument( "Shape does not match, the program requires a parameter with a " "shape of " "(%s), while the loaded parameter (namely [ %s ]) has a shape of " "(%s).", tensor->dims(), vec_tensor_name_list[i], it->second->dims())); TensorCopySync(*(it->second.get()), tensor->place(), tensor); map_load_tensor.erase(it); } if (map_load_tensor.size() > 0) { std::string used_tensor_message = "There is [" + std::to_string(map_load_tensor.size()) + "] tensor in model file not used: "; for (auto& tensor_temp : map_load_tensor) { used_tensor_message += " " + tensor_temp.first; } LOG(ERROR) << used_tensor_message; } return true; } bool SaveTensorToDisk(const std::string& file_name, const std::map<std::string, Tensor*>& map_tensor) { MkDirRecursively(DirName(file_name).c_str()); std::ofstream fout(file_name, std::ios::binary); PADDLE_ENFORCE_EQ( fout.is_open(), true, platform::errors::Unavailable("File (%s) open failed.", file_name)); // first 256 byte for reserve for fulture upgrade char* kReserveBuffer = new char[model_file_reserve_size]; fout.write(kReserveBuffer, sizeof(char) * model_file_reserve_size); delete[] kReserveBuffer; fout.write(tensor_number_mark.c_str(), sizeof(char) * tensor_number_mark.size()); size_t tensor_number = map_tensor.size(); fout.write(reinterpret_cast<const char*>(&tensor_number), sizeof(tensor_number)); for (auto& itera : map_tensor) { // first save tensor name fout.write(tensor_name_mark.c_str(), sizeof(char) * tensor_name_mark.size()); size_t name_length = itera.first.size(); fout.write(reinterpret_cast<const char*>(&name_length), sizeof(name_length)); fout.write(itera.first.c_str(), sizeof(char) * name_length); // write tensor version constexpr uint32_t version = 0; fout.write(reinterpret_cast<const char*>(&version), sizeof(version)); // the 2nd field, tensor description // int32_t size // void* protobuf message auto tensor = itera.second; proto::VarType::TensorDesc desc; desc.set_data_type(tensor->type()); auto dims = framework::vectorize(tensor->dims()); auto* pb_dims = desc.mutable_dims(); pb_dims->Resize(static_cast<int>(dims.size()), 0); std::copy(dims.begin(), dims.end(), pb_dims->begin()); int32_t size = desc.ByteSize(); fout.write(reinterpret_cast<const char*>(&size), sizeof(size)); auto out = desc.SerializeAsString(); fout.write(out.data(), size); // save tensor uint64_t data_size = tensor->numel() * framework::SizeOfType(tensor->type()); auto* data_ptr = tensor->data(); if (platform::is_gpu_place(tensor->place())) { #if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP) framework::Tensor temp; TensorCopySync(*tensor, platform::CPUPlace(), &temp); data_ptr = temp.data(); #else PADDLE_THROW(platform::errors::Unavailable( "Tensor is in CUDA device, but paddle not compiled with CUDA.")); #endif } fout.write(static_cast<const char*>(data_ptr), static_cast<std::streamsize>(data_size)); } if (!fout) { PADDLE_THROW(platform::errors::Unavailable( "Model save failed, error when writing data into model file [%s].", file_name)); } fout.close(); return true; } bool LoadTensorFromDisk( const std::string& file_name, std::map<std::string, std::shared_ptr<Tensor>>* map_tensor) { std::ifstream fin(file_name, std::ios::binary); PADDLE_ENFORCE_EQ( fin.is_open(), true, platform::errors::Unavailable("File (%s) open failed.", file_name)); ReadReserveBuffer(fin); size_t tensor_number = ReadTensorNumber(fin); for (size_t i = 0; i < tensor_number; ++i) { std::string str_tensor_name = ReadTensorName(fin); std::shared_ptr<Tensor> tensor_temp(new Tensor()); uint32_t version; fin.read(reinterpret_cast<char*>(&version), sizeof(version)); CheckInStreamState(fin, sizeof(version)); PADDLE_ENFORCE_EQ(version, 0U, platform::errors::InvalidArgument( "Only version 0 tensor is supported.")); proto::VarType::TensorDesc desc; { // int32_t size // proto buffer int32_t size; fin.read(reinterpret_cast<char*>(&size), sizeof(size)); CheckInStreamState(fin, sizeof(size)); std::unique_ptr<char[]> buf(new char[size]); fin.read(reinterpret_cast<char*>(buf.get()), size); CheckInStreamState(fin, sizeof(size)); PADDLE_ENFORCE_EQ( desc.ParseFromArray(buf.get(), size), true, platform::errors::InvalidArgument("Parse tensor desc failed.")); } { // read tensor std::vector<int64_t> dims; dims.reserve(static_cast<size_t>(desc.dims().size())); std::copy(desc.dims().begin(), desc.dims().end(), std::back_inserter(dims)); auto new_dim = framework::make_ddim(dims); tensor_temp->Resize(new_dim); void* buf; framework::VisitDataType(desc.data_type(), DeserializedDataFunctor(&buf, tensor_temp.get(), platform::CPUPlace())); size_t size = tensor_temp->numel() * framework::SizeOfType(desc.data_type()); fin.read(reinterpret_cast<char*>(buf), size); CheckInStreamState(fin, size); } (*map_tensor)[str_tensor_name] = tensor_temp; } return true; } } // namespace framework } // namespace paddle
36.741602
80
0.64238
[ "shape", "vector", "model" ]
0f1b514c98d3b17045906f3578f2e62897bd7d76
19,377
cpp
C++
src/nbla/function/generic/lstm.cpp
daniel-falk/nnabla
3fe132ea52dc10521cc029a5d6ba8f565cf65ccf
[ "Apache-2.0" ]
2,792
2017-06-26T13:05:44.000Z
2022-03-28T07:55:26.000Z
src/nbla/function/generic/lstm.cpp
daniel-falk/nnabla
3fe132ea52dc10521cc029a5d6ba8f565cf65ccf
[ "Apache-2.0" ]
138
2017-06-27T07:04:44.000Z
2022-02-28T01:37:15.000Z
src/nbla/function/generic/lstm.cpp
daniel-falk/nnabla
3fe132ea52dc10521cc029a5d6ba8f565cf65ccf
[ "Apache-2.0" ]
380
2017-06-26T13:23:52.000Z
2022-03-25T16:51:30.000Z
// Copyright 2019,2020,2021 Sony Corporation. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <nbla/function/lstm.hpp> namespace nbla { NBLA_REGISTER_FUNCTION_SOURCE(LSTM, int, float, bool, bool); template <typename T> void LSTM<T>::setup_impl(const Variables &inputs, const Variables &outputs) { Shape_t inshape = inputs[0]->shape(); Shape_t hshape = inputs[1]->shape(); Shape_t cshape = inputs[2]->shape(); Shape_t outshape = outputs[0]->shape(); // Check input dimensions NBLA_CHECK(inputs[0]->ndim() == 3, error_code::value, "Input x must be a 3 dimensional array with a shape of (steps, " "batch_size, input_size)."); seq_len_ = inshape[0]; batch_size_ = inshape[1]; input_dim_ = inshape[2]; // Assuming this function takes h as (numLayer, numD, B, M) hidden_size_ = inputs[1]->shape()[3]; num_directions_ = this->bidirectional_ ? 2 : 1; // Check shape of h & c const char *error_msg_h = "Input h must be a 4 dimensional array with a " "shape of (num_layers, num_directions, batch_size, " "hidden_size)."; NBLA_CHECK(inputs[1]->ndim() == 4, error_code::value, error_msg_h); NBLA_CHECK(hshape[0] == this->num_layers_, error_code::value, error_msg_h); NBLA_CHECK(hshape[1] == num_directions_, error_code::value, error_msg_h); NBLA_CHECK(hshape[2] == batch_size_, error_code::value, error_msg_h); NBLA_CHECK(hshape == cshape, error_code::value, "Input c must has the same shape as input h."); // Check weight shape at 0th layer Shape_t w0_shape = inputs[3]->shape(); const char *error_msg_w0 = "Input w0 must be a 4 dimensional array with a " "shape of (num_directions, 4, hidden_size, " "input_size + hidden_size)."; NBLA_CHECK(inputs[2]->ndim() == 4, error_code::value, error_msg_w0); NBLA_CHECK(w0_shape[0] == num_directions_, error_code::value, error_msg_w0); NBLA_CHECK(w0_shape[1] == 4, error_code::value, error_msg_w0); NBLA_CHECK(w0_shape[2] == hidden_size_, error_code::value, error_msg_w0); NBLA_CHECK(w0_shape[3] == hidden_size_ + input_dim_, error_code::value, error_msg_w0); weight_exists_ = true; bias_exists_ = true; if (inputs.size() == 4) { weight_exists_ = false; bias_exists_ = false; } else if (inputs.size() == 5) { Shape_t opt_shape = inputs[4]->shape(); if (this->num_layers_ > 1 && opt_shape.size() == 5) { bias_exists_ = false; } else if (this->num_layers_ > 1 && opt_shape.size() != 5) { NBLA_ERROR(error_code::value, "Weight argument must be passed when num_layers > 1"); } else if (this->num_layers_ == 1 && opt_shape.size() != 4) { NBLA_ERROR(error_code::value, "Weight argument cannot be passed when num_layers == 1"); } else if (this->num_layers_ == 1 && opt_shape.size() == 4) { weight_exists_ = false; } } else if ((inputs.size() > 5) && (this->num_layers_ == 1)) { NBLA_ERROR(error_code::value, "Weight argument cannot be passed when num_layers == 1"); } // Check weight shape if (weight_exists_) { Shape_t w_shape = inputs[4]->shape(); const char *error_msg_w = "Input w must be a 5 dimensional array with a " "shape of (num_layers - 1, num_directions, 4, " "hidden_size, num_directions * hidden_size + " "hidden_size)."; NBLA_CHECK(inputs[4]->ndim() == 5, error_code::value, error_msg_w); NBLA_CHECK(w_shape[0] == this->num_layers_ - 1, error_code::value, error_msg_w); NBLA_CHECK(w_shape[1] == num_directions_, error_code::value, error_msg_w); NBLA_CHECK(w_shape[2] == 4, error_code::value, error_msg_w); NBLA_CHECK(w_shape[3] == hidden_size_, error_code::value, error_msg_w); NBLA_CHECK(w_shape[4] == num_directions_ * hidden_size_ + hidden_size_, error_code::value, error_msg_w); } // Check bias shape if (bias_exists_) { const int b_index = weight_exists_ ? 5 : 4; Shape_t b_shape = inputs[b_index]->shape(); const char *error_msg_b = "Input b must be a 4 dimensional array with a " "shape of (num_layers, 4, num_directions, " "hidden_size)."; NBLA_CHECK(inputs[b_index]->ndim() == 4, error_code::value, error_msg_b); NBLA_CHECK(b_shape[0] == this->num_layers_, error_code::value, error_msg_b); NBLA_CHECK(b_shape[1] == num_directions_, error_code::value, error_msg_b); NBLA_CHECK(b_shape[2] == 4, error_code::value, error_msg_b); NBLA_CHECK(b_shape[3] == hidden_size_, error_code::value, error_msg_b); } // Set output shapes outputs[0]->reshape({seq_len_, batch_size_, num_directions_ * hidden_size_}, true); outputs[1]->reshape(inputs[1]->shape(), true); outputs[2]->reshape(inputs[2]->shape(), true); } template <typename T> vector<vector<CgVariablePtr>> LSTM<T>::lstm_cell(shared_ptr<CgVariable> x, shared_ptr<CgVariable> h, shared_ptr<CgVariable> c, shared_ptr<CgVariable> w, shared_ptr<CgVariable> b) { // Graph construction vector<CgVariablePtr> b_vec; vector<int> t_axes{1, 0}; auto concatenate = make_shared<CgFunction>(create_Concatenate(this->ctx_, 1)); auto xh = connect(concatenate, {x, h}, 1); auto split = make_shared<CgFunction>(create_Split(this->ctx_, 0)); auto w_vec = connect(split, {w}, 4); if (bias_exists_ == true) { auto split = make_shared<CgFunction>(create_Split(this->ctx_, 0)); b_vec = connect(split, {b}, 4); } auto transpose1 = make_shared<CgFunction>(create_Transpose(this->ctx_, t_axes)); auto affine1 = make_shared<CgFunction>(create_Affine(this->ctx_, 1)); vector<CgVariablePtr> i_t; if (bias_exists_ == true) { i_t = connect(affine1, {xh[0], connect(transpose1, {w_vec[0]}, 1)[0], b_vec[0]}, 1); } else { i_t = connect(affine1, { xh[0], connect(transpose1, {w_vec[0]}, 1)[0], }, 1); } auto transpose2 = make_shared<CgFunction>(create_Transpose(this->ctx_, t_axes)); auto affine2 = make_shared<CgFunction>(create_Affine(this->ctx_, 1)); vector<CgVariablePtr> f_t; if (bias_exists_ == true) { f_t = connect(affine2, {xh[0], connect(transpose2, {w_vec[1]}, 1)[0], b_vec[1]}, 1); } else { f_t = connect(affine2, { xh[0], connect(transpose2, {w_vec[1]}, 1)[0], }, 1); } auto transpose3 = make_shared<CgFunction>(create_Transpose(this->ctx_, t_axes)); auto affine3 = make_shared<CgFunction>(create_Affine(this->ctx_, 1)); vector<CgVariablePtr> g_t; if (bias_exists_ == true) { g_t = connect(affine3, {xh[0], connect(transpose3, {w_vec[2]}, 1)[0], b_vec[2]}, 1); } else { g_t = connect(affine3, { xh[0], connect(transpose3, {w_vec[2]}, 1)[0], }, 1); } auto transpose4 = make_shared<CgFunction>(create_Transpose(this->ctx_, t_axes)); auto affine4 = make_shared<CgFunction>(create_Affine(this->ctx_, 1)); vector<CgVariablePtr> o_t; if (bias_exists_ == true) { o_t = connect(affine4, {xh[0], connect(transpose4, {w_vec[3]}, 1)[0], b_vec[3]}, 1); } else { o_t = connect(affine4, { xh[0], connect(transpose4, {w_vec[3]}, 1)[0], }, 1); } auto sigmoid1 = make_shared<CgFunction>(create_Sigmoid(this->ctx_)); auto mul1 = make_shared<CgFunction>(create_Mul2(this->ctx_, false)); auto tmp1 = connect(mul1, {connect(sigmoid1, f_t, 1)[0], c}, 1); // F.sigmoid(f_t) * c auto sigmoid2 = make_shared<CgFunction>(create_Sigmoid(this->ctx_)); auto mul2 = make_shared<CgFunction>(create_Mul2(this->ctx_, false)); auto tanh2 = make_shared<CgFunction>(create_Tanh(this->ctx_)); auto add2 = make_shared<CgFunction>(create_Add2(this->ctx_, true)); auto tmp2 = connect(mul2, {connect(sigmoid2, i_t, 1)[0], connect(tanh2, g_t, 1)[0]}, 1); // F.sigmoid(i_t) * F.tanh(g_t) auto c_t = connect(add2, {tmp1[0], tmp2[0]}, 1); auto sigmoid3 = make_shared<CgFunction>(create_Sigmoid(this->ctx_)); auto mul3 = make_shared<CgFunction>(create_Mul2(this->ctx_, false)); auto tanh3 = make_shared<CgFunction>(create_Tanh(this->ctx_)); auto h_t = connect(mul3, {connect(sigmoid3, o_t, 1)[0], connect(tanh3, c_t, 1)[0]}, 1); // F.sigmoid(o_t) * F.tanh(c_t) return {h_t, c_t}; } template <typename T> vector<vector<CgVariablePtr>> LSTM<T>::create_fixed_length_lstm_graph( shared_ptr<CgVariable> in_x, shared_ptr<CgVariable> in_h, shared_ptr<CgVariable> in_c, shared_ptr<CgVariable> in_w0, shared_ptr<CgVariable> in_w, shared_ptr<CgVariable> in_b) { vector<CgVariablePtr> xs, hn, cn; vector<CgVariablePtr> ys_out, hn_out, cn_out; if (seq_len_ == 1) { auto tmp = cg_utils::get_item_nd(this->ctx_, in_x, vector<int>{0}); xs.push_back(tmp); } else { auto split = make_shared<CgFunction>(create_Split(this->ctx_, 0)); xs = connect(split, {in_x}, in_x->variable()->shape()[0]); } // Create graph & pass value for (int i = 0; i < num_layers_; i++) { vector<CgVariablePtr> hs; shared_ptr<CgVariable> hf_var, cf_var, wf_var, bf_var; shared_ptr<CgVariable> hb_var, cb_var, wb_var, bb_var; auto wi = in_w0; if (i > 0) { wi = cg_utils::get_item_nd(this->ctx_, in_w, vector<int>{i - 1}); // w[i-1]; } // Forward on graph hf_var = cg_utils::get_item_nd(this->ctx_, in_h, vector<int>{i, 0}); // h0[i,0] cf_var = cg_utils::get_item_nd(this->ctx_, in_c, vector<int>{i, 0}); // c[i,0] wf_var = cg_utils::get_item_nd(this->ctx_, wi, vector<int>{0}); // wi[0] if (bias_exists_ == true) { bf_var = cg_utils::get_item_nd(this->ctx_, in_b, vector<int>{i, 0}); // b[i, 0] } for (vector<CgVariablePtr>::size_type k = 0; k < xs.size(); k++) { auto tmp = lstm_cell(xs[k], hf_var, cf_var, wf_var, bf_var); hf_var = (tmp[0])[0]; cf_var = (tmp[1])[0]; hs.push_back(hf_var); } hn.push_back(hf_var); cn.push_back(cf_var); if (bidirectional_ == false) { xs = hs; continue; } // backward on graph hb_var = cg_utils::get_item_nd(this->ctx_, in_h, vector<int>{i, 1}); // h0[i,1] cb_var = cg_utils::get_item_nd(this->ctx_, in_c, vector<int>{i, 1}); // c0[i,1] wb_var = cg_utils::get_item_nd(this->ctx_, wi, vector<int>{1}); // wi[1] if (bias_exists_ == true) { bb_var = cg_utils::get_item_nd(this->ctx_, in_b, vector<int>{i, 1}); // b[i, 1] } if (xs.size() > 1) { std::reverse(std::begin(xs), std::end(xs)); } for (vector<CgVariablePtr>::size_type k = 0; k < xs.size(); k++) { int j = xs.size() - 1 - k; auto tmp = lstm_cell(xs[k], hb_var, cb_var, wb_var, bb_var); hb_var = (tmp[0])[0]; cb_var = (tmp[1])[0]; auto concatenate = make_shared<CgFunction>(create_Concatenate(this->ctx_, 1)); auto h_t = connect(concatenate, {hs[j], hb_var}, 1); hs[j] = h_t[0]; } hn.push_back(hb_var); cn.push_back(cb_var); xs = hs; } auto stack_y = make_shared<CgFunction>(create_Stack(this->ctx_, 0)); ys_out = connect(stack_y, xs, 1); vector<int> shape_ys{seq_len_, batch_size_, num_directions_ * hidden_size_}; auto reshape_ys = make_shared<CgFunction>(create_Reshape(this->ctx_, shape_ys, true)); ys_out = connect(reshape_ys, ys_out, 1); auto stack_hn = make_shared<CgFunction>(create_Stack(this->ctx_, 0)); hn_out = connect(stack_hn, hn, 1); vector<int> shape_hn{num_layers_, num_directions_, batch_size_, hidden_size_}; auto reshape = make_shared<CgFunction>(create_Reshape(this->ctx_, shape_hn, true)); hn_out = connect(reshape, hn_out, 1); auto stack_cn = make_shared<CgFunction>(create_Stack(this->ctx_, 0)); cn_out = connect(stack_cn, cn, 1); auto reshape_cn = make_shared<CgFunction>(create_Reshape(this->ctx_, shape_hn, true)); cn_out = connect(reshape_cn, cn_out, 1); return {ys_out, hn_out, cn_out}; } template <typename T> void LSTM<T>::forward_impl_training(const Variables &inputs, const Variables &outputs) { bool need_grad = this->training_; x_ = make_shared<CgVariable>(inputs[0]->view(), need_grad); // x h_ = make_shared<CgVariable>(inputs[1]->view(), need_grad); // h c_ = make_shared<CgVariable>(inputs[2]->view(), need_grad); // c w0_ = make_shared<CgVariable>(inputs[3]->view(), need_grad); // w0 if (inputs.size() == 5) { if (weight_exists_) { w_ = make_shared<CgVariable>(inputs[4]->view(), need_grad); // w } else if (bias_exists_) { b_ = make_shared<CgVariable>(inputs[4]->view(), need_grad); // b } } if (inputs.size() > 5) { w_ = make_shared<CgVariable>(inputs[4]->view(), need_grad); // w b_ = make_shared<CgVariable>(inputs[5]->view(), need_grad); // b } auto out_lstm = create_fixed_length_lstm_graph(x_, h_, c_, w0_, w_, b_); ys_ = out_lstm[0]; hn_ = out_lstm[1]; cn_ = out_lstm[2]; auto sink = make_shared<CgFunction>(create_Sink(this->ctx_, false)); auto dummy = connect(sink, {ys_[0], hn_[0], cn_[0]}, 1); dummy[0]->forward(false, true); cg_utils::copy_data_cgvariable_to_variable<T>(this->ctx_, ys_[0], outputs[0]); cg_utils::copy_data_cgvariable_to_variable<T>(this->ctx_, hn_[0], outputs[1]); cg_utils::copy_data_cgvariable_to_variable<T>(this->ctx_, cn_[0], outputs[2]); } template <typename T> void LSTM<T>::forward_impl_inference(const Variables &inputs, const Variables &outputs) { bool need_grad = this->training_; x_ = make_shared<CgVariable>(inputs[0]->view(), need_grad); // x h_ = make_shared<CgVariable>(inputs[1]->view(), need_grad); // h c_ = make_shared<CgVariable>(inputs[2]->view(), need_grad); // c w0_ = make_shared<CgVariable>(inputs[3]->view(), need_grad); // w0 if (inputs.size() == 5) { if (weight_exists_) { w_ = make_shared<CgVariable>(inputs[4]->view(), need_grad); // w } else if (bias_exists_) { b_ = make_shared<CgVariable>(inputs[4]->view(), need_grad); // b } } if (inputs.size() > 5) { w_ = make_shared<CgVariable>(inputs[4]->view(), need_grad); // w b_ = make_shared<CgVariable>(inputs[5]->view(), need_grad); // b } auto out_lstm = create_fixed_length_lstm_graph(x_, h_, c_, w0_, w_, b_); ys_ = out_lstm[0]; hn_ = out_lstm[1]; cn_ = out_lstm[2]; auto sink = make_shared<CgFunction>(create_Sink(this->ctx_, false)); auto dummy = connect(sink, {ys_[0], hn_[0], cn_[0]}, 1); dummy[0]->forward(true, false); cg_utils::copy_data_cgvariable_to_variable<T>(this->ctx_, ys_[0], outputs[0]); cg_utils::copy_data_cgvariable_to_variable<T>(this->ctx_, hn_[0], outputs[1]); cg_utils::copy_data_cgvariable_to_variable<T>(this->ctx_, cn_[0], outputs[2]); } template <typename T> void LSTM<T>::forward_impl(const Variables &inputs, const Variables &outputs) { if (this->training_) { forward_impl_training(inputs, outputs); } else { forward_impl_inference(inputs, outputs); } } template <typename T> void LSTM<T>::backward_impl(const Variables &inputs, const Variables &outputs, const vector<bool> &propagate_down, const vector<bool> &accum) { if (!(propagate_down[0] || propagate_down[1] || propagate_down[2] || propagate_down[3] || (inputs.size() > 4 && propagate_down[4]) || (inputs.size() > 5 && propagate_down[5]))) { return; } NBLA_CHECK(this->training_, error_code::value, "Backward is called for training only."); if (inputs.size() > 5 && propagate_down[5]) { NBLA_CHECK(propagate_down[3] == propagate_down[4], error_code::value, "If bias is backpropagated, so should weights."); } // setting data for input variable & propagate_down & accum x_->variable()->set_data(inputs[0]->data()); if (!propagate_down[0]) { x_->set_need_grad(false); } if (!accum[0]) { x_->variable()->grad()->zero(); } else { x_->variable()->set_grad(inputs[0]->grad()); } h_->variable()->set_data(inputs[1]->data()); if (!propagate_down[1]) { h_->set_need_grad(false); } if (!accum[1]) { h_->variable()->grad()->zero(); } else { h_->variable()->set_grad(inputs[1]->grad()); } c_->variable()->set_data(inputs[2]->data()); if (!propagate_down[2]) { c_->set_need_grad(false); } if (!accum[2]) { c_->variable()->grad()->zero(); } else { c_->variable()->set_grad(inputs[2]->grad()); } w0_->variable()->set_data(inputs[3]->data()); if (!propagate_down[3]) { w0_->set_need_grad(false); } if (!accum[3]) { w0_->variable()->grad()->zero(); } else { w0_->variable()->set_grad(inputs[3]->grad()); } if (inputs.size() == 5) { if (weight_exists_) { w_->variable()->set_data(inputs[4]->data()); if (!propagate_down[4]) { w_->set_need_grad(false); } if (!accum[4]) { w_->variable()->grad()->zero(); } else { w_->variable()->set_grad(inputs[4]->grad()); } } else if (bias_exists_) { b_->variable()->set_data(inputs[4]->data()); if (!propagate_down[4]) { b_->set_need_grad(false); } if (!accum[4]) { b_->variable()->grad()->zero(); } else { b_->variable()->set_grad(inputs[4]->grad()); } } } if (inputs.size() == 6) { w_->variable()->set_data(inputs[4]->data()); if (!propagate_down[4]) { w_->set_need_grad(false); } if (!accum[4]) { w_->variable()->grad()->zero(); } else { w_->variable()->set_grad(inputs[4]->grad()); } b_->variable()->set_data(inputs[5]->data()); if (!propagate_down[5]) { b_->set_need_grad(false); } if (!accum[5]) { b_->variable()->grad()->zero(); } else { b_->variable()->set_grad(inputs[5]->grad()); } } ys_[0]->variable()->grad()->zero(); hn_[0]->variable()->grad()->zero(); cn_[0]->variable()->grad()->zero(); auto sink = make_shared<CgFunction>(create_Sink(this->ctx_, false)); auto dummy = connect(sink, {ys_[0], hn_[0], cn_[0]}, 1); ys_[0]->variable()->set_grad(outputs[0]->grad()); hn_[0]->variable()->set_grad(outputs[1]->grad()); cn_[0]->variable()->set_grad(outputs[2]->grad()); dummy[0]->backward(nullptr, true); } }
36.491525
80
0.612788
[ "shape", "vector" ]
0f1dba863df84abd471c8053bf01cecda0b11888
9,487
cpp
C++
Source Code/main.cpp
DanAndersen/gpu-ant-sim
db79642f2c197862a22c335844f60b25cf55e15b
[ "MIT" ]
4
2015-01-04T19:14:06.000Z
2016-07-13T18:31:11.000Z
Source Code/main.cpp
hzfmax/gpu-ant-sim
db79642f2c197862a22c335844f60b25cf55e15b
[ "MIT" ]
null
null
null
Source Code/main.cpp
hzfmax/gpu-ant-sim
db79642f2c197862a22c335844f60b25cf55e15b
[ "MIT" ]
1
2021-02-03T07:30:55.000Z
2021-02-03T07:30:55.000Z
#ifdef _WIN32 #include <windows.h> #endif #define GLEW_STATIC 1 #include <GL/glew.h> #include <stdio.h> #include <GL/glut.h> #include <GL/glui.h> #include "AntSim.h" #include <glm/gtc/type_ptr.hpp> static int winWidth = 800; static int winHeight = 600; static int winId = -1; static GLUI *glui; AntSim *antsim; const int NUM_SUPPORTED_CUBE_LENGTHS = 3; int SUPPORTED_CUBE_LENGTHS[NUM_SUPPORTED_CUBE_LENGTHS] = {32, 64, 128}; int selectedCubeLengthButton = 0; /***************************************************************************** *****************************************************************************/ static void leftButtonDownCB(void) { } /***************************************************************************** *****************************************************************************/ static void leftButtonUpCB(void) { } /***************************************************************************** *****************************************************************************/ static void middleButtonDownCB(void) { } /***************************************************************************** *****************************************************************************/ static void middleButtonUpCB(void) { } /***************************************************************************** *****************************************************************************/ static void rightButtonDownCB(void) { } /***************************************************************************** *****************************************************************************/ static void rightButtonUpCB(void) { } /***************************************************************************** *****************************************************************************/ static void mouseCB(int button, int state, int x, int y) { if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) leftButtonDownCB(); else if (button == GLUT_LEFT_BUTTON && state == GLUT_UP) leftButtonUpCB(); else if (button == GLUT_MIDDLE_BUTTON && state == GLUT_DOWN) middleButtonDownCB(); else if (button == GLUT_MIDDLE_BUTTON && state == GLUT_UP) middleButtonUpCB(); else if (button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN) rightButtonDownCB(); else if (button == GLUT_RIGHT_BUTTON && state == GLUT_UP) rightButtonUpCB(); } /***************************************************************************** *****************************************************************************/ static void motionCB(int x, int y) { } void passiveMotionCB(int,int){ } /***************************************************************************** *****************************************************************************/ void reshapeCB(int width, int height) { int tx, ty, tw, th; GLUI_Master.get_viewport_area(&tx, &ty, &tw, &th); if (th == 0) th = 1; antsim->width = tw; antsim->height = th; GLdouble aspect = (GLdouble)tw / (GLdouble)th; glViewport(0, 0, tw, th); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(60.0, aspect, 0.001, 1000); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } /***************************************************************************** *****************************************************************************/ void keyboardCB(unsigned char key, int x, int y) { } /***************************************************************************** *****************************************************************************/ void idleFunc() { if ( glutGetWindow() != winId ) { glutSetWindow(winId); } GLUI_Master.sync_live_all(); glutPostRedisplay(); } /***************************************************************************** *****************************************************************************/ void refreshCB() { if (antsim->simulationRunning) { antsim->update(); antsim->display(); glutSwapBuffers(); } } /***************************************************************************** *****************************************************************************/ void initialize() { // Initialize glew library glewInit(); // Create the gpgpu object antsim = new AntSim(winWidth, winHeight); } void __cdecl onChangeCubeLength(int id) { int selectedCubeLength = SUPPORTED_CUBE_LENGTHS[selectedCubeLengthButton]; printf("selecting cube length: %d\n", selectedCubeLength); antsim->cubeLength = selectedCubeLength; } void __cdecl restart(int id) { printf("restart button pressed\n"); antsim->restart(); } /***************************************************************************** *****************************************************************************/ void MakeGUI() { glui = GLUI_Master.create_glui("Ant Colony Simulation", 0, 0, 0); // initialization GLUI_Panel *initialization_panel = glui->add_panel("Initialization"); GLUI_Spinner *simulation_num_ants_spinner = glui->add_spinner_to_panel(initialization_panel, "Number of Ants", GLUI_SPINNER_INT, &antsim->numAnts); simulation_num_ants_spinner->set_int_limits(1, 128); int CHANGE_CUBE_LENGTH_ID = 0; GLUI_Panel *cube_length_panel = glui->add_panel_to_panel(initialization_panel, "World Size"); GLUI_RadioGroup *simulation_cube_length_radio_group = glui->add_radiogroup_to_panel(cube_length_panel, &selectedCubeLengthButton, CHANGE_CUBE_LENGTH_ID, (GLUI_Update_CB)onChangeCubeLength); for (int i = 0; i < NUM_SUPPORTED_CUBE_LENGTHS; i++) { std::string cubeLengthLabel = std::to_string(static_cast<long long>(SUPPORTED_CUBE_LENGTHS[i])); glui->add_radiobutton_to_group(simulation_cube_length_radio_group, cubeLengthLabel.c_str()); } onChangeCubeLength(0); int RESTART_ID = 1; GLUI_Button *restart_button = glui->add_button_to_panel(initialization_panel, "Restart", RESTART_ID, (GLUI_Update_CB)restart); // simulation GLUI_Panel *simulation_panel = glui->add_panel("Simulation"); GLUI_Spinner *simulation_random_movement_probability = glui->add_spinner_to_panel(simulation_panel, "Random Movement Probability", GLUI_SPINNER_FLOAT, &antsim->randomMovementProbability); simulation_random_movement_probability->set_float_limits(0.0, 1.0); GLUI_Spinner *simulation_food_nest_score_multiplier_spinner = glui->add_spinner_to_panel(simulation_panel, "Food/Nest Score Multiplier (default = 10)", GLUI_SPINNER_FLOAT, &antsim->foodNestScoreMultiplier); simulation_food_nest_score_multiplier_spinner->set_float_limits(1, 50); GLUI_Spinner *simulation_trail_score_multiplier_spinner = glui->add_spinner_to_panel(simulation_panel, "Trail Score Multiplier (default = 1)", GLUI_SPINNER_FLOAT, &antsim->trailScoreMultiplier); simulation_trail_score_multiplier_spinner->set_float_limits(1, 50); GLUI_Spinner *simulation_trail_fade_rate_spinner = glui->add_spinner_to_panel(simulation_panel, "Trail Fade Rate", GLUI_SPINNER_FLOAT, &antsim->trailDissipationPerFrame); simulation_trail_fade_rate_spinner->set_float_limits(0.0, 1.0); simulation_trail_fade_rate_spinner->set_speed(0.01f); // visualization panel GLUI_Panel *visualization_panel = glui->add_panel("Visualization"); glui->add_rotation_to_panel(visualization_panel, "Rotation", antsim->view_rotate()); GLUI_Spinner *visualization_update_rate_spinner = glui->add_spinner_to_panel(visualization_panel, "Update Rate (sec)", GLUI_SPINNER_FLOAT, &antsim->updateIntervalSeconds); visualization_update_rate_spinner->set_float_limits(0, 0.1); GLUI_Spinner *visualization_trail_opacity_spinner = glui->add_spinner_to_panel(visualization_panel, "Trail Opacity", GLUI_SPINNER_FLOAT, &antsim->trailOpacity); visualization_trail_opacity_spinner->set_float_limits(0.0, 1.0); GLUI_Spinner *visualization_camera_distance_spinner = glui->add_spinner_to_panel(visualization_panel, "Camera Distance", GLUI_SPINNER_FLOAT, &antsim->cameraDistance); visualization_camera_distance_spinner->set_float_limits(0.0, 10.0); GLUI_Panel *legend_panel = glui->add_panel("Legend"); glui->add_statictext_to_panel(legend_panel, "Red = nest"); glui->add_statictext_to_panel(legend_panel, "Green = food (fades as consumed)"); glui->add_statictext_to_panel(legend_panel, "Blue = pheromone trail (fades over time)"); glui->add_statictext_to_panel(legend_panel, "White = ant"); glui->set_main_gfx_window(winId); /* We register the idle callback with GLUI, *not* with GLUT */ GLUI_Master.set_glutIdleFunc(idleFunc); } /***************************************************************************** *****************************************************************************/ int main(int argc, char *argv[]) { // init OpenGL/GLUT glutInit(&argc, argv); // create main window glutInitWindowPosition(0, 0); glutInitWindowSize(winWidth, winHeight); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA); winId = glutCreateWindow("Ant Colony Visualization"); initialize(); // setup callbacks glutDisplayFunc(refreshCB); GLUI_Master.set_glutReshapeFunc(reshapeCB); GLUI_Master.set_glutKeyboardFunc(keyboardCB); GLUI_Master.set_glutMouseFunc(mouseCB); GLUI_Master.set_glutSpecialFunc( NULL ); glutMotionFunc(motionCB); glutPassiveMotionFunc(passiveMotionCB); // force initial matrix setup reshapeCB(winWidth, winHeight); // set modelview matrix stack to identity glMatrixMode(GL_MODELVIEW); glLoadIdentity(); // make GLUI GUI MakeGUI(); glutMainLoop(); return (TRUE); }
32.050676
207
0.570254
[ "object" ]
0f202a08d6a4269bc520f994c7292c5e63a435b5
2,356
cpp
C++
call_stack/ProcessInformation.cpp
kkptm/CppLikeCSharp
b2d8d9da9973c733205aa945c9ba734de0c734bc
[ "MIT" ]
4
2021-10-14T01:43:00.000Z
2022-03-13T02:16:08.000Z
call_stack/ProcessInformation.cpp
kkptm/CppLikeCSharp
b2d8d9da9973c733205aa945c9ba734de0c734bc
[ "MIT" ]
null
null
null
call_stack/ProcessInformation.cpp
kkptm/CppLikeCSharp
b2d8d9da9973c733205aa945c9ba734de0c734bc
[ "MIT" ]
2
2022-03-13T02:16:06.000Z
2022-03-14T14:32:57.000Z
#ifdef _WIN32_WCE #include "ProcessInformation.h" #pragma warning(push) #pragma warning(disable:4201) #include <Windows.h> #include <Tlhelp32.h> #include <Psapi.h> #include <Pkfuncs.h> #include <WINERROR.H> #pragma warning(pop) using namespace std; namespace stacktrace { static std::string ToString(const wchar_t* str) { char* newStr = new char[2*wcslen(str)+1]; WideCharToMultiByte(CP_ACP, 0, str, -1, newStr, 2*wcslen(str)+1, 0, NULL); std::string output(newStr); delete[] newStr; return output; } ProcessInformation ProcessInformation::GetProcessInformation() { return ProcessInformation(GetProcessName(), GetProcessId(), /*GetProcessVersion(),*/ GetProcessBaseAddress(), GetProcessStackFrames()); } std::string ProcessInformation::GetProcessName() { wchar_t fileName[2048]; GetModuleFileNameW(0, fileName, 2048); return stacktrace::ToString(fileName); } std::string ProcessInformation::GetFileName(std::string file) { int ind = file.find_last_of('\\'); if (ind == 0) return file; return file.substr(ind+1,file.size()-ind); } int ProcessInformation::GetProcessBaseAddress() { ModuleInformations moduleInformations = ModuleInformation::GetModuleInformations(); ModuleInformations::iterator it; for (it = moduleInformations.begin(); it != moduleInformations.end(); ++it) if (it->GetName() == GetFileName(GetProcessName())) return it->GetBaseAddress(); return 0; } StackFrames ProcessInformation::GetProcessStackFrames() { std::list< StackFrame > stackFrames; const int callSnapshotExsLength = 256; CallSnapshotEx callSnapshots[256]; int count = 0; int skipFrame = 0; do { count = GetThreadCallStack((HANDLE)GetCurrentThreadId(), callSnapshotExsLength, callSnapshots, STACKSNAP_EXTENDED_INFO, skipFrame); for (int i = 0; i < count; i++){ vector<int> params(4); for (int j = 0; j < 4; j++) params[j] = (int)callSnapshots[i].dwParams[j]; stackFrames.push_back(StackFrame(callSnapshots[i].dwReturnAddr, callSnapshots[i].dwFramePtr,params,GetProcessBaseAddress())); } skipFrame += count; } while (count == callSnapshotExsLength); return stackFrames; } int ProcessInformation::GetProcessId() { return GetCurrentProcessId(); } } #endif
29.08642
140
0.690577
[ "vector" ]
0f20bdc7f08abea642cb23583ac89d213d0a64b7
3,931
cpp
C++
src/Application.cpp
AlexLukasT/SFML-Game-Template
92ebc7d254dbc22d106063f6b91fd4a25e92baa1
[ "MIT" ]
null
null
null
src/Application.cpp
AlexLukasT/SFML-Game-Template
92ebc7d254dbc22d106063f6b91fd4a25e92baa1
[ "MIT" ]
null
null
null
src/Application.cpp
AlexLukasT/SFML-Game-Template
92ebc7d254dbc22d106063f6b91fd4a25e92baa1
[ "MIT" ]
null
null
null
#include"..\include\Application.hpp" Application::Application() { std::cout << "[Application] Start" << std::endl; this->initVariables(); this->initWindow(); this->initStates(); if (this->showFps) this->initFpsText(); } Application::~Application() { // delete object created in constructor with "new" delete this->window; while (!this->states.empty()) { // empty the states by deleting the objects and pointers delete this->states.top(); this->states.pop(); } } // initializers void Application::initWindow() { // Initialize the window with settings from graphics.cfg std::ifstream ifs("C:/Users/AlexanderTemme/Projects/BattleChess/settings/graphics.cfg"); this->videoModes = sf::VideoMode::getFullscreenModes(); std::string temp; // dummy variable to store the option names in sf::VideoMode windowSize = sf::VideoMode::getDesktopMode(); bool fullscreen = false; unsigned frameRateLimit = 60; bool vSyncEnabled = false; unsigned antialisingLevel = 0; if (ifs.is_open()) { ifs >> temp >> windowSize.width >> windowSize.height; ifs >> temp >> fullscreen; ifs >> temp >> frameRateLimit; ifs >> temp >> vSyncEnabled; ifs >> temp >> antialisingLevel; ifs >> temp >> this->showFps; } ifs.close(); sf::ContextSettings windowSettings; windowSettings.antialiasingLevel = antialisingLevel; if (fullscreen) this->window = new sf::RenderWindow(windowSize, "BattleChess", sf::Style::Fullscreen, windowSettings); else this->window = new sf::RenderWindow(windowSize, "BattleChess", sf::Style::Default, windowSettings); this->window->setFramerateLimit(frameRateLimit); this->window->setVerticalSyncEnabled(vSyncEnabled); } void Application::initVariables() { this->window = NULL; this->dt = 0.f; } void Application::initStates() { // Start in state main menu MainMenuState* mainMenuState = new MainMenuState(this->window, &this->dt, &this->states); this->states.push(mainMenuState); } void Application::initFpsText() { if (!this->font.loadFromFile("fonts/Dosis-Light.ttf")) throw "Error::Application::Could not load font"; this->fpsText.setFont(this->font); this->fpsText.setCharacterSize(20); this->fpsText.setString("120"); this->fpsText.setFillColor(sf::Color::Green); this->fpsText.setPosition( this->window->getSize().x - this->fpsText.getGlobalBounds().width, 0 ); } // functions void Application::updateDt() { // Update DateTime with the time to update and render one frame this->dt = this->dtClock.restart().asSeconds(); } void Application::updateFps() { if (fmod(this->totalClock.getElapsedTime().asSeconds(), 1.f) <= 0.1) { // update the frame counter approximately every second (and not every frame) this->fpsText.setString(std::to_string(static_cast<int>(1 / this->dt))); } } void Application::updateSFMLEvents() { while (this->window->pollEvent(this->sfEvent)) { if (this->sfEvent.type == sf::Event::Closed) { this->quit(); } } } void Application::updateStates() { if (this->states.empty()) { // No states existing -> close window this->quit(); } else { // Get the current running state, which is on top of the stack State* currentState = this->states.top(); currentState->update(); if (currentState->getQuit()) { // State wants to quit currentState->endState(); delete currentState; this->states.pop(); } } } void Application::update() { this->updateDt(); this->updateFps(); this->updateSFMLEvents(); this->updateStates(); } void Application::render() { this->window->clear(); if (!this->states.empty()) this->states.top()->render(); if (this->showFps) this->window->draw(this->fpsText); this->window->display(); } void Application::run() { int counter = 0; while (this->window->isOpen()) { this->update(); this->render(); counter++; } } void Application::quit() { std::cout << "[Application] Quit" << std::endl; this->window->close(); }
21.960894
89
0.685831
[ "render", "object" ]
0f22b7a31d692562fe471294088259cbcae2cd1f
14,533
cpp
C++
openstudiocore/src/utilities/filetypes/test/EpwFile_GTest.cpp
zhouchong90/OpenStudio
f8570cb8297547b5e9cc80fde539240d8f7b9c24
[ "BSL-1.0", "blessing" ]
null
null
null
openstudiocore/src/utilities/filetypes/test/EpwFile_GTest.cpp
zhouchong90/OpenStudio
f8570cb8297547b5e9cc80fde539240d8f7b9c24
[ "BSL-1.0", "blessing" ]
null
null
null
openstudiocore/src/utilities/filetypes/test/EpwFile_GTest.cpp
zhouchong90/OpenStudio
f8570cb8297547b5e9cc80fde539240d8f7b9c24
[ "BSL-1.0", "blessing" ]
null
null
null
/********************************************************************** * Copyright (c) 2008-2014, Alliance for Sustainable Energy. * All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********************************************************************/ #include <gtest/gtest.h> #include "../EpwFile.hpp" #include "../../time/Time.hpp" #include "../../time/Date.hpp" #include <resources.hxx> using namespace openstudio; TEST(Filetypes, EpwFile) { try{ // LOCATION,Climate Zone 1,CA,USA,CTZRV2,725945,40.80,-124.20,-8.0,13.0 // DESIGN CONDITIONS,1,Climate Design Data 2009 ASHRAE Handbook,,Heating,12,-0.6,0.6,-4.1,2.7,5.3,-2.2,3.2,3.8,11.1,12.3,9.7,11.3,2,90,Cooling,8,6.5,21.6,15.2,19.9,15.1,18.7,14.6,16.8,19.5,16.1,18.6,15.5,17.6,4.3,320,15.9,11.4,17.5,15.1,10.8,16.8,14.4,10.3,16.2,47.3,19.8,45,18.5,43.3,17.6,1804,Extremes,9,8.2,7.4,20.8,-2.5,28.3,1.7,2.2,-3.7,29.8,-4.6,31.1,-5.6,32.3,-6.8,33.9 // TYPICAL/EXTREME PERIODS,6,Summer - Week Nearest Max Temperature For Period,Extreme,7/ 8,7/14,Summer - Week Nearest Average Temperature For Period,Typical,8/12,8/18,Winter - Week Nearest Min Temperature For Period,Extreme,1/15,1/21,Winter - Week Nearest Average Temperature For Period,Typical,1/22,1/28,Autumn - Week Nearest Average Temperature For Period,Typical,11/26,12/ 2,Spring - Week Nearest Average Temperature For Period,Typical,5/27,6/ 2 // GROUND TEMPERATURES,3,.5,,,,9.66,10.10,10.96,11.78,13.32,14.13,14.35,13.94,12.99,11.81,10.64,9.87,2,,,,10.27,10.38,10.87,11.41,12.60,13.35,13.73,13.65,13.10,12.29,11.37,10.64,4,,,,10.90,10.82,11.04,11.35,12.13,12.72,13.10,13.19,12.95,12.47,11.85,11.28 // HOLIDAYS/DAYLIGHT SAVINGS,No,0,0,0 // COMMENTS 1,California Climate Zone 01 Version 2; // COMMENTS 2, -- Ground temps produced with a standard soil diffusivity of 2.3225760E-03 {m**2/day} // DATA PERIODS,1,1,Data,Sunday, 1/ 1,12/31 path p = resourcesPath() / toPath("runmanager/USA_CO_Golden-NREL.724666_TMY3.epw"); EpwFile epwFile(p); EXPECT_EQ(p, epwFile.path()); EXPECT_EQ("F188656D", epwFile.checksum()); EXPECT_EQ("Denver Centennial Golden Nr", epwFile.city()); EXPECT_EQ("CO", epwFile.stateProvinceRegion()); EXPECT_EQ("USA", epwFile.country()); EXPECT_EQ("TMY3", epwFile.dataSource()); EXPECT_EQ("724666", epwFile.wmoNumber()); EXPECT_EQ(39.74, epwFile.latitude()); EXPECT_EQ(-105.18, epwFile.longitude()); EXPECT_EQ(-7, epwFile.timeZone()); EXPECT_EQ(1829, epwFile.elevation()); EXPECT_EQ(Time(0,1,0,0), epwFile.timeStep()); EXPECT_EQ(DayOfWeek(DayOfWeek::Sunday), epwFile.startDayOfWeek()); EXPECT_EQ(Date(MonthOfYear::Jan, 1), epwFile.startDate()); EXPECT_EQ(Date(MonthOfYear::Dec, 31), epwFile.endDate()); }catch(...){ ASSERT_TRUE(false); } } TEST(Filetypes, EpwFile_Data) { try{ path p = resourcesPath() / toPath("runmanager/USA_CO_Golden-NREL.724666_TMY3.epw"); EpwFile epwFile(p); EXPECT_EQ(p, epwFile.path()); EXPECT_EQ("F188656D", epwFile.checksum()); EXPECT_EQ("Denver Centennial Golden Nr", epwFile.city()); EXPECT_EQ("CO", epwFile.stateProvinceRegion()); EXPECT_EQ("USA", epwFile.country()); EXPECT_EQ("TMY3", epwFile.dataSource()); EXPECT_EQ("724666", epwFile.wmoNumber()); EXPECT_EQ(39.74, epwFile.latitude()); EXPECT_EQ(-105.18, epwFile.longitude()); EXPECT_EQ(-7, epwFile.timeZone()); EXPECT_EQ(1829, epwFile.elevation()); EXPECT_EQ(Time(0,1,0,0), epwFile.timeStep()); EXPECT_EQ(DayOfWeek(DayOfWeek::Sunday), epwFile.startDayOfWeek()); EXPECT_EQ(Date(MonthOfYear::Jan, 1), epwFile.startDate()); EXPECT_EQ(Date(MonthOfYear::Dec, 31), epwFile.endDate()); // Up to here, everything should be the same as the first test. Now ask for the data std::vector<EpwDataPoint> data = epwFile.data(); EXPECT_EQ(8760,data.size()); // The last data point should be on 12/31/1996, with a dry bulb temp of 4C and presure 81100 EXPECT_EQ(4.0,data[8759].dryBulbTemperature().get()); EXPECT_EQ(81100,data[8759].atmosphericStationPressure().get()); // Try out the alternate access functions, dew point temperature should be -1C EXPECT_EQ(-1.0,data[8759].fieldByName("Dew Point Temperature").get()); EXPECT_EQ(-1.0,data[8759].field(EpwDataField("Dew Point Temperature")).get()); // The last data point should not have a liquid precipitation depth EXPECT_FALSE(data[8759].fieldByName("Liquid Precipitation Depth")); // Get a time series boost::optional<openstudio::TimeSeries> series = epwFile.getTimeSeries("Wind Speed"); ASSERT_TRUE(series); ASSERT_EQ(8760,series->values().size()); DateTimeVector seriesTimes = series->dateTimes(); ASSERT_EQ(8760,seriesTimes.size()); // Check the times in the data and the time series DateTime current(Date(1,1,1999),Time(0,1)); // Use 1999 to avoid leap years Time delta(0,1); for(unsigned i=0;i<8760;i++) { // This is a lot more complicated that it probably should be to avoid the year being a problem DateTime datatime = data[i].dateTime(); EXPECT_EQ(datatime.date().monthOfYear(), current.date().monthOfYear()); EXPECT_EQ(datatime.date().dayOfMonth(), current.date().dayOfMonth()); EXPECT_EQ(datatime.time().hours(), current.time().hours()); EXPECT_EQ(datatime.time().minutes(), current.time().minutes()); DateTime seriestime = seriesTimes[i]; EXPECT_EQ(seriestime.date().monthOfYear(), current.date().monthOfYear()); EXPECT_EQ(seriestime.date().dayOfMonth(), current.date().dayOfMonth()); EXPECT_EQ(seriestime.time().hours(), current.time().hours()); EXPECT_EQ(seriestime.time().minutes(), current.time().minutes()); current += delta; } // We should redo the original tests because we have reparsed the entire file EXPECT_EQ(p, epwFile.path()); EXPECT_EQ("F188656D", epwFile.checksum()); EXPECT_EQ("Denver Centennial Golden Nr", epwFile.city()); EXPECT_EQ("CO", epwFile.stateProvinceRegion()); EXPECT_EQ("USA", epwFile.country()); EXPECT_EQ("TMY3", epwFile.dataSource()); EXPECT_EQ("724666", epwFile.wmoNumber()); EXPECT_EQ(39.74, epwFile.latitude()); EXPECT_EQ(-105.18, epwFile.longitude()); EXPECT_EQ(-7, epwFile.timeZone()); EXPECT_EQ(1829, epwFile.elevation()); EXPECT_EQ(Time(0,1,0,0), epwFile.timeStep()); EXPECT_EQ(DayOfWeek(DayOfWeek::Sunday), epwFile.startDayOfWeek()); EXPECT_EQ(Date(MonthOfYear::Jan, 1), epwFile.startDate()); EXPECT_EQ(Date(MonthOfYear::Dec, 31), epwFile.endDate()); }catch(...){ ASSERT_TRUE(false); } } TEST(Filetypes, EpwFile_International_Data) { try{ path p = resourcesPath() / toPath("utilities/Filetypes/CHN_Guangdong.Shaoguan.590820_CSWD.epw"); EpwFile epwFile(p,true); EXPECT_EQ(p, epwFile.path()); EXPECT_EQ("B68C068B", epwFile.checksum()); EXPECT_EQ("Shaoguan", epwFile.city()); EXPECT_EQ("Guangdong", epwFile.stateProvinceRegion()); EXPECT_EQ("CHN", epwFile.country()); EXPECT_EQ("CSWD", epwFile.dataSource()); EXPECT_EQ("590820", epwFile.wmoNumber()); EXPECT_EQ(24.68, epwFile.latitude()); EXPECT_EQ(113.6, epwFile.longitude()); EXPECT_EQ(8, epwFile.timeZone()); EXPECT_EQ(61, epwFile.elevation()); EXPECT_EQ(Time(0,1,0,0), epwFile.timeStep()); EXPECT_EQ(DayOfWeek(DayOfWeek::Sunday), epwFile.startDayOfWeek()); EXPECT_EQ(Date(MonthOfYear::Jan, 1), epwFile.startDate()); EXPECT_EQ(Date(MonthOfYear::Dec, 31), epwFile.endDate()); // Up to here, everything should be the same as the first test. Now ask for the data std::vector<EpwDataPoint> data = epwFile.data(); EXPECT_EQ(8760,data.size()); // The last data point check EXPECT_EQ(14.7,data[8759].dryBulbTemperature().get()); EXPECT_EQ(101100,data[8759].atmosphericStationPressure().get()); // Try out the alternate access functions, dew point temperature should be -1C EXPECT_EQ(11.7,data[8759].fieldByName("Dew Point Temperature").get()); EXPECT_EQ(11.7,data[8759].field(EpwDataField("Dew Point Temperature")).get()); // The last data point should not have a liquid precipitation depth EXPECT_FALSE(data[8759].fieldByName("Liquid Precipitation Depth")); // Get a time series boost::optional<openstudio::TimeSeries> series = epwFile.getTimeSeries("Wind Speed"); ASSERT_TRUE(series); ASSERT_EQ(8760,series->values().size()); DateTimeVector seriesTimes = series->dateTimes(); ASSERT_EQ(8760,seriesTimes.size()); // Check the times in the data and the time series DateTime current(Date(1,1,1999),Time(0,1)); // Use 1999 to avoid leap years Time delta(0,1); for(unsigned i=0;i<8760;i++) { // This is a lot more complicated that it probably should be to avoid the year being a problem DateTime datatime = data[i].dateTime(); EXPECT_EQ(datatime.date().monthOfYear(), current.date().monthOfYear()); EXPECT_EQ(datatime.date().dayOfMonth(), current.date().dayOfMonth()); EXPECT_EQ(datatime.time().hours(), current.time().hours()); EXPECT_EQ(datatime.time().minutes(), current.time().minutes()); DateTime seriestime = seriesTimes[i]; EXPECT_EQ(seriestime.date().monthOfYear(), current.date().monthOfYear()); EXPECT_EQ(seriestime.date().dayOfMonth(), current.date().dayOfMonth()); EXPECT_EQ(seriestime.time().hours(), current.time().hours()); EXPECT_EQ(seriestime.time().minutes(), current.time().minutes()); current += delta; } // No need to redo the original tests here since the data should have been loaded in the constructor }catch(...){ ASSERT_TRUE(false); } } TEST(Filetypes, EpwFile_TMY) { try{ path p = resourcesPath() / toPath("utilities/Filetypes/USA_CO_Golden-NREL.724666_TMY3.epw"); EpwFile epwFile(p); EXPECT_EQ(p, epwFile.path()); EXPECT_EQ("BDF687C1", epwFile.checksum()); EXPECT_EQ("Denver Centennial Golden Nr", epwFile.city()); EXPECT_EQ("CO", epwFile.stateProvinceRegion()); EXPECT_EQ("USA", epwFile.country()); EXPECT_EQ("TMY3", epwFile.dataSource()); EXPECT_EQ("724666", epwFile.wmoNumber()); EXPECT_EQ(39.74, epwFile.latitude()); EXPECT_EQ(-105.18, epwFile.longitude()); EXPECT_EQ(-7, epwFile.timeZone()); EXPECT_EQ(1829, epwFile.elevation()); EXPECT_EQ(Time(0,1,0,0), epwFile.timeStep()); EXPECT_EQ(DayOfWeek(DayOfWeek::Sunday), epwFile.startDayOfWeek()); EXPECT_FALSE(epwFile.startDateActualYear()); EXPECT_FALSE(epwFile.endDateActualYear()); EXPECT_EQ(Date(MonthOfYear::Jan, 1), epwFile.startDate()); EXPECT_EQ(Date(MonthOfYear::Dec, 31), epwFile.endDate()); EXPECT_EQ(365, (epwFile.endDate() - epwFile.startDate()).totalDays() + 1); }catch(...){ ASSERT_TRUE(false); } } TEST(Filetypes, EpwFile_Wrap_TMY) { try{ path p = resourcesPath() / toPath("utilities/Filetypes/USA_CO_Golden-NREL.wrap.epw"); EpwFile epwFile(p); EXPECT_TRUE(false); }catch(...){ EXPECT_TRUE(true); } } TEST(Filetypes, EpwFile_AMY) { try{ path p = resourcesPath() / toPath("utilities/Filetypes/USA_CO_Golden-NREL.amy"); EpwFile epwFile(p); EXPECT_EQ(p, epwFile.path()); EXPECT_EQ("521A957C", epwFile.checksum()); EXPECT_EQ("Denver Centennial Golden Nr", epwFile.city()); EXPECT_EQ("CO", epwFile.stateProvinceRegion()); EXPECT_EQ("USA", epwFile.country()); EXPECT_EQ("TMY3", epwFile.dataSource()); EXPECT_EQ("724666", epwFile.wmoNumber()); EXPECT_EQ(39.74, epwFile.latitude()); EXPECT_EQ(-105.18, epwFile.longitude()); EXPECT_EQ(-7, epwFile.timeZone()); EXPECT_EQ(1829, epwFile.elevation()); EXPECT_EQ(Time(0,1,0,0), epwFile.timeStep()); EXPECT_EQ(DayOfWeek(DayOfWeek::Friday), epwFile.startDayOfWeek()); ASSERT_TRUE(epwFile.startDateActualYear()); EXPECT_EQ(1999, epwFile.startDateActualYear().get()); ASSERT_TRUE(epwFile.endDateActualYear()); EXPECT_EQ(1999, epwFile.endDateActualYear().get()); EXPECT_EQ(Date(MonthOfYear::Jan, 1, 1999), epwFile.startDate()); EXPECT_EQ(Date(MonthOfYear::Dec, 31, 1999), epwFile.endDate()); EXPECT_EQ(365, (epwFile.endDate() - epwFile.startDate()).totalDays() + 1); }catch(...){ ASSERT_TRUE(false); } } TEST(Filetypes, EpwFile_Wrap_AMY) { try{ path p = resourcesPath() / toPath("utilities/Filetypes/USA_CO_Golden-NREL.wrap.amy"); EpwFile epwFile(p); EXPECT_EQ(p, epwFile.path()); EXPECT_EQ("8F74A20B", epwFile.checksum()); EXPECT_EQ("Denver Centennial Golden Nr", epwFile.city()); EXPECT_EQ("CO", epwFile.stateProvinceRegion()); EXPECT_EQ("USA", epwFile.country()); EXPECT_EQ("TMY3", epwFile.dataSource()); EXPECT_EQ("724666", epwFile.wmoNumber()); EXPECT_EQ(39.74, epwFile.latitude()); EXPECT_EQ(-105.18, epwFile.longitude()); EXPECT_EQ(-7, epwFile.timeZone()); EXPECT_EQ(1829, epwFile.elevation()); EXPECT_EQ(Time(0,1,0,0), epwFile.timeStep()); EXPECT_EQ(DayOfWeek(DayOfWeek::Saturday), epwFile.startDayOfWeek()); ASSERT_TRUE(epwFile.startDateActualYear()); EXPECT_EQ(1999, epwFile.startDateActualYear().get()); ASSERT_TRUE(epwFile.endDateActualYear()); EXPECT_EQ(2000, epwFile.endDateActualYear().get()); EXPECT_EQ(Date(MonthOfYear::Apr, 10, 1999), epwFile.startDate()); EXPECT_EQ(Date(MonthOfYear::Apr, 8, 2000), epwFile.endDate()); // 2000 is a leap year EXPECT_EQ(365, (epwFile.endDate() - epwFile.startDate()).totalDays() + 1); }catch(...){ ASSERT_TRUE(false); } }
49.264407
453
0.668135
[ "vector" ]
0f29068582df2888c200f2a3491e1a14f6ba46e6
3,187
hpp
C++
lib/parsers/sourceparser.hpp
AstyCo/LazyRT
718e2faf8cb3181c0513e80c3db355f45616bc61
[ "MIT" ]
null
null
null
lib/parsers/sourceparser.hpp
AstyCo/LazyRT
718e2faf8cb3181c0513e80c3db355f45616bc61
[ "MIT" ]
null
null
null
lib/parsers/sourceparser.hpp
AstyCo/LazyRT
718e2faf8cb3181c0513e80c3db355f45616bc61
[ "MIT" ]
null
null
null
#ifndef SOURCE_PARSER_HPP #define SOURCE_PARSER_HPP #include "tokenizer.hpp" #include <types/splitted_string.hpp> class FileNode; class FileTree; class IncludeDirective; template < typename T > class SimpleStack { std::vector< T > stack; public: void push(const T &value) { stack.push_back(value); } bool isOnTop(const T &value) const { if (stack.empty()) return false; return stack.back() == value; } void pop() { stack.pop_back(); } void clear() { stack.clear(); } }; template < typename T > class SparceStack { int _deep = 0; SimpleStack< T > _stack; public: void push(const T &value) { ++_deep; _stack.push(value); } bool pop(int totalDeep) { if (_stack.isOnTop(totalDeep)) { --_deep; _stack.pop(); return true; } return false; } void clear() { _deep = 0; _stack.clear(); } int deep() const { return _deep; } }; class SourceParser { using TokenVector = std::vector< Token >; using TokenNameSet = std::unordered_set< TokenName, EnumClassHash >; public: explicit SourceParser(const FileTree &ftree); void parseFile(FileNode *node); private: bool parseScopedName(const TokenVector &v, int offset, int end, SplittedPath &name); int getIdentifierStart(const TokenVector &v, int offset) const; void skipOperatorOverloadingReverse(const TokenVector &v, int &offset) const; void skipLine(const TokenVector &tokens, int &offset) const; void skipUntilEndif(const TokenVector &tokens, int &offset) const; bool skipTemplate(const TokenVector &v, int &offset) const; bool skipTemplateReverse(const TokenVector &tokens, int &offset) const; void prepare(); TokenName readUntil(const TokenVector &tokens, int &offset, const TokenNameSet &tokenNames); void increment(const TokenVector &tokens, int &offset, bool checkRange = false); void increment_pp(int &offset, int n = 1) const { offset += n; } void decrement_pp(int &offset, int n = 1) const { offset -= n; } bool isTopLevelCB() const; void setNamespace(); void dealWithClassDeclaration(const TokenVector &tokens, int offset); void parseIncludeFilename(const TokenVector &tokens, int &offset, IncludeDirective &dir); void readPath(const TokenVector &tokens, int &offset, SplittedPath &path); bool checkOffset(const TokenVector &tokens, int offset) const; void assertOnBadRange(const TokenVector &tokens, int offset) const; bool isClassToken(const TokenVector &tokens, int offset) const; bool isInheritanceToken(const TokenVector &tokens, int offset) const; private: const FileTree &_fileTree; FileNode *_node; ScopedName _currentNamespace; std::vector< ScopedName > _listUsingNamespace; int _openBracketCount; int _openCurlyBracketCount; SparceStack< int > _stackNamespaceBrackets; SparceStack< int > _stackExternConstruction; }; #endif // SOURCE_PARSER_HPP
27.239316
78
0.650769
[ "vector" ]
0f2c72d9d7c9f850d36a47325d9abb2ce0c413d2
3,136
cpp
C++
csrc/test_keyutils.cpp
LaudateCorpus1/amazon-corretto-crypto-provider
80b3fa918a4787dd5d1d4e3b2451f7e0e5ae5aad
[ "Apache-2.0" ]
157
2019-07-15T17:33:37.000Z
2022-03-17T03:23:49.000Z
csrc/test_keyutils.cpp
LaudateCorpus1/amazon-corretto-crypto-provider
80b3fa918a4787dd5d1d4e3b2451f7e0e5ae5aad
[ "Apache-2.0" ]
84
2019-07-15T19:21:12.000Z
2022-03-29T22:29:07.000Z
csrc/test_keyutils.cpp
LaudateCorpus1/amazon-corretto-crypto-provider
80b3fa918a4787dd5d1d4e3b2451f7e0e5ae5aad
[ "Apache-2.0" ]
31
2019-07-15T22:44:35.000Z
2022-01-07T03:40:43.000Z
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 #include "keyutils.h" #include "test_utils.h" #include "util.h" using namespace AmazonCorrettoCryptoProvider; namespace { #define DER_LENGTH 138 /* SEQUENCE (3 elem) INTEGER 0 SEQUENCE (2 elem) OBJECT IDENTIFIER 1.2.840.10045.2.1 ecPublicKey (ANSI X9.62 public key type) OBJECT IDENTIFIER 1.2.840.10045.3.1.7 prime256v1 (ANSI X9.62 named elliptic curve) OCTET STRING (1 elem) SEQUENCE (3 elem) INTEGER 1 OCTET STRING (32 byte) 4309C0677521479DA8FA16DF15736134686FE38E479195AB794A7214CBE2494F [1] (1 elem) BIT STRING (520 bit) 0000010011011110000010010000100000000111000000110010111010001111001101… */ static const uint8_t validPKCS8ECKey[DER_LENGTH] = { 0x30, 0x81, 0x87, 0x02, 0x01, 0x00, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x04, 0x6d, 0x30, 0x6b, 0x02, 0x01, 0x01, 0x04, 0x20, 0x43, 0x09, 0xc0, 0x67, 0x75, 0x21, 0x47, 0x9d, 0xa8, 0xfa, 0x16, 0xdf, 0x15, 0x73, 0x61, 0x34, 0x68, 0x6f, 0xe3, 0x8e, 0x47, 0x91, 0x95, 0xab, 0x79, 0x4a, 0x72, 0x14, 0xcb, 0xe2, 0x49, 0x4f, 0xa1, 0x44, 0x03, 0x42, 0x00, 0x04, 0xde, 0x09, 0x08, 0x07, 0x03, 0x2e, 0x8f, 0x37, 0x9a, 0xd5, 0xad, 0xe5, 0xc6, 0x9d, 0xd4, 0x63, 0xc7, 0x4a, 0xe7, 0x20, 0xcb, 0x90, 0xa0, 0x1f, 0x18, 0x18, 0x72, 0xb5, 0x21, 0x88, 0x38, 0xc0, 0xdb, 0xba, 0xf6, 0x99, 0xd8, 0xa5, 0x3b, 0x83, 0xe9, 0xe3, 0xd5, 0x61, 0x99, 0x73, 0x42, 0xc6, 0x6c, 0xe8, 0x0a, 0x95, 0x40, 0x41, 0x3b, 0x0d, 0x10, 0xa7, 0x4a, 0x93, 0xdb, 0x5a, 0xe7, 0xec, }; void test_deserialize_valid_key() { EVP_PKEY* result = der2EvpPrivateKey(validPKCS8ECKey, DER_LENGTH, false, EX_INVALID_KEY); TEST_ASSERT(result); EVP_PKEY_free(result); } void test_deserialize_invalid_der() { uint8_t invalidKey[DER_LENGTH]; memcpy(invalidKey, validPKCS8ECKey, DER_LENGTH); // This makes the private key invalid invalidKey[34] = 0; try { der2EvpPrivateKey(invalidKey, DER_LENGTH, false, EX_INVALID_KEY); FAIL(); } catch (...) { // Expected } } void test_deserialize_empty() { // This makes the DER encoding invalid for a PKCS8 key but still the right length uint8_t emptyKey[1] = {0x00}; try { der2EvpPrivateKey(emptyKey, 0, false, EX_INVALID_KEY); FAIL(); } catch (...) { // Expected } } void test_deserialize_extra_data() { uint8_t invalidKey[DER_LENGTH]; memcpy(invalidKey, validPKCS8ECKey, DER_LENGTH); // This sets the der to have 0 elements but still has data and will hit the extra key info invalidKey[0] = 0; try { der2EvpPrivateKey(invalidKey, DER_LENGTH, false, EX_INVALID_KEY); FAIL(); } catch (...) { // Expected } } }// anon namespace int main() { BEGIN_TEST(); RUNTEST(test_deserialize_valid_key); RUNTEST(test_deserialize_invalid_der); RUNTEST(test_deserialize_empty); RUNTEST(test_deserialize_extra_data); END_TEST(); }
32.329897
100
0.67602
[ "object" ]
0f2c85156bb4dcd2b41d0f8b0afcffd4de9e1f4b
704
cpp
C++
Unreal/Plugins/AirSim/Source/Car/CarWheelRear.cpp
jelaredulla/thesis
dc348652cc0bd0a35e5d7506144d641510c2483b
[ "MIT" ]
null
null
null
Unreal/Plugins/AirSim/Source/Car/CarWheelRear.cpp
jelaredulla/thesis
dc348652cc0bd0a35e5d7506144d641510c2483b
[ "MIT" ]
null
null
null
Unreal/Plugins/AirSim/Source/Car/CarWheelRear.cpp
jelaredulla/thesis
dc348652cc0bd0a35e5d7506144d641510c2483b
[ "MIT" ]
null
null
null
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #include "CarWheelRear.h" #include "TireConfig.h" #include "UObject/ConstructorHelpers.h" UCarWheelRear::UCarWheelRear() { ShapeRadius = 18.0f; ShapeWidth = 15.0f; bAffectedByHandbrake = true; SteerAngle = 0.f; // Setup suspension forces SuspensionForceOffset = -4.0f; SuspensionMaxRaise = 8.0f; SuspensionMaxDrop = 12.0f; SuspensionNaturalFrequency = 9.0f; SuspensionDampingRatio = 1.05f; // Find the tire object and set the data for it static ConstructorHelpers::FObjectFinder<UTireConfig> TireData(TEXT("/AirSim/VehicleAdv/Vehicle/WheelData/Vehicle_BackTireConfig.Vehicle_BackTireConfig")); TireConfig = TireData.Object; }
28.16
156
0.774148
[ "object" ]
0f39de3955d5c04fa32be8f147bf85d450735a03
5,503
hpp
C++
src/netspeak/util/StringIdMap.hpp
netspeak/netspeak4-application-cpp
b322c19e22c71f39be95b37b14f43daab1cb9024
[ "MIT" ]
null
null
null
src/netspeak/util/StringIdMap.hpp
netspeak/netspeak4-application-cpp
b322c19e22c71f39be95b37b14f43daab1cb9024
[ "MIT" ]
7
2020-06-02T18:37:02.000Z
2021-02-17T11:04:22.000Z
src/netspeak/util/StringIdMap.hpp
netspeak/netspeak4-application-ngrams
b322c19e22c71f39be95b37b14f43daab1cb9024
[ "MIT" ]
null
null
null
#ifndef NETSPEAK_UTIL_STRING_ID_MAP_HPP #define NETSPEAK_UTIL_STRING_ID_MAP_HPP #include <stdint.h> #include <cstring> #include <string> #include <vector> namespace netspeak { namespace util { /** * @brief This is a highly specialized data structure for strings with ids. * * The data stored is a collection of strings where each string has a unique id * of type `Id`. Ids are assumed to incrementing number. Random ids are not * supported. * * This collection implements efficient maps mapping from id to string and * string to id. At most 2^32-1 elements are supported. * * Memory consumption is tuned to be as minimal as possible. * * To get the string data from an iterator, use the `get_c_str` methods. * * @tparam Id */ template <typename Id> class StringIdMap { private: typedef uint32_t CharDataOffset; public: struct string_entry { private: CharDataOffset offset_; friend class StringIdMap; friend class Builder; string_entry() = delete; string_entry(CharDataOffset offset) : offset_(offset) {} }; typedef std::pair<string_entry, Id> ValueType; typedef typename std::vector<ValueType>::const_iterator const_iterator; class Builder { private: std::vector<char> char_data_; std::vector<ValueType> id_data_; friend class StringIdMap; public: Builder() : char_data_(), id_data_() {} Builder(const Builder&) = delete; void append(const std::string& word, Id id) { // new entry string_entry offset(static_cast<CharDataOffset>(char_data_.size())); id_data_.emplace_back(offset, id); // append characters char_data_.insert(char_data_.end(), word.begin(), word.end()); char_data_.push_back('\0'); } }; private: static const char* get_c_str(const char* data, const string_entry& entry) { return data + static_cast<size_t>(entry.offset_); } static const char* get_c_str(const char* data, const ValueType& value) { return get_c_str(data, value.first); } static bool str_less_than(const char* a, const char* b) { return ::strcmp(a, b) < 0; } static std::vector<ValueType> create_sorted_words( const std::vector<char>& char_data_, std::vector<ValueType>&& id_data) { std::vector<ValueType> sorted_words(std::move(id_data)); sorted_words.shrink_to_fit(); const auto data = char_data_.data(); std::sort(sorted_words.begin(), sorted_words.end(), [data](const ValueType& a, const ValueType& b) { return str_less_than(get_c_str(data, a), get_c_str(data, b)); }); return std::move(sorted_words); } static std::vector<uint32_t> create_id_map( const std::vector<ValueType>& sorted_words_) { std::vector<uint32_t> id_map; const uint32_t len = static_cast<uint32_t>(sorted_words_.size()); for (uint32_t i = 0; i < len; i++) { size_t index = static_cast<size_t>(sorted_words_[i].second); if (index < id_map.size()) { id_map[index] = i; } else { // fill the gaps with end() for (size_t i = id_map.size(); i < index; i++) { id_map.push_back(len); } id_map.push_back(i); } } id_map.shrink_to_fit(); return id_map; } public: explicit StringIdMap(Builder&& builder) { char_data_ = std::move(builder.char_data_); char_data_.shrink_to_fit(); sorted_words_ = std::move(create_sorted_words(char_data_, std::move(builder.id_data_))); id_map_ = std::move(create_id_map(sorted_words_)); } StringIdMap(const StringIdMap&) = delete; public: size_t size() const { return sorted_words_.size(); } bool empty() const { return size() == 0; } const_iterator begin() const { return sorted_words_.begin(); } const_iterator end() const { return sorted_words_.end(); } const_iterator find_for_id(Id id) const { size_t index = static_cast<size_t>(id); if (index < id_map_.size()) { auto it = begin(); std::advance(it, id_map_[index]); return it; } return end(); } const_iterator find_for_word(const char* word) const { // see the following for the implementation: // https://en.cppreference.com/w/cpp/algorithm/binary_search#Possible_implementation const auto data = char_data_.data(); typedef const char* CharPtr; auto it = std::lower_bound(begin(), end(), word, [data](const ValueType& a, const CharPtr& b) { return str_less_than(get_c_str(data, a), b); }); if (!(it == end()) && !str_less_than(word, get_c_str(data, *it))) { return it; } return end(); } const_iterator find_for_word(const std::string& str) const { return find_for_word(str.c_str()); } const char* get_c_str(const string_entry& entry) const { return get_c_str(char_data_.data(), entry); } const char* get_c_str(const ValueType& value) const { return get_c_str(char_data_.data(), value); } private: // This stores the raw character data. // All words are terminated by a NUL character. std::vector<char> char_data_; // This stores the `const char*` (compressed as an uint32_t) and the id for // the word. std::vector<ValueType> sorted_words_; // This stores the index in `sorted_words_` each id maps to. // Gaps are filled with `sorted_words_.size()`. std::vector<uint32_t> id_map_; }; } // namespace util } // namespace netspeak #endif
27.515
88
0.657278
[ "vector" ]
0f3c278e1b22798226f177b1736ea161ab848b25
4,186
cpp
C++
src/questionwindow.cpp
caozx1110/ThunderClass
e7e06a6cefa63887e2ebcbf34c2d855c06651aee
[ "Apache-2.0" ]
1
2022-03-31T06:27:32.000Z
2022-03-31T06:27:32.000Z
src/questionwindow.cpp
caozx1110/ThunderClass
e7e06a6cefa63887e2ebcbf34c2d855c06651aee
[ "Apache-2.0" ]
null
null
null
src/questionwindow.cpp
caozx1110/ThunderClass
e7e06a6cefa63887e2ebcbf34c2d855c06651aee
[ "Apache-2.0" ]
null
null
null
#include "questionwindow.h" #include "ui_questionwindow.h" //6-16 QuestionWindow::QuestionWindow(QWidget *parent, TeacherProcess* pProc, bool IsSendToAll) : QDialog(parent), ui(new Ui::QuestionWindow) { ui->setupUi(this); m_pProc = pProc; m_ChoiceAnswList.clear(); //6-19,清除回答列表 //6-17,根据是否发送全班设定控件是否可用 m_bIsSendToAll = IsSendToAll; ui->edtQptionA->setEnabled(m_bIsSendToAll); ui->edtQptionB->setEnabled(m_bIsSendToAll); ui->edtQptionC->setEnabled(m_bIsSendToAll); ui->edtQptionD->setEnabled(m_bIsSendToAll); ui->btnCount->setEnabled(m_bIsSendToAll); //6-19 model = new QStandardItemModel(); model->setColumnCount(5); //列数为5 //设置表头 model->setHeaderData(0, Qt::Horizontal, QString::fromStdString("用户名")); model->setHeaderData(1, Qt::Horizontal, QString::fromStdString("A")); model->setHeaderData(2, Qt::Horizontal, QString::fromStdString("B")); model->setHeaderData(3, Qt::Horizontal, QString::fromStdString("C")); model->setHeaderData(4, Qt::Horizontal, QString::fromStdString("D")); //设定参数 ui->tableView->setModel(model); ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers); //使表格不可编辑 ui->tableView->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft); //表头居左 ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); //改变列宽,充满屏幕 } QuestionWindow::~QuestionWindow() { delete ui; } void QuestionWindow::on_btnQuit_clicked() { this->close(); //关闭界面 } //6-17改为两种情况 void QuestionWindow::on_btnSend_clicked() { QMessageBox MsgBox; if (m_bIsSendToAll) //群发 { ui->lblSendToName->setText("全班同学"); //发送 m_pProc->SendChoice(ui->txtedtQues->toPlainText(), ui->edtQptionA->text(), ui->edtQptionB->text(), ui->edtQptionC->text(), ui->edtQptionD->text()); } else //单发 { QString SendToName; m_pProc->SendQues(ui->txtedtQues->toPlainText(), SendToName); //发送 ui->lblSendToName->setText(SendToName); } MsgBox.setText("发送成功!"); MsgBox.exec(); } //6-17更改显示 //在界面上增加答案 void QuestionWindow::AddAnswer(const QString Name, const QString Ans) { QString text = ui->txtedtAnswer->toPlainText(); if (m_bIsSendToAll) //如果是群发选择题,储存回答信息 { m_ChoiceAnswList.push_back(pair<QString, QString>(Name, Ans)); } if (text == "") //如果是第一条消息不需要换行 { ui->txtedtAnswer->setText(Name + ": " + Ans); } else { ui->txtedtAnswer->setText(text + "\n" + Name + ": " + Ans); } } //6-19 //统计回答信息 void QuestionWindow::on_btnCount_clicked() { unsigned int i = 0; //清空表格 model->removeRows(0, model->rowCount() - 1); //根据回答列表设置表格内容 for (i = 0; i < m_ChoiceAnswList.size(); i++) { model->setItem(i, 0, new QStandardItem(m_ChoiceAnswList[i].first)); //model->item(i, 0)->setTextAlignment(Qt::AlignCenter); //设置字符位置 //根据答案信息设定选项的选择与否 m_ChoiceAnswList[i].second.contains("A") ? model->setItem(i, 1, new QStandardItem("Checked")) : model->setItem(i, 1, new QStandardItem("")); m_ChoiceAnswList[i].second.contains("B") ? model->setItem(i, 2, new QStandardItem("Checked")) : model->setItem(i, 2, new QStandardItem("")); m_ChoiceAnswList[i].second.contains("C") ? model->setItem(i, 3, new QStandardItem("Checked")) : model->setItem(i, 3, new QStandardItem("")); m_ChoiceAnswList[i].second.contains("D") ? model->setItem(i, 4, new QStandardItem("Checked")) : model->setItem(i, 4, new QStandardItem("")); } //统计某个选项有多少人选择 model->setItem(i, 0, new QStandardItem("总计")); model->item(i, 0)->setForeground(QBrush(QColor(255, 0, 0))); //设置字符颜色 //看每一列的选择人数 for(unsigned int j = 1; j <= 4; j++) { unsigned int Count = 0; for (unsigned int k = 0; k < m_ChoiceAnswList.size(); k++) { if (model->item(k, j)->text() == "Checked") { Count++; } } //设置总共的选择人数 model->setItem(i, j, new QStandardItem(QString::number(Count))); model->item(i, j)->setForeground(QBrush(QColor(255, 0, 0))); //设置字符颜色 } }
31.007407
155
0.628524
[ "model" ]
0f3e041dd83e999627e97dec8b99d070a4b12650
1,793
cpp
C++
Array/4Sum II.cpp
HectorTa1989/LeetCode-Cpp
506c92d5b0f3084e6a5099b99a3cffdd327211d9
[ "MIT" ]
null
null
null
Array/4Sum II.cpp
HectorTa1989/LeetCode-Cpp
506c92d5b0f3084e6a5099b99a3cffdd327211d9
[ "MIT" ]
null
null
null
Array/4Sum II.cpp
HectorTa1989/LeetCode-Cpp
506c92d5b0f3084e6a5099b99a3cffdd327211d9
[ "MIT" ]
null
null
null
/*Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are such that A[i] + B[j] + C[k] + D[l] is zero. To make problem a bit easier, all A, B, C, D have same length of N where 0 ≤ N ≤ 500. All integers are in the range of -228 to 228 - 1 and the result is guaranteed to be at most 231 - 1. Example: Input: A = [ 1, 2] B = [-2,-1] C = [-1, 2] D = [ 0, 2] Output: 2 Explanation: The two tuples are: 1. (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0 2. (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0*/ //Runtime: 368 ms, faster than 43.04% of C++ online submissions for 4Sum II. //Memory Usage: 43.9 MB, less than 31.82% of C++ online submissions for 4Sum II. class Solution { public: int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) { unordered_map<int, int> absum; auto cnt = 0; for (auto a: A) for (auto b: B) absum[a + b]++; for (auto c: C) for (auto d: D) cnt += absum[0 - c - d]; return cnt; } }; //Runtime: 628 ms, faster than 17.03% of C++ online submissions for 4Sum II. //Memory Usage: 32.2 MB, less than 54.55% of C++ online submissions for 4Sum II. class Solution { public: int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) { int count; map<int, int> AB; for(int a : A) for(int b : B) AB[a + b]++; count = 0; for(int c : C) for(int d : D){ int sum = -c - d; if(AB.find(sum) != AB.end()) count += AB[sum]; } return count; } };
29.393443
140
0.492471
[ "vector" ]
0f44976c4c534aeb0e38e2cd41cee12efaa18e22
1,618
cpp
C++
HDUOJ/1548/bfs.cpp
codgician/ACM
391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4
[ "MIT" ]
2
2018-02-14T01:59:31.000Z
2018-03-28T03:30:45.000Z
HDUOJ/1548/bfs.cpp
codgician/ACM
391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4
[ "MIT" ]
null
null
null
HDUOJ/1548/bfs.cpp
codgician/ACM
391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4
[ "MIT" ]
2
2017-12-30T02:46:35.000Z
2018-03-28T03:30:49.000Z
#include <iostream> #include <cstdio> #include <algorithm> #include <cmath> #include <string> #include <cstring> #include <iomanip> #include <climits> #include <vector> #include <queue> #include <map> #include <set> #include <stack> #include <functional> #include <iterator> #define SIZE 201 using namespace std; typedef struct _Node { int pt; int step; } Node; int arr[SIZE]; bool hasVisited[SIZE]; int floorNum; int bfs(int startPt, int endPt) { memset(hasVisited, false, sizeof(hasVisited)); queue<Node> q; Node startNode; startNode.pt = startPt; startNode.step = 0; q.push(startNode); hasVisited[startPt] = true; while (!q.empty()) { Node cntNode = q.front(); q.pop(); if (cntNode.pt == endPt) return cntNode.step; for (int i = -1; i < 2; i += 2) { Node nextNode; nextNode.pt = cntNode.pt + arr[cntNode.pt] * i; nextNode.step = cntNode.step + 1; if (nextNode.pt < 0 || nextNode.pt >= floorNum || hasVisited[nextNode.pt]) continue; hasVisited[nextNode.pt] = true; q.push(nextNode); } } return -1; } int main() { ios::sync_with_stdio(false); while (cin >> floorNum) { if (floorNum == 0) break; int startPt, endPt; cin >> startPt >> endPt; startPt--; endPt--; for (int i = 0; i < floorNum; i++) { cin >> arr[i]; } int ans = bfs(startPt, endPt); cout << ans << endl; } return 0; }
18.597701
86
0.537701
[ "vector" ]
0f456aaaa503dd6a5f596ac85555b82f1e5599fd
30,488
cpp
C++
src/third_party/mozjs/extract/js/src/wasm/WasmCompile.cpp
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
src/third_party/mozjs/extract/js/src/wasm/WasmCompile.cpp
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
src/third_party/mozjs/extract/js/src/wasm/WasmCompile.cpp
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- * vim: set ts=8 sts=2 et sw=2 tw=80: * * Copyright 2015 Mozilla Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "wasm/WasmCompile.h" #include "mozilla/Maybe.h" #include <algorithm> #ifndef __wasi__ # include "jit/ProcessExecutableMemory.h" #endif #include "util/Text.h" #include "vm/HelperThreads.h" #include "vm/Realm.h" #include "wasm/WasmBaselineCompile.h" #include "wasm/WasmCraneliftCompile.h" #include "wasm/WasmGenerator.h" #include "wasm/WasmIonCompile.h" #include "wasm/WasmOpIter.h" #include "wasm/WasmProcess.h" #include "wasm/WasmSignalHandlers.h" #include "wasm/WasmValidate.h" using namespace js; using namespace js::jit; using namespace js::wasm; uint32_t wasm::ObservedCPUFeatures() { enum Arch { X86 = 0x1, X64 = 0x2, ARM = 0x3, MIPS = 0x4, MIPS64 = 0x5, ARM64 = 0x6, ARCH_BITS = 3 }; #if defined(JS_CODEGEN_X86) MOZ_ASSERT(uint32_t(jit::CPUInfo::GetSSEVersion()) <= (UINT32_MAX >> ARCH_BITS)); return X86 | (uint32_t(jit::CPUInfo::GetSSEVersion()) << ARCH_BITS); #elif defined(JS_CODEGEN_X64) MOZ_ASSERT(uint32_t(jit::CPUInfo::GetSSEVersion()) <= (UINT32_MAX >> ARCH_BITS)); return X64 | (uint32_t(jit::CPUInfo::GetSSEVersion()) << ARCH_BITS); #elif defined(JS_CODEGEN_ARM) MOZ_ASSERT(jit::GetARMFlags() <= (UINT32_MAX >> ARCH_BITS)); return ARM | (jit::GetARMFlags() << ARCH_BITS); #elif defined(JS_CODEGEN_ARM64) MOZ_ASSERT(jit::GetARM64Flags() <= (UINT32_MAX >> ARCH_BITS)); return ARM64 | (jit::GetARM64Flags() << ARCH_BITS); #elif defined(JS_CODEGEN_MIPS32) MOZ_ASSERT(jit::GetMIPSFlags() <= (UINT32_MAX >> ARCH_BITS)); return MIPS | (jit::GetMIPSFlags() << ARCH_BITS); #elif defined(JS_CODEGEN_MIPS64) MOZ_ASSERT(jit::GetMIPSFlags() <= (UINT32_MAX >> ARCH_BITS)); return MIPS64 | (jit::GetMIPSFlags() << ARCH_BITS); #elif defined(JS_CODEGEN_NONE) return 0; #else # error "unknown architecture" #endif } FeatureArgs FeatureArgs::build(JSContext* cx, const FeatureOptions& options) { FeatureArgs features; #define WASM_FEATURE(NAME, LOWER_NAME, ...) \ features.LOWER_NAME = wasm::NAME##Available(cx); JS_FOR_WASM_FEATURES(WASM_FEATURE, WASM_FEATURE); #undef WASM_FEATURE features.sharedMemory = wasm::ThreadsAvailable(cx) ? Shareable::True : Shareable::False; features.hugeMemory = wasm::IsHugeMemoryEnabled(); // See comments in WasmConstants.h regarding the meaning of the wormhole // options. bool wormholeOverride = wasm::SimdWormholeAvailable(cx) && options.simdWormhole; features.simdWormhole = wormholeOverride; if (wormholeOverride) { features.v128 = true; } return features; } SharedCompileArgs CompileArgs::build(JSContext* cx, ScriptedCaller&& scriptedCaller, const FeatureOptions& options) { bool baseline = BaselineAvailable(cx); bool ion = IonAvailable(cx); bool cranelift = CraneliftAvailable(cx); // At most one optimizing compiler. MOZ_RELEASE_ASSERT(!(ion && cranelift)); // Debug information such as source view or debug traps will require // additional memory and permanently stay in baseline code, so we try to // only enable it when a developer actually cares: when the debugger tab // is open. bool debug = cx->realm() && cx->realm()->debuggerObservesAsmJS(); bool forceTiering = cx->options().testWasmAwaitTier2() || JitOptions.wasmDelayTier2; // The <Compiler>Available() predicates should ensure no failure here, but // when we're fuzzing we allow inconsistent switches and the check may thus // fail. Let it go to a run-time error instead of crashing. if (debug && (ion || cranelift)) { JS_ReportErrorASCII(cx, "no WebAssembly compiler available"); return nullptr; } if (forceTiering && !(baseline && (cranelift || ion))) { // This can happen only in testing, and in this case we don't have a // proper way to signal the error, so just silently override the default, // instead of adding a skip-if directive to every test using debug/gc. forceTiering = false; } if (!(baseline || ion || cranelift)) { JS_ReportErrorASCII(cx, "no WebAssembly compiler available"); return nullptr; } CompileArgs* target = cx->new_<CompileArgs>(std::move(scriptedCaller)); if (!target) { return nullptr; } target->baselineEnabled = baseline; target->ionEnabled = ion; target->craneliftEnabled = cranelift; target->debugEnabled = debug; target->forceTiering = forceTiering; target->features = FeatureArgs::build(cx, options); Log(cx, "available wasm compilers: tier1=%s tier2=%s", baseline ? "baseline" : "none", ion ? "ion" : (cranelift ? "cranelift" : "none")); return target; } /* * [SMDOC] Tiered wasm compilation. * * "Tiered compilation" refers to the mechanism where we first compile the code * with a fast non-optimizing compiler so that we can start running the code * quickly, while in the background recompiling the code with the slower * optimizing compiler. Code created by baseline is called "tier-1"; code * created by the optimizing compiler is called "tier-2". When the tier-2 code * is ready, we "tier up" the code by creating paths from tier-1 code into their * tier-2 counterparts; this patching is performed as the program is running. * * ## Selecting the compilation mode * * When wasm bytecode arrives, we choose the compilation strategy based on * switches and on aspects of the code and the hardware. If switches allow * tiered compilation to happen (the normal case), the following logic applies. * * If the code is sufficiently large that tiered compilation would be beneficial * but not so large that it might blow our compiled code budget and make * compilation fail, we choose tiered compilation. Otherwise we go straight to * optimized code. * * The expected benefit of tiering is computed by TieringBeneficial(), below, * based on various estimated parameters of the hardware: ratios of object code * to byte code, speed of the system, number of cores. * * ## Mechanics of tiering up; patching * * Every time control enters a tier-1 function, the function prologue loads its * tiering pointer from the tiering jump table (see JumpTable in WasmCode.h) and * jumps to it. * * Initially, an entry in the tiering table points to the instruction inside the * tier-1 function that follows the jump instruction (hence the jump is an * expensive nop). When the tier-2 compiler is finished, the table is patched * racily to point into the tier-2 function at the correct prologue location * (see loop near the end of Module::finishTier2()). As tier-2 compilation is * performed at most once per Module, there is at most one such racy overwrite * per table element during the lifetime of the Module. * * The effect of the patching is to cause the tier-1 function to jump to its * tier-2 counterpart whenever the tier-1 function is called subsequently. That * is, tier-1 code performs standard frame setup on behalf of whatever code it * jumps to, and the target code (tier-1 or tier-2) allocates its own frame in * whatever way it wants. * * The racy writing means that it is often nondeterministic whether tier-1 or * tier-2 code is reached by any call during the tiering-up process; if F calls * A and B in that order, it may reach tier-2 code for A and tier-1 code for B. * If F is running concurrently on threads T1 and T2, T1 and T2 may see code * from different tiers for either function. * * Note, tiering up also requires upgrading the jit-entry stubs so that they * reference tier-2 code. The mechanics of this upgrading are described at * WasmInstanceObject::getExportedFunction(). * * ## Current limitations of tiering * * Tiering is not always seamless. Partly, it is possible for a program to get * stuck in tier-1 code. Partly, a function that has tiered up continues to * force execution to go via tier-1 code to reach tier-2 code, paying for an * additional jump and a slightly less optimized prologue than tier-2 code could * have had on its own. * * Known tiering limitiations: * * - We can tier up only at function boundaries. If a tier-1 function has a * long-running loop it will not tier up until it returns to its caller. If * this loop never exits (a runloop in a worker, for example) then the * function will never tier up. * * To do better, we need OSR. * * - Wasm Table entries are never patched during tier-up. A Table of funcref * holds not a JSFunction pointer, but a (code*,Tls*) pair of pointers. When * a table.set operation is performed, the JSFunction value is decomposed and * its code and Tls pointers are stored in the table; subsequently, when a * table.get operation is performed, the JSFunction value is reconstituted * from its code pointer using fairly elaborate machinery. (The mechanics are * the same also for the reflected JS operations on a WebAssembly.Table. For * everything, see WasmTable.{cpp,h}.) The code pointer in the Table will * always be the code pointer belonging to the best tier that was active at * the time when that function was stored in that Table slot; in many cases, * it will be tier-1 code. As a consequence, a call through a table will * first enter tier-1 code and then jump to tier-2 code. * * To do better, we must update all the tables in the system when an instance * tiers up. This is expected to be very hard. * * - Imported Wasm functions are never patched during tier-up. Imports are held * in FuncImportTls values in the instance's Tls, and for a wasm callee, * what's stored is the raw code pointer into the best tier of the callee that * was active at the time the import was resolved. That could be baseline * code, and if it is, the situation is as for Table entries: a call to an * import will always go via that import's tier-1 code, which will tier up * with an indirect jump. * * To do better, we must update all the import tables in the system that * import functions from instances whose modules have tiered up. This is * expected to be hard. */ // Classify the current system as one of a set of recognizable classes. This // really needs to get our tier-1 systems right. // // TODO: We don't yet have a good measure of how fast a system is. We // distinguish between mobile and desktop because these are very different kinds // of systems, but we could further distinguish between low / medium / high end // within those major classes. If we do so, then constants below would be // provided for each (class, architecture, system-tier) combination, not just // (class, architecture) as now. // // CPU clock speed is not by itself a good predictor of system performance, as // there are high-performance systems with slow clocks (recent Intel) and // low-performance systems with fast clocks (older AMD). We can also use // physical memory, core configuration, OS details, CPU class and family, and // CPU manufacturer to disambiguate. enum class SystemClass { DesktopX86, DesktopX64, DesktopUnknown32, DesktopUnknown64, MobileX86, MobileArm32, MobileArm64, MobileUnknown32, MobileUnknown64 }; static SystemClass ClassifySystem() { bool isDesktop; #if defined(ANDROID) || defined(JS_CODEGEN_ARM) || defined(JS_CODEGEN_ARM64) isDesktop = false; #else isDesktop = true; #endif if (isDesktop) { #if defined(JS_CODEGEN_X64) return SystemClass::DesktopX64; #elif defined(JS_CODEGEN_X86) return SystemClass::DesktopX86; #elif defined(JS_64BIT) return SystemClass::DesktopUnknown64; #else return SystemClass::DesktopUnknown32; #endif } else { #if defined(JS_CODEGEN_X86) return SystemClass::MobileX86; #elif defined(JS_CODEGEN_ARM) return SystemClass::MobileArm32; #elif defined(JS_CODEGEN_ARM64) return SystemClass::MobileArm64; #elif defined(JS_64BIT) return SystemClass::MobileUnknown64; #else return SystemClass::MobileUnknown32; #endif } } // Code sizes in machine code bytes per bytecode byte, again empirical except // where marked. // // The Ion estimate for ARM64 is the measured Baseline value scaled by a // plausible factor for optimized code. static const double x64Tox86Inflation = 1.25; static const double x64IonBytesPerBytecode = 2.45; static const double x86IonBytesPerBytecode = x64IonBytesPerBytecode * x64Tox86Inflation; static const double arm32IonBytesPerBytecode = 3.3; static const double arm64IonBytesPerBytecode = 3.0 / 1.4; // Estimate static const double x64BaselineBytesPerBytecode = x64IonBytesPerBytecode * 1.43; static const double x86BaselineBytesPerBytecode = x64BaselineBytesPerBytecode * x64Tox86Inflation; static const double arm32BaselineBytesPerBytecode = arm32IonBytesPerBytecode * 1.39; static const double arm64BaselineBytesPerBytecode = 3.0; static double OptimizedBytesPerBytecode(SystemClass cls) { switch (cls) { case SystemClass::DesktopX86: case SystemClass::MobileX86: case SystemClass::DesktopUnknown32: return x86IonBytesPerBytecode; case SystemClass::DesktopX64: case SystemClass::DesktopUnknown64: return x64IonBytesPerBytecode; case SystemClass::MobileArm32: case SystemClass::MobileUnknown32: return arm32IonBytesPerBytecode; case SystemClass::MobileArm64: case SystemClass::MobileUnknown64: return arm64IonBytesPerBytecode; default: MOZ_CRASH(); } } static double BaselineBytesPerBytecode(SystemClass cls) { switch (cls) { case SystemClass::DesktopX86: case SystemClass::MobileX86: case SystemClass::DesktopUnknown32: return x86BaselineBytesPerBytecode; case SystemClass::DesktopX64: case SystemClass::DesktopUnknown64: return x64BaselineBytesPerBytecode; case SystemClass::MobileArm32: case SystemClass::MobileUnknown32: return arm32BaselineBytesPerBytecode; case SystemClass::MobileArm64: case SystemClass::MobileUnknown64: return arm64BaselineBytesPerBytecode; default: MOZ_CRASH(); } } double wasm::EstimateCompiledCodeSize(Tier tier, size_t bytecodeSize) { SystemClass cls = ClassifySystem(); switch (tier) { case Tier::Baseline: return double(bytecodeSize) * BaselineBytesPerBytecode(cls); case Tier::Optimized: return double(bytecodeSize) * OptimizedBytesPerBytecode(cls); } MOZ_CRASH("bad tier"); } // If parallel Ion compilation is going to take longer than this, we should // tier. static const double tierCutoffMs = 10; // Compilation rate values are empirical except when noted, the reference // systems are: // // Late-2013 MacBook Pro (2.6GHz 4 x hyperthreaded Haswell, Mac OS X) // Late-2015 Nexus 5X (1.4GHz 4 x Cortex-A53 + 1.8GHz 2 x Cortex-A57, Android) // Ca-2016 SoftIron Overdrive 1000 (1.7GHz 4 x Cortex-A57, Fedora) // // The rates are always per core. // // The estimate for ARM64 is the Baseline compilation rate on the SoftIron // (because we have no Ion yet), divided by 5 to estimate Ion compile rate and // then divided by 2 to make it more reasonable for consumer ARM64 systems. static const double x64IonBytecodesPerMs = 2100; static const double x86IonBytecodesPerMs = 1500; static const double arm32IonBytecodesPerMs = 450; static const double arm64IonBytecodesPerMs = 750; // Estimate // Tiering cutoff values: if code section sizes are below these values (when // divided by the effective number of cores) we do not tier, because we guess // that parallel Ion compilation will be fast enough. static const double x64DesktopTierCutoff = x64IonBytecodesPerMs * tierCutoffMs; static const double x86DesktopTierCutoff = x86IonBytecodesPerMs * tierCutoffMs; static const double x86MobileTierCutoff = x86DesktopTierCutoff / 2; // Guess static const double arm32MobileTierCutoff = arm32IonBytecodesPerMs * tierCutoffMs; static const double arm64MobileTierCutoff = arm64IonBytecodesPerMs * tierCutoffMs; static double CodesizeCutoff(SystemClass cls) { switch (cls) { case SystemClass::DesktopX86: case SystemClass::DesktopUnknown32: return x86DesktopTierCutoff; case SystemClass::DesktopX64: case SystemClass::DesktopUnknown64: return x64DesktopTierCutoff; case SystemClass::MobileX86: return x86MobileTierCutoff; case SystemClass::MobileArm32: case SystemClass::MobileUnknown32: return arm32MobileTierCutoff; case SystemClass::MobileArm64: case SystemClass::MobileUnknown64: return arm64MobileTierCutoff; default: MOZ_CRASH(); } } // As the number of cores grows the effectiveness of each core dwindles (on the // systems we care about for SpiderMonkey). // // The data are empirical, computed from the observed compilation time of the // Tanks demo code on a variable number of cores. // // The heuristic may fail on NUMA systems where the core count is high but the // performance increase is nil or negative once the program moves beyond one // socket. However, few browser users have such systems. static double EffectiveCores(uint32_t cores) { if (cores <= 3) { return pow(cores, 0.9); } return pow(cores, 0.75); } #ifndef JS_64BIT // Don't tier if tiering will fill code memory to more to more than this // fraction. static const double spaceCutoffPct = 0.9; #endif // Figure out whether we should use tiered compilation or not. static bool TieringBeneficial(uint32_t codeSize) { uint32_t cpuCount = GetHelperThreadCPUCount(); MOZ_ASSERT(cpuCount > 0); // It's mostly sensible not to background compile when there's only one // hardware thread as we want foreground computation to have access to that. // However, if wasm background compilation helper threads can be given lower // priority then background compilation on single-core systems still makes // some kind of sense. That said, this is a non-issue: as of September 2017 // 1-core was down to 3.5% of our population and falling. if (cpuCount == 1) { return false; } // Compute the max number of threads available to do actual background // compilation work. uint32_t workers = GetMaxWasmCompilationThreads(); // The number of cores we will use is bounded both by the CPU count and the // worker count, since the worker count already takes this into account. uint32_t cores = workers; SystemClass cls = ClassifySystem(); // Ion compilation on available cores must take long enough to be worth the // bother. double cutoffSize = CodesizeCutoff(cls); double effectiveCores = EffectiveCores(cores); if ((codeSize / effectiveCores) < cutoffSize) { return false; } // Do not implement a size cutoff for 64-bit systems since the code size // budget for 64 bit is so large that it will hardly ever be an issue. // (Also the cutoff percentage might be different on 64-bit.) #ifndef JS_64BIT // If the amount of executable code for baseline compilation jeopardizes the // availability of executable memory for ion code then do not tier, for now. // // TODO: For now we consider this module in isolation. We should really // worry about what else is going on in this process and might be filling up // the code memory. It's like we need some kind of code memory reservation // system or JIT compilation for large modules. double ionRatio = OptimizedBytesPerBytecode(cls); double baselineRatio = BaselineBytesPerBytecode(cls); double needMemory = codeSize * (ionRatio + baselineRatio); double availMemory = LikelyAvailableExecutableMemory(); double cutoff = spaceCutoffPct * MaxCodeBytesPerProcess; // If the sum of baseline and ion code makes us exceeds some set percentage // of the executable memory then disable tiering. if ((MaxCodeBytesPerProcess - availMemory) + needMemory > cutoff) { return false; } #endif return true; } CompilerEnvironment::CompilerEnvironment(const CompileArgs& args) : state_(InitialWithArgs), args_(&args) {} CompilerEnvironment::CompilerEnvironment(CompileMode mode, Tier tier, OptimizedBackend optimizedBackend, DebugEnabled debugEnabled) : state_(InitialWithModeTierDebug), mode_(mode), tier_(tier), optimizedBackend_(optimizedBackend), debug_(debugEnabled) {} void CompilerEnvironment::computeParameters() { MOZ_ASSERT(state_ == InitialWithModeTierDebug); state_ = Computed; } // Check that this architecture either: // - is cache-coherent, which is the case for most tier-1 architectures we care // about. // - or has the ability to invalidate the instruction cache of all threads, so // background compilation in tiered compilation can be synchronized across all // threads. static bool IsICacheSafe() { #ifdef JS_CODEGEN_ARM64 return jit::CanFlushICacheFromBackgroundThreads(); #else return true; #endif } void CompilerEnvironment::computeParameters(Decoder& d) { MOZ_ASSERT(!isComputed()); if (state_ == InitialWithModeTierDebug) { computeParameters(); return; } bool baselineEnabled = args_->baselineEnabled; bool ionEnabled = args_->ionEnabled; bool debugEnabled = args_->debugEnabled; bool craneliftEnabled = args_->craneliftEnabled; bool forceTiering = args_->forceTiering; bool hasSecondTier = ionEnabled || craneliftEnabled; MOZ_ASSERT_IF(debugEnabled, baselineEnabled); MOZ_ASSERT_IF(forceTiering, baselineEnabled && hasSecondTier); // Various constraints in various places should prevent failure here. MOZ_RELEASE_ASSERT(baselineEnabled || ionEnabled || craneliftEnabled); MOZ_RELEASE_ASSERT(!(ionEnabled && craneliftEnabled)); uint32_t codeSectionSize = 0; SectionRange range; if (StartsCodeSection(d.begin(), d.end(), &range)) { codeSectionSize = range.size; } if (baselineEnabled && hasSecondTier && CanUseExtraThreads() && (TieringBeneficial(codeSectionSize) || forceTiering) && IsICacheSafe()) { mode_ = CompileMode::Tier1; tier_ = Tier::Baseline; } else { mode_ = CompileMode::Once; tier_ = hasSecondTier ? Tier::Optimized : Tier::Baseline; } optimizedBackend_ = craneliftEnabled ? OptimizedBackend::Cranelift : OptimizedBackend::Ion; debug_ = debugEnabled ? DebugEnabled::True : DebugEnabled::False; state_ = Computed; } template <class DecoderT> static bool DecodeFunctionBody(DecoderT& d, ModuleGenerator& mg, uint32_t funcIndex) { uint32_t bodySize; if (!d.readVarU32(&bodySize)) { return d.fail("expected number of function body bytes"); } if (bodySize > MaxFunctionBytes) { return d.fail("function body too big"); } const size_t offsetInModule = d.currentOffset(); // Skip over the function body; it will be validated by the compilation // thread. const uint8_t* bodyBegin; if (!d.readBytes(bodySize, &bodyBegin)) { return d.fail("function body length too big"); } return mg.compileFuncDef(funcIndex, offsetInModule, bodyBegin, bodyBegin + bodySize); } template <class DecoderT> static bool DecodeCodeSection(const ModuleEnvironment& env, DecoderT& d, ModuleGenerator& mg) { if (!env.codeSection) { if (env.numFuncDefs() != 0) { return d.fail("expected code section"); } return mg.finishFuncDefs(); } uint32_t numFuncDefs; if (!d.readVarU32(&numFuncDefs)) { return d.fail("expected function body count"); } if (numFuncDefs != env.numFuncDefs()) { return d.fail( "function body count does not match function signature count"); } for (uint32_t funcDefIndex = 0; funcDefIndex < numFuncDefs; funcDefIndex++) { if (!DecodeFunctionBody(d, mg, env.numFuncImports() + funcDefIndex)) { return false; } } if (!d.finishSection(*env.codeSection, "code")) { return false; } return mg.finishFuncDefs(); } SharedModule wasm::CompileBuffer(const CompileArgs& args, const ShareableBytes& bytecode, UniqueChars* error, UniqueCharsVector* warnings, JS::OptimizedEncodingListener* listener) { Decoder d(bytecode.bytes, 0, error, warnings); ModuleEnvironment moduleEnv(args.features); if (!DecodeModuleEnvironment(d, &moduleEnv)) { return nullptr; } CompilerEnvironment compilerEnv(args); compilerEnv.computeParameters(d); ModuleGenerator mg(args, &moduleEnv, &compilerEnv, nullptr, error); if (!mg.init(nullptr)) { return nullptr; } if (!DecodeCodeSection(moduleEnv, d, mg)) { return nullptr; } if (!DecodeModuleTail(d, &moduleEnv)) { return nullptr; } return mg.finishModule(bytecode, listener); } void wasm::CompileTier2(const CompileArgs& args, const Bytes& bytecode, const Module& module, Atomic<bool>* cancelled) { UniqueChars error; Decoder d(bytecode, 0, &error); OptimizedBackend optimizedBackend = args.craneliftEnabled ? OptimizedBackend::Cranelift : OptimizedBackend::Ion; ModuleEnvironment moduleEnv(args.features); if (!DecodeModuleEnvironment(d, &moduleEnv)) { return; } CompilerEnvironment compilerEnv(CompileMode::Tier2, Tier::Optimized, optimizedBackend, DebugEnabled::False); compilerEnv.computeParameters(d); ModuleGenerator mg(args, &moduleEnv, &compilerEnv, cancelled, &error); if (!mg.init(nullptr)) { return; } if (!DecodeCodeSection(moduleEnv, d, mg)) { return; } if (!DecodeModuleTail(d, &moduleEnv)) { return; } if (!mg.finishTier2(module)) { return; } // The caller doesn't care about success or failure; only that compilation // is inactive, so there is no success to return here. } class StreamingDecoder { Decoder d_; const ExclusiveBytesPtr& codeBytesEnd_; const Atomic<bool>& cancelled_; public: StreamingDecoder(const ModuleEnvironment& env, const Bytes& begin, const ExclusiveBytesPtr& codeBytesEnd, const Atomic<bool>& cancelled, UniqueChars* error, UniqueCharsVector* warnings) : d_(begin, env.codeSection->start, error, warnings), codeBytesEnd_(codeBytesEnd), cancelled_(cancelled) {} bool fail(const char* msg) { return d_.fail(msg); } bool done() const { return d_.done(); } size_t currentOffset() const { return d_.currentOffset(); } bool waitForBytes(size_t numBytes) { numBytes = std::min(numBytes, d_.bytesRemain()); const uint8_t* requiredEnd = d_.currentPosition() + numBytes; auto codeBytesEnd = codeBytesEnd_.lock(); while (codeBytesEnd < requiredEnd) { if (cancelled_) { return false; } codeBytesEnd.wait(); } return true; } bool readVarU32(uint32_t* u32) { return waitForBytes(MaxVarU32DecodedBytes) && d_.readVarU32(u32); } bool readBytes(size_t size, const uint8_t** begin) { return waitForBytes(size) && d_.readBytes(size, begin); } bool finishSection(const SectionRange& range, const char* name) { return d_.finishSection(range, name); } }; static SharedBytes CreateBytecode(const Bytes& env, const Bytes& code, const Bytes& tail, UniqueChars* error) { size_t size = env.length() + code.length() + tail.length(); if (size > MaxModuleBytes) { *error = DuplicateString("module too big"); return nullptr; } MutableBytes bytecode = js_new<ShareableBytes>(); if (!bytecode || !bytecode->bytes.resize(size)) { return nullptr; } uint8_t* p = bytecode->bytes.begin(); memcpy(p, env.begin(), env.length()); p += env.length(); memcpy(p, code.begin(), code.length()); p += code.length(); memcpy(p, tail.begin(), tail.length()); p += tail.length(); MOZ_ASSERT(p == bytecode->end()); return bytecode; } SharedModule wasm::CompileStreaming( const CompileArgs& args, const Bytes& envBytes, const Bytes& codeBytes, const ExclusiveBytesPtr& codeBytesEnd, const ExclusiveStreamEndData& exclusiveStreamEnd, const Atomic<bool>& cancelled, UniqueChars* error, UniqueCharsVector* warnings) { CompilerEnvironment compilerEnv(args); ModuleEnvironment moduleEnv(args.features); { Decoder d(envBytes, 0, error, warnings); if (!DecodeModuleEnvironment(d, &moduleEnv)) { return nullptr; } compilerEnv.computeParameters(d); if (!moduleEnv.codeSection) { d.fail("unknown section before code section"); return nullptr; } MOZ_RELEASE_ASSERT(moduleEnv.codeSection->size == codeBytes.length()); MOZ_RELEASE_ASSERT(d.done()); } ModuleGenerator mg(args, &moduleEnv, &compilerEnv, &cancelled, error); if (!mg.init(nullptr)) { return nullptr; } { StreamingDecoder d(moduleEnv, codeBytes, codeBytesEnd, cancelled, error, warnings); if (!DecodeCodeSection(moduleEnv, d, mg)) { return nullptr; } MOZ_RELEASE_ASSERT(d.done()); } { auto streamEnd = exclusiveStreamEnd.lock(); while (!streamEnd->reached) { if (cancelled) { return nullptr; } streamEnd.wait(); } } const StreamEndData& streamEnd = exclusiveStreamEnd.lock(); const Bytes& tailBytes = *streamEnd.tailBytes; { Decoder d(tailBytes, moduleEnv.codeSection->end(), error, warnings); if (!DecodeModuleTail(d, &moduleEnv)) { return nullptr; } MOZ_RELEASE_ASSERT(d.done()); } SharedBytes bytecode = CreateBytecode(envBytes, codeBytes, tailBytes, error); if (!bytecode) { return nullptr; } return mg.finishModule(*bytecode, streamEnd.tier2Listener); }
33.837958
80
0.711788
[ "object" ]
0f465bc7880ad713377ad6a4a1e313f5433f6aa9
3,850
cpp
C++
src/wow64_process.cpp
updawg/D2RMH
9e667513614150af736c4342b650a89dd632d99c
[ "MIT" ]
null
null
null
src/wow64_process.cpp
updawg/D2RMH
9e667513614150af736c4342b650a89dd632d99c
[ "MIT" ]
null
null
null
src/wow64_process.cpp
updawg/D2RMH
9e667513614150af736c4342b650a89dd632d99c
[ "MIT" ]
null
null
null
/* * Copyright (c) 2021 Soar Qin<soarchin@gmail.com> * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ #include "wow64_process.h" #include "os_structs.h" #ifdef _MSC_VER #pragma comment(linker, "/alternatename:__imp__NtWow64QueryInformationProcess64@20=__imp__NtWow64QueryInformationProcess64") #pragma comment(linker, "/alternatename:__imp__NtWow64ReadVirtualMemory64@28=__imp__NtWow64ReadVirtualMemory64") #endif #include <vector> #include <cstdint> #include <stdexcept> #ifndef _M_IX86 # error "This application must be built as an x86 executable" #endif #define IS_TRUE(clause, msg) if (!(clause)) { throw std::runtime_error(msg); } void checkIfProcessIsX64(HANDLE handle) { BOOL is_wow64_process = TRUE; IS_TRUE(::IsWow64Process(handle, &is_wow64_process), "IsWow64Process failed"); IS_TRUE(FALSE == is_wow64_process, "Target process is not x64 one"); } uint32_t readMemory64(HANDLE handle, uint64_t address, uint32_t length, void *data) { IS_TRUE(handle, "No process handle obtained"); NTSTATUS status = NtWow64ReadVirtualMemory64(handle, address, data, length, FALSE); if(!NT_SUCCESS(status)) { return 0; } return length; } void readPBI(HANDLE handle, sys::PROCESS_BASIC_INFORMATION64 &pbi) { IS_TRUE(handle, "No process handle obtained"); NTSTATUS status = NtWow64QueryInformationProcess64(handle, sys::ProcessBasicInformation, &pbi, sizeof(pbi), NULL); IS_TRUE(NT_SUCCESS(status), "NtQueryInformationProcess failed"); } uint32_t readPEBData(HANDLE handle, sys::PEB64 *peb) { sys::PROCESS_BASIC_INFORMATION64 pbi = {0}; readPBI(handle, pbi); return readMemory64(handle, pbi.PebBaseAddress, sizeof(sys::PEB64), peb); } bool getModulesViaPEB(HANDLE handle, const std::function<bool(uint64_t, uint64_t, const wchar_t*)> &cb) { sys::PEB64 peb; readPEBData(handle, &peb); // ------------------------------------------------------------------------ // Read memory from pointer to loader data structures. // ------------------------------------------------------------------------ std::vector<uint8_t> read_peb_ldr_data(sizeof(sys::PEB_LDR_DATA64)); readMemory64(handle, (uint64_t)peb.LoaderData, sizeof(sys::PEB_LDR_DATA64), read_peb_ldr_data.data()); sys::PEB_LDR_DATA64 *peb_ldr_data = (sys::PEB_LDR_DATA64 *)read_peb_ldr_data.data(); sys::PEB_LDR_DATA64 *loader_data = (sys::PEB_LDR_DATA64 *)peb.LoaderData; ULONGLONG address = peb_ldr_data->InLoadOrderModuleList.Flink; uint32_t counter = 1; // ------------------------------------------------------------------------ // Traversing loader data structures. // ------------------------------------------------------------------------ for (;;) { std::vector<uint8_t> read_ldr_table_entry(sizeof(sys::LDR_DATA_TABLE_ENTRY64)); readMemory64(handle, address, sizeof(sys::LDR_DATA_TABLE_ENTRY64), read_ldr_table_entry.data()); sys::LDR_DATA_TABLE_ENTRY64 *ldr_table_entry = (sys::LDR_DATA_TABLE_ENTRY64 *)read_ldr_table_entry.data(); if (!ldr_table_entry->BaseAddress) { break; } std::vector<uint8_t> unicode_name(ldr_table_entry->BaseDllName.MaximumLength); readMemory64(handle, ldr_table_entry->BaseDllName.Buffer, ldr_table_entry->BaseDllName.MaximumLength, unicode_name.data()); if (!cb(ldr_table_entry->BaseAddress, ldr_table_entry->SizeOfImage, (const wchar_t*)unicode_name.data())) { break; } ldr_table_entry = (sys::LDR_DATA_TABLE_ENTRY64 *)read_ldr_table_entry.data(); address = (uint64_t)ldr_table_entry->InLoadOrderModuleList.Flink; } return true; }
37.745098
124
0.658961
[ "vector" ]
0f477d61450951138659818700135b5c80e39dae
23,972
cpp
C++
main.cpp
AdamWSL/welding_robot
db65bc9ce5e667875dd82d1a16037383f581cada
[ "MIT" ]
5
2021-05-08T09:02:37.000Z
2021-12-26T03:27:57.000Z
main.cpp
AdamWSL/welding_robot
db65bc9ce5e667875dd82d1a16037383f581cada
[ "MIT" ]
null
null
null
main.cpp
AdamWSL/welding_robot
db65bc9ce5e667875dd82d1a16037383f581cada
[ "MIT" ]
1
2021-08-14T04:09:11.000Z
2021-08-14T04:09:11.000Z
/* Includes ------------------------------------------------------------------*/ #include "matplotlibcpp.h" #include <iostream> #include "coppeliaSim.h" #include "sys_log.h" #include "core/BsplineBasic.h" #include "core/BezierCurve.h" #include "core/Timer.h" #include "core/ACSRank_3D.hpp" #include "core/read_STL.hpp" #include "core/ACS_GTSP.hpp" /* Usr defines ---------------------------------------------------------------*/ using namespace std; namespace plt = matplotlibcpp; enum Pose_t { x, y, z, alpha, beta, gamma }; _simObjectHandle_Type *Tip_target; _simObjectHandle_Type *Tip_op; _simObjectHandle_Type *Joint[6]; _simObjectHandle_Type *platform[2]; _simSignalHandle_Type *weld_cmd; /*Test*/ STLReader model; ACS_Rank SearchPath; ACS_GTSP GlobalRoute; BezierCurve<float, 3> straight_line(2); BezierCurve<float, 2> platform_angle(2); BS_Basic<float, 3, 0, 0, 0> *smooth_curve1; Timer timer; int demo_type; bool is_running = false; float start_time = 0; float total_time = 0; float current_pt[6]; float target_pt[6]; std::vector<float> smooth_x, smooth_y, smooth_z; /* Founctions ----------------------------------------------------------------*/ // float[6], float[3] bool go_next_point(float *next, float *res) { static float last[6] = {0}; bool state = false; for (int i(0); i < 6; i++) { state |= (next[i] != last[i]) ? 1 : 0; } if(state){ float start_pt[3] = {current_pt[0], current_pt[1], current_pt[2]}; float next_pt[3] = {next[0], next[1], next[2]}; float **ctrl_pt = new float *[3]; ctrl_pt[0] = start_pt; ctrl_pt[1] = next_pt; straight_line.SetParam(ctrl_pt, total_time); start_time = timer.getMs(); for (int i(0); i < 6; i++) { last[i] = next[i]; } } float now_time = (float)timer.getMs() - start_time; if (now_time >= total_time) return false; else { straight_line.getCurvePoint(now_time, res); printf("This point: %.3f, %.3f, %.3f \n", res[0], res[1], res[2]); return true; } } void manual_input() { if (is_running == true) { if (demo_type == 1) { // exit: current time > move time ? float now_time = (float)timer.getMs() - start_time; if (now_time >= total_time) is_running = false; float res[3] = {}; straight_line.getCurvePoint(now_time, res); target_pt[0] = res[0]; target_pt[1] = res[1]; target_pt[2] = res[2]; cout << "Target(x,y,z):" << target_pt[0] << ", " << target_pt[1] << ", " << target_pt[2] << endl; } else if (demo_type == 2) { // exit: current time > move time ? float now_time = (float)timer.getMs() - start_time; if (now_time >= total_time) is_running = false; float res[2]; platform_angle.getCurvePoint(now_time, res); platform[0]->obj_Target.angle_f = res[0]; platform[1]->obj_Target.angle_f = res[1]; cout << "Target(pitch, yaw):" << res[0] << ", " << res[1] << endl; } else { static int i = 0; if(i < smooth_x.size()) { static clock_t lastTime = clock(); if (clock() - lastTime >= 10) { lastTime = clock(); if(smooth_x[i] - target_pt[0] < 0.3 && smooth_y[i] - target_pt[1] < 0.3 && smooth_z[i] - target_pt[2] < 0.3) target_pt[0] = smooth_x[i]; target_pt[1] = smooth_y[i]; target_pt[2] = smooth_z[i]; cout << "Target(x,y,z):" << target_pt[0] << ", " << target_pt[1] << ", " << target_pt[2] << endl; i++; } } else { is_running = false; } // // 论文和答辩中简单的演示,简单的状态机 // static int stage = 0; // switch(stage) // { // case 0: // { // //到第一个点 // total_time = 3000; // float next[3] = {SearchPath.route_points[0].x, SearchPath.route_points[0].y, SearchPath.route_points[0].z}; // if(go_next_point(next,res)) // { // // target_pt[0] = res[0]; // // target_pt[1] = res[1]; // // target_pt[2] = res[2]; // } // else // { // start_time = timer.getMs(); // stage = 1; // } // } // break; // case 1: // { // //开始焊接,到第二个点 // weld_cmd->target = 1; // float next[3] = {SearchPath.route_points[1].x, SearchPath.route_points[1].y, SearchPath.route_points[1].z}; // if(go_next_point(next,res)) // { // // target_pt[0] = res[0]; // // target_pt[1] = res[1]; // // target_pt[2] = res[2]; // } // else{ // const std::vector<ACS_Node<float> *> *path = SearchPath.best_matrix[1][2].getPath(); // int pt_num = (*path).size(); // float start_pt[3] = {SearchPath.route_points[1].x, SearchPath.route_points[1].y, SearchPath.route_points[1].z}; // float end_pt[3] = {SearchPath.route_points[2].x, SearchPath.route_points[2].y, SearchPath.route_points[2].z}; // float **ctrl_pt = new float *[pt_num]; // for (int i = 0; i < pt_num; ++i) // { // ctrl_pt[i] = new float[3]; // ctrl_pt[i][0] = (*path)[i]->pt.x; // ctrl_pt[i][1] = (*path)[i]->pt.y; // ctrl_pt[i][2] = (*path)[i]->pt.z; // } // smooth_curve1 = new BS_Basic<float, 3, 0, 0, 0>(pt_num); // smooth_curve1->SetParam(start_pt, end_pt, ctrl_pt, total_time); // start_time = timer.getMs(); // weld_cmd->target = 0; // stage = 2; // } // } // break; // case 2: // { // //停止焊接,到下面焊路 // float now_time = (float)timer.getMs() - start_time; // if(now_time < total_time + 500) // { // smooth_curve1->getCurvePoint(now_time, res); // } // else // { // weld_cmd->target = 1; // stage = 3; // } // } // break; // case 3: // { // // 第二段焊路 // float next[3] = {SearchPath.route_points[3].x, SearchPath.route_points[3].y, SearchPath.route_points[3].z}; // if(go_next_point(next,res)) // { // } // else // { // while(1){} // } // } // break; // default: // break; // } // target_pt[0] = res[0]; // target_pt[1] = res[1]; // target_pt[2] = res[2]; // } } } else { //Select type cout << "Please choose control type: 1) Manipulator 2) Platform 3) Demo : "; cin >> demo_type; if (demo_type == 1) { //Set terminal points float start_pt[3] = {current_pt[0], current_pt[1], current_pt[2]}; float next_pt[3]; float **ctrl_pt = new float *[3]; ctrl_pt[0] = start_pt; ctrl_pt[1] = next_pt; cout << "Current point:(" << current_pt[0] << ", " << current_pt[1] << ", " << current_pt[2] << ")" << endl; cout << "Next point(x, y, z) and Time(t): "; cin >> next_pt[0] >> next_pt[1] >> next_pt[2] >> total_time; straight_line.SetParam(ctrl_pt, total_time); //Set time start_time = timer.getMs(); is_running = true; } else if (demo_type == 2) { //Set terminal points float start_pt[2] = {platform[0]->obj_Data.angle_f, platform[1]->obj_Data.angle_f}; float next_pt[2]; float **ctrl_pt = new float *[2]; ctrl_pt[0] = start_pt; ctrl_pt[1] = next_pt; cout << "Current point:(" << platform[0]->obj_Data.angle_f << ", " << platform[1]->obj_Data.angle_f << ")" << endl; cout << "Target angle(pitch, yaw) and Time(t): "; cin >> next_pt[0] >> next_pt[1] >> total_time; platform_angle.SetParam(ctrl_pt, total_time); //Set time start_time = timer.getMs(); is_running = true; } else if(demo_type == 3) { /* 读取工件模型 */ model.readFile("./files/cubic.stl"); const std::vector<Triangles<float>> meshes = model.TriangleList(); /* 搜索路径 */ SearchPath.creatGridMap(meshes, 0.005, 10,"./files/cubic_grid_map.in"); SearchPath.searchBestPathOfPoints(0.5, "./files/cubic_weld_points.in", "./files/graph.in"); GlobalRoute.readFromGraphFile("./files/graph.in"); GlobalRoute.computeSolution(); GlobalRoute.read_all_segments(SearchPath.best_matrix); /* 曲线平滑 */ int pt_num = GlobalRoute.g_path_x.size(); float start_pt[3] = {GlobalRoute.g_path_x[0], GlobalRoute.g_path_y[0], GlobalRoute.g_path_z[0]}; float end_pt[3] = {GlobalRoute.g_path_x[pt_num - 1], GlobalRoute.g_path_y[pt_num - 1], GlobalRoute.g_path_z[pt_num - 1]}; float **ctrl_pt = new float *[pt_num]; for (int i = 0; i < pt_num; ++i) { ctrl_pt[i] = new float[3]; ctrl_pt[i][0] = GlobalRoute.g_path_x[i]; ctrl_pt[i][1] = GlobalRoute.g_path_y[i]; ctrl_pt[i][2] = GlobalRoute.g_path_z[i]; } BS_Basic<float, 3, 0, 0, 0> smooth_curve(pt_num); smooth_curve.SetParam(start_pt, end_pt, ctrl_pt, 150); clock_t base_t = clock(); clock_t now_t = clock()-base_t; float res[3]; do { if(clock() - base_t - now_t >= 10) { now_t = clock() - base_t; smooth_curve.getCurvePoint(now_t, res); smooth_x.push_back(res[0]); smooth_y.push_back(res[1]); smooth_z.push_back(res[2]); //printf("Curve point: %f, %f, %f, time:%d \n", res[0], res[1], res[2], now_t); } } while (now_t <= 150); //二次平滑 const float constrain = 0.05; pt_num = smooth_y.size(); float second_start_pt[9] = {GlobalRoute.g_path_x[0], GlobalRoute.g_path_y[0], GlobalRoute.g_path_z[0],0,0,0,0,0,0}; float second_end_pt[9] = {GlobalRoute.g_path_x[pt_num - 1], GlobalRoute.g_path_y[pt_num - 1], GlobalRoute.g_path_z[pt_num - 1],0,0,0,0,0,0}; float **second_pt = new float*[pt_num]; for (int i = 0; i < pt_num; ++i) { second_pt[i] = new float[9]; second_pt[i][0] = smooth_x[i]; second_pt[i][1] = smooth_y[i]; second_pt[i][2] = smooth_z[i]; for (int j(3); j < 9; j++) second_pt[i][j] = constrain; } smooth_x.clear(); smooth_y.clear(); smooth_z.clear(); BS_Basic<float, 3, 2, 2, 2> second_curve(pt_num); second_curve.SetParam(second_start_pt,second_end_pt,second_pt, 6000); base_t = clock(); now_t = clock()-base_t; do { if(clock() - base_t - now_t >= 50) { now_t = clock() - base_t; second_curve.getCurvePoint(now_t, res); smooth_x.push_back(res[0]); smooth_y.push_back(res[1]); smooth_z.push_back(res[2]); //printf("Second point: %f, %f, %f, time:%d \n", res[0], res[1], res[2], now_t); } } while (now_t <= 6000); start_time = timer.getMs(); is_running = true; } else { cout << "Unidentified type, please select again." << endl; } } } /** * @brief This is the main function for user. */ void Usr_Main() { //这里是主循环,可以运行我们的各部分算法 manual_input(); } /** * @brief User can config simulation client in this function. * @note It will be called before entering the main loop. */ void Usr_ConfigSimulation() { //添加关节对象,每个关节可以读写位置和速度,不用单独控制每个关节可以注释下面这段 Joint[0] = CoppeliaSim->Add_Object("IRB4600_joint1", JOINT, {SIM_VELOCITY | CLIENT_RW, SIM_POSITION | CLIENT_RW}); Joint[1] = CoppeliaSim->Add_Object("IRB4600_joint2", JOINT, {SIM_VELOCITY | CLIENT_RW, SIM_POSITION | CLIENT_RW}); Joint[2] = CoppeliaSim->Add_Object("IRB4600_joint3", JOINT, {SIM_VELOCITY | CLIENT_RW, SIM_POSITION | CLIENT_RW}); Joint[3] = CoppeliaSim->Add_Object("IRB4600_joint4", JOINT, {SIM_VELOCITY | CLIENT_RW, SIM_POSITION | CLIENT_RW}); Joint[4] = CoppeliaSim->Add_Object("IRB4600_joint5", JOINT, {SIM_VELOCITY | CLIENT_RW, SIM_POSITION | CLIENT_RW}); Joint[5] = CoppeliaSim->Add_Object("IRB4600_joint6", JOINT, {SIM_VELOCITY | CLIENT_RW, SIM_POSITION | CLIENT_RW}); //读写执行末端相对于器件坐标系的位姿 Tip_target = CoppeliaSim->Add_Object("IRB4600_IkTarget", OTHER_OBJECT, {SIM_POSITION | CLIENT_WO, SIM_ORIENTATION | CLIENT_WO}); Tip_op = CoppeliaSim->Add_Object("IRB4600_IkTip", OTHER_OBJECT, {SIM_POSITION | CLIENT_RO, SIM_ORIENTATION | CLIENT_RO}); platform[0] = CoppeliaSim->Add_Object("platform_yaw", JOINT, {SIM_POSITION | CLIENT_RW}); platform[1] = CoppeliaSim->Add_Object("platform_pitch", JOINT, {SIM_POSITION | CLIENT_RW}); weld_cmd = CoppeliaSim->Add_Object("weld_cmd", SIM_INTEGER_SIGNAL, {SIM_SIGNAL_OP | CLIENT_WO}); /*Init value*/ target_pt[x] = 1.76; //-0.2; target_pt[y] = 0.09; target_pt[z] = 1.42; target_pt[alpha] = 0; target_pt[beta] = M_PI_2 + M_PI_2/2; target_pt[gamma] = -M_PI_2; Tip_target->obj_Target.position_3f[0] = target_pt[x] + 0;//1.7; Tip_target->obj_Target.position_3f[1] = target_pt[y] + 0; Tip_target->obj_Target.position_3f[2] = target_pt[z] + 0; Tip_target->obj_Target.orientation_3f[0] = target_pt[alpha]; Tip_target->obj_Target.orientation_3f[1] = target_pt[beta]; Tip_target->obj_Target.orientation_3f[2] = target_pt[gamma]; } /** * @brief These two function will be called for each loop. * User can set their message to send or read from sim enviroment. */ void Usr_SendToSimulation() { //这里可以设置关节指令 Tip_target->obj_Target.position_3f[0] = target_pt[x] + 0; //1.7; Tip_target->obj_Target.position_3f[1] = target_pt[y] + 0; Tip_target->obj_Target.position_3f[2] = target_pt[z] + 0; Tip_target->obj_Target.orientation_3f[0] = target_pt[alpha]; Tip_target->obj_Target.orientation_3f[1] = target_pt[beta]; Tip_target->obj_Target.orientation_3f[2] = target_pt[gamma]; } void Usr_ReadFromSimulation() { //这里可以读取反馈 current_pt[x] = Tip_op->obj_Data.position_3f[0] - 0; //1.7; current_pt[y] = Tip_op->obj_Data.position_3f[1] - 0; current_pt[z] = Tip_op->obj_Data.position_3f[2] - 0; current_pt[alpha] = Tip_op->obj_Data.orientation_3f[0]; current_pt[beta] = Tip_op->obj_Data.orientation_3f[1]; current_pt[gamma] = Tip_op->obj_Data.orientation_3f[2]; } inline void show_vector_improve() { std::map<std::string, std::string> keywords; std::vector<float> x1, y1, z1; srand(time(0)); float r = 2; float beta = 0.8; x1.push_back(0); y1.push_back(0); z1.push_back(0); x1.push_back(5); y1.push_back(5); z1.push_back(5); x1.push_back(-2); y1.push_back(-2); z1.push_back(-2); for(float i = 0; i < 5;) { x1.push_back(i); y1.push_back(i); z1.push_back(i); i += 0.2; } // keywords.insert(std::pair<std::string, std::string>("c", "red")); // keywords.insert(std::pair<std::string, std::string>("linewidth", "2")); // plt::plot3(x1, y1, z1, keywords,1); keywords.clear(); keywords.insert(std::pair<std::string, std::string>("c", "red")); keywords.insert(std::pair<std::string, std::string>("marker", "^")); plt::scatter(x1, y1, z1, 1,keywords,1); x1.clear(); y1.clear(); z1.clear(); Point3<float> vector_a = Point3<float>(5,5,5); for (int i(0); i < 1000; i++) { float phi = -M_PI + 2*M_PI*(float)(rand()) / (float)RAND_MAX; float theta = -M_PI + 2*M_PI*(float)(rand()) / (float)RAND_MAX; float x = r * sin(theta) * cos(phi); float y = r * sin(theta) * sin(phi); float z = r * cos(theta); Point3<float> vector_b(x,y,z); float cos_garmma = power(Point3<float>::dot(vector_b, vector_a) / (vector_a.norm() * vector_b.norm()),3); x = beta*(1 + cos_garmma) * r * sin(theta) * cos(phi); y = beta*(1 + cos_garmma) * r * sin(theta) * sin(phi); z = beta*(1 + cos_garmma) * r * cos(theta); x1.push_back(x); y1.push_back(y); z1.push_back(z); } keywords.clear(); keywords.insert(std::pair<std::string, std::string>("c", "blue")); keywords.insert(std::pair<std::string, std::string>("marker", "o")); plt::scatter(x1, y1, z1, 1, keywords, 1); } /** * @brief It's NOT recommended that user modefies this function. * Plz programm the functions with the prefix "Usr_". */ int main(int argc, char *argv[]) { // STLReader model; // ACS_Rank SearchPath; // ACS_GTSP GlobalRoute; /* 读取工件模型 */ // model.readFile("./files/cubic.stl"); // const std::vector<Triangles<float>> meshes = model.TriangleList(); // /* // 搜索路径 // */ // SearchPath.creatGridMap(meshes, 0.005, 10,"./files/cubic_grid_map.in"); // SearchPath.searchBestPathOfPoints(0.5, "./files/cubic_weld_points.in", "./files/graph.in"); // GlobalRoute.readFromGraphFile("./files/graph.in"); // GlobalRoute.computeSolution(); // GlobalRoute.read_all_segments(SearchPath.best_matrix); // /* // 结果可视化 // */ // GlobalRoute.plot_route_path(1); // SearchPath.plot_route_point(1); // SearchPath.plot_grid_map(1); // SearchPath.show_plot(); // /* // 曲线平滑 // */ // int pt_num = GlobalRoute.g_path_x.size(); // float start_pt[3] = {SearchPath.route_points[0].x, SearchPath.route_points[0].y, SearchPath.route_points[0].z}; // float end_pt[3] = {SearchPath.route_points[1].x, SearchPath.route_points[1].y, SearchPath.route_points[1].z}; // //{GlobalRoute.g_path_x[pt_num - 1], GlobalRoute.g_path_y[pt_num - 1], GlobalRoute.g_path_z[pt_num - 1]}; // float **ctrl_pt = new float *[pt_num]; // for (int i = 0; i < pt_num; ++i) // { // ctrl_pt[i] = new float[3]; // ctrl_pt[i][0] = GlobalRoute.g_path_x[i]; // ctrl_pt[i][1] = GlobalRoute.g_path_y[i]; // ctrl_pt[i][2] = GlobalRoute.g_path_z[i]; // } // BS_Basic<float, 3, 0, 0, 0> smooth_curve(pt_num); // smooth_curve.SetParam(start_pt, end_pt, ctrl_pt, 500); // clock_t base_t = clock(); // clock_t now_t = clock()-base_t; // float res[3]; // std::vector<float> smooth_x, smooth_y, smooth_z; // do // { // if(clock() - base_t - now_t >= 25) // { // now_t = clock() - base_t; // smooth_curve.getCurvePoint(now_t, res); // smooth_x.push_back(res[0]); // smooth_y.push_back(res[1]); // smooth_z.push_back(res[2]); // printf("Curve point: %f, %f, %f, time:%d \n", res[0], res[1], res[2], now_t); // } // } while (now_t <= 500); // //二次平滑 // const float constrain = 0.2; // pt_num = smooth_y.size(); // float second_start_pt[9] = {SearchPath.route_points[0].x, SearchPath.route_points[0].y, SearchPath.route_points[0].z,0,0,0,0,0,0}; // float second_end_pt[9] = {SearchPath.route_points[1].x, SearchPath.route_points[1].y, SearchPath.route_points[1].z,0,0,0,0,0,0}; // float **second_pt = new float*[pt_num]; // for (int i = 0; i < pt_num; ++i) // { // second_pt[i] = new float[9]; // second_pt[i][0] = smooth_x[i]; // second_pt[i][1] = smooth_y[i]; // second_pt[i][2] = smooth_z[i]; // for (int j(3); j < 9; j++) // second_pt[i][j] = constrain; // } // smooth_x.clear(); // smooth_y.clear(); // smooth_z.clear(); // BS_Basic<float, 3, 2, 2, 2> second_curve(pt_num); // second_curve.SetParam(second_start_pt,second_end_pt,second_pt, 500); // base_t = clock(); // now_t = clock()-base_t; // do // { // if(clock() - base_t - now_t >= 2) // { // now_t = clock() - base_t; // second_curve.getCurvePoint(now_t, res); // smooth_x.push_back(res[0]); // smooth_y.push_back(res[1]); // smooth_z.push_back(res[2]); // printf("Second point: %f, %f, %f, time:%d \n", res[0], res[1], res[2], now_t); // } // } while (now_t <= 500); // std::map<std::string, std::string> keywords; // keywords.insert(std::pair<std::string, std::string>("c", "red")); // plt::plot3(smooth_x, smooth_y, smooth_z,keywords,1); // plt::show(); // exit(0); /* System Logger tool init. */ std::cout << "[System Logger] Configuring... \n"; std::cout << "[System Logger] Logger is ready ! \n"; /* Simulation connection init. */ CoppeliaSim_Client *hClient = &CoppeliaSim_Client::getInstance(); std::cout << "[CoppeliaSim Client] Connecting to server.. \n"; while (!hClient->Start("127.0.0.1", 5000, 5, false)) { }; std::cout << "[CoppeliaSim Client] Successfully connected to server, configuring...\n"; Usr_ConfigSimulation(); std::cout << "[CoppeliaSim Client] Configure done, simulation is ready ! \n"; while (1) { // Abandon top 5 data static int init_num = 5; if (hClient->Is_Connected()) { hClient->ComWithServer(); } if (init_num > 0) init_num--; else { Usr_ReadFromSimulation(); Usr_Main(); Usr_SendToSimulation(); } }; } /************************* END-OF-FILE SCUT-ROBOTLAB **************************/
37.45625
152
0.500042
[ "vector", "model" ]
0f497246eabb69d80cce1d898ab760cbe0531688
50,445
cpp
C++
game/g_combat.cpp
kugelrund/Elite-Reinforce
a2fe0c0480ff2d9cdc241b9e5416ee7f298f00ca
[ "DOC" ]
10
2017-07-04T14:38:48.000Z
2022-03-08T22:46:39.000Z
game/g_combat.cpp
kugelrund/Elite-Reinforce
a2fe0c0480ff2d9cdc241b9e5416ee7f298f00ca
[ "DOC" ]
null
null
null
game/g_combat.cpp
kugelrund/Elite-Reinforce
a2fe0c0480ff2d9cdc241b9e5416ee7f298f00ca
[ "DOC" ]
1
2019-04-23T19:40:32.000Z
2019-04-23T19:40:32.000Z
// g_combat.c #include "g_local.h" #include "b_local.h" #include "g_functions.h" #include "anims.h" #include "objectives.h" #include "..\cgame\cg_text.h" #include "..\cgame\cg_local.h" extern cvar_t *g_debugDamage; extern qboolean stop_icarus; gentity_t *g_lastClientDamaged; int ffireLevel = 0; //Current level of "anger" for friendly fire int ffireForgivenessTimer = 0; int killPlayerTimer = 0; int loadBrigTimer = 0; extern int teamCount[]; extern int teamLastEnemyTime[]; extern const int FFIRE_LEVEL_RETALIATION = 10; extern void NPC_TempLookTarget ( gentity_t *self, int lookEntNum, int minLookTime, int maxLookTime ); extern void G_AddVoiceEvent( gentity_t *self, int event, int speakDebounceTime ); extern qboolean PM_HasAnimation( gentity_t *ent, int animation ); extern qboolean G_TeamEnemy( gentity_t *self ); extern void ChangeWeapon( gentity_t *ent, int newWeapon ); extern void AddSightEvent( gentity_t *owner, vec3_t position, float radius, alertEventLevel_e alertLevel ); extern void AddSoundEvent( gentity_t *owner, vec3_t position, float radius, alertEventLevel_e alertLevel ); extern void G_SetEnemy( gentity_t *self, gentity_t *enemy ); extern void PM_SetLegsAnimTimer( gentity_t *ent, int *legsAnimTimer, int time ); extern void PM_SetTorsoAnimTimer( gentity_t *ent, int *torsoAnimTimer, int time ); extern int PM_PickAnim( gentity_t *self, int minAnim, int maxAnim ); extern qboolean PM_InOnGroundAnim (gentity_t *self); /* ============ AddScore Adds score to both the client and his team ============ */ void AddScore( gentity_t *ent, int score ) { if ( !ent->client ) { return; } // no scoring during pre-match warmup ent->client->ps.persistant[PERS_SCORE] += score; } /* ================= TossClientItems Toss the weapon and powerups for the killed player ================= */ void TossClientItems( gentity_t *self ) { gitem_t *item; int weapon; // drop the weapon if not a gauntlet or machinegun weapon = self->s.weapon; // if ( weapon > WP_PHASER && self->client->ps.ammo[ weapon ] ) if ( weapon > WP_PHASER && self->client->ps.ammo[ weaponData[weapon].ammoIndex ] ) // checkme { // find the item type for this weapon item = FindItemForWeapon( (weapon_t) weapon ); // spawn the item Drop_Item( self, item, 0, qtrue ); } } /* ================== LookAtKiller ================== */ void LookAtKiller( gentity_t *self, gentity_t *inflictor, gentity_t *attacker ) { vec3_t dir; vec3_t angles; if ( attacker && attacker != self ) { VectorSubtract (attacker->s.pos.trBase, self->s.pos.trBase, dir); } else if ( inflictor && inflictor != self ) { VectorSubtract (inflictor->s.pos.trBase, self->s.pos.trBase, dir); } else { self->client->ps.stats[STAT_DEAD_YAW] = self->currentAngles[YAW]; return; } self->client->ps.stats[STAT_DEAD_YAW] = vectoyaw ( dir ); angles[YAW] = vectoyaw ( dir ); angles[PITCH] = 0; angles[ROLL] = 0; } void ObjectDie (gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath ) { if(self->target) G_UseTargets(self, attacker); //remove my script_targetname G_FreeEntity( self ); } /* ================== ExplodeDeath ================== */ //FIXME: all hacked up... void CG_SurfaceExplosion( vec3_t origin, vec3_t normal, float radius, float shake_speed, qboolean smoke ); void ExplodeDeath( gentity_t *self ) { // gentity_t *tent; vec3_t forward; self->takedamage = qfalse;//stop chain reaction runaway loops self->s.loopSound = 0; VectorCopy( self->currentOrigin, self->s.pos.trBase ); // tent = G_TempEntity( self->s.origin, EV_FX_EXPLOSION ); AngleVectors(self->s.angles, forward, NULL, NULL); CG_SurfaceExplosion( self->currentOrigin, forward, 20.0f, 12.0f, ((self->spawnflags&4)==qfalse) ); //FIXME: This needs to be consistent to all exploders! G_Sound(self, self->sounds ); if(self->splashDamage > 0 && self->splashRadius > 0) { gentity_t *attacker = self; if ( self->owner ) { attacker = self->owner; } G_RadiusDamage( self->currentOrigin, attacker, self->splashDamage, self->splashRadius, attacker, MOD_UNKNOWN ); } ObjectDie( self, self, self, 20, 0 ); } void ExplodeDeath_Wait( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath ) { self->e_DieFunc = dieF_NULL; self->nextthink = level.time + Q_irand(100, 500); self->e_ThinkFunc = thinkF_ExplodeDeath; } void GoExplodeDeath( gentity_t *self, gentity_t *other, gentity_t *activator) { if (self->behaviorSet[BSET_USE]) { G_ActivateBehavior(self,BSET_USE); } self->targetname = ""; //Make sure this entity cannot be told to explode again (recursive death fix) ExplodeDeath( self ); } void G_ActivateBehavior (gentity_t *self, int bset ); void G_CheckVictoryScript(gentity_t *self) { if ( self->behaviorSet[BSET_VICTORY] ) { G_ActivateBehavior( self, BSET_VICTORY ); } else { G_AddVoiceEvent( self, Q_irand(EV_VICTORY1, EV_VICTORY3), 2000 ); } } qboolean OnSameTeam( gentity_t *ent1, gentity_t *ent2 ) { if ( !ent1->client || !ent2->client ) { if ( ent1->noDamageTeam ) { if ( ent2->client && ent2->client->playerTeam == ent1->noDamageTeam ) { return qtrue; } else if ( ent2->noDamageTeam == ent1->noDamageTeam ) { if ( ent1->splashDamage && ent2->splashDamage && Q_stricmp("ambient_etherian_fliers", ent1->classname) != 0 ) {//Barrels, exploding breakables and mines will blow each other up return qfalse; } else { return qtrue; } } } return qfalse; } return ( ent1->client->playerTeam == ent2->client->playerTeam ); } /* ------------------------- G_AlertTeam ------------------------- */ void G_AlertTeam( gentity_t *victim, gentity_t *attacker, float radius, float soundDist ) { gentity_t *radiusEnts[ 128 ]; vec3_t mins, maxs; int numEnts; if ( attacker == NULL || attacker->client == NULL ) return; //Setup the bbox to search in for ( int i = 0; i < 3; i++ ) { mins[i] = victim->currentOrigin[i] - radius; maxs[i] = victim->currentOrigin[i] + radius; } //Get the number of entities in a given space numEnts = gi.EntitiesInBox( mins, maxs, radiusEnts, 128 ); //Cull this list for ( int i = 0; i < numEnts; i++ ) { //Validate clients if ( radiusEnts[i]->client == NULL ) continue; //only want NPCs if ( radiusEnts[i]->NPC == NULL ) continue; //Don't bother if they're ignoring enemies if ( radiusEnts[i]->svFlags & SVF_IGNORE_ENEMIES ) continue; //This NPC specifically flagged to ignore alerts if ( radiusEnts[i]->NPC->aiFlags & NPCAI_IGNORE_ALERTS ) continue; //Skip the requested avoid radiusEnts[i] if present if ( radiusEnts[i] == victim ) continue; //Must be on the same team if ( radiusEnts[i]->client->playerTeam != victim->client->playerTeam ) continue; //Must be alive if ( radiusEnts[i]->health <= 0 ) continue; if ( radiusEnts[i]->enemy == NULL ) { if ( DistanceSquared( radiusEnts[i]->currentOrigin, victim->currentOrigin ) > (soundDist*soundDist) ) { if ( InFOV( victim, radiusEnts[i], radiusEnts[i]->NPC->stats.hfov, radiusEnts[i]->NPC->stats.vfov ) && NPC_ClearLOS( radiusEnts[i], victim->currentOrigin ) ) { G_SetEnemy( radiusEnts[i], attacker ); } continue; } //FIXME: This can have a nasty cascading effect if setup wrong... G_SetEnemy( radiusEnts[i], attacker ); } } } /* ------------------------- G_DeathAlert ------------------------- */ #define DEATH_ALERT_RADIUS 512 #define DEATH_ALERT_SOUND_RADIUS 256 void G_DeathAlert( gentity_t *victim, gentity_t *attacker ) { G_AlertTeam( victim, attacker, DEATH_ALERT_RADIUS, DEATH_ALERT_SOUND_RADIUS ); } /* ---------------------------------------- DeathFX Applies appropriate special effects that occur while the entity is dying Not to be confused with NPC_RemoveBodyEffects (NPC.cpp), which only applies effect when removing the body ---------------------------------------- */ static void DeathFX( gentity_t *ent ) { if ( !ent || !ent->client ) return; switch( ent->client->playerTeam ) { case TEAM_STASIS: // Scale them down while they die, plus play the teleport out effect for them ent->s.eFlags |= EF_SCALE_DOWN; ent->client->ps.eFlags |= EF_SCALE_DOWN; ent->fx_time = level.time; G_AddEvent( ent, EV_STASIS_TELEPORT_OUT, 0 ); break; case TEAM_BORG: ent->s.eFlags |= EF_BORG_SPARKIES; ent->client->ps.eFlags |= EF_BORG_SPARKIES; break; case TEAM_FORGE: G_AddEvent( ent, EV_FORGE_FADE, 0 ); break; default: break; } } void G_SetMissionStatusText( gentity_t *attacker, int mod ) { if ( statusTextIndex >= 0 ) { return; } if ( mod == MOD_FALLING ) {//fell to your death statusTextIndex = IGT_WATCHYOURSTEP; } else if ( mod == MOD_SURGICAL_LASER ) {//fell to your death statusTextIndex = IGT_JUDGEMENTMUCHDESIRED; } else if ( mod == MOD_CRUSH ) {//crushed statusTextIndex = IGT_JUDGEMENTMUCHDESIRED; } else if ( attacker && attacker->client && attacker->client->playerTeam == TEAM_BORG ) {//assimilated statusTextIndex = Q_irand( IGT_RESISTANCEISFUTILE, IGT_NAMEIS8OF12 ); } else if ( attacker && Q_stricmp( "trigger_hurt", attacker->classname ) == 0 ) {//Killed by something that should have been clearly dangerous // statusTextIndex = Q_irand( IGT_JUDGEMENTDESIRED, IGT_JUDGEMENTMUCHDESIRED ); statusTextIndex = IGT_JUDGEMENTMUCHDESIRED; } else if ( attacker && attacker->s.number != 0 && attacker->client && attacker->client->playerTeam == TEAM_STARFLEET ) {//killed by a teammate statusTextIndex = IGT_INSUBORDINATION; } /* else if () {//killed a teammate- note: handled above if ( Q_irand( 0, 1 ) ) { statusTextIndex = IGT_YOUCAUSEDDEATHOFTEAMMATE; } else { statusTextIndex = IGT_KILLEDANINNOCENTCREWMAN; } } else { //This next block is not contiguous IGT_INADEQUATE, IGT_RESPONSETIME, IGT_SHOOTINRANGE, IGT_TRYAGAIN, IGT_TRAINONHOLODECK, IGT_WHATCOLORSHIRT, IGT_NOTIMPRESS7OF9, IGT_NEELIXFAREDBETTER, IGT_THATMUSTHURT, IGT_TUVOKDISAPPOINTED, IGT_STARFLEETNOTIFYFAMILY, IGT_TEAMMATESWILLMISSYOU, IGT_LESSTHANEXEMPLARY, IGT_SACRIFICEDFORTHEWHOLE, IGT_NOTLIVELONGANDPROSPER, IGT_BETTERUSEOFSIMULATIONS, } */ /* //These can be set by designers IGT_INSUBORDINATION, IGT_YOUCAUSEDDEATHOFTEAMMATE, IGT_DIDNTPROTECTTECH, IGT_DIDNTPROTECT7OF9, IGT_NOTSTEALTHYENOUGH, IGT_STEALTHTACTICSNECESSARY, */ } void G_MakeTeamVulnerable( void ) { int i, newhealth; gentity_t *ent = &g_entities[0]; gentity_t *self = &g_entities[0]; if ( !self->client ) { return; } for ( i = 0; i < globals.num_entities ; i++, ent++) { if ( !ent ) { continue; } if ( !ent->inuse ) { continue; } if ( !ent->client ) { continue; } if ( ent->client->playerTeam != TEAM_STARFLEET ) { continue; } if ( !(ent->flags&FL_UNDYING) ) { continue; } if ( !ent->client->squadname ) { continue; } if ( !ent->client->squadname[0] ) { continue; } if ( Q_stricmp(self->client->squadname, ent->client->squadname) ) { continue; } ent->flags &= ~FL_UNDYING; newhealth = Q_irand( 5, 40 ); if ( ent->health > newhealth ) { ent->health = newhealth; } } } /* ================== player_die ================== */ void NPC_SetAnim(gentity_t *ent,int type,int anim,int priority); void player_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath ) { int anim; int contents; qboolean deathScript = qfalse; if ( self->client->ps.pm_type == PM_DEAD ) return; //Use any target we had if ( meansOfDeath != MOD_KNOCKOUT ) { G_UseTargets( self, self ); } //HACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACK if ( self->s.number == 0 && attacker && attacker->client && attacker->client->playerTeam == TEAM_BORG ) {//when Munro is killed by a Borg, try to use the scriptrunner that plays the assimilated mini-cinematic G_UseTargets2( self, self, "assimilatemunro" ); } //HACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACK if ( attacker ) { G_CheckVictoryScript(attacker); } self->enemy = attacker; self->client->renderInfo.lookTarget = ENTITYNUM_WORLD; self->client->ps.persistant[PERS_KILLED]++; if ( self->client->playerTeam == TEAM_STARFLEET ) {//FIXME: just HazTeam members in formation on away missions? //or more controlled- via deathscripts? // Don't count player if (( &g_entities[0] != NULL && g_entities[0].client ) && (self->s.number != 0)) {//add to the number of teammates lost g_entities[0].client->ps.persistant[PERS_TEAMMATES_KILLED]++; } else // Player died, fire off scoreboard soon { cg.missionStatusDeadTime = level.time + 1000; // Too long?? Too short?? } } if ( self->s.number == 0 && attacker ) { G_SetMissionStatusText( attacker, meansOfDeath ); //TEST: If player killed, unmark all teammates from being undying so they can buy it too //NOTE: we want this to happen ONLY on our squad ONLY on missions... in the tutorial or on voyager levels this could be really weird. G_MakeTeamVulnerable(); } if ( attacker && attacker->client) { if ( attacker == self || OnSameTeam (self, attacker ) ) { AddScore( attacker, -1 ); } else { AddScore( attacker, 1 ); } } else { AddScore( self, -1 ); } // if client is in a nodrop area, don't drop anything contents = gi.pointcontents( self->currentOrigin, -1 ); if ( self->s.number != 0 && !( contents & CONTENTS_NODROP ) && (self->s.weapon == WP_COMPRESSION_RIFLE || self->s.weapon == WP_SCAVENGER_RIFLE)) { TossClientItems( self ); } self->takedamage = qfalse; // no gibbing // Sigh...borg shouldn't drop their weapon attachments when they die.. if ( self->client->playerTeam != TEAM_BORG ) { self->s.weapon = WP_NONE; } self->s.powerups = 0; //FIXME: do this on a callback? So people can't walk through long death anims? //Maybe set on last frame? Would be cool for big blocking corpses if the never got set? if ( self->client->playerTeam == TEAM_PARASITE ) { self->contents = CONTENTS_NONE; // FIXME: temp fix } else { self->contents = CONTENTS_CORPSE; self->maxs[2] = -8; } self->clipmask&=~CONTENTS_MONSTERCLIP;//so dead NPC can fly off ledges self->currentAngles[0] = 0; self->currentAngles[2] = 0; if ( attacker ) { LookAtKiller (self, inflictor, attacker); } VectorCopy( self->currentAngles, self->client->ps.viewangles ); self->s.loopSound = 0; // remove powerups memset( self->client->ps.powerups, 0, sizeof(self->client->ps.powerups) ); if(meansOfDeath == MOD_FALLING && self->client->playerTeam == TEAM_STARFLEET) { if ( self->client->ps.groundEntityNum == ENTITYNUM_NONE ) { NPC_SetAnim(self, SETANIM_BOTH, BOTH_FALLDEATH1INAIR, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); //FIXME: make this an event // G_Sound(self, G_SoundIndex("*falling1.wav")); //we never got this sound... G_Sound(self, G_SoundIndex("*fall1.wav")); self->client->ps.gravity *= 0.5;//Fall a bit slower } else { NPC_SetAnim(self, SETANIM_BOTH, BOTH_FALLDEATH1LAND, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); //FIXME: make this an event //PM_AddEvent( EV_FALL_FAR ); G_Sound(self, G_SoundIndex("*fall1.wav"));//FIXME: CRUNCH sounding hard land? } } else {// normal death anim = PM_PickAnim( self, BOTH_DEATH1, BOTH_DEATH7 ); //initialize to good data if ( (self->s.legsAnim&~ANIM_TOGGLEBIT) == BOTH_RESTRAINED1 || (self->s.legsAnim&~ANIM_TOGGLEBIT) == BOTH_RESTRAINED1POINT ) {//super special case, floating in air lying down anim = BOTH_RESTRAINED1; } else if ( PM_InOnGroundAnim( self ) && PM_HasAnimation( self, BOTH_LYINGDEATH1 ) ) {//on ground, need different death anim anim = BOTH_LYINGDEATH1; } else if(self->client->ps.pm_time > 0 && self->client->ps.pm_flags & PMF_TIME_KNOCKBACK && self->client->ps.velocity[2] > 0) { float thrown, dot; vec3_t throwdir, forward; AngleVectors(self->currentAngles, forward, NULL, NULL); thrown = VectorNormalize2(self->client->ps.velocity, throwdir); dot = DotProduct(forward, throwdir); if(thrown > 100) { if(dot > 0.3 && PM_HasAnimation( self, BOTH_DEATHFORWARD1 )) { self->client->ps.gravity *= 0.8; self->client->ps.friction = 0; if ( PM_HasAnimation( self, BOTH_DEATHFORWARD2) ) { anim = Q_irand(BOTH_DEATHFORWARD1, BOTH_DEATHFORWARD2);//okay, i assume he has 2 since he has 1 } else { anim = BOTH_DEATHFORWARD1; } } else if(dot < -0.3 && PM_HasAnimation( self, BOTH_DEATHBACKWARD1 )) { self->client->ps.gravity *= 0.8; self->client->ps.friction = 0; if ( PM_HasAnimation( self, BOTH_DEATHBACKWARD2) ) { anim = Q_irand(BOTH_DEATHBACKWARD1, BOTH_DEATHBACKWARD2); } else { anim = BOTH_DEATHBACKWARD1; } } } } if ( meansOfDeath == MOD_KNOCKOUT ) { //FIXME: knock-out sound, and don't remove me G_AddEvent( self, EV_JUMP, 0 ); G_UseTargets2( self, self, self->target2 ); G_AlertTeam( self, attacker, 512, 32 ); if ( self->NPC ) {//stick around for a while self->NPC->timeOfDeath = level.time + 10000; } } else if ( meansOfDeath == MOD_SNIPER ) { gentity_t *tent; vec3_t spot; if ( self->client->playerTeam != TEAM_BOTS && self->client->playerTeam != TEAM_STASIS ) { VectorCopy( self->currentOrigin, spot ); if ( self->client->playerTeam != TEAM_PARASITE ) spot[2] += 24; tent = G_TempEntity( spot, EV_DISINTEGRATION ); tent->s.eventParm = PW_REGEN; tent->owner = self; G_AlertTeam( self, attacker, 512, 88 ); if ( self->NPC ) {//need to pad deathtime some to stick around long enough for death effect to play self->NPC->timeOfDeath = level.time + 2000; } } } else if ( meansOfDeath == MOD_PHASER_ALT ) { gentity_t *tent; if ( self->client->playerTeam != TEAM_BOTS && self->client->playerTeam != TEAM_STASIS ) { tent = G_TempEntity( self->currentOrigin, EV_DISINTEGRATION ); tent->s.eventParm = PW_DISINT_3; tent->owner = self; G_AlertTeam( self, attacker, 512, 88 ); if ( self->NPC ) {//need to pad deathtime some to stick around long enough for death effect to play self->NPC->timeOfDeath = level.time + 2000; } } } else { if ( meansOfDeath == MOD_DREADNOUGHT ) { gentity_t *tent; tent = G_TempEntity( self->currentOrigin, EV_DISINTEGRATION ); tent->s.eventParm = PW_DISINT_1; tent->owner = self; } else if ( meansOfDeath == MOD_QUANTUM ) { gentity_t *tent; tent = G_TempEntity( self->currentOrigin, EV_DISINTEGRATION ); tent->s.eventParm = PW_DISINT_2; tent->owner = self; } G_AddEvent( self, Q_irand(EV_DEATH1, EV_DEATH3), self->health ); G_DeathAlert( self, attacker ); } NPC_SetAnim(self, SETANIM_BOTH, anim, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD); } // don't allow player to respawn for a few seconds self->client->respawnTime = level.time + 3000;//self->client->ps.legsAnimTimer; //lock it to this anim forever if ( self->client ) { PM_SetLegsAnimTimer( self, &self->client->ps.legsAnimTimer, -1 ); PM_SetTorsoAnimTimer( self, &self->client->ps.torsoAnimTimer, -1 ); } //Flying creatures should drop when killed //FIXME: This may screw up certain things that expect to float even while dead <?> self->svFlags &= ~SVF_CUSTOM_GRAVITY; self->client->ps.pm_type = PM_DEAD; //need to update STAT_HEALTH here because ClientThink_real for self may happen before STAT_HEALTH is updated from self->health and pmove will stomp death anim with a move anim self->client->ps.stats[STAT_HEALTH] = self->health; if ( VALIDSTRING( self->behaviorSet[BSET_DEATH] ) ) { G_ActivateBehavior( self, BSET_DEATH ); deathScript = qtrue; } if ( self->NPC && (self->NPC->scriptFlags&SCF_FFDEATH) && VALIDSTRING( self->behaviorSet[BSET_FFDEATH] ) ) {//FIXME: should running this preclude running the normal deathscript? G_ActivateBehavior( self, BSET_FFDEATH ); deathScript = qtrue; } //WARNING!!! DO NOT DO THIS WHILE RUNNING A SCRIPT, ICARUS WILL CRASH!!! if ( !deathScript ) { //Should no longer run scripts ICARUS_FreeEnt(self); } // Set pending objectives to failed OBJ_SetPendingObjectives(self); gi.linkentity (self); // Start any necessary death fx for this entity DeathFX( self ); } /* ================ CheckArmor ================ */ int CheckArmor (gentity_t *ent, int damage, int dflags) { gclient_t *client; int save; int count; if (!damage) return 0; client = ent->client; if (!client) return 0; if (dflags & DAMAGE_NO_ARMOR) return 0; // armor count = client->ps.stats[STAT_ARMOR]; save = ceil( (float) damage * ARMOR_PROTECTION ); //Always round up if (damage == 1) { if ( client->ps.stats[STAT_ARMOR] > 0 ) client->ps.stats[STAT_ARMOR] -= save; return 0; } if (save >= count) save = count; if (!save) return 0; client->ps.stats[STAT_ARMOR] -= save; return save; } void G_ApplyKnockback( gentity_t *targ, vec3_t newDir, float knockback ) { vec3_t kvel; float mass; if (targ->physicsBounce > 0) //overide the mass mass = targ->physicsBounce; else mass = 200; VectorScale (newDir, g_knockback->value * (float)knockback / mass * 0.8, kvel); kvel[2] = newDir[2] * g_knockback->value * (float)knockback / mass * 1.5; VectorAdd (targ->client->ps.velocity, kvel, targ->client->ps.velocity); // set the timer so that the other client can't cancel // out the movement immediately if ( !targ->client->ps.pm_time ) { int t; t = knockback * 2; if ( t < 50 ) { t = 50; } if ( t > 200 ) { t = 200; } targ->client->ps.pm_time = t; targ->client->ps.pm_flags |= PMF_TIME_KNOCKBACK; } } void ReCalcDamageForLocation (gentity_t *target, vec3_t pdir, vec3_t ppoint, int *damage) { /* vec3_t dir, point, point_dir, tempvec; vec3_t forward, right, up; vec3_t tangles, tcenter; float tradius, hdist; float udot, fdot, rdot; int Vertical, Forward, Lateral; int HitLoc; //get target forward, right and up if(target->client) {//ignore player's pitch and roll VectorSet(tangles, 0, target->currentAngles[YAW], 0); } AngleVectors(tangles, forward, right, up); //get center of target VectorAdd(target->absmin, target->absmax, tcenter); VectorScale(tcenter, 0.5, tcenter); //get radius width of target tradius = (fabs(target->maxs[0]) + fabs(target->maxs[1]) + fabs(target->mins[0]) + fabs(target->mins[1]))/4; //get impact point if(ppoint && !VectorCompare(ppoint, vec3_origin)) { VectorCopy(ppoint, point); } else { return; } //get impact dir if(pdir && !VectorCompare(pdir, vec3_origin)) { VectorCopy(pdir, dir); } else { return; } //put point at controlled distance from center VectorSubtract(point, tcenter, tempvec); tempvec[2] = 0; hdist = VectorLength(tempvec); VectorMA(point, hdist - tradius, dir, point); //now a point on the surface of a cylinder with a radius of tradius VectorSubtract(point, tcenter, point_dir); VectorNormalize(point_dir); //Get bottom to top (Vertical) position index udot = DotProduct(up, point_dir); if(udot>.666) Vertical = 4; else if(udot>.333) Vertical = 3; else if(udot>-.333) Vertical = 2; else if(udot>-.666) Vertical = 1; else Vertical = 0; //Get back to front (Forward) position index fdot = DotProduct(forward, point_dir); if(fdot>.666) Forward = 4; else if(fdot>.333) Forward = 3; else if(fdot>-.333) Forward = 2; else if(fdot>-.666) Forward = 1; else Forward = 0; //Get left to right (Lateral) position index rdot = DotProduct(right, point_dir); if(rdot>.666) Lateral = 4; else if(rdot>.333) Lateral = 3; else if(rdot>-.333) Lateral = 2; else if(rdot>-.666) Lateral = 1; else Lateral = 0; HitLoc = Vertical * 25 + Forward * 5 + Lateral; if(HitLoc <= 10) {//feet *damage = floor(*damage * 0.10); } else if(HitLoc <= 50) {//legs *damage = floor(*damage * 0.30); } else if(HitLoc == 56||HitLoc == 60||HitLoc == 61||HitLoc == 65||HitLoc == 66||HitLoc == 70|| HitLoc == 83||HitLoc == 87||HitLoc == 88||HitLoc == 92||HitLoc == 93||HitLoc == 97) {//arms *damage = floor(*damage * 0.20); } else if((HitLoc >= 107 && HitLoc <= 109)|| (HitLoc >= 112 && HitLoc <= 114)|| (HitLoc >= 117 && HitLoc <= 119)) {//head *damage *= 2; } */ } /* void G_TeamRetaliation ( gentity_t *targ, gentity_t *attacker, qboolean stopIcarus ) 1: Get entire team mad at player 2: Stop team from running scripts 3: If on a Voyager map (?!), load the brig after a certain delay- Else, just bring up "mission failed" FIXME: need to do this because you could potentially kill everyone. can't rely on everyone being undying */ void G_TeamRetaliation ( gentity_t *targ, gentity_t *attacker, qboolean stopIcarus ) { gentity_t *teammate; int teamcount = 0; if ( !attacker->client ) { return; } if ( Q_strncmp( "_holo", level.mapname, 5 ) == 0 ) {//only do this if not on a holodeck return; } //attacker->client->playerTeam = TEAM_FREE; attacker->flags &= ~FL_GODMODE; attacker->flags &= ~FL_UNDYING; if ( !stop_icarus ) {//don't restart ICARUS if it's already been stopped...? stop_icarus = stopIcarus; } //find each member of the team and get them angry at you for ( int i = 1; i < globals.num_entities; i++ ) { teammate = &g_entities[i]; if ( !teammate ) { continue; } if ( !teammate->inuse ) { continue; } if ( !teammate->NPC ) { continue; } if ( !teammate->client ) { continue; } if ( teammate->client->ps.stats[STAT_HEALTH] <= 0 ) { continue; } if ( teammate->s.eFlags & EF_NODRAW ) { continue; } if ( teammate->client->playerTeam != TEAM_STARFLEET ) { continue; } if ( teammate == targ || !Q_irand(0, 1) ) { G_AddVoiceEvent( teammate, Q_irand( EV_FF_3A, EV_FF_3C ), 2000 ); } teamcount++;//count them up //mad at me forever G_ClearEnemy( teammate ); G_SetEnemy( teammate, attacker ); teammate->svFlags |= SVF_LOCKEDENEMY; teammate->NPC->behaviorState = BS_RUN_AND_SHOOT; teammate->client->renderInfo.lookTarget = 0; if ( teammate->client->race != RACE_HOLOGRAM ) {//doctor unkillable if ( !teammate->contents ) { teammate->contents = CONTENTS_BODY; } teammate->NPC->ignorePain = qfalse; teammate->flags &= ~FL_UNDYING; teammate->flags &= ~FL_GODMODE; } teammate->svFlags &= ~SVF_IGNORE_ENEMIES; teammate->flags &= ~FL_DONT_SHOOT; teammate->behaviorSet[BSET_DEATH] = NULL; teammate->behaviorSet[BSET_FFDEATH] = NULL; teammate->behaviorSet[BSET_FFIRE] = NULL; teammate->behaviorSet[BSET_PAIN] = NULL; //give 'em a weapon if ( teammate->client->ps.weapon == WP_NONE || teammate->client->ps.weapon == WP_TRICORDER ) { int wp; if ( !Q_irand(0, 1) ) { wp = WP_COMPRESSION_RIFLE; } else { wp = WP_PHASER; } teammate->client->ps.stats[STAT_WEAPONS] = ( 1 << wp ); teammate->client->ps.ammo[weaponData[wp].ammoIndex] = 999; RegisterItem( FindItemForWeapon( (weapon_t) wp) ); //make sure the weapon is cached in case this runs at startup ChangeWeapon( teammate, wp ); teammate->client->ps.weapon = wp; teammate->client->ps.weaponstate = WEAPON_READY; } } if ( !teamcount ) {//killed all teammates //end map now ffireLevel = FFIRE_LEVEL_RETALIATION; killPlayerTimer = level.time + 500; if ( Q_irand( 0, 1 ) ) { statusTextIndex = IGT_YOUCAUSEDDEATHOFTEAMMATE; } else { statusTextIndex = IGT_KILLEDANINNOCENTCREWMAN; } } } void G_FriendlyFireReaction( gentity_t *targ, gentity_t *attacker, qboolean inCombat ) {//NOTE: you only get in here if a starfleet teammember shot another starfleet teammember int ffireEvent = 0; if ( attacker != &g_entities[0] || targ == &g_entities[0] ) {//attacker isn't player, or target is the player ignore it return; } if ( !targ->NPC ) {//Only bother with friendly fire checks if the player shot an NPC return; } if ( targ->health <= 0 ) {//player killed an NPC teammate, they should turn on player if ( VALIDSTRING( targ->behaviorSet[BSET_FFDEATH] ) ) {//they're going to run a special friendly fire death script //Will make them run the ffdeath script targ->NPC->scriptFlags |= SCF_FFDEATH; } else if ( targ->enemy != attacker ) {//they were killed by the player without provocation - this way if ( Q_strncmp( "_holo", level.mapname, 5 ) != 0 ) {//only do this if not on a holodeck //after a certain amount of time, end map anyway ffireLevel = FFIRE_LEVEL_RETALIATION; if ( !killPlayerTimer ) {//start the kill player timer if we haven't already killPlayerTimer = level.time + 10 * 1000; if ( Q_irand( 0, 1 ) ) { statusTextIndex = IGT_YOUCAUSEDDEATHOFTEAMMATE; } else { statusTextIndex = IGT_KILLEDANINNOCENTCREWMAN; } } //those who are killed after the team turns on the player //do not repeat this behavior... and those that may have //been spawned by ffdeathscripts do not do this either (like security) G_TeamRetaliation( targ, attacker, qtrue ); } } else if ( !teamCount[TEAM_STARFLEET] ) {//killed everyone on your team! if ( Q_strncmp( "_holo", level.mapname, 5 ) != 0 ) {//only do this if not on a holodeck //end map now ffireLevel = FFIRE_LEVEL_RETALIATION; killPlayerTimer = level.time + 500; if ( Q_irand( 0, 1 ) ) { statusTextIndex = IGT_YOUCAUSEDDEATHOFTEAMMATE; } else { statusTextIndex = IGT_KILLEDANINNOCENTCREWMAN; } } } else {//Killed a crewmate who was attacking you - start a 30 second timer to end the level one way or another gentity_t *brigent = NULL; while( (brigent = G_Find(brigent, FOFS(classname), "target_level_change" )) != NULL ) { if(!brigent->message) G_Error( "target_level_change without level map name"); if ( Q_stricmp("_brig", brigent->message) == 0 ) { break; } } if ( brigent ) {//there is a brig changelevel entity on the map, use it in 30 seconds. if ( !loadBrigTimer ) { loadBrigTimer = level.time + 30000; } } else if ( !killPlayerTimer ) {//start the kill player timer if we haven't already if ( Q_strncmp( "_holo", level.mapname, 5 ) != 0 ) {//only do this if not on a holodeck killPlayerTimer = level.time + 30000; if ( Q_irand( 0, 1 ) ) { statusTextIndex = IGT_YOUCAUSEDDEATHOFTEAMMATE; } else { statusTextIndex = IGT_KILLEDANINNOCENTCREWMAN; } } } } return; } if ( inCombat ) {//we're in combat //okay, say something, but doesn't count toward ffire counter if ( TIMER_Done( targ, "ffireDebounce" ) ) { TIMER_Set( targ, "ffireDebounce", 1000 ); G_AddVoiceEvent( targ, Q_irand( EV_FF_1A, EV_FF_2C ), 2000 ); } return; } //else we are not in combat... //shot a teammate, but he's still alive if ( targ->enemy == attacker ) {//Target is already mad at player, just yell at him for continuing to shoot if ( TIMER_Done( targ, "ffireDebounce" ) ) { TIMER_Set( targ, "ffireDebounce", 1000 ); G_AddVoiceEvent( targ, Q_irand( EV_FF_3A, EV_FF_3C ), 2000 ); } return; } //okay, he's not alreayd mad at player, inc the ffire counter //2) Only inc the global ffire counter every 1 sec max if ( level.time - ffireForgivenessTimer >= 1000 ) { //NOTE: counter is reset evey 2 minutes that passes without ffire and during combat ffireLevel++; ffireForgivenessTimer = level.time; //3) If the counter >= 10, get team mad if ( ffireLevel >= FFIRE_LEVEL_RETALIATION ) {//we are angry enough to attack //if have a ffire script, run that instead if ( VALIDSTRING( targ->behaviorSet[BSET_FFIRE] ) ) {//Got two fair warnings, third strike you're out G_ActivateBehavior( targ, BSET_FFIRE ); } else if ( attacker->client->playerTeam == TEAM_STARFLEET )//not in disguise, but this is guaranteed {//Okay, we can't just stand here and do nothing... //NOTE: this will also make the targ yell at the attacker again G_TeamRetaliation( targ, attacker, qtrue ); } } else {//they're getting pissed //1) Only reply and every 1 sec max if ( TIMER_Done( targ, "ffireDebounce" ) ) { TIMER_Set( targ, "ffireDebounce", 1000 ); //reply if ( ffireLevel < 3 ) { ffireEvent = Q_irand( EV_FF_1A, EV_FF_1C ); } else if ( ffireLevel < 6 ) { ffireEvent = Q_irand( EV_FF_2A, EV_FF_2C ); } else //must be 9 or higher { ffireEvent = Q_irand( EV_FF_3A, EV_FF_3C ); } if ( (targ->client->ps.legsAnim&~ANIM_TOGGLEBIT) != BOTH_RESTRAINED1 && (targ->client->ps.legsAnim&~ANIM_TOGGLEBIT) != BOTH_RESTRAINED1POINT ) { NPC_TempLookTarget( targ, attacker->s.number, 2000, 4000 ); } } } } if ( ffireEvent ) {//say whatever we were going to say G_AddVoiceEvent( targ, ffireEvent, 2000 ); } } /* ============ T_Damage targ entity that is being damaged inflictor entity that is causing the damage attacker entity that caused the inflictor to damage targ example: targ=monster, inflictor=rocket, attacker=player dir direction of the attack for knockback point point at which the damage is being inflicted, used for headshots damage amount of damage being inflicted knockback force to be applied against targ as a result of the damage inflictor, attacker, dir, and point can be NULL for environmental effects dflags these flags are used to control how T_Damage works DAMAGE_RADIUS damage was indirect (from a nearby explosion) DAMAGE_NO_ARMOR armor does not protect from this damage DAMAGE_NO_KNOCKBACK do not affect velocity, just view angles DAMAGE_NO_PROTECTION kills godmode, armor, everything DAMAGE_NO_HIT_LOC Damage not based on hit location ============ */ void G_Damage( gentity_t *targ, gentity_t *inflictor, gentity_t *attacker, vec3_t dir, vec3_t point, int damage, int dflags, int mod ) { gclient_t *client; int take; int save; int asave; int knockback; vec3_t newDir; if (!targ->takedamage) { return; } if ( targ->health <= 0 ) { return; } if ( !inflictor ) { inflictor = &g_entities[ENTITYNUM_WORLD]; } if ( !attacker ) { attacker = &g_entities[ENTITYNUM_WORLD]; } if ( attacker->s.number != 0 && damage >= 2 && targ->s.number != 0 && attacker->client && attacker->client->playerTeam == TEAM_STARFLEET ) {//player-helpers do only half damage to enemies damage = ceil((float)damage/2.0f); } if ( targ->client ) { if ( ( targ->client->race == RACE_HIROGEN ) && ( targ->s.powerups & ( 1 << PW_HIROGEN_SHIELD ) ) ) { //Shield is up, take no damage if ( targ->s.powerups & ( 1 << PW_HIROGEN_SHIELD ) ) return; } } client = targ->client; if ( client ) { if ( client->noclip ) { return; } } if ( dflags&DAMAGE_NO_DAMAGE ) { damage = 0; } if ( dir == NULL ) { dflags |= DAMAGE_NO_KNOCKBACK; } else { VectorNormalize2( dir, newDir ); } if ( targ->s.number != 0 ) {//not the player if ( (targ->flags&FL_GODMODE) || (targ->flags&FL_UNDYING) ) {//have god or undying on, so ignore no protection flag dflags &= ~DAMAGE_NO_PROTECTION; } } if(PM_InOnGroundAnim(targ)) { dflags |= DAMAGE_NO_KNOCKBACK; } knockback = damage; //Attempt to apply extra knockback if ( dflags & DAMAGE_EXTRA_KNOCKBACK ) { knockback *= 2; } if ( knockback > 200 ) { knockback = 200; } if ( targ->flags & FL_NO_KNOCKBACK ) { knockback = 0; } else if ( !g_teamKnockback->integer && targ->client && attacker->client && targ->client->playerTeam == attacker->client->playerTeam ) { knockback = 0; } else if ( dflags & DAMAGE_NO_KNOCKBACK ) { knockback = 0; } else if ( mod == MOD_STASIS ) {//HACK, need a dflags field on ents knockback = 0; } // figure momentum add, even if the damage won't be taken if ( knockback && targ->client && !(dflags&DAMAGE_DEATH_KNOCKBACK) ) { G_ApplyKnockback( targ, newDir, knockback ); } // check for godmode, completely getting out of the damage if ( targ->flags & FL_GODMODE && !(dflags&DAMAGE_NO_PROTECTION) ) { if ( targ->client && attacker->client && targ->client->playerTeam == attacker->client->playerTeam ) {//complain, but don't turn on them G_FriendlyFireReaction( targ, attacker, qtrue ); } return; } // Check for team damage if ( targ != attacker && !(dflags&DAMAGE_IGNORE_TEAM) && OnSameTeam (targ, attacker) ) {//on same team if ( !targ->client ) {//a non-player object should never take damage from an ent on the same team return; } if ( attacker->client && attacker->client->playerTeam == targ->noDamageTeam ) {//NPC or player shot an object on his own team return; } if ( attacker->s.number != 0 && targ->s.number != 0 &&//player not involved in any way in this exchange attacker->client && targ->client &&//two NPCs attacker->client->playerTeam == targ->client->playerTeam ) //on the same team {//NPCs on same team don't hurt each other return; } if ( targ->s.number == 0 &&//player was hit attacker->client && targ->client &&//by an NPC attacker->client->playerTeam == TEAM_STARFLEET ) //on the same team { if ( attacker->enemy != targ )//by accident {//do no damage, no armor loss, no reaction, run no scripts return; } } } // add to the attacker's hit counter if ( attacker->client && targ != attacker && targ->health > 0 ) { if ( OnSameTeam( targ, attacker ) ) { attacker->client->ps.persistant[PERS_HITS] -= damage; } else { attacker->client->ps.persistant[PERS_HITS] += damage; } } take = damage; save = 0; //FIXME: Do not use this method of difficulty changing // Scale the amount of damage given to the player based on the skill setting /* if ( targ->s.number == 0 && targ != attacker ) { take *= ( g_spskill->integer + 1) * 0.75; } if ( take < 1 ) { take = 1; } */ //don't lose armor if on same team // save some from armor asave = CheckArmor (targ, take, dflags); take -= asave; if ( ( targ->client != NULL ) && ( targ->client->playerTeam == TEAM_HIROGEN ) ) { if ( ( Q_stricmp( targ->NPC_type, "hirogenalpha" ) == 0 ) && !( targ->s.powerups & ( 1 << PW_HIROGEN_SHIELD ) ) ) { take = 1; targ->NPC->localState++; targ->NPC->squadState = 0; } } if ( g_debugDamage->integer ) { gi.Printf( "[%d]client:%i health:%i damage:%i armor:%i\n", level.time, targ->s.number, targ->health, take, asave ); } // add to the damage inflicted on a player this frame // the total will be turned into screen blends and view angle kicks // at the end of the frame if ( client ) { client->ps.persistant[PERS_ATTACKER] = attacker->s.number; //attack can be the world ent client->damage_armor += asave; client->damage_blood += take; client->damage_knockback += knockback; if ( dir ) { //can't check newdir since it's local, newdir is dir normalized VectorCopy ( newDir, client->damage_from ); client->damage_fromWorld = qfalse; } else { VectorCopy ( targ->currentOrigin, client->damage_from ); client->damage_fromWorld = qtrue; } } // do the damage if ( take || (dflags&DAMAGE_NO_DAMAGE) ) { if ( !targ->client || !attacker->client ) { targ->health = targ->health - take; if ( (targ->flags&FL_UNDYING) && !(dflags&DAMAGE_NO_PROTECTION) ) { if(targ->health < 1) { if ( VALIDSTRING( targ->behaviorSet[BSET_DEATH] ) ) { G_ActivateBehavior( targ, BSET_DEATH ); } targ->health = 1; } } } else {//two clients team_t targTeam = TEAM_FREE; team_t attackerTeam = TEAM_FREE; if ( targ->client ) { targTeam = targ->client->playerTeam; } else { targTeam = targ->noDamageTeam; } if ( targTeam == TEAM_DISGUISE ) { targTeam = TEAM_STARFLEET; } if ( attacker->client ) { attackerTeam = attacker->client->playerTeam; } else { attackerTeam = attacker->noDamageTeam; } if ( attackerTeam == TEAM_DISGUISE ) { attackerTeam = TEAM_STARFLEET; } if ( targTeam != attackerTeam ) {//on the same team targ->health = targ->health - take; //MCG - Falling should never kill player- only if a trigger_hurt does so. if ( mod == MOD_FALLING && targ->s.number == 0 && targ->health < 1 ) { targ->health = 1; } if ( (targ->flags&FL_UNDYING) && !(dflags&DAMAGE_NO_PROTECTION) ) { if ( targ->health < 1 ) { if ( VALIDSTRING( targ->behaviorSet[BSET_DEATH] ) ) { G_ActivateBehavior( targ, BSET_DEATH ); } //Turn off Hirogen boss' shield upon "death" if ( ( targ->client != NULL ) && ( targ->client->playerTeam == TEAM_HIROGEN ) ) { if ( Q_stricmp( targ->NPC_type, "hirogenalpha" ) == 0 ) { targ->s.powerups &= ~( 1 << PW_HIROGEN_SHIELD ); targ->client->ps.powerups[ PW_HIROGEN_SHIELD ] = -1; targ->NPC->ignorePain = qtrue; } } targ->health = 1; } } else if ( targ->health < 1 && attacker->client ) { // The player or NPC just killed an enemy so increment the kills counter attacker->client->ps.persistant[PERS_ENEMIES_KILLED]++; } } else if ( targTeam == TEAM_STARFLEET ) {//on the same team, and target is a starfleet officer qboolean inCombat = qfalse; qboolean takeDamage = qtrue; qboolean yellAtAttacker = qtrue; if ( level.time - teamLastEnemyTime[TEAM_STARFLEET] < 10000 ) {//Team is in combat inCombat = qtrue; } //1) player doesn't take damage from teammates unless they're angry at him if ( targ->s.number == 0 ) {//the player if ( attacker->enemy != targ && attacker != targ ) {//an NPC shot the player by accident takeDamage = qfalse; } } //2) NPCs don't take any damage from player during combat else {//an NPC if ( (inCombat || (dflags & DAMAGE_RADIUS)) && !(dflags&DAMAGE_IGNORE_TEAM) ) {//An NPC got hit by player and this is during combat or it was slash damage //NOTE: though it's not realistic to have teammates not take splash damage, // even when not in combat, it feels really bad to have them able to // actually be killed by the player's splash damage takeDamage = qfalse; } if ( inCombat && (dflags & DAMAGE_RADIUS) ) {//you're fighting and it's just radius damage, so don't even mention it yellAtAttacker = qfalse; } } if ( takeDamage ) { targ->health = targ->health - take; } if ( (targ->flags&FL_UNDYING) && !(dflags&DAMAGE_NO_PROTECTION) && attacker->s.number != 0 ) {//guy is marked undying and we're not the player or we're in combat if ( targ->health < 1 ) { if ( VALIDSTRING( targ->behaviorSet[BSET_DEATH] ) ) { G_ActivateBehavior( targ, BSET_DEATH ); } targ->health = 1; } } if ( yellAtAttacker ) { G_FriendlyFireReaction( targ, attacker, inCombat ); } } } if ( targ->client ) { targ->client->ps.stats[STAT_HEALTH] = targ->health; g_lastClientDamaged = targ; } if ( targ->health <= 0 ) { if ( knockback && targ->client && (dflags&DAMAGE_DEATH_KNOCKBACK) ) {//only do knockback on death G_ApplyKnockback( targ, newDir, knockback ); } if ( client ) targ->flags |= FL_NO_KNOCKBACK; if (targ->health < -999) targ->health = -999; targ->enemy = attacker; targ->infoString = NULL;//Dead things have no ID GEntity_DieFunc (targ, inflictor, attacker, take, mod); return; } else { GEntity_PainFunc(targ, attacker, take); if ( targ->s.number == 0 ) {//player run painscript if ( VALIDSTRING( targ->behaviorSet[BSET_PAIN] ) ) { G_ActivateBehavior( targ, BSET_PAIN ); } if ( targ->health <= 25 ) { if ( VALIDSTRING( targ->behaviorSet[BSET_FLEE] ) ) { G_ActivateBehavior( targ, BSET_FLEE ); } } } } } } /* ============ CanDamage Returns qtrue if the inflictor can directly damage the target. Used for explosions and melee attacks. ============ */ qboolean CanDamage (gentity_t *targ, vec3_t origin) { vec3_t dest; trace_t tr; vec3_t midpoint; // use the midpoint of the bounds instead of the origin, because // bmodels may have their origin is 0,0,0 VectorAdd (targ->absmin, targ->absmax, midpoint); VectorScale (midpoint, 0.5, midpoint); VectorCopy (midpoint, dest); gi.trace ( &tr, origin, vec3_origin, vec3_origin, dest, ENTITYNUM_NONE, MASK_SOLID); if (tr.fraction == 1.0) return qtrue; // this should probably check in the plane of projection, // rather than in world coordinate, and also include Z VectorCopy (midpoint, dest); dest[0] += 15.0; dest[1] += 15.0; gi.trace ( &tr, origin, vec3_origin, vec3_origin, dest, ENTITYNUM_NONE, MASK_SOLID); if (tr.fraction == 1.0) return qtrue; VectorCopy (midpoint, dest); dest[0] += 15.0; dest[1] -= 15.0; gi.trace ( &tr, origin, vec3_origin, vec3_origin, dest, ENTITYNUM_NONE, MASK_SOLID); if (tr.fraction == 1.0) return qtrue; VectorCopy (midpoint, dest); dest[0] -= 15.0; dest[1] += 15.0; gi.trace ( &tr, origin, vec3_origin, vec3_origin, dest, ENTITYNUM_NONE, MASK_SOLID); if (tr.fraction == 1.0) return qtrue; VectorCopy (midpoint, dest); dest[0] -= 15.0; dest[1] -= 15.0; gi.trace ( &tr, origin, vec3_origin, vec3_origin, dest, ENTITYNUM_NONE, MASK_SOLID); if (tr.fraction == 1.0) return qtrue; return qfalse; } /* ============ G_RadiusDamage ============ */ void G_RadiusDamage ( vec3_t origin, gentity_t *attacker, float damage, float radius, gentity_t *ignore, int mod) { float points, dist; gentity_t *ent; gentity_t *entityList[MAX_GENTITIES]; int numListedEntities; vec3_t mins, maxs; vec3_t v; vec3_t dir; int i, e; if ( radius < 1 ) { radius = 1; } for ( i = 0 ; i < 3 ; i++ ) { mins[i] = origin[i] - radius; maxs[i] = origin[i] + radius; } numListedEntities = gi.EntitiesInBox( mins, maxs, entityList, MAX_GENTITIES ); for ( e = 0 ; e < numListedEntities ; e++ ) { ent = entityList[ e ]; if ( ent == ignore ) continue; if ( !ent->takedamage ) continue; if ( !ent->contents ) continue; // find the distance from the edge of the bounding box for ( i = 0 ; i < 3 ; i++ ) { if ( origin[i] < ent->absmin[i] ) { v[i] = ent->absmin[i] - origin[i]; } else if ( origin[i] > ent->absmax[i] ) { v[i] = origin[i] - ent->absmax[i]; } else { v[i] = 0; } } dist = VectorLength( v ); if ( dist >= radius ) { continue; } points = damage * ( 1.0 - dist / radius ); if (CanDamage (ent, origin)) { VectorSubtract (ent->currentOrigin, origin, dir); // push the center of mass higher than the origin so players // get knocked into the air more dir[2] += 24; G_Damage (ent, NULL, attacker, dir, origin, (int)points, DAMAGE_RADIUS, mod); } } }
27.595733
1,739
0.678164
[ "object" ]