Пример #1
0
        public DistalSynapse( Cell inputSource, float permanence )
        {
            // Set fields
            this.InputSource = inputSource;
            this.Permanence = permanence;

            SelectablelType = SelectableObjectType.DistalSynapse;
        }
Пример #2
0
		/// <summary>
		/// Helper Method to get color from cell activity
		/// </summary>
		/// <param name="cell"></param>
		/// <param name="color"></param>
		/// <param name="alphaValue"></param>
		private void GetColorFromCell(Cell cell, out Color color, out float alphaValue)
		{
			color = this._dictionaryCellColors[HtmCellColors.Inactive].HtmColor;
			alphaValue = .1f; // All conditions can be false. 
			Simulation3DForm visualizerForm = Simulation3D.Form;

			try
			{
				// Currently predicting cells.
				if (visualizerForm.ShowPredictingCells && cell.PredictiveState[Global.T])
				{
					if (cell.IsSegmentPredicting)
					{
						// Sequence predicting cells (t+1).
						if (visualizerForm.ShowSeqPredictingCells)
						{
							alphaValue = 1f;
							color = this._dictionaryCellColors[HtmCellColors.SequencePredicting].HtmColor;
						}
					}
					else
					{
						// Lost predicting cells for t+k.
						alphaValue = 1f;
						color = this._dictionaryCellColors[HtmCellColors.Selected].HtmColor;

						// New predicting cells for t+k.
						foreach (var segment in cell.DistalSegments)
						{
							if (segment.ActiveState[Global.T])
							{
								color = this._dictionaryCellColors[HtmCellColors.Predicting].HtmColor;
							}
						}
					}
				}

				// Learning in t+0.
				if (visualizerForm.ShowLearningCells && cell.LearnState[Global.T])
				{
					alphaValue = 1f;
					color = this._dictionaryCellColors[HtmCellColors.Learning].HtmColor;
				}
				else // Learning cells are all active
					if (visualizerForm.ShowActiveCells && cell.ActiveState[Global.T])
					{
						alphaValue = 1f;
						color = this._dictionaryCellColors[HtmCellColors.Active].HtmColor;
					}

				// Sequence predicted cells.
				if (cell.GetSequencePredictingDistalSegment () != null)
				{
					// False predicted cells.
					if (visualizerForm.ShowFalsePredictedCells && !cell.ActiveState[Global.T])
					{
						alphaValue = 1f;
						color = this._dictionaryCellColors[HtmCellColors.FalsePrediction].HtmColor;
					}

					// Correctly predicting in t+0.
					if (visualizerForm.ShowCorrectPredictedCells && cell.ActiveState[Global.T])
					{
						alphaValue = 1f;
						color = this._dictionaryCellColors[HtmCellColors.RightPrediction].HtmColor;
					}
				}
			}
			catch (Exception)
			{
				
			}
		}
Пример #3
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Segment"/> class.
 /// </summary>
 internal DistalSegment( Cell cell)
 {
     this.parentCell = cell;
 }
Пример #4
0
 /// <summary>
 /// Create a new synapse for this segment attached to the specified lateral cell.
 /// </summary>
 /// <param name="lateralCell">the lateral cell of the synapse to create.</param>
 /// <param name="initialPermanence">the initial permanence of the synapse.</param>
 internal void CreateSynapse(Cell lateralCell, float initialPermanence)
 {
     var newSynapse = new DistalSynapse(this, lateralCell, initialPermanence);
     this.Synapses.Add(newSynapse);
 }
Пример #5
0
		public void DrawCellRectangle(Cell cell, Graphics grpOnBitmap, Color color,
			bool drawFill, bool drawOutline)
		{
			Point cellPoint;
			Size cellSize;
			this.GetCellDisplayPointAndSize(cell, out cellPoint, out cellSize);

			if (drawFill)
			{
				grpOnBitmap.FillRectangle(new SolidBrush(color),
										  cellPoint.X, cellPoint.Y,
										  cellSize.Width, cellSize.Height);
			}

			if (drawOutline)
			{
				grpOnBitmap.DrawRectangle(new Pen(Color.WhiteSmoke, 1),
										  cellPoint.X, cellPoint.Y,
										  cellSize.Width, cellSize.Height);
			}
		}
