-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
241 lines (194 loc) · 9.21 KB
/
Program.cs
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
using Microsoft.Bonsai.SimulatorApi.Client;
using Microsoft.Bonsai.SimulatorApi.Models;
using System;
using Newtonsoft.Json;
using System.Net.Http;
using System.Threading;
using System.Text;
namespace CatchAndRun
{
class Program
{
/// <summary>
///
/// </summary>
/// <param name="args"></param>
/// <remarks>
/// You can run the example by itself, or pass the predict and http://localhost:5000/v1/prediction url
/// </remarks>
static void Main(string[] args)
{
if (args.Length == 0)
TrainAndAssess();
else
{
if (args[0] == "predict")
RunPrediction(args[1]);//assumes the second value is the URL
}
}
/// <summary>
/// Run the Train or Assessment loop
/// </summary>
private static void TrainAndAssess()
{
int sequenceId = 1;
String workspaceName = GetWorkspace();
String accessKey = GetAccessKey();
BonsaiClientConfig bcConfig = new BonsaiClientConfig(workspaceName, accessKey);
BonsaiClient client = new BonsaiClient(bcConfig);
//the cartpole model
Model model = new Model();
// object that indicates if we have registered successfully
object registered = null;
string sessionId = "";
while (true)
{
// go through the registration process
if (registered == null)
{
var sessions = client.Session;
SimulatorInterface sim_interface = new SimulatorInterface();
//シミュレータ名(Bonsaiにはここの名称が表示される)
sim_interface.Name = "CatchAndRun";
sim_interface.Timeout = 60;
sim_interface.Capabilities = null;
// minimum required
sim_interface.SimulatorContext = bcConfig.SimulatorContext;
var registrationResponse = sessions.CreateWithHttpMessagesAsync(workspaceName, sim_interface).Result;
if (registrationResponse.Body.GetType() == typeof(SimulatorSessionResponse))
{
registered = registrationResponse;
SimulatorSessionResponse sessionResponse = registrationResponse.Body;
// this is required
sessionId = sessionResponse.SessionId;
}
Console.WriteLine(DateTime.Now + " - registered session " + sessionId);
}
else // now we are registered
{
Console.WriteLine(DateTime.Now + " - advancing " + sequenceId);
// build the SimulatorState object
SimulatorState simState = new SimulatorState();
simState.SequenceId = sequenceId; // required
simState.State = model.State; // required
simState.Halted = model.Halted; // required
try
{
// advance only returns an object, so we need to check what type of object
var response = client.Session.AdvanceWithHttpMessagesAsync(workspaceName, sessionId, simState).Result;
// if we get an error during advance
if (response.Body.GetType() == typeof(EventModel))
{
EventModel eventModel = (EventModel)response.Body;
Console.WriteLine(DateTime.Now + " - received event: " + eventModel.Type);
sequenceId = eventModel.SequenceId; // get the sequence from the result
// now check the type of event and handle accordingly
if (eventModel.Type == EventType.EpisodeStart)
{
Config config = new Config();
// use eventModel.EpisodeStart.Config to obtain values
dynamic startConfig = eventModel.EpisodeStart.Config;
#region 環境値の入力(今回は未使用)
if (startConfig.catch_position_x != null)
{
config.catch_position_x = startConfig.catch_position_x;
}
if (startConfig.catch_position_y != null)
{
config.catch_position_y = startConfig.catch_position_y;
}
if (startConfig.run_position_x != null)
{
config.run_position_x = startConfig.run_position_x;
}
if (startConfig.catch_position_y != null)
{
config.catch_position_y = startConfig.run_position_y;
}
#endregion
model.Start(config);
}
else if (eventModel.Type == EventType.EpisodeStep)
{
Action action = new Action();
dynamic stepAction = eventModel.EpisodeStep.Action;
//bonsaiから入力された移動先
action.catch_position_x = stepAction.catch_position_x;
action.catch_position_y = stepAction.catch_position_y;
//入力値をもとにシミュレートする
model.Step(action);
}
else if (eventModel.Type == EventType.EpisodeFinish)
{
Console.WriteLine("Episode Finish");
}
else if (eventModel.Type == EventType.Idle)
{
Thread.Sleep(Convert.ToInt32(eventModel.Idle.CallbackTime) * 1000);
}
else if (eventModel.Type == EventType.Unregister)
{
try
{
client.Session.DeleteWithHttpMessagesAsync(workspaceName, sessionId).Wait();
}
catch (Exception ex)
{
Console.WriteLine("cannot unregister: " + ex.Message);
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("Error occurred at " + DateTime.UtcNow + ":");
Console.WriteLine(ex.ToString());
Console.WriteLine("Simulation will now end");
Environment.Exit(0);
}
}
}
}
private static void RunPrediction(string predictionurl)
{
Model model = new Model();
HttpClient bc = new HttpClient();
while (true)
{
// create the request object -- using random numbers in the state range
string reqJson = JsonConvert.SerializeObject(model.State);
var request = new HttpRequestMessage()
{
Method = HttpMethod.Get,
RequestUri = new Uri(predictionurl),
Content = new StringContent(reqJson, Encoding.UTF8, "application/json")
};
var resp = bc.SendAsync(request).Result;
resp.EnsureSuccessStatusCode();
var respJson = resp.Content.ReadAsStringAsync().Result;
// convert the json string to a dynamic object with Kp and Ki types
Action resultObj = (Action)JsonConvert.DeserializeObject(respJson);
//Console.WriteLine($"Kp = {resultObj.}");
model.Step(resultObj);
}
}
private static string GetWorkspace()
{
if (Environment.GetEnvironmentVariable("SIM_WORKSPACE") != null)
{
return Environment.GetEnvironmentVariable("SIM_WORKSPACE");
}
//fill in your Bonsai workspace ID
return "<your_bonsai_workspace_id>";
}
private static String GetAccessKey()
{
if (Environment.GetEnvironmentVariable("SIM_ACCESS_KEY") != null)
{
return Environment.GetEnvironmentVariable("SIM_ACCESS_KEY");
}
//fill in your Bonsai access key
return "<your_bonsai_access_key>";
}
}
}