Changeset 3269
- Timestamp:
- 04/05/10 18:52:23 (15 years ago)
- Location:
- trunk/sources
- Files:
-
- 14 edited
Legend:
- Unmodified
- Added
- Removed
-
trunk/sources/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.3/Symbol.cs
r3223 r3269 26 26 using System.Linq; 27 27 using HeuristicLab.Persistence.Default.CompositeSerializers.Storable; 28 using HeuristicLab.Data; 29 using HeuristicLab.Parameters; 28 30 29 31 namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding { 30 32 [StorableClass] 31 33 [Item("Symbol", "Represents a symbol in a symbolic function tree.")] 32 public abstract class Symbol : Item { 33 private List<List<Symbol>> allowedSubFunctions = new List<List<Symbol>>(); 34 private int minArity = -1; 35 private int maxArity = -1; 36 private double tickets = 1.0; 37 private IOperator initializer; 38 private IOperator manipulator; 39 private int minTreeHeight = -1; 40 private int minTreeSize = -1; 34 public abstract class Symbol : ParameterizedNamedItem { 35 #region Parameter Properties 36 public IValueParameter<DoubleValue> TicketsParameter { 37 get { return (IValueParameter<DoubleValue>)Parameters["Tickets"]; } 38 } 39 #endregion 41 40 42 private string name;43 public virtual string Name{44 get { return name; }41 #region Properties 42 public DoubleValue Tickets { 43 get { return TicketsParameter.Value; } 45 44 set { 46 if (string.IsNullOrEmpty(value)) throw new ArgumentException(); 47 if (value != name) { 48 name = value; 49 } 45 if (value.Value < 0.0) throw new ArgumentException("Number of tickets must be positive"); 46 TicketsParameter.Value = value; 50 47 } 51 48 } 49 #endregion 52 50 53 protected Symbol() { 54 name = this.GetType().Name; 55 } 56 57 public int MinSubTrees { 58 get { 59 return minArity; 60 } 61 protected internal set { 62 if (value < 0) throw new ArgumentException(); 63 if (minArity != value) { 64 minArity = value; 65 while (minArity > allowedSubFunctions.Count) allowedSubFunctions.Add(new List<Symbol>()); 66 ResetCachedValues(); 67 } 68 } 69 } 70 71 public int MaxSubTrees { 72 get { 73 return maxArity; 74 } 75 protected internal set { 76 if (value < 0) throw new ArgumentException(); 77 if (value < minArity) throw new ArgumentException(); 78 if (value != maxArity) { 79 maxArity = value; 80 while (allowedSubFunctions.Count > maxArity) allowedSubFunctions.RemoveAt(allowedSubFunctions.Count - 1); 81 while (maxArity > allowedSubFunctions.Count) { 82 if (allowedSubFunctions.Count > 0) { 83 // copy the list of allowed sub-functions from the previous slot 84 allowedSubFunctions.Add(new List<Symbol>(allowedSubFunctions[allowedSubFunctions.Count - 1])); 85 } else { 86 // add empty list 87 allowedSubFunctions.Add(new List<Symbol>()); 88 } 89 } 90 ResetCachedValues(); 91 } 92 } 93 } 94 95 96 public int MinTreeSize { 97 get { 98 if (minTreeSize <= 0) { 99 RecalculateMinimalTreeSize(); 100 } 101 // Debug.Assert(minTreeSize > 0); 102 return minTreeSize; 103 } 104 } 105 106 public int MinTreeHeight { 107 get { 108 if (minTreeHeight <= 0) { 109 RecalculateMinimalTreeHeight(); 110 } 111 // Debug.Assert(minTreeHeight > 0); 112 return minTreeHeight; 113 } 114 } 115 116 public double Tickets { 117 get { return tickets; } 118 set { 119 if (value < 0.0) throw new ArgumentException("Number of tickets must be positive"); 120 if (value != tickets) { 121 tickets = value; 122 } 123 } 124 } 125 126 public IOperator Initializer { 127 get { return initializer; } 128 set { 129 if (initializer != value) { 130 initializer = value; 131 } 132 } 133 } 134 135 public IOperator Manipulator { 136 get { return manipulator; } 137 set { 138 if (manipulator != value) { 139 manipulator = value; 140 } 141 } 51 protected Symbol() 52 : base() { 53 Parameters.Add(new ValueParameter<DoubleValue>("Tickets", new DoubleValue(1.0))); 142 54 } 143 55 … … 145 57 return new SymbolicExpressionTreeNode(this); 146 58 } 147 148 public IEnumerable<Symbol> GetAllowedSubFunctions(int index) {149 if (index < 0 || index > MaxSubTrees) throw new ArgumentException("Index outside of allowed range. index = " + index);150 return allowedSubFunctions[index];151 }152 153 public void AddAllowedSubFunction(Symbol symbol, int index) {154 if (index < 0 || index > MaxSubTrees) throw new ArgumentException("Index outside of allowed range. index = " + index);155 if (allowedSubFunctions[index] == null) {156 allowedSubFunctions[index] = new List<Symbol>();157 }158 if (!allowedSubFunctions[index].Contains(symbol)) {159 allowedSubFunctions[index].Add(symbol);160 }161 ResetCachedValues();162 }163 public void RemoveAllowedSubFunction(Symbol symbol, int index) {164 if (index < 0 || index > MaxSubTrees) throw new ArgumentException("Index outside of allowed range. index = " + index);165 if (allowedSubFunctions[index].Contains(symbol)) {166 allowedSubFunctions[index].Remove(symbol);167 ResetCachedValues();168 }169 }170 171 private void ResetCachedValues() {172 minTreeHeight = -1;173 minTreeSize = -1;174 }175 176 public bool IsAllowedSubFunction(Symbol symbol, int index) {177 return GetAllowedSubFunctions(index).Contains(symbol);178 }179 180 private void RecalculateMinimalTreeSize() {181 if (MinSubTrees == 0) minTreeSize = 1;182 else {183 minTreeSize = int.MaxValue; // prevent infinite recursion184 minTreeSize = 1 + (from slot in Enumerable.Range(0, MinSubTrees)185 let minForSlot = (from function in GetAllowedSubFunctions(slot)186 where function != this187 select function.MinTreeSize).DefaultIfEmpty(0).Min()188 select minForSlot).Sum();189 }190 }191 192 private void RecalculateMinimalTreeHeight() {193 if (MinSubTrees == 0) minTreeHeight = 1;194 else {195 minTreeHeight = int.MaxValue;196 minTreeHeight = 1 + (from slot in Enumerable.Range(0, MinSubTrees)197 let minForSlot = (from function in GetAllowedSubFunctions(slot)198 where function != this199 select function.MinTreeHeight).DefaultIfEmpty(0).Min()200 select minForSlot).Max();201 }202 }203 204 public override string ToString() {205 return name;206 }207 59 } 208 60 } -
trunk/sources/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.3/SymbolicExpressionTreeCreator.cs
r3239 r3269 20 20 #endregion 21 21 22 using System.Linq; 22 23 using HeuristicLab.Core; 23 24 using HeuristicLab.Data; … … 72 73 SymbolicExpressionTreeParameter.ActualValue = Create(RandomParameter.ActualValue, SymbolicExpressionGrammarParameter.ActualValue, 73 74 MaxTreeSizeParameter.ActualValue, MaxTreeHeightParameter.ActualValue); 74 return base.Apply(); 75 76 foreach (var node in SymbolicExpressionTreeParameter.ActualValue.IterateNodesPostfix()) { 77 node.ResetLocalParameters(RandomParameter.ActualValue); 78 } 79 return null; 75 80 } 76 81 -
trunk/sources/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.3/SymbolicExpressionTreeNode.cs
r3252 r3269 76 76 return maxHeight + 1; 77 77 } 78 79 //public virtual IOperation CreateShakingOperation(IScope scope) { 80 // return null; 81 //} 82 83 //public virtual IOperation CreateInitOperation(IScope scope) { 84 // return null; 85 //} 78 79 public virtual void ResetLocalParameters(IRandom random) { } 80 public virtual void ShakeLocalParameters(IRandom random, double shakingFactor) { } 86 81 87 82 protected internal virtual void AddSubTree(SymbolicExpressionTreeNode tree) { -
trunk/sources/HeuristicLab.Problems.ArtificialAnt/3.3/Symbols/Prog3.cs
r3223 r3269 23 23 namespace HeuristicLab.Problems.ArtificialAnt { 24 24 public sealed class Prog3 : Symbol { 25 26 25 public Prog3() 27 26 : base() { 28 MinSubTrees = 3; MaxSubTrees = 3;29 27 } 30 28 } -
trunk/sources/HeuristicLab.Problems.DataAnalysis.Regression/3.3/Symbolic/ArithmeticExpressionGrammar.cs
r3257 r3269 29 29 using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.GeneralSymbols; 30 30 using HeuristicLab.Problems.DataAnalysis.Regression.Symbolic.Symbols; 31 using HeuristicLab.Data; 31 32 namespace HeuristicLab.Problems.DataAnalysis.Regression.Symbolic { 32 33 [StorableClass] 33 public class ArithmeticExpressionGrammar : Item, ISymbolicExpressionGrammar { 34 public class ArithmeticExpressionGrammar : NamedItemCollection<Symbol>, ISymbolicExpressionGrammar { 35 36 private List<string> variableNames = new List<string>(); 37 public IEnumerable<string> VariableNames { 38 get { return variableNames; } 39 set { 40 variableNames = new List<string>(value); 41 var variable = (HeuristicLab.Problems.DataAnalysis.Regression.Symbolic.Symbols.Variable)allSymbols[5]; 42 variable.VariableNames = new ItemList<HeuristicLab.Data.StringValue>(variableNames.Select(x => new StringValue(x))); 43 } 44 } 34 45 35 46 public ArithmeticExpressionGrammar() 36 : base() {47 : this(allSymbols) { 37 48 } 49 50 public ArithmeticExpressionGrammar(IEnumerable<Symbol> symbols) 51 : base(symbols) { 52 allSymbols = new List<Symbol>(symbols); 53 } 54 38 55 #region ISymbolicExpressionGrammar Members 39 56 [Storable] -
trunk/sources/HeuristicLab.Problems.DataAnalysis.Regression/3.3/Symbolic/SimpleArithmeticExpressionEvaluator.cs
r3257 r3269 53 53 if (node.Symbol is HeuristicLab.Problems.DataAnalysis.Regression.Symbolic.Symbols.Variable) { 54 54 var variableTreeNode = node as VariableTreeNode; 55 return dataset[row, 1 /*dataset.VariableIndex(variableTreeNode.VariableName)*/] * 1.0; //variableTreeNode.Weight;55 return dataset[row, dataset.VariableIndex(variableTreeNode.VariableName)] * variableTreeNode.Weight; 56 56 } else if (node.Symbol is Constant) { 57 57 return ((ConstantTreeNode)node).Value; -
trunk/sources/HeuristicLab.Problems.DataAnalysis.Regression/3.3/Symbolic/SymbolicRegressionProblem.cs
r3257 r3269 111 111 get { return EvaluatorParameter.Value; } 112 112 } 113 public ISymbolicExpressionGrammar FunctionTreeGrammar {114 get { return FunctionTreeGrammarParameter.Value; }113 public ArithmeticExpressionGrammar FunctionTreeGrammar { 114 get { return (ArithmeticExpressionGrammar)FunctionTreeGrammarParameter.Value; } 115 115 } 116 116 public ISingleObjectiveSolutionsVisualizer Visualizer { … … 147 147 creator.SymbolicExpressionTreeParameter.ActualName = "SymbolicRegressionModel"; 148 148 evaluator.QualityParameter.ActualName = "TrainingMeanSquaredError"; 149 InputVariablesParameter.ValueChanged += new EventHandler(InputVariablesParameter_ValueChanged); 149 150 ParameterizeSolutionCreator(); 150 151 ParameterizeEvaluator(); … … 152 153 153 154 Initialize(); 155 } 156 157 void InputVariablesParameter_ValueChanged(object sender, EventArgs e) { 158 FunctionTreeGrammar.VariableNames = InputVariablesParameter.Value.Select(x => x.Value); 154 159 } 155 160 -
trunk/sources/HeuristicLab.Problems.DataAnalysis.Regression/3.3/Symbolic/Symbols/Constant.cs
r3258 r3269 21 21 22 22 using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding; 23 using HeuristicLab.Core; 24 using HeuristicLab.Operators; 25 using HeuristicLab.Random; 26 using HeuristicLab.Data; 27 using HeuristicLab.Persistence.Default.CompositeSerializers.Storable; 28 using HeuristicLab.Parameters; 23 29 namespace HeuristicLab.Problems.DataAnalysis.Regression.Symbolic.Symbols { 30 [StorableClass] 31 [Item("Constant", "Represents a constant value.")] 24 32 public sealed class Constant : Symbol { 33 #region Parameter Properties 34 public IValueParameter<DoubleValue> MinValueParameter { 35 get { return (IValueParameter<DoubleValue>)Parameters["MinValue"]; } 36 } 37 public IValueParameter<DoubleValue> MaxValueParameter { 38 get { return (IValueParameter<DoubleValue>)Parameters["MaxValue"]; } 39 } 40 #endregion 41 #region Propeties 42 public DoubleValue MinValue { 43 get { return MinValueParameter.Value; } 44 set { MinValueParameter.Value = value; } 45 } 46 public DoubleValue MaxValue { 47 get { return MaxValueParameter.Value; } 48 set { MaxValueParameter.Value = value; } 49 } 50 #endregion 51 public Constant() 52 : base() { 53 Parameters.Add(new ValueParameter<DoubleValue>("MinValue", "The minimal value of the constant.", new DoubleValue(-20.0))); 54 Parameters.Add(new ValueParameter<DoubleValue>("MaxValue", "The maximal value of the constant.", new DoubleValue(20.0))); 55 } 56 25 57 public override SymbolicExpressionTreeNode CreateTreeNode() { 26 58 return new ConstantTreeNode(this); -
trunk/sources/HeuristicLab.Problems.DataAnalysis.Regression/3.3/Symbolic/Symbols/ConstantTreeNode.cs
r3258 r3269 24 24 using System.Collections.Generic; 25 25 using HeuristicLab.Persistence.Default.CompositeSerializers.Storable; 26 using HeuristicLab.Core; 27 using HeuristicLab.Data; 28 using HeuristicLab.Random; 26 29 namespace HeuristicLab.Problems.DataAnalysis.Regression.Symbolic.Symbols { 27 30 [StorableClass] 28 31 public sealed class ConstantTreeNode : SymbolicExpressionTreeTerminalNode { 32 public new Constant Symbol { 33 get { return (Constant)base.Symbol; } 34 } 29 35 public override bool HasLocalParameters { 30 36 get { … … 39 45 set { constantValue = value; } 40 46 } 41 42 47 // copy constructor 43 48 private ConstantTreeNode(ConstantTreeNode original) … … 48 53 public ConstantTreeNode(Constant constantSymbol) : base(constantSymbol) { } 49 54 55 public override void ResetLocalParameters(IRandom random) { 56 base.ResetLocalParameters(random); 57 var range = Symbol.MaxValue.Value - Symbol.MaxValue.Value; 58 Value = random.NextDouble() * range - Symbol.MinValue.Value; 59 } 60 50 61 public override object Clone() { 51 62 return new ConstantTreeNode(this); -
trunk/sources/HeuristicLab.Problems.DataAnalysis.Regression/3.3/Symbolic/Symbols/Variable.cs
r3258 r3269 21 21 22 22 using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding; 23 using HeuristicLab.Core; 24 using HeuristicLab.Operators; 25 using HeuristicLab.Random; 26 using HeuristicLab.Data; 27 using HeuristicLab.Persistence.Default.CompositeSerializers.Storable; 28 using HeuristicLab.Parameters; 23 29 namespace HeuristicLab.Problems.DataAnalysis.Regression.Symbolic.Symbols { 30 [StorableClass] 31 [Item("Variable", "Represents a variable value.")] 24 32 public sealed class Variable : Symbol { 33 #region Parameter Properties 34 public IValueParameter<DoubleValue> WeightNuParameter { 35 get { return (IValueParameter<DoubleValue>)Parameters["WeightNu"]; } 36 } 37 public IValueParameter<DoubleValue> WeightSigmaParameter { 38 get { return (IValueParameter<DoubleValue>)Parameters["WeightSigma"]; } 39 } 40 public IValueParameter<ItemList<StringValue>> VariableNamesParameter { 41 get { return (IValueParameter<ItemList<StringValue>>)Parameters["VariableNames"]; } 42 } 43 #endregion 44 #region Properties 45 public DoubleValue WeightNu { 46 get { return WeightNuParameter.Value; } 47 set { WeightNuParameter.Value = value; } 48 } 49 public DoubleValue WeightSigma { 50 get { return WeightSigmaParameter.Value; } 51 set { WeightSigmaParameter.Value = value; } 52 } 53 public ItemList<StringValue> VariableNames { 54 get { return VariableNamesParameter.Value; } 55 set { VariableNamesParameter.Value = value; } 56 } 57 #endregion 58 public Variable() 59 : base() { 60 Parameters.Add(new ValueParameter<DoubleValue>("WeightNu", "The mean value for the initialization of weight ((N(nu, sigma)).", new DoubleValue(1.0))); 61 Parameters.Add(new ValueParameter<DoubleValue>("WeightSigma", "The sigma value for the initialization of weight (N(nu, sigma))", new DoubleValue(1.0))); 62 Parameters.Add(new ValueParameter<ItemList<StringValue>>("VariableNames", "The list of possible variable names for initialization.")); 63 } 64 25 65 public override SymbolicExpressionTreeNode CreateTreeNode() { 26 66 return new VariableTreeNode(this); -
trunk/sources/HeuristicLab.Problems.DataAnalysis.Regression/3.3/Symbolic/Symbols/VariableTreeNode.cs
r3258 r3269 24 24 using System.Collections.Generic; 25 25 using HeuristicLab.Persistence.Default.CompositeSerializers.Storable; 26 using HeuristicLab.Core; 27 using HeuristicLab.Data; 28 using HeuristicLab.Random; 26 29 namespace HeuristicLab.Problems.DataAnalysis.Regression.Symbolic.Symbols { 27 30 [StorableClass] 28 31 public sealed class VariableTreeNode : SymbolicExpressionTreeTerminalNode { 29 32 public new Variable Symbol { 33 get { return (Variable)base.Symbol; } 34 } 30 35 private double weight; 31 36 [Storable] … … 50 55 public VariableTreeNode(Variable variableSymbol) : base(variableSymbol) { } 51 56 57 public override void ResetLocalParameters(IRandom random) { 58 base.ResetLocalParameters(random); 59 var normalDistributedRNG = new NormalDistributedRandom(random, Symbol.WeightNu.Value, Symbol.WeightSigma.Value); 60 weight = normalDistributedRNG.NextDouble(); 61 int variableIndex = random.Next(0, Symbol.VariableNames.Count); 62 variableName = Symbol.VariableNames[variableIndex].Value; 63 } 64 52 65 public override object Clone() { 53 66 return new VariableTreeNode(this); -
trunk/sources/HeuristicLab.Random/3.3/HeuristicLab.Random-3.3.csproj
r2900 r3269 93 93 <SubType>Code</SubType> 94 94 </Compile> 95 <Compile Include="NormalRandomizer.cs" /> 95 96 <Compile Include="Properties\AssemblyInfo.cs" /> 96 97 <Compile Include="RandomCreator.cs" /> 98 <Compile Include="UniformRandomizer.cs" /> 97 99 </ItemGroup> 98 100 <ItemGroup> -
trunk/sources/HeuristicLab.Random/3.3/NormalRandomizer.cs
r2524 r3269 1 1 #region License Information 2 2 /* HeuristicLab 3 * Copyright (C) 2002-20 08Heuristic and Evolutionary Algorithms Laboratory (HEAL)3 * Copyright (C) 2002-2010 Heuristic and Evolutionary Algorithms Laboratory (HEAL) 4 4 * 5 5 * This file is part of HeuristicLab. … … 26 26 using HeuristicLab.Data; 27 27 using HeuristicLab.Persistence.Default.CompositeSerializers.Storable; 28 using HeuristicLab.Operators; 29 using HeuristicLab.Parameters; 28 30 29 31 namespace HeuristicLab.Random { … … 31 33 /// Normally distributed random number generator. 32 34 /// </summary> 33 [EmptyStorableClass] 34 public class NormalRandomizer : OperatorBase { 35 private static int MAX_NUMBER_OF_TRIES = 100; 36 37 /// <inheritdoc select="summary"/> 38 public override string Description { 39 get { return "Initializes the value of variable 'Value' to a random value normally distributed with 'Mu' and 'Sigma'."; } 35 [StorableClass] 36 [Item("NormalRandomizer", "Initializes the value of variable 'Value' to a random value normally distributed with parameters 'Mu' and 'Sigma'")] 37 public class NormalRandomizer : SingleSuccessorOperator { 38 #region parameter properties 39 public ILookupParameter<IRandom> RandomParameter { 40 get { return (ILookupParameter<IRandom>)Parameters["Random"]; } 40 41 } 41 42 /// <summary> 43 /// Gets or sets the value for µ. 44 /// </summary> 45 /// <remarks>Gets or sets the variable with the name <c>Mu</c> through the method 46 /// <see cref="OperatorBase.GetVariable"/> of class <see cref="OperatorBase"/>.</remarks> 47 public double Mu { 48 get { return ((DoubleData)GetVariable("Mu").Value).Data; } 49 set { ((DoubleData)GetVariable("Mu").Value).Data = value; } 42 public IValueLookupParameter<DoubleValue> MuParameter { 43 get { return (IValueLookupParameter<DoubleValue>)Parameters["Mu"]; } 50 44 } 51 /// <summary> 52 /// Gets or sets the value for sigma. 53 /// </summary> 54 /// <remarks>Gets or sets the variable with the name <c>Sigma</c> through the method 55 /// <see cref="OperatorBase.GetVariable"/> of class <see cref="OperatorBase"/>.</remarks> 56 public double Sigma { 57 get { return ((DoubleData)GetVariable("Sigma").Value).Data; } 58 set { ((DoubleData)GetVariable("Sigma").Value).Data = value; } 45 public IValueLookupParameter<DoubleValue> SigmaParameter { 46 get { return (IValueLookupParameter<DoubleValue>)Parameters["Sigma"]; } 59 47 } 60 48 public ILookupParameter<DoubleValue> ValueParameter { 49 get { return (ILookupParameter<DoubleValue>)Parameters["Value"]; } 50 } 51 #endregion 52 #region Properties 53 public DoubleValue Mu { 54 get { return MuParameter.ActualValue; } 55 set { MuParameter.ActualValue = value; } 56 } 57 public DoubleValue Max { 58 get { return SigmaParameter.ActualValue; } 59 set { SigmaParameter.ActualValue = value; } 60 } 61 #endregion 61 62 /// <summary> 62 63 /// Initializes a new instance of <see cref="NormalRandomizer"/> with four variable infos … … 64 65 /// </summary> 65 66 public NormalRandomizer() { 66 AddVariableInfo(new VariableInfo("Mu", "Parameter mu of the normal distribution", typeof(DoubleData), VariableKind.None)); 67 GetVariableInfo("Mu").Local = true; 68 AddVariable(new Variable("Mu", new DoubleData(0.0))); 69 70 AddVariableInfo(new VariableInfo("Sigma", "Parameter sigma of the normal distribution", typeof(DoubleData), VariableKind.None)); 71 GetVariableInfo("Sigma").Local = true; 72 AddVariable(new Variable("Sigma", new DoubleData(1.0))); 73 74 AddVariableInfo(new VariableInfo("Value", "The value to manipulate (actual type is one of: IntData, DoubleData, ConstrainedIntData, ConstrainedDoubleData)", typeof(IObjectData), VariableKind.In)); 75 AddVariableInfo(new VariableInfo("Random", "The random generator to use", typeof(MersenneTwister), VariableKind.In)); 67 Parameters.Add(new LookupParameter<IRandom>("Random", "A random generator that supplies uniformly distributed values.")); 68 Parameters.Add(new ValueLookupParameter<DoubleValue>("Mu", "Mu parameter of the normal distribution (N(mu,sigma)).")); 69 Parameters.Add(new ValueLookupParameter<DoubleValue>("Sigma", "Sigma parameter of the normal distribution (N(mu,sigma)).")); 70 Parameters.Add(new LookupParameter<DoubleValue>("Value", "The value that should be set to a random value.")); 76 71 } 77 72 78 73 /// <summary> 79 /// Generates a new normally distributed random variable and assigns it to the specified variable 80 /// in the given <paramref name="scope"/>. 74 /// Generates a new normally distributed random variable and assigns it to the specified variable. 81 75 /// </summary> 82 /// <param name="scope">The scope where to assign the new random value to.</param> 83 /// <returns><c>null</c>.</returns> 84 public override IOperation Apply(IScope scope) { 85 IObjectData value = GetVariableValue<IObjectData>("Value", scope, false); 86 MersenneTwister mt = GetVariableValue<MersenneTwister>("Random", scope, true); 87 double mu = GetVariableValue<DoubleData>("Mu", scope, true).Data; 88 double sigma = GetVariableValue<DoubleData>("Sigma", scope, true).Data; 76 public override IOperation Apply() { 77 IRandom random = RandomParameter.ActualValue; 78 double mu = MuParameter.ActualValue.Value; 79 double sigma = SigmaParameter.ActualValue.Value; 89 80 90 NormalDistributedRandom n = new NormalDistributedRandom(mt, mu, sigma);91 RandomizeNormal(value, n);81 NormalDistributedRandom normalRandom = new NormalDistributedRandom(random, mu, sigma); 82 ValueParameter.ActualValue = new DoubleValue(normalRandom.NextDouble()); 92 83 return null; 93 }94 95 private void RandomizeNormal(IObjectData value, NormalDistributedRandom n) {96 // dispatch manually based on dynamic type97 if (value is IntData)98 RandomizeNormal((IntData)value, n);99 else if (value is DoubleData)100 RandomizeNormal((DoubleData)value, n);101 else throw new InvalidOperationException("Can't handle type " + value.GetType().Name);102 }103 104 /// <summary>105 /// Generates a new double random number based on a continuous, normally distributed random number106 /// generator <paramref name="normal"/>.107 /// </summary>108 /// <param name="data">The double object where to assign the new value to.</param>109 /// <param name="normal">The continuous, normally distributed random variable.</param>110 public void RandomizeNormal(DoubleData data, NormalDistributedRandom normal) {111 data.Data = normal.NextDouble();112 }113 114 /// <summary>115 /// Generates a new int random number based on a continuous, normally distributed random number116 /// generator <paramref name="normal"/>.117 /// </summary>118 /// <param name="data">The int object where to assign the new value to.</param>119 /// <param name="normal">The continuous, normally distributed random variable.</param>120 public void RandomizeNormal(IntData data, NormalDistributedRandom normal) {121 data.Data = (int)Math.Round(normal.NextDouble());122 84 } 123 85 } -
trunk/sources/HeuristicLab.Random/3.3/UniformRandomizer.cs
r2524 r3269 1 1 #region License Information 2 2 /* HeuristicLab 3 * Copyright (C) 2002-20 08Heuristic and Evolutionary Algorithms Laboratory (HEAL)3 * Copyright (C) 2002-2010 Heuristic and Evolutionary Algorithms Laboratory (HEAL) 4 4 * 5 5 * This file is part of HeuristicLab. … … 26 26 using HeuristicLab.Data; 27 27 using HeuristicLab.Persistence.Default.CompositeSerializers.Storable; 28 using HeuristicLab.Operators; 29 using HeuristicLab.Parameters; 28 30 29 31 namespace HeuristicLab.Random { … … 31 33 /// Uniformly distributed random number generator. 32 34 /// </summary> 33 [ EmptyStorableClass]34 public class UniformRandomizer : OperatorBase {35 private static int MAX_NUMBER_OF_TRIES = 100;36 /// <inheritdoc select="summary"/>37 public override string Description{38 get { return "Initializes the value of variable 'Value' to a random value uniformly distributed between 'Min' and 'Max' (exclusive)"; }35 [StorableClass] 36 [Item("UniformRandomizer", "Initializes the value of variable 'Value' to a random value uniformly distributed between 'Min' and 'Max'")] 37 public class UniformRandomizer : SingleSuccessorOperator { 38 #region parameter properties 39 public ILookupParameter<IRandom> RandomParameter { 40 get { return (ILookupParameter<IRandom>)Parameters["Random"]; } 39 41 } 40 41 /// <summary> 42 /// Gets or sets the maximum value of the random number generator (exclusive). 43 /// </summary> 44 /// <remarks>Gets or sets the variable with name <c>Max</c> through the 45 /// <see cref="OperatorBase.GetVariable"/> method of class <see cref="OperatorBase"/>.</remarks> 46 public double Max { 47 get { return ((DoubleData)GetVariable("Max").Value).Data; } 48 set { ((DoubleData)GetVariable("Max").Value).Data = value; } 42 public IValueLookupParameter<DoubleValue> MinParameter { 43 get { return (IValueLookupParameter<DoubleValue>)Parameters["Min"]; } 49 44 } 50 /// <summary> 51 /// Gets or sets the minimum value of the random number generator. 52 /// </summary> 53 /// <remarks>Gets or sets the variable with name <c>Min</c> through the 54 /// <see cref="OperatorBase.GetVariable"/> method of class <see cref="OperatorBase"/>.</remarks> 55 public double Min { 56 get { return ((DoubleData)GetVariable("Min").Value).Data; } 57 set { ((DoubleData)GetVariable("Min").Value).Data = value; } 45 public IValueLookupParameter<DoubleValue> MaxParameter { 46 get { return (IValueLookupParameter<DoubleValue>)Parameters["Max"]; } 58 47 } 48 public ILookupParameter<DoubleValue> ValueParameter { 49 get { return (ILookupParameter<DoubleValue>)Parameters["Value"]; } 50 } 51 #endregion 52 #region Properties 53 public DoubleValue Min { 54 get { return MinParameter.ActualValue; } 55 set { MinParameter.ActualValue = value; } 56 } 57 public DoubleValue Max { 58 get { return MaxParameter.ActualValue; } 59 set { MaxParameter.ActualValue = value; } 60 } 61 #endregion 59 62 60 63 /// <summary> … … 63 66 /// between 0.0 and 1.0. 64 67 /// </summary> 65 public UniformRandomizer() { 66 AddVariableInfo(new VariableInfo("Value", "The value to manipulate (type is one of: IntData, ConstrainedIntData, DoubleData, ConstrainedDoubleData)", typeof(IObjectData), VariableKind.In)); 67 AddVariableInfo(new VariableInfo("Random", "The random generator to use", typeof(MersenneTwister), VariableKind.In)); 68 AddVariableInfo(new VariableInfo("Min", "Lower bound of the uniform distribution (inclusive)", typeof(DoubleData), VariableKind.None)); 69 GetVariableInfo("Min").Local = true; 70 AddVariable(new Variable("Min", new DoubleData(0.0))); 71 72 AddVariableInfo(new VariableInfo("Max", "Upper bound of the uniform distribution (exclusive)", typeof(DoubleData), VariableKind.None)); 73 GetVariableInfo("Max").Local = true; 74 AddVariable(new Variable("Max", new DoubleData(1.0))); 68 public UniformRandomizer() 69 : base() { 70 Parameters.Add(new LookupParameter<IRandom>("Random", "A random generator that supplies uniformly distributed values.")); 71 Parameters.Add(new ValueLookupParameter<DoubleValue>("Min", "The minimal allowed value (inclusive)")); 72 Parameters.Add(new ValueLookupParameter<DoubleValue>("Max", "The maximal allowed value (exclusive)")); 73 Parameters.Add(new LookupParameter<DoubleValue>("Value", "The value that should be set to a random value.")); 75 74 } 76 75 … … 78 77 /// Generates a new uniformly distributed random variable. 79 78 /// </summary> 80 /// <param name="scope">The scope where to apply the random number generator.</param> 81 /// <returns><c>null</c>.</returns> 82 public override IOperation Apply(IScope scope) { 83 IObjectData value = GetVariableValue<IObjectData>("Value", scope, false); 84 MersenneTwister mt = GetVariableValue<MersenneTwister>("Random", scope, true); 85 double min = GetVariableValue<DoubleData>("Min", scope, true).Data; 86 double max = GetVariableValue<DoubleData>("Max", scope, true).Data; 79 public override IOperation Apply() { 80 IRandom random = RandomParameter.ActualValue; 81 double min = MinParameter.ActualValue.Value; 82 double max = MaxParameter.ActualValue.Value; 87 83 88 RandomizeUniform(value, mt, min, max);84 ValueParameter.ActualValue = new DoubleValue(random.NextDouble() * (max - min) + min); 89 85 return null; 90 86 } 91 92 /// <summary> 93 /// Generates a new random number depending on the type of the <paramref name="value"/>. 94 /// </summary> 95 /// <exception cref="ArgumentException">Thrown when an unhandleable type appears.</exception> 96 /// <param name="value">The object whose data should be a new randomly generated number.</param> 97 /// <param name="mt">The MersenneTwister to generate a new random number.</param> 98 /// <param name="min">The left border of the interval in which the next random number has to lie.</param> 99 /// <param name="max">The right border (exclusive) of the interval in which the next random number 100 /// has to lie.</param> 101 private void RandomizeUniform(IObjectData value, MersenneTwister mt, double min, double max) { 102 // Dispatch manually based on dynamic type, 103 // a bit awkward but necessary until we create a better type hierarchy for numeric types (gkronber 15.11.2008). 104 if (value is DoubleData) 105 RandomizeUniform((DoubleData)value, mt, min, max); 106 else if (value is IntData) 107 RandomizeUniform((IntData)value, mt, min, max); 108 else throw new ArgumentException("Can't handle type " + value.GetType().Name); 109 } 110 111 /// <summary> 112 /// Generates a new double random number. 113 /// </summary> 114 /// <param name="data">The double object which the new value is assigned to.</param> 115 /// <param name="mt">The random number generator.</param> 116 /// <param name="min">The left border of the interval in which the next random number has to lie.</param> 117 /// <param name="max">The right border (exclusive) of the interval in which the next random number 118 /// has to lie.</param> 119 public void RandomizeUniform(DoubleData data, MersenneTwister mt, double min, double max) { 120 data.Data = mt.NextDouble() * (max - min) + min; 121 } 122 123 /// <summary> 124 /// Generates a new int random number. 125 /// </summary> 126 /// <param name="data">The int object which the new value is assigned to.</param> 127 /// <param name="mt">The random number generator.</param> 128 /// <param name="min">The left border of the interval in which the next random number has to lie.</param> 129 /// <param name="max">The right border (exclusive) of the interval in which the next random number 130 /// has to lie.</param> 131 public void RandomizeUniform(IntData data, MersenneTwister mt, double min, double max) { 132 data.Data = (int)Math.Floor(mt.NextDouble() * (max - min) + min); 133 } 134 } 87 } 135 88 }
Note: See TracChangeset
for help on using the changeset viewer.