Пример #6
0
		public void GetCellDisplayPointAndSize(Cell cell, out Point displayPoint, out Size displaySize)
		{
			PointF cellLocation;
			SizeF cellSize;
			this.GetCellVirtualPointAndSize(cell, out cellLocation, out cellSize);

			displayPoint = this.ConvertViewPointToDisplayPoint(cellLocation);
			displaySize = this.GetSizeOnDisplay(cellSize);
		}
Пример #7
0
        ///<summary>
        ///Create a new SegmentUpdate that is to modify the state of the Region
        ///either by adding a new segment to a cell, new synapses to a segemnt,
        ///or updating permanences of existing synapses on some segment.
        ///</summary>
        ///<param name="cell">cell the cell that is to have a segment added or updated.
        ///  </param>
        ///<param name="distalSegment">the segment that is to be updated (null here means a new
        ///  segment is to be created on the parent cell).</param> 
        ///<param name="activeDistalSynapses">the set of active synapses on the segment 
        ///  that are to have their permanences updated.</param> 
        ///<param name="addNewSynapses">set to true if new synapses are to be added to the
        ///  segment (or if new segment is being created) or false if no new synapses
        ///  should be added instead only existing permanences updated.</param> 
        ///
        public SegmentUpdate(Cell cell, DistalSegment distalSegment, List<Synapse> activeDistalSynapses,
		                     bool addNewSynapses = false)
        {
            // Set fields
            this.Cell = cell;
            this.DistalSegment = distalSegment;
            this.ActiveDistalSynapses = new List<Synapse>(activeDistalSynapses);
            this.AddNewSynapses = addNewSynapses;
            this.CellsToConnect = new List<Cell>();
            this.NumberPredictionSteps = 1;
            this.CreationStep = (int) cell.Statistics.StepCounter;

            // Set of cells that have LearnState output = true at time step t.
            var cellsToConnect = new List<Cell>();

            // If adding new synapses, find the current set of learning cells within
            // the Region and select a random subset of them to connect the segment to.
            // Do not add > 1 synapse to the same cell on a given segment
            Region region = this.Cell.Column.Region;

            if (this.AddNewSynapses)
            {
                // Gather all cells from segment in order to avoid use them as learning cells.
                var cellsInSegment = new List<Cell>();
                if (distalSegment != null)
                {
                    foreach (var synapse in distalSegment.Synapses)
                    {
                        if (synapse is DistalSynapse)
                        {
                            cellsInSegment.Add(((DistalSynapse) synapse).InputSource);
                        }
                    }
                }

                // Define limits to choose cells to connect.
                int minY, maxY, minX, maxX;
                if (region.LocalityRadius > 0)
                {
                    // Only allow connecting to Columns within locality radius
                    minX = Math.Max(0, cell.Column.PositionInRegion.X - region.LocalityRadius);
                    minY = Math.Max(0, cell.Column.PositionInRegion.Y - region.LocalityRadius);
                    maxX = Math.Min(region.Size.Width - 1,
                                    cell.Column.PositionInRegion.X + region.LocalityRadius);
                    maxY = Math.Min(region.Size.Height - 1,
                                    cell.Column.PositionInRegion.Y + region.LocalityRadius);
                }
                else
                {
                    // Now I want to allow connections over all the region!
                    // If locality radius is 0, it means 'no restriction'
                    minX = 0;
                    minY = 0;
                    maxX = region.Size.Width - 1;
                    maxY = region.Size.Height - 1;
                }

                // Set of cells that have LearnState output = true at time step t.
                for (int x = minX; x <= maxX; x++)
                {
                    for (int y = minY; y <= maxY; y++)
                    {
                        Column column = region.GetColumn(x, y);

                        // Skip cells in our own column (don't connect to ourself)
                        if (column != cell.Column)
                        {
                            foreach (var learningCell in column.Cells)
                            {
                                // Skip cells that already are linked to the segment (case it exists).
                                if (learningCell.LearnState[Global.T - 1] && !cellsInSegment.Contains(learningCell))
                                {
                                    cellsToConnect.Add(learningCell);
                                }
                            }
                        }
                    }
                }
            }

            // Basic allowed number of new Synapses
            int newNumberSynapses = region.NumberNewSynapses;
            if (distalSegment != null)
            {
                newNumberSynapses = Math.Max(0, newNumberSynapses - activeDistalSynapses.Count);
            }

            // Clamp at learn cells
            newNumberSynapses = Math.Min(cellsToConnect.Count, newNumberSynapses);

            // Randomly choose (newNumberSynapses) learning cells to add connections to
            if (cellsToConnect.Count > 0 && newNumberSynapses > 0)
            {
                this.CellsToConnect = this.ChooseRandomCells(cellsToConnect, newNumberSynapses);
            }
        }
