Beispiel #1
0
static void parse_module(module_info *info, const char *pathname)
{
	char *module_image;
	char *ptr;
	size_t len;
	size_t pos;
	dbg1_error_msg("parse_module('%s')", pathname);

	/* Read (possibly compressed) module */
	len = 64 * 1024 * 1024; /* 64 Mb at most */
	module_image = xmalloc_open_zipped_read_close(pathname, &len);
	/* module_image == NULL is ok here, find_keyword handles it */
//TODO: optimize redundant module body reads

	/* "alias1 symbol:sym1 alias2 symbol:sym2" */
	reset_stringbuf();
	pos = 0;
	while (1) {
		ptr = find_keyword(module_image + pos, len - pos, "alias=");
		if (!ptr) {
			ptr = find_keyword(module_image + pos, len - pos, "__ksymtab_");
			if (!ptr)
				break;
			/* DOCME: __ksymtab_gpl and __ksymtab_strings occur
			 * in many modules. What do they mean? */
			if (strcmp(ptr, "gpl") == 0 || strcmp(ptr, "strings") == 0)
				goto skip;
			dbg2_error_msg("alias:'symbol:%s'", ptr);
			append("symbol:");
		} else {
			dbg2_error_msg("alias:'%s'", ptr);
		}
		append(ptr);
		appendc(' ');
 skip:
		pos = (ptr - module_image);
	}
	bksp(); /* remove last ' ' */
	info->aliases = copy_stringbuf();
	replace(info->aliases, '-', '_');

	/* "dependency1 depandency2" */
	reset_stringbuf();
	ptr = find_keyword(module_image, len, "depends=");
	if (ptr && *ptr) {
		replace(ptr, ',', ' ');
		replace(ptr, '-', '_');
		dbg2_error_msg("dep:'%s'", ptr);
		append(ptr);
	}
	info->deps = copy_stringbuf();

	free(module_image);
}
Beispiel #2
0
struct keyword *
find_keyword(vector keywords, vector v, char * name)
{
	struct keyword *keyword;
	int i;
	int len;

	if (!name || !keywords)
		return NULL;

	if (!v)
		v = keywords;

	len = strlen(name);

	for (i = 0; i < VECTOR_SIZE(v); i++) {
		keyword = VECTOR_SLOT(v, i);
		if ((strlen(keyword->string) == len) &&
		    !strcmp(keyword->string, name))
			return keyword;
		if (keyword->sub) {
			keyword = find_keyword(keywords, keyword->sub, name);
			if (keyword)
				return keyword;
		}
	}
	return NULL;
}
/**
 * Create a new program line with number 'number' and the command in 's'.
 */
void create_line(unsigned int number, char *s) {
  unsigned char command;
  char * args;
  program_line * new_line;
  args = find_args(s);
  command = find_keyword(s);
  if (command != CMD_UNKNOWN) {
    delete_line(number);
    new_line = malloc(sizeof(program_line));
    new_line->number = number;
    new_line->command = command;
    new_line->args = malloc(strlen(args) + 1);
    strcpy(new_line->args, args);
    if (program && number > program->number) {
      program_line *line = program;
      while (line->next && number > line->next->number) {
        line = line->next;
      }
      new_line->next = line->next;
      line->next = new_line;
    } else {
      new_line->next = program;
      program = new_line;
    }
  } else {
    lcd_puts("Unknown command!\n");
  }
}
bool readSLParameterPoolData(std::string filename, std::string keyword, int n_values, std::vector<double>& values)
{
	int    i,rc;
	FILE  *in;

	char key[keyword.size()];
	strcpy(key, keyword.c_str());

	in = fopen_strip(filename.c_str());
	if (in == NULL) {
		printf("ERROR: Cannot open file >%s<!\n",filename.c_str());
		return FALSE;
	}

	// find keyword
	if (!find_keyword(in, key)) {
		printf("ERROR: cannot find keyword %s\n", key);
		fclose(in);
		return FALSE;
	} else {
		for (i=1; i<=n_values; ++i) {
			rc=fscanf(in,"%lf",&(values[i]));
			if (rc != 1)
			{
				printf("ERROR rc != 1\n");
				return FALSE;
			}
		}
	}

	fclose(in);

	return TRUE;
}
Beispiel #5
0
static int
ok_identifier(const char *name)
{
    const char *p = name;

    if (*p != '\0' && (my_is_xid_start(*p) || *p == '_')) {
	while (*++p != '\0' && (my_is_xid_cont(*p) || *p == '_'));
	if (*p == '\0' && !find_keyword(name))
	    return 1;
    }
    return 0;
}
/**
 * Execute the BASIC command in 's'.
 */
void execute(char *s) {
  unsigned char command;
  char * args;
  reset_interrupted();
  s = skip_whitespace(s);
  args = find_args(s);
  command = find_keyword(s);
  if (command != CMD_UNKNOWN) {
    command_functions[command](args);
  } else {
    lcd_puts("Unknown command!\n");
  }
}
Beispiel #7
0
/*!*****************************************************************************
 *******************************************************************************
\note  read_sensor_filters
\date  May 2000
\remarks 

parses the sensor filter configuration file into global variables

 *******************************************************************************
 Function Parameters: [in]=input,[out]=output

 \param[in]     fname : name of configuration file

 ******************************************************************************/
int
read_sensor_filters(char *fname) {

  int j, i,rc;
  char   string[100];
  FILE  *in;
  double dum;

  sprintf(string,"%s%s",CONFIG,fname);
  in = fopen(string,"r");
  if (in == NULL) {
    printf("ERROR: Cannot open file >%s<!\n",string);
    return FALSE;
  }

  /* find all joint variables and read them into the appropriate array */
  for (i=1; i<= n_dofs; ++i) {
    if (!find_keyword(in, &(joint_names[i][0]))) {
      printf("ERROR: Cannot find filters for >%s<!\n",joint_names[i]);
      return FALSE;
    }
    rc=fscanf(in,"%d %d %d %d",&(fth[i].cutoff),
	   &(fthd[i].cutoff),&(fthdd[i].cutoff),&(fload[i].cutoff));
  }
  
  for (i=1; i<= n_misc_sensors; ++i) {
    if (!find_keyword(in, &(misc_sensor_names[i][0]))) {
      printf("ERROR: Cannot find filters for >%s<!\n",misc_sensor_names[i]);
      return FALSE;
    }
    rc=fscanf(in,"%d",&(fmisc_sensor[i].cutoff));
  }
  
  fclose(in);

  return TRUE;

}
Beispiel #8
0
void Eliza::find_response() {
	find_keyword();
	std::string tempStr = m_sKeyWord;
	tempStr.insert(0, " ");
	tempStr.append(" ");
	if(tempStr.find(" MY ") != std::string::npos ||
		tempStr.find(" I'M ") != std::string::npos ||
		tempStr.find(" I ") != std::string::npos) {
		memorise_input();
	}
	save_user_name();
	if(!bot_understand()) {
		handle_unknown_sentence();
	}
}
Beispiel #9
0
size_t cconv_utf8(const char** inbuf, size_t* inleft, char**  outbuf, size_t* outleft, const language_zh_map *m, int map_size)
{
	const char *ps_inbuf;
	char *ps_outbuf;
	int index;
	size_t i_proc, o_proc, i_conv = 0, o_conv;

	ps_inbuf  = *inbuf;
	ps_outbuf = *outbuf;
	for (; *inleft > 0 && *outleft > 0; )
	{
		if((i_proc = utf8_char_width(const_bin_c_str(ps_inbuf))) > *inleft)
			break;

		if(i_proc > 1 &&
		  (index = find_keyword(ps_inbuf, &i_proc, m, 0, map_size - 1, i_conv)) != -1)
		{
			o_proc = strlen(map_val(m, index));
			memcpy(ps_outbuf, map_val(m, index), o_proc);
			ps_inbuf  += i_proc;
			ps_outbuf += o_proc;
			*inleft   -= i_proc;
			*outleft  -= o_proc;
			i_conv    += i_proc;
			continue;
		}
		
		if(i_proc == -1)
		{
			errno  = EINVAL;
			return (size_t)(-2);
		}

		memcpy(ps_outbuf, ps_inbuf, i_proc);
		ps_inbuf  += i_proc;
		ps_outbuf += i_proc;
		*inleft   -= i_proc;
		*outleft  -= i_proc;
		i_conv    += i_proc;
	}

	o_conv = ps_outbuf - *outbuf;
	*ps_outbuf = '\0';
	*inbuf  = ps_inbuf;
	*outbuf = ps_outbuf;
	return o_conv;
}
Beispiel #10
0
void ofxEliza::find_response() {
	find_keyword();
	std::string tempStr = m_sKeyWord;
	tempStr.insert(0, " ");
	tempStr.append(" ");
	if(tempStr.find(" MY ") != std::string::npos ||
       tempStr.find(" I'M ") != std::string::npos ||
       tempStr.find(" I ") != std::string::npos) {
		m_sSymbol = "@";
        extract_suffix();
        memory.push(m_sSuffix);
	}
	save_user_name();
	if(!bot_understand()) {
		handle_unknown_sentence();
	}
}
Beispiel #11
0
/*!*****************************************************************************
 *******************************************************************************
\note  init_pp
\date  June 1999
   
\remarks 

    initialize the post processing

 *******************************************************************************
 Function Parameters: [in]=input,[out]=output

 \param[in]     name : name of the post processing file

 ******************************************************************************/
int
init_pp(char *name)

{

  int i,j,n,rc;
  char   string[100];
  FILE  *in;


  /* get the post processing information */

  sprintf(string,"%s%s",PREFS,name);
  in = fopen_strip(string);
  if (in == NULL) {
    printf("ERROR: Cannot open file >%s<!\n",string);
    return FALSE;
  }

  /* find all blobs and read their information */

  sprintf(string,"PREDICT");
  if (find_keyword(in, string)) {
    rc=fscanf(in,"%lf",&predict);
  } else {
    predict = 0.0;
  }

  for (i=1; i<= max_blobs; ++i) {

    sprintf(string,"%s_KALMAN",blob_names[i]);
    if (find_keyword(in, string)) {
      blobpp[i].filter_type = KALMAN;
      for (j= _X_; j<= _Z_; ++j)
	for (n= _X_; n<= _Z_; ++n)
	  rc=fscanf(in,"%lf",&(blobpp[i].kal[j][n]));
    } else {
      for (j= _X_; j<= _Z_; ++j)
	for (n= _X_; n<= _Z_; ++n)
	  blobpp[i].kal[j][n]=1.0;
    }

    sprintf(string,"%s_BUTTER",blob_names[i]);
    if (find_keyword(in, string)) {
      blobpp[i].filter_type = BUTTER;
      for (j= _X_; j<= _Z_; ++j)
	for (n= _X_; n<= _Z_; ++n)
	  rc=fscanf(in,"%d",&(blobpp[i].fblob[j][n].cutoff));
    } else {
      for (j= _X_; j<= _Z_; ++j)
	for (n= _X_; n<= _Z_; ++n)
	  blobpp[i].fblob[j][n].cutoff=100;
    }

    sprintf(string,"%s_ACCELERATION",blob_names[i]);
    if (find_keyword(in, string)) {
      for (j= _X_; j<= _Z_; ++j)
	rc=fscanf(in,"%lf",&(blobpp[i].acc[j]));
    } else {
      for (j= _X_; j<= _Z_; ++j)
	blobpp[i].acc[j]=NOT_USED;
    }

  }

  /* do any blobs coincide with the endeffector? */
  sprintf(string,"ENDEFFECTOR");
  if (find_keyword(in, string)) {
    for (i=1; i<=max_blobs; ++i) {
      rc=fscanf(in,"%d",&blob_is_endeffector[i]);
      if (blob_is_endeffector[i] > n_endeffs || blob_is_endeffector[i] < 0)
	blob_is_endeffector[i] = FALSE;
    }
  } else {
    for (i=1; i<=max_blobs; ++i)
      blob_is_endeffector[i]=FALSE;
  }

  learn_transformation_flag = FALSE;
  for (i=1; i<=max_blobs; ++i) {
    if (blob_is_endeffector[i])
      learn_transformation_flag = TRUE;
  }

  
  fclose(in);
  remove_temp_file();

  /* keep track of which post processing script we are using */
  strcpy(current_pp_name,name);

  return TRUE;

}
Beispiel #12
0
/*!*****************************************************************************
 *******************************************************************************
  \note  read_sine_script
  \date  June 1999

  \remarks

  parse a script which describes the sine task

 *******************************************************************************
 Function Parameters: [in]=input,[out]=output

  none

 ******************************************************************************/
