public void ColumnMutated(MutationType type, IFluentBaseColumn column)
 {
     _mutation.Add(new FluentMutation {
         Type = type,
         Column = column
     });
 }
Esempio n. 2
0
 public SingleTaskGeneticSolver(AdjacencyMatrix matrix, MutationType mutation, CrossoverType crossover, SelectionType selectionType, int populationSize, int MaxTime)
 {
     this.SolverTitle  = "Single Thread Solver";
     this.crossover    = crossover;
     this.matrix       = matrix;
     this.mutation     = mutation;
     maxPopulationSize = populationSize;
     selector          = selectionType;
     rnd               = new Random();
     this.MaxTime      = MaxTime;
     results           = new List <Candidate>();
     time              = new Stopwatch();
     bestPerTwoMinutes = new List <Candidate>();
     result            = new Result(this);
     minutes           = 0;
 }
Esempio n. 3
0
        protected override State Reduce(State state, MutationType <Mutation> mutation)
        {
            var newState = state;

            switch (mutation._mutation)
            {
            case Mutation.INCREMENT:
                newState.Counter++;
                break;

            case Mutation.DECREMENT:
                newState.Counter--;
                break;
            }

            return(newState);
        }
        private void MutateAgent(Agent a)
        {
            MutationType mutationToPerform = m_config.ChooseMutationType();

            switch (mutationToPerform)
            {
            case MutationType.AddLink: a.NeuralNetwork.Mutator.MutateNewLink(); break;

            case MutationType.AddNode: a.NeuralNetwork.Mutator.MutateNewNode(); break;

            case MutationType.DeleteLink: a.NeuralNetwork.Mutator.MutateDeleteLink(); break;

            case MutationType.DeleteNode: a.NeuralNetwork.Mutator.MutateDeleteNode(); break;

            case MutationType.ModifyWeight: a.NeuralNetwork.Mutator.MutateWeight(); break;
            }
        }
Esempio n. 5
0
        protected void OnColumnMutated(MutationType type, IFluentBaseColumn column)
        {
            if (SupressChangeNotification)
            {
                return;
            }

            IFluentRecord record = Parent.SuperColumn == null ? (IFluentRecord)Parent.ColumnFamily : (IFluentRecord)Parent.SuperColumn;

            record.MutationTracker.ColumnMutated(type, column);

            if (CollectionChanged != null)
            {
                var action = type == MutationType.Added ? NotifyCollectionChangedAction.Add : (type == MutationType.Removed ? NotifyCollectionChangedAction.Remove : NotifyCollectionChangedAction.Replace);
                CollectionChanged(this, new NotifyCollectionChangedEventArgs(action, column));
            }
        }
        public override void PersistMutation(object entity, MutationType type, string path, object value)
        {
            var avatar = entity as Avatar;

            using (var db = DAFactory.Get())
            {
                switch (path)
                {
                    case "Avatar_Description":
                        db.Avatars.UpdateDescription(avatar.Avatar_Id, avatar.Avatar_Description);
                        break;
                    case "Avatar_PrivacyMode":
                        db.Avatars.UpdatePrivacyMode(avatar.Avatar_Id, avatar.Avatar_PrivacyMode);
                        break;
                }
            }
        }
Esempio n. 7
0
        public virtual void ColumnMutated(MutationType type, IFluentBaseColumn column)
        {
            if (ParentRecord is FluentSuperColumn)
            {
                var superColumn = (FluentSuperColumn)ParentRecord;
                var superColumnFamilyMutationTracker = superColumn.Family.MutationTracker;

                // check to see if there is a mutation for this column already, so we don't create duplicate mutations
                if (!superColumnFamilyMutationTracker.GetMutations().Any(x => x.Column.ColumnName == superColumn.ColumnName))
                {
                    superColumnFamilyMutationTracker.ColumnMutated(MutationType.Changed, superColumn);
                }
            }

            _mutation.Add(new FluentMutation {
                Type   = type,
                Column = column
            });
        }
