static void Main(string[] args) { try { GravityModel grav = new GravityModel("egm96", ""); double lat = 27.99, lon0 = 86.93, h = 8820; // Mt Everest { // Slow method of evaluating the values at several points on a circle of // latitude. for (int i = -5; i <= 5; ++i) { double lon = lon0 + i * 0.2; double gx, gy, gz; grav.Gravity(lat, lon, h, out gx, out gy, out gz); Console.WriteLine(String.Format("{0} {1} {2} {3}", lon, gx, gy, gz)); } } { // Fast method of evaluating the values at several points on a circle of // latitude using GravityCircle. GravityCircle circ = grav.Circle(lat, h, GravityModel.Mask.ALL); for (int i = -5; i <= 5; ++i) { double lon = lon0 + i * 0.2; double gx, gy, gz; circ.Gravity(lon, out gx, out gy, out gz); Console.WriteLine(String.Format("{0} {1} {2} {3}", lon, gx, gy, gz)); } } } catch (GeographicErr e) { Console.WriteLine(String.Format("Caught exception: {0}", e.Message)); } }
public void Load(BinaryReader br, int major, int minor, MapInternals.Ground gnd) { if ((major == 1 && minor >= 3) || major > 1) { _name = br.ReadCString(40); _animationType = br.ReadInt32(); _animationSpeed = br.ReadSingle(); if (_animationSpeed < 0.0F || _animationSpeed >= 100.0F) { _animationSpeed = 1.0F; } _blockType = br.ReadInt32(); } _modelName = br.ReadCString(80); _nodeName = br.ReadCString(80); _position.X = br.ReadSingle(); _position.Y = br.ReadSingle(); _position.Z = br.ReadSingle(); _rotation.X = br.ReadSingle(); _rotation.Y = br.ReadSingle(); _rotation.Z = br.ReadSingle(); _scale.X = br.ReadSingle(); _scale.Y = br.ReadSingle(); _scale.Z = br.ReadSingle(); _model = SharedInformation.ContentManager.Load <GravityModel>(@"data\model\" + _modelName); }
public GravityPoint(GravityModel model, Level level) : base(model, level.World, LoadAnimation(model.texture)) { switch (model.orientation) { case "Down": gravity = VelocityValues.Instance.GravityDown; break; case "Up": gravity = VelocityValues.Instance.GravityUp; break; case "Left": gravity = VelocityValues.Instance.GravityLeft; break; case "Right": gravity = VelocityValues.Instance.GravityRight; break; } Enabled = true; Body.Awake = false; Body.IgnoreCCD = true; Body.CollisionCategories = Collide.Instance.None; Body.CollidesWith = Collide.Instance.None; platman = level.Platman; }
public SparseTwinIndex <float> Distribute(SparseArray <float> productions, SparseArray <float> attractions) { var zoneSystem = this.Parent.ZoneSystem; var zoneArray = zoneSystem.ZoneArray; var flatZones = zoneArray.GetFlatData(); ZoneX = zoneArray.CreateSimilarArray <float>(); var flatX = ZoneX.GetFlatData(); ZoneY = zoneArray.CreateSimilarArray <float>(); var flatY = ZoneY.GetFlatData(); var numberOfZones = flatZones.Length; for (int i = 0; i < numberOfZones; i++) { var zone = flatZones[i]; flatX[i] = zone.X; flatY[i] = zone.Y; } SparseTwinIndex <float> data; if (this.UseGPU) { float[] friction = this.ComputeFriction(flatX, flatY, flatZones); data = new GPUGravityModel(friction, UpdateProgress, this.Epsilon, this.MaxBalanceIterations).ProcessFlow(productions, attractions); } else { var validZones = zoneArray.ValidIndexies().ToArray(); data = new GravityModel(FrictionFunction, UpdateProgress, this.Epsilon, this.MaxBalanceIterations).ProcessFlow(productions, attractions, validZones); } this.Progress = 1; return(data); }
private void OnSelectGravityModel(object sender, EventArgs e) { OpenFileDialog dlg = new OpenFileDialog(); dlg.Filter = "Gravity Model (*.egm)|*.egm"; dlg.DefaultExt = "egm"; if (dlg.ShowDialog() == DialogResult.Cancel) { return; } m_path = dlg.FileName.Substring(0, dlg.FileName.LastIndexOf('\\')).Replace('\\', '/'); int length = dlg.FileName.LastIndexOf('.') - dlg.FileName.LastIndexOf('\\') - 1; m_name = dlg.FileName.Substring(dlg.FileName.LastIndexOf('\\') + 1, length); try { m_gm = new GravityModel(m_name, m_path); m_gravityModelNameTextBox.Text = dlg.FileName; m_nameTextBox.Text = m_gm.GravityModelName; m_descriptionTextBox.Text = m_gm.Description; m_dateTextBox.Text = m_gm.DateTime; m_updateButton.Enabled = true; m_normGravButton.Enabled = true; m_GravityCircleButton.Enabled = true; m_validateButton.Enabled = true; } catch (Exception xcpt) { MessageBox.Show(xcpt.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
GravityView MakeGravityView(GravityModel gravityModel) { var gravityView = ResourceCache.Instantiate <GravityView>(gravityModel.Name, gravities.transform); gravityView.UpdateModel(gravityModel); gravityView.transform.localPosition = new Vector2(gravityModel.Position.col * gemSize.x, gravityModel.Position.row * gemSize.y); return(gravityView); }
public void LoadData() { var production = GetData(Production, UnloadProduction); var attraction = GetData(Attraction, UnloadAttraction); var friction = GetData(Friction, UnloadFriction); ApplyBalance(ref production, ref attraction); var model = new GravityModel(friction, (p) => Progress = p, MaximumError, MaxIterations); Data = model.ProcessFlow(production, attraction, production.ValidIndexArray()); }
public void Test_Evaluate(string coord, double height, double GX, double GY, double GZ) { var c = new GeoCoords(coord); var model = new GravityModel("egm96", Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "gravity")); { var(_, gx, gy, gz) = model.Gravity(c.Latitude, c.Longitude, height); Assert.AreEqual(GX, gx, 1e-5); Assert.AreEqual(GY, gy, 1e-5); Assert.AreEqual(GZ, gz, 1e-5); } }
public void Test_LoadModel() { var model = new GravityModel("egm96", Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "gravity")); { Assert.AreEqual("Earth Gravity Model 1996", model.Description); Assert.AreEqual(DateTime.Parse("1997-01-01"), model.DateTime); Assert.AreEqual("egm96", model.GravityModelName); Assert.AreEqual(3986004.418e8, model.MassConstant); Assert.AreEqual(7292115e-11, model.AngularVelocity); } }
private IEnumerable <SparseTwinIndex <float> > CPUDoublyConstrained(IZone[] zones, IEnumerator <SparseArray <float> > ep, IEnumerator <SparseArray <float> > ea, IEnumerator <IDemographicCategory> ec) { float completed = 0f; var frictionSparse = this.Root.ZoneSystem.ZoneArray.CreateSquareTwinArray <float>(); var productions = new List <SparseArray <float> >(); var attractions = new List <SparseArray <float> >(); var cats = new List <IDemographicCategory>(); // We need to pre load all of our generations in order to handle blending properly while (ep.MoveNext() & ea.MoveNext() & ec.MoveNext()) { productions.Add(ep.Current); attractions.Add(ea.Current); cats.Add(ec.Current); } var ret = this.Root.ZoneSystem.ZoneArray.CreateSquareTwinArray <float>(); SparseArray <float> production = this.Root.ZoneSystem.ZoneArray.CreateSimilarArray <float>(); SparseArray <float> attraction = this.Root.ZoneSystem.ZoneArray.CreateSimilarArray <float>(); this.CurrentMultiSetIndex = -1; foreach (var multiset in this.MultiBlendSets) { this.CurrentMultiSetIndex++; var numberOfSubsets = multiset.Subsets.Count; var productionSet = new float[numberOfSubsets][][]; var attractionSet = new float[numberOfSubsets][][]; var multiCatSet = new IDemographicCategory[numberOfSubsets][]; SetupFrictionData(productions, attractions, cats, multiset, productionSet, attractionSet, multiCatSet); this.ComputeFriction(zones, multiCatSet, productionSet, attractionSet, frictionSparse.GetFlatData(), production.GetFlatData(), attraction.GetFlatData()); string balanceFileName; SparseArray <float> balanceFactors = GetWarmBalancingFactors(attraction, out balanceFileName); if (this.CullSmallValues) { var tempValues = new GravityModel(frictionSparse, null, this.Epsilon, this.MaxIterations) .ProcessFlow(production, attraction, production.ValidIndexArray(), balanceFactors); this.Cull(tempValues, frictionSparse.GetFlatData(), production.GetFlatData(), attraction.GetFlatData()); if (!String.IsNullOrWhiteSpace(this.SaveFrictionFileName)) { this.SaveFriction(frictionSparse.GetFlatData()); } } yield return(new GravityModel(frictionSparse, (p => this.Progress = (p * (1f / (this.MultiBlendSets.Count)) + (completed / (this.MultiBlendSets.Count)))), this.Epsilon, this.MaxIterations) .ProcessFlow(production, attraction, production.ValidIndexArray(), balanceFactors)); if (balanceFileName != null) { SaveBalanceFactors(balanceFileName, balanceFactors); } completed += 1f; } }
static void Main(string[] args) { try { GravityModel grav = new GravityModel("egm96",""); double lat = 27.99, lon = 86.93, h = 8820; // Mt Everest double gx, gy, gz; grav.Gravity(lat, lon, h, out gx, out gy, out gz); Console.WriteLine(String.Format("{0} {1} {2}", gx, gy, gz)); } catch (GeographicErr e) { Console.WriteLine(String.Format("Caught exception: {0}", e.Message)); } }
public object Load(Stream stream, string assetName) { GravityModel model = new GravityModel(); if (!model.Load(stream)) { return(false); } stream.Close(); return(model); }
static void Main(string[] args) { try { GravityModel grav = new GravityModel("egm96", ""); double lat = 27.99, lon = 86.93, h = 8820; // Mt Everest double gx, gy, gz; grav.Gravity(lat, lon, h, out gx, out gy, out gz); Console.WriteLine(String.Format("{0} {1} {2}", gx, gy, gz)); } catch (GeographicErr e) { Console.WriteLine(String.Format("Caught exception: {0}", e.Message)); } }
public void TestSimpleGravityModelSolution() { var data = CreateData(); var gm = new GravityModel(data, null, 0.0f, 300); var o = SparseArray <float> .CreateSparseArray(new[] { 1, 2 }, new float[] { 2, 2 }); var d = SparseArray <float> .CreateSparseArray(new[] { 1, 2 }, new[] { 1.5f, 2.5f }); var ret = gm.ProcessFlow(o, d, new[] { 1, 2 }); var result = ret.GetFlatData(); Assert.AreEqual(0.5f, result[0][0], 0.0001f); Assert.AreEqual(1.5f, result[0][1], 0.0001f); Assert.AreEqual(1f, result[1][0], 0.0001f); Assert.AreEqual(1f, result[1][1], 0.0001f); }
private void button8_Click(object sender, EventArgs e) { ts2 = new CancellationTokenSource(); ct2 = ts2.Token; ct_p = ts_p.Token; tabControl1.SelectedTab = tabControl1.TabPages[1]; this.Refresh(); ReferenceSystem.Default def = (ReferenceSystem.Default)listBox1.SelectedItem; відмінитиПоточнуОпераціюToolStripMenuItem.Enabled = true; var task = Task.Factory.StartNew(() => { addText("Обчислення розпочато...\r\n"); string file = SphericalHarmonicAnalyze.Properties.Settings.Default.inGravityModel; GravityModel gm = new GravityModel(SphericalHarmonicAnalyze.Properties.Settings.Default.modelMaxOrder); gm.loadFromFile(SphericalHarmonicAnalyze.Properties.Settings.Default.inGravityModel, new setProgressDel(addVal)); ReferenceSystem elipsoid = new ReferenceSystem(def); elipsoid.gridParameters.cellSize = SphericalHarmonicAnalyze.Properties.Settings.Default.GridCellSize; elipsoid.gridParameters.coLatitudeBounds = SphericalHarmonicAnalyze.Properties.Settings.Default.minCoLatitude; elipsoid.maxDegree = SphericalHarmonicAnalyze.Properties.Settings.Default.modelMaxOrder; int greedColumnsCount, greedRowsCount; List <double[]> greed = MathFunc.generateGrid(elipsoid.gridParameters.cellSize, out greedColumnsCount, out greedRowsCount, SphericalHarmonicAnalyze.Properties.Settings.Default.minCoLatitude, SphericalHarmonicAnalyze.Properties.Settings.Default.maxCoLatitude, SphericalHarmonicAnalyze.Properties.Settings.Default.longW, SphericalHarmonicAnalyze.Properties.Settings.Default.longE); addText("Колонок: {0}\r\n", greed.Count); double[][] h_dg = GravityModel.getGeoidHeightAndAnomalys(elipsoid, gm, greed, d: new setProgressDel(addVal), ct: ct2, ct2: ct_p); if (ct2.IsCancellationRequested) { addText("Перервано...\r\n"); addVal(0, 1, ""); Thread.CurrentThread.Abort(); } ; addText("dg обчислено\r\n"); IOFunc.writeGeoidHeightsAndAnomalysToTxt(greed, h_dg[0], h_dg[1], elipsoid, file + "B_L_N_dg.txt"); addText("Готово...\r\nРезультати записано в файл: " + file + "NEW____________B_L_N_dg.txt\r\n"); }, ct2); var t3 = Task.Factory.StartNew(() => { label1: if (task.IsCompleted) { if (checkBox1.Checked) { System.Diagnostics.Process.Start("rundll32.exe", "powrprof.dll,SetSuspendState 0,1,0"); } ; } else { task.Wait(); goto label1; } }); }
private void OnValidate(object sender, EventArgs e) { try { double lon = -86.0; double lat = 32.0; double alt = 0.0; double x, y, z; GravityModel gm = new GravityModel(m_name, m_path); gm.Disturbance(lat, lon, alt, out x, out y, out z); gm.GeoidHeight(lat, lon); gm.Gravity(lat, lon, alt, out x, out y, out z); gm.Phi(5000000.0, 5000000.0, out x, out y); gm.SphericalAnomaly(lat, lon, alt, out x, out y, out z); gm.T(5000000.0, 5000000.0, 5000000.0); gm.U(5000000.0, 5000000.0, 5000000.0, out x, out y, out z); gm.V(5000000.0, 5000000.0, 5000000.0, out x, out y, out z); gm.W(5000000.0, 5000000.0, 5000000.0, out x, out y, out z); NormalGravity ng = new NormalGravity(NormalGravity.StandardModels.GRS80); ng = new NormalGravity(NormalGravity.StandardModels.WGS84); ng = new NormalGravity(6378137.0, 3.986005e+14, 7.292115147e-5, 1.08263e-3, false); ng = gm.ReferenceEllipsoid(); ng.DynamicalFormFactor(1); Geocentric geo = ng.Earth(); ng.Gravity(lat, alt, out x, out z); ng.Phi(5000000.0, 5000000.0, out x, out y); ng.SurfaceGravity(lat); ng.U(5000000.0, 5000000.0, 5000000.0, out x, out y, out z); ng.V0(5000000.0, 5000000.0, 5000000.0, out x, out y, out z); GravityCircle gc = gm.Circle(lat, 0.0, GravityModel.Mask.ALL); gc.Capabilities(); gc.Capabilities(GravityModel.Mask.GRAVITY); gc.Disturbance(lon, out x, out y, out z); gc.GeoidHeight(lon); gc.Gravity(lon, out x, out y, out z); gc.SphericalAnomaly(lon, out x, out y, out z); gc.T(lon); gc.V(lon, out x, out y, out z); gc.W(lon, out x, out y, out z); MessageBox.Show("No errors detected", "OK", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception xcpt) { MessageBox.Show(xcpt.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private void toolStripButton2_Click(object sender, EventArgs e) { ReferenceSystem elipsoid = new ReferenceSystem(ReferenceSystem.Default.WGS84); elipsoid.gridParameters.cellSize = 30d; elipsoid.gridParameters.coLatitudeBounds = 15D; elipsoid.maxDegree = 100; double[] gmN = GravityModel.generateNormalModel(elipsoid, 10); GravityModel gm = new GravityModel(100); gm.loadFromFile(SphericalHarmonicAnalyze.Properties.Settings.Default.inGravityModel, new setProgressDel(addVal)); int greedColumnsCount, greedRowsCount; GravityModel gm2 = new GravityModel(gm); List <double[]> greed = MathFunc.generateGrid(elipsoid.gridParameters.cellSize, out greedColumnsCount, out greedRowsCount, elipsoid.gridParameters.coLatitudeBounds); double[] h = GravityModel.getGeoidHeight(elipsoid, gm2, greed); double[] dg = GravityModel.getAnomaly(elipsoid, gm, greed); IOFunc.writeGeoidHeightsAndAnomalysToTxt(greed, h, dg, elipsoid, "result.txt"); }
private void обчисленняЗаВихідноюМоделлюToolStripMenuItem_Click(object sender, EventArgs e) { tabControl1.SelectedTab = tabControl1.TabPages[1]; this.Refresh(); var task = Task.Factory.StartNew(() => { addText("Обчислення розпочато...\r\n"); string file = SphericalHarmonicAnalyze.Properties.Settings.Default.inGravityModel; GravityModel gm = new GravityModel(SphericalHarmonicAnalyze.Properties.Settings.Default.modelMaxOrder); gm.loadFromFile(SphericalHarmonicAnalyze.Properties.Settings.Default.inGravityModel, new setProgressDel(addVal)); ReferenceSystem elipsoid = new ReferenceSystem(ReferenceSystem.Default.WGS84); elipsoid.gridParameters.cellSize = SphericalHarmonicAnalyze.Properties.Settings.Default.GridCellSize; elipsoid.gridParameters.coLatitudeBounds = SphericalHarmonicAnalyze.Properties.Settings.Default.minCoLatitude; elipsoid.maxDegree = SphericalHarmonicAnalyze.Properties.Settings.Default.modelMaxOrder; int greedColumnsCount, greedRowsCount; List <double[]> greed = MathFunc.generateGrid(elipsoid.gridParameters.cellSize, out greedColumnsCount, out greedRowsCount, elipsoid.gridParameters.coLatitudeBounds); double[] h = GravityModel.getGeoidHeight(elipsoid, gm, greed); double[] dg = GravityModel.getAnomaly(elipsoid, gm, greed); IOFunc.writeGeoidHeightsAndAnomalysToTxt(greed, h, dg, elipsoid, file + "B_L_N_dg.txt"); addText("Готово...\r\nРезультати записано в файл: " + file + "B_L_N_dg.txt"); }); }
public GravityPage() { Model = new GravityModel { IsSupported = GravitySensor.IsSupported, SensorCount = GravitySensor.Count }; InitializeComponent(); if (Model.IsSupported) { Gravity = new GravitySensor(); Gravity.DataUpdated += Gravity_DataUpdated; Gravity.AccuracyChanged += Gravity_AccuracyChanged; canvas.Series = new List <Series>() { new Series() { Color = SKColors.Red, Name = "X", FormattedText = "X={0:f2}m/s^2", }, new Series() { Color = SKColors.Green, Name = "Y", FormattedText = "Y={0:f2}m/s^2", }, new Series() { Color = SKColors.Blue, Name = "Z", FormattedText = "Z={0:f2}m/s^2", }, }; } }
private void initCampaignDataSources() { #region Assign sensor model references accelerometerModel = new AccelerometerModel { IsSupported = Accelerometer.IsSupported, SensorCount = Accelerometer.Count }; gravityModel = new GravityModel { IsSupported = GravitySensor.IsSupported, SensorCount = GravitySensor.Count }; gyroscopeModel = new GyroscopeModel { IsSupported = Gyroscope.IsSupported, SensorCount = Gyroscope.Count }; hRMModel = new HRMModel { IsSupported = HeartRateMonitor.IsSupported, SensorCount = HeartRateMonitor.Count }; humidityModel = new HumidityModel { IsSupported = HumiditySensor.IsSupported, SensorCount = HumiditySensor.Count }; lightModel = new LightModel { IsSupported = LightSensor.IsSupported, SensorCount = LightSensor.Count }; linearAccelerationModel = new LinearAccelerationModel { IsSupported = LinearAccelerationSensor.IsSupported, SensorCount = LinearAccelerationSensor.Count }; magnetometerModel = new MagnetometerModel { IsSupported = Magnetometer.IsSupported, SensorCount = Magnetometer.Count }; orientationModel = new OrientationModel { IsSupported = OrientationSensor.IsSupported, SensorCount = OrientationSensor.Count }; pressureModel = new PressureModel { IsSupported = PressureSensor.IsSupported, SensorCount = PressureSensor.Count }; proximityModel = new ProximityModel { IsSupported = ProximitySensor.IsSupported, SensorCount = ProximitySensor.Count }; temperatureModel = new TemperatureModel { IsSupported = TemperatureSensor.IsSupported, SensorCount = TemperatureSensor.Count }; ultravioletModel = new UltravioletModel { IsSupported = UltravioletSensor.IsSupported, SensorCount = UltravioletSensor.Count }; #endregion #region Assign sensor references and sensor measurement event handlers if (accelerometerModel.IsSupported) { accelerometer = new Accelerometer(); accelerometer.PausePolicy = SensorPausePolicy.None; accelerometer.Interval = Tools.DEFAULT_SENSOR_SAMPLING_INTERVAL; accelerometer.DataUpdated += storeAccelerometerDataCallback; sensorMap[Tools.ACCELEROMETER] = accelerometer; } if (gravityModel.IsSupported) { gravity = new GravitySensor(); gravity.PausePolicy = SensorPausePolicy.None; gravity.Interval = Tools.DEFAULT_SENSOR_SAMPLING_INTERVAL; gravity.DataUpdated += storeGravitySensorDataCallback; sensorMap[Tools.GRAVITY] = gravity; } if (gyroscopeModel.IsSupported) { gyroscope = new Gyroscope(); gyroscope.PausePolicy = SensorPausePolicy.None; gyroscope.Interval = Tools.DEFAULT_SENSOR_SAMPLING_INTERVAL; gyroscope.DataUpdated += storeGyroscopeDataCallback; sensorMap[Tools.GYROSCOPE] = gyroscope; } if (hRMModel.IsSupported) { hRM = new HeartRateMonitor(); hRM.PausePolicy = SensorPausePolicy.None; hRM.Interval = Tools.DEFAULT_SENSOR_SAMPLING_INTERVAL; hRM.DataUpdated += storeHeartRateMonitorDataCallback; sensorMap[Tools.HRM] = hRM; } if (humidityModel.IsSupported) { humidity = new HumiditySensor(); humidity.PausePolicy = SensorPausePolicy.None; humidity.Interval = Tools.DEFAULT_SENSOR_SAMPLING_INTERVAL; humidity.DataUpdated += storeHumiditySensorDataCallback; sensorMap[Tools.HUMIDITY] = humidity; } if (lightModel.IsSupported) { light = new LightSensor(); light.PausePolicy = SensorPausePolicy.None; light.Interval = Tools.DEFAULT_SENSOR_SAMPLING_INTERVAL; light.DataUpdated += storeLightSensorDataCallback; sensorMap[Tools.LIGHT] = light; } if (linearAccelerationModel.IsSupported) { linearAcceleration = new LinearAccelerationSensor(); linearAcceleration.PausePolicy = SensorPausePolicy.None; linearAcceleration.Interval = Tools.DEFAULT_SENSOR_SAMPLING_INTERVAL; linearAcceleration.DataUpdated += storeLinearAccelerationSensorDataCallback; sensorMap[Tools.LINEARACCELERATION] = linearAcceleration; } if (magnetometerModel.IsSupported) { magnetometer = new Magnetometer(); magnetometer.PausePolicy = SensorPausePolicy.None; magnetometer.Interval = Tools.DEFAULT_SENSOR_SAMPLING_INTERVAL; magnetometer.DataUpdated += storeMagnetometerDataCallback; sensorMap[Tools.MAGNETOMETER] = magnetometer; } if (orientationModel.IsSupported) { orientation = new OrientationSensor(); orientation.PausePolicy = SensorPausePolicy.None; orientation.Interval = Tools.DEFAULT_SENSOR_SAMPLING_INTERVAL; orientation.DataUpdated += storeOrientationSensorDataCallback; sensorMap[Tools.ORIENTATION] = orientation; } if (pressureModel.IsSupported) { pressure = new PressureSensor(); pressure.PausePolicy = SensorPausePolicy.None; pressure.Interval = Tools.DEFAULT_SENSOR_SAMPLING_INTERVAL; pressure.DataUpdated += storePressureSensorDataCallback; sensorMap[Tools.PRESSURE] = pressure; } if (proximityModel.IsSupported) { proximity = new ProximitySensor(); proximity.PausePolicy = SensorPausePolicy.None; proximity.Interval = Tools.DEFAULT_SENSOR_SAMPLING_INTERVAL; proximity.DataUpdated += storeProximitySensorDataCallback; sensorMap[Tools.PROXIMITY] = proximity; } if (temperatureModel.IsSupported) { temperature = new TemperatureSensor(); temperature.PausePolicy = SensorPausePolicy.None; temperature.Interval = Tools.DEFAULT_SENSOR_SAMPLING_INTERVAL; temperature.DataUpdated += storeTemperatureSensorDataCallback; sensorMap[Tools.TEMPERATURE] = temperature; } if (ultravioletModel.IsSupported) { ultraviolet = new UltravioletSensor(); ultraviolet.PausePolicy = SensorPausePolicy.None; ultraviolet.Interval = Tools.DEFAULT_SENSOR_SAMPLING_INTERVAL; ultraviolet.DataUpdated += storeUltravioletSensorDataCallback; sensorMap[Tools.ULTRAVIOLET] = ultraviolet; } #endregion loadCampaignSettings(); }
private void button4_Click(object sender, EventArgs e) { Action fileProc = () => { System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); MathNet.Numerics.Control.LinearAlgebraProvider = new MathNet.Numerics.Algorithms.LinearAlgebra.Mkl.MklLinearAlgebraProvider(); MathNet.Numerics.Control.NumberOfParallelWorkerThreads = Environment.ProcessorCount; addText("Обробка файлу вимірювань...\r\n"); double[][] SGG_data = null; if (System.IO.File.Exists("sgg_data.bin")) { SGG_data = IOFunc.binLoad_SGG_data("sgg_data.bin"); } else { SGG_data = Data.IOFunc.read_SGG_data(SphericalHarmonicAnalyze.Properties.Settings.Default.SGG_measures, new setProgressDel(addVal)); IOFunc.binwrite_SGG_data("sgg_data.bin", SGG_data); } addText("Дані вимірювань оброблено: {0} шт.\r\n", SGG_data.Length); Thread.Sleep(500); ReferenceSystem elipsoid = new ReferenceSystem(ReferenceSystem.Default.TideFree); elipsoid.gridParameters.cellSize = SphericalHarmonicAnalyze.Properties.Settings.Default.GridCellSize; elipsoid.gridParameters.coLatitudeBounds = SphericalHarmonicAnalyze.Properties.Settings.Default.minCoLatitude; elipsoid.maxDegree = SphericalHarmonicAnalyze.Properties.Settings.Default.modelMaxOrder; int greedColumnsCount, greedRowsCount; List <double[]> greed = MathFunc.generateGrid(elipsoid.gridParameters.cellSize, out greedColumnsCount, out greedRowsCount, elipsoid.gridParameters.coLatitudeBounds, 180 - elipsoid.gridParameters.coLatitudeBounds); addText("Сітку згенеровано: {0} комірок \r\n", greed.Count); double avgR = MathFunc.getAvgRadius(SGG_data); List <int>[] map = MathFunc.getMappingOfPoints(elipsoid, SGG_data, greed.ToArray(), greedRowsCount, greedColumnsCount, avgR); sw.Stop(); addText("Точки віднесено до комірок сітки за: {0}.\r\n", sw.Elapsed.ToString()); addText("Кількість клітинок сітки всього: {0}\r\n", greed.Count); int res1 = 0; foreach (var item in map) { res1 += item.Count; } addText("Використано вимірів: {0}\r\nСер радіус: {1}\r\n", res1, avgR); test.checkMap(SGG_data, map, greed, elipsoid); List <int>[] newMap = null; MathFunc.checkGreed(ref greed, map, out newMap); addText("Кількість клітинок сітки, в яких присутні дані вимірювань: {0}\r\n", greed.Count); map = newMap; newMap = null; IOFunc.writeGreedToCsvFileWithMeasureCount(greed, map, "greed_new_map.txt"); double[] avgRadius; sw.Restart(); double[] regularisedValues = MathFunc.regularization(SGG_data, greed.ToArray(), map, out avgRadius); sw.Stop(); addText("Регуляризація (на основі сферичної відстані) виконана за: {0}.\r\n", sw.Elapsed.ToString()); IOFunc.writeGreedToCsvFileWithMeasureS(greed, regularisedValues, "greed_regular_grad.txt"); avgRadius[0] = Math.Round(avgRadius[0]); elipsoid.satelliteSphere = avgRadius[0]; addText("Середній радіус: {0,10:0.000}.\r\nМінімальний радіус: {1,10:0.0000}\r\nМаксимальний радіус:{2,10:0.0000}\r\n", avgRadius[0], avgRadius[1], avgRadius[2]); SGG_data = null; map = null; int[][] t_nm = MathFunc.get_nm(elipsoid.maxDegree); sw.Restart(); MathNet.Numerics.LinearAlgebra.Double.DenseMatrix dm = new MathNet.Numerics.LinearAlgebra.Double.DenseMatrix(greed.Count, (MathFunc.getArraySize(elipsoid.maxDegree) - 3) * 2 - (elipsoid.maxDegree - 1)); sw.Stop(); addText("Пам'ять для матриці коефіцієнтів виділено за: {0}.\r\n", sw.Elapsed.ToString()); sw.Restart(); int progress = 0; //Обчислення елементів матриці var p = Parallel.For(0, dm.RowCount, (i) => { double[] line = MathFunc.getCoefMatrixLineKoop(elipsoid, elipsoid.maxDegree, t_nm, elipsoid.satelliteSphere, greed[i][0], greed[i][1]); lock (dm) { dm.SetRow(i, line); } progress++; if (progress / 100D == Math.Round(progress / 100D)) { addVal(progress, dm.RowCount, "Визначено"); } }); if (!p.IsCompleted) { throw new Exception("Parallel.For"); } ; IOFunc.writeMatrixToMatLabFile(dm, @"matlab\A.mat", "A"); sw.Stop(); richTextBox1.Invoke(new setProgressDel(addVal), new object[] { 0, dm.RowCount, "" }); addText("Матриця {0} на {1} ({2}MB) згенерована за: {3,10}\r\n", dm.RowCount, dm.ColumnCount, dm.ColumnCount * dm.RowCount * 8 / 1000000, sw.Elapsed.ToString() /* + "\r\nЗапис у файл...\r\n"*/); if (true) { GravityModel gm08 = new GravityModel(elipsoid.maxDegree); gm08.loadFromFile("GO_CONS_EGM_GCF_2.gfc", new setProgressDel(addVal)); MathNet.Numerics.LinearAlgebra.Double.DenseVector dmL = new MathNet.Numerics.LinearAlgebra.Double.DenseVector(gm08.getGradientForGrid(elipsoid, greed));//regularisedValues); MathNet.Numerics.LinearAlgebra.Double.DenseVector dmL2; GravityModel gm = new GravityModel(elipsoid.maxDegree); if (radioButton1.Checked) { sw.Restart(); gm.loadFromFile(SphericalHarmonicAnalyze.Properties.Settings.Default.inGravityModel, new setProgressDel(addVal)); sw.Stop(); addText("Вихідна модель завантажена за: {0}.\r\n", sw.Elapsed.ToString()); sw.Restart(); dmL2 = new MathNet.Numerics.LinearAlgebra.Double.DenseVector(gm.getGradientForGrid(elipsoid, greed)); sw.Stop(); addText("Градієнти за вихідною моделлю обчислені для сітки за: {0}.\r\n", sw.Elapsed.ToString()); } else { sw.Restart(); gm = GravityModel.getNormalModel(elipsoid, elipsoid.maxDegree); dmL2 = new MathNet.Numerics.LinearAlgebra.Double.DenseVector(gm.getGradientForGrid(elipsoid, greed)); sw.Stop(); addText("Нормальні градієнти обчислені для сітки за: {0}.\r\n", sw.Elapsed.ToString()); } dmL = dmL - dmL2; dmL2 = null; IOFunc.writeMatrixToMatLabFile(dmL.ToColumnMatrix(), @"matlab\L.mat", "L"); sw.Restart(); MathNet.Numerics.LinearAlgebra.Double.DenseVector dmLNormal = null; dmLNormal = (MathNet.Numerics.LinearAlgebra.Double.DenseVector)dm.TransposeThisAndMultiply(dmL); dmL = null; IOFunc.writeMatrixToMatLabFile(dmLNormal.ToColumnMatrix(), @"matlab\LNorm.mat", "LNorm"); sw.Stop(); addText("Стовпчик вільних членів обчислений за: {0}.\r\n", sw.Elapsed.ToString()); MathNet.Numerics.LinearAlgebra.Double.DenseMatrix dmANorm = null; sw.Restart(); dmANorm = (MathNet.Numerics.LinearAlgebra.Double.DenseMatrix)dm.TransposeThisAndMultiply(dm); dm = null; sw.Stop(); addText("Нормальна матриця коефіціэнтів обчислена за: {0}.\r\n", sw.Elapsed.ToString()); IOFunc.writeMatrixToMatLabFile(dmANorm, @"matlab\ANorm.mat", "ANorm"); //dmLNormal = (MathNet.Numerics.LinearAlgebra.Double.DenseVector)dmLNormal.Multiply(5e-8); var x = dmANorm.Inverse(); var res = (MathNet.Numerics.LinearAlgebra.Double.DenseVector)x.Multiply(dmLNormal); IOFunc.writeModeVectorlToTxtFile(res, elipsoid, @"matlab\_out.AL"); addText(@"Результат за методом A\L знайдено..."); x = null; GravityModel gm_R = new GravityModel(gm); gm_R.addDeltaCoef(res.ToArray()); res = null; double[] h = GravityModel.getGeoidHeight(elipsoid, gm_R, greed); double[] dg = GravityModel.getAnomaly(elipsoid, gm_R, greed); IOFunc.writeGeoidHeightsAndAnomalysToTxt(greed, h, dg, elipsoid, @"output\result_AL.txt"); IOFunc.writeGravityModelToTxtFile(gm_R, @"output\model_AL.gcf"); sw.Restart(); addText(dmANorm.Rank().ToString() + "\r\n"); dmANorm = null; dmLNormal = null; sw.Stop(); addText("Невідомі знайдено за: {0}.\r\n", sw.Elapsed.ToString()); } }; if (System.IO.File.Exists(SphericalHarmonicAnalyze.Properties.Settings.Default.inGravityModel)) { tabControl1.SelectedTab = tabControl1.TabPages[1]; this.UseWaitCursor = true; ts = new CancellationTokenSource(); ct = ts.Token; tsk = Task.Factory.StartNew(fileProc, ct); var setCur = Task.Factory.StartNew(() => { tsk.Wait(); this.UseWaitCursor = false; addText("Обчислення завершені!"); }); richTextBox1.SaveFile(@"output\zvit.rtf"); } }
private void InitializeFlows() { Progress = 0; // we are going to need to split based on this information ZoneArray = Root.ZoneSystem.ZoneArray; var validZones = ZoneArray.ValidIndexies().ToArray(); //Generate the place of work place of residence OD's SparseArray <float> o = ZoneArray.CreateSimilarArray <float>(); SparseArray <float> d = ZoneArray.CreateSimilarArray <float>(); var numCat = Categories.Count; // Start burning that CPU Thread.CurrentThread.Priority = ThreadPriority.Highest; SparseTwinIndex <float> workplaceDistribution = null; SparseTwinIndex <float> prevWorkplaceDistribution = null; float[] friction; float[] nextFriction = null; for (int i = 0; i < numCat; i++) { CurrentOccupationIndex = i; Task assignToPopulation = null; if (i > 0) { assignToPopulation = new Task(delegate { if (prevWorkplaceDistribution != null) { // We actually are assigning to the previous category with this data so we need i - 1 AssignToWorkers(prevWorkplaceDistribution, Categories[i - 1]); prevWorkplaceDistribution = null; } }); assignToPopulation.Start(); } Task computeNextFriction = null; if (i + 1 < numCat) { computeNextFriction = new Task(delegate { nextFriction = ComputeFriction(ZoneArray.GetFlatData(), Categories[i + 1], nextFriction); }); computeNextFriction.Start(); } Categories[i].Generate(o, d); GravityModel gravityModel = new GravityModel(ImpedenceFunction, (progress => Progress = (progress / numCat) + ((float)i / numCat)), Epsilon, MaxIterations); workplaceDistribution = gravityModel.ProcessFlow(o, d, validZones); Progress = ((float)(i + 1) / numCat); if (assignToPopulation != null) { assignToPopulation.Wait(); assignToPopulation.Dispose(); } if (computeNextFriction != null) { computeNextFriction.Wait(); computeNextFriction.Dispose(); } prevWorkplaceDistribution = workplaceDistribution; friction = nextFriction; nextFriction = friction; } nextFriction = null; prevWorkplaceDistribution = null; AssignToWorkers(workplaceDistribution, Categories[numCat - 1]); // ok now we can relax Thread.CurrentThread.Priority = ThreadPriority.Normal; GC.Collect(); }
private void OnSelectGravityModel(object sender, EventArgs e) { OpenFileDialog dlg = new OpenFileDialog(); dlg.Filter = "Gravity Model (*.egm)|*.egm"; dlg.DefaultExt = "egm"; if (dlg.ShowDialog() == DialogResult.Cancel) return; m_path = dlg.FileName.Substring(0, dlg.FileName.LastIndexOf('\\')).Replace('\\', '/'); int length = dlg.FileName.LastIndexOf('.') - dlg.FileName.LastIndexOf('\\') - 1; m_name = dlg.FileName.Substring(dlg.FileName.LastIndexOf('\\') + 1, length); try { m_gm = new GravityModel(m_name, m_path); m_gravityModelNameTextBox.Text = dlg.FileName; m_nameTextBox.Text = m_gm.GravityModelName; m_descriptionTextBox.Text = m_gm.Description; m_dateTextBox.Text = m_gm.DateTime; m_updateButton.Enabled = true; m_normGravButton.Enabled = true; m_GravityCircleButton.Enabled = true; m_validateButton.Enabled = true; } catch (Exception xcpt) { MessageBox.Show(xcpt.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public void Load(BinaryReader br, int major, int minor, MapInternals.Ground gnd) { if ((major == 1 && minor >= 3) || major > 1) { _name = br.ReadCString(40); _animationType = br.ReadInt32(); _animationSpeed = br.ReadSingle(); if (_animationSpeed < 0.0F || _animationSpeed >= 100.0F) _animationSpeed = 1.0F; _blockType = br.ReadInt32(); } _modelName = br.ReadCString(80); _nodeName = br.ReadCString(80); _position.X = br.ReadSingle(); _position.Y = br.ReadSingle(); _position.Z = br.ReadSingle(); _rotation.X = br.ReadSingle(); _rotation.Y = br.ReadSingle(); _rotation.Z = br.ReadSingle(); _scale.X = br.ReadSingle(); _scale.Y = br.ReadSingle(); _scale.Z = br.ReadSingle(); _model = SharedInformation.ContentManager.Load<GravityModel>(@"data\model\" + _modelName); }
private void OnValidate(object sender, EventArgs e) { try { double lon = -86.0; double lat = 32.0; double alt = 0.0; double x, y, z; GravityModel gm = new GravityModel(m_name,m_path); gm.Disturbance( lat, lon, alt, out x, out y, out z); gm.GeoidHeight(lat,lon); gm.Gravity(lat,lon,alt,out x,out y, out z); gm.Phi(5000000.0,5000000.0,out x,out y); gm.SphericalAnomaly(lat,lon,alt,out x, out y, out z); gm.T(5000000.0,5000000.0,5000000.0); gm.U(5000000.0,5000000.0,5000000.0,out x,out y,out z); gm.V(5000000.0,5000000.0,5000000.0,out x,out y,out z); gm.W(5000000.0,5000000.0,5000000.0,out x,out y,out z); NormalGravity ng = new NormalGravity(NormalGravity.StandardModels.GRS80); ng = new NormalGravity( NormalGravity.StandardModels.WGS84); ng = new NormalGravity(6378137.0,3.986005e+14,7.292115147e-5,-1.0,1.08263e-3); ng = gm.ReferenceEllipsoid(); ng.DynamicalFormFactor(1); Geocentric geo = ng.Earth(); ng.Gravity(lat,alt,out x, out z); ng.Phi(5000000.0,5000000.0,out x,out y); ng.SurfaceGravity(lat); ng.U(5000000.0,5000000.0,5000000.0,out x, out y, out z); ng.V0(5000000.0,5000000.0,5000000.0,out x, out y, out z); GravityCircle gc = gm.Circle(lat,0.0,GravityModel.Mask.ALL); gc.Capabilities(); gc.Capabilities(GravityModel.Mask.GRAVITY); gc.Disturbance(lon, out x, out y, out z); gc.GeoidHeight(lon); gc.Gravity(lon, out x, out y, out z); gc.SphericalAnomaly(lon, out x, out y, out z); gc.T(lon); gc.V(lon, out x, out y, out z); gc.W(lon, out x, out y, out z); MessageBox.Show("No errors detected", "OK", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception xcpt) { MessageBox.Show(xcpt.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public static GravityModel Get(GravityType gravityType, Position position) { var gravityModel = new GravityModel(gravityType, position); return(gravityModel); }
private void InitializeFlows() { this.Progress = 0; // we are going to need to split based on this information this.ZoneArray = this.Root.ZoneSystem.ZoneArray; var occupations = this.Root.Demographics.OccupationCategories; var validZones = this.ZoneArray.ValidIndexies().ToArray(); var numberOfZones = validZones.Length; //[Occupation][O , D] var distribution = occupations.CreateSimilarArray <SparseTwinIndex <float> >(); //Generate the place of work place of residence OD's SparseArray <float> O = this.ZoneArray.CreateSimilarArray <float>(); SparseArray <float> D = this.ZoneArray.CreateSimilarArray <float>(); var occupationIndexes = occupations.ValidIndexies().ToArray(); var numCat = Categories.Count; // Start burning that CPU Thread.CurrentThread.Priority = ThreadPriority.Highest; SparseTwinIndex <float> workplaceDistribution = null; SparseTwinIndex <float> prevWorkplaceDistribution = null; float[] friction = null; float[] nextFriction = null; MultiRunGPUGravityModel multiRunGPU = null; for (int i = 0; i < numCat; i++) { this.CurrentOccupationIndex = i; Task assignToPopulation = null; if (i > 0) { assignToPopulation = new Task(delegate() { if (prevWorkplaceDistribution != null) { // We actually are assigning to the previous category with this data so we need i - 1 AssignToWorkers(prevWorkplaceDistribution, this.Categories[i - 1]); prevWorkplaceDistribution = null; } }); assignToPopulation.Start(); } Task computeNextFriction = null; if (i + 1 < numCat) { computeNextFriction = new Task(delegate() { nextFriction = this.ComputeFriction(ZoneArray.GetFlatData(), this.Categories[i + 1], nextFriction); }); computeNextFriction.Start(); } this.Categories[i].Generate(O, D); if (this.UseGPU) { if (i == 0) { try { Parallel.Invoke(() => friction = this.ComputeFriction(ZoneArray.GetFlatData(), this.Categories[i], friction), () => multiRunGPU = new MultiRunGPUGravityModel(O.GetFlatData().Length, (progress => this.Progress = (progress / numCat) + ((float)i / numCat)), this.Epsilon, this.MaxIterations)); } catch (AggregateException e) { throw new XTMFRuntimeException(e.InnerException.Message + "\r\n" + e.InnerException.StackTrace); } } workplaceDistribution = multiRunGPU.ProcessFlow(friction, O, D); } else { GravityModel gravityModel = new GravityModel(ImpedenceFunction, (progress => this.Progress = (progress / numCat) + ((float)i / numCat)), this.Epsilon, this.MaxIterations); workplaceDistribution = gravityModel.ProcessFlow(O, D, validZones); } this.Progress = ((float)(i + 1) / numCat); if (assignToPopulation != null) { try { assignToPopulation.Wait(); assignToPopulation.Dispose(); assignToPopulation = null; } catch (AggregateException e) { throw new XTMFRuntimeException(e.InnerException.Message + "\r\n" + e.InnerException.StackTrace); } } if (computeNextFriction != null) { try { computeNextFriction.Wait(); computeNextFriction.Dispose(); computeNextFriction = null; } catch (AggregateException e) { throw new XTMFRuntimeException(e.InnerException.Message + "\r\n" + e.InnerException.StackTrace); } } prevWorkplaceDistribution = workplaceDistribution; var frictionTemp = friction; friction = nextFriction; nextFriction = friction; } friction = null; nextFriction = null; prevWorkplaceDistribution = null; if (multiRunGPU != null) { multiRunGPU.Dispose(); multiRunGPU = null; } AssignToWorkers(workplaceDistribution, this.Categories[numCat - 1]); workplaceDistribution = null; // ok now we can relax Thread.CurrentThread.Priority = ThreadPriority.Normal; GC.Collect(); }