Esempio n. 1
0
 // Author: Greg Kulasik
 public void Draw()
 {
     foreach (Block b in blocks)
     {
         SOM.drawBox(b.GetX(), b.GetY(), b.color);
     }
 }
Esempio n. 2
0
        /// <summary>
        /// Changes initial Root Wt to an array.
        /// </summary>
        /// <param name="root">The root JSON token.</param>
        /// <param name="fileName">The name of the apsimx file.</param>
        private static void UpgradeToVersion55(JObject root, string fileName)
        {
            foreach (var SOM in JsonUtilities.ChildrenOfType(root, "SoilOrganicMatter"))
            {
                double soilcnr;
                if (SOM["SoilCN"] is JArray)
                {
                    soilcnr = Convert.ToDouble(SOM["SoilCN"][0], CultureInfo.InvariantCulture); // This can happen when importing old APSIM file.
                }
                else
                {
                    soilcnr = Convert.ToDouble(SOM["SoilCN"], CultureInfo.InvariantCulture);
                }
                SOM.Remove("SoilCN");
                double[] thickness = MathUtilities.StringsToDoubles(JsonUtilities.Values(SOM, "Thickness"));

                double[] SoilCNVector = new double[thickness.Length];

                for (int layer = 0; layer < thickness.Length; layer++)
                {
                    SoilCNVector[layer] = soilcnr;
                }

                JsonUtilities.SetValues(SOM, "SoilCN", SoilCNVector);
            }
        }
Esempio n. 3
0
        public void Dataset_GetInstance_WithLabelsAndKeys()
        {
            // Arrange
            string  filename = @"Dataset\Iris.csv";
            IReader reader   = new CSVReader(filename);
            SOM     som      = new SOM();

            som.GetData(reader);

            Dataset dataset = som.Dataset;

            dataset.SetKey("Id");
            dataset.SetLabel("Species");

            // Act
            double[] result = dataset.GetInstance <double>(0);


            // Assert
            int    expectedCount = 4;
            double x1            = 5.1;
            double x2            = 3.5;
            double x3            = 1.4;
            double x4            = 0.2;

            Assert.AreEqual(expectedCount, result.Length);
            Assert.AreEqual(x1, result[0]);
            Assert.AreEqual(x2, result[1]);
            Assert.AreEqual(x3, result[2]);
            Assert.AreEqual(x4, result[3]);
        }
        void setAllowed(SOM allowed)
        {
            foreach (SOM value in Enum.GetValues(typeof(SOM)))
            {
                if (allowed.HasFlag(value))
                {
                    switch (value)
                    {
                    case SOM.Joy:
                        SoMJoyRadio.Enabled = true;
                        break;

                    case SOM.Anger:
                        SoMAngerRadio.Enabled = true;
                        break;

                    case SOM.Fear:
                        SoMFearRadio.Enabled = true;
                        break;

                    case SOM.Sorrow:
                        SoMSorrowRadio.Enabled = true;
                        break;
                    }
                }
            }
        }
Esempio n. 5
0
        /// <summary>
        /// </summary>
        /// <param name="root">The root JSON token.</param>
        /// <param name="fileName">The name of the apsimx file.</param>
        private static void UpgradeToVersion52(JObject root, string fileName)
        {
            foreach (var SOM in JsonUtilities.ChildrenOfType(root, "SoilOrganicMatter"))
            {
                double rootWt = Convert.ToDouble(SOM["RootWt"]);
                SOM.Remove("RootWt");
                double[] thickness = MathUtilities.StringsToDoubles(JsonUtilities.Values(SOM, "Thickness"));

                double   profileDepth   = MathUtilities.Sum(thickness);
                double   cumDepth       = 0;
                double[] rootWtFraction = new double[thickness.Length];

                for (int layer = 0; layer < thickness.Length; layer++)
                {
                    double fracLayer = Math.Min(1.0, MathUtilities.Divide(profileDepth - cumDepth, thickness[layer], 0.0));
                    cumDepth += thickness[layer];
                    rootWtFraction[layer] = fracLayer * Math.Exp(-3.0 * Math.Min(1.0, MathUtilities.Divide(cumDepth, profileDepth, 0.0)));
                }
                // get the actuall FOM distribution through layers (adds up to one)
                double totFOMfraction = MathUtilities.Sum(rootWtFraction);
                for (int layer = 0; layer < thickness.Length; layer++)
                {
                    rootWtFraction[layer] /= totFOMfraction;
                }
                double[] rootWtVector = MathUtilities.Multiply_Value(rootWtFraction, rootWt);

                JsonUtilities.SetValues(SOM, "RootWt", rootWtVector);
            }
        }
 public SoMSelectorForm(SOM allowed, Result result)
 {
     InitializeComponent();
     this.allowed = allowed;
     this.result  = result;
     setAllowed(allowed);
     setLabel(result);
 }
