<commit_before>// $Id$

/*
Copyright (c) 2007-2009, Trustees of The Leland Stanford Junior University
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
Neither the name of the Stanford University nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/*booksim_config.cpp
 *
 *Contains all the configurable parameters in a network
 *
 */

#include "booksim.hpp"
#include "booksim_config.hpp"

BookSimConfig::BookSimConfig( )
{
  //========================================================
  // Network options
  //========================================================

  // Channel length listing file
  AddStrField( "channel_file", "" ) ;

  // Use read/write request reply scheme

  _int_map["use_read_write"] = 0;

  _int_map["read_request_begin_vc"] = 0;
  _int_map["read_request_end_vc"] = 5;

  _int_map["write_request_begin_vc"] = 2;
  _int_map["write_request_end_vc"] = 7;

  _int_map["read_reply_begin_vc"] = 8;
  _int_map["read_reply_end_vc"] = 13;

  _int_map["write_reply_begin_vc"] = 10;
  _int_map["write_reply_end_vc"] = 15;

  // Physical sub-networks
  _int_map["physical_subnetworks"] = 1;

  // Control Injection of Packets into Replicated Networks
  _int_map["read_request_subnet"] = 0;

  _int_map["read_reply_subnet"] = 0;

  _int_map["write_request_subnet"] = 0;

  _int_map["write_reply_subnet"] = 0;

  // TCC Simulation Traffic Trace
  AddStrField( "trace_file", "trace-file.txt" ) ;

  //==== Topology options =======================
  //important
  AddStrField( "topology", "torus" );
  _int_map["k"] = 8; //network radix
  _int_map["n"] = 2; //network dimension
  _int_map["c"] = 1; //concentration
  AddStrField( "routing_function", "none" );
  _int_map["use_noc_latency"] = 1;

  //not critical
  _int_map["x"] = 8; //number of routers in X
  _int_map["y"] = 8; //number of routers in Y
  _int_map["xr"] = 1; //number of nodes per router in X only if c>1
  _int_map["yr"] = 1; //number of nodes per router in Y only if c>1
  _int_map["limit"] = 0; //how many of the nodes are actually used

  _int_map["link_failures"] = 0; //legacy
  _int_map["fail_seed"]     = 0; //legacy

  //==== Cmesh topology options =======================
  _int_map["express_channels"] = 0; //for Cmesh only, 0=no express channels
  //==== Single-node options ===============================

  _int_map["in_ports"]  = 5;
  _int_map["out_ports"] = 5;
  _int_map["voq"] = 0; //output queuing

  //========================================================
  // Router options
  //========================================================

  //==== General options ===================================

  AddStrField( "router", "iq" );

  _int_map["output_delay"] = 0;
  _int_map["credit_delay"] = 0;
  _float_map["internal_speedup"] = 1.0;

  //==== Input-queued ======================================

  // Control of virtual channel speculation
  _int_map["speculative"] = 0 ;

  // what to use to inhibit speculative allocator grants?
  AddStrField("filter_spec_grants", "confl_nonspec_gnts");

  _int_map["num_vcs"]         = 16;
  _int_map["vc_buf_size"]     = 8;

  _int_map["wait_for_tail_credit"] = 0; // reallocate a VC before a tail credit?
  _int_map["vc_busy_when_full"] = 0; // mark VCs as in use when they have no credit available
  _int_map["vc_priority_donation"] = 0; // allow high-priority flits to donate their priority to low-priority that they are queued up behind
  _int_map["replies_inherit_priority"] = 0; // whenusing request-reply traffic (use_read_write=1) with age-based priority, make replies inherit their corresponding requests' age

  _int_map["hold_switch_for_packet"] = 0; // hold a switch config for the entire packet

  _int_map["input_speedup"]     = 1;  // expansion of input ports into crossbar
  _int_map["output_speedup"]    = 1;  // expansion of output ports into crossbar

  _int_map["routing_delay"]    = 0;
  _int_map["vc_alloc_delay"]   = 0;
  _int_map["sw_alloc_delay"]   = 0;
  _int_map["st_prepare_delay"] = 0;
  _int_map["st_final_delay"]   = 0;

  //==== Event-driven =====================================

  _int_map["vct"] = 0;

  //==== Allocators ========================================

  AddStrField( "vc_allocator", "islip" );
  AddStrField( "sw_allocator", "islip" );

  AddStrField( "vc_alloc_arb_type", "round_robin" );
  AddStrField( "sw_alloc_arb_type", "round_robin" );

  _int_map["alloc_iters"] = 1;

  // dub: allow setting the number of iterations for each allocator separately
  // (a value of 0 indicates it should inherit its value from alloc_iters)
  _int_map["vc_alloc_iters"] = 0;
  _int_map["sw_alloc_iters"] = 0;

  //==== Traffic ========================================

  AddStrField( "traffic", "uniform" );

  _int_map["perm_seed"] = 0;         // seed value for random permuation trafficpattern generator

  _float_map["injection_rate"]       = 0.1; //if 0.0 assumes it is batch mode
  _int_map["injection_rate_uses_flits"] = 0;

  _int_map["const_flits_per_packet"] = 1; //use  read_request_size etc insted

  AddStrField( "injection_process", "bernoulli" );

  _float_map["burst_alpha"] = 0.5; // burst interval
  _float_map["burst_beta"]  = 0.5; // burst length

  AddStrField( "priority", "none" );  // message priorities

  _int_map["batch_size"] = 1000;
  _int_map["batch_count"] = 1;
  _int_map["max_outstanding_requests"] = 4;

  _int_map["read_request_size"]  = 1; //flit per packet
  _int_map["write_request_size"] = 1; //flit per packet
  _int_map["read_reply_size"]    = 1; //flit per packet
  _int_map["write_reply_size"]   = 1; //flit per packet

  //==== Simulation parameters ==========================

  // types:
  //   latency    - average + latency distribution for a particular injection rate
  //   throughput - sustained throughput for a particular injection rate

  AddStrField( "sim_type", "latency" );

  _int_map["warmup_periods"] = 3; // number of samples periods to "warm-up" the simulation

  _int_map["sample_period"] = 1000; // how long between measurements
  _int_map["max_samples"]   = 10;   // maximum number of sample periods in a simulation

  _float_map["latency_thres"] = 500.0; // if avg. latency exceeds the threshold, assume unstable
  _float_map["warmup_thres"] = 0.05; // consider warmed up once relative change in latency and throughput between successive iterations is smaller than this

  // consider converged once relative change in latency / throughput between successive iterations is smaller than this
  _float_map["stopping_thres"] = 0.05;
  _float_map["acc_stopping_thres"] = 0.05;

  _int_map["sim_count"]     = 1;   // number of simulations to perform

  _int_map["include_queuing"] =1; // non-zero includes source queuing latency

  //  _int_map["reorder"]         = 0;  // know what you're doing

  //_int_map["flit_timing"]     = 0;  // know what you're doing
  //_int_map["split_packets"]   = 0;  // know what you're doing

  _int_map["seed"]            = 0; //random seed for simulation, e.g. traffic

  _int_map["print_activity"] = 0;

  _int_map["print_csv_results"] = 0;
  _int_map["print_vc_stats"] = 0;

  _int_map["drain_measured_only"] = 0;

  _int_map["viewer_trace"] = 0;

  AddStrField("watch_file", "");
  AddStrField("watch_out", "");

  AddStrField("stats_out", "");
  AddStrField("flow_out", "");

  //==================Power model params=====================
  _int_map["sim_power"] = 0;
  AddStrField("power_output_file","pwr_tmp");
  AddStrField("tech_file", "../utils/temp");
  _int_map["channel_width"] = 128;
  _int_map["channel_sweep"] = 0;

  //==================Network file===========================
  AddStrField("network_file","");
}

//A list of important simulator for the booksim gui, anything else not listed here is still included
//but just not very organized
vector< pair<string, vector< string> > > *BookSimConfig::GetImportantMap(){
  //Vector of 5 categories, each category is a vector of potions. Maps don't work because it autosorts
  vector< pair<string, vector< string> > > *important = new  vector< pair<string, vector< string> > >;
  important->push_back( make_pair( "Topology", vector<string>() ));
  (*important)[0].second.push_back("topology");
  (*important)[0].second.push_back("k");
  (*important)[0].second.push_back("n");
  (*important)[0].second.push_back("c");
  (*important)[0].second.push_back( "routing_function");
  (*important)[0].second.push_back("use_noc_latency");

  important->push_back(make_pair("Router", vector<string>()));
  (*important)[1].second.push_back("router");
  (*important)[1].second.push_back("num_vcs");
  (*important)[1].second.push_back("vc_buf_size");
  (*important)[1].second.push_back("routing_delay");
  (*important)[1].second.push_back("vc_alloc_delay");
  (*important)[1].second.push_back("sw_alloc_delay");
  (*important)[1].second.push_back("st_prepare_delay");
  (*important)[1].second.push_back("st_final_delay");

  important->push_back(make_pair("Allocator", vector<string>()));
  (*important)[2].second.push_back("vc_allocator");
  (*important)[2].second.push_back("vc_alloc_arb_type");
  (*important)[2].second.push_back("sw_allocator");
  (*important)[2].second.push_back("sw_alloc_arb_type");
  (*important)[2].second.push_back( "priority");
  (*important)[2].second.push_back("speculative");

  important->push_back(make_pair("Simulation", vector<string>()));
 (*important)[3].second.push_back("traffic");
 (*important)[3].second.push_back("injection_rate");
 (*important)[3].second.push_back("injection_rate_uses_flits");
 (*important)[3].second.push_back("sim_type");
 (*important)[3].second.push_back("latency_thres");
 (*important)[3].second.push_back("const_flits_per_packet");
 (*important)[3].second.push_back("injection_process");
 (*important)[3].second.push_back("sample_period");

  important->push_back(make_pair("Statistics", vector<string>()));
  (*important)[4].second.push_back("print_activity");
  (*important)[4].second.push_back("print_csv_results");
  (*important)[4].second.push_back("print_vc_stats");
  (*important)[4].second.push_back("stats_out");
  (*important)[4].second.push_back("sim_power");
  (*important)[4].second.push_back("power_output_file");

  return important;
}

