void
nest::aeif_cond_exp::init_buffers_()
{
  B_.spike_exc_.clear(); // includes resize
  B_.spike_inh_.clear(); // includes resize
  B_.currents_.clear();  // includes resize
  Archiving_Node::clear_history();

  B_.logger_.reset();

  B_.step_ = Time::get_resolution().get_ms();

  // We must integrate this model with high-precision to obtain decent results
  B_.IntegrationStep_ = std::min( 0.01, B_.step_ );

  if ( B_.s_ == 0 )
    B_.s_ =
      gsl_odeiv_step_alloc( gsl_odeiv_step_rkf45, State_::STATE_VEC_SIZE );
  else
    gsl_odeiv_step_reset( B_.s_ );

  if ( B_.c_ == 0 )
    B_.c_ = gsl_odeiv_control_yp_new( P_.gsl_error_tol, P_.gsl_error_tol );
  else
    gsl_odeiv_control_init(
      B_.c_, P_.gsl_error_tol, P_.gsl_error_tol, 0.0, 1.0 );

  if ( B_.e_ == 0 )
    B_.e_ = gsl_odeiv_evolve_alloc( State_::STATE_VEC_SIZE );
  else
    gsl_odeiv_evolve_reset( B_.e_ );

  B_.I_stim_ = 0.0;
}
Exemple #2
0
CAMLprim value ml_gsl_odeiv_evolve_alloc(value dim)
{
  gsl_odeiv_evolve *e = gsl_odeiv_evolve_alloc(Int_val(dim));
  value res;
  Abstract_ptr(res, e);
  return res;
}
int main(int argc, char** argv) {

    // Tamanho do sistema a ser resolvido
    size_t dim = 2;
	
	// Definicao dos erros por passo de tempo
	double abstol = 1.e-6;
	double reltol = 1.e-10;

    // Definindo o metodo a ser usado
    const gsl_odeiv_step_type* T = gsl_odeiv_step_rk8pd;

    // Alocando espaco para utilizar o metodo T e a dimensao do 
    //  numero de equacoes a serem resolvidas.
    gsl_odeiv_step* s = gsl_odeiv_step_alloc(T, dim);
    
    // Verifica e obtem o melhor passo na evolucao da variavel, de
    //  acordo com os erros absoluto e relativo alimentados.
    gsl_odeiv_control* c = gsl_odeiv_control_y_new(abstol, reltol);

    // Alocando espaco para aplicar as operacoes de solucao numerica
    gsl_odeiv_evolve* e = gsl_odeiv_evolve_alloc(dim);

    // Definicao dos parametros usados e do sistema a ser resolvido
    //  (funcao e seu jacobiano).
    double mu = 10;
    gsl_odeiv_system sys = {func, jac, 2, &mu};

    // Definicao das variaveis e suas condicoes iniciais
    double t = 0.0, tf = 100.0;
    double h = 1e-2;
    double y[2] = { 1.0, 0.0 }; // C.I. das variaveis 

    // Variaveis auxiliares
    int status;

    printf ("%.5e %.5e %.5e\n", t, y[0], y[1]);
    while (t < tf)
    {
        // Evolucao da funcao.
        // Importante!! t e h sao passados por referencia e seus valores
        // mudam a cada iteracao. Dessa maneira, o passo de tempo NAO eh
        // fixo!!!
        status = gsl_odeiv_evolve_apply(e, c, s, &sys, &t, tf, &h, y);

        if(status != GSL_SUCCESS)
        {
            printf ("error, return value=%d\n", status);
            break;
        }

        printf ("%.5e %.5e %.5e\n", t, y[0], y[1]);
    }

    // Desalocando a memoria...
    gsl_odeiv_evolve_free (e);
    gsl_odeiv_control_free (c);

    return (EXIT_SUCCESS);
}
void
nest::iaf_cond_exp::init_buffers_()
{
  B_.spike_exc_.clear(); // includes resize
  B_.spike_inh_.clear(); // includes resize
  B_.currents_.clear();  // includes resize
  Archiving_Node::clear_history();

  B_.logger_.reset();

  B_.step_ = Time::get_resolution().get_ms();
  B_.IntegrationStep_ = B_.step_;

  if ( B_.s_ == 0 )
    B_.s_ = gsl_odeiv_step_alloc( gsl_odeiv_step_rkf45, State_::STATE_VEC_SIZE );
  else
    gsl_odeiv_step_reset( B_.s_ );

  if ( B_.c_ == 0 )
    B_.c_ = gsl_odeiv_control_y_new( 1e-3, 0.0 );
  else
    gsl_odeiv_control_init( B_.c_, 1e-3, 0.0, 1.0, 0.0 );

  if ( B_.e_ == 0 )
    B_.e_ = gsl_odeiv_evolve_alloc( State_::STATE_VEC_SIZE );
  else
    gsl_odeiv_evolve_reset( B_.e_ );

  B_.sys_.function = iaf_cond_exp_dynamics;
  B_.sys_.jacobian = NULL;
  B_.sys_.dimension = State_::STATE_VEC_SIZE;
  B_.sys_.params = reinterpret_cast< void* >( this );

  B_.I_stim_ = 0.0;
}
Exemple #5
0
static odegsl_t *
odesys_odegsl_ctor (odesys_t * ode)
{
  odegsl_t *odegsl;
  molecule_t *molecule = ode->params->molecule;
  int ncoef = molecule->get_ncoef (molecule);

  if (MEMORY_ALLOC (odegsl) < 0)
    {
      MEMORY_OOMERR;
      fprintf (stderr,
	       "%s %d: unable to allocate memory for odegsl object.\n",
	       __func__, __LINE__);
      return NULL;
    }

  odegsl->system.dimension = 2 * ncoef;
  odegsl->system.function = odesys_tdse_function;
  odegsl->system.jacobian = NULL;
  odegsl->system.params = (void *) ode->params;

  /* Note that we hard-code the ODE step type here. The step type
     chosen is a general purpose type. In the future, should probably
     try others. */
  odegsl->step = gsl_odeiv_step_alloc (gsl_odeiv_step_rkf45, 2 * ncoef);
  odegsl->evolve = gsl_odeiv_evolve_alloc (2 * ncoef);
  odegsl->control = gsl_odeiv_control_standard_new
    (ode->eps_abs, ode->eps_rel, ode->y_scale, ode->dydx_scale);

  odegsl->hstep = ode->hstep;
  odegsl->hinit = ode->hstep;

  return odegsl;
}
void
nest::iaf_cond_alpha_mc::init_buffers_()
{
  B_.spikes_.resize( NUM_SPIKE_RECEPTORS );
  for ( size_t n = 0; n < NUM_SPIKE_RECEPTORS; ++n )
  {
    B_.spikes_[ n ].clear();
  } // includes resize

  B_.currents_.resize( NUM_CURR_RECEPTORS );
  for ( size_t n = 0; n < NUM_CURR_RECEPTORS; ++n )
  {
    B_.currents_[ n ].clear();
  } // includes resize

  B_.logger_.reset();
  Archiving_Node::clear_history();

  B_.step_ = Time::get_resolution().get_ms();
  B_.IntegrationStep_ = B_.step_;

  if ( B_.s_ == 0 )
  {
    B_.s_ =
      gsl_odeiv_step_alloc( gsl_odeiv_step_rkf45, State_::STATE_VEC_SIZE );
  }
  else
  {
    gsl_odeiv_step_reset( B_.s_ );
  }

  if ( B_.c_ == 0 )
  {
    B_.c_ = gsl_odeiv_control_y_new( 1e-3, 0.0 );
  }
  else
  {
    gsl_odeiv_control_init( B_.c_, 1e-3, 0.0, 1.0, 0.0 );
  }

  if ( B_.e_ == 0 )
  {
    B_.e_ = gsl_odeiv_evolve_alloc( State_::STATE_VEC_SIZE );
  }
  else
  {
    gsl_odeiv_evolve_reset( B_.e_ );
  }

  B_.sys_.function = iaf_cond_alpha_mc_dynamics;
  B_.sys_.jacobian = NULL;
  B_.sys_.dimension = State_::STATE_VEC_SIZE;
  B_.sys_.params = reinterpret_cast< void* >( this );
  for ( size_t n = 0; n < NCOMP; ++n )
  {
    B_.I_stim_[ n ] = 0.0;
  }
}
void
nest::hh_psc_alpha_gap::init_buffers_()
{
  B_.spike_exc_.clear(); // includes resize
  B_.spike_inh_.clear(); // includes resize
  B_.currents_.clear();  // includes resize

  // allocate strucure for gap events here
  // function is called from Scheduler::prepare_nodes() before the
  // first call to update
  // so we already know which interpolation scheme to use according
  // to the properties of this neurons
  // determine size of structure depending on interpolation scheme
  // and unsigned int Scheduler::min_delay() (number of simulation time steps
  // per min_delay step)

  // resize interpolation_coefficients depending on interpolation order
  const size_t quantity = kernel().connection_manager.get_min_delay()
    * ( kernel().simulation_manager.get_wfr_interpolation_order() + 1 );

  B_.interpolation_coefficients.resize( quantity, 0.0 );

  B_.last_y_values.resize( kernel().connection_manager.get_min_delay(), 0.0 );

  B_.sumj_g_ij_ = 0.0;

  Archiving_Node::clear_history();

  B_.logger_.reset();

  B_.step_ = Time::get_resolution().get_ms();
  B_.IntegrationStep_ = B_.step_;

  if ( B_.s_ == 0 )
    B_.s_ =
      gsl_odeiv_step_alloc( gsl_odeiv_step_rkf45, State_::STATE_VEC_SIZE );
  else
    gsl_odeiv_step_reset( B_.s_ );

  if ( B_.c_ == 0 )
    B_.c_ = gsl_odeiv_control_y_new( 1e-6, 0.0 );
  else
    gsl_odeiv_control_init( B_.c_, 1e-6, 0.0, 1.0, 0.0 );

  if ( B_.e_ == 0 )
    B_.e_ = gsl_odeiv_evolve_alloc( State_::STATE_VEC_SIZE );
  else
    gsl_odeiv_evolve_reset( B_.e_ );

  B_.sys_.function = hh_psc_alpha_gap_dynamics;
  B_.sys_.jacobian = NULL;
  B_.sys_.dimension = State_::STATE_VEC_SIZE;
  B_.sys_.params = reinterpret_cast< void* >( this );

  B_.I_stim_ = 0.0;
}
int
sys_driver (const gsl_odeiv_step_type * T,
	    const gsl_odeiv_system * sys,
	    double t0, double t1, double hstart,
	    double y[], double epsabs, double epsrel,
	    const char desc[])
{
  /* This function evolves a system sys with stepper T from t0 to t1.
     Step length is varied via error control with possibly different
     absolute and relative error tolerances.
  */
  
  int s = 0;
  int steps = 0;

  double t = t0;
  double h = hstart;

  gsl_odeiv_step * step = gsl_odeiv_step_alloc (T, sys->dimension);

  gsl_odeiv_control *c =
    gsl_odeiv_control_standard_new (epsabs, epsrel, 1.0, 0.0);
  gsl_odeiv_evolve *e = gsl_odeiv_evolve_alloc (sys->dimension);

  while (t < t1)
    {
      s = gsl_odeiv_evolve_apply (e, c, step, sys, &t, t1, &h, y);

      if (s != GSL_SUCCESS) 
	{
	  gsl_test(s, "sys_driver: %s evolve_apply returned %d",
		   gsl_odeiv_step_name (step), s);
	  break;
	}

      if (steps > 1e7)
	{
	  gsl_test(GSL_EMAXITER, 
		   "sys_driver: %s evolve_apply reached maxiter at t=%g",
		   gsl_odeiv_step_name (step), t);
	  s = GSL_EMAXITER;
	  break;
	}

      steps++;
    }

  gsl_test(s, "%s %s [%g,%g], %d steps completed", 
	   gsl_odeiv_step_name (step), desc, t0, t1, steps);

  gsl_odeiv_evolve_free (e);
  gsl_odeiv_control_free (c);
  gsl_odeiv_step_free (step);

  return s;
}
Exemple #9
0
pert_ode * pert_ode_init (size_t Nv) {
    pert_ode * po = (pert_ode *) malloc (sizeof(pert_ode));
    po->Te = gsl_odeiv_step_rkf45;
    po->se = gsl_odeiv_step_alloc (po->Te, 2*Nv*Nv+Nv);
    po->ce = gsl_odeiv_control_y_new (5e-7, 0);
    po->ee = gsl_odeiv_evolve_alloc (2*Nv*Nv+Nv);
	po->syse.jacobian = NULL;
	po->syse.dimension = 2*Nv*Nv+Nv;
	return po;
}
Exemple #10
0
struct_ode_base *new_ode_base( int NX, double *x_init, int (*func_ode_base)(), int (*jacobian)(), void * params) {
    int i;
    struct_ode_base *old=NULL;
    struct_ode_base * s;
    if (old == NULL) {
        s = malloc(sizeof (struct_ode_base));
        s->NX = NX;
        s->x = malloc(s->NX * sizeof (double));
        for (i = 0; i < s->NX; i++) {
            s->x[i] = 0;
        }
        s->sys.function = NULL;
        s->sys.jacobian = NULL;
    } else {
        s = old;
    }
    s->params = params;
    // relative errors and steps
    s->eps_rel = 1e-6;
    s->eps_abs = 1e-6;
    s->h = 1e-6;
    s->hmax = 1;
    if (x_init != NULL) {
        for (i = 0; i < s->NX; i++) {
            s->x[i] = x_init[i];
        }
    }
    i = 0;
    s->T = gsl_odeiv_step_rkck;
    if (old != NULL) {
        gsl_odeiv_evolve_free(s->e);
        gsl_odeiv_control_free(s->c);
        gsl_odeiv_step_free(s->s);
    }
    s->s = gsl_odeiv_step_alloc(s->T, s->NX);
    s->c = gsl_odeiv_control_y_new(s->eps_abs, s->eps_rel);
    s->e = gsl_odeiv_evolve_alloc(s->NX);
    s->sys.dimension = s->NX;
    if (func_ode_base != NULL) {
        s->sys.function = func_ode_base;
    }
    if (jacobian != NULL) {
        s->sys.jacobian = jacobian;
    }
    s->sys.params = s;
    s->time_second = 0.0;
    s->nb_step = 0;
    if (old == NULL) {
        s->print_values = 0;
    }
    s->debug = 0;
    return s;
}
Exemple #11
0
static PyObject *
PyGSL_odeiv_evolve_init(PyObject *self, PyObject *args)
{
     PyGSL_odeiv_step *step = NULL;
     PyGSL_odeiv_control *control = NULL;
     PyGSL_odeiv_evolve *a_ev = NULL;


     /* step, control */
     FUNC_MESS_BEGIN();
     if(0== PyArg_ParseTuple(args, "O!O!:odeiv_evolve.__init__", 
			     &PyGSL_odeiv_step_pytype, &step,
			     &PyGSL_odeiv_control_pytype, &control)){
	  return NULL;
     }

     if(!step){
	  PyErr_SetString(PyExc_TypeError, "The first argument must be a step object!");
	  goto fail;
     }

     if(!control){
	  PyErr_SetString(PyExc_TypeError, "The second argument must be a control object!");
	  goto fail;
     }

     a_ev =  (PyGSL_odeiv_evolve *) PyObject_NEW(PyGSL_odeiv_evolve, &PyGSL_odeiv_evolve_pytype);
     if(NULL == a_ev){
	  PyErr_NoMemory();
	  return NULL;
     }
     


     a_ev->step = step;
     a_ev->control = control;

     a_ev->evolve = gsl_odeiv_evolve_alloc(step->system.dimension);
     if(NULL == a_ev){
	  PyErr_NoMemory();
	  goto fail;
     }
     Py_INCREF(step);
     Py_INCREF(control);
     FUNC_MESS_END();
     return (PyObject *) a_ev;
 fail:
     FUNC_MESS("FAIL");
     Py_DECREF(a_ev);
     return NULL;
}
void
nest::aeif_psc_alpha::init_buffers_()
{
  B_.spike_exc_.clear(); // includes resize
  B_.spike_inh_.clear(); // includes resize
  B_.currents_.clear();  // includes resize
  Archiving_Node::clear_history();

  B_.logger_.reset();

  B_.step_ = Time::get_resolution().get_ms();

  // We must integrate this model with high-precision to obtain decent results
  B_.IntegrationStep_ = std::min( 0.01, B_.step_ );

  if ( B_.s_ == 0 )
  {
    B_.s_ =
      gsl_odeiv_step_alloc( gsl_odeiv_step_rkf45, State_::STATE_VEC_SIZE );
  }
  else
  {
    gsl_odeiv_step_reset( B_.s_ );
  }

  if ( B_.c_ == 0 )
  {
    B_.c_ = gsl_odeiv_control_yp_new( P_.gsl_error_tol, P_.gsl_error_tol );
  }
  else
  {
    gsl_odeiv_control_init(
      B_.c_, P_.gsl_error_tol, P_.gsl_error_tol, 0.0, 1.0 );
  }

  if ( B_.e_ == 0 )
  {
    B_.e_ = gsl_odeiv_evolve_alloc( State_::STATE_VEC_SIZE );
  }
  else
  {
    gsl_odeiv_evolve_reset( B_.e_ );
  }

  B_.sys_.jacobian = NULL;
  B_.sys_.dimension = State_::STATE_VEC_SIZE;
  B_.sys_.params = reinterpret_cast< void* >( this );
  B_.sys_.function = aeif_psc_alpha_dynamics;

  B_.I_stim_ = 0.0;
}
/* Many good algorithms don't need the Jacobian, so we'll just pass a null pointer */
void gslode(void * mypars, double max_time, FILE *theory)
{
	/* Create our ODE system */
	gsl_odeiv_system sys = {func, NULL, DIM, mypars};

	/* Range of time to simulate*/	
	double t = 0.0, t1 = max_time;
	/* Initial step size, will be modified as needed by adaptive alogorithm */
	double h = 1e-6;
	/* initial conditions, No */
	double y[DIM] = { No, 0.0 };


	/* Define method as Embedded Runge-Kutta Prince-Dormand (8,9) method */
	const gsl_odeiv_step_type * T
	 = gsl_odeiv_step_rk4;
//	 = gsl_odeiv_step_rk8pd;
	/* allocate stepper for our method of correct dimension*/
	gsl_odeiv_step * s
	 = gsl_odeiv_step_alloc (T, DIM);
	/* control will maintain absolute and relative error */
	gsl_odeiv_control * c
	 = gsl_odeiv_control_y_new (1e-6, 0.0);
	/* allocate the evolver */
	gsl_odeiv_evolve * e
	 = gsl_odeiv_evolve_alloc (DIM);

	/*dummy to make easy to switch to regular printing */
	double ti = t1; 
	int i;

	/* Uncomment the outer for loop to print *
	 * Npts sample pts at regular intervals   */
	for (i = 1; i <= NPTS; i++){   ti = i * t1 / NPTS;
		while (t < ti)
		{
			int status = gsl_odeiv_evolve_apply (e, c, s,
												&sys,
												&t, t1,
												&h, y);
			if (status != GSL_SUCCESS)
			   break;
//			fprintf(theory,"%.6e %.6e %.6e\n",t,y[0],y[1]); //adaptive mesh
		}
		fprintf(theory,"%g %g %g\n",t,y[0],y[1]);  }

	gsl_odeiv_evolve_free (e);
	gsl_odeiv_control_free (c);
	gsl_odeiv_step_free (s);
}
Exemple #14
0
void integrator_init(LALStatus *status, INT2 num, void *params,
		int(*derivator)(REAL8, const REAL8[], REAL8[], void *),
		integrator_System *integrator) {
	INITSTATUS(status, "integrator_init", INTEGRATORC);
	ATTATCHSTATUSPTR(status);
	integrator->solver_type = gsl_odeiv_step_rkf45;
	integrator->solver_step
			= gsl_odeiv_step_alloc(integrator->solver_type, num);
	integrator->solver_control = gsl_odeiv_control_standard_new(1.0e-9, 1.0e-9,
			.2, .2);
	integrator->solver_evolve = gsl_odeiv_evolve_alloc(num);
	integrator->solver_system.jacobian = NULL;
	integrator->solver_system.dimension = num;
	integrator->solver_system.params = params;
	integrator->solver_system.function = derivator;
	DETATCHSTATUSPTR(status);
	RETURN (status);
}
Exemple #15
0
void ode_alloc(odesolver_t* par)
{
    const gsl_odeiv_step_type *T = gsl_odeiv_step_rkf45;
    
    par->s = gsl_odeiv_step_alloc(T, DIM);
    par->c = gsl_odeiv_control_y_new(1e-12, 0.);
    par->e = gsl_odeiv_evolve_alloc(DIM);
    par->sys.function = deriv;
    par->sys.jacobian = NULL;
    par->sys.dimension = DIM;
    par->sys.params = NULL;
    
    par->points[0].t = 0.;
    par->points[0].y[0] = 0.;
    par->points[0].y[1] = 2.;
    par->points[0].y[2] = 1.;
    par->points[0].y[3] = 0.;
    par->cur_idx = 0;
}
//Handles data from MarkovChannel class.
void MarkovGslSolver::init( vector< double > initialState )
{
	nVars_ = initialState.size();

	if ( stateGsl_ == 0 )
		stateGsl_ = new double[ nVars_ ];

	state_ = initialState;
	initialState_ = initialState;

	Q_.resize( nVars_ );

	for ( unsigned int i = 0; i < nVars_; ++i )
		Q_[i].resize( nVars_, 0.0 );	

	isInitialized_ = 1;

	assert( gslStepType_ != 0 );
	if ( gslStep_ )
		gsl_odeiv_step_free(gslStep_);

	gslStep_ = gsl_odeiv_step_alloc( gslStepType_, nVars_ );
	assert( gslStep_ != 0 );

	if ( !gslEvolve_ )
		gslEvolve_ = gsl_odeiv_evolve_alloc(nVars_);
	else
		gsl_odeiv_evolve_reset(gslEvolve_);

	assert(gslEvolve_ != 0);

	if ( !gslControl_ )
		gslControl_ = gsl_odeiv_control_y_new( absAccuracy_, relAccuracy_ );
	else 
		gsl_odeiv_control_init(gslControl_,absAccuracy_, relAccuracy_, 1, 0);

	assert(gslControl_!= 0);
        
	gslSys_.function = &MarkovGslSolver::evalSystem;
	gslSys_.jacobian = 0;
	gslSys_.dimension = nVars_;
	gslSys_.params = static_cast< void * >( &Q_ );
}
void
nest::ht_neuron::init_buffers_()
{
  // Reset spike buffers.
  for ( std::vector< RingBuffer >::iterator it = B_.spike_inputs_.begin();
        it != B_.spike_inputs_.end();
        ++it )
  {
    it->clear(); // include resize
  }

  B_.currents_.clear(); // include resize

  B_.logger_.reset();

  Archiving_Node::clear_history();

  B_.step_ = Time::get_resolution().get_ms();
  B_.IntegrationStep_ = B_.step_;

  if ( B_.s_ == 0 )
    B_.s_ =
      gsl_odeiv_step_alloc( gsl_odeiv_step_rkf45, State_::STATE_VEC_SIZE );
  else
    gsl_odeiv_step_reset( B_.s_ );

  if ( B_.c_ == 0 )
    B_.c_ = gsl_odeiv_control_y_new( 1e-3, 0.0 );
  else
    gsl_odeiv_control_init( B_.c_, 1e-3, 0.0, 1.0, 0.0 );

  if ( B_.e_ == 0 )
    B_.e_ = gsl_odeiv_evolve_alloc( State_::STATE_VEC_SIZE );
  else
    gsl_odeiv_evolve_reset( B_.e_ );

  B_.sys_.function = ht_neuron_dynamics;
  B_.sys_.jacobian = 0;
  B_.sys_.dimension = State_::STATE_VEC_SIZE;
  B_.sys_.params = reinterpret_cast< void* >( this );

  B_.I_stim_ = 0.0;
}
Exemple #18
0
int main(int argc, char** argv){
	if(argc < 3){
		fprintf(stderr, "%s gamma gmax\n", argv[0]);
		return EXIT_FAILURE;
	}

	const gsl_odeiv_step_type *T = gsl_odeiv_step_rkf45;
	gsl_odeiv_step 		*s = gsl_odeiv_step_alloc(T, 3);
	gsl_odeiv_control 	*c = gsl_odeiv_control_y_new(1e-6, 0.0); //(abs, rel)
	gsl_odeiv_evolve 	*e = gsl_odeiv_evolve_alloc(3); // 3-dimensional
	vdp_params par = {2, 4, atof(argv[1]), atof(argv[2]), 0, 0};

	gsl_odeiv_system sys = {vdp, jac_vdp, 3, &par};

	double t 	= 0.0;	//Start at this value
	double t1 	= 20;
	double interval = 0.1;
	double h	= 1e-6;	//Start at this timestep
	double y[3]	= {1.0, 0.1, 3.0}; //Initial condition

	while(t < t1){
		int status = gsl_odeiv_evolve_apply(e, c, s, &sys, &t, t1, &h, y);
		if(status != GSL_SUCCESS){
			fprintf(stderr, "Could not evaluate step.");
			break;
		}
//		if(t > t2 + interval){
			printf("%.5e %.5e %.5e %.5e\n", t, y[0], y[1], y[2]);
//			t2 = t;
//		}
	}

	//Print out data to stderr
	fprintf(stderr, "count: %d\n", par.count);
	fprintf(stderr, "jaccount: %d\n", par.jac_count);

	//Free up memory
	gsl_odeiv_evolve_free(e);
	gsl_odeiv_control_free(c);
	gsl_odeiv_step_free(s);
	return EXIT_SUCCESS;
}
Exemple #19
0
void ode(double  *params, double maxtime, double * sps)
{
    double *y;
    y = sps;
    const gsl_odeiv_step_type *T = gsl_odeiv_step_gear2;
    gsl_odeiv_step *stp = gsl_odeiv_step_alloc(T, 27);
    gsl_odeiv_control *c = gsl_odeiv_control_y_new(1e-4, 0.0);
    gsl_odeiv_evolve * e = gsl_odeiv_evolve_alloc(27);
    gsl_odeiv_system sys = {func, 0, 27, params};

    double t = 0.0, t1 = maxtime;
    double h = 1e-6;


    while (t < t1) {
        gsl_odeiv_evolve_apply (e, c, stp, &sys, &t, t1, &h, y);
    }
  
    gsl_odeiv_evolve_free (e);
    gsl_odeiv_control_free (c);
    gsl_odeiv_step_free (stp);
}
Exemple #20
0
int
main (void)
{
  const gsl_odeiv_step_type * T 
    = gsl_odeiv_step_rk8pd;

  gsl_odeiv_step * s 
    = gsl_odeiv_step_alloc (T, 2);
  gsl_odeiv_control * c 
    = gsl_odeiv_control_y_new (1e-6, 0.0);
  gsl_odeiv_evolve * e 
    = gsl_odeiv_evolve_alloc (2);

  double mu = 10;
  gsl_odeiv_system sys = {func, jac, 2, &mu};

  double t = 0.0, t1 = 100.0;
  double h = 1e-6;
  double y[2] = { 1.0, 0.0 };

  while (t < t1)
    {
      int status = gsl_odeiv_evolve_apply (e, c, s,
                                           &sys, 
                                           &t, t1,
                                           &h, y);

      if (status != GSL_SUCCESS)
          break;

      printf ("%.5e %.5e %.5e\n", t, y[0], y[1]);
    }

  gsl_odeiv_evolve_free (e);
  gsl_odeiv_control_free (c);
  gsl_odeiv_step_free (s);
  return 0;
}
Exemple #21
0
void runOde(double * data, double tmax, double dt,ODEparams * pa)
{

	const gsl_odeiv_step_type * T = gsl_odeiv_step_rk8pd;
  	gsl_odeiv_step * s = gsl_odeiv_step_alloc (T, 2);
  	gsl_odeiv_control * c = gsl_odeiv_control_y_new (1e-10, 0.0);
  	gsl_odeiv_evolve * e  = gsl_odeiv_evolve_alloc (2);
  	gsl_odeiv_system sys = {func, jac, 2, pa};
  	int totalframe=ceil(tmax/dt);
  	int i=0;
	double t1=dt,t=0.0;  		
	double h = 1e-10;
	double y[2] = { pa->x0,pa->y0};
	

	while(t1<tmax)
    {
       while (t < t1)
  	    {  
	               int status = gsl_odeiv_evolve_apply (e, c, s,
					       &sys, 
					       &t, t1,
					       &h, y);
	  
        	  if (status != GSL_SUCCESS)
	               break;
      	}	  
	    i++;	
      	t1+=dt;
      	data[i]=y[0];
/*    	printf("%lf %lf\n",t1,y[0]); */

	}
	gsl_odeiv_evolve_free (e);
  	gsl_odeiv_control_free (c);
	gsl_odeiv_step_free (s);

}
/**
 * @brief Integrates the Tolman-Oppenheimer-Volkov stellar structure equations.
 * @details
 * Solves the Tolman-Oppenheimer-Volkov stellar structure equations using the
 * pseudo-enthalpy formalism introduced in:
 * Lindblom (1992) "Determining the Nuclear Equation of State from Neutron-Star
 * Masses and Radii", Astrophys. J. 398 569.
 * @param[out] radius The radius of the star in m.
 * @param[out] mass The mass of the star in kg.
 * @param[out] love_number_k2 The k_2 tidal love number of the star.
 * @param[in] central_pressure_si The central pressure of the star in Pa.
 * @param eos Pointer to the Equation of State structure.
 * @retval 0 Success.
 * @retval <0 Failure.
 */
