1 | using System;
|
---|
2 | using System.Collections.Generic;
|
---|
3 | using System.Linq;
|
---|
4 | using System.Text;
|
---|
5 | using HeuristicLab.Core;
|
---|
6 | using HeuristicLab.Data;
|
---|
7 |
|
---|
8 | namespace 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 | }
|
---|