Example #1
0
        public RandomnessTexture(GraphicsState graphics)
        {
            const int size = 2048;

            var rf = graphics.Device.ResourceFactory;

            Texture = rf.CreateTexture(new TextureDescription(size, size, 1, 1, 1, PixelFormat.R32_G32_B32_A32_Float,
                                                              TextureUsage.Sampled, TextureType.Texture2D));
            Sampler = rf.CreateSampler(new SamplerDescription(SamplerAddressMode.Wrap, SamplerAddressMode.Wrap,
                                                              SamplerAddressMode.Wrap, SamplerFilter.MinPoint_MagPoint_MipPoint, null, 0, 0, 0, 0,
                                                              SamplerBorderColor.TransparentBlack));
            ResourceLayout = rf.CreateResourceLayout(new ResourceLayoutDescription(
                                                         new ResourceLayoutElementDescription(nameof(Texture), ResourceKind.TextureReadOnly,
                                                                                              ShaderStages.Compute | ShaderStages.Fragment | ShaderStages.Vertex),
                                                         new ResourceLayoutElementDescription(nameof(Sampler), ResourceKind.Sampler,
                                                                                              ShaderStages.Compute | ShaderStages.Fragment | ShaderStages.Vertex)
                                                         ));
            ResourceSet = rf.CreateResourceSet(new ResourceSetDescription(ResourceLayout, Texture, Sampler));

            var random  = new TRandom(42);
            var texture = new RgbaFloat[size * size];

            for (var i = 0; i < size * size; i++)
            {
                var vec = Vector2.Normalize(new Vector2((float)random.Normal(0, 1), (float)random.Normal(0, 1)))
                          * (float)random.NextDouble().Squared().Squared().Squared() * 2;
                texture[i] = new RgbaFloat(
                    vec.X, vec.Y, (float)random.NextDouble(), (float)random.NextDouble()
                    );
            }

            graphics.Device.UpdateTexture(Texture, texture, 0, 0, 0, size, size, 1, 0, 0);
        }
        private static IEnumerable <Order> GenerateRandom(
            int orderCount,
            string baseCurrency,
            string quoteCurrency,
            double minPrice,
            double maxPrice)
        {
            var price  = new TRandom();
            var amount = new TRandom();

            for (var i = 0; i < orderCount; i++)
            {
                yield return(new Order(
                                 new CurrencyPair(baseCurrency, quoteCurrency),
                                 Side.Buy,
                                 decimal.Round((decimal)price.NextDouble(minPrice, maxPrice), 4),
                                 amount.Next(1, 100)));

                yield return(new Order(
                                 new CurrencyPair(baseCurrency, quoteCurrency),
                                 Side.Sell,
                                 decimal.Round((decimal)price.NextDouble(minPrice, maxPrice), 4),
                                 amount.Next(1, 100)));
            }
        }
Example #3
0
        public static Cell GenerateRandomCell(Type cell, Simulation simulation)
        {
            Vector startingVector = new Vector(random.NextDouble() * 20 - 10,
                                               random.NextDouble() * 20 - 10,
                                               random.NextDouble() * 20 - 10);

            return((Cell)Activator.CreateInstance(cell, simulation, startingVector,
                                                  (0.875 + random.NextDouble() / 4), 0.8));
        }
Example #4
0
        /// <summary>
        /// Generates random normalized vector;
        /// </summary>
        /// <returns>Generated vector;</returns>
        public static Vector Create(TRandom random)
        {
            double fi  = random.NextDouble() * Math.PI * 2;
            double fi1 = random.NextDouble() * Math.PI * 2;

            Vector retval = new Vector(Math.Cos(fi) * Math.Cos(fi1), Math.Sin(fi) * Math.Cos(fi1), Math.Sin(fi1));

            return(retval);
        }
Example #5
0
        double GetGradient(int x, int y)
        {
            rndEngine.Reset(rowSeed[y]);
            for (int i = 0; i < x; i++)
            {
                rndEngine.NextDouble();
            }

            return(rndEngine.NextDouble());
        }
