Ejemplo n.º 1
0
	void exec( ) throw( general_error )
	{
		iec61853_module_t solver;
		msg_handler msgs( *this );
		solver._imsg = &msgs;

		util::matrix_t<double> input = as_matrix("input"), par;
		if ( input.ncols() != iec61853_module_t::COL_MAX )
			throw exec_error( "iec61853", "six data columns required for input matrix: IRR,TC,PMP,VMP,VOC,ISC");

		if (!solver.calculate( input, as_integer("nser"), as_integer("type"), par, as_boolean("verbose") ))
			throw exec_error( "iec61853", "failed to solve for parameters");

		assign("n", var_data((ssc_number_t)solver.n));
		assign("alphaIsc", var_data((ssc_number_t)solver.alphaIsc));
		assign("betaVoc", var_data((ssc_number_t)solver.betaVoc));
		assign( "gammaPmp", var_data((ssc_number_t)solver.gammaPmp) );
		assign( "Il", var_data((ssc_number_t)solver.Il) );
		assign( "Io", var_data((ssc_number_t)solver.Io) );
		assign( "C1", var_data((ssc_number_t)solver.C1) );
		assign( "C2", var_data((ssc_number_t)solver.C2) );
		assign( "C3", var_data((ssc_number_t)solver.C3) );
		assign( "D1", var_data((ssc_number_t)solver.D1) );
		assign( "D2", var_data((ssc_number_t)solver.D2) );
		assign( "D3", var_data((ssc_number_t)solver.D3) );
		assign( "Egref", var_data((ssc_number_t)solver.Egref) );

		ssc_number_t *output = allocate( "output", par.nrows(), par.ncols() );
		size_t c = 0;
		for( size_t i=0;i<par.nrows();i++ )
			for( size_t j=0;j<par.ncols();j++ )
				output[c++] = (ssc_number_t)par(i, j);
	}