Пример #8
0
		private float PickDistalSynapseConnections ( Ray ray, Column column, Cell cell, ref DistalSynapse returnedDistalSynapse )
		{
			float intersectDistance;
			float minDistance = float.MaxValue;

			returnedDistalSynapse = null;

			// Draw Connections if existing
			if (cell.IsDataGridSelected ||
				(Simulation3D.Form.ShowTemporalLearning && cell.PredictiveState[Global.T]))
			{
				Vector3 rayP1 = ray.Position;
				Vector3 rayP2 = rayP1 + ray.Direction;

				foreach (DistalSegment segment in cell.DistalSegments)
				{
					foreach (DistalSynapse synapse in segment.Synapses)
					{
						synapse.mouseOver = false;

						var distalSynapse = synapse as DistalSynapse;

						// Get the two vectors to draw line between
						var startPosition = new Vector3 ( column.PositionInRegion.X, cell.Index, column.PositionInRegion.Y + _zHtmRegion );

						// Get input source position
						int x = distalSynapse.InputSource.Column.PositionInRegion.X;
						int y = distalSynapse.InputSource.Index;
						int z = distalSynapse.InputSource.Column.PositionInRegion.Y;
						var endPosition = new Vector3 ( x, y, z + _zHtmPlane );

						bool intersect;
						Vector3 Line1ClosestPt = new Vector3 ();
						Vector3 Line2ClosestPt = new Vector3 ();
						intersect = Math3D.ClosestPointsLineSegmentToLine ( out Line1ClosestPt, out Line2ClosestPt, startPosition, endPosition, rayP1, rayP2, 0.1f, out intersectDistance );

						if (intersect && intersectDistance < minDistance)
						{
							minDistance = intersectDistance;
							returnedDistalSynapse = synapse;
						}
					}
				}
			}

			return minDistance;
		}
Пример #9
0
			public DistalSynapseComparisonCopy(Cell outputCell,
											   DistalSynapse originalSynapse, DistalSynapse savedSynapse)
			{
				this.OutputCell = outputCell;
				this.OriginalSynapse = originalSynapse;
				this.SavedSynapse = savedSynapse;
			}
