1 | using System;
|
---|
2 | using System.Collections.Generic;
|
---|
3 | using System.Diagnostics;
|
---|
4 |
|
---|
5 | namespace HeuristicLab.Algorithms.DataAnalysis.ContinuedFractionRegression {
|
---|
6 | public class Agent {
|
---|
7 | public ContinuedFraction pocket;
|
---|
8 | public double pocketObjValue;
|
---|
9 | public ContinuedFraction current;
|
---|
10 | public double currentObjValue;
|
---|
11 | public IList<Agent> children = new List<Agent>();
|
---|
12 |
|
---|
13 | public void MaintainPocketCurrentInvariant() {
|
---|
14 | if (currentObjValue < pocketObjValue) {
|
---|
15 | Swap(ref pocket, ref current);
|
---|
16 | Swap(ref pocketObjValue, ref currentObjValue);
|
---|
17 | }
|
---|
18 | }
|
---|
19 |
|
---|
20 | public void MaintainInvariant() {
|
---|
21 | foreach (var child in children) {
|
---|
22 | MaintainParentChildInvariant(parent: this, child);
|
---|
23 | }
|
---|
24 | MaintainPocketCurrentInvariant();
|
---|
25 | }
|
---|
26 |
|
---|
27 |
|
---|
28 | private static void MaintainParentChildInvariant(Agent parent, Agent child) {
|
---|
29 | if (child.pocketObjValue < parent.pocketObjValue) {
|
---|
30 | Swap(ref child.pocket, ref parent.pocket);
|
---|
31 | Swap(ref child.pocketObjValue, ref parent.pocketObjValue);
|
---|
32 | }
|
---|
33 | }
|
---|
34 |
|
---|
35 | public IEnumerable<Agent> IterateLevels() {
|
---|
36 | var agents = new List<Agent>() { this };
|
---|
37 | int i = 0;
|
---|
38 | while (i < agents.Count) {
|
---|
39 | var p = agents[i];
|
---|
40 | foreach (var child in p.children)
|
---|
41 | agents.Add(child);
|
---|
42 | i++;
|
---|
43 | }
|
---|
44 | return agents;
|
---|
45 | }
|
---|
46 | public IEnumerable<Agent> IteratePostOrder() {
|
---|
47 | var agents = new List<Agent>();
|
---|
48 | IteratePostOrderRec(this, agents);
|
---|
49 | return agents;
|
---|
50 | }
|
---|
51 | public IEnumerable<Agent> IteratePreOrder() {
|
---|
52 | var agents = new List<Agent>();
|
---|
53 | IteratePreOrderRec(this, agents);
|
---|
54 | return agents;
|
---|
55 | }
|
---|
56 |
|
---|
57 | private void IteratePostOrderRec(Agent agent, List<Agent> agents) {
|
---|
58 | foreach (var child in agent.children) {
|
---|
59 | IteratePostOrderRec(child, agents);
|
---|
60 | }
|
---|
61 | agents.Add(agent);
|
---|
62 | }
|
---|
63 |
|
---|
64 | private void IteratePreOrderRec(Agent agent, List<Agent> agents) {
|
---|
65 | agents.Add(agent);
|
---|
66 | foreach (var child in agent.children) {
|
---|
67 | IteratePreOrderRec(child, agents);
|
---|
68 | }
|
---|
69 | }
|
---|
70 |
|
---|
71 |
|
---|
72 | private static void Swap<T>(ref T a, ref T b) {
|
---|
73 | var temp = a;
|
---|
74 | a = b;
|
---|
75 | b = temp;
|
---|
76 | }
|
---|
77 |
|
---|
78 | internal void AssertInvariant() {
|
---|
79 | Debug.Assert(pocketObjValue <= currentObjValue);
|
---|
80 | foreach (var ch in children) {
|
---|
81 | Debug.Assert(pocketObjValue <= ch.pocketObjValue);
|
---|
82 | }
|
---|
83 | }
|
---|
84 | }
|
---|
85 | }
|
---|