Esempio n. 8
0
 /// <summary>
 /// metoda, która ustawia currentMutationType w zależności od stanu kontrolek
 /// </summary>
 private void UpdateCurrentMutationType()
 {
     if (checkBoxDisableMutation.Checked)
     {
         currentMutationType = MutationType.NONE;
     }
     else if (radioButtonConstantMutation.Checked)
     {
         currentMutationType = MutationType.CONSTANT;
     }
     else if (radioButtonPercentMutation.Checked)
     {
         currentMutationType = MutationType.PERCENT;
     }
     else if (radioButtonRandomMutation.Checked)
     {
         currentMutationType = MutationType.RANDOM;
     }
 }
		public virtual void ColumnMutated(MutationType type, IFluentBaseColumn column)
		{
			if (ParentRecord is FluentSuperColumn) {
				var superColumn = (FluentSuperColumn)ParentRecord;

				if (superColumn.Family != null) {
					var superColumnFamilyMutationTracker = superColumn.Family.MutationTracker;

					// check to see if there is a mutation for this column already, so we don't create duplicate mutations
					if (!superColumnFamilyMutationTracker.GetMutations().Any(x => x.Column.ColumnName == superColumn.ColumnName))
						superColumnFamilyMutationTracker.ColumnMutated(MutationType.Changed, superColumn);
				}
			}

			_mutation.Add(new FluentMutation {
				Type = type,
				Column = column
			});
		}
Esempio n. 10
0
 public GenomeSettings
 (
     int elitism,
     float mutationRate,
     FitnessScalingType scalingType,
     ReproductionType reproductionType,
     SelectionType selectionType,
     MutationType mutationType,
     CrossoverType crossoverType
 )
 {
     this.elitism          = elitism;
     this.mutationRate     = mutationRate;
     this.scalingType      = scalingType;
     this.reproductionType = reproductionType;
     this.selectionType    = selectionType;
     this.mutationType     = mutationType;
     this.crossoverType    = crossoverType;
 }
        public override void DemandMutation(object entity, MutationType type, string path, object value, ISecurityContext context)
        {
            var neigh = entity as Neighborhood;

            //currently, only admins can mutate neighborhoods
            var volt = (context as VoltronSession);

            if (volt == null)
            {
                throw new SecurityException("Neighborhoods cannot be mutated by non-voltron connections.");
            }
            using (var da = DAFactory.Get())
            {
                var mod = da.Avatars.GetModerationLevel(volt.AvatarId);
                if (mod < 2)
                {
                    throw new SecurityException("Neighborhoods can only be mutated by administrators.");
                }
            }

            switch (path)
            {
            case "Neighborhood_Description":
                var desc = value as string;
                if (desc != null && desc.Length > 1000)
                {
                    throw new Exception("Description too long!");
                }
                break;

            case "Neighborhood_Name":
                var name = value as string;
                if (name != null && name.Length > 100)
                {
                    throw new Exception("Name too long!");
                }
                break;

            default:
                throw new SecurityException("Field: " + path + " may not be mutated by users");
            }
        }
Esempio n. 12
0
        /// <summary>
        /// Gets a list of concrete mutations for the mutation type specified
        /// </summary>
        /// <param name="mutationType"></param>
        /// <returns></returns>
        public static IEnumerable <Type> GetMutationList(MutationType mutationType)
        {
            foreach (Type type in AllAccessibleTypes)
            {
                if (type.IsAbstract)
                {
                    continue;
                }

                if (type.GetCustomAttributes(typeof(MutationAttribute), true).Length > 0)
                {
                    var meta = (MutationAttribute)type.GetCustomAttributes(typeof(MutationAttribute), true)[0];

                    if (meta.Type == mutationType)
                    {
                        yield return(type);
                    }
                }
            }
        }
Esempio n. 13
0
        public static double GetChanceFor(MutationType type)
        {
            switch (type)
            {
            case MutationType.AddNode:
                return(AddNewNode);

            case MutationType.AddConnection:
                return(AddNewConnection);

            case MutationType.MutateWeight:
                return(MutateWeight);

            case MutationType.ChangeFunction:
                return(ChangeNodeFunction);

            default:
                return(0.0);
            }
        }
