Пример #1
0
TEST( WaveTable, Clone )
{
    int length       = randomInt( 2, 256 );
    float frequency  = randomFloat( 20, 880 );
    WaveTable* table = new WaveTable( length, frequency );

    table->setAccumulator( randomSample( 0.0, ( SAMPLE_TYPE ) length ));

    // randomly create content

    if ( randomBool() )
    {
        for ( int i = 0; i < length; ++i )
            table->getBuffer()[ i ] = randomSample( -1.0, 1.0 );
    }

    // create clone and validate its properties against the source table

    WaveTable* clone = table->clone();

    EXPECT_EQ( table->tableLength, clone->tableLength )
        << "expected cloned WaveTables length to equal the source WaveTables";

    EXPECT_EQ( table->getFrequency(), clone->getFrequency() )
        << "expected cloned WaveTable frequency to equal the source WaveTables";

    EXPECT_EQ( table->getAccumulator(), clone->getAccumulator() )
        << "expected cloned WaveTable accumulator to equal the source WaveTables";

    EXPECT_EQ( table->hasContent(), table->hasContent() )
        << "expected cloned WaveTable hasContent value to equal the source WaveTables";

    if ( table->hasContent() )
    {
        for ( int i = 0; i < length; ++i ) {
            EXPECT_EQ( table->getBuffer()[ i ], clone->getBuffer()[ i ])
                << "expected cloned WaveTable buffer to have equal buffer contents, but it didn't";
        }
    }
    delete table;
    delete clone;
}
Пример #2
0
void Sample::resample() {
    switch (_sampleType) {
    case SampleType::RANDOM:
        randomSample();
        break;
    case SampleType::JITTERED:
        jitteredSample();
        break;
    }
    switch (_filterType) {
    case FilterType::BOX:
        boxFilter();
        break;
    case FilterType::TENT:
        tentFilter();
        break;
    }
}
Пример #3
0
TEST( WaveTable, Accumulator )
{
    int length       = randomInt( 2, 256 );
    float frequency  = randomFloat( 20, 880 );
    WaveTable* table = new WaveTable( length, frequency );

    EXPECT_EQ( 0.0, table->getAccumulator() )
        << "expected WaveTable accumulator to be 0.0 upon construction";

    for ( int i = 0; i < randomInt( 1, 100 ); ++i )
    {
        SAMPLE_TYPE value = randomSample( 0.0, ( SAMPLE_TYPE ) length );
        table->setAccumulator( value );

        EXPECT_EQ( value, table->getAccumulator() )
            << "expected WaveTable accumulator to be " << value << " after setter, got " << table->getAccumulator() << " instead";
    }
    delete table;
}
Пример #4
0
TEST( WaveTable, HasContent )
{
    int length       = randomInt( 2, 256 );
    float frequency  = randomFloat( 20, 880 );
    WaveTable* table = new WaveTable( length, frequency );

    ASSERT_FALSE( table->hasContent() )
        << "expected WaveTable to have no content upon construction";

    SAMPLE_TYPE* buffer = table->getBuffer();

    for ( int i = 0; i < length; ++i )
        buffer[ i ] = randomSample( -1.0, 1.0 );

    ASSERT_TRUE( table->hasContent() )
        << "expected WaveTable to report to have content after assignment of sample values in buffer";

    delete table;
}
Пример #5
0
/**
 * Region Initialization (from Numenta docs):
 * Prior to receiving any inputs, the region is initialized by computing a list of initial
 * potential synapses for each column. This consists of a random set of inputs selected
 * from the input space. Each input is represented by a synapse and assigned a random
 * permanence value. The random permanence values are chosen with two criteria.
 * First, the values are chosen to be in a small range around connectedPerm (the minimum
 * permanence value at which a synapse is considered "connected"). This enables potential
 * synapses to become connected (or disconnected) after a small number of training
 * iterations. Second, each column has a natural center over the input region, and the
 * permanence values have a bias towards this center (they have higher values near
 * the center).
 *
 * In addition to this I have added a concept of Locality Radius, which is an
 * additional parameter to control how far away synapse connections can be made
 * instead of allowing connections anywhere.  The reason for this is that in the
 * case of video images I wanted to experiment with forcing each Column to only
 * learn on a small section of the total input to more effectively learn lines or
 * corners in a small section without being 'distracted' by learning larger patterns
 * in the overall input space (which hopefully higher hierarchical Regions would
 * handle more successfully).  Passing in 0 for locality radius will mean no restriction
 * which will more closely follow the Numenta doc if desired.
 *
 * @param inputSize: (x,y) size of input data matrix from the external source.
 * @param colGridSize: (x,y) number of Columns to create to represent this Region.
 * @param pctInputPerCol: Percent of input bits each Column has potential synapses for.
 * @param pctMinOverlap: Minimum percent of column's synapses for column to be considered.
 * @param localityRadius: Furthest number of columns away to allow distal synapses.
 * @param pctLocalActivity: Approximate percent of Columns within average receptive
 *  field radius to be winners after inhibition.
 * @param cellsPerCol: Number of (temporal context) cells to use for each Column.
 * @param segActiveThreshold: Number of active synapses to activate a segment.
 * @param newSynapseCount: number of new distal synapses added if none activated during
 *  learning.
 * @param inputData the array to be used for input data bits.  The contents
 *  of this array must be externally updated between time steps (between
 *  calls to Region.runOnce()).
 * @return a pointer to a newly allocated Region structure (NULL if any malloc calls
 *  have failed).
 */
