Beispiel #1
0
void C_LinStatExpCovMPinv(SEXP linexpcov, double tol) {

    int pq, pqn;

    /* correct working dimension */    
    pq = get_dimension(linexpcov);

    /* reduce dimension to non-zero variance part */        
    C_linexpcovReduce(linexpcov);
            
    /* reduced dimension */
    pqn = get_dimension(linexpcov);
    INTEGER(GET_SLOT(GET_SLOT(linexpcov, PL2_svdmemSym), PL2_pSym))[0] = pqn;
 
    /* compute MPinv in reduced dimension */                   
    /* GET_SLOT is assumed NOT to return a fresh object so
       we don't PROTECT here */
    C_MPinv(PROTECT(GET_SLOT(linexpcov, PL2_covarianceSym)), tol,
            PROTECT(GET_SLOT(linexpcov, PL2_svdmemSym)), linexpcov);
    UNPROTECT(2);

    /* make sure to reset svdmem to original dimension;
       the dimension of linexpcov is reset in C_TestStatistic */
    INTEGER(GET_SLOT(GET_SLOT(linexpcov, PL2_svdmemSym), PL2_pSym))[0] = pq;
}
Beispiel #2
0
void MPI_Reduce_Hypercube(void* sendbuf, void* recvbuf, int count, MPI_Datatype datatype, MPI_Op op, int iproc, int nproc, int from_proc, MPI_Comm comm)
{
    if(nproc == 1) return; // TODO really we should just copy sendbuf to recvbuf
    MPI_Status status;
    iproc = (iproc - from_proc) % nproc;
    
    int i, j;
    int dimension = get_dimension(nproc - 1);
    int my_dimension = get_dimension(iproc);
    int bit_mask = 1;
    int my_neighbor = iproc;
    
    bit_mask = bit_mask << (dimension - 1);
    
    for(i = 0; i < dimension; i++)
    {
        my_neighbor = iproc ^ bit_mask;
        if(my_neighbor < nproc)
        {
            my_neighbor = (my_neighbor + from_proc) % nproc;
            if(my_dimension > get_dimension(bit_mask))
            {
                // printf("%d am doing nothing\n", iproc);
            }
            else
            {
                if(iproc >= bit_mask)
                {
                    // printf("%d am sending to %d\n", iproc, my_neighbor);
                    MPI_Send(sendbuf, count, datatype, my_neighbor, 0, comm);
                }
                else
                {
                    // printf("%d am receiving a message from %d\n", iproc, my_neighbor);
                    MPI_Recv(recvbuf, count, datatype, my_neighbor, 0, comm, &status);
                    if(datatype == MPI_DOUBLE)
                    {
                        double* sbuf = (double*) sendbuf;
                        double* rbuf = (double*) recvbuf;
                        // perform a sum reduce
                        if(op == MPI_SUM)
                        {
                            for(j = 0; j < count; j++)
                            {
                                *(sbuf + j) = *(sbuf + j) + *(rbuf + j);
                                *(rbuf + j) = *(sbuf + j);
                            }
                        }
                    }
                }
            }
        }
        bit_mask = bit_mask >> 1;
    }
}
Beispiel #3
0
/*!
	Extracts all the neighbours of the specified cell for the given
	codimension.

	\param id is the id of the cell
	\param codimension the codimension for which the neighbours
	are requested. For a three-dimensional cell a codimension
	equal 1 will extract the face neighbours, a codimension equal
	2 will extract the edge negihbours and a codimension equal
	3 will extract the vertex neighbours. For a two-dimensional
	cell a codimension qual 1 will extract the face neighbours,
	and a codimension equal 2 will extract the vertex neighbours.
	\param complete controls if the list of neighbours should contain
	only the neighbours for the specified codimension, or should contain
	also the neighbours for lower codimensions.
	\result The neighbours for the specified codimension.
*/
std::vector<long> Patch::extract_cell_neighs(const long &id, int codimension, bool complete) const
{
	assert(codimension >= 1 && codimension <= get_dimension());

	if (codimension == 1) {
		return extract_cell_face_neighs(id);
	} else if (codimension == get_dimension()) {
		return extract_cell_vertex_neighs(id, complete);
	} else if (codimension == 2) {
		return extract_cell_edge_neighs(id, complete);
	} else {
		return std::vector<long>();
	}
}
Beispiel #4
0
earth_planet::earth_planet(int segments, std::string target, const double &ctol) : base(base_format(1,segments,1000).size(), 0, 1, 6 + segments + 1 +1, segments+2,ctol),
 encoding(1,segments,1000), vmax(3000),n_segments(segments)
{
	std::vector<double> lb_v(get_dimension());
	std::vector<double> ub_v(get_dimension());

	//Start
	lb_v[encoding.leg_start_epoch_i(0)[0]] = 0;
	ub_v[encoding.leg_start_epoch_i(0)[0]] = 1000;

	//End
	lb_v[encoding.leg_end_epoch_i(0)[0]] = 500;
	ub_v[encoding.leg_end_epoch_i(0)[0]] = 1500;

	//Start Velocity
	std::vector<int> tmp = encoding.leg_start_velocity_i(0);
	for (std::vector<int>::size_type i = 0; i < tmp.size() ; ++i)
	{
		lb_v[tmp[i]] = -3;
		ub_v[tmp[i]] = 3;
	}

	//End Velocity
	tmp = encoding.leg_end_velocity_i(0);
	for (std::vector<int>::size_type i = 0; i < tmp.size() ; ++i)
	{
		lb_v[tmp[i]] = 0;
		ub_v[tmp[i]] = 0;
	}

	//I Throttles
	for (int j = 0; j<encoding.n_segments(0); ++j)
	{
		tmp = encoding.segment_thrust_i(0,j);
		for (std::vector<int>::size_type i = 0; i < tmp.size() ; ++i)
		{
			lb_v[tmp[i]] = -1;
			ub_v[tmp[i]] = 1;
		}
	}

	set_bounds(lb_v,ub_v);

	//traj_fb constructor
	std::vector<planet_ptr> sequence;
	sequence.push_back(planet_ptr(new planet_ss("earth")));
	sequence.push_back(planet_ptr(new planet_ss(target)));
	trajectory = fb_traj(sequence,segments,1000,0.05,boost::numeric::bounds<double>::highest());
}
double GSLOptimizer::optimize(unsigned int iter,
                              const gsl_multimin_fminimizer_type*t,
                              double ms, double mxs) {
  fis_= get_optimized_attributes();
  best_score_=std::numeric_limits<double>::max();
  unsigned int n= get_dimension();
  if (n ==0) {
    IMP_LOG(TERSE, "Nothing to optimize" << std::endl);
    return get_scoring_function()->evaluate(false);
  }
  gsl_multimin_fminimizer *s=gsl_multimin_fminimizer_alloc (t, n);

  gsl_vector *x= gsl_vector_alloc(get_dimension());
  update_state(x);
  gsl_vector *ss= gsl_vector_alloc(get_dimension());
  gsl_vector_set_all(ss, mxs);

  gsl_multimin_function f= internal::create_f_function_data(this);
  gsl_multimin_fminimizer_set (s, &f, x, ss);
  try {
    int status;
    do {
      --iter;
      //update_state(x);
      status = gsl_multimin_fminimizer_iterate(s);
      if (status) {
        IMP_LOG(TERSE, "Ending optimization because of state " << s
                << std::endl);
        break;
      }
      double sz= gsl_multimin_fminimizer_size(s);
      status= gsl_multimin_test_size(sz, ms);
      update_states();
      if (status == GSL_SUCCESS) {
        IMP_LOG(TERSE, "Ending optimization because of small size " << sz
                << std::endl);
        break;
      }
    } while (status == GSL_CONTINUE && iter >0);
  } catch (AllDone){
  }
  gsl_vector *ret=gsl_multimin_fminimizer_x (s);
  best_score_=gsl_multimin_fminimizer_minimum (s);
  write_state(ret);
  gsl_multimin_fminimizer_free (s);
  gsl_vector_free (x);
  return best_score_;
}
Beispiel #6
0
/**
 * Constructor using std::vector (for python exposition purposes)
 *
 * @param[in] p base::problem to be rotated
 * @param[in] rotation std::vector<std::vector<double> > expressing the problem rotation
 *
 * @see problem::base constructors.
 */
rotated::rotated(const base &p,
				 const std::vector<std::vector<double> > &rotation):
		base_meta(
		 p,
		 p.get_dimension(),
		 p.get_i_dimension(),
		 p.get_f_dimension(),
		 p.get_c_dimension(),
		 p.get_ic_dimension(),
		 p.get_c_tol()),
	m_Rotate(),m_normalize_translation(), m_normalize_scale()
{
	if(!(rotation.size()==get_dimension())){
			pagmo_throw(value_error,"The input matrix dimensions seem incorrect");
	}
	if(p.get_i_dimension()>0){
		pagmo_throw(value_error,"Input problem has an integer dimension. Cannot rotate it.");
	}
	m_Rotate.resize(rotation.size(),rotation.size());
	for (base::size_type i = 0; i < rotation.size(); ++i) {
		if(!(rotation.size()==rotation[i].size())){
			pagmo_throw(value_error,"The input matrix seems not to be square");
		}
		for (base::size_type j = 0; j < rotation[i].size(); ++j) {
			m_Rotate(i,j) = rotation[i][j];
		}
	}
	m_InvRotate = m_Rotate.transpose();
	
	Eigen::MatrixXd check = m_InvRotate * m_Rotate;
	if(!check.isIdentity(1e-5)){
		pagmo_throw(value_error,"The input matrix seems not to be orthonormal (to a tolerance of 1e-5)");
	}
	configure_new_bounds();
}
Beispiel #7
0
double C_TestStatistic(const SEXP linexpcov, const int type, const double tol) {

    int pq;
    double ans = 0.0;

    /* this is possibly the reduced one, see C_LinStatExpCovMPinv */    
    pq = get_dimension(linexpcov);

    switch(type) {
        /* maxabs-type test statistic */
        case 1:
            ans = C_maxabsTestStatistic(
                REAL(GET_SLOT(linexpcov, PL2_linearstatisticSym)),
                REAL(GET_SLOT(linexpcov, PL2_expectationSym)),
                REAL(GET_SLOT(linexpcov, PL2_covarianceSym)),
                pq, tol);
            break;
        /* quadform-type test statistic */
        case 2:
            ans = C_quadformTestStatistic(
                REAL(GET_SLOT(linexpcov, PL2_linearstatisticSym)), 
                REAL(GET_SLOT(linexpcov, PL2_expectationSym)),
                REAL(GET_SLOT(linexpcov, PL2_MPinvSym)), pq);
            break;
        default: error("C_TestStatistic: undefined value for type argument");
    }

    /* dimension was potentially reduced; reset to initial value */
    INTEGER(GET_SLOT(linexpcov, PL2_dimensionSym))[0] = 
        LENGTH(GET_SLOT(linexpcov, PL2_linearstatisticSym));

    return(ans);
}
Beispiel #8
0
void RaytracerApplication::render()
{
    int width, height;

    get_dimension( &width, &height );
    glViewport( 0, 0, width, height );

    Camera& camera = scene.camera;
    camera.aspect = real_t( width ) / real_t( height );

    glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );

    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();
    glMatrixMode( GL_MODELVIEW );
    glLoadIdentity();

    if ( raytracing ) {
        assert( buffer );
        glColor4d( 1.0, 1.0, 1.0, 1.0 );
        glRasterPos2f( -1.0f, -1.0f );
        glDrawPixels( buf_width, buf_height, GL_RGBA, GL_UNSIGNED_BYTE, &buffer[0] );

    } else {
        glPushAttrib( GL_ALL_ATTRIB_BITS );
        render_scene( scene );
        glPopAttrib();
    }
}
Beispiel #9
0
void RaytracerApplication::handle_event( const SDL_Event& event )
{
    int width, height;

    if ( !raytracing ) {
        camera_control.handle_event( this, event );
    }

    switch ( event.type )
    {
    case SDL_KEYDOWN:
        switch ( event.key.keysym.sym )
        {
        case KEY_RAYTRACE:
            get_dimension( &width, &height );
            toggle_raytracing( width, height );
            break;
        case KEY_SCREENSHOT:
            output_image();
            break;
        default:
            break;
        }
    default:
        break;
    }
}
Beispiel #10
0
/// Implementation of the sparsity structure
void luksan_vlcek_3::set_sparsity(int &lenG, std::vector<int> &iGfun, std::vector<int> &jGvar) const
{
	//Initial point
	decision_vector x0(get_dimension(),1);
	//Numerical procedure
	estimate_sparsity(x0, lenG, iGfun, jGvar);
}
gsl_vector* GSLOptimizer::get_state() const {
  gsl_vector *r= gsl_vector_alloc (get_dimension());
  for (unsigned int i=0; i< fis_.size(); ++i) {
    gsl_vector_set(r, i, get_scaled_value(fis_[i]));
  }
  return r;
}
Beispiel #12
0
void RaytracerApplication::handle_event( const SDL_Event& event )
{
    int width, height;

    if ( !raytracing ) {
        camera_control.handle_event( this, event );
    }

    switch ( event.type )
    {
    case SDL_KEYDOWN:
        switch ( event.key.keysym.sym )
        {
        case KEY_RAYTRACE:
            get_dimension( &width, &height );
            toggle_raytracing( width, height );
            break;
        case KEY_SEND_PHOTONS:
            raytracer.initialize(&scene, options.num_samples, 0, 0);
            queue_render_photon=true;
            
        case KEY_SCREENSHOT:
            output_image();
            break;
        default:
            break;
        }
    default:
        break;
    }
}
Beispiel #13
0
double C_ConditionalPvalue(const double tstat, SEXP linexpcov,
                           const int type, double tol,
                           int *maxpts, double *releps, double *abseps) {
                           
    int pq;
    double ans = 1.0;
    
    pq = get_dimension(linexpcov);

    switch(type) {
        /* maxabs-type test statistic */
        case MAXABS:
            ans = C_maxabsConditionalPvalue(tstat,
                REAL(GET_SLOT(linexpcov, PL2_covarianceSym)),
                pq, maxpts, releps, abseps, &tol);
            break;
        /* quadform-type test statistic */
        case QUADFORM:
            /* var = 0 => rank = 0 */
            if (REAL(GET_SLOT(linexpcov, PL2_rankSym))[0] > 0.5)
                ans = C_quadformConditionalPvalue(tstat, 
                    REAL(GET_SLOT(linexpcov, PL2_rankSym))[0]);
            break;
        default: error("C_ConditionalPvalue: undefined value for type argument");
    }
    return(ans);
}
Beispiel #14
0
void PhysicsApplication::render()
{
    int width, height;

    // query current window size, resize viewport
    get_dimension( &width, &height );
    glViewport( 0, 0, width, height );

    // fix camera aspect
    Camera& camera = scene.camera;
    camera.aspect = real_t( width ) / real_t( height );

    // clear buffer
    glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );

    // reset matrices
    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();
    glMatrixMode( GL_MODELVIEW );
    glLoadIdentity();

    glPushAttrib( GL_ALL_ATTRIB_BITS );
    render_scene( scene );
    glPopAttrib();
}
Beispiel #15
0
point  bordered::calc_element_dimension() const {
	auto dim=get_dimension() -  point{ right+left, top+bottom };
	return {
		std::max(dim.x, 0),
		std::max(dim.y, 0)
	};
}
Beispiel #16
0
void frame::set_cursor(const point& pt) {
	CONS_ASSERT(handle, "invalid handle");
	if(wmove(handle.get(), pt.y, pt.x)==ERR) {
		std::ostringstream oss;
		oss << "Unable to move cursor to " << pt
		    << "\tFrame dimensions are " << get_dimension();
		throw CONS_MAKE_EXCEPTION(oss.str());
	}
}
Beispiel #17
0
void frame::set_dimension(const point& dimension) {
	CONS_ASSERT(handle, "inavlid handle");
	if(wresize(handle.get(), dimension.y, dimension.x)==ERR) {
		std::ostringstream oss;
		oss << "Unable to resize frame from: " << get_dimension() 
		    << " to "                          << dimension;
		throw CONS_MAKE_EXCEPTION(oss.str());
	}
	touchwin(handle.get());
}
Beispiel #18
0
/**
 * _gtk_size_group_get_child_requisition:
 * @widget: a #GtkWidget
 * @requisition: location to store computed requisition.
 * 
 * Retrieve the "child requisition" of the widget, taking account grouping
 * of the widget's requisition with other widgets.
 **/