PowerConfig::PowerConfig( )
{

  _int_map["H_INVD2"] = 0;
  _int_map["W_INVD2"] = 0;
  _int_map["H_DFQD1"] = 0;
  _int_map["W_DFQD1"] = 0;
  _int_map["H_ND2D1"] = 0;
  _int_map["W_ND2D1"] = 0;
  _int_map["H_SRAM"] = 0;
  _int_map["W_SRAM"] = 0;
  _float_map["Vdd"] = 0;
  _float_map["R"] = 0;
  _float_map["IoffSRAM"] = 0;
  _float_map["IoffP"] = 0;
  _float_map["IoffN"] = 0;
  _float_map["Cg_pwr"] = 0;
  _float_map["Cd_pwr"] = 0;
  _float_map["Cgdl"] = 0;
  _float_map["Cg"] = 0;
  _float_map["Cd"] = 0;
  _float_map["LAMBDA"] = 0;
  _float_map["MetalPitch"] = 0;
  _float_map["Rw"] = 0;
  _float_map["Cw_gnd"] = 0;
  _float_map["Cw_cpl"] = 0;
  _float_map["wire_length"] = 0;

}
<commit_msg>use sane default for router configuration<commit_after>// $Id$

/*
Copyright (c) 2007-2009, Trustees of The Leland Stanford Junior University
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
Neither the name of the Stanford University nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/*booksim_config.cpp
 *
 *Contains all the configurable parameters in a network
 *
 */

#include "booksim.hpp"
#include "booksim_config.hpp"

BookSimConfig::BookSimConfig( )
{
  //========================================================
  // Network options
  //========================================================

  // Channel length listing file
  AddStrField( "channel_file", "" ) ;

  // Use read/write request reply scheme

  _int_map["use_read_write"] = 0;

  _int_map["read_request_begin_vc"] = 0;
  _int_map["read_request_end_vc"] = 5;

  _int_map["write_request_begin_vc"] = 2;
  _int_map["write_request_end_vc"] = 7;

  _int_map["read_reply_begin_vc"] = 8;
  _int_map["read_reply_end_vc"] = 13;

  _int_map["write_reply_begin_vc"] = 10;
  _int_map["write_reply_end_vc"] = 15;

  // Physical sub-networks
  _int_map["physical_subnetworks"] = 1;

  // Control Injection of Packets into Replicated Networks
  _int_map["read_request_subnet"] = 0;

  _int_map["read_reply_subnet"] = 0;

  _int_map["write_request_subnet"] = 0;

  _int_map["write_reply_subnet"] = 0;

  // TCC Simulation Traffic Trace
  AddStrField( "trace_file", "trace-file.txt" ) ;

  //==== Topology options =======================
  //important
  AddStrField( "topology", "torus" );
  _int_map["k"] = 8; //network radix
  _int_map["n"] = 2; //network dimension
  _int_map["c"] = 1; //concentration
  AddStrField( "routing_function", "none" );
  _int_map["use_noc_latency"] = 1;

  //not critical
  _int_map["x"] = 8; //number of routers in X
  _int_map["y"] = 8; //number of routers in Y
  _int_map["xr"] = 1; //number of nodes per router in X only if c>1
  _int_map["yr"] = 1; //number of nodes per router in Y only if c>1
  _int_map["limit"] = 0; //how many of the nodes are actually used

  _int_map["link_failures"] = 0; //legacy
  _int_map["fail_seed"]     = 0; //legacy

  //==== Cmesh topology options =======================
  _int_map["express_channels"] = 0; //for Cmesh only, 0=no express channels
  //==== Single-node options ===============================

  _int_map["in_ports"]  = 5;
  _int_map["out_ports"] = 5;
  _int_map["voq"] = 0; //output queuing

  //========================================================
  // Router options
  //========================================================

  //==== General options ===================================

  AddStrField( "router", "iq" );

  _int_map["output_delay"] = 0;
  _int_map["credit_delay"] = 0;
  _float_map["internal_speedup"] = 1.0;

  //==== Input-queued ======================================

  // Control of virtual channel speculation
  _int_map["speculative"] = 0 ;

  // what to use to inhibit speculative allocator grants?
  AddStrField("filter_spec_grants", "confl_nonspec_gnts");

  _int_map["num_vcs"]         = 16;
  _int_map["vc_buf_size"]     = 8;

  _int_map["wait_for_tail_credit"] = 0; // reallocate a VC before a tail credit?
  _int_map["vc_busy_when_full"] = 0; // mark VCs as in use when they have no credit available
  _int_map["vc_priority_donation"] = 0; // allow high-priority flits to donate their priority to low-priority that they are queued up behind
  _int_map["replies_inherit_priority"] = 0; // whenusing request-reply traffic (use_read_write=1) with age-based priority, make replies inherit their corresponding requests' age

  _int_map["hold_switch_for_packet"] = 0; // hold a switch config for the entire packet

  _int_map["input_speedup"]     = 1;  // expansion of input ports into crossbar
  _int_map["output_speedup"]    = 1;  // expansion of output ports into crossbar

  _int_map["routing_delay"]    = 1;
  _int_map["vc_alloc_delay"]   = 1;
  _int_map["sw_alloc_delay"]   = 1;
  _int_map["st_prepare_delay"] = 0;
  _int_map["st_final_delay"]   = 1;

  //==== Event-driven =====================================

  _int_map["vct"] = 0;

  //==== Allocators ========================================

  AddStrField( "vc_allocator", "islip" );
  AddStrField( "sw_allocator", "islip" );

  AddStrField( "vc_alloc_arb_type", "round_robin" );
  AddStrField( "sw_alloc_arb_type", "round_robin" );

  _int_map["alloc_iters"] = 1;

  // dub: allow setting the number of iterations for each allocator separately
  // (a value of 0 indicates it should inherit its value from alloc_iters)
  _int_map["vc_alloc_iters"] = 0;
  _int_map["sw_alloc_iters"] = 0;

  //==== Traffic ========================================

  AddStrField( "traffic", "uniform" );

  _int_map["perm_seed"] = 0;         // seed value for random permuation trafficpattern generator

  _float_map["injection_rate"]       = 0.1; //if 0.0 assumes it is batch mode
  _int_map["injection_rate_uses_flits"] = 0;

  _int_map["const_flits_per_packet"] = 1; //use  read_request_size etc insted

  AddStrField( "injection_process", "bernoulli" );

  _float_map["burst_alpha"] = 0.5; // burst interval
  _float_map["burst_beta"]  = 0.5; // burst length

  AddStrField( "priority", "none" );  // message priorities

  _int_map["batch_size"] = 1000;
  _int_map["batch_count"] = 1;
  _int_map["max_outstanding_requests"] = 4;

  _int_map["read_request_size"]  = 1; //flit per packet
  _int_map["write_request_size"] = 1; //flit per packet
  _int_map["read_reply_size"]    = 1; //flit per packet
  _int_map["write_reply_size"]   = 1; //flit per packet

  //==== Simulation parameters ==========================

  // types:
  //   latency    - average + latency distribution for a particular injection rate
  //   throughput - sustained throughput for a particular injection rate

  AddStrField( "sim_type", "latency" );

  _int_map["warmup_periods"] = 3; // number of samples periods to "warm-up" the simulation

  _int_map["sample_period"] = 1000; // how long between measurements
  _int_map["max_samples"]   = 10;   // maximum number of sample periods in a simulation

  _float_map["latency_thres"] = 500.0; // if avg. latency exceeds the threshold, assume unstable
  _float_map["warmup_thres"] = 0.05; // consider warmed up once relative change in latency and throughput between successive iterations is smaller than this

  // consider converged once relative change in latency / throughput between successive iterations is smaller than this
  _float_map["stopping_thres"] = 0.05;
  _float_map["acc_stopping_thres"] = 0.05;

  _int_map["sim_count"]     = 1;   // number of simulations to perform

  _int_map["include_queuing"] =1; // non-zero includes source queuing latency

  //  _int_map["reorder"]         = 0;  // know what you're doing

  //_int_map["flit_timing"]     = 0;  // know what you're doing
  //_int_map["split_packets"]   = 0;  // know what you're doing

  _int_map["seed"]            = 0; //random seed for simulation, e.g. traffic

  _int_map["print_activity"] = 0;

  _int_map["print_csv_results"] = 0;
  _int_map["print_vc_stats"] = 0;

  _int_map["drain_measured_only"] = 0;

  _int_map["viewer_trace"] = 0;

  AddStrField("watch_file", "");
  AddStrField("watch_out", "");

  AddStrField("stats_out", "");
  AddStrField("flow_out", "");

  //==================Power model params=====================
  _int_map["sim_power"] = 0;
  AddStrField("power_output_file","pwr_tmp");
  AddStrField("tech_file", "../utils/temp");
  _int_map["channel_width"] = 128;
  _int_map["channel_sweep"] = 0;

  //==================Network file===========================
  AddStrField("network_file","");
}

