Beispiel #1
0
void PA::MarkAsTodo(unsigned mark) {
    if (_listlink.empty()) {
        warning_message("The list has not listed or it's invalid.");
        my_pause();
        return;
    }

    map_iterator it = _listlink.find(mark);
    if (it == _listlink.end()) {
        warning_message("The number doesn't exist in the list.");
        my_pause();
        return;
    }
    (*(it->second))->mark_todo();
}
Beispiel #2
0
void PA::Delete(unsigned mark) {
    if (_listlink.empty()) {
        warning_message("The list has not listed or it's invalid.");
        my_pause();
        return;
    }

    map_iterator it = _listlink.find(mark);
    if (it == _listlink.end()) {
        warning_message("The number doesn't exist in the list.");
        my_pause();
        return;
    }
    delete *(it->second);
    _affair.erase(it->second);
    _listlink.erase(it);
}
Beispiel #3
0
/*-------------------------------------------------------------------------
 * (function: allocate_more_node_output_pins)
 * 	Makes more space in the node for pin connections ... 
 *-----------------------------------------------------------------------*/
void allocate_more_output_pins(nnode_t *node, int width)
{
	int i;

	if (width <= 0)
	{
		warning_message(NETLIST_ERROR, -1, -1, "tried adding output pins for with <= 0 %s\n", node->name);
		return;
	}

	node->output_pins = (npin_t**)realloc(node->output_pins, sizeof(npin_t*)*(node->num_output_pins+width));
	for (i = 0; i < width; i++)
	{
		node->output_pins[node->num_output_pins+i] = NULL;
	}
	node->num_output_pins += width;
}
Beispiel #4
0
/*---------------------------------------------------------------------------
 * (function: hookup_hb_input_pins_from_signal_list)
 *   For each pin in this list hook it up to the inputs according to 
 *   indexes and width. Extra pins are tied to PAD for later resolution.
 *--------------------------------------------------------------------------*/
void hookup_hb_input_pins_from_signal_list(nnode_t *node, int n_start_idx, signal_list_t* input_list, int il_start_idx, int width, netlist_t *netlist) 
{
	int i;

	for (i = 0; i < width; i++)
	{
		if (il_start_idx+i < input_list->count)
		{
			oassert(input_list->count > (il_start_idx+i));
			add_input_pin_to_node(node, input_list->pins[il_start_idx+i], n_start_idx+i);
		}
		else
		{
			/* connect with "pad" signal for later resolution */
			add_input_pin_to_node(node, get_pad_pin(netlist), n_start_idx+i);

			if (global_args.all_warnings)
				warning_message(NETLIST_ERROR, -1, -1, "padding an input port with HB_PAD for node %s\n", node->name);
		}
	}	
}
Beispiel #5
0
/**
 * timer_callback:
 * @message: message to display.
 *
 * This callback is run every minute until we are ready to shutdown, it
 * ensures regular warnings are sent to logged in users and handles
 * preventing new logins.  Once time is up, it handles shutting down.
 *
 * This will modify delay each time it is called.
 **/
static void
timer_callback (const char *message)
{
	nih_local char *msg = NULL;
	int             warn = FALSE;

	delay--;
	msg = NIH_MUST (warning_message (message));


	/* Write /etc/nologin with less than 5 minutes remaining */
	if (delay <= 5) {
		FILE *nologin;

		nologin = fopen (ETC_NOLOGIN, "w");
		if (nologin) {
			fputs (msg, nologin);
			fclose (nologin);
		}
	}

	/* Only warn at particular intervals */
	if (delay < 10) {
		warn = TRUE;
	} else if (delay < 60) {
		warn = (delay % 15 ? FALSE : TRUE);
	} else if (delay < 180) {
		warn = (delay % 30 ? FALSE : TRUE);
	} else {
		warn = (delay % 60 ? FALSE : TRUE);
	}

	if (warn)
		wall (msg);

	/* Shutdown the machine at zero */
	if (! delay)
		shutdown_now ();
}
Beispiel #6
0
/*---------------------------------------------------------------------------
 * (function: hookup_input_pins_from_signal_list)
 * 	For each pin in this list hook it up to the inputs according to indexes and width
 *--------------------------------------------------------------------------*/
void hookup_input_pins_from_signal_list(nnode_t *node, int n_start_idx, signal_list_t* input_list, int il_start_idx, int width, netlist_t *netlist) 
{
	int i;

	for (i = 0; i < width; i++)
	{
		if (il_start_idx+i < input_list->count)
		{
			oassert(input_list->count > (il_start_idx+i));
			npin_t *pin = input_list->pins[il_start_idx+i];
			add_input_pin_to_node(node, pin, n_start_idx+i);

		}
		else
		{
			/* pad with 0's */
			add_input_pin_to_node(node, get_zero_pin(netlist), n_start_idx+i);

			if (global_args.all_warnings)
				warning_message(NETLIST_ERROR, -1, -1, "padding an input port with 0 for node %s\n", node->name);
		}
	}	
}
Beispiel #7
0
bool load_files( const char **argv )
{
    std::string base_name;     // Contains the base part of a saved name.
    std::string workspace;     // Used to hold expanded abbreviations.
    bool base_valid = false;   // =true if base_name contains valid material.
    int  file_count = 0;       // Number of files loaded.
    bool First_File = true;    // =false when at least one file has been loaded.
    YEditFile *leading_file;   // Reference to the first file loaded.

    // Tell user if there's a problem.
    if( argv[1] == NULL ) {
        error_message( "You must specify at least one filename" );
        return false;
    }

    // Default value for initial position = no change.
    long line_number   = -1;
    int  column_number = -1;

    // For each parameter.
    for( argv++; *argv; argv++ ) {

        // If we're looking at a switch (accept either '-' or '/')...
        if( **argv == '-'  ||  **argv == '/' ) {
            switch( *++*argv ) {

                // Set initial line number. Note that user's line number 1 based.
            case 'l':
            case 'L':
                line_number = std::atol( ++*argv ) - 1L;
                break;

                // Set initial column number. Note that user's column number 1 based.
            case 'c':
            case 'C':
                column_number = std::atoi( ++*argv ) - 1;
                break;

            // If the user sets restricted mode anywhere on the command line, set it globally.
            // The editor is either restricted or not!
            case 'r':
            case 'R':
                restricted_mode = true;
                break;

                // Print message and wait for acknowledgment.
            default:
                warning_message( "Unrecognized switch (%c) ignored", **argv );
                break;

            } // End of switch statement which handles each switch type.
        }   // End of switch handling if...

        // Otherwise it was no switch, it must be a file name (or wildcard spec).
        else {
            FileNameMatcher wild_match;
            char *file_name;

            // If the current argument is an abbreviation, try expanding it.
            if( **argv == '.' && base_valid ) {
                workspace = base_name;
                workspace.append( *argv );
                *argv = workspace.c_str( );
            }

            // Otherwise, save the base part of the current name.
            else {
                const char *end_pointer = std::strrchr( *argv, '.' );
                if( end_pointer != NULL ) {
                    base_name.assign( *argv, end_pointer - *argv );
                    base_valid   = true;
                }
            }

            wild_match.set_name( *argv );

            // If no files match the spec, assume the spec is the name of a new file.
            if( ( file_name = wild_match.next( ) ) == NULL ) {
                if( std::strchr( *argv, '*' ) != NULL ||
                    std::strchr( *argv, '?' ) != NULL ) {
                    warning_message( "No files match %s", *argv );
                }
                else {
                    load_file( *argv, line_number, column_number );
                    file_count++;
                    if( First_File ) {
                        First_File = false;
                        leading_file = &FileList::active_file( );
                    }
                }
            }

            else {

                // Loop over all names which match the wildcard spec and load them.
                while( file_name != NULL ) {
                    load_file( file_name, line_number, column_number );
                    file_count++;
                    if( First_File ) {
                        First_File = false;
                        leading_file = &FileList::active_file( );
                    }
                    file_name = wild_match.next( );
                }
            }

        } // End of if...else... that determines if we are looking at a switch.
    }   // End of loop that passes over all command line arguments.

    if( file_count == 0 ) {
        error_message( "No files loaded" );
        return false;
    }

    FileList::lookup( leading_file->name( ) );
    return true;
}
Beispiel #8
0
/*---------------------------------------------------------------------------------------------
 * (function: get_options)
 *-------------------------------------------------------------------------*/
void get_options(int argc, char **argv)
{
	/* Set up the global arguments to their default. */
	set_default_options();
	

	/* Parse the command line options.  */
	const char *optString = "hc:V:WREh:o:a:B:b:N:f:s:S:p:g:t:T:L:H:GA3";
	int opt = getopt(argc, argv, optString);
	while(opt != -1) 
	{
		switch(opt)
		{
			/* arch file */
			case 'a':
				global_args.arch_file = optarg;
				configuration.arch_file = optarg;
			break;
			/* config file */
			case 'c':
				global_args.config_file = optarg;
			break;
			case 'V':
				global_args.verilog_file = optarg;
			break;
			case 'o':
				global_args.output_file = optarg;
			break;
			#ifdef VPR5
			case 'B':
				global_args.activation_blif_file = optarg;
			break;
			case 'N':
				global_args.activation_netlist_file = optarg;
			break;
			#endif
			case 'b':
				global_args.blif_file = optarg;
			break;
			case 'f':
				#ifdef VPR5
				global_args.high_level_block = optarg;
				#endif
				#ifdef VPR6
				warning_message(0, -1, 0, "Option -f: VPR 6.0 doesn't have this feature yet.  You'll need to deal with the output_blif.c differences wrapped by \"if (global_args.high_level_block != NULL)\"\n");
				#endif
			break;
			case 'h':
				print_usage();
				exit(-1);
			break;
			case 'g':
				global_args.sim_num_test_vectors = atoi(optarg);
			break;
			case '3':
				global_args.sim_generate_three_valued_logic = 1;
			break;
			case 'L':
				global_args.sim_hold_low = optarg;
			break;
			case 'H':
				global_args.sim_hold_high = optarg;
			break;
			case 't':
				global_args.sim_vector_input_file = optarg;
			break;
			case 'T':
				global_args.sim_vector_output_file = optarg;
			break;
			case 'p':
				global_args.sim_additional_pins = optarg;
			break;
			case 'G':
				configuration.output_netlist_graphs = 1;
			break;
			case 'A':
				configuration.output_ast_graphs = 1;
			break;
			case 'W':
				global_args.all_warnings = 1;
			break;
			case 'E':
				global_args.sim_output_both_edges = 1;
			break;
			case 'R':
				global_args.sim_output_rising_edge = 1;
			break;
			default :
				print_usage();
				error_message(-1, 0, -1, "Invalid arguments.\n");
			break;
		}
		opt = getopt(argc, argv, optString);
	}

	if (
			   !global_args.config_file
			&& !global_args.blif_file
			&& !global_args.verilog_file
			&& ((!global_args.activation_blif_file) || (!global_args.activation_netlist_file)))
	{
		print_usage();
		error_message(-1,0,-1,"Must include either "
				#ifdef VPR5
				"a activation blif and netlist file, "
				#endif
				"a config file, a blif netlist, or a verilog file\n");
	}
	else if ((global_args.config_file && global_args.verilog_file) || global_args.activation_blif_file)
	{
		warning_message(-1,0,-1, "Using command line options for verilog input file!!!\n");
	}
}
Beispiel #9
0
	std::string tracker_warning_alert::message() const
	{
		return tracker_alert::message() + " warning: " + warning_message();
	}
Beispiel #10
0
int main (
   int argc ,    // Number of command line arguments (includes prog name)
   char *argv[]  // Arguments (prog name is argv[0])
   )

