Пример #1
0
bool NeuronFactory::close() {

    std::map<Neuron*, std::string>::iterator n_iter;

    for (n_iter = this->models.begin(); n_iter != this->models.end(); ++n_iter) {
        void* handle = dlopen(n_iter->second.c_str(), RTLD_LAZY);
        if (!handle) {
            std::cerr << "Cannot load library: " << dlerror() << std::endl;
            return false;
        }

        // reset errors
        dlerror();

        // load the symbols
        destroy_t* destroy_model = (destroy_t*) dlsym(handle, "destroy");
        const char* dlsym_error = dlerror();
        if (dlsym_error) {
            std::cerr << "Cannot load symbol create: " << dlsym_error << std::endl;
            std::cerr << "This does not appear to be a valid dtnet neuron model library." << std::endl;
            return false;
        }

        destroy_model(n_iter->first);
    }

    std::map<std::string, void*>::iterator h_iter;
    for (h_iter = this->handles.begin(); h_iter != this->handles.end(); ++h_iter) {
        dlclose(h_iter->second);
    }

    return true;
}
Пример #2
0
int main(int argc, char **argv)
{
	char input_file_name[1024];
	char model_file_name[1024];
	const char *error_msg;

	parse_command_line(argc, argv, input_file_name, model_file_name);
	read_problem(input_file_name);
	error_msg = check_parameter(&prob,&param);

	if(error_msg)
	{
		fprintf(stderr,"Error: %s\n",error_msg);
		exit(1);
	}

	if(flag_cross_validation)
	{
		do_cross_validation();
	}
	else
	{
		model_=train(&prob, &param);
		save_model(model_file_name, model_);
		destroy_model(model_);
	}
	destroy_param(&param);
	free(prob.y);
	free(prob.x);
	free(x_space);
	free(line);

	return 0;
}
/**
 * Destroys a part and removes it from the knowledge model.
 *
 * Primitive models need a different creation than compound models.
 *
 * persistent:
 * - stored permanently
 * - outside CYBOI
 * - longer than CYBOI lives
 *
 * transient:
 * - stored in computer memory (RAM)
 * - only accessible from within CYBOI
 * - created and destroyed by CYBOI
 * - not available anymore after CYBOI has been destroyed
 *
 * Expected parameters:
 * - model (required): the knowledge model to be destroyed
 *
 * @param p0 the parameters
 * @param p1 the parameters count
 * @param p2 the knowledge
 * @param p3 the knowledge count
 * @param p4 the knowledge size
 */