Пример #10
0
		private void DrawConnectionBetweenCells(Graphics grpOnBitmap, Cell outputCell,
			Cell inputCell, Color color, string text, bool dashed = false)
		{
			SizeF cellSize;
			PointF cellStartPointVirtual, cellEndPointVirtual;
			this.GetCellVirtualPointAndSize(inputCell, out cellStartPointVirtual, out cellSize);
			this.GetCellVirtualPointAndSize(outputCell, out cellEndPointVirtual, out cellSize);

			// Note that the start and end points are from the center of the
			// cell rectangle, that's why we add cell size / 2
			// To the start points of the cell rectangles.
			cellStartPointVirtual.X += cellSize.Width / 2;
			cellEndPointVirtual.X += cellSize.Width / 2;
			cellStartPointVirtual.Y += cellSize.Height / 2;
			cellEndPointVirtual.Y += cellSize.Height / 2;

			Point pntConnectionStart = this.ConvertViewPointToDisplayPoint(cellStartPointVirtual);
			Point pntConnectionEnd = this.ConvertViewPointToDisplayPoint(cellEndPointVirtual);

			PointF closestPoint;
			double distanceToLine = this.FindDistanceToLineSegment(this._lastMouseLocation,
																   pntConnectionStart, pntConnectionEnd, out closestPoint);

			bool focusedOnConnection = false;
			float connectionWidth = 5.0f;
			if (distanceToLine < 10)
			{
				focusedOnConnection = true;
				connectionWidth = 30f;
			}

			var pen = new Pen(color, connectionWidth);
			pen.StartCap = LineCap.Round;
			pen.EndCap = LineCap.ArrowAnchor;
			if (dashed)
			{
				pen.DashStyle = DashStyle.Dash;
			}

			grpOnBitmap.DrawLine(pen,
								 pntConnectionStart, pntConnectionEnd);

			// If the user focuses on the connection with the mouse, 
			// Then display the permanence.
			if (focusedOnConnection)
			{
				// Draw text on top of the line.
				GraphicsState gs = grpOnBitmap.Save();

				var angleOfConnectionRadians = (float)Math.Atan2(pntConnectionEnd.Y - pntConnectionStart.Y,
																  pntConnectionEnd.X - pntConnectionStart.X);
				float angleOfConnectionDegrees =
					MathHelper.ToDegrees(angleOfConnectionRadians);
				if ((angleOfConnectionDegrees < 90) && (angleOfConnectionDegrees >= 0))
				{
					angleOfConnectionDegrees += 180;
				}
				else if ((angleOfConnectionDegrees <= 0) && (angleOfConnectionDegrees >= -90))
				{
					angleOfConnectionDegrees += 180;
				}

				var font = new Font("Arial", 12);
				SizeF textSize = grpOnBitmap.MeasureString(text, font);
				grpOnBitmap.RotateTransform(angleOfConnectionDegrees + 180);
				var pntConnectionCenter = new Point((pntConnectionStart.X + pntConnectionEnd.X) / 2,
													(pntConnectionStart.Y + pntConnectionEnd.Y) / 2);
				var pntStringDrawingPoint = new Point((int)(pntConnectionCenter.X - (textSize.Width / 2)),
													  (int)(pntConnectionCenter.Y - (textSize.Height / 2)));
				grpOnBitmap.TranslateTransform(pntConnectionCenter.X,
											   pntConnectionCenter.Y, MatrixOrder.Append);

				grpOnBitmap.DrawString(text, font, Brushes.Black, 0, 0);

				grpOnBitmap.Restore(gs);
			}
		}
Пример #11
0
        public void TestSynapse()
        {
            this.DefaultSynapseValues();

            var cell = new Cell(null, 0);
            cell.ActiveState[Global.T] = true;
            cell.LearnState[Global.T] = true;

            Synapse syn = new DistalSynapse(cell, Synapse.ConnectedPermanence);
            Assert.Equal(true, syn.IsConnected());

            Assert.Equal(true, syn.IsActive(Global.T));
            Assert.Equal(false, syn.IsActive(Global.T - 1));
            Assert.Equal(false, syn.IsActiveFromLearning(Global.T - 1));

            syn.DecreasePermanence();
            Assert.Equal(false, syn.IsConnected());
            Assert.Equal(true, syn.IsActive(Global.T));

            cell.ActiveState[Global.T] = false;
            Assert.Equal(false, syn.IsActive(Global.T));
        }
