public void Test_AsyncSender_SendSuccess()
        {
            ManualResetEventSlim senderCalledWaiter = new ManualResetEventSlim(initialState: false);

            bool sendCalled = false;

            Task AsyncSenderSend(SharedBuffer buffer, BackgroundErrorCallback raiseBackgroundError)
            {
                sendCalled = true;
                senderCalledWaiter.Set();

                return(Task.CompletedTask);
            }

            FactoryContext factoryContext = CreateFactoryContext(asyncSendFunc: AsyncSenderSend);

            LiveModel liveModel = CreateLiveModel(factoryContext);

            liveModel.Init();
            RankingResponse response = liveModel.ChooseRank(EventId, ContextJsonWithPdf);

            senderCalledWaiter.Wait(TimeSpan.FromSeconds(1));

            Assert.IsTrue(sendCalled);
        }
Beispiel #2
0
        private LiveModel ConfigureLiveModel()
        {
            Configuration config;
            ApiStatus     apiStatus = new ApiStatus();

            if (!Configuration.TryLoadConfigurationFromJson(PseudoLocConfigJson, out config, apiStatus))
            {
                Assert.Fail("Failed to parse pseudolocalized configuration JSON: " + apiStatus.ErrorMessage);
            }

            TempFileDisposable interactionDisposable = new TempFileDisposable();

            this.TestCleanup.Add(interactionDisposable);

            TempFileDisposable observationDisposable = new TempFileDisposable();

            this.TestCleanup.Add(observationDisposable);

            config["interaction.file.name"] = interactionDisposable.Path;
            config["observation.file.name"] = observationDisposable.Path;

            LiveModel liveModel = new LiveModel(config);

            liveModel.Init();
            liveModel.RefreshModel();

            return(liveModel);
        }
        public void Test_LiveModel_ReportOutcome()
        {
            LiveModel liveModel = this.ConfigureLiveModel();

            Run_LiveModelReportOutcomeF_Test(liveModel, PseudoLocEventId, 1.0f);
            Run_LiveModelReportOutcomeJson_Test(liveModel, PseudoLocEventId, PseudoLocOutcomeJson);
        }
        public static void PdfExample(string configPath)
        {
            const float  outcome     = 1.0f;
            const string eventId     = "event_id";
            const string contextJson = "{\"GUser\":{\"id\":\"a\",\"major\":\"eng\",\"hobby\":\"hiking\"},\"_multi\":[ { \"TAction\":{\"a1\":\"f1\"} },{\"TAction\":{\"a2\":\"f2\"}}],\"p\":[0.2, 0.8]}";

            LiveModel liveModel = Helpers.CreateLiveModelOrExit(configPath);

            ApiStatus apiStatus = new ApiStatus();

            RankingResponse rankingResponse = new RankingResponse();

            if (!liveModel.TryChooseRank(eventId, contextJson, rankingResponse, apiStatus))
            {
                Helpers.WriteStatusAndExit(apiStatus);
            }

            long actionId;

            if (!rankingResponse.TryGetChosenAction(out actionId, apiStatus))
            {
                Helpers.WriteStatusAndExit(apiStatus);
            }

            Console.WriteLine($"Chosen action id: {actionId}");

            if (!liveModel.TryQueueOutcomeEvent(eventId, outcome, apiStatus))
            {
                Helpers.WriteStatusAndExit(apiStatus);
            }
        }
Beispiel #5
0
        public void Test_LiveModel_ChooseRank()
        {
            LiveModel liveModel = this.ConfigureLiveModel();

            Run_LiveModelChooseRank_Test(liveModel, PseudoLocEventId, PseudoLocContextJsonWithPdf);
            Run_LiveModelChooseRankWithFlags_Test(liveModel, PseudoLocEventId, PseudoLocContextJsonWithPdf);
        }
Beispiel #6
0
        public async Task <ActionResult <LiveModel> > PostLive([FromBody] LiveModel Live)
        {
            _context.Live.Add(Live);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetLive", new { id = Live.ID }, Live));
        }
