Пример #1
0
 public Rods(SimulatorInterface simInterface)
     : base(simInterface)
 {
     this.mode = this.Register<string>("{get, es_rod_controller_server, mode}");
     this.speed = this.Register<float>("{get, es_rod_controller_server, speed}");
     //			this.Register(new Connector.Setter(setCtrlRodPosition), "{get, es_rod_position_server, control_position_array_str}"); // TODO: this should be uncomented when Lib.StringToArray learns to parse subarrays
 }
Пример #2
0
 public Reactor(SimulatorInterface simInterface)
     : base(simInterface)
 {
     this.burnup = this.Register<float>("{get, es_core_server, burnup}");
     this.boron = this.Register<float>("{get, es_core_server, boron}");
     this.flux = this.Register<float>("{get, es_core_server, flux}");
     this.tavg = this.Register<float>("{get, es_core_server, tavg}");
 }
Пример #3
0
        public Simulator(ServerInterface serverInterface, string simId)
        {
            this.simId = simId;
            this.simInterface = serverInterface.ConnectToSim(this.simId);

            this.Init();
            this.log = new SimulatorLog(this.simInterface);
        }
Пример #4
0
        public Simulator(ServerInterface serverInterface, string name, string description)
        {
            this.simId = serverInterface.StartSim(name, description);
            this.simInterface = serverInterface.ConnectToSim(this.simId);

            this.Init();
            this.log = new SimulatorLog(this.simInterface);
        }
Пример #5
0
 public Turbine(SimulatorInterface simInterface)
     : base(simInterface)
 {
     this.power = this.Register<float>("{get, es_turbine_server, power}");
     this.tref = this.Register<float>("{get, es_turbine_server, tref}");
     this.target = this.Register<float>("{get, es_turbine_server, target}");
     this.rate = this.Register<float>("{get, es_turbine_server, rate}");
     this.go = this.Register<bool>("{get, es_turbine_server, go}");
 }
Пример #6
0
        public void TestSessionCreateGetAndDelete()
        {
            SimulatorInterface createBody = new SimulatorInterface(name: "sim");

            SimulatorSessionResponse createResponse = this.client.Session.CreateAsync(config.Workspace, createBody).Result;

            Assert.NotNull(createResponse);
            Assert.NotEmpty(createResponse.SessionId);

            SimulatorSessionResponse getResponse = this.client.Session.GetAsync(config.Workspace, createResponse.SessionId).Result;

            Assert.NotNull(getResponse);
            Assert.Equal(getResponse.SessionId, createResponse.SessionId);

            this.client.Session.DeleteAsync(config.Workspace, createResponse.SessionId).Wait();
        }
Пример #7
0
        public void TestSessionAdvance()
        {
            SimulatorInterface createBody = new SimulatorInterface(name: "sim");

            SimulatorSessionResponse createResponse = this.client.Session.CreateAsync(config.Workspace, createBody).Result;

            Assert.NotNull(createResponse);
            Assert.NotEmpty(createResponse.SessionId);

            SimulatorState advanceBody     = new SimulatorState(sequenceId: 1, state: new { number1 = 1, number2 = 2 });
            EventModel     advanceResponse = this.client.Session.AdvanceAsync(config.Workspace, createResponse.SessionId, advanceBody).Result;

            Assert.True(advanceResponse.Type == EventType.Idle);
            Assert.NotNull(advanceResponse.Idle);

            this.client.Session.DeleteAsync(config.Workspace, createResponse.SessionId).Wait();
        }
Пример #8
0
 public SyncData(SimulatorInterface simInterface)
 {
     this.simInterface = simInterface;
     this.Sync();
 }
Пример #9
0
 public SimulatorLog(SimulatorInterface simInterface)
 {
     this.simInterface = simInterface;
     this.syncData = new SyncData(this.simInterface);
 }
Пример #10
0
 public Clock(SimulatorInterface simInterface)
     : base(simInterface)
 {
     this.logTicks = this.Register<bool>("{get, es_clock_server, log_ticks}");
     this.status = this.Register<string>("{get, es_clock_server, status}");
 }
Пример #11
0
 /// <summary>
 /// Registers a simulator with the Bonsai platform.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='workspaceName'>
 /// The workspace identifier.
 /// </param>
 /// <param name='body'>
 /// Information and capabilities about the simulator.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <SimulatorSessionResponse> CreateAsync(this ISession operations, string workspaceName, SimulatorInterface body, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.CreateWithHttpMessagesAsync(workspaceName, body, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
Пример #12
0
 /// <summary>
 /// Registers a simulator with the Bonsai platform.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='workspaceName'>
 /// The workspace identifier.
 /// </param>
 /// <param name='body'>
 /// Information and capabilities about the simulator.
 /// </param>
 public static SimulatorSessionResponse Create(this ISession operations, string workspaceName, SimulatorInterface body)
 {
     return(operations.CreateAsync(workspaceName, body).GetAwaiter().GetResult());
 }
Пример #13
0
        /// <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();

                    sim_interface.Name         = "Cartpole-CSharp";
                    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 (not used in Cartpole)

                                model.Start(config);
                            }
                            else if (eventModel.Type == EventType.EpisodeStep)
                            {
                                Action action = new Action();

                                dynamic stepAction = eventModel.EpisodeStep.Action;

                                action.Command = stepAction.command.Value;

                                // move the model forward
                                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);
                    }
                }
            }
        }
Пример #14
0
        /// <summary>
        /// Registers a simulator with the Bonsai platform.
        /// </summary>
        /// <param name='workspaceName'>
        /// The workspace identifier.
        /// </param>
        /// <param name='body'>
        /// Information and capabilities about the simulator.
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="ProblemDetailsException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <HttpOperationResponse <SimulatorSessionResponse> > CreateWithHttpMessagesAsync(string workspaceName, SimulatorInterface body, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (workspaceName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "workspaceName");
            }
            if (body == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "body");
            }
            if (body != null)
            {
                body.Validate();
            }
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("workspaceName", workspaceName);
                tracingParameters.Add("body", body);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "Create", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "v2/workspaces/{workspaceName}/simulatorSessions").ToString();

            _url = _url.Replace("{workspaceName}", System.Uri.EscapeDataString(workspaceName));
            // Create HTTP transport objects
            var _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("POST");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers


            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            if (body != null)
            {
                _requestContent      = Rest.Serialization.SafeJsonConvert.SerializeObject(body, Client.SerializationSettings);
                _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
                _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json-patch+json; charset=utf-8");
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 201)
            {
                var ex = new ProblemDetailsException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    ProblemDetails _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <ProblemDetails>(_responseContent, Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new HttpOperationResponse <SimulatorSessionResponse>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            // Deserialize Response
            if ((int)_statusCode == 201)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <SimulatorSessionResponse>(_responseContent, Client.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }