Ejemplo n.º 1
0
void mixMarkov(vector< vector<int> >& X, int trainingNum, int numOfState, 
        int K, vector<double>& pi, vector< vector<double> >& thetaInit,
        vector< vector< vector<double> > >& thetaTrans) {
    vector < vector< map<int, int> > > sigma;
    vector<double> ll_variables(3);
    vector< vector<double> > condProb(trainingNum);
    initVariable(pi, thetaInit, thetaTrans);
    setSigma(X, sigma, trainingNum);

    estep(X, pi, thetaInit, thetaTrans, condProb);
    
    ll_variables = computeLL(X, thetaInit, thetaTrans);
    
    for (iter = 1; iter<= MAX_ITER; ++iter) {
        mstep(pi, thetaInit, thetaTrans, condProb);
        estep(X, pi, thetaInit, thetaTrans, condProb);
        vector<double> new_ll_variables(3);
        new_ll_variables = computeLL(X, thetaInit, thetaTrans);
        
        //check for convergence
        if (new_ll_variables[0] + new_ll_variables[1] + new_ll_variables[2] - (ll_variables[0] + ll_variables[1] + ll_variables[2]) >TOL ) {
            ll_variables = new_ll_variables; 
        } else {
            break;
        }
    }
}
Ejemplo n.º 2
0
 void ChainArray::initialise(uint id, const Eigen::VectorXd& sample, 
     double energy, double sigma, double beta)
 {
   setSigma(id, sigma);
   setBeta(id, beta);
   cache_[id].push_back({ sample, energy, sigma_[id], beta_[id], true, SwapType::NoAttempt});
   lastState_[id] = cache_[id].back();
 }
Ejemplo n.º 3
0
      /* Sets all parameters in one pass.
       *
       * @param mu      Mean
       * @param sig     Standard deviation
       *
       * \warning If (sig <= 0.0), it will be set to 1.0.
       */
   GaussianDistribution& GaussianDistribution::setParameters( double mu,
                                                              double sig )
   {

      mean = mu;

         // Set sigma, check limits and recompute
      setSigma(sig);

      return (*this);

   }  // End of method 'GaussianDistribution::setParameters()'
Ejemplo n.º 4
0
// set the widget to the stored default values
void FFTOptions::loadWidgetDefaults() {
  setSampleRate(_dialogDefaults->value("spectrum/freq",100.0).toDouble());
  setInterleavedAverage(_dialogDefaults->value("spectrum/average",true).toBool());
  setFFTLength(_dialogDefaults->value("spectrum/len",12).toInt());
  setApodize(_dialogDefaults->value("spectrum/apodize",true).toBool());
  setRemoveMean(_dialogDefaults->value("spectrum/removeMean",true).toBool());
  setVectorUnits(_dialogDefaults->value("spectrum/vUnits","V").toString());
  setRateUnits(_dialogDefaults->value("spectrum/rUnits","Hz").toString());
  setApodizeFunction(ApodizeFunction(_dialogDefaults->value("spectrum/apodizeFxn",WindowOriginal).toInt()));
  setSigma(_dialogDefaults->value("spectrum/gaussianSigma",1.0).toDouble());
  setOutput(PSDType(_dialogDefaults->value("spectrum/output",PSDPowerSpectralDensity).toInt()));
  setInterpolateOverHoles(_dialogDefaults->value("spectrum/interpolateHoles",true).toInt());
}
Ejemplo n.º 5
0
    virtual void internalTransition(devs::Time time) override
    {
        CellDevs::internalTransition(time);
        switch (mState) {
        case INIT:
            mState = IDLE;
            setSigma(devs::Time(0.0));
            break;
        case IDLE:
            setLastTime(time);
            mState = NEWSTATE;
            setSigma(devs::Time(0.0));
            break;
        case NEWSTATE:
            bool v_state = getBooleanState("s");
            unsigned int n = getBooleanNeighbourStateNumber("s", true);

            if (v_state && (n < 2 || n > 3)) {
                setBooleanState("s",false);
                modify();
                mState = INIT;
                setSigma(mTimeStep);
            }
            else if (!v_state && (n == 3)) {
                setBooleanState("s",true);
                modify();
                mState = INIT;
                setSigma(mTimeStep);
            }
            else {
                mState = IDLE;
                setSigma(devs::infinity);
            }
            break;
        }
    }