Ejemplo n.º 2
0
SEXP rsqlite_query_send(SEXP handle, SEXP statement, SEXP bind_data) {
  SQLiteConnection* con = rsqlite_connection_from_handle(handle);
  sqlite3* db_connection = con->drvConnection;
  sqlite3_stmt* db_statement = NULL;
  int state, bind_count;
  int rows = 0, cols = 0;

  if (con->resultSet) {
    if (con->resultSet->completed != 1)
      warning("Closing result set with pending rows");
    rsqlite_result_free(con);
  }
  rsqlite_result_alloc(con);
  SQLiteResult* res = con->resultSet;

  /* allocate and init a new result set */
  res->completed = 0;
  char* dyn_statement = RS_DBI_copyString(CHAR(asChar(statement)));
  res->statement = dyn_statement;
  res->drvResultSet = db_statement;
  state = sqlite3_prepare_v2(db_connection, dyn_statement, -1,
      &db_statement, NULL);

  if (state != SQLITE_OK) {
    exec_error(con, "error in statement");
  }
  if (db_statement == NULL) {
    exec_error(con, "nothing to execute");
  }
  res->drvResultSet = (void*) db_statement;
  bind_count = sqlite3_bind_parameter_count(db_statement);
  if (bind_count > 0 && bind_data != R_NilValue) {
    rows = GET_LENGTH(GET_ROWNAMES(bind_data));
    cols = GET_LENGTH(bind_data);
  }

  res->isSelect = sqlite3_column_count(db_statement) > 0;
  res->rowCount = 0;      /* fake's cursor's row count */
  res->rowsAffected = -1; /* no rows affected */
  rsqlite_exception_set(con, state, "OK");

  if (res->isSelect) {
    if (bind_count > 0) {
      select_prepared_query(db_statement, bind_data, bind_count, rows, con);
    }
  } else {
    if (bind_count > 0) {
      non_select_prepared_query(db_statement, bind_data, bind_count, rows, con);
    } else {
      state = sqlite3_step(db_statement);
      if (state != SQLITE_DONE) {
        exec_error(con, "rsqlite_query_send: could not execute1");
      }
    }
    res->completed = 1;
    res->rowsAffected = sqlite3_changes(db_connection);
  }

  return handle;
}
Ejemplo n.º 3
0
static void		execute_shell(t_shell *sh, CMD *c, int fd_out, int fd_error)
{
	sh->inside_status = 1;
	if (c->type == C_ERROR)
	{
		exec_error(c, fd_error);
		change_status(sh, 1);
	}
	else if (c->type == C_BUILTIN && !is_extern_builtin(c))
		exec_builtin(sh, c, fd_out, fd_error);
	else
		sh->inside_status = 0;
}
Ejemplo n.º 4
0
static void
non_select_prepared_query(sqlite3_stmt* db_statement,
                          SEXP bind_data,
                          int bind_count,
                          int rows,
                          SQLiteConnection* con) {
  int state, i;
  char bindingErrorMsg[2048];
  bindingErrorMsg[0] = '\0';
  RSQLiteParams* params =
      RS_SQLite_createParameterBinding(bind_count, bind_data,
          db_statement, bindingErrorMsg);
  if (params == NULL) {
    /* FIXME: this UNPROTECT is ugly, paired to caller */
    UNPROTECT(1);
    exec_error(con, bindingErrorMsg);
  }

  /* we need to step through the query for each row */
  for (i = 0; i < rows; i++) {
    state = bind_params_to_stmt(params, db_statement, i);
    if (state != SQLITE_OK) {
      UNPROTECT(1);
      exec_error(con, "rsqlite_query_send: could not bind data");
    }
    state = sqlite3_step(db_statement);
    if (state != SQLITE_DONE) {
      UNPROTECT(1);
      exec_error(con, "rsqlite_query_send: could not execute");
    }
    state = sqlite3_reset(db_statement);
    sqlite3_clear_bindings(db_statement);
    if (state != SQLITE_OK) {
      UNPROTECT(1);
      exec_error(con, "rsqlite_query_send: could not reset statement");
    }
  }
  RS_SQLite_freeParameterBinding(&params);
}
Ejemplo n.º 5
0
static void
select_prepared_query(sqlite3_stmt* db_statement,
                      SEXP bind_data,
                      int bind_count,
                      int rows,
                      SQLiteConnection* con) {
  char bindingErrorMsg[2048];
  bindingErrorMsg[0] = '\0';
  RSQLiteParams* params =
      RS_SQLite_createParameterBinding(bind_count, bind_data,
          db_statement, bindingErrorMsg);
  if (params == NULL) {
    /* FIXME: this UNPROTECT is ugly, paired to caller */
    UNPROTECT(1);
    exec_error(con, bindingErrorMsg);
  }
  con->resultSet->drvData = params;
}
Ejemplo n.º 6
0
	void exec( ) throw( general_error )
	{
		size_t i, j, nrows, ncols; 
		// rated output ac
		double Paco = as_double("inv_cec_cg_paco");
		bool kW_units = (as_integer("inv_cec_cg_sample_power_units") == 1);

		// 6 columns period, tier, max usage, max usage units, buy, sell
		ssc_number_t *inv_cec_cg_test_samples_in = as_matrix("inv_cec_cg_test_samples", &nrows, &ncols);
		if (nrows != 18)
		{
			std::ostringstream ss;
			ss << "The samples table must have 18 rows. Number of rows in samples table provided is " << nrows << " rows.";
			throw exec_error("inv_cec_cg", ss.str());
		}
		if ((ncols % 3) != 0)
		{
			std::ostringstream ss;
			ss << "The samples table must have number of columns divisible by 3. Number of columns in samples table provided is " << ncols << " columns.";
			throw exec_error("inv_cec_cg", ss.str());
		}
		size_t num_samples = ncols / 3;
		size_t columns_per_sample = 3;
		util::matrix_t<float> inv_cec_cg_test_samples(nrows, ncols);
		inv_cec_cg_test_samples.assign(inv_cec_cg_test_samples_in, nrows, ncols);

		ssc_number_t vdc = 0, Pout = 0, eff = 0, Pin=0, Pin2=0;

		// set Pout, Pin=Pout/eff and Pin^2 for least squares fit
		// 6 is for the required power output percentages at each voltage for each sample
		util::matrix_t<ssc_number_t> &inv_cec_cg_Vmin = allocate_matrix("inv_cec_cg_Vmin", 6 * num_samples, 3);
		util::matrix_t<ssc_number_t> &inv_cec_cg_Vnom = allocate_matrix("inv_cec_cg_Vnom", 6 * num_samples, 3);
		util::matrix_t<ssc_number_t> &inv_cec_cg_Vmax = allocate_matrix("inv_cec_cg_Vmax", 6 * num_samples, 3);


		ssc_number_t *inv_cec_cg_Vdc = allocate("inv_cec_cg_Vdc", 3);
		ssc_number_t *inv_cec_cg_Vdc_Vnom = allocate("inv_cec_cg_Vdc_Vnom", 3);
		ssc_number_t *inv_cec_cg_Pdco = allocate("inv_cec_cg_Pdco", 3);
		ssc_number_t *inv_cec_cg_Psco = allocate("inv_cec_cg_Psco", 3);
		ssc_number_t *inv_cec_cg_C0 = allocate("inv_cec_cg_C0", 3);
		ssc_number_t *inv_cec_cg_C1 = allocate("inv_cec_cg_C1", 2);
		ssc_number_t *inv_cec_cg_C2 = allocate("inv_cec_cg_C2", 2);
		ssc_number_t *inv_cec_cg_C3 = allocate("inv_cec_cg_C3", 2);

		for (i = 0; i < 3; i++)
			inv_cec_cg_Vdc[i] = 0;

		for (j = 0; j < num_samples; j++)
		{
			for (i = 0; i < inv_cec_cg_test_samples.nrows(); i++)
			{
				vdc = inv_cec_cg_test_samples.at(i, j*columns_per_sample + 1);
				Pout = inv_cec_cg_test_samples.at(i, j*columns_per_sample);
				if (kW_units) Pout *= 1000; // kW to W
				eff = inv_cec_cg_test_samples.at(i, j*columns_per_sample+2);
				Pin = Pout;
				if (eff != 0.0f) Pin = (ssc_number_t)(100.0*Pout) / eff;
				Pin2 = Pin*Pin;
				if (i < 6) // Vmin 0 offset
				{
					inv_cec_cg_Vdc[0] += vdc;
					inv_cec_cg_Vmin.at(j * 6 + i, 0) = Pout;
					inv_cec_cg_Vmin.at(j * 6 + i, 1) = Pin;
					inv_cec_cg_Vmin.at(j * 6 + i, 2) = Pin2;
				}
				else if (i < 12) // Vnom 6 offset 
				{
					inv_cec_cg_Vdc[1] += vdc;
					inv_cec_cg_Vnom.at(j * 6 + i - 6, 0) = Pout;
					inv_cec_cg_Vnom.at(j * 6 + i-6, 1) = Pin;
					inv_cec_cg_Vnom.at(j * 6 + i-6, 2) = Pin2;
				}
				else // Vmax 12 offset
				{
					inv_cec_cg_Vdc[2] += vdc;
					inv_cec_cg_Vmax.at(j * 6 + i - 12, 0) = Pout;
					inv_cec_cg_Vmax.at(j * 6 + i - 12, 1) = Pin;
					inv_cec_cg_Vmax.at(j * 6 + i - 12, 2) = Pin2;
				}
			}
		}
		
		

		ssc_number_t *inv_cec_cg_Vmin_abc = allocate("inv_cec_cg_Vmin_abc", 3);
		ssc_number_t *inv_cec_cg_Vnom_abc = allocate("inv_cec_cg_Vnom_abc", 3);
		ssc_number_t *inv_cec_cg_Vmax_abc = allocate("inv_cec_cg_Vmax_abc", 3);


		std::vector<double> Pout_vec(inv_cec_cg_Vmin.nrows());
		std::vector<double> Pin_vec(inv_cec_cg_Vmin.nrows());
		int info;
		double C[3];// initial guesses for lsqfit
		size_t data_size = 3;

		// Vmin non-linear
		for (i = 0; i < inv_cec_cg_Vmin.nrows(); i++)
		{
			Pin_vec[i] = inv_cec_cg_Vmin.at(i, 1);
			Pout_vec[i] = inv_cec_cg_Vmin.at(i, 0);
		}
		C[0] = -1e-6;
		C[1] = 1;
		C[2] = 1e3;
		if (!(info=lsqfit(Quadratic_fit_eqn, 0, C, data_size, &Pin_vec[0], &Pout_vec[0], inv_cec_cg_Vmin.nrows())))
		{
			throw exec_error("inv_cec_cg", util::format("error in nonlinear least squares fit, error %d", info));
			return;
		}
		inv_cec_cg_Vmin_abc[0] = (ssc_number_t)C[0];
		inv_cec_cg_Vmin_abc[1] = (ssc_number_t)C[1];
		inv_cec_cg_Vmin_abc[2] = (ssc_number_t)C[2];

		// Vnom non-linear
		for (i = 0; i < inv_cec_cg_Vnom.nrows(); i++)
		{
			Pin_vec[i] = inv_cec_cg_Vnom.at(i, 1);
			Pout_vec[i] = inv_cec_cg_Vnom.at(i, 0);
		}
		C[0] = -1e-6;
		C[1] = 1;
		C[2] = 1e3;
		if (!(info = lsqfit(Quadratic_fit_eqn, 0, C, data_size, &Pin_vec[0], &Pout_vec[0], inv_cec_cg_Vnom.nrows())))
		{
			throw exec_error("inv_cec_cg", util::format("error in nonlinear least squares fit, error %d", info));
			return;
		}
		inv_cec_cg_Vnom_abc[0] = (ssc_number_t)C[0];
		inv_cec_cg_Vnom_abc[1] = (ssc_number_t)C[1];
		inv_cec_cg_Vnom_abc[2] = (ssc_number_t)C[2];

		// Vmax non-linear
		for (i = 0; i < inv_cec_cg_Vmax.nrows(); i++)
		{
			Pin_vec[i] = inv_cec_cg_Vmax.at(i, 1);
			Pout_vec[i] = inv_cec_cg_Vmax.at(i, 0);
		}
		C[0] = -1e-6;
		C[1] = 1;
		C[2] = 1e3;
		if (!(info = lsqfit(Quadratic_fit_eqn, 0, C, data_size, &Pin_vec[0], &Pout_vec[0], inv_cec_cg_Vmax.nrows())))
		{
			throw exec_error("inv_cec_cg", util::format("error in nonlinear least squares fit, error %d", info));
			return;
		}
		inv_cec_cg_Vmax_abc[0] = (ssc_number_t)C[0];
		inv_cec_cg_Vmax_abc[1] = (ssc_number_t)C[1];
		inv_cec_cg_Vmax_abc[2] = (ssc_number_t)C[2];

		// Fill in intermediate values
		//Vdc (Vmin, Vnom, Vmax)
		for (i = 0; i < 3;i++)
			inv_cec_cg_Vdc[i] /= (6 * num_samples);

		// Vdc-Vnom
		for (i = 0; i < 3; i++)
			inv_cec_cg_Vdc_Vnom[i] = inv_cec_cg_Vdc[i] - inv_cec_cg_Vdc[1];

		ssc_number_t a, b, c;
		// Pdco and Psco and C0
		a = inv_cec_cg_Vmin_abc[0];
		b = inv_cec_cg_Vmin_abc[1];
		c = inv_cec_cg_Vmin_abc[2];
		inv_cec_cg_Pdco[0] = (ssc_number_t)(-b + sqrt(b*b - 4 * a*(c - Paco)));
		inv_cec_cg_Psco[0] = (-b + sqrt(b*b - 4 * a*c));
		inv_cec_cg_C0[0] = a;
		if (a != 0)
		{
			inv_cec_cg_Pdco[0] /= (ssc_number_t)(2.0*a);
			inv_cec_cg_Psco[0] /= (ssc_number_t)(2.0*a);
		}

		a = inv_cec_cg_Vnom_abc[0];
		b = inv_cec_cg_Vnom_abc[1];
		c = inv_cec_cg_Vnom_abc[2];
		inv_cec_cg_Pdco[1] = (ssc_number_t)(-b + sqrt(b*b - 4 * a*(c - Paco)));
		inv_cec_cg_Psco[1] = (-b + sqrt(b*b - 4 * a*c));
		inv_cec_cg_C0[1] = a;
		if (a != 0)
		{
			inv_cec_cg_Pdco[1] /= (ssc_number_t)(2.0*a);
			inv_cec_cg_Psco[1] /= (ssc_number_t)(2.0*a);
		}

		// TODO - limit Psco max to not be less than zero per note in Workbook
		a = inv_cec_cg_Vmax_abc[0];
		b = inv_cec_cg_Vmax_abc[1];
		c = inv_cec_cg_Vmax_abc[2];
		inv_cec_cg_Pdco[2] = (ssc_number_t)(-b + sqrt(b*b - 4 * a*(c - Paco)));
		inv_cec_cg_Psco[2] = (-b + sqrt(b*b - 4 * a*c));
		inv_cec_cg_C0[2] = a;
		if (a != 0)
		{
			inv_cec_cg_Pdco[2] /= (ssc_number_t)(2.0*a);
			inv_cec_cg_Psco[2] /= (ssc_number_t)(2.0*a);
		}

		// C1, C2, C3 linear least squares
		// C1 Y=Pdco, X=Vdc-Vnom
		std::vector<double> X(3);
		std::vector<double> Y(3);
		double slope, intercept;

		// C1 using linear least squares fit
		for (i = 0; i < 3; i++)
		{
			X[i] = inv_cec_cg_Vdc_Vnom[i];
			Y[i] = inv_cec_cg_Pdco[i];
		}
		if ((info = linlsqfit(&slope, &intercept, &X[0], &Y[0], data_size)))
		{
			throw exec_error("inv_cec_cg", util::format("error in linear least squares fit, error %d", info));
			return;
		}
		inv_cec_cg_C1[0] = (ssc_number_t)slope;
		inv_cec_cg_C1[1] = (ssc_number_t)intercept;


		// C2 using linear least squares fit
		for (i = 0; i < 3; i++)
		{
			X[i] = inv_cec_cg_Vdc_Vnom[i];
			Y[i] = inv_cec_cg_Psco[i];
		}
		if ((info = linlsqfit(&slope, &intercept, &X[0], &Y[0], data_size)))
		{
			throw exec_error("inv_cec_cg", util::format("error in linear least squares fit, error %d", info));
			return;
		}
		inv_cec_cg_C2[0] = (ssc_number_t)slope;
		inv_cec_cg_C2[1] = (ssc_number_t)intercept;

		// C2 using linear least squares fit
		for (i = 0; i < 3; i++)
		{
			X[i] = inv_cec_cg_Vdc_Vnom[i];
			Y[i] = inv_cec_cg_C0[i];
		}
		if ((info = linlsqfit(&slope, &intercept, &X[0], &Y[0], data_size)))
		{
			throw exec_error("inv_cec_cg", util::format("error in linear least squares fit, error %d", info));
			return;
		}
		inv_cec_cg_C3[0] = (ssc_number_t)slope;
		inv_cec_cg_C3[1] = (ssc_number_t)intercept;

		// vdco is the average of Vnom of all samples column 2 and rows 7 through 12

		assign("Pdco", (var_data)inv_cec_cg_C1[1]);
		assign("Vdco", (var_data)inv_cec_cg_Vdc[1]);
		assign("Pso", (var_data)inv_cec_cg_C2[1]);
		assign("c0", (var_data)inv_cec_cg_C3[1]);
		assign("c1", (var_data)(inv_cec_cg_C1[0] / inv_cec_cg_C1[1]));
		assign("c2", (var_data)(inv_cec_cg_C2[0] / inv_cec_cg_C2[1]));
		assign("c3", (var_data)(inv_cec_cg_C3[0] / inv_cec_cg_C3[1]));
	}
