Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 91a3be1

Browse files
Changed how function options are specified to use a custom class for more flexibility.
Added Function.cs and FunctionInst.cs. Added ReadInputAtMemoryStart as an option for individual functions.
1 parent f3b4426 commit 91a3be1

File tree

8 files changed

+296
-19
lines changed

8 files changed

+296
-19
lines changed

‎AIProgrammer.Fitness/AIProgrammer.Fitness.csproj‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@
5454
<Compile Include="Concrete\LogicalAndFitness.cs" />
5555
<Compile Include="Concrete\CsvSplitFitness.cs" />
5656
<Compile Include="Concrete\GuidingFunctionFitness.cs" />
57+
<Compile Include="Concrete\Research\TrimLeftOfQuoteFitness.cs" />
5758
<Compile Include="Concrete\Research\ExtractInQuotesExtraFitness.cs" />
5859
<Compile Include="Concrete\XmlToJsonFitness.cs" />
5960
<Compile Include="Concrete\WarningCountdownFitness.cs" />

‎AIProgrammer.Fitness/Concrete/FindQuoteFitness.cs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ protected override double GetFitnessMethod(string program)
119119

120120
result = b;
121121
_console.Append(b);
122-
}, null, new InterpreterOptions() { FunctionMaxIterationCounts=new int[]{ 100 } });
122+
}, null, new Function[] { new Function(){MaxIterationCount= 100 } });
123123
_bf.Run(_maxIterationCount);
124124
}
125125
catch
@@ -197,7 +197,7 @@ protected override void RunProgramMethod(string program)
197197
(b) =>
198198
{
199199
Console.Write(b + " ");
200-
}, null, new InterpreterOptions() { FunctionMaxIterationCounts=new int[]{ 100 } });
200+
}, null, new Function[] { new Function(){MaxIterationCount= 100 } });
201201

202202
bf.Run(_maxIterationCount);
203203
}

‎AIProgrammer.Fitness/Concrete/Research/ExtractInQuotesExtraFitness.cs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,7 @@ protected override double GetFitnessMethod(string program)
131131
countBonus += (_bf.m_CurrentInstructionPointer + 1 < program.Length) && program[_bf.m_CurrentInstructionPointer + 1] == '!' ? 50 : 0;
132132
aBonus++;
133133
}
134-
}, new InterpreterOptions() { FunctionMaxIterationCounts=new int[]{ 100 } });
134+
}, new Function[] { new Function(){MaxIterationCount= 100 } });
135135
_bf.Run(_maxIterationCount);
136136

137137
// Give a bonus for using multiple memory registers, supporting diversity.
@@ -211,7 +211,7 @@ protected override void RunProgramMethod(string program)
211211
(b) =>
212212
{
213213
_console.Append((char)b);
214-
}, null, new InterpreterOptions() { FunctionMaxIterationCounts=new int[]{ 100 } });
214+
}, null, new Function[] { new Function(){MaxIterationCount= 100 } });
215215

216216
bf.Run(_maxIterationCount);
217217
}
Lines changed: 233 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,233 @@
1+
using AIProgrammer.Fitness.Base;
2+
using AIProgrammer.GeneticAlgorithm;
3+
using AIProgrammer.Managers;
4+
using AIProgrammer.Types;
5+
using Newtonsoft.Json;
6+
using System;
7+
using System.Collections.Generic;
8+
using System.Linq;
9+
using System.Text;
10+
using System.Text.RegularExpressions;
11+
using System.Threading.Tasks;
12+
using System.Xml;
13+
14+
namespace AIProgrammer.Fitness.Concrete
15+
{
16+
/// <summary>
17+
/// Removes text to the left of the first quote. Example: one "two" three => "two" three
18+
/// </summary>
19+
public class TrimLeftOfQuoteFitness : FitnessBase
20+
{
21+
private static string[] _trainingExamples = { "dot \"inside\" over", "million \"test\" rights", "final \"foresting\" service" };
22+
private static string[] _trainingResults = new string[] { "\"inside\" over", "\"test\" rights", "\"foresting\" service" };
23+
24+
#region Settings
25+
26+
/// <summary>
27+
/// Previously generated BrainPlus code for FindQuoteFitness.
28+
/// The first function returns 0 (to storage) if the current memory value is a quote and a positive value otherwise.
29+
/// The second function removes the first and last character from a string.
30+
/// Note, the function was not actually used in the solution.
31+
/// Another potential useful function: removing first and last character from a string (starts at memory location 0): +>!+!>++>,>$[...+.!,.<>..<],ドル>$-,[<.>>,]@
32+
/// </summary>
33+
public override string AppendCode
34+
{
35+
get
36+
{
37+
return "A!,+*+>+*+<[[---$*]]>-,[-@-+,>,<,[,ドル>+-.!<]<][!+[<[[+$+[[+<[[>$+[[-+,ドル->!>>$<$[+-,>6,$.-><-[!-[$>,+,,[,!+>!,,[$![!5@";
38+
}
39+
}
40+
41+
public override int? GenomeSize
42+
{
43+
get
44+
{
45+
return 15;
46+
}
47+
}
48+
49+
public override int? MaxGenomeSize
50+
{
51+
get
52+
{
53+
return 100;
54+
}
55+
}
56+
57+
public override int? ExpandAmount
58+
{
59+
get
60+
{
61+
return 2;
62+
}
63+
}
64+
65+
public override int? ExpandRate
66+
{
67+
get
68+
{
69+
return 5000;
70+
}
71+
}
72+
73+
#endregion
74+
75+
public TrimLeftOfQuoteFitness(GA ga, int maxIterationCount, string appendFunctions = null)
76+
: base(ga, maxIterationCount, appendFunctions)
77+
{
78+
if (_targetFitness == 0)
79+
{
80+
for (int i = 0; i < _trainingExamples.Length; i++)
81+
{
82+
_targetFitness += _trainingResults[i].Length * 256;
83+
_targetFitness += 10; // length fitness
84+
}
85+
}
86+
}
87+
88+
#region FitnessBase Members
89+
90+
protected override double GetFitnessMethod(string program)
91+
{
92+
double countBonus = 0;
93+
double penalty = 0;
94+
95+
for (int i = 0; i < _trainingExamples.Length; i++)
96+
{
97+
try
98+
{
99+
int state = 0;
100+
HashSet<int> memoryHash = new HashSet<int>();
101+
int aBonus = 0;
102+
103+
_console.Clear();
104+
105+
// Run the program.
106+
_bf = new Interpreter(program, () =>
107+
{
108+
if (state < _trainingExamples[i].Length)
109+
{
110+
// Store data in different memory positions, so that function can access the data.
111+
memoryHash.Add(_bf.m_CurrentDataPointer);
112+
113+
// Send input.
114+
return (byte)_trainingExamples[i][state++];
115+
}
116+
else
117+
{
118+
// Not ready for input.
119+
return 0;
120+
}
121+
},
122+
(b) =>
123+
{
124+
_console.Append((char)b);
125+
},
126+
(function) =>
127+
{
128+
if (function == 'a' && aBonus < 2 && _bf.IsInsideLoop)
129+
{
130+
countBonus += 50;
131+
countBonus += (_bf.m_CurrentInstructionPointer + 1 < program.Length) && program[_bf.m_CurrentInstructionPointer + 1] == '!' ? 50 : 0;
132+
aBonus++;
133+
}
134+
}, new Function[] { new Function() { MaxIterationCount = 100 } });
135+
_bf.Run(_maxIterationCount);
136+
137+
// Give a bonus for using multiple memory registers, supporting diversity.
138+
countBonus += memoryHash.Count * 25;
139+
}
140+
catch
141+
{
142+
}
143+
144+
_output.Append(_console.ToString());
145+
_output.Append("|");
146+
147+
// Check result.
148+
for (int j = 0; j < _trainingResults[i].Length; j++)
149+
{
150+
if (_console.Length > j)
151+
{
152+
Fitness += 256 - Math.Abs(_console[j] - _trainingResults[i][j]);
153+
}
154+
}
155+
156+
// Length bonus (percentage of 10).
157+
Fitness += 10 * ((_trainingResults[i].Length - Math.Abs(_console.Length - _trainingResults[i].Length)) / _trainingResults[i].Length);
158+
159+
// Make the AI wait until a solution is found without the penalty.
160+
Fitness -= penalty;
161+
162+
// Check for solution.
163+
IsFitnessAchieved();
164+
165+
// Bonus for less operations to optimize the code.
166+
countBonus += ((_maxIterationCount - _bf.m_Ticks) / 20.0);
167+
168+
Ticks += _bf.m_Ticks;
169+
TotalTicks += _bf.m_TotalTicks;
170+
}
171+
172+
if (_fitness != Double.MaxValue)
173+
{
174+
_fitness = Fitness + countBonus;
175+
}
176+
177+
return _fitness;
178+
}
179+
180+
protected override void RunProgramMethod(string program)
181+
{
182+
for (int i = 0; i < 99; i++)
183+
{
184+
// Get input from the user.
185+
Console.WriteLine();
186+
Console.Write(">: ");
187+
string line = Console.ReadLine();
188+
int index = 0;
189+
190+
_console.Clear();
191+
192+
try
193+
{
194+
// Run the program.
195+
Interpreter bf = new Interpreter(program, () =>
196+
{
197+
byte b;
198+
199+
// Send the next character.
200+
if (index < line.Length)
201+
{
202+
b = (byte)line[index++];
203+
}
204+
else
205+
{
206+
b = 0;
207+
}
208+
209+
return b;
210+
},
211+
(b) =>
212+
{
213+
_console.Append((char)b);
214+
}, null, new Function[] { new Function() { MaxIterationCount = 100 } });
215+
216+
bf.Run(_maxIterationCount);
217+
}
218+
catch
219+
{
220+
}
221+
222+
Console.WriteLine(_console.ToString());
223+
}
224+
}
225+
226+
public override string GetConstructorParameters()
227+
{
228+
return _maxIterationCount.ToString();
229+
}
230+
231+
#endregion
232+
}
233+
}