//A list of important simulator for the booksim gui, anything else not listed here is still included
//but just not very organized
vector< pair<string, vector< string> > > *BookSimConfig::GetImportantMap(){
  //Vector of 5 categories, each category is a vector of potions. Maps don't work because it autosorts
  vector< pair<string, vector< string> > > *important = new  vector< pair<string, vector< string> > >;
  important->push_back( make_pair( "Topology", vector<string>() ));
  (*important)[0].second.push_back("topology");
  (*important)[0].second.push_back("k");
  (*important)[0].second.push_back("n");
  (*important)[0].second.push_back("c");
  (*important)[0].second.push_back( "routing_function");
  (*important)[0].second.push_back("use_noc_latency");

  important->push_back(make_pair("Router", vector<string>()));
  (*important)[1].second.push_back("router");
  (*important)[1].second.push_back("num_vcs");
  (*important)[1].second.push_back("vc_buf_size");
  (*important)[1].second.push_back("routing_delay");
  (*important)[1].second.push_back("vc_alloc_delay");
  (*important)[1].second.push_back("sw_alloc_delay");
  (*important)[1].second.push_back("st_prepare_delay");
  (*important)[1].second.push_back("st_final_delay");

  important->push_back(make_pair("Allocator", vector<string>()));
  (*important)[2].second.push_back("vc_allocator");
  (*important)[2].second.push_back("vc_alloc_arb_type");
  (*important)[2].second.push_back("sw_allocator");
  (*important)[2].second.push_back("sw_alloc_arb_type");
  (*important)[2].second.push_back( "priority");
  (*important)[2].second.push_back("speculative");

  important->push_back(make_pair("Simulation", vector<string>()));
 (*important)[3].second.push_back("traffic");
 (*important)[3].second.push_back("injection_rate");
 (*important)[3].second.push_back("injection_rate_uses_flits");
 (*important)[3].second.push_back("sim_type");
 (*important)[3].second.push_back("latency_thres");
 (*important)[3].second.push_back("const_flits_per_packet");
 (*important)[3].second.push_back("injection_process");
 (*important)[3].second.push_back("sample_period");

  important->push_back(make_pair("Statistics", vector<string>()));
  (*important)[4].second.push_back("print_activity");
  (*important)[4].second.push_back("print_csv_results");
  (*important)[4].second.push_back("print_vc_stats");
  (*important)[4].second.push_back("stats_out");
  (*important)[4].second.push_back("sim_power");
  (*important)[4].second.push_back("power_output_file");

  return important;
}

PowerConfig::PowerConfig( )
{

  _int_map["H_INVD2"] = 0;
  _int_map["W_INVD2"] = 0;
  _int_map["H_DFQD1"] = 0;
  _int_map["W_DFQD1"] = 0;
  _int_map["H_ND2D1"] = 0;
  _int_map["W_ND2D1"] = 0;
  _int_map["H_SRAM"] = 0;
  _int_map["W_SRAM"] = 0;
  _float_map["Vdd"] = 0;
  _float_map["R"] = 0;
  _float_map["IoffSRAM"] = 0;
  _float_map["IoffP"] = 0;
  _float_map["IoffN"] = 0;
  _float_map["Cg_pwr"] = 0;
  _float_map["Cd_pwr"] = 0;
  _float_map["Cgdl"] = 0;
  _float_map["Cg"] = 0;
  _float_map["Cd"] = 0;
  _float_map["LAMBDA"] = 0;
  _float_map["MetalPitch"] = 0;
  _float_map["Rw"] = 0;
  _float_map["Cw_gnd"] = 0;
  _float_map["Cw_cpl"] = 0;
  _float_map["wire_length"] = 0;

}
<|endoftext|>


<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                           License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved.
// Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// @Authors
//    Fangfang Bai, fangfang@multicorewareinc.com
//    Jin Ma,       jin@multicorewareinc.com
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//
//   * The name of the copyright holders may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors as is and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/

#include "../perf_precomp.hpp"
#include "opencv2/ts/ocl_perf.hpp"

#ifdef HAVE_OPENCL

namespace opencv_test {
namespace ocl {

typedef tuple<Size, MatType, int> FilterParams;
typedef TestBaseWithParam<FilterParams> FilterFixture;

///////////// Blur ////////////////////////

typedef FilterFixture BlurFixture;

OCL_PERF_TEST_P(BlurFixture, Blur,
                ::testing::Combine(OCL_TEST_SIZES, OCL_TEST_TYPES, OCL_PERF_ENUM(3, 5)))
{
    const FilterParams params = GetParam();
    const Size srcSize = get<0>(params);
    const int type = get<1>(params), ksize = get<2>(params), bordertype = BORDER_CONSTANT;
    const double eps = CV_MAT_DEPTH(type) <= CV_32S ? 1 : 1e-5;

    checkDeviceMaxMemoryAllocSize(srcSize, type);

    UMat src(srcSize, type), dst(srcSize, type);
    declare.in(src, WARMUP_RNG).out(dst);

    OCL_TEST_CYCLE() cv::blur(src, dst, Size(ksize, ksize), Point(-1, -1), bordertype);

    SANITY_CHECK(dst, eps);
}

///////////// SqrBoxFilter ////////////////////////

typedef tuple<Size, MatType, Size> SqrBoxFilterParams;
typedef TestBaseWithParam<SqrBoxFilterParams> SqrBoxFilterFixture;

OCL_PERF_TEST_P(SqrBoxFilterFixture, SqrBoxFilter,
                ::testing::Combine(OCL_TEST_SIZES, OCL_PERF_ENUM(CV_8UC1, CV_8UC4, CV_32FC1, CV_32FC4),
                                   OCL_PERF_ENUM(Size(3, 3), Size(20, 3), Size(3, 20), Size(20, 20))))
{
    const SqrBoxFilterParams params = GetParam();
    const Size srcSize = get<0>(params), ksize = get<2>(params);
    const int type = get<1>(params), depth = CV_MAT_DEPTH(type),
            ddepth = depth == CV_8U ? CV_32S : CV_32F;
    const double eps = ddepth == CV_32S ? 0 : 5e-5;

    checkDeviceMaxMemoryAllocSize(srcSize, CV_MAKE_TYPE(ddepth, CV_MAT_CN(type)));

    UMat src(srcSize, type), dst(srcSize, type);
    declare.in(src, WARMUP_RNG).out(dst);

    OCL_TEST_CYCLE() cv::sqrBoxFilter(src, dst, ddepth, ksize, Point(-1, -1), false);

    SANITY_CHECK(dst, eps);
}

///////////// Laplacian////////////////////////

typedef FilterFixture LaplacianFixture;

OCL_PERF_TEST_P(LaplacianFixture, Laplacian,
                ::testing::Combine(OCL_TEST_SIZES, OCL_TEST_TYPES, OCL_PERF_ENUM(3, 5)))
{
    const FilterParams params = GetParam();
    const Size srcSize = get<0>(params);
    const int type = get<1>(params), ksize = get<2>(params);
    const double eps = CV_MAT_DEPTH(type) <= CV_32S ? 1 : 2e-5;

    checkDeviceMaxMemoryAllocSize(srcSize, type);

    UMat src(srcSize, type), dst(srcSize, type);
    declare.in(src, WARMUP_RNG).out(dst);

    OCL_TEST_CYCLE() cv::Laplacian(src, dst, -1, ksize, 1);

    SANITY_CHECK(dst, eps);
}

///////////// Erode ////////////////////

typedef FilterFixture ErodeFixture;

OCL_PERF_TEST_P(ErodeFixture, Erode,
            ::testing::Combine(OCL_TEST_SIZES, OCL_TEST_TYPES, OCL_PERF_ENUM(3, 5)))
{
    const FilterParams params = GetParam();
    const Size srcSize = get<0>(params);
    const int type = get<1>(params), ksize = get<2>(params);
    const Mat ker = getStructuringElement(MORPH_RECT, Size(ksize, ksize));

    checkDeviceMaxMemoryAllocSize(srcSize, type);

    UMat src(srcSize, type), dst(srcSize, type);
    declare.in(src, WARMUP_RNG).out(dst).in(ker);

    OCL_TEST_CYCLE() cv::erode(src, dst, ker);

    SANITY_CHECK(dst);
}

///////////// Dilate ////////////////////

typedef FilterFixture DilateFixture;

OCL_PERF_TEST_P(DilateFixture, Dilate,
            ::testing::Combine(OCL_TEST_SIZES, OCL_TEST_TYPES, OCL_PERF_ENUM(3, 5)))
{
    const FilterParams params = GetParam();
    const Size srcSize = get<0>(params);
    const int type = get<1>(params), ksize = get<2>(params);
    const Mat ker = getStructuringElement(MORPH_RECT, Size(ksize, ksize));

    checkDeviceMaxMemoryAllocSize(srcSize, type);

    UMat src(srcSize, type), dst(srcSize, type);
    declare.in(src, WARMUP_RNG).out(dst).in(ker);

    OCL_TEST_CYCLE() cv::dilate(src, dst, ker);

    SANITY_CHECK(dst);
}

///////////// MorphologyEx ////////////////////////

CV_ENUM(MorphOp, MORPH_OPEN, MORPH_CLOSE, MORPH_GRADIENT, MORPH_TOPHAT, MORPH_BLACKHAT)

typedef tuple<Size, MatType, MorphOp, int> MorphologyExParams;
typedef TestBaseWithParam<MorphologyExParams> MorphologyExFixture;

OCL_PERF_TEST_P(MorphologyExFixture, MorphologyEx,
                ::testing::Combine(OCL_TEST_SIZES, OCL_TEST_TYPES, MorphOp::all(), OCL_PERF_ENUM(3, 5)))
{
    const MorphologyExParams params = GetParam();
    const Size srcSize = get<0>(params);
    const int type = get<1>(params), op = get<2>(params), ksize = get<3>(params);
    const Mat ker = getStructuringElement(MORPH_RECT, Size(ksize, ksize));

    checkDeviceMaxMemoryAllocSize(srcSize, type);

    UMat src(srcSize, type), dst(srcSize, type);
    declare.in(src, WARMUP_RNG).out(dst).in(ker);

    OCL_TEST_CYCLE() cv::morphologyEx(src, dst, op, ker);

    SANITY_CHECK(dst);
}

///////////// Sobel ////////////////////////

typedef Size_MatType SobelFixture;

OCL_PERF_TEST_P(SobelFixture, Sobel,
            ::testing::Combine(OCL_TEST_SIZES, OCL_TEST_TYPES))
{
    const Size_MatType_t params = GetParam();
    const Size srcSize = get<0>(params);
    const int type = get<1>(params), dx = 1, dy = 1;

    checkDeviceMaxMemoryAllocSize(srcSize, type, sizeof(float) * 2);

    UMat src(srcSize, type), dst(srcSize, type);
    declare.in(src, WARMUP_RNG).out(dst);

    OCL_TEST_CYCLE() cv::Sobel(src, dst, -1, dx, dy);

    SANITY_CHECK(dst, 1e-6);
}

///////////// Scharr ////////////////////////

typedef Size_MatType ScharrFixture;

OCL_PERF_TEST_P(ScharrFixture, Scharr,
            ::testing::Combine(OCL_TEST_SIZES, OCL_TEST_TYPES))
{
    const Size_MatType_t params = GetParam();
    const Size srcSize = get<0>(params);
    const int type = get<1>(params), dx = 1, dy = 0;
    const double eps = CV_MAT_DEPTH(type) <= CV_32S ? 1 : 1e-5;

    checkDeviceMaxMemoryAllocSize(srcSize, type, sizeof(float) * 2);

    UMat src(srcSize, type), dst(srcSize, type);
    declare.in(src, WARMUP_RNG).out(dst);

    OCL_TEST_CYCLE() cv::Scharr(src, dst, -1, dx, dy);

    SANITY_CHECK(dst, eps);
}

///////////// GaussianBlur ////////////////////////

typedef FilterFixture GaussianBlurFixture;

OCL_PERF_TEST_P(GaussianBlurFixture, GaussianBlur,
            ::testing::Combine(OCL_TEST_SIZES, OCL_TEST_TYPES, OCL_PERF_ENUM(3, 5, 7)))
{
    const FilterParams params = GetParam();
    const Size srcSize = get<0>(params);
    const int type = get<1>(params), ksize = get<2>(params);
    const double eps = CV_MAT_DEPTH(type) <= CV_32S ? 2 + DBL_EPSILON : 3e-4;

    checkDeviceMaxMemoryAllocSize(srcSize, type);

    UMat src(srcSize, type), dst(srcSize, type);
    declare.in(src, WARMUP_RNG).out(dst);

    OCL_TEST_CYCLE() cv::GaussianBlur(src, dst, Size(ksize, ksize), 1, 1, cv::BORDER_CONSTANT);

    SANITY_CHECK(dst, eps);
}

///////////// Filter2D ////////////////////////

typedef FilterFixture Filter2DFixture;

OCL_PERF_TEST_P(Filter2DFixture, Filter2D,
            ::testing::Combine(OCL_TEST_SIZES, OCL_TEST_TYPES, OCL_PERF_ENUM(3, 5)))
{
    const FilterParams params = GetParam();
    const Size srcSize = get<0>(params);
    const int type = get<1>(params), ksize = get<2>(params);
    const double eps = CV_MAT_DEPTH(type) <= CV_32S ? 1 : 1e-5;

    checkDeviceMaxMemoryAllocSize(srcSize, type);

    UMat src(srcSize, type), dst(srcSize, type);
    Mat kernel(ksize, ksize, CV_32SC1);
    declare.in(src, WARMUP_RNG).in(kernel).out(dst);
    randu(kernel, -3.0, 3.0);

    OCL_TEST_CYCLE() cv::filter2D(src, dst, -1, kernel);

    SANITY_CHECK(dst, eps);
}

///////////// Bilateral ////////////////////////

typedef TestBaseWithParam<Size> BilateralFixture;

OCL_PERF_TEST_P(BilateralFixture, Bilateral, OCL_TEST_SIZES)
{
    const Size srcSize = GetParam();
    const int d = 7;
    const double sigmacolor = 50.0, sigmaspace = 50.0;

    checkDeviceMaxMemoryAllocSize(srcSize, CV_8UC1);

    UMat src(srcSize, CV_8UC1), dst(srcSize, CV_8UC1);
    declare.in(src, WARMUP_RNG).out(dst);

    OCL_TEST_CYCLE() cv::bilateralFilter(src, dst, d, sigmacolor, sigmaspace);

    SANITY_CHECK(dst);
}

///////////// MedianBlur ////////////////////////

typedef tuple<Size, int> MedianBlurParams;
typedef TestBaseWithParam<MedianBlurParams> MedianBlurFixture;

OCL_PERF_TEST_P(MedianBlurFixture, Bilateral, ::testing::Combine(OCL_TEST_SIZES, OCL_PERF_ENUM(3, 5)))
{
    MedianBlurParams params = GetParam();
    const Size srcSize = get<0>(params);
    const int ksize = get<1>(params);

    checkDeviceMaxMemoryAllocSize(srcSize, CV_8UC1);

    UMat src(srcSize, CV_8UC1), dst(srcSize, CV_8UC1);
    declare.in(src, WARMUP_RNG).out(dst);

    OCL_TEST_CYCLE() cv::medianBlur(src, dst, ksize);

    SANITY_CHECK(dst);
}

} } // namespace opencv_test::ocl

