示例#1
0
        public void Execute(bool startNovelty = false)
        {
            Console.WriteLine("Starting TestSocketIOClient Example...");

            socket = new Client("http://localhost:3000/"); // url to the nodejs / socket.io instance

            socket.Opened += SocketOpened;


            socket.Message += SocketMessage;
            socket.SocketConnectionClosed += SocketConnectionClosed;


            socket.Error += SocketError;

            // register for 'connect' event with io server
            socket.On("connect", (fn) =>
            {
                Console.WriteLine("\r\nConnected event...\r\n");
                Console.WriteLine("Connected To Socket Object");

                //begin our threaded novelty evaluations on connect
                if (startNovelty)
                {
                    simpleExperiment.StartNoveltyEvaluations();
                }
            });

            socket.On("toggleNetwork", (fn) =>
            {
                print.WriteLine("Incoming select: " + fn.Json.ToJsonString());

                //we see an incoming request for selection
                long selectionID = (long)fn.Json.Args[0];

                //we have the ID, now we must do some toggling
                //we could call the evolution manager directly, but perhaps it's best to separate these objects? In case there are many experiements or someting?
                //or maybe the experiment wants to not the selection information
                bool toggle = simpleExperiment.toggleNetwork(selectionID);

                if (toggle)
                {
                    print.WriteLine("Successful toggle, as suspected");
                }

                EvolutionManager eManager = EvolutionManager.SharedEvolutionManager;


                string isSelected = string.Format("{0}:::{1}+[{2}]", (int)SocketIOMessageTypes.ACK, fn.AckId, JsonConvert.SerializeObject(eManager.isSelected(selectionID)));

                print.WriteLine("Responding to toggleNetwork with: " + JsonConvert.SerializeObject(eManager.isSelected(selectionID)));

                socket.Send(isSelected);
            });
            //you simply make a request for the next body, no
            socket.On("getBodies", (fn) =>
            {
                if (fn.Json.Args.Length > 0)
                {
                    //we accept a parameter describing the number of desired bodies
                    int numberOfBodies = (int)fn.Json.Args[0];

                    //We must generate our collection of bodies and send them back in a JSON object
                    string[] bodies = simpleExperiment.fetchBodies(numberOfBodies);

                    //we have all of our bodies, we must send them back now!
                    string bodiesMessage = formattedSocketMessage(fn.AckId, JsonConvert.SerializeObject(bodies));

                    //now return information to our socket
                    socket.Send(bodiesMessage);
                }
            });
            socket.On("getGenomes", (fn) =>
            {
                if (fn.Json.Args.Length > 0)
                {
                    //we accept a parameter describing the number of desired bodies
                    JArray con = (JArray)fn.Json.Args[0];

                    List <long> genomeIDs = new List <long>();

                    foreach (var idString in con)
                    {
                        long genomeID;

                        if (long.TryParse(idString.ToString(), out genomeID))
                        {
                            //Console.WriteLine("Genomeid: " + genomeID);
                            genomeIDs.Add(genomeID);
                        }
                        else
                        {
                            throw new Exception("Failure to send appropriate genomeID");
                        }
                    }

                    try
                    {
                        //We must find our collection of bodies and send them back in a JSON object
                        Dictionary <long, string> bodies = simpleExperiment.fetchBodiesFromIDs(genomeIDs);

                        //we have all of our bodies, we must send them back now!
                        string bodiesMessage = formattedSocketMessage(fn.AckId, JsonConvert.SerializeObject(bodies));

                        print.WriteLine("Sending bodies: " + JsonConvert.SerializeObject(bodies.Keys));

                        //now return information to our socket
                        socket.Send(bodiesMessage);
                    }
                    catch (Exception e)
                    {
                        //we failed to fetch the bodies, throw an error, this is some serious stuff!
                        Console.WriteLine("Failed to fetch bodies and send response");
                        Console.WriteLine(e.Message);
                        Console.WriteLine(e.StackTrace);
                        throw e;
                    }
                }
            });
            socket.On("getBest", (fn) =>
            {
                if (fn.Json.Args.Length > 0)
                {
                    long lastQueryTime = (long)fn.Json.Args[0];
                    //long.TryParse(fn.Json.Args[0], out lastQueryTime);

                    //get our best bodies
                    var bodyAndTime = simpleExperiment.fetchBestBodies(lastQueryTime);

                    //we have all of our bodies, we must send them back now!
                    string bodiesMessage = formattedSocketMessage(fn.AckId, JsonConvert.SerializeObject(bodyAndTime));

                    print.WriteLine("Sending best: " + JsonConvert.SerializeObject(bodyAndTime.Second.Keys));

                    //now return information to our socket
                    socket.Send(bodiesMessage);
                }
            });
            socket.On("ping", (fn) =>
            {
                print.WriteLine("Incoming Ping: " + fn.Json.ToJsonString());

                int value = (int)fn.Json.Args[0];

                value = value + 1;

                //string jSon = SimpleJson.SimpleJson.SerializeObject(net);

                string jSon = simpleExperiment.fetchNextBodyJSON();

                //Dictionary<string, object> stuff =new Dictionary<string,object>();
                //stuff.Add("c#says", "pong");
                //stuff.Add("valuePlusOne", value);
                //string data = SimpleJson.SimpleJson.SerializeObject(stuff);

                //string.Format("{\"{0}\": \"{1}\", \"{2}\": {3} }", "c#Says", "pong", "value", value);

                string tosend = string.Format("{0}:::{1}+[{2}]", (int)SocketIOMessageTypes.ACK, fn.AckId, jSon);

                print.WriteLine("Responding to ping with: " + jSon);
                socket.Send(tosend);//new AckMessage() { AckId = fn.AckId, MessageText = "pong" });
            });
            socket.On("runFullPCA", (fn) =>
            {
                int xBins, yBins, genomeSelector;
                double topPercent;
                bool firstBehavior;
                bool.TryParse(fn.Json.Args[0], out firstBehavior);
                int.TryParse(fn.Json.Args[1], out xBins);
                int.TryParse(fn.Json.Args[2], out yBins);
                int.TryParse(fn.Json.Args[3], out genomeSelector);
                double.TryParse(fn.Json.Args[4], out topPercent);

                //want to send in custom params for selecting what method to grab genomes (or to send a genome array)

                //if (fn.Json.Args.Length > 0)
                //{
                //    //we accept a parameter describing the number of desired bodies
                //    JArray con = (JArray)fn.Json.Args[3];


                // Create new stopwatch
                Stopwatch stopwatch = new Stopwatch();

                // Begin timing
                stopwatch.Start();

                //grab ALL of our saved genomes, and make sure they are unique individuals
                //we group them by a genome ID, then we select the first object in the group, voila, distinct!
                List <NeatGenome> allGenomes;

                switch (genomeSelector)
                {
                case 0:
                    allGenomes = simpleExperiment.fetchAllGenomes().GroupBy(g => g.GenomeId).Select(group => group.First()).ToList();
                    break;

                case 1:
                    allGenomes = simpleExperiment.fetchBestGenomes(topPercent).GroupBy(g => g.GenomeId).Select(group => group.First()).ToList();
                    break;

                default:
                    allGenomes = simpleExperiment.fetchAllGenomes().GroupBy(g => g.GenomeId).Select(group => group.First()).ToList();
                    break;
                }


                EvolutionManager.SharedEvolutionManager.saveGenomes(allGenomes);


                // Begin timing
                stopwatch.Stop();

                Console.WriteLine("Fetch Genomes: " + stopwatch.ElapsedMilliseconds);



                var uidAndPoints = runPCA(allGenomes, firstBehavior, xBins, yBins);

                try
                {
                    //we have all of our bodies, we must send them back now!
                    string bodiesMessage = formattedSocketMessage(fn.AckId, JsonConvert.SerializeObject(uidAndPoints));

                    print.WriteLine("Sending pca analysis for IDs: " + JsonConvert.SerializeObject(uidAndPoints));

                    //now return information to our socket
                    socket.Send(bodiesMessage);
                }
                catch (Exception e)
                {
                    //we failed to fetch the bodies, throw an error, this is some serious stuff!
                    Console.WriteLine("Failed to fetch bodies and send response");
                    Console.WriteLine(e.Message);
                    Console.WriteLine(e.StackTrace);
                    throw e;
                }
            });
            socket.On("runPCA", (empty) =>
            {
                //we accept a parameter describing the number of desired bodies
                //JArray con = (JArray)fn.Json.Args[0];


                //grab the best individuals (already having been evaluated, we grab their behavior and PCA

                //get our best bodies
                List <NeatGenome> topBodyAndTime = simpleExperiment.fetchBestGenomes(.1);

                var uidAndPoints = runPCA(topBodyAndTime);

                try{
                    //we have all of our bodies, we must send them back now!
                    string bodiesMessage = formattedSocketMessage(empty.AckId, JsonConvert.SerializeObject(uidAndPoints));

                    print.WriteLine("Sending pca analysis for IDs: " + JsonConvert.SerializeObject(uidAndPoints));

                    //now return information to our socket
                    socket.Send(bodiesMessage);
                }
                catch (Exception e)
                {
                    //we failed to fetch the bodies, throw an error, this is some serious stuff!
                    Console.WriteLine("Failed to fetch bodies and send response");
                    Console.WriteLine(e.Message);
                    Console.WriteLine(e.StackTrace);
                    throw e;
                }
            });

            //socket.On("evaluateGenomes", (data) =>
            //{
            //    print.WriteLine(data);
            //    //Console.WriteLine("  raw message:      {0}", data.RawMessage);
            //    //Console.WriteLine("  string message:   {0}", data.MessageText);
            //    //Console.WriteLine("  json data string: {0}", data.Json.ToJsonString());
            //    //Console.WriteLine("  json raw:         {0}", data.Json.Args[0]);

            //});


            // register for 'update' events - message is a json 'Part' object
            socket.On("update", (data) =>
            {
                print.WriteLine("recv [socket].[update] event");
                //Console.WriteLine("  raw message:      {0}", data.RawMessage);
                //Console.WriteLine("  string message:   {0}", data.MessageText);
                //Console.WriteLine("  json data string: {0}", data.Json.ToJsonString());
                //Console.WriteLine("  json raw:         {0}", data.Json.Args[0]);
            });

            // register for 'update' events - message is a json 'Part' object
            socket.On("getArchiveIDs", (data) =>
            {
                //let's go fetch our novelty ids!
                List <long> archiveIDs = simpleExperiment.GetNoveltyArchive();

                if (archiveIDs != null)
                {
                    //we have all of our ids, we must send them back now!
                    string bodiesMessage = formattedSocketMessage(data.AckId, JsonConvert.SerializeObject(archiveIDs));

                    socket.Send(bodiesMessage);
                }
            });

            // Grabs the current generation ids for viewing purposes!
            socket.On("getCurrentIDs", (data) =>
            {
                //let's go fetch our novelty ids!
                List <long> currentIDs = simpleExperiment.GetMultiCurrentGeneration();

                if (currentIDs != null)
                {
                    //we have all of our ids, we must send them back now!
                    string bodiesMessage = formattedSocketMessage(data.AckId, JsonConvert.SerializeObject(currentIDs));

                    socket.Send(bodiesMessage);
                }
            });


            // make the socket.io connection
            socket.Connect();
        }