Free cookie consent management tool by TermsFeed Policy Generator

Changeset 3269


Ignore:
Timestamp:
04/05/10 18:52:23 (14 years ago)
Author:
gkronber
Message:

Implemented initialization of Variable and Constant terminal nodes. #938 (Data types and operators for regression problems)

Location:
trunk/sources
Files:
14 edited

Legend:

Unmodified
Added
Removed
  • trunk/sources/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.3/Symbol.cs

    r3223 r3269  
    2626using System.Linq;
    2727using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
     28using HeuristicLab.Data;
     29using HeuristicLab.Parameters;
    2830
    2931namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
    3032  [StorableClass]
    3133  [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
    4140
    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; }
    4544      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;
    5047      }
    5148    }
     49    #endregion
    5250
    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)));
    14254    }
    14355
     
    14557      return new SymbolicExpressionTreeNode(this);
    14658    }
    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 recursion       
    184         minTreeSize = 1 + (from slot in Enumerable.Range(0, MinSubTrees)
    185                            let minForSlot = (from function in GetAllowedSubFunctions(slot)
    186                                              where function != this
    187                                              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 != this
    199                                                select function.MinTreeHeight).DefaultIfEmpty(0).Min()
    200                              select minForSlot).Max();
    201       }
    202     }
    203 
    204     public override string ToString() {
    205       return name;
    206     }
    20759  }
    20860}
  • trunk/sources/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.3/SymbolicExpressionTreeCreator.cs

    r3239 r3269  
    2020#endregion
    2121
     22using System.Linq;
    2223using HeuristicLab.Core;
    2324using HeuristicLab.Data;
     
    7273      SymbolicExpressionTreeParameter.ActualValue = Create(RandomParameter.ActualValue, SymbolicExpressionGrammarParameter.ActualValue,
    7374        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;
    7580    }
    7681
  • trunk/sources/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.3/SymbolicExpressionTreeNode.cs

    r3252 r3269  
    7676      return maxHeight + 1;
    7777    }
    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) { }
    8681
    8782    protected internal virtual void AddSubTree(SymbolicExpressionTreeNode tree) {
  • trunk/sources/HeuristicLab.Problems.ArtificialAnt/3.3/Symbols/Prog3.cs

    r3223 r3269  
    2323namespace HeuristicLab.Problems.ArtificialAnt {
    2424  public sealed class Prog3 : Symbol {
    25 
    2625    public Prog3()
    2726      : base() {
    28       MinSubTrees = 3; MaxSubTrees = 3;
    2927    }
    3028  }
  • trunk/sources/HeuristicLab.Problems.DataAnalysis.Regression/3.3/Symbolic/ArithmeticExpressionGrammar.cs

    r3257 r3269  
    2929using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.GeneralSymbols;
    3030using HeuristicLab.Problems.DataAnalysis.Regression.Symbolic.Symbols;
     31using HeuristicLab.Data;
    3132namespace HeuristicLab.Problems.DataAnalysis.Regression.Symbolic {
    3233  [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    }
    3445
    3546    public ArithmeticExpressionGrammar()
    36       : base() {
     47      : this(allSymbols) {
    3748    }
     49
     50    public ArithmeticExpressionGrammar(IEnumerable<Symbol> symbols)
     51      : base(symbols) {
     52      allSymbols = new List<Symbol>(symbols);
     53    }
     54
    3855    #region ISymbolicExpressionGrammar Members
    3956    [Storable]
  • trunk/sources/HeuristicLab.Problems.DataAnalysis.Regression/3.3/Symbolic/SimpleArithmeticExpressionEvaluator.cs

    r3257 r3269  
    5353      if (node.Symbol is HeuristicLab.Problems.DataAnalysis.Regression.Symbolic.Symbols.Variable) {
    5454        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;
    5656      } else if (node.Symbol is Constant) {
    5757        return ((ConstantTreeNode)node).Value;
  • trunk/sources/HeuristicLab.Problems.DataAnalysis.Regression/3.3/Symbolic/SymbolicRegressionProblem.cs

    r3257 r3269  
    111111      get { return EvaluatorParameter.Value; }
    112112    }
    113     public ISymbolicExpressionGrammar FunctionTreeGrammar {
    114       get { return FunctionTreeGrammarParameter.Value; }
     113    public ArithmeticExpressionGrammar FunctionTreeGrammar {
     114      get { return (ArithmeticExpressionGrammar)FunctionTreeGrammarParameter.Value; }
    115115    }
    116116    public ISingleObjectiveSolutionsVisualizer Visualizer {
     
    147147      creator.SymbolicExpressionTreeParameter.ActualName = "SymbolicRegressionModel";
    148148      evaluator.QualityParameter.ActualName = "TrainingMeanSquaredError";
     149      InputVariablesParameter.ValueChanged += new EventHandler(InputVariablesParameter_ValueChanged);
    149150      ParameterizeSolutionCreator();
    150151      ParameterizeEvaluator();
     
    152153
    153154      Initialize();
     155    }
     156
     157    void InputVariablesParameter_ValueChanged(object sender, EventArgs e) {
     158      FunctionTreeGrammar.VariableNames = InputVariablesParameter.Value.Select(x => x.Value);
    154159    }
    155160
  • trunk/sources/HeuristicLab.Problems.DataAnalysis.Regression/3.3/Symbolic/Symbols/Constant.cs

    r3258 r3269  
    2121
    2222using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
     23using HeuristicLab.Core;
     24using HeuristicLab.Operators;
     25using HeuristicLab.Random;
     26using HeuristicLab.Data;
     27using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
     28using HeuristicLab.Parameters;
    2329namespace HeuristicLab.Problems.DataAnalysis.Regression.Symbolic.Symbols {
     30  [StorableClass]
     31  [Item("Constant", "Represents a constant value.")]
    2432  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
    2557    public override SymbolicExpressionTreeNode CreateTreeNode() {
    2658      return new ConstantTreeNode(this);
  • trunk/sources/HeuristicLab.Problems.DataAnalysis.Regression/3.3/Symbolic/Symbols/ConstantTreeNode.cs

    r3258 r3269  
    2424using System.Collections.Generic;
    2525using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
     26using HeuristicLab.Core;
     27using HeuristicLab.Data;
     28using HeuristicLab.Random;
    2629namespace HeuristicLab.Problems.DataAnalysis.Regression.Symbolic.Symbols {
    2730  [StorableClass]
    2831  public sealed class ConstantTreeNode : SymbolicExpressionTreeTerminalNode {
     32    public new Constant Symbol {
     33      get { return (Constant)base.Symbol; }
     34    }
    2935    public override bool HasLocalParameters {
    3036      get {
     
    3945      set { constantValue = value; }
    4046    }
    41 
    4247    // copy constructor
    4348    private ConstantTreeNode(ConstantTreeNode original)
     
    4853    public ConstantTreeNode(Constant constantSymbol) : base(constantSymbol) { }
    4954
     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
    5061    public override object Clone() {
    5162      return new ConstantTreeNode(this);
  • trunk/sources/HeuristicLab.Problems.DataAnalysis.Regression/3.3/Symbolic/Symbols/Variable.cs

    r3258 r3269  
    2121
    2222using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
     23using HeuristicLab.Core;
     24using HeuristicLab.Operators;
     25using HeuristicLab.Random;
     26using HeuristicLab.Data;
     27using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
     28using HeuristicLab.Parameters;
    2329namespace HeuristicLab.Problems.DataAnalysis.Regression.Symbolic.Symbols {
     30  [StorableClass]
     31  [Item("Variable", "Represents a variable value.")]
    2432  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
    2565    public override SymbolicExpressionTreeNode CreateTreeNode() {
    2666      return new VariableTreeNode(this);
  • trunk/sources/HeuristicLab.Problems.DataAnalysis.Regression/3.3/Symbolic/Symbols/VariableTreeNode.cs

    r3258 r3269  
    2424using System.Collections.Generic;
    2525using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
     26using HeuristicLab.Core;
     27using HeuristicLab.Data;
     28using HeuristicLab.Random;
    2629namespace HeuristicLab.Problems.DataAnalysis.Regression.Symbolic.Symbols {
    2730  [StorableClass]
    2831  public sealed class VariableTreeNode : SymbolicExpressionTreeTerminalNode {
    29    
     32    public new Variable Symbol {
     33      get { return (Variable)base.Symbol; }
     34    }
    3035    private double weight;
    3136    [Storable]
     
    5055    public VariableTreeNode(Variable variableSymbol) : base(variableSymbol) { }
    5156
     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
    5265    public override object Clone() {
    5366      return new VariableTreeNode(this);
  • trunk/sources/HeuristicLab.Random/3.3/HeuristicLab.Random-3.3.csproj

    r2900 r3269  
    9393      <SubType>Code</SubType>
    9494    </Compile>
     95    <Compile Include="NormalRandomizer.cs" />
    9596    <Compile Include="Properties\AssemblyInfo.cs" />
    9697    <Compile Include="RandomCreator.cs" />
     98    <Compile Include="UniformRandomizer.cs" />
    9799  </ItemGroup>
    98100  <ItemGroup>
  • trunk/sources/HeuristicLab.Random/3.3/NormalRandomizer.cs

    r2524 r3269  
    11#region License Information
    22/* HeuristicLab
    3  * Copyright (C) 2002-2008 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
     3 * Copyright (C) 2002-2010 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
    44 *
    55 * This file is part of HeuristicLab.
     
    2626using HeuristicLab.Data;
    2727using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
     28using HeuristicLab.Operators;
     29using HeuristicLab.Parameters;
    2830
    2931namespace HeuristicLab.Random {
     
    3133  /// Normally distributed random number generator.
    3234  /// </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"]; }
    4041    }
    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"]; }
    5044    }
    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"]; }
    5947    }
    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
    6162    /// <summary>
    6263    /// Initializes a new instance of <see cref="NormalRandomizer"/> with four variable infos
     
    6465    /// </summary>
    6566    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."));
    7671    }
    7772
    7873    /// <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.
    8175    /// </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;
    8980
    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());
    9283      return null;
    93     }
    94 
    95     private void RandomizeNormal(IObjectData value, NormalDistributedRandom n) {
    96       // dispatch manually based on dynamic type
    97       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 number
    106     /// 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 number
    116     /// 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());
    12284    }
    12385  }
  • trunk/sources/HeuristicLab.Random/3.3/UniformRandomizer.cs

    r2524 r3269  
    11#region License Information
    22/* HeuristicLab
    3  * Copyright (C) 2002-2008 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
     3 * Copyright (C) 2002-2010 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
    44 *
    55 * This file is part of HeuristicLab.
     
    2626using HeuristicLab.Data;
    2727using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
     28using HeuristicLab.Operators;
     29using HeuristicLab.Parameters;
    2830
    2931namespace HeuristicLab.Random {
     
    3133  /// Uniformly distributed random number generator.
    3234  /// </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"]; }
    3941    }
    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"]; }
    4944    }
    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"]; }
    5847    }
     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
    5962
    6063    /// <summary>
     
    6366    /// between 0.0 and 1.0.
    6467    /// </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."));
    7574    }
    7675
     
    7877    /// Generates a new uniformly distributed random variable.
    7978    /// </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;
    8783
    88       RandomizeUniform(value, mt, min, max);
     84      ValueParameter.ActualValue = new DoubleValue(random.NextDouble() * (max - min) + min);
    8985      return null;
    9086    }
    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  }
    13588}
Note: See TracChangeset for help on using the changeset viewer.