Esempio n. 14
0
        private static NeatGenome MutateOfType(MutationType type, NeatGenome genome, Population population)
        {
            switch (type)
            {
            case MutationType.MutateWeight:
                return(ChangeWeight(genome));

            case MutationType.AddConnection:
                return(AddConnection(genome, population));

            case MutationType.AddNode:
                return(AddNode(genome, population));

            case MutationType.ChangeFunction:             //and then maybe "mutateCurrentFunction type"
                return(ChangeNodeFunction(genome));

            default:
                return(genome);
            }
        }
        public static int CalculateMutations(MutationType mutationType, int mutationRateStart, int mutationRateEnd, int countOfChilds, int generationCount, int generation)
        {
            int initialMutationsByRate = countOfChilds * mutationRateStart / 100;
            int endMutationsByRate     = countOfChilds * mutationRateEnd / 100;

            switch (mutationType)
            {
            case MutationType.konstant:
                return(initialMutationsByRate);

            case MutationType.linear:
                return(initialMutationsByRate + ((endMutationsByRate - initialMutationsByRate) / generationCount) * generation);

            case MutationType.exponentiel:
                return((int)(initialMutationsByRate * Math.Pow((endMutationsByRate / initialMutationsByRate), (generation / generationCount))));

            default:
                return(0);
            }
            return(initialMutationsByRate);
        }
        public override void PersistMutation(object entity, MutationType type, string path, object value)
        {
            var neigh = entity as Neighborhood;

            switch (path)
            {
            case "Neighborhood_Description":
                using (var db = DAFactory.Get())
                {
                    db.Neighborhoods.UpdateDescription(neigh.Id, neigh.Neighborhood_Description);
                }
                break;

            case "Neighborhood_Name":
                using (var db = DAFactory.Get())
                {
                    db.Neighborhoods.UpdateName(neigh.Id, neigh.Neighborhood_Name);
                }
                break;
            }
        }
    private NeatGenome <T>?Create(
        NeatGenome <T> parent,
        IRandomSource rng,
        ref DiscreteDistribution mutationTypeDist)
    {
        // Determine the type of mutation to attempt.
        MutationType mutationTypeId = (MutationType)DiscreteDistribution.Sample(rng, mutationTypeDist);

        // Attempt to create a child genome using the selected mutation type.
        NeatGenome <T>?childGenome = mutationTypeId switch
        {
            // Note. These subroutines will return null if they cannot produce a child genome,
            // e.g. 'delete connection' will not succeed if there is only one connection.
            MutationType.ConnectionWeight => _mutateWeightsStrategy.CreateChildGenome(parent, rng),
            MutationType.AddNode => _addNodeStrategy.CreateChildGenome(parent, rng),
            MutationType.AddConnection => _addConnectionStrategy.CreateChildGenome(parent, rng),
            MutationType.DeleteConnection => _deleteConnectionStrategy.CreateChildGenome(parent, rng),
            _ => throw new Exception($"Unexpected mutationTypeId [{mutationTypeId}]."),
        };

        if (childGenome is not null)
        {
            return(childGenome);
        }

        // The chosen mutation type was not possible; remove that type from the set of possible types.
        mutationTypeDist = mutationTypeDist.RemoveOutcome((int)mutationTypeId);

        // Sanity test.
        if (mutationTypeDist.Probabilities.Length == 0)
        {
            // This shouldn't be possible, hence this is an exceptional circumstance.
            // Note. Connection weight and 'add node' mutations should always be possible, because there should
            // always be at least one connection.
            throw new Exception("All types of genome mutation failed.");
        }

        return(null);
    }
Esempio n. 18
0
        public void SwapShapes(Random rand)
        {
            int   s1    = rand.Next(Shapes.Length);
            Shape shape = Shapes[s1];

            shape.PreviousState = shape.Clone() as Shape;
            if (rand.Next(2) == 0)
            {
                int s2;
                do
                {
                    s2 = rand.Next(Shapes.Length);
                } while (s1 == s2);
                ShiftShapeIndex(s1, s2);
            }
            else
            {
                int s2 = rand.Next(Shapes.Length);
                Shapes[s1] = Shapes[s2];
                Shapes[s2] = shape;
            }
            LastMutation = MutationType.SwapShapes;
        }
        /// <summary>
        /// Constructor with parameters.
        /// </summary>
        /// <param name="populationSize">The population size.</param>
        /// <param name="encodingType">The encoding type used in the chromosome.</param>
        /// <param name="selectionType">The selection type.</param>
        /// <param name="crossoverType">The crossover type.</param>
        /// <param name="mutationType">The mutation type.</param>
        /// <param name="mutationRate">The mutation rate.</param>
        /// <param name="elitisim">The elistism rate.</param>
        /// <param name="stoppingCriteriaOptions">The stopping critieria options used to stop the algorithm from executing forever.
        /// Optional if not specified, it will use the default which is set to an iteration threshold with maximum of 1000 iterations.</param>
        public GAOptions(int populationSize, EncodingType encodingType, SelectionType selectionType, CrossoverType crossoverType, MutationType mutationType,
                         double mutationRate, double elitisim, StoppingCriteriaOptions stoppingCriteriaOptions = null)
        {
            PopulationSize = populationSize;
            EncodingType   = encodingType;
            SelectionType  = selectionType;
            CrossoverType  = crossoverType;
            MutationType   = mutationType;
            MutationRate   = mutationRate;
            Elitism        = elitisim;

            if (stoppingCriteriaOptions == null)
            {
                // if not specified the GA will use an iteration based stopping criteria, set to a maximum iteration of 1000.
                StoppingCriteriaOptions = new StoppingCriteriaOptions
                {
                    StoppingCriteriaType = StoppingCriteriaType.SpecifiedIterations,
                    MaximumIterations    = 1000
                };
                return;
            }

            StoppingCriteriaOptions = stoppingCriteriaOptions;
        }
