<commit_before>/*
 * Copyright (c) 2015, Cryptonomex, Inc.
 * All rights reserved.
 *
 * This source code is provided for evaluation in private test networks only, until September 8, 2015. After this date, this license expires and
 * the code may not be used, modified or distributed for any purpose. Redistribution and use in source and binary forms, with or without modification,
 * are permitted until September 8, 2015, provided that the following conditions are met:
 *
 * 1. The code and/or derivative works are used only for private test networks consisting of no more than 10 P2P nodes.
 *
 * 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.
 */
#pragma once

#include <graphene/app/application.hpp>
#include <graphene/chain/database.hpp>
#include <fc/io/json.hpp>

using namespace graphene::db;

#define GRAPHENE_TESTING_GENESIS_TIMESTAMP (1431700000)

#define PUSH_TX \
   graphene::chain::test::_push_transaction

#define PUSH_BLOCK \
   graphene::chain::test::_push_block

// See below
#define REQUIRE_OP_VALIDATION_SUCCESS( op, field, value ) \
{ \
   const auto temp = op.field; \
   op.field = value; \
   op.validate(); \
   op.field = temp; \
}
#define REQUIRE_OP_VALIDATION_FAILURE( op, field, value ) \
{ \
   const auto temp = op.field; \
   op.field = value; \
   BOOST_REQUIRE_THROW( op.validate(), fc::exception ); \
   op.field = temp; \
}
#define REQUIRE_OP_EVALUATION_SUCCESS( op, field, value ) \
{ \
   const auto temp = op.field; \
   op.field = value; \
   trx.operations.back() = op; \
   op.field = temp; \
   db.push_transaction( trx, ~0 ); \
}
///Shortcut to require an exception when processing a transaction with an operation containing an expected bad value
/// Uses require insteach of check, because these transactions are expected to fail. If they don't, subsequent tests
/// may spuriously succeed or fail due to unexpected database state.
#define REQUIRE_THROW_WITH_VALUE(op, field, value) \
{ \
   auto bak = op.field; \
   op.field = value; \
   trx.operations.back() = op; \
   op.field = bak; \
   BOOST_REQUIRE_THROW(db.push_transaction(trx, ~0), fc::exception); \
}
///This simply resets v back to its default-constructed value. Requires v to have a working assingment operator and
/// default constructor.
#define RESET(v) v = decltype(v)()
///This allows me to build consecutive test cases. It's pretty ugly, but it works well enough for unit tests.
/// i.e. This allows a test on update_account to begin with the database at the end state of create_account.
#define INVOKE(test) ((struct test*)this)->test_method(); trx.clear()

#define PREP_ACTOR(name) \
   fc::ecc::private_key name ## _private_key = generate_private_key(BOOST_PP_STRINGIZE(name));