static int
read_sine_script(void)
{
    int j,i,rc;
    static char string[100];
    static char fname[100] = "default.sine";
    FILE *fp;
    int found = FALSE;
    double total_amp;
    double ratio;

    /* clear the current parameters */
    for (i=1; i<=n_dofs; ++i) {
        off[i] = joint_default_state[i].th;
        n_sine[i] = 0;
        for (j=1; j<=MAX_SINE; ++j) {
            amp[i][j] = phase[i][j] = freq[i][j] = 0.0;
        }
    }

    /* open the script, and parse the parameters */

    while (TRUE) {
        if (!get_string("Name of the Sine Script File\0",fname,fname))
            return FALSE;

        /* try to read this file */
        sprintf(string,"%s%s",PREFS,fname);
        fp = fopen_strip(string);
        if (fp != NULL)
            break;
    }

    for (i=1; i<= n_dofs; ++i) {
        if (find_keyword(fp, &(joint_names[i][0]))) {
            found = TRUE;
            total_amp = 0.0;
            rc=fscanf(fp,"%d %lf",&n_sine[i],&off[i]);
            /* check for out of range */
            if (off[i] > joint_range[i][MAX_THETA]) {
                off[i] = joint_range[i][MAX_THETA];
                printf("Reduced offset of joint %s to %f\n",joint_names[i],off[i]);
            }
            if (off[i] < joint_range[i][MIN_THETA]) {
                off[i] = joint_range[i][MIN_THETA];
                printf("Reduced offset of joint %s to %f\n",joint_names[i],off[i]);
            }
            for (j=1; j<=n_sine[i]; ++j) {
                rc=fscanf(fp,"%lf %lf %lf",&(amp[i][j]),&(phase[i][j]),&(freq[i][j]));
                total_amp += amp[i][j];
            }
            /* check for out of range */
            if (total_amp+off[i] > joint_range[i][MAX_THETA]) {
                ratio = total_amp/(joint_range[i][MAX_THETA]-off[i]+1.e-10);
                for (j=1; j<=n_sine[i]; ++j)
                    amp[i][j] /= ratio;
                printf("Reduced amplitude of joint %s to %f\n",joint_names[i],
                       amp[i][j]);
            }
            if (-total_amp+off[i] < joint_range[i][MIN_THETA]) {
                ratio = total_amp/(off[i]-joint_range[i][MIN_THETA]+1.e-10);
                for (j=1; j<=n_sine[i]; ++j)
                    amp[i][j] /= ratio;
                printf("Reduced amplitude of joint %s to %f\n",joint_names[i],
                       amp[i][j]);
            }
        }
    }

    fclose(fp);
    remove_temp_file();


    return found;

}
void read_vehicle_profile(const std::string& unitName, UnitProfile *profile)
{
    int field;
    char temp_str[80];
    parameter_list param_list;
    int temp_int;
    short not_done = true;

    std::string file_path = "units/profiles/";
    file_path += unitName;
    file_path += ".pfl";

    profile->unitname = unitName;

    try {
	std::auto_ptr<filesystem::ReadFile> file(
                filesystem::openRead(file_path));

	while( not_done ) {
	    for(int i=0; i<80; i++) {
		file->read(&(temp_str[i]), 1, 1);
		if(temp_str[i] == '\n') {
		    temp_str[i] = 0;
		    break;
		}
	    }
	    string_to_params( temp_str, &param_list );
	    find_keyword( param_list.params[0], &field, (char * ) field_headers, max_field_key );

	    switch(field) {
		case _hit_points:
		    {
 			sscanf( param_list.params[1], "%d", &temp_int );
			profile->hit_points = (short) temp_int;
		    }
		    break;

		case _attack_x:
		    {
   			sscanf( param_list.params[1], "%d", &temp_int );
			profile->attack_factor = (short) temp_int;
		    }
		    break;

		case _reload_time:
		    {
			sscanf( param_list.params[1], "%d", &temp_int );
			profile->reload_time = (char) temp_int;
		    }
		    break;

		case _react_time :
		    {
			sscanf( param_list.params[1], "%d", &temp_int );
			profile->reaction_time = (char) temp_int;
		    }
		    break;

		case _range_max : 
		    {
			sscanf( param_list.params[1], "%d", &temp_int );
			profile->attack_range = (long) temp_int;
		    }
		    break;

		case _regen_time: 
		    {
			sscanf( param_list.params[1], "%d", &temp_int );
			profile->regen_time = (short) temp_int;
		    }
		    break;

		case _defend_range: 
		    {
			sscanf( param_list.params[1], "%d", &temp_int );
			profile->defend_range = (long) temp_int;
		    }
		    break;

		case _speed_rate: 
		    {
			sscanf( param_list.params[1], "%d", &temp_int );
			profile->speed_rate = (char) temp_int;
		    }
		    break;

		case _speed_factor:
		    {
			sscanf( param_list.params[1], "%d", &temp_int );
			profile->speed_factor = (char) temp_int;
		    }
		    break;

		case _repath_time: 
		    {
			sscanf( param_list.params[1], "%d", &temp_int );
			profile->repath_time = (char) temp_int;
		    }
		    break;

		case _fuel_capacity:
		    {
			sscanf( param_list.params[1], "%d", &temp_int );
			profile->fuel_capacity = (short ) temp_int;
		    }
		    break;

		case _tracking_rate:
		    {
			sscanf( param_list.params[1], "%d", &temp_int );
			profile->tracking_rate = (char) temp_int;
		    }
		    break;

		case _jamm_able:
		    {
			sscanf( param_list.params[1], "%d", &temp_int );
			profile->jammable = (char) temp_int;
		    }
		    break;

		case _jamming_time:
		    {
			sscanf( param_list.params[1], "%d", &temp_int );
			profile->jamming_time = (char) temp_int;
		    }
		    break;

		case _jamming_range:
		    {
			sscanf( param_list.params[1], "%d", &temp_int );
			profile->jamming_range = (long) temp_int;
		    }
		    break;

		case _fueling_range:
		    {
			sscanf( param_list.params[1], "%d", &temp_int );
			profile->fueling_range = (long) temp_int;
		    }
		    break;

		case _end :
		    {
			not_done = false;
		    }
		    break;
	    } // ** switch
	} // ** while ( !feof )
    } catch(std::exception& e) {
	throw Exception("Error while reading unitprofile '%s': %s",
		file_path.c_str(), e.what());
    }
} // function
static void parse_module(module_info *info, const char *pathname)
{
	char *module_image;
	char *ptr;
	size_t len;
	size_t pos;
	dbg1_error_msg("parse_module('%s')", pathname);

	/* Read (possibly compressed) module */
	len = 64 * 1024 * 1024; /* 64 Mb at most */
	module_image = xmalloc_open_zipped_read_close(pathname, &len);
	/* module_image == NULL is ok here, find_keyword handles it */
//TODO: optimize redundant module body reads

	/* "alias1 symbol:sym1 alias2 symbol:sym2" */
	reset_stringbuf();
	pos = 0;
	while (1) {
		unsigned start = stringbuf_idx;
		ptr = find_keyword(module_image + pos, len - pos, "alias=");
		if (!ptr) {
			ptr = find_keyword(module_image + pos, len - pos, "__ksymtab_");
			if (!ptr)
				break;
			/* DOCME: __ksymtab_gpl and __ksymtab_strings occur
			 * in many modules. What do they mean? */
			if (strcmp(ptr, "gpl") == 0 || strcmp(ptr, "strings") == 0)
				goto skip;
			dbg2_error_msg("alias:'symbol:%s'", ptr);
			append("symbol:");
		} else {
			dbg2_error_msg("alias:'%s'", ptr);
		}
		append(ptr);
		appendc(' ');
		/*
		 * Don't add redundant aliases, such as:
		 * libcrc32c.ko symbol:crc32c symbol:crc32c
		 */
		if (start) { /* "if we aren't the first alias" */
			char *found, *last;
			stringbuf[stringbuf_idx] = '\0';
			last = stringbuf + start;
			/*
			 * String at last-1 is " symbol:crc32c "
			 * (with both leading and trailing spaces).
			 */
			if (strncmp(stringbuf, last, stringbuf_idx - start) == 0)
				/* First alias matches us */
				found = stringbuf;
			else
				/* Does any other alias match? */
				found = strstr(stringbuf, last-1);
			if (found < last-1) {
				/* There is absolutely the same string before us */
				dbg2_error_msg("redundant:'%s'", last);
				stringbuf_idx = start;
				goto skip;
			}
		}
 skip:
		pos = (ptr - module_image);
	}
	bksp(); /* remove last ' ' */
	info->aliases = copy_stringbuf();
	replace(info->aliases, '-', '_');

	/* "dependency1 depandency2" */
	reset_stringbuf();
	ptr = find_keyword(module_image, len, "depends=");
	if (ptr && *ptr) {
		replace(ptr, ',', ' ');
		replace(ptr, '-', '_');
		dbg2_error_msg("dep:'%s'", ptr);
		append(ptr);
	}
	info->deps = copy_stringbuf();

	free(module_image);
}
Beispiel #15
0
int
parse_config(void *context, FILE *cfg, const struct Keyword *grammar) {
    enum Token token;
    char buffer[256];
    const struct Keyword *keyword = NULL;
    void *sub_context = NULL;
    int result;

    while ((token = next_token(cfg, buffer, sizeof(buffer))) != TOKEN_END) {
        switch (token) {
            case TOKEN_ERROR:
                err("%s: tokenizer error", __func__);
                return -1;
            case TOKEN_WORD:
                if (keyword && sub_context && keyword->parse_arg) {
                    result = keyword->parse_arg(sub_context, buffer);
                    if (result <= 0)
                        return result;

                } else if ((keyword = find_keyword(grammar, buffer))) {
                    if (keyword->create)
                        sub_context = keyword->create();
                    else
                        sub_context = context;

                    if (sub_context == NULL) {
                        err("failed to create subcontext");
                        return -1;
                    }

                    /* Special case for wildcard grammars i.e. tables */
                    if (keyword->keyword == NULL && keyword->parse_arg) {
                        result = keyword->parse_arg(sub_context, buffer);
                        if (result <= 0)
                            return result;
                    }

                } else {
                    err("%s: unknown keyword %s", __func__, buffer);
                    return -1;
                }
                break;
            case TOKEN_OBRACE:
                if (keyword && sub_context && keyword->block_grammar) {
                    result = parse_config(sub_context, cfg,
                            keyword->block_grammar);
                    if (result <= 0)
                        return result;
                } else {
                    err("%s: block without context", __func__);
                    return -1;
                }
                break;
            case TOKEN_EOL:
                if (keyword && sub_context && keyword->finalize) {
                    result = keyword->finalize(context, sub_context);
                    if (result <= 0)
                        return result;
                }

                keyword = NULL;
                sub_context = NULL;
                break;
            case TOKEN_CBRACE:
                /* Finalize the current subcontext before returning */
                if (keyword && sub_context && keyword->finalize) {
                    result = keyword->finalize(context, sub_context);
                    if (result <= 0)
                        return result;
                }

                /* fall through */
            case TOKEN_END:
                return 1;
        }
    }
    return 1;
}
Beispiel #16
0
void
read_script(void)
     