#endif // HAVE_OPENCL
<commit_msg>imgproc(perf): add GaussianBlur cases for SIFT<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                           License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved.
// Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// @Authors
//    Fangfang Bai, fangfang@multicorewareinc.com
//    Jin Ma,       jin@multicorewareinc.com
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//
//   * The name of the copyright holders may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors as is and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/

#include "../perf_precomp.hpp"
#include "opencv2/ts/ocl_perf.hpp"

#ifdef HAVE_OPENCL

namespace opencv_test {
namespace ocl {

typedef tuple<Size, MatType, int> FilterParams;
typedef TestBaseWithParam<FilterParams> FilterFixture;

///////////// Blur ////////////////////////

typedef FilterFixture BlurFixture;

OCL_PERF_TEST_P(BlurFixture, Blur,
                ::testing::Combine(OCL_TEST_SIZES, OCL_TEST_TYPES, OCL_PERF_ENUM(3, 5)))
{
    const FilterParams params = GetParam();
    const Size srcSize = get<0>(params);
    const int type = get<1>(params), ksize = get<2>(params), bordertype = BORDER_CONSTANT;
    const double eps = CV_MAT_DEPTH(type) <= CV_32S ? 1 : 1e-5;

    checkDeviceMaxMemoryAllocSize(srcSize, type);

    UMat src(srcSize, type), dst(srcSize, type);
    declare.in(src, WARMUP_RNG).out(dst);

    OCL_TEST_CYCLE() cv::blur(src, dst, Size(ksize, ksize), Point(-1, -1), bordertype);

    SANITY_CHECK(dst, eps);
}

///////////// SqrBoxFilter ////////////////////////

typedef tuple<Size, MatType, Size> SqrBoxFilterParams;
typedef TestBaseWithParam<SqrBoxFilterParams> SqrBoxFilterFixture;

OCL_PERF_TEST_P(SqrBoxFilterFixture, SqrBoxFilter,
                ::testing::Combine(OCL_TEST_SIZES, OCL_PERF_ENUM(CV_8UC1, CV_8UC4, CV_32FC1, CV_32FC4),
                                   OCL_PERF_ENUM(Size(3, 3), Size(20, 3), Size(3, 20), Size(20, 20))))
{
    const SqrBoxFilterParams params = GetParam();
    const Size srcSize = get<0>(params), ksize = get<2>(params);
    const int type = get<1>(params), depth = CV_MAT_DEPTH(type),
            ddepth = depth == CV_8U ? CV_32S : CV_32F;
    const double eps = ddepth == CV_32S ? 0 : 5e-5;

    checkDeviceMaxMemoryAllocSize(srcSize, CV_MAKE_TYPE(ddepth, CV_MAT_CN(type)));

    UMat src(srcSize, type), dst(srcSize, type);
    declare.in(src, WARMUP_RNG).out(dst);

    OCL_TEST_CYCLE() cv::sqrBoxFilter(src, dst, ddepth, ksize, Point(-1, -1), false);

    SANITY_CHECK(dst, eps);
}

///////////// Laplacian////////////////////////

typedef FilterFixture LaplacianFixture;

OCL_PERF_TEST_P(LaplacianFixture, Laplacian,
                ::testing::Combine(OCL_TEST_SIZES, OCL_TEST_TYPES, OCL_PERF_ENUM(3, 5)))
{
    const FilterParams params = GetParam();
    const Size srcSize = get<0>(params);
    const int type = get<1>(params), ksize = get<2>(params);
    const double eps = CV_MAT_DEPTH(type) <= CV_32S ? 1 : 2e-5;

    checkDeviceMaxMemoryAllocSize(srcSize, type);

    UMat src(srcSize, type), dst(srcSize, type);
    declare.in(src, WARMUP_RNG).out(dst);

    OCL_TEST_CYCLE() cv::Laplacian(src, dst, -1, ksize, 1);

    SANITY_CHECK(dst, eps);
}

///////////// Erode ////////////////////

typedef FilterFixture ErodeFixture;

OCL_PERF_TEST_P(ErodeFixture, Erode,
            ::testing::Combine(OCL_TEST_SIZES, OCL_TEST_TYPES, OCL_PERF_ENUM(3, 5)))
{
    const FilterParams params = GetParam();
    const Size srcSize = get<0>(params);
    const int type = get<1>(params), ksize = get<2>(params);
    const Mat ker = getStructuringElement(MORPH_RECT, Size(ksize, ksize));

    checkDeviceMaxMemoryAllocSize(srcSize, type);

    UMat src(srcSize, type), dst(srcSize, type);
    declare.in(src, WARMUP_RNG).out(dst).in(ker);

    OCL_TEST_CYCLE() cv::erode(src, dst, ker);

    SANITY_CHECK(dst);
}

///////////// Dilate ////////////////////

typedef FilterFixture DilateFixture;

OCL_PERF_TEST_P(DilateFixture, Dilate,
            ::testing::Combine(OCL_TEST_SIZES, OCL_TEST_TYPES, OCL_PERF_ENUM(3, 5)))
{
    const FilterParams params = GetParam();
    const Size srcSize = get<0>(params);
    const int type = get<1>(params), ksize = get<2>(params);
    const Mat ker = getStructuringElement(MORPH_RECT, Size(ksize, ksize));

    checkDeviceMaxMemoryAllocSize(srcSize, type);

    UMat src(srcSize, type), dst(srcSize, type);
    declare.in(src, WARMUP_RNG).out(dst).in(ker);

    OCL_TEST_CYCLE() cv::dilate(src, dst, ker);

    SANITY_CHECK(dst);
}

///////////// MorphologyEx ////////////////////////

CV_ENUM(MorphOp, MORPH_OPEN, MORPH_CLOSE, MORPH_GRADIENT, MORPH_TOPHAT, MORPH_BLACKHAT)

typedef tuple<Size, MatType, MorphOp, int> MorphologyExParams;
typedef TestBaseWithParam<MorphologyExParams> MorphologyExFixture;

OCL_PERF_TEST_P(MorphologyExFixture, MorphologyEx,
                ::testing::Combine(OCL_TEST_SIZES, OCL_TEST_TYPES, MorphOp::all(), OCL_PERF_ENUM(3, 5)))
{
    const MorphologyExParams params = GetParam();
    const Size srcSize = get<0>(params);
    const int type = get<1>(params), op = get<2>(params), ksize = get<3>(params);
    const Mat ker = getStructuringElement(MORPH_RECT, Size(ksize, ksize));

    checkDeviceMaxMemoryAllocSize(srcSize, type);

    UMat src(srcSize, type), dst(srcSize, type);
    declare.in(src, WARMUP_RNG).out(dst).in(ker);

    OCL_TEST_CYCLE() cv::morphologyEx(src, dst, op, ker);

    SANITY_CHECK(dst);
}

///////////// Sobel ////////////////////////

typedef Size_MatType SobelFixture;

OCL_PERF_TEST_P(SobelFixture, Sobel,
            ::testing::Combine(OCL_TEST_SIZES, OCL_TEST_TYPES))
{
    const Size_MatType_t params = GetParam();
    const Size srcSize = get<0>(params);
    const int type = get<1>(params), dx = 1, dy = 1;

    checkDeviceMaxMemoryAllocSize(srcSize, type, sizeof(float) * 2);

    UMat src(srcSize, type), dst(srcSize, type);
    declare.in(src, WARMUP_RNG).out(dst);

    OCL_TEST_CYCLE() cv::Sobel(src, dst, -1, dx, dy);

    SANITY_CHECK(dst, 1e-6);
}

///////////// Scharr ////////////////////////

typedef Size_MatType ScharrFixture;

OCL_PERF_TEST_P(ScharrFixture, Scharr,
            ::testing::Combine(OCL_TEST_SIZES, OCL_TEST_TYPES))
{
    const Size_MatType_t params = GetParam();
    const Size srcSize = get<0>(params);
    const int type = get<1>(params), dx = 1, dy = 0;
    const double eps = CV_MAT_DEPTH(type) <= CV_32S ? 1 : 1e-5;

    checkDeviceMaxMemoryAllocSize(srcSize, type, sizeof(float) * 2);

    UMat src(srcSize, type), dst(srcSize, type);
    declare.in(src, WARMUP_RNG).out(dst);

    OCL_TEST_CYCLE() cv::Scharr(src, dst, -1, dx, dy);

    SANITY_CHECK(dst, eps);
}

///////////// GaussianBlur ////////////////////////

typedef FilterFixture OCL_GaussianBlurFixture;

PERF_TEST_P_(OCL_GaussianBlurFixture, GaussianBlur)
{
    const FilterParams& params = GetParam();
    const Size srcSize = get<0>(params);
    const int type = get<1>(params), ksize = get<2>(params);

    checkDeviceMaxMemoryAllocSize(srcSize, type);

    UMat src(srcSize, type), dst(srcSize, type);
    declare.in(src, WARMUP_RNG).out(dst);

    OCL_TEST_CYCLE() cv::GaussianBlur(src, dst, Size(ksize, ksize), 1, 1, cv::BORDER_CONSTANT);

    SANITY_CHECK_NOTHING();
}

INSTANTIATE_TEST_CASE_P(/*nothing*/, OCL_GaussianBlurFixture,
    ::testing::Combine(
        OCL_TEST_SIZES,
        OCL_TEST_TYPES,
        OCL_PERF_ENUM(3, 5, 7)
    )
);

INSTANTIATE_TEST_CASE_P(SIFT, OCL_GaussianBlurFixture,
    ::testing::Combine(
        ::testing::Values(sz1080p),
        ::testing::Values(CV_32FC1),
        OCL_PERF_ENUM(11, 13, 17, 21, 27)
    )
);

INSTANTIATE_TEST_CASE_P(DISABLED_FULL, OCL_GaussianBlurFixture,
    ::testing::Combine(
        ::testing::Values(sz1080p),
        ::testing::Values(
            CV_8UC1, CV_8UC2, CV_8UC3, CV_8UC4,
            CV_8SC1, CV_8SC2, CV_8SC3, CV_8SC4,
            CV_16UC1, CV_16UC2, CV_16UC3, CV_16UC4,
            CV_16SC1, CV_16SC2, CV_16SC3, CV_16SC4,
            CV_32SC1, CV_32SC2, CV_32SC3, CV_32SC4,
            CV_32FC1, CV_32FC2, CV_32FC3, CV_32FC4,
            CV_64FC1, CV_64FC2, CV_64FC3, CV_64FC4
        ),
        OCL_PERF_ENUM(3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29)
    )
);

///////////// Filter2D ////////////////////////

typedef FilterFixture Filter2DFixture;

OCL_PERF_TEST_P(Filter2DFixture, Filter2D,
            ::testing::Combine(OCL_TEST_SIZES, OCL_TEST_TYPES, OCL_PERF_ENUM(3, 5)))
{
    const FilterParams params = GetParam();
    const Size srcSize = get<0>(params);
    const int type = get<1>(params), ksize = get<2>(params);
    const double eps = CV_MAT_DEPTH(type) <= CV_32S ? 1 : 1e-5;

    checkDeviceMaxMemoryAllocSize(srcSize, type);

    UMat src(srcSize, type), dst(srcSize, type);
    Mat kernel(ksize, ksize, CV_32SC1);
    declare.in(src, WARMUP_RNG).in(kernel).out(dst);
    randu(kernel, -3.0, 3.0);

    OCL_TEST_CYCLE() cv::filter2D(src, dst, -1, kernel);

    SANITY_CHECK(dst, eps);
}

///////////// Bilateral ////////////////////////

typedef TestBaseWithParam<Size> BilateralFixture;

OCL_PERF_TEST_P(BilateralFixture, Bilateral, OCL_TEST_SIZES)
{
    const Size srcSize = GetParam();
    const int d = 7;
    const double sigmacolor = 50.0, sigmaspace = 50.0;

    checkDeviceMaxMemoryAllocSize(srcSize, CV_8UC1);

    UMat src(srcSize, CV_8UC1), dst(srcSize, CV_8UC1);
    declare.in(src, WARMUP_RNG).out(dst);

    OCL_TEST_CYCLE() cv::bilateralFilter(src, dst, d, sigmacolor, sigmaspace);

    SANITY_CHECK(dst);
}

///////////// MedianBlur ////////////////////////

typedef tuple<Size, int> MedianBlurParams;
typedef TestBaseWithParam<MedianBlurParams> MedianBlurFixture;

OCL_PERF_TEST_P(MedianBlurFixture, Bilateral, ::testing::Combine(OCL_TEST_SIZES, OCL_PERF_ENUM(3, 5)))
{
    MedianBlurParams params = GetParam();
    const Size srcSize = get<0>(params);
    const int ksize = get<1>(params);

    checkDeviceMaxMemoryAllocSize(srcSize, CV_8UC1);

    UMat src(srcSize, CV_8UC1), dst(srcSize, CV_8UC1);
    declare.in(src, WARMUP_RNG).out(dst);

    OCL_TEST_CYCLE() cv::medianBlur(src, dst, ksize);

    SANITY_CHECK(dst);
}

} } // namespace opencv_test::ocl

