示例#1
0
 inline typename boost::enable_if< boost::is_directed_graph<Graph>,
 boost::tuple< typename boost::graph_traits<Graph>::vertex_descriptor,
               typename boost::property_traits<PositionMap>::value_type,
               typename Graph::edge_bundled > >::type 
   operator()(Graph& g,
              RRGVisitor vis,
              PositionMap g_position) const {
   typedef typename boost::property_traits<PositionMap>::value_type PositionValue;
   typedef typename boost::graph_traits<Graph>::vertex_descriptor Vertex;
   typedef typename Graph::edge_bundled EdgeProp;
   typedef boost::tuple< typename boost::graph_traits<Graph>::vertex_descriptor,
                         typename boost::property_traits<PositionMap>::value_type,
                         typename Graph::edge_bundled > ResultType;
   using std::back_inserter;
   
   while(true) {
     PositionValue p_new = get_sample(*space);
     
     std::vector<Vertex> Pred, Succ;
     select_neighborhood(p_new, back_inserter(Pred), back_inserter(Succ), g, *space, g_position);
     
     Vertex x_near; bool was_expanded; EdgeProp ep;
     boost::tie(x_near, was_expanded, ep) = detail::expand_to_nearest(p_new, Pred, g, vis);
     if( was_expanded )
       return ResultType(x_near, p_new, ep);
   };
   
   return ResultType();
 };