Region* newRegion(int inputSizeX, int inputSizeY, int colGridSizeX, int colGridSizeY,
    float pctInputPerCol, float pctMinOverlap, int localityRadius,
    float pctLocalActivity, int cellsPerCol, int segActiveThreshold,
    int newSynapseCount, char* inputData) {

  Region* region = malloc(sizeof(Region));
  if(region==NULL) return NULL;

  region->inputWidth = inputSizeX;
  region->inputHeight = inputSizeY;
  region->nInput = region->inputWidth * region->inputHeight;
  region->iters = 0;
  region->inputData = inputData;

  region->localityRadius = localityRadius;
  region->cellsPerCol = cellsPerCol;
  region->segActiveThreshold = segActiveThreshold;
  region->newSynapseCount = newSynapseCount;

  region->pctInputPerCol = pctInputPerCol;
  region->pctMinOverlap = pctMinOverlap;
  region->pctLocalActivity = pctLocalActivity;

  region->spatialHardcoded = false;
  region->spatialLearning = true;
  region->temporalLearning = true;

  /*Reduce the number of columns and map centers of input x,y correctly.
  //column grid will be relative to size of input grid in both dimensions*/
  region->width = colGridSizeX;
  region->height = colGridSizeY;
  region->numCols = region->width*region->height;
  region->xSpace = (region->inputWidth-1*1.0) / fmaxf(1.0,(region->width-1));
  region->ySpace = (region->inputHeight-1*1.0) / fmaxf(1.0,(region->height-1));

  /*Create the columns based on the size of the input data to connect to.*/
  region->columns = malloc(region->numCols * sizeof(Column));
  if(region->columns==NULL) return NULL;

  int cx,cy;
  for(cx=0; cx<region->width; ++cx) {
    for(cy=0; cy<region->height; ++cy) {
      int srcPosX = roundf(cx*region->xSpace);
      int srcPosY = roundf(cy*region->ySpace);
      initColumn(&(region->columns[(cy*region->width)+cx]), region,
          srcPosX,srcPosY, cx,cy);
    }
  }

  /*  #size the output array as double grid for 4-cell, else just pad the first
  //  #array dimension for 2 or 3 cell (and same size if just 1-cell)
  //  if cellsPerCol==4:
  //    outShape = (len(self.columnGrid)*2, len(self.columnGrid[0])*2)
  //  else:
  //    outShape = (len(self.columnGrid)*cellsPerCol, len(self.columnGrid[0]))
  //  self.outData = numpy.zeros(outShape, dtype=numpy.uint8)*/

  /*how far apart are 2 Columns in terms of input space; calc radius from that*/
  float inputRadiusf = region->localityRadius*region->xSpace;

  /*Now connect all potentialSynapses for the Columns*/
  int synapsesPerSegment = 1;
  if(region->localityRadius==0)
    synapsesPerSegment = (region->inputWidth*region->inputHeight) * pctInputPerCol;
  else
    synapsesPerSegment = (inputRadiusf*inputRadiusf) * pctInputPerCol;

  /*The minimum number of inputs that must be active for a column to be
  //considered during the inhibition step.*/
  region->minOverlap = synapsesPerSegment * pctMinOverlap;

  /*int longerSide = max(_inputWidth, _inputHeight);
  //random.seed(42) #same connections each time for easier debugging*/

  /* create array of InputCells and array to hold subset of InputCells for
   * selecting random subsets within radius of spatial pooler columns */
  int i,s,x,y;
  int nc = region->nInput;
  region->inputCells = malloc(nc * sizeof(Cell));
  Cell** ssInputCells = malloc(nc * sizeof(Cell*));
  Cell** randCells = malloc(synapsesPerSegment * sizeof(Cell*));
  for(i=0; i<nc; ++i) {
    initInputCell(&(region->inputCells[i]), region, i);
    ssInputCells[i] = &(region->inputCells[i]);
  }

  int inputRadius = roundf(inputRadiusf);
  int minY = 0;
  int maxY = region->inputHeight-1;
  int minX = 0;
  int maxX = region->inputWidth-1;

  for(i=0; i<region->numCols; ++i) {
    if(region->spatialHardcoded) /*no proximal synpases for hardcoded case*/
      break;
    Column* col = &(region->columns[i]);

    /*restrict synapse connections if localityRadius is non-zero*/
    if(region->localityRadius > 0) {
      minY = max(0, col->iy-inputRadius);
      maxY = min(region->inputHeight-1, col->iy+inputRadius);
      minX = max(0, col->ix-inputRadius);
      maxX = min(region->inputWidth-1, col->ix+inputRadius);

      /*repopulate inputCells with cells within locality radius*/
      s=0;
      for(x=minX; x<=maxX; ++x) {
        for(y=minY; y<=maxY; ++y) {
          int index = (y*region->inputWidth)+x;
          ssInputCells[s++] = &(region->inputCells[index]);
        }
      }
      nc = s;
    }

    /*connect initial proximal synapses.
    //ensure we sample unique input positions to connect synapses to*/
    randomSample(ssInputCells, nc, randCells, synapsesPerSegment);

    /*printf("Column %d (%d, %d) connected to: ", i, col->cx, col->cy);*/
    for(s=0; s<synapsesPerSegment; ++s) {
      Cell* icell = randCells[s];
      /*printf("%d ", icell->index);*/
      if(FULL_DEFAULT_SPATIAL_PERMANENCE) {
        createSynapse(col->proximalSegment, icell, MAX_PERM);
      }
      else {
        /*default to all synapses having connected + 1/3.  Unused synapses will
         * be decremented away over time.  This is easier than having half the
         * synapses disconnected since it's harder for them to become connected
         * when first learning.*/
        int permanence = CONNECTED_PERM + (CONNECTED_PERM/3);
        createSynapse(col->proximalSegment, icell, permanence);
      }
    }
    /*printf("\n");*/

    processSegment(col->proximalSegment); /*calculate initial synapse connections*/

    /* This is code suggested by the Numenta doc.  I use fixed default permanence
     * instead to make initial learning faster/easier (based on my experiments).
    //    Util.createRandomSubset(allPos, randPos, synapsesPerSegment, rand);
    //    for(Point pt : randPos) {
    //      InputCell icell = new InputCell(
    //          pt.x, pt.y, (pt.y*_inputHeight)+pt.x, _inputData);
    //      if(FULL_DEFAULT_SPATIAL_PERMANENCE)
    //        col.addProximalSynapse(icell, 1.0f);
    //      else {
    //        double permanence = Synapse.CONNECTED_PERM +
    //                           (Synapse.PERMANENCE_INC*rand.nextGaussian());
    //        permanence = Math.max(0.0, permanence);
    //        double dx = col.ix()-pt.x;
    //        double dy = col.iy()-pt.y;
    //        double distance = Math.sqrt((dx*dx) + (dy*dy));
    //        double ex = distance / (longerSide*RAD_BIAS_STD_DEV);
    //        double localityBias = (RAD_BIAS_PEAK/0.4) * Math.exp((ex*ex)/-2);
    //        col.addProximalSynapse(icell, (float)(permanence*localityBias));
    //      }
    //    }*/
  }
  free(randCells);
  free(ssInputCells);

  if(!region->spatialHardcoded)
    region->inhibitionRadius = averageReceptiveFieldSize(region);
  else
    region->inhibitionRadius = 0;

  /*desiredLocalActivity A parameter controlling the number of columns that will be*/
  float dla = 0;
  if(region->localityRadius==0)
    dla = region->inhibitionRadius * region->pctLocalActivity;
  else
    dla = (region->localityRadius*region->localityRadius) * region->pctLocalActivity;
  region->desiredLocalActivity = max(2, round(dla));

  if(DEBUG) {
    printf("\nRegion Created (ANSI C)");
    printf("\ncolumnGrid = (%d, %d)", colGridSizeX, colGridSizeY);
    printf("\nxSpace, ySpace = %f %f", region->xSpace, region->ySpace);
    printf("\ninputRadius = %d", inputRadius);
    printf("\ninitial inhibitionRadius = %f", region->inhibitionRadius);
    printf("\ndesiredLocalActivity = %d", region->desiredLocalActivity);
    printf("\nsynapsesPerProximalSegment = %d", synapsesPerSegment);
    printf("\nminOverlap = %g", region->minOverlap);
    printf("\nconPerm,permInc = %i %i\n", CONNECTED_PERM, PERMANENCE_INC);
  }

  return region;
}
Пример #6
0
int main(int argc, char** argv)
{
  ifstream fin(argv[1],ios::in);
  int ngenes = 133772;
  int nsamples = 160;
  cout<<"make matrix"<<endl;
  mat Data = makeMatrix(fin, ngenes, nsamples);
  cout<<"finish making matrix"<<endl;
  uvec tumor(80), ctrl(80);
  for(int i=0; i<80; i++){
    tumor(i) = 2*i;
    ctrl(i) = 2*i+1;
  }

  mat tumorData = Data.cols(tumor);
  mat ctrlData = Data.cols(ctrl);
  tumorData = tumorData.t();
  ctrlData = ctrlData.t();
  
  //init boostup
  int nb = 100;
  int iter = 0;
  set<int> res;
  uvec sample(10);
  randomSample(sample, 10000+iter, 0, 79);

  mat tumorSample = tumorData.rows(sample);
  mat ctrlSample = ctrlData.rows(sample);
  network test(100000);
  makeNetwork(test, ctrlSample, 0.75);
  cout<<"successfully make network"<<endl;

  //到makeNetwork才会出现问题;
  /*
  double thes = 0.75;
  mat net1 = makeNetwork(tumorSample, thes);
  mat net2 = makeNetwork(ctrlSample, thes);
  cout<<"first statage"<<endl;
 
  mat resnet = mergeNetwork(net1, net2);
  uvec indices = find(resnet==1);
  res = getGeneSet(indices, 10);
  iter++;
  set<int>::iterator it_test = res.begin();
  for(;it_test != res.end(); it_test++)
    cout<<*it_test<<" ";
  cout<<endl;
  while(iter < nb){
    randomSample(sample, 10000+iter, 0,79);
    tumorSample = tumorData.rows(sample);
    ctrlSample = ctrlData.rows(sample);
    net1 = makeNetwork(tumorSample, thes);
    net2 = makeNetwork(ctrlSample, thes);
    resnet = mergeNetwork(net1, net2);
    indices = find(resnet==1);
    set<int> tmpset = getGeneSet(indices, 10);
    set_intersection(tmpset.begin(),tmpset.end(),res.begin(),res.end(), inserter(res, res.end()));
    iter++;
  }
  cout<<"after boostrap:"<<endl;
  for(it_test=res.begin();it_test!=res.end();it_test++)
    cout<<*it_test<<" ";
  cout<<endl;
  */
  return 0;
}