#endif // HAVE_OPENCL
<|endoftext|>


<commit_before>#include <stdexcept>
#include <memory>
#include <functional>
#include <algorithm>

namespace crashes {

	typedef std::function<void (int)> on_feedback;

	namespace detail {

		//////////////////////////////////////////////
		typedef std::shared_ptr<size_t> shared_number;

		////////////////////
		class simple_count {
			size_t copy_nr;
		public:

			simple_count():copy_nr(0){}

			size_t get_copy_nr() const {
				return copy_nr;
			}

			void increment() {
				++copy_nr;
			}

			bool should_have_crashed_on(size_t) {
				return false;
			}
		};

		////////////////////////////////////////////
		template <typename TSharedInt=shared_number>
		class shared_count {
			TSharedInt copy_nr;

		public:

			shared_count():copy_nr(new size_t(0)){}

			size_t get_copy_nr() const {
				return *copy_nr;
			}

			void increment() {
				++(*copy_nr);
			}

			bool should_have_crashed_on(size_t) {
				return false;
			}
		};

		////////////////////////////////////////
		struct should_decrement_on_destruction {
			static const bool should_decrement=true;
		};

		//////////////////////////////////////////
		struct shouldnt_decrement_on_destruction {
			static const bool should_decrement=false;
		};

		/////////////////////
		template <typename T,typename TDecrement>
		class total_count
		{
			static size_t count_nr;

		public:

			total_count()
			{
				increment();
			}

			size_t get_copy_nr() const {
				return count_nr;
			}

			void increment() {
				++count_nr;
			}

			bool should_have_crashed_on(size_t N) {
				return count_nr>=N;
			}

			//protected:

			~total_count()
			{
				if (TDecrement::should_decrement)
					--count_nr;
			}
		};
		template <typename T,typename TDecrement> size_t total_count<T,TDecrement>::count_nr(0);

		////////////////////////////////////////////////////////////////////////////////////////////////////
		template <size_t MaxN,typename TFeedback=on_feedback, typename TCounter=simple_count>
		struct when {
			class copies {
				TCounter counter;
				TFeedback feedback;
			public:

				copies() {
					if (counter.should_have_crashed_on(MaxN))
						throw std::runtime_error("illegal number of copies");
				}

				virtual ~copies() {} //todo: review

				copies(const copies& other):
					counter(other.counter),
					feedback(other.feedback)
				{
					counter.increment();
					size_t count=counter.get_copy_nr();
					if (feedback)
						feedback(count);
					if (count>=MaxN)
						throw std::runtime_error("illegal number of copies");
				}

				copies& operator=(copies const& other)  {
					copies tmp(other);
					swap(other);
					return *this;
				}

				void swap(copies const& other) {
					std::swap(counter,other.counter);
					std::swap(feedback,other.feedback);
				}

			public:

				void set_feedback(TFeedback const& f) {
					feedback=f;
				}

			};
			typedef copies copy;
		};
	}

	/// crashes on MaxN total number of copies
	template <size_t MaxN>
	struct on : public detail::when<MaxN,on_feedback,detail::shared_count<detail::shared_number>>
	{};

	/// crashes on MaxN'th copy
	template <size_t MaxN>
	struct after : public detail::when<MaxN,on_feedback,detail::simple_count>
	{};

	/// crashes on MaxN total instances of T
	template <size_t MaxN,typename T>
	struct on_total : public detail::when<MaxN,on_feedback,detail::total_count<T,detail::should_decrement_on_destruction>>
	{
		// instead typedef  copies instance - for gcc/standard complience
		typedef typename crashes::detail::when<MaxN, std::function<void(int)>, crashes::detail::total_count<T, crashes::detail::should_decrement_on_destruction> >::copies instances;
		typedef typename crashes::detail::when<MaxN, std::function<void(int)>, crashes::detail::total_count<T, crashes::detail::should_decrement_on_destruction> >::copies instance;
	};

	/// crashes on MaxN total instances of T
	template <size_t MaxN,typename T>
	struct after_total : public detail::when<MaxN,on_feedback,detail::total_count<T,detail::shouldnt_decrement_on_destruction>>
	{
		typedef typename crashes::detail::when<MaxN, std::function<void(int)>, crashes::detail::total_count<T, crashes::detail::shouldnt_decrement_on_destruction> >::copies instances;
		typedef typename crashes::detail::when<MaxN, std::function<void(int)>, crashes::detail::total_count<T, crashes::detail::shouldnt_decrement_on_destruction> >::copies instance;
	};
}<commit_msg>slightly shorter<commit_after>#include <stdexcept>
#include <memory>
#include <functional>
#include <algorithm>

namespace crashes {

	typedef std::function<void (int)> on_feedback;

	namespace detail {

		//////////////////////////////////////////////
		typedef std::shared_ptr<size_t> shared_number;

		////////////////////
		class simple_count {
			size_t copy_nr;
		public:

			simple_count():copy_nr(0){}

			size_t get_copy_nr() const {
				return copy_nr;
			}

			void increment() {
				++copy_nr;
			}

			bool should_have_crashed_on(size_t) {
				return false;
			}
		};

		////////////////////////////////////////////
		template <typename TSharedInt=shared_number>
		class shared_count {
			TSharedInt copy_nr;

		public:

			shared_count():copy_nr(new size_t(0)){}

			size_t get_copy_nr() const {
				return *copy_nr;
			}

			void increment() {
				++(*copy_nr);
			}

			bool should_have_crashed_on(size_t) {
				return false;
			}
		};

		////////////////////////////////////////
		struct should_decrement_on_destruction {
			static const bool should_decrement=true;
		};

		//////////////////////////////////////////
		struct shouldnt_decrement_on_destruction {
			static const bool should_decrement=false;
		};

		/////////////////////
		template <typename T,typename TDecrement>
		class total_count
		{
			static size_t count_nr;

		public:

			total_count()
			{
				increment();
			}

			size_t get_copy_nr() const {
				return count_nr;
			}

			void increment() {
				++count_nr;
			}

			bool should_have_crashed_on(size_t N) {
				return count_nr>=N;
			}

			//protected:

			~total_count()
			{
				if (TDecrement::should_decrement)
					--count_nr;
			}
		};
		template <typename T,typename TDecrement> size_t total_count<T,TDecrement>::count_nr(0);

		////////////////////////////////////////////////////////////////////////////////////////////////////
		template <size_t MaxN,typename TFeedback=on_feedback, typename TCounter=simple_count>
		struct when {
			class copies {
				TCounter counter;
				TFeedback feedback;
			public:

				copies() {
					if (counter.should_have_crashed_on(MaxN))
						throw std::runtime_error("illegal number of copies");
				}

				virtual ~copies() {} //todo: review

				copies(const copies& other):
					counter(other.counter),
					feedback(other.feedback)
				{
					counter.increment();
					size_t count=counter.get_copy_nr();
					if (feedback)
						feedback(count);
					if (count>=MaxN)
						throw std::runtime_error("illegal number of copies");
				}

				copies& operator=(copies const& other)  {
					copies tmp(other);
					swap(other);
					return *this;
				}

				void swap(copies const& other) {
					std::swap(counter,other.counter);
					std::swap(feedback,other.feedback);
				}

			public:

				void set_feedback(TFeedback const& f) {
					feedback=f;
				}

			};
			typedef copies copy;
		};
	}

	/// crashes on MaxN total number of copies
	template <size_t MaxN>
	struct on : public detail::when<MaxN,on_feedback,detail::shared_count<detail::shared_number>>
	{};

	/// crashes on MaxN'th copy
	template <size_t MaxN>
	struct after : public detail::when<MaxN,on_feedback,detail::simple_count>
	{};

	/// crashes on MaxN total instances of T
	template <size_t MaxN,typename T>
	struct on_total : public detail::when<MaxN,on_feedback,detail::total_count<T,detail::should_decrement_on_destruction>>
	{
		// instead typedef  copies instance - for gcc/standard complience
		typedef typename detail::when<MaxN, std::function<void(int)>, crashes::detail::total_count<T, crashes::detail::should_decrement_on_destruction> >::copies instances;
		typedef typename detail::when<MaxN, std::function<void(int)>, crashes::detail::total_count<T, crashes::detail::should_decrement_on_destruction> >::copies instance;
	};

	/// crashes on MaxN total instances of T
	template <size_t MaxN,typename T>
	struct after_total : public detail::when<MaxN,on_feedback,detail::total_count<T,detail::shouldnt_decrement_on_destruction>>
	{
		typedef typename detail::when<MaxN, std::function<void(int)>, crashes::detail::total_count<T, crashes::detail::shouldnt_decrement_on_destruction> >::copies instances;
		typedef typename detail::when<MaxN, std::function<void(int)>, crashes::detail::total_count<T, crashes::detail::shouldnt_decrement_on_destruction> >::copies instance;
	};
}<|endoftext|>


<commit_before>// Time:  O(logn)
// Space: O(logn)

class Solution {
public:
    int findKthNumber(int n, int k) {
        int result = 0;

        vector<int> cnts(10);
        for (int i = 1; i < 10; i++) {
            cnts[i] = cnts[i - 1] * 10 + 1;
        }

        vector<int> nums;
        for (int i = n; i > 0; i /= 10) {
            nums.push_back(i % 10);
        }
        int total = n;
        int target = 0;
        for (int i = nums.size() - 1; i >= 0 && k; --i) {
            target = target * 10 + nums[i];
            const auto start = i == nums.size() - 1 ? 1 : 0;
            for (int j = start; j < 10; ++j) {
                int candidate = result * 10 + j;
                int num;
                if (candidate < target) {
                    num = cnts[i + 1];
                } else if (candidate > target) {
                    num = cnts[i];
                } else {
                    num = total - cnts[i + 1] * (j - start) - cnts[i] * (9 - j);
                }
                if (k > num) {
                    k -= num;
                } else {
                    result = candidate;
                    --k;
                    total = num - 1;
                    break;
                }
            }
        }
        return result;
    }
};

// Time:  O(logn * logn)
// Space: O(logn)
class Solution2 {
public:
    int findKthNumber(int n, int k) {
        int result = 0;
        int index = 0;
        findKthNumberHelper(n, k, 0, &index, &result);
        return result;
    }

private:
    bool findKthNumberHelper(int n, int k, int cur, int *index, int *result) {
        if (cur) {
            ++(*index);
            if (*index == k) {
                *result = cur;
                return true;
            }
        }
        for (int i = (cur == 0 ? 1 : 0); i <= 9; ++i, cur /= 10) {
            cur = cur * 10 + i;
            int cnt = count(n, cur);
            if (k > cnt + *index) {
                *index += cnt;
                continue;
            }
            if (cur <= n && findKthNumberHelper(n, k, cur, index, result)) {
                return true;
            }
        }
        return false;
    }

    int count(int n, long long prefix) {  // Time:  O(logn)
        int result = 0;
        int number = 1;
        while (prefix <= n) {
            result += number;
            prefix *= 10;
            number *= 10;
        }
        result -= max(number / 10 - (n - prefix / 10 + 1), static_cast<long long>(0));
        return result;
    }
};
<commit_msg>Update k-th-smallest-in-lexicographical-order.cpp<commit_after>// Time:  O(logn)
// Space: O(logn)

class Solution {
public:
    int findKthNumber(int n, int k) {
        int result = 0;

        vector<int> cnts(10);
        for (int i = 1; i <= 9; ++i) {
            cnts[i] = cnts[i - 1] * 10 + 1;
        }

        vector<int> nums;
        for (int i = n; i > 0; i /= 10) {
            nums.push_back(i % 10);
        }
        int total = n;
        int target = 0;
        for (int i = nums.size() - 1; i >= 0 && k; --i) {
            target = target * 10 + nums[i];
            const auto start = i == nums.size() - 1 ? 1 : 0;
            for (int j = start; j <= 9; ++j) {
                int candidate = result * 10 + j;
                int num;
                if (candidate < target) {
                    num = cnts[i + 1];
                } else if (candidate > target) {
                    num = cnts[i];
                } else {
                    num = total - cnts[i + 1] * (j - start) - cnts[i] * (9 - j);
                }
                if (k > num) {
                    k -= num;
                } else {
                    result = candidate;
                    --k;
                    total = num - 1;
                    break;
                }
            }
        }
        return result;
    }
};

// Time:  O(logn * logn)
// Space: O(logn)
class Solution2 {
public:
    int findKthNumber(int n, int k) {
        int result = 0;
        int index = 0;
        findKthNumberHelper(n, k, 0, &index, &result);
        return result;
    }

private:
    bool findKthNumberHelper(int n, int k, int cur, int *index, int *result) {
        if (cur) {
            ++(*index);
            if (*index == k) {
                *result = cur;
                return true;
            }
        }
        for (int i = (cur == 0 ? 1 : 0); i <= 9; ++i, cur /= 10) {
            cur = cur * 10 + i;
            int cnt = count(n, cur);
            if (k > cnt + *index) {
                *index += cnt;
                continue;
            }
            if (cur <= n && findKthNumberHelper(n, k, cur, index, result)) {
                return true;
            }
        }
        return false;
    }

    int count(int n, long long prefix) {  // Time:  O(logn)
        int result = 0;
        int number = 1;
        while (prefix <= n) {
            result += number;
            prefix *= 10;
            number *= 10;
        }
        result -= max(number / 10 - (n - prefix / 10 + 1), static_cast<long long>(0));
        return result;
    }
};
<|endoftext|>


<commit_before>// RUN: %clang %s -S -emit-llvm -o - | grep -e "define linkonce_odr.*_ZlsR11std_ostreamRK8StreamerI3FooE"
// PR8007: friend function not instantiated.

struct std_ostream
{
  int dummy;
};

std_ostream cout;

template <typename STRUCT_TYPE>
struct Streamer
{
    friend std_ostream& operator << (std_ostream& o, const Streamer& f)
        {
            Streamer s(f);
            s(o);
            return o;
        }

    Streamer(const STRUCT_TYPE& s) : s(s) {}

    const STRUCT_TYPE& s;
    void operator () (std_ostream&) const;
};

typedef struct Foo {} Foo;

std_ostream& operator << (std_ostream& o, const Streamer<Foo>& f);
/*std_ostream& operator << (std_ostream& o, const Streamer<Foo>& f)
{
  // Sema should flag this as a redefinition
}*/

template <>
void Streamer<Foo>::operator () (std_ostream& o) const
{
}

int main(void)
{
    Foo foo;
    cout << foo;
}
<commit_msg>check whether sema issues a redefinition error<commit_after>// RUN: %clang %s -S -emit-llvm -o - | grep -e "define linkonce_odr.*_ZlsR11std_ostreamRK8StreamerI3FooE"
// RUN: %clang -cc1 %s -DREDEFINE -verify
// PR8007: friend function not instantiated.

struct std_ostream
{
  int dummy;
};

std_ostream cout;

template <typename STRUCT_TYPE>
struct Streamer
{
    friend std_ostream& operator << (std_ostream& o, const Streamer& f) // expected-error{{redefinition of 'operator<<'}}
        {
            Streamer s(f);
            s(o);
            return o;
        }

    Streamer(const STRUCT_TYPE& s) : s(s) {}

    const STRUCT_TYPE& s;
    void operator () (std_ostream&) const;
};

typedef struct Foo {} Foo;

std_ostream& operator << (std_ostream&, const Streamer<Foo>&);
#ifdef REDEFINE
std_ostream& operator << (std_ostream& o, const Streamer<Foo>&) // expected-note{{is here}}
{
  // Sema should flag this as a redefinition
  return o;
}
#endif

template <>
void Streamer<Foo>::operator () (std_ostream& o) const // expected-note{{requested here}}
{
}

int main(void)
{
    Foo foo;
    cout << foo;
}
<|endoftext|>


<commit_before>/*

 Copyright (c) 2013, Ford Motor Company
 All rights reserved.

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions are met:

 Redistributions of source code must retain the above copyright notice, this
 list of conditions and the following disclaimer.

 Redistributions in binary form must reproduce the above copyright notice,
 this list of conditions and the following
 disclaimer in the documentation and/or other materials provided with the
 distribution.

 Neither the name of the Ford Motor Company nor the names of its contributors
 may be used to endorse or promote products derived from this software
 without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 POSSIBILITY OF SUCH DAMAGE.
 */

#include "application_manager/commands/mobile/slider_request.h"
#include "application_manager/application_manager_impl.h"
#include "application_manager/application_impl.h"
#include "application_manager/message_helper.h"
#include "utils/helpers.h"

namespace application_manager {

namespace commands {

SliderRequest::SliderRequest(const MessageSharedPtr& message)
 : CommandRequestImpl(message) {
  subscribe_on_event(hmi_apis::FunctionID::UI_OnResetTimeout);
}

SliderRequest::~SliderRequest() {
}

bool SliderRequest::Init() {

  /* Timeout in milliseconds.
     If omitted a standard value of 10000 milliseconds is used.*/
  if ((*message_)[strings::msg_params].keyExists(strings::timeout)) {
    default_timeout_ =
        (*message_)[strings::msg_params][strings::timeout].asUInt();
  }

  return true;
}

void SliderRequest::Run() {
  LOG4CXX_AUTO_TRACE(logger_);

  ApplicationSharedPtr application =
      application_manager::ApplicationManagerImpl::instance()->application(
          (*message_)[strings::params][strings::connection_key].asUInt());

  if (!application) {
    LOG4CXX_ERROR(logger_, "Application is not registered");
    SendResponse(false, mobile_apis::Result::APPLICATION_NOT_REGISTERED);
    return;
  }

  if ((*message_)[strings::msg_params][strings::num_ticks].asInt()
      < (*message_)[strings::msg_params][strings::position].asInt()) {
    LOG4CXX_ERROR(logger_, "INVALID_DATA");
    SendResponse(false, mobile_apis::Result::INVALID_DATA);
    return;
  }

  if ((*message_)[strings::msg_params].keyExists(strings::slider_footer)) {
    if (1 < (*message_)[strings::msg_params][strings::slider_footer].length()) {
      if ((*message_)[strings::msg_params][strings::num_ticks].asUInt()
          != (*message_)[strings::msg_params]
                         [strings::slider_footer].length()) {
        LOG4CXX_ERROR(logger_, "INVALID_DATA");
        SendResponse(false, mobile_apis::Result::INVALID_DATA);
        return;
      }
    }
  }

  if (IsWhiteSpaceExist()) {
    LOG4CXX_ERROR(logger_, "Incoming slider has contains \t\n \\t \\n");
    SendResponse(false, mobile_apis::Result::INVALID_DATA);
    return;
  }

  smart_objects::SmartObject msg_params = smart_objects::SmartObject(
      smart_objects::SmartType_Map);
  msg_params = (*message_)[strings::msg_params];
  msg_params[strings::app_id] = application->app_id();

  if (!(*message_)[strings::msg_params].keyExists(strings::timeout)) {
    msg_params[strings::timeout] = default_timeout_;
  }

  SendHMIRequest(hmi_apis::FunctionID::UI_Slider, &msg_params, true);
}

void SliderRequest::on_event(const event_engine::Event& event) {
  LOG4CXX_AUTO_TRACE(logger_);
  using namespace helpers;
  const smart_objects::SmartObject& message = event.smart_object();

  const event_engine::Event::EventID event_id = event.id();
  if (event_id == hmi_apis::FunctionID::UI_OnResetTimeout) {
    LOG4CXX_INFO(logger_, "Received UI_OnResetTimeout event");
    ApplicationManagerImpl::instance()->updateRequestTimeout(connection_key(),
      correlation_id(),
      default_timeout());
    return;
  }
  if (event_id != hmi_apis::FunctionID::UI_Slider) {
    LOG4CXX_ERROR(logger_, "Received unknown event" << event.id());
    return;
  }

  LOG4CXX_INFO(logger_, "Received UI_Slider event");

  const hmi_apis::Common_Result::eType response_code =
      static_cast<hmi_apis::Common_Result::eType>(
      message[strings::params][hmi_response::code].asInt());

  smart_objects::SmartObject response_msg_params = message[strings::msg_params];
  if (response_code == hmi_apis::Common_Result::ABORTED &&
      response_msg_params[strings::data].keyExists(strings::slider_position)) {
    //Copy slider_position info to msg_params section
        response_msg_params[strings::slider_position] =
        message[strings::params][strings::data][strings::slider_position];
  }

  const bool is_response_success =
      Compare<hmi_apis::Common_Result::eType, EQ, ONE>(
        response_code,
        hmi_apis::Common_Result::SUCCESS,
        hmi_apis::Common_Result::WARNINGS);

  SendResponse(is_response_success,
               MessageHelper::HMIToMobileResult(response_code),
               0,
               &response_msg_params);
}

bool SliderRequest::IsWhiteSpaceExist() {
  LOG4CXX_AUTO_TRACE(logger_);
  const char* str = NULL;

  str = (*message_)[strings::msg_params][strings::slider_header].asCharArray();
  if (!CheckSyntax(str)) {
    LOG4CXX_ERROR(logger_, "Invalid slider_header value syntax check failed");
    return true;
  }

  if ((*message_)[strings::msg_params].keyExists(strings::slider_footer)) {
    const smart_objects::SmartArray* sf_array =
        (*message_)[strings::msg_params][strings::slider_footer].asArray();

    smart_objects::SmartArray::const_iterator it_sf = sf_array->begin();
    smart_objects::SmartArray::const_iterator it_sf_end = sf_array->end();

    for (; it_sf != it_sf_end; ++it_sf) {
      str = (*it_sf).asCharArray();
      if (!CheckSyntax(str)) {
        LOG4CXX_ERROR(logger_, "Invalid slider_footer syntax check failed");
        return true;
      }
    }
  }
  return false;
}

}  // namespace commands
}  // namespace application_manager

<commit_msg>Implements sending 'sliderPosition' to app on respose TIMED_OUT<commit_after>/*

 Copyright (c) 2013, Ford Motor Company
 All rights reserved.

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions are met:

 Redistributions of source code must retain the above copyright notice, this
 list of conditions and the following disclaimer.

 Redistributions in binary form must reproduce the above copyright notice,
 this list of conditions and the following
 disclaimer in the documentation and/or other materials provided with the
 distribution.

 Neither the name of the Ford Motor Company nor the names of its contributors
 may be used to endorse or promote products derived from this software
 without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 POSSIBILITY OF SUCH DAMAGE.
 */