示例#2
0
vector<string> vertex_cover(const graph g) {
	vector<connection> list;
	copy(g.begin(), g.end(), back_inserter(list));

	sort(list.begin(), list.end(), [](connection a, connection b) {
		return a.second.size() > b.second.size();
	});

	vector<string> cover;
	while (list.size()) {
		connection max = list.at(0);
		cover.push_back(max.first);

		list.erase(list.begin());

		for (string conc : max.second) {
			if (!list.size())
				break;

			auto to_remove = find_if(list.begin(), list.end(), [conc](connection c) {
				return c.first == conc;
			});

			if (to_remove != list.end()) {
				list.erase(to_remove);
			}
		}
	}

	return cover;
}
示例#3
0
string find_best_key(vector<string> &v) {
    
   
    //Sort the vector by size
    //Gets the longest str length
    sort (v.begin(), v.end(), [](const string& s1, const string& s2){
	   return s1.size() < s2.size();
       }
    );
    
    //Gets the longest str length
    long longest_str_len = v.back().length();
    vector<string> best_keys;
    
    //only copy if the word is the largest
    copy_if(v.begin(), 
            v.end(), 
            back_inserter(best_keys), 
            [longest_str_len](string str) {
                return str.length() == longest_str_len;                        
            }
    );
         
    
    //sort by the value of the keys
    sort(best_keys.begin(), best_keys.end());
    
    //return the smallest key
    return best_keys[0];
     
        
    
}
示例#4
0
文件: accum.cpp 项目: MGZX/cpp_primer
int main()
{
	vector<int> vec(10);              // default initialized to 0
	fill(vec.begin(), vec.end(), 1);  // reset each element to 1

	// sum the elements in vec starting the summation with the value 0
	int sum = accumulate(vec.cbegin(), vec.cend(), 0);
	cout << sum << endl;
	
	// set a subsequence of the container to 10
	fill(vec.begin(), vec.begin() + vec.size()/2, 10);
	cout << accumulate(vec.begin(), vec.end(), 0) << endl;

	// reset the same subsequence to 0
	fill_n(vec.begin(), vec.size()/2, 0);
	cout << accumulate(vec.begin(), vec.end(), 0) << endl;

	// create 10 elements on the end of vec each with the value 42
	fill_n(back_inserter(vec), 10, 42);
	cout << accumulate(vec.begin(), vec.end(), 0) << endl;
	
	// concatenate elements in a vector of strings and store in sum 
	vector<string> v;
	string s;
	while (cin >> s)
		v.push_back(s);
	string concat = accumulate(v.cbegin(), v.cend(), string(""));
	cout << concat << endl;
	
	return 0;
}
示例#5
0
void DevSetup::loadAudioDevices (AudioDevices const& d, QComboBox * cb, QAudioDeviceInfo const& device, QAudioDeviceInfo const& defaultDevice)
{
  using std::copy;
  using std::back_inserter;

  int currentIndex = -1;
  int defaultIndex = 0;
  for (AudioDevices::const_iterator p = d.cbegin (); p != d.cend (); ++p)
    {
      // convert supported channel counts into something we can store in the item model
      QList<QVariant> channelCounts;
      QList<int> scc (p->supportedChannelCounts ());
      copy (scc.cbegin (), scc.cend (), back_inserter (channelCounts));

      cb->addItem (p->deviceName (), channelCounts);
      if (*p == device)
	{
	  currentIndex = p - d.cbegin ();
	}
      else if (*p == defaultDevice)
	{
	  defaultIndex = p - d.cbegin ();
	}
    }
  cb->setCurrentIndex (currentIndex != -1 ? currentIndex : defaultIndex);
}
void spider::PageDownloader::download() const {
    using std::back_inserter;
    using std::string;
    using std::vector;

    try {
        Url const& url = getUrl();
        std::cerr << "Downloading page: " << url << std::endl;
    
        HttpResponse response = getResponse();

        int statusCode = response.getStatusCode();
        if (statusCode < 200 || statusCode >= 400) {
            return;  // ignore errors
        }
        if (statusCode >= 300 && statusCode < 400) {
            handleRedirect(response);
            return;
        }
        
        string content = getContent(response);
        
        vector<Url> urls;
        m_finder.getUrls(url, content, back_inserter(urls));
        
        m_manager.download(url, urls.begin(), urls.end());

    } catch (ConnectionException const& exception) {
        std::cerr << exception.what() << std::endl;
    }
}
int main()
{
  CGAL::set_pretty_mode(cout);

  // build a random convex 20-gon p
  {
    Polygon_2 p;
    random_convex_set_2(20, back_inserter(p), Point_generator(1.0));
    cout << "------------------------------\nInput:\n" << p << endl;
    compute(p.vertices_begin(), p.vertices_end());
  }

  // try identical points
  {
    Polygon_2 p;
    for (int i = 1; i < 3; ++i) {
      cout << "------------------------------\nInput:\n" << p << endl;
      compute(p.vertices_begin(), p.vertices_end());
      p.push_back(Point_2(0,0));
    }
  }


  return 0;
} 
示例#8
0
double average_analysis(const Vec<Student_info>& students)
{
    Vec<double> grades;

    transform(students.begin(), students.end(),
              back_inserter(grades), average_grade);
    return median(grades);
}
void compute(ForwardIterator f, ForwardIterator l)
{
  // compute the minimal enclosing rectangle p_m of p
  Polygon_2 p_r;
  min_rectangle_2(f, l, back_inserter(p_r));
  cout << "Min_rectangle:\n" << p_r << endl;

  // compute the minimal enclosing parallelogram p_p of p
  Polygon_2 p_p;
  min_parallelogram_2(f, l, back_inserter(p_p));
  cout << "Min_parallelogram:\n" << p_p << endl;

  // compute the minimal enclosing strip p_s of p
  Line_2 lines[2];
  min_strip_2(f, l, lines);
  cout << "Min_strip:\n" << lines[0] << "\n" << lines[1] << endl;
}
示例#10
0
vector<Student_info>
extract_fails(vector<Student_info>& students) {
	vector<Student_info> fail;
	remove_copy_if(students.begin(), students.end(),
	               back_inserter(fail), pgrade);
	students.erase(remove_if(students.begin(), students.end(),
	                         fgrade), students.end());
	return fail;
}
示例#11
0
// median of the nonzero elements of `s.homework', or `0' if no such elements exist
double optimistic_median(const Student_info& s)
{
    Vec<double> nonzero;
    remove_copy(s.homework.begin(), s.homework.end(),
                back_inserter(nonzero), 0);

    if (nonzero.empty())
        return grade(s.midterm, s.final, 0);
    else
        return grade(s.midterm, s.final, median(nonzero));
void splitSentenceAndResult(const vector<string> &input, vector<string> *sentence, vector<vector<string>> *correctResultList) {
    for (const auto &str : input) {
        auto split = Utility::splitString(str);
        sentence->emplace_back(move(split[0]));
        vector<string> temp;
        temp.reserve(split.size() - 1);
        move(split.begin() + 1, split.end(), back_inserter(temp));
        correctResultList->emplace_back(move(temp));
    }
}
static bool_vec make_bool_vec(const std::string& str) {
  std::vector<bool> res;
  res.reserve(str.size());
  std::transform(begin(str), end(str), back_inserter(res), [](const char c) {
    assert(c == '0' || c == '1');
    return c == '1';
  });
  assert(res.size() == str.size());
  return res;
}
示例#14
0
int main() {
    vector<int> vec{1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
    list<int> lst;
    copy(vec.crbegin() + 3, vec.crend() - 3, back_inserter(lst));
    for (const auto i : lst){
        cout << i << ' ';
    }
    cout << endl;

    return 0;
}
示例#15
0
vector<Point> chull(const vector<Point>& pst){
    vector<Point> points(pst);
    vector<Point> lupper,llower,edges;
    typedef vector<Point>::size_type vcs;

    sort(points.begin(),points.end(),point_order_x);
    vector<Point>::const_iterator it;

    //Constructing the upper hull. The point with lowest x will be part of
    //the hull
    lupper.push_back(points[0]);
    lupper.push_back(points[1]);

    //Loop the rest of the points to obtain the upper hull
    for(it=points.begin()+2;it!=points.end();++it){
        lupper.push_back(*it);

        //while size>2 and not a right turn
        while ((lupper.size() > 2) && !iscw(lupper))
            lupper.erase(lupper.end() - 2);
    }

    //Constructing the lower hull.
    it = points.end()-1;
    llower.push_back(*it);
    llower.push_back(*(it-1));

    for(it=points.end()-3;it>=points.begin();--it){
        llower.push_back(*it);

        //while size>2 and not a right turn
        while ((llower.size() > 2) && !iscw(llower))
            llower.erase(llower.end() - 2);

    }

    //First llower is already in lupper
    copy(lupper.begin(),lupper.end(),back_inserter(edges));
    copy(llower.begin()+1,llower.end(),back_inserter(edges)); 
    return edges;
}
示例#16
0
void Digraph<K, V>::find_finish(vector<K>& finish) {
    //reset
    search_set.clear();

    for (int i = vertices.size() - 1; i >= 0; i--) {
        if (search_set.count(i) == 0) {
            vector< Vertex<K, V>*> tra;
            dfs_loop(vertices[i], back_inserter(tra));
            count_finish(tra, finish);
        }
    }
    //    cout << finish.size() << " " << vertices.size() << endl;
    assert(finish.size() == vertices.size());
}
示例#17
0
Value * FunctionCallNode::GenerateCode (CodeGeneratorState & state) const {
	Function * callee = state.module->getFunction (this->name.c_str ());
	if (NULL == callee)
		throw "Unknown function called";

	if (callee->arg_size () != this->params->size ())
		throw "Prototype mismatch";

	vector <Value *> arguments;
	arguments.reserve (this->params->size ());
	transform (this->params->begin (), this->params->end (), back_inserter (arguments), bind2nd (mem_fun (& IASTNode::GenerateCode), state));

	return state.builder->CreateCall (callee, arguments.begin (), arguments.end (), "tmp");
}
示例#18
0
void Storage::InsertMeasureSets(
    const map<time_t, vector<entity::Measurement>>& measure_sets)
{
    vector<entity::Measurement> measures;
    for (auto it = measure_sets.begin(); it != measure_sets.end(); ++it) {
        copy(it->second, back_inserter(measures));
    }
    for (auto m_it = measures.begin(); m_it != measures.end(); ++m_it) {
        if (m_it->is_numeric)
            InsertMeasureAsNumeric(*m_it);
        else
            InsertMeasureAsText(*m_it);
    }
}
示例#19
0
void Digraph<K, V>::finish_loop(vector<K>& finish) {
    reverse_edges();
    search_set.clear();
    if (connect.size_of() != vertices.size()) {
        throw exception();
    }
    connect.reset();

    for (int i = finish.size()-1; i >= 0; i--) {
        if (search_set.count(finish[i]) == 0) {
            vector< Vertex<K, V>*> tra;
            dfs_loop(vertices[finish[i]], back_inserter(tra));
            analyse_part(tra);
        }
    }
}
void MorphemeDisambiguatorClass::train(const string &trainingFilename,
                                       size_t concurrency,
                                       size_t maxIter,
                                       double regularizationCoefficientL1,
                                       double regularizationCoefficientL2,
                                       double epsilonForConvergence,
                                       const std::string &modelFilename) {
    ifstream ifs(trainingFilename);
    vector<Observation> observationList;

    while (true) {
        vector<string> sequence = Utility::readSequence(ifs);
        vector<bool> flags;
        bool has_flags = false;
        for (auto &s : sequence) {
            bool flag = false;
            if (!s.empty() && s[0] == '>') {
                s = string(s.begin() + 1, s.end());
                flag = true;
            }
            flags.push_back(flag);
            has_flags = has_flags || flag;
        }
        
        if (!ifs) {
            break;
        }
        vector<string> sentence;
        vector<vector<string>> correctResultList;
        splitSentenceAndResult(sequence, &sentence, &correctResultList);
        auto dictResultListList = lookupSentence(sentence, *dictionary);
        auto commonAttributeSetList = convertSentenceToCommonAttributeSetList(sentence, dictResultListList, options);
        assert(sentence.size() == dictResultListList.size() &&
               sentence.size() == commonAttributeSetList.size());
        for (size_t i = 0; i < sentence.size(); ++i) {
            if (!has_flags || flags[i]) {
                auto o = generateTrainingObservationList(dictResultListList[i], commonAttributeSetList[i], correctResultList[i]);
                move(o.begin(), o.end(), back_inserter(observationList));
            }
        }
    }
    ifs.close();

    MaxEntProcessor maxent;
    maxent.train(observationList, concurrency, maxIter, regularizationCoefficientL1, regularizationCoefficientL2, epsilonForConvergence);
    maxent.writeModel(modelFilename);
}
示例#21
0
int main()
{
    vector<int> iVector;
    cout << "Input a set of int :" << endl;
    istream_iterator<int> inIter(cin);
    istream_iterator<int> endIn;

    ostream_iterator<int> outIter(cout, " ");
    copy(inIter, endIn, back_inserter(iVector));

    for(auto end = iVector.end(); end != iVector.begin();)
    {
        *outIter++ = *(--end);
    }
    cout << endl;
    return(0);
}
示例#22
0
/**
// Constructor.
//
// @param grammar
//  The ParserGrammar to generate this ParserStateMachine from.
//
// @param error_policy
//  The error policy to report errors during generation to or null to 
//  silently swallow errors.
*/
ParserStateMachine::ParserStateMachine( ParserGrammar& grammar, ParserErrorPolicy* error_policy )
{
    ParserGenerator parser_generator( grammar, error_policy );
    if ( parser_generator.errors() == 0 )
    {
        identifier_ = parser_generator.identifier();
        actions_.swap( parser_generator.actions() );
        productions_.swap( parser_generator.productions() );
        symbols_.swap( parser_generator.symbols() );
        states_.reserve( parser_generator.states().size() );
        copy( parser_generator.states().begin(), parser_generator.states().end(), back_inserter(states_) );
        start_symbol_ = parser_generator.start_symbol();
        end_symbol_ = parser_generator.end_symbol();
        error_symbol_ = parser_generator.error_symbol();
        start_state_ = parser_generator.start_state();
        lexer_state_machine_.reset();
    }
}
示例#23
0
int main()
{
    unsigned int size = 11;
    //    std::cin >> size;
    Digraph<int, int> g(size);
    Console_reader r;
    for (unsigned int i = 0; i < size; ++i) {
        g.add_vertex(i, i);
    }
    g.set_edge_istream(r);
    vector<int> res;
    g.scc_size(back_inserter(res));
    unsigned int sum = 0;
    for (auto& i: res) {
        cout << i << " ";
        sum += i;
    }
    //    cout << sum << endl;
    assert(sum == g.vertices.size());
    return 0;
}
示例#24
0
int main() 
{
	vector<int> iVector{ 1, 22, 3434, 83448, 83781 }, iRet;
	// cout the int which is bigger than 1024 using function class
	int count = count_if(iVector.begin(), iVector.end(), bind(std::greater<int>(), _1, 1024));

	vector<string> sVector{"pooh", "hello", "pooh", "world"};
	// find the first string not equal to "pooh"
	vector<string>::iterator position = find_if(sVector.begin(), sVector.end(), bind(std::not_equal_to<string>(), _1, "pooh"));

	// multiplies each element in iVector, and put the result to iRet;
	std::transform(iVector.begin(), iVector.end(), back_inserter(iRet), bind(std::multiplies<int>(), _1, 2));

	cout << "cout : " << count << endl;
	cout << "The first string : " << *position << endl;
	for (const auto& item: iRet) 
	{
		cout << item << " ";
	}
	cout << endl;
	return 0;
}
示例#25
0
void SaveUnweightedDistances(const StudentNetwork& network,
							 const string& filename,
							 FilterFunc filter) {
	ofstream bfs_file{filename};
	for (auto vertex_d : network.GetVertexDescriptors()) {
		auto student_id = network[vertex_d];

		// Determine whether or not we should process this student.
		if (!filter(student_id)) { continue; }

		bfs_file << network[vertex_d] << "\t";

		// unweighted distance stats
		auto unweighted_distances = network.FindUnweightedDistances(vertex_d);

		// get the second member of the pair
		auto distance_values = vector<string>{};
		transform(begin(unweighted_distances), end(unweighted_distances),
				back_inserter(distance_values),
				[](pair<Student::Id, double> elt)
				{ return to_string(elt.second); });
		bfs_file << join(distance_values, "\t") << endl;
	}
}
示例#26
0
int main() {
  vector<int> vec{1, 2, 3, 4, 5, 6, 7, 8, 9};
  vector<int> vec1, vec2;
  list<int> lst;
  auto it1 = back_inserter(vec1);
  auto it2 = front_inserter(lst);
  auto it3 = inserter(vec2, vec2.begin());
  copy(vec.begin(), vec.end(), it1);
  for (auto& x : vec1) {
    cout << x << ' ';
  }
  cout << endl;
  copy(vec.begin(), vec.end(), it2);
  for (auto& x : lst) {
    cout << x << ' ';
  }
  cout << endl;
  copy(vec.begin(), vec.end(), it3);
  for (auto& x : vec2) {
    cout << x << ' ';
  }
  cout << endl;
  return 0;
}
示例#27
0
int main()
{
    vector<int> iVec;
    for (int i = 0; i < 10; ++i)
        iVec.push_back(i);

    print_vector(iVec);

//    vector<int>::iterator itr = find();
    cout << "inserter: ";
    vector<int> vecInserter;
    replace_copy(iVec.begin(), iVec.end(), inserter(vecInserter, vecInserter.begin()), 9, 10);
    print_vector(vecInserter);

    cout << "back_inserter: ";
    vector<int> vecBack;
    replace_copy(iVec.begin(), iVec.end(), back_inserter(vecBack), 9, 10);
    print_vector(vecBack);

    cout << "front_inserter: ";
    list<int> listFront;
    replace_copy(iVec.begin(), iVec.end(), front_inserter(listFront), 9, 10);
    print_list(listFront);
}
示例#28
0
void View::signals_changed()
{
	using sigrok::Channel;

	vector< shared_ptr<TraceTreeItem> > new_top_level_items;

	const auto device = session_.device();
	if (!device)
		return;

	shared_ptr<sigrok::Device> sr_dev = device->device();
	assert(sr_dev);

	const vector< shared_ptr<Channel> > channels(
		sr_dev->channels());

	// Make a list of traces that are being added, and a list of traces
	// that are being removed
	const vector<shared_ptr<Trace>> prev_trace_list = list_by_type<Trace>();
	const set<shared_ptr<Trace>> prev_traces(
		prev_trace_list.begin(), prev_trace_list.end());

	const unordered_set< shared_ptr<Signal> > sigs(session_.signals());

	set< shared_ptr<Trace> > traces(sigs.begin(), sigs.end());

#ifdef ENABLE_DECODE
	const vector< shared_ptr<DecodeTrace> > decode_traces(
		session().get_decode_signals());
	traces.insert(decode_traces.begin(), decode_traces.end());
#endif

	set< shared_ptr<Trace> > add_traces;
	set_difference(traces.begin(), traces.end(),
		prev_traces.begin(), prev_traces.end(),
		inserter(add_traces, add_traces.begin()));

	set< shared_ptr<Trace> > remove_traces;
	set_difference(prev_traces.begin(), prev_traces.end(),
		traces.begin(), traces.end(),
		inserter(remove_traces, remove_traces.begin()));

	// Make a look-up table of sigrok Channels to pulseview Signals
	unordered_map<shared_ptr<sigrok::Channel>, shared_ptr<Signal> >
		signal_map;
	for (const shared_ptr<Signal> &sig : sigs)
		signal_map[sig->channel()] = sig;

	// Populate channel groups
	for (auto entry : sr_dev->channel_groups()) {
		const shared_ptr<sigrok::ChannelGroup> &group = entry.second;

		if (group->channels().size() <= 1)
			continue;

		// Find best trace group to add to
		TraceTreeItemOwner *owner = find_prevalent_trace_group(
			group, signal_map);

		// If there is no trace group, create one
		shared_ptr<TraceGroup> new_trace_group;
		if (!owner) {
			new_trace_group.reset(new TraceGroup());
			owner = new_trace_group.get();
		}

		// Extract traces for the trace group, removing them from
		// the add list
		const vector< shared_ptr<Trace> > new_traces_in_group =
			extract_new_traces_for_channels(group->channels(),
				signal_map, add_traces);

		// Add the traces to the group
		const pair<int, int> prev_v_extents = owner->v_extents();
		int offset = prev_v_extents.second - prev_v_extents.first;
		for (shared_ptr<Trace> trace : new_traces_in_group) {
			assert(trace);
			owner->add_child_item(trace);

			const pair<int, int> extents = trace->v_extents();
			if (trace->enabled())
				offset += -extents.first;
			trace->force_to_v_offset(offset);
			if (trace->enabled())
				offset += extents.second;
		}

		// If this is a new group, enqueue it in the new top level
		// items list
		if (!new_traces_in_group.empty() && new_trace_group)
			new_top_level_items.push_back(new_trace_group);
	}

	// Enqueue the remaining logic channels in a group
	vector< shared_ptr<Channel> > logic_channels;
	copy_if(channels.begin(), channels.end(), back_inserter(logic_channels),
		[](const shared_ptr<Channel>& c) {
			return c->type() == sigrok::ChannelType::LOGIC; });
	const vector< shared_ptr<Trace> > non_grouped_logic_signals =
		extract_new_traces_for_channels(logic_channels,
			signal_map, add_traces);
	const shared_ptr<TraceGroup> non_grouped_trace_group(
		make_shared<TraceGroup>());
	for (shared_ptr<Trace> trace : non_grouped_logic_signals)
		non_grouped_trace_group->add_child_item(trace);
	new_top_level_items.push_back(non_grouped_trace_group);

	// Enqueue the remaining channels as free ungrouped traces
	const vector< shared_ptr<Trace> > new_top_level_signals =
		extract_new_traces_for_channels(channels,
			signal_map, add_traces);
	new_top_level_items.insert(new_top_level_items.end(),
		new_top_level_signals.begin(), new_top_level_signals.end());

	// Enqueue any remaining traces i.e. decode traces
	new_top_level_items.insert(new_top_level_items.end(),
		add_traces.begin(), add_traces.end());

	// Remove any removed traces
	for (shared_ptr<Trace> trace : remove_traces) {
		TraceTreeItemOwner *const owner = trace->owner();
		assert(owner);
		owner->remove_child_item(trace);
	}

	// Add and position the pending top levels items
	for (auto item : new_top_level_items) {
		add_child_item(item);

		// Position the item after the last present item
		int offset = v_extents().second;
		const pair<int, int> extents = item->v_extents();
		if (item->enabled())
			offset += -extents.first;
		item->force_to_v_offset(offset);
		if (item->enabled())
			offset += extents.second;
	}

	update_layout();

	header_->update();
	viewport_->update();
}
示例#29
0
int main(int argc, char *argv[])
{
#if defined(macintosh)
  argc = ccommand(&argv);
#endif

  if (flagOption(argc,argv,"--help") || flagOption(argc,argv,"--pete-help"))
  {
    cout << "gen_operators produces global functions for C++\n";
    cout << "operators (+ - * etc.) that create expression trees.\n";
    cout << "Global assignment operators may be produced as well.\n";
    cout << "This function can also produce operator tag structs.\n\n";

    cout << "Options:\n";
    cout << "--help:           Print this message.\n";
    cout << "--pete-help:      Print this message.\n";
    cout << "--classes file:   Read the class descriptors from file.\n";
    cout << "                  If no class file is provided, then\n";
    cout << "                  no operators or assignment operators\n";
    cout << "                  are produced.\n";
    cout << "--o file:         Name of file to write operator info to.\n";
    cout << "                  If not specified, output goes to the\n";
    cout << "                  terminal.\n";
    cout << "--operators file: Read the operator descriptors from\n";
    cout << "                  file.\n";
    cout << "                  If no operator file is provided, then\n";
    cout << "                  the standard set of PETE operators is\n";
    cout << "                  used (most of the C++ operators).\n";
    cout << "--pete-ops:       Add the set of PETE operators to those\n";
    cout << "                  input from the operator file.\n";
    cout << "--guard string:   Use string for the include guard\n";
    cout << "                  (defaults to GENERATED_OPERATORS_H).\n";
    cout << "--scalars:        If this flag is present, only generate\n";
    cout << "                  operators involving user-defined scalars.";
    cout << "--extra-classes:  If this flag is present, only generate\n";
    cout << "                  operators involving the extraClasses.\n";
    cout << "--no-expression:  If this flag is present, don't generate\n";
    cout << "                  operators involving Expression<T>\n";
    cout << "--assign-ops:     If this flag is present, generate the\n";
    cout << "                  assignment operators that call\n";
    cout << "                  evaluate().\n";
    cout << "--op-tags:        If this flag is present, generate the\n";
    cout << "                  operator tag structs\n";
    cout << "--no-shift-guard: If this flag is present, put no guards\n";
    cout << "                  around the scalar << class and \n";
    cout << "                  scalar >> class operators (they can\n";
    cout << "                  get confused with stream operations).\n\n";

    cout << "These two options are used internally by PETE:\n";
    cout << "--insert-op:      Used to build the file\n";
    cout << "                  src/tools/PeteOps.cpp.\n";
//    cout << "--lanl-boilerplate:  Includes the standard ACL header and\n";
//    cout << "                  footer." << endl;
    return 0;
  }

  vector<string> filesUsed;
  filesUsed.push_back("gen_operators");

  bool printOperators = flagOption(argc,argv,"--classes");
  string cls = stringOption(argc,argv,"--classes","");
  string ofile = stringOption(argc, argv, "--o", "");
  string guardDef(printOperators ?
		  "GENERATED_OPERATORS_H" : "OPERATOR_TAGS_H");
  string includeGuard = stringOption(argc,argv,"--guard",guardDef);
  bool justScalars = flagOption(argc,argv,"--scalars");
  bool justExtraClasses = flagOption(argc,argv,"--extra-classes");
  bool expression = !flagOption(argc,argv,"--no-expression");
  bool assignment = flagOption(argc,argv,"--assign-ops");
  bool printTags = flagOption(argc,argv,"--op-tags");
  bool shiftGuard = !flagOption(argc,argv,"--no-shift-guard");
  bool insertOp = flagOption(argc,argv,"--insert-op");
  bool addPeteOps = (!flagOption(argc,argv,"--operators")) ||
    flagOption(argc,argv,"--pete-ops");
//  bool lanlBoilerplate = flagOption(argc,argv,"--lanl-boilerplate");

  string prefix, suffix;

  // Input the operator descriptors.
  
  map<string, vector<OperatorDescriptor> > mOps;
  map<string, vector<OperatorDescriptor> > inputOps;  

  if (flagOption(argc,argv,"--operators"))
  {
    string ops = stringOption(argc,argv,"--operators","");
    ifstream fOps(ops.c_str());
    filesUsed.push_back(ops);
    PInsist1(!!fOps, "ERROR: couldn't open operator description file \""
	    "%s\"", ops.c_str());

    Parser<OperatorDescriptor> pOps(fOps, ops, mOps);
    pOps.addKeyword("TAG");
    pOps.addKeyword("FUNCTION");
    pOps.addKeyword("EXPR");
    pOps.addKeyword("ARG");
    pOps.addKeyword("STREXPR");

    pOps.parse();
    prefix = pOps.prefixText();
    suffix = pOps.suffixText();
  }
  inputOps = mOps;
 
//// XXX
//vector<OperatorDescriptor> tmp(mOps["unaryOps"]);
//for(int i=0; i< tmp.size(); i++) std::cout<<tmp[i];
 
  if (addPeteOps)
  {
    peteOps(mOps);
  }
  
  // Create vectors for unary operators.
  
  vector<OperatorDescriptor> unaryOps(mOps["unaryOps"]);
  copy(mOps["unaryBoolOps"].begin(), mOps["unaryBoolOps"].end(),
       back_inserter(unaryOps));
  copy(mOps["unarySpecialOps"].begin(), mOps["unarySpecialOps"].end(),
       back_inserter(unaryOps));
  
  vector<OperatorDescriptor> &unaryCastOps = mOps["unaryCastOps"];

  // Create vectors for binary operators.
  
  vector<OperatorDescriptor> binaryOps(mOps["binaryOps"]);
  copy(mOps["binaryBoolOps"].begin(), mOps["binaryBoolOps"].end(),
       back_inserter(binaryOps));
  //  copy(mOps["binaryLeftOps"].begin(), mOps["binaryLeftOps"].end(),
  //       back_inserter(binaryOps));
  copy(mOps["binarySpecialOps"].begin(), mOps["binarySpecialOps"].end(),
       back_inserter(binaryOps));
    
  vector<OperatorDescriptor> binaryLeftOps(mOps["binaryLeftOps"]);

  // Create reference for trinary operators.
  
  vector<OperatorDescriptor> &trinaryOps = mOps["trinaryOps"];
    
  // Create vector for assignment operators.
  
  vector<OperatorDescriptor> assignOps(mOps["assignOp"]);
  copy(mOps["binaryAssignOps"].begin(),
       mOps["binaryAssignOps"].end(),
       back_inserter(assignOps));
  copy(mOps["binaryAssignBoolOps"].begin(),
       mOps["binaryAssignBoolOps"].end(),
       back_inserter(assignOps));

  // Input the class descriptors.

  map<string, vector<ClassDescriptor> > mClasses;  

  vector<ClassDescriptor> classes;
  vector<ClassDescriptor> extraClasses;
  vector<ClassDescriptor> scalars;
  vector<ClassDescriptor> generalT;
  vector<ClassDescriptor> userClasses;
  vector<ClassDescriptor> expressionClass;

  if (printOperators)
  {
    ifstream fClasses(cls.c_str());
    filesUsed.push_back(cls);
    if (justScalars)
    {
      filesUsed.push_back("(Only operations with scalars were printed.)");
    }

    PInsist1(!!fClasses, "ERROR: couldn't open class description file \""
	    "%s\"", cls.c_str());
    
    Parser<ClassDescriptor> pClasses(fClasses, cls, mClasses);

    pClasses.addKeyword("ARG");
    pClasses.addKeyword("CLASS");

    pClasses.parse();
    if (prefix.size() != 0)
      prefix += "\n\n";
    if (suffix.size() != 0)
      suffix += "\n\n";
    prefix += pClasses.prefixText();
    suffix += pClasses.suffixText();
  
    classes = mClasses["classes"];
    extraClasses = mClasses["extraClasses"];
    scalars = mClasses["scalars"];

    userClasses = classes;

    if (expression)
    {
      expressionClass.push_back(ClassDescriptor("class T[n]",
						"Expression<T[n]>"));
      classes.push_back(ClassDescriptor("class T[n]",
					"Expression<T[n]>"));
    }

    if (!justScalars)
      {
	scalars.push_back(ClassDescriptor("class T[n]","T[n]"));
      }
  }

  generalT.push_back(ClassDescriptor("class T[n]","T[n]"));

  // Set up streams for printing.
  
  ostream *ofl = &cout;
  if (ofile != string(""))
    {
      ofl = new ofstream(ofile.c_str());

      PInsist1(ofl != NULL, "ERROR: couldn't open class description file \""
	       "%s\"", ofile.c_str());
      PInsist1(!!*ofl, "ERROR: couldn't open class description file \""
	       "%s\"", ofile.c_str());
    }
        
  // Print header.
  
  printHeader(*ofl,includeGuard,filesUsed,lanlBoilerplate,prefix);

  // The following code is used when we generate PeteOps.cpp from
  // PeteOps.in.  Users should never use the --insert-ops option.

  if (insertOp)
  {
    *ofl << "#include \"OperatorDescriptor.h\"" << endl
	 << "#include <vector>" << endl
	 << "#include <map>" << endl
	 << "#include <string>" << endl
	 << "using std::map;" << endl
	 << "using std::vector;" << endl
	 << "using std::string;" << endl
	 << endl;
    *ofl << endl
	 << "void peteOps(map<string,"
	 << "vector<OperatorDescriptor> > &m)" << endl
	 << "{" << endl;

    map<string,vector<OperatorDescriptor> >::iterator opvec;

    for(opvec = mOps.begin();opvec != mOps.end();++opvec)
    {
      printList(*ofl,InsertOp(opvec->first),opvec->second);
    }

    *ofl << "}" << endl;
  }

  // Print operator tags.
  
  if (printTags)
  {
    printList(*ofl,UnaryOp(),           inputOps["unaryOps"]);
    printList(*ofl,UnaryBoolOp(),       inputOps["unaryBoolOps"]);
    printList(*ofl,UnaryCastOp(),       inputOps["unaryCastOps"]);
    printList(*ofl,UnarySpecialOp(),    inputOps["unarySpecialOps"]);
    printList(*ofl,BinaryOp(),          inputOps["binaryOps"]);
    printList(*ofl,BinaryBoolOp(),      inputOps["binaryBoolOps"]);
    printList(*ofl,BinaryLeftOp(),      inputOps["binaryLeftOps"]);
    printList(*ofl,BinarySpecialOp(),   inputOps["binarySpecialOps"]);
    printList(*ofl,BinaryAssignOp(),    inputOps["binaryAssignOps"]);
    printList(*ofl,BinaryAssignOp(),    inputOps["assignOp"]);
    printList(*ofl,BinaryAssignBoolOp(),inputOps["binaryAssignBoolOps"]);
    printList(*ofl,TrinaryOp(),         inputOps["trinaryOps"]);
  }

  // Print operators.

  if (printOperators)
  {
    if (!justScalars)
    {
      if (!justExtraClasses)
      {
	printList(*ofl,UnaryFunction(),unaryOps,userClasses);
	printList(*ofl,UnaryCastFunction(),unaryCastOps,userClasses);
	printList(*ofl,BinaryFunction(),binaryOps,userClasses,userClasses);
	printList(*ofl,BinaryFunction(),binaryLeftOps,userClasses,userClasses);
	printList(*ofl,BinaryFunction(),binaryOps,
		  userClasses, expressionClass);
	printList(*ofl,BinaryFunction(),binaryLeftOps,
		  userClasses, expressionClass);
	printList(*ofl,BinaryFunction(),binaryOps,
		  expressionClass, userClasses);
	printList(*ofl,BinaryFunction(),binaryLeftOps,
		  expressionClass, userClasses);
      }
      else
      {
	printList(*ofl,UnaryFunction(),unaryOps,extraClasses);
	printList(*ofl,UnaryCastFunction(),unaryCastOps,extraClasses);
	printList(*ofl,BinaryFunction(),binaryOps,extraClasses,extraClasses);
	printList(*ofl,BinaryFunction(),binaryLeftOps,extraClasses,
		  extraClasses);
	printList(*ofl,BinaryFunction(),binaryOps,classes,extraClasses);
	printList(*ofl,BinaryFunction(),binaryLeftOps,classes,extraClasses);
	printList(*ofl,BinaryFunction(),binaryOps,extraClasses,classes);
	printList(*ofl,BinaryFunction(),binaryLeftOps,extraClasses,classes);
      }
    }

    if (!justExtraClasses)
    {
      printList(*ofl,BinaryFunction(),binaryOps,userClasses,scalars);
      printList(*ofl,BinaryFunction(),binaryLeftOps,userClasses,scalars);
      printList(*ofl,BinaryFunction(),binaryOps,scalars,userClasses);
    }
    else
    {
      printList(*ofl,BinaryFunction(),binaryOps,extraClasses,scalars);
      printList(*ofl,BinaryFunction(),binaryLeftOps,extraClasses,scalars);
      printList(*ofl,BinaryFunction(),binaryOps,scalars,extraClasses);
    }

    // The following flag covers the common situation where you define
    // ostream << class.  Some compilers define cout to be a class that
    // inherits from ostream, so the compiler would use the PETE shift
    // operators T << class which defines shift for scalars and the user
    // class.  Since this shift operration is pretty bizzare, and stream
    // output is pretty common, the default behaviour of PETE is to turn
    // off the operators that allow for scalar << container and
    // scalar << expression.

    if (shiftGuard)
    {
      *ofl << "#ifdef PETE_ALLOW_SCALAR_SHIFT" << endl;
    }
    if (!justExtraClasses)
    {
      printList(*ofl,BinaryFunction(),binaryLeftOps,scalars,userClasses);
    }
    else
    {
      printList(*ofl,BinaryFunction(),binaryLeftOps,scalars,extraClasses);
    }
    if (shiftGuard)
    {
      *ofl << "#endif // PETE_ALLOW_SCALAR_SHIFT" << endl;
    }

    if (!justScalars)
    {
      if (!justExtraClasses)
      {
	printList(*ofl,TrinaryFunction(),trinaryOps,userClasses,
		  generalT,generalT);
      }
      else
      {
	printList(*ofl,TrinaryFunction(),trinaryOps,extraClasses,generalT,
		  generalT);
      }
    }


    // Operators involving expression are guarded to make it easy to combine
    // operator files for different classes.  It's possible to generate
    // files that you can combine by using --no-expression for one of them, but
    // this approach is simpler.  Thanks to J. Striegnitz,
    // Research Center Juelich for coming up with this approach.

    if (expression)
    {
      *ofl << "#ifndef PETE_EXPRESSION_OPERATORS" << endl;
      *ofl << "#define PETE_EXPRESSION_OPERATORS" << endl;
      if (printOperators)
      {
	if (!justScalars)
	{
	  if (!justExtraClasses)
	  {
	    printList(*ofl,UnaryFunction(),unaryOps,expressionClass);
	    printList(*ofl,UnaryCastFunction(),unaryCastOps,expressionClass);
	    printList(*ofl,BinaryFunction(),binaryOps,
		      expressionClass, expressionClass);
	    printList(*ofl,BinaryFunction(),binaryLeftOps,
		      expressionClass, expressionClass);
	  }
	}
	
	if (!justExtraClasses)
	{
	  printList(*ofl,BinaryFunction(),binaryOps,expressionClass,scalars);
	  printList(*ofl,BinaryFunction(),binaryLeftOps,
		    expressionClass, scalars);
	  printList(*ofl,BinaryFunction(),binaryOps,scalars,expressionClass);
	}
	
	if (shiftGuard)
	{
	  *ofl << "#ifdef PETE_ALLOW_SCALAR_SHIFT" << endl;
	}
	if (!justExtraClasses)
	{
	  printList(*ofl,BinaryFunction(),binaryLeftOps,scalars,
		    expressionClass);
	}
	if (shiftGuard)
	{
	  *ofl << "#endif // PETE_ALLOW_SCALAR_SHIFT" << endl;
	}

	if (!justScalars)
	{
	  if (!justExtraClasses)
	  {
	    printList(*ofl,TrinaryFunction(),trinaryOps,expressionClass,
		      generalT,generalT);
	  }
	}
      }
      *ofl << "#endif  // PETE_EXPRESSION_OPERATORS" << endl;
    }
  }

  // Print assignment operators.
  
  if (assignment)
  {
    if (!justExtraClasses)
    {
      printList(*ofl,AssignFunctionForClass(),assignOps,userClasses);
    }
    else
    {
      printList(*ofl,AssignFunctionForClass(),assignOps,extraClasses);
    }
  }

  // Print footer.
  
  printFooter(*ofl,includeGuard,lanlBoilerplate,suffix);
  
  // Clean up.
  
  if (ofile != string(""))
    delete ofl;
}
示例#30
0
int global_smooth(ImagePyramid& v_copy, LinkPyramid& w_copy, const level_t lv,
                  const floating_t thresh1, const floating_t thresh2,
                  const size_t top_level)
{
    using boost::transform;
    using boost::adaptors::filter;
    using common::pars;
    using std::back_inserter;
    using stats::print_roots;
    using std::vector;
    using util::fmt;
    using std::cout;
    using std::endl;

    auto root_cnt = 0;

    auto is_weak = [&w_copy, &thresh1](const auto& par, const auto& desc) {
        return w_copy(par, desc) < thresh1;
    };
    auto is_strong = [&w_copy, &thresh2](const auto& par, const auto& desc) {
        return w_copy(par, desc) > thresh2;
    };

    auto is_root = [&w_copy, top_level](const auto& node) {
        return node.level >= top_level ||
               util::is_zero(sum_upward_links(w_copy, node));
    };

    erase_weak_links(w_copy, lv, is_weak);
    normalize(w_copy, lv);

    for (const Node& node : w_copy.nodes(lv)) {
        if (is_root(node) /*|| 1./util::condition(v_copy(node)) < 1e-6*/) {
            root_cnt++;
            continue;
        }
        else {
            auto buf = std::vector<Mat3c> {};
            buf.reserve(4);
            auto is_accepted = [is_strong, &node](auto& par) {
                return is_strong(par, node);
            };

            transform(filter(pars(node), is_accepted), back_inserter(buf),
            [&](auto par) {
                return v_copy(par);
            });

            if (buf.empty()) {
                auto par = strongest_parent(w_copy, node);
                buf.push_back(v_copy(par));
            }

            v_copy(node) = util::average(buf, Mat3c::Zero(3, 3));
        }
    }

    // Print some information
    auto node_range = w_copy.nodes(lv);
    cout << endl;
    stats::print_roots(node_range, is_root);
    stats::print_accepted(node_range, is_strong, is_root);
    cout << "    weak: <" << util::fmt(thresh1, 5) << endl
         << "accepted: >" << util::fmt(thresh2, 5) << endl
         << "   nodes: " << node_range.size() << endl;
    return root_cnt;
} /* smooth_core */