Ejemplo n.º 7
0
/* evaluate a simple command (3.9.1)
 * 
 * this function doesn't put stuff in background, it always wait()s, so
 * it only needs to fork() real programs
 * ----------------------------------------------------------------------- */
int eval_simple_command(struct eval *e, struct ncmd *ncmd) {
  union node *nptr;
  int argc;
  char **argv;
  int status;
  union node *args = NULL;
  union node *assigns = NULL;
  union command cmd = { NULL };
  enum hash_id id = H_BUILTIN;
  struct vartab vars;
/*  struct fdstack io;*/
  union node *r;
  union node *redir = ncmd->rdir;

  /* expand arguments,
     if there are arguments we start a hashed search for the command */
  if(expand_args(ncmd->args, &args, 0)) {
    stralloc_nul(&args->narg.stra);
    cmd = exec_hash(args->narg.stra.s, &id);
  }

  /* expand and set the variables,
     mark them for export if we're gonna execute a command */
  if(expand_vars(ncmd->vars, &assigns)) {
    /* if we don't exit after the command, have a command and not a 
       special builtin the variable changes should be temporary */
    if(!(e->flags & E_EXIT) && cmd.ptr && id != H_SBUILTIN)
      vartab_push(&vars);
    
    for(nptr = assigns; nptr; nptr = nptr->list.next)
      var_setsa(&nptr->narg.stra, (cmd.ptr ? V_EXPORT : V_DEFAULT));

    tree_free(assigns);
  }
  
  /* do redirections if present */
/*  if(redir && id != H_SBUILTIN && id != H_EXEC)
    fdstack_push(&io);*/
    
  if(redir/* && id != H_PROGRAM*/) {
    for(r = redir; r; r = r->list.next) {
      struct fd *fd = NULL;
      
      /* if its the exec special builtin the new fd needs to be persistent */
      if(id != H_EXEC) fd_alloca(fd);
      
      /* return if a redirection failed */
      if(redir_eval(&r->nredir, fd, (id == H_EXEC ? R_NOW : 0))) {
        status = 1;
        goto end;
      }
      
      /* check if we need to initialize fd buffers for the new redirection */
      if(fd_needbuf(r->nredir.fd)) {
        /* if its not exec then set up buffers for 
           temporary redirections on the stack */
        if(id != H_EXEC)
          fd_setbuf(r->nredir.fd, alloca(FD_BUFSIZE), FD_BUFSIZE);
        else
          fd_allocbuf(r->nredir.fd, FD_BUFSIZE);
      }
    }
  }
  
  /* if there is no command we can return after 
     setting the vars and doing the redirections */
  if(args == NULL) {
    status = 0;
    goto end;
  }

  /* when the command wasn't found we abort */
  if(cmd.ptr == NULL) {
    sh_error(args->narg.stra.s);
    status = exec_error();
    goto end;
  }

  /* assemble argument list */
  argc = tree_count(args);
  
  argv = alloca((argc + 1) * sizeof(char *));
  expand_argv(args, argv);

  /* execute the command, this may or may not return, depending on E_EXIT */
  status = exec_command(id, cmd, argc, argv, (e->flags & E_EXIT), redir);

end:

  /* restore variable stack */
  if(varstack == &vars)
    vartab_pop(&vars);

  if(args)
    tree_free(args);
  
  /* undo redirections */
  if(id != H_EXEC) {
    for(r = redir; r; r = r->list.next)
      fd_pop(r->nredir.fd);
  }
  
/*  if(fdstack == &io)
    fdstack_pop(&io);*/

  return status;
}
Ejemplo n.º 8
0
/* execute another program, possibly searching for it first
 * 
 * if the 'exec' argument is set it will never return
 * ----------------------------------------------------------------------- */