void memorise_destructing(void* p0, void* p1, void* p2, void* p3, void* p4) {

    log_terminated_message((void*) INFORMATION_LEVEL_LOG_MODEL, (void*) L"Destroy knowledge model.");

    // The knowledge model name name, abstraction, model, details.
    void** nn = NULL_POINTER_MEMORY_MODEL;
    void** nnc = NULL_POINTER_MEMORY_MODEL;
    void** nns = NULL_POINTER_MEMORY_MODEL;
    void** na = NULL_POINTER_MEMORY_MODEL;
    void** nac = NULL_POINTER_MEMORY_MODEL;
    void** nas = NULL_POINTER_MEMORY_MODEL;
    void** nm = NULL_POINTER_MEMORY_MODEL;
    void** nmc = NULL_POINTER_MEMORY_MODEL;
    void** nms = NULL_POINTER_MEMORY_MODEL;
    void** nd = NULL_POINTER_MEMORY_MODEL;
    void** ndc = NULL_POINTER_MEMORY_MODEL;
    void** nds = NULL_POINTER_MEMORY_MODEL;

    // Get knowledge model name.
    get_universal_compound_element_by_name(
        (void*) &nn, (void*) &nnc, (void*) &nns,
        (void*) &na, (void*) &nac, (void*) &nas,
        (void*) &nm, (void*) &nmc, (void*) &nms,
        (void*) &nd, (void*) &ndc, (void*) &nds,
        p0, p1,
        (void*) MODEL_DESTROY_MEMORY_OPERATION_CYBOL_NAME, (void*) MODEL_DESTROY_MEMORY_OPERATION_CYBOL_NAME_COUNT,
        p2, p3);

    // The knowledge model name, abstraction, model, details.
    void** en = NULL_POINTER_MEMORY_MODEL;
    void** enc = NULL_POINTER_MEMORY_MODEL;
    void** ens = NULL_POINTER_MEMORY_MODEL;
    void** ea = NULL_POINTER_MEMORY_MODEL;
    void** eac = NULL_POINTER_MEMORY_MODEL;
    void** eas = NULL_POINTER_MEMORY_MODEL;
    void** em = NULL_POINTER_MEMORY_MODEL;
    void** emc = NULL_POINTER_MEMORY_MODEL;
    void** ems = NULL_POINTER_MEMORY_MODEL;
    void** ed = NULL_POINTER_MEMORY_MODEL;
    void** edc = NULL_POINTER_MEMORY_MODEL;
    void** eds = NULL_POINTER_MEMORY_MODEL;

    // Get knowledge model.
    get_universal_compound_element_by_name(
        (void*) &en, (void*) &enc, (void*) &ens,
        (void*) &ea, (void*) &eac, (void*) &eas,
        (void*) &em, (void*) &emc, (void*) &ems,
        (void*) &ed, (void*) &edc, (void*) &eds,
        p2, p3,
        (void*) *nm, (void*) *nmc,
        p2, p3);

    // Destroy knowledge model.
    destroy_model(em, *emc, *ems , *ea, *eac);

    // Remove knowledge model from given whole model.
    remove_compound_element_by_name(p2, p3, p4, *NULL_POINTER_MEMORY_MODEL, *NULL_POINTER_MEMORY_MODEL, *NULL_POINTER_MEMORY_MODEL, (void*) *nm, (void*) *nmc);
}
Пример #4
0
int main(int argc, char **argv)
{
	FILE *input, *output;
	int i;

	// parse options
	for(i=1;i<argc;i++)
	{
		if(argv[i][0] != '-') break;
		++i;
		switch(argv[i-1][1])
		{
			case 'b':
				flag_predict_probability = atoi(argv[i]);
				break;

			default:
				fprintf(stderr,"unknown option\n");
				exit_with_help();
				break;
		}
	}
	if(i>=argc)
		exit_with_help();

	input = fopen(argv[i],"r");
	if(input == NULL)
	{
		fprintf(stderr,"can't open input file %s\n",argv[i]);
		exit(1);
	}

	output = fopen(argv[i+2],"w");
	if(output == NULL)
	{
		fprintf(stderr,"can't open output file %s\n",argv[i+2]);
		exit(1);
	}

	if((model_=load_model(argv[i+1]))==0)
	{
		fprintf(stderr,"can't open model file %s\n",argv[i+1]);
		exit(1);
	}

	line = (char *) malloc(max_line_len*sizeof(char));
	x = (struct feature_node *) malloc(max_nr_attr*sizeof(struct feature_node));
	do_predict(input, output, model_);
	destroy_model(model_);
	free(line);
	free(x);
	fclose(input);
	fclose(output);
	return 0;
}
Пример #5
0
void destroy_scene(struct scene * scene) {

	uint32_t i;

	if (!scene) return;
	if (scene->objects) {
		for(i = 0; i < scene->objects_len; i++) {
			destroy_model(scene->objects[i].model);
		}
		free(scene->objects);
	}
	free(scene);
}
/**
 * Destroys a compound model.
 *
 * @param p0 the model
 * @param p1 the model count
 * @param p2 the model size
 * @param p3 the model abstraction
 * @param p4 the model abstraction count
 */