Esempio n. 20
0
 public RiskMatrix(Currency c1, Currency c2, MutationType shiftType, RiskMetric metric, double shiftStepSize1, double shiftStepSize2, int nScenarios, ICurrencyProvider currencyProvider, bool returnDifferential = true)
 {
 }
Esempio n. 21
0
        public override void DemandMutation(object entity, MutationType type, string path, object value, ISecurityContext context)
        {
            var lot = entity as Lot;

            if (lot.DbId == 0)
            {
                throw new SecurityException("Unclaimed lots cannot be mutated");
            }

            var roomies = lot.Lot_RoommateVec;

            switch (path)
            {
            //Owner only
            case "Lot_Description":
                context.DemandAvatar(lot.Lot_LeaderID, AvatarPermissions.WRITE);
                var desc = value as string;
                if (desc != null && desc.Length > 500)
                {
                    throw new Exception("Description too long!");
                }
                break;

            case "Lot_Name":
                context.DemandAvatar(lot.Lot_LeaderID, AvatarPermissions.WRITE);
                if (!GlobalRealestate.ValidateLotName((string)value))
                {
                    throw new Exception("Invalid lot name");
                }
                //Lot_Name is a special case, it has to be unique so we have to hit the db in the security check
                //for this mutation.
                TryChangeLotName(lot, (string)value);
                break;

            case "Lot_Category":
                context.DemandAvatar(lot.Lot_LeaderID, AvatarPermissions.WRITE);

                if (lot.Lot_IsOnline)
                {
                    throw new SecurityException("Lot must be offline to change category!");
                }

                //7 days
                if (((Epoch.Now - lot.Lot_LastCatChange) / (60 * 60)) < 168)
                {
                    throw new SecurityException("You must wait 7 days to change your lot category again");
                }
                break;

            case "Lot_SkillGamemode":
                context.DemandAvatar(lot.Lot_LeaderID, AvatarPermissions.WRITE);

                var  svalue = (uint)value;
                uint minSkill;
                if (!SkillGameplayCategory.TryGetValue((LotCategory)lot.Lot_Category, out minSkill))
                {
                    minSkill = 0;
                }
                if (Math.Min(2, Math.Max(minSkill, svalue)) != svalue)
                {
                    throw new SecurityException("Invalid gamemode for this category.");
                }

                if (lot.Lot_IsOnline)
                {
                    throw new SecurityException("Lot must be offline to change skill mode!");
                }
                break;

            //roommate only
            case "Lot_Thumbnail":
                context.DemandAvatars(roomies, AvatarPermissions.WRITE);
                //TODO: needs to be generic data, png, size 288x288, less than 1MB
                break;

            case "Lot_IsOnline":
            case "Lot_NumOccupants":
            case "Lot_RoommateVec":
            case "Lot_SpotLightText":
                context.DemandInternalSystem();
                break;

            case "Lot_LotAdmitInfo.LotAdmitInfo_AdmitList":
            case "Lot_LotAdmitInfo.LotAdmitInfo_BanList":
                context.DemandAvatars(roomies, AvatarPermissions.WRITE);
                int atype = (path == "Lot_LotAdmitInfo.LotAdmitInfo_AdmitList") ? 0 : 1;
                using (var db = DAFactory.Get())
                {     //need to check db constraints
                    switch (type)
                    {
                    case MutationType.ARRAY_REMOVE_ITEM:
                        //Remove bookmark at index value
                        var removedAva = (uint)value;
                        db.LotAdmit.Delete(new DbLotAdmit
                        {
                            lot_id     = (int)lot.DbId,
                            avatar_id  = removedAva,
                            admit_type = (byte)atype
                        });
                        break;

                    case MutationType.ARRAY_SET_ITEM:
                        //Add a new bookmark
                        var newAva = (uint)value;
                        db.LotAdmit.Create(new DbLotAdmit
                        {
                            lot_id     = (int)lot.DbId,
                            avatar_id  = newAva,
                            admit_type = (byte)atype
                        });
                        break;
                    }
                }
                break;

            case "Lot_LotAdmitInfo.LotAdmitInfo_AdmitMode":
                context.DemandAvatars(roomies, AvatarPermissions.WRITE);
                //can only set valid values
                var mode = (byte)value;
                if (mode < 0 || mode > 3)
                {
                    throw new Exception("Invalid admit mode!");
                }
                break;

            default:
                throw new SecurityException("Field: " + path + " may not be mutated by users");
            }
        }
 /// <summary>
 /// PlatformEntity mutation of a certain type
 /// </summary>
 /// <param name="entity">PlatformEntity the mutation acts on</param>
 /// <param name="type">The type of mutation to occur</param>
 public MutationAttribute(Type entity, MutationType type)
 {
     this.Entity = entity;
     this.Type   = type;
 }