Пример #12
0
        private void dataGridCells_SelectionChanged( object sender, EventArgs e )
        {
            if (this.dataGridCells.SelectedRows.Count > 0)
            {
                // Get old selection
                if (this._selectedCell != null)
                {
                    this._selectedCell.IsDataGridSelected = false;
                }

                // Retrieve selected Column
                this._selectedCell = this.dataGridCells.SelectedRows[0].DataBoundItem as Cell;
                this._selectedCell.IsDataGridSelected = true;

                // Deactivate Column selection:
                Column selectedColumn = this._selectedCell.Column;
                selectedColumn.IsDataGridSelected = false;
            }
        }
Пример #13
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DistalSynapse"/> class and 
 /// sets its input source and initial permanance values.
 /// </summary>
 /// <param name="distalSeg">
 /// </param>
 /// <param name="inputSource">
 /// An object providing source of the input to this synapse (either 
 /// a <see cref="Column"/>'s <see cref="Cell"/> or a special 
 /// <see cref="InputCell"/>).
 /// </param>
 /// <param name="permanence">Initial permanence value.</param>
 public DistalSynapse(DistalSegment distalSeg, Cell inputSource, float permanence)
     : this(inputSource, permanence)
 {
     // Set fields
     this.DistalSegment = distalSeg;
 }
Пример #14
0
		/// <summary>
		/// Draw distal synapse connections for chosen cells
		/// </summary>
		/// <param name="worldTranslation"></param>
		/// <param name="worldRotate"></param>
		/// <param name="column"></param>
		/// <param name="cell"></param>
		private void DrawDistalSynapseConnections(ref Matrix worldTranslation, 
			ref Matrix worldRotate, Column column, Cell cell)
		{
			try
			{
				// Draw Connections if existing
				if (cell.IsDataGridSelected || 
					(Simulation3D.Form.ShowTemporalLearning && cell.PredictiveState[Global.T]))
				{
					foreach (var segment in cell.DistalSegments)
					{
						foreach (var synapse in segment.Synapses)
						{
							var distalSynapse = synapse as DistalSynapse;

							// Get the two vectors to draw line between
							var startPosition = new Vector3(column.PositionInRegion.X,
								cell.Index, column.PositionInRegion.Y);

							// Get input source position
							int x = distalSynapse.InputSource.Column.PositionInRegion.X;
							int y = distalSynapse.InputSource.Index;
							int z = distalSynapse.InputSource.Column.PositionInRegion.Y;
							var endPosition = new Vector3(x, y, z);

							//Color color = distalSynapse.IsActive(Global.T) ? Color.Black : Color.White;
							Color color;
							float alphaValue;
							GetColorFromDistalSynapse ( distalSynapse, out color, out alphaValue );
							this._connectionLine.SetUpVertices(startPosition, endPosition, color);

							// Draw line
							this._connectionLine.Draw(worldTranslation * worldRotate,
								this._viewMatrix, this._projectionMatrix);
						}
					}
				}
			}
			catch (Exception)
			{
				// Is sometimes raised because of collections modification by another thread.
			}
		}
Пример #15
0
			public DistalSynapseChange(DistalSynapse synapse, Cell outputCell,
									   EDistalSynapseChange change, string changeText)
			{
				this.Synapse = synapse;
				this.OutputCell = outputCell;
				this.ChangeType = change;
				this.ChangeText = changeText;
			}
Пример #16
0
		private float PickCell ( Ray ray, Matrix worldTranslation, Column column, Cell cell, ref Cell returnedCell )
		{
			cell.mouseOver = false;

			BoundingBox box = this._cube.GetBoundingBox ( worldTranslation );

			float? intersectDistance = ray.Intersects ( box );

			if (intersectDistance != null)
			{
				returnedCell = cell;
				return (float)intersectDistance;
			}
				
			return float.MaxValue;
		}