{

/*
   Declarations of local variables
*/

/*
   User's command control line related variables are here.
   Control_file_number and control_files permit nesting of 'CONTROL' commands.
   If control_file_number equals -1, control commands are read from stdin.
   Otherwise they are read from that file in FILE *control_files.
   Up to MAX_CONTROL_FILES can be stacked.
*/

   int control_file_number = -1 ;           // Stack pointer for control files
   FILE *control_files[MAX_CONTROL_FILES] ; // This is the stack

   char *control_line ;    // User's commands here
   char *command, *rest ;  // Pointers to its command and parameter parts
   int n_command, n_rest ; // Lengths of those parts

/*
   These are network parameters which may be set by the user via commands.
   They are initialized to defaults which indicate that the user has not
   yet set them.  As they are set, their current values are placed here.
   When learning is done for a network, their values are copied from here
   into the network object.  When a network is read, the object's values
   are copied from it to here.  Otherwise, these variables are not used;
   the values in the network object itself are used.  The only purpose of
   these variables is to keep track of current values.
*/

   int net_model = -1 ;     // Network model (see NETMOD_? in CONST.H)
   int out_model = -1 ;     // Output model (see OUTMOD_? in CONST.H)
   int n_inputs = -1 ;      // Number of input neurons
   int n_outputs = -1 ;     // Number of output neurons
   int n_hidden1 = -1 ;     // Number of hidden layer one neurons
   int n_hidden2 = -1 ;     // Ditto layer 2 (0 if just one hidden layer)


   TrainingSet *tset = NULL ;            // Training set here
   Network *network = NULL ;             // Network here
   struct LearnParams learn_params ;     // General learning parameters
   struct AnnealParams anneal_params ;   // Simulated annealing parameters
   struct GenInitParams geninit_params ; // Genetic initialization parameters
   struct KohParams koh_params ;         // Kohonen parameters

   int classif_output = -1 ;  // Current class (0=reject) for classif training
   char out_file[80] = "" ;   // File for EXECUTE output
   double threshold ;         // CLASSIFY confusion reject cutoff

/*
   Miscellaneous variables
*/

   int i, n, m ;
   double p ;
   char *msg ;
   FILE *fp ;

/*
--------------------------------------------------------------------------------

   Program starts here.

   Verify that a careless user didn't fail to set the integer size
   correctly when compiling.

--------------------------------------------------------------------------------
*/

#if VERSION_16_BIT
   if (sizeof(int) > 2) {
      printf ( "\nRecompile with VERSION_16_BIT set to 0 in CONST.H" ) ;
      exit ( 1 ) ;
      }
#else
   if (sizeof(int) < 4) {
      printf ( "\nRecompile with VERSION_16_BIT set to 1 in CONST.H" ) ;
      exit ( 1 ) ;
      }
#endif

printf ( "\nNEURAL - Program to train and test neural networks" ) ;
printf("\nCopyright (c) 1993 by Academic Press, Inc.");
printf("\nAll rights reserved.  Permission is hereby granted, until further notice,");
printf("\nto make copies of this diskette, which are not for resale, provided these");
printf("\ncopies are made from this master diskette only, and provided that the");
printf("\nfollowing copyright notice appears on the diskette label:");
printf("\n(c) 1993 by Academic Press, Inc.");
printf("\nExcept as previously stated, no part of the computer program embodied in");
printf("\nthis diskette may be reproduced or transmitted in any form or by any means,");
printf("\nelectronic or mechanical, including input into storage in any information");
printf("\nsystem for resale, without permission in writing from the publisher.");
printf("\nProduced in the United States of America.");
printf("\nISBN 0-12-479041-0");

/*
   Process command line parameters
*/

   mem_name[0] = 0 ;  // Default is no memory allocation file

   for (i=1 ; i<argc ; i++) {  // Process all command line args
      str_to_upr ( argv[i] ) ; // Easier if all upper case

      if (! strcmp ( argv[i] , "/DEBUG" )) {
         sscanf ( argv[++i] , "%s" , mem_name ) ;
         if ((strlen ( mem_name ) > 1)  ||  ! isalpha ( mem_name[0] )) {
            printf ( "\nIllegal DEBUG drive (%s); must be 1 letter." ) ;
            exit ( 1 ) ;
            }
         continue ;
         }

      printf ( "\nIllegal command line parameter (%s)", argv[i] ) ;
      exit ( 1 ) ;
      }

/*
   Initialize memory allocation debugging
*/

   if (strlen ( mem_name )) {
      strcat ( mem_name , ":mem.log" ) ;
      fp = fopen ( mem_name , "wt" ) ;
      if (fp == NULL) {
         printf ( "\nCannot open debugging file %s", mem_name ) ;
         exit ( 1 ) ;
         }
      fclose ( fp ) ;
      mem_log = 1 ;
      }
   else 
      mem_log = 0 ;

   mem_used = 0 ;

/*
   Initialize defaults
*/

   learn_params.init = -1 ;
   learn_params.quit_err = 0.0 ;
   learn_params.retries = 32767 ;

   anneal_params.temps0 = 3 ;
   anneal_params.temps = 4 ;
   anneal_params.iters0 = 50 ;
   anneal_params.iters = 20 ;
   anneal_params.setback0 = 50 ;
   anneal_params.setback = 20 ;
   anneal_params.start0 = 3.0 ;
   anneal_params.start = 4.0 ;
   anneal_params.stop0 = 1.0 ;
   anneal_params.stop = 0.02 ;

   geninit_params.pool = 50 ;
   geninit_params.gens = 3 ;
   geninit_params.climb = 0 ;
   geninit_params.overinit = 1.5 ;
   geninit_params.pcross = 0.8 ;
   geninit_params.pmutate = 0.0001 ;

   koh_params.normalization = 0 ;  // 0=multiplicative, 1=Z 
   koh_params.learn_method = 1 ;   // 0=additive, 1=subtractive
   koh_params.rate = 0.4 ;         // learning rate
   koh_params.reduction = 0.99 ;   // learning rate reduction

   learn_params.ap = &anneal_params ;
   learn_params.gp = &geninit_params ;
   learn_params.kp = &koh_params ;

   act_func_init () ; // Initialize interpolation table for activation function

   MEMTEXT ( "NEURAL: control_line, msg" ) ;
   if (((control_line = (char *) MALLOC ( CONTROL_LINE_LENGTH+1 )) == NULL)
    || ((msg = (char *) MALLOC ( CONTROL_LINE_LENGTH+1 )) == NULL)) {
      printf ( "\nInsufficient memory" ) ;
      exit ( 1 ) ;
      }

/*
   Main loop processes all commands
*/

   for (;;) {

      get_control_line ( control_line , &control_file_number, control_files ) ;

      split_control_line ( control_line , &command , &n_command ,
                           &rest , &n_rest ) ;

      if (! n_command) {
         if (n_rest) {
            sprintf ( msg , "No colon after command: %s", rest ) ;
            error_message ( msg ) ;
            }
         continue ;
         }

      sprintf ( msg , "%s : %s", command, rest ) ;
      normal_message ( msg ) ;

/*
   Act on the command
*/

      if (! strcmp ( command , "QUIT" ))
         break ;

      if (! strcmp ( command , "CONTROL" )) {
         stack_control_file ( rest , &control_file_number , control_files ) ;
         continue ;
         }

      if (! strcmp ( command , "NETWORK MODEL" )) {
         if (! strcmp ( rest , "LAYER" ))
            n = NETMOD_LAYER ;
         else if (! strcmp ( rest , "KOHONEN" ))
            n = NETMOD_KOH ;
         else {
            sprintf ( msg , "Illegal NETWORK MODEL: %s", rest ) ;
            error_message ( msg ) ;
            continue ;
            }
         if (net_model == n)
            continue ;
         if (ok_to_clear_weights( &network )) {
            net_model = n ;
            learn_params.init = -1 ;
            }
         else
            warning_message ( "Command aborted" ) ;
         continue ;
         }

      if (! strcmp ( command , "OUTPUT MODEL" )) {
         if (! strcmp ( rest , "CLASSIFY" ))
            n = OUTMOD_CLASSIFY ;
         else if (! strcmp ( rest , "AUTO" ))
            n = OUTMOD_AUTO ;
         else if (! strcmp ( rest , "GENERAL" ))
            n = OUTMOD_GENERAL ;
         else {
            sprintf ( msg , "Illegal OUTPUT MODEL: %s", rest ) ;
            error_message ( msg ) ;
            continue ;
            }
         if (out_model == n)
            continue ;
         if ((ok_to_clear_tset( &tset )) && (ok_to_clear_weights( &network)))
            out_model = n ;
         else
            warning_message ( "Command aborted" ) ;
         continue ;
         }

      if (! strcmp ( command , "N INPUTS" )) {
         m = sscanf ( rest , "%d" , &n ) ;
         if ((m <= 0)  ||  (n <= 0)  ||  (n > MAX_INPUTS)) {
            sprintf ( msg , "Illegal N INPUTS: %s", rest ) ;
            error_message ( msg ) ;
            continue ;
            }
         if (n_inputs == n)
            continue ;
         if ((ok_to_clear_tset( &tset)) && (ok_to_clear_weights(&network)))
            n_inputs = n ;
         else
            warning_message ( "Command aborted" ) ;
         continue ;
         }

      if (! strcmp ( command , "N OUTPUTS" )) {
         m = sscanf ( rest , "%d" , &n ) ;
         if ((m <= 0)  ||  (n <= 0)  ||  (n > MAX_OUTPUTS)) {
            sprintf ( msg , "Illegal N OUTPUTS: %s", rest ) ;
            error_message ( msg ) ;
            continue ;
            }
         if (n_outputs == n)
            continue ;
         if ((ok_to_clear_tset( &tset)) && (ok_to_clear_weights(&network)))
            n_outputs = n ;
         else
            warning_message ( "Command aborted" ) ;
         continue ;
         }

      if (! strcmp ( command , "N HIDDEN1" )) {
         m = sscanf ( rest , "%d" , &n ) ;
         if ((m <= 0)  ||  (n < 0)  ||  (n > MAX_HIDDEN)) {
            sprintf ( msg , "Illegal N HIDDEN1: %s", rest ) ;
            error_message ( msg ) ;
            continue ;
            }
         if (n_hidden1 == n)
            continue ;
         if (ok_to_clear_weights( &network ))
            n_hidden1 = n ;
         else
            warning_message ( "Command aborted" ) ;
         continue ;
         }

      if (! strcmp ( command , "N HIDDEN2" )) {
         m = sscanf ( rest , "%d" , &n ) ;
         if ((m <= 0)  ||  (n < 0)  ||  (n > MAX_HIDDEN)) {
            sprintf ( msg , "Illegal N HIDDEN2: %s", rest ) ;
            error_message ( msg ) ;
            continue ;
            }
         if (n  &&  ! n_hidden1) {
            error_message ( "N HIDDEN2 must be 0 if N HIDDEN1 IS 0." ) ;
            continue ;
            }
         if (n_hidden2 == n)
            continue ;
         if (ok_to_clear_weights( &network ))
            n_hidden2 = n ;
         else
            warning_message ( "Command aborted" ) ;
         continue ;
         }

      if (! strcmp ( command , "TRAIN" )) {
         if ((out_model == OUTMOD_AUTO)  &&  (n_outputs != n_inputs)) {
            warning_message ( "Setting N OUTPUTS = N INPUTS" ) ;
            n_outputs = n_inputs ;
            }
         if (out_model <= 0)
            error_message ( "TRAIN used before OUTPUT MODEL set." ) ;
         else if (n_inputs <= 0)
            error_message ( "TRAIN used before N INPUTS set." ) ;
         else if (n_outputs <= 0)
            error_message ( "TRAIN used before N OUTPUTS set." ) ;
         else if ((net_model != NETMOD_KOH) && (out_model == OUTMOD_CLASSIFY)
                  &&  (classif_output < 0))
            error_message( "CLASSIFY output mode but CLASSIFY OUTPUT not set.");
         else if ((net_model == NETMOD_KOH)  &&  (out_model != OUTMOD_CLASSIFY))
            error_message( "KOHONEN network requires CLASSIFY output mode.");
         else {
            if (tset == NULL) {
               MEMTEXT ( "NEURAL: new tset" ) ;
               tset = new TrainingSet ( out_model , n_inputs , n_outputs ) ;
               }
            tset->train ( rest , classif_output ) ;
            }
         continue ;
         }

      if (check_anneal ( command , rest , &anneal_params ))
         continue ;

      if (check_genetic ( command , rest , &geninit_params ))
         continue ;

      if (check_kohonen ( command , rest , &koh_params , &network ))
         continue ;

      if (check_learn_params ( command , rest , &learn_params , net_model ))
         continue ;

      if (! strcmp ( command , "LEARN" )) {
         if ((tset == NULL)  ||  (tset->ntrain == 0)) {
            error_message ( "Cannot LEARN; No training set exists." ) ;
            continue ;
            }
         if ((net_model == NETMOD_KOH)  &&  (out_model != OUTMOD_CLASSIFY)) {
            error_message( "KOHONEN network requires CLASSIFY output mode.");
            continue ;
            }
         if (learn_params.init < 0) {
            error_message( "Initialization method not set.");
            continue ;
            }
         if (network == NULL) {
            if (net_model == NETMOD_LAYER) {
               if (n_hidden1 < 0) {
                  error_message ( "LEARN used before N HIDDEN1 set." ) ;
                  continue ;
                  }
               else if (n_hidden2 < 0) {
                  error_message ( "LEARN used before N HIDDEN2 set." ) ;
                  continue ;
                  }
               else {
                  MEMTEXT ( "NEURAL: new LayerNet" ) ;
                  network = new LayerNet ( out_model , n_inputs , n_hidden1 ,
                                           n_hidden2 , n_outputs , 1 , 1 ) ;
                  }
               }
            else if (net_model == NETMOD_KOH) {
               MEMTEXT ( "NEURAL: new KohNet" ) ;
               network = new KohNet ( n_inputs , n_outputs ,
                                      &koh_params , 1 , 1 ) ;
               }
            }
         if ((network == NULL)  ||  (! network->ok)) {  // Malloc failure?
            memory_message ( "to create network." ) ;
            if (network != NULL) {
               delete network ;
               network = NULL ;
               }
            continue ;
            }
         network->learn ( tset , &learn_params ) ;
         if (network->neterr > 0.999999) {  // Indicates massive failure
            MEMTEXT ( "NEURAL: learn failure delete network" ) ;
            delete network ;
            network = NULL ;
            }
         else {
            sprintf ( msg , "Final error = %.4lf%% of max possible",
                      100.0 * network->neterr ) ;
            normal_message ( msg ) ;
            }
         continue ;
         }

      if (! strcmp ( command , "SAVE WEIGHTS" )) {
         if (network == NULL)
            error_message ( "There are no learned weights to save." ) ;
         else
            wt_save ( network , net_model , 0 , rest ) ;
         continue ;
         }

      if (! strcmp ( command , "RESTORE WEIGHTS" )) {
         if (network != NULL) {
            MEMTEXT ( "NEURAL: delete network for restore" ) ;
            delete network ;
            network = NULL ;
            }
         network = wt_restore ( rest , &net_model ) ;
         if (network == NULL)
            continue ;
         if (tset != NULL) {
            if ((tset->nin != network->nin)
             || (tset->nout != network->nout)
             || (tset->outmod != network->outmod)) {
               error_message ( "Network conflicts with existing training set.");
               continue ;
               }
            }
         out_model = network->outmod ;
         n_inputs = network->nin ;
         n_outputs = network->nout ;
         if (net_model == NETMOD_LAYER) {
            n_hidden1 = ((LayerNet*) network)->nhid1 ;
            n_hidden2 = ((LayerNet*) network)->nhid2 ;
            }
         if (net_model == NETMOD_KOH)
            koh_params.normalization = ((KohNet *) network)->normalization ;
         learn_params.init = -1 ;
         continue ;
         }

      if (! strcmp ( command , "CLEAR TRAINING" )) {
         if (tset != NULL) {
            MEMTEXT ( "NEURAL: delete tset" ) ;
            delete tset ;
            tset = NULL ;
            }
         continue ;
         }

      if (! strcmp ( command , "CLEAR WEIGHTS" )) {
         if (network != NULL) {
            MEMTEXT ( "NEURAL: delete network" ) ;
            delete network ;
            network = NULL ;
            }
         continue ;
         }

      if (! strcmp ( command , "CLASSIFY OUTPUT" )) {
         if (net_model == NETMOD_KOH) {
            error_message ( "Cannot specify output for KOHONEN model." ) ;
            continue ;
            }
         if (n_outputs < 0) {
            error_message ( "CLASSIFY OUTPUT used before N OUTPUTS set." ) ;
            continue ;
            }
         if (out_model != OUTMOD_CLASSIFY) {
            error_message
                  ( "CLASSIFY OUTPUT only valid when OUTPUT MODEL:CLASSIFY" ) ;
            continue ;
            }
         m = sscanf ( rest , "%d" , &n ) ;
         if ((m <= 0)  ||  (n < 0)) {
            sprintf ( msg , "Illegal CLASSIFY OUTPUT: %s", rest ) ;
            error_message ( msg ) ;
            }
         else if (n > n_outputs) {
            sprintf ( msg , "CLASSIFY OUTPUT (%d) exceeds N OUTPUTS (%d)",
                      n, n_outputs ) ;
            error_message ( msg ) ;
            }
         else
            classif_output = n ;
         continue ;
         }


      if (! strcmp ( command , "OUTPUT FILE" )) {
         strcpy ( out_file , rest ) ;
         continue ;
         }

      if (! strcmp ( command , "EXECUTE" )) {
         if (network == NULL)
            error_message ( "There is no trained network" ) ;
         else
            network->execute_from_file ( rest , out_file ) ;
         continue ;
         }

      if (! strcmp ( command , "CLASSIFY" )) {
         if (network == NULL)
            error_message ( "There is no trained network" ) ;
         else if (out_model != OUTMOD_CLASSIFY)
            error_message ( "CLASSIFY valid only in CLASSIFY output mode" ) ;
         else
            network->classify_from_file ( rest , threshold ) ;
         continue ;
         }

      if (! strcmp ( command , "RESET CONFUSION" )) {
         if (network == NULL)
            error_message ( "There is no trained network" ) ;
         else
            network->reset_confusion () ;
         continue ;
         }

      if (! strcmp ( command , "CONFUSION THRESHOLD" )) {
         p = atof ( rest ) ;
         if ((p < 0.0)  ||  (p > 100.0)) {
            sprintf ( msg , "Illegal CONFUSION THRESHOLD: %s", rest ) ;
            error_message ( msg ) ;
            }
         else
            threshold = p / 100.0 ;
         continue ;
         }

      if (! strcmp ( command , "SHOW CONFUSION" )) {
         if (network == NULL)
            error_message ( "There is no trained network" ) ;
         else if (out_model != OUTMOD_CLASSIFY)
            error_message ( "CONFUSION valid only in CLASSIFY output mode" ) ;
         else
            network->show_confusion () ;
         continue ;
         }

      if (! strcmp ( command , "SAVE CONFUSION" )) {
         if (network == NULL)
            error_message ( "There is no trained network" ) ;
         else if (out_model != OUTMOD_CLASSIFY)
            error_message ( "CONFUSION valid only in CLASSIFY output mode" ) ;
         else
            network->save_confusion ( rest ) ;
         continue ;
         }

      sprintf ( msg , "Unknown command: %s", command ) ;
      error_message ( msg ) ;

      } // Endless command loop

   MEMTEXT ( "NEURAL: control_line, msg" ) ;
   FREE ( control_line ) ;
   FREE ( msg ) ;
   MEMCLOSE () ;
   return 0 ;
}
/*--------------------------------------------------------------------------
 * (function: define_decoded_mux)
 *------------------------------------------------------------------------*/