‎AIProgrammer.Interpreter/Interpreter.cs‎

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ private class FunctionCallObj
102102
/// <summary>
103103
/// The list of functions and their starting instruction index.
104104
/// </summary>
105-
private readonly Dictionary<char, KeyValuePair<int,int>> m_Functions = new Dictionary<char, KeyValuePair<int,int>>();
105+
private readonly Dictionary<char, FunctionInst> m_Functions = new Dictionary<char, FunctionInst>();
106106

107107
/// <summary>
108108
/// Identifier for next function. Will serve as the instruction to call this function.
@@ -147,9 +147,9 @@ private class FunctionCallObj
147147
private byte? m_ReturnValue;
148148

149149
/// <summary>
150-
/// Options for the interpreter.
150+
/// Options for function behavior in the interpreter.
151151
/// </summary>
152-
private InterpreterOptions m_Options = newInterpreterOptions();
152+
private Function[] m_Options = null;
153153

154154
#endregion
155155

@@ -210,7 +210,7 @@ private class FunctionCallObj
210210
/// <param name="output">Function to call when output command (.) is executed.</param>
211211
/// <param name="function">Callback handler to notify that a function is being executed: callback(instruction).</param>
212212
/// <param name="options">Additional interpreter options.</param>
213-
public Interpreter(string programCode, Func<byte> input, Action<byte> output, Action<char> function = null, InterpreterOptions options = null)
213+
public Interpreter(string programCode, Func<byte> input, Action<byte> output, Action<char> function = null, Function[] options = null)
214214
{
215215
// Save the program code
216216
this.m_Source = programCode.ToCharArray();
@@ -396,10 +396,13 @@ public Interpreter(string programCode, Func<byte> input, Action<byte> output, Ac
396396
this.m_Storage = 0;
397397
this.m_ReturnValue = null;
398398

399+
// Load options for this function.
400+
FunctionInst functionOptions = m_Functions[instruction];
401+
399402
// Set the function input pointer to the parent's starting memory. Calls for input (,) from within the function will read from parent's memory, each call advances the parent memory cell that gets read from. This allows passing multiple values to a function.
400403
// Note, if we set the starting m_FunctionInputPointer to 0, functions will read from the first input position (0).
401404
// If we set it to m_DataPointer, functions will read input from the current position in the parent memory (n). This is trickier for the GA to figure out, because it may have to downshift the memory back to 0 before calling the function so that the function gets all input. Setting this to 0 makes it easier for the function to get the input.
402-
this.m_FunctionInputPointer = this.m_Options.ReadFunctionInputAtMemoryStart ? 0 : this.m_DataPointer;
405+
this.m_FunctionInputPointer = functionOptions.ReadInputAtMemoryStart ? 0 : this.m_DataPointer;
403406

404407
// Set the data pointer to the functions starting memory address.
405408
this.m_DataPointer = _functionSize * (instruction - 96); // each function gets a space of 1000 memory slots.
@@ -411,10 +414,10 @@ public Interpreter(string programCode, Func<byte> input, Action<byte> output, Ac
411414
this.m_Ticks = 0;
412415

413416
// Set the max iteration count for this function, if one was specified.
414-
this.m_MaxIterationCount = m_Functions[instruction].Value > 0 ? m_Functions[instruction].Value : this.m_MaxIterationCount;
417+
this.m_MaxIterationCount = functionOptions.MaxIterationCount > 0 ? functionOptions.MaxIterationCount : this.m_MaxIterationCount;
415418

416419
// Set the instruction pointer to the beginning of the function.
417-
this.m_InstructionPointer = m_Functions[instruction].Key;
420+
this.m_InstructionPointer = functionOptions.InstructionPointer;
418421
}
419422
});
420423
}
@@ -522,11 +525,11 @@ private void ScanFunctions(string source)
522525
this.m_InstructionPointer = source.IndexOf('@');
523526
while (this.m_InstructionPointer > -1 && this.m_InstructionPointer < source.Length - 1 && !m_Stop)
524527
{
525-
// Extract a max iteration count, if specified.
526-
intmaxFunctionIterationCount = m_Options.FunctionMaxIterationCounts != null && m_Options.FunctionMaxIterationCounts.Length > m_Functions.Count ? m_Options.FunctionMaxIterationCounts[m_Functions.Count] : 0;
528+
// Retrieve any settings for this function.
529+
FunctionfunctionDetail = m_Options != null && m_Options.Length > m_Functions.Count ? m_Options[m_Functions.Count] : null;
527530

528531
// Store the function.
529-
m_Functions.Add(m_NextFunctionCharacter++, new KeyValuePair<int,int>(this.m_InstructionPointer, maxFunctionIterationCount));
532+
m_Functions.Add(m_NextFunctionCharacter++, new FunctionInst(this.m_InstructionPointer, functionDetail));
530533

531534
this.m_InstructionPointer = source.IndexOf('@', this.m_InstructionPointer + 1);
532535
}

‎AIProgrammer.Types/AIProgrammer.Types.csproj‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,13 +39,14 @@
3939
<Reference Include="System.Xml" />
4040
</ItemGroup>
4141
<ItemGroup>
42+
<Compile Include="FunctionInst.cs" />
4243
<Compile Include="GAParams.cs" />
4344
<Compile Include="GAStatus.cs" />
4445
<Compile Include="Genome.cs" />
4546
<Compile Include="Interface\IFitness.cs" />
4647
<Compile Include="Interface\IFunction.cs" />
4748
<Compile Include="Interface\IGeneticAlgorithm.cs" />
48-
<Compile Include="InterpreterOptions.cs" />
49+
<Compile Include="Function.cs" />
4950
<Compile Include="Properties\AssemblyInfo.cs" />
5051
<Compile Include="TargetParams.cs" />
5152
</ItemGroup>

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /