mat find_inliers(mat data, const parameters& params) { uint_fast32_t n_inliers = 0; double outlier_proportion; uvec best_indices; uvec indices = rand_indices(0, data.n_cols); uint_fast32_t iter = 0; uint_fast32_t iter_max = -1; while (iter < iter_max) { mat maybe_inliers = data.cols(indices.head(params.nfit_points)); mat model = params.model_function(maybe_inliers); mat distances = params.distance_function(model, data); uvec inliers = find(distances < params.distance_threshold); if (inliers.n_elem > n_inliers) { n_inliers = inliers.n_elem; best_indices = inliers; outlier_proportion = 1.0 - (double) inliers.n_elem / (double) data.n_cols; iter_max = lround( log(1.0 - 0.99) / log(1.0 - pow(1.0 - outlier_proportion, params.nfit_points)) ); } indices = shuffle(indices); // generate new random indexes ++iter; } return data.cols(best_indices); }
bool attack_cpa<real>::setup(crypto_instance *crypto, const parameters ¶ms) { if (!params.get("num_events", m_nevents) || !params.get("num_reports", m_nreports) || !params.get("byte", m_byte) || !params.get("offset", m_offset) || !params.get("bits", m_bits)) { fprintf(stderr, "required parameters: byte, offset, bits\n"); return false; } m_mask = 0; for (unsigned int i = m_offset; i < (m_offset + m_bits); ++i) m_mask |= 1 << i; m_crypto = crypto; m_guesses = 1 << m_crypto->estimate_bits(); m_center = m_bits >> 1; m_traces = 0; // allocate storage for intermediate results in advance m_t1.resize(m_nevents, 0); m_t2.resize(m_nevents, 0); m_w1.resize(m_guesses, 0); m_w2.resize(m_guesses, 0); m_tw.resize(m_guesses * m_nevents, 0); m_dtemp.resize(m_guesses * m_nevents, 0); m_maxes.resize(m_guesses * m_nreports, 0); return true; }
object_ptr interpreter::make_text (parameters &command) { TRACE ('f', command); string first = shift(command); string font = ""; double size = 12.0; //Default size is 12 for text //If conversion succeeds, then next string on list is the fontname, //otherwise the string that couldn't be converted to a double is //the fontname. try{ size = from_string<double>(first); font = shift(command); } catch (runtime_error &error){ font = first; } //At this point, the rest of the words are text to be printed. string textdata{}; parameters::const_iterator itor = command.begin(); parameters::const_iterator end = command.end(); --end; for(; itor != end; ++itor){ textdata += *itor + ' '; }textdata += *itor;//remove trailing space return make_shared<text> (font, points(size), textdata); }
object_ptr interpreter::make_line (parameters &command) { TRACE ('f', command); if(command.size() > 2) throw runtime_error ("syntax error"); double length = from_string<double>(shift(command)); double thick = 2.0; //Default thickness of 2 if(command.size() != 0) thick = from_string<double>(shift(command)); return make_shared<line> (inches(length), points(thick)); }
void interpreter::interpret (const parameters& params) { DEBUGF ('i', params); param begin = params.cbegin(); string command = *begin; auto itor = interp_map.find (command); if (itor == interp_map.end()) throw runtime_error ("syntax error"); interpreterfn func = itor->second; func (++begin, params.cend()); }
datasource_ptr datasource_cache::create(const parameters& params, bool bind) { boost::optional<std::string> type = params.get<std::string>("type"); if ( ! type) { throw config_error(std::string("Could not create datasource. Required ") + "parameter 'type' is missing"); } #ifdef MAPNIK_THREADSAFE mutex::scoped_lock lock(mutex_); #endif datasource_ptr ds; std::map<std::string,boost::shared_ptr<PluginInfo> >::iterator itr=plugins_.find(*type); if ( itr == plugins_.end() ) { throw config_error(std::string("Could not create datasource. No plugin ") + "found for type '" + * type + "' (searched in: " + plugin_directories() + ")"); } if ( ! itr->second->handle()) { throw std::runtime_error(std::string("Cannot load library: ") + lt_dlerror()); } // http://www.mr-edd.co.uk/blog/supressing_gcc_warnings #ifdef __GNUC__ __extension__ #endif create_ds* create_datasource = reinterpret_cast<create_ds*>(lt_dlsym(itr->second->handle(), "create")); if (! create_datasource) { throw std::runtime_error(std::string("Cannot load symbols: ") + lt_dlerror()); } #ifdef MAPNIK_LOG MAPNIK_LOG_DEBUG(datasource_cache) << "datasource_cache: Size=" << params.size(); parameters::const_iterator i = params.begin(); for (; i != params.end(); ++i) { MAPNIK_LOG_DEBUG(datasource_cache) << "datasource_cache: -- " << i->first << "=" << i->second; } #endif ds = datasource_ptr(create_datasource(params, bind), datasource_deleter()); MAPNIK_LOG_DEBUG(datasource_cache) << "datasource_cache: Datasource=" << ds << " type=" << type; return ds; }
object_ptr interpreter::make_rectangle (parameters &command) { TRACE ('f', command); if(command.size() > 3) throw runtime_error ("syntax error"); double width = from_string<double>(shift(command)); double height = from_string<double>(shift(command)); double thick = 2.0; //Default thickness of 2 if(command.size() != 0) thick = from_string<double>(shift(command)); return make_shared<rectangle> (inches(width), inches(height), points(thick)); }
static void test_exceptions() { { string s( "x$1?y" ); parameters const p( MAKE_PARAMS( "foo" ) ); ASSERT_EXCEPTION( p.substitute( &s ), invalid_argument ); } { string s( "x$1?{y" ); parameters const p( MAKE_PARAMS( "foo" ) ); ASSERT_EXCEPTION( p.substitute( &s ), invalid_argument ); } }
static return_type extract(parameters const& params, std::string const& name, boost::optional<T> const& default_opt_value) { boost::optional<T> result(default_opt_value); parameters::const_iterator itr = params.find(name); if (itr != params.end()) { util::apply_visitor(value_extractor_visitor<T>(result),itr->second); } return result; }
static boost::python::tuple getstate(const parameters& p) { using namespace boost::python; dict d; parameters::const_iterator pos=p.begin(); while(pos!=p.end()) { d[pos->first] = pos->second; ++pos; } return boost::python::make_tuple(d); }
shape_datasource::shape_datasource(const parameters ¶ms) : shape_name_(params.get("file")), type_(datasource::Vector), file_length_(0), indexed_(false), desc_(params.get("name")) { try { shape_io shape(shape_name_); init(shape); for (int i=0;i<shape.dbf().num_fields();++i) { field_descriptor const& fd=shape.dbf().descriptor(i); std::string fld_name=fd.name_; switch (fd.type_) { case 'C': case 'D': case 'M': case 'L': desc_.add_descriptor(attribute_descriptor(fld_name,String)); break; case 'N': case 'F': { if (fd.dec_>0) { desc_.add_descriptor(attribute_descriptor(fld_name,Double,false,8)); } else { desc_.add_descriptor(attribute_descriptor(fld_name,Integer,false,4)); } break; } default: // std::clog << "unknown type "<<fd.type_<<"\n"; break; } } } catch (datasource_exception& ex) { std::clog<<ex.what()<<std::endl; throw; } }
static void test_braces() { { string s( "x${1}y" ); parameters const p( MAKE_PARAMS( "foo" ) ); ASSERT_NO_EXCEPTION( p.substitute( &s ) ); ASSERT_TRUE( s == "xfooy" ); } { string s( "x${ 1 }y" ); parameters const p( MAKE_PARAMS( "foo" ) ); ASSERT_NO_EXCEPTION( p.substitute( &s ) ); ASSERT_TRUE( s == "x foo y" ); } { string s( "x${1}y" ); parameters const p( MAKE_PARAMS( "" ) ); ASSERT_NO_EXCEPTION( p.substitute( &s ) ); ASSERT_TRUE( s == "xy" ); } { string s( "x${ 1 }y" ); parameters const p( MAKE_PARAMS( "" ) ); ASSERT_NO_EXCEPTION( p.substitute( &s ) ); ASSERT_TRUE( s == "xy" ); } }
void interpreter::interpret (const parameters& params) { DEBUGF ('i', params); param begin = params.cbegin(); // First word contains command name // Either define, draw, border, or moveby string command = *begin; DEBUGF('i', command); auto itor = interp_map.find (command); if (itor == interp_map.end()) throw runtime_error ("syntax error"); interpreterfn func = itor->second; for (auto i = begin; i != params.cend(); ++i) { cout << *i << " "; } cout << endl; func (++begin, params.cend()); }
boost::python::dict dict_params(parameters& p) { boost::python::dict d; parameters::const_iterator pos=p.begin(); while(pos!=p.end()) { boost::python::list vals; pickle_value serializer( vals ); mapnik::value_holder val = pos->second; boost::apply_visitor( serializer, val ); d[pos->first] = vals[0]; ++pos; } return d; }
object_ptr interpreter::make_polygon (parameters &command) { TRACE ('f', command); double thick = 2.0; //Default thickness of 2 if (command.size() % 2 == 1){ thick = from_string<double>(command.back()); command.pop_back(); } coordlist poly_points{}; while(!command.empty()){ double x = from_string<double>(shift(command)); double y = from_string<double>(shift(command)); poly_points.push_back({inches(x), inches(y)}); } return make_shared<polygon> (poly_points, points(thick)); }
boost::python::list list_params(parameters& p) { boost::python::list l; parameters::const_iterator pos=p.begin(); while(pos!=p.end()) { boost::python::list vals; pickle_value serializer( vals ); mapnik::value_holder val = pos->second; boost::apply_visitor( serializer, val ); l.append(boost::python::make_tuple(pos->first,vals[0])); ++pos; } return l; }
static boost::python::tuple getstate(const parameters& p) { using namespace boost::python; dict d; parameters::const_iterator pos=p.begin(); while(pos!=p.end()) { boost::python::list vals; pickle_value serializer( vals ); mapnik::value_holder val = pos->second; boost::apply_visitor( serializer, val ); d[pos->first] = vals[0]; ++pos; } return boost::python::make_tuple(d); }
chained_datasource::chained_datasource(const parameters& params, bool _bind) : datasource(params) { // Iterate over params and populate m_source_params // from all parameters that start with "src_" for (parameters::const_iterator iter=params.begin(); iter!=params.end(); iter++) { const std::string &name(iter->first); if (!boost::starts_with(name, "src_")) continue; const std::string sub_name(name.substr(4)); source_params_[sub_name]=iter->second; } if (_bind) { bind(); } }
void go(parameters & params) { tpie::file_stream<item_type> fs; tpie::serialization_writer ss; if (params.gen_tpie) fs.open(params.stream_name("tpie")); if (params.gen_serialization) ss.open(params.stream_name("ser")); tpie::stream_size_type numbers = static_cast<tpie::stream_size_type>(params.megabytes * 1024 * 1024 / sizeof(item_type)); boost::mt19937 rng(params.seed); boost::uniform_01<> basedist; boost::variate_generator<boost::mt19937, boost::uniform_01<> > rng01(rng, basedist); boost::exponential_distribution<> dist(2); for (tpie::stream_size_type i = 0; i < numbers; ++i) { item_type x = dist(rng01); if (params.gen_tpie) fs.write(x); if (params.gen_serialization) ss.serialize(x); } if (params.gen_tpie) fs.close(); if (params.gen_serialization) ss.close(); }
parameters::parameters(const parameters &rhs) { m_stud_mode = rhs.get_stud_rendering_mode(); m_mode = rhs.get_rendering_mode(); m_vbuffer_criteria = rhs.get_vbuffer_criteria(); m_shading = rhs.get_shading(); m_debug = rhs.get_debug(); m_culling = rhs.get_culling(); m_shader = rhs.get_shader(); }
void initParameters(parameters &inputParameters) { //temporary file parameter one; //number 0: vacant one.name = "reserved"; one.isTrue = false; one.queue = 0; inputParameters.push_back(one); //number 1 one.name = "negative"; one.isTrue = false; one.queue = 0; inputParameters.push_back(one); //number 2 one.name = "rgb100"; one.isTrue = false; one.queue = 0; inputParameters.push_back(one); //number 3 one.name = "diagonal"; one.isTrue = false; one.queue = 0; inputParameters.push_back(one); //number 4 one.name = "frame"; one.isTrue = false; one.queue = 0; inputParameters.push_back(one); //number 5 one.name = "circle"; one.isTrue = false; one.queue = 0; inputParameters.push_back(one); }
std::unique_ptr <database> managerimp::make_database ( std::string const& name, scheduler& scheduler, beast::journal journal, int readthreads, parameters const& backendparameters, parameters fastbackendparameters) { std::unique_ptr <backend> backend (make_backend ( backendparameters, scheduler, journal)); std::unique_ptr <backend> fastbackend ( (fastbackendparameters.size () > 0) ? make_backend (fastbackendparameters, scheduler, journal) : nullptr); return std::make_unique <databaseimp> (name, scheduler, readthreads, std::move (backend), std::move (fastbackend), journal); }
void interpreter::do_draw (parameters ¶ms) { TRACE ('i', params); string name = shift (params); object_map::const_iterator itor = objmap.find (name); if (itor == objmap.end()) { throw runtime_error (name + ": no such object"); } degrees angle = degrees (0); if (params.size() == 3) { angle = degrees (from_string<double> (params.back())); params.pop_back(); } if (params.size() != 2) throw runtime_error ("syntax error"); xycoords coords (inches (from_string<double> (params.front())), inches (from_string<double> (params.back()))); itor->second->draw (outfile, coords, angle); }
//! Initialize the oracle void init() { assert(params.valid()); // Initialize the random number generator rng.seed(static_cast<unsigned>(params.random_seed)); uniform_prob = boost::uniform_real<double>(0,1); // Construct the graph and make CPTs if (num_finite() > 2 * params.num_parents) { for (size_t j = 2 * params.num_parents; j < num_finite(); ++j) { // Choose NUM_PARENTS random parents finite_domain parents; std::vector<size_t> r(randperm(j, rng)); for (size_t k = 0; k < params.num_parents; ++k) parents.insert(finite_seq[r[k]]); parents.insert(finite_seq[j]); tablef f(parents.plus(finite_seq[j])); // RIGHT HERE NOW: MAKE FACTOR bn.add_factor(parents, finite_seq[j]); } } }
static void test_simple() { { string s( "x$1y" ); parameters const p( MAKE_PARAMS( "foo" ) ); ASSERT_NO_EXCEPTION( p.substitute( &s ) ); ASSERT_TRUE( s == "xfooy" ); } { string s( "x$1y" ); parameters const p( MAKE_PARAMS( "" ) ); ASSERT_NO_EXCEPTION( p.substitute( &s ) ); ASSERT_TRUE( s == "xy" ); } { string s( "x$1y" ); parameters const p( MAKE_PARAMS( "\\" ) ); ASSERT_NO_EXCEPTION( p.substitute( &s ) ); ASSERT_TRUE( s == "x\\y" ); } }
bool GetScore(ap::template_2d_array<float,true>& Responses, ap::template_1d_array<unsigned short int, true>& Code, parameters tMUD, ap::template_1d_array<short int,true>& trialnr, ap::template_1d_array<double,true>& windowlen, int numchannels, int NumberOfSequences, int NumberOfChoices, int mode, ap::real_2d_array &pscore) { /////////////////////////////////////////////////////////////////////// // Section: Define variables int row_Responses, col_Responses, row_MUD, col_MUD, dslen, count, max, NumberOfEpochs, numVariables; bool flag = true; ap::real_2d_array Responses_double; ap::template_2d_array<float, true> Responses_copy; ap::real_2d_array DATA; ap::real_2d_array tmp_MUD; ap::real_1d_array score; ap::real_1d_array weights; vector<short int> trial; //vector<short int> trial_copy; vector<int> range; vector<int> code_indx; vector<short int>::iterator it; /////////////////////////////////////////////////////////////////////// // Section: Get Dimmensions row_Responses = Responses.gethighbound(1)+1; col_Responses = Responses.gethighbound(0)+1; row_MUD = tMUD.MUD.gethighbound(1)+1; col_MUD = tMUD.MUD.gethighbound(0)+1; /////////////////////////////////////////////////////////////////////// // Section: Extract from the signal only the channels containing the "in" variables numVariables = static_cast<int>( col_Responses/static_cast<double>( numchannels ) ); Responses_copy.setbounds(0, row_Responses-1, 0, numVariables*(tMUD.channels.gethighbound(1)+1)-1); Responses_double.setbounds(0, row_Responses-1, 0, numVariables*(tMUD.channels.gethighbound(1)+1)-1); for (int i=0; i<row_Responses; i++) { for (int j=0; j<tMUD.channels.gethighbound(1)+1; j++) { ap::vmove(Responses_copy.getrow(i, j*numVariables, ((j+1)*numVariables)-1), Responses.getrow(i, static_cast<int>(tMUD.channels(j)-1)*numVariables, static_cast<int>(tMUD.channels(j)*numVariables)-1)); } } for (int i=0; i<row_Responses; i++) { for (int j=0; j<numVariables*(tMUD.channels.gethighbound(1)+1); j++) Responses_double(i,j) = static_cast<double>( Responses_copy(i,j) ); } for (int i=0; i<row_Responses; i++) trial.push_back(trialnr(i)); /////////////////////////////////////////////////////////////////////// // Section: Downsampling the MUD dslen = ap::iceil((row_MUD-1)/tMUD.DF)+1; tmp_MUD.setbounds(0, dslen, 0, col_MUD-1); for (int j=0; j<col_MUD; j++) { for (int i=0; i<dslen; i++) { if (j==0) tmp_MUD(i,0) = tMUD.MUD(i*tMUD.DF, 0)-1; if (j==1) { tmp_MUD(i,1) = tMUD.MUD(i*tMUD.DF, 1) - windowlen(0); tmp_MUD(i,1) = ap::ifloor(tmp_MUD(i,1)/tMUD.DF)+1; tmp_MUD(i,1) = tmp_MUD(i,1) + (tmp_MUD(i,0)*numVariables); } if (j==2) tmp_MUD(i,2) = tMUD.MUD(i*tMUD.DF, 2); } } /////////////////////////////////////////////////////////////////////// // Section: Computing the score DATA.setbounds(0, row_Responses-1, 0, dslen-1); score.setbounds(0, row_Responses-1); weights.setbounds(0, dslen-1); double valor; for (int i=0; i<dslen; i++) { valor = tmp_MUD(i,1); ap::vmove(DATA.getcolumn(i, 0, row_Responses-1), Responses_double.getcolumn(static_cast<int>( tmp_MUD(i,1) ), 0, row_Responses-1)); valor = DATA(0,i); weights(i) = tmp_MUD(i,2); } matrixvectormultiply(DATA, 0, row_Responses-1, 0, dslen-1, FALSE, weights, 0, dslen-1, 1, score, 0, row_Responses-1, 0); /////////////////////////////////////////////////////////////////////// // Section: Make sure that the epochs are not outside of the boundaries #if 0 // jm Mar 18, 2011 trial_copy = trial; it = unique(trial_copy.begin(), trial_copy.end()); trial_copy.resize(it-trial_copy.begin()); max = *max_element(trial_copy.begin(), trial_copy.end()); #else // jm max = *max_element(trial.begin(), trial.end()); #endif // jm count = 0; for (size_t i=0; i<trial.size(); i++) { if (trial[i] == max) count++; } if (count == NumberOfSequences*NumberOfChoices) NumberOfEpochs = *max_element(trial.begin(), trial.end()); else NumberOfEpochs = *max_element(trial.begin(), trial.end())-1; /////////////////////////////////////////////////////////////////////// // Section: Create a matrix with the scores for each sequence pscore.setbounds(0, NumberOfChoices-1, 0, (NumberOfEpochs*NumberOfSequences)-1); for (int i=0; i<NumberOfEpochs; i++) { for (size_t j=0; j<trial.size(); j++) { if (trial[j] == i+1) range.push_back(static_cast<int>(j)); } if ((range.size() != 0) && (range.size() == NumberOfSequences*NumberOfChoices)) { for (int k=0; k<NumberOfChoices; k++) { for (size_t j=0; j<range.size(); j++) { if (Code(range[j]) == k+1) code_indx.push_back(range[j]); } for (size_t j=0; j<code_indx.size(); j++) { if (code_indx.size() == NumberOfSequences) pscore(k,static_cast<int>((i*NumberOfSequences)+j)) = score(code_indx[j]); } code_indx.clear(); } flag = true; } else { flag = false; break; } range.clear(); } return flag; }
void interpreter::do_newpage (parameters ¶ms) { if (params.size() != 0) throw runtime_error ("syntax error"); endpage(); ++pagenr; startpage(); }
matches im_utility::diff(const std::string &im_file1, const std::string &im_file2, const parameters ¶ms, key_points *im1_kps, key_points *im2_kps) { using namespace cv; matches mt; std::vector<KeyPoint> im1_key_points, im2_key_points; std::vector<DMatch> matches; std::vector<DMatch> good_matches; double min_hessian = 400.0; if (params.find(key_hessian_threshold) != params.end()) min_hessian = params.at(key_hessian_threshold); double sigma = 2.0; if (params.find(key_match_threshold) != params.end()) sigma = params.at(key_match_threshold); int speedup = speedup_default; if (params.find(key_speedup) != params.end()) speedup = params.at(key_speedup); //auto info = getBuildInformation(); if (speedup == speedup_use_cuda) { using namespace gpu; DeviceInfo dev; auto name = dev.name(); GpuMat img1, img2; // upload data img1.upload(imread(im_file1, CV_LOAD_IMAGE_GRAYSCALE)); img2.upload(imread(im_file2, CV_LOAD_IMAGE_GRAYSCALE)); // detect keypoints & computing descriptors SURF_GPU surf; GpuMat kps_gpu1, kps_gpu2; GpuMat desc_gpu1, desc_gpu2; surf(img1, GpuMat(), kps_gpu1, desc_gpu1); surf(img2, GpuMat(), kps_gpu2, desc_gpu2); // matching descriptors BFMatcher_GPU matcher_gpu(NORM_L2); GpuMat trainIdx, distance; matcher_gpu.matchSingle(desc_gpu1, desc_gpu2, trainIdx, distance); // download results std::vector<float> desc1, desc2; surf.downloadKeypoints(kps_gpu1, im1_key_points); surf.downloadKeypoints(kps_gpu2, im2_key_points); surf.downloadDescriptors(desc_gpu1, desc1); surf.downloadDescriptors(desc_gpu2, desc2); BFMatcher_GPU::matchDownload(trainIdx, distance, matches); good_matches = matches; } else if (speedup == speedup_use_ocl) { using namespace ocl; DevicesInfo devs; getOpenCLDevices(devs, CVCL_DEVICE_TYPE_GPU); int dev = 0; if (params.find(key_ocl_dev) != params.end()) dev = params.at(key_ocl_dev); if (dev < 0 || dev >= devs.size()) dev = 0; setDevice(devs[dev]); SURF_OCL surf(800.0); BFMatcher_OCL matcher(NORM_L2); oclMat desc1, desc2; oclMat im1, im2; im1 = imread(im_file1, CV_LOAD_IMAGE_GRAYSCALE); im2 = imread(im_file2, CV_LOAD_IMAGE_GRAYSCALE); surf(im1, oclMat(), im1_key_points, desc1); surf(im2, oclMat(), im2_key_points, desc2); matcher.match(desc1, desc2, matches); double max_dist = 0; double min_dist = 100; for (int i = 0; i < desc1.rows; i++) { double dist = matches[i].distance; if (dist < min_dist) min_dist = dist; if (dist > max_dist) max_dist = dist; } for (int i = 0; i < desc1.rows; i++) { if (matches[i].distance <= max(sigma * min_dist, 0.02)) { good_matches.push_back(matches[i]); } } } else { auto get_file_desc = [](const std::string &filename, double min_hessian, std::vector<cv::KeyPoint> *out_key_points) { using namespace cv; Mat desc; Mat img = imread(filename, CV_LOAD_IMAGE_GRAYSCALE); if (!img.data) return desc; SurfFeatureDetector detecter(min_hessian); std::vector<KeyPoint> key_points; detecter.detect(img, key_points); if (out_key_points) *out_key_points = key_points; if (key_points.empty()) { std::cout << "no feature detected: " << filename << std::endl; return desc; } SurfDescriptorExtractor extractor; extractor.compute(img, key_points, desc); return desc; }; auto im1_desc = get_file_desc(im_file1, min_hessian, &im1_key_points); auto im2_desc = get_file_desc(im_file2, min_hessian, &im2_key_points); FlannBasedMatcher matcher; matcher.match(im1_desc, im2_desc, matches); double max_dist = 0; double min_dist = 100; for (int i = 0; i < im1_desc.rows; i++) { double dist = matches[i].distance; if (dist < min_dist) min_dist = dist; if (dist > max_dist) max_dist = dist; } for (int i = 0; i < im1_desc.rows; i++) { if (matches[i].distance <= max(sigma * min_dist, 0.02)) { good_matches.push_back(matches[i]); } } } auto conv_keypoint = [](const std::vector<KeyPoint> &kps) { key_points out; std::transform(kps.begin(), kps.end(), std::back_inserter(out), [](const KeyPoint &kp){ //return key_point{ kp.pt.x, kp.pt.y, kp.size, kp.angle }; key_point p; p.x = kp.pt.x; p.y = kp.pt.y; p.size = kp.size; p.angle = kp.angle; return p; }); return out; }; auto kps1 = conv_keypoint(im1_key_points); auto kps2 = conv_keypoint(im2_key_points); if (im1_kps) *im1_kps = kps1; if (im2_kps) *im2_kps = kps2; std::transform(good_matches.begin(), good_matches.end(), std::back_inserter(mt), [&](const DMatch &m) { //return match{ kps1[m.queryIdx] , kps2[m.trainIdx] , m.distance }; match ma; ma.pt1 = kps1[m.queryIdx]; ma.pt2 = kps2[m.trainIdx]; ma.distance = m.distance; return ma; }); return mt; }
parameters diagonalize_bisection(localized_matrix<double, MATRIX_MAJOR>& mat, double* eigvals, localized_matrix<double, MATRIX_MAJOR>& eigvecs, parameters const& params) { rokko::parameters params_out; char jobz = 'V'; // eigenvalues / eigenvectors int dim = mat.outerSize(); int ldim_mat = mat.innerSize(); int ldim_eigvec = eigvecs.innerSize(); std::vector<lapack_int> ifail(dim); lapack_int m; // output: found eigenvalues double abstol; get_key(params, "abstol", abstol); if (abstol < 0) { std::cerr << "Error in diagonalize_bisection" << std::endl << "abstol is negative value, which means QR method." << std::endl << "To use dsyevx as bisection solver, set abstol a positive value" << std::endl; throw; } if (!params.defined("abstol")) { // default: optimal value for bisection method abstol = 2 * LAPACKE_dlamch('S'); } params_out.set("abstol", abstol); char uplow = get_matrix_part(params); lapack_int il, iu; double vl, vu; char range = get_eigenvalues_range(params, vl, vu, il, iu); int info; if(mat.is_col_major()) info = LAPACKE_dsyevx(LAPACK_COL_MAJOR, jobz, range, uplow, dim, &mat(0,0), ldim_mat, vl, vu, il, iu, abstol, &m, eigvals, &eigvecs(0,0), ldim_eigvec, &ifail[0]); else info = LAPACKE_dsyevx(LAPACK_ROW_MAJOR, jobz, range, uplow, dim, &mat(0,0), ldim_mat, vl, vu, il, iu, abstol, &m, eigvals, &eigvecs(0,0), ldim_eigvec, &ifail[0]); if (info) { std::cerr << "Error at dsyevx function. info=" << info << std::endl; if (params.get_bool("verbose")) { std::cerr << "This means that "; if (info < 0) { std::cerr << "the " << abs(info) << "-th argument had an illegal value." << std::endl; } else { std::cerr << "This means that " << info << " eigenvectors failed to converge." << std::endl; std::cerr << "The indices of the eigenvectors that failed to converge:" << std::endl; for (int i=0; i<ifail.size(); ++i) { if (ifail[i] == 0) break; std::cerr << ifail[i] << " "; } std::cerr << std::endl; } } exit(1); } params_out.set("m", m); params_out.set("ifail", ifail); if (params.get_bool("verbose")) { print_verbose("dsyevx (bisecition)", jobz, range, uplow, vl, vu, il, iu, params_out); } return params_out; }
int cochleo_stream::run(const parameters& param) { static const std::size_t frames_per_buffer = 64; try { portaudio::AutoSystem autoSys; portaudio::System &sys = portaudio::System::instance(); cout << "===================================================" << endl << endl; auto& device = sys.deviceByIndex(param.device_id()); BOOST_LOG_TRIVIAL(info) << "Opening device " << device.name(); // mono capture interleaved portaudio::DirectionSpecificStreamParameters input_parameters(device,1,portaudio::FLOAT32,true,0.0,NULL); portaudio::StreamParameters stream_params(input_parameters, portaudio::DirectionSpecificStreamParameters::null(), device.defaultSampleRate(), frames_per_buffer, paNoFlag); // signal_renderer renderer(stream.sampleRate(), 5); // portaudio::MemFunCallbackStream<signal_renderer> stream(stream_params, renderer, &signal_renderer::callback); // BOOST_LOG_TRIVIAL(info) << "Starting 5 s recording"; // stream.start(); // stream.stop(); // stream.close(); // sys.terminate(); } catch(const portaudio::PaException &e) { std::cout << "A PortAudio error occured: " << e.paErrorText() << std::endl; } catch(const portaudio::PaCppException &e) { std::cout << "A PortAudioCpp error occured: " << e.what() << std::endl; } catch(const std::exception &e) { std::cout << "A generic exception occured: " << e.what() << std::endl; } catch(...) { std::cout << "An unknown exception occured." << std::endl; } // BOOST_LOG_TRIVIAL(info) << "Input file is " << params.input() << ", " << audio.to_string(); // // initialize filterbank // filterbank fb(audio.sample_frequency(), // params.low_frequency(), // params.high_frequency(), // params.nb_channels()); // BOOST_LOG_TRIVIAL(info) << "Gammatone filtering on " // << params.nb_channels() << " channels from " // << (int)fb.begin()->center_frequency() << "Hz to " // << (int)fb.rbegin()->center_frequency() << "Hz"; // // declare the resulting multichannel cochleogram. // // cochleogram[i][j] where i is audio channel, j is the // // corresponding cochleogram // std::vector<std::vector<double> > cochleogram(audio.nb_channels(), // std::vector<double>(xsize*ysize)); // // xaxis is time, yaxis are center frequencies // const auto xaxis = gammatone::detail::linspace(0.0, audio.duration(), audio.size()); // const auto yaxis = fb.center_frequency(); // const auto xsize = xaxis.size(); // const auto ysize = yaxis.size(); // // process separatly on each audio channel // for(size_t i=0; i<audio.nb_channels(); i++) // { // fb.reset(); // fb.compute(xsize,ysize,audio.channel(i).data(),cochleogram[i].data()); // if(params.normalize()) normalization(xsize,ysize,cochleogram[i].data()); // } // BOOST_LOG_TRIVIAL(info) << "Entering " << renderer::vtk_version(); // renderer vtk(16/9.0); // vtk.render(xaxis,yaxis,cochleogram[0].data()); return 0; }