Example #6
0
        static List <GameObject> CreateGameObjects()
        {
            var random      = new TRandom();
            var gameObjects = new List <GameObject>();

            var floor = new GameObject();

            floor.Mesh = Primitives.CreatePlane();
            floor.Transform.Scale.X = 100;
            floor.Transform.Scale.Z = 100;
            gameObjects.Add(floor);

            _playerGO = new GameObject();
            _playerGO.Transform.Position.Y = 2;

            for (int i = 0; i < 1000; i++)
            {
                var newObstacleGO = new GameObject();
                newObstacleGO.Mesh = Primitives.CreateCube36();
                newObstacleGO.Transform.Position.X = (float)random.NextDouble(-100, 100);
                newObstacleGO.Transform.Position.Z = (float)random.NextDouble(-100, 100);
                newObstacleGO.Transform.Position.Y = (float)random.NextDouble(1, 10);
                newObstacleGO.Transform.Scale.X    = (float)random.NextDouble(0.1f, 3);
                newObstacleGO.Transform.Scale.Y    = (float)random.NextDouble(0.1f, 3);
                newObstacleGO.Transform.Scale.Z    = (float)random.NextDouble(0.1f, 3);
                newObstacleGO.Transform.Rotation.X = (float)random.NextDouble(0, 360);
                newObstacleGO.Transform.Rotation.Y = (float)random.NextDouble(0, 360);
                newObstacleGO.Transform.Rotation.Z = (float)random.NextDouble(0, 360);
                gameObjects.Add(newObstacleGO);
            }


            return(gameObjects);
        }
Example #7
0
        public RequestBuilder(Client client, ISettings settings)
        {
            _client   = client;
            _settings = settings;

            if (_sessionHash == null)
            {
                GenerateNewHash();
            }

            _course = (float)TRandomDevice.NextDouble(0, 359.9);
        }
Example #8
0
        /// <summary>
        /// Generates a few random <see cref="LocationFix"/>es to act like a real GPS sensor.
        /// </summary>
        /// <param name="requestEnvelope">The <see cref="RequestEnvelope"/> these <see cref="LocationFix"/>es are used for.</param>
        /// <param name="timestampSinceStart">The milliseconds passed since starting the <see cref="Session"/> used by the current <see cref="RequestEnvelope"/>.</param>
        /// <returns></returns>
        private List <LocationFix> BuildLocationFixes(RequestEnvelope requestEnvelope, long timestampSinceStart)
        {
            var     locationFixes = new List <LocationFix>();
            TRandom Random        = new TRandom();

            if (requestEnvelope.Requests.Count == 0 || requestEnvelope.Requests[0] == null)
            {
                return(locationFixes);
            }

            var providerCount = Random.Next(4, 10);

            for (var i = 0; i < providerCount; i++)
            {
                var timestampSnapshot = timestampSinceStart + (150 * (i + 1) + Random.Next(250 * (i + 1) - 150 * (i + 1)));
                if (timestampSnapshot >= timestampSinceStart)
                {
                    if (locationFixes.Count != 0)
                    {
                        break;
                    }

                    timestampSnapshot = timestampSinceStart - Random.Next(20, 50);

                    if (timestampSnapshot < 0)
                    {
                        timestampSnapshot = 0;
                    }
                }

                locationFixes.Insert(0, new LocationFix
                {
                    TimestampSnapshot  = (ulong)timestampSnapshot,
                    Latitude           = (float)_client.CurrentLatitude,
                    Longitude          = (float)_client.CurrentLongitude,
                    HorizontalAccuracy = (float)Random.NextDouble(5.0, 25.0),
                    VerticalAccuracy   = (float)Random.NextDouble(5.0, 25.0),
                    Altitude           = (float)_client.CurrentAltitude,
                    Provider           = "fused",
                    ProviderStatus     = 3,
                    LocationType       = 1,
                    // Speed = ?,
                    Course = -1,
                    // Floor = 0
                });
            }
            return(locationFixes);
        }
Example #9
0
        public void Mutation()
        {
            bool first = true;

            foreach (var specimen in Population)
            {
                if (first)
                {
                    first = false;
                    continue;
                }
                var net = specimen.Value;
                foreach (var layer in net.Layers)
                {
                    foreach (var neuron in layer.Neurons)
                    {
                        var weights = neuron.GetWeights();
                        for (var i = 0; i < weights.Length; i++)
                        {
                            if (Random.NextDouble() < Config.MutationChance)
                            {
                                weights[i] += Config.RandOptions.Normal.NextDouble();
                            }
                        }
                    }
                }
            }
        }
        private static TIndividual GetRandomIndiviual <TIndividual>(IReadOnlyList <TIndividual> individuals, TRandom rnd)
        {
            double count = individuals.Count;

            double p(int index)
            {
                double rank = count - index;

                return(2 * rank / (count * (count + 1.0)));
            }

            var r = rnd.NextDouble(0, 1);

            var minP = 0.0;
            var i    = 0;

            foreach (var individual in individuals)
            {
                var maxP = p(i) + minP;

                if (r >= minP && r <= maxP)
                {
                    return(individual);
                }
                i++;
                minP = maxP;
            }

            return(individuals.Last());
        }
        /// <summary>
        /// Helper method assisting with generation of random telemetry data
        /// </summary>
        private static int GetRandomWeightedNumber(int max, int min, double probabilityPower)
        {
            var randomDouble = _random.NextDouble();

            var result = Math.Floor(min + (max + 1 - min) * (Math.Pow(randomDouble, probabilityPower)));

            return((int)result);
        }
Example #12
0
        public static void Main()
        {
            // 1) Use TRandom to generate a few random numbers - via IGenerator methods.
            Console.WriteLine("TRandom in action, used as an IGenerator");
            var trandom = new TRandom();

            Console.WriteLine(trandom.Next() - trandom.Next(5) + trandom.Next(3, 5));
            Console.WriteLine(trandom.NextDouble() * trandom.NextDouble(5.5) * trandom.NextDouble(10.1, 21.9));
            Console.WriteLine(trandom.NextBoolean());

            Console.WriteLine();

            // 2) Use TRandom to generate a few random numbers - via extension methods.
            Console.WriteLine("TRandom in action, used as an IGenerator augmented with extension methods");
            Console.WriteLine(string.Join(", ", trandom.Integers().Take(10)));
            Console.WriteLine(string.Join(", ", trandom.Doubles().Take(10)));
            Console.WriteLine(string.Join(", ", trandom.Booleans().Take(10)));

            Console.WriteLine();

            // 3) Use TRandom to generate a few distributed numbers.
            Console.WriteLine("TRandom in action, used as to get distributed numbers");
            Console.WriteLine(trandom.Normal(1.0, 0.1));
            Console.WriteLine(string.Join(", ", trandom.NormalSamples(1.0, 0.1).Take(20)));
            Console.WriteLine(trandom.Poisson(5));
            Console.WriteLine(string.Join(", ", trandom.PoissonSamples(5).Take(20)));

            Console.WriteLine();

            // 4) There are many generators available - XorShift128 is the default.
            var alf = new ALFGenerator(TMath.Seed());
            var nr3 = new NR3Generator();
            var std = new StandardGenerator(127);

            // 5) You can also use distribution directly, even with custom generators.
            Console.WriteLine("Showcase of some distributions");
            Console.WriteLine("Static sample for Normal: " + NormalDistribution.Sample(alf, 1.0, 0.1));
            Console.WriteLine("New instance for Normal: " + new NormalDistribution(1.0, 0.1).NextDouble());

            Console.WriteLine();
        }
        /// <summary>
        /// Generates a few random <see cref="LocationFix"/>es to act like a real GPS sensor.
        /// </summary>
        /// <param name="requestEnvelope">The <see cref="RequestEnvelope"/> these <see cref="LocationFix"/>es are used for.</param>
        /// <param name="timestampSinceStart">The milliseconds passed since starting the <see cref="Session"/> used by the current <see cref="RequestEnvelope"/>.</param>
        /// <returns></returns>
        private List <Signature.Types.LocationFix> BuildLocationFixes(RequestEnvelope requestEnvelope, long timestampSinceStart)
        {
            var locationFixes = new List <Signature.Types.LocationFix>();

            if (requestEnvelope.Requests.Count == 0 || requestEnvelope.Requests[0] == null)
            {
                return(locationFixes);
            }

            var providerCount = TRandomDevice.Next(4, 10);

            for (var i = 0; i < providerCount; i++)
            {
                var timestampSnapshot = timestampSinceStart + (150 * (i + 1) + TRandomDevice.Next(250 * (i + 1) - 150 * (i + 1)));
                if (timestampSnapshot >= timestampSinceStart)
                {
                    if (locationFixes.Count != 0)
                    {
                        break;
                    }

                    timestampSnapshot = timestampSinceStart - TRandomDevice.Next(20, 50);

                    if (timestampSnapshot < 0)
                    {
                        timestampSnapshot = 0;
                    }
                }
                var tmpCourse = -1F;
                var mpSpeed   = 0F;


                if (_client.Platform == Platform.Ios)
                {
                    tmpCourse = (float)TRandomDevice.NextDouble(100, 330);
                    mpSpeed   = (float)TRandomDevice.NextDouble(0.9, 2.2);
                }


                locationFixes.Insert(0, new Signature.Types.LocationFix {
                    TimestampSnapshot  = (ulong)timestampSnapshot,
                    Latitude           = (float)_client.CurrentLatitude,
                    Longitude          = (float)_client.CurrentLongitude,
                    HorizontalAccuracy = (float)TRandomDevice.NextDouble(5.0, 25.0),
                    VerticalAccuracy   = (float)TRandomDevice.NextDouble(5.0, 25.0),
                    Altitude           = (float)_client.CurrentAltitude,
                    Provider           = "fused",
                    ProviderStatus     = 3,
                    LocationType       = 1,
                    Speed  = mpSpeed,
                    Course = tmpCourse,
                    // Floor = 0
                });
            }
            return(locationFixes);
        }
Example #14
0
        public static async Task HandleAccountAfterCreation(Configuration config, AccountCreationResult account)
        {
            var random = new TRandom();

            POGOLib.Official.Configuration.Hasher = new PokeHashHasher(config.TutorialSettings.HashKey);
            var client = await GetSession(new PtcLoginProvider(account.Username, account.Password),
                                          config.TutorialSettings.Latitude, config.TutorialSettings.Longitude);

            if (!await client.StartupAsync())
            {
                throw new SessionFailedError();
            }

            if (config.TutorialSettings.Level2 || config.TutorialSettings.Level5)
            {
                var ts = await Tutorial.GetTutorialState(client);

                await Tutorial.CompleteTutorial(client, ts);

                // Level 2: Stop here.
                // Level 5: Keep going.
                if (config.TutorialSettings.Level5)
                {
                    while (client.Player.Stats.Level < 5)
                    {
                        var lat = client.Player.Latitude + random.NextDouble(0.005, -0.005);
                        var lng = client.Player.Longitude + random.NextDouble(0.005, -0.005);
                        client.Player.SetCoordinates(lat, lng);

                        foreach (var cell in client.Map.Cells)
                        {
                            foreach (var pokemon in cell.CatchablePokemons)
                            {
                                if (DistanceBetweenPlaces(client.Player.Longitude, client.Player.Latitude,
                                                          pokemon.Latitude, pokemon.Longitude) <= client.GlobalSettings.MapSettings
                                    .EncounterRangeMeters / 1000)
                                {
                                    var encRes = EncounterResponse.Parser.ParseFrom(await client.RpcClient.
                                                                                    SendRemoteProcedureCallAsync(new Request
                                    {
                                        RequestType    = RequestType.Encounter,
                                        RequestMessage = new EncounterMessage
                                        {
                                            EncounterId     = pokemon.EncounterId,
                                            SpawnPointId    = pokemon.SpawnPointId,
                                            PlayerLatitude  = client.Player.Latitude,
                                            PlayerLongitude = client.Player.Longitude
                                        }.ToByteString()
                                    }));

                                    await Task.Delay(random.Next(825, 1250));

                                    if (encRes.Status == EncounterResponse.Types.Status.EncounterSuccess)
                                    {
                                        while (true)
                                        {
                                            var r = CatchPokemonResponse.Parser.ParseFrom(
                                                await client.RpcClient.SendRemoteProcedureCallAsync(new Request
                                            {
                                                RequestType    = RequestType.CatchPokemon,
                                                RequestMessage = new CatchPokemonMessage
                                                {
                                                    EncounterId           = pokemon.EncounterId,
                                                    HitPokemon            = true,
                                                    SpawnPointId          = pokemon.SpawnPointId,
                                                    NormalizedHitPosition = 1,
                                                    NormalizedReticleSize = random.NextDouble(1.7, 1.95),
                                                    Pokeball     = ItemId.ItemPokeBall,
                                                    SpinModifier = 1
                                                }.ToByteString()
                                            }));

                                            if (r.Status == CatchPokemonResponse.Types.CatchStatus.CatchSuccess ||
                                                r.Status == CatchPokemonResponse.Types.CatchStatus.CatchEscape)
                                            {
                                                break;
                                            }
                                        }
                                    }
                                }
                            }

                            foreach (var fort in cell.Forts)
                            {
                                if (DistanceBetweenPlaces(client.Player.Longitude, client.Player.Latitude,
                                                          fort.Longitude, fort.Latitude) <=
                                    client.GlobalSettings.FortSettings.InteractionRangeMeters / 1000)
                                {
                                    if (fort.Type == FortType.Checkpoint)
                                    {
                                        await client.RpcClient.SendRemoteProcedureCallAsync(new Request
                                        {
                                            RequestType    = RequestType.FortDetails,
                                            RequestMessage = new FortDetailsMessage
                                            {
                                                FortId    = fort.Id,
                                                Latitude  = fort.Latitude,
                                                Longitude = fort.Longitude
                                            }.ToByteString()
                                        });

                                        await Task.Delay(random.Next(600, 750));

                                        await client.RpcClient.SendRemoteProcedureCallAsync(new Request
                                        {
                                            RequestType    = RequestType.FortSearch,
                                            RequestMessage = new FortSearchMessage
                                            {
                                                FortId          = fort.Id,
                                                FortLatitude    = fort.Latitude,
                                                FortLongitude   = fort.Longitude,
                                                PlayerLatitude  = client.Player.Latitude,
                                                PlayerLongitude = client.Player.Longitude
                                            }.ToByteString()
                                        });
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Example #15
0
        public ResponseMessage SortPoints([FromBody] PointsVm pointsVm)
        {
            try
            {
                var tspmode     = TTSPmode.tspOpen;
                var gf          = TGISFormat.gfSHP;
                var mTSP        = new List <int>();
                var sortedPoint = new List <GeoNode>();

                //var point = JsonConvert.DeserializeObject<points>(w);

                //var count = point.coordinates.Count - 1;

                var shpfolder = _appSettings.RoutewareSettings.ShapeFolder.Replace("{{region}}", pointsVm.Region);
                var binfolder = _appSettings.RoutewareSettings.BinFolder.Replace("{{region}}", pointsVm.Region);
                var outfolder = _appSettings.RoutewareSettings.OutputFolder.Replace("{{region}}", pointsVm.Region);

                var NW = new TNetwork();
                NW.InitPassword(_appSettings.RoutewareSettings.Password);
                NW.Directory = binfolder;

                NW.Open(true, true, true, 0); // open attributes too, don't cache coord3 and open externID without caching
                NW.OpenLimit(1, 1, false);
                NW.OpenLimit(2, 2, true);
                NW.OpenRoadName(1, false);
                NW.CreateArrayTime(3); // 3 time arrays: 0,1,2
                NW.CreateArrayCost(1); // 1 cost array:  0
                                       // set speed as value based upon road classes 1,2,3,4,6 (store in index 0)
                TRoadClassSpeed rcs = new TRoadClassSpeed();
                rcs[1] = 110;
                rcs[2] = 80;
                rcs[3] = 65;
                rcs[4] = 55;
                rcs[5] = 45;
                rcs[6] = 25;
                NW.CalculateTime(0, rcs);

                TRandom r = new TRandom();
                r.SetSeed(987654321);
                // read speed into ArrayTime[2] from field "speed" in link.dbf
                NW.ReadSpeed(2, shpfolder + "\\link.dbf", 0, "speed", false);

                int link;

                // set speed as random value from 60-100 km/h (store in index 1)
                for (link = 1; link <= NW.LinkCount; link++)
                {
                    NW.SetSpeed(1, link, 60 + 40 * (float)r.NextDouble());
                }

                // set cost as the same as time from index 0
                for (link = 1; link <= NW.LinkCount; link++)
                {
                    NW.SetCost(0, link, NW.GetTime(0, link));
                }
                NW.UpdateAlphas();

                TSpatialSearch ss  = new TSpatialSearch(NW);
                TLocationList  ll  = new TLocationList();
                TBitArray      TBA = new TBitArray(1000);
                TIntegerList   nl  = new TIntegerList();

                if (pointsVm.Nodes != null)
                {
                    for (int i = 0; i < pointsVm.Nodes.Count; i++)
                    {
                        TFloatPoint fp;
                        fp.x = Convert.ToDouble(pointsVm.Nodes[i].Coordinates[0]);
                        fp.y = Convert.ToDouble(pointsVm.Nodes[i].Coordinates[1]);
                        TLocation ll1      = new TLocation();
                        int       side     = 0;
                        double    distance = 0;

                        TFloatPoint fPnew = new TFloatPoint();

                        ss.NearestLocation(fp, out ll1, out side, out distance, out fPnew);
                        ll.Add1(ll1);
                        ll.Add3(fp);
                        ll.Add4(ll1, fp);
                        nl.Add(ss.NearestNodeSimple(fp));
                    }

                    ll.Sort();
                    nl.Sort();
                    nl.RemoveDuplicates();
                }

                TRouteCalc calc = new TRouteCalc(NW, false);
                calc.SetTime(0);
                calc.SetFastest(false);
                calc.MaxSpeed = 110; // 90 > 80 and 110 > 80
                float[][] matrix = calc.Matrix(nl, (tspmode != TTSPmode.tspRoundTrip), false);
                // A faster and straight-line matrix
                // TMatrix Matrix = NW.Matrix(NL,(mode != TTspmode.tspRoundTrip));
                // optimize sequence of matrix
                TTSP tsp = new TTSP {
                    Mode = tspmode
                };
                tsp.Execute(matrix);

                for (int i = 0; i < nl.Count; i++)
                {
                    mTSP.Add(tsp.SortedIndex[i]);
                }

                // Use TDrivingDirections for output
                TGISWrite          output = NW.GISoutputInit(outfolder + "tsp_driving", gf);
                TDrivingDirections dd     = new TDrivingDirections(calc)
                {
                    ConcatenationMode = TConcatenationMode.cmCompact,
                    RoundTrip         = (tspmode == TTSPmode.tspRoundTrip),
                    SortedIndex       = tsp.SortedIndex
                };

                dd.RouteList(output, nl);
                output = NW.GISoutputInit(outfolder + "tsp", gf);
                output.StartHeader(1, TObjectTypes.otPline);
                output.AddField("sequence", TGISField.gfInteger, 0, 0);
                int d = 0;
                if (tspmode != TTSPmode.tspRoundTrip)
                {
                    d = 1;
                }
                for (int i = 0; i < nl.Count - d; i++)
                {
                    int node1 = nl[tsp.SortedIndex[i]];
                    int node2 = i != nl.Count - 1 ? nl[tsp.SortedIndex[i + 1]] : nl[tsp.SortedIndex[0]];

                    calc.Route(node1, node2);
                    TRoute             route = calc.RouteFind(node2);
                    TFloatPointArrayEx list  = NW.GetGISSectionRoute(route);
                    output.AddObject(1, false, i.ToString(CultureInfo.InvariantCulture));
                    output.AddSection(1, ref list);
                }
                output.Close();

                output = NW.GISoutputInit(outfolder + "tsppoint", gf);
                output.StartHeader(1, TObjectTypes.otPoint);
                output.AddField("sequence", TGISField.gfInteger, 0, 0);
                for (int i = 0; i < nl.Count; i++)
                {
                    int         node1 = nl[tsp.SortedIndex[i]];
                    TFloatPoint p1    = NW.Node2Coordinate(node1);
                    output.AddPoint2(p1, i.ToString(CultureInfo.InvariantCulture));
                }
                output.Close();

                for (int i = 0; i < mTSP.Count; i++)
                {
                    sortedPoint.Add(pointsVm.Nodes[mTSP[i]]);
                }

                return(new ResponseMessage {
                    Status = "Ok", Data = sortedPoint
                });
            }
            catch (Exception ex)
            {
                return(new ResponseMessage {
                    Status = "Error", Message = "Error sorting nodes."
                });
            }
        }
        private void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            for (int i = 0; i < Pop_Size; i++)
            {
                Thread.Sleep((int)(Sleeper * 100));
                _parameters.ListOfPoints.Add(new ObservablePoint(trandom.NextDouble(F1LeftConstraint, F1RightConstraint),
                                                                 trandom.NextDouble(F2LeftConstraint, F2RightConstraint)
                                                                 ));
                DomainChart.EditBSeriesCollection(_parameters.ListOfPoints);
            }



            while (_parameters.IterationNumber < _parameters.IterationLimit && !_Stop)
            {
                // inicjalizacja tablic
                InitializePopulation(ref PopulationAfterSelection, Pop_Size / 2);
                InitializePopulation(ref PopulationAfterMutation, Pop_Size / 2);
                InitializePopulation(ref PopulationAfterCrossing, Pop_Size / 4);

                InitializePopulation(ref PopulationFunctionValue, Pop_Size);
                InitializePopulation(ref PopulationFunctionValueAfterSelection, Pop_Size / 2);
                InitializePopulation(ref PopulationFunctionValueAfterCrossing, Pop_Size / 4);

                // czas na obserwacje popsize'a i wykresu wartosci funkcji

                // wszystkie operacje wykonujemy na tablicy znajdujacej sie w Parameters   public double[][][] Population; // [2][popsize][popsize]

                FillRandomValues(ref Population);

                // operacja selekcji

                // 2 warianty i tutaj trzeba zrobic ze na zasadzie losowej jest wybierana metoda selekcji

                // selekcja turniejowa --> losujemy 2 punkty z populacji i wygrywa lepszy (o mniejszej wartosci),
                // dzielimy popsize na 2 rowne zbiory i jeden zbior jest porownywany wzgledem f1 a drugi wzgledem f2



                Selection(Population, ref PopulationAfterSelection);

                // parametr, aby w nastepnej iteracji uzupelnic brakujace osobniki w populacji
                refill = true;


                Function2ValueCountForAllPopulation(PopulationAfterSelection, ref PopulationFunctionValueAfterSelection);



                // selekcja ruletkowa --> obliczamy fitness, jaki to jest procent z calosci dla danego osobnika, obliczamy dystrybuante,
                // generujemy liczby losowe i szeregujemy okreslajac ktore elementy maja przetrwac

                // mozna tutaj juz wrzucic te osobniki na wykres dziedziny



                _parameters.RewriteThePoints(PopulationAfterSelection);

                DomainChart.EditASeriesCollection(_parameters.ListOfPoints);

                CheckDomain(ref PopulationOutsideTheDomain, PopulationAfterSelection);
                _parameters.RewriteThePoints(PopulationOutsideTheDomain);
                DomainChart.SetPointsOutsideTheDomain(_parameters.ListOfPoints);


                _parameters.RewriteThePoints(PopulationFunctionValueAfterSelection);
                ParetoChart.EditSeriesCollection(_parameters.ListOfPoints);

                ParetoChart.MakeParetoFunctions(FindMinAndMax(PopulationFunctionValueAfterSelection));

                CheckParetoDomain(ref PopulationOutsideTheDomain, PopulationFunctionValueAfterSelection);
                _parameters.RewriteThePoints(PopulationOutsideTheDomain);

                ParetoChart.SetPointsOutsideTheDomain(_parameters.ListOfPoints);



                MainChart.EditSeriesCollection(PopulationFunctionValueAfterSelection, _parameters.IterationNumber);

                // operacja
                Mutation(PopulationAfterSelection, ref PopulationAfterMutation);


                // losujemy ktore punkty zostana poddane mutacji (sprawdzamy wszystkie pod wzgledem prawdopodobienstwa) (prawdopodobienstwo mutacji dla kazdego osobnika)
                // jezeli wylosowano osobnika to losujemy kat oraz dlugosc wektora
                // sprawdzamy czy zmutowany osobnik znajduje sie w dziedzinie
                // jezeli nie wykorzystujemy funkcje kary aby zwiekszyc wartosc osobnika

                // mozna tutaj juz wrzucic te osobniki na wykres dziedziny


                // operacja krzyzowania
                // to jest chyba najtrudniejsza operacja, duzo pierdolenia z przeksztalceniami
                // ogolnie to staramy sie tak skrzyzowac aby np calkowicie odbic jeden punkt
                // do dyskusji jak to robimy

                Crossing(PopulationAfterMutation, ref PopulationAfterCrossing);

                // mozna tutaj juz wrzucic te osobniki na wykres dziedziny


                // obliczenie minimum
                SearchForMinValue(PopulationFunctionValueAfterSelection, ref MinF1, ref MinF2);

                _parameters.Minimum = $"{{{Math.Round(MinF1,2)};{Math.Round(MinF2,2)}}}";

                // przepisywanie tablicy PopulationAfterCrossing do Population

                Array.Clear(Population, 0, Population.Length);
                Array.Copy(PopulationAfterCrossing, Population, PopulationAfterCrossing.Length);

                // przepisywanie tablicy PopulationFunctionValueAfterCrossing do PopulationFunctionValue
                Array.Clear(PopulationFunctionValue, 0, PopulationFunctionValue.Length);
                Array.Copy(PopulationFunctionValueAfterCrossing, PopulationFunctionValue, PopulationFunctionValueAfterCrossing.Length);

                // czyszczenie tablic
                Array.Clear(PopulationAfterSelection, 0, PopulationAfterSelection.Length);
                Array.Clear(PopulationAfterMutation, 0, PopulationAfterMutation.Length);
                Array.Clear(PopulationAfterCrossing, 0, PopulationAfterCrossing.Length);

                Array.Clear(PopulationFunctionValueAfterSelection, 0, PopulationFunctionValueAfterSelection.Length);
                Array.Clear(PopulationFunctionValueAfterCrossing, 0, PopulationFunctionValueAfterCrossing.Length);

                // finalne utworzenie wykresu dziedziny oraz pareto frontu a takze wykresu wartosci poszczegolnych funkcji

                // jezeli przez 5 iteracji nie ma poprawy minimum zatrzymujemy algorytm

                // musimy obliczyc jeszcze to spierdolone odchylenie
                // suma po wszystkich punktach w populacji (od i do licznosci pareto frontu) |f(f1) - f2|

                _parameters.IterationNumber++;
                e.Cancel = true;
                Thread.Sleep(4000);
            }
        }
Example #17
0
 public static decimal NextDecimal(this TRandom randomizer)
 {
     return(Convert.ToDecimal(randomizer.NextDouble()));
 }