Ejemplo n.º 6
0
  gBathProperties::gBathProperties(Molecule* pMol)
    :m_Sigma(sigmaDefault),
    m_Epsilon(epsilonDefault),
    m_Sigma_chk(-1),
    m_Epsilon_chk(-1)
  {
    ErrorContext c(pMol->getName());
    m_host = pMol;
    PersistPtr pp = pMol->get_PersistentPointer();

    PersistPtr ppPropList = pp->XmlMoveTo("propertyList");
    if (!ppPropList)
      ppPropList = pp; //Be forgiving; we can get by without a propertyList element

    setSigma(ppPropList->XmlReadPropertyDouble("me:sigma"));
    setEpsilon(ppPropList->XmlReadPropertyDouble("me:epsilon"));
  }
Ejemplo n.º 7
0
    virtual devs::Time init(devs::Time /* time */) override
    {
        mTimeStep = value::toDouble(m_parameters["TimeStep"]);

        initBooleanNeighbourhood("s",false);
        if (!existState("s")) {
            double colour = mRand.getDouble();

            if (colour > 0.5) initBooleanState("s", true);
            else initBooleanState("s", false);
        }

        mState = INIT;
        neighbourModify();
        setSigma(devs::Time(0.0));
        return devs::Time(0.0);
    }