Esempio n. 7
0
        public IActionResult Index()
        {
            Map map = new Map(25);
            SOM som = new SOM(map, 20);

            map.InitializeNodeWeights();
            HomeViewModel model = new HomeViewModel(som);

            return(View(model));
        }
Esempio n. 8
0
        static void Main(string[] args)
        {
            int[] layerSizes = new int[3] {
                3, 4, 1
            };
            TransferFunction[] TFuncs = new TransferFunction[3] {
                TransferFunction.None,
                TransferFunction.Sigmoid,
                TransferFunction.Linear
            };

            BackPropagationNetwork bpn = new BackPropagationNetwork(layerSizes, TFuncs);

            double[] input   = new double[] { 4, 6, 8 }; //, new double[] {4, 7, 5}, new double[] {7, 4, 8}, new double[] {6, 7, 5}, new double[] {7, 7, 8}};
            double[] desired = new double[] { -0.86 };   //, new double[] {0.15}, new double[] {0.72 }, new double[] {0.53 }, new double[] { 0.44 } };

            /*double[] output = new double[1];
             *
             *
             * double error = 0.0;
             *
             * for(int i = 0; i < 10; i++)
             * {
             *
             *      error = bpn.Train(ref input, ref desired, 0.15, 0.1);
             *      bpn.Run(ref input, out output);
             *      if (i % 1 == 0)
             *          Console.WriteLine("Iteration {0}: \n\t Input {1:0.000} {2:0.000} {3:0.000} Output {4:0.000} error{5:0.000}", i, input[0], input[1], input[2], output[0], error);
             *
             *
             * }*/

            double[][] inputs =
            {
                new double[] {  0.4, 11.8,  0.1 },
                new double[] {  1.9,  1.9, 19.5 },
                new double[] {  1.2, 23.2,  0.3 },
                new double[] { 20.9,  0.0,  7.9 },
                new double[] { 13.0, 19.0, 11.0 },
                new double[] { 15.5,  2.9, 68.3 }
            };

            string[] names = new string[] { "Apples", "Avocado", "Leave", "Beef Steak", "Jam", "Brazil Nuts" };

            SOM somnetwork = new SOM(3, names, inputs);

            Console.WriteLine("----");
            string row = "Water";

            double[] water  = new double[] { 0.0, 0.0, 0.0 };
            int[]    result = somnetwork.Result(water);
            Console.WriteLine(row + " " + result[0] + " " + result[1]);

            Console.ReadKey();
        }
