public void VariationSendsFeatureEventForUnknownFlagWhenClientIsNotInitialized() { var config = BasicConfig() .DataSource(new MockDataSourceThatNeverInitializes().AsSingletonFactory()) .Events(_factory); using (LdClient client = TestUtil.CreateClient(config.Build(), user)) { string result = client.StringVariation("flag", "b"); Assert.Equal("b", result); Assert.Collection(eventProcessor.Events, e => CheckIdentifyEvent(e, user), e => { EvaluationEvent fe = Assert.IsType <EvaluationEvent>(e); Assert.Equal("flag", fe.FlagKey); Assert.Equal("b", fe.Value.AsString); Assert.Null(fe.Variation); Assert.Null(fe.FlagVersion); Assert.Equal("b", fe.Default.AsString); Assert.Null(fe.Reason); Assert.NotEqual(0, fe.Timestamp.Value); }); } }
public void VariationDetailSendsFeatureEventWithReasonForValidFlag() { var flag = new FeatureFlagBuilder().Value(LdValue.Of("a")).Variation(1).Version(1000) .TrackEvents(true).DebugEventsUntilDate(UnixMillisecondTime.OfMillis(2000)) .Reason(EvaluationReason.OffReason).Build(); _testData.Update(_testData.Flag("flag").PreconfiguredFlag(flag)); using (LdClient client = MakeClient(user)) { EvaluationDetail <string> result = client.StringVariationDetail("flag", "b"); Assert.Equal("a", result.Value); Assert.Equal(EvaluationReason.OffReason, result.Reason); Assert.Collection(eventProcessor.Events, e => CheckIdentifyEvent(e, user), e => { EvaluationEvent fe = Assert.IsType <EvaluationEvent>(e); Assert.Equal("flag", fe.FlagKey); Assert.Equal("a", fe.Value.AsString); Assert.Equal(1, fe.Variation); Assert.Equal(1000, fe.FlagVersion); Assert.Equal("b", fe.Default.AsString); Assert.True(fe.TrackEvents); Assert.Equal(UnixMillisecondTime.OfMillis(2000), fe.DebugEventsUntilDate); Assert.Equal(EvaluationReason.OffReason, fe.Reason); Assert.NotEqual(0, fe.Timestamp.Value); }); } }
private void TestInlineUserSerialization(User user, LdValue expectedJsonValue, EventsConfiguration config) { config.InlineUsersInEvents = true; var f = new EventOutputFormatter(config); var evalEvent = new EvaluationEvent { FlagKey = "flag", User = user }; var outputEvent = SerializeOneEvent(f, evalEvent); Assert.Equal(LdValue.Null, outputEvent.Get("userKey")); Assert.Equal(expectedJsonValue, outputEvent.Get("user")); Assert.Equal(user.Anonymous ? LdValue.Of("anonymousUser") : LdValue.Null, outputEvent.Get("contextKind")); var identifyEvent = new IdentifyEvent { User = user }; outputEvent = SerializeOneEvent(f, identifyEvent); Assert.Equal(LdValue.Null, outputEvent.Get("userKey")); Assert.Equal(expectedJsonValue, outputEvent.Get("user")); Assert.False(outputEvent.Dictionary.ContainsKey("contextKind")); var customEvent = new CustomEvent { EventKey = "customkey", User = user }; outputEvent = SerializeOneEvent(f, customEvent); Assert.Equal(LdValue.Null, outputEvent.Get("userKey")); Assert.Equal(expectedJsonValue, outputEvent.Get("user")); Assert.Equal(user.Anonymous ? LdValue.Of("anonymousUser") : LdValue.Null, outputEvent.Get("contextKind")); var indexEvent = new IndexEvent { User = user }; outputEvent = SerializeOneEvent(f, indexEvent); Assert.Equal(LdValue.Null, outputEvent.Get("userKey")); Assert.Equal(expectedJsonValue, outputEvent.Get("user")); Assert.False(outputEvent.Dictionary.ContainsKey("contextKind")); }
public void VariationSendsFeatureEventWithReasonForUnknownFlagWhenClientIsNotInitialized() { var config = BasicConfig() .DataSource(new MockDataSourceThatNeverInitializes().AsSingletonFactory()) .Events(_factory); using (LdClient client = TestUtil.CreateClient(config.Build(), user)) { EvaluationDetail <string> result = client.StringVariationDetail("flag", "b"); var expectedReason = EvaluationReason.ErrorReason(EvaluationErrorKind.ClientNotReady); Assert.Equal("b", result.Value); Assert.Equal(expectedReason, result.Reason); Assert.Collection(eventProcessor.Events, e => CheckIdentifyEvent(e, user), e => { EvaluationEvent fe = Assert.IsType <EvaluationEvent>(e); Assert.Equal("flag", fe.FlagKey); Assert.Equal("b", fe.Value.AsString); Assert.Null(fe.Variation); Assert.Null(fe.FlagVersion); Assert.Equal("b", fe.Default.AsString); Assert.False(fe.TrackEvents); Assert.Null(fe.DebugEventsUntilDate); Assert.Equal(expectedReason, fe.Reason); Assert.NotEqual(0, fe.Timestamp.Value); }); } }
public void UserKeyIsSetInsteadOfUserWhenNotInlined() { var user = User.Builder("userkey") .Name("me") .Build(); var userJson = LdValue.Parse(@"{""key"":""userkey"",""name"":""me""}"); var f = new EventOutputFormatter(new EventsConfiguration()); var evalEvent = new EvaluationEvent { FlagKey = "flag", User = user }; var outputEvent = SerializeOneEvent(f, evalEvent); Assert.Equal(LdValue.Null, outputEvent.Get("user")); Assert.Equal(user.Key, outputEvent.Get("userKey").AsString); // user is always inlined in identify event var identifyEvent = new IdentifyEvent { User = user }; outputEvent = SerializeOneEvent(f, identifyEvent); Assert.Equal(LdValue.Null, outputEvent.Get("userKey")); Assert.Equal(userJson, outputEvent.Get("user")); var customEvent = new CustomEvent { EventKey = "customkey", User = user }; outputEvent = SerializeOneEvent(f, customEvent); Assert.Equal(LdValue.Null, outputEvent.Get("user")); Assert.Equal(user.Key, outputEvent.Get("userKey").AsString); // user is always inlined in index event var indexEvent = new IndexEvent { Timestamp = _fixedTimestamp, User = user }; outputEvent = SerializeOneEvent(f, indexEvent); Assert.Equal(LdValue.Null, outputEvent.Get("userKey")); Assert.Equal(userJson, outputEvent.Get("user")); }
public void FlagReturnsFallthroughVariationAndEventIfPrerequisiteIsMetAndThereAreNoRules() { var f0 = new FeatureFlagBuilder("feature0") .On(true) .Prerequisites(new Prerequisite("feature1", 1)) .OffVariation(1) .FallthroughVariation(0) .Variations(fallthroughValue, offValue, onValue) .Version(1) .Build(); var f1 = new FeatureFlagBuilder("feature1") .On(true) .FallthroughVariation(1) // this is what makes the prerequisite pass .Variations(LdValue.Of("nogo"), LdValue.Of("go")) .Version(2) .Build(); var evaluator = BasicEvaluator.WithStoredFlags(f1); var result = evaluator.Evaluate(f0, baseUser, EventFactory.Default); var expected = new EvaluationDetail <LdValue>(fallthroughValue, 0, EvaluationReason.FallthroughReason); Assert.Equal(expected, result.Result); Assert.Equal(1, result.PrerequisiteEvents.Count); EvaluationEvent e = result.PrerequisiteEvents[0]; Assert.Equal(f1.Key, e.FlagKey); Assert.Equal(LdValue.Of("go"), e.Value); Assert.Equal(f1.Version, e.FlagVersion); Assert.Equal(f0.Key, e.PrerequisiteOf); }
public void FlagReturnsOffVariationAndEventIfPrerequisiteIsOff() { var f0 = new FeatureFlagBuilder("feature0") .On(true) .Prerequisites(new Prerequisite("feature1", 1)) .OffVariation(1) .FallthroughVariation(0) .Variations(fallthroughValue, offValue, onValue) .Version(1) .Build(); var f1 = new FeatureFlagBuilder("feature1") .On(false) .OffVariation(1) // note that even though it returns the desired variation, it is still off and therefore not a match .Variations(LdValue.Of("nogo"), LdValue.Of("go")) .Version(2) .Build(); var evaluator = BasicEvaluator.WithStoredFlags(f1); var result = evaluator.Evaluate(f0, baseUser, EventFactory.Default); var expected = new EvaluationDetail <LdValue>(offValue, 1, EvaluationReason.PrerequisiteFailedReason("feature1")); Assert.Equal(expected, result.Result); Assert.Equal(1, result.PrerequisiteEvents.Count); EvaluationEvent e = result.PrerequisiteEvents[0]; Assert.Equal(f1.Key, e.FlagKey); Assert.Equal(LdValue.Of("go"), e.Value); Assert.Equal(f1.Version, e.FlagVersion); Assert.Equal(f0.Key, e.PrerequisiteOf); }
void drawFrequencies(object sender, RoutedEventArgs e) { EvaluationEvent occupancyEvent = this._dataField as EvaluationEvent; this._signalPlot.DrawFrequency(occupancyEvent); this.Loaded -= drawFrequencies; }
/// <summary> /// Draws the frequency. /// </summary> /// <param name="event_">The event.</param> /// <exception cref="System.ArgumentException">The Amplitudes cannot be null and should include more than 1 frequencies</exception> public void DrawFrequency(EvaluationEvent event_) { if (!event_.HasFrequencies || event_.FrequencyAmplitudes.Length < 2) { throw new ArgumentException("The Amplitudes cannot be null and should include more than 1 frequencies"); } this._event = event_; this.draw(); }
/// <summary> /// Draws the frequency. /// </summary> /// <param name="event_">The event.</param> /// <exception cref="System.ArgumentException">The Amplitudes cannot be null and should include more than 1 frequencies</exception> public void DrawFrequency(EvaluationEvent event_) { if (!event_.HasFrequencies || event_.FrequencyAmplitudes.Length < 2) { throw new ArgumentException("The Amplitudes cannot be null and should include more than 1 frequencies"); } this._children.Clear(); double x0 = 0, x1 = Math.PI, y0 = 0, y1 = double.NegativeInfinity; for (int i = 0; i < event_.FrequencyAmplitudes.Length; i++) { if (event_.FrequencyAmplitudes[i] > y1) { y1 = event_.FrequencyAmplitudes[i]; } } DataStatVisualHost parent = (DataStatVisualHost)((Grid)this.Parent).Parent; double h = parent.Width - 10; double yScale = -this.RenderSize.Height / (y1 - y0); double xScale = this.RenderSize.Width / (x1 - x0); this._dataTransformMatrix.M11 = xScale; this._dataTransformMatrix.M22 = yScale; this._dataTransformMatrix.OffsetY = this.RenderSize.Height - y0 * yScale; this._dataTransformMatrix.OffsetX = -x0 * xScale; this._geometryTransform.Matrix = this._dataTransformMatrix; double thickness = this._thickness / (2 * xScale); parent.YMAX = y1.ToString("0.0000"); StreamGeometry geom = new StreamGeometry(); using (var gc = geom.Open()) { gc.BeginFigure(new Point(0, event_.FrequencyAmplitudes[0]), false, false); double dist = Math.PI / (event_.FrequencyAmplitudes.Length - 1); for (int i = 0; i <= event_.FrequencyAmplitudes.Length; i++) { gc.LineTo(new Point(i * dist, event_.FrequencyAmplitudes[i]), true, true); } } geom.Transform = this._geometryTransform; if (geom.CanFreeze) { geom.Freeze(); } DrawingVisual visual = new DrawingVisual(); using (var vc = visual.RenderOpen()) { vc.DrawGeometry(null, new Pen(this._trendlineBrush, 2.5 * this._thickness), geom); } this._children.Add(visual); }
private bool ShouldDebugEvent(EvaluationEvent fe) { if (fe.DebugEventsUntilDate != null) { long lastPast = Interlocked.Read(ref _lastKnownPastTime); if (fe.DebugEventsUntilDate.Value.Value > lastPast && fe.DebugEventsUntilDate.Value.Value > UnixMillisecondTime.Now.Value) { return(true); } } return(false); }
public void MultipleLevelsOfPrerequisitesProduceMultipleEvents() { var f0 = new FeatureFlagBuilder("feature0") .On(true) .Prerequisites(new Prerequisite("feature1", 1)) .OffVariation(1) .FallthroughVariation(0) .Variations(fallthroughValue, offValue, onValue) .Version(1) .Build(); var f1 = new FeatureFlagBuilder("feature1") .On(true) .Prerequisites(new Prerequisite("feature2", 1)) .FallthroughVariation(1) .Variations(LdValue.Of("nogo"), LdValue.Of("go")) .Version(2) .Build(); var f2 = new FeatureFlagBuilder("feature2") .On(true) .FallthroughVariation(1) .Variations(LdValue.Of("nogo"), LdValue.Of("go")) .Version(3) .Build(); var evaluator = BasicEvaluator.WithStoredFlags(f1, f2); var result = evaluator.Evaluate(f0, baseUser, EventFactory.Default); var expected = new EvaluationDetail <LdValue>(fallthroughValue, 0, EvaluationReason.FallthroughReason); Assert.Equal(expected, result.Result); Assert.Equal(2, result.PrerequisiteEvents.Count); EvaluationEvent e0 = result.PrerequisiteEvents[0]; Assert.Equal(f2.Key, e0.FlagKey); Assert.Equal(LdValue.Of("go"), e0.Value); Assert.Equal(f2.Version, e0.FlagVersion); Assert.Equal(f1.Key, e0.PrerequisiteOf); EvaluationEvent e1 = result.PrerequisiteEvents[1]; Assert.Equal(f1.Key, e1.FlagKey); Assert.Equal(LdValue.Of("go"), e1.Value); Assert.Equal(f1.Version, e1.FlagVersion); Assert.Equal(f0.Key, e1.PrerequisiteOf); }
public void VariationSendsFeatureEventForUnknownFlag() { using (LdClient client = MakeClient(user)) { string result = client.StringVariation("flag", "b"); Assert.Equal("b", result); Assert.Collection(eventProcessor.Events, e => CheckIdentifyEvent(e, user), e => { EvaluationEvent fe = Assert.IsType <EvaluationEvent>(e); Assert.Equal("flag", fe.FlagKey); Assert.Equal("b", fe.Value.AsString); Assert.Null(fe.Variation); Assert.Null(fe.FlagVersion); Assert.Equal("b", fe.Default.AsString); Assert.Null(fe.Reason); Assert.NotEqual(0, fe.Timestamp.Value); }); } }
private void WriteEvaluationEvent(EvaluationEvent ee, bool debug) { WriteBase(debug ? "debug" : "feature", ee.Timestamp, ee.FlagKey); WriteUserOrKey(ee.User, debug, true); if (ee.FlagVersion.HasValue) { _obj.Name("version").Int(ee.FlagVersion.Value); } if (ee.Variation.HasValue) { _obj.Name("variation").Int(ee.Variation.Value); } LdValueConverter.WriteJsonValue(ee.Value, _obj.Name("value")); if (!ee.Default.IsNull) { LdValueConverter.WriteJsonValue(ee.Default, _obj.Name("default")); } _obj.MaybeName("prereqOf", ee.PrereqOf != null).String(ee.PrereqOf); WriteReason(ee.Reason); }
public void VariationSendsFeatureEventForDefaultValue() { var flag = new FeatureFlagBuilder().Version(1000).Build(); _testData.Update(_testData.Flag("flag").PreconfiguredFlag(flag)); using (LdClient client = MakeClient(user)) { string result = client.StringVariation("flag", "b"); Assert.Equal("b", result); Assert.Collection(eventProcessor.Events, e => CheckIdentifyEvent(e, user), e => { EvaluationEvent fe = Assert.IsType <EvaluationEvent>(e); Assert.Equal("flag", fe.FlagKey); Assert.Equal("b", fe.Value.AsString); Assert.Null(fe.Variation); Assert.Equal(1000, fe.FlagVersion); Assert.Equal("b", fe.Default.AsString); Assert.Null(fe.Reason); Assert.NotEqual(0, fe.Timestamp.Value); }); } }
public void VariationDetailSendsFeatureEventWithReasonForUnknownFlag() { using (LdClient client = MakeClient(user)) { EvaluationDetail <string> result = client.StringVariationDetail("flag", "b"); var expectedReason = EvaluationReason.ErrorReason(EvaluationErrorKind.FlagNotFound); Assert.Equal("b", result.Value); Assert.Equal(expectedReason, result.Reason); Assert.Collection(eventProcessor.Events, e => CheckIdentifyEvent(e, user), e => { EvaluationEvent fe = Assert.IsType <EvaluationEvent>(e); Assert.Equal("flag", fe.FlagKey); Assert.Equal("b", fe.Value.AsString); Assert.Null(fe.Variation); Assert.Null(fe.FlagVersion); Assert.Equal("b", fe.Default.AsString); Assert.False(fe.TrackEvents); Assert.Null(fe.DebugEventsUntilDate); Assert.Equal(expectedReason, fe.Reason); Assert.NotEqual(0, fe.Timestamp.Value); }); } }
/// <summary> /// Initializes a new instance of the <see cref="SpatialDataPropertySetting"/> class. /// </summary> /// <param name="host">The main document to which this control belongs.</param> /// <param name="dataField">The data field.</param> public SpatialDataPropertySetting(OSMDocument host, ISpatialData dataField) { InitializeComponent(); this._host = host; this._dataField = dataField; this._spatialDataField = dataField as SpatialDataField; if (this._spatialDataField != null) { this._eventCase.Visibility = System.Windows.Visibility.Collapsed; this._includeCost.IsChecked = this._spatialDataField.UseCostFunctionForEventCapturing; this._includeCost.Checked += _includeCost_Checked; this._includeCost.Unchecked += _includeCost_Unchecked; if (this._spatialDataField.EventCapturingInterval != null) { this._intervalMax.Text = this._spatialDataField.EventCapturingInterval.Maximum.ToString(format); this._intervalMin.Text = this._spatialDataField.EventCapturingInterval.Minimum.ToString(format); this._capture.IsChecked = this._spatialDataField.UseToCaptureEvent; this._outsideInterval.IsChecked = this._spatialDataField.CaptureEventWhenOutsideInterval; } else { this._capture.IsChecked = false; this._capture.IsEnabled = false; this._outsideInterval.IsChecked = false; this._outsideInterval.IsEnabled = false; } this._intervalMin.TextChanged += _intervalMin_TextChanged; this._intervalMax.TextChanged += _intervalMax_TextChanged; this._capture.Checked += _capture_Checked; this._capture.Unchecked += _capture_Unchecked; this._outsideInterval.Checked += _outsideInterval_Checked; this._outsideInterval.Unchecked += _outsideInterval_Unchecked; this._method.Items.Add(CostCalculationMethod.RawValue); this._method.Items.Add(CostCalculationMethod.WrittenFormula); this._method.Items.Add(CostCalculationMethod.Interpolation); if (this._spatialDataField.HasBuiltInRepulsion) { this._method.Items.Add(CostCalculationMethod.BuiltInRepulsion); } this._method.SelectedItem = this._spatialDataField.CostCalculationType; this._method.SelectionChanged += new SelectionChangedEventHandler(_method_SelectionChanged); this._include.IsChecked = this._spatialDataField.IncludeInActivityGeneration; this._vis.Click += new RoutedEventHandler(_vis_Click); } else { this._desirability.Visibility = System.Windows.Visibility.Collapsed; this._setDataCostProperties.Visibility = System.Windows.Visibility.Collapsed; } switch (this._dataField.Type) { case DataType.SpatialData: this._signal.Visibility = System.Windows.Visibility.Collapsed; this._activityTimePeriod.Visibility = System.Windows.Visibility.Collapsed; this._activityEngagementEvent.Visibility = System.Windows.Visibility.Collapsed; this._simulationResult.Visibility = System.Windows.Visibility.Collapsed; this._dataType.Text = "Spatial Data Field"; break; case DataType.ActivityPotentialField: this._signal.Visibility = System.Windows.Visibility.Collapsed; this._simulationResult.Visibility = System.Windows.Visibility.Collapsed; this._eventCase.Visibility = System.Windows.Visibility.Collapsed; this._dataType.Text = "Activity"; this._maximumEngagementTime.TextChanged += new TextChangedEventHandler(activityEngagementTime_TextChanged); this._maximumEngagementTime.Text = ((Activity)this._dataField).MaximumEngagementTime.ToString(format); this._minimumEngagementTime.TextChanged += new TextChangedEventHandler(activityEngagementTime_TextChanged); this._minimumEngagementTime.Text = ((Activity)this._dataField).MinimumEngagementTime.ToString(format); this._captureActivityEvent.IsChecked = ((Activity)this._dataField).UseToCaptureEvent; this._captureActivityEvent.Checked += _captureActivityEvent_Checked; this._captureActivityEvent.Unchecked += _captureActivityEvent_Unchecked; break; case DataType.OccupancyEvent: this._simulationResult.Visibility = System.Windows.Visibility.Collapsed; this._activityTimePeriod.Visibility = System.Windows.Visibility.Collapsed; this._activityEngagementEvent.Visibility = System.Windows.Visibility.Collapsed; EvaluationEvent occupancyEvent = this._dataField as EvaluationEvent; switch (occupancyEvent.EventType) { case EvaluationEventType.Optional: this._dataType.Text = "Optional Occupancy Event"; this._mandatoryEvntInfo.Visibility = System.Windows.Visibility.Collapsed; break; case EvaluationEventType.Mandatory: this._dataType.Text = "Mandatory Occupancy Event"; this._hasActivityEvents.IsChecked = ((MandatoryEvaluationEvent)occupancyEvent).HasActivityEngagementEvent; break; } if (occupancyEvent.HasFrequencies) { try { this.Loaded += drawFrequencies; } catch (Exception error) { MessageBox.Show(error.Report()); } } else { this._signal.Visibility = System.Windows.Visibility.Collapsed; } this._timeStep.Text = occupancyEvent.TimeStep.ToString(format); this._duration.Text = occupancyEvent.Duration.ToString(format); this._likelihood.Text = occupancyEvent.Likelihood.ToString(format); this._timeSamplingRate.Text = occupancyEvent.TimeSamplingRate.ToString(format); this._velocityCap.Text = occupancyEvent.MaximumVelocityMagnitude.ToString(format); this._visibilityAngle.Text = occupancyEvent.VisibilityAngle.ToString(format); this._hasCapturedDataEvents.IsChecked = occupancyEvent.HasCapturedDataEvents; this._hasCapturedVisualEvents.IsChecked = occupancyEvent.HasCapturedVisualEvents; break; case DataType.SimulationResult: this._setDataCostProperties.Visibility = System.Windows.Visibility.Collapsed; this._desirability.Visibility = System.Windows.Visibility.Collapsed; this._signal.Visibility = System.Windows.Visibility.Collapsed; this._activityTimePeriod.Visibility = System.Windows.Visibility.Collapsed; this._activityEngagementEvent.Visibility = System.Windows.Visibility.Collapsed; this._eventCase.Visibility = System.Windows.Visibility.Collapsed; if (this._dataField.GetType() == typeof(SimulationResult)) { this._s_duration.Text = ((SimulationResult)this._dataField).SimulationDuration.ToString(format); this._s_timeStep.Text = ((SimulationResult)this._dataField).TimeStep.ToString(format); this._mandatorySimulationResults.Visibility = System.Windows.Visibility.Collapsed; this._dataType.Text = "Optional Occupancy Simulation Results"; } else //if (this._dataField.GetType() == typeof(MandatorySimulationResult)) { this._s_duration.Text = ((SimulationResult)this._dataField).SimulationDuration.ToString(format); this._s_timeStep.Text = ((SimulationResult)this._dataField).TimeStep.ToString(format); this._distance.Text = ((MandatorySimulationResult)this._dataField).WalkedDistancePerHour.ToString(format); this._walkingTime.Text = ((MandatorySimulationResult)this._dataField).WalkingTime.ToString(percent); this._timeInMainStations.Text = ((MandatorySimulationResult)this._dataField).TimeInMainStations.ToString(percent); this._engagementTime.Text = ((MandatorySimulationResult)this._dataField).ActivityEngagementTime.ToString(percent); this._dataType.Text = "Mandatory Occupancy Simulation Results"; this._sequencesWhichNeededVisualDetection.Text = ((MandatorySimulationResult)this._dataField).SequencesWhichNeededVisualDetection.ToString(); this._averageDelayChanceForVisualDetection.Text = ((MandatorySimulationResult)this._dataField).AverageDelayChanceForVisualDetection.ToString(percent); this._minimumDelayChanceForVisualDetection.Text = ((MandatorySimulationResult)this._dataField).MinimumDelayChanceForVisualDetection.ToString(percent); this._maximumDelayChanceForVisualDetection.Text = ((MandatorySimulationResult)this._dataField).MaximumDelayChanceForVisualDetection.ToString(percent); } break; } this._boxPlot._canvas.Loaded += new RoutedEventHandler(_canvas_Loaded); }
public void EvaluationEventIsSerialized() { Func<EvaluationEvent> MakeBasicEvent = () => new EvaluationEvent { Timestamp = _fixedTimestamp, FlagKey = "flag", FlagVersion = 11, User = User.Builder("userkey").Name("me").Build(), Value = LdValue.Of("flagvalue"), Default = LdValue.Of("defaultvalue") }; var fe = MakeBasicEvent(); TestEventSerialization(fe, LdValue.Parse(@"{ ""kind"":""feature"", ""creationDate"":100000, ""key"":""flag"", ""version"":11, ""userKey"":""userkey"", ""value"":""flagvalue"", ""default"":""defaultvalue"" }")); var feWithVariation = MakeBasicEvent(); feWithVariation.Variation = 1; TestEventSerialization(feWithVariation, LdValue.Parse(@"{ ""kind"":""feature"", ""creationDate"":100000, ""key"":""flag"", ""version"":11, ""userKey"":""userkey"", ""value"":""flagvalue"", ""variation"":1, ""default"":""defaultvalue"" }")); var feWithReason = MakeBasicEvent(); feWithReason.Variation = 1; feWithReason.Reason = EvaluationReason.RuleMatchReason(1, "id"); TestEventSerialization(feWithReason, LdValue.Parse(@"{ ""kind"":""feature"", ""creationDate"":100000, ""key"":""flag"", ""version"":11, ""userKey"":""userkey"", ""value"":""flagvalue"", ""variation"":1, ""default"":""defaultvalue"", ""reason"":{""kind"":""RULE_MATCH"",""ruleIndex"":1,""ruleId"":""id""} }")); var feUnknownFlag = new EvaluationEvent { Timestamp = fe.Timestamp, FlagKey = "flag", User = fe.User, Value = LdValue.Of("defaultvalue"), Default = LdValue.Of("defaultvalue") }; TestEventSerialization(feUnknownFlag, LdValue.Parse(@"{ ""kind"":""feature"", ""creationDate"":100000, ""key"":""flag"", ""userKey"":""userkey"", ""value"":""defaultvalue"", ""default"":""defaultvalue"" }")); var debugEvent = new DebugEvent { FromEvent = feWithVariation }; TestEventSerialization(debugEvent, LdValue.Parse(@"{ ""kind"":""debug"", ""creationDate"":100000, ""key"":""flag"", ""version"":11, ""user"":{""key"":""userkey"",""name"":""me""}, ""value"":""flagvalue"", ""variation"":1, ""default"":""defaultvalue"" }")); var eventWithAnonUser = MakeBasicEvent(); eventWithAnonUser.User = User.Builder("anon-key").Anonymous(true).Build(); TestEventSerialization(eventWithAnonUser, LdValue.Parse(@"{ ""kind"":""feature"", ""creationDate"":100000, ""key"":""flag"", ""version"":11, ""userKey"":""anon-key"", ""contextKind"":""anonymousUser"", ""value"":""flagvalue"", ""default"":""defaultvalue"" }")); }
/// <summary> /// Applies filter on the specified spatial data. /// </summary> /// <param name="spatialData">The spatial data.</param> /// <param name="name">The name of the filtered data.</param> /// <param name="filter">The weighting factors of the filter.</param> /// <param name="rayIndices">The ray indices.</param> /// <param name="cellularFloor">The cellular floor.</param> /// <returns>ISpatialData.</returns> public static ISpatialData Apply(ISpatialData spatialData, string name, double[,] filter, Dictionary <Index, Index[]> rayIndices, CellularFloor cellularFloor) { int neighborhood_range = filter.GetLength(0); Dictionary <Cell, double> filtered = new Dictionary <Cell, double>(); foreach (Cell cell in spatialData.Data.Keys) { double value = IsovistClippedGaussian.Apply(spatialData, cell, filter, neighborhood_range, rayIndices, cellularFloor); filtered.Add(cell, value); } ISpatialData newData = null; switch (spatialData.Type) { case DataType.SpatialData: if (spatialData.GetType() == typeof(SpatialDataField)) { newData = new SpatialDataField(name, filtered); } else if (spatialData.GetType() == typeof(SimulationResult)) { SimulationResult simulationResult = (SimulationResult)spatialData; newData = new SimulationResult(name, filtered, simulationResult.TimeStep, simulationResult.SimulationDuration); } else if (spatialData.GetType() == typeof(MandatorySimulationResult)) { MandatorySimulationResult mandatorySimulationResult = (MandatorySimulationResult)spatialData; newData = new MandatorySimulationResult(name, filtered, mandatorySimulationResult.TimeStep, mandatorySimulationResult.SimulationDuration, mandatorySimulationResult.WalkedDistancePerHour, mandatorySimulationResult.TimeInMainStations, mandatorySimulationResult.WalkingTime, mandatorySimulationResult.ActivityEngagementTime, mandatorySimulationResult.SequencesWhichNeededVisualDetection, mandatorySimulationResult.AverageDelayChanceForVisualDetection, mandatorySimulationResult.MinimumDelayChanceForVisualDetection, mandatorySimulationResult.MaximumDelayChanceForVisualDetection); } break; case DataType.ActivityPotentialField: newData = new FieldUtility.Activity(filtered, ((Activity)spatialData).Origins, ((Activity)spatialData).DestinationArea, ((Activity)spatialData).DefaultState, name, cellularFloor); ((Activity)newData).TrySetEngagementTime(((Activity)spatialData).MinimumEngagementTime, ((Activity)spatialData).MaximumEngagementTime); break; case DataType.OccupancyEvent: if (spatialData.GetType() == typeof(MandatoryEvaluationEvent)) { MandatoryEvaluationEvent event_ = (MandatoryEvaluationEvent)spatialData; newData = new SpatialAnalysis.Events.MandatoryEvaluationEvent(name, filtered, event_.Likelihood, event_.TimeSamplingRate, event_.TimeStep, event_.Duration, event_.MaximumVelocityMagnitude, event_.VisibilityAngle, event_.HasCapturedVisualEvents, event_.HasCapturedDataEvents, event_.EventType, event_.CapturedEventTrails) { HasActivityEngagementEvent = event_.HasActivityEngagementEvent }; } else { EvaluationEvent event_ = (EvaluationEvent)spatialData; newData = new SpatialAnalysis.Events.EvaluationEvent(name, filtered, event_.Likelihood, event_.TimeSamplingRate, event_.TimeStep, event_.Duration, event_.MaximumVelocityMagnitude, event_.VisibilityAngle, event_.HasCapturedVisualEvents, event_.HasCapturedDataEvents, event_.EventType, event_.CapturedEventTrails); } break; } return(newData); }
internal void AddToSummary(EvaluationEvent ee) { _summarizer.SummarizeEvent(ee.Timestamp, ee.FlagKey, ee.FlagVersion, ee.Variation, ee.Value, ee.Default); }
public void RecordEvaluationEvent(EvaluationEvent e) => SubmitMessage(new EventProcessorInternal.EventMessage(e));
/// <summary> /// Captures the evaluation event. /// </summary> /// <param name="captureDataEvent">if set to <c>true</c> captures data event.</param> /// <param name="captureVisualEvents">if set to <c>true</c> captures visual events.</param> /// <param name="timeSamplingRate">The time sampling rate.</param> /// <param name="dataFieldName">Name of the data field.</param> /// <param name="fileAddress">The file address to which the data will be saved.</param> /// <param name="visualEventSetting">The visual event setting.</param> /// <param name="includedVisibility">if set to <c>true</c> captures events when visibility exists.</param> /// <param name="frequencyAnalysis">if set to <c>true</c> frequency analysis will be done.</param> /// <returns>EvaluationEvent.</returns> /// <exception cref="System.ArgumentException">Agent location cannot be found</exception> public EvaluationEvent CaptureEvent(bool captureDataEvent, bool captureVisualEvents, int timeSamplingRate, string dataFieldName, string fileAddress, VisibilityTarget visualEventSetting, bool includedVisibility, bool frequencyAnalysis) { int timeStepCounter = 0; double captured = 0; double uncaptured = 0; int percent = 0; List <SpatialDataField> dataFields = new List <SpatialDataField>(); foreach (var item in this._host.cellularFloor.AllSpatialDataFields.Values) { SpatialDataField data = item as SpatialDataField; if (data != null) { if (data.UseToCaptureEvent) { dataFields.Add(data); } } } List <StateBase> states = null; if (!string.IsNullOrEmpty(fileAddress) && !string.IsNullOrWhiteSpace(fileAddress)) { states = new List <StateBase>(); } List <double> signal = null; if (frequencyAnalysis) { signal = new List <double>(); } var trailData = new Dictionary <Cell, double>(); foreach (Cell item in this._host.cellularFloor.Cells) { trailData.Add(item, 0.0d); } while (this.TotalWalkTime < this.Duration) { this.TimeStep = this.FixedTimeStep; this.TotalWalkTime += this.FixedTimeStep; while (this.TimeStep != 0.0d) { this.TimeStepUpdate(); } timeStepCounter++; if (this.ReportProgress != null) { double percentd = 100 * this.TotalWalkTime / this.Duration; if ((int)percentd != percent) { percent = (int)percentd; this.ReportProgress(percent); } } Cell vantageCell = this._host.cellularFloor.FindCell(this.CurrentState.Location); // capturing events var eventRaised = true; if (captureDataEvent && captureVisualEvents) { if (includedVisibility) { eventRaised = visualEventSetting.VisualEventRaised(this.CurrentState, this.VisibilityCosineFactor, this._host.cellularFloor); } else { eventRaised = !visualEventSetting.VisualEventRaised(this.CurrentState, this.VisibilityCosineFactor, this._host.cellularFloor); } if (eventRaised) { foreach (var item in dataFields) { if (item.EventCaptured(vantageCell) == null) { eventRaised = false; break; } } } } else if (captureDataEvent && !captureVisualEvents) { foreach (var item in dataFields) { if (item.EventCaptured(vantageCell) == null) { eventRaised = false; break; } } } else if (!captureDataEvent && captureVisualEvents) { if (includedVisibility) { eventRaised = visualEventSetting.VisualEventRaised(this.CurrentState, this.VisibilityCosineFactor, this._host.cellularFloor); } else { eventRaised = !visualEventSetting.VisualEventRaised(this.CurrentState, this.VisibilityCosineFactor, this._host.cellularFloor); } } //updating data bool record = (timeStepCounter % timeSamplingRate == 0); if (eventRaised) { captured++; if (states != null && record) { states.Add(this.CurrentState.Copy()); } if (signal != null && record) { signal.Add(1.0d); } if (trailData.ContainsKey(vantageCell)) { trailData[vantageCell] += 1; } else { throw new ArgumentException("Agent location cannot be found"); } } else { uncaptured++; if (states != null && record) { states.Add(null); } if (signal != null && record) { signal.Add(0.0d); } } //checking to see if events are captured } if (!string.IsNullOrEmpty(fileAddress) && !string.IsNullOrWhiteSpace(fileAddress)) { using (System.IO.StreamWriter sw = new System.IO.StreamWriter(fileAddress)) { foreach (var item in states) { if (item == null) { sw.WriteLine("null"); } else { sw.WriteLine(item.ToString()); } } } } foreach (Cell item in this._host.cellularFloor.Cells) { if (item.FieldOverlapState == OverlapState.Outside) { trailData.Remove(item); } } double probability = captured / (captured + uncaptured); var event_ = new EvaluationEvent(dataFieldName, trailData, probability, timeSamplingRate, this.FixedTimeStep * 1000, this.Duration / (60 * 60), this.VelocityMagnitude, this.VisibilityAngle, captureVisualEvents, captureDataEvent, EvaluationEventType.Optional, null);//states.ToArray()); if (frequencyAnalysis) { event_.LoadFrequencyAmplitudes(signal.ToArray()); signal.Clear(); signal = null; } return(event_); }