int exec_program(char *path, char **argv, int exec, union node *redir) {
  int ret = 0;
  sigset_t nset, oset;
  
  /* if we're gonna execve() a program and 'exec' isn't 
     set or we aren't in the root shell environment we
     have to fork() so we can return */
  if(!exec || sh->parent) {
    pid_t pid;
    struct fdstack io;
    unsigned int n;

    fdstack_push(&io);

    /* buffered fds which have not a real effective file descriptor,
       like here-docs which are read from strallocs and command
       expansions, which write to strallocs can't be shared across
       different process spaces, so we have to establish pipes */
    if((n = fdstack_npipes(FD_HERE|FD_SUBST)))
      fdstack_pipe(n, fdstack_alloc(n));

    /* block child and interrupt signal, so we won't terminate ourselves
       when the child does */
    /*
    sigemptyset(&nset);
    sigaddset(&nset, SIGINT);

#ifdef SIGCHLD
    sigaddset(&nset, SIGCHLD);
#endif
    sigemptyset(&oset);
    sigprocmask(SIG_BLOCK, &nset, &oset);
*/
    sig_block();

    /* in the parent wait for the child to finish and then return 
       or exit, according to the 'exec' argument */
    if((pid = fork())) {
      int status = 1;

      /* this will close child ends of the pipes and read data from the parent end :) */
      fdstack_pop(&io);
      fdstack_data();

      
      job_wait(NULL, pid, &status, 0);
      job_status(pid, status);

      ret = WEXITSTATUS(status);

#ifndef __MINGW32__
      sigprocmask(SIG_SETMASK, &oset, NULL);
#endif
      
      /* exit if 'exec' is set, otherwise return */
      if(exec) sh_exit(ret);
      return ret;
    }

    /* ...in the child we always exit */
    sh_forked();
  }

  fdtable_exec();
  fdstack_flatten();

  /* when there is a path then we gotta execute a command,
     otherwise we exit/return immediately */
  if(path) {
    /* export environment */
    char **envp;
    unsigned long envn = var_count(V_EXPORT) + 1;
    envp = var_export(alloca(envn * sizeof(char *)));

    /* try to execute the program */
    execve(path, argv, envp);

    /* execve() returned so it failed, we're gonna map 
       the error code to the appropriate POSIX errors */
    ret = exec_error();

    /* yield an error message */
    sh_error(path);
  }

  /* we never return at this point! */
  exit(ret);
}
Ejemplo n.º 9
0
	void exec( ) throw( general_error )
	{
		bool header_only = as_boolean("header_only");
		const char *file = as_string("file_name");

		weatherfile wfile( file, header_only );
		if (!wfile.ok()) 
		{
			assign( "error", var_data(wfile.message()) );
			throw exec_error("wfreader", "failed to read local weather file: " + std::string(file) + "  " + wfile.message());
		}
		
		if( wfile.has_message() ) log( wfile.message(), SSC_WARNING );

		weather_header hdr;
		wfile.header( &hdr );

		size_t records = wfile.nrecords();
		
		for (int i = 3; i < 100; i++){

		}

		assign( "lat", var_data( (ssc_number_t)hdr.lat ) );
		assign( "lon", var_data( (ssc_number_t)hdr.lon ) );
		assign( "tz", var_data( (ssc_number_t)hdr.tz ) );
		assign( "elev", var_data( (ssc_number_t)hdr.elev ) );
		assign( "location", var_data( std::string( hdr.location ) ) );
		assign( "city", var_data( std::string( hdr.city ) ) );
		assign( "state", var_data( std::string( hdr.state ) ) );
		assign( "country", var_data( std::string( hdr.country ) ) );
		assign( "description", var_data( std::string( hdr.description ) ) );
		assign( "source", var_data( std::string( hdr.source ) ) );
		assign( "url", var_data( std::string( hdr.url ) ) );

		assign( "start", var_data( (ssc_number_t)wfile.start_sec() ) );
		assign( "step", var_data( (ssc_number_t)wfile.step_sec() ) );
		assign( "nrecords", var_data( (ssc_number_t)wfile.nrecords() ) );

		switch( wfile.type() )
		{
		case weatherfile::TMY2: assign("format", var_data("tmy2") ); break;
		case weatherfile::TMY3: assign("format", var_data("tmy3") ); break;
		case weatherfile::EPW: assign("format", var_data("epw") ); break;
		case weatherfile::SMW: assign("format", var_data("smw") ); break;
		case weatherfile::WFCSV: assign("format", var_data("csv") ); break;
		default: assign("format", var_data("invalid")); break;
		}

		if ( header_only )
			return;

		ssc_number_t *p_year = allocate( "year", records );
		ssc_number_t *p_month = allocate( "month", records );
		ssc_number_t *p_day = allocate( "day", records );
		ssc_number_t *p_hour = allocate( "hour", records );
		ssc_number_t *p_minute = allocate( "minute", records );
		
		ssc_number_t *p_global = allocate( "global", records );
		ssc_number_t *p_beam = allocate( "beam", records );
		ssc_number_t *p_diffuse = allocate( "diffuse", records );
		ssc_number_t *p_poa = allocate( "poa", records );
		
		ssc_number_t *p_wspd = allocate( "wspd", records );
		ssc_number_t *p_wdir = allocate( "wdir", records );
		ssc_number_t *p_tdry = allocate( "tdry", records );
		ssc_number_t *p_twet = allocate( "twet", records );
		ssc_number_t *p_tdew = allocate( "tdew", records );
		ssc_number_t *p_rhum = allocate( "rhum", records );
		ssc_number_t *p_pres = allocate( "pres", records );
		ssc_number_t *p_snow = allocate( "snow", records );
		ssc_number_t *p_albedo = allocate( "albedo", records );

		double gh_sum = 0.0, dn_sum = 0.0, df_sum = 0.0;
		double temp_sum = 0.0, wind_sum = 0.0;
		double snow_max = -1;

		double ts_hour = wfile.step_sec() / 3600.0;

		weather_record wf;

		for (int i=0;i<(int)records;i++)
		{
			if (!wfile.read( &wf ))
				throw exec_error("wfreader", "could not read data line " + util::to_string(i+1) + " of 8760");

			p_year[i] = (ssc_number_t)wf.year;
			p_month[i] = (ssc_number_t)wf.month;
			p_day[i] = (ssc_number_t)wf.day;
			p_hour[i] = (ssc_number_t)wf.hour;
			p_minute[i] = (ssc_number_t)wf.minute;

			p_global[i] = (ssc_number_t)wf.gh;
			p_beam[i] = (ssc_number_t)wf.dn;
			p_diffuse[i] = (ssc_number_t)wf.df;
			p_poa[i] = (ssc_number_t)wf.poa;

			p_wspd[i] = (ssc_number_t)wf.wspd;
			p_wdir[i] = (ssc_number_t)wf.wdir;
			p_tdry[i] = (ssc_number_t)wf.tdry;
			p_twet[i] = (ssc_number_t)wf.twet;
			p_tdew[i] = (ssc_number_t)wf.tdew;
			p_rhum[i] = (ssc_number_t)wf.rhum;
			p_pres[i] = (ssc_number_t)wf.pres;
			p_snow[i] = (ssc_number_t)wf.snow;
			p_albedo[i] = (ssc_number_t)wf.alb;	

			gh_sum += wf.gh * ts_hour;
			dn_sum += wf.dn * ts_hour;
			df_sum += wf.df * ts_hour;
			temp_sum += wf.tdry;
			wind_sum += wf.wspd; 
			if (!std::isnan(wf.snow) && (wf.snow > snow_max))
				snow_max = wf.snow;
		}
		
		if (snow_max < 0)
			snow_max = snow_max = std::numeric_limits<double>::quiet_NaN();


		assign("annual_global", var_data((ssc_number_t)(0.001 * gh_sum / 365)));
		assign("annual_beam", var_data((ssc_number_t) (0.001 * dn_sum / 365)));
		assign("annual_diffuse", var_data((ssc_number_t)(0.001 * df_sum / 365)));
		assign("annual_tdry", var_data((ssc_number_t)(temp_sum / records)));
		assign("annual_wspd", var_data((ssc_number_t)(wind_sum / records)));
		assign("annual_snow", var_data((ssc_number_t)snow_max));
	}