Esempio n. 9
0
        private void StartButton_Click(object sender, EventArgs e)
        {
            GenerateRandomInput();               // генеруємо дані
            somnetwork = new SOM(length, input); // створюємо і вчимо мережу

            // Прив'язка таблиць до DataGriedView
            GeneratedNumbers.DataSource = GeneratedTable;
            Result.DataSource           = ResultTable;
            insert.DataSource           = ParametersTable;

            // Створення колонок у таблицях
            GeneratedTable.Columns.Add("ID");
            for (int i = 0; i < parameters; i++)
            {
                string str = Convert.ToString(i + 1);
                GeneratedTable.Columns.Add(str);
            }

            ResultTable.Columns.Add("ID");
            ResultTable.Columns.Add("Winning Neuron coordinates");
            ResultTable.Columns.Add("Cluster");

            ParametersTable.Columns.Add("Parameters");

            // Додавання рядків у таблиці
            for (int i = 0; i < size; i++)
            {
                DataRow row = GeneratedTable.NewRow();
                row[0] = i + 1;
                for (int j = 0; j < parameters; j++)
                {
                    row[j + 1] = Math.Round(input[i][j], 3);
                }
                GeneratedTable.Rows.Add(row);
            }

            int[][] result = somnetwork.Result();

            for (int i = 0; i < size; i++)
            {
                DataRow row = ResultTable.NewRow();
                row[0] = i + 1;
                row[1] = Convert.ToString(result[i][0] + "; " + result[i][1]);
                row[2] = result[i][2];
                ResultTable.Rows.Add(row);
            }

            for (int i = 0; i < parameters; i++)
            {
                DataRow row = ParametersTable.NewRow();
                ParametersTable.Rows.Add(row);
            }
        }
Esempio n. 10
0
        void ISoMSelector.acquireSoM(SOM allowed, Result result)
        {
            DataPlayer active = Turn == 0?Player1:Player2;

            (this as IGameObservable).notifyObservers(Messages.GameMessages.GetSOM, active,
                                                      new List <object>()
            {
                new SoMRequest()
                {
                    Allowed = allowed, Result = result
                }
            });
        }
Esempio n. 11
0
        SOM IMatchView.selectSoM(SOM allowed, Result result)
        {
            SoMSelectorForm somForm = new SoMSelectorForm(allowed, result);
            DialogResult    d       = somForm.ShowDialog();

            if (d.Equals(DialogResult.OK))
            {
                return(somForm.Selected);
            }
            else
            {
                return(SOM.None);
            }
        }
Esempio n. 12
0
        private static List <Node> GetFlattenedMap(SOM mSom)
        {
            var flattenedNodes = new List <Node>();

            for (int i = 0; i < mSom.Width; i++)
            {
                for (int k = 0; k < mSom.Width; k++)
                {
                    flattenedNodes.Add(mSom.Map[i, k]);
                }
            }

            return(flattenedNodes);
        }
Esempio n. 13
0
        // Author: Tom Zdanowski and Nathan Hester
        public static void Draw(GameState state)
        {
            // 1. Sets up the so called background which involves the container and preview window
            SOM.drawBackground();

            // 2. add activeShape and nextShape via getter and setter from GameState
            state.getActiveShape().Draw();
            state.getNextShape().Draw();

            // 3. fill in grid for tetris board
            state.getGrid().Draw();

            // 4. add strings to showcase the currentLevel, currentScore, and totalLinesCleared
            SOM.drawStrings(state);
        }
Esempio n. 14
0
        public void SOM_MapRadius_CalculateMapRadius()
        {
            // Arrange
            var x = 10;
            var y = 8;

            // Act
            SOM    som    = new SOM(x, y);
            double radius = som.MapRadius;

            // Assert
            double expected = 10.0;

            Assert.AreEqual(expected, radius);
        }
Esempio n. 15
0
    // Use this for initialization
    void Start()
    {
        problem = ProblemSales.Import(problemPath);
        bois    = new List <MotionModelSalesBoi>();
        points  = new List <GameObject>();
        spawnObjects();
        som = new SOM(problem.pointsOfInterest, problem.startPositions, problem.goalPositions);
        List <float[]> interestings = new List <float[]>();

        interestings.AddRange(problem.pointsOfInterest);
        interestings.AddRange(problem.goalPositions);
        interestings.AddRange(problem.startPositions);
        vGraph   = new VisibilityGraph(problem.obstacles, interestings);
        cooldown = waitTime;
        som.drawState(cooldown);
        Debug.Break();
    }