Пример #17
0
		public void GetCellVirtualPointAndSize(Cell cell, out PointF absolutePositionCell, out SizeF sizeCell)
		{
			// Relative cell position in column
			var relativePositionCell = new PointF();
			relativePositionCell.Y = cell.Index / this._numberCellsInColumn.Width;
			relativePositionCell.X = cell.Index % this._numberCellsInColumn.Width;

			// Absolute cell position in column
			absolutePositionCell = new PointF();
			absolutePositionCell.X = cell.Column.PositionInRegion.X +
									 relativePositionCell.X * this._sizeCellInColumn.Width;
			absolutePositionCell.Y = cell.Column.PositionInRegion.Y +
									 relativePositionCell.Y * this._sizeCellInColumn.Height;
			sizeCell = new SizeF(this._sizeCellInColumn.Width, this._sizeCellInColumn.Height);

			// If the viewer mode is sideview of the cells,
			// Calculate the position and size differently.
			if (this._viewerMode == Mode.ColumnsSideView)
			{
				PointF positionColumn;
				SizeF sizeColumn;
				this.GetColumnVirtualPointAndSize(cell.Column, out positionColumn, out sizeColumn);
				absolutePositionCell = positionColumn;
				absolutePositionCell.Y = _sizeColumnInVirtual.Height * cell.Index;
				sizeCell = _sizeColumnInVirtual;
			}
		}
Пример #18
0
		//Keep track of nearest object by setting others to null.
		private void TrackNearestObject ( float distance, ref float nearestDistance, Cell returnedCell, ref Cell nearestCell, DistalSynapse returnedDistalSynapse, ref DistalSynapse nearestDistalSynapse, ProximalSynapse returnedProximalSynapse, ref ProximalSynapse nearestProximalSynapse )
		{
			if (distance < nearestDistance)
			{
				nearestDistance = distance;

				if (returnedCell != null)
				{
					nearestCell = returnedCell;
					nearestDistalSynapse = null;
					nearestProximalSynapse = null;
				}
				if (returnedDistalSynapse != null)
				{
					nearestCell = null;
					nearestDistalSynapse = returnedDistalSynapse;
					nearestProximalSynapse = null;
				}
				if (returnedProximalSynapse != null)
				{
					nearestCell = null;
					nearestDistalSynapse = null;
					nearestProximalSynapse = returnedProximalSynapse;
				}
			}
		}
Пример #19
0
        /// <summary>
        /// Randomly sample values (numberRandomSamples) from the Cell array of length n (numberRandomSamples less than n).
        /// Runs in O(2 numberRandomSamples) worst case time.
        /// Result is written to the result array of length m containing the randomly chosen cells.
        /// </summary>
        /// <param name="cells">input Cells to randomly choose from.</param>
        /// <param name="numberRandomSamples">the number of random samples to take 
        ///   (numberRandomSamples less than equal to resultCells.Length)</param>
        private List<Cell> ChooseRandomCells(List<Cell> cells, int numberRandomSamples)
        {
            var resultCells = new Cell[numberRandomSamples];

            int numberCells = cells.Count;
            int currentLenght = 0;
            for (int i = numberCells - numberRandomSamples; i < numberCells; i++)
            {
                int position = _random.Next(i + 1);
                Cell cell = cells[position];

                // If (subset contains item already) then use item[i] instead
                bool contains = false;
                for (int j = 0; j < currentLenght; ++j)
                {
                    Cell initialResultCell = resultCells[j];
                    if (initialResultCell == cell)
                    {
                        contains = true;
                        break;
                    }
                }
                if (contains)
                {
                    resultCells[currentLenght] = cells[i];
                }
                else
                {
                    resultCells[currentLenght] = cell;
                }

                currentLenght++;
            }

            return new List<Cell>(resultCells);
        }