Ejemplo n.º 8
0
bool cvzMmcm_IDL::read(yarp::os::ConnectionReader& connection) {
  yarp::os::idl::WireReader reader(connection);
  reader.expectAccept();
  if (!reader.readListHeader()) { reader.fail(); return false; }
  yarp::os::ConstString tag = reader.readTag();
  bool direct = (tag=="__direct__");
  if (direct) tag = reader.readTag();
  while (!reader.isError()) {
    // TODO: use quick lookup, this is just a test
    if (tag == "start") {
      start();
      yarp::os::idl::WireWriter writer(reader);
      if (!writer.isNull()) {
        if (!writer.writeListHeader(0)) return false;
      }
      reader.accept();
      return true;
    }
    if (tag == "pause") {
      pause();
      yarp::os::idl::WireWriter writer(reader);
      if (!writer.isNull()) {
        if (!writer.writeListHeader(0)) return false;
      }
      reader.accept();
      return true;
    }
    if (tag == "quit") {
      bool _return;
      _return = quit();
      yarp::os::idl::WireWriter writer(reader);
      if (!writer.isNull()) {
        if (!writer.writeListHeader(1)) return false;
        if (!writer.writeBool(_return)) return false;
      }
      reader.accept();
      return true;
    }
    if (tag == "setLearningRate") {
      double l;
      if (!reader.readDouble(l)) {
        reader.fail();
        return false;
      }
      setLearningRate(l);
      yarp::os::idl::WireWriter writer(reader);
      if (!writer.isNull()) {
        if (!writer.writeListHeader(0)) return false;
      }
      reader.accept();
      return true;
    }
    if (tag == "getLearningRate") {
      double _return;
      _return = getLearningRate();
      yarp::os::idl::WireWriter writer(reader);
      if (!writer.isNull()) {
        if (!writer.writeListHeader(1)) return false;
        if (!writer.writeDouble(_return)) return false;
      }
      reader.accept();
      return true;
    }
    if (tag == "setSigma") {
      double s;
      if (!reader.readDouble(s)) {
        reader.fail();
        return false;
      }
      setSigma(s);
      yarp::os::idl::WireWriter writer(reader);
      if (!writer.isNull()) {
        if (!writer.writeListHeader(0)) return false;
      }
      reader.accept();
      return true;
    }
    if (tag == "getSigma") {
      double _return;
      _return = getSigma();
      yarp::os::idl::WireWriter writer(reader);
      if (!writer.isNull()) {
        if (!writer.writeListHeader(1)) return false;
        if (!writer.writeDouble(_return)) return false;
      }
      reader.accept();
      return true;
    }
    if (tag == "getActivity") {
      int32_t x;
      int32_t y;
      int32_t z;
      if (!reader.readI32(x)) {
        reader.fail();
        return false;
      }
      if (!reader.readI32(y)) {
        reader.fail();
        return false;
      }
      if (!reader.readI32(z)) {
        reader.fail();
        return false;
      }
      double _return;
      _return = getActivity(x,y,z);
      yarp::os::idl::WireWriter writer(reader);
      if (!writer.isNull()) {
        if (!writer.writeListHeader(1)) return false;
        if (!writer.writeDouble(_return)) return false;
      }
      reader.accept();
      return true;
    }
    if (tag == "saveWeightsToFile") {
      std::string path;
      if (!reader.readString(path)) {
        reader.fail();
        return false;
      }
      bool _return;
      _return = saveWeightsToFile(path);
      yarp::os::idl::WireWriter writer(reader);
      if (!writer.isNull()) {
        if (!writer.writeListHeader(1)) return false;
        if (!writer.writeBool(_return)) return false;
      }
      reader.accept();
      return true;
    }
    if (tag == "loadWeightsFromFile") {
      std::string path;
      if (!reader.readString(path)) {
        reader.fail();
        return false;
      }
      bool _return;
      _return = loadWeightsFromFile(path);
      yarp::os::idl::WireWriter writer(reader);
      if (!writer.isNull()) {
        if (!writer.writeListHeader(1)) return false;
        if (!writer.writeBool(_return)) return false;
      }
      reader.accept();
      return true;
    }
    if (tag == "saveRF") {
      std::string path;
      if (!reader.readString(path)) {
        reader.fail();
        return false;
      }
      bool _return;
      _return = saveRF(path);
      yarp::os::idl::WireWriter writer(reader);
      if (!writer.isNull()) {
        if (!writer.writeListHeader(1)) return false;
        if (!writer.writeBool(_return)) return false;
      }
      reader.accept();
      return true;
    }
    if (tag == "help") {
      std::string functionName;
      if (!reader.readString(functionName)) {
        functionName = "--all";
      }
      std::vector<std::string> _return=help(functionName);
      yarp::os::idl::WireWriter writer(reader);
        if (!writer.isNull()) {
          if (!writer.writeListHeader(2)) return false;
          if (!writer.writeTag("many",1, 0)) return false;
          if (!writer.writeListBegin(BOTTLE_TAG_INT, static_cast<uint32_t>(_return.size()))) return false;
          std::vector<std::string> ::iterator _iterHelp;
          for (_iterHelp = _return.begin(); _iterHelp != _return.end(); ++_iterHelp)
          {
            if (!writer.writeString(*_iterHelp)) return false;
           }
          if (!writer.writeListEnd()) return false;
        }
      reader.accept();
      return true;
    }
    if (reader.noMore()) { reader.fail(); return false; }
    yarp::os::ConstString next_tag = reader.readTag();
    if (next_tag=="") break;
    tag = tag + "_" + next_tag;
  }
  return false;
}
Ejemplo n.º 9
0
 GM(const arma::vec & mu, const arma::mat & sigma) {
   setMu(mu);
   setSigma(sigma);
 }
Ejemplo n.º 10
0
 //create gaussian model with the highest loglikelyhood for the given data
 GM(const arma::mat& data) {
   setMu(arma::conv_to<arma::vec>::from(arma::mean(data, 1)));
   setSigma(arma::cov(data.t()));
 }