void define_decoded_mux(nnode_t *node, FILE *out)
{
	int i, j;

	oassert(node->input_port_sizes[0] == node->input_port_sizes[1]);

	fprintf(out, ".names");

	if (global_args.high_level_block != NULL)
	{
		/* printout all the port hookups */
		for (i = 0; i < node->num_input_pins; i++)
		{
			/* now hookup the input wires with their respective ports.  [1+i] to skip output spot. */
			if (node->input_pins[i]->net->driver_pin->node->related_ast_node != NULL)
			{
				fprintf(out, " %s^^%i-%i", node->input_pins[i]->net->driver_pin->node->name, node->input_pins[i]->net->driver_pin->node->related_ast_node->far_tag, node->input_pins[i]->net->driver_pin->node->related_ast_node->high_number); 
			}
			else
			{
				fprintf(out, " %s", node->input_pins[i]->net->driver_pin->node->name); 
			}
		}
		/* now print the output */
		if (node->related_ast_node != NULL)
			fprintf(out, " %s^^%i-%i", node->name, node->related_ast_node->far_tag, node->related_ast_node->high_number);
		else
			fprintf(out, " %s", node->name);
	}
	else
	{
		/* printout all the port hookups */
		for (i = 0; i < node->num_input_pins; i++)
		{
			/* now hookup the input wires with their respective ports.  [1+i] to skip output spot. */
			/* Just print the driver_pin->name NOT driver_pin->node->name -- KEN */
			nnet_t *net = node->input_pins[i]->net;

			if (!net->driver_pin)
			{
				// Add a warning for an undriven net.
				int line_number = node->related_ast_node?node->related_ast_node->line_number:0;
				warning_message(NETLIST_ERROR, line_number, -1, "Net %s driving node %s is itself undriven.", net->name, node->name);

				fprintf(out, " %s", "unconn");
			}
			else
			{
				if (net->driver_pin->name != NULL)
				{
					if ((net->driver_pin->node->type == MULTIPLY) ||
				    	(net->driver_pin->node->type == HARD_IP) ||
				    	(net->driver_pin->node->type == MEMORY) ||
				    	(net->driver_pin->node->type == ADD) ||
				    	(net->driver_pin->node->type == MINUS))
					{
						fprintf(out, " %s", net->driver_pin->name);
					}
				}
				else
				{
					fprintf(out, " %s", net->driver_pin->node->name);
				}
			}
		}

		// Now print the output
		fprintf(out, " %s", node->name);
	}
	fprintf(out, "\n");

	oassert(node->num_output_pins == 1);

	/* generates: 1----- 1\n-1----- 1\n ... */
	for (i = 0; i < node->input_port_sizes[0]; i++)
	{
		for (j = 0; j < node->num_input_pins; j++)
		{
			if (i == j)
				fprintf(out, "1");
			else if (i+node->input_port_sizes[0] == j)
				fprintf(out, "1");
			else if (i > node->input_port_sizes[0])
				fprintf(out, "0");
			else
				fprintf(out, "-");
		}
		fprintf(out, " 1\n");
	}

	fprintf(out, "\n");
}
/*---------------------------------------------------------------------------
 * (function: output_blif)
 * 	The function that prints out the details for a blif formatted file
 *-------------------------------------------------------------------------*/