void
_gtk_size_group_get_child_requisition (GtkWidget      *widget,
				       GtkRequisition *requisition)
{
  initialize_size_group_quarks ();

  if (requisition)
    {
      if (get_size_groups (widget))
	{
	  requisition->width = get_dimension (widget, GTK_SIZE_GROUP_HORIZONTAL);
	  requisition->height = get_dimension (widget, GTK_SIZE_GROUP_VERTICAL);

	  /* Only do the full computation if we actually have size groups */
	}
      else
	get_fast_child_requisition (widget, requisition);
    }
}
Beispiel #19
0
/// Implementation of the sparsity structure: automated detection
void earth_planet::set_sparsity(int &lenG, std::vector<int> &iGfun, std::vector<int> &jGvar) const
{
	//Initial point
	decision_vector x0(get_dimension());
	for (pagmo::decision_vector::size_type i = 0; i<x0.size(); ++i)
	{
		x0[i] = get_lb()[i] + (get_ub()[i] - get_lb()[i]) / 3.12345;
	}
	//Numerical procedure
	estimate_sparsity(x0, lenG, iGfun, jGvar);
}
Beispiel #20
0
//Content
point frame::write(const point& pt, char ch) {
	CONS_ASSERT(handle, "inavlid handle");
	set_cursor(pt); //throws
	if(waddch(handle.get(), ch)==ERR) {
		std::ostringstream oss;
		oss << "Unable to write char to frame at point: " << pt 
			<< " frame size: " << get_dimension();
		throw CONS_MAKE_EXCEPTION(oss.str());
	}
	return get_cursor();
}
Beispiel #21
0
point frame::write(const point& pt, const std::string& str) {
	CONS_ASSERT(handle, "inavlid handle");
	set_cursor(pt); //throws
	if(waddstr(handle.get(), str.c_str())==ERR) {
		std::ostringstream oss;
		oss << "Unable to write string to frame at point: " << pt 
		    << " string size: " << str.size()
			<< " frame size: " << get_dimension();
		throw CONS_MAKE_EXCEPTION(oss.str());
	}
	return get_cursor();
}
Beispiel #22
0
void MPI_Broadcast_Hypercube(void* buffer, int count, MPI_Datatype datatype, int iproc, int nproc, int from_proc, MPI_Comm comm)
{
    if(nproc == 1) return;
    MPI_Status status; 
    iproc = (iproc - from_proc) % nproc;
    
    int i;
    int dimension = get_dimension(nproc - 1);
    int my_dimension = get_dimension(iproc);
    int bit_mask = 1;
    int my_neighbor = iproc;
    
    for(i = 0; i < dimension; i++)
    {
        my_neighbor = iproc ^ bit_mask;
        if(my_neighbor < nproc)
        {
            my_neighbor = (my_neighbor + from_proc) % nproc;
            if(iproc < bit_mask)
            {
                //printf("%d: sending to %d\n", iproc, my_neighbor);
                MPI_Send(buffer, count, datatype, my_neighbor, 0, comm);
            }
            else
            {
                if(my_dimension == get_dimension(bit_mask))
                {
                    //printf("%d: receiving a message from %d\n", iproc, my_neighbor);
                    MPI_Recv(buffer, count, datatype, my_neighbor, 0, comm, &status);
                }
                else
                {
                    // printf("%d: not doing anything\n", iproc);
                }
            }
        }
        bit_mask = bit_mask << 1;
    }
}
Beispiel #23
0
/* Get the dimensions of the variable and add it to the index.
   This is complicated because of references to other variables */