Ejemplo n.º 11
0
int main(int argc,char** argv)
{
  FloatImage img;
  FloatImage mask;
  LabelImage mask2;
  std::vector<FloatImage> atlasImages;
  MixtureSpec mixture;
  AtlasSpec atlas; 
  PdfEstimate hatf;
  Parameters params;  
  Population pop,selPop,popRuns;

  float maxMu,minMu,minVar,maxVar,mean;
  std::vector<float> lowLimit;
  std::vector<float> upLimit;  
  //  float* fitness;

  bool terminate;
  bool boolstatus;
  bool changed_n = false;

  int intstatus,i,j,itercount,rr,n; 
  int pveLabels,pureLabels;  

  if(argc < 5) {
    cout << "Genetic algorithm for mixture model optimization" << endl;
    cout << "Usage: gamixture [-unsigned] imagefile maskfile atlasfile fmmparamfile [paramaters]" << endl;
    cout << "Optional parameters are :" << endl;
    cout << "-alpha:             parameter for blended crossover, defaults to " << DEFAULT_ALPHA << endl;
    cout << "-size:              population size, defaults to " << DEFAULT_POPSIZE << endl;
    cout << "-terminationthr:    threshold for terminating the algorithm, defaults to "<< DEFAULT_TERMINATIONTHR << endl; 
    cout << "-xoverrate:         crossover rate, defaults to " << DEFAULT_XOVERRATE << endl;
    cout << "-maxgenerations:    maximum number of generations, defaults to " << DEFAULT_MAXGENERATIONS << endl;
    cout << "-sortpop            whether to use the permutation operator, defaults to " << DEFAULT_SORTPOP << endl;
    cout << "-parzenn            number of points for Parzen estimate (for approximate ML), defaults to " << DEFAULT_PARZENN << endl;
    cout << "-parzensigma        window width parameter for the Parzen estimate, defaults to " << DEFAULT_PARZENSIGMA << endl;         
    cout << "-equalvar           whether component densities should have equal variances, defaults to " << DEFAULT_EQUALVAR << endl;  
    cout << "-restarts           the number of individual runs of the GA, defaults to " << DEFAULT_RESTARTS << endl;  
   return(1);
  }
  intstatus = readImage(argv[1],img);
  if(intstatus != 0) {
    cout << "Could not read image file " << argv[1] << " " << intstatus << endl;
    return(2);
  }  
  cout << "Image dimensions: " << img.header.x_dim << " " << img.header.y_dim << " " << img.header.z_dim << endl;
  if(!(strcmp(argv[2],"default"))) {
    mask.copyImage(img);
    mask.thresholdImage(VERY_SMALL);
    mask2.thresholdImage(img,VERY_SMALL); //!?!?!?!
  }
  else {
    intstatus = readImage(argv[2],mask);
    if(intstatus != 0) {
      cout << "Could not read image (brainmask) file " << argv[2] << " " << intstatus << endl;
      return(3);
    }  
    mask.thresholdImage(0.0001);
    mask2.thresholdImage(mask,0.5);//!?!?!
  } 
   
  boolstatus = atlas.readAtlasSpec(argv[3]);
  if(boolstatus == false) {
    cout << "Could not read atlas file " << argv[3] << endl;
    return(4);
  }   
 
  intstatus = params.parseParams(argc - 4,&(argv[4]));
  if(intstatus != 0) {  
    cout << "Incorrect parameter value input" << endl;
    return(6);
  }
  if(atlas.n > 0) {
    atlasImages.resize(atlas.n);
    intstatus = atlas.readAtlasImages(atlasImages);
    if(intstatus != 0) {
      cout << "Could not read probabilistic atlas. Error: " << intstatus << endl;
    return(6);
    }  
    cout << "The atlas files have been read" << endl;
    if(atlas.maskAtlas(atlasImages,mask) == false) {
      cout << "Could not mask atlas" << endl;
      return(7);
    }  
    cout << "The atlas has been masked" << endl;
  }
  else {
   // taking care for the case where atlas->n == 0
   // then we assume that the atlas is defined by the mask
    atlas.n = 1;
    changed_n = true;
    atlasImages.resize(atlas.n);
    boolstatus = atlasImages[0].copyImage(mask);
  } 
  mixture.allocateMixtureSpec(atlas);
  
  // compute the number of pve labels and pure labels.
  // remember that pve labels have to have indeces greater than pure labels
  pureLabels = 0;
  pveLabels = 0;
  for(i = 0;i < atlas.numberOfLabels;i++) {
    if(atlas.labelTypes[i].pureLabel == true) pureLabels++;
    else pveLabels++;     
  }
  cout << "purelabels:  " << pureLabels << " Pvelabels: " << pveLabels << endl; 
  
  
  // initializing the Parzen windows
  hatf.n = params.parzenN;
  computeX(&hatf,img,mask2,0.999);
  setSigma(&hatf,params.parzenSigma); 
  
  // Setting the limits for GA
  maxMu = hatf.x[hatf.n - 1];
  minMu = hatf.x[0];
  minVar = hatf.sigma * hatf.sigma;
  maxVar = 0.0;  // this is re-set later on  

  lowLimit.resize(3*pureLabels + pveLabels); 
  upLimit.resize(3*pureLabels + pveLabels); 
  // initialize by defults, then adapt the necessary values
  for(i = 0; i < pureLabels;i++) {
    upLimit[3*i] = maxMu;
    lowLimit[3*i] = minMu;
    upLimit[3*i + 1] = maxVar;  // this is re-set later on
    lowLimit[3*i + 1] = minVar;
    if(changed_n)  {
      upLimit[3*i + 2] = 1.0;  
    }
    else { 
      upLimit[3*i + 2] = 0.0; 
    } // this is changed afterwards
    lowLimit[3*i + 2] = 0.0;
  }
  upLimit[0] = 0.0;  // adjustment for the background label
  lowLimit[0] = 0.0;
  upLimit[2] = 0.0;
   
  // pve classes
  for(i = 0; i <pveLabels;i++) {
    if(changed_n) {
      upLimit[pureLabels*3 + i] = 1.0;
    }
    else {
      upLimit[pureLabels*3 + i] = 0.0;
    }
    lowLimit[pureLabels*3 + i] = 0.0;
  }  
  for(i = 0; i < atlas.n;i++) {
    rr = i + 1;
    cout << "Region " << rr << ":computing parzen estimate..." << endl;;  
    computeY(&hatf,img,atlasImages[i]);
    //  if(i == 5) writeEstimate("tmp.parzen",&hatf,true);
  
    cout << "Region " << rr << ":Genetic algorithm..." << endl;
    // set the region wise limits
    maxVar = 0.0;
    mean = 0.0;
    for(j = 0;j < hatf.n; j++) {
      mean = mean +  (hatf.x[1] - hatf.x[0])*(hatf.y[j])*(hatf.x[j]);
    }
    for(j = 0;j < hatf.n; j++) {
      maxVar = maxVar + (hatf.x[1] - hatf.x[0])*hatf.y[j]*(hatf.x[j] - mean)*(hatf.x[j] - mean);
    }
    maxVar = maxVar/pureLabels;
    for(j = 0; j < pureLabels;j++) {
       upLimit[3*j + 1] = maxVar;
    }
    if(!atlas.regionLowProb.empty()) {
      for(j = 1; j < pureLabels;j++) {
        lowLimit[j*3 + 2] = atlas.regionLowProb[i][j];
        upLimit[j*3 + 2] = atlas.regionUpProb[i][j];
      }
      for(j = 0; j < pveLabels;j++) {
        lowLimit[pureLabels*3 + j] = atlas.regionLowProb[i][pureLabels + j];
        upLimit[pureLabels*3 + j] = atlas.regionUpProb[i][pureLabels + j];
      }
    }
    else {
      if(!changed_n) {
        for(j = 1; j < pureLabels;j++) { // skip background
          upLimit[3*j + 2] = 0.0; 
        }
        for(j = 0; j < pveLabels;j++) {
          upLimit[pureLabels*3 + j] = 0.0;
        }
        for(j = 0;j < atlas.permittedLabels[i].len;j++) {
	  //   cout << atlas.permittedLabels[i].list[j] << " ";  
          if(atlas.permittedLabels[i].list[j] > (pureLabels -1)) {
            upLimit[3*pureLabels + atlas.permittedLabels[i].list[j] - pureLabels] = 1.0;
          }
          else {
            upLimit[atlas.permittedLabels[i].list[j]*3 + 2] = 1.0;
          }
        }
      }
    } 
    popRuns.gaInitializePopulation(params.restarts,1,pureLabels + pveLabels,pveLabels,atlas.labelTypes,lowLimit,upLimit,params.equalVar);
    for(n = 0;n < params.restarts;n++) {
      pop.gaInitializePopulation(params.size,1,pureLabels + pveLabels,pveLabels,
                           atlas.labelTypes,lowLimit,upLimit,params.equalVar);
      pop.gaSortPopulation(1);
      pop.gaEvaluate(&hatf);
      pop.gaReorder();
      selPop.copyPartialPopulation(&pop);
      terminate = false;
      itercount = 0;
      while((!terminate) && (itercount < params.maxGenerations)) {
        gaTournamentSelection(&selPop,&pop,1);
        gaBLX(&pop,&selPop,params.xoverRate,1,params.alpha,lowLimit,upLimit,params.equalVar); 
        if(params.sortPop) {
          pop.gaSortPopulation(1);
        }
        pop.gaEvaluate(&hatf);
        pop.gaReorder();
        terminate = pop.gaTerminate(params.terminationThr);
        itercount++;
      }
      if(!(params.sortPop)) pop.gaSortPopulation(1); 
      cout << "GA converged after " << itercount << " iterations." << endl;
      cout << "the KL distance is " << pop.energies[0] << "." << endl;
      // put the best invividual into popRuns
     for(j = 0;j < pureLabels;j++) {
        popRuns.gaSetMu(n,j,pop.gaGetMu(0,j));
        popRuns.gaSetSigma2(n,j,pop.gaGetSigma2(0,j));
        popRuns.gaSetProb(n,j,pop.gaGetProb(0,j));     
      }
      for(j = 0;j < pveLabels;j++) {
        popRuns.gaSetProb(n,j + pureLabels,pop.gaGetProb(0,j + pureLabels));
      }
      popRuns.energies[n] = pop.energies[0];
    }
    if( params.restarts > 1) popRuns.gaReorder(); 
    // convert the best indivual to mixtureSpec
    for(j = 0;j < pureLabels;j++) {
      mixture.putMu(i,j,popRuns.gaGetMu(0,j));
      mixture.putSigma2(i,j,popRuns.gaGetSigma2(0,j));
      mixture.putProb(i,j,popRuns.gaGetProb(0,j));     
    }
    for(j = 0;j < pveLabels;j++) {
      mixture.putProb(i,j + pureLabels,popRuns.gaGetProb(0,j + pureLabels));
    }
  }
  mixture.printMixture();
  intstatus = writeMixtureParameters(argv[4],mixture, true);
  if(intstatus != 0) {
    cout << "Error in writing the mixture parameters file" << argv[4] << endl;
    return(7);
  }
  return(0); 
}
Ejemplo n.º 12
0
 virtual void updateSigma(devs::Time)
 {
     setSigma(devs::Time(0.0));
 }