Free cookie consent management tool by TermsFeed Policy Generator

source: branches/3.1/sources/HeuristicLab.SimOpt/RandomDoubleInitializer.cs @ 583

Last change on this file since 583 was 583, checked in by abeham, 16 years ago

Adding communication framework to branch 3.1 (ticket #278)

File size: 1.8 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Text;
5using HeuristicLab.Core;
6using HeuristicLab.Data;
7
8namespace HeuristicLab.SimOpt {
9  public class RandomDoubleInitializer : SimOptInitializationOperatorBase {
10    public override string Description {
11      get { return @"Initializes a DoubleData or ConstrainedDoubleData randomly in a given interval"; }
12    }
13
14    public RandomDoubleInitializer()
15      : base() {
16      AddVariableInfo(new VariableInfo("Min", "Minimum of the desired value", typeof(DoubleData), VariableKind.In));
17      AddVariableInfo(new VariableInfo("Max", "Maximum of the desired value", typeof(DoubleData), VariableKind.In));
18    }
19
20    protected override void Apply(IScope scope, IRandom random, IItem item) {
21      double min = GetVariableValue<DoubleData>("Min", scope, true).Data;
22      double max = GetVariableValue<DoubleData>("Max", scope, true).Data;
23      if (item is DoubleData) {
24        double r = random.NextDouble();
25        ((DoubleData)item).Data = min + (r * max - r * min);
26        return;
27      } else if (item is ConstrainedDoubleData) {
28        ConstrainedDoubleData data = (item as ConstrainedDoubleData);
29        for (int tries = 100; tries >= 0; tries--) {
30          double r = random.NextDouble();
31          double newValue = min + (r * max - r * min);
32
33          if (IsIntegerConstrained(data)) newValue = Math.Round(newValue);
34          if (data.TrySetData(newValue)) return;
35        }
36        throw new InvalidProgramException("ERROR: RandomDoubleInitializer couldn't find a valid value in 100 tries");
37      } else throw new InvalidOperationException("ERROR: RandomDoubleInitializer does not know how to work with " + ((item != null) ? (item.GetType().ToString()) : ("null")) + " data");
38    }
39  }
40}
Note: See TracBrowser for help on using the repository browser.