void output_blif(char *file_name, netlist_t *netlist)
{
	int i;
	int count = 0;
	short first_time_inputs = FALSE;
	short first_time_outputs = FALSE;
	FILE *out;
	char *out_file;

	/* open the file for output */
	if (global_args.high_level_block != NULL)
	{
		out_file = (char*)malloc(sizeof(char)*(1+strlen(file_name)+strlen(global_args.high_level_block)+6)); 
		sprintf(out_file, "%s_%s.blif", file_name, global_args.high_level_block); 
		out = fopen(out_file, "w");
	}
	else
	{
		out = fopen(file_name, "w");
	}
	
	if (out == NULL)
	{
		error_message(NETLIST_ERROR, -1, -1, "Could not open output file %s\n", file_name);
	}

	fprintf(out, ".model %s\n", top_module->children[0]->types.identifier);

	/* generate all te signals */
	for (i = 0; i < netlist->num_top_input_nodes; i++)
	{
		if (first_time_inputs == FALSE)
		{
			count = fprintf(out, ".inputs");
			first_time_inputs = TRUE;
		}

		if(netlist->top_input_nodes[i]->output_pins[0]->net->fanout_pins != NULL)
		{
			if (global_args.high_level_block != NULL)
			{
				if (strlen(netlist->top_input_nodes[i]->name) + count < 79)
					count = count + fprintf(out, " %s^^%i-%i", netlist->top_input_nodes[i]->name, netlist->top_input_nodes[i]->related_ast_node->far_tag, netlist->top_input_nodes[i]->related_ast_node->high_number);
				else
				{
					/* wrapping line */
					count = fprintf(out, " \\\n %s^^%i-%i", netlist->top_input_nodes[i]->name,netlist->top_input_nodes[i]->related_ast_node->far_tag, netlist->top_input_nodes[i]->related_ast_node->high_number);
					count = count - 3;
				}
			}
			else
			{
				if (strlen(netlist->top_input_nodes[i]->name) + count < 79)
				{
					count = count + fprintf(out, " %s", netlist->top_input_nodes[i]->name);
				}
				else
				{
					/* wrapping line */
					count = fprintf(out, " \\\n %s", netlist->top_input_nodes[i]->name);
					count = count - 3;
				}
			}
		}
	}
	fprintf(out, "\n");

	count = 0;
	for (i = 0; i < netlist->num_top_output_nodes; i++)
	{
		if (netlist->top_output_nodes[i]->input_pins[0]->net->driver_pin == NULL)
		{
			warning_message(NETLIST_ERROR, netlist->top_output_nodes[i]->related_ast_node->line_number, netlist->top_output_nodes[i]->related_ast_node->file_number, "This output is undriven (%s) and will be removed\n", netlist->top_output_nodes[i]->name);
		}
		else
		{	
			if (first_time_outputs == FALSE)
			{
				count = fprintf(out, ".outputs");
				first_time_outputs = TRUE;
			}

			if (global_args.high_level_block != NULL)
			{
				if ((strlen(netlist->top_output_nodes[i]->name) + count) < 79)
					count = count + fprintf(out, " %s^^%i-%i", netlist->top_output_nodes[i]->name,netlist->top_output_nodes[i]->related_ast_node->far_tag, netlist->top_output_nodes[i]->related_ast_node->high_number);
				else
				{
					/* wrapping line */
					count = fprintf(out, "\\\n %s^^%i-%i", netlist->top_output_nodes[i]->name,netlist->top_output_nodes[i]->related_ast_node->far_tag, netlist->top_output_nodes[i]->related_ast_node->high_number);
					count = count - 3;
				}
			}
			else
			{
				if ((strlen(netlist->top_output_nodes[i]->name) + count) < 79)
					count = count + fprintf(out, " %s", netlist->top_output_nodes[i]->name);
				else
				{
					/* wrapping line */
					count = fprintf(out, "\\\n %s", netlist->top_output_nodes[i]->name);
					count = count - 3;
				}
			}
		}
	}
	fprintf(out, "\n");

	/* add gnd, unconn, and vcc */
	fprintf(out, "\n.names gnd\n.names unconn\n.names vcc\n1\n");
	fprintf(out, "\n");

	/* traverse the internals of the flat net-list */
	if (strcmp(configuration.output_type, "blif") == 0)
	{
		depth_first_traversal_to_output(OUTPUT_TRAVERSE_VALUE, out, netlist);	
	}
	else
	{
		error_message(NETLIST_ERROR, 0, -1, "Invalid output file type.");
	}

	/* connect all the outputs up to the last gate */
	for (i = 0; i < netlist->num_top_output_nodes; i++)
	{
		/* KEN -- DPRAM WORKING HERE FOR JASON */
		nnode_t *node = netlist->top_output_nodes[i];
		if (node->input_pins[0]->net->driver_pin != NULL)
		{
			if (global_args.high_level_block != NULL)
			{
				fprintf(out, ".names %s^^%i-%i %s^^%i-%i\n1 1\n",
						node->input_pins[0]->net->driver_pin->node->name,
						node->input_pins[0]->net->driver_pin->node->related_ast_node->far_tag,
						node->input_pins[0]->net->driver_pin->node->related_ast_node->high_number,
						node->name,
						node->related_ast_node->far_tag,
						node->related_ast_node->high_number
				);
			}
			else
			{
				/*
				 *  Use the name of the driver pin as the name of the driver
				 *  as long as that name is set, and is not equal to the name of the output pin.
				 *
				 * 	Otherwise, use the name of the driver node.
				 */
				char *driver = node->input_pins[0]->net->driver_pin->name;
				char *output = node->name;
				if (!driver || !strcmp(driver,output))
					driver = node->input_pins[0]->net->driver_pin->node->name;

				/* Skip if the driver and output have the same name (i.e. the output of a flip-flop) */
				if (strcmp(driver,output) != 0) fprintf(out, ".names %s %s\n1 1\n", driver, output);
			}

		}
		fprintf(out, "\n");
	}

	/* finish off the top level module */
	fprintf(out, ".end\n");
	fprintf(out, "\n");

	/* Print out any hard block modules */
#ifdef VPR6
	add_the_blackbox_for_mults(out);
	add_the_blackbox_for_adds(out);
	output_hard_blocks(out);
#endif

	fclose(out);
}
/*-------------------------------------------------------------------------
 * (function: define_logical_function)
 *-----------------------------------------------------------------------*/