Esempio n. 16
0
        /// <summary>
        /// Changes initial Root Wt to an array.
        /// </summary>
        /// <param name="root">The root JSON token.</param>
        /// <param name="fileName">The name of the apsimx file.</param>
        private static void UpgradeToVersion55(JObject root, string fileName)
        {
            foreach (var SOM in JsonUtilities.ChildrenOfType(root, "SoilOrganicMatter"))
            {
                double soilcnr = Convert.ToDouble(SOM["SoilCN"]);
                SOM.Remove("SoilCN");
                double[] thickness = MathUtilities.StringsToDoubles(JsonUtilities.Values(SOM, "Thickness"));

                double[] SoilCNVector = new double[thickness.Length];

                for (int layer = 0; layer < thickness.Length; layer++)
                {
                    SoilCNVector[layer] = soilcnr;
                }

                JsonUtilities.SetValues(SOM, "SoilCN", SoilCNVector);
            }
        }
Esempio n. 17
0
        public async Task <HttpResponseMessage> PlotTrajectory()
        {
            try
            {
                HttpRequestMessage requestMessage = this.Request;

                if (!requestMessage.Content.IsMimeMultipartContent())
                {
                    throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
                }

                TrajectoryRequest request = new TrajectoryRequest();

                string root     = System.Web.HttpContext.Current.Server.MapPath(FILE_UPLOAD_PATH);
                var    provider = new MultipartFormDataStreamProvider(root);

                var result = await Request.Content.ReadAsMultipartAsync(provider);

                var map = result.FormData["map"];

                SOM som = JsonConvert.DeserializeObject <SOM>(map);

                string file = provider.FileData.Last().LocalFileName;

                IReader reader = new CSVReader(file);

                TrajectoryMapper trajectoryMapper = new TrajectoryMapper(som);
                trajectoryMapper.GetData(reader);

                TrajectoryResponse trajectoryResponse = new TrajectoryResponse()
                {
                    Trajectories = trajectoryMapper.GetTrajectories().ToArray()
                };

                File.Delete(result.FileData.First().LocalFileName);

                return(Request.CreateResponse(HttpStatusCode.OK, trajectoryResponse));
            } catch (Exception ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex));
            }
        }
Esempio n. 18
0
        /// <summary>
        /// Handles when a key is raised on a map.
        /// </summary>
        /// <param name="sender">The <see cref="IToolTargetMapContainer"/> the event came from. Cannot be null.</param>
        /// <param name="map">The <see cref="EditorMap"/>. Cannot be null.</param>
        /// <param name="camera">The <see cref="ICamera2D"/>. Cannot be null.</param>
        /// <param name="e">The <see cref="System.Windows.Forms.MouseEventArgs"/> instance containing the event data. Cannot be null.</param>
        protected override void MapContainer_KeyUp(IToolTargetMapContainer sender, EditorMap map, ICamera2D camera, KeyEventArgs e)
        {
            // Handle deletes
            if (e.KeyCode == Keys.Delete)
            {
                // Only delete when it is an Entity that is on this map
                var removed = new List <object>();
                foreach (var x in SOM.SelectedObjects.OfType <MapGrh>().ToImmutable())
                {
                    if (map.Spatial.CollectionContains(x))
                    {
                        map.RemoveMapGrh(x);
                        removed.Add(x);
                    }
                }

                SOM.SetManySelected(SOM.SelectedObjects.Except(removed).ToImmutable());
            }

            base.MapContainer_KeyUp(sender, map, camera, e);
        }
Esempio n. 19
0
        public List <List <double> > GetOutputs2(List <List <double> > xs)
        {
            List <List <double> > results = new List <List <double> >();

            foreach (var x in xs)
            {
                this.network.SetInput(x);

                this.network.Calculate();

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

                this.network.OutputLayer.Neurons.ForEach(n => {
                    outputs.Add(SOM.CalculateDistance(n));
                });

                results.Add(outputs);
            }

            return(NeuronOutputConverter.MinOneHotEncode(results));
        }
Esempio n. 20
0
        /// <summary>
        /// Handles when a mouse button is pressed on a map.
        /// </summary>
        /// <param name="sender">The <see cref="IToolTargetMapContainer"/> the event came from. Cannot be null.</param>
        /// <param name="map">The <see cref="EditorMap"/>. Cannot be null.</param>
        /// <param name="camera">The <see cref="ICamera2D"/>. Cannot be null.</param>
        /// <param name="e">The <see cref="System.Windows.Forms.MouseEventArgs"/> instance containing the event data. Cannot be null.</param>
        protected override void MapContainer_MouseDown(IToolTargetMapContainer sender, EditorMap map, ICamera2D camera,
                                                       MouseEventArgs e)
        {
            var wasMapGrhPlaced = false;

            if (e.Button == MouseButtons.Left)
            {
                // Left-click
                if (Input.IsKeyDown(_placeMapGrhKey))
                {
                    PlaceMapGrh(map, camera, e.Position(), TileMode);
                    wasMapGrhPlaced = true;
                }
            }

            base.MapContainer_MouseDown(sender, map, camera, e);

            if (wasMapGrhPlaced)
            {
                SOM.Clear();
            }
        }
Esempio n. 21
0
        public void SOM_IgnoreColumns_GetIsLabelColumn_WhenIsLabelTrue()
        {
            // Arrange
            string  filename = @"Dataset\Iris.csv";
            IReader reader   = new CSVReader(filename);
            SOM     som      = new SOM();

            som.GetData(reader);

            // Act
            Dataset dataset = som.Dataset;

            dataset.SetLabel("Species");

            List <int> ignoreColumns = dataset.GetIgnoreColumns();

            // Assert
            string expected = "Species";
            string result   = dataset.Features[ignoreColumns[0]].FeatureName;

            Assert.AreEqual(expected, result);
        }
        void IConnectionObserver.update(object code)
        {
            if (code != null)
            {
                List <NamedParameter> dataList = (List <NamedParameter>)code;

                List <NamedParameter> m = DataTypes.findAll(dataList, DataType.serverMessage);
                if (m != null && m.Count > 0)
                {
                    Messages.GameMessages msg = (Messages.GameMessages)m[0].data;
                    switch (msg)
                    {
                    case Messages.GameMessages.UpdateMatch:
                        updateData(dataList);
                        break;

                    case Messages.GameMessages.UpdateAll:
                        updateData(dataList);
                        break;

                    case Messages.GameMessages.GetSOM:
                        List <NamedParameter> somRequest = DataTypes.findAll(dataList, DataType.SoMRequest);
                        SOM selected = myView.selectSoM((somRequest[0].data as SoMRequest).Allowed, (somRequest[0].data as SoMRequest).Result);
                        MessageSentFromView(MatchViewMessage.SoM, new List <object>()
                        {
                            selected
                        }, this);
                        break;

                    case Messages.GameMessages.GameOver:
                        //Determine who won
                        bool won = Match.Turn == 0 ? player.Equals(Match.Player1) : player.Equals(Match.Player2);
                        myView.gameOver(won);
                        break;
                    } //End Switch
                }     //End MEssage if
            }         //End Code if
        }
Esempio n. 23
0
 public ActionResult Iterate(SOM som)
 {
     som.Map.Grid[0, 0] = new SOMColor(0, 0, 0);
     return(View(som));
 }
Esempio n. 24
0
 public WinnerDistance(double dist, SOM.Neuron neuron)
 {
     winner = neuron;
     distance = dist;
 }
Esempio n. 25
0
 private WinnerDistance getRangeWinner(int length, int start, int end, SOM.Neuron[,] outputs, double[] pattern)
 {
     SOM.Neuron winner = null;
     double min = double.MaxValue;
     for (int i = start; i < end; i++)
         for (int j = 0; j < length; j++)
         {
             // double d = Distance(pattern, outputs[i, j].Weights);
             double d = DistanceCalculator.DistancePearson(pattern, outputs[i, j].Weights);
             if (d < min)
             {
                 min = d;
                 winner = outputs[i, j];
             }
         }
     return new WinnerDistance(min, winner);
 }