void destroy_compound_model(void** model, void* model_count, void* model_size,
    void* model_abstr, void* model_abstr_count) {

    // das gesamte Compound durchgehen und f?r jedes Element im Compound wieder destroy model aufrufen

    int compound_counter = *NUMBER_0_INTEGER_MEMORY_MODEL;

    // The element name.
    void** en = NULL_POINTER_MEMORY_MODEL;
    void** enc = NULL_POINTER_MEMORY_MODEL;
    void** ens = NULL_POINTER_MEMORY_MODEL;
    // The element abstraction.
    void** ea = NULL_POINTER_MEMORY_MODEL;
    void** eac = NULL_POINTER_MEMORY_MODEL;
    void** eas = NULL_POINTER_MEMORY_MODEL;
    // The element model.
    void** em = NULL_POINTER_MEMORY_MODEL;
    void** emc = NULL_POINTER_MEMORY_MODEL;
    void** ems = NULL_POINTER_MEMORY_MODEL;
    // The element details.
    void** ed = NULL_POINTER_MEMORY_MODEL;
    void** edc = NULL_POINTER_MEMORY_MODEL;
    void** eds = NULL_POINTER_MEMORY_MODEL;

    while (*NUMBER_1_INTEGER_MEMORY_MODEL) {

        if (compound_counter >= *((int*) model_count)) {

            break;
        }

        // Get element.
        get_compound_element_by_index(*model, model_count, (void*) &compound_counter,
            (void*) &en, (void*) &enc, (void*) &ens,
            (void*) &ea, (void*) &eac, (void*) &eas,
            (void*) &em, (void*) &emc, (void*) &ems,
            (void*) &ed, (void*) &edc, (void*) &eds);

        destroy_model(em, *emc, *ems, *ea, *eac);

        compound_counter = compound_counter + *NUMBER_1_INTEGER_MEMORY_MODEL;
    }
}
Пример #7
0
// Interface function of matlab
// now assume prhs[0]: label prhs[1]: features
int main(int argc, char **argv)
{
	const char *error_msg;
	// fix random seed to have same results for each run
	// (for cross validation)
	srand(1);

	char input_file_name[1024];
	char model_file_name[1024];

   
	parse_command_line(argc, argv, input_file_name, model_file_name);
	read_problem(input_file_name);
	error_msg = check_parameter(&prob,&param);
	if(error_msg)
	{
		fprintf(stderr,"Error: %s\n",error_msg);
		destroy_param(&param);
		free(prob.y);
		free(prob.x);
		free(x_space);
		exit(1);
	}

	if(cross_validation_flag)
	{
		do_cross_validation();
	}
	else
	{
		model_=FGM_train(&prob, &param);
		printf("training is done!\n");
		save_model_poly(model_file_name, model_);
		printf("model is saved!\n");
		destroy_model(model_);
	}
        destroy_param(&param);
		free(prob.y);
		free(prob.x);
		free(x_space);
		
}
Пример #8
0
void mexFunction( int nlhs, mxArray *plhs[],
		int nrhs, const mxArray *prhs[] )
{
	int prob_estimate_flag = 0;
	struct model *model_;
	char cmd[CMD_LEN];
	col_format_flag = 0;

	if(nrhs > 5 || nrhs < 3)
	{
		exit_with_help();
		fake_answer(plhs);
		return;
	}
	if(nrhs == 5)
	{
		mxGetString(prhs[4], cmd, mxGetN(prhs[4])+1);
		if(strcmp(cmd, "col") == 0)
		{			
			col_format_flag = 1;
		}
	}

	if(mxIsStruct(prhs[2]))
	{
		const char *error_msg;

		// parse options
		if(nrhs>=4)
		{
			int i, argc = 1;
			char *argv[CMD_LEN/2];

			// put options in argv[]
			mxGetString(prhs[3], cmd,  mxGetN(prhs[3]) + 1);
			if((argv[argc] = strtok(cmd, " ")) != NULL)
				while((argv[++argc] = strtok(NULL, " ")) != NULL)
					;

			for(i=1;i<argc;i++)
			{
				if(argv[i][0] != '-') break;
				if(++i>=argc)
				{
					exit_with_help();
					fake_answer(plhs);
					return;
				}
				switch(argv[i-1][1])
				{
					case 'b':
						prob_estimate_flag = atoi(argv[i]);
						break;
					default:
						mexPrintf("unknown option\n");
						exit_with_help();
						fake_answer(plhs);
						return;
				}
			}
		}

		model_ = Malloc(struct model, 1);
		error_msg = matlab_matrix_to_model(model_, prhs[2]);
		if(error_msg)
		{
			mexPrintf("Error: can't read model: %s\n", error_msg);
			destroy_model(model_);
			fake_answer(plhs);
			return;
		}

		if(prob_estimate_flag)
		{
			if(model_->param.solver_type!=L2_LR)
			{
				mexPrintf("probability output is only supported for logistic regression\n");
				prob_estimate_flag=0;
			}
		}

		if(mxIsSparse(prhs[1]))
			do_predict(plhs, prhs, model_, prob_estimate_flag);
		else
		{
			mexPrintf("Testing_instance_matrix must be sparse\n");
			fake_answer(plhs);
		}

		// destroy model_
		destroy_model(model_);
	}
	else
	{
Пример #9
0
/**
 * The main entry function.
 *
 * Command line arguments have to be in order:
 * - command (cyboi)
 * - abstraction (compound|operation)
 * - location (inline|file|ftp|http)
 * - model (a compound model or primitive operation, for example: exit or model.submodel)
 *
 * Usage:
 * cyboi compound|operation inline|file|ftp|http model.submodel
 *
 * Example 1 (starts up and right away shuts down the system):
 * cyboi operation inline exit
 *
 * Example 2 (calls the startup routine of some application):
 * cyboi compound file /application/logic/startup.cybol
 *
 * The main function follows a system lifecycle to start up,
 * run and shut down the CYBOI system, in the following order:
 * 1 initialize global variables
 * 2 create statics (state/ logic knowledge container etc.)
 * 3 create startup signal and add to signal memory
 * 4 run dynamics (signal waiting loop)
 * 5 destroy startup signal
 * 6 destroy statics (state/ logic knowledge container etc.)
 *
 * @param p0 the argument count (argc)
 * @param p1 the argument vector (argv)
 * @return the return value
 */
int main(int p0, char** p1) {

    // Return 1 to indicate an error, by default.
    int r = 1;

    //
    // Global variables.
    //

    // Initialize global variables.
    // CAUTION!
    // They have to be initialized before the command line parameter check below!
    // Otherwise, the logger may not be able to log possible error messages.
    initialize_global_variables();

    //
    // Testing.
    //

    // Call testing procedures.
    // Comment/ uncomment this as needed.
    // CAUTION!
    // This has to stand AFTER the initialization of the
    // global variables because these are used by the testing code.
//    test();
//    return 0;

    if (p1 != NULL_POINTER) {

        if (p0 == STARTUP_PARAMETERS_COUNT) {

            //
            // Knowledge container.
            //

            // The knowledge container and its count and size.
            void* k = NULL_POINTER;
            int kc = 0;
            int ks = 0;

            // Create knowledge container.
            create_compound((void*) &k, (void*) &ks);

            //
            // Internals container.
            //

            // The internals container and its count and size.
            void* i = NULL_POINTER;
            int ic = 0;
            int is = 0;

            // Create internals container.
//??            create_internals((void*) &i, (void*) &ic, (void*) &is);

            //
            // Signal container.
            //

            // The signal container and its count and size.
            void* s = NULL_POINTER;
            int sc = 0;
            int ss = 0;

            // Create signal container.
            create_signal_memory((void*) &s, (void*) &ss);

            //
            // Startup model.
            //

            // Initialize persistent part abstraction, location, model
            // and their counts and sizes.
            void* ppa = (void*) p1[ABSTRACTION_STARTUP_PARAMETER_INDEX];
            int ppac = strlen(p1[ABSTRACTION_STARTUP_PARAMETER_INDEX]);
            int ppas = ppac;
            void* ppl = (void*) p1[LOCATION_STARTUP_PARAMETER_INDEX];
            int pplc = strlen(p1[LOCATION_STARTUP_PARAMETER_INDEX]);
            int ppls = pplc;
            void* ppm = (void*) p1[MODEL_STARTUP_PARAMETER_INDEX];
            int ppmc = strlen(p1[MODEL_STARTUP_PARAMETER_INDEX]);
            int ppms = ppmc;

            // Initialize transient part abstraction, model
            // and their counts and sizes.
            // CAUTION! A transient location is not stored,
            // since that is only needed temporarily
            // for model loading.
            void* tpa = NULL_POINTER;
            int tpac = 0;
            int tpas = 0;
            void* tpm = NULL_POINTER;
            int tpmc = 0;
            int tpms = 0;

            // Create transient part abstraction, model
            // and their counts and sizes.
            interpret_model((void*) &tpa, (void*) &tpac, (void*) &tpas,
                (void*) &ppa, (void*) &ppac,
                (void*) &STRING_ABSTRACTION, (void*) &STRING_ABSTRACTION_COUNT);
            interpret_located_model((void*) &tpm, (void*) &tpmc, (void*) &tpms,
                (void*) &ppa, (void*) &ppac,
                (void*) &ppl, (void*) &pplc,
                (void*) &ppm, (void*) &ppmc);

            //
            // Startup signal.
            //

            // Add startup signal to signal memory.
            set_signal((void*) &s, (void*) &sc, (void*) &ss,
                (void*) &tpm, (void*) &tpmc,
                (void*) &NORMAL_PRIORITY,
                (void*) &tpa, (void*) &tpac);

            //
            // Waiting loop.
            //

            // The system is now started up and complete so that a loop
            // can be entered, waiting for signals (events/ interrupts)
            // which are stored/ found in the signal memory.
            // The loop is left as soon as its shutdown flag is set.
            wait((void*) &s, (void*) &sc, (void*) &ss,
                (void*) &k, (void*) &kc, (void*) &ks,
                (void*) &i, (void*) &ic, (void*) &is);

            //
            // Destruction.
            //

            //?? Do not forget to destroy startup abstraction etc. HERE!

            // Destroy startup model.
            destroy_model((void*) &tpm, (void*) &tpmc, (void*) &tpms,
                (void*) &NULL_POINTER, (void*) &NULL_POINTER, (void*) &NULL_POINTER,
                (void*) &tpa, (void*) &tpac,
                (void*) &tpa, (void*) &tpac,
                (void*) &tpm, (void*) &tpmc,
                (void*) &NULL_POINTER, (void*) &NULL_POINTER,
                (void*) &NULL_POINTER, (void*) &NULL_POINTER,
                (void*) &NULL_POINTER, (void*) &NULL_POINTER);

            // Destroy signal container.
            destroy_signal_memory((void*) &s, (void*) &ss);

            // Destroy internals container.
//??            destroy_internals((void*) &i, (void*) &ic, (void*) &is);

            // Destroy knowledge container.
            destroy_compound((void*) &k, (void*) &ks);

            log_message((void*) &INFO_LOG_LEVEL, (void*) &EXIT_CYBOI_NORMALLY_MESSAGE, (void*) &EXIT_CYBOI_NORMALLY_MESSAGE_COUNT);

            // Return 0 to indicate proper shutdown.
            r = 0;

        } else {

            log_message((void*) &ERROR_LOG_LEVEL, (void*) &COULD_NOT_EXECUTE_CYBOI_THE_COMMAND_LINE_ARGUMENT_NUMBER_IS_INCORRECT_MESSAGE, (void*) &COULD_NOT_EXECUTE_CYBOI_THE_COMMAND_LINE_ARGUMENT_NUMBER_IS_INCORRECT_MESSAGE_COUNT);
            log_message((void*) &INFO_LOG_LEVEL, (void*) &USAGE_MESSAGE, (void*) &USAGE_MESSAGE_COUNT);
        }

    } else {

        log_message((void*) &ERROR_LOG_LEVEL, (void*) &COULD_NOT_EXECUTE_CYBOI_THE_COMMAND_LINE_ARGUMENT_VECTOR_IS_NULL_MESSAGE, (void*) &COULD_NOT_EXECUTE_CYBOI_THE_COMMAND_LINE_ARGUMENT_VECTOR_IS_NULL_MESSAGE_COUNT);
    }

    return r;
}
Пример #10
0
// Interface function of matlab
// now assume prhs[0]: label prhs[1]: features
void mexFunction( int nlhs, mxArray *plhs[],
		int nrhs, const mxArray *prhs[] )
{
	const char *error_msg;
	// fix random seed to have same results for each run
	// (for cross validation)
	srand(1);

	// Transform the input Matrix to libsvm format
	if(nrhs > 0 && nrhs < 5)
	{
		int err=0;

		if(!mxIsDouble(prhs[0]) || !mxIsDouble(prhs[1])) {
			mexPrintf("Error: label vector and instance matrix must be double\n");
			fake_answer(plhs);
			return;
		}

		if(parse_command_line(nrhs, prhs, NULL))
		{
			exit_with_help();
			destroy_param(&param);
			fake_answer(plhs);
			return;
		}

		if(mxIsSparse(prhs[1]))
			err = read_problem_sparse(prhs[0], prhs[1]);
		else
		{
			mexPrintf("Training_instance_matrix must be sparse\n");
			destroy_param(&param);
			fake_answer(plhs);
			return;
		}

		// train's original code
		error_msg = check_parameter(&prob, &param);

		if(err || error_msg)
		{
			if (error_msg != NULL)
				mexPrintf("Error: %s\n", error_msg);
			destroy_param(&param);
			free(prob.y);
			free(prob.x);
			free(x_space);
			fake_answer(plhs);
			return;
		}

		if(cross_validation_flag)
		{
			double *ptr;
			plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL);
			ptr = mxGetPr(plhs[0]);
			ptr[0] = do_cross_validation();
		}
		else
		{
			const char *error_msg;

			model_ = train(&prob, &param);
			error_msg = model_to_matlab_structure(plhs, model_);
			if(error_msg)
				mexPrintf("Error: can't convert libsvm model to matrix structure: %s\n", error_msg);
			destroy_model(model_);
		}
		destroy_param(&param);
		free(prob.y);
		free(prob.x);
		free(x_space);
	}
	else
	{
		exit_with_help();
		fake_answer(plhs);
		return;
	}
}
Пример #11
0
//void copy_parameter(param_temp,&param)
//{
//	param_t
//}
// Interface function of matlab
// now assume prhs[0]: label prhs[1]: features
int main(int argc, char **argv)
{
	const char *error_msg;
	// fix random seed to have same results for each run
	// (for cross validation)
	srand(1);

	char input_file_name[1024];
	char model_file_name[1024];
	char param_file_name[1024];

    
	int n_flag = 0;
	parse_command_line(argc, argv, input_file_name, model_file_name,n_flag,param_file_name);
	char char_para;
	int length_param = 0;
	double *para_entry; // 
	//n_flag = 1;
	//int para_B[20] = {2, 3, 4, 5, 6, 7, 8, 9, 10, 12,14,16, 18, 20, 25, 30,35,40,45,50};
	int para_B[40] = {2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 16, 18, 20, 24, 25, 26, 30,32, 35, 38, 40, 42, 45, 48, 50, 55, 60, 65,70,75,80, 85, 90, 95, 100, 105, 110, 115, 120};
	//int para_B[32] = { 20, 24, 25, 26, 30,32, 35, 38, 40, 42, 45, 48, 50, 55,  60, 80, 100, 120, 140, 160, 180, 200, 220, 240, 260, 280};

	if (n_flag==1)
	{
		read_parameter(param_file_name, para_entry, char_para, length_param);
	}

	read_problem(input_file_name);
	


	error_msg = check_parameter(&prob,&param);
//parameter *param_temp = new parameter[1];
//copy_parameter(param_temp,&param);
	if(error_msg)
	{
		fprintf(stderr,"Error: %s\n",error_msg);
		exit(1);
	}

	if(cross_validation_flag)
	{
		do_cross_validation();
	}
	else
	{
		if(n_flag==0)
		{
			model_ = FGM_train(&prob, &param);
			printf("training is done!\n");
			save_model_poly(model_file_name, model_);
			printf("model is saved!\n");
			destroy_model(model_);
		}
		else
		{
			int i;
			if (char_para=='C')
			{
				length_param = length_param;
			}else
			{
				length_param = 40;
			}
			for (i=0;i<length_param;i++)
			{
				char param_char[1000];
			    char model_file[1024];
				strcpy(model_file,model_file_name);
				if (char_para=='C')
				{
					param.C = para_entry[i];
					sprintf(param_char, "%.10lf ", para_entry[i]); 
					strcat(model_file,".c.");
					strcat(model_file,param_char);
				    model_=FGM_train(&prob, &param);
				}
				else
				{
					int B = para_B[i];
					param.B = B;
					sprintf(param_char, "%d ", param.B); 
					printf("%d\n ", param.B); 
					strcat(model_file,".B.");
					strcat(model_file,param_char);
				    model_=FGM_train(&prob, &param);
				}
				
				printf("training is done!\n");
				save_model_poly(model_file, model_);
				printf("model is saved!\n");
				destroy_model(model_);
				if(model_->feature_pair>600)
				{
					break;
				}
			}
		}

	}
	if (n_flag==1)
	{
		delete []para_entry;
	}
	
	destroy_param(&param);
	free(prob.y);
	free(prob.x);
	free(x_space);

}
Пример #12
0
void mexFunction( int nlhs, mxArray *plhs[],
		int nrhs, const mxArray *prhs[] )
{
	const char *error_msg;
	srand(1);

	if(nrhs == 7) /* force alphas_in and w_in to be initialized */
	{
		int err=0;

		if(!mxIsClass(prhs[0], "single") || !mxIsClass(prhs[1], "single") || !mxIsClass(prhs[4], "single") || !mxIsClass(prhs[4], "single") || !mxIsClass(prhs[6], "single")) {
			mexPrintf("Error: label vector, instance matrix and alphas_in must be float\n");
			fake_answer(plhs);
			return;
		}

		if(parse_command_line(nrhs, prhs, NULL))
		{
			exit_with_help();
			destroy_param(&param);
			fake_answer(plhs);
			return;
		}
#ifdef _DENSE_REP
		if(!mxIsSparse(prhs[1]))
			err = read_problem_sparse(prhs[0], prhs[1], prhs[4], prhs[5], prhs[6]);
		else
		{
			mexPrintf("Training_instance_matrix must be dense\n");
			destroy_param(&param);
			fake_answer(plhs);
			return;
		}
#else
		if(mxIsSparse(prhs[1]))
			err = read_problem_sparse(prhs[0], prhs[1], prhs[4]);
		else
		{
			mexPrintf("Training_instance_matrix must be sparse\n");
			destroy_param(&param);
			fake_answer(plhs);
			return;
		}
#endif

		error_msg = check_parameter(&prob, &param);

		if(err || error_msg)
		{
			if (error_msg != NULL)
				mexPrintf("Error: %s\n", error_msg);
			destroy_param(&param);
			free(prob.y);
			free(prob.x);
            free(prob.alphas_in);
            free(prob.w_in);
			/*free(x_space);*/
			fake_answer(plhs);
			return;
		}
        
		if(cross_validation_flag)
		{
			float *ptr;
			plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL);
			ptr = (float*) mxGetPr(plhs[0]);
			ptr[0] = do_cross_validation();
		}
		else
		{            
			const char *error_msg;
			model_ = train(&prob, &param);            
            
			error_msg = model_to_matlab_structure(plhs, model_);            
            
			if(error_msg)
				mexPrintf("Error: can't convert libsvm model to matrix structure: %s\n", error_msg);
            
			destroy_model(model_);
		}
		destroy_param(&param);
		free(prob.y);
		free(prob.x);
        free(prob.alphas_in);
        free(prob.w_in);
		/*free(x_space);*/
	}
	else
	{
		exit_with_help();
		fake_answer(plhs);
		return;
	}
}
Пример #13
0
// Interface function of matlab
// now assume prhs[0]: label prhs[1]: features
void mexFunction( int nlhs, mxArray *plhs[],
		int nrhs, const mxArray *prhs[] )
{
	const char *error_msg;
	// fix random seed to have same results for each run
	// (for cross validation)
	srand(1);

	// Transform the input Matrix to libsvm format
	if(nrhs > 0 && nrhs <= 5)
	{
		int err=0;

		//if(!mxIsDouble(prhs[0]) || !mxIsDouble(prhs[1])) {
		if(!mxIsDouble(prhs[0])) {
			mexPrintf("Error: label vector and instance matrix must be double\n");
			fake_answer(plhs);
			return;
		}

		if(parse_command_line(nrhs, prhs, NULL))
		{
			exit_with_help();
			destroy_param(&param);
			fake_answer(plhs);
			return;
		}
#ifdef DEBUG
	mexPrintf("reading problem sparse...\n");
	mexEvalString("drawnow");
	wait(5);
#endif

#ifdef _DENSE_REP
		if(!mxIsSparse(prhs[1]))
			err = read_problem_sparse(prhs[0], prhs[1]);
		else
		{
			mexPrintf("Training_instance_matrix must be dense\n");
			destroy_param(&param);
			fake_answer(plhs);
			return;
		}
#else
		if(mxIsSparse(prhs[1]))
			err = read_problem_sparse(prhs[0], prhs[1]);
		else
		{
			mexPrintf("Training_instance_matrix must be sparse\n");
			destroy_param(&param);
			fake_answer(plhs);
			return;
		}
#endif

#ifdef DEBUG
	mexPrintf("read_problem_sparse done.\n");
	mexEvalString("drawnow");
	wait(5);
#endif

		// xren: delete the input instance matrix to free up space
		if (nrhs==5) {
			mxArray* var=(mxArray*)prhs[4];
			int status=mexCallMATLAB(0,NULL,1, &var, "clear");
			if (status!=0) mexPrintf("Failed to delete variable %s\n",mxArrayToString(prhs[4]));
			//mxDestroyArray( (mxArray*)prhs[1] );
		}
#ifdef DEBUG
	mexPrintf("free memory done.\n");
	mexEvalString("drawnow");
	wait(5);
#endif
		// train's original code
		error_msg = check_parameter(&prob, &param);

		if(err || error_msg)
		{
			if (error_msg != NULL)
				mexPrintf("Error: %s\n", error_msg);
			destroy_param(&param);
			free(prob.y);
			free(prob.x);
			free(x_space);
			fake_answer(plhs);
			return;
		}
        
		if(cross_validation_flag)
		{
			double *ptr;
			plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL);
			ptr = mxGetPr(plhs[0]);
			ptr[0] = do_cross_validation();
		}
		else
		{
			const char *error_msg;
			model_ = train(&prob, &param);
			error_msg = model_to_matlab_structure(plhs, model_);
			if(error_msg)
				mexPrintf("Error: can't convert libsvm model to matrix structure: %s\n", error_msg);
			destroy_model(model_);
		}
		destroy_param(&param);
		free(prob.y);
		free(prob.x);
		free(x_space);
	}
	else
	{
		exit_with_help();
		fake_answer(plhs);
		return;
	}
}
Пример #14
0
int main(int argc, char *argv[])
{
    char *infile,*outfile;
	int i, nt=1, report_level=1;
	
	/* TODO. Parsing of input with error checking. 
	   Input syntax on form: -numtraj=4 etc. ?*/
	
	if (argc < 3){
		printf("To few arguments to nsm.");
	    exit(-1);	
	}
	
	/* Input file. */
	infile  = argv[1];
	
	/* Output file (or directory). */
	outfile = argv[2]; 
	
	/* Read model specification */
	urdme_model *model;
	model = read_model(infile);
	model->infile = infile;
	
	if (model == NULL){
		printf("Fatal error. Couldn't load model file or currupt model file.");
		return(-1);
	}
	
    /*reopen MAT file*/
    MATFile *input_file;
    mxArray *temp,*sopts;

    input_file = matOpen(infile,"r");
    if (input_file == NULL){
        printf("Failed to open mat-file.\n");
        return(-1);   
    }

	/* Initialize RNG(s).  */
    /* Look for seed */
    temp = matGetVariable(input_file, "seed");

    /* Initialize rng from GSL. */
    const gsl_rng_type * T;
    T = gsl_rng_taus2;
    gsl_rng_env_setup();
    runif = gsl_rng_alloc (T);
    //gsl_rng_set (runif, 463728648);  //Why would we seed the name number each time??

    long int seed;
    /* If seed is provided as a parameter, it takes precedence. */
    if (argc > 3) {
        srand48((long int)atoi(argv[3]));
        gsl_rng_set(runif,(long int)atoi(argv[3]));
    }else if(temp != NULL){
        seed = (long int) mxGetScalar(temp);
        srand48(seed);
        gsl_rng_set(runif,seed);
    }else{
		/* Not a foolproof solution */
        //srand48((long int)time(NULL)+(long int)(1e9*clock()));
        srand48( time(NULL) * getpid() );
        gsl_rng_set(runif,time(NULL) * getpid());
    }
	
	/* Look for an optional parameter matrix. */
	const double *matfile_parameters; 
	int mpar = 0;
	int npar = 0;
	int param_case=0;
	
    temp = matGetVariable(input_file, "parameters");
	if (temp != NULL) {
		matfile_parameters = (double *)mxGetPr(temp);
		mpar = mxGetM(temp);
		npar = mxGetN(temp); 
	}
	
	/* Look if a parameter case if supplied as a parameter. */
	if (argc > 4) {
	    param_case = (int)atoi(argv[4]);
	}
	
	if (param_case > npar ) {
		printf("nsmcore: Fatal error, parameter case is larger than n-dimension in parameter matrix.\n");
		exit(-1);
	}
	
	/* Create global parameter variable for this parameter case. */
	parameters = (double *)malloc(mpar*sizeof(double));
	memcpy(parameters,&matfile_parameters[npar*param_case],mpar*sizeof(double));
	
    /* Initialize extra args */
	model->num_extra_args = 4;
	model->extra_args=malloc(model->num_extra_args*sizeof(void *));
	
	/* Set report level */
    temp = matGetVariable(input_file, "report");
   
    if (temp != NULL)
        report_level = (int) mxGetScalar(temp);
    else
        if (nt > 1)
            report_level=0;
        else
            report_level=1;

	model->extra_args[0] = malloc(sizeof(int));
	*(int *)(model->extra_args[0]) = report_level;

    /* Set tau_d */
    sopts = matGetVariable(input_file, "sopts");
    if(sopts==NULL){
        printf("Step length (tau_d) is missing in the model file\n");
        return(-1);   
    }
    model->extra_args[1] = malloc(sizeof(double));
    model->extra_args[2] = malloc(sizeof(double));
    model->extra_args[3] = malloc(sizeof(double));
    double*sopts_tmp = mxGetPr(sopts);
    //printf("HERE: tau_d=%e\n",sopts_tmp[0]);
    //printf("HERE: max_jump=%e\n",sopts_tmp[1]);
    //printf("HERE: err_tol=%e\n",sopts_tmp[2]);
    *(double*)model->extra_args[1] = sopts_tmp[0];
    *(double*)model->extra_args[2] = sopts_tmp[1];
    *(double*)model->extra_args[3] = sopts_tmp[2];
    //printf("HERE: tau_d=%e\n",*(double *)(model->extra_args[1]));
    //printf("HERE: max_jump=%e\n",*(double *)(model->extra_args[2]));
    //printf("HERE: err_tol=%e\n",*(double *)(model->extra_args[3]));
    /* close MAT file*/
    matClose(input_file);

	/* Allocate memory to hold nt solutions. */
	init_sol(model,nt);

    /* Get a writer to store the output trajectory on a hdf5 file. */
    urdme_output_writer *writer;
    writer = get_urdme_output_writer(model,outfile);
    printf("writer = get_urdme_output_writer(model,%s);\n",outfile);
	
    printf("dfsp_core\n");
    dfsp_core(model, writer);
	
    /* Write the timespan vector to the output file */
    printf("write_tspan\n");
    write_tspan(writer,model);

    
    //free(parameters);
    
    printf("destroy_output_writer\n");
    destroy_output_writer(writer);
    printf("destroy_model\n");
    destroy_model(model);
	
	return(0);
	
}