#include "application_manager/commands/mobile/slider_request.h"
#include "application_manager/application_manager_impl.h"
#include "application_manager/application_impl.h"
#include "application_manager/message_helper.h"
#include "utils/helpers.h"

namespace application_manager {

namespace commands {

SliderRequest::SliderRequest(const MessageSharedPtr& message)
 : CommandRequestImpl(message) {
  subscribe_on_event(hmi_apis::FunctionID::UI_OnResetTimeout);
}

SliderRequest::~SliderRequest() {
}

bool SliderRequest::Init() {

  /* Timeout in milliseconds.
     If omitted a standard value of 10000 milliseconds is used.*/
  if ((*message_)[strings::msg_params].keyExists(strings::timeout)) {
    default_timeout_ =
        (*message_)[strings::msg_params][strings::timeout].asUInt();
  }

  return true;
}

void SliderRequest::Run() {
  LOG4CXX_AUTO_TRACE(logger_);

  ApplicationSharedPtr application =
      application_manager::ApplicationManagerImpl::instance()->application(
          (*message_)[strings::params][strings::connection_key].asUInt());

  if (!application) {
    LOG4CXX_ERROR(logger_, "Application is not registered");
    SendResponse(false, mobile_apis::Result::APPLICATION_NOT_REGISTERED);
    return;
  }

  if ((*message_)[strings::msg_params][strings::num_ticks].asInt() <
      (*message_)[strings::msg_params][strings::position].asInt()) {
    LOG4CXX_ERROR(logger_, "INVALID_DATA");
    SendResponse(false, mobile_apis::Result::INVALID_DATA);
    return;
  }

  if ((*message_)[strings::msg_params].keyExists(strings::slider_footer)) {
    if (1 < (*message_)[strings::msg_params][strings::slider_footer].length()) {
      if ((*message_)[strings::msg_params][strings::num_ticks].asUInt()
          != (*message_)[strings::msg_params]
                         [strings::slider_footer].length()) {
        LOG4CXX_ERROR(logger_, "INVALID_DATA");
        SendResponse(false, mobile_apis::Result::INVALID_DATA);
        return;
      }
    }
  }

  if (IsWhiteSpaceExist()) {
    LOG4CXX_ERROR(logger_, "Incoming slider has contains \t\n \\t \\n");
    SendResponse(false, mobile_apis::Result::INVALID_DATA);
    return;
  }

  smart_objects::SmartObject msg_params = smart_objects::SmartObject(
      smart_objects::SmartType_Map);
  msg_params = (*message_)[strings::msg_params];
  msg_params[strings::app_id] = application->app_id();

  if (!(*message_)[strings::msg_params].keyExists(strings::timeout)) {
    msg_params[strings::timeout] = default_timeout_;
  }

  SendHMIRequest(hmi_apis::FunctionID::UI_Slider, &msg_params, true);
}

void SliderRequest::on_event(const event_engine::Event& event) {
  LOG4CXX_AUTO_TRACE(logger_);
  using namespace helpers;
  using namespace smart_objects;
  using namespace hmi_apis;

  const SmartObject& message = event.smart_object();

  const event_engine::Event::EventID event_id = event.id();
  if (event_id == FunctionID::UI_OnResetTimeout) {
    LOG4CXX_INFO(logger_, "Received UI_OnResetTimeout event");
    ApplicationManagerImpl::instance()->updateRequestTimeout(connection_key(),
      correlation_id(),
      default_timeout());
    return;
  }

  if (event_id != FunctionID::UI_Slider) {
    LOG4CXX_ERROR(logger_, "Received unknown event" << event.id());
    return;
  }

  LOG4CXX_DEBUG(logger_, "Received UI_Slider event");

  const Common_Result::eType response_code = static_cast<Common_Result::eType>(
      message[strings::params][hmi_response::code].asInt());

  SmartObject response_msg_params = message[strings::msg_params];

  const bool is_timeout_aborted =
      Compare<Common_Result::eType, EQ, ONE>(
        response_code,
        Common_Result::TIMED_OUT,
        Common_Result::ABORTED);

  if (is_timeout_aborted) {
    if (message[strings::params][strings::data]
        .keyExists(strings::slider_position)) {
      //Copy slider_position info to msg_params section
      response_msg_params[strings::slider_position] =
          message[strings::params][strings::data][strings::slider_position];
    } else {
      LOG4CXX_ERROR(logger_, strings::slider_position << " field is absent"
                    " in response.");
      response_msg_params[strings::slider_position] = 0;
    }
  }

  const bool is_response_success =
      Compare<Common_Result::eType, EQ, ONE>(
        response_code,
        Common_Result::SUCCESS,
        Common_Result::WARNINGS);

  SendResponse(is_response_success,
               MessageHelper::HMIToMobileResult(response_code),
               0,
               &response_msg_params);
}

bool SliderRequest::IsWhiteSpaceExist() {
  LOG4CXX_AUTO_TRACE(logger_);
  const char* str = NULL;

  str = (*message_)[strings::msg_params][strings::slider_header].asCharArray();
  if (!CheckSyntax(str)) {
    LOG4CXX_ERROR(logger_, "Invalid slider_header value syntax check failed");
    return true;
  }

  if ((*message_)[strings::msg_params].keyExists(strings::slider_footer)) {
    const smart_objects::SmartArray* sf_array =
        (*message_)[strings::msg_params][strings::slider_footer].asArray();

    smart_objects::SmartArray::const_iterator it_sf = sf_array->begin();
    smart_objects::SmartArray::const_iterator it_sf_end = sf_array->end();

    for (; it_sf != it_sf_end; ++it_sf) {
      str = (*it_sf).asCharArray();
      if (!CheckSyntax(str)) {
        LOG4CXX_ERROR(logger_, "Invalid slider_footer syntax check failed");
        return true;
      }
    }
  }
  return false;
}

}  // namespace commands
}  // namespace application_manager

<|endoftext|>


<commit_before>// renderable_sprite.t.cpp
#include <engine/rendering/renderable_sprite.h>
#include <engine/rendering/renderer.h>
#include <gtest/gtest.h>

TEST( RenderableSpriteTest, Construction )
{
    using namespace StevensDev::sgdr;

    RenderableSprite blank;
    RenderableSprite copy( blank );

    Renderer renderer;

    // can't continue if can't find the texture
    ASSERT_TRUE( renderer.loadTexture( "test", "res/texture/block.png" ) );

    RenderableSprite texture( renderer.getTexture( "test" ) );
    RenderableSprite sprite( sf::Sprite( renderer.getTexture( "test" ) ) );

    texture = sprite;
}

TEST( RenderableSpriteTest, Position )
{
    using namespace StevensDev::sgdr;

    Renderer renderer;

    // can't continue if can't find the texture
    ASSERT_TRUE( renderer.loadTexture( "test", "res/texture/block.png" ) );

    RenderableSprite sprite( renderer.getTexture( "test" ) );

    sprite.setPosition( 25.0f, 25.0f );

    EXPECT_EQ( 25.0f, sprite.getPositionX() );
    EXPECT_EQ( 25.0f, sprite.getPositionY() );

    sprite.move( -25.0f, -25.0f );

    EXPECT_EQ( 0.0f, sprite.getPositionX() );
    EXPECT_EQ( 0.0f, sprite.getPositionY() );
}

TEST( RenderableSpriteTest, Print )
{
    using namespace StevensDev::sgdr;

    Renderer renderer;

    // can't continue if can't find the texture
    ASSERT_TRUE( renderer.loadTexture( "test", "res/texture/block.png" ) );

    RenderableSprite sprite( renderer.getTexture( "test" ) );
    sprite.setPosition( 0.0f, 0.0f );

    std::ostringstream oss;

    oss << sprite;

    EXPECT_STREQ( "{ \"x\": 0.0, \"y\": 0.0 }", oss.str().c_str() );
}<commit_msg>Correct resource paths.<commit_after>// renderable_sprite.t.cpp
#include <engine/rendering/renderable_sprite.h>
#include <engine/rendering/renderer.h>
#include <gtest/gtest.h>

TEST( RenderableSpriteTest, Construction )
{
    using namespace StevensDev::sgdr;

    RenderableSprite blank;
    RenderableSprite copy( blank );

    Renderer renderer;

    // can't continue if can't find the texture
    ASSERT_TRUE( renderer.loadTexture( "test", "res/texture/actor/block/block.png" ) );

    RenderableSprite texture( renderer.getTexture( "test" ) );
    RenderableSprite sprite( sf::Sprite( renderer.getTexture( "test" ) ) );

    texture = sprite;
}

TEST( RenderableSpriteTest, Position )
{
    using namespace StevensDev::sgdr;

    Renderer renderer;

    // can't continue if can't find the texture
    ASSERT_TRUE( renderer.loadTexture( "test", "res/texture/actor/block/block.png" ) );

    RenderableSprite sprite( renderer.getTexture( "test" ) );

    sprite.setPosition( 25.0f, 25.0f );

    EXPECT_EQ( 25.0f, sprite.getPositionX() );
    EXPECT_EQ( 25.0f, sprite.getPositionY() );

    sprite.move( -25.0f, -25.0f );

    EXPECT_EQ( 0.0f, sprite.getPositionX() );
    EXPECT_EQ( 0.0f, sprite.getPositionY() );
}

TEST( RenderableSpriteTest, Print )
{
    using namespace StevensDev::sgdr;

    Renderer renderer;

    // can't continue if can't find the texture
    ASSERT_TRUE( renderer.loadTexture( "test", "res/texture/actor/block/block.png" ) );

    RenderableSprite sprite( renderer.getTexture( "test" ) );
    sprite.setPosition( 0.0f, 0.0f );

    std::ostringstream oss;

    oss << sprite;

    EXPECT_STREQ( "{ \"x\": 0.0, \"y\": 0.0 }", oss.str().c_str() );
}<|endoftext|>