Beispiel #7
0
        public async Task <IActionResult> PutLive(int id, LiveModel Live)
        {
            if (id != Live.ID)
            {
                return(BadRequest());
            }

            _context.Entry(Live).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!LiveExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Beispiel #8
0
        public void Test_LiveModel_RequestDecision()
        {
            LiveModel liveModel = this.ConfigureLiveModel();

            Run_LiveModelRequestDecision_Test(liveModel, PseudoLocContextJsonWithPdf);
            Run_LiveModelRequestDecisionWithFlags_Test(liveModel, PseudoLocContextJsonWithPdf);
        }
Beispiel #9
0
        private static LiveModel CreateLiveModelOrExit(string clientJsonPath)
        {
            if (!File.Exists(clientJsonPath))
            {
                WriteErrorAndExit($"Could not find file with path '{clientJsonPath}'.");
            }

            string json = File.ReadAllText(clientJsonPath);

            ApiStatus apiStatus = new ApiStatus();

            Configuration config;

            if (!Configuration.TryLoadConfigurationFromJson(json, out config, apiStatus))
            {
                WriteStatusAndExit(apiStatus);
            }

            LiveModel liveModel = new LiveModel(config);

            if (!liveModel.TryInit(apiStatus))
            {
                WriteStatusAndExit(apiStatus);
            }

            liveModel.BackgroundError += LiveModel_BackgroundError;

            return(liveModel);
        }
Beispiel #10
0
        public void Test_LiveModel_RequestMultiSlotDecision()
        {
            LiveModel liveModel = this.ConfigureLiveModel();

            Run_LiveModelRequestMultiSlot_Test(liveModel, PseudoLocMultiSlotContextWithPdf, PseudoLocEventId);
            Run_LiveModelRequestMultiSlotWithFlags_Test(liveModel, PseudoLocMultiSlotContextWithPdf, PseudoLocEventId);
        }
        public override void Run()
        {
            LiveModel liveModel = Helpers.CreateLiveModelOrExit(this.ConfigPath);

            RLSimulator rlSim = new RLSimulator(liveModel, useSlates: this.UseSlates);
            rlSim.StepInterval = TimeSpan.FromMilliseconds(this.SleepIntervalMs);
            rlSim.OnError += (sender, apiStatus) => Helpers.WriteStatusAndExit(apiStatus);
            rlSim.Run(this.Steps);
        }
Beispiel #12
0
        public override void Run()
        {
            LiveModel liveModel = Helpers.CreateLiveModelOrExit(this.ConfigPath);

            RLDriver rlDriver = new RLDriver(liveModel, loopKind: this.GetLoopKind());

            rlDriver.StepInterval = TimeSpan.FromMilliseconds(this.SleepIntervalMs);

            rlDriver.Run(new StatsFileStepProvider(StatsConfig, Seed, Steps));
        }
Beispiel #13
0
        // TODO: Pull this out to a separate sample once we implement the simulator in this.
        public static void BasicUsageExample(string [] args)
        {
            const float  outcome     = 1.0f;
            const string eventId     = "event_id";
            const string contextJson = "{'GUser':{'id':'a','major':'eng','hobby':'hiking'},'_multi':[ { 'TAction':{'a1':'f1'} },{'TAction':{'a2':'f2'}}]}";

            if (args.Length != 1)
            {
                WriteErrorAndExit("Missing path to client configuration json");
            }

            if (!File.Exists(args[0]))
            {
                WriteErrorAndExit($"Could not find file with path '{args[0]}'.");
            }

            string json = File.ReadAllText(args[0]);

            ApiStatus apiStatus = new ApiStatus();

            Configuration config;

            if (!Configuration.TryLoadConfigurationFromJson(json, out config, apiStatus))
            {
                WriteStatusAndExit(apiStatus);
            }

            LiveModel liveModel = new LiveModel(config);

            if (!liveModel.TryInit(apiStatus))
            {
                WriteStatusAndExit(apiStatus);
            }

            RankingResponse rankingResponse = new RankingResponse();

            if (!liveModel.TryChooseRank(eventId, contextJson, rankingResponse, apiStatus))
            {
                WriteStatusAndExit(apiStatus);
            }

            long actionId;

            if (!rankingResponse.TryGetChosenAction(out actionId, apiStatus))
            {
                WriteStatusAndExit(apiStatus);
            }

            Console.WriteLine($"Chosen action id: {actionId}");

            if (!liveModel.TryReportOutcome(eventId, outcome, apiStatus))
            {
                WriteStatusAndExit(apiStatus);
            }
        }
Beispiel #14
0
        public void Test_LiveModel_ReportOutcome()
        {
            LiveModel liveModel = this.ConfigureLiveModel();

            Run_LiveModelReportOutcomeF_Test(liveModel, PseudoLocEventId, 1.0f);
            Run_LiveModelReportOutcomeJson_Test(liveModel, PseudoLocEventId, PseudoLocOutcomeJson);
            Run_LiveModelReportOutcomeSlotF_Test(liveModel, PseudoLocEventId, 1, 1.0f);
            Run_LiveModelReportOutcomeSlotJson_Test(liveModel, PseudoLocEventId, 1, PseudoLocOutcomeJson);
            Run_LiveModelReportOutcomeSlotStringIdF_Test(liveModel, PseudoLocEventId, "SlotId", 1.0f);
            Run_LiveModelReportOutcomeSlotStringIdJson_Test(liveModel, PseudoLocEventId, "SlotId", PseudoLocOutcomeJson);
        }
        public void Test_CustomSender_FailsWhenNotRegistered()
        {
            const int TypeNotRegisteredError = 10; // see errors_data.h

            ApiStatus apiStatus = new ApiStatus();
            LiveModel liveModel = CreateLiveModel();

            Assert.IsFalse(liveModel.TryInit(apiStatus), "Should not be able to configure a model with BINDING_SENDER if custom factory is not set.");

            Assert.AreEqual(TypeNotRegisteredError, apiStatus.ErrorCode);
        }
Beispiel #16
0
        public void Test_LiveModel_ChooseRankE2E()
        {
            LiveModel liveModel = this.ConfigureLiveModel();

            RankingResponse rankingResponse1 = liveModel.ChooseRank(PseudoLocEventId, PseudoLocContextJsonWithPdf);

            ValidatePdf(rankingResponse1);

            RankingResponse rankingResponse2 = liveModel.ChooseRank(PseudoLocEventId, PseudoLocContextJsonWithPdf, ActionFlags.Deferred);

            ValidatePdf(rankingResponse2);
        }
Beispiel #17
0
        private void Run_LiveModelRequestContinuousAction_Test(LiveModel liveModel, string contextJson)
        {
            NativeMethods.LiveModelRequestContinuousActionOverride =
                (IntPtr liveModelPtr, IntPtr eventIdPtr, IntPtr contextJsonPtr, IntPtr continuousActionResponse, IntPtr ApiStatus) =>
            {
                string contextJsonMarshalledBack = NativeMethods.StringMarshallingFunc(contextJsonPtr);
                Assert.AreEqual(contextJson, contextJsonMarshalledBack, "Marshalling contextJson does not work properly in LiveModelRequestContinuousAction");

                return(NativeMethods.SuccessStatus);
            };

            liveModel.RequestContinuousAction(PseudoLocEventId, contextJson);
        }
Beispiel #18
0
        // TODO: Create a real CCB context json and add an E2E test (pending CCB E2E and
        // clarity around sample mode.)

        private void Run_LiveModelReportActionTaken_Test(LiveModel liveModel, string eventId)
        {
            NativeMethods.LiveModelReportActionTakenOverride =
                (IntPtr liveModelPtr, IntPtr eventIdPtr, IntPtr apiStatus) =>
            {
                string eventIdMarshalledBack = NativeMethods.StringMarshallingFunc(eventIdPtr);
                Assert.AreEqual(eventId, eventIdMarshalledBack, "Marshalling eventId does not work properly in LiveModelReportActionTaken");

                return(NativeMethods.SuccessStatus);
            };

            liveModel.QueueActionTakenEvent(eventId);
        }
Beispiel #19
0
        private void Run_LiveModelReportOutcomeSlotF_Test(LiveModel liveModel, string eventId, uint slotIndex, float outcome)
        {
            NativeMethods.LiveModelReportOutcomeSlotFOverride =
                (IntPtr liveModelPtr, IntPtr eventIdPtr, uint slotI, float o, IntPtr apiStatus) =>
            {
                string eventIdMarshalledBack = NativeMethods.StringMarshallingFunc(eventIdPtr);
                Assert.AreEqual(eventId, eventIdMarshalledBack, "Marshalling eventId does not work properly in LiveModelReportOutcomeSlotF");

                return(NativeMethods.SuccessStatus);
            };

            liveModel.QueueOutcomeEvent(eventId, slotIndex, outcome);
        }
Beispiel #20
0
        private void Run_LiveModelRequestMultiSlotWithFlags_Test(LiveModel liveModel, string contextJson, string eventId)
        {
            NativeMethods.LiveModelRequestMultiSlotDecisionWithFlagsOverride =
                (IntPtr liveModelPtr, IntPtr eventIdPtr, IntPtr contextJsonPtr, uint flags, IntPtr rankingResponse, IntPtr ApiStatus) =>
            {
                string contextJsonMarshalledBack = NativeMethods.StringMarshallingFunc(contextJsonPtr);
                Assert.AreEqual(contextJson, contextJsonMarshalledBack, "Marshalling contextJson does not work properly in LiveModelRequestDecisionWithFlags");

                return(NativeMethods.SuccessStatus);
            };

            liveModel.RequestMultiSlotDecision(eventId, contextJson, ActionFlags.Deferred);
        }
        private void Run_LiveModelRequestMultiSlotDetailed_Test(LiveModel liveModel, string contextJson, string eventId)
        {
            NativeMethods.LiveModelRequestMultiSlotDecisionDetailedOverride =
                (IntPtr liveModelPtr, IntPtr eventIdPtr, IntPtr contextJsonPtr, int contextJsonSize, IntPtr rankingResponse, IntPtr ApiStatus) =>
            {
                string contextJsonMarshalledBack = NativeMethods.StringMarshallingFunc(contextJsonPtr);
                Assert.AreEqual(contextJson, contextJsonMarshalledBack, "Marshalling contextJson does not work properly in LiveModelRequestMultiSlotDecisionDetailed");

                return(NativeMethods.SuccessStatus);
            };

            liveModel.RequestMultiSlotDecisionDetailed(eventId, contextJson);
        }
Beispiel #22
0
        private void Run_LiveModelReportOutcomeJson_Test(LiveModel liveModel, string eventId, string outcomeJson)
        {
            NativeMethods.LiveModelReportOutcomeJsonOverride =
                (IntPtr liveModelPtr, IntPtr eventIdPtr, IntPtr outcomeJsonPtr, IntPtr apiStatus) =>
            {
                string eventIdMarshalledBack = NativeMethods.StringMarshallingFunc(eventIdPtr);
                Assert.AreEqual(eventId, eventIdMarshalledBack, "Marshalling eventId does not work properly in LiveModelReportOutcomeJson");

                string outcomeJsonMarshalledBack = NativeMethods.StringMarshallingFunc(outcomeJsonPtr);
                Assert.AreEqual(outcomeJson, outcomeJsonMarshalledBack, "Marshalling eventId does not work properly in LiveModelReportOutcomeJson");

                return(NativeMethods.SuccessStatus);
            };
        }
        private LiveModel CreateLiveModel(FactoryContext factoryContext = null)
        {
            Configuration config;
            ApiStatus     apiStatus = new ApiStatus();

            if (!Configuration.TryLoadConfigurationFromJson(CustomSenderConfigJson, out config, apiStatus))
            {
                Assert.Fail("Failed to parse pseudolocalized configuration JSON: " + apiStatus.ErrorMessage);
            }

            LiveModel liveModel = factoryContext == null ? new LiveModel(config) : new LiveModel(config, factoryContext);

            return(liveModel);
        }
        public override void Run()
        {
            LiveModel liveModel = Helpers.CreateLiveModelOrExit(this.ConfigPath);
            RLDriver  rlDriver  = new RLDriver(liveModel);

            rlDriver.StepInterval = TimeSpan.FromMilliseconds(this.SleepIntervalMs);
            PerfTestStepProvider stepProvider = new PerfTestStepProvider(this.ActionsCount, this.SharedFeatures, this.ActionFeatures)
            {
                Duration = TimeSpan.FromMilliseconds(this.DurationMs), Tag = this.Tag
            };

            rlDriver.Run(stepProvider);
            stepProvider.Stats.Print();
        }
        public override void Run()
        {
            LiveModel liveModel = Helpers.CreateLiveModelOrExit(this.ConfigPath);
            RLDriver  rlDriver  = new RLDriver(liveModel, loopKind: this.GetLoopKind());

            rlDriver.StepInterval = TimeSpan.FromMilliseconds(this.SleepIntervalMs);

            using (TextReader textReader = File.OpenText(this.LogPath))
            {
                IEnumerable <string> dsJsonLines  = textReader.LazyReadLines();
                ReplayStepProvider   stepProvider = new ReplayStepProvider(dsJsonLines);

                rlDriver.Run(stepProvider);
            }
        }
Beispiel #26
0
        //convert from "RTModel" to "Currencies" for the first entry (ignor magnitude)
        private List <Currency> FirstEntryConverter(List <Country> Countries, LiveModel RTRates)
        {
            List <Currency> CurrenciesList = new List <Currency>();

            foreach (var qoute in RTRates.quotes)
            {
                string   issuesCountryName = Countries.Find(t => t.Code == qoute.Key.Substring(3)).Name;
                Currency newCurrency       = new Currency()
                {
                    Value = float.Parse(qoute.Value), IssuedCountryCode = qoute.Key.Substring(3), IssuedCountryName = issuesCountryName, Direction = "+", Magnitude = 0
                };
                CurrenciesList.Add(newCurrency);
            }
            return(CurrenciesList);
        }
Beispiel #27
0
        public static void RunSimulator(string [] args)
        {
            if (args.Length != 1)
            {
                // TODO: Better usage
                WriteErrorAndExit("Missing path to client configuration json");
            }

            LiveModel liveModel = CreateLiveModelOrExit(args[0]);

            RLSimulator rlSim = new RLSimulator(liveModel);

            rlSim.OnError += (sender, apiStatus) => WriteStatusAndExit(apiStatus);
            rlSim.Run();
        }
Beispiel #28
0
        private void Run_LiveModelChooseRankWithFlags_Test(LiveModel liveModel, string eventId, string contextJson)
        {
            NativeMethods.LiveModelChooseRankWithFlagsOverride =
                (IntPtr liveModelPtr, IntPtr eventIdPtr, IntPtr contextJsonPtr, uint flags, IntPtr rankingResponse, IntPtr apiStatus) =>
            {
                string eventIdMarshalledBack = NativeMethods.StringMarshallingFunc(eventIdPtr);
                Assert.AreEqual(eventId, eventIdMarshalledBack, "Marshalling eventId does not work properly in LiveModelChooseRank");

                string contextJsonMarshalledBack = NativeMethods.StringMarshallingFunc(contextJsonPtr);
                Assert.AreEqual(contextJson, contextJsonMarshalledBack, "Marshalling contextJson does not work properly in LiveModelChooseRank");

                return(NativeMethods.SuccessStatus);
            };

            liveModel.ChooseRank(eventId, contextJson, ActionFlags.Deferred);
        }
        public void Test_CustomSender_InitSuccess()
        {
            bool initCalled = false;

            void SenderInit(ApiStatus status)
            {
                initCalled = true;
            }

            FactoryContext factoryContext = CreateFactoryContext(initAction: SenderInit);

            LiveModel liveModel = CreateLiveModel(factoryContext);

            liveModel.Init();

            Assert.IsTrue(initCalled, "MockSender.Init should be called and succeed, which means LiveModel.Init should succeed.");
        }
Beispiel #30
0
        //convert from "RTModel" to "Currencies" and colculate the magnitude , country
        private List <Currency> Converter(List <Country> Countries, LiveModel RTRates, Currencies DbRates)
        {
            List <Currency>            CurrenciesList       = new List <Currency>();
            Dictionary <string, float> dictionaryCurrencies = DbRates.CurrenciesList.ToDictionary(key => key.IssuedCountryCode, value => value.Value);

            foreach (var qoute in RTRates.quotes)
            {
                string   issuesCountryName = Countries.Find(t => t.Code == qoute.Key.Substring(3)).Name;
                Currency newCurrency       = new Currency()
                {
                    Value = float.Parse(qoute.Value), IssuedCountryCode = qoute.Key.Substring(3), IssuedCountryName = issuesCountryName
                };
                addDirectionAndMagnitude(qoute, dictionaryCurrencies, newCurrency);
                CurrenciesList.Add(newCurrency);
            }
            return(CurrenciesList);
        }