void process_dimensions (
        struct adios_var_header_struct_v1 * var_header,
        struct adios_index_var_struct_v1 * v_index
        )
{
    // Get number of dimensions first
    struct adios_dimension_struct_v1 * d = var_header->dims;
    v_index->characteristics [0].dims.count = 0;
    while (d)
    {
        v_index->characteristics [0].dims.count++;
        d = d->next;
    }

    if (v_index->characteristics [0].dims.count)
    {
        // (local, global, local offset)
        v_index->characteristics [0].dims.dims = malloc
            (3 * 8 * v_index->characteristics [0].dims.count);

        int j;
        d = var_header->dims;
        for (j = 0; j < v_index->characteristics [0].dims.count; j++)
        {
            v_index->characteristics [0].dims.dims [j * 3 + 0] =
                get_dimension (&d->dimension, 1);
            v_index->characteristics [0].dims.dims [j * 3 + 1] =
                get_dimension (&d->global_dimension, 0);
            v_index->characteristics [0].dims.dims [j * 3 + 2] =
                get_dimension (&d->local_offset, 0);

            d = d->next;
        }
    } 
    else
    {
        v_index->characteristics [0].dims.dims = NULL;
    }
}
Beispiel #24
0
void C_LinStatExpCovMPinv(SEXP linexpcov, double tol) {

    int pq, pqn;

    /* correct working dimension */    
    pq = get_dimension(linexpcov);

    /* reduce dimension to non-zero variance part */        
    C_linexpcovReduce(linexpcov);
            
    /* reduced dimension */
    pqn = get_dimension(linexpcov);
    INTEGER(GET_SLOT(GET_SLOT(linexpcov, PL2_svdmemSym), PL2_pSym))[0] = pqn;
 
    /* compute MPinv in reduced dimension */                   
    C_MPinv(GET_SLOT(linexpcov, PL2_covarianceSym), tol,
            GET_SLOT(linexpcov, PL2_svdmemSym), linexpcov);

    /* make sure to reset svdmem to original dimension;
       the dimension of linexpcov is reset in C_TestStatistic */
    INTEGER(GET_SLOT(GET_SLOT(linexpcov, PL2_svdmemSym), PL2_pSym))[0] = pq;
}
Beispiel #25
0
void Application::take_screenshot()
{
    static const size_t MAX_LEN = 256;
    char filename[MAX_LEN];
    int width, height;

    get_dimension( &width, &height );
    imageio_gen_name( filename, MAX_LEN );

    if ( imageio_save_screenshot( filename, width, height ) ) {
        std::cout << "Saved image to '" << filename << "'.\n";
    } else {
        std::cout << "Error saving raytraced image to '" << filename << "'.\n";
    }
}
Beispiel #26
0
point frame::write(const point& pt, std::string::const_iterator first, 
                                    std::string::const_iterator last) {
	CONS_ASSERT(handle, "invalid handle");
	set_cursor(pt); //throws
	if(waddnstr(handle.get(), &*first, std::distance(first, last))==ERR) {

		std::ostringstream oss;
		oss << "Unable to write string to frame   no. of chars: " 
		    << std::distance(first, last) 
			<< " size: " << get_dimension() 
			<< " pos " << pt;
		throw CONS_MAKE_EXCEPTION(oss.str());
	}
	return get_cursor();
}
Beispiel #27
0
void bordered::refresh() {
	frame_.clear();
 	auto dim=get_dimension();

	if(right
	&& mvwvline(frame_.get_handle(), 0, dim.x-1, '|', dim.y)) {
		throw CONS_MAKE_EXCEPTION("unable to draw right border");
	}
	if(left
	&& mvwvline(frame_.get_handle(), 0, 0, '|', dim.y)) {
		throw CONS_MAKE_EXCEPTION("unable to draw left border");
	}
	if(top
	&& mvwhline(frame_.get_handle(), 0, 0, '-', dim.x)) {
		throw CONS_MAKE_EXCEPTION("unable to draw top border");
	}
	if(bottom
	&& mvwhline(frame_.get_handle(), dim.y-1, 0, '-', dim.x)) {
		throw CONS_MAKE_EXCEPTION("unable to draw bottom border");
	}
	frame_.refresh();
	if(element) element->refresh();
}
Beispiel #28
0
void RaytracerApplication::render()
{
    int width, height;

    // query current window size, resize viewport
    get_dimension( &width, &height );
    glViewport( 0, 0, width, height );

    // fix camera aspect
    Camera& camera = scene.camera;
    camera.aspect = real_t( width ) / real_t( height );

    // clear buffer
    glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );

    // reset matrices
    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();
    glMatrixMode( GL_MODELVIEW );
    glLoadIdentity();

    if ( raytracing ) {
        // if raytracing, just display the buffer
        assert( buffer );
        glColor4d( 1.0, 1.0, 1.0, 1.0 );
        glRasterPos2f( -1.0f, -1.0f );
        glDrawPixels( buf_width, buf_height, GL_RGBA,
              GL_UNSIGNED_BYTE, &buffer[0] );

    } else {
        // else, render the scene using opengl
        glPushAttrib( GL_ALL_ATTRIB_BITS );
        render_scene( scene );
        glPopAttrib();
    }
}
Beispiel #29
0
void get_grid_params(e *E){

    int      t,i,j,k;

    int	     temp_id;
    int      salt_id;
    int      status = 0;
    float    scale = 1.0;
    float    offset = 0.0;

    // open the mom4 temperature file and read the dimensions info
   if ((E->retval = nc_open(E->temperature_file_name, NC_NOWRITE, &E->ncid)))
		fail("couldn't open temperature file\n");	

    get_dimension(E, "xt_ocean", &E->xt_ocean);
    get_dimension(E, "yt_ocean", &E->yt_ocean);
    get_dimension(E, "st_ocean", &E->st_ocean);
    get_dimension(E, "Time", &E->time);

    E->T = malloc4d_double(E->time+1, E->st_ocean, E->yt_ocean, E->xt_ocean); 
    get_field(E,"temp", &E->T[0][0][0][0]);

    E->lon = malloc(E->xt_ocean*sizeof(double));
    E->lat = malloc(E->yt_ocean*sizeof(double));
    E->depth = malloc(E->st_ocean*sizeof(double));
    E->times = malloc(E->time*sizeof(double));

    get_field(E, "xt_ocean", &E->lon[0]);
    get_field(E, "yt_ocean", &E->lat[0]);
    get_field(E, "st_ocean", &E->depth[0]);
    get_field(E, "Time", &E->times[0]);   

 
    // read in the _FillValue
    nc_inq_varid (E->ncid, "temp", &temp_id);
    nc_get_att_float(E->ncid, temp_id, "_FillValue", &E->fillValue_temp);
    //printf("fillValue = %f\n", E->fillValue);
    // read in the scale and offset
    status = nc_get_att_float(E->ncid, temp_id, "scale_factor", &scale);
    if(status != NC_NOERR) scale = 1.0;
    status = nc_get_att_float(E->ncid, temp_id, "add_offset", &offset);
    if(status != NC_NOERR) offset = 0.0;

    //printf("scale = %f\noffset = %f\n", scale, offset);	
    // apply scale and offset to fillvalue
    if(status == NC_NOERR) E->fillValue_temp = E->fillValue_temp*scale + offset;
 
    // unpack the data
    for(t=0;t<E->time;t++){
        for(i=0;i<E->st_ocean;i++){
            for(j=0;j<E->yt_ocean;j++){
                for(k=0;k<E->xt_ocean;k++){
                    E->T[t][i][j][k] = E->T[t][i][j][k]*scale + offset;
                }
            }
         }
     }

    nc_close(E->ncid);
    


    // get salinity
    if ((E->retval = nc_open(E->salinity_file_name, NC_NOWRITE, &E->ncid)))
		fail("couldn't open salinity file\n");	
    
    E->S = malloc4d_double(E->time+1, E->st_ocean, E->yt_ocean, E->xt_ocean); 
    get_field(E,"salt", &E->S[0][0][0][0]);

    // malloc room for the sound speed variable
    E->c = malloc4d_double(E->time+1, E->st_ocean, E->yt_ocean, E->xt_ocean);

    // read in scale factor and offsets for temp and salinity
    // read in _FillValue for temp and salinity
    // read in st_ocean (metres)


    // read in the _FillValue
    nc_inq_varid (E->ncid, "salt", &salt_id);
    nc_get_att_float(E->ncid, salt_id, "_FillValue", &E->fillValue_salt);
    //printf("fillValue = %f\n", E->fillValue);
    // read in the scale and offset
    status = nc_get_att_float(E->ncid, salt_id, "scale_factor", &scale);
    if(status != NC_NOERR) scale = 1.0;
    status = nc_get_att_float(E->ncid, salt_id, "add_offset", &offset);
    if(status != NC_NOERR) offset = 0.0;
    //printf("scale = %f\noffset = %f\n", scale, offset);
    
    // apply scale and offset to fillvalue
    if(status == NC_NOERR) E->fillValue_salt = E->fillValue_salt*scale + offset;
    nc_close(E->ncid);
    
    
    // unpack the data
    for(t=0;t<E->time;t++){
        for(i=0;i<E->st_ocean;i++){
            for(j=0;j<E->yt_ocean;j++){
                for(k=0;k<E->xt_ocean;k++){
                    E->S[t][i][j][k] = E->S[t][i][j][k]*scale + offset;
                }
            }
         }
     }

    nc_close(E->ncid);

}
Beispiel #30
0
void C_Node(SEXP node, SEXP learnsample, SEXP weights,
            SEXP fitmem, SEXP controls, int TERMINAL, int depth) {

    int nobs, ninputs, jselect, q, j, k, i;
    double mincriterion, sweights, *dprediction;
    double *teststat, *pvalue, smax, cutpoint = 0.0, maxstat = 0.0;
    double *standstat, *splitstat;
    SEXP responses, inputs, x, expcovinf, linexpcov;
    SEXP varctrl, splitctrl, gtctrl, tgctrl, split, testy, predy;
    double *dxtransf, *thisweights;
    int *itable;

    nobs = get_nobs(learnsample);
    ninputs = get_ninputs(learnsample);
    varctrl = get_varctrl(controls);
    splitctrl = get_splitctrl(controls);
    gtctrl = get_gtctrl(controls);
    tgctrl = get_tgctrl(controls);
    mincriterion = get_mincriterion(gtctrl);
    responses = GET_SLOT(learnsample, PL2_responsesSym);
    inputs = GET_SLOT(learnsample, PL2_inputsSym);
    testy = get_test_trafo(responses);
    predy = get_predict_trafo(responses);
    q = ncol(testy);

    /* <FIXME> we compute C_GlobalTest even for TERMINAL nodes! </FIXME> */

    /* compute the test statistics and the node criteria for each input */
    C_GlobalTest(learnsample, weights, fitmem, varctrl,
                 gtctrl, get_minsplit(splitctrl),
                 REAL(S3get_teststat(node)), REAL(S3get_criterion(node)), depth);

    /* sum of weights: C_GlobalTest did nothing if sweights < mincriterion */
    sweights = REAL(GET_SLOT(GET_SLOT(fitmem, PL2_expcovinfSym),
                             PL2_sumweightsSym))[0];
    REAL(VECTOR_ELT(node, S3_SUMWEIGHTS))[0] = sweights;

    /* compute the prediction of this node */
    dprediction = REAL(S3get_prediction(node));

    /* <FIXME> feed raw numeric values OR dummy encoded factors as y
       Problem: what happens for survival times ? */
    C_prediction(REAL(predy), nobs, ncol(predy), REAL(weights),
                 sweights, dprediction);
    /* </FIXME> */

    teststat = REAL(S3get_teststat(node));
    pvalue = REAL(S3get_criterion(node));

    /* try the two out of ninputs best inputs variables */
    /* <FIXME> be more flexible and add a parameter controlling
               the number of inputs tried </FIXME> */
    for (j = 0; j < 2; j++) {

        smax = C_max(pvalue, ninputs);
        REAL(S3get_maxcriterion(node))[0] = smax;

        /* if the global null hypothesis was rejected */
        if (smax > mincriterion && !TERMINAL) {

            /* the input variable with largest association to the response */
            jselect = C_whichmax(pvalue, teststat, ninputs) + 1;

            /* get the raw numeric values or the codings of a factor */
            x = get_variable(inputs, jselect);
            if (has_missings(inputs, jselect)) {
                expcovinf = GET_SLOT(get_varmemory(fitmem, jselect),
                                     PL2_expcovinfSym);
                thisweights = C_tempweights(jselect, weights, fitmem, inputs);
            } else {
                expcovinf = GET_SLOT(fitmem, PL2_expcovinfSym);
                thisweights = REAL(weights);
            }

            /* <FIXME> handle ordered factors separatly??? </FIXME> */
            if (!is_nominal(inputs, jselect)) {

                /* search for a split in a ordered variable x */
                split = S3get_primarysplit(node);

                /* check if the n-vector of splitstatistics
                   should be returned for each primary split */
                if (get_savesplitstats(tgctrl)) {
                    C_init_orderedsplit(split, nobs);
                    splitstat = REAL(S3get_splitstatistics(split));
                } else {
                    C_init_orderedsplit(split, 0);
                    splitstat = REAL(get_splitstatistics(fitmem));
                }

                C_split(REAL(x), 1, REAL(testy), q, thisweights, nobs,
                        INTEGER(get_ordering(inputs, jselect)), splitctrl,
                        GET_SLOT(fitmem, PL2_linexpcov2sampleSym),
                        expcovinf, REAL(S3get_splitpoint(split)), &maxstat,
                        splitstat);
                S3set_variableID(split, jselect);
            } else {

                /* search of a set of levels (split) in a numeric variable x */
                split = S3get_primarysplit(node);

                /* check if the n-vector of splitstatistics
                   should be returned for each primary split */
                if (get_savesplitstats(tgctrl)) {
                    C_init_nominalsplit(split,
                                        LENGTH(get_levels(inputs, jselect)),
                                        nobs);
                    splitstat = REAL(S3get_splitstatistics(split));
                } else {
                    C_init_nominalsplit(split,
                                        LENGTH(get_levels(inputs, jselect)),
                                        0);
                    splitstat = REAL(get_splitstatistics(fitmem));
                }

                linexpcov = get_varmemory(fitmem, jselect);
                standstat = Calloc(get_dimension(linexpcov), double);
                C_standardize(REAL(GET_SLOT(linexpcov,
                                            PL2_linearstatisticSym)),
                              REAL(GET_SLOT(linexpcov, PL2_expectationSym)),
                              REAL(GET_SLOT(linexpcov, PL2_covarianceSym)),
                              get_dimension(linexpcov), get_tol(splitctrl),
                              standstat);

                C_splitcategorical(INTEGER(x),
                                   LENGTH(get_levels(inputs, jselect)),
                                   REAL(testy), q, thisweights,
                                   nobs, standstat, splitctrl,
                                   GET_SLOT(fitmem, PL2_linexpcov2sampleSym),
                                   expcovinf, &cutpoint,
                                   INTEGER(S3get_splitpoint(split)),
                                   &maxstat, splitstat);

                /* compute which levels of a factor are available in this node
                   (for printing) later on. A real `table' for this node would
                   induce too much overhead here. Maybe later. */

                itable = INTEGER(S3get_table(split));
                dxtransf = REAL(get_transformation(inputs, jselect));
                for (k = 0; k < LENGTH(get_levels(inputs, jselect)); k++) {
                    itable[k] = 0;
                    for (i = 0; i < nobs; i++) {
                        if (dxtransf[k * nobs + i] * thisweights[i] > 0) {
                            itable[k] = 1;
                            continue;
                        }
                    }
                }

                Free(standstat);
            }
            if (maxstat == 0) {
                if (j == 1) {
                    S3set_nodeterminal(node);
                } else {
                    /* do not look at jselect in next iteration */
                    pvalue[jselect - 1] = R_NegInf;
                }
            } else {
                S3set_variableID(split, jselect);
                break;
            }
        } else {