-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCartPole2dAsync.cs
More file actions
86 lines (72 loc) · 2.34 KB
/
CartPole2dAsync.cs
File metadata and controls
86 lines (72 loc) · 2.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
using System.Threading.Tasks;
using Gym.Environments.Envs.Classic;
using Gym.Rendering.WinForm;
using OneOf;
using RLMatrix;
public class CartPole2dAsync : IEnvironmentAsync<float[,]>
{
public int stepCounter { get; set; }
public int maxSteps { get; set; }
public bool isDone { get; set; }
public OneOf<int, (int, int)> stateSize { get; set; }
public int[] actionSize { get; set; }
private CartPoleEnv myEnv;
private float[,] myState;
public CartPole2dAsync()
{
Task.Run(async () => await InitialiseAsync()).Wait(); // Initialize in constructor asynchronously
}
public Task<float[,]> GetCurrentState()
{
return Task.FromResult(myState ?? new float[2, 2]);
}
public async Task InitialiseAsync()
{
myEnv = new CartPoleEnv(WinFormEnvViewer.Factory);
stepCounter = 0;
maxSteps = 100000;
stateSize = (2, 2);
actionSize = new int[] { myEnv.ActionSpace.Shape.Size };
await Task.Run(() => myEnv.Reset()); // Assuming Reset is not async; wrap in Task.Run
isDone = false;
myState = new float[2, 2]; // Initialize state with default values
}
public Task Reset()
{
return Task.Run(() =>
{
myEnv.Reset(); // Assuming Reset is not async; wrap in Task.Run
myState = new float[2, 2];
isDone = false;
stepCounter = 0;
});
}
public Task<(float, bool)> Step(int[] actionsIds)
{
return Task.Run(() =>
{
if (isDone)
Reset().Wait(); // Reset if done
var actionId = actionsIds[0];
var (observation, reward, done, information) = myEnv.Step(actionId);
SixLabors.ImageSharp.Image img = myEnv.Render();
float[] observationArray = observation.ToFloatArray();
myState[0, 0] = observationArray[0];
myState[0, 1] = observationArray[1];
myState[1, 0] = observationArray[2];
myState[1, 1] = observationArray[3];
isDone = done;
stepCounter++;
if (stepCounter > maxSteps)
isDone = true;
if (isDone)
reward = 0;
return (reward, isDone);
});
}
~CartPole2dAsync()
{
myEnv.CloseEnvironment();
myEnv.Dispose();
}
}