void define_logical_function(nnode_t *node, short type, FILE *out)
{
	int i, j;
	char *temp_string;
	int flag = 0;

	fprintf(out, ".names");


	if (global_args.high_level_block != NULL)
	{
		/* printout all the port hookups */
		for (i = 0; i < node->num_input_pins; i++)
		{
			/* now hookup the input wires with their respective ports.  [1+i] to skip output spot. */
			if (node->input_pins[i]->net->driver_pin->node->related_ast_node != NULL)
				fprintf(out, " %s^^%i-%i", node->input_pins[i]->net->driver_pin->node->name, 	node->input_pins[i]->net->driver_pin->node->related_ast_node->far_tag, node->input_pins[i]->net->driver_pin->node->related_ast_node->high_number); 
			else
				fprintf(out, " %s", node->input_pins[i]->net->driver_pin->node->name); 
		}
		/* now print the output */
		if (node->related_ast_node != NULL)
			fprintf(out, " %s^^%i-%i", node->name, node->related_ast_node->far_tag, node->related_ast_node->high_number);
		else
			fprintf(out, " %s", node->name);
	}
	else
	{
		/* printout all the port hookups */
		for (i = 0; i < node->num_input_pins; i++)
		{
			/* now hookup the input wires with their respective ports.  [1+i] to skip output spot. */
			/* Just print the driver_pin->name NOT driver_pin->node->name -- KEN */
			nnet_t *net = node->input_pins[i]->net;
			if (net && net->driver_pin)
			{	
				if (net->driver_pin->name != NULL)
				{
					if ((net->driver_pin->node->type == MULTIPLY) ||
					(net->driver_pin->node->type == HARD_IP) ||
					(net->driver_pin->node->type == MEMORY) ||
					(net->driver_pin->node->type == ADD) ||
					(net->driver_pin->node->type == MINUS) )
					{
						fprintf(out, " %s", net->driver_pin->name);
					}				
				}
				else
				{
					fprintf(out, " %s", net->driver_pin->node->name);
				}
			}
			else
			{
				int line_number = node->related_ast_node?node->related_ast_node->line_number:0;
				warning_message(NETLIST_ERROR, line_number, -1, "Net %s driving node %s is itself undriven.", net->name, node->name);

				fprintf(out, " %s", "unconn");
			}
		}
		/* now print the output */
		fprintf(out, " %s", node->name);
	}
	fprintf(out, "\n");

	oassert(node->num_output_pins == 1);

	/* print out the blif definition of this gate */
	switch (node->type) 
	{
		case LOGICAL_AND:
		{
			/* generates: 111111 1 */
			for (i = 0; i < node->num_input_pins; i++)
			{
				fprintf(out, "1");
			}
			fprintf(out, " 1\n");
			break;
		}
		case LOGICAL_OR:
		{
			/* generates: 1----- 1\n-1----- 1\n ... */
			for (i = 0; i < node->num_input_pins; i++)
			{
				for (j = 0; j < node->num_input_pins; j++)
				{
					if (i == j)
						fprintf(out, "1");
					else
						fprintf(out, "-");
				}
				fprintf(out, " 1\n");
			}
			break;
		}
		case LOGICAL_NAND:
		{
			/* generates: 0----- 1\n-0----- 1\n ... */
			for (i = 0; i < node->num_input_pins; i++)
			{
				for (j = 0; j < node->num_input_pins; j++)
				{
					if (i == j)
						fprintf(out, "0");
					else
						fprintf(out, "-");
				}
				fprintf(out, " 1\n");
			}
			break;
		}
		case LOGICAL_NOT:
		case LOGICAL_NOR:
		{
			/* generates: 0000000 1 */
			for (i = 0; i < node->num_input_pins; i++)
			{
				fprintf(out, "0");
			}
			fprintf(out, " 1\n");
			break;
		}
		case LOGICAL_EQUAL:
		case LOGICAL_XOR:
		{
			oassert(node->num_input_pins <= 3);
			/* generates: a 1 when odd number of 1s */
			for (i = 0; i < my_power(2, node->num_input_pins); i++)
			{
				if ((i % 8 == 1) || (i % 8 == 2) || (i % 8 == 4) || (i % 8 == 7))
				{
					temp_string = convert_long_long_to_bit_string(i, node->num_input_pins);
					fprintf(out, "%s", temp_string);
					free(temp_string);
					fprintf(out, " 1\n");
				}
			}
			break;
		}
		case NOT_EQUAL:
		case LOGICAL_XNOR:
		{
			oassert(node->num_input_pins <= 3);
			for (i = 0; i < my_power(2, node->num_input_pins); i++)
			{
				if ((i % 8 == 0) || (i % 8 == 3) || (i % 8 == 5) || (i % 8 == 6))
				{
					temp_string = convert_long_long_to_bit_string(i, node->num_input_pins);
					fprintf(out, "%s", temp_string);
					free(temp_string);
					fprintf(out, " 1\n");
				}
			}
			break;
		}
		default:
			oassert(FALSE);
			break;
	}

	fprintf(out, "\n");
	if (flag == 1)
		output_blif_pin_connect(node, out);
}
Beispiel #14
0
int
main (int   argc,
      char *argv[])
{
	char **         args;
	nih_local char *message = NULL;
	size_t          messagelen;
	nih_local char *msg = NULL;
	int             arg;
	pid_t           pid = 0;

	nih_main_init (argv[0]);

	nih_option_set_usage (_("TIME [MESSAGE]"));
	nih_option_set_synopsis (_("Bring the system down."));
	nih_option_set_help (
		_("TIME may have different formats, the most common is simply "
		  "the word 'now' which will bring the system down "
		  "immediately.  Other valid formats are +m, where m is the "
		  "number of minutes to wait until shutting down and hh:mm "
		  "which specifies the time on the 24hr clock.\n"
		  "\n"
		  "Logged in users are warned by a message sent to their "
		  "terminal, you may include an optional MESSAGE included "
		  "with this.  Messages can be sent without actually "
		  "bringing the system down by using the -k option.\n"
		  "\n"
		  "If TIME is given, the command will remain in the "
		  "foreground until the shutdown occurs.  It can be cancelled "
		  "by Control-C, or by another user using the -c option.\n"
		  "\n"
		  "The system is brought down into maintenance (single-user) "
		  "mode by default, you can change this with either the -r or "
		  "-h option which specify a reboot or system halt "
		  "respectively.  The -h option can be further modified with "
		  "-H or -P to specify whether to halt the system, or to "
		  "power it off afterwards.  The default is left up to the "
		  "shutdown scripts."));

	args = nih_option_parser (NULL, argc, argv, options, FALSE);
	if (! args)
		exit (1);

	/* If the runlevel wasn't given explicitly, set it to 1 so we go
	 * down into single-user mode.
	 */
	if (! runlevel) {
		runlevel = '1';
		init_halt = NULL;
	}


	/* When may be specified with -g, or must be first argument */
	if (! (cancel || when || args[0])) {
		fprintf (stderr, _("%s: time expected\n"), program_name);
		nih_main_suggest_help ();
		exit (1);
	} else if (! (cancel || when)) {
		when = NIH_MUST (nih_strdup (NULL, args[0]));
		arg = 1;
	} else {
		arg = 0;
	}

	/* Parse the time argument */
	if (when) {
		if (! strcmp (when, "now")) {
			/* "now" means, err, now */
			delay = 0;
		} else if (strchr (when, ':')) {
			/* Clock time */
			long       hours, mins;
			char      *endptr;
			struct tm *tm;
			time_t     now;

			hours = strtoul (when, &endptr, 10);
			if ((*endptr != ':') || (hours < 0) || (hours > 23)) {
				fprintf (stderr, _("%s: illegal hour value\n"),
					 program_name);
				nih_main_suggest_help ();
				exit (1);
			}

			mins = strtoul (endptr + 1, &endptr, 10);
			if (*endptr || (mins < 0) || (mins > 59)) {
				fprintf (stderr,
					 _("%s: illegal minute value\n"),
					 program_name);
				nih_main_suggest_help ();
				exit (1);
			}

			/* Subtract the current time to get the delay.
			 * Add a whole day if we go negative */
			now = time (NULL);
			tm = localtime (&now);
			delay = (((hours * 60) + mins)
				 - ((tm->tm_hour * 60) + tm->tm_min));
			if (delay < 0)
				delay += 1440;
		} else {
			/* Delay in minutes */
			char *endptr;

			delay = strtoul (when, &endptr, 10);
			if (*endptr || (delay < 0)) {
				fprintf (stderr, _("%s: illegal time value\n"),
					 program_name);
				nih_main_suggest_help ();
				exit (1);
			}
		}
		nih_free (when);
	}


	/* The rest of the arguments are a message.
	 * Really this should be just the next argument, but that's not
	 * how this has been traditionally done *sigh*
	 */
	message = NIH_MUST (nih_strdup (NULL, ""));
	messagelen = 0;
	for (; args[arg]; arg++) {
		message = NIH_MUST (nih_realloc (
				  message, NULL,
				  messagelen + strlen(args[arg]) + 4));

		strcat (message, args[arg]);
		strcat (message, " ");
		messagelen += strlen (args[arg]) + 1;
	}

	/* Terminate with \r\n */
	if (messagelen)
		strcat (message, "\r\n");


	/* Check we're root, or setuid root */
	setuid (geteuid ());
	if (getuid ()) {
		nih_fatal (_("Need to be root"));
		exit (1);
	}

	/* Look for an existing pid file and deal with the existing
	 * process if there is one.
	 */
	pid = nih_main_read_pidfile ();
	if (pid > 0) {
		if (cancel) {
			if (kill (pid, SIGINT) < 0) {
				nih_error (_("Shutdown is not running"));
				exit (1);
			}

			if (messagelen)
				wall (message);

			exit (0);
		} else if (kill (pid, 0) == 0) {
			nih_error (_("Another shutdown is already running"));
			exit (1);
		}
	} else if (cancel) {
		nih_error (_("Cannot find pid of running shutdown"));
		exit (1);
	}

	/* Send an initial message */
	msg = NIH_MUST (warning_message (message));
	wall (msg);

	if (warn_only)
		exit (0);


	/* Give us a sane environment */
	if (chdir ("/") < 0)
		nih_warn ("%s: %s", _("Unable to change directory"),
			  strerror (errno));
	umask (022);

	/* Shutdown now? */
	if (! delay)
		shutdown_now ();

	/* Save our pid so we can be interrupted later */
	if (nih_main_write_pidfile (getpid ()) < 0) {
		NihError *err;

		err = nih_error_get ();
		nih_warn ("%s: %s: %s", nih_main_get_pidfile(),
			  _("Unable to write pid file"), err->message);
		nih_free (err);
	}


	/* Ignore a whole bunch of signals */
	nih_signal_set_ignore (SIGCHLD);
	nih_signal_set_ignore (SIGHUP);
	nih_signal_set_ignore (SIGTSTP);
	nih_signal_set_ignore (SIGTTIN);
	nih_signal_set_ignore (SIGTTOU);

	/* Catch the usual quit signals */
	nih_signal_set_handler (SIGINT, nih_signal_handler);
	NIH_MUST (nih_signal_add_handler (NULL, SIGINT,
					  cancel_callback, NULL));
	nih_signal_set_handler (SIGQUIT, nih_signal_handler);
	NIH_MUST (nih_signal_add_handler (NULL, SIGQUIT,
					  cancel_callback, NULL));
	nih_signal_set_handler (SIGTERM, nih_signal_handler);
	NIH_MUST (nih_signal_add_handler (NULL, SIGTERM,
					  cancel_callback, NULL));

	/* Call a timer every minute until we shutdown */
	NIH_MUST (nih_timer_add_periodic (NULL, 60,
					  (NihTimerCb)timer_callback,
					  message));

	/* Hang around */
	nih_main_loop ();

	return 0;
}
Beispiel #15
0
int LayerNet::ssg_core (
   TrainingSet *tptr ,        // Training set to use
   struct LearnParams *lptr , // User's general learning parameters
   LayerNet *avgnet ,         // Work area used to keep average weights
   LayerNet *bestnet ,        // And the best so far
   double *work1 ,            // Gradient work vector
   double *work2 ,            // Ditto
   double *grad ,             // Ditto
   double *avg_grad ,         // Ditto
   int n_grad                 // Length of above vectors
   )
{
   int ntemps, niters, setback, reg, nvars, user_quit ;
   int i, iter, itemp, n_good, n_bad, use_grad ;
   char msg[80] ;
   double tempmult, temp, fval, bestfval, starttemp, stoptemp, fquit ;
   double avg_func, new_fac, gradlen, grad_weight, weight_used ;
   enum RandomDensity density ;
   SingularValueDecomp *sptr ;
   struct AnnealParams *aptr ; // User's annealing parameters

   aptr = lptr->ap ;

   ntemps = aptr->temps0 ;
   niters = aptr->iters0 ;
   setback = aptr->setback0 ;
   starttemp = aptr->start0 ;
   stoptemp = aptr->stop0 ;
   if (aptr->random0 == ANNEAL_GAUSSIAN)
      density = NormalDensity ;
   else if (aptr->random0 == ANNEAL_CAUCHY)
      density = CauchyDensity ;

   if (! (ntemps * niters))
      return 0 ;

/*
   Initialize other local parameters.  Note that there is no sense using
   regression if there are no hidden layers.
*/

   use_grad = (grad != NULL) ;
   fquit = lptr->quit_err ;
   reg = nhid1 ;

/*
   Allocate the singular value decomposition object for REGRESS.
   Also allocate a work area for REGRESS to preserve matrix.
*/

   if (reg) {                 // False if no hidden layers
      if (nhid2 == 0)         // One hidden layer
         nvars = nhid1_n ;
      else                    // Two hidden layers
         nvars = nhid2_n ;

      i = (model == NETMOD_COMPLEX)  ?  2 * tptr->ntrain : tptr->ntrain ;

      if (i < nvars) {
         warning_message ( "Too few training sets for regression." ) ;
         reg = 0 ;
         }
      else {
         MEMTEXT ( "SSG: new SingularValueDecomp" ) ;
         sptr = new SingularValueDecomp ( i , nvars , 1 ) ;

         if ((sptr == NULL)  || ! sptr->ok) {
            memory_message (
               "for SS(G) with regression.  Using total randomization.");
            if (sptr != NULL)
               delete sptr ;
            reg = 0 ;
            }
         }
      }

/*
   For the basic algorithm, we will keep the current 'average' network
   weight set in avgnet.  This will be the moving center about which the
   perturbation is done.
   Although not directly related to the algorithm itself, we keep track
   of the best network ever found in bestnet.  That is what the user
   will get at the end.
*/

   copy_weights ( bestnet , this ) ; // Current weights are best so far
   copy_weights ( avgnet , this ) ;  // Center of perturbation
   bestfval = trial_error ( tptr ) ;

/*
   If this is being used to initialize the weights, make sure that they are
   not identically zero.  Do this by setting bestfval huge so that
   SOMETHING is accepted later.
*/

   if (nhid1) {
      i = nhid1 * nin_n ;
      while (i--) {
         if (fabs(hid1_coefs[i]) > 1.e-10)
            break ;
         }
      if (i < 0)
         bestfval = 1.e30 ;
      }

/*
   Initialize by cumulating a bunch of points
*/

   normal_message ( "Initializing..." ) ;
   avg_func = 0.0 ;                       // Mean function around center
   if (use_grad) {
      for (i=0 ; i<n_grad ; i++)          // Zero the mean gradient
         avg_grad[i] = 0.0 ;
      }

   for (iter=0 ; iter<niters ; iter++) {  // Initializing iterations

      perturb ( avgnet , this , starttemp , reg , density ) ; // Move point

      if (reg)                            // If using regression, estimate
         fval = regress ( tptr , sptr ) ; // out weights now, ignore fval
      if (use_grad)                       // Also need gradient?
         fval = gradient ( tptr , work1 , work2 , grad ) ; // fval redundant
      else if (! reg)                     // If reg we got fval from regress
         fval = trial_error ( tptr ) ;

      avg_func += fval ;                  // Cumulate mean function

      if (use_grad) {                     // Also need gradient?
         for (i=0 ; i<n_grad ; i++)       // Cumulate mean gradient
            avg_grad[i] += grad[i] ;
         }

      if (fval < bestfval) {              // If this iteration improved
         bestfval = fval ;                // then update the best so far
         copy_weights ( bestnet , this ) ; // Keep the network
         if (bestfval <= fquit)           // If we reached the user's
            goto FINISH ;                 // limit, we can quit
         }

      if ((user_quit = user_pressed_escape ()) != 0)
         goto FINISH ;

      } // Loop: for all initial iters

   avg_func /= niters ;          // Mean of all points around avgnet
   new_fac = 1.0 / niters ;      // Weight of each point

   sprintf ( msg , "  avg=%.6lf  best=%.6lf", avg_func, bestfval ) ;
   progress_message ( msg ) ;

   if (use_grad) {               // Also need gradient?
      gradlen = 0.0 ;            // Will cumulate grad length
      for (i=0 ; i<n_grad ; i++) {  // Find gradient mean and length
         avg_grad[i] /= niters ;
         gradlen += avg_grad[i] * avg_grad[i] ;
         }
      gradlen = sqrt ( gradlen ) ;
      grad_weight = 0.5 ;
      }

/*
   This is the temperature reduction loop and the iteration within
   temperature loop.
*/

   temp = starttemp ;
   tempmult = exp( log( stoptemp / starttemp ) / (ntemps-1)) ;
   user_quit = 0 ;                           // Flags user pressed ESCape

   for (itemp=0 ; itemp<ntemps ; itemp++) {  // Temp reduction loop

      n_good = n_bad = 0 ;                   // Counts better and worse

      sprintf ( msg , "Temp=%.3lf ", temp ) ;
      normal_message ( msg ) ;

      for (iter=0 ; iter<niters ; iter++) {  // Iters per temp loop

         if ((n_bad >= 10)  &&
             ((double) n_good / (double) (n_good+n_bad)  <  0.15))
            break ;

         perturb ( avgnet , this , temp ,
                   reg , density ) ;         // Randomly perturb about center

         if (use_grad)                       // Bias per gradient?
            weight_used = shift ( grad , this , grad_weight , reg ) ;

         if (reg) {                          // If using regression, estimate
            fval = regress ( tptr , sptr ) ; // out weights now
            if ((user_quit = user_pressed_escape ()) != 0)
               break ;
            if (fval >= avg_func) {          // If this would raise mean
               ++n_bad ;                     // Count this bad point for user
               continue ;                    // Skip it and try again
               }
            }

         if (use_grad)                       // Need gradient, fval redundant
            fval = gradient ( tptr , work1 , work2 , grad ) ;
         else if (! reg)                     // If reg we got fval from regress
            fval = trial_error ( tptr ) ;

         if ((user_quit = user_pressed_escape ()) != 0)
            break ;

         if (fval >= avg_func) {             // If this would raise mean
            ++n_bad ;                        // Count this bad point for user
            continue ;                       // Skip it and try again
            }

         ++n_good ;

         if (fval < bestfval) {              // If this iteration improved
            bestfval = fval ;                // then update the best so far
            copy_weights ( bestnet , this ) ; // Keep the network

            if (bestfval <= fquit)           // If we reached the user's
               break ;                       // limit, we can quit

            iter -= setback ;                // It often pays to keep going
            if (iter < 0)                    // at this temperature if we
               iter = 0 ;                    // are still improving
            }

         adjust ( avgnet , this , reg , new_fac ) ; // Move center slightly
         avg_func = new_fac * fval  +  (1.0 - new_fac) * avg_func ;
         if (use_grad) {
            grad_weight = new_fac * weight_used + (1.0 - new_fac) * grad_weight ;
            for (i=0 ; i<n_grad ; i++)          // Adjust mean gradient
               avg_grad[i] = new_fac * grad[i] + (1.0 - new_fac) * avg_grad[i] ;
            }
         }                                   // Loop: for all iters at a temp

/*
   Iters within temp loop now complete
*/

      sprintf ( msg , " %.3lf%% improved  avg=%.5lf  best=%.5lf",
         100.0 * n_good / (double) (n_good+n_bad), avg_func, bestfval ) ;
      progress_message ( msg ) ;

      if (use_grad) {
         gradlen = 0.0 ;                        // Will cumulate grad length
         for (i=0 ; i<n_grad ; i++)             // Find gradient length
            gradlen += avg_grad[i] * avg_grad[i] ;
         gradlen = sqrt ( gradlen ) ;
         sprintf ( msg , "  grad=%.5lf", gradlen ) ;
         progress_message ( msg ) ;
         }

      if (bestfval <= fquit)  // If we reached the user's
         break ;              // limit, we can quit

      if (user_quit)
         break ;

      temp *= tempmult ;      // Reduce temp for next pass
      }                       // through this temperature loop


/*
   The trials left this weight set and neterr in random condition.
   Make them equal to the best, which will be the original
   if we never improved.
*/

FINISH:
   copy_weights ( this , bestnet ) ; // Return best weights in this net
   neterr = bestfval ;               // Trials destroyed weights, err

   if (reg) {
      MEMTEXT ( "SSG: delete SingularValueDecomp" ) ;
      delete sptr ;
      }

   if (user_quit)
      return 1 ;
   else
      return 0 ;
}
Beispiel #16
0
//*******************************************************************
// WinMain - Neural main
//
// parameters:
//             hInstance     - The instance of this instance of this
//                             application.
//             hPrevInstance - The instance of the previous instance
//                             of this application. This will be 0
//                             if this is the first instance.
//             lpszCmdLine   - A long pointer to the command line that
//                             started this application.
//             cmdShow       - Indicates how the window is to be shown
//                             initially. ie. SW_SHOWNORMAL, SW_HIDE,
//                             SW_MIMIMIZE.
//
// returns:
//             wParam from last message.
//
//*******************************************************************
int PASCAL WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
						 LPSTR lpszCmdLine, int cmdShow)
{


/*
	Declarations of local variables
*/

	int control_file_number = -1 ;           // Stack pointer for control files
	FILE *control_files[MAX_CONTROL_FILES] ; // This is the stack

	char *control_line ;    // User's commands here
	char *command, *rest ;  // Pointers to its command and parameter parts
	int n_command, n_rest ; // Lengths of those parts

	int net_model = -1 ;     // Network model (see NETMOD_? in CONST.H)
	int out_model = -1 ;     // Output model (see OUTMOD_? in CONST.H)
	int n_inputs = -1 ;      // Number of input neurons
	int n_outputs = -1 ;     // Number of output neurons
	int n_hidden1 = -1 ;     // Number of hidden layer one neurons
	int n_hidden2 = -1 ;     // Ditto layer 2 (0 if just one hidden layer)


	TrainingSet *tset = NULL ;            // Training set here
	Network *network = NULL ;             // Network here
	struct LearnParams learn_params ;     // General learning parameters
	struct AnnealParams anneal_params ;   // Simulated annealing parameters
	struct GenInitParams geninit_params ; // Genetic initialization parameters
	struct KohParams koh_params ;         // Kohonen parameters

	int classif_output = -1 ;  // Current class (0=reject) for classif training
	char out_file[80] = "" ;   // File for EXECUTE output
	float threshold ;         // CLASSIFY confusion reject cutoff
	char resp_file[80]="";     // file for initializing output neuron's name
	char train_file[80]="";
/*
	Miscellaneous variables
*/

	int i, n, m ;
	float p ;
	char *msg ;
	FILE *fp ;
	unsigned long me,mc;
	char *fname;
	char *control;

#if VERSION_16_BIT
	if (sizeof(int) > 2) {
		printf ( "\nRecompile with VERSION_16_BIT set to 0 in CONST.H" ) ;
		exit ( 1 ) ;
		}
#else
	if (sizeof(int) < 4) {
		printf ( "\nRecompile with VERSION_16_BIT set to 1 in CONST.H" ) ;
		exit ( 1 ) ;
		}
#endif


printf ( "\nNEURAL SYSTEM - Program to train and test neural networks" ) ;

if (argc>1)
{
  strcpy(fname,argv[1]);
}


/*
   Process command line parameters
*/

   mem_name[0] = 0 ;  // Default is no memory allocation file
 /*
   if (strlen ( mem_name )) {
      strcat ( mem_name , ":mem.log" ) ;
      fp = fopen ( mem_name , "wt" ) ;
      if (fp == NULL) {
	 printf ( "\nCannot open debugging file %s", mem_name ) ;
	 exit ( 1 ) ;
	 }
      fclose ( fp ) ;
      mem_log = 1 ;
      }
   else
      mem_log = 0 ;
   */
   mem_log  = 0 ;
   mem_used = 0 ;
/*
   Initialize defaults
*/

   learn_params.init = -1 ;
   learn_params.quit_err = 0.0 ;
   learn_params.retries = 32767 ;

   anneal_params.temps0 = 3 ;
   anneal_params.temps = 4 ;
   anneal_params.iters0 = 50 ;
   anneal_params.iters = 20 ;
   anneal_params.setback0 = 50 ;
   anneal_params.setback = 20 ;
   anneal_params.start0 = 3.0 ;
   anneal_params.start = 4.0 ;
   anneal_params.stop0 = 1.0 ;
   anneal_params.stop = 0.02 ;

   geninit_params.pool = 50 ;
   geninit_params.gens = 3 ;
   geninit_params.climb = 0 ;
   geninit_params.overinit = 1.5 ;
   geninit_params.pcross = 0.8 ;
   geninit_params.pmutate = 0.0001 ;

   koh_params.normalization = 0 ;  // 0=multiplicative, 1=Z
   koh_params.learn_method = 1 ;   // 0=additive, 1=subtractive
   koh_params.rate = 0.4 ;         // learning rate
   koh_params.reduction = 0.99 ;   // learning rate reduction

   learn_params.ap = &anneal_params ;
   learn_params.gp = &geninit_params ;
   learn_params.kp = &koh_params ;


   act_func_init () ; // Initialize interpolation table for activation function

   MEMTEXT ( "NEURAL: control_line, msg" ) ;
   if (((control_line = (char *) MALLOC ( CONTROL_LINE_LENGTH+1 )) == NULL)
    || ((msg = (char *) MALLOC ( CONTROL_LINE_LENGTH+1 )) == NULL)) {
      printf ( "\nInsufficient memory" ) ;
      exit ( 1 ) ;
      }

/*
   Main loop processes all commands
*/

   for (;;) {
      if (argv[1])
      {
	 strcpy(control_line,"CONTROL:");
	 strcat(control_line,fname);
	 //printf("%s\n",control_line);
	 argv[1]=NULL;
      }
      else
	 get_control_line ( control_line , &control_file_number, control_files ) ;

      split_control_line ( control_line , &command , &n_command ,
			   &rest , &n_rest ) ;

      if (! n_command) {
	 if (n_rest) {
	    sprintf ( msg , "No colon after command: %s", rest ) ;
	    error_message ( msg ) ;
	    }
	 continue ;
	 }

      sprintf ( msg , "%s : %s", command, rest ) ;
      normal_message ( msg ) ;

/*
   Act on the command
*/

      if (! strcmp ( command , "QUIT" ))
	 break ;

      if (! strcmp ( command , "CONTROL" )) {
	 stack_control_file (rest, &control_file_number, control_files) ;
	 continue ;
	 }

      if (! strcmp ( command , "NETWORK MODEL" )) {
	 // Multi layer network
	 if (! strcmp ( rest , "LAYER" ))
	    n = NETMOD_LAYER ;
	 // Kohonen network
	 else if (! strcmp ( rest , "KOHONEN" ))
	    n = NETMOD_KOH ;
	 // Hopfield network
	 else if (! strcmp ( rest , "HOPFIELD" ))
	    n = NETMOD_HOP ;
	// Bidirectionnal associative memory network
	 else if (! strcmp ( rest , "BAM" ))
	    n = NETMOD_BAM ;

	 else {
	    sprintf ( msg , "Illegal NETWORK MODEL: %s", rest ) ;
	    error_message ( msg ) ;
	    continue ;
	    }
	 if (net_model == n)
	    continue ;
	 if (ok_to_clear_weights( &network )) {
	    net_model = n ;
	    learn_params.init = -1 ;
	    }
	 else
	    warning_message ( "Command aborted" ) ;
	 continue ;
	 }

      if (! strcmp ( command , "OUTPUT MODEL" )) {
	 if (! strcmp ( rest , "CLASSIFY" ))
	    n = OUTMOD_CLASSIFY ;
	 else if (! strcmp ( rest , "AUTO" ))
	    n = OUTMOD_AUTO ;
	 else if (! strcmp ( rest , "GENERAL" ))
	    n = OUTMOD_GENERAL ;
	 else {
	    sprintf ( msg , "Illegal OUTPUT MODEL: %s", rest ) ;
	    error_message ( msg ) ;
	    continue ;
	    }
	 if (out_model == n)
	    continue ;
	 if ((ok_to_clear_tset( &tset )) && (ok_to_clear_weights( &network)))
	    out_model = n ;
	 else
	    warning_message ( "Command aborted" ) ;
	 continue ;
	 }

      if (! strcmp ( command , "N INPUTS" )) {
	 m = sscanf ( rest , "%d" , &n ) ;
	 if ((m <= 0)  ||  (n <= 0)  ||  (n > MAX_INPUTS)) {
	    sprintf ( msg , "Illegal N INPUTS: %s", rest ) ;
	    error_message ( msg ) ;
	    continue ;
	    }
	 if (n_inputs == n)
	    continue ;
	 if ((ok_to_clear_tset( &tset)) && (ok_to_clear_weights(&network)))
	    n_inputs = n ;
	 else
	    warning_message ( "Command aborted" ) ;
	 continue ;
	 }

      if (! strcmp ( command , "N OUTPUTS" )) {
	 m = sscanf ( rest , "%d" , &n ) ;
	 if ((m <= 0)  ||  (n <= 0)  ||  (n > MAX_OUTPUTS)) {
	    sprintf ( msg , "Illegal N OUTPUTS: %s", rest ) ;
	    error_message ( msg ) ;
	    continue ;
	    }
	 if (n_outputs == n)
	    continue ;
	 if ((ok_to_clear_tset( &tset)) && (ok_to_clear_weights(&network)))
	    n_outputs = n ;
	 else
	    warning_message ( "Command aborted" ) ;
	 continue ;
	 }

      if (! strcmp ( command , "N HIDDEN1" )) {
	 m = sscanf ( rest , "%d" , &n ) ;
	 if ((m <= 0)  ||  (n < 0)  ||  (n > MAX_HIDDEN)) {
	    sprintf ( msg , "Illegal N HIDDEN1: %s", rest ) ;
	    error_message ( msg ) ;
	    continue ;
	    }
	 if (n_hidden1 == n)
	    continue ;
	 if (ok_to_clear_weights( &network ))
	    n_hidden1 = n ;
	 else
	    warning_message ( "Command aborted" ) ;
	 continue ;
	 }

      if (! strcmp ( command , "N HIDDEN2" )) {
	 m = sscanf ( rest , "%d" , &n ) ;
	 if ((m <= 0)  ||  (n < 0)  ||  (n > MAX_HIDDEN)) {
	    sprintf ( msg , "Illegal N HIDDEN2: %s", rest ) ;
	    error_message ( msg ) ;
	    continue ;
	    }
	 if (n  &&  ! n_hidden1) {
	    error_message ( "N HIDDEN2 must be 0 if N HIDDEN1 IS 0." ) ;
	    continue ;
	    }
	 if (n_hidden2 == n)
	    continue ;
	 if (ok_to_clear_weights( &network ))
	    n_hidden2 = n ;
	 else
	    warning_message ( "Command aborted" ) ;
	 continue ;
	 }

      if (! strcmp ( command , "TRAIN" )) {
	 if ((out_model == OUTMOD_AUTO)  &&  (n_outputs != n_inputs)) {
	    warning_message ( "Setting N OUTPUTS = N INPUTS" ) ;
	    n_outputs = n_inputs ;
	    }
	 if (out_model <= 0)
	    error_message ( "TRAIN used before OUTPUT MODEL set." ) ;
	 else if (n_inputs <= 0)
	    error_message ( "TRAIN used before N INPUTS set." ) ;
	 else if (n_outputs <= 0)
	    error_message ( "TRAIN used before N OUTPUTS set." ) ;
	 else if ((net_model == NETMOD_HOP) && (n_inputs != n_outputs))
	    error_message("HOPFIELD netowork requires INPUTS = OUTPUTS.");
	 else if ((net_model == NETMOD_BAM) && (out_model != OUTMOD_GENERAL))
	    error_message("BAM network requires AUTO output mode.");
	 else if ((net_model == NETMOD_HOP) && (out_model != OUTMOD_AUTO))
	    error_message("HOFIELD network requires AUTO output mode.");
	 else if ((net_model != NETMOD_KOH) && (out_model == OUTMOD_CLASSIFY)
		  &&  (classif_output < 0))
	    error_message( "CLASSIFY output mode but CLASSIFY OUTPUT not set.");
	 else if ((net_model == NETMOD_KOH)  &&  (out_model != OUTMOD_CLASSIFY))
	    error_message( "KOHONEN network requires CLASSIFY output mode.");
	 else {
	    if (tset == NULL) {
	       MEMTEXT ( "NEURAL: new tset" ) ;
	       tset = new TrainingSet ( out_model , n_inputs , n_outputs ) ;
	       }
	    tset->train ( rest , classif_output ) ;
	    strcpy(train_file,rest);
	 }
	 continue ;
	 }

      if (check_anneal ( command , rest , &anneal_params ))
	 continue ;

      if (check_genetic ( command , rest , &geninit_params ))
	 continue ;

      if (check_kohonen ( command , rest , &koh_params , &network ))
	 continue ;

      if (check_learn_params ( command , rest , &learn_params , net_model ))
	 continue ;

      if (! strcmp ( command , "LEARN" )) {
	 if ((tset == NULL)  ||  (tset->ntrain == 0)) {
	    error_message ( "Cannot LEARN; No training set exists." ) ;
	    continue ;
	    }
	 if ((net_model == NETMOD_KOH)  &&  (out_model != OUTMOD_CLASSIFY)) {
	    error_message( "KOHONEN network requires CLASSIFY output mode.");
	    continue ;
	    }
	 if (learn_params.init < 0) {
	    error_message( "Initialization method not set.");
	    continue ;
	    }
	 if (network == NULL)
	 {
	    if (net_model == NETMOD_LAYER)
	    {
	       if (n_hidden1 < 0)
	       {
		  error_message ( "LEARN used before N HIDDEN1 set." ) ;
		  continue ;
	       }
	       else if (n_hidden2 < 0)
	       {
		  error_message ( "LEARN used before N HIDDEN2 set." ) ;
		  continue ;
	       }
	       else
	       {
		  MEMTEXT ( "NEURAL: new LayerNet" ) ;
		  network = new LayerNet ( out_model , n_inputs , n_hidden1 ,
					   n_hidden2 , n_outputs , 1 , 1 ) ;
	       }
	    }
	    else if (net_model == NETMOD_KOH)
	    {
	       MEMTEXT ( "NEURAL: new KohNet" ) ;
	       network = new KohNet ( n_inputs , n_outputs ,
				      &koh_params , 1 , 1 ) ;
	    }
	    else if (net_model == NETMOD_HOP)
	    {

	       MEMTEXT ( "NEURAL: new HopNet" );
	       network = new HopNet (n_inputs,n_outputs, 1,1);
	    }

	    else if (net_model == NETMOD_BAM)
	    {
	       MEMTEXT ("NEURAL: new BamNet");
	       network = new LayerNet ( out_model , n_inputs , n_hidden1 ,
					n_hidden2 , n_outputs , 1 , 1 ) ;

	    }
	 }
	 if ((network == NULL)  ||  (! network->ok)) {  // Malloc failure?
	    memory_message ( "to create network." ) ;
	    if (network != NULL) {
	       delete network ;
	       network = NULL ;
	       }
	    continue ;
	    }
	 normal_message("Learning...\n");
	 network->learn ( tset , &learn_params ) ;
	 normal_message("End of Learning\n");
	 if (network->neterr > 0.999999) {  // Indicates massive failure
	    MEMTEXT ( "NEURAL: learn failure delete network" ) ;
	    delete network ;
	    network = NULL ;
	    }
	 else {
	    sprintf ( msg , "Final error = %.4lf%% of max possible",
		      100.0 * network->neterr ) ;
	    normal_message ( msg ) ;
	    }
	 continue ;
	 }

      if (! strcmp ( command , "SAVE WEIGHTS" )) {
	 if (network == NULL)
	    error_message ( "There are no learned weights to save." ) ;
	 else
	    wt_save ( network , net_model , 0 , rest ) ;
	 continue ;
	 }

      if (! strcmp ( command , "RESTORE WEIGHTS" )) {
	 if (network != NULL) {
	    MEMTEXT ( "NEURAL: delete network for restore" ) ;
	    delete network ;
	    network = NULL ;
	    }
	 network = wt_restore ( rest , &net_model ) ;
	 if (network == NULL)
	    continue ;
	 if (tset != NULL) {
	    if ((tset->nin != network->nin)
	     || (tset->nout != network->nout)
	     || (tset->outmod != network->outmod)) {
	       error_message ( "Network conflicts with existing training set.");
	       continue ;
	       }
	    }
	 out_model = network->outmod ;
	 n_inputs = network->nin ;
	 n_outputs = network->nout ;
	 if (net_model == NETMOD_LAYER) {
	    n_hidden1 = ((LayerNet*) network)->nhid1 ;
	    n_hidden2 = ((LayerNet*) network)->nhid2 ;
	    }
	 if (net_model == NETMOD_KOH)
	    koh_params.normalization = ((KohNet *) network)->normalization ;
	 learn_params.init = -1 ;
	 continue ;
	 }

      if (! strcmp ( command , "CLEAR TRAINING" )) {
	 if (tset != NULL) {
	    MEMTEXT ( "NEURAL: delete tset" ) ;
	    delete tset ;
	    tset = NULL ;
	    }
	 continue ;
	 }

      if (! strcmp ( command , "CLEAR WEIGHTS" )) {
	 if (network != NULL) {
	    MEMTEXT ( "NEURAL: delete network" ) ;
	    delete network ;
	    network = NULL ;
	    }
	 continue ;
	 }

      if (! strcmp ( command , "CLASSIFY OUTPUT" )) {
	 if (net_model == NETMOD_KOH) {
	    error_message ( "Cannot specify output for KOHONEN model." ) ;
	    continue ;
	    }
	 if (n_outputs < 0) {
	    error_message ( "CLASSIFY OUTPUT used before N OUTPUTS set." ) ;
	    continue ;
	    }
	 if (out_model != OUTMOD_CLASSIFY) {
	    error_message
		  ( "CLASSIFY OUTPUT only valid when OUTPUT MODEL:CLASSIFY" ) ;
	    continue ;
	    }
	 m = sscanf ( rest , "%d" , &n ) ;
	 if ((m <= 0)  ||  (n < 0)) {
	    sprintf ( msg , "Illegal CLASSIFY OUTPUT: %s", rest ) ;
	    error_message ( msg ) ;
	    }
	 else if (n > n_outputs) {
	    sprintf ( msg , "CLASSIFY OUTPUT (%d) exceeds N OUTPUTS (%d)",
		      n, n_outputs ) ;
	    error_message ( msg ) ;
	    }
	 else
	    classif_output = n ;
	 continue ;
	 }

      if (! strcmp ( command , "OUTPUT FILE" )) {
	 strcpy ( out_file , rest ) ;
	 continue ;
	 }

      if (! strcmp ( command , "EXECUTE" ))
      {
	 if (network == NULL)
	    error_message ( "There is no trained network" ) ;
	 else
	 {
	    network->execute_from_file ( rest , out_file) ;
	    continue ;
	 }
      }

      if (! strcmp ( command , "TEST NETWORK" ))
      {
	 if (network == NULL)
	    error_message ( "There is no trained network" ) ;
	 else
	 {
	    network->test_from_file ( rest ,out_file,net_model) ;
	    continue ;
	 }
      }

      if (! strcmp ( command , "CLASSIFY" )) {
	 if (network == NULL)
	    error_message ( "There is no trained network" ) ;
	 else if (out_model != OUTMOD_CLASSIFY)
	    error_message ( "CLASSIFY valid only in CLASSIFY output mode" ) ;
	 else
	    network->classify_from_file ( rest , threshold ) ;
	 continue ;
	 }

      if (! strcmp ( command , "RESET CONFUSION" )) {
         if (network == NULL)
            error_message ( "There is no trained network" ) ;
         else
            network->reset_confusion () ;
         continue ;
         }

      if (! strcmp ( command , "CONFUSION THRESHOLD" )) {
	 p = atof ( rest ) ;
	 if ((p < 0.0)  ||  (p > 100.0)) {
	    sprintf ( msg , "Illegal CONFUSION THRESHOLD: %s", rest ) ;
            error_message ( msg ) ;
            }
	 else
            threshold = p / 100.0 ;
         continue ;
         }

      if (! strcmp ( command , "SHOW CONFUSION" )) {
         if (network == NULL)
            error_message ( "There is no trained network" ) ;
         else if (out_model != OUTMOD_CLASSIFY)
	    error_message ( "CONFUSION valid only in CLASSIFY output mode" ) ;
         else
            network->show_confusion () ;
         continue ;
	 }

      if (! strcmp ( command , "SAVE CONFUSION" )) {
         if (network == NULL)
            error_message ( "There is no trained network" ) ;
         else if (out_model != OUTMOD_CLASSIFY)
            error_message ( "CONFUSION valid only in CLASSIFY output mode" ) ;
         else
            network->save_confusion ( rest ) ;
	 continue ;
         }

      sprintf ( msg , "Unknown command: %s", command ) ;
      error_message ( msg ) ;

      } // Endless command loop

   MEMTEXT ( "NEURAL: control_line, msg" ) ;
   FREE ( control_line ) ;
   FREE ( msg ) ;
   MEMCLOSE () ;
   exit ( 0 ) ;
}
Beispiel #17
0
int MultiBodyTree::addBody(int body_index, int parent_index, JointType joint_type,
						   const vec3 &parent_r_parent_body_ref, const mat33 &body_T_parent_ref,
						   const vec3 &body_axis_of_motion_, idScalar mass,
						   const vec3 &body_r_body_com, const mat33 &body_I_body,
						   const int user_int, void *user_ptr) {
	if (body_index < 0) {
		error_message("body index must be positive (got %d)\n", body_index);
		return -1;
	}
	vec3 body_axis_of_motion(body_axis_of_motion_);
	switch (joint_type) {
		case REVOLUTE:
		case PRISMATIC:
			// check if axis is unit vector
			if (!isUnitVector(body_axis_of_motion)) {
				warning_message(
					"axis of motion not a unit axis ([%f %f %f]), will use normalized vector\n",
					body_axis_of_motion(0), body_axis_of_motion(1), body_axis_of_motion(2));
				idScalar length = std::sqrt(std::pow(body_axis_of_motion(0), 2) +
											std::pow(body_axis_of_motion(1), 2) +
											std::pow(body_axis_of_motion(2), 2));
				if (length < std::sqrt(std::numeric_limits<idScalar>::min())) {
					error_message("axis of motion vector too short (%e)\n", length);
					return -1;
				}
				body_axis_of_motion = (1.0 / length) * body_axis_of_motion;
			}
			break;
		case FIXED:
			break;
		case FLOATING:
			break;
		default:
			error_message("unknown joint type %d\n", joint_type);
			return -1;
	}

	// sanity check for mass properties. Zero mass is OK.
	if (mass < 0) {
		m_mass_parameters_are_valid = false;
		error_message("Body %d has invalid mass %e\n", body_index, mass);
		if (!m_accept_invalid_mass_parameters) {
			return -1;
		}
	}

	if (!isValidInertiaMatrix(body_I_body, body_index, FIXED == joint_type)) {
		m_mass_parameters_are_valid = false;
		// error message printed in function call
		if (!m_accept_invalid_mass_parameters) {
			return -1;
		}
	}

	if (!isValidTransformMatrix(body_T_parent_ref)) {
		return -1;
	}

	return m_init_cache->addBody(body_index, parent_index, joint_type, parent_r_parent_body_ref,
								 body_T_parent_ref, body_axis_of_motion, mass, body_r_body_com,
								 body_I_body, user_int, user_ptr);
}
/*---------------------------------------------------------------------------------------------
 * (function: output_activation_file_ace_and_function_file)
 *	Creates the 2 files (+1 .ace file) for the power estimation.
 *	Traverses the blif_netlist, net_netlist to print out tranisition densities
 * 	and static probabilities.  Also, pushes out functions based on the clustered
 *	netlist.
 *-------------------------------------------------------------------------------------------*/