{ 
  
  int     i,j,k,m,rc;
  char    fname[100];
  double  dummy;
  int     idummy;
  FILE   *in,*out;
  int     n_train_data_columns;
  int     n_test_data_columns;
  Vector  row;
  char    identification_string[100];
  char    string[100];
  int     num;
  char    vnames[50][100];
  int     ans = 0;
  double  o_noise, c_noise;
  int     old_indx_flag = FALSE;

  Matrix  D_train=NULL;
  char  **vnames_train=NULL;
  char  **units_train=NULL;
  double  freq_train;
  int     n_cols_train;
  int     n_rows_train;
  
  Matrix  D_test=NULL;
  char  **vnames_test=NULL;
  char  **units_test=NULL;
  double  freq_test;
  int     n_cols_test;
  int     n_rows_test;
  

  /* I need the filename of the script file: first check whether the
     user provided it in the argv_global variables */

  if (argc_global > 0) {
    in = fopen(argv_global[1],"r");
    if (in != NULL) {
      fclose(in);
      strcpy(fname,argv_global[1]);
    } else {
      if (!getFile(fname)) exit(-1);
    }
  } else {
    if (!getFile(fname)) exit(-1);
  }

  /* this allows to generate the LWPR */
  if (argc_global > 1) {
    sscanf(argv_global[2],"%d",&new_model);
  } else {
    get_int("Generate new LWPR = 1; Read from file = 0",ans,&ans);
    if (ans) new_model = TRUE;
  }

  if (!readLWPRScript(fname,new_model,LWPR1)) {

    fprintf(stderr,"Error when reading script file >%s<\n",fname);
    exit(-1);

  }
  

  /* now read additional variables from the script */
  in  = fopen_strip(fname);

  /* check for included files */
  if (find_keyword(in,"include")) {  
    char  fname_include[100];
    FILE *fp_include;

    rc=fscanf(in,"%s",fname_include);
    fp_include = fopen_strip(fname_include);
    fseek(fp_include, 0, SEEK_END);
    rewind(in);
    while ((rc=fgetc(in)) != EOF)
      fputc(rc,fp_include);

    fclose(in);
    in = fp_include;

    rewind(in);
  }
    
  /* All the names in file will be parsed. Here I define the names of the
     variables. Note that the variables defining the dimensionality of
     the LWPR must come first since we need them to allocate other 
     variables */

  i=0; 

  /* this block has all variables needed to create a LWPR */

  sprintf(vnames[++i],"n_in_w");
  sprintf(vnames[++i],"n_in_reg");
  sprintf(vnames[++i],"n_out");
  sprintf(vnames[++i],"lwpr_name");
  sprintf(vnames[++i],"n_in_reg_2nd");
  sprintf(vnames[++i],"n_out_2nd");

  /* this block specifies all variables needed to get the data
     for training and testing, as well as some other parameters */

  sprintf(vnames[++i],"sampling_method");
  sprintf(vnames[++i],"index_function");
  sprintf(vnames[++i],"max_iterations");
  sprintf(vnames[++i],"eval_time");
  sprintf(vnames[++i],"cutoff");
  sprintf(vnames[++i],"blending");

  sprintf(vnames[++i],"file_name_train_data");
  sprintf(vnames[++i],"file_name_test_data");

  sprintf(vnames[++i],"name_train_in_w_columns");
  sprintf(vnames[++i],"name_train_in_reg_columns");
  sprintf(vnames[++i],"name_train_out_columns");
  sprintf(vnames[++i],"name_test_in_w_columns");
  sprintf(vnames[++i],"name_test_in_reg_columns");
  sprintf(vnames[++i],"name_test_out_columns");
  sprintf(vnames[++i],"name_train_in_reg_2nd_columns");
  sprintf(vnames[++i],"name_train_out_2nd_columns");
  sprintf(vnames[++i],"name_test_in_reg_2nd_columns");
  sprintf(vnames[++i],"name_test_out_2nd_columns");


  out = fopen("lwpr_test_varnames","w");
  for (j=1; j<=i; ++j) 
    fprintf(out,"%s\n",vnames[j]);
  fclose(out);
  remove_temp_file();

  /* parse keywords */
  i = 0;

  if (!find_keyword(in,vnames[++i])) {
    printf("Could not find variable >%s<\n",vnames[i]);
    exit(-i);
  }
  rc=fscanf(in,"%d",&n_in_w);

  if (!find_keyword(in,vnames[++i])) {
    printf("Could not find variable >%s<\n",vnames[i]);
    exit(-i);
  }
  rc=fscanf(in,"%d",&n_in_reg);

  if (!find_keyword(in,vnames[++i])) {
    printf("Could not find variable >%s<\n",vnames[i]);
    exit(-i);
  }
  rc=fscanf(in,"%d",&n_out);

  if (!find_keyword(in,vnames[++i])) {
    printf("Could not find variable >%s<\n",vnames[i]);
    exit(-i);
  }
  rc=fscanf(in,"%s",lwpr_name);

  if (!find_keyword(in,vnames[++i])) {
      if (lwprs[LWPR1].use_reg_2nd) {
	printf("Could not find variable >%s<\n",vnames[i]);
	exit(-i);
      }
  } else {
    rc=fscanf(in,"%d",&n_in_reg_2nd);
  }
    
  if (!find_keyword(in,vnames[++i])) {
    if (lwprs[LWPR1].use_reg_2nd) {
      printf("Could not find variable >%s<\n",vnames[i]);
      exit(-i);
    }
  } else {
    rc=fscanf(in,"%d",&n_out_2nd);
  }

  /* at last the parameters need to steer the training and testing of
     the LWPR */
  if (!find_keyword(in,vnames[++i])) {
    printf("Could not find variable >%s<\n",vnames[i]);
    exit(-i);
  }
  rc=fscanf(in,"%d",&sampling_method);

  if (!find_keyword(in,vnames[++i])) {
    printf("Could not find variable >%s<\n",vnames[i]);
    exit(-i);
  }
  rc=fscanf(in,"%d",&index_function);

  if (!find_keyword(in,vnames[++i])) {
    printf("Could not find variable >%s<\n",vnames[i]);
    exit(-i);
  }
  rc=fscanf(in,"%ld",&max_iterations);

  if (!find_keyword(in,vnames[++i])) {
    printf("Could not find variable >%s<\n",vnames[i]);
    exit(-i);
  }
  rc=fscanf(in,"%ld",&eval_time);

  if (find_keyword(in,vnames[++i])) {
    rc=fscanf(in,"%lf",&cutoff);
  }

  if (find_keyword(in,vnames[++i])) {
    rc=fscanf(in,"%d",&blending);
  }

  if (!find_keyword(in,vnames[++i]) && argc_global <= 2) {
    printf("Could not find variable >%s<\n",vnames[i]);
    exit(-i);
  }
  if (argc_global > 2) {
    strcpy(fname_train_data,argv_global[3]);
  } else {
    rc=fscanf(in,"%s",fname_train_data);
  }

  if (!find_keyword(in,vnames[++i]) && argc_global <= 3) {
    printf("Could not find variable >%s<\n",vnames[i]);
    exit(-i);
  }
  if (argc_global > 3) {
    strcpy(fname_test_data,argv_global[4]);
  } else {
    rc=fscanf(in,"%s",fname_test_data);
  }


  // at this point the data files can be read -- they are expected to be in
  // MRDPLOT format

  printf("Reading training data from >%s<...",fname_train_data);
  if (!mrdplot_convert(fname_train_data, &D_train, &vnames_train, &units_train, 
		       &freq_train, &n_cols_train, &n_rows_train)) {
    printf("Problems reading MRDPLOT file >%s<\n",fname_train_data);
    exit(-999);
  }
  printf("done\n");
  printf("%d rows with %d columns read\n",n_rows_train,n_cols_train);

  printf("Reading test data from >%s<...",fname_test_data);
  if (!mrdplot_convert(fname_test_data, &D_test, &vnames_test, &units_test, 
		       &freq_test, &n_cols_test, &n_rows_test)) {
    printf("Problems reading MRDPLOT file >%s<\n",fname_test_data);
    exit(-999);
  }
  printf("done\n");
  printf("%d rows with %d columns read\n",n_rows_test,n_cols_test);


  // allocate memory for all arrays
  Xw_train       = my_matrix(1,n_rows_train,1,n_in_w);      
  Xreg_train     = my_matrix(1,n_rows_train,1,n_in_reg);
  Xreg_train_2nd = my_matrix(1,n_rows_train,1,n_in_reg_2nd);
  Xw_test        = my_matrix(1,n_rows_test,1,n_in_w);
  Xreg_test      = my_matrix(1,n_rows_test,1,n_in_reg);
  Xreg_test_2nd  = my_matrix(1,n_rows_test,1,n_in_reg_2nd);
  Y_train        = my_matrix(1,n_rows_train,1,n_out);
  Y_train_2nd    = my_matrix(1,n_rows_train,1,n_out_2nd);
  Y_test         = my_matrix(1,n_rows_test,1,n_out);
  Y_test_2nd     = my_matrix(1,n_rows_test,1,n_out_2nd);
  x_w            = my_vector(1,n_in_w);
  x_reg          = my_vector(1,n_in_reg);
  x_reg_2nd      = my_vector(1,n_in_reg_2nd);
  y              = my_vector(1,n_out);
  y_2nd          = my_vector(1,n_out_2nd);
  conf           = my_vector(1,n_out);
  conf_2nd       = my_vector(1,n_out_2nd);
  var_y          = my_vector(1,n_out);
  var_y_2nd      = my_vector(1,n_out_2nd);
  mean_y         = my_vector(1,n_out);
  mean_y_2nd     = my_vector(1,n_out_2nd);

  // sort the test and training data into the appropriate arrays

  if (!find_keyword(in,vnames[++i])) {
    printf("Could not find variable >%s<\n",vnames[i]);
    exit(-i);
  }
  for (j=1; j<=n_in_w; ++j) {
    rc=fscanf(in,"%s",string);
    if (!(k=findIndex(string,vnames_train,n_cols_train))) {
      printf("Couldn't find column >%s< in training data\n",string);
      exit(-i);
    } else {
      for (m=1; m<=n_rows_train; ++m)
	Xw_train[m][j] = D_train[m][k];
    }
  }

  if (!find_keyword(in,vnames[++i])) {
    printf("Could not find variable >%s<\n",vnames[i]);
    exit(-i);
  }
  for (j=1; j<=n_in_reg; ++j) {
    rc=fscanf(in,"%s",string);
    if (!(k=findIndex(string,vnames_train,n_cols_train))) {
      printf("Couldn't find column >%s< in training data\n",string);
      exit(-i);
    } else {
      for (m=1; m<=n_rows_train; ++m)
	Xreg_train[m][j] = D_train[m][k];
    }
  }
  
  if (!find_keyword(in,vnames[++i])) {
    printf("Could not find variable >%s<\n",vnames[i]);
    exit(-i);
  }
  for (j=1; j<=n_out; ++j) {
    rc=fscanf(in,"%s",string);
    if (!(k=findIndex(string,vnames_train,n_cols_train))) {
      printf("Couldn't find column >%s< in training data\n",string);
      exit(-i);
    } else {
      for (m=1; m<=n_rows_train; ++m)
	Y_train[m][j] = D_train[m][k];
    }
  }
  

  if (!find_keyword(in,vnames[++i])) {
    printf("Could not find variable >%s<\n",vnames[i]);
    exit(-i);
  }
  for (j=1; j<=n_in_w; ++j) {
    rc=fscanf(in,"%s",string);
    if (!(k=findIndex(string,vnames_test,n_cols_test))) {
      printf("Couldn't find column >%s< in test data\n",string);
      exit(-i);
    } else {
      for (m=1; m<=n_rows_test; ++m)
	Xw_test[m][j] = D_test[m][k];
    }
  }

  if (!find_keyword(in,vnames[++i])) {
    printf("Could not find variable >%s<\n",vnames[i]);
    exit(-i);
  }
  for (j=1; j<=n_in_reg; ++j) {
    rc=fscanf(in,"%s",string);
    if (!(k=findIndex(string,vnames_test,n_cols_test))) {
      printf("Couldn't find column >%s< in test data\n",string);
      exit(-i);
    } else {
      for (m=1; m<=n_rows_test; ++m)
	Xreg_test[m][j] = D_test[m][k];
    }
  }
  
  if (!find_keyword(in,vnames[++i])) {
    printf("Could not find variable >%s<\n",vnames[i]);
    exit(-i);
  }
  for (j=1; j<=n_out; ++j) {
    rc=fscanf(in,"%s",string);
    if (!(k=findIndex(string,vnames_test,n_cols_test))) {
      printf("Couldn't find column >%s< in test data\n",string);
      exit(-i);
    } else {
      for (m=1; m<=n_rows_test; ++m)
	Y_test[m][j] = D_test[m][k];
    }
  }
  

  if (lwprs[LWPR1].use_reg_2nd) {

    if (!find_keyword(in,vnames[++i])) {
    printf("Could not find variable >%s<\n",vnames[i]);
    exit(-i);
  }
    for (j=1; j<=n_in_reg_2nd; ++j) {
      rc=fscanf(in,"%s",string);
      if (!(k=findIndex(string,vnames_train,n_cols_train))) {
	printf("Couldn't find column >%s< in training data\n",string);
	exit(-i);
      } else {
	for (m=1; m<=n_rows_train; ++m)
	  Xreg_train_2nd[m][j] = D_train[m][k];
      }
    }
    
    if (!find_keyword(in,vnames[++i])) {
    printf("Could not find variable >%s<\n",vnames[i]);
    exit(-i);
  }
    for (j=1; j<=n_out_2nd; ++j) {
      rc=fscanf(in,"%s",string);
      if (!(k=findIndex(string,vnames_train,n_cols_train))) {
	printf("Couldn't find column >%s< in training data\n",string);
	exit(-i);
      } else {
	for (m=1; m<=n_rows_train; ++m)
	  Y_train_2nd[m][j] = D_train[m][k];
      }
    }
    
    if (!find_keyword(in,vnames[++i])) {
    printf("Could not find variable >%s<\n",vnames[i]);
    exit(-i);
  }
    for (j=1; j<=n_in_reg_2nd; ++j) {
      rc=fscanf(in,"%s",string);
      if (!(k=findIndex(string,vnames_test,n_cols_test))) {
	printf("Couldn't find column >%s< in test data\n",string);
      exit(-i);
      } else {
	for (m=1; m<=n_rows_test; ++m)
	  Xreg_test_2nd[m][j] = D_test[m][k];
      }
    }
    
    if (!find_keyword(in,vnames[++i])) {
    printf("Could not find variable >%s<\n",vnames[i]);
    exit(-i);
  }
    for (j=1; j<=n_out_2nd; ++j) {
      rc=fscanf(in,"%s",string);
      if (!(k=findIndex(string,vnames_test,n_cols_test))) {
	printf("Couldn't find column >%s< in test data\n",string);
	exit(-i);
      } else {
	for (m=1; m<=n_rows_test; ++m)
	  Y_test_2nd[m][j] = D_test[m][k];
      }
    }

  }

  fclose(in);

  n_train_data = n_rows_train;
  n_test_data  = n_rows_test;


  if (NORMALIZE_BY_TRAIN) {

    for (i=1; i<=n_train_data; ++i) {
      vec_add_size(mean_y,Y_train[i],n_out,mean_y);
    }
    vec_mult_scalar(mean_y,1./(double)n_train_data,mean_y);

    for (i=1; i<=n_train_data; ++i) {
      for (j=1; j<=n_out; ++j) {
	var_y[j] += sqr(Y_train[i][j]-mean_y[j]);
      }
    }
    vec_mult_scalar(var_y,1./(double)n_train_data,var_y);

    if (lwprs[LWPR1].use_reg_2nd) {

      for (i=1; i<=n_train_data; ++i) {
	vec_add_size(mean_y_2nd,Y_train_2nd[i],n_out,mean_y_2nd);
      }
      vec_mult_scalar(mean_y_2nd,1./(double)n_train_data,mean_y_2nd);
      
      for (i=1; i<=n_train_data; ++i) {
	for (j=1; j<=n_out_2nd; ++j) {
	  var_y_2nd[j] += sqr(Y_train_2nd[i][j]-mean_y_2nd[j]);
	}
      }
      vec_mult_scalar(var_y_2nd,1./(double)n_train_data,var_y_2nd);

    }

  } else {

    for (i=1; i<=n_test_data; ++i) {
      vec_add_size(mean_y,Y_test[i],n_out,mean_y);
    }
    vec_mult_scalar(mean_y,1./(double)n_test_data,mean_y);

    for (i=1; i<=n_test_data; ++i) {
      for (j=1; j<=n_out; ++j) {
	var_y[j] += sqr(Y_test[i][j]-mean_y[j]);
      }
    }
    vec_mult_scalar(var_y,1./(double)n_test_data,var_y);

    if (lwprs[LWPR1].use_reg_2nd) {

      for (i=1; i<=n_test_data; ++i) {
	vec_add_size(mean_y_2nd,Y_test_2nd[i],n_out,mean_y_2nd);
      }
      vec_mult_scalar(mean_y_2nd,1./(double)n_test_data,mean_y_2nd);
      
      for (i=1; i<=n_train_data; ++i) {
	for (j=1; j<=n_out_2nd; ++j) {
	  var_y_2nd[j] += sqr(Y_test_2nd[i][j]-mean_y_2nd[j]);
	}
      }
      vec_mult_scalar(var_y_2nd,1./(double)n_train_data,var_y_2nd);

    }
  }

  
}
Beispiel #17
0
/*
 * main
 */
