Esempio n. 1
0
	std::string NodeEepromHelper::read_serial() const
	{
		//read the serial number 
		uint32 serial = read(NodeEepromMap::SERIAL_ID).as_uint32();

		//if the serial stored in eeprom is invalid (uninitialized)
		if(serial == 0xFFFFFFFF || serial == 0xAAAAAAAA || serial == 0)
		{
			//this node uses the legacy serial number

			//read the serial from the legacy serial id eeprom location
			serial = read(NodeEepromMap::LEGACY_SERIAL_ID).as_uint16();
		}

		//get the model number of the node
		WirelessModels::NodeModel fullModel = read_model();

		//split the model into its 2 pieces
		uint16 model = static_cast<uint16>(fullModel / 10000);
		uint16 modelClass = fullModel % 10000;

		//build the string result
		std::stringstream modelStr;
		modelStr << std::setfill('0') << std::setw(4) << model;

		std::stringstream modelClassStr;
		modelClassStr << std::setfill('0') << std::setw(4) << modelClass;

		std::stringstream serialStr;
		serialStr << std::setfill('0') << std::setw(5) << serial;

		return modelStr.str() + "-" + modelClassStr.str() + "-" + serialStr.str();
	}
Esempio n. 2
0
IMP_VOID ipConfigTargetClassifieri( IpTargetClassifier *pstTgtClfier, IpClassifierPara *pstPara )
{
	IpClassifierPara *pstParams=&pstTgtClfier->stPara;
	if (pstPara == NULL)
	{
		pstParams->s32ClassType = IMP_TGT_TYPE_HUMAN;
		pstParams->s8SvmFuncType = CLASSIFY;
		pstParams->s32ClassfierAnimal = 0;
		pstParams->s32UseBorderConstrain = 0;
	}
	else
	{
		pstParams->s32ClassType = pstPara->s32ClassType;
		pstParams->s8SvmFuncType = pstPara->s8SvmFuncType;
		pstParams->s32ClassfierAnimal = pstPara->s32ClassfierAnimal;
		pstParams->s32UseBorderConstrain = pstPara->s32UseBorderConstrain;
	}
	pstParams->stTgtPara.stHumanPara.s32MinSize = HUMAN_SIZE_MIN;
	pstParams->stTgtPara.stHumanPara.s32MaxSize = HUMAN_SIZE_MAX;
	pstParams->stTgtPara.stHumanPara.s32MinVelo = HUMAN_VELO_MIN;
	pstParams->stTgtPara.stHumanPara.s32MaxVelo = HUMAN_VELO_MAX;

	pstParams->stTgtPara.stVehiclePara.s32MinSize = VEHICLE_SIZE_MIN;
	pstParams->stTgtPara.stVehiclePara.s32MaxSize = VEHICLE_SIZE_MAX;
	pstParams->stTgtPara.stVehiclePara.s32MinVelo = VEHICLE_VELO_MIN;
	pstParams->stTgtPara.stVehiclePara.s32MaxVelo = VEHICLE_VELO_MAX;


	pstParams->pstModel = read_model(parfil_svm);
}
Esempio n. 3
0
int main (int argc, char* argv[])
{
  MODEL *model; 

  read_input_parameters(argc,argv,modelfile,outfile, &verbosity, &format);

  if (format) {
    model=read_binary_model(modelfile);
  } else {
    model=read_model(modelfile);
    if(model->kernel_parm.kernel_type == 0) { /* linear kernel */
        /* compute weight vector */
        add_weight_vector_to_linear_model(model);
    }
  }
    if(model->kernel_parm.kernel_type == 0) { /* linear kernel */
        FILE* modelfl = fopen (outfile, "wb");
        if (modelfl==NULL)
        { perror (modelfile); exit (1); }

        if (verbosity > 1)
            fprintf(modelfl,"B=%.32g\n",model->b);
        long i=0;
        for (i= 0; i< model->totwords; ++i) 
            fprintf(modelfl,"%.32g\n",model->lin_weights[i]);
    } else {
        fprintf(stderr,"No output besides linear models\n");
    }
  free_model(model,1);
  return(0);
}
int SVMModule::LoadSVMModelFile(std::string modelFile)
{
        MODEL* model = read_model((char*)modelFile.c_str());
        if(model == NULL)
               return -1;
        add_weight_vector_to_linear_model(model);
	m_pTrainModel = model;
        return 0;
}
Esempio n. 5
0
voxel_model::voxel_model(const variant& node)
  : name_(node["model"].as_string()), anim_time_(0.0), old_anim_time_(0.0),
    invalidated_(false), model_(1.0f), proto_model_(1.0f)
{
	aabb_[0] = glm::vec3(std::numeric_limits<float>::max(),std::numeric_limits<float>::max(),std::numeric_limits<float>::max());
	aabb_[1] = glm::vec3(std::numeric_limits<float>::min(),std::numeric_limits<float>::min(),std::numeric_limits<float>::min());
	Model base(read_model(json::parse_from_file(name_)));

	attachment_points_ = base.attachment_points;

	feet_ = base.feet_position;

	for(const LayerType& layer_type : base.layer_types) {
		variant variation_name = node[layer_type.name];
		if(variation_name.is_null()) {
			variation_name = variant("default");
		}

		auto variation_itor = layer_type.variations.find(variation_name.as_string());
		ASSERT_LOG(variation_itor != layer_type.variations.end(), "Could not find variation of layer " << layer_type.name << " name " << variation_name.as_string() << " in model " << name_);

		if(layer_type.symmetric) {
			Layer left;
			Layer right;
			left.name = right.name = variation_itor->second.name;
			for(const VoxelPair& p : variation_itor->second.map) {
				if(p.first[0] < 0) {
					left.map.insert(p);
				} else {
					right.map.insert(p);
				}
			}

			children_.push_back(voxel_model_ptr(new voxel_model(left, layer_type)));
			children_.back()->name_ = "left_" + layer_type.name;
			children_.push_back(voxel_model_ptr(new voxel_model(right, layer_type)));
			children_.back()->name_ = "right_" + layer_type.name;

		} else {
			children_.push_back(voxel_model_ptr(new voxel_model(variation_itor->second, layer_type)));
		}
	}

	for(const Animation& anim : base.animations) {
		animations_[anim.name].reset(new Animation(anim));
	}

	for(auto child : children_) {
		if(child->aabb_[0].x < aabb_[0].x) { aabb_[0].x = child->aabb_[0].x; }
		if(child->aabb_[0].y < aabb_[0].y) { aabb_[0].y = child->aabb_[0].y; }
		if(child->aabb_[0].z < aabb_[0].z) { aabb_[0].z = child->aabb_[0].z; }
		if(child->aabb_[1].x > aabb_[1].x) { aabb_[1].x = child->aabb_[1].x; }
		if(child->aabb_[1].y > aabb_[1].y) { aabb_[1].y = child->aabb_[1].y; }
		if(child->aabb_[1].z > aabb_[1].z) { aabb_[1].z = child->aabb_[1].z; }
	}
}
Esempio n. 6
0
STRUCTMODEL read_struct_model(char *file, STRUCT_LEARN_PARM *sparm)
{
  /* Reads structural model sm from file file. This function is used
     only in the prediction module, not in the learning module. */
  STRUCTMODEL sm;
  sm.svm_model=read_model(file);
  sm.w=sm.svm_model->lin_weights;
  sm.sizePsi=sm.svm_model->totwords;
  return(sm);
}
Esempio n. 7
0
int cmd_add_model(const char* arg) {
	char* argv, *ptr, *ptr2, *model;
	struct data_model* mdl;

	argv = strdupa(arg + strlen("add-model "));

	if ((ptr = strtok(argv, " ")) == NULL) {
		cmd_add_model_help();
		return 1;
	}

	/* add .yin if not specified */
	ptr2 = strstr(ptr, ".yin");
	if (ptr2 == NULL) {
		asprintf(&ptr2, "%s.yin", ptr);
		model = ptr2;
	} else {
		ptr2 = NULL;
		model = ptr;
	}

	mdl = read_model(model);
	free(ptr2);
	if (mdl == NULL) {
		return 1;
	}

	add_hint(mdl->name);

	ptr = strtok(NULL, " ");
	if (ptr != NULL) {
		if (strcmp(ptr, "*") == 0) {
			ncds_features_enableall(mdl->name);
			return 0;
		} else {
			ncds_feature_enable(mdl->name, ptr);
		}
	}
	while ((ptr = strtok(NULL, " ")) != NULL) {
		ncds_feature_enable(mdl->name, ptr);
	}

	return 0;
}
Esempio n. 8
0
//-----------------------------------------------------------------------------
bool datareader_c::read( solution_ptr& solution, std::string scenario_id, xml_element_ptr top ) {
  if( !buffer_line() ) return false;
  //print_cells();

  solution = solution_ptr( new solution_c( solution_c::MODEL ) );
  solution->scenario_id = scenario_id;
  component_ptr component = boost::dynamic_pointer_cast<solution_c>( solution );

  xml_element_ptr element;
  std::string key, tag;

  for( unsigned i = 0; i < top->elements(); i++ ) {
    element = top->element( i );
    tag = element->get_name();
    if( tag == "Field" ) {
      read_field( component, element );
    } else if( tag == "Model" ) {
      read_model( component, element );
    }
  }

  return true;
}
Esempio n. 9
0
//-----------------------------------------------------------------------------
bool datareader_c::read( trial_ptr& trial, std::string scenario_id, xml_element_ptr top ) {
  if( !buffer_line() ) return false;
  //print_cells();

  trial = trial_ptr( new trial_c() );
  trial->scenario_id = scenario_id;
  component_ptr component = boost::dynamic_pointer_cast<trial_c>( trial );

  xml_element_ptr element;
  std::string key, name;

  for( unsigned i = 0; i < top->elements(); i++ ) {
    element = top->element( i );
    name = element->get_name();
    if( name == "Field" ) {
      read_field( component, element );
    } else if( name == "Model" ) {
      read_model( component, element );
    }
  }

  return true;
}
Esempio n. 10
0
int main_classify (int argc, char* argv[])
{
  DOC *doc;   /* test example */
  WORDSVM *words;
  long max_docs,max_words_doc,lld;
  long totdoc=0,queryid,slackid;
  long correct=0,incorrect=0,no_accuracy=0;
  long res_a=0,res_b=0,res_c=0,res_d=0,wnum,pred_format;
  long j;
  double t1,runtime=0;
  double dist,doc_label,costfactor;
  char *line,*comment; 
  FILE *predfl,*docfl;
  MODEL *model; 

  read_input_parameters(argc,argv,docfile,modelfile,predictionsfile,
			&verbosity,&pred_format);

  nol_ll(docfile,&max_docs,&max_words_doc,&lld); /* scan size of input file */
  max_words_doc+=2;
  lld+=2;

  line = (char *)my_malloc(sizeof(char)*lld);
  words = (WORDSVM *)my_malloc(sizeof(WORDSVM)*(max_words_doc+10));

  model=read_model(modelfile);

  if(model->kernel_parm.kernel_type == 0) { /* linear kernel */
    /* compute weight vector */
    add_weight_vector_to_linear_model(model);
  }
  
  if(verbosity>=2) {
    printf("Classifying test examples.."); fflush(stdout);
  }

  if ((docfl = fopen (docfile, "r")) == NULL)
  { perror (docfile); exit (1); }
  if ((predfl = fopen (predictionsfile, "w")) == NULL)
  { perror (predictionsfile); exit (1); }

  while((!feof(docfl)) && fgets(line,(int)lld,docfl)) {
    if(line[0] == '#') continue;  /* line contains comments */
    parse_document(line,words,&doc_label,&queryid,&slackid,&costfactor,&wnum,
		   max_words_doc,&comment);
    totdoc++;
    if(model->kernel_parm.kernel_type == 0) {   /* linear kernel */
      for(j=0;(words[j]).wnum != 0;j++) {  /* Check if feature numbers   */
	if((words[j]).wnum>model->totwords) /* are not larger than in     */
	  (words[j]).wnum=0;               /* model. Remove feature if   */
      }                                        /* necessary.                 */
      doc = create_example(-1,0,0,0.0,create_svector(words,comment,1.0));
      t1=get_runtime();
      dist=classify_example_linear(model,doc);
      runtime+=(get_runtime()-t1);
      free_example(doc,1);
    }
    else {                             /* non-linear kernel */
      doc = create_example(-1,0,0,0.0,create_svector(words,comment,1.0));
      t1=get_runtime();
      dist=classify_example(model,doc);
      runtime+=(get_runtime()-t1);
      free_example(doc,1);
    }
    if(dist>0) {
      if(pred_format==0) { /* old weired output format */
	fprintf(predfl,"%.8g:+1 %.8g:-1\n",dist,-dist);
      }
      if(doc_label>0) correct++; else incorrect++;
      if(doc_label>0) res_a++; else res_b++;
    }
    else {
      if(pred_format==0) { /* old weired output format */
	fprintf(predfl,"%.8g:-1 %.8g:+1\n",-dist,dist);
      }
      if(doc_label<0) correct++; else incorrect++;
      if(doc_label>0) res_c++; else res_d++;
    }
    if(pred_format==1) { /* output the value of decision function */
      fprintf(predfl,"%.8g\n",dist);
    }
    if((int)(0.01+(doc_label*doc_label)) != 1) 
      { no_accuracy=1; } /* test data is not binary labeled */
    if(verbosity>=2) {
      if(totdoc % 100 == 0) {
	printf("%ld..",totdoc); fflush(stdout);
      }
    }
  }  
  free(line);
  free(words);
  free_model(model,1);

  if(verbosity>=2) {
    printf("done\n");

/*   Note by Gary Boone                     Date: 29 April 2000        */
/*      o Timing is inaccurate. The timer has 0.01 second resolution.  */
/*        Because classification of a single vector takes less than    */
/*        0.01 secs, the timer was underflowing.                       */
    printf("Runtime (without IO) in cpu-seconds: %.2f\n",
	   (float)(runtime/100.0));
    
  }
  if((!no_accuracy) && (verbosity>=1)) {
    printf("Accuracy on test set: %.2f%% (%ld correct, %ld incorrect, %ld total)\n",(float)(correct)*100.0/totdoc,correct,incorrect,totdoc);
    printf("Precision/recall on test set: %.2f%%/%.2f%%\n",(float)(res_a)*100.0/(res_a+res_b),(float)(res_a)*100.0/(res_a+res_c));
  }

  return(0);
}
int main(int argc, char** argv) {
  std::string source_file;
  std::string output_file;
  try {
    namespace po=boost::program_options;
    po::options_description desc("Options");
    desc.add_options()
    ("help,h", "Print help messages")
    ("source,s", po::value<std::string>(&source_file)->required(), "Specify an source file")
    ("output,o", po::value<std::string>(&output_file)->default_value(boost::filesystem::current_path().string<std::string>()+"/detector.data"), "Specify an output file");

    po::positional_options_description p;
    p.add("source",-1);

    po::variables_map vm;
    po::store(po::command_line_parser(argc,argv).options(desc).positional(p).run(), vm);

    if (vm.count("help")) {
      std::cout << "Usage: " << argv[0] << " [options] source" << std::endl;
      std::cout << desc;
      return 0;
    }

    po::notify(vm);
  }
  catch(std::exception& e) {
    std::cerr << "Error: " << e.what() << std::endl;
    return 1;
  }
  catch(...) {
    std::cerr << "Exception of unknown type!" << std::endl;
    return 1;
  }

  std::vector<float> single_detector_vector;
  std::vector<unsigned int> single_detector_vector_indices;

  char model_file[source_file.size()+1];
  strcpy(model_file, source_file.c_str());
  MODEL *model=read_model(model_file);

  DOC** supveclist = model->supvec;
  single_detector_vector.clear();
  single_detector_vector.resize(model->totwords, 0.);

  for (long ssv = 1; ssv < model->sv_num; ++ssv) {
    DOC* single_support_vector = supveclist[ssv];
    SVECTOR* single_support_vector_values = single_support_vector->fvec;
    WORD single_support_vector_component;
    for (long singleFeature = 0; singleFeature < model->totwords; ++singleFeature) {
      single_support_vector_component = single_support_vector_values->words[singleFeature];
      single_detector_vector.at(single_support_vector_component.wnum-1) += (single_support_vector_component.weight * model->alpha[ssv]);
    }
  }

  free_model(model,1);

  std::ofstream result_data;
  result_data.open(output_file.c_str(), std::ofstream::out|std::ofstream::app);

  for(std::vector<float>::iterator iter=single_detector_vector.begin(); iter!=single_detector_vector.end(); iter++) {
    result_data << *iter << std::endl;
  }
}
Esempio n. 12
0
int candidate_tag(option& opt, std::ifstream& ifs)
{
    int rl = -1;
    int lines = 0;
    feature_generator fgen;
    std::istream& is = opt.is;
    std::ostream& os = opt.os;
    bool inner = false;
    std::string comment_outer, comment_inner;
    comments_type comments;

    // Load a model.
    model_type model;
    read_model(model, ifs, opt);

    // Create an instance of a classifier on the model.
    classifier_type inst(model);
    labels_type labels;

    // Objects for performance evaluation.
    classias::accuracy acc;
    classias::precall pr(labels.size());

    for (;;) {
        // Read a line.
        std::string line;
        std::getline(is, line);
        if (is.eof()) {
            break;
        }
        ++lines;

        // An empty line or comment line.
        if (line.empty() || line.compare(0, 1, "#") == 0) {
            if (opt.output & option::OUTPUT_COMMENT) {
                if (0 < inst.size()) {
                    // Store the comment line to the current instance.
                    comments[inst.size()-1] += line;
                    comments[inst.size()-1] += '\n';
                } else if (inner) {
                    comment_inner += line;
                    comment_inner += '\n';
                } else {
                    comment_outer += line;
                    comment_outer += '\n';
                }
            }
            continue;
        }

        if (line.compare(0, 4, "@boi") == 0) {
            // Begin of an instance.
            rl = -1;
            inst.clear();
            labels.clear();
            comments.clear();
            inner = true;

        } else if (line == "@eoi") {
            inst.finalize();

            // Determine whether we output this instance or not.
            if (opt.condition == option::CONDITION_ALL ||
                (opt.condition == option::CONDITION_FALSE && rl != inst.argmax())) {

                // Output BOI.
                os << comment_outer;
                os << "@boi" << std::endl;
                os << comment_inner;

                if (opt.output & option::OUTPUT_ALL) {
                    for (int i = 0;i < inst.size();++i) {
                        // Output the reference label.
                        if (opt.output & option::OUTPUT_RLABEL) {
                            os << ((i == rl) ? '+' : '-');
                        }
                        // Output the predicted label.
                        os << ((i == inst.argmax()) ? '+' : '-');
                        os << labels[i];

                        // Output the score/probability if necessary.
                        if (opt.output & option::OUTPUT_PROBABILITY) {
                            os << opt.value_separator << inst.prob(i);
                        } else if (opt.output & option::OUTPUT_SCORE) {
                            os << opt.value_separator << inst.score(i);
                        }

                        os << std::endl;
                        os << comments[i];
                    }

                } else {
                    // Output the reference label.
                    if (opt.output & option::OUTPUT_RLABEL) {
                        os << labels[rl] << opt.token_separator;
                    }
                    // Output the predicted label.
                    os << labels[inst.argmax()];

                    // Output the score/probability if necessary.
                    if (opt.output & option::OUTPUT_PROBABILITY) {
                        os << opt.value_separator << inst.prob(inst.argmax());
                    } else if (opt.output & option::OUTPUT_SCORE) {
                        os << opt.value_separator << inst.score(inst.argmax());
                    }

                    os << std::endl;

                }

                // Output EOI.
                os << "@eoi" << std::endl;
            }

            // Accumulate the performance.
            if (opt.test) {
                acc.set(inst.argmax() == rl);
            }

            rl = -1;
            inst.clear();
            labels.clear();
            comments.clear();
            comment_inner.clear();
            comment_outer.clear();
            inner = false;

        } else {
            std::string label;
            bool truth = false;
            parse_line(inst, fgen, label, truth, opt, line, lines);
            if (truth) {
                rl = inst.size() - 1;
            }
            labels.push_back(label);
            if (labels.size() != inst.size()) {
                throw invalid_data("", line, lines);
            }
            if ((int)comments.size() < inst.size()) {
                comments.resize(inst.size());
            }
        }
    }

    // Output the performance if necessary.
    if (opt.test) {
        acc.output(os);
    }

    return 0;
}
Esempio n. 13
0
Classifier::Classifier(string output, Trainer::KernelType kernel,
                       Location* le, Location* re, Location* n,
                       roiFnT roiFn) {
    // check if the output directory exists, or else bail
    DIR* dir;
    dir = opendir(output.c_str());
    if (dir == NULL) {
        string err = "Trainer::Trainer. The directory " + output + " does not exist. Bailing out.";
        throw (err);
    }
    closedir(dir);

    outputDirectory = output;
    roiFunction = roiFn;
    kernelType = kernel;

    // Build a set of feature extraction objects and stuff them into the
    // extractor vector
    Feature* f = (Feature*) new FeatureLX();
    featureExtractors.push_back(f);
    f = (Feature*) new FeatureRX();
    featureExtractors.push_back(f);
    f = (Feature*) new FeatureNX();
    featureExtractors.push_back(f);
    f = (Feature*) new FeatureLRDist();
    featureExtractors.push_back(f);
    f = (Feature*) new FeatureLNDist();
    featureExtractors.push_back(f);
    f = (Feature*) new FeatureRNDist();
    featureExtractors.push_back(f);
    f = (Feature*) new FeatureLNAngle();
    featureExtractors.push_back(f);
    f = (Feature*) new FeatureRNAngle();
    featureExtractors.push_back(f);
    f = (Feature*) new FeatureLRNArea();
    featureExtractors.push_back(f);

    nFeatures = (int)Feature::End - 1;

    // read extremal feature values and other data generated during
    // training that we need for classification
    readParameters();

    // create location extractors
    leftEye = le;
    rightEye = re;
    nose = n;

    // load models
    for (unsigned int i = 0; i < Globals::numZones; i++) {
        char buffer[Globals::smallBufferSize];
        sprintf(buffer, "%d.model", i + 1);
        string str = buffer;
        string modelFileName = outputDirectory + "/" + Globals::modelNamePrefix + str;

        MODEL* model = read_model((char*)modelFileName.c_str());
        if (!model) {
            string err = "Classifier::Classifier. read_model returned NULL.";
            throw (err);
        }
        if (model->kernel_parm.kernel_type == 0) { /* linear kernel */
            /* compute weight vector */
            add_weight_vector_to_linear_model(model);
        }
        models.push_back(model);
    }
}
Esempio n. 14
0
File: dfsp.c Progetto: Aratz/pyurdme
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);
	
}
Esempio n. 15
0
	void* new_chipmunk_data(char* received, int* okay)
	{
		chipmunk_data* c = (chipmunk_data*)mmalloc(sizeof(chipmunk_data));
		model* m;
		char* remember;
	
	//	pthread_mutex_init(&c->lock, NULL);

		c->del = 0;
	
		c->px = (mFloat)0.0;
		c->py = (mFloat)0.0;
		c->an = (mFloat)0.0;
		c->vx = (mFloat)0.0;
		c->vy = (mFloat)0.0;
		c->av = (mFloat)0.0;
		c->ax = (mFloat)0.0;
		c->ay = (mFloat)0.0;
		c->aa = (mFloat)0.0;

		#warning FIXME: Check for errors.
		sscanf(strtok_r(received, " ", &remember), "%d", &c->key_up   );
		sscanf(strtok_r(NULL    , " ", &remember), "%d", &c->key_down );
		sscanf(strtok_r(NULL    , " ", &remember), "%d", &c->key_left );
		sscanf(strtok_r(NULL    , " ", &remember), "%d", &c->key_right);

		LOG("Client's up key: %d", c->key_up);
		LOG("Client's down key: %d", c->key_down);
		LOG("Client's left key: %d", c->key_left);
		LOG("Client's right key: %d", c->key_right);

		c->key_is_up = 0;
		c->key_is_down = 0;
		c->key_is_left = 0;
		c->key_is_right = 0;

		/* TODO: Read-write?? */
		simple_lock(&physics_lock);
	
		/* Could not find file :( */
		if((m = read_model(space, cpvzero, MODELS "square", NULL, NULL, (void*)c, CHARACTER)) == NULL)
		{
//			pthread_mutex_destroy(&c->lock);
			mfree(c);
		
			LOG("I'm an so sorry. File " MODELS "square" " was not found.");
			*okay = 0;
		
			simple_unlock(&physics_lock);

			return NULL;
		}

		lAdd(&chipmunk_data_array, (void*)c);
		simple_unlock(&physics_lock);

		c->mod = m;

		*okay = 1;
		return (void*)c;
	}