The execute Function


aboucher - Posted on 02 February 2009

The execute function implements the algorithm itself. It returns an integer indicating whether the algorithm succeeded (returns 0) or failed (returns any value different from 0).

The moving average algorithm proceeds as follows:

  1. Loop through all the nodes of the grid.
  2. At each node u:
    1. retrive the neighbors of u
    2. compute the average of all the neighbors
    3. store the result and proceed to the next node

A possible implementation of this algorithm could be:


int MovingAverage::execute() {
  grid_->select_property( new_prop_name_ );
  neighborhood_->select_property( prop_name_ );

  // iterate through the grid
  for( Geostat_grid::iterator current_node_ptr = grid_->begin() ;
       current_node_ptr != grid_->end() ; ++current_node_ptr ) {

    // find the neighbors of the current node
    neighborhood_->find_neighbors( *current_node_ptr );
   
    // if the current node has no neighbors, skip it
    if( neighborhood_->is_empty() ) continue;


    // compute the average of the neighboring values.
    float sum = 0.0;
    for( Neighborhood::iterator neighbor_ptr = neighborhood_->begin();
               neighbor_ptr != neighborhood_->end() ; ++neighbor_ptr ) {
      sum += neighbor_ptr->property_value();
    }

    // compute the average: divide the sum by the number of values
    sum /= static_cast<float>( neighborhood_->size() );

    // assign the computed average to the current node
    current_node_ptr->set_property_value( sum );
  }
  return 0;
}