public void TestMethod2()
        {
            Topology t = new Topology(new int[] { 2048, 40 });

            int[] coords = new int[] { 200, 10 };
            var   indx   = HtmCompute.GetFlatIndexFromCoordinates(coords, t.HtmTopology);
        }
示例#2
0
 /**
  *
  *
  *
  * @param shape
  * @param useColumnMajorOrdering
  *
  *
  *
  */
 /// <summary>
 /// Constructs a new <see cref="Coordinator"/> object to be configured with specified dimensions and major ordering.
 /// </summary>
 /// <param name="shape">the dimensions of this sparse array</param>
 /// <param name="useColumnMajorOrdering">flag indicating whether to use column ordering or row major ordering. if false
 ///                                      (the default), then row major ordering will be used. If true, then column major
 ///                                      ordering will be used.</param>
 public Topology(int[] shape, bool useColumnMajorOrdering)
 {
     this.dimensions         = shape;
     this.numDimensions      = shape.Length;
     this.dimensionMultiples = InitDimensionMultiples(
         useColumnMajorOrdering ? HtmCompute.Reverse(shape) : shape);
     isColumnMajor = useColumnMajorOrdering;
 }
        /// <summary>
        /// Initialize all columns inside of partition and connect them to sensory input.
        /// It returns the average connected span of the partition.
        /// </summary>
        /// <param name="msg"></param>
        private void createAndConnectColumns(ConnectAndConfigureColumnsMsg msg)
        {
            DateTime startTime = DateTime.Now;

            Log(msg, Self, "Entered.");

            List <double> avgConnections = new List <double>();

            Random rnd;

            if (this.config.RandomGenSeed > 0)
            {
                rnd = new Random(this.config.RandomGenSeed);
            }
            else
            {
                rnd = new Random();
            }

            if (this.dict.Count == 0)
            {
            }

            foreach (var element in this.dict)
            {
                if (this.config == null)
                {
                    throw new ArgumentException($"HtmConfig must be set in the message.");
                }

                int colIndx = (int)element.Key;

                // Gets RF
                var potential = HtmCompute.MapPotential(this.config, colIndx, rnd);
                var column    = (Column)this.dict[colIndx];

                // This line initializes all synases in the potential pool of synapses.
                // It creates the pool on proximal dendrite segment of the column.
                // After initialization permancences are set to zero.
                //connectColumnToInputRF(c.HtmConfig, data.Potential, data.Column);
                column.CreatePotentialPool(this.config, potential, -1);

                var perms = HtmCompute.InitSynapsePermanences(this.config, potential, rnd);

                avgConnections.Add(HtmCompute.CalcAvgSpanOfConnectedSynapses(column, this.config));

                //Log(msg, Self, $".:). {dict.Count}/{dict.Keys.Min()}/{dict.Keys.Min()} - duration: {(DateTime.Now - startTime).TotalSeconds}");

                HtmCompute.UpdatePermanencesForColumn(this.config, perms, column, potential, true);
            }

            double avgConnectedSpan = ArrayUtils.average(avgConnections.ToArray());

            Log(msg, Self, "Completed.");
            Sender.Tell(avgConnectedSpan, Self);
            Log(msg, Self, $"Response sent. {(DateTime.Now - startTime).TotalSeconds}");
        }
        public void TestMethod3()
        {
            Topology t = new Topology(new int[] { 2048, 40 });

            int[] coords  = new int[] { 200, 10 };
            var   indx    = HtmCompute.GetFlatIndexFromCoordinates(coords, t.HtmTopology);
            var   coords2 = HtmCompute.GetCoordinatesFromIndex(indx, t.HtmTopology);

            Assert.AreEqual(coords[0], coords2[0]);
            Assert.AreEqual(coords[1], coords2[1]);
        }