int XLALSimNeutronStarTOVODEIntegrate(double *radius, double *mass,
    double *love_number_k2, double central_pressure_si,
    LALSimNeutronStarEOS * eos)
{
    /* ode integration variables */
    const double epsabs = 0.0, epsrel = 1e-6;
    double y[TOV_ODE_VARS_DIM];
    double dy[TOV_ODE_VARS_DIM];
    struct tov_ode_vars *vars = tov_ode_vars_cast(y);
    gsl_odeiv_system sys = { tov_ode, NULL, TOV_ODE_VARS_DIM, eos };
    gsl_odeiv_step *step =
        gsl_odeiv_step_alloc(gsl_odeiv_step_rk8pd, TOV_ODE_VARS_DIM);
    gsl_odeiv_control *ctrl = gsl_odeiv_control_y_new(epsabs, epsrel);
    gsl_odeiv_evolve *evolv = gsl_odeiv_evolve_alloc(TOV_ODE_VARS_DIM);

    /* central values */
    /* note: will be updated with Lindblom's series expansion */
    /* geometrisized units for variables in length (m) */
    double pc = central_pressure_si * LAL_G_C4_SI;
    double ec =
        XLALSimNeutronStarEOSEnergyDensityOfPressureGeometerized(pc, eos);
    double hc =
        XLALSimNeutronStarEOSPseudoEnthalpyOfPressureGeometerized(pc, eos);
    double dedp_c =
        XLALSimNeutronStarEOSEnergyDensityDerivOfPressureGeometerized(pc, eos);
    double dhdp_c = 1.0 / (ec + pc);
    double dedh_c = dedp_c / dhdp_c;
    double dh = -1e-3 * hc;
    double h0 = hc + dh;
    double h1 = 0.0 - dh;
    double r0 = sqrt(-3.0 * dh / (2.0 * LAL_PI * (ec + 3.0 * pc)));
    double m0 = 4.0 * LAL_PI * r0 * r0 * r0 * ec / 3.0;
    double H0 = r0 * r0;
    double b0 = 2.0 * r0;

    double yy;
    double c;
    double h;
    size_t i;

    /* series expansion for the initial core */

    /* second factor of Eq. (7) of Lindblom (1992) */
    r0 *= 1.0 + 0.25 * dh * (ec - 3.0 * pc  - 0.6 * dedh_c) / (ec + 3.0 * pc);
    /* second factor of Eq. (8) of Lindblom (1992) */
    m0 *= 1.0 + 0.6 * dh * dedh_c / ec;

    /* perform integration */
    vars->r = r0;
    vars->m = m0;
    vars->H = H0;
    vars->b = b0;
    h = h0;
    while (h > h1) {
        int s =
            gsl_odeiv_evolve_apply(evolv, ctrl, step, &sys, &h, h1, &dh, y);
        if (s != GSL_SUCCESS)
            XLAL_ERROR(XLAL_EERR,
                "Error encountered in GSL's ODE integrator\n");
    }

    /* take one final Euler step to get to surface */
    tov_ode(h, y, dy, eos);
    for (i = 0; i < TOV_ODE_VARS_DIM; ++i)
        y[i] += dy[i] * (0.0 - h1);

    /* compute tidal Love number k2 */
    c = vars->m / vars->r;      /* compactness */
    yy = vars->r * vars->b / vars->H;

    /* convert from geometric units to SI units */
    *radius = vars->r;
    *mass = vars->m * LAL_MSUN_SI / LAL_MRSUN_SI;
    *love_number_k2 = tidal_Love_number_k2(c, yy);

    /* free ode memory */
    gsl_odeiv_evolve_free(evolv);
    gsl_odeiv_control_free(ctrl);
    gsl_odeiv_step_free(step);
    return 0;
}
Exemple #23
0
void GslInternal::init(){
  // Init ODE rhs function and quadrature functions
  f_.init();
  casadi_assert(f_.getNumInputs()==DAE_NUM_IN);
  casadi_assert(f_.getNumOutputs()==DAE_NUM_OUT);
  if(!q_.isNull()){
    q_.init();
    casadi_assert(q_.getNumInputs()==DAE_NUM_IN);
    casadi_assert(q_.getNumOutputs()==DAE_NUM_OUT);
  }

  // Number of states
  int nx = f_.output(INTEGRATOR_XF).numel();

  // Add quadratures, if any
  if(!q_.isNull()) nx += q_.output().numel();

  // Number of parameters
  int np = f_.input(DAE_P).numel();

  setDimensions(nx,np);

  // If time was not specified, initialise it.
  if (f_.input(DAE_T).numel()==0) {
    std::vector<MX> in1(DAE_NUM_IN);
    in1[DAE_T] = MX("T");
    in1[DAE_Y] = MX("Y",f_.input(DAE_Y).size1(),f_.input(DAE_Y).size2());
    in1[DAE_YDOT] = MX("YDOT",f_.input(DAE_YDOT).size1(),f_.input(DAE_YDOT).size2());
    in1[DAE_P] = MX("P",f_.input(DAE_P).size1(),f_.input(DAE_P).size2());
    std::vector<MX> in2(in1);
    in2[DAE_T] = MX();
    f_ = MXFunction(in1,f_.call(in2));
    f_.init();
  }
  
  // We only allow for 0-D time
  casadi_assert_message(f_.input(DAE_T).numel()==1, "IntegratorInternal: time must be zero-dimensional, not (" <<  f_.input(DAE_T).size1() << 'x' << f_.input(DAE_T).size2() << ")");
  
  // ODE right hand side must be a dense matrix
  casadi_assert_message(f_.output(DAE_RES).dense(),"ODE right hand side must be dense: reformulate the problem");
  
  // States and RHS should match 
  casadi_assert_message(f_.output(DAE_RES).size()==f_.input(DAE_Y).size(),
    "IntegratorInternal: rhs of ODE is (" <<  f_.output(DAE_RES).size1() << 'x' << f_.output(DAE_RES).size2() << ") - " << f_.output(DAE_RES).size() << " non-zeros" << std::endl <<
    "              ODE state matrix is (" <<  f_.input(DAE_Y).size1() << 'x' << f_.input(DAE_Y).size2() << ") - " << f_.input(DAE_Y).size() << " non-zeros" << std::endl <<
    "Mismatch between number of non-zeros"
  );

  IntegratorInternal::init();
  
  jac_f_ = Jacobian(f_,DAE_Y,DAE_RES);
  dt_f_ = Jacobian(f_,DAE_T,DAE_RES);
  
  jac_f_.init();
  dt_f_.init();
  
  // define the type of routine for making steps: 
  type_ptr = gsl_odeiv_step_rkf45;
  // some other possibilities (see GSL manual):          
  //   = gsl_odeiv_step_rk4;
  //   = gsl_odeiv_step_rkck;
  //   = gsl_odeiv_step_rk8pd;
  //   = gsl_odeiv_step_rk4imp;
  //   = gsl_odeiv_step_bsimp;  
  //   = gsl_odeiv_step_gear1;
  //   = gsl_odeiv_step_gear2;
  
  step_ptr = gsl_odeiv_step_alloc (type_ptr, nx);
  control_ptr = gsl_odeiv_control_y_new (abstol_, reltol_);
  evolve_ptr = gsl_odeiv_evolve_alloc (nx);
  
  my_system.function = rhs_wrapper;	// the right-hand-side functions dy[i]/dt 
  my_system.jacobian = jac_wrapper;	// the Jacobian df[i]/dy[j] 
  my_system.dimension = nx;	// number of diffeq's 
  my_system.params = this;	// parameters to pass to rhs and jacobian
  
  is_init = true;
  
}
Exemple #24
0
// The actual (user defined) qoi routine
void qoiRoutine(const QUESO::GslVector&                    paramValues,
                const QUESO::GslVector*                    paramDirection,
                const void*                                functionDataPtr,
                      QUESO::GslVector&                    qoiValues,
                      QUESO::DistArray<QUESO::GslVector*>* gradVectors,
                      QUESO::DistArray<QUESO::GslMatrix*>* hessianMatrices,
                      QUESO::DistArray<QUESO::GslVector*>* hessianEffects)
{
  if (paramDirection  &&
      functionDataPtr && 
      gradVectors     &&
      hessianMatrices &&
      hessianEffects) {
    // Just to eliminate INTEL compiler warnings
  }

  double A             = paramValues[0];
  double E             = paramValues[1];
  double beta          = ((qoiRoutine_Data *) functionDataPtr)->m_beta;
  double criticalMass  = ((qoiRoutine_Data *) functionDataPtr)->m_criticalMass;
  double criticalTime  = ((qoiRoutine_Data *) functionDataPtr)->m_criticalTime;

  double params[]={A,E,beta};
      	
  // integration
  const gsl_odeiv_step_type *T   = gsl_odeiv_step_rkf45; //rkf45; //gear1;
        gsl_odeiv_step      *s   = gsl_odeiv_step_alloc(T,1);
        gsl_odeiv_control   *c   = gsl_odeiv_control_y_new(1e-6,0.0);
        gsl_odeiv_evolve    *e   = gsl_odeiv_evolve_alloc(1);
        gsl_odeiv_system     sys = {func, NULL, 1, (void *)params}; 
	
  double temperature = 0.1;
  double h = 1e-3;
  double Mass[1];
  Mass[0]=1.;
  
  double temperature_old = 0.;
  double M_old[1];
  M_old[0]=1.;
	
  double crossingTemperature = 0.;
  //unsigned int loopSize = 0;
  while ((temperature < criticalTime*beta) &&
         (Mass[0]     > criticalMass     )) {
    int status = gsl_odeiv_evolve_apply(e, c, s, &sys, &temperature, criticalTime*beta, &h, Mass);
    UQ_FATAL_TEST_MACRO((status != GSL_SUCCESS),
                        paramValues.env().fullRank(),
                        "qoiRoutine()",
                        "gsl_odeiv_evolve_apply() failed");
    //printf("t = %6.1lf, mass = %10.4lf\n",t,Mass[0]);
    //loopSize++;

    if (Mass[0] <= criticalMass) {
      crossingTemperature = temperature_old + (temperature - temperature_old) * (M_old[0]-criticalMass)/(M_old[0]-Mass[0]);
    }
		
    temperature_old=temperature;
    M_old[0]=Mass[0];
  }

  if (criticalMass > 0.) qoiValues[0] = crossingTemperature/beta; // QoI = time to achieve critical mass
  if (criticalTime > 0.) qoiValues[0] = Mass[0];                  // QoI = mass fraction remaining at critical time
	
  //printf("loopSize = %d\n",loopSize);
  if ((paramValues.env().displayVerbosity() >= 3) && (paramValues.env().fullRank() == 0)) {
    printf("In qoiRoutine(), A = %g, E = %g, beta = %.3lf, criticalTime = %.3lf, criticalMass = %.3lf: qoi = %lf.\n",A,E,beta,criticalTime,criticalMass,qoiValues[0]);
  }

  gsl_odeiv_evolve_free (e);
  gsl_odeiv_control_free(c);
  gsl_odeiv_step_free   (s);

  return;
}
Exemple #25
0
static gsl_odeiv_evolve* make_evolve(VALUE dim)
{
  return gsl_odeiv_evolve_alloc(FIX2INT(dim));
}
int
main (void)
{
  const gsl_odeiv_step_type * T 
    = gsl_odeiv_step_rk8pd;

  gsl_odeiv_step * s 
    = gsl_odeiv_step_alloc (T, 4);
  gsl_odeiv_control * c 
    = gsl_odeiv_control_y_new (1e-6, 0.0);
  gsl_odeiv_evolve * e 
    = gsl_odeiv_evolve_alloc (4);
  double d; 
  gsl_odeiv_system sys = {func, jac, 4, &d};
  int ii=1, num = 100; // minimum number of points to have 
  double t = 0.0, t1 =.140, ti;
  double h = 1e-6, velx, vely, vtot, vangle;
 
// initialization of all the shooter physical parameters. 
 pi = 4.0*atan(1.0); 
 m = 1.4;              //mass of the ball, Kg
 r = .3;               //radius of the ball, meters 
 Iball = 2.0*m/5.0*r*r;    // I of ball
 l0 = .45;            // distance between pivot and ball rest, m
 gamm = .5;         // angle of the wrist. radians
 Iarm = (1.75)*l0*l0/3.0; // moment of inertia of the catapult ar,
   k = 70;           // torsional spring constant of the catapult spring. j/rad/rad
 marmg_gam = 13.7;     // m_catapult_arm * g * cm distance to pivot. For the potential energy in the arm lift; 
 theta0 = 90*2*pi/360; // the zero of the force is at theta0. For this simulation, it is combined wiht k to get the starting torque and how fast that decreases with angle. 
 g = 9.8;            // gravity , m/s^2
 A =m*r*r+Iball;  
 B = Iball+Iarm+m*(l0*l0+r*r)-2*l0*r*sin(gamm);  // ignoring the non-linear terms here in the coef...not too systematic!!!
 C =  -Iball + m*r*(l0*sin(gamm)-r); 
 det = A*B-C*C; 
 // initial conditions in y = phi, phidot, theta, thetadot
  double y[4] = { 0.0, 0.0, -0.40, 0.0};// initial consditions (phi, phidot, theta, thetadot) 
  while (ii < num) 
    { 
      ti = ii*t1/num; 
      ii++;
  while (t < ti)
      {
      int status = gsl_odeiv_evolve_apply (e, c, s,
                                           &sys, 
                                           &t, ti,
                                           &h, y);

      if (status != GSL_SUCCESS)
          break;
      // have to use the release co-ordinates to determine the final velocity vector of the ball. 
      velx = -l0*sin(y[2])*y[3]+r*y[1]*cos(y[2]+gamm)-r*y[0]*y[3]*sin(y[2]+gamm)-r*y[3]*cos(y[2]+gamm); 
      vely = l0*y[3]*cos(y[2])+r*y[0]*y[3]*cos(y[2]+gamm)+r*y[1]*sin(y[2]+gamm)-r*y[3]*sin(y[2]+gamm); 
	//      printf("%.5e %.5e %.5e  %.5e  %.5e\n", t, y[0], y[1], y[2], y[3]);
      vtot = pow(velx*velx+vely*vely,.5); 
      vangle = -180*atan(vely/velx)/pi; 
      printf("%.5e %.5e %.5e  %.5e  %.5e  %.5e\n", t, y[0], 180*y[2]/pi, vtot, vangle, y[1]-y[3]);
      }
    }
  gsl_odeiv_evolve_free(e);
  gsl_odeiv_control_free(c);
  gsl_odeiv_step_free(s);
  return 0;
}
Exemple #27
0
double
fevol_shrinker (double bisec_param, int print, char * filename, void * p)
{
 const gsl_odeiv_step_type * T
    = STEPPER;

  gsl_odeiv_step * s
    = gsl_odeiv_step_alloc (T, 2);
  gsl_odeiv_control * c
    = gsl_odeiv_control_y_new (STEPPER_ERROR, 0.0);
  gsl_odeiv_evolve * e
    = gsl_odeiv_evolve_alloc (2);

  double dt=PRINT_DT, t_last=0.;

  gsl_odeiv_system sys = {func_shrinker, jac_dummy, 2, p};

  double t = T0;
  double h = H0;
  double A = bisec_param;
  double y[2] = {
    A*t + ((3*A - 4*(-1 + k)*pow(A,3))*pow(2 + k,-1)*pow(t,3))/12. +
    (A*(15 - 40*(-1 + k)*pow(A,2) + 16*pow(A,4)*(1 - 3*k + 2*pow(k,2)))*
     pow(t,5)*pow(8 + 6*k + pow(k,2),-1))/160.,
    A + ((3*A - 4*(-1 + k)*pow(A,3))*pow(2 + k,-1)*pow(t,2))/4. +
    (A*(15 - 40*(-1 + k)*pow(A,2) + 16*pow(A,4)*(1 - 3*k + 2*pow(k,2)))*
     pow(t,4)*pow(8 + 6*k + pow(k,2),-1))/32.,
  };

  FILE * file;

  if (print){
    file = fopen(filename, "a");
    fprintf(file, "# A = %.15f\n", bisec_param );
  }

  while (t < T_MAX)
    {
      int status =
	gsl_odeiv_evolve_apply (e, c, s,
				&sys,
				&t, T_MAX,
				&h, y);

      if (status != GSL_SUCCESS)
	break;
      /* are we still in the strip [0,pi]? */
      if ( 0. > y[0] || y[0] > 3.15 )
	break;

      if (print /* && t_last+dt < t */)
	{
	  fprintf (file,
		   "%.15f %.15f %.15f\n",
		   t, y[0], y[1]/* , y[2], y[3] */);
	  t_last+=dt;
	  dt*=PRINT_DT_RATIO;
	}
      /* printf("%.15f\r",t); */
    }

  gsl_odeiv_evolve_free (e);
  gsl_odeiv_control_free (c);
  gsl_odeiv_step_free (s);
  if (print) {
    fprintf( file, "\n\n\n" );
    fclose( file );
  }

  return y[1];
}
Exemple #28
0
double
Likelihood<V, M>::lnValue(const QUESO::GslVector & paramValues) const
{
  double resultValue = 0.;

  m_env.subComm().Barrier();
  //env.syncPrintDebugMsg("Entering likelihoodRoutine()",1,env.fullComm());

  // Compute likelihood for scenario 1
  double betaTest = m_beta1;
  if (betaTest) {
    double A                       = paramValues[0];
    double E                       = paramValues[1];
    double beta                    = m_beta1;
    double variance                = m_variance1;
    const std::vector<double>& Te  = m_Te1;
    const std::vector<double>& Me  = m_Me1;
    std::vector<double> Mt(Me.size(),0.);

    double params[]={A,E,beta};

    // integration
    const gsl_odeiv_step_type *T   = gsl_odeiv_step_rkf45; //rkf45; //gear1;
          gsl_odeiv_step      *s   = gsl_odeiv_step_alloc(T,1);
          gsl_odeiv_control   *c   = gsl_odeiv_control_y_new(1e-6,0.0);
          gsl_odeiv_evolve    *e   = gsl_odeiv_evolve_alloc(1);
          gsl_odeiv_system     sys = {func, NULL, 1, (void *)params};

    double t = 0.1, t_final = 1900.;
    double h = 1e-3;
    double Mass[1];
    Mass[0]=1.;

    unsigned int i = 0;
    double t_old = 0.;
    double M_old[1];
    M_old[0]=1.;

    double misfit=0.;
    //unsigned int loopSize = 0;
    while ((t < t_final) && (i < Me.size())) {
      int status = gsl_odeiv_evolve_apply(e, c, s, &sys, &t, t_final, &h, Mass);
      UQ_FATAL_TEST_MACRO((status != GSL_SUCCESS),
                          paramValues.env().fullRank(),
                          "likelihoodRoutine()",
                          "gsl_odeiv_evolve_apply() failed");
      //printf("t = %6.1lf, mass = %10.4lf\n",t,Mass[0]);
      //loopSize++;

      while ( (i < Me.size()) && (t_old <= Te[i]) && (Te[i] <= t) ) {
        Mt[i] = (Te[i]-t_old)*(Mass[0]-M_old[0])/(t-t_old) + M_old[0];
        misfit += (Me[i]-Mt[i])*(Me[i]-Mt[i]);
        //printf("%i %lf %lf %lf %lf\n",i,Te[i],Me[i],Mt[i],misfit);
        i++;
      }

      t_old=t;
      M_old[0]=Mass[0];
    }
    resultValue += misfit/variance;

    //printf("loopSize = %d\n",loopSize);
    if ((paramValues.env().displayVerbosity() >= 10) && (paramValues.env().fullRank() == 0)) {
      printf("In likelihoodRoutine(), A = %g, E = %g, beta = %.3lf: misfit = %lf, likelihood = %lf.\n",A,E,beta,misfit,resultValue);
    }

    gsl_odeiv_evolve_free (e);
    gsl_odeiv_control_free(c);
    gsl_odeiv_step_free   (s);
  }

  // Compute likelihood for scenario 2
  betaTest = m_beta2;
  if (betaTest > 0.) {
    double A                       = paramValues[0];
    double E                       = paramValues[1];
    double beta                    = m_beta2;
    double variance                = m_variance2;
    const std::vector<double>& Te  = m_Te2;
    const std::vector<double>& Me  = m_Me2;
    std::vector<double> Mt(Me.size(),0.);

    double params[]={A,E,beta};

    // integration
    const gsl_odeiv_step_type *T   = gsl_odeiv_step_rkf45; //rkf45; //gear1;
          gsl_odeiv_step      *s   = gsl_odeiv_step_alloc(T,1);
          gsl_odeiv_control   *c   = gsl_odeiv_control_y_new(1e-6,0.0);
          gsl_odeiv_evolve    *e   = gsl_odeiv_evolve_alloc(1);
          gsl_odeiv_system     sys = {func, NULL, 1, (void *)params};

    double t = 0.1, t_final = 1900.;
    double h = 1e-3;
    double Mass[1];
    Mass[0]=1.;

    unsigned int i = 0;
    double t_old = 0.;
    double M_old[1];
    M_old[0]=1.;

    double misfit=0.;
    //unsigned int loopSize = 0;
    while ((t < t_final) && (i < Me.size())) {
      int status = gsl_odeiv_evolve_apply(e, c, s, &sys, &t, t_final, &h, Mass);
      UQ_FATAL_TEST_MACRO((status != GSL_SUCCESS),
                          paramValues.env().fullRank(),
                          "likelihoodRoutine()",
                          "gsl_odeiv_evolve_apply() failed");
      //printf("t = %6.1lf, mass = %10.4lf\n",t,Mass[0]);
      //loopSize++;

      while ( (i < Me.size()) && (t_old <= Te[i]) && (Te[i] <= t) ) {
        Mt[i] = (Te[i]-t_old)*(Mass[0]-M_old[0])/(t-t_old) + M_old[0];
        misfit += (Me[i]-Mt[i])*(Me[i]-Mt[i]);
        //printf("%i %lf %lf %lf %lf\n",i,Te[i],Me[i],Mt[i],misfit);
        i++;
      }

      t_old=t;
      M_old[0]=Mass[0];
    }
    resultValue += misfit/variance;

    //printf("loopSize = %d\n",loopSize);
    if ((paramValues.env().displayVerbosity() >= 10) && (paramValues.env().fullRank() == 0)) {
      printf("In likelihoodRoutine(), A = %g, E = %g, beta = %.3lf: misfit = %lf, likelihood = %lf.\n",A,E,beta,misfit,resultValue);
    }

    gsl_odeiv_evolve_free (e);
    gsl_odeiv_control_free(c);
    gsl_odeiv_step_free   (s);
  }

  // Compute likelihood for scenario 3
  betaTest = m_beta3;
  if (betaTest > 0.) {
    double A                       = paramValues[0];
    double E                       = paramValues[1];
    double beta                    = m_beta3;
    double variance                = m_variance3;
    const std::vector<double>& Te  = m_Te3;
    const std::vector<double>& Me  = m_Me3;
    std::vector<double> Mt(Me.size(),0.);

    double params[]={A,E,beta};

    // integration
    const gsl_odeiv_step_type *T   = gsl_odeiv_step_rkf45; //rkf45; //gear1;
          gsl_odeiv_step      *s   = gsl_odeiv_step_alloc(T,1);
          gsl_odeiv_control   *c   = gsl_odeiv_control_y_new(1e-6,0.0);
          gsl_odeiv_evolve    *e   = gsl_odeiv_evolve_alloc(1);
          gsl_odeiv_system     sys = {func, NULL, 1, (void *)params};

    double t = 0.1, t_final = 1900.;
    double h = 1e-3;
    double Mass[1];
    Mass[0]=1.;

    unsigned int i = 0;
    double t_old = 0.;
    double M_old[1];
    M_old[0]=1.;

    double misfit=0.;
    //unsigned int loopSize = 0;
    while ((t < t_final) && (i < Me.size())) {
      int status = gsl_odeiv_evolve_apply(e, c, s, &sys, &t, t_final, &h, Mass);
      UQ_FATAL_TEST_MACRO((status != GSL_SUCCESS),
                          paramValues.env().fullRank(),
                          "likelihoodRoutine()",
                          "gsl_odeiv_evolve_apply() failed");
      //printf("t = %6.1lf, mass = %10.4lf\n",t,Mass[0]);
      //loopSize++;

      while ( (i < Me.size()) && (t_old <= Te[i]) && (Te[i] <= t) ) {
        Mt[i] = (Te[i]-t_old)*(Mass[0]-M_old[0])/(t-t_old) + M_old[0];
        misfit += (Me[i]-Mt[i])*(Me[i]-Mt[i]);
        //printf("%i %lf %lf %lf %lf\n",i,Te[i],Me[i],Mt[i],misfit);
        i++;
      }

      t_old=t;
      M_old[0]=Mass[0];
    }
    resultValue += misfit/variance;

    //printf("loopSize = %d\n",loopSize);
    if ((paramValues.env().displayVerbosity() >= 10) && (paramValues.env().fullRank() == 0)) {
      printf("In likelihoodRoutine(), A = %g, E = %g, beta = %.3lf: misfit = %lf, likelihood = %lf.\n",A,E,beta,misfit,resultValue);
    }

    gsl_odeiv_evolve_free (e);
    gsl_odeiv_control_free(c);
    gsl_odeiv_step_free   (s);
  }

  m_env.subComm().Barrier();
  //env.syncPrintDebugMsg("Leaving likelihoodRoutine()",1,env.fullComm());

  return -.5*resultValue;
}
Exemple #29
0
double
fevol_shrinker_eigenproblem (double bisec_param, int print, char * filename, void * p)
{
 const gsl_odeiv_step_type * T
    = STEPPER;

  gsl_odeiv_step * s
    = gsl_odeiv_step_alloc (T, 4);
  gsl_odeiv_control * c
    = gsl_odeiv_control_y_new (STEPPER_ERROR, 0.0);
  gsl_odeiv_evolve * e
    = gsl_odeiv_evolve_alloc (4);

  double dt=PRINT_DT, t_last=0.;

  gsl_odeiv_system sys = {func_shrinker_eigenproblem, jac_dummy, 4, (void*)&bisec_param};

  double t = T0;
  double h = H0;
  double A = *(double*)p;
  double y[4] = {		      /* expressions derived using
					 ~/SeriesSolve.nb */
    A*t + ((3*A - 4*(-1 + k)*pow(A,3))*pow(2 + k,-1)*pow(t,3))/12. +
    (A*(15 - 40*(-1 + k)*pow(A,2) + 16*pow(A,4)*(1 - 3*k + 2*pow(k,2)))*
     pow(t,5)*pow(8 + 6*k + pow(k,2),-1))/160.,
    A + ((3*A - 4*(-1 + k)*pow(A,3))*pow(2 + k,-1)*pow(t,2))/4. +
    (A*(15 - 40*(-1 + k)*pow(A,2) + 16*pow(A,4)*(1 - 3*k + 2*pow(k,2)))*
     pow(t,4)*pow(8 + 6*k + pow(k,2),-1))/32.,
    t,
    1.
  };

  FILE * file;

  if (print){
    file = fopen(filename, "a");
    fprintf(file, "# A = %.15f\n# lambda = %.15f\n", A, bisec_param );
  }

  while (t < T_MAX)
    {
      int status =
	gsl_odeiv_evolve_apply (e, c, s,
				&sys,
				&t, T_MAX,
				&h, y);

      if (status != GSL_SUCCESS)
	break;
      /* are we still in the strip [0,pi]?  is the lienarized solution
       reasonably boundaed?*/
      if ( 0. > y[0]
	   || y[0] > 3.15
	   || fabs(y[2]) > 10. )
	break;

      if (print /* && t_last+dt < t */)
	{
	  fprintf (file,
		   "%.15E %.15E %.15E %.15E %.15E\n",
		   t, y[0], y[1], y[2], y[3]);
	  t_last+=dt;
	  dt*=PRINT_DT_RATIO;
	}
      /* printf("%.15f\r",t); */
    }

  gsl_odeiv_evolve_free (e);
  gsl_odeiv_control_free (c);
  gsl_odeiv_step_free (s);
  if (print) {
    fprintf( file, "\n\n\n" );
    fclose( file );
  }

  return y[2];
}
Exemple #30
0
int main()
{
	
  double E2=0.;
  double A,E,beta,te[11],Me[11],Mt[11];
  int num_data;
  FILE *inp, *outp;
	
  inp = fopen("global.dat","r");
  fscanf(inp,"%lf %lf %lf",&A,&E,&beta);    /* read kinetic parameters */
	
  beta/=60.;	/* Convert heating rate to K/s */
  
  double params[]={A,E,beta};
      	
  // read experimental data
  int i=0;
  int status;
  while (1){
    status = fscanf(inp,"%lf %lf",&te[i],&Me[i]);
    if (status == EOF) break;
    i++;
  }
  num_data = i;
  fclose(inp);
	
  // integration
  const gsl_odeiv_step_type * T = gsl_odeiv_step_gear1;
	
  gsl_odeiv_step *s = gsl_odeiv_step_alloc(T,1);
  gsl_odeiv_control *c = gsl_odeiv_control_y_new(1e-6,0.0);
  gsl_odeiv_evolve *e = gsl_odeiv_evolve_alloc(1);
	
  gsl_odeiv_system sys = {func, NULL, 1, (void *)params}; 
	
  double t = 0.1, t1 = 800.;
  double h = 1e-3;
  double M[1];
         M[0]=1.;
  
  outp = fopen("global.out","w");
  fprintf(outp,"Temp (K)    M\n------------------\n");

  i=0;
  double t_old=0., M_old[1];
  M_old[0]=1.;
	
  while (t < t1){
    int status = gsl_odeiv_evolve_apply(e, c, s, &sys, &t, t1, &h, M);
		
    if (status != GSL_SUCCESS) break;
			
    fprintf(outp,"%6.1lf %10.4lf\n",t,M[0]);
		
    if ( (t >= te[i]) && (t_old <= te[i]) ) {
      Mt[i] = (te[i]-t_old)*(M[0]-M_old[0])/(t-t_old) + M_old[0];
      E2+=(Me[i]-Mt[i])*(Me[i]-Mt[i]);
      // fprintf(outp,"%i %lf %lf %lf %lf\n",i,te[i],Me[i],Mt[i],E2);
      i++;
    }
		
    t_old=t;
    M_old[0]=M[0];
	
  }
	
  fprintf(outp,"For A = %g, E = %g, and beta = %.3lf\n",A,E,beta);
  fprintf(outp,"the sum of squared errors is %lf.",E2);

  gsl_odeiv_evolve_free(e);
  gsl_odeiv_control_free(c);
  gsl_odeiv_step_free(s);

  fclose(outp);
	
  return 0;
	
}