Esempio n. 26
0
        /// <summary>
        /// This method looks at the type of request the player sent,
        /// and puts the appropriate data and type in to msg.data before adding it to MyMessages
        /// </summary>
        /// <param name="player"></param>
        /// <param name="msg"></param>
        public void addNewMessage(DataPlayer player, Messages.GameMessages msg, String data = null)
        {
            player = players.Find(n => n.Equals(player));
            if (player == null)
            {
                sendFeedback("addNewMessage", "Player Not Found\n PlayerName:" + player.PlayerName + "\n" +
                             msg.ToString());
                return;
            }
            if (player.InGame)//Use in game handler
            {
                IPlayable  game    = games.Find(n => n.Player1.Equals(player) || n.Player2.Equals(player));
                DataPlayer player1 = players.Find(n => n.Equals(game.Player1)),
                           player2 = players.Find(n => n.Equals(game.Player2));
                switch (msg)
                {
                case Messages.GameMessages.UpdateMatch:
                    updatePlayerInMatch(player);
                    break;

                case Messages.GameMessages.somChosen:
                    SOM som = (SOM)Enum.Parse(typeof(SOM), data);
                    game.getMessageFromConnection(Messages.GameMessages.somChosen,
                                                  player,
                                                  new List <object> {
                        som
                    });
                    game.Match.Transcript += "SoM chosen:" + som.ToString() + "\n";
                    break;

                case Messages.GameMessages.GameOver:
                    //Reset players,remove finished match from list
                    player1.InGame = false;
                    player2.InGame = false;
                    Matches.Remove(player1.ActiveMatch);
                    player1.ActiveMatch = new Match();
                    player1.ActiveMatch = null;
                    player2.ActiveMatch = null;
                    game = null;
                    break;

                case Messages.GameMessages.SendActiveMatches:
                    updatePlayerInMatch(player);
                    break;

                default:    //Covers all argument requests
                    game.getMessageFromConnection(msg, player, null);
                    break;
                }
            }
            else //Use lobby handler
            {
                switch (msg)
                {
                case Messages.GameMessages.SendActiveMatches:
                    updatePlayer(player);
                    break;

                case Messages.GameMessages.CreateMatch:
                    createMatch(player);
                    break;

                case Messages.GameMessages.LeaveMatch:
                    leaveMatch(player);
                    break;

                case Messages.GameMessages.UpdateAll:
                    updatePlayer(player);
                    break;

                case Messages.GameMessages.JoinMatch:
                    if (data == null)
                    {
                        addSignalMessage(Messages.GameMessages.InvalidMatch, player);
                    }
                    else
                    {
                        joinMatch(data, player);
                    }
                    break;

                case Messages.GameMessages.PlayerReady:
                    lockInPlayer(player);
                    break;

                case Messages.GameMessages.PlayerNotReady:
                    lockOutPlayer(player);
                    break;

                case Messages.GameMessages.UpdateMatch:
                    updatePlayerInMatch(player);
                    break;

                default:
                    break;
                }
            }
        }
Esempio n. 27
0
 public SOMController()
 {
     _model = new SOM(10, 10, 0.3, 40);
 }