int main(int argc, char **argv)
{
  int configfile;
  int nlines, i, keyword;
  char *configfilename, *configbuffer, *p, **lines;
  int interval = 10;
  int dev_mismatch = 0;
  
  struct stat statbuf;

  /* Read configuration file. */
  if(argc > 1)
    configfilename = argv[1];
  else
    configfilename = "/etc/fancontrol";

  configfile = open(configfilename, O_RDONLY);
  if(configfile < 0)
    {
      perror(configfilename);
      return 1;
    }
  if(fstat(configfile, &statbuf) < 0)
    {
      perror(configfilename);
      close(configfile);
      return 1;
    }
  if(statbuf.st_size <= 0)
    {
      fprintf(stderr, "Configuration file %s is empty.\n", configfilename);
      close(configfile);
      return 1;
    }
  configbuffer = (char*) malloc(statbuf.st_size + 1);
  if(configbuffer == NULL)
    {
      fprintf(stderr, "Insufficient memory.\n");
      close(configfile);
      return 0;
    }
  if(read_whole_persist(configfile, configbuffer, statbuf.st_size) != statbuf.st_size)
    {
      fprintf(stderr,  "Can't read the configuration file %s.\n",
	      configfilename);
      close(configfile);
      return 1;
    }
  configbuffer[statbuf.st_size] = '\0';
  close(configfile);

  /* Parse configuration. */
  p = configbuffer;
  nlines = 1;
  while(*p)
    if(*p++ == '\n')
      nlines++;
  
  lines = (char**) malloc(nlines * sizeof(char*));
  if(lines == NULL)
    {
      fprintf(stderr, "Insufficient memory.\n");
      free(configbuffer);
      return 1;
    }

  for(p = configbuffer, i = 0; i < nlines ; i++)
    {
      lines[i] = p;
      p = strchr(p, '\n');
      if(p != NULL)
	*p++ = '\0';
    }

  /* Parse lines, create descriptors. */
  for(i = 0; i < nlines; i++)
    {
      p = strchr(lines[i], '#');
      if(p != NULL)
	*p = '\0';
      p = strchr(lines[i], '=');
      if(p != NULL)
	{
	  *p = '\0';
	  p++;
	  keyword = find_keyword(lines[i]);
	  switch(keyword)
	    {
	    case INTERVAL:
	      if((sscanf(p, "%i", &interval) != 1)
		 || (interval < 1)
		 || (interval > 100))
		interval = 10;
	      break;
	    case DEVPATH:
	      dev_mismatch |= check_devpaths(p);
	      break;
	    case DEVNAME:
	      dev_mismatch |= check_devnames(p);
	      break;
	    case FCTEMPS:
	      configure_fctemps(p);
	      break;
	    case FCFANS:
	      configure_fcfans(p);
	      break;
	    case MINTEMP:
	    case MAXTEMP:
		configure_common_param(p, keyword);
	      break;
	    case MINSTART:
	    case MINSTOP:
	    case MINPWM:
	    case MAXPWM:
	      configure_fan_control_param(p, keyword);
	      break;
	    }
	}
    }

  if(dev_mismatch)
    {
      fprintf(stderr, "Devices do not match saved paths and names, exiting.\n");
      return 1;
    }

  /*
    Do not try to run if configuration does not contain
    at least one sensor and at least one control.
  */
  if((temp_sensors_head == NULL) || (fan_controls_head == NULL))
    {
      fprintf(stderr, "No devices defined, exiting.\n");
      return 1;
    }

  /* Set handler for restoring the fans uncontrolled state */
  struct sigaction act;

  memset(&act, 0, sizeof(act));
  act.sa_handler = sighandler;

  sigaction(SIGTERM, &act, NULL);
  sigaction(SIGINT, &act, NULL);
  sigaction(SIGQUIT, &act, NULL);

  /* Enable fan control */
  struct fan_control *current_control;
  current_control = fan_controls_head;
  while(current_control)
    {
      fan_enable(current_control->address, 1);
      current_control = current_control->next;
    }

  /* Main loop. */
  while(running)
    {
      /* Read all temperatures. */
      struct temp_sensor *current_temp_sensor;
      current_temp_sensor = temp_sensors_head;
      while(current_temp_sensor)
	{
	  read_temperature(current_temp_sensor);
	  current_temp_sensor = current_temp_sensor->next;
	}
      
      /* Read all fan speeds */
      struct fan_sensor *current_fan_sensor;
      current_fan_sensor = fan_sensors_head;
      while(current_fan_sensor)
	{
	  read_fan_speed(current_fan_sensor);
	  current_fan_sensor = current_fan_sensor->next;
	}

      /* 
	 Read current PWM value for controls,
	 determine and set new PWM values.
      */
      current_control = fan_controls_head;
      while(current_control)
	{
	  int min_fan_speed, new_pwm;
	  read_fan_pwm(current_control);
	  min_fan_speed = get_min_fan_speed(current_control);
	  new_pwm = get_max_pwm_by_temperature(current_control);

	  /* Check if we are starting a stopped fan */
	  if((new_pwm > current_control->minpwm)
	    && ((min_fan_speed == 0) 
		|| (current_control->value <= current_control->minpwm)))
	    new_pwm = current_control->minstart;

	  /* Set new PWM if it changed */
	  if(new_pwm != current_control->value)
	    set_fan_pwm(current_control, new_pwm);
	  current_control = current_control->next;
	}
      sleep(interval);
    }

  /* Restore fans */
  restore_fans();
  return 0;
}
/* A malha deve estar alocada.
 * */
