private void SpatialDataAndActivities() { var cellularDataNames = new TextBlock() { Text = "Spatial Data".ToUpper(), FontSize = 13, FontWeight = FontWeights.DemiBold, }; this._dataNames.Items.Add(cellularDataNames); foreach (var item in this._host.cellularFloor.AllSpatialDataFields.Values) { SpatialDataField spatialData = item as SpatialDataField; if (spatialData != null) { this._dataNames.Items.Add(spatialData); } } if (this._host.AllActivities.Count > 0) { var fieldNames = new TextBlock() { Text = "Activity".ToUpper(), FontSize = 13, FontWeight = FontWeights.DemiBold, }; this._dataNames.Items.Add(fieldNames); foreach (var item in this._host.AllActivities.Values) { this._dataNames.Items.Add(item); } } this._dataNames.SelectionChanged += new SelectionChangedEventHandler(_dataNames_SelectionChanged); }
/// <summary> /// Add a field of spatial data. This methods is thread safe. /// </summary> /// <param name="data">The data field</param> public void AddSpatialDataField(SpatialDataField data) { lock (_lock) { this.AllSpatialDataFields.Add(data.Name, data); } }
private Dictionary <Cell, double> loadData() { Dictionary <Cell, double> cellToValue = new Dictionary <Cell, double>(); if (this._selectedData.SelectedSpatialData.Type == DataType.SpatialData) { SpatialDataField dataField = (SpatialDataField )this._selectedData.SelectedSpatialData; if (!this._selectedData.VisualizeCost) { cellToValue = (dataField).Data; } else { cellToValue = new Dictionary <Cell, double>(); foreach (Cell item in dataField.Data.Keys) { double val = dataField.GetCost(dataField.Data[item]); cellToValue.Add(item, val); } } } else { cellToValue = this._selectedData.SelectedSpatialData.Data; } return(cellToValue); }
/// <summary> /// Initializes a new instance of the <see cref="SetSpatialDataFieldCost"/> class. /// </summary> /// <param name="host">The main document to which this control belongs.</param> /// <param name="function">The function or spatial data field.</param> public SetSpatialDataFieldCost(OSMDocument host, Function function) { InitializeComponent(); this._host = host; this._function = function; this._spatialDataFieldName.Text = this._function.Name; this._spatialDataField = function as SpatialDataField; if (this._spatialDataField != null) { this._method.Items.Add(CostCalculationMethod.RawValue); this._method.Items.Add(CostCalculationMethod.WrittenFormula); this._method.Items.Add(CostCalculationMethod.Interpolation); } else { this._method.Items.Add(CostCalculationMethod.RawValue); this._method.Items.Add(CostCalculationMethod.WrittenFormula); this._method.Items.Add(CostCalculationMethod.Interpolation); } this._method.SelectedItem = function.CostCalculationType; this._method.SelectionChanged += new SelectionChangedEventHandler(_method_SelectionChanged); this._include.IsChecked = function.IncludeInActivityGeneration; this._vis.Click += new RoutedEventHandler(_vis_Click); }
/// <summary> /// Draw a data field /// </summary> /// <param name="data">The data.</param> /// <param name="colorSteps">The color steps.</param> /// <param name="transformation">The transformation.</param> /// <param name="visualizeCost">if set to <c>true</c> [visualize cost].</param> private void drawSpatialDataField(SpatialDataField data, int colorSteps, Func <UV, Point> transformation, bool visualizeCost) { if (this._host.ColorCode.Steps != colorSteps) { this._host.ColorCode.SetSteps(colorSteps); } //set the dimention of the WriteableBitmap and assign it to the scene double _h = ((UIElement)this.Parent).RenderSize.Height; double _w = ((UIElement)this.Parent).RenderSize.Width; this.Scene.Height = _h; this.Scene.Width = _w; this.Scene.Source = null; this._view = null; this._view = BitmapFactory.New((int)_w, (int)_h); this.Scene.Source = _view; //start to draw if (visualizeCost) { Dictionary <Cell, double> costs = new Dictionary <Cell, double>(); double min = double.PositiveInfinity; double max = double.NegativeInfinity; foreach (KeyValuePair <Cell, double> item in data.Data) { double val = data.GetCost(data.Data[item.Key]); costs.Add(item.Key, val); min = (min > val) ? val : min; max = (max < val) ? val : max; } using (this._view.GetBitmapContext()) { foreach (Cell cell in costs.Keys) { Point p1 = transformation(cell); Point p2 = transformation(cell + new UV(this._host.cellularFloor.CellSize, this._host.cellularFloor.CellSize)); var color = this._host.ColorCode.GetColor((costs[cell] - min) / (max - min)); this._view.FillRectangle((int)p1.X, (int)p1.Y, (int)p2.X, (int)p2.Y, color); } } costs.Clear(); costs = null; } else { using (this._view.GetBitmapContext()) { foreach (Cell cell in data.Data.Keys) { Point p1 = transformation(cell); Point p2 = transformation(cell + new UV(this._host.cellularFloor.CellSize, this._host.cellularFloor.CellSize)); var color = this._host.ColorCode.GetColor((data.Data[cell] - data.Min) / (data.Max - data.Min)); this._view.FillRectangle((int)p1.X, (int)p1.Y, (int)p2.X, (int)p2.Y, color); } } } }
/// <summary> /// Initializes a new instance of the <see cref="InterpolationFormulaSet"/> class. /// </summary> /// <param name="data">The data.</param> public InterpolationFormulaSet(SpatialDataField data) { InitializeComponent(); this._data = new SortedDictionary <double, double>(); this._addBtn.Click += _addBtn_Click; this._removeBtn.Click += _removeBtn_Click; this._min = data.Min; this._max = data.Max; this._ok.Click += _ok_Click; this.Loaded += Window_Loaded; }
/// <summary> /// Initializes a new instance of the <see cref="TextFormulaSet"/> class. /// </summary> /// <param name="host">The main document to which this class belongs.</param> /// <param name="spatialDataField">The spatial data field.</param> public TextFormulaSet(OSMDocument host, SpatialDataField spatialDataField) { InitializeComponent(); this._host = host; this._min = spatialDataField.Min; this._max = spatialDataField.Max; this._test.Click += _test_Click; this.main.TextChanged += main_TextChanged; this.Loaded += Window_Loaded; this._insetParameter.Click += new RoutedEventHandler(_insetParameter_Click); this.main.Text = spatialDataField.TextFormula; this._spatialDataField = spatialDataField; this.LinkedParameters = new HashSet <Parameter>(); }
private void onlySpatialData(Dictionary <string, SpatialDataField> data) { var cellularDataNames = new TextBlock() { Text = "Spatial Data".ToUpper(), FontSize = 13, FontWeight = FontWeights.DemiBold, }; this._dataNames.Items.Add(cellularDataNames); foreach (var item in data.Values) { SpatialDataField spatialData = item as SpatialDataField; if (spatialData != null) { this._dataNames.Items.Add(spatialData); } } this._dataNames.SelectionChanged += new SelectionChangedEventHandler(_dataNames_SelectionChanged); }
/// <summary> /// Initializes a new instance of the <see cref="VisualizeFunction"/> class. /// </summary> /// <param name="function">The function.</param> public VisualizeFunction(Function function) { InitializeComponent(); this._name.Text = function.Name; SpatialDataField data = function as SpatialDataField; if (data != null) { this._min = data.Min; this._max = data.Max; this._MIN.IsEnabled = false; this._MAX.IsEnabled = false; } else { this._min = 0; this._max = 10; } this._MIN.Text = this._min.ToString(); this._MAX.Text = this._max.ToString(); this.CostFunction = function.GetCost; this._test.Click += new RoutedEventHandler(_test_Click); this._close.Click += new RoutedEventHandler(_close_Click); }
void _runBtm_Click(object sender, RoutedEventArgs e) { //input validation #region Events validation #region data event if (this._includedataEvents.IsChecked.Value) { bool dataEventAssigned = false; foreach (var item in this._host.cellularFloor.AllSpatialDataFields.Values) { SpatialDataField spatialDataField = item as SpatialDataField; if (spatialDataField != null) { if (spatialDataField.UseToCaptureEvent) { dataEventAssigned = true; break; } } } if (!dataEventAssigned) { var result = MessageBox.Show("Do you want to ignore spatial data events?", "Spatial data events are not defined", MessageBoxButton.YesNo, MessageBoxImage.Warning); if (result == MessageBoxResult.Yes) { this._includedataEvents.IsChecked = false; } else { return; } } } #endregion #region activity engagement events if (this._includeActivityEngagementEvents.IsChecked.Value) { bool activityEventAssigned = false; foreach (var item in this._host.AllActivities.Values) { if (item.UseToCaptureEvent) { activityEventAssigned = true; break; } } if (!activityEventAssigned) { var result = MessageBox.Show("Do you want to ignore activity engagement events?", "Activity engagement events are not defined", MessageBoxButton.YesNo, MessageBoxImage.Warning); if (result == MessageBoxResult.Yes) { this._includeActivityEngagementEvents.IsChecked = false; } else { return; } } } #endregion #region visual events if (this._includeVisualEvents.IsChecked.Value) { if (this._host.VisualEventSettings == null) { var result = MessageBox.Show("Do you want to ignore visual events?", "Visual events are not defined", MessageBoxButton.YesNo, MessageBoxImage.Warning); if (result == MessageBoxResult.Yes) { this._includeVisualEvents.IsChecked = false; } else { return; } } } #endregion if (!this._includeVisualEvents.IsChecked.Value && !this._includedataEvents.IsChecked.Value && !this._includeActivityEngagementEvents.IsChecked.Value) { MessageBox.Show("Cannot proceed without defining events in relation to spatial data, visibility or activity engagement!"); return; } #endregion #region numeric data validation double timeStep, duration; int timeSamplingRate; if (!double.TryParse(_timeStep.Text, out timeStep)) { MessageBox.Show("Invalid value for 'Time Step'"); return; } else if (timeStep <= 0) { MessageBox.Show("'Time Step' must be larger than zero"); return; } if (!double.TryParse(_timeDuration.Text, out duration)) { MessageBox.Show("Invalid value for 'Total Simulation Duration'"); return; } else if (duration <= 0) { MessageBox.Show("'Total Simulation Duration' must be larger than zero"); return; } if (!int.TryParse(_timeSamplingRate.Text, out timeSamplingRate)) { MessageBox.Show("Invalid value for 'Time Sampling Rate'"); return; } else if (timeSamplingRate <= 0) { MessageBox.Show("'Time Sampling Rate' must be larger than zero"); return; } #endregion #region Event Name Validation if (string.IsNullOrEmpty(_dataFieldName.Text) || string.IsNullOrWhiteSpace(_dataFieldName.Text)) { MessageBox.Show("A name is needed to save the captured event Data!", "Invalid Name"); return; } if (this._host.AllOccupancyEvent.ContainsKey(_dataFieldName.Text)) { MessageBox.Show(string.Format("'{0}' is already assigned to an exiting event Data!", _dataFieldName.Text), "Invalid Name"); return; } #endregion #region trail Data File Address if (string.IsNullOrEmpty(this._trailDataFileAddress) || string.IsNullOrWhiteSpace(this._trailDataFileAddress)) { var result = MessageBox.Show("Do you want to ignore saving the trail data of events?", "Invalid input", MessageBoxButton.YesNo, MessageBoxImage.Warning); if (result == MessageBoxResult.No) { return; } } #endregion this._runBtm.Click -= _runBtm_Click; Dispatcher.Invoke(new Action(() => { this._closeBtm.SetValue(Button.IsEnabledProperty, false); this._runBtm.SetValue(Button.IsEnabledProperty, false); this._interface.SetValue(StackPanel.IsEnabledProperty, false); this._progress.SetValue(Grid.VisibilityProperty, System.Windows.Visibility.Visible); }), DispatcherPriority.ContextIdle); EvaluationEvent capturedOccupancyEvent = null; switch (this._eventType) { case EvaluationEventType.Optional: var simulator_OP = new OptionalScenarioSimulation(this._host, timeStep, duration); //register report progress event simulator_OP.ReportProgress += this.updateProgressBar; capturedOccupancyEvent = simulator_OP.CaptureEvent(this._includedataEvents.IsChecked.Value, this._includeVisualEvents.IsChecked.Value, (int)double.Parse(this._pointPerSeconds.Text), _dataFieldName.Text, this._trailDataFileAddress, this._host.VisualEventSettings, this._visibilityExists.IsChecked.Value, this._analyzeFrequency.IsChecked.Value); this._host.AllOccupancyEvent.Add(capturedOccupancyEvent.Name, capturedOccupancyEvent); simulator_OP.ReportProgress -= this.updateProgressBar; break; case EvaluationEventType.Mandatory: if (!this._host.AgentMandatoryScenario.IsReadyForPerformance()) { MessageBox.Show(this._host.AgentMandatoryScenario.Message, "Incomplete Scenario", MessageBoxButton.OK, MessageBoxImage.Error); return; } this._host.AgentMandatoryScenario.LoadQueues(this._host.AllActivities, 0.0); var simulator_MAN = new SpatialAnalysis.Agents.MandatoryScenario.MandatoryScenarioSimulation(this._host, timeStep, duration); //register report progress event simulator_MAN.ReportProgress += this.updateProgressBar; capturedOccupancyEvent = simulator_MAN.CaptureEvent(this._includedataEvents.IsChecked.Value, this._includeVisualEvents.IsChecked.Value, this._includeActivityEngagementEvents.IsChecked.Value, (int)double.Parse(this._pointPerSeconds.Text), _dataFieldName.Text, this._trailDataFileAddress, this._host.VisualEventSettings, this._visibilityExists.IsChecked.Value, this._analyzeFrequency.IsChecked.Value); this._host.AllOccupancyEvent.Add(capturedOccupancyEvent.Name, capturedOccupancyEvent); simulator_MAN.ReportProgress -= this.updateProgressBar; break; } this._closeBtm.IsEnabled = true; }
// load the data before creating the mesh private void loadData() { #region load cells and their values if (this._selection.SelectedSpatialData.Type == DataType.SpatialData) { SpatialDataField dataField = this._selection.SelectedSpatialData as SpatialDataField; if (!this._selection.VisualizeCost) { this.cellToValue = (dataField).Data; } else { this.cellToValue = new Dictionary <Cell, double>(); foreach (Cell item in dataField.Data.Keys) { double val = dataField.GetCost(dataField.Data[item]); this.cellToValue.Add(item, val); } } } else { this.cellToValue = this._selection.SelectedSpatialData.Data; } #endregion #region load max value and min value and z scale this.MaxValue = double.NegativeInfinity; this.MinValue = double.PositiveInfinity; foreach (KeyValuePair <Cell, double> item in this.cellToValue) { if (this.MinValue > item.Value) { this.MinValue = item.Value; } if (this.MaxValue < item.Value) { this.MaxValue = item.Value; } } double sizeOfFloor = Math.Min( this._host.cellularFloor.TopRight.U - this._host.cellularFloor.Origin.U, this._host.cellularFloor.TopRight.V - this._host.cellularFloor.Origin.V); double maxHeight = this.MaxValue - this.MinValue; if (maxHeight > sizeOfFloor) { this.SuggestedZScale = sizeOfFloor / maxHeight; } else { this.SuggestedZScale = 1; } #endregion #region load point3d this.point3DAndCell = new Map <Point3D, Cell>(); foreach (KeyValuePair <Cell, double> item in this.cellToValue) { Point3D pnt = new Point3D(item.Key.U, item.Key.V, item.Value - this.MinValue);// + SpatialDataToMesh.Epsilon); this.point3DAndCell.Add(item.Key, pnt); } #endregion }
/// <summary> /// calculated the static cost of the selected spatial data fields. /// </summary> /// <returns></returns> public Dictionary <Cell, double> GetStaticCost() { /*Get the cost of the spatial data*/ double minimumSpatialValue = 1.0d; List <SpatialDataField> includedData = new List <SpatialDataField>(); foreach (Function function in this.AllSpatialDataFields.Values) { SpatialDataField dataField = function as SpatialDataField; if (dataField != null) { if (dataField.IncludeInActivityGeneration /*&& * dataField.Name != CellularFloor.DistanceFromEdgesOfField && * dataField.Name != CellularFloor.DistanceFromPhysicalBarriers && * dataField.Name != CellularFloor.DistanceFromVisualBarriers*/) { includedData.Add(dataField); } } } var staticCost = new Dictionary <Cell, double>(); double min = double.PositiveInfinity; foreach (Cell cell in this.Cells) { if (cell.FieldOverlapState == OverlapState.Inside) { double cost = 0; foreach (SpatialDataField dataField in includedData) { if (dataField.Data.ContainsKey(cell)) { cost += dataField.GetCost(dataField.Data[cell]); } else { throw new ArgumentException("Data field does not include value for the given cell"); } min = Math.Min(min, cost); } staticCost.Add(cell, cost); } } if (double.IsInfinity(min)) { foreach (Cell item in staticCost.Keys.ToArray()) { staticCost[item] = minimumSpatialValue; } } else { foreach (Cell item in staticCost.Keys.ToArray()) { staticCost[item] -= (min - minimumSpatialValue); } } includedData.Clear(); //apply barrierCostFactor /* * var distanceFromEdgesOfField = this.AllSpatialDataFields[CellularFloor.DistanceFromEdgesOfField]; * if (distanceFromEdgesOfField.IncludeInActivityGeneration) includedData.Add(distanceFromEdgesOfField); * * var distanceFromPhysicalBarriers = this.AllSpatialDataFields[CellularFloor.DistanceFromPhysicalBarriers]; * if (distanceFromPhysicalBarriers.IncludeInActivityGeneration) includedData.Add(distanceFromPhysicalBarriers); * * var distanceFromVisualBarriers = this.AllSpatialDataFields[CellularFloor.DistanceFromVisualBarriers]; * if (distanceFromVisualBarriers.IncludeInActivityGeneration) includedData.Add(distanceFromVisualBarriers); * * if (includedData.Count != 0) * { * foreach (Cell cell in staticCost.Keys.ToArray()) * { * double costFactor = 1; * foreach (SpatialDataField dataField in includedData) * { * if (dataField.Data.ContainsKey(cell)) * { * costFactor += dataField.GetCost(dataField.Data[cell]); * } * else * { * throw new ArgumentException("Data field does not include barrier cost value for the given cell"); * } * } * staticCost[cell] *= costFactor; * } * } * includedData.Clear(); */ includedData = null; return(staticCost); }
private void done_Click(object sender, RoutedEventArgs e) { if (string.IsNullOrEmpty(this._addData._dataName.Text)) { MessageBox.Show("Enter Data Field Name"); return; } if (this._host.cellularFloor.AllSpatialDataFields.ContainsKey(this._addData._dataName.Text)) { MessageBox.Show("The Data Field Name Exists. Try a Different Name..."); return; } if (this._addData._defaultValueMethod.IsChecked.Value) { double globalValue = 0; if (!double.TryParse(this._addData.dataValue.Text, out globalValue)) { MessageBox.Show("Cannot Read the Default Value"); return; } Dictionary <Cell, double> values = new Dictionary <Cell, double>(); foreach (Cell item in this._host.cellularFloor.Cells) { if (item.FieldOverlapState != OverlapState.Outside) { values.Add(item, globalValue); } } if (this._barriers != null) { for (int i = 0; i < this._barriers.Count; i++) { var indices = this._host.cellularFloor.GetIndicesInsideBarrier(this._barriers[i], .0000001); foreach (Index index in indices) { var cell = this._host.cellularFloor.FindCell(index); if (cell != null) { if (cell.FieldOverlapState != OverlapState.Outside) { if (values.ContainsKey(cell)) { values[cell] = this._regionValues[i]; } else { values.Add(cell, this._regionValues[i]); } } } } } } SpatialDataField newData = new SpatialDataField(this._addData._dataName.Text, values); this._host.cellularFloor.AddSpatialDataField(newData); } else //this._addData._interpolationMethod.IsChecked.Value == true; { if (this._barriers.Count == 0) { MessageBox.Show("At least one region needs to be defined"); return; } double value = 0; if (!double.TryParse(this._addData.regionValue.Text, out value)) { MessageBox.Show("Enter a valid value for the region!"); return; } double r = 0; if (!double.TryParse(this._addData._range.Text, out r)) { MessageBox.Show("'Neighborhood Size' should be a number larger than 1", "Missing Input", MessageBoxButton.OK, MessageBoxImage.Information); return; } int range = (int)r; if (range < 1) { MessageBox.Show("'Neighborhood Size' should be a number larger than 1", "Missing Input", MessageBoxButton.OK, MessageBoxImage.Information); return; } if (this._host.FieldGenerator == null || this._host.FieldGenerator.Range != range) { this._host.FieldGenerator = new SpatialDataCalculator(this._host, range, OSMDocument.AbsoluteTolerance); } //test the interpolation function if (!this._addData.LoadFunction()) { return; } //creating heap and labeled collections var destinations = new HashSet <Index>(); for (int i = 0; i < this._barriers.Count; i++) { var indices = this._host.cellularFloor.GetIndicesInsideBarrier(this._barriers[i], OSMDocument.AbsoluteTolerance); destinations.UnionWith(indices); } if (destinations.Count == 0) { MessageBox.Show("Select destination cells for interpolation!"); return; } SpatialDataField newData = this._host.FieldGenerator.GetSpatialDataField(destinations, value, this._addData._dataName.Text, this._addData.InterpolationFunction); this._host.cellularFloor.AddSpatialDataField(newData); } this.terminateDataCreation(); }
/// <summary> /// Initializes a new instance of the <see cref="GaussianFilterUI"/> class. /// </summary> /// <param name="host">The main document to which this window belongs</param> public GaussianFilterUI(OSMDocument host) { InitializeComponent(); this._host = host; this.Owner = this._host; TextBlock cellularDataNames = new TextBlock() { Text = "Data".ToUpper(), FontSize = 14, FontWeight = FontWeights.Bold, Foreground = new SolidColorBrush(Colors.DarkGray) }; this.dataNames.Items.Add(cellularDataNames); foreach (Function item in this._host.cellularFloor.AllSpatialDataFields.Values) { SpatialDataField data = item as SpatialDataField; if (data != null) { this.dataNames.Items.Add(data); } } TextBlock fieldNames = new TextBlock() { Text = "Activity".ToUpper(), FontSize = 14, FontWeight = FontWeights.Bold, Foreground = new SolidColorBrush(Colors.DarkGray) }; if (this._host.AllActivities.Count > 0) { this.dataNames.Items.Add(fieldNames); foreach (KeyValuePair <string, Activity> item in this._host.AllActivities) { this.dataNames.Items.Add(item.Value); } } TextBlock eventNames = new TextBlock { Text = "Occupancy Events".ToUpper(), FontSize = 14, FontWeight = FontWeights.Bold, Foreground = new SolidColorBrush(Colors.DarkGray) }; if (this._host.AllOccupancyEvent.Count > 0) { this.dataNames.Items.Add(eventNames); foreach (SpatialAnalysis.Events.EvaluationEvent item in this._host.AllOccupancyEvent.Values) { this.dataNames.Items.Add(item); } } TextBlock simulationNames = new TextBlock { Text = "Simulation Results".ToUpper(), FontSize = 14, FontWeight = FontWeights.Bold, Foreground = new SolidColorBrush(Colors.DarkGray) }; if (this._host.AllSimulationResults.Count > 0) { this.dataNames.Items.Add(simulationNames); foreach (SimulationResult item in this._host.AllSimulationResults.Values) { this.dataNames.Items.Add(item); } } if (this._host.ViewBasedGaussianFilter != null) { this._range.Text = this._host.ViewBasedGaussianFilter.Range.ToString(); } this.Loaded += GuassianFilterUI_Loaded; this.dataNames.SelectionChanged += dataNames_SelectionChanged; this._apply.Click += _apply_Click; this._cancel.Click += _cancel_Click; this.dataNames.SelectionChanged += DataNames_SelectionChanged; }
/// <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); }
/// <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_); }
void getEscapeRoute_Click(object sender, RoutedEventArgs e) { if (this.Visibility != System.Windows.Visibility.Visible) { this.hide_Show(); } //set the escape Route Type var result = MessageBox.Show("Do you want to simplify the escape routes?", "Set Escape Route Type", MessageBoxButton.YesNo, MessageBoxImage.Question); switch (result) { case MessageBoxResult.No: this._escapeRouteType = EscapeRouteType.All; break; case MessageBoxResult.Yes: this._escapeRouteType = EscapeRouteType.WeightedAndSimplified; var setting = new SimplifiedEspaceRouteSetting(this._host); setting.Owner = this._host; setting.ShowDialog(); setting = null; #region Calculating static costs List <SpatialDataField> includedData = new List <SpatialDataField>(); foreach (Function function in this._host.cellularFloor.AllSpatialDataFields.Values) { SpatialDataField dataField = function as SpatialDataField; if (dataField != null) { if (dataField.IncludeInActivityGeneration) { includedData.Add(dataField); } } } this._staticCosts = new Dictionary <Cell, double>(); foreach (Cell item in this._host.cellularFloor.Cells) { if (item.FieldOverlapState == OverlapState.Inside) { double cost = 0; foreach (SpatialDataField dataField in includedData) { cost += dataField.GetCost(dataField.Data[item]); } this._staticCosts.Add(item, cost); } } #endregion break; default: break; } this._host.Menues.IsEnabled = false; this._host.UIMessage.Text = "Click on your desired vantage point on screen"; this._host.UIMessage.Visibility = Visibility.Visible; this._host.Cursor = Cursors.Pen; this._host.FloorScene.MouseLeftButtonDown += getEscapeRoute_MouseLeftButtonDown; this._host.MouseBtn.MouseDown += releaseGetEscapeRouteIsovist; }
private void _run_Click(object sender, RoutedEventArgs e) { #region Validate simulates annealing parameters int iterationCount = 0; if (!int.TryParse(this._numberOfIterations.Text, out iterationCount)) { this.invalidInput("Number of Iterations"); return; } if (iterationCount <= 0) { this.valueSmallerThanZero("Number of Iterations"); return; } this._iterationCount = iterationCount; double minimumEnergy = 0; if (!double.TryParse(this._minimumTemperature.Text, out minimumEnergy)) { this.invalidInput("Minimum Temperature"); return; } if (minimumEnergy < 0) { MessageBox.Show("'Minimum Temperature' should not be smaller than zero!", "Invalid Input", MessageBoxButton.OK, MessageBoxImage.Error); return; } double maximumEnergy = 0; if (!double.TryParse(this._maximumTemperature.Text, out maximumEnergy)) { this.invalidInput("Maximum Temperature"); return; } if (maximumEnergy <= 0) { this.valueSmallerThanZero("Maximum Temperature"); return; } #endregion #region validation of training subset //double trainingRatio = 0; //if (!double.TryParse(this._ratioOfTrainingSubset.Text, out trainingRatio)) //{ // MessageBox.Show("Invalied 'Ratio of Training Subset'", "Invalid Input", // MessageBoxButton.OK, MessageBoxImage.Error); // return; //} //else //{ // if (trainingRatio <= 0 || trainingRatio > 1.0) // { // MessageBox.Show("'Ratio of Training Subset' must be larger than zero and smaller than or equal to 1", // "Invalid Input", MessageBoxButton.OK, MessageBoxImage.Error); // return; // } //} #endregion #region Validate duration and timeStep parameters double timeStep = 0; if (!double.TryParse(this._timeStep.Text, out timeStep)) { MessageBox.Show("Invalid input for 'Time Step'!", "Invalid Input", MessageBoxButton.OK, MessageBoxImage.Error); return; } else { if (timeStep <= 0) { MessageBox.Show("'Time Step' must be larger than zero!", "Invalid Input", MessageBoxButton.OK, MessageBoxImage.Error); return; } } this._timeStepValue = timeStep; this._durationValue = this._host.trailVisualization.AgentWalkingTrail.TimeIntervalBetweenInterpolatedStates;//convert seconds to hours #endregion #region Check to see if spatial data has been included int spatialDataCount = 0; foreach (Function function in this._host.cellularFloor.AllSpatialDataFields.Values) { SpatialDataField dataField = function as SpatialDataField; if (dataField != null) { if (dataField.IncludeInActivityGeneration) { spatialDataCount++; } } } if (spatialDataCount == 0) { var res = MessageBox.Show("There is no a spatial data field included to calculate cost/desirability!"); return; } #endregion #region extracting the ralated parameters and checking to see if number of parameter is not zero this.AllParameters = new HashSet <Parameter>(); if (this._isoExternalDepth.IsChecked.Value) { this.AllParameters.Add(this._host.Parameters[AgentParameters.OPT_IsovistExternalDepth.ToString()]); } if (this._numberOfDestinations.IsChecked.Value) { this.AllParameters.Add(this._host.Parameters[AgentParameters.OPT_NumberOfDestinations.ToString()]); } if (this._velocityMagnetude.IsChecked.Value) { this.AllParameters.Add(this._host.Parameters[AgentParameters.GEN_VelocityMagnitude.ToString()]); } if (this._angularVelocity.IsChecked.Value) { this.AllParameters.Add(this._host.Parameters[AgentParameters.GEN_AngularVelocity.ToString()]); } if (this._bodySize.IsChecked.Value) { this.AllParameters.Add(this._host.Parameters[AgentParameters.GEN_BodySize.ToString()]); } if (this._accelerationMagnitude.IsChecked.Value) { this.AllParameters.Add(this._host.Parameters[AgentParameters.GEN_AccelerationMagnitude.ToString()]); } if (this._barrierRepulsionRange.IsChecked.Value) { this.AllParameters.Add(this._host.Parameters[AgentParameters.GEN_BarrierRepulsionRange.ToString()]); } if (this._repulsionChangeRate.IsChecked.Value) { this.AllParameters.Add(this._host.Parameters[AgentParameters.GEN_MaximumRepulsion.ToString()]); } if (this._barrierFriction.IsChecked.Value) { this.AllParameters.Add(this._host.Parameters[AgentParameters.GEN_BarrierFriction.ToString()]); } if (this._bodyElasticity.IsChecked.Value) { this.AllParameters.Add(this._host.Parameters[AgentParameters.GEN_AgentBodyElasticity.ToString()]); } if (this._visibilityAngle.IsChecked.Value) { this.AllParameters.Add(this._host.Parameters[AgentParameters.GEN_VisibilityAngle.ToString()]); } if (this._decisionMakingPeriodLamdaFactor.IsChecked.Value) { this.AllParameters.Add(this._host.Parameters[AgentParameters.OPT_DecisionMakingPeriodLambdaFactor.ToString()]); } if (this._angleDistributionLambdaFactor.IsChecked.Value) { this.AllParameters.Add(this._host.Parameters[AgentParameters.OPT_AngleDistributionLambdaFactor.ToString()]); } if (this._desirabilityDistributionLambdaFactor.IsChecked.Value) { this.AllParameters.Add(this._host.Parameters[AgentParameters.OPT_DesirabilityDistributionLambdaFactor.ToString()]); } foreach (var item in this._host.Parameters) { foreach (var function in item.Value.LinkedFunctions) { if (function.IncludeInActivityGeneration) { this.AllParameters.Add(item.Value); break; } } } if (this.AllParameters.Count == 0) { MessageBox.Show("No parameter is included to account for the variability in the optimization process", "Parameter Not Assigned", MessageBoxButton.OK, MessageBoxImage.Error); return; } #endregion //execute visibility changes in the interface Dispatcher.Invoke(new Action(() => { this._run_close.SetValue(Button.VisibilityProperty, System.Windows.Visibility.Collapsed); this._run_close.SetValue(Button.ContentProperty, "Close"); this._mainInterface.SetValue(Grid.VisibilityProperty, System.Windows.Visibility.Collapsed); this._progressPanel.SetValue(StackPanel.VisibilityProperty, System.Windows.Visibility.Visible); }), DispatcherPriority.ContextIdle); //unregister run button event this._run_close.Click -= this._run_Click; //create annealing SimulatedAnnealingSolver solver = new SimulatedAnnealingSolver(this.AllParameters); //register UI update event for best fitness changes solver.BestFitnessUpdated += solver_BestFitnessUpdated; //register UI update event for fitness changes solver.FitnessUpdated += solver_FitnessUpdated; //Setting the initial iteration to zero this._counter = 0; //initializing the trial visualization this._host.trailVisualization.InitiateTrainingVisualization(); //running the annealing process solver.Solve(minimumEnergy, maximumEnergy, iterationCount, this.measureFitnessWithInterfaceUpdate); //unregister UI update event for fitness changes solver.BestFitnessUpdated -= solver_BestFitnessUpdated; //unregister UI update event for fitness changes solver.FitnessUpdated -= solver_FitnessUpdated; //showing the close btn. The close event is not registered yet Dispatcher.Invoke(new Action(() => { this._run_close.SetValue(Button.VisibilityProperty, System.Windows.Visibility.Visible); }), DispatcherPriority.ContextIdle); //updating the FreeNavigationAgentCharacters this._host.FreeNavigationAgentCharacter = FreeNavigationAgent.Create(this._host.trailVisualization.AgentWalkingTrail.InterpolatedStates[0]); //Show the last parameter setting on UI this._sb.Clear(); foreach (var item in this.AllParameters) { this._sb.AppendLine(item.ToString()); } this._updateMessage.SetValue(TextBlock.TextProperty, this._sb.ToString()); //set Window closing events this._run_close.Click += (s, e1) => { var result = MessageBox.Show("Do you want to clear the training data from screen?", "", MessageBoxButton.YesNo, MessageBoxImage.Exclamation); if (result == MessageBoxResult.Yes) { this._host.trailVisualization.TerminateTrainingVisualization(); } this.Close(); }; }
void _run_Click(object sender, RoutedEventArgs e) { #region Validate activity related input if (this._applyFilter.IsChecked.Value) { int gr = 0; if (!int.TryParse(this._gaussianRangeDefault.Text, out gr)) { MessageBox.Show("Invalid input for Gaussian filter range"); return; } else { if (gr < 2) { MessageBox.Show("Gaussian filter range should be larger than 1!"); return; } else { this._gaussianRange = gr; } } if (this._host.ViewBasedGaussianFilter.Range != gr) { this._host.ViewBasedGaussianFilter = new IsovistClippedGaussian(this._host.cellularFloor, gr); } } int _r = 0; if (!int.TryParse(this._neighborhoodRangePotential.Text, out _r)) { MessageBox.Show("Invalid input for potential field calculation range!"); return; } else { if (_r < 1) { MessageBox.Show("Potential field calculation range should be larger than 0!"); return; } else { if (this._host.FieldGenerator.Range != _r) { this._host.FieldGenerator = new Data.Visualization.SpatialDataCalculator(this._host, _r, OSMDocument.AbsoluteTolerance); } } } #endregion #region Validate simulates annealing parameters int iterationCount = 0; if (!int.TryParse(this._numberOfIterations.Text, out iterationCount)) { this.invalidInput("Number of Iterations"); return; } if (iterationCount <= 0) { this.valueSmallerThanZero("Number of Iterations"); return; } this._iterationCount = iterationCount; double minimumEnergy = 0; if (!double.TryParse(this._minimumTemperature.Text, out minimumEnergy)) { this.invalidInput("Minimum Temperature"); return; } if (minimumEnergy < 0) { MessageBox.Show("'Minimum Temperature' should not be smaller than zero!", "Invalid Input", MessageBoxButton.OK, MessageBoxImage.Error); return; } double maximumEnergy = 0; if (!double.TryParse(this._maximumTemperature.Text, out maximumEnergy)) { this.invalidInput("Maximum Temperature"); return; } if (maximumEnergy <= 0) { this.valueSmallerThanZero("Maximum Temperature"); return; } #endregion #region validation of training subset //double trainingRatio = 0; //if(!double.TryParse(this._ratioOfTrainingSubset.Text, out trainingRatio)) //{ // MessageBox.Show("Invalied 'Ratio of Training Subset'", "Invalid Input", // MessageBoxButton.OK, MessageBoxImage.Error); // return; //} //else //{ // if(trainingRatio<=0 || trainingRatio>1.0) // { // MessageBox.Show("'Ratio of Training Subset' must be larger than zero and smaller than or equal to 1", // "Invalid Input", MessageBoxButton.OK, MessageBoxImage.Error); // return; // } //} #endregion #region Validate duration and timeStep parameters double timeStep = 0; if (!double.TryParse(this._timeStep.Text, out timeStep)) { MessageBox.Show("Invalid input for 'Time Step'!", "Invalid Input", MessageBoxButton.OK, MessageBoxImage.Error); return; } else { if (timeStep <= 0) { MessageBox.Show("'Time Step' must be larger than zero!", "Invalid Input", MessageBoxButton.OK, MessageBoxImage.Error); return; } } this._timeStepValue = timeStep; this._durationValue = this._host.trailVisualization.AgentWalkingTrail.TimeIntervalBetweenInterpolatedStates;//convert seconds to hours #endregion #region Check to see if spatial data has been included int spatialDataCount = 0; foreach (Function function in this._host.cellularFloor.AllSpatialDataFields.Values) { SpatialDataField dataField = function as SpatialDataField; if (dataField != null) { if (dataField.IncludeInActivityGeneration) { spatialDataCount++; } } } if (spatialDataCount == 0) { var res = MessageBox.Show("There is no a spatial data field included to calculate cost/desirability!"); return; } #endregion #region extracting the ralated parameters and checking to see if number of parameter is not zero this.AllParameters = new HashSet <Parameter>(); if (this._velocityMagnetude.IsChecked.Value) { this.AllParameters.Add(this._host.Parameters[AgentParameters.GEN_VelocityMagnitude.ToString()]); } if (this._angularVelocity.IsChecked.Value) { this.AllParameters.Add(this._host.Parameters[AgentParameters.GEN_AngularVelocity.ToString()]); } if (this._bodySize.IsChecked.Value) { this.AllParameters.Add(this._host.Parameters[AgentParameters.GEN_BodySize.ToString()]); } if (this._accelerationMagnitude.IsChecked.Value) { this.AllParameters.Add(this._host.Parameters[AgentParameters.GEN_AccelerationMagnitude.ToString()]); } if (this._barrierRepulsionRange.IsChecked.Value) { this.AllParameters.Add(this._host.Parameters[AgentParameters.GEN_BarrierRepulsionRange.ToString()]); } if (this._repulsionChangeRate.IsChecked.Value) { this.AllParameters.Add(this._host.Parameters[AgentParameters.GEN_MaximumRepulsion.ToString()]); } if (this._barrierFriction.IsChecked.Value) { this.AllParameters.Add(this._host.Parameters[AgentParameters.GEN_BarrierFriction.ToString()]); } if (this._bodyElasticity.IsChecked.Value) { this.AllParameters.Add(this._host.Parameters[AgentParameters.GEN_AgentBodyElasticity.ToString()]); } if (this._angularDeviationCost.IsChecked.Value) { this.AllParameters.Add(this._host.Parameters[AgentParameters.MAN_AngularDeviationCost.ToString()]); } if (this._distanceCost.IsChecked.Value) { this.AllParameters.Add(this._host.Parameters[AgentParameters.MAN_DistanceCost.ToString()]); } foreach (var item in this._host.Parameters) { foreach (var function in item.Value.LinkedFunctions) { if (function.IncludeInActivityGeneration) { this.AllParameters.Add(item.Value); break; } } } if (this.AllParameters.Count == 0) { MessageBox.Show("No parameter is included to account for the variability in the optimization process", "Parameter Not Assigned", MessageBoxButton.OK, MessageBoxImage.Error); return; } #endregion #region Trail Related Stuff this._trailIndices = new HashSet <Index>(); foreach (var item in this._host.trailVisualization.AgentWalkingTrail.ApproximatedPoints) { Index index = this._host.cellularFloor.FindIndex(item); if (this._host.cellularFloor.Cells[index.I, index.J].FieldOverlapState != OverlapState.Inside) { MessageBox.Show("The training process cannot proceed with this trail. Parts of the trail are not included in the walkable field!", "Invalid Trail", MessageBoxButton.OK, MessageBoxImage.Exclamation); return; } else { this._trailIndices.Add(index); } } this._trailIndices = CellUtility.ExpandInWalkableField(this._host.cellularFloor, this._trailIndices); this._defaultState = this._host.trailVisualization.AgentWalkingTrail.InterpolatedStates[this._host.trailVisualization.AgentWalkingTrail.InterpolatedStates.Length - 1]; this._cellDestination = this._host.cellularFloor.FindCell(this._defaultState.Location); UV p1 = this._cellDestination; var p2 = p1 + UV.UBase * this._host.cellularFloor.CellSize; var p3 = p1 + UV.UBase * this._host.cellularFloor.CellSize + UV.VBase * this._host.cellularFloor.CellSize; var p4 = p1 + UV.VBase * this._host.cellularFloor.CellSize; this._destination = new BarrierPolygon(new UV[] { p1, p2, p3, p4 }); #endregion //execute visibility changes in the interface Dispatcher.Invoke(new Action(() => { this._run_close.SetValue(Button.VisibilityProperty, System.Windows.Visibility.Collapsed); this._run_close.SetValue(Button.ContentProperty, "Close"); this._mainInterface.SetValue(Grid.VisibilityProperty, System.Windows.Visibility.Collapsed); this._progressPanel.SetValue(StackPanel.VisibilityProperty, System.Windows.Visibility.Visible); }), DispatcherPriority.ContextIdle); //unregister run button event this._run_close.Click -= this._run_Click; //create annealing SimulatedAnnealingSolver solver = new SimulatedAnnealingSolver(this.AllParameters); //register UI update event for best fitness changes solver.BestFitnessUpdated += solver_BestFitnessUpdated; //register UI update event for fitness changes solver.FitnessUpdated += solver_FitnessUpdated; //Setting the initial iteration to zero this._counter = 0; //initializing the trial visualization this._host.trailVisualization.InitiateTrainingVisualization(); //running the annealing process solver.Solve(minimumEnergy, maximumEnergy, iterationCount, this.measureFitnessWithInterfaceUpdate); //unregister UI update event for fitness changes solver.BestFitnessUpdated -= solver_BestFitnessUpdated; //unregister UI update event for fitness changes solver.FitnessUpdated -= solver_FitnessUpdated; //showing the close btn. The close event is not registered yet Dispatcher.Invoke(new Action(() => { this._run_close.SetValue(Button.VisibilityProperty, System.Windows.Visibility.Visible); }), DispatcherPriority.ContextIdle); //Show the last parameter setting on UI this._sb.Clear(); foreach (var item in this.AllParameters) { this._sb.AppendLine(item.ToString()); } this._updateMessage.SetValue(TextBlock.TextProperty, this._sb.ToString()); //set Window closing events this._run_close.Click += (s, e1) => { var result = MessageBox.Show("Do you want to clear the training data from screen?", "", MessageBoxButton.YesNo, MessageBoxImage.Exclamation); if (result == MessageBoxResult.Yes) { this._host.trailVisualization.TerminateTrainingVisualization(); } this.Close(); }; }
void _done_Click1(object sender, RoutedEventArgs e) { #region validate input double externalDepth; if (!double.TryParse(this.IsovistExternalDepth.Text, out externalDepth)) { MessageBox.Show("Inappropriate input for external isovist depth"); return; } if (externalDepth <= 0) { MessageBox.Show("External isovist depth should be larger than zero"); return; } try { this._host.Parameters[AgentParameters.OPT_IsovistExternalDepth.ToString()].Value = externalDepth; } catch (Exception error) { MessageBox.Show(error.Report()); return; } int num; if (!int.TryParse(this.AngleIntercept.Text, out num)) { MessageBox.Show("Inappropriate input for 'Maximum Number of Destinations in Isovist Perimeter'"); return; } if (num <= 19) { MessageBox.Show("'Maximum Number of Destinations in Isovist Perimeter' should be larger than 20"); return; } try { this._host.Parameters[AgentParameters.OPT_NumberOfDestinations.ToString()].Value = num; } catch (Exception error) { MessageBox.Show(error.Report()); return; } #endregion #region Check if spatial data has been assigned to the static cost int includedData = 0; foreach (Function function in this._host.cellularFloor.AllSpatialDataFields.Values) { SpatialDataField dataField = function as SpatialDataField; if (dataField != null) { if (dataField.IncludeInActivityGeneration) { includedData++; } } } if (includedData == 0) { var res = MessageBox.Show("There is no a spatial data with a defined cost method assigned to the calculation of the 'Escape Routes'.\nDo you want to continue?", "Spatial Data Cost", MessageBoxButton.YesNo, MessageBoxImage.Warning); if (res == MessageBoxResult.No) { return; } } var staticCost = this._host.cellularFloor.GetStaticCost(); #endregion #region Calculate var allAgentScapeRoutes = new List <AgentEscapeRoutes>(); foreach (Cell item in this._host.cellularFloor.Cells) { if (item.BarrierBufferOverlapState == OverlapState.Outside) { allAgentScapeRoutes.Add(new AgentEscapeRoutes(item)); } } if (allAgentScapeRoutes.Count == 0) { MessageBox.Show("There is no cell out of barrier buffers"); this._done.Content = "Close"; this._done.Click -= _done_Click1; this._done.Click += _done_Click2; return; } this.progressState.Visibility = System.Windows.Visibility.Visible; this.progressBar.Maximum = allAgentScapeRoutes.Count; this.IsEnabled = false; this._cancelWindow.Visibility = Visibility.Collapsed; var timer = new System.Diagnostics.Stopwatch(); timer.Start(); /* * foreach (var item in allAgentScapeRoutes) * { * item.ComputeDestinations(this._host.AgentIsovistExternalDepth, this._host.AgentIsovistInternalDepth, * this._host.MaximumNumberOfDestinations, this._host.cellularFloor, staticCost, filter, 0.0000001d); * } */ Parallel.ForEach(allAgentScapeRoutes, (a) => { //step 1 a.ComputeDestinations(this._host.AgentIsovistExternalDepth, this._host.MaximumNumberOfDestinations, this._host.cellularFloor, staticCost, 0.0000001d); Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback) delegate { double val = this.progressBar.Value + 1; this.progressBar.SetValue(ProgressBar.ValueProperty, val); } , null); Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback) delegate { double x = this.progressBar.Value / this.progressBar.Maximum; int percent = (int)(x * 100); int minutes = (int)Math.Floor(timer.Elapsed.TotalMinutes); int seconds = (int)(timer.Elapsed.Seconds); string message = string.Format("{0} minutes and {1} seconds\n%{2} completed", minutes.ToString(), seconds.ToString(), percent.ToString()); this.report.SetValue(TextBlock.TextProperty, message); } , null); Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, new Action(() => { })).Wait(TimeSpan.FromMilliseconds(1)); }); var t = timer.Elapsed.TotalMilliseconds; timer.Stop(); this.IsEnabled = true; #endregion int nulls = 0; Dictionary <Cell, AgentEscapeRoutes> data = new Dictionary <Cell, AgentEscapeRoutes>(); foreach (var item in allAgentScapeRoutes) { if (item.Destinations == null) { nulls++; } else { data.Add(item.VantageCell, item); } } allAgentScapeRoutes.Clear(); allAgentScapeRoutes = null; staticCost.Clear(); staticCost = null; //includedData.Clear(); //includedData = null; this.progressState.Visibility = System.Windows.Visibility.Collapsed; StringBuilder sb = new StringBuilder(); int min = (int)Math.Floor(timer.Elapsed.TotalMinutes); int sec = (int)(timer.Elapsed.Seconds); int average = (int)(timer.Elapsed.TotalMilliseconds * 1000 / progressBar.Maximum); sb.AppendLine("Escape Route Analysis Results:".ToUpper()); sb.AppendLine(string.Format("Analyzed Isovists: \t\t{0}", ((int)progressBar.Maximum).ToString())); sb.AppendLine(string.Format("Blind Access Isovists: \t{0}", nulls.ToString())); sb.AppendLine(string.Format("Total Time: \t\t{0} Min and {1} Sec", min.ToString(), sec.ToString())); sb.AppendLine(string.Format("Average Time: \t\t{0} MS (per isovist)", (((double)average) / 1000).ToString())); string text = sb.ToString(); this.finalReport.Visibility = System.Windows.Visibility.Visible; this.finalReport.Text = text; this._done.Content = "Close"; this._done.Click -= _done_Click1; this._done.Click += _done_Click2; this._host.AgentScapeRoutes = data; if (nulls != 0) { this._visualize.Visibility = System.Windows.Visibility.Visible; this._visualize.Click += _visualize_Click; } }
/// <summary> /// Initializes a new instance of the <see cref="SpatialDataFieldSelection"/> class. /// </summary> /// <param name="host">The main document to which this class belongs.</param> /// <param name="title">The title.</param> /// <param name="allowForMultipleSelections">if set to <c>true</c> multiple selections is allowed.</param> public SpatialDataFieldSelection(OSMDocument host, string title, bool allowForMultipleSelections) { InitializeComponent(); this._host = host; this._title.Text = title; if (allowForMultipleSelections) { this.dataNames.SelectionMode = SelectionMode.Multiple; } else { this.dataNames.SelectionMode = SelectionMode.Single; } this.cellularDataNames = new TextBlock() { Text = "Data".ToUpper(), FontSize = 14, FontWeight = FontWeights.Bold, Foreground = new SolidColorBrush(Colors.DarkGray) }; this.dataNames.Items.Add(this.cellularDataNames); foreach (Function item in this._host.cellularFloor.AllSpatialDataFields.Values) { SpatialDataField data = item as SpatialDataField; if (data != null) { this.dataNames.Items.Add(data); } } this.fieldNames = new TextBlock() { Text = "Activity".ToUpper(), FontSize = 14, FontWeight = FontWeights.Bold, Foreground = new SolidColorBrush(Colors.DarkGray) }; if (this._host.AllActivities.Count > 0) { this.dataNames.Items.Add(this.fieldNames); foreach (KeyValuePair <string, Activity> item in this._host.AllActivities) { this.dataNames.Items.Add(item.Value); } } this._eventNames = new TextBlock { Text = "Occupancy Events".ToUpper(), FontSize = 14, FontWeight = FontWeights.Bold, Foreground = new SolidColorBrush(Colors.DarkGray) }; if (this._host.AllOccupancyEvent.Count > 0) { this.dataNames.Items.Add(this._eventNames); foreach (SpatialAnalysis.Events.EvaluationEvent item in this._host.AllOccupancyEvent.Values) { this.dataNames.Items.Add(item); } } this.dataNames.SelectionChanged += dataNames_SelectionChanged; this.Result = false; this.AllSelectedSpatialData = new List <ISpatialData>(); this.Loaded += dataSelection_Loaded; this.KeyDown += new KeyEventHandler(_dataSelection_KeyDown); }
/// <summary> /// Initializes a new instance of the <see cref="SelectDataFor2DVisualization"/> class. /// </summary> /// <param name="cellularFloor">The cellular floor.</param> /// <param name="allActivities">All activities.</param> /// <param name="allEvents">All events.</param> public SelectDataFor2DVisualization(OSMDocument host) { InitializeComponent(); this._host = host; this._colorStep.Text = this._host.ColorCode.Steps.ToString(); this.VisualizeCost = false; this.Loaded += new RoutedEventHandler(SelectDataForVisualization_Loaded); this.dataNames.SelectionMode = SelectionMode.Single; this._selectedItem.Text = string.Empty; var cellularDataNames = new TextBlock() { Text = "Spatial Data".ToUpper(), FontSize = 14, FontWeight = FontWeights.Bold, Foreground = new SolidColorBrush(Colors.DarkGray) }; this.dataNames.Items.Add(cellularDataNames); foreach (Function item in this._host.cellularFloor.AllSpatialDataFields.Values) { SpatialDataField data = item as SpatialDataField; if (data != null) { this.dataNames.Items.Add(data.Name); } } if (this._host.AllActivities.Count > 0) { var fieldNames = new TextBlock() { Text = "Activities".ToUpper(), FontSize = 14, FontWeight = FontWeights.Bold, Foreground = new SolidColorBrush(Colors.DarkGray) }; this.dataNames.Items.Add(fieldNames); foreach (var item in this._host.AllActivities.Values) { this.dataNames.Items.Add(item.Name); } } if (this._host.AllOccupancyEvent.Count > 0) { var eventNames = new TextBlock { Text = "Occupancy Events".ToUpper(), FontSize = 14, FontWeight = FontWeights.Bold, Foreground = new SolidColorBrush(Colors.DarkGray) }; this.dataNames.Items.Add(eventNames); foreach (var item in this._host.AllOccupancyEvent.Values) { this.dataNames.Items.Add(item.Name); } } if (this._host.AllSimulationResults.Count > 0) { var simulationResults = new TextBlock { Text = "Simulation Results".ToUpper(), FontSize = 14, FontWeight = FontWeights.Bold, Foreground = new SolidColorBrush(Colors.DarkGray) }; this.dataNames.Items.Add(simulationResults); foreach (var item in this._host.AllSimulationResults.Values) { this.dataNames.Items.Add(item.Name); } } this.dataNames.SelectionChanged += dataNames_SelectionChanged; this.KeyDown += SelectDataFor2DVisualization_KeyDown; }