Esempio n. 28
0
        /// <summary>
        /// Game decision point. This method gets messages from connection and decides what arguments to call, as well
        /// as taking care of runtime handlers for SoM requests
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="player"></param>
        /// <param name="data"></param>
        public void getMessageFromConnection(Messages.GameMessages msg, DataPlayer player, List <object> data)
        {
            if (!checkTurn(player))//Not right turn?
            {
                (this as IGameObservable).notifyObservers(Messages.GameMessages.NotPlayerTurn, player, null);
                Match.updateTranscript("Not your turn");
                return;
            }
            CharacterData    attacker = Turn == 0?Player1.Character:Player2.Character, defender = Turn == 0?Player2.Character:Player1.Character;
            ArgNames         actionName  = 0;
            ArgumentFeedback argFeedback = null;

            if (waiting && msg != Messages.GameMessages.somChosen)
            {
                Match.updateTranscript("Waiting for SOM");
                return;
            }

            switch (msg)
            {
            ///This case handles the response from a request to get SoM from the user
            ///We need to translate the response (SoMName,value) into values the Handler needs (JoySorrowValue,AngerFearValue)
            case Messages.GameMessages.somChosen:
                SOM name = (SOM)data[0];
                switch (name)
                {
                case SOM.Joy:
                    argFeedback = SoMHandler(1, 0);
                    break;

                case SOM.Sorrow:
                    argFeedback = SoMHandler(-1, 0);
                    break;

                case SOM.Anger:
                    argFeedback = SoMHandler(0, 1);
                    break;

                case SOM.Fear:
                    argFeedback = SoMHandler(0, -1);
                    break;
                }
                waiting = false;    //Just in case
                break;

            case Messages.GameMessages.Trick:
                actionName  = ArgNames.Trick;
                argFeedback = arguments[actionName].doArgument(attacker, defender, World);
                if ((arguments[actionName] as Trick).repeatTurn())
                {
                    Turn--;    //We turn it back then the regular turn counter turns it back to my turn
                }
                break;

            case Messages.GameMessages.Manipulate:
                actionName = ArgNames.Manipulate;
                goto case Messages.GameMessages.SoMDependentArgument;

            case Messages.GameMessages.Taunt:
                actionName = ArgNames.Taunt;
                goto case Messages.GameMessages.SoMDependentArgument;

            case Messages.GameMessages.Focus:
                actionName = ArgNames.Focus;
                goto case Messages.GameMessages.SoMDependentArgument;

            case Messages.GameMessages.Empathy:
                actionName  = ArgNames.Empathy;
                argFeedback = (arguments[actionName] as Empathy).doArgument(attacker, defender, World);
                if (argFeedback != null && argFeedback.result == Result.None)
                {
                    Match.updateTranscript("Empathy cannot be used\n");
                }
                break;

            case Messages.GameMessages.Bluff:
                actionName = ArgNames.Bluff;
                goto case Messages.GameMessages.GenericArgument;

            case Messages.GameMessages.Charm:
                actionName = ArgNames.Charm;
                goto case Messages.GameMessages.GenericArgument;

            case Messages.GameMessages.Coerce:
                actionName = ArgNames.Coerce;
                goto case Messages.GameMessages.GenericArgument;

            case Messages.GameMessages.Convince:
                actionName = ArgNames.Convince;
                goto case Messages.GameMessages.GenericArgument;

            case Messages.GameMessages.Scare:
                actionName = ArgNames.Scare;
                goto case Messages.GameMessages.GenericArgument;

            case Messages.GameMessages.GenericArgument:
                argFeedback = arguments[actionName].doArgument(attacker, defender, World);
                break;

            case Messages.GameMessages.SoMDependentArgument:
                (arguments[actionName] as SoMDependentArgument).Selector = this;

                argFeedback = (arguments[actionName] as SoMDependentArgument).doArgument(attacker, defender, World);
                //If true then it succeeded so it needs to get SoM
                if (argFeedback == null)
                {
                    waiting = true;
                }
                break;
            }//End Switch

            //Update transcript if there is feedback
            if (argFeedback != null)
            {
                argFeedback.playerName = player.PlayerName;
                Match.updateTranscript(argFeedback);
            }

            if (!waiting)
            {
                //Check Game over
                if (Match.Goal.isGoalReached(defender))
                {
                    (this as IGameObservable).notifyObservers(Messages.GameMessages.GameOver, Match.Player1, null);
                    (this as IGameObservable).notifyObservers(Messages.GameMessages.GameOver, Match.Player2, null);
                }
                else//Not over
                {
                    //Tell players to update and go to next turn
                    (this as IGameObservable).notifyObservers(Messages.GameMessages.ArgumentDone, player, null);
                    Turn = (Turn + 1) % 2;
                }
            }
        }