void MeshIoMsh::readFileMsh(const char* filename, Mesh * mesh)
{
    /*
     * O que é feito:
     *
     * 1) primeiramente lê-se apenas as células (conectividade clássica);
     * 2) depois são construídos as facet-edges e(ou) facet-faces, lendo-se
     *    os elementos de dimensões menores.
     *
     * */

    FEPIC_ASSERT(mesh, "invalid mesh pointer", std::invalid_argument);


    this->fi_registerFile(filename, ".msh");

    FILE * file_ptr = fopen(filename, "r");

    double  coord[3];
    int     type_tag;
    char    buffer[256];
    std::tr1::shared_ptr<Point> p_ptr(new Point());
    std::tr1::shared_ptr<Cell> c_ptr(mesh->createCell());

    int const spacedim = mesh->spaceDim();
    FEPIC_ASSERT(spacedim>0 && spacedim < 4, "mesh has invalid spacedim", std::invalid_argument);

    long    nodes_file_pos;  // $Nodes
    long    elems_file_pos;  // $Elements

    // nós
    nodes_file_pos = find_keyword("$Nodes", 6, file_ptr);
    //nodes_file_pos++;  // only to avoid gcc warning: variable ‘nodes_file_pos’ set but not used [-Wunused-but-set-variable]

    FEPIC_ASSERT(nodes_file_pos>0, "invalid file format", std::invalid_argument);

    int num_pts(0);
    int node_number(0);
    if ( EOF == fscanf(file_ptr, "%d", &num_pts) )
        FEPIC_ASSERT(false, "invalid msh format", std::runtime_error);

    //mesh->resizePointL(num_pts);

    //mesh->printInfo();
    //std::cout << "DEBUGGGGGGGGGGGGGGGGGGG:  "<<mesh << std::endl;
    //printf("DEBUGGGGGGGGGGGGGGGGGGGGGGGGGGG num_pts=%d; numNodesTotal()=%d; numNodes()=%d\n",num_pts,mesh->numNodesTotal(), mesh->numNodes());

    if (NULL == fgets(buffer, sizeof(buffer), file_ptr)) // escapa do \n
        FEPIC_ASSERT(false, "invalid msh format", std::runtime_error);
    for (int i=0; i< num_pts; ++i)
    {
        if ( NULL == fgets(buffer, sizeof(buffer), file_ptr) )
            FEPIC_ASSERT(false, "invalid msh format", std::runtime_error);
        sscanf(buffer, "%d %lf %lf %lf", &node_number, &coord[0], &coord[1], &coord[2]);
        FEPIC_ASSERT(node_number==i+1, "wrong file format", std::invalid_argument);
        p_ptr->setCoord(coord, spacedim);
        //mesh->getNodePtr(i)->setCoord(coord,spacedim);
        mesh->pushPoint(p_ptr.get());
    }
    // os pontos não estão completas: falta atribuir os labels

    // contagem de elementos e alocação

    elems_file_pos = find_keyword("$Elements", 9, file_ptr);

    FEPIC_ASSERT(elems_file_pos>0, "invalid file format", std::invalid_argument);

    int num_cells=0;
    int num_elms;

    if (EOF == fscanf(file_ptr, "%d", &num_elms) )
        FEPIC_ASSERT(false, "invalid msh format", std::runtime_error);

    /* ---------------------------------------
     * Detectando a ordem da malha, verificando sequencia dos elementos,
     * e contando o número de células.
     * --------------------------------------- */
    const int meshm_cell_msh_tag = mesh->cellMshTag();

    if (mshTag2ctype(EMshTag(meshm_cell_msh_tag)) != mesh->cellType())
    {
        //FEPIC_ASSERT(false, "invalid msh format", std::runtime_error);
        printf("ERROR: ctype2mshTag() = %d\n", ctype2mshTag(mesh->cellType()));
        printf("ERROR: cell->getMshTag() = %d\n", c_ptr->getMshTag());
        throw;
    }


    bool wrong_file_err=true;
    int  elem_number;               // contagem para verificação de erros.
    for (int k = 0; k < num_elms; ++k)
    {

        if (EOF == fscanf(file_ptr, "%d %d", &elem_number, &type_tag) )
            FEPIC_ASSERT(false, "invalid msh format", std::runtime_error);

        // check sequence
        if (elem_number != k+1)
        {
            wrong_file_err=true;
            break;
        }

        // check type
        if (type_tag == meshm_cell_msh_tag)
        {
            wrong_file_err=false;
            ++num_cells;
        }

        if (!fgets(buffer, sizeof(buffer), file_ptr) || feof(file_ptr))
        {
            wrong_file_err=true;
            break;
        }

    }
    FEPIC_ASSERT(!wrong_file_err, "Wrong file format. Make sure you created the mesh with correct file format. ", std::invalid_argument);

    Cell*  cell;
    //cell = Cell::create(mesh->cellType());



    /* --------------------------------------
     * Lendo as células
     * -------------------------------------- */
    fseek (file_ptr , elems_file_pos , SEEK_SET );
    if (EOF == fscanf(file_ptr, "%d", &num_elms) )
        FEPIC_ASSERT(false, "invalid msh format", std::runtime_error);

    this->timer.restart();

    int  inc(0);
    int  nodes_per_cell = mesh->nodesPerCell();
    int  id_aux;
    int  numm_tags;
    int  elm_dim;
    int  physical;
    int const cell_dim = mesh->cellDim();
    int const cell_msh_tag = mesh->cellMshTag();
    for (int k=0; k < num_elms; ++k)
    {
        if ( EOF == fscanf(file_ptr, "%d %d %d %d", &elem_number, &type_tag, &numm_tags, &physical) )
            FEPIC_ASSERT(false, "invalid msh format", std::runtime_error);

        // sincronização
        FEPIC_ASSERT(elem_number==k+1, "invalid file format", std::invalid_argument);

        for (int j=1; j<numm_tags; ++j)
        {
            if ( EOF == fscanf(file_ptr, "%s", buffer) )
                FEPIC_ASSERT(false, "invalid msh format", std::runtime_error);
        }

        elm_dim = dimForMshTag(EMshTag(type_tag));

        if (elm_dim==0)
        {
            if ( EOF == fscanf(file_ptr, "%d", &id_aux) )
                FEPIC_ASSERT(false, "invalid msh format", std::runtime_error);
            --id_aux;
            mesh->getNodePtr(id_aux)->setTag(physical);
        }
        else if (elm_dim == cell_dim)
        {
            cell = mesh->pushCell((int*)0);
            ++inc;
            FEPIC_ASSERT(cell_msh_tag == type_tag, "Invalid cell or invalid mesh", std::runtime_error);
            for (int i=0; i< nodes_per_cell; ++i)
            {
                if ( EOF == fscanf(file_ptr, "%d", &id_aux) )
                    FEPIC_ASSERT(false, "invalid msh format", std::runtime_error);
                cell->setNodeId(i, id_aux-1);
            }
            cell->setTag(physical);
            //mesh->pushCell(cell);
        }
        else
        {
            if ( NULL == fgets(buffer, sizeof(buffer), file_ptr) )
                FEPIC_ASSERT(false, "invalid msh format", std::runtime_error);
        }
    }// end for k


    this->timer.elapsed("readFileMsh(): read connectivity");
    // até aqui, apenas foi lido a conectividade
    //

    /* constroi as facets e Corners */
    if (mesh->qBuildAdjacency())
        mesh->buildAdjacency();
    else
    {
        fclose(file_ptr);
        return;
    }

    /*
    ___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|__
    _|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| */

    this->timer.restart();
    /* Procura por elementos no contorno que coincidam com as facets. Quando encontrados,
     * os labels são propagados para as respectivas facet que por sua vez propagam os
     * labels para seus nós. Os labels só são propagados se eles não foram definidos
     * nos nós anteriormente.
     */
    fseek (file_ptr , elems_file_pos , SEEK_SET );
    fscanf(file_ptr, "%d", &num_elms);

    int n_nodes               = mesh->nodesPerCell();
    //int n_vertices_per_facet  = mesh->verticesPerFacet();
    int n_nodes_per_facet     = mesh->nodesPerFacet();
    //int n_vertices_per_corner = mesh->verticesPerCorner();
    int n_nodes_per_corner    = mesh->nodesPerCorner();


    int* nodes  = new int[n_nodes_per_facet];      // facet nodes
    //int* vtcs   = new int[n_vertices_per_facet];
    int* bnodes = new int[n_nodes_per_corner];     // corner nodes
    //int* bvtcs  = new int[n_vertices_per_corner];
    int facet_id;
    int corner_id;

    for (int k=0; k < num_elms; ++k)
    {

        fscanf(file_ptr, "%d %d %d %d", &elem_number, &type_tag, &numm_tags, &physical);

        //// sincronização
        //FEPIC_ASSERT(elem_number==k+1, "invalid file format", std::invalid_argument);

        for (int j=1; j<numm_tags; ++j)
        {
            fscanf(file_ptr, "%s", buffer);
        }

        elm_dim = dimForMshTag(EMshTag(type_tag));

        if ((elm_dim == 0) && (cell_dim!=2))
        {
            fscanf(file_ptr, "%d", &id_aux);
        }
        else if (elm_dim == cell_dim-1) // facets
        {
            for (int i=0; i<n_nodes_per_facet; ++i)
            {
                fscanf(file_ptr, "%d", &nodes[i]);
                --nodes[i];
                if (mesh->getNodePtr(nodes[i])->getTag() == 0)
                    mesh->getNodePtr(nodes[i])->setTag(physical);
            }
            //std::copy( nodes, nodes + n_vertices_per_facet, vtcs );
            if (cell_dim > 1)
            {
                if (mesh->getFacetIdFromVertices(nodes, facet_id))
                    mesh->getFacetPtr(abs(facet_id))->setTag(physical); //std::cout << (++TESTE) << std::endl;
                else
                {
                    printf("WARNING: INVALID FACET IN INPUT MESH! vtcs: ");
                    for (int zz = 0; zz < n_nodes_per_facet; ++zz)
                        printf("%d ", nodes[zz]);
                    printf("\n");
                }
            }
        }
        else if (elm_dim == cell_dim-2) // corners
        {
            for (int i=0; i<n_nodes_per_corner; ++i)
            {
                fscanf(file_ptr, "%d", &bnodes[i]);
                --bnodes[i];
                if (mesh->getNodePtr(bnodes[i])->getTag() == 0)
                    mesh->getNodePtr(bnodes[i])->setTag(physical);
            }
            //std::copy( bnodes, bnodes + n_vertices_per_corner, bvtcs );
            if (cell_dim>2)
            {
                if (mesh->getCornerIdFromVertices(bnodes, corner_id))
                {
                    mesh->getCornerPtr(abs(corner_id))->setTag(physical); //std::cout << (++TESTE) << std::endl;
                }
                else if (mesh->isVertex(mesh->getNodePtr(bnodes[0])) ) // if is vertex
                    printf("WARNING: INVALID CORNER IN INPUT MESH!\n");
            }
        }
        else
        {
            for (int i=0; i<n_nodes; ++i)
            {
                fscanf(file_ptr, "%d", &id_aux);
                --id_aux;

                if ((mesh->getNodePtr(id_aux)->getTag()) == 0)
                    mesh->getNodePtr(id_aux)->setTag(physical);
            }
        }


    }

    this->timer.elapsed("readFileMsh(): search for boundary elements");

    if (mesh->cellDim()>2)
    {
        const int n_corners_per_facet = mesh->numCornersPerFacet();
        // int facetm_facets[n_corners_per_facet];
        int *facetm_facets = new int [n_corners_per_facet];
        Facet const* facet;
        Corner* corner;
        for (int i = 0; i < mesh->numFacetsTotal(); ++i)
        {
            facet = mesh->getFacetPtr(i);
            if (facet->isDisabled())
                continue;
            mesh->getCellPtr(facet->getIncidCell())->getFacetCornersId(facet->getPosition(), facetm_facets);

            for (int j = 0; j < n_corners_per_facet; ++j)
            {
                corner = mesh->getCornerPtr(facetm_facets[j]);
                if (corner->getTag() == 0)
                    corner->setTag(facet->getTag());
            }
        }

        delete [] facetm_facets;
        facetm_facets = NULL;
    }

    if (mesh->cellDim()>1)
    {
        const int n_cells_total = mesh->numCellsTotal();
        Cell * cell;
        Facet * facet;
        for (int i = 0; i < n_cells_total; ++i)
        {
            cell = mesh->getCellPtr(i);
            if (cell->isDisabled())
                continue;
            for (int j = 0; j < mesh->numFacetsPerCell(); ++j)
            {
                facet = mesh->getFacetPtr(cell->getFacetId(j));

                if (facet->getTag() == 0)
                    facet->setTag(cell->getTag());
            }
        } // end loop
    } // endif

    fclose(file_ptr);
    //File.close();

    delete [] nodes;
    //delete [] vtcs;
    delete [] bnodes;
    //delete [] bvtcs;

    mesh->timer.addItems(this->timer);
}
ECellType MeshIoMsh::identifiesMshMeshType(const char* filename, int &space_dim) const
{
    /*
     * O que é feito:
     *
     * 1) primeiramente lê-se apenas as células (conectividade clássica);
     * 2) depois são construídos as facet-edges e(ou) facet-faces, lendo-se
     *    os elementos de dimensões menores.
     *
     * */

    FILE * file_ptr = fopen(filename, "r");

    FEPIC_ASSERT(file_ptr, "can not find mesh file", std::invalid_argument);

    double  coord[3];
    int     type_tag;
    char    buffer[256];

    long    nodes_file_pos;  // $Nodes
    long    elems_file_pos;  // $Elements

    // nós
    nodes_file_pos = find_keyword("$Nodes", 6, file_ptr);
    //nodes_file_pos++;  // only to avoid gcc warning: variable ‘nodes_file_pos’ set but not used [-Wunused-but-set-variable]

    FEPIC_ASSERT(nodes_file_pos>0, "invalid file format", std::invalid_argument);

    space_dim = 1;

    int num_pts(0);
    int node_number(0);
    fscanf(file_ptr, "%d", &num_pts);

    fgets(buffer, sizeof(buffer), file_ptr); // escapa do \n
    for (int i=0; i< num_pts; ++i)
    {
        fgets(buffer, sizeof(buffer), file_ptr);
        sscanf(buffer, "%d %lf %lf %lf", &node_number, &coord[0], &coord[1], &coord[2]);
        FEPIC_ASSERT(node_number==i+1, "wrong file format", std::invalid_argument);
        if (coord[1] != 0)
            space_dim = 2;
        if (coord[2] != 0)
        {
            space_dim = 3;
            break;
        }
    }

    // contagem de elementos e alocação
    elems_file_pos = find_keyword("$Elements", 9, file_ptr);

    FEPIC_ASSERT(elems_file_pos>0, "invalid file format", std::invalid_argument);

//  int num_cells=0;
    int num_elms;

    fscanf(file_ptr, "%d", &num_elms);

    /* ---------------------------------------
     * Detectando a ordem da malha, verificando sequencia dos elementos,
     * e contando o número de células.
     * --------------------------------------- */
//  bool wrong_file_err=true;
    int  elem_number, elm_dim, numm_tags, physical;
    int current_elm_dim = 0;
    ECellType current_elm_type = UNDEFINED_CELLT;
    fgets(buffer, sizeof(buffer), file_ptr); // escapa do \n
    for (int k=0; k < num_elms; ++k)
    {

        fscanf(file_ptr, "%d %d %d %d", &elem_number, &type_tag, &numm_tags, &physical);

        //// sincronização
        FEPIC_ASSERT(elem_number==k+1, "invalid file format", std::invalid_argument);

        for (int j=1; j<numm_tags; ++j)
        {
            fscanf(file_ptr, "%s", buffer);
        }

        elm_dim = dimForMshTag(EMshTag(type_tag));

        if(elm_dim > current_elm_dim)
        {
            current_elm_type = mshTag2ctype(EMshTag(type_tag));
            current_elm_dim = elm_dim;
            if (elm_dim==3)
                break;
        }

        fgets(buffer, sizeof(buffer), file_ptr);

    }

    fclose(file_ptr);

    return current_elm_type;

}
Beispiel #20
0
void	parse_config(FILE *fptr)
{
	char 			*line;
	unsigned char	keywords_found;
	
	
	line=(char *)xmalloc(512);
	keywords_found=0;
	
	while (!feof(fptr))
	{
		fgets(line, 512, fptr);
		
		if (isalnum(line[0]))
		{
			switch(find_keyword(line))
			{
				case	-1:	fprintf(stderr, "\nPARSE_CONFIG: unknown option: %s\n", line);
							break;
							
				case	0:	boot_filename=parse_filename(line);
							printf("    Boot image:                      %s\n", boot_filename);
							keywords_found++;
							break;
						
				case	1:	loader_filename=parse_filename(line);
							printf("    Kernel loader image:             %s\n", loader_filename);			
							keywords_found++;
							break;

				case	2:	kernel_filename=parse_filename(line);
							printf("    Kernel image:                    %s\n", kernel_filename);			
							keywords_found++;
							break;
						
				case	3:	output_filename=parse_filename(line);
							printf("    Output image:                    %s\n", output_filename);
							keywords_found++;
							break;

				case	4:	output_sectors=parse_ulong(line);
							printf("    Output sectors:                  %lu\n", output_sectors);
							keywords_found++;
							break;

						
//				case	5:	boot_setup.heads=parse_int(line);
//							printf("    Number of heads:                 %d\n", boot_setup.heads);
//							keywords_found++;
//							break;
						
//				case	6:	boot_setup.sectors=parse_int(line);
//							printf("    Sectors per track:               %d\n", boot_setup.sectors);
//							keywords_found++;
//							break;
						
				case	7:	boot_setup.bytes_per_sector=parse_ulong(line);
							printf("    Bytes per sector:                %d\n", boot_setup.bytes_per_sector);
							keywords_found++;
							break;	
						
				default:	fprintf(stderr, "\nPARSE_CONFIG: unknown option: %s", line);
							break;
			}	
		}
	}
	

	free(line);	
	printf("\n");
	if (keywords_found!=keywords)
	{
		fprintf(stderr, "\nPARSE_CONFIG: missing options in boot.cfg\n");
		die();
	}		
}
Beispiel #21
0
 * get next token 
 */
static uint8_t get_token( void )
{
    const struct keyword *keyword;
    char *lex = argv[curtok];
    uint8_t class;

    token.lex = lex;
    if( curtok >= argc )
    {
	token.class = C_EOL;
	return C_EOL;
    }
    curtok++;
    keyword = find_keyword( lex );
    if( keyword )
	memcpy_P( &class, &keyword->class, sizeof(class) );
    else if( lex[0] == '-' || isdigit(lex[0]) )
    {
	token.val = strtol( lex, 0, 10 ); 
        class = C_NUM;
    }
    else
	class = C_BAD;
    token.class = class;
    return( class );
}

static void expect_token( uint8_t class, const char *what )
{