void output_activation_file_ace_and_function_file(char *output_filename, int lut_size, netlist_t *LUT_netlist, netlist_t *CLUSTER_netlist)
{
	char *ace_file_name = (char*)malloc(sizeof(char)*(strlen(output_filename)+4+1));
	char *ac2_file_name = (char*)malloc(sizeof(char)*(strlen(output_filename)+4+1));
	char *function_file_name = (char*)malloc(sizeof(char)*(strlen(output_filename)+4+1));
	int i, j, k, l;
	FILE *ace_out;
	FILE *ac2_out;
	FILE *function_out;
	long sc_spot;
	nnode_t *lut_node;
	activation_t *act_data;

	sprintf(ace_file_name, "%s.ace", output_filename);
	sprintf(ac2_file_name, "%s.ac2", output_filename);
	sprintf(function_file_name, "%s.fun", output_filename);

	ace_out = fopen(ace_file_name, "w");
	if (ace_out == NULL)
	{
		error_message(ACTIVATION_ERROR, -1, -1, "Could not open output file %s\n", ace_file_name);
	}
	ac2_out = fopen(ac2_file_name, "w");
	if (ac2_out == NULL)
	{
		error_message(ACTIVATION_ERROR, -1, -1, "Could not open output file %s\n", ac2_file_name);
	}
	function_out = fopen(function_file_name, "w");
	if (function_out == NULL)
	{
		error_message(ACTIVATION_ERROR, -1, -1, "Could not open output file %s\n", function_file_name);
	}

	/* Go through the LUT netlist and print out the ace files */
	for (i = 0; i < LUT_netlist->num_forward_levels; i++)
	{
		for (j = 0; j < LUT_netlist->num_at_forward_level[i]; j++)
		{
			/* initialize the activation data */
			nnode_t *current_node = LUT_netlist->forward_levels[i][j];
			activation_t *act_data = (activation_t*)current_node->node_data;

			if (current_node->type != OUTPUT_NODE)
			{
				for (k = 0; k < current_node->num_output_pins; k++)
				{
					if (current_node->output_pins[0]->net->num_fanout_pins != 0)
					{
						/* IF this node fans out */
						fprintf(ace_out, "%s %f %f\n", current_node->name, act_data->static_probability[k], act_data->transition_density[k]);
					}
				}
			}
			else
			{
				fprintf(ace_out, "out:%s %f %f\n", current_node->name, act_data->static_probability[0], act_data->transition_density[0]);
			}
		}
	}

	fclose(ace_out);

	/* now create the ac2 file and function file */

	/* first we spit out the clocks */
	for (i = 0; i < CLUSTER_netlist->num_clocks; i++)
	{
		nnode_t *cluster_node = CLUSTER_netlist->clocks[i];
		fprintf (ac2_out, "global_net_probability %s 0.5\n", cluster_node->name);
		fprintf (ac2_out, "global_net_density %s 2.0\n", cluster_node->name);
	}

	/* next we make the intercluster probabilities for inputs */
	for (i = 0; i < CLUSTER_netlist->num_top_input_nodes; i++)
	{
		nnode_t *cluster_node = CLUSTER_netlist->top_input_nodes[i];

		if (cluster_node->type == CLOCK_NODE)
		{
			continue;
		}

		/* find the equivalent blif point */
		if ((sc_spot = sc_lookup_string(LUT_netlist->nodes_sc, cluster_node->name)) == -1)
		{
			warning_message(ACTIVATION_ERROR, -1, -1, "Could not find %s INPUT in LUT netlist ...\n", cluster_node->name);
			continue;
		}
		lut_node = (nnode_t *)LUT_netlist->nodes_sc->data[sc_spot];	
		act_data = (activation_t*)lut_node->node_data;

		oassert(lut_node->num_output_pins == 1); /* assumption now, but will change with heterognenous blocks */
		fprintf (ac2_out, "intercluster_net_probability %s %f\n", cluster_node->name, act_data->static_probability[0]);
		fprintf (ac2_out, "intercluster_net_density %s %f\n", cluster_node->name, act_data->transition_density[0]);
	}

	/* next we make the intercluster probabilities for inputs */
	for (i = 0; i < CLUSTER_netlist->num_top_output_nodes; i++)
	{
		nnode_t *cluster_node = CLUSTER_netlist->top_output_nodes[i];

		/* find the equivalent blif point */
		if ((sc_spot = sc_lookup_string(LUT_netlist->nodes_sc, cluster_node->name)) == -1)
		{
			warning_message(ACTIVATION_ERROR, -1, -1, "Could not find %s OUTPUT in LUT netlist ...\n", cluster_node->name);
			continue;
		}
		lut_node = (nnode_t *)LUT_netlist->nodes_sc->data[sc_spot];	
		act_data = (activation_t*)lut_node->node_data;

		oassert(lut_node->num_output_pins == 0); /* assumption now, but will change with heterognenous blocks */
		fprintf (ac2_out, "intercluster_net_probability %s %f\n", (cluster_node->name+4), act_data->static_probability[0]); /* +4 to skip "out:" that isn't needed in output */
		fprintf (ac2_out, "intercluster_net_density %s %f\n", (cluster_node->name+4), act_data->transition_density[0]);
	}

	/* next we make the intercluster probabilities */
	for (i = 0; i < CLUSTER_netlist->num_internal_nodes; i++)
	{
		nnode_t *cluster_node = CLUSTER_netlist->internal_nodes[i];
		netlist_t* internal_subblocks = cluster_node->internal_netlist;

		if (internal_subblocks == NULL)
		{
			/* INPUT/OUTPUT pins and globals (clocks) have no subblocks */
			continue;
		}

		/* now we process the internal structure of the node, which represents the subblocks.  This is stored in an internall netlist. */
		for (k = 0; k < internal_subblocks->num_internal_nodes; k++)
		{
			nnode_t *current_subblock = internal_subblocks->internal_nodes[k];
			char *output_search_name = (char*)malloc(sizeof(char)*(strlen(current_subblock->name)+1+4));
			sprintf(output_search_name, "out:%s", current_subblock->name);

			if ((sc_spot = sc_lookup_string(internal_subblocks->nodes_sc, output_search_name)) != -1)
			{
				/* IF - this is an output of the cluster then we need inter cluster info */

				/* now find this node */
				/* find the equivalent blif point */
				if ((sc_spot = sc_lookup_string(LUT_netlist->nodes_sc, current_subblock->name)) == -1)
				{
					error_message(ACTIVATION_ERROR, -1, -1, "Could not find %s in LUT netlist ...\n", current_subblock->name);
				}
				lut_node = (nnode_t *)LUT_netlist->nodes_sc->data[sc_spot];
				act_data = (activation_t*)lut_node->node_data;

				/* Finally, put in th output switching values */
				fprintf (ac2_out, "intercluster_net_probability %s %f\n", current_subblock->name, act_data->static_probability[0]);
				fprintf (ac2_out, "intercluster_net_density %s %f\n", current_subblock->name, act_data->transition_density[0]);
			}

			free(output_search_name);
		}
	}

	/* next we process the subblocks */
	for (i = 0; i < CLUSTER_netlist->num_internal_nodes; i++)
	{
		nnode_t *cluster_node = CLUSTER_netlist->internal_nodes[i];
		netlist_t* internal_subblocks = cluster_node->internal_netlist;

		if (internal_subblocks == NULL)
		{
			/* INPUT/OUTPUT pins and globals (clocks) have no subblocks */
			oassert(FALSE);
			continue;
		}

		/* now we process the internal structure of the node, which represents the subblocks.  This is stored in an internall netlist. */
		for (k = 0; k < internal_subblocks->num_internal_nodes; k++)
		{
			nnode_t *current_subblock = internal_subblocks->internal_nodes[k];
			char probability_string[4096];
			char density_string[4096];
			int input_active_count = 0;
			short is_clock = FALSE;
			int input_index = 0;

			sprintf(probability_string, "subblock_probability %s", current_subblock->name);
			sprintf(density_string, "subblock_density %s", current_subblock->name);

			/* first get all the input values */
			for (l = 0; l < lut_size+1; l++)
			{
				if (current_subblock->input_pins[input_index] != NULL)
				{
					nnode_t *input_node = current_subblock->input_pins[input_index]->net->driver_pin->node;
			
					/* find the equivalent blif point */
					if ((sc_spot = sc_lookup_string(LUT_netlist->nodes_sc, input_node->name)) == -1)
					{
						error_message(ACTIVATION_ERROR, -1, -1, "Could not find %s in LUT netlist ...\n", input_node->name);
					}
					lut_node = (nnode_t *)LUT_netlist->nodes_sc->data[sc_spot];	
					act_data = (activation_t*)lut_node->node_data;
			
					if (lut_node->type == CLOCK_NODE)
					{
						/* IF - the clock spot */
						if (l == lut_size)
						{
							/* only print it out if this is the last spot */
							sprintf(probability_string, "%s %f", probability_string, act_data->static_probability[0]);
							sprintf(density_string, "%s %f", density_string,  act_data->transition_density[0]);
							is_clock = TRUE;
						}
						else
						{
							sprintf(probability_string, "%s 0.0", probability_string);
							sprintf(density_string, "%s 0.0", density_string);
						}
					}
					else
					{
						sprintf(probability_string, "%s %f", probability_string, act_data->static_probability[0]);
						sprintf(density_string, "%s %f", density_string,  act_data->transition_density[0]);

						input_index++;
					}

					input_active_count ++;
				}	
				else
				{
					/* No connection to this input */
					sprintf(probability_string, "%s 0.0", probability_string);
					sprintf(density_string, "%s 0.0", density_string);
				}
			}
			
			if (is_clock == FALSE)
			{
				/* IF - there is no clock meaning this is just a LUT, output the probabilities */
				sprintf(probability_string, "%s 0.0", probability_string);
				sprintf(density_string, "%s 0.0", density_string);
			}

			/* now find this node */
			/* find the equivalent blif point */
			if ((sc_spot = sc_lookup_string(LUT_netlist->nodes_sc, current_subblock->name)) == -1)
			{
				error_message(ACTIVATION_ERROR, -1, -1, "Could not find %s in LUT netlist ...\n", current_subblock->name);
			}
			lut_node = (nnode_t *)LUT_netlist->nodes_sc->data[sc_spot];
			act_data = (activation_t*)lut_node->node_data;

			/* find the values of the switching between LUT and FF */
			if ((lut_node->type == FF_NODE) && (input_active_count > 0))
			{
				/* LUT + FF */
				/* IF - this is a FF node and has more than 1 input, then it's a LUT-FF */
				activation_t *input_node_to_ff_act_data = (activation_t *)lut_node->input_pins[0]->net->driver_pin->node->node_data;
				sprintf(probability_string, "%s %f", probability_string, input_node_to_ff_act_data->static_probability[0]);
				sprintf(density_string, "%s %f", density_string,  input_node_to_ff_act_data->transition_density[0]);

				/* print out the function of this node based on it's inputs function */
				oassert (lut_node->input_pins[0]->net->driver_pin->node->associated_function != NULL)
				fprintf(function_out, "subblock_function %s ", lut_node->name);
		
				for (l = 0; l < pow2(lut_size); l++)
				{
					fprintf(function_out, "%d", lut_node->input_pins[0]->net->driver_pin->node->associated_function[l]);
				}
	
				fprintf(function_out, "\n");
			}
			else if (lut_node->type == FF_NODE)
			{
				/* FF */
				/* ELSE - this is a FF_NODE only */
				sprintf(probability_string, "%s 0.0", probability_string);
				sprintf(density_string, "%s 0.0", density_string);

				/* output function is just a buffer since this is just a FF */
				fprintf(function_out, "subblock_function %s ", lut_node->name);
				for (l = 0; l < pow2(lut_size); l++)
				{
					if (l % 2 == 0)
					{
						fprintf(function_out, "0");
					}
					else
					{
						fprintf(function_out, "1");
					}
				}
				fprintf(function_out, "\n");
			}
			else
			{
				/* LUT */
				/* print out the function of this node based on it's just a LUT */
				oassert (lut_node->associated_function != NULL)
				fprintf(function_out, "subblock_function %s ", lut_node->name);
		
				for (l = 0; l < pow2(lut_size); l++)
				{
					fprintf(function_out, "%d", lut_node->associated_function[l]);
				}
	
				fprintf(function_out, "\n");
			}

			/* Finally, put in th output switching values */
			sprintf(probability_string, "%s %f", probability_string, act_data->static_probability[0]);
			sprintf(density_string, "%s %f", density_string,  act_data->transition_density[0]);

			/* output the values created for the subblock */
			fprintf(ac2_out, "%s\n", probability_string);
			fprintf(ac2_out, "%s\n", density_string);
		}
	}

	fclose(function_out);
	fclose(ac2_out);
}