Esempio n. 29
0
 public double MeasureScore(SOM model)
 {
     throw new NotImplementedException();
 }
Esempio n. 30
0
 public SOMTrainer(SOMNetwork network, int epoch, SOM algorithm, List <SOMSetting> setting) : base(network, epoch, algorithm)
 {
     this.setting = setting;
 }
Esempio n. 31
0
        private double ActionTrain(double[] pattern, SOM.Neuron winner, int iLengthStart, int iLengthEnd)
        {
            double error = 0;

            for (int i = iLengthStart; i < iLengthEnd; i++)
            {
                for (int j = 0; j < length; j++)
                {
                    error += outputs[i, j].UpdateWeights(pattern, winner, iteration);
                }
            }
            return error;
        }
Esempio n. 32
0
        public static void Demo()
        {
            SOMNetwork network = SOMNetwork.Create(9, 3);

            network.Display();

            var dataSet = DataGenerator.GenerateDataSet3();

            var som = new SOM(network);

            List <SOMSetting> setting = new List <SOMSetting>();

            setting.Add(new SOMSetting()
            {
                FromEpoch = 0, ToEpoch = 500, LearningRate = 0.8, Radius = 2
            });
            setting.Add(new SOMSetting()
            {
                FromEpoch = 501, ToEpoch = 1000, LearningRate = 0.4, Radius = 1
            });

            SOMTrainer trainer = new SOMTrainer(network, 1000, som, setting);

            //Normalizer2 normalizer = new Normalizer2();
            Normalizer2 normalizer = new Normalizer2();

            normalizer.Fit(dataSet.XList);

            var normalizedX = normalizer.Normalize(dataSet.XList);

            trainer.Fit(normalizedX);

            List <List <double> > convertedX = trainer.GetOutputs(normalizedX);

            List <List <double> > convertedX2 = trainer.GetOutputs2(normalizedX);

            network.Display();

            Console.WriteLine("OLD VECTORS===>");
            Utils.DisplayListList(dataSet.XList);

            Console.WriteLine("OLD VECTORS(NORMALIZED)===>");
            Utils.DisplayListList(normalizedX);

            Console.WriteLine("NEW CLUSTERED VECTORS===>");
            Utils.DisplayListList(convertedX);

            Console.WriteLine("NEW CLUSTERED VECTORS(DISTANCE)===>");
            Utils.DisplayListList(convertedX2);

            StringBuilder sb_x = new StringBuilder();
            StringBuilder sb_y = new StringBuilder();

            foreach (var l in convertedX2)
            {
                var maxIndex = l.IndexOf(l.Max());

                for (var x = 0; x < network.OutputNeuronCountPerDim; x++)
                {
                    for (var y = 0; y < network.OutputNeuronCountPerDim; y++)
                    {
                        if (x * network.OutputNeuronCountPerDim + y == maxIndex)
                        {
                            sb_x.Append(x + ",");
                            sb_y.Append(y + ",");
                            Console.Write("(" + x + "," + y + "),");
                        }
                    }
                }
                Console.WriteLine();
            }
            StringBuilder sb = new StringBuilder();

            sb.AppendLine("import matplotlib.pyplot as plt");
            sb.AppendLine("x1=[" + sb_x.ToString().TrimEnd(",".ToCharArray()) + "]");
            sb.AppendLine("y1=[" + sb_y.ToString().TrimEnd(",".ToCharArray()) + "]");
            sb.AppendLine("plt.plot(x1,y1,'b^')");
            sb.AppendLine("plt.show()");

            var file = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "display.py");

            File.WriteAllText(file, sb.ToString());
            Console.WriteLine("saved to path: " + file);

            System.Diagnostics.Process.Start("C:\\ProgramData\\Anaconda3\\envs\\keras\\python.exe", "\"" + file + "\"");
        }
Esempio n. 33
0
 public TrajectoryMapper(SOM som)
 {
     _som         = som;
     Trajectories = new List <Trajectory>();
 }