Ejemplo n.º 10
0
	void exec( ) throw( general_error )
	{
		//if ( 0 >= load_library("typelib") ) throw exec_error( "tcsgeneric_solar", util::format("could not load the tcs type library.") );

		//bool debug_mode = (__DEBUG__ == 1);  // When compiled in VS debug mode, this will use the trnsys weather file; otherwise, it will attempt to open the file with name that was passed in
		// type260_genericsolar uses 'poa_beam' from the weather reader, which is not available from a "trnsys_weatherreader", so this must be set to false
		bool debug_mode = false;

		//Add weather file reader unit
		int weather = 0;
		if(debug_mode) weather = add_unit("trnsys_weatherreader", "TRNSYS weather reader");
		else weather = add_unit("weatherreader", "TCS weather reader");
		
		// Add time-of-use reader
		int	tou = add_unit("tou_translator", "Time of Use Translator");
		//Add Physical Solar Field Model
		int	type260_genericsolar = add_unit( "sam_mw_gen_type260", "Generic solar model" );

		if(debug_mode)
		{
			set_unit_value( weather, "file_name", "C:/svn_NREL/main/ssc/tcsdata/typelib/TRNSYS_weather_outputs/tucson_trnsys_weather.out" );
			set_unit_value( weather, "i_hour", "TIME" );
			set_unit_value( weather, "i_month", "month" );
			set_unit_value( weather, "i_day", "day" );
			set_unit_value( weather, "i_global", "GlobalHorizontal" );
			set_unit_value( weather, "i_beam", "DNI" );
			set_unit_value( weather, "i_diff", "DiffuseHorizontal" );
			set_unit_value( weather, "i_tdry", "T_dry" );
			set_unit_value( weather, "i_twet", "T_wet" );
			set_unit_value( weather, "i_tdew", "T_dew" );
			set_unit_value( weather, "i_wspd", "WindSpeed" );
			set_unit_value( weather, "i_wdir", "WindDir" );
			set_unit_value( weather, "i_rhum", "RelHum" );
			set_unit_value( weather, "i_pres", "AtmPres" );
			set_unit_value( weather, "i_snow", "SnowCover" );
			set_unit_value( weather, "i_albedo", "GroundAlbedo" );
			set_unit_value( weather, "i_poa", "POA" );
			set_unit_value( weather, "i_solazi", "Azimuth" );
			set_unit_value( weather, "i_solzen", "Zenith" );
			set_unit_value( weather, "i_lat", "Latitude" );
			set_unit_value( weather, "i_lon", "Longitude" );
			set_unit_value( weather, "i_shift", "Shift" );
		}
		else
		{
			//Set weatherreader parameters
			set_unit_value_ssc_string( weather, "file_name" );
			set_unit_value_ssc_double( weather, "track_mode" );    //, 1 );
			set_unit_value_ssc_double( weather, "tilt" );          //, 0 );
			set_unit_value_ssc_double( weather, "azimuth" );       //, 0 );
		}

		set_unit_value_ssc_matrix(tou, "weekday_schedule"); // tou values from control will be between 1 and 9
		set_unit_value_ssc_matrix(tou, "weekend_schedule");

		//Set parameters
        set_unit_value_ssc_double(type260_genericsolar, "latitude" ); //, 35);
        set_unit_value_ssc_double(type260_genericsolar, "longitude" ); //, -117);
        set_unit_value_ssc_double(type260_genericsolar, "istableunsorted");
		set_unit_value_ssc_matrix(type260_genericsolar, "OpticalTable" ); //, opt_data);
        //set_unit_value_ssc_matrix(type260_genericsolar, "OpticalTableUns" );
        set_unit_value_ssc_double(type260_genericsolar, "timezone" ); //, -8);
        set_unit_value_ssc_double(type260_genericsolar, "theta_stow" ); //, 170);
        set_unit_value_ssc_double(type260_genericsolar, "theta_dep" ); //, 10);
        set_unit_value_ssc_double(type260_genericsolar, "interp_arr" ); //, 1);
        set_unit_value_ssc_double(type260_genericsolar, "rad_type" ); //, 1);
        set_unit_value_ssc_double(type260_genericsolar, "solarm" ); //, solarm);
        set_unit_value_ssc_double(type260_genericsolar, "T_sfdes" ); //, T_sfdes);
        set_unit_value_ssc_double(type260_genericsolar, "irr_des" ); //, irr_des);
        set_unit_value_ssc_double(type260_genericsolar, "eta_opt_soil" ); //, eta_opt_soil);
        set_unit_value_ssc_double(type260_genericsolar, "eta_opt_gen" ); //, eta_opt_gen);
        set_unit_value_ssc_double(type260_genericsolar, "f_sfhl_ref" ); //, f_sfhl_ref);
        set_unit_value_ssc_array(type260_genericsolar, "sfhlQ_coefs" ); //, [1,-0.1,0,0]);
        set_unit_value_ssc_array(type260_genericsolar, "sfhlT_coefs" ); //, [1,0.005,0,0]);
        set_unit_value_ssc_array(type260_genericsolar, "sfhlV_coefs" ); //, [1,0.01,0,0]);
        set_unit_value_ssc_double(type260_genericsolar, "qsf_des" ); //, q_sf);
        set_unit_value_ssc_double(type260_genericsolar, "w_des" ); //, w_gr_des);
        set_unit_value_ssc_double(type260_genericsolar, "eta_des" ); //, eta_cycle_des);
        set_unit_value_ssc_double(type260_genericsolar, "f_wmax" ); //, 1.05);
        set_unit_value_ssc_double(type260_genericsolar, "f_wmin" ); //, 0.25);
        set_unit_value_ssc_double(type260_genericsolar, "f_startup" ); //, 0.2);
        set_unit_value_ssc_double(type260_genericsolar, "eta_lhv" ); //, 0.9);
        set_unit_value_ssc_array(type260_genericsolar, "etaQ_coefs" ); //, [0.9,0.1,0,0,0]);
        set_unit_value_ssc_array(type260_genericsolar, "etaT_coefs" ); //, [1,-0.002,0,0,0]);
        set_unit_value_ssc_double(type260_genericsolar, "T_pcdes" ); //, 21);
        set_unit_value_ssc_double(type260_genericsolar, "PC_T_corr" ); //, 1);
        set_unit_value_ssc_double(type260_genericsolar, "f_Wpar_fixed" ); //, f_Wpar_fixed);
        set_unit_value_ssc_double(type260_genericsolar, "f_Wpar_prod" ); //, f_Wpar_prod);
        set_unit_value_ssc_array(type260_genericsolar, "Wpar_prodQ_coefs" ); //, [1,0,0,0]);
        set_unit_value_ssc_array(type260_genericsolar, "Wpar_prodT_coefs" ); //, [1,0,0,0]);
        set_unit_value_ssc_array(type260_genericsolar, "Wpar_prodD_coefs" ); //, [1,0,0,0]);
        set_unit_value_ssc_double(type260_genericsolar, "hrs_tes" ); //, hrs_tes);
        set_unit_value_ssc_double(type260_genericsolar, "f_charge" ); //, 0.98);
        set_unit_value_ssc_double(type260_genericsolar, "f_disch" ); //, 0.98);
        set_unit_value_ssc_double(type260_genericsolar, "f_etes_0" ); //, 0.1);
        set_unit_value_ssc_double(type260_genericsolar, "f_teshl_ref" ); //, 0.35);
        set_unit_value_ssc_array(type260_genericsolar, "teshlX_coefs" ); //, [1,0,0,0]);
        set_unit_value_ssc_array(type260_genericsolar, "teshlT_coefs" ); //, [1,0,0,0]);
        set_unit_value_ssc_double(type260_genericsolar, "ntod" ); //, 9);
        set_unit_value_ssc_array(type260_genericsolar, "disws" ); //, [0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1]);
        set_unit_value_ssc_array(type260_genericsolar, "diswos" ); //, [0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1]);
        set_unit_value_ssc_array(type260_genericsolar, "qdisp" ); //, [1,1,1,1,1,1,1,1,1]);
        set_unit_value_ssc_array(type260_genericsolar, "fdisp" ); //, [0,0,0,0,0,0,0,0,0]);
        set_unit_value_ssc_matrix(type260_genericsolar, "exergy_table" );
        set_unit_value_ssc_double(type260_genericsolar, "storage_config"); //Direct storage=0,Indirect storage=1


		//Set the initial values
        set_unit_value_ssc_double(type260_genericsolar, "ibn" ); //, 0.);	//Beam-normal (DNI) irradiation
        set_unit_value_ssc_double(type260_genericsolar, "ibh" ); //, 0.);	//	Beam-horizontal irradiation
        set_unit_value_ssc_double(type260_genericsolar, "itoth" ); //, 0.);	//	Total horizontal irradiation
        set_unit_value_ssc_double(type260_genericsolar, "tdb" ); //, 15.);	//	Ambient dry-bulb temperature
        set_unit_value_ssc_double(type260_genericsolar, "twb" ); //, 10.);	//	Ambient wet-bulb temperature
        set_unit_value_ssc_double(type260_genericsolar, "vwind" ); //, 1.);	//	Wind velocity

		// Connect the units
		bool bConnected = connect(weather, "beam", type260_genericsolar, "ibn");
		bConnected &= connect(weather, "global", type260_genericsolar, "itoth");
		bConnected &= connect(weather, "poa_beam", type260_genericsolar, "ibh");
		bConnected &= connect(weather, "tdry", type260_genericsolar, "tdb");
		bConnected &= connect(weather, "twet", type260_genericsolar, "twb");
		bConnected &= connect(weather, "wspd", type260_genericsolar, "vwind");
		//location
		bConnected &= connect(weather, "lat", type260_genericsolar, "latitude");
		bConnected &= connect(weather, "lon", type260_genericsolar, "longitude");
		bConnected &= connect(weather, "tz", type260_genericsolar, "timezone");
		bConnected &= connect(tou, "tou_value", type260_genericsolar, "TOUPeriod");


		// Example for changing an input variable name in the SSC interface
		// set_unit_value( u3, "m_dot_htf", as_double("m_dot_htf_init") );


		// check if all connections worked
		if ( !bConnected )
			throw exec_error( "tcsgeneric_solar", util::format("there was a problem connecting outputs of one unit to inputs of another for the simulation.") );
		
        size_t hours = 8760;

        //Load the solar field adjustment factors
        sf_adjustment_factors sf_haf(this);
        if (!sf_haf.setup())
			throw exec_error("tcsgeneric_solar", "failed to setup sf adjustment factors: " + sf_haf.error());
        //allocate array to pass to tcs
        ssc_number_t *sf_adjust = allocate("sf_adjust", hours);
        for( size_t i=0; i<hours; i++)
            sf_adjust[i] = sf_haf(i);
        set_unit_value_ssc_array(type260_genericsolar, "sf_adjust");

		// Run simulation
		if (0 > simulate(3600.0, hours*3600.0, 3600.0) )
			throw exec_error( "tcsgeneric_solar", util::format("there was a problem simulating in tcsgeneric_solar.") );

		// get the outputs
		if (!set_all_output_arrays() )
			throw exec_error( "tcsgeneric_solar", util::format("there was a problem returning the results from the simulation.") );

		// annual accumulations
		size_t count = 0;
		ssc_number_t *enet = as_array("enet", &count);
		if (!enet || count != 8760)
			throw exec_error("tcsgeneric_solar", "Failed to retrieve hourly net energy");

		adjustment_factors haf(this, "adjust");
		if (!haf.setup())
			throw exec_error("tcsgeneric_solar", "failed to setup adjustment factors: " + haf.error());


		ssc_number_t *hourly = allocate("gen", count);
		for (size_t i = 0; i < count; i++)
		{
			hourly[i] = enet[i] * 1000 * haf(i); // convert from MWh to kWh
		}

		accumulate_annual("gen",        "annual_energy");
		accumulate_annual("w_gr",                 "annual_w_gr",1000); // convert from MWh to kWh
		accumulate_annual("q_sf",                 "annual_q_sf");
		accumulate_annual("q_to_pb",              "annual_q_to_pb");
		accumulate_annual("q_to_tes",             "annual_q_to_tes");
		accumulate_annual("q_from_tes",           "annual_q_from_tes");
		accumulate_annual("q_hl_sf",              "annual_q_hl_sf");
		accumulate_annual("q_hl_tes",             "annual_q_hl_tes");
		accumulate_annual("q_dump_tot",           "annual_q_dump_tot");
		accumulate_annual("q_startup",            "annual_q_startup");
		double fuel_MWht = accumulate_annual("q_fossil",             "annual_q_fossil");


		// monthly accumulations
		accumulate_monthly("gen",       "monthly_energy");
		accumulate_monthly("w_gr",                "monthly_w_gr",1000); // convert from MWh to kWh
		accumulate_monthly("q_sf",                "monthly_q_sf");
		accumulate_monthly("q_to_pb",             "monthly_q_to_pb");
		accumulate_monthly("q_to_tes",            "monthly_q_to_tes");
		accumulate_monthly("q_from_tes",          "monthly_q_from_tes");
		accumulate_monthly("q_hl_sf",             "monthly_q_hl_sf");
		accumulate_monthly("q_hl_tes",            "monthly_q_hl_tes");
		accumulate_monthly("q_dump_tot",          "monthly_q_dump_tot");
		accumulate_monthly("q_startup",           "monthly_q_startup");
		accumulate_monthly("q_fossil",            "monthly_q_fossil");

		ssc_number_t ae = as_number("annual_energy");
		ssc_number_t pg = as_number("annual_w_gr");
		ssc_number_t convfactor = (pg != 0) ? 100 * ae / pg : 0;
		assign("conversion_factor", convfactor);


		// metric outputs moved to technology
		double kWhperkW = 0.0;
		double nameplate = as_double("system_capacity");
		double annual_energy = 0.0;
		for (int i = 0; i < 8760; i++)
			annual_energy += hourly[i];
		if (nameplate > 0) kWhperkW = annual_energy / nameplate;
		assign("capacity_factor", var_data((ssc_number_t)(kWhperkW / 87.6)));
		assign("kwh_per_kw", var_data((ssc_number_t)kWhperkW));

		assign("system_heat_rate", (ssc_number_t)3.413); // samsim tcsgeneric_solar
		assign("annual_fuel_usage", var_data((ssc_number_t)(fuel_MWht * 1000.0)));


	}