示例#5
0
        /// <summary>
        /// This method updates the permanence matrix with a column's new permanence values. The column is identified by its index, which reflects the row in
        /// the matrix, and the permanence is given in 'sparse' form, (i.e. an array whose members are associated with specific indexes). It is in charge of
        /// implementing 'clipping' - ensuring that the permanence values are always between 0 and 1 - and 'trimming' - enforcing sparseness by zeroing out all
        /// permanence values below 'synPermTrimThreshold'. Every method wishing to modify the permanence matrix should do so through this method.
        /// </summary>
        /// <param name="htmConfig"></param>
        /// <param name="perm">An array of permanence values for a column. The array is "sparse", i.e. it contains an entry for each input bit, even if the permanence value is 0.</param>
        /// <param name="maskPotential">Indexes of potential connections to input neurons.</param>
        /// <param name="raisePerm">a boolean value indicating whether the permanence values</param>
        public void UpdatePermanencesForColumnSparse(HtmConfig htmConfig, double[] perm, int[] maskPotential, bool raisePerm)
        {
            if (raisePerm)
            {
                HtmCompute.RaisePermanenceToThresholdSparse(htmConfig, perm);
            }

            ArrayUtils.LessOrEqualXThanSetToY(perm, htmConfig.SynPermTrimThreshold, 0);
            ArrayUtils.EnsureBetweenMinAndMax(perm, htmConfig.SynPermMin, htmConfig.SynPermMax);
            SetProximalPermanencesSparse(htmConfig, perm, maskPotential);
        }
        public void NeighborhoodTest()
        {
            var parameters = GetDefaultParams();

            int cellsDim1 = 64;
            int cellsDim2 = 64;

            parameters.setInputDimensions(new int[] { 32 });
            parameters.setColumnDimensions(new int[] { cellsDim1 });

            var sp = new SpatialPooler();

            var mem = new Connections();

            parameters.apply(mem);
            sp.Init(mem);

            for (int rad = 1; rad < 10; rad++)
            {
                using (StreamWriter sw = new StreamWriter($"neighborhood-test-rad{rad}-center-from-{cellsDim1}-to-{0}.csv"))
                {
                    sw.WriteLine($"{cellsDim1}|{cellsDim2}|{rad}|First column defines center of neiborhood. All other columns define indicies of neiborhood columns");

                    for (int center = 0; center < 64; center++)
                    {
                        var nbs = HtmCompute.GetNeighborhood(center, rad, mem.HtmConfig.ColumnTopology.HtmTopology);

                        StringBuilder sb = new StringBuilder();

                        sb.Append(center);
                        sb.Append('|');

                        foreach (var neighobordCellIndex in nbs)
                        {
                            sb.Append(neighobordCellIndex);
                            sb.Append('|');
                        }

                        string str = sb.ToString();

                        sw.WriteLine(str.TrimEnd('|'));
                    }
                }
            }
        }
        void adaptSynapses(AdaptSynapsesMsg msg)
        {
            ParallelOptions opts = new ParallelOptions();

            opts.MaxDegreeOfParallelism = msg.ColumnKeys.Count;

            Parallel.ForEach(msg.ColumnKeys, opts, (colPair) =>
            {
                Column activeColumn = (Column)this.dict[colPair.Key];
                //Pool pool = c.getPotentialPools().get(activeColumns[i]);
                Pool pool     = activeColumn.ProximalDendrite.RFPool;
                double[] perm = pool.getDensePermanences(this.config.NumInputs);
                int[] indexes = pool.getSparsePotential();
                ArrayUtils.raiseValuesBy(msg.PermanenceChanges, perm);

                HtmCompute.UpdatePermanencesForColumn(this.config, perm, activeColumn, indexes, true);
            });

            // We send this to ensure reliable messaging. No other result is required here.
            Sender.Tell(0, Self);
        }
示例#8
0
        /// <summary>
        /// Initialize all columns inside of partition and connect them to sensory input.
        /// It returns the average connected span of the partition.
        /// </summary>
        /// <param name="msg"></param>
        //TODO remove unnecessary argument
        private double CreateAndConnectColumns(ConnectAndConfigureColumnsMsg msg)
        {
            Debug.Write(".");
            List <double> avgConnections = new List <double>();

            Random rnd;

            if (this.HtmConfig.RandomGenSeed > 0)
            {
                rnd = new Random(this.HtmConfig.RandomGenSeed);
            }
            else
            {
                rnd = new Random();
            }

            foreach (var element in this.Dict)
            {
                if (this.HtmConfig == null)
                {
                    throw new ArgumentException($"HtmConfig must be set in the message.");
                }

                int colIndx = -1;

                Column column;

                if (element.Key is string)
                {
                    if (!int.TryParse(element.Key as string, out colIndx))
                    {
                        throw new ArgumentException($"The key must be of type 'int' or string convertable to 'int");
                    }

                    column = (Column)this.Dict[element.Key];
                }
                else
                {
                    colIndx = (int)element.Key;
                    column  = (Column)this.Dict[colIndx];
                }

                // Gets RF
                var potential = HtmCompute.MapPotential(this.HtmConfig, colIndx, rnd);


                // This line initializes all synases in the potential pool of synapses.
                // It creates the pool on proximal dendrite segment of the column.
                // After initialization permancences are set to zero.
                //connectColumnToInputRF(c.HtmConfig, data.Potential, data.Column);
                column.CreatePotentialPool(this.HtmConfig, potential, -1);

                var perms = HtmCompute.InitSynapsePermanences(this.HtmConfig, potential, rnd);

                avgConnections.Add(HtmCompute.CalcAvgSpanOfConnectedSynapses(column, this.HtmConfig));

                HtmCompute.UpdatePermanencesForColumn(this.HtmConfig, perms, column, potential, true);
            }

            Debug.Write(".");

            double avgConnectedSpan = ArrayUtils.Average(avgConnections.ToArray());

            Debug.Write(".");
            return(avgConnectedSpan);
        }