#define ACTOR(name) \
   PREP_ACTOR(name) \
   const auto& name = create_account(BOOST_PP_STRINGIZE(name), name ## _private_key.get_public_key()); \
   account_id_type name ## _id = name.id; (void)name ## _id;

#define GET_ACTOR(name) \
   fc::ecc::private_key name ## _private_key = generate_private_key(BOOST_PP_STRINGIZE(name)); \
   const account_object& name = get_account(BOOST_PP_STRINGIZE(name)); \
   account_id_type name ## _id = name.id; \
   (void)name ##_id

#define ACTORS_IMPL(r, data, elem) ACTOR(elem)
#define ACTORS(names) BOOST_PP_SEQ_FOR_EACH(ACTORS_IMPL, ~, names)

namespace graphene { namespace chain {

struct database_fixture {
   // the reason we use an app is to exercise the indexes of built-in
   //   plugins
   graphene::app::application app;
   genesis_state_type genesis_state;
   chain::database &db;
   signed_transaction trx;
   public_key_type genesis_key;
   account_id_type genesis_account;
   fc::ecc::private_key private_key = fc::ecc::private_key::generate();
   fc::ecc::private_key delegate_priv_key = fc::ecc::private_key::regenerate(fc::sha256::hash(string("null_key")) );
   public_key_type delegate_pub_key;

   optional<fc::temp_directory> data_dir;
   bool skip_key_index_test = false;
   uint32_t anon_acct_count;

   database_fixture();
   ~database_fixture();

   static fc::ecc::private_key generate_private_key(string seed);
   string generate_anon_acct_name();
   static void verify_asset_supplies( const database& db );
   void verify_account_history_plugin_index( )const;
   void open_database();
   signed_block generate_block(uint32_t skip = ~0,
                               const fc::ecc::private_key& key = generate_private_key("null_key"),
                               int miss_blocks = 0);

   /**
    * @brief Generates block_count blocks
    * @param block_count number of blocks to generate
    */
   void generate_blocks(uint32_t block_count);

   /**
    * @brief Generates blocks until the head block time matches or exceeds timestamp
    * @param timestamp target time to generate blocks until
    */
   void generate_blocks(fc::time_point_sec timestamp, bool miss_intermediate_blocks = true);

   account_create_operation make_account(
      const std::string& name = "nathan",
      public_key_type = public_key_type()
      );

   account_create_operation make_account(
      const std::string& name,
      const account_object& registrar,
      const account_object& referrer,
      uint8_t referrer_percent = 100,
      public_key_type key = public_key_type()
      );

   void force_global_settle(const asset_object& what, const price& p);
   void force_settle(account_id_type who, asset what)
   { force_settle(who(db), what); }
   void force_settle(const account_object& who, asset what);
   void update_feed_producers(asset_id_type mia, flat_set<account_id_type> producers)
   { update_feed_producers(mia(db), producers); }
   void update_feed_producers(const asset_object& mia, flat_set<account_id_type> producers);
   void publish_feed(asset_id_type mia, account_id_type by, const price_feed& f)
   { publish_feed(mia(db), by(db), f); }
   void publish_feed(const asset_object& mia, const account_object& by, const price_feed& f);
   void borrow(account_id_type who, asset what, asset collateral)
   { borrow(who(db), what, collateral); }
   void borrow(const account_object& who, asset what, asset collateral);
   void cover(account_id_type who, asset what, asset collateral_freed)
   { cover(who(db), what, collateral_freed); }
   void cover(const account_object& who, asset what, asset collateral_freed);

   const asset_object& get_asset( const string& symbol )const;
   const account_object& get_account( const string& name )const;
   const asset_object& create_bitasset(const string& name,
                                       account_id_type issuer = account_id_type(1),
                                       uint16_t market_fee_percent = 100 /*1%*/,
                                       uint16_t flags = charge_market_fee);
   const asset_object& create_prediction_market(const string& name,
                                       account_id_type issuer = account_id_type(1),
                                       uint16_t market_fee_percent = 100 /*1%*/,
                                       uint16_t flags = charge_market_fee);
   const asset_object& create_user_issued_asset( const string& name );
   const asset_object& create_user_issued_asset( const string& name,
                                                 const account_object& issuer,
                                                 uint16_t flags );
   void issue_uia( const account_object& recipient, asset amount );

   const account_object& create_account(
      const string& name,
      const public_key_type& key = public_key_type()
      );

   const account_object& create_account(
      const string& name,
      const account_object& registrar,
      const account_object& referrer,
      uint8_t referrer_percent = 100,
      const public_key_type& key = public_key_type()
      );

   const account_object& create_account(
      const string& name,
      const private_key_type& key,
      const account_id_type& registrar_id = account_id_type(),
      const account_id_type& referrer_id = account_id_type(),
      uint8_t referrer_percent = 100
      );

   const delegate_object& create_delegate( const account_object& owner );
   const witness_object& create_witness(account_id_type owner,
                                        const fc::ecc::private_key& signing_private_key = generate_private_key("null_key"));
   const witness_object& create_witness(const account_object& owner,
                                        const fc::ecc::private_key& signing_private_key = generate_private_key("null_key"));
   uint64_t fund( const account_object& account, const asset& amount = asset(500000) );
   void sign( signed_transaction& trx, const fc::ecc::private_key& key );
   const limit_order_object* create_sell_order( account_id_type user, const asset& amount, const asset& recv );
   const limit_order_object* create_sell_order( const account_object& user, const asset& amount, const asset& recv );
   asset cancel_limit_order( const limit_order_object& order );
   void transfer( account_id_type from, account_id_type to, const asset& amount, const asset& fee = asset() );
   void transfer( const account_object& from, const account_object& to, const asset& amount, const asset& fee = asset() );
   void fund_fee_pool( const account_object& from, const asset_object& asset_to_fund, const share_type amount );
   void enable_fees( share_type fee = GRAPHENE_BLOCKCHAIN_PRECISION );
   void upgrade_to_lifetime_member( account_id_type account );
   void upgrade_to_lifetime_member( const account_object& account );
   void upgrade_to_annual_member( account_id_type account );
   void upgrade_to_annual_member( const account_object& account );
   void print_market( const string& syma, const string& symb )const;
   string pretty( const asset& a )const;
   void print_limit_order( const limit_order_object& cur )const;
   void print_call_orders( )const;
   void print_joint_market( const string& syma, const string& symb )const;
   int64_t get_balance( account_id_type account, asset_id_type a )const;
   int64_t get_balance( const account_object& account, const asset_object& a )const;
};

namespace test {
bool _push_block( database& db, const signed_block& b, uint32_t skip_flags = 0 );
processed_transaction _push_transaction( database& db, const signed_transaction& tx, uint32_t skip_flags = 0 );
}

} }
<commit_msg>db_fixture.hpp:  Implement some macros for exception checking<commit_after>/*
 * Copyright (c) 2015, Cryptonomex, Inc.
 * All rights reserved.
 *
 * This source code is provided for evaluation in private test networks only, until September 8, 2015. After this date, this license expires and
 * the code may not be used, modified or distributed for any purpose. Redistribution and use in source and binary forms, with or without modification,
 * are permitted until September 8, 2015, provided that the following conditions are met:
 *
 * 1. The code and/or derivative works are used only for private test networks consisting of no more than 10 P2P nodes.
 *
 * 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.
 */
#pragma once

#include <graphene/app/application.hpp>
#include <graphene/chain/database.hpp>
#include <fc/io/json.hpp>

#include <iostream>

using namespace graphene::db;

#define GRAPHENE_TESTING_GENESIS_TIMESTAMP (1431700000)

#define PUSH_TX \
   graphene::chain::test::_push_transaction

#define PUSH_BLOCK \
   graphene::chain::test::_push_block

// See below
#define REQUIRE_OP_VALIDATION_SUCCESS( op, field, value ) \
{ \
   const auto temp = op.field; \
   op.field = value; \
   op.validate(); \
   op.field = temp; \
}
#define REQUIRE_OP_EVALUATION_SUCCESS( op, field, value ) \
{ \
   const auto temp = op.field; \
   op.field = value; \
   trx.operations.back() = op; \
   op.field = temp; \
   db.push_transaction( trx, ~0 ); \
}

#define GRAPHENE_REQUIRE_THROW( expr, exc_type )          \
{                                                         \
   std::string req_throw_info = fc::json::to_string(      \
      fc::mutable_variant_object()                        \
      ("source_file", __FILE__)                           \
      ("source_lineno", __LINE__)                         \
      ("expr", #expr)                                     \
      ("exc_type", #exc_type)                             \
      );                                                  \
   std::cout << "GRAPHENE_REQUIRE_THROW begin "           \
      << req_throw_info << std::endl;                     \
   BOOST_REQUIRE_THROW( expr, exc_type );                 \
   std::cout << "GRAPHENE_REQUIRE_THROW end "             \
      << req_throw_info << std::endl;                     \
}

#define GRAPHENE_CHECK_THROW( expr, exc_type )            \
{                                                         \
   std::string req_throw_info = fc::json::to_string(      \
      fc::mutable_variant_object()                        \
      ("source_file", __FILE__)                           \
      ("source_lineno", __LINE__)                         \
      ("expr", #expr)                                     \
      ("exc_type", #exc_type)                             \
      );                                                  \
   std::cout << "GRAPHENE_CHECK_THROW begin "             \
      << req_throw_info << std::endl;                     \
   BOOST_CHECK_THROW( expr, exc_type );                   \
   std::cout << "GRAPHENE_CHECK_THROW end "               \
      << req_throw_info << std::endl;                     \
}

#define REQUIRE_OP_VALIDATION_FAILURE_2( op, field, value, exc_type ) \
{ \
   const auto temp = op.field; \
   op.field = value; \
   GRAPHENE_REQUIRE_THROW( op.validate(), exc_type ); \
   op.field = temp; \
}
#define REQUIRE_OP_VALIDATION_FAILURE( op, field, value ) \
   REQUIRE_OP_VALIDATION_FAILURE_2( op, field, value, fc::exception )

#define REQUIRE_THROW_WITH_VALUE_2(op, field, value, exc_type) \
{ \
   auto bak = op.field; \
   op.field = value; \
   trx.operations.back() = op; \
   op.field = bak; \
   GRAPHENE_REQUIRE_THROW(db.push_transaction(trx, ~0), exc_type); \
}

#define REQUIRE_THROW_WITH_VALUE( op, field, value ) \
   REQUIRE_THROW_WITH_VALUE_2( op, field, value, fc::exception )

///This simply resets v back to its default-constructed value. Requires v to have a working assingment operator and
/// default constructor.
#define RESET(v) v = decltype(v)()
///This allows me to build consecutive test cases. It's pretty ugly, but it works well enough for unit tests.
/// i.e. This allows a test on update_account to begin with the database at the end state of create_account.
#define INVOKE(test) ((struct test*)this)->test_method(); trx.clear()

#define PREP_ACTOR(name) \
   fc::ecc::private_key name ## _private_key = generate_private_key(BOOST_PP_STRINGIZE(name));

#define ACTOR(name) \
   PREP_ACTOR(name) \
   const auto& name = create_account(BOOST_PP_STRINGIZE(name), name ## _private_key.get_public_key()); \
   account_id_type name ## _id = name.id; (void)name ## _id;

#define GET_ACTOR(name) \
   fc::ecc::private_key name ## _private_key = generate_private_key(BOOST_PP_STRINGIZE(name)); \
   const account_object& name = get_account(BOOST_PP_STRINGIZE(name)); \
   account_id_type name ## _id = name.id; \
   (void)name ##_id

#define ACTORS_IMPL(r, data, elem) ACTOR(elem)
#define ACTORS(names) BOOST_PP_SEQ_FOR_EACH(ACTORS_IMPL, ~, names)

namespace graphene { namespace chain {

struct database_fixture {
   // the reason we use an app is to exercise the indexes of built-in
   //   plugins
   graphene::app::application app;
   genesis_state_type genesis_state;
   chain::database &db;
   signed_transaction trx;
   public_key_type genesis_key;
   account_id_type genesis_account;
   fc::ecc::private_key private_key = fc::ecc::private_key::generate();
   fc::ecc::private_key delegate_priv_key = fc::ecc::private_key::regenerate(fc::sha256::hash(string("null_key")) );
   public_key_type delegate_pub_key;

   optional<fc::temp_directory> data_dir;
   bool skip_key_index_test = false;
   uint32_t anon_acct_count;

   database_fixture();
   ~database_fixture();

   static fc::ecc::private_key generate_private_key(string seed);
   string generate_anon_acct_name();
   static void verify_asset_supplies( const database& db );
   void verify_account_history_plugin_index( )const;
   void open_database();
   signed_block generate_block(uint32_t skip = ~0,
                               const fc::ecc::private_key& key = generate_private_key("null_key"),
                               int miss_blocks = 0);

   /**
    * @brief Generates block_count blocks
    * @param block_count number of blocks to generate
    */
   void generate_blocks(uint32_t block_count);

   /**
    * @brief Generates blocks until the head block time matches or exceeds timestamp
    * @param timestamp target time to generate blocks until
    */
   void generate_blocks(fc::time_point_sec timestamp, bool miss_intermediate_blocks = true);

   account_create_operation make_account(
      const std::string& name = "nathan",
      public_key_type = public_key_type()
      );

   account_create_operation make_account(
      const std::string& name,
      const account_object& registrar,
      const account_object& referrer,
      uint8_t referrer_percent = 100,
      public_key_type key = public_key_type()
      );

   void force_global_settle(const asset_object& what, const price& p);
   void force_settle(account_id_type who, asset what)
   { force_settle(who(db), what); }
   void force_settle(const account_object& who, asset what);
   void update_feed_producers(asset_id_type mia, flat_set<account_id_type> producers)
   { update_feed_producers(mia(db), producers); }
   void update_feed_producers(const asset_object& mia, flat_set<account_id_type> producers);
   void publish_feed(asset_id_type mia, account_id_type by, const price_feed& f)
   { publish_feed(mia(db), by(db), f); }
   void publish_feed(const asset_object& mia, const account_object& by, const price_feed& f);
   void borrow(account_id_type who, asset what, asset collateral)
   { borrow(who(db), what, collateral); }
   void borrow(const account_object& who, asset what, asset collateral);
   void cover(account_id_type who, asset what, asset collateral_freed)
   { cover(who(db), what, collateral_freed); }
   void cover(const account_object& who, asset what, asset collateral_freed);

   const asset_object& get_asset( const string& symbol )const;
   const account_object& get_account( const string& name )const;
   const asset_object& create_bitasset(const string& name,
                                       account_id_type issuer = account_id_type(1),
                                       uint16_t market_fee_percent = 100 /*1%*/,
                                       uint16_t flags = charge_market_fee);
   const asset_object& create_prediction_market(const string& name,
                                       account_id_type issuer = account_id_type(1),
                                       uint16_t market_fee_percent = 100 /*1%*/,
                                       uint16_t flags = charge_market_fee);
   const asset_object& create_user_issued_asset( const string& name );
   const asset_object& create_user_issued_asset( const string& name,
                                                 const account_object& issuer,
                                                 uint16_t flags );
   void issue_uia( const account_object& recipient, asset amount );

   const account_object& create_account(
      const string& name,
      const public_key_type& key = public_key_type()
      );

   const account_object& create_account(
      const string& name,
      const account_object& registrar,
      const account_object& referrer,
      uint8_t referrer_percent = 100,
      const public_key_type& key = public_key_type()
      );

   const account_object& create_account(
      const string& name,
      const private_key_type& key,
      const account_id_type& registrar_id = account_id_type(),
      const account_id_type& referrer_id = account_id_type(),
      uint8_t referrer_percent = 100
      );

   const delegate_object& create_delegate( const account_object& owner );
   const witness_object& create_witness(account_id_type owner,
                                        const fc::ecc::private_key& signing_private_key = generate_private_key("null_key"));
   const witness_object& create_witness(const account_object& owner,
                                        const fc::ecc::private_key& signing_private_key = generate_private_key("null_key"));
   uint64_t fund( const account_object& account, const asset& amount = asset(500000) );
   void sign( signed_transaction& trx, const fc::ecc::private_key& key );
   const limit_order_object* create_sell_order( account_id_type user, const asset& amount, const asset& recv );
   const limit_order_object* create_sell_order( const account_object& user, const asset& amount, const asset& recv );
   asset cancel_limit_order( const limit_order_object& order );
   void transfer( account_id_type from, account_id_type to, const asset& amount, const asset& fee = asset() );
   void transfer( const account_object& from, const account_object& to, const asset& amount, const asset& fee = asset() );
   void fund_fee_pool( const account_object& from, const asset_object& asset_to_fund, const share_type amount );
   void enable_fees( share_type fee = GRAPHENE_BLOCKCHAIN_PRECISION );
   void upgrade_to_lifetime_member( account_id_type account );
   void upgrade_to_lifetime_member( const account_object& account );
   void upgrade_to_annual_member( account_id_type account );
   void upgrade_to_annual_member( const account_object& account );
   void print_market( const string& syma, const string& symb )const;
   string pretty( const asset& a )const;
   void print_limit_order( const limit_order_object& cur )const;
   void print_call_orders( )const;
   void print_joint_market( const string& syma, const string& symb )const;
   int64_t get_balance( account_id_type account, asset_id_type a )const;
   int64_t get_balance( const account_object& account, const asset_object& a )const;
};

namespace test {
bool _push_block( database& db, const signed_block& b, uint32_t skip_flags = 0 );
processed_transaction _push_transaction( database& db, const signed_transaction& tx, uint32_t skip_flags = 0 );
}

} }
<|endoftext|>


<commit_before>#ifndef GAME_HPP
#define GAME_HPP

#include <stack>
#include <SFML/Graphics.hpp>

//Fixes cyclic dependecy of GameState class
class GameState;

class Game{
public:
    std::stack<GameState*> states;
    sf::RenderWindow window;

    void pushState(GameState* state);
    void popState();
    void changeState(GameState* state);
    GameState* peekState();

    //Main game loop
    void gameLoop();

    Game();
    ~Game();
};

#endif
<commit_msg>texture manager added to game.hpp<commit_after>#ifndef GAME_HPP
#define GAME_HPP

#include <stack>
#include <SFML/Graphics.hpp>
#include "texture_manager.hpp"
//Fixes cyclic dependecy of GameState class
class GameState;

class Game{
private:
    void loadTextures();

public:
    std::stack<GameState*> states;

    sf::RenderWindow window;
    TextureManager texmgr;
    sf::Sprite background;

    void pushState(GameState* state);
    void popState();
    void changeState(GameState* state);
    GameState* peekState();

    //Main game loop
    void gameLoop();

    Game();
    ~Game();
};

#endif
<|endoftext|>


<commit_before>#include <vector>

#include <opengm/functions/explicit_function.hxx>
#include <opengm/unittests/test.hxx>
#include <opengm/graphicalmodel/graphicalmodel.hxx>
#include <opengm/operations/adder.hxx>
#include <opengm/operations/minimizer.hxx>
#include <opengm/inference/icm.hxx>
#include <opengm/utilities/metaprogramming.hxx>

#include <opengm/functions/learnable/lpotts.hxx>
//#include <opengm/learning/maximum-likelihood-learning.hxx>
#include <opengm/learning/maximum_likelihood_learning.hxx>
#include <opengm/learning/loss/hammingloss.hxx>
#include <opengm/learning/dataset/testdatasets.hxx>

//*************************************

typedef double ValueType;
typedef size_t IndexType;
typedef size_t LabelType;
typedef opengm::meta::TypeListGenerator<
    opengm::ExplicitFunction<ValueType,IndexType,LabelType>,
    opengm::functions::learnable::LPotts<ValueType,IndexType,LabelType>,
    opengm::functions::learnable::LSumOfExperts<ValueType,IndexType,LabelType>
>::type FunctionListType;

typedef opengm::GraphicalModel<
    ValueType,opengm::Adder,
    FunctionListType,
    opengm::DiscreteSpace<IndexType,LabelType>
> GM;

typedef opengm::learning::HammingLoss     LOSS;
typedef opengm::datasets::TestDataset0<GM,LOSS> DS0;
typedef opengm::datasets::TestDataset1<GM,LOSS> DS1;
typedef opengm::datasets::TestDataset2<GM,LOSS> DS2;
typedef opengm::datasets::TestDatasetSimple<GM,LOSS> DSSimple;
typedef opengm::ICM<GM,opengm::Minimizer> INF;

typedef typename opengm::BeliefPropagationUpdateRules<GM, opengm::Integrator> UpdateRules;
typedef typename opengm::MessagePassing<GM, opengm::Integrator, UpdateRules, opengm::MaxDistance> BeliefPropagation;
//*************************************

int main() {
   std::cout << " Includes are fine :-) " << std::endl;
   /*
   {
      DS0 dataset;
      std::cout << "Dataset includes " << dataset.getNumberOfModels() << " instances and has " << dataset.getNumberOfWeights() << " parameters."<<std::endl;
      opengm::learning::MaximumLikelihoodLearner<DS0,LOSS>::Weight weight;
      opengm::learning::MaximumLikelihoodLearner<DS0,LOSS> learner(dataset,weight);
      INF::Parameter infWeight;
      learner.learn<INF>(infWeight);

   }
*/

   {
      DS1 dataset;
      std::cout << "Dataset includes " << dataset.getNumberOfModels() << " instances and has " << dataset.getNumberOfWeights() << " parameters."<<std::endl;
      opengm::learning::MaximumLikelihoodLearner<DS1>::Parameter gradientParameter;
      gradientParameter.maximumNumberOfIterations_ = 3;
      gradientParameter.gradientStep_ = 0.1111;
      gradientParameter.weightAccuracy_ = 0.0000111;
      gradientParameter.gradientStoppingCriteria_ = 0.000000011;
      gradientParameter.infoFlag_ = true;
      gradientParameter.infoEveryStep_ = true;
      opengm::learning::MaximumLikelihoodLearner<DS1> learner(dataset,gradientParameter);

      //INF::Parameter infParam;
      //learner.learn<INF>(infParam);
      //learner.learn();
      const size_t maxNumberOfBPIterations = 40;
      const ValueType convergenceBound = 1e-7;
      const ValueType damping = 0.5;
      BeliefPropagation::Parameter parametersBP(maxNumberOfBPIterations, convergenceBound, damping);

      learner.learn<BeliefPropagation>(parametersBP);

   }
/*

   {
      DS2 dataset;
      std::cout << "Dataset includes " << dataset.getNumberOfModels() << " instances and has " << dataset.getNumberOfWeights() << " parameters."<<std::endl;
      opengm::learning::MaximumLikelihoodLearner<DS2,LOSS>::Weight weight;
      opengm::learning::MaximumLikelihoodLearner<DS2,LOSS> learner(dataset,weight);
      INF::Parameter infWeight;
      learner.learn<INF>(infWeight);
   }

/*
   {
      DSSimple dataset;
      std::cout << "Dataset includes " << dataset.getNumberOfModels() << " instances and has " << dataset.getNumberOfWeights() << " parameters."<<std::endl;
      opengm::learning::MaximumLikelihoodLearner<DSSimple,LOSS>::Weight weight;
      opengm::learning::MaximumLikelihoodLearner<DSSimple,LOSS> learner(dataset,weight);
      INF::Parameter infWeight;
      learner.learn<INF>(infWeight);
   }
*/
}
<commit_msg> add second dataset to mll test<commit_after>#include <vector>

#include <opengm/functions/explicit_function.hxx>
#include <opengm/unittests/test.hxx>
#include <opengm/graphicalmodel/graphicalmodel.hxx>
#include <opengm/operations/adder.hxx>
#include <opengm/operations/minimizer.hxx>
#include <opengm/inference/icm.hxx>
#include <opengm/utilities/metaprogramming.hxx>

#include <opengm/functions/learnable/lpotts.hxx>
//#include <opengm/learning/maximum-likelihood-learning.hxx>
#include <opengm/learning/maximum_likelihood_learning.hxx>
#include <opengm/learning/loss/hammingloss.hxx>
#include <opengm/learning/dataset/testdatasets.hxx>

//*************************************

typedef double ValueType;
typedef size_t IndexType;
typedef size_t LabelType;
typedef opengm::meta::TypeListGenerator<
    opengm::ExplicitFunction<ValueType,IndexType,LabelType>,
    opengm::functions::learnable::LPotts<ValueType,IndexType,LabelType>,
    opengm::functions::learnable::LSumOfExperts<ValueType,IndexType,LabelType>
>::type FunctionListType;

typedef opengm::GraphicalModel<
    ValueType,opengm::Adder,
    FunctionListType,
    opengm::DiscreteSpace<IndexType,LabelType>
> GM;

typedef opengm::learning::HammingLoss     LOSS;
typedef opengm::datasets::TestDataset0<GM,LOSS> DS0;
typedef opengm::datasets::TestDataset1<GM,LOSS> DS1;
typedef opengm::datasets::TestDataset2<GM,LOSS> DS2;
typedef opengm::datasets::TestDatasetSimple<GM,LOSS> DSSimple;
typedef opengm::ICM<GM,opengm::Minimizer> INF;

typedef typename opengm::BeliefPropagationUpdateRules<GM, opengm::Integrator> UpdateRules;
typedef typename opengm::MessagePassing<GM, opengm::Integrator, UpdateRules, opengm::MaxDistance> BeliefPropagation;
//*************************************

int main() {
   std::cout << " Includes are fine :-) " << std::endl;
   /*
   {
      DS0 dataset;
      std::cout << "Dataset includes " << dataset.getNumberOfModels() << " instances and has " << dataset.getNumberOfWeights() << " parameters."<<std::endl;
      opengm::learning::MaximumLikelihoodLearner<DS0,LOSS>::Weight weight;
      opengm::learning::MaximumLikelihoodLearner<DS0,LOSS> learner(dataset,weight);
      INF::Parameter infWeight;
      learner.learn<INF>(infWeight);

   }
*/

   {
      DS1 dataset;
      std::cout << "Dataset includes " << dataset.getNumberOfModels() << " instances and has " << dataset.getNumberOfWeights() << " parameters."<<std::endl;
      opengm::learning::MaximumLikelihoodLearner<DS1>::Parameter gradientParameter;
      gradientParameter.maximumNumberOfIterations_ = 3;
      gradientParameter.gradientStep_ = 0.1111;
      gradientParameter.weightAccuracy_ = 0.0000111;
      gradientParameter.gradientStoppingCriteria_ = 0.000000011;
      gradientParameter.infoFlag_ = true;
      gradientParameter.infoEveryStep_ = true;
      opengm::learning::MaximumLikelihoodLearner<DS1> learner(dataset,gradientParameter);

      //INF::Parameter infParam;
      //learner.learn<INF>(infParam);
      //learner.learn();
      const size_t maxNumberOfBPIterations = 40;
      const ValueType convergenceBound = 1e-7;
      const ValueType damping = 0.5;
      BeliefPropagation::Parameter parametersBP(maxNumberOfBPIterations, convergenceBound, damping);

      learner.learn<BeliefPropagation>(parametersBP);

   }

   {
      DS2 dataset;
      std::cout << "Dataset includes " << dataset.getNumberOfModels() << " instances and has " << dataset.getNumberOfWeights() << " parameters."<<std::endl;
      opengm::learning::MaximumLikelihoodLearner<DS2>::Parameter gradientParameter;
      gradientParameter.maximumNumberOfIterations_ = 3;
      gradientParameter.gradientStep_ = 0.1111;
      gradientParameter.weightAccuracy_ = 0.0000111;
      gradientParameter.gradientStoppingCriteria_ = 0.000000011;
      gradientParameter.infoFlag_ = true;
      gradientParameter.infoEveryStep_ = true;
      opengm::learning::MaximumLikelihoodLearner<DS2> learner(dataset,gradientParameter);

      //INF::Parameter infParam;
      //learner.learn<INF>(infParam);
      //learner.learn();
      const size_t maxNumberOfBPIterations = 40;
      const ValueType convergenceBound = 1e-7;
      const ValueType damping = 0.5;
      BeliefPropagation::Parameter parametersBP(maxNumberOfBPIterations, convergenceBound, damping);

      learner.learn<BeliefPropagation>(parametersBP);

   }
/*

   {
      DS2 dataset;
      std::cout << "Dataset includes " << dataset.getNumberOfModels() << " instances and has " << dataset.getNumberOfWeights() << " parameters."<<std::endl;
      opengm::learning::MaximumLikelihoodLearner<DS2,LOSS>::Weight weight;
      opengm::learning::MaximumLikelihoodLearner<DS2,LOSS> learner(dataset,weight);
      INF::Parameter infWeight;
      learner.learn<INF>(infWeight);
   }

/*
   {
      DSSimple dataset;
      std::cout << "Dataset includes " << dataset.getNumberOfModels() << " instances and has " << dataset.getNumberOfWeights() << " parameters."<<std::endl;
      opengm::learning::MaximumLikelihoodLearner<DSSimple,LOSS>::Weight weight;
      opengm::learning::MaximumLikelihoodLearner<DSSimple,LOSS> learner(dataset,weight);
      INF::Parameter infWeight;
      learner.learn<INF>(infWeight);
   }
*/
}
<|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2011, John Haddon. All rights reserved.
//  Copyright (c) 2012, Image Engine Design Inc. 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 John Haddon nor the names of
//        any other contributors to this software 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.
//
//////////////////////////////////////////////////////////////////////////

#include "GafferUI/Frame.h"
#include "GafferUI/Style.h"
#include "GafferUI/GraphGadget.h"

#include "IECore/CurvesPrimitive.h"
#include "IECore/MeshPrimitive.h"
#include "IECore/SimpleTypedData.h"

#include "math.h"

using namespace GafferUI;
using namespace IECore;
using namespace Imath;
using namespace boost;

IE_CORE_DEFINERUNTIMETYPED( Frame );

Frame::Frame( GadgetPtr child )
	:	IndividualContainer( child ), m_border( 1 )
{
}

Frame::~Frame()
{
}

Imath::Box3f Frame::bound() const
{
	Imath::Box3f b = IndividualContainer::bound();
	if( b.isEmpty() )
	{
		return b;
	}
	b.max += V3f( m_border, m_border, 0 );
	b.min -= V3f( m_border, m_border, 0 );
	return b;
}

void Frame::doRenderLayer( Layer layer, const Style *style ) const
{
	if( layer != GraphLayer::Nodes )
	{
		return;
	}

	Imath::Box3f b = IndividualContainer::bound();

	style->renderFrame( Box2f( V2f( b.min.x, b.min.y ), V2f( b.max.x, b.max.y ) ), m_border );

	IndividualContainer::doRenderLayer( layer, style );
}
<commit_msg>Frame : Minor tweaks<commit_after>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2011, John Haddon. All rights reserved.
//  Copyright (c) 2012, Image Engine Design Inc. 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 John Haddon nor the names of
//        any other contributors to this software 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.
//
//////////////////////////////////////////////////////////////////////////

#include "GafferUI/Frame.h"
#include "GafferUI/Style.h"
#include "GafferUI/GraphGadget.h"

#include "IECore/CurvesPrimitive.h"
#include "IECore/MeshPrimitive.h"
#include "IECore/SimpleTypedData.h"

using namespace GafferUI;
using namespace IECore;
using namespace Imath;
using namespace boost;

IE_CORE_DEFINERUNTIMETYPED( Frame );

Frame::Frame( GadgetPtr child )
	:	IndividualContainer( child ), m_border( 1 )
{
}

Frame::~Frame()
{
}

Imath::Box3f Frame::bound() const
{
	Imath::Box3f b = IndividualContainer::bound();
	if( b.isEmpty() )
	{
		return b;
	}
	b.max += V3f( m_border, m_border, 0 );
	b.min -= V3f( m_border, m_border, 0 );
	return b;
}

void Frame::doRenderLayer( Layer layer, const Style *style ) const
{
	IndividualContainer::doRenderLayer( layer, style );
	if( layer != Layer::Main )
	{
		return;
	}

	Imath::Box3f b = IndividualContainer::bound();
	style->renderFrame( Box2f( V2f( b.min.x, b.min.y ), V2f( b.max.x, b.max.y ) ), m_border );
}
<|endoftext|>


<commit_before>//
//  IInputListener.h
//  CatchiOS
//
//  Created by John Barbero Unenge on 9/24/12.
//  Copyright (c) 2012 John Barbero Unenge. All rights reserved.
//

#ifndef CatchiOS_IInputListener_hpp
#define CatchiOS_IInputListener_hpp

#include "EInputType.hpp"

class IInputListener {
public:
    virtual void didRecieveInputEvent(InputType input, float locX, float locY);
};

#endif
<commit_msg>didRecieveInputEvent declared taking two ints instead of two floats<commit_after>//
//  IInputListener.h
//  CatchiOS
//
//  Created by John Barbero Unenge on 9/24/12.
//  Copyright (c) 2012 John Barbero Unenge. All rights reserved.
//

#ifndef CatchiOS_IInputListener_hpp
#define CatchiOS_IInputListener_hpp

#include "EInputType.hpp"

class IInputListener {
public:
    virtual void didRecieveInputEvent(InputType input, int locX, int locY);
};

#endif
<|endoftext|>


<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2015-2016 Francois Beaune, The appleseedhq Organization
//
// 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.
//

// Interface header.
#include "renderersettings.h"

// appleseed-max headers.
#include "renderer/datachunks.h"
#include "utilities.h"

// appleseed.renderer headers.
#include "renderer/api/project.h"
#include "renderer/api/utility.h"

// 3ds Max headers.
#include <ioapi.h>

namespace asr = renderer;

namespace
{
    struct DefaultRendererSettings
      : public RendererSettings
    {
        DefaultRendererSettings()
        {
            m_pixel_samples = 16;
            m_passes = 1;
            m_gi = true;
            m_caustics = false;
            m_bounces = 3;
            m_background_emits_light = true;
            m_output_mode = OutputMode::RenderOnly;
            m_rendering_threads = 0;    // 0 = as many as there are logical cores
        }
    };
}

const RendererSettings& RendererSettings::defaults()
{
    static DefaultRendererSettings default_settings;
    return default_settings;
}

void RendererSettings::apply(
    asr::Project&   project,
    const char*     config_name) const
{
    asr::ParamArray& params = project.configurations().get_by_name(config_name)->get_parameters();

    params.insert_path("sampling_mode", "qmc");

    if (m_rendering_threads == 0)
        params.insert_path("rendering_threads", "auto");
    else params.insert_path("rendering_threads", m_rendering_threads);

    params.insert_path("generic_frame_renderer.passes", m_passes);
    params.insert_path("shading_result_framebuffer", m_passes == 1 ? "ephemeral" : "permanent");
    params.insert_path("uniform_pixel_renderer.samples", m_pixel_samples);

    if (m_gi)
        params.insert_path("pt.max_path_length", m_bounces == 0 ? 0 : m_bounces + 1);
    else params.insert_path("pt.max_path_length", 1);

    params.insert_path("pt.enable_caustics", m_caustics);

    //params.insert_path("shading_engine.override_shading.mode", "shading_normal");
}

bool RendererSettings::save(ISave* isave) const
{
    bool success = true;

    //
    // Image Sampling settings.
    //

    isave->BeginChunk(ChunkSettingsImageSampling);

        isave->BeginChunk(ChunkSettingsImageSamplingPixelSamples);
        success &= write<int>(isave, m_pixel_samples);
        isave->EndChunk();

        isave->BeginChunk(ChunkSettingsImageSamplingPasses);
        success &= write<int>(isave, m_passes);
        isave->EndChunk();

    isave->EndChunk();

    //
    // Lighting settings.
    //

    isave->BeginChunk(ChunkSettingsLighting);

        isave->BeginChunk(ChunkSettingsLightingGI);
        success &= write<bool>(isave, m_gi);
        isave->EndChunk();

        isave->BeginChunk(ChunkSettingsLightingCaustics);
        success &= write<bool>(isave, m_caustics);
        isave->EndChunk();

        isave->BeginChunk(ChunkSettingsLightingBounces);
        success &= write<int>(isave, m_bounces);
        isave->EndChunk();

        isave->BeginChunk(ChunkSettingsLightingBackgroundEmitsLight);
        success &= write<bool>(isave, m_background_emits_light);
        isave->EndChunk();

    isave->EndChunk();

    //
    // Output settings.
    //

    isave->BeginChunk(ChunkSettingsOutput);

        isave->BeginChunk(ChunkSettingsOutputMode);
        switch (m_output_mode)
        {
          case OutputMode::RenderOnly:
            success &= write<BYTE>(isave, 0x00);
            break;
          case OutputMode::SaveProjectOnly:
            success &= write<BYTE>(isave, 0x01);
            break;
          case OutputMode::SaveProjectAndRender:
            success &= write<BYTE>(isave, 0x02);
            break;
        }
        isave->EndChunk();

        isave->BeginChunk(ChunkSettingsOutputProjectFilePath);
        success &= write(isave, m_project_file_path);
        isave->EndChunk();

    isave->EndChunk();

    //
    // System settings.
    //

    isave->BeginChunk(ChunkSettingsSystem);

        isave->BeginChunk(ChunkSettingsSystemRenderingThreads);
        success &= write<int>(isave, m_rendering_threads);
        isave->EndChunk();

    isave->EndChunk();

    return success;
}

IOResult RendererSettings::load(ILoad* iload)
{
    IOResult result = IO_OK;

    while (true)
    {
        result = iload->OpenChunk();
        if (result == IO_END)
            return IO_OK;
        if (result != IO_OK)
            break;

        switch (iload->CurChunkID())
        {
          case ChunkSettingsImageSampling:
            result = load_image_sampling_settings(iload);
            break;

          case ChunkSettingsLighting:
            result = load_lighting_settings(iload);
            break;

          case ChunkSettingsOutput:
            result = load_output_settings(iload);
            break;

          case ChunkSettingsSystem:
            result = load_system_settings(iload);
            break;
        }

        if (result != IO_OK)
            break;

        result = iload->CloseChunk();
        if (result != IO_OK)
            break;
    }

    return result;
}

IOResult RendererSettings::load_image_sampling_settings(ILoad* iload)
{
    IOResult result = IO_OK;

    while (true)
    {
        result = iload->OpenChunk();
        if (result == IO_END)
            return IO_OK;
        if (result != IO_OK)
            break;

        switch (iload->CurChunkID())
        {
          case ChunkSettingsImageSamplingPixelSamples:
            result = read<int>(iload, &m_pixel_samples);
            break;

          case ChunkSettingsImageSamplingPasses:
            result = read<int>(iload, &m_passes);
            break;
        }

        if (result != IO_OK)
            break;

        result = iload->CloseChunk();
        if (result != IO_OK)
            break;
    }

    return result;
}

IOResult RendererSettings::load_lighting_settings(ILoad* iload)
{
    IOResult result = IO_OK;

    while (true)
    {
        result = iload->OpenChunk();
        if (result == IO_END)
            return IO_OK;
        if (result != IO_OK)
            break;

        switch (iload->CurChunkID())
        {
          case ChunkSettingsLightingGI:
            result = read<bool>(iload, &m_gi);
            break;

          case ChunkSettingsLightingCaustics:
            result = read<bool>(iload, &m_caustics);
            break;

          case ChunkSettingsLightingBounces:
            result = read<int>(iload, &m_bounces);
            break;

          case ChunkSettingsLightingBackgroundEmitsLight:
            result = read<bool>(iload, &m_background_emits_light);
            break;
        }

        if (result != IO_OK)
            break;

        result = iload->CloseChunk();
        if (result != IO_OK)
            break;
    }

    return result;
}

IOResult RendererSettings::load_output_settings(ILoad* iload)
{
    IOResult result = IO_OK;

    while (true)
    {
        result = iload->OpenChunk();
        if (result == IO_END)
            return IO_OK;
        if (result != IO_OK)
            break;

        switch (iload->CurChunkID())
        {
          case ChunkSettingsOutputMode:
            {
                BYTE mode;
                result = read<BYTE>(iload, &mode);
                if (result == IO_OK)
                {
                    switch (mode)
                    {
                      case 0x00:
                        m_output_mode = OutputMode::RenderOnly;
                        break;
                      case 0x01:
                        m_output_mode = OutputMode::SaveProjectOnly;
                        break;
                      case 0x02:
                        m_output_mode = OutputMode::SaveProjectAndRender;
                        break;
                      default:
                        result = IO_ERROR;
                        break;
                    }
                }
            }
            break;

          case ChunkSettingsOutputProjectFilePath:
            result = read(iload, &m_project_file_path);
            break;
        }

        if (result != IO_OK)
            break;

        result = iload->CloseChunk();
        if (result != IO_OK)
            break;
    }

    return result;
}

IOResult RendererSettings::load_system_settings(ILoad* iload)
{
    IOResult result = IO_OK;

    while (true)
    {
        result = iload->OpenChunk();
        if (result == IO_END)
            return IO_OK;
        if (result != IO_OK)
            break;

        switch (iload->CurChunkID())
        {
          case ChunkSettingsSystemRenderingThreads:
            result = read<int>(iload, &m_rendering_threads);
            break;
        }

        if (result != IO_OK)
            break;

        result = iload->CloseChunk();
        if (result != IO_OK)
            break;
    }

    return result;
}
<commit_msg>Switch tile ordering to spiral<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2015-2016 Francois Beaune, The appleseedhq Organization
//
// 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.
//

// Interface header.
#include "renderersettings.h"

// appleseed-max headers.
#include "renderer/datachunks.h"
#include "utilities.h"

// appleseed.renderer headers.
#include "renderer/api/project.h"
#include "renderer/api/utility.h"

// 3ds Max headers.
#include <ioapi.h>

namespace asr = renderer;

namespace
{
    struct DefaultRendererSettings
      : public RendererSettings
    {
        DefaultRendererSettings()
        {
            m_pixel_samples = 16;
            m_passes = 1;
            m_gi = true;
            m_caustics = false;
            m_bounces = 3;
            m_background_emits_light = true;
            m_output_mode = OutputMode::RenderOnly;
            m_rendering_threads = 0;    // 0 = as many as there are logical cores
        }
    };
}

const RendererSettings& RendererSettings::defaults()
{
    static DefaultRendererSettings default_settings;
    return default_settings;
}

void RendererSettings::apply(
    asr::Project&   project,
    const char*     config_name) const
{
    asr::ParamArray& params = project.configurations().get_by_name(config_name)->get_parameters();

    params.insert_path("sampling_mode", "qmc");

    if (m_rendering_threads == 0)
        params.insert_path("rendering_threads", "auto");
    else params.insert_path("rendering_threads", m_rendering_threads);

    params.insert_path("generic_frame_renderer.tile_ordering", "spiral");
    params.insert_path("generic_frame_renderer.passes", m_passes);
    params.insert_path("shading_result_framebuffer", m_passes == 1 ? "ephemeral" : "permanent");

    params.insert_path("uniform_pixel_renderer.samples", m_pixel_samples);

    if (m_gi)
        params.insert_path("pt.max_path_length", m_bounces == 0 ? 0 : m_bounces + 1);
    else params.insert_path("pt.max_path_length", 1);

    params.insert_path("pt.enable_caustics", m_caustics);

    //params.insert_path("shading_engine.override_shading.mode", "shading_normal");
}

bool RendererSettings::save(ISave* isave) const
{
    bool success = true;

    //
    // Image Sampling settings.
    //

    isave->BeginChunk(ChunkSettingsImageSampling);

        isave->BeginChunk(ChunkSettingsImageSamplingPixelSamples);
        success &= write<int>(isave, m_pixel_samples);
        isave->EndChunk();

        isave->BeginChunk(ChunkSettingsImageSamplingPasses);
        success &= write<int>(isave, m_passes);
        isave->EndChunk();

    isave->EndChunk();

    //
    // Lighting settings.
    //

    isave->BeginChunk(ChunkSettingsLighting);

        isave->BeginChunk(ChunkSettingsLightingGI);
        success &= write<bool>(isave, m_gi);
        isave->EndChunk();

        isave->BeginChunk(ChunkSettingsLightingCaustics);
        success &= write<bool>(isave, m_caustics);
        isave->EndChunk();

        isave->BeginChunk(ChunkSettingsLightingBounces);
        success &= write<int>(isave, m_bounces);
        isave->EndChunk();

        isave->BeginChunk(ChunkSettingsLightingBackgroundEmitsLight);
        success &= write<bool>(isave, m_background_emits_light);
        isave->EndChunk();

    isave->EndChunk();

    //
    // Output settings.
    //

    isave->BeginChunk(ChunkSettingsOutput);

        isave->BeginChunk(ChunkSettingsOutputMode);
        switch (m_output_mode)
        {
          case OutputMode::RenderOnly:
            success &= write<BYTE>(isave, 0x00);
            break;
          case OutputMode::SaveProjectOnly:
            success &= write<BYTE>(isave, 0x01);
            break;
          case OutputMode::SaveProjectAndRender:
            success &= write<BYTE>(isave, 0x02);
            break;
        }
        isave->EndChunk();

        isave->BeginChunk(ChunkSettingsOutputProjectFilePath);
        success &= write(isave, m_project_file_path);
        isave->EndChunk();

    isave->EndChunk();

    //
    // System settings.
    //

    isave->BeginChunk(ChunkSettingsSystem);

        isave->BeginChunk(ChunkSettingsSystemRenderingThreads);
        success &= write<int>(isave, m_rendering_threads);
        isave->EndChunk();

    isave->EndChunk();

    return success;
}

IOResult RendererSettings::load(ILoad* iload)
{
    IOResult result = IO_OK;

    while (true)
    {
        result = iload->OpenChunk();
        if (result == IO_END)
            return IO_OK;
        if (result != IO_OK)
            break;

        switch (iload->CurChunkID())
        {
          case ChunkSettingsImageSampling:
            result = load_image_sampling_settings(iload);
            break;

          case ChunkSettingsLighting:
            result = load_lighting_settings(iload);
            break;

          case ChunkSettingsOutput:
            result = load_output_settings(iload);
            break;

          case ChunkSettingsSystem:
            result = load_system_settings(iload);
            break;
        }

        if (result != IO_OK)
            break;

        result = iload->CloseChunk();
        if (result != IO_OK)
            break;
    }

    return result;
}

IOResult RendererSettings::load_image_sampling_settings(ILoad* iload)
{
    IOResult result = IO_OK;

    while (true)
    {
        result = iload->OpenChunk();
        if (result == IO_END)
            return IO_OK;
        if (result != IO_OK)
            break;

        switch (iload->CurChunkID())
        {
          case ChunkSettingsImageSamplingPixelSamples:
            result = read<int>(iload, &m_pixel_samples);
            break;

          case ChunkSettingsImageSamplingPasses:
            result = read<int>(iload, &m_passes);
            break;
        }

        if (result != IO_OK)
            break;

        result = iload->CloseChunk();
        if (result != IO_OK)
            break;
    }

    return result;
}

IOResult RendererSettings::load_lighting_settings(ILoad* iload)
{
    IOResult result = IO_OK;

    while (true)
    {
        result = iload->OpenChunk();
        if (result == IO_END)
            return IO_OK;
        if (result != IO_OK)
            break;

        switch (iload->CurChunkID())
        {
          case ChunkSettingsLightingGI:
            result = read<bool>(iload, &m_gi);
            break;

          case ChunkSettingsLightingCaustics:
            result = read<bool>(iload, &m_caustics);
            break;

          case ChunkSettingsLightingBounces:
            result = read<int>(iload, &m_bounces);
            break;

          case ChunkSettingsLightingBackgroundEmitsLight:
            result = read<bool>(iload, &m_background_emits_light);
            break;
        }

        if (result != IO_OK)
            break;

        result = iload->CloseChunk();
        if (result != IO_OK)
            break;
    }

    return result;
}

IOResult RendererSettings::load_output_settings(ILoad* iload)
{
    IOResult result = IO_OK;

    while (true)
    {
        result = iload->OpenChunk();
        if (result == IO_END)
            return IO_OK;
        if (result != IO_OK)
            break;

        switch (iload->CurChunkID())
        {
          case ChunkSettingsOutputMode:
            {
                BYTE mode;
                result = read<BYTE>(iload, &mode);
                if (result == IO_OK)
                {
                    switch (mode)
                    {
                      case 0x00:
                        m_output_mode = OutputMode::RenderOnly;
                        break;
                      case 0x01:
                        m_output_mode = OutputMode::SaveProjectOnly;
                        break;
                      case 0x02:
                        m_output_mode = OutputMode::SaveProjectAndRender;
                        break;
                      default:
                        result = IO_ERROR;
                        break;
                    }
                }
            }
            break;

          case ChunkSettingsOutputProjectFilePath:
            result = read(iload, &m_project_file_path);
            break;
        }

        if (result != IO_OK)
            break;

        result = iload->CloseChunk();
        if (result != IO_OK)
            break;
    }

    return result;
}

IOResult RendererSettings::load_system_settings(ILoad* iload)
{
    IOResult result = IO_OK;

    while (true)
    {
        result = iload->OpenChunk();
        if (result == IO_END)
            return IO_OK;
        if (result != IO_OK)
            break;

        switch (iload->CurChunkID())
        {
          case ChunkSettingsSystemRenderingThreads:
            result = read<int>(iload, &m_rendering_threads);
            break;
        }

        if (result != IO_OK)
            break;

        result = iload->CloseChunk();
        if (result != IO_OK)
            break;
    }

    return result;
}
<|endoftext|>


<commit_before>/*  cis_splice_effects_identifier.cc -- 'cis-splice-effects identify' methods

    Copyright (c) 2015, The Griffith Lab

    Author: Avinash Ramu <aramu@genome.wustl.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 <stdexcept>
#include <set>
#include "common.h"
#include "cis_splice_effects_identifier.h"
#include "junctions_annotator.h"
#include "junctions_extractor.h"
#include "variants_annotator.h"

//Usage for this tool
void CisSpliceEffectsIdentifier::usage(ostream& out) {
    out << "Usage:"
        << "\t\t" << "regtools cis-splice-effects identify [options] variants.vcf alignments.bam ref.fa annotations.gtf" << endl;
    out << "Options:" << endl;
    out << "\t\t" << "-o STR\tOutput file containing the aberrant splice junctions with annotations. [STDOUT]" << endl;
    out << "\t\t" << "-v STR\tOutput file containing variants annotated as splice relevant (VCF format)." << endl;
    out << "\t\t" << "-j STR\tOutput file containing the aberrant junctions in BED12 format." << endl;
    out << "\t\t" << "-s INT\tStrand specificity of RNA library preparation \n"
        << "\t\t\t " << "(0 = unstranded, 1 = first-strand/RF, 2, = second-strand/FR). REQUIRED" << endl;
    out << "\t\t" << "-t STR\tTag used in bam to label strand. [XS]" << endl;
    out << "\t\t" << "-a INT\tMinimum anchor length. Junctions which satisfy a minimum \n"
        << "\t\t\t " << "anchor length on both sides are reported. [8]" << endl;
    out << "\t\t" << "-m INT\tMinimum intron length. [70]" << endl;
    out << "\t\t" << "-M INT\tMaximum intron length. [500000]" << endl;
    out << "\t\t" << "-w INT\tWindow size in b.p to identify splicing events in.\n"
        << "\t\t\t " << "The tool identifies events in variant.start +/- w basepairs.\n"
        << "\t\t\t " << "Default behaviour is to look at the window between previous and next exons." << endl;
    out << "\t\t" << "-e INT\tMaximum distance from the start/end of an exon \n"
        << "\t\t\t " << "to annotate a variant as relevant to splicing, the variant \n"
        << "\t\t\t " << "is in exonic space, i.e a coding variant. [3]" << endl;
    out << "\t\t" << "-i INT\tMaximum distance from the start/end of an exon \n"
        << "\t\t\t " << "to annotate a variant as relevant to splicing, the variant \n"
        << "\t\t\t " << "is in intronic space. [2]" << endl;
    out << "\t\t" << "-I\tAnnotate variants in intronic space within a transcript(not to be used with -i)." << endl;
    out << "\t\t" << "-E\tAnnotate variants in exonic space within a transcript(not to be used with -e)." << endl;
    out << "\t\t" << "-S\tDon't skip single exon transcripts." << endl;
    out << endl;
}

//Return stream to write output to
void CisSpliceEffectsIdentifier::close_ostream() {
    if(ofs_.is_open())
        ofs_.close();
}

//Return stream to write output to
//If output file is not empty, attempt to open
//If output file is empty, set to cout
void CisSpliceEffectsIdentifier::set_ostream() {
    if(output_file_ == "NA") {
        common::copy_stream(cout, ofs_);
    } else {
        ofs_.open(output_file_.c_str());
        if(!ofs_.is_open())
            throw runtime_error("Unable to open " +
                                output_file_);
    }
    if(output_junctions_bed_ != "NA") {
        ofs_junctions_bed_.open(output_junctions_bed_.c_str());
        if(!ofs_junctions_bed_.is_open())
            throw runtime_error("Unable to open " +
                                output_junctions_bed_);
    }
    if(output_barcodes_file_ != "NA") {
        ofs_barcode_counts_.open(output_barcodes_file_.c_str());
        if(!ofs_barcode_counts_.is_open())
            throw runtime_error("Unable to open " +
                                output_barcodes_file_);
    }
}

//Do QC on files
void CisSpliceEffectsIdentifier::file_qc() {
    if(vcf_ == "NA" || bam_ == "NA" ||
       ref_ == "NA" || gtf_ == "NA") {
        usage(std::cout);
        throw runtime_error("Error parsing inputs!(2)\n\n");
    }
    if(!common::file_exists(vcf_) || !common::file_exists(bam_) ||
       !common::file_exists(ref_) || !common::file_exists(gtf_)) {
        throw runtime_error("Please make sure input files exist.\n\n");
    }
}

//Parse command line options
void CisSpliceEffectsIdentifier::parse_options(int argc, char* argv[]) {
    optind = 1; //Reset before parsing again.
    stringstream help_ss;
    char c;
    while((c = getopt(argc, argv, "o:w:v:j:e:Ei:ISht:s:a:m:M:b:")) != -1) {
        switch(c) {
            case 'o':
                output_file_ = string(optarg);
                break;
            case 'w':
                window_size_ = atoi(optarg);
                break;
            case 'v':
                annotated_variant_file_ = string(optarg);
                break;
            case 'j':
                output_junctions_bed_ = string(optarg);
                break;
            case 'i':
                intronic_min_distance_ = atoi(optarg);
                break;
            case 'e':
                exonic_min_distance_ = atoi(optarg);
                break;
            case 'I':
                all_intronic_space_ = true;
                break;
            case 'E':
                all_exonic_space_ = true;
                break;
            case 'S':
                skip_single_exon_genes_ = false;
                break;
            case 'h':
                usage(help_ss);
                throw common::cmdline_help_exception(help_ss.str());
            case 's':
                strandness_ = atoi(optarg);
                break;
            case 't':
                strand_tag_ = string(optarg);
                break;
            case 'a':
                min_anchor_length_ = atoi(optarg);
                break;
            case 'm':
                min_intron_length_ = atoi(optarg);
                break;
            case 'M':
                max_intron_length_ = atoi(optarg);
                break;
            case 'b':
                output_barcodes_file_ = string(optarg);
            default:
                usage(std::cerr);
                throw runtime_error("Error parsing inputs!(1)\n\n");
        }
    }
    if(argc - optind >= 4) {
        vcf_ = string(argv[optind++]);
        bam_ = string(argv[optind++]);
        ref_ = string(argv[optind++]);
        gtf_ = string(argv[optind++]);
    }
    if(optind < argc ||
       vcf_ == "NA" ||
       bam_ == "NA" ||
       ref_ == "NA" ||
       gtf_ == "NA"){
        usage(std::cerr);
        throw runtime_error("Error parsing inputs!(2)\n\n");
    }
    if(strandness_ == -1){
        usage(std::cerr);
        throw runtime_error("Please supply strand specificity with '-s' option!\n\n");
    }
    file_qc();
    cerr << "Variant file: " << vcf_ << endl;
    cerr << "Alignment file: " << bam_ << endl;
    cerr << "Reference fasta file: " << ref_ << endl;
    cerr << "Annotation file: " << gtf_ << endl;
    if(window_size_ != 0) {
        cerr << "Window size: " << window_size_ << endl;
    }
    if(output_file_ != "NA")
        cerr << "Output file: " << output_file_ << endl;
    if(output_junctions_bed_ != "NA")
        cerr << "Output junctions BED file: " << output_junctions_bed_ << endl;
    if(annotated_variant_file_ != "NA") {
        cerr << "Annotated variants file: " << annotated_variant_file_ << endl;
        write_annotated_variants_ = true;
    }
    cerr << endl;
}

//Call the junctions annotator
void CisSpliceEffectsIdentifier::annotate_junctions(const GtfParser& gp1) {
    JunctionsAnnotator ja1(ref_, gp1);
    ja1.set_gtf_parser(gp1);
    set_ostream();
    //Annotate the junctions in the set and write to file
    AnnotatedJunction::print_header(ofs_, true);
    int i = 0;
    //This is ugly, waiting to start using C++11/14
    for (set<Junction>::iterator j1 = unique_junctions_.begin(); j1 != unique_junctions_.end(); j1++) {
        Junction j = *j1;
        AnnotatedJunction line(j);
        ja1.get_splice_site(line);
        ja1.annotate_junction_with_gtf(line);
        line.name = j.name = get_junction_name(++i);
        if(output_junctions_bed_ != "NA") {
            j.print(ofs_junctions_bed_);
        }
        if(output_barcodes_file_ !="NA") {
            j.print(ofs_barcode_counts_);
        }
        line.variant_info = variant_set_to_string(junction_to_variant_[j]);
        line.print(ofs_, true);
    }
    close_ostream();
}

//get name for the junction
string CisSpliceEffectsIdentifier::get_junction_name(int i) {
    stringstream name_ss;
    name_ss << "JUNC" << setfill('0') << setw(8) << i;
    return name_ss.str();
}

//The workhorse
void CisSpliceEffectsIdentifier::identify() {
    //GTF parser object
    GtfParser gp1(gtf_);
    gp1.load();
    //variant annotator
    VariantsAnnotator va(vcf_, gp1, annotated_variant_file_, intronic_min_distance_, exonic_min_distance_, all_intronic_space_, all_exonic_space_, skip_single_exon_genes_);
    va.open_vcf_in();
    if(write_annotated_variants_)
        va.open_vcf_out();
    cerr << endl;
    //Annotate each variant and pay attention to splicing related ones
    while(va.read_next_record()) {
        AnnotatedVariant v1 = va.annotate_record_with_transcripts();
        if(v1.annotation != non_splice_region_annotation_string) {
            string region_start = window_size_ ? common::num_to_str(v1.start - window_size_) :
                                           common::num_to_str(v1.cis_effect_start);
            string region_end = window_size_ ? common::num_to_str(v1.end + window_size_) :
                                           common::num_to_str(v1.cis_effect_end);
            string variant_region = v1.chrom + ":" + region_start + "-" + region_end;
            cerr << "Variant " << v1;
            cerr << "Variant region is " << variant_region << endl;
            cerr << endl;
            if(write_annotated_variants_)
                va.write_annotation_output(v1);
            //Extract junctions near this variant
            JunctionsExtractor je1(bam_, variant_region, strandness_, strand_tag_, min_anchor_length_, min_intron_length_, max_intron_length_);
            je1.identify_junctions_from_BAM();
            vector<Junction> junctions = je1.get_all_junctions();
            //Add all the junctions to the unique set
            for (size_t i = 0; i < junctions.size(); i++) {
                //Allow partial overlap - either junction start or end is within window
                if((junctions[i].start >= v1.cis_effect_start && junctions[i].start <= v1.cis_effect_end) ||
                   (junctions[i].end <= v1.cis_effect_end && junctions[i].end >= v1.cis_effect_start)) {
                   unique_junctions_.insert(junctions[i]);
                   //add to the map of junctions to variants
                   junction_to_variant_[junctions[i]].insert(v1);
                }
                //Didn't delete since we might add an option to do this in the future
                //Don't allow partial overlap - if window is specified junction has to lie entirely within window
                // if(common::coordinate_diff(junctions[i].start, v1.start) < window_size_ &&
                //    common::coordinate_diff(junctions[i].end, v1.start) <= window_size_) {
                //        unique_junctions_.insert(junctions[i]);
                //        //add to the map of junctions to variants
                //        junction_to_variant_[junctions[i]].insert(v1);
                // }
            }
        }
    }
    annotate_junctions(gp1);
}
<commit_msg>print_barcodes instead of print<commit_after>/*  cis_splice_effects_identifier.cc -- 'cis-splice-effects identify' methods

    Copyright (c) 2015, The Griffith Lab

    Author: Avinash Ramu <aramu@genome.wustl.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 <stdexcept>
#include <set>
#include "common.h"
#include "cis_splice_effects_identifier.h"
#include "junctions_annotator.h"
#include "junctions_extractor.h"
#include "variants_annotator.h"

//Usage for this tool
void CisSpliceEffectsIdentifier::usage(ostream& out) {
    out << "Usage:"
        << "\t\t" << "regtools cis-splice-effects identify [options] variants.vcf alignments.bam ref.fa annotations.gtf" << endl;
    out << "Options:" << endl;
    out << "\t\t" << "-o STR\tOutput file containing the aberrant splice junctions with annotations. [STDOUT]" << endl;
    out << "\t\t" << "-v STR\tOutput file containing variants annotated as splice relevant (VCF format)." << endl;
    out << "\t\t" << "-j STR\tOutput file containing the aberrant junctions in BED12 format." << endl;
    out << "\t\t" << "-s INT\tStrand specificity of RNA library preparation \n"
        << "\t\t\t " << "(0 = unstranded, 1 = first-strand/RF, 2, = second-strand/FR). REQUIRED" << endl;
    out << "\t\t" << "-t STR\tTag used in bam to label strand. [XS]" << endl;
    out << "\t\t" << "-a INT\tMinimum anchor length. Junctions which satisfy a minimum \n"
        << "\t\t\t " << "anchor length on both sides are reported. [8]" << endl;
    out << "\t\t" << "-m INT\tMinimum intron length. [70]" << endl;
    out << "\t\t" << "-M INT\tMaximum intron length. [500000]" << endl;
    out << "\t\t" << "-w INT\tWindow size in b.p to identify splicing events in.\n"
        << "\t\t\t " << "The tool identifies events in variant.start +/- w basepairs.\n"
        << "\t\t\t " << "Default behaviour is to look at the window between previous and next exons." << endl;
    out << "\t\t" << "-e INT\tMaximum distance from the start/end of an exon \n"
        << "\t\t\t " << "to annotate a variant as relevant to splicing, the variant \n"
        << "\t\t\t " << "is in exonic space, i.e a coding variant. [3]" << endl;
    out << "\t\t" << "-i INT\tMaximum distance from the start/end of an exon \n"
        << "\t\t\t " << "to annotate a variant as relevant to splicing, the variant \n"
        << "\t\t\t " << "is in intronic space. [2]" << endl;
    out << "\t\t" << "-I\tAnnotate variants in intronic space within a transcript(not to be used with -i)." << endl;
    out << "\t\t" << "-E\tAnnotate variants in exonic space within a transcript(not to be used with -e)." << endl;
    out << "\t\t" << "-S\tDon't skip single exon transcripts." << endl;
    out << endl;
}

//Return stream to write output to
void CisSpliceEffectsIdentifier::close_ostream() {
    if(ofs_.is_open())
        ofs_.close();
}

//Return stream to write output to
//If output file is not empty, attempt to open
//If output file is empty, set to cout
void CisSpliceEffectsIdentifier::set_ostream() {
    if(output_file_ == "NA") {
        common::copy_stream(cout, ofs_);
    } else {
        ofs_.open(output_file_.c_str());
        if(!ofs_.is_open())
            throw runtime_error("Unable to open " +
                                output_file_);
    }
    if(output_junctions_bed_ != "NA") {
        ofs_junctions_bed_.open(output_junctions_bed_.c_str());
        if(!ofs_junctions_bed_.is_open())
            throw runtime_error("Unable to open " +
                                output_junctions_bed_);
    }
    if(output_barcodes_file_ != "NA") {
        ofs_barcode_counts_.open(output_barcodes_file_.c_str());
        if(!ofs_barcode_counts_.is_open())
            throw runtime_error("Unable to open " +
                                output_barcodes_file_);
    }
}

//Do QC on files
void CisSpliceEffectsIdentifier::file_qc() {
    if(vcf_ == "NA" || bam_ == "NA" ||
       ref_ == "NA" || gtf_ == "NA") {
        usage(std::cout);
        throw runtime_error("Error parsing inputs!(2)\n\n");
    }
    if(!common::file_exists(vcf_) || !common::file_exists(bam_) ||
       !common::file_exists(ref_) || !common::file_exists(gtf_)) {
        throw runtime_error("Please make sure input files exist.\n\n");
    }
}

//Parse command line options
void CisSpliceEffectsIdentifier::parse_options(int argc, char* argv[]) {
    optind = 1; //Reset before parsing again.
    stringstream help_ss;
    char c;
    while((c = getopt(argc, argv, "o:w:v:j:e:Ei:ISht:s:a:m:M:b:")) != -1) {
        switch(c) {
            case 'o':
                output_file_ = string(optarg);
                break;
            case 'w':
                window_size_ = atoi(optarg);
                break;
            case 'v':
                annotated_variant_file_ = string(optarg);
                break;
            case 'j':
                output_junctions_bed_ = string(optarg);
                break;
            case 'i':
                intronic_min_distance_ = atoi(optarg);
                break;
            case 'e':
                exonic_min_distance_ = atoi(optarg);
                break;
            case 'I':
                all_intronic_space_ = true;
                break;
            case 'E':
                all_exonic_space_ = true;
                break;
            case 'S':
                skip_single_exon_genes_ = false;
                break;
            case 'h':
                usage(help_ss);
                throw common::cmdline_help_exception(help_ss.str());
            case 's':
                strandness_ = atoi(optarg);
                break;
            case 't':
                strand_tag_ = string(optarg);
                break;
            case 'a':
                min_anchor_length_ = atoi(optarg);
                break;
            case 'm':
                min_intron_length_ = atoi(optarg);
                break;
            case 'M':
                max_intron_length_ = atoi(optarg);
                break;
            case 'b':
                output_barcodes_file_ = string(optarg);
            default:
                usage(std::cerr);
                throw runtime_error("Error parsing inputs!(1)\n\n");
        }
    }
    if(argc - optind >= 4) {
        vcf_ = string(argv[optind++]);
        bam_ = string(argv[optind++]);
        ref_ = string(argv[optind++]);
        gtf_ = string(argv[optind++]);
    }
    if(optind < argc ||
       vcf_ == "NA" ||
       bam_ == "NA" ||
       ref_ == "NA" ||
       gtf_ == "NA"){
        usage(std::cerr);
        throw runtime_error("Error parsing inputs!(2)\n\n");
    }
    if(strandness_ == -1){
        usage(std::cerr);
        throw runtime_error("Please supply strand specificity with '-s' option!\n\n");
    }
    file_qc();
    cerr << "Variant file: " << vcf_ << endl;
    cerr << "Alignment file: " << bam_ << endl;
    cerr << "Reference fasta file: " << ref_ << endl;
    cerr << "Annotation file: " << gtf_ << endl;
    if(window_size_ != 0) {
        cerr << "Window size: " << window_size_ << endl;
    }
    if(output_file_ != "NA")
        cerr << "Output file: " << output_file_ << endl;
    if(output_junctions_bed_ != "NA")
        cerr << "Output junctions BED file: " << output_junctions_bed_ << endl;
    if(annotated_variant_file_ != "NA") {
        cerr << "Annotated variants file: " << annotated_variant_file_ << endl;
        write_annotated_variants_ = true;
    }
    cerr << endl;
}

//Call the junctions annotator
void CisSpliceEffectsIdentifier::annotate_junctions(const GtfParser& gp1) {
    JunctionsAnnotator ja1(ref_, gp1);
    ja1.set_gtf_parser(gp1);
    set_ostream();
    //Annotate the junctions in the set and write to file
    AnnotatedJunction::print_header(ofs_, true);
    int i = 0;
    //This is ugly, waiting to start using C++11/14
    for (set<Junction>::iterator j1 = unique_junctions_.begin(); j1 != unique_junctions_.end(); j1++) {
        Junction j = *j1;
        AnnotatedJunction line(j);
        ja1.get_splice_site(line);
        ja1.annotate_junction_with_gtf(line);
        line.name = j.name = get_junction_name(++i);
        if(output_junctions_bed_ != "NA") {
            j.print(ofs_junctions_bed_);
        }
        if(output_barcodes_file_ !="NA") {
            j.print_barcodes(ofs_barcode_counts_);
        }
        line.variant_info = variant_set_to_string(junction_to_variant_[j]);
        line.print(ofs_, true);
    }
    close_ostream();
}

//get name for the junction
string CisSpliceEffectsIdentifier::get_junction_name(int i) {
    stringstream name_ss;
    name_ss << "JUNC" << setfill('0') << setw(8) << i;
    return name_ss.str();
}

//The workhorse
void CisSpliceEffectsIdentifier::identify() {
    //GTF parser object
    GtfParser gp1(gtf_);
    gp1.load();
    //variant annotator
    VariantsAnnotator va(vcf_, gp1, annotated_variant_file_, intronic_min_distance_, exonic_min_distance_, all_intronic_space_, all_exonic_space_, skip_single_exon_genes_);
    va.open_vcf_in();
    if(write_annotated_variants_)
        va.open_vcf_out();
    cerr << endl;
    //Annotate each variant and pay attention to splicing related ones
    while(va.read_next_record()) {
        AnnotatedVariant v1 = va.annotate_record_with_transcripts();
        if(v1.annotation != non_splice_region_annotation_string) {
            string region_start = window_size_ ? common::num_to_str(v1.start - window_size_) :
                                           common::num_to_str(v1.cis_effect_start);
            string region_end = window_size_ ? common::num_to_str(v1.end + window_size_) :
                                           common::num_to_str(v1.cis_effect_end);
            string variant_region = v1.chrom + ":" + region_start + "-" + region_end;
            cerr << "Variant " << v1;
            cerr << "Variant region is " << variant_region << endl;
            cerr << endl;
            if(write_annotated_variants_)
                va.write_annotation_output(v1);
            //Extract junctions near this variant
            JunctionsExtractor je1(bam_, variant_region, strandness_, strand_tag_, min_anchor_length_, min_intron_length_, max_intron_length_);
            je1.identify_junctions_from_BAM();
            vector<Junction> junctions = je1.get_all_junctions();
            //Add all the junctions to the unique set
            for (size_t i = 0; i < junctions.size(); i++) {
                //Allow partial overlap - either junction start or end is within window
                if((junctions[i].start >= v1.cis_effect_start && junctions[i].start <= v1.cis_effect_end) ||
                   (junctions[i].end <= v1.cis_effect_end && junctions[i].end >= v1.cis_effect_start)) {
                   unique_junctions_.insert(junctions[i]);
                   //add to the map of junctions to variants
                   junction_to_variant_[junctions[i]].insert(v1);
                }
                //Didn't delete since we might add an option to do this in the future
                //Don't allow partial overlap - if window is specified junction has to lie entirely within window
                // if(common::coordinate_diff(junctions[i].start, v1.start) < window_size_ &&
                //    common::coordinate_diff(junctions[i].end, v1.start) <= window_size_) {
                //        unique_junctions_.insert(junctions[i]);
                //        //add to the map of junctions to variants
                //        junction_to_variant_[junctions[i]].insert(v1);
                // }
            }
        }
    }
    annotate_junctions(gp1);
}
<|endoftext|>


<commit_before>#include "aquila/global.h"
#include "aquila/source/SignalSource.h"
#include "aquila/source/Frame.h"
#include "aquila/source/FramesCollection.h"
#include <unittestpp.h>
#include <algorithm>

bool equalSamples(Aquila::Frame frame, Aquila::SampleType arr[])
{
    return std::equal(std::begin(frame), std::end(frame), arr);
}

SUITE(FramesCollection)
{
    const int SIZE = 10;
    Aquila::SampleType testArray[SIZE] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
    Aquila::FrequencyType sampleFrequency  = 100;
    Aquila::SignalSource data(testArray, SIZE, sampleFrequency);

    TEST(Empty)
    {
        Aquila::FramesCollection frames;
        CHECK_EQUAL(0u, frames.count());
    }

    TEST(EmptyWhenZeroSamples)
    {
        Aquila::FramesCollection frames(data, 0);
        CHECK_EQUAL(0u, frames.count());
    }

    TEST(FiveSamplesPerFrame)
    {
        Aquila::FramesCollection frames(data, 5);
        CHECK_EQUAL(2u, frames.count());
        Aquila::SampleType arr0[5] = {0, 1, 2, 3, 4};
        CHECK(equalSamples(frames.frame(0), arr0));
        Aquila::SampleType arr1[5] = {5, 6, 7, 8, 9};
        CHECK(equalSamples(frames.frame(1), arr1));
    }

    TEST(TwoSamplesPerFrame)
    {
        Aquila::FramesCollection frames(data, 2);
        CHECK_EQUAL(5u, frames.count());
        Aquila::SampleType arr[2] = {0, 1};
        CHECK(equalSamples(frames.frame(0), arr));
    }

    TEST(OneSamplePerFrame)
    {
        Aquila::FramesCollection frames(data, 1);
        CHECK_EQUAL(10u, frames.count());
        Aquila::SampleType arr[1] = {0};
        CHECK(equalSamples(frames.frame(0), arr));
    }

    TEST(AllSamplesPerFrame)
    {
        Aquila::FramesCollection frames(data, 10);
        CHECK_EQUAL(1u, frames.count());
        Aquila::SampleType arr[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
        CHECK(equalSamples(frames.frame(0), arr));
    }

    TEST(MoreThanHalfSamplesPerFrame)
    {
        Aquila::FramesCollection frames(data, 7);
        CHECK_EQUAL(1u, frames.count());
        Aquila::SampleType arr[7] = {0, 1, 2, 3, 4, 5, 6};
        CHECK(equalSamples(frames.frame(0), arr));
    }

    TEST(TooManySamplesPerFrame)
    {
        Aquila::FramesCollection frames(data, 11);
        CHECK_EQUAL(0u, frames.count());
    }

    TEST(Duration)
    {
        // sampling at 100 Hz -> 10 miliseconds is 1 sample
        auto frames = Aquila::FramesCollection::createFromDuration(data, 10);
        CHECK_EQUAL(10u, frames.count());
    }

    TEST(Duration2)
    {
        // sampling at 100 Hz -> 50 miliseconds is 5 samples
        auto frames = Aquila::FramesCollection::createFromDuration(data, 50);
        CHECK_EQUAL(2u, frames.count());
    }

    TEST(DurationWithOverlap)
    {
        // sampling at 100 Hz -> 50 miliseconds is 5 samples
        // 80% overlap -> 4 common samples between consecutive frames
        // frame data:  0  1  2  3  4  5  6  7  8  9
        // frame 0:    |             |
        // frame 1:       |             |
        // frame 2:          |             |
        // frame 3:             |             |
        // frame 4:                |             |
        // frame 5:                   |              |
        auto frames = Aquila::FramesCollection::createFromDuration(data, 50, 0.8);
        CHECK_EQUAL(6u, frames.count());
    }

    TEST(ApplySimpleFunction)
    {
        Aquila::FramesCollection frames(data, 5);
        auto energies = frames.apply<double>(Aquila::mean);
        double expected[2] = {2.0, 7.0};
        CHECK_ARRAY_CLOSE(expected, energies, 2, 0.000001);
    }

    TEST(ApplyLambda)
    {
        Aquila::FramesCollection frames(data, 5);
        auto maximums = frames.apply<Aquila::SampleType>(
            [&](const Aquila::SignalSource& s) {
                return *std::max_element(s.begin(), s.end());
            }
        );
        Aquila::SampleType expected[2] = {4.0, 9.0};
        CHECK_ARRAY_CLOSE(expected, maximums, 2, 0.000001);
    }
}
<commit_msg>Test for applying SignalSource member functions to the collection.<commit_after>#include "aquila/global.h"
#include "aquila/source/SignalSource.h"
#include "aquila/source/Frame.h"
#include "aquila/source/FramesCollection.h"
#include <unittestpp.h>
#include <algorithm>

bool equalSamples(Aquila::Frame frame, Aquila::SampleType arr[])
{
    return std::equal(std::begin(frame), std::end(frame), arr);
}

SUITE(FramesCollection)
{
    const int SIZE = 10;
    Aquila::SampleType testArray[SIZE] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
    Aquila::FrequencyType sampleFrequency  = 100;
    Aquila::SignalSource data(testArray, SIZE, sampleFrequency);

    TEST(Empty)
    {
        Aquila::FramesCollection frames;
        CHECK_EQUAL(0u, frames.count());
    }

    TEST(EmptyWhenZeroSamples)
    {
        Aquila::FramesCollection frames(data, 0);
        CHECK_EQUAL(0u, frames.count());
    }

    TEST(FiveSamplesPerFrame)
    {
        Aquila::FramesCollection frames(data, 5);
        CHECK_EQUAL(2u, frames.count());
        Aquila::SampleType arr0[5] = {0, 1, 2, 3, 4};
        CHECK(equalSamples(frames.frame(0), arr0));
        Aquila::SampleType arr1[5] = {5, 6, 7, 8, 9};
        CHECK(equalSamples(frames.frame(1), arr1));
    }

    TEST(TwoSamplesPerFrame)
    {
        Aquila::FramesCollection frames(data, 2);
        CHECK_EQUAL(5u, frames.count());
        Aquila::SampleType arr[2] = {0, 1};
        CHECK(equalSamples(frames.frame(0), arr));
    }

    TEST(OneSamplePerFrame)
    {
        Aquila::FramesCollection frames(data, 1);
        CHECK_EQUAL(10u, frames.count());
        Aquila::SampleType arr[1] = {0};
        CHECK(equalSamples(frames.frame(0), arr));
    }

    TEST(AllSamplesPerFrame)
    {
        Aquila::FramesCollection frames(data, 10);
        CHECK_EQUAL(1u, frames.count());
        Aquila::SampleType arr[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
        CHECK(equalSamples(frames.frame(0), arr));
    }

    TEST(MoreThanHalfSamplesPerFrame)
    {
        Aquila::FramesCollection frames(data, 7);
        CHECK_EQUAL(1u, frames.count());
        Aquila::SampleType arr[7] = {0, 1, 2, 3, 4, 5, 6};
        CHECK(equalSamples(frames.frame(0), arr));
    }

    TEST(TooManySamplesPerFrame)
    {
        Aquila::FramesCollection frames(data, 11);
        CHECK_EQUAL(0u, frames.count());
    }

    TEST(Duration)
    {
        // sampling at 100 Hz -> 10 miliseconds is 1 sample
        auto frames = Aquila::FramesCollection::createFromDuration(data, 10);
        CHECK_EQUAL(10u, frames.count());
    }

    TEST(Duration2)
    {
        // sampling at 100 Hz -> 50 miliseconds is 5 samples
        auto frames = Aquila::FramesCollection::createFromDuration(data, 50);
        CHECK_EQUAL(2u, frames.count());
    }

    TEST(DurationWithOverlap)
    {
        // sampling at 100 Hz -> 50 miliseconds is 5 samples
        // 80% overlap -> 4 common samples between consecutive frames
        // frame data:  0  1  2  3  4  5  6  7  8  9
        // frame 0:    |             |
        // frame 1:       |             |
        // frame 2:          |             |
        // frame 3:             |             |
        // frame 4:                |             |
        // frame 5:                   |              |
        auto frames = Aquila::FramesCollection::createFromDuration(data, 50, 0.8);
        CHECK_EQUAL(6u, frames.count());
    }

    TEST(ApplySimpleFunction)
    {
        Aquila::FramesCollection frames(data, 5);
        auto energies = frames.apply<double>(Aquila::mean);
        double expected[2] = {2.0, 7.0};
        CHECK_ARRAY_CLOSE(expected, energies, 2, 0.000001);
    }

    TEST(ApplyLambda)
    {
        Aquila::FramesCollection frames(data, 5);
        auto maximums = frames.apply<Aquila::SampleType>(
            [&](const Aquila::SignalSource& s) {
                return *std::max_element(s.begin(), s.end());
            }
        );
        Aquila::SampleType expected[2] = {4.0, 9.0};
        CHECK_ARRAY_CLOSE(expected, maximums, 2, 0.000001);
    }

    TEST(ApplyMemberFunction)
    {
        Aquila::FramesCollection frames(data, 5);
        auto lengths = frames.apply<std::size_t>(
            &Aquila::SignalSource::getSamplesCount
        );
        std::size_t expected[2] = {5, 5};
        CHECK_ARRAY_EQUAL(expected, lengths, 2);
    }
}
<|endoftext|>