Esempio n. 23
0
 public MutationResult(MutationType mutationType, Dictionary <string, ExpressionResult> args) : base(null)
 {
     this.mutationType   = mutationType;
     this.gqlRequestArgs = args;
     paramExp            = Expression.Parameter(mutationType.ContextType);
 }
Esempio n. 24
0
        public override void PersistMutation(object entity, MutationType type, string path, object value)
        {
            var lot = entity as Lot;

            switch (path)
            {
            case "Lot_Description":
                using (var db = DAFactory.Get())
                {
                    db.Lots.UpdateDescription(lot.DbId, lot.Lot_Description);
                }
                break;

            case "Lot_Thumbnail":
                var imgpath = Path.Combine(NFS.GetBaseDirectory(), "Lots/" + lot.DbId.ToString("x8") + "/thumb.png");
                var data    = (cTSOGenericData)value;

                using (var db = DAFactory.Get())
                {
                    db.Lots.SetDirty(lot.DbId, 1);
                }

                using (FileStream fs = File.Open(imgpath, FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    fs.Write(data.Data, 0, data.Data.Length);
                }
                lot.Lot_Thumbnail = new cTSOGenericData(new byte[0]);
                break;

            case "Lot_Category":
                uint minSkill;
                if (!SkillGameplayCategory.TryGetValue((LotCategory)lot.Lot_Category, out minSkill))
                {
                    minSkill = 0;
                }
                lot.Lot_SkillGamemode = Math.Min(2, Math.Max(minSkill, lot.Lot_SkillGamemode));
                using (var db = DAFactory.Get())
                {
                    db.Lots.UpdateLotCategory(lot.DbId, (LotCategory)(lot.Lot_Category), lot.Lot_SkillGamemode);
                }
                break;

            case "Lot_SkillGamemode":
                using (var db = DAFactory.Get())
                {
                    db.Lots.UpdateLotSkillMode(lot.DbId, lot.Lot_SkillGamemode);
                }
                break;

            case "Lot_IsOnline":
                lock (CityRepresentation.City_ReservedLotInfo) CityRepresentation.City_ReservedLotInfo = CityRepresentation.City_ReservedLotInfo.SetItem(lot.Lot_Location_Packed, lot.Lot_IsOnline);
                break;

            case "Lot_SpotLightText":
                lock (CityRepresentation)
                {
                    var clone = new HashSet <uint>(CityRepresentation.City_SpotlightsVector);    //need to convert this to a hashset to add to it properly
                    if (lot.Lot_SpotLightText != "")
                    {
                        clone.Add(lot.Lot_Location_Packed);
                    }
                    else
                    {
                        clone.Remove(lot.Lot_Location_Packed);
                    }
                    CityRepresentation.City_SpotlightsVector = ImmutableList.ToImmutableList(clone);
                }
                break;

            case "Lot_LotAdmitInfo.LotAdmitInfo_AdmitMode":
                using (var db = DAFactory.Get())
                {
                    db.Lots.UpdateLotAdmitMode(lot.DbId, (byte)value);
                }
                break;
            }
        }
Esempio n. 25
0
 public virtual void DemandMutation(object entity, MutationType type, string path, object value, ISecurityContext context)
 {
 }
Esempio n. 26
0
 /// <summary>
 /// 設定情報を表示します
 /// </summary>
 private void DisplaySettingInfo(ChromosomesType cht, SelectionType st, CrossOverType crt, MutationType mt, float mr, int size, int ittr)
 {
     SettingListBox.Items.Clear();
     SettingListBox.Items.Add($"染色体タイプ: {cht}");
     SettingListBox.Items.Add($"選択タイプ: {st}");
     SettingListBox.Items.Add($"交叉タイプ: {crt}");
     SettingListBox.Items.Add($"突然変異タイプ: {mt}");
     SettingListBox.Items.Add($"突然変異率: {mr} [%]");
     SettingListBox.Items.Add($"個体数: {size}");
     SettingListBox.Items.Add($"最大世代数: {ittr}");
 }
        internal GeneticSolver createNewSolver(bool isMultiThread)
        {
            MutationType    mutation  = null;
            CrossoverType   crossover = null;
            SelectionType   selection = null;
            GeneticSolver   solver    = null;//add parameters TO DO
            AdjacencyMatrix matrix    = new AdjacencyMatrix(tspXmlFile);

            switch (mutationIndex)
            {
            case 0:
            {
                if (!isMultiThread)
                {
                    mutation = new InversionMutation(mutationChance);
                }
                else
                {
                    mutation = new MultiThreadInversionMutation(mutationChance);
                }
                break;
            }

            case 1:
            {
                if (!isMultiThread)
                {
                    mutation = new TranspositionMutation(mutationChance);
                }
                else
                {
                    mutation = new MultiThreadTranspositionMutation(mutationChance);
                }
                break;
            }
            }

            switch (crossoverIndex)
            {
            case 0:
            {
                if (!isMultiThread)
                {
                    crossover = new PMXCrossover(crossoverChance);
                }
                else
                {
                    crossover = new MultiThreadPMXCrossover(crossoverChance);          //new PMXCrossover(crossoverChance); //
                }
                break;
            }

            case 1:
            {
                if (!isMultiThread)
                {
                    crossover = new OXCrossover(crossoverChance);
                }
                else
                {
                    crossover = new MultiThreadOXCrossover(crossoverChance);
                }
                break;
            }
            }

            switch (selectorIndex)
            {
            case 0:
            {
                if (!isMultiThread)
                {
                    selection = new TournamentSelection(selectorSize);
                }
                else
                {
                    selection = new MultiThreadTournamentSelection(selectorSize);
                }
                break;
            }

            case 1:
            {
                if (!isMultiThread)
                {
                    selection = new RouletteSelection(selectorSize);
                }
                else
                {
                    selection = new MultiThreadRouletteSelection(selectorSize);
                }
                break;
            }
            }

            if (mutation != null && selection != null && crossover != null)
            {
                if (isMultiThread)
                {
                    MultiTaskOptions.parallelOptCrossover.MaxDegreeOfParallelism = int.Parse(View.tbxLvlCrossover.Text);
                    MultiTaskOptions.parallelOptMutation.MaxDegreeOfParallelism  = int.Parse(View.tbxLvlMutation.Text);
                    MultiTaskOptions.parallelOptSelection.MaxDegreeOfParallelism = int.Parse(View.tbxLvlSelector.Text);
                    solver = new MultiTaskGeneticSolver(matrix, mutation, crossover, selection, populationSize, timeMS);
                }
                else
                {
                    solver = new SingleTaskGeneticSolver(matrix, mutation, crossover, selection, populationSize, timeMS);
                }
            }
            return(solver);
        }
Esempio n. 28
0
 public virtual void PersistMutation(object entity, MutationType type, string path, object value)
 {
 }
        public ExperimentParameters(
            int numberOfDimensions,

            int basePopulationSize,
            int offspringPopulationSize,
            int numberOfGenerations,

            int seed = EvolutionDefaults.Seed,
            bool trackEvolutionSteps             = EvolutionDefaults.TrackEvolutionSteps,
            bool useRedundantConstraintsRemoving = Defaults.UseRedundantConstraintsRemoving,
            bool useDataNormalization            = Defaults.UseDataNormalization,
            bool allowQuadraticTerms             = Defaults.AllowQuadraticTerms,
            bool useSeeding = Defaults.UseSeeding,

            ISet <TermType> allowedTermsTypes       = default(ISet <TermType>),
            BenchmarkType typeOfBenchmark           = Defaults.TypeOfBenchmark,
            double ballnBoundaryValue               = Defaults.BallnBoundaryValue,
            double cubenBoundaryValue               = Defaults.CubenBoundaryValue,
            double simplexnBoundaryValue            = Defaults.SimplexnBoundaryValue,
            IList <Constraint> referenceConstraints = default(IList <Constraint>),

            long numberOfDomainSamples         = Defaults.NumberOfDomainSamples,
            int numberOfTestPoints             = Defaults.NumberOfTestPoints,
            int numberOfPositivePoints         = Defaults.NumberOfPositivePoints,
            int numberOfNegativePoints         = Defaults.NumberOfNegativePoints,
            double defaultDomainLowerLimit     = Defaults.DefaultDomainLowerLimit,
            double defaultDomainUpperLimit     = Defaults.DefaultDomainUpperLimit,
            int maxNumberOfPointsInSingleArray = Defaults.MaxNumberOfPointsInSingleArray,

            double globalLearningRate     = double.NaN,
            double individualLearningRate = double.NaN,
            double stepThreshold          = EvolutionDefaults.StepThreshold,
            double rotationAngle          = EvolutionDefaults.RotationAngle,
            MutationType typeOfMutation   = EvolutionDefaults.TypeOfMutation,

            int numberOfParentsSolutionsToSelect            = EvolutionDefaults.NumberOfParentsSolutionsToSelect,
            ParentsSelectionType typeOfParentsSelection     = EvolutionDefaults.TypeOfParentsSelection,
            SurvivorsSelectionType typeOfSurvivorsSelection = EvolutionDefaults.TypeOfSurvivorsSelection,

            int oneFifthRuleCheckInterval    = EvolutionDefaults.OneFifthRuleCheckInterval,
            double oneFifthRuleScalingFactor = EvolutionDefaults.OneFifthRuleScalingFactor,

            bool useRecombination = EvolutionDefaults.UseRecombination,
            RecombinationType typeOfObjectsRecombination       = EvolutionDefaults.TypeOfObjectsRecombination,
            RecombinationType typeOfStdDeviationsRecombination = EvolutionDefaults.TypeOfStdDeviationsRecombination,
            RecombinationType typeOfRotationsRecombination     = EvolutionDefaults.TypeOfRotationsRecombination)
        {
            if (typeOfBenchmark == BenchmarkType.Other && referenceConstraints == default(IList <Constraint>))
            {
                throw new ArgumentException("In case of choosing BenchmarkType = Other, it is obligatory to provide reference constraints.");
            }

            AllowedTermsTypes = allowedTermsTypes == default(ISet <TermType>)
                ? Defaults.AllowedTermsTypes
                : allowedTermsTypes;

            //HACK
            //AllowedTermsTypes = new HashSet<TermType>
            //{
            //    TermType.Linear,
            //    TermType.Quadratic
            //};

            //NumberOfConstraintsCoefficients = numberOfDimensions * AllowedTermsTypes.Count + 1;

            NumberOfConstraintsCoefficients = typeOfBenchmark == BenchmarkType.Balln && allowQuadraticTerms
                ? numberOfDimensions * 2 + 1
                : numberOfDimensions + 1;

            //MaximumNumberOfConstraints = typeOfBenchmark == BenchmarkType.Other
            //    // ReSharper disable once PossibleNullReferenceException : It is checked before
            //    ? referenceConstraints.Count
            //    : GetMaximumNumberOfConstraints(numberOfDimensions, typeOfBenchmark, allowQuadraticTerms);

            //MaximumNumberOfConstraints = GetMaximumNumberOfConstraints(numberOfDimensions, typeOfBenchmark,
            //    allowQuadraticTerms);
            MaximumNumberOfConstraints = numberOfDimensions * numberOfDimensions;

            var objectVectorSize = NumberOfConstraintsCoefficients * MaximumNumberOfConstraints;

            NumberOfDimensions = numberOfDimensions;

            EvolutionParameters = new EvolutionParameters(
                objectVectorSize, basePopulationSize, offspringPopulationSize, numberOfGenerations, seed, trackEvolutionSteps,
                oneFifthRuleCheckInterval, oneFifthRuleScalingFactor, numberOfParentsSolutionsToSelect, (int)typeOfParentsSelection, (int)typeOfSurvivorsSelection,
                globalLearningRate, individualLearningRate, stepThreshold, rotationAngle, (int)typeOfMutation,
                useRecombination, (int)typeOfObjectsRecombination, (int)typeOfStdDeviationsRecombination, (int)typeOfRotationsRecombination);
            Seed = seed;
            TrackEvolutionSteps             = trackEvolutionSteps;
            UseRedundantConstraintsRemoving = useRedundantConstraintsRemoving;
            UseDataNormalization            = useDataNormalization;
            AllowQuadraticTerms             = allowQuadraticTerms;
            UseSeeding = useSeeding;

            TypeOfBenchmark       = typeOfBenchmark;
            BallnBoundaryValue    = ballnBoundaryValue;
            CubenBoundaryValue    = cubenBoundaryValue;
            SimplexnBoundaryValue = simplexnBoundaryValue;
            ReferenceConstraints  = referenceConstraints;

            NumberOfDomainSamples          = numberOfDomainSamples;
            NumberOfTestPoints             = numberOfTestPoints;
            NumberOfPositivePoints         = numberOfPositivePoints;
            NumberOfNegativePoints         = numberOfNegativePoints;
            DefaultDomainLowerLimit        = defaultDomainLowerLimit;
            DefaultDomainUpperLimit        = defaultDomainUpperLimit;
            MaxNumberOfPointsInSingleArray = maxNumberOfPointsInSingleArray;
        }
Esempio n. 30
0
 public static bool DoMutation(this Random rand, MutationType type)
 {
     return(rand.NextDouble() <= MutationChances.GetChanceFor(type));
 }
Esempio n. 31
0
 public void SwapShapes(Random rand)
 {
     int s1 = rand.Next(Shapes.Length);
     Shape shape = Shapes[s1];
     shape.PreviousState = shape.Clone() as Shape;
     if (rand.Next(2) == 0) {
         int s2;
         do {
             s2 = rand.Next(Shapes.Length);
         } while (s1 == s2);
         ShiftShapeIndex(s1, s2);
     } else {
         int s2 = rand.Next(Shapes.Length);
         Shapes[s1] = Shapes[s2];
         Shapes[s2] = shape;
     }
     LastMutation = MutationType.SwapShapes;
 }
Esempio n. 32
0
 public GeneticIndividual(int[] topology, int numberOfEvaluations, MutationType mutation) : base(topology, numberOfEvaluations, mutation)
 {
 }
        public override void DemandMutation(object entity, MutationType type, string path, object value, ISecurityContext context)
        {
            var avatar = entity as Avatar;

            switch (path)
            {
            case "Avatar_BookmarksVec":
                context.DemandAvatar(avatar.Avatar_Id, AvatarPermissions.WRITE);
                using (var db = DAFactory.Get)
                {     //need to check db constraints here.
                    switch (type)
                    {
                    case MutationType.ARRAY_REMOVE_ITEM:
                        //Remove bookmark at index value
                        var removedBookmark = value as Bookmark;
                        if (removedBookmark != null)
                        {
                            db.Bookmarks.Delete(new DbBookmark
                            {
                                avatar_id = avatar.Avatar_Id,
                                type      = removedBookmark.Bookmark_Type,
                                target_id = removedBookmark.Bookmark_TargetID
                            });
                        }
                        break;

                    case MutationType.ARRAY_SET_ITEM:
                        //Add a new bookmark
                        var newBookmark = value as Bookmark;
                        if (newBookmark != null)
                        {
                            db.Bookmarks.Create(new DbBookmark
                            {
                                avatar_id = avatar.Avatar_Id,
                                target_id = newBookmark.Bookmark_TargetID,
                                type      = newBookmark.Bookmark_Type
                            });
                        }
                        break;
                    }
                }
                break;

            case "Avatar_Description":
                context.DemandAvatar(avatar.Avatar_Id, AvatarPermissions.WRITE);
                var desc = value as string;
                if (desc != null && desc.Length > 500)
                {
                    throw new Exception("Description too long!");
                }
                break;

            case "Avatar_Skills.AvatarSkills_LockLv_Body":
            case "Avatar_Skills.AvatarSkills_LockLv_Charisma":
            case "Avatar_Skills.AvatarSkills_LockLv_Cooking":
            case "Avatar_Skills.AvatarSkills_LockLv_Creativity":
            case "Avatar_Skills.AvatarSkills_LockLv_Logic":
            case "Avatar_Skills.AvatarSkills_LockLv_Mechanical":
                context.DemandAvatar(avatar.Avatar_Id, AvatarPermissions.WRITE);
                var level = (ushort)value;
                //need silly rules so this isnt gamed.
                //to change on city level must not be on a lot (city must own claim), need to db query the other locks

                var skills    = avatar.Avatar_Skills;
                var limit     = avatar.Avatar_SkillsLockPoints;
                var skillname = "lock_" + path.Substring(34).ToLower();

                using (var da = DAFactory.Get)
                {
                    if (((da.AvatarClaims.GetByAvatarID(avatar.Avatar_Id)?.location) ?? 0) != 0)
                    {
                        throw new Exception("Lot owns avatar! Lock using the VM commands.");
                    }
                    if (level > limit - da.Avatars.GetOtherLocks(avatar.Avatar_Id, skillname))
                    {
                        throw new Exception("Cannot lock this many skills!");
                    }
                }
                break;

            case "Avatar_PrivacyMode":
                context.DemandAvatar(avatar.Avatar_Id, AvatarPermissions.WRITE);
                var mode = (byte)value;
                if (mode > 1)
                {
                    throw new Exception("Invalid privacy mode!");
                }
                break;

            case "Avatar_Top100ListFilter.Top100ListFilter_Top100ListID":
                context.DemandAvatar(avatar.Avatar_Id, AvatarPermissions.WRITE);
                var cat = (LotCategory)((uint)value);

                using (var db = DAFactory.Get)
                {     //filters baby! YES! about time i get a f*****g break in this game
                    var filter = db.LotClaims.Top100Filter(ShardId, cat, 10);
                    avatar.Avatar_Top100ListFilter.Top100ListFilter_ResultsVec = ImmutableList.ToImmutableList(filter.Select(x => x.location));
                }

                break;

            default:
                throw new SecurityException("Field: " + path + " may not be mutated by users");
            }
        }