/// <summary> /// /// </summary> /// <param name="geo">Establishes geo vs cartesian / Euclidean.</param> /// <param name="calculator">Optional; defaults to Haversine or cartesian depending on units.</param> /// <param name="worldBounds">Optional; defaults to GEO_WORLDBOUNDS or MAX_WORLDBOUNDS depending on units.</param> public SpatialContext(bool geo, DistanceCalculator calculator, Rectangle worldBounds) { this.geo = geo; if (calculator == null) { calculator = IsGeo() ? (DistanceCalculator)new GeodesicSphereDistCalc.Haversine() : new CartesianDistCalc(); } this.calculator = calculator; if (worldBounds == null) { worldBounds = IsGeo() ? new RectangleImpl(-180, 180, -90, 90, this) : new RectangleImpl(-Double.MaxValue, Double.MaxValue,-Double.MaxValue, Double.MaxValue, this); } else { if (IsGeo()) Debug.Assert(worldBounds.Equals(new RectangleImpl(-180, 180, -90, 90, this))); if (worldBounds.GetCrossesDateLine()) throw new ArgumentException("worldBounds shouldn't cross dateline: " + worldBounds, "worldBounds"); } //hopefully worldBounds' rect implementation is compatible this.worldBounds = new RectangleImpl(worldBounds, this); shapeReadWriter = MakeShapeReadWriter(); }
public CachedDistanceFunctionValue(AtomicReader reader, ShapeFieldCacheDistanceValueSource enclosingInstance) { cache = enclosingInstance.provider.GetCache(reader); this.enclosingInstance = enclosingInstance; from = enclosingInstance.from; calculator = enclosingInstance.ctx.GetDistCalc(); nullValue = (enclosingInstance.ctx.IsGeo() ? 180 : double.MaxValue); }
public void CalculateDistanceTest() { DistanceCalculator target = new DistanceCalculator(); // TODO: Initialize to an appropriate value double time = 5; // TODO: Initialize to an appropriate value double speed = 6; // TODO: Initialize to an appropriate value double expected = 30; // TODO: Initialize to an appropriate value double actual; actual = target.CalculateDistance(time, speed); Assert.AreEqual(expected, actual); //Assert.Inconclusive("Verify the correctness of this test method."); }
static DistanceCalculator() { var calculator = new DistanceCalculator(); var distanceData = new DistanceData { DistanceM = 1, Calc = "kilometers" }; calculator.Calculate(distanceData); MilesToKilometers = distanceData.DistanceKm.Value; distanceData.DistanceKm = 1; distanceData.Calc = "miles"; calculator.Calculate(distanceData); KilometersToMiles = distanceData.DistanceM.Value; }
public DistanceDocValues(DistanceValueSource enclosingInstance, IndexReader reader) { this.enclosingInstance = enclosingInstance; ptX = FieldCache_Fields.DEFAULT.GetDoubles(reader, enclosingInstance.strategy.GetFieldNameX()/*, true*/); ptY = FieldCache_Fields.DEFAULT.GetDoubles(reader, enclosingInstance.strategy.GetFieldNameY()/*, true*/); validX = FieldCache_Fields.DEFAULT.GetDocsWithField(reader, enclosingInstance.strategy.GetFieldNameX()); validY = FieldCache_Fields.DEFAULT.GetDocsWithField(reader, enclosingInstance.strategy.GetFieldNameY()); from = enclosingInstance.from; calculator = enclosingInstance.strategy.GetSpatialContext().GetDistCalc(); nullValue = (enclosingInstance.strategy.GetSpatialContext().IsGeo() ? 180 : double.MaxValue); }
public void DistanceCalculation() { var termWeightRepresentation = new Mock<ITermWeightRepresentation>(); termWeightRepresentation.Setup(x => x.TermWeight(It.Is<string>(y => y == "bee"))).Returns(0.91629); termWeightRepresentation.Setup(x => x.TermWeight(It.Is<string>(y => y == "wasp"))).Returns(0.91629); termWeightRepresentation.Setup(x => x.TermWeight(It.Is<string>(y => y == "fly"))).Returns(0.22314); var termsCollection = new TermsCollection(new[] {"bee", "wasp", "fly", "fruit", "like"}); var distanceCalculator = new DistanceCalculator(); double actualDistance = distanceCalculator.CalculateDistance(termWeightRepresentation.Object, termsCollection); Assert.AreEqual(1.314903211, actualDistance, 0.0001); }
protected void btnCalculate_Click(object sender, EventArgs e) { try { DistanceCalculator distanceCalculator = new DistanceCalculator(); lblDistance.Text = distanceCalculator.CalculateDistance (Convert.ToDouble(txtTime.Text), Convert.ToDouble(txtSpeed.Text)).ToString(); } catch (Exception ex) { lblDistance.Text = ex.Message; } }
/// <summary> /// Finds the point on this spline that minimises a given distance function /// </summary> /// <param name="distance"> Distance function </param> /// <param name="iterations"> Number of iterations (accuracy). 5 is pretty good. </param> /// <returns> Returns the time on the spline of the closest point </returns> public override float FindClosestPoint( DistanceToPointDelegate distance, int iterations ) { DistanceCalculator calculator = new DistanceCalculator( distance ); float closestFraction = 0; int numControlPoints = ControlPoints.Count; Evaluator eval = new Evaluator( ); for ( int cpIndex = 0; cpIndex < numControlPoints; ++cpIndex ) { MakeEvaluator( ref eval, this, cpIndex ); closestFraction = calculator.GetClosestPointInInterval( eval, 1.0f, iterations ); } return closestFraction; }
public void ProbabilityMatrixCalculation() { var queryRepresentation = new Mock<ITermWeightRepresentation>(); var documentRepresentation = new Mock<ITermWeightRepresentation>(); queryRepresentation.Setup(x => x.TermWeight(It.Is<string>(y => y == "fruit"))).Returns(0.51083); queryRepresentation.Setup(x => x.TermWeight(It.Is<string>(y => y == "fly"))).Returns(0.22314); documentRepresentation.Setup(x => x.TermWeight(It.Is<string>(y => y == "bee"))).Returns(0.91629); documentRepresentation.Setup(x => x.TermWeight(It.Is<string>(y => y == "wasp"))).Returns(0.91629); documentRepresentation.Setup(x => x.TermWeight(It.Is<string>(y => y == "fly"))).Returns(0.22314); var termsCollection = new TermsCollection(new[] {"bee", "wasp", "fly", "fruit", "like"}); var distanceCalculator = new DistanceCalculator(); var probabilityMatrix = new ProbabilityMatrixCalculator(); double probability = probabilityMatrix.CalculateProbability(queryRepresentation.Object, documentRepresentation.Object, termsCollection); Assert.AreEqual(0.067932752, probability, 0.0001); }
public static double CalcLostEnergy(IList <Position> positions) { Debug.WriteLine("List Count: " + positions.Count); AltitudeDatum altitudeBefore; double speedBefore = 0; double airSum = 0; double rollingSum = 0; double convertLossSum = 0; double regeneLossSum = 0; double lostEnergy = 0; altitudeBefore = AltitudeCalculator.CalcAltitude(positions[1].Latitude, positions[1].Longitude); for (int i = 3; i < positions.Count; i++) { var positionBefore = positions[i - 3]; var positionCurrent = positions[i - 2]; var positionAfter = positions[i - 1]; var distanceDiff = DistanceCalculator.CalcDistance(positionBefore.Latitude, positionBefore.Longitude, positionCurrent.Latitude, positionCurrent.Longitude); //Debug.WriteLine("DistanceDiff: " + distanceDiff); // meter per sec var speed = SpeedCalculator.CalcSpeed(positionBefore.Latitude, positionBefore.Longitude, positionBefore.Timestamp.DateTime, positionAfter.Latitude, positionAfter.Longitude, positionAfter.Timestamp.DateTime, positionCurrent.Latitude, positionCurrent.Longitude) / 3.6; //Debug.WriteLine("Speed: " + speed * 3.6); if (i == 3) { speedBefore = speed; } var altitude = AltitudeCalculator.CalcAltitude(positionCurrent.Latitude, positionCurrent.Longitude); double altitudeDiff = 0; if (altitude != null && altitudeBefore != null) { altitudeDiff = altitude.Altitude - altitudeBefore.Altitude; } altitudeBefore = altitude; //Debug.WriteLine("AltitudeDiff: " + altitudeDiff); double airResistancePower = 0; if (speed > 1.0 / 3.6 && distanceDiff > 0) { airResistancePower = AirResistanceCalculator.CalcPower( Constants.Rho, Car.GetLeaf().CdValue, Car.GetLeaf().FrontalProjectedArea, speed, speed); } //Debug.WriteLine("AirResistace: " + airResistancePower); airSum += airResistancePower; double rollingResistancePower = 0; if (speed > 1.0 / 3.6 && distanceDiff > 0) { rollingResistancePower = RollingResistanceCalculator.CalcPower( Constants.Myu, Car.GetLeaf().Weight, Math.Atan(altitudeDiff / distanceDiff), speed); } //Debug.WriteLine("rollingResistancePower: " + rollingResistancePower); rollingSum += rollingResistancePower; double climbingResistancePower = 0; if (speed > 1.0 / 3.6 && distanceDiff > 0) { climbingResistancePower = ClimbingResistanceCalculator.CalcPowerPreVer( Car.GetLeaf().Weight, altitudeDiff); } //Debug.WriteLine("climbingResistancePower: " + climbingResistancePower); double accResistancePower = 0; if (speed > 1.0 / 3.6 && distanceDiff > 0) { accResistancePower = AccResistanceCalculator.CalcPower( speedBefore, positionBefore.Timestamp.DateTime, speed, positionCurrent.Timestamp.DateTime, Car.GetLeaf().Weight); } //Debug.WriteLine("accResistancePower: " + accResistancePower); double drivingResistancePower = airResistancePower + rollingResistancePower + climbingResistancePower + accResistancePower; double torque = 0; if (drivingResistancePower > 0 && speed > 0) { torque = drivingResistancePower * 1000 * 3600 / speed * Car.GetLeaf().TireRadius / Car.GetLeaf().ReductionRatio; } //Debug.WriteLine("torque: " + torque); var efficiency = EfficiencyCalculator.CalcEfficiency(Car.GetLeaf(), speed, torque).Efficiency; //Debug.WriteLine("efficiency: " + efficiency); double convertLoss = ConvertLossCalculator.CalcEnergyPreVer( drivingResistancePower, speed, efficiency); //Debug.WriteLine("convertLoss: " + convertLoss); convertLossSum += Math.Abs(convertLoss); double regeneEnergy = RegeneEnergyCalculator.CalcEnergy(drivingResistancePower, speed, Car.GetLeaf(), efficiency); //Debug.WriteLine("regeneEnergy: " + regeneEnergy); double regeneLoss = RegeneLossCalculator.CalcEnergyPreVer(drivingResistancePower, speed, efficiency); //Debug.WriteLine($"{positionCurrent.Timestamp.DateTime}: {regeneLoss}, {efficiency}"); regeneLossSum += Math.Abs(regeneLoss); lostEnergy += LostEnergyCalculator.CalcEnergy(convertLoss, regeneLoss, airResistancePower, rollingResistancePower); //Debug.WriteLine("LostEnergy: " + lostEnergy); speedBefore = speed; //var consumedEnergy = ConsumedEnergyCaluculator.CalcEnergy(drivingResistancePower, Car.GetLeaf(), speed, efficiency); //Debug.WriteLine($"Efficiency: {efficiency}, CalcEfficiency: {(consumedEnergy / convertLoss) * 100}"); //LostEnergyList.Add(lostEnergy); } Debug.WriteLine("LostEnergy: " + lostEnergy); Debug.WriteLine("Air: " + airSum); Debug.WriteLine("Rolling: " + rollingSum); Debug.WriteLine("Convert: " + convertLossSum); Debug.WriteLine("Regene: " + regeneLossSum); return(lostEnergy); }
public bool IsInRange(Person person) { distance = DistanceCalculator.DistanceBetweenWarriors(person.Coordinate, owner.Coordinate); return(distance <= maxDistance); }
protected void Init(DistanceUnits units, DistanceCalculator calculator, Rectangle worldBounds) { if (units == null) throw new ArgumentException("units can't be null", "units"); this.units = units; if (calculator == null) { calculator = IsGeo() ? (DistanceCalculator)new GeodesicSphereDistCalc.Haversine(units.EarthRadius()) : new CartesianDistCalc(); } this.calculator = calculator; if (worldBounds == null) { worldBounds = IsGeo() ? GEO_WORLDBOUNDS : MAX_WORLDBOUNDS; } else { if (IsGeo()) Debug.Assert(new RectangleImpl(worldBounds).Equals(GEO_WORLDBOUNDS)); if (worldBounds.GetCrossesDateLine()) throw new ArgumentException("worldBounds shouldn't cross dateline: " + worldBounds, "worldBounds"); } //copy so we can ensure we have the right implementation worldBounds = MakeRect(worldBounds.GetMinX(), worldBounds.GetMaxX(), worldBounds.GetMinY(), worldBounds.GetMaxY()); this.worldBounds = worldBounds; shapeReadWriter = MakeShapeReadWriter(); this.maxCircleDistance = IsGeo() ? calculator.DegreesToDistance(180) : (double?)null; }
private void toolStripComboBox1_SelectedIndexChanged(object sender, EventArgs e) { // Alarm Clock //Basic Calculator //Change Return //Circular Primes //Coin Flip Simulation //Distance Calculator //Factorial Finder //Fibonacci Sequence //Friday the 13th //Gravity Simulation //Gray Code //Guess the Number //Happy Numbers //Houseold budget //Latin Squares //Least / greatest Common Denominator //Lotto //Mortgage Calculator //Neon Number //Next Prime Number //Nth Natural Number //Number Base Converter //Number of Days //Pascal's Triangle //Pi Nth Digit //prime Factorization //Pseudo Random Number Generator //r to Nth Digit //Ramanujan Number //Roman Number Generator //Roman to Arabic Converter //Tax Calculator //Unit Converter //UUID //Vigentere Cipher switch (toolStripComboBox1.Text) { case "Distance Calculator": { DistanceCalculator distanceCalculatorApp = new DistanceCalculator(); distanceCalculatorApp.MdiParent = this; distanceCalculatorApp.Show(); break; } case "Tax Calculator": { TaxCalculator taxCalculatorApp = new TaxCalculator(); taxCalculatorApp.MdiParent = this; taxCalculatorApp.Show(); break; } case "Factorial Finder": { FactorialFinder factorialFinderApp = new FactorialFinder(); factorialFinderApp.MdiParent = this; factorialFinderApp.Show(); break; } case "Happy Numbers": { HappyNumber happyNumberApp = new HappyNumber(); happyNumberApp.MdiParent = this; happyNumberApp.Show(); break; } case "Coin Flip Simulation": { CoinToser coinToserApp = new CoinToser(); coinToserApp.MdiParent = this; coinToserApp.Show(); break; } case "Change Return": { ChangeReturn changeReturnApp = new ChangeReturn(); changeReturnApp.MdiParent = this; changeReturnApp.Show(); break; } /*case 7: * { * DistanceCalculator distanceCalculatorApp = new DistanceCalculator(); * distanceCalculatorApp.MdiParent = this; * distanceCalculatorApp.Show(); * break; * } * * case 8: * { * DistanceCalculator distanceCalculatorApp = new DistanceCalculator(); * distanceCalculatorApp.MdiParent = this; * distanceCalculatorApp.Show(); * break; * } * * case 9: * { * DistanceCalculator distanceCalculatorApp = new DistanceCalculator(); * distanceCalculatorApp.MdiParent = this; * distanceCalculatorApp.Show(); * break; * } * * case 10: * { * DistanceCalculator distanceCalculatorApp = new DistanceCalculator(); * distanceCalculatorApp.MdiParent = this; * distanceCalculatorApp.Show(); * break; * } * * case 11: * { * DistanceCalculator distanceCalculatorApp = new DistanceCalculator(); * distanceCalculatorApp.MdiParent = this; * distanceCalculatorApp.Show(); * break; * } * * case 12: * { * DistanceCalculator distanceCalculatorApp = new DistanceCalculator(); * distanceCalculatorApp.MdiParent = this; * distanceCalculatorApp.Show(); * break; * } * * case 13: * { * DistanceCalculator distanceCalculatorApp = new DistanceCalculator(); * distanceCalculatorApp.MdiParent = this; * distanceCalculatorApp.Show(); * break; * } * * case 14: * { * DistanceCalculator distanceCalculatorApp = new DistanceCalculator(); * distanceCalculatorApp.MdiParent = this; * distanceCalculatorApp.Show(); * break; * } * * case 15: * { * DistanceCalculator distanceCalculatorApp = new DistanceCalculator(); * distanceCalculatorApp.MdiParent = this; * distanceCalculatorApp.Show(); * break; * } * * case 16: * { * DistanceCalculator distanceCalculatorApp = new DistanceCalculator(); * distanceCalculatorApp.MdiParent = this; * distanceCalculatorApp.Show(); * break; * } * * case 17: * { * DistanceCalculator distanceCalculatorApp = new DistanceCalculator(); * distanceCalculatorApp.MdiParent = this; * distanceCalculatorApp.Show(); * break; * } * */ default: break; } }
/// <summary> /// Обновление навигационных данных /// </summary> /// <param name="data"></param> /// <param name="date"></param> private void BuildHistoryRow(List <CarStateModel> data, DateTime date) { var r = new LoadedHistoryRows { Date = date, Data = data }; var slowTask = new Task(delegate { try { var dc = new DistanceCalculator(); for (var i = 0; i < data.Count() - 1; i++) { r.Mileage += dc.Calculate(data[i], data[i + 1]); } } catch { } if (!data.Any()) { return; } try { r.MiddleSpeed = data.Sum(p => p.Spd) / 10 / data.Count(); var moving = data.Where(p => p.Spd > 10).ToList(); if (!moving.Any()) { return; } var hStart = moving.Min(p => p.hh); var minStart = moving.Where(p => p.hh == hStart).Min(p => p.mm); var hStop = moving.Max(p => p.hh); var mStop = moving.Where(p => p.hh == hStop).Max(p => p.mm); r.Start = hStart + ":" + minStart; r.Stop = hStop + ":" + mStop; } catch { } }); slowTask.ContinueWith(delegate { if (_dispatcher != null) { _dispatcher.BeginInvoke(new Action(() => { var item = HistoryRows.OrderBy(s => s.Date) .LastOrDefault(o => o.StringDate.Equals(r.StringDate) || o.Date < r.Date); if (item != null) { var indx = HistoryRows.IndexOf(item); _foundselected = HistoryRows[indx].Equals(SelectedHistoryRow); DistanceAll -= HistoryRows[indx].Mileage; HistoryRows[indx] = r; if (_foundselected) { SelectedHistoryRow = r; } _foundselected = false; DistanceAll += r.Mileage; } else { HistoryRows.Add(r); DistanceAll += r.Mileage; } })); } }); slowTask.Start(); }
public void SetUp() { _uut = new DistanceCalculator(); }
public static double Calcdistance(DistanceCalculator point1, DistanceCalculator point2) //static { return(Math.Sqrt(Math.Pow((point1.x - point2.x), 2) + Math.Pow((point1.y - point2.y), 2) + Math.Pow((point1.z - point2.z), 2))); }
public double Calcdistance(DistanceCalculator point) //instance { return(Math.Sqrt(Math.Pow((point.x - this.x), 2) + Math.Pow((point.y - this.y), 2) + Math.Pow((point.z - this.z), 2))); }
public void TracePathTestWithPalindromicContig() { const int kmerLengthConst = 5; const int dangleThreshold = 3; const int redundantThreshold = 6; var sequences = new List <ISequence>() { new Sequence(Alphabets.DNA, "ATGCCTC") { ID = "0" }, new Sequence(Alphabets.DNA, "CCTCCTAT") { ID = "1" }, new Sequence(Alphabets.DNA, "TCCTATC") { ID = "2" }, new Sequence(Alphabets.DNA, "TGCCTCCT") { ID = "3" }, new Sequence(Alphabets.DNA, "ATCTTAGC") { ID = "4" }, new Sequence(Alphabets.DNA, "CTATCTTAG") { ID = "5" }, new Sequence(Alphabets.DNA, "CTTAGCG") { ID = "6" }, new Sequence(Alphabets.DNA, "GCCTCCTAT") { ID = "7" }, new Sequence(Alphabets.DNA, "TAGCGCGCTA") { ID = "8" }, new Sequence(Alphabets.DNA, "AGCGCGC") { ID = "9" }, new Sequence(Alphabets.DNA, "TTTTTT") { ID = "10" }, new Sequence(Alphabets.DNA, "TTTTTAAA") { ID = "11" }, new Sequence(Alphabets.DNA, "TAAAAA") { ID = "12" }, new Sequence(Alphabets.DNA, "TTTTAG") { ID = "13" }, new Sequence(Alphabets.DNA, "TTTAGC") { ID = "14" }, new Sequence(Alphabets.DNA, "GCGCGCCGCGCG") { ID = "15" }, }; KmerLength = kmerLengthConst; SequenceReads.Clear(); SetSequenceReads(sequences); CreateGraph(); DanglingLinksThreshold = dangleThreshold; DanglingLinksPurger = new DanglingLinksPurger(dangleThreshold); RedundantPathLengthThreshold = redundantThreshold; RedundantPathsPurger = new RedundantPathsPurger(redundantThreshold); UnDangleGraph(); RemoveRedundancy(); IList <ISequence> contigs = BuildContigs().ToList(); ReadContigMapper mapper = new ReadContigMapper(); ReadContigMap maps = mapper.Map(contigs, sequences, kmerLengthConst); MatePairMapper builder = new MatePairMapper(); CloneLibrary.Instance.AddLibrary("abc", 5, 15); ContigMatePairs pairedReads = builder.MapContigToMatePairs(sequences, maps); OrientationBasedMatePairFilter filter = new OrientationBasedMatePairFilter(); ContigMatePairs overlap = filter.FilterPairedReads(pairedReads, 0); DistanceCalculator dist = new DistanceCalculator(overlap); overlap = dist.CalculateDistance(); ContigGraph graph = new ContigGraph(); graph.BuildContigGraph(contigs, this.KmerLength); TracePath path = new TracePath(); IList <ScaffoldPath> paths = path.FindPaths(graph, overlap, kmerLengthConst, 3); Assert.AreEqual(paths.Count, 3); Assert.AreEqual(paths.First().Count, 3); ScaffoldPath scaffold = paths.First(); Assert.AreEqual("ATGCCTCCTATCTTAGC", graph.GetNodeSequence(scaffold[0].Key).ConvertToString()); Assert.AreEqual("TTAGCGCG", graph.GetNodeSequence(scaffold[1].Key).ConvertToString()); Assert.AreEqual("GCGCGC", graph.GetNodeSequence(scaffold[2].Key).ConvertToString()); }
// Update is called once per frame void Update() { distanceUI.text = string.Format("{000}", DistanceCalculator.getDistance()); }
public void CalculateMoves() { CalculatedMoves = new Moves(); var movesSoFar = new Moves(); PlayCardsTask.PlayCardsBeginTurn(BotState, movesSoFar); AILog.Log("MovesCalculator", "Starting armies: " + BotState.MyIncome.Total); CalculateXBonusMoves(movesSoFar, BotTerritory.DeploymentType.Normal, BotTerritory.DeploymentType.Normal); AILog.Log("MovesCalculator", "Armies used after calculateXBonusMoves type 1: " + movesSoFar.GetTotalDeployment()); BotState.DeleteBadMovesTask.CalculateDeleteBadMovesTask(movesSoFar); CalculateXBonusMoves(movesSoFar, BotTerritory.DeploymentType.Normal, BotTerritory.DeploymentType.Conservative); BotState.DeleteBadMovesTask.CalculateDeleteBadMovesTask(movesSoFar); CalculateXBonusMoves(movesSoFar, BotTerritory.DeploymentType.Conservative, BotTerritory.DeploymentType.Conservative); BotState.DeleteBadMovesTask.CalculateDeleteBadMovesTask(movesSoFar); AILog.Log("MovesCalculator", "Armies used after calculateXBonusMoves type 2: " + movesSoFar.GetTotalDeployment()); CalculateSnipeBonusMoves(movesSoFar); BotState.DeleteBadMovesTask.CalculateDeleteBadMovesTask(movesSoFar); AILog.Log("MovesCalculator", "Armies used after calculateSnipeBonusMoves: " + movesSoFar.GetTotalDeployment()); CalculateXBonusMoves(movesSoFar, 0, BotTerritory.DeploymentType.Normal); BotState.DeleteBadMovesTask.CalculateDeleteBadMovesTask(movesSoFar); BotState.TerritoryValueCalculator.CalculateTerritoryValues(BotState.VisibleMap, BotState.WorkingMap); BotState.ExpansionTask.CalculateExpansionMoves(movesSoFar); BotState.DeleteBadMovesTask.CalculateDeleteBadMovesTask(movesSoFar); AILog.Log("MovesCalculator", "Armies used after calculateExpansionMoves: " + movesSoFar.GetTotalDeployment()); BotState.TerritoryValueCalculator.CalculateTerritoryValues(BotState.VisibleMap, BotState.WorkingMap); CalculateNoPlanBreakDefendMoves(movesSoFar, false, false, true, BotTerritory.DeploymentType.Normal, BotTerritory.DeploymentType.Normal); BotState.DeleteBadMovesTask.CalculateDeleteBadMovesTask(movesSoFar); AILog.Log("MovesCalculator", "Armies used after calculateNoPlanBreakDefendMoves1: " + movesSoFar.GetTotalDeployment()); BotState.TerritoryValueCalculator.CalculateTerritoryValues(BotState.VisibleMap, BotState.WorkingMap); CalculateNoPlanBreakDefendMoves(movesSoFar, false, true, false, BotTerritory.DeploymentType.Normal, BotTerritory.DeploymentType.Normal); BotState.DeleteBadMovesTask.CalculateDeleteBadMovesTask(movesSoFar); AILog.Log("MovesCalculator", "Armies used after calculateNoPlanBreakDefendMoves: " + movesSoFar.GetTotalDeployment()); BotState.TerritoryValueCalculator.CalculateTerritoryValues(BotState.VisibleMap, BotState.WorkingMap); CalculateNoPlanBreakDefendMoves(movesSoFar, false, false, true, BotTerritory.DeploymentType.Conservative, BotTerritory.DeploymentType.Conservative); BotState.DeleteBadMovesTask.CalculateDeleteBadMovesTask(movesSoFar); BotState.TerritoryValueCalculator.CalculateTerritoryValues(BotState.VisibleMap, BotState.WorkingMap); CalculateNoPlanBreakDefendMoves(movesSoFar, false, true, true, BotTerritory.DeploymentType.Normal, BotTerritory.DeploymentType.Conservative); BotState.DeleteBadMovesTask.CalculateDeleteBadMovesTask(movesSoFar); BotState.TerritoryValueCalculator.CalculateTerritoryValues(BotState.VisibleMap, BotState.WorkingMap); CalculateFlankBonusMoves(movesSoFar); BotState.DeleteBadMovesTask.CalculateDeleteBadMovesTask(movesSoFar); AILog.Log("MovesCalculator", "Armies used after calculateFlankBonusMoves: " + movesSoFar.GetTotalDeployment()); BotState.TerritoryValueCalculator.CalculateTerritoryValues(BotState.VisibleMap, BotState.WorkingMap); CalculateNoPlanBreakDefendMoves(movesSoFar, true, false, false, BotTerritory.DeploymentType.Normal, BotTerritory.DeploymentType.Normal); BotState.DeleteBadMovesTask.CalculateDeleteBadMovesTask(movesSoFar); BotState.TerritoryValueCalculator.CalculateTerritoryValues(BotState.VisibleMap, BotState.WorkingMap); CalculateNoPlanBreakDefendMoves(movesSoFar, true, false, false, BotTerritory.DeploymentType.Normal, BotTerritory.DeploymentType.Conservative); BotState.DeleteBadMovesTask.CalculateDeleteBadMovesTask(movesSoFar); BotState.TerritoryValueCalculator.CalculateTerritoryValues(BotState.VisibleMap, BotState.VisibleMap); CalculateNoPlanAttackTerritoriesMoves(movesSoFar); BotState.DeleteBadMovesTask.CalculateDeleteBadMovesTask(movesSoFar); AILog.Log("MovesCalculator", "Armies used after calculateNoPlanAttackTerritoriesMoves2: " + movesSoFar.GetTotalDeployment()); BotState.TerritoryValueCalculator.CalculateTerritoryValues(BotState.VisibleMap, BotState.VisibleMap); CalculateMoveIdleArmiesMoves(movesSoFar); BotState.DeleteBadMovesTask.CalculateDeleteBadMovesTask(movesSoFar); CalculateJoinInAttacksMoves(movesSoFar); BotState.DeleteBadMovesTask.CalculateDeleteBadMovesTask(movesSoFar); var supportTransferMoves = TransferMovesChooser.CalculateJoinStackMoves(BotState); BotState.DeleteBadMovesTask.CalculateDeleteBadMovesTask(movesSoFar); MovesCommitter.CommittMoves(BotState, supportTransferMoves); movesSoFar.MergeMoves(supportTransferMoves); CalculateNoPlanCleanupMoves(movesSoFar); BotState.DeleteBadMovesTask.CalculateDeleteBadMovesTask(movesSoFar); CalculateMoveIdleArmiesMoves(movesSoFar); BotState.DeleteBadMovesTask.CalculateDeleteBadMovesTask(movesSoFar); CalculateJoinInAttacksMoves(movesSoFar); BotState.DeleteBadMovesTask.CalculateDeleteBadMovesTask(movesSoFar); CalculateNoPlanTryoutAttackMoves(movesSoFar); BotState.DeleteBadMovesTask.CalculateDeleteBadMovesTask(movesSoFar); AILog.Log("MovesCalculator", "Armies used after all moves done: " + movesSoFar.GetTotalDeployment()); BotState.MapUpdater.UpdateMap(BotState.WorkingMap); DistanceCalculator.CalculateDistanceToBorder(BotState, BotState.VisibleMap, BotState.WorkingMap); BotState.ExpansionMapUpdater.UpdateExpansionMap(); DistanceCalculator.CalculateDistanceToUnimportantTerritories(BotState.ExpansionMap, BotState.VisibleMap); DistanceCalculator.CalculateDistanceToImportantExpansionTerritories(BotState.ExpansionMap, BotState.VisibleMap); DistanceCalculator.CalculateDistanceToOpponentBorderCare3(BotState.ExpansionMap, BotState.VisibleMap); foreach (BotBonus emBonus in BotState.ExpansionMap.Bonuses.Values) { emBonus.ExpansionValue = BotState.VisibleMap.Bonuses[emBonus.ID].ExpansionValue; } DistanceCalculator.CalculateDistanceToHighlyImportantExpansionTerritories(BotState.ExpansionMap, BotState.VisibleMap); DistanceCalculator.CalculateDistanceToOpponentBorderCare4(BotState.ExpansionMap, BotState.VisibleMap); var transferMoves = TransferMovesChooser.CalculateTransferMoves2(BotState); MovesCommitter.CommittMoves(BotState, transferMoves); movesSoFar.MergeMoves(transferMoves); CalculateDelayMoves(movesSoFar); MovesCleaner.CleanupMoves(BotState, movesSoFar); movesSoFar = BotState.MovesScheduler2.ScheduleMoves(movesSoFar); PlayCardsTask.DiscardCardsEndTurn(BotState, movesSoFar); CalculatedMoves = movesSoFar; }
public async IAsyncEnumerable <OfferResource <Consumable> > QueryOffersAsync(Consumable con, string region) { NullCheck.ThrowIfNull <Consumable>(con); var consumable = new ConsumableEntity().Build(con); var maxDistance = con.kilometer; var consumableAddress = con.address; var location = new AddressEntity().build(consumableAddress); _addressMaker.SetCoordinates(location); var query = from o in _context.offer as IQueryable <OfferEntity> join c in _context.consumable on o.id equals c.offer_id join ap in _context.address on o.address_id equals ap.Id where consumable.category == c.category && !c.is_deleted && o.region == region select new { o, c, ap }; if (!string.IsNullOrEmpty(consumable.name)) { query = query.Where(collection => consumable.name == collection.c.name); } if (!string.IsNullOrEmpty(consumable.manufacturer)) { query = query.Where(collection => consumable.manufacturer == collection.c.manufacturer);; } if (consumable.amount > 0) { query = query.Where(collection => consumable.amount <= collection.c.amount); } List <OfferResource <Consumable> > resources = new List <OfferResource <Consumable> >(); var results = await query.ToListAsync(); foreach (var data in results) { var resource = new Consumable().build(data.c); var yLatitude = data.ap.Latitude; var yLongitude = data.ap.Longitude; var distance = DistanceCalculator.computeDistance(location.Latitude, location.Longitude, yLatitude, yLongitude); if (distance > maxDistance && maxDistance != 0) { continue; } resource.kilometer = (int)Math.Round(distance); var provider = new Provider().Build(data.o); var providerAddress = new Address().Build(data.ap); provider.address = providerAddress; var offer = new OfferResource <Consumable>() { resource = resource }; // ---- HOTFIX // Vorerst sollen keine persönliche Daten veröffentlicht werden. provider.ispublic = false; // ---- END HOTFIX if (provider.ispublic) { offer.provider = provider; } yield return(offer); } }
/// <summary> /// Generates pilot status string. /// </summary> /// <returns></returns> private string GetPilotStatus(string playerGuid) { var db = DataContextFactory.GetAndromedaDataContext(); //Check if the user has a ship //Did we get a valid GUID? Guid?guid; Guid tempGuid; if (Guid.TryParse(playerGuid, out tempGuid)) { guid = tempGuid; } else { guid = null; } //Is there a ship with this GUID? if (guid != null) { if (!db.Spaceships.Any(i => i.PlayerGuid == guid)) { guid = null; } } //Return if the guid was invalid or if there was no ship found if (guid == null) { return(""); } //Generate value string result = ""; var player = db.Players.Single(i => i.FirstShipGuid == guid); NumberFormatInfo nfi = new NumberFormatInfo() { NumberDecimalDigits = 0, NumberGroupSeparator = "." }; result += string.Format(Localization.FleetInfo_ShipsAndCredits, player.PlayerMoney.Value.ToString("N", nfi), player.Spaceships.Count); result += "<br />"; int shipIndex = 0; foreach (var spaceship in player.Spaceships) { shipIndex++; result += string.Format(Localization.FleetInfo_ShipN, shipIndex); spaceship.UpdateTravelStatus(); string travelStatus; if (spaceship.IsInTransit) { var currentStar = db.Stars.Single(i => i.Id == spaceship.CurrentStarId.Value); var targetStar = db.Stars.Single(i => i.Id == spaceship.TargetStarId.Value); var coordinates = spaceship.Coordinates; travelStatus = string.Format(Localization.FleetInfo_ShipEnRoute, currentStar.Name, targetStar.Name, DistanceCalculator.GetDistance(currentStar.X.Value, currentStar.Y.Value, targetStar.X.Value, targetStar.Y.Value).ToString("0.0"), DistanceCalculator.GetDistance(targetStar.X.Value, targetStar.Y.Value, coordinates.Item1, coordinates.Item2).ToString("0.0")); } else { travelStatus = string.Format(Localization.FleetInfo_ShipInPort, db.Stars.Single(i => i.Id == spaceship.CurrentStarId.Value).Name); } string hardwareStatus = string.Format(Localization.FleetInfo_Hardware, spaceship.FreeCapacity, spaceship.TotalCapacity, spaceship.SpeedInLightYearsPerMinute, spaceship.SensorRangeInLightYears, spaceship.DriveCount, spaceship.SensorCount, spaceship.CannonCount, spaceship.ShieldCount); if (spaceship.SensorCount > 0 || spaceship.DriveCount > 0 || spaceship.CannonCount > 0 || spaceship.ShieldCount > 0) { hardwareStatus += string.Format(Localization.FleetInfo_SpaceOccupiedByComponents, spaceship.DriveCount * Constants.DriveCostInCapacity + spaceship.SensorCount * Constants.SensorCostInCapacity + spaceship.CannonCount * Constants.CannonCostInCapacity + spaceship.ShieldCount * Constants.ShieldCostInCapacity); } string cargoStatus; if (spaceship.CommodityInHolds.Count == 0) { cargoStatus = string.Format(Localization.FleetInfo_NoCargo); } else { string cargoInHold = ""; foreach (var cargo in spaceship.CommodityInHolds) { cargoInHold += string.Format(Localization.FleetInfo_CargoItem, cargo.Commodity.Name, cargo.Count); } cargoStatus = string.Format(Localization.FleetInfo_CargoHeader, cargoInHold); } //This string does not need localization result += string.Format("{0}<br /><br />{1}<br /><br />{2}", travelStatus, hardwareStatus, cargoStatus); } return(result); }
public ShapeFieldCacheDistanceValueSource(Point from, DistanceCalculator calc, ShapeFieldCacheProvider<Point> provider) { this.from = from; this.provider = provider; this.calculator = calc; }
public static ECOLOGTuple calculateEcologTuple(GPSTuple previusGPS, GPSTuple currentGPSTuple, DataTable roadLinks, Car car) { // ECOLOGTupleの空のインスタンスを作成 ECOLOGTuple retTuple = new ECOLOGTuple(); // GPSTupleから現在地、GPS時刻、速度を取得。 // 端末時刻は時刻同期がちゃんと取れてる必要があるので、GPS時刻を使うのが無難な気がする。 retTuple.Jst = currentGPSTuple.GpsTime; retTuple.Latitude = currentGPSTuple.Latitude; retTuple.Longitude = currentGPSTuple.Longitude; retTuple.Speed = currentGPSTuple.Speed; // 10mメッシュ標高データから取得する。 // シングルトンクラスのGetInstance()はインスタンスそのものを返すのでnewいらない。 AltitudeCalculator altitudeCalculator = AltitudeCalculator.GetInstance(); Tuple <int, double> meshIdAltitudeTuple = altitudeCalculator.CalcAltitude(currentGPSTuple.Latitude, currentGPSTuple.Longitude); retTuple.TerrainAltitude = meshIdAltitudeTuple.Item2; double previusAltitude = altitudeCalculator.CalcAltitude(previusGPS.Latitude, previusGPS.Longitude).Item2; double altitudeDiff = retTuple.TerrainAltitude - previusAltitude; // distance double distanceDiff = DistanceCalculator.CalcDistance(previusGPS.Latitude, previusGPS.Longitude, currentGPSTuple.Latitude, currentGPSTuple.Longitude); // calculate resistancePower double airResistancePower = 0; double rollingResistancePower = 0; double climbingResistancePower = 0; double accResitancePower = 0; if (currentGPSTuple.Speed > 1 && distanceDiff > 0) { airResistancePower = AirResistanceCalculator.CalcPower(Rho, car.CdValue, car.FrontalProjectedArea, (currentGPSTuple.Speed + WindSpeed) / 3.6, currentGPSTuple.Speed / 3.6); rollingResistancePower = RollingResistanceCalculator.CalcPower(Myu, car.Weight, Math.Atan(altitudeDiff / distanceDiff), // TODO: 前のタプルとの標高差と距離が角度求めるには必要。 currentGPSTuple.Speed / 3.6); climbingResistancePower = ClimbingResistanceCalculator.CalcPower(car.Weight, Math.Atan(altitudeDiff / distanceDiff), // TODO: rollingResistancePowerと同様 currentGPSTuple.Speed / 3.6); accResitancePower = AccResistanceCalculator.CalcPower(previusGPS.Speed / 3.6, previusGPS.GpsTime, currentGPSTuple.Speed / 3.6, currentGPSTuple.GpsTime, car.Weight); } double drivingResistancePower = airResistancePower + rollingResistancePower + climbingResistancePower + accResitancePower; // torque double torque = 0; if (drivingResistancePower > 0 && currentGPSTuple.Speed > 0) { torque = drivingResistancePower * 1000 * 3600 / (currentGPSTuple.Speed / 3.6) * car.TireRadius / car.ReductionRatio; } // Efficiency int efficiency = EfficiencyCalculator.GetInstance().GetEfficiency(car, currentGPSTuple.Speed / 3.6, torque); // 各種損失はSensorLogInserterReの計算メソッドを用いて算出する double convertLoss = ConvertLossCaluculator.CalcEnergy(drivingResistancePower, car, currentGPSTuple.Speed / 3.6, efficiency); double regeneEnergy = RegeneEnergyCalculator.CalcEnergy(drivingResistancePower, currentGPSTuple.Speed / 3.6, car, efficiency); double regeneLoss = RegeneLossCalculator.CalcEnergy(drivingResistancePower, regeneEnergy, car, currentGPSTuple.Speed / 3.6, efficiency); double lostEnergy = LostEnergyCalculator.CalcEnergy(convertLoss, regeneLoss, airResistancePower, rollingResistancePower); // link and semantic_link // 近傍リンクをSQLで指定、すべてのリンクに対して、GPS点とリンクの距離を求める // 最近傍リンクまでの距離が閾値を超えない場合には、それをGPS点が通過するリンクとする return(retTuple); }
public async IAsyncEnumerable <OfferResource <Personal> > QueryOffersAsync(Manpower manpower, string region) { NullCheck.ThrowIfNull <Manpower>(manpower); var maxDistance = manpower.kilometer; var manpowerAddress = manpower.address; var location = new AddressEntity().build(manpowerAddress); _addressMaker.SetCoordinates(location); var query = from o in _context.offer as IQueryable <OfferEntity> join personal in _context.personal on o.id equals personal.offer_id join ap in _context.address on o.address_id equals ap.Id where !personal.is_deleted && o.region == region select new { o, personal, ap }; if (!string.IsNullOrEmpty(manpower.institution)) { query = query.Where(collection => manpower.institution == collection.personal.institution);; } if (manpower.qualification.Any()) { query = query.Where(collection => manpower.qualification.Contains(collection.personal.qualification)); } if (manpower.area.Any()) { query = query.Where(collection => manpower.area.Contains(collection.personal.area)); } if (!string.IsNullOrEmpty(manpower.researchgroup)) { query = query.Where(collection => manpower.researchgroup == collection.personal.researchgroup);; } if (manpower.experience_rt_pcr) { query = query.Where(collection => collection.personal.experience_rt_pcr);; } List <OfferResource <Personal> > resources = new List <OfferResource <Personal> >(); var results = await query.ToListAsync(); foreach (var data in results) { var resource = new Personal().build(data.personal); var yLatitude = data.ap.Latitude; var yLongitude = data.ap.Longitude; var distance = DistanceCalculator.computeDistance(location.Latitude, location.Longitude, yLatitude, yLongitude); if (distance > maxDistance && maxDistance != 0) { continue; } resource.kilometer = (int)Math.Round(distance); var provider = new Provider().Build(data.o); var providerAddress = new Address().Build(data.ap); provider.address = providerAddress; var offer = new OfferResource <Personal>() { resource = resource }; // ---- HOTFIX // Vorerst sollen keine persönliche Daten veröffentlicht werden. provider.ispublic = false; // ---- END HOTFIX if (provider.ispublic) { offer.provider = provider; } yield return(offer); } }
private void Start() { distanceCalculator = new DistanceCalculator(playerTransform, groundLayer); }
/// <summary> /// Return true if plan needs to be updated /// </summary> /// <returns></returns> public override bool shouldUpdatePlan() { return((this.plan == null || DistanceCalculator.squareEuclidianDistance(base.targetLocation, Player.Instance.transform.position) >= base.minMoveDistance) && !isCharging); }
public void SetUp() { calculator = new DistanceCalculator(); }
/// <summary> /// /// </summary> /// <param name="units">Required; and establishes geo vs cartesian.</param> /// <param name="calculator">Optional; defaults to Haversine or cartesian depending on units.</param> /// <param name="worldBounds">Optional; defaults to GEO_WORLDBOUNDS or MAX_WORLDBOUNDS depending on units.</param> public SpatialContext(DistanceUnits units, DistanceCalculator calculator, Rectangle worldBounds) { Init(units, calculator, worldBounds); }
private bool markIsCloseEnough(Vector userPos, Vector markPos, double proximityThreshhold) { return(DistanceCalculator.DistanceInKm(userPos, markPos) < proximityThreshhold); }
private void CalcEcolog(int count) { if (count == 2) { _altitudeBefore = AltitudeCalculator.CalcAltitude(PositionCollection[count - 1].Latitude, PositionCollection[count - 1].Longitude); //Debug.WriteLine("AltitudeBefore: " + _altitudeBefore.Altitude); } else if (PositionCollection.Count > 2) { var positionBefore = PositionCollection[count - 3]; var positionCurrent = PositionCollection[count - 2]; var positionAfter = PositionCollection[count - 1]; var distanceDiff = DistanceCalculator.CalcDistance(positionBefore.Latitude, positionBefore.Longitude, positionCurrent.Latitude, positionCurrent.Longitude); //Debug.WriteLine("DistanceDiff: " + distanceDiff); // meter per sec var speed = SpeedCalculator.CalcSpeed(positionBefore.Latitude, positionBefore.Longitude, positionBefore.Timestamp.DateTime, positionAfter.Latitude, positionAfter.Longitude, positionAfter.Timestamp.DateTime, positionCurrent.Latitude, positionCurrent.Longitude) / 3.6; //Debug.WriteLine("Speed: " + speed * 3.6); if (count == 3) { _speedBefore = speed; } var altitude = AltitudeCalculator.CalcAltitude(positionCurrent.Latitude, positionCurrent.Longitude); //var altitude = new AltitudeDatum { Altitude = 40 }; double altitudeDiff = 0; if (altitude != null && _altitudeBefore != null) { altitudeDiff = altitude.Altitude - _altitudeBefore.Altitude; } _altitudeBefore = altitude; //Debug.WriteLine("AltitudeDiff: " + altitudeDiff); double airResistancePower = 0; if (speed > 1.0 / 3.6 && distanceDiff > 0) { airResistancePower = AirResistanceCalculator.CalcPower( Constants.Rho, Car.GetLeaf().CdValue, Car.GetLeaf().FrontalProjectedArea, speed, speed); } //Debug.WriteLine("AirResistace: " + airResistancePower); double rollingResistancePower = 0; if (speed > 1.0 / 3.6 && distanceDiff > 0) { rollingResistancePower = RollingResistanceCalculator.CalcPower( Constants.Myu, Car.GetLeaf().Weight, Math.Atan(altitudeDiff / distanceDiff), speed); } //Debug.WriteLine("rollingResistancePower: " + rollingResistancePower); double climbingResistancePower = 0; if (speed > 1.0 / 3.6 && distanceDiff > 0) { climbingResistancePower = ClimbingResistanceCalculator.CalcPowerPreVer( Car.GetLeaf().Weight, altitudeDiff); } //Debug.WriteLine("climbingResistancePower: " + climbingResistancePower); double accResistancePower = 0; if (speed > 1.0 / 3.6 && distanceDiff > 0) { accResistancePower = AccResistanceCalculator.CalcPower( _speedBefore, positionBefore.Timestamp.DateTime, speed, positionCurrent.Timestamp.DateTime, Car.GetLeaf().Weight); } //Debug.WriteLine("accResistancePower: " + accResistancePower); double drivingResistancePower = airResistancePower + rollingResistancePower + climbingResistancePower + accResistancePower; double torque = 0; if (drivingResistancePower > 0 && speed > 0) { torque = drivingResistancePower * 1000 * 3600 / speed * Car.GetLeaf().TireRadius / Car.GetLeaf().ReductionRatio; } //Debug.WriteLine("torque: " + torque); var efficiency = EfficiencyCalculator.CalcEfficiency(Car.GetLeaf(), speed, torque).Efficiency; //var efficiency = 90; //Debug.WriteLine("efficiency: " + efficiency); double convertLoss = ConvertLossCalculator.CalcEnergyPreVer( drivingResistancePower, speed, efficiency); //Debug.WriteLine("convertLoss: " + convertLoss); double regeneEnergy = RegeneEnergyCalculator.CalcEnergy(drivingResistancePower, speed, Car.GetLeaf(), efficiency); //Debug.WriteLine("regeneEnergy: " + regeneEnergy); double regeneLoss = RegeneLossCalculator.CalcEnergyPreVer(drivingResistancePower, speed, efficiency); //Debug.WriteLine($"{positionCurrent.Timestamp.DateTime}: {regeneLoss}, {efficiency}"); double lostEnergy = LostEnergyCalculator.CalcEnergy(convertLoss, regeneLoss, airResistancePower, rollingResistancePower); //Debug.WriteLine("LostEnergy: " + lostEnergy); _speedBefore = speed; //var consumedEnergy = ConsumedEnergyCaluculator.CalcEnergy(drivingResistancePower, Car.GetLeaf(), speed, efficiency); //Debug.WriteLine($"Efficiency: {efficiency}, CalcEfficiency: {(consumedEnergy / convertLoss) * 100}"); LostEnergyList.Add(lostEnergy); AirResistanceList.Add(airResistancePower); RollingResistanceList.Add(rollingResistancePower); ConvertLossList.Add(Math.Abs(convertLoss)); RegeneLossList.Add(Math.Abs(regeneLoss)); } }
public static double CalculateDiagonalXY() { double distance = DistanceCalculator.CalculateDistance2D(0, 0, Width, Height); return(distance); }
static void Main() { #region Builder Sample Console.WriteLine("Builder Sample"); var simpleRoom = new SimpleRoomBuilder().Build(); simpleRoom.Describe(); var familyRoom = new FamilyRoomBuilder().Build(); familyRoom.Describe(); #endregion #region Factory Sample ProcessCharging(PaymentServiceFactory.ServicesAvailable.Brazilian, "*****@*****.**", 178.90f, EnumChargingOptions.CreditCard); ProcessCharging(PaymentServiceFactory.ServicesAvailable.Italian, "*****@*****.**", 188.70f, EnumChargingOptions.DebitCard); #endregion #region Singleton Sample Console.WriteLine("Singleton Sample"); SingletonDemo.Current.Message = "This text will be printed by " + "the singleton."; SingletonDemo.Current.Print(); #endregion #region Singleton Configuration Sample Console.WriteLine("Singleton Configuration Sample"); for (int i = 0; i < 20; i++) { Console.WriteLine($"Random Number Parameter: {Configuration.Current.RandomNumber}. Last Time Loaded {Configuration.Current.LastTimeLoaded}"); Thread.Sleep(1000); } #endregion #region Proxy Sample Console.WriteLine("Proxy Sample"); ExecuteProxySample(new ProxyRoomPicture()); #endregion #region Command Sample Console.WriteLine(""); Console.WriteLine("Command Sample"); var package = new Package("Shopping in New York"); var likeCommand = new LikeCmd(package); var dislikeCommand = new DislikeCmd(package); var loveCommand = new LoveCmd(package); var commandInvoker = new CommandInvoker(); var keepAsking = true; while (keepAsking) { Console.WriteLine($"Your oppinion about {package.Name}:"); Console.WriteLine("1 - Like"); Console.WriteLine("2 - Dislike"); Console.WriteLine("3 - Love"); Console.WriteLine("4 - Undo last command"); Console.WriteLine("Any other key - Exit"); var key = Console.ReadKey(); Console.WriteLine(""); switch (key.Key) { case ConsoleKey.NumPad1: case ConsoleKey.D1: commandInvoker.Command = likeCommand; break; case ConsoleKey.NumPad2: case ConsoleKey.D2: commandInvoker.Command = dislikeCommand; break; case ConsoleKey.NumPad3: case ConsoleKey.D3: commandInvoker.Command = loveCommand; break; case ConsoleKey.NumPad4: case ConsoleKey.D4: if (commandInvoker.Command != null) { commandInvoker.Undo(); commandInvoker.Command = null; } else { Console.WriteLine("There is no Command to Undo!"); } break; default: keepAsking = false; break; } if ((keepAsking) && (commandInvoker.Command != null)) { commandInvoker.Invoke(); } } #endregion #region Dependency Injection Sample var userAddress = new UserAddress { City = "São Paulo", Country = "Brazil", ZipCode = "01001-001" }; var destinationAddress = new UserAddress { City = "Rio de Janeiro", Country = "Brazil", ZipCode = "22460-050" }; var distanceCalculator = new DistanceCalculator(userAddress, destinationAddress); distanceCalculator.Calculate(); #endregion Console.ReadKey(); }
public static double CalculateDiagonalXZ() { double distance = DistanceCalculator.CalculateDistance2D(0, 0, Width, Depth); return(distance); }
public ValueSource MakeValueSource(SpatialArgs args, DistanceCalculator calc) { var p = (PointPrefixTreeFieldCacheProvider)GetCacheProvider(); Point point = args.GetShape().GetCenter(); return new ShapeFieldCacheDistanceValueSource(point, calc, p); }
public static double CalculateDiagonalYZ() { double distance = DistanceCalculator.CalculateDistance2D(0, 0, Height, Depth); return(distance); }
public DistanceValueSource(TwoDoublesStrategy strategy, Point from, DistanceCalculator calc) { this.strategy = strategy; this.from = from; this.calculator = calc; }
static void Main() { var reader = new StreamReader("../../input/2.txt"); Console.SetIn(reader); var firstInputLineParams = Console.ReadLine() .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) .Select(x => int.Parse(x)) .ToArray(); var numberOfBuildings = firstInputLineParams[0]; var numberOfStreets = firstInputLineParams[1]; var numberOfHospitals = firstInputLineParams[2]; var hospitals = new HashSet<int>(); var readHospitals = Console.ReadLine() .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) .Select(x => int.Parse(x)); foreach (var h in readHospitals) { hospitals.Add(h); } var graph = new Graph<int>(); var connections = new List<int[]>(); for (int i = 0; i < numberOfStreets; i++) { connections.Add(Console.ReadLine() .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) .Select(x => int.Parse(x)) .ToArray()); } // AddNodesToGraph foreach (var connection in connections) { var fromNode = connection[0]; var toNode = connection[1]; var distance = connection[2]; if (!graph.ContainsNode(fromNode)) { graph.AddNode(fromNode); } if (!graph.ContainsNode(toNode)) { graph.AddNode(toNode); } graph.AddConnection(fromNode, toNode, distance, true); } var distanceCalc = new DistanceCalculator<int>(); var minDist = int.MaxValue; foreach (var hospital in hospitals) { var dist = distanceCalc.CalculateDistances(graph, hospital) .Where(x => !hospitals.Contains(x.Key)) .Sum(x => x.Value); if (minDist > dist) { minDist = dist; } } Console.WriteLine(minDist); }
public DistanceSimilarity(SpatialContext ctx, Point queryPoint) { this.queryPoint = queryPoint; this.distCalc = ctx.GetDistCalc(); this.nullValue = (ctx.IsGeo() ? 180 : double.MaxValue); }
/** * See {@link SpatialContext#SpatialContext(com.spatial4j.core.distance.DistanceUnits, com.spatial4j.core.distance.DistanceCalculator, com.spatial4j.core.shape.Rectangle)}. * * @param geometryFactory optional */ public NtsSpatialContext(GeometryFactory geometryFactory, bool geo, DistanceCalculator calculator, Rectangle worldBounds) : base(geo, calculator, worldBounds) { this.geometryFactory = geometryFactory ?? new GeometryFactory(); }
public DistanceFunctionValue(DistanceValueSource enclosingInstance, AtomicReader reader) { this.enclosingInstance = enclosingInstance; ptX = FieldCache.DEFAULT.GetDoubles(reader, enclosingInstance.strategy.FieldNameX, true); ptY = FieldCache.DEFAULT.GetDoubles(reader, enclosingInstance.strategy.FieldNameY, true); validX = FieldCache.DEFAULT.GetDocsWithField(reader, enclosingInstance.strategy.FieldNameX); validY = FieldCache.DEFAULT.GetDocsWithField(reader, enclosingInstance.strategy.FieldNameY); from = enclosingInstance.from; calculator = enclosingInstance.strategy.SpatialContext.GetDistCalc(); nullValue = (enclosingInstance.strategy.SpatialContext.IsGeo() ? 180 : double.MaxValue); }
private static void MakeCorrectedGpsForDoppler(DataTable gpsRawTable, InsertConfig.GpsCorrection correction) { DataTable correctedGpsTable = DataTableUtil.GetCorrectedGpsDopplerTable(); #region インデックスが 0 の場合 DataRow firstRow = correctedGpsTable.NewRow(); CopyRawDataDopplerToCorrectedRow(firstRow, gpsRawTable.Rows[0]); firstRow.SetField(CorrectedGpsDao.ColumnDistanceDifference, 0); //firstRow.SetField(CorrectedGpsDao.ColumnSpeed, 0); firstRow.SetField(CorrectedGpsDao.ColumnHeading, 0); var meshAndAltitude = AltitudeCalculator.GetInstance().CalcAltitude( gpsRawTable.Rows[0].Field <double>(CorrectedGpsDao.ColumnLatitude), gpsRawTable.Rows[0].Field <double>(CorrectedGpsDao.ColumnLongitude)); firstRow.SetField(CorrectedGpsDao.ColumnTerrainAltitude, meshAndAltitude.Item2); var linkAndTheta = LinkMatcher.GetInstance().MatchLink( firstRow.Field <double>(CorrectedGpsDao.ColumnLatitude), firstRow.Field <double>(CorrectedGpsDao.ColumnLongitude), 0f); firstRow.SetField(CorrectedGpsDao.ColumnLinkId, linkAndTheta.Item1); firstRow.SetField(CorrectedGpsDao.ColumnRoadTheta, linkAndTheta.Item2); correctedGpsTable.Rows.Add(firstRow); #endregion #region インデックスがiの場合 for (int i = 1; i < gpsRawTable.Rows.Count - 1; i++) { DataRow row = correctedGpsTable.NewRow(); CopyRawDataDopplerToCorrectedRow(row, gpsRawTable.Rows[i]); // 距離の算出 row.SetField(CorrectedGpsDao.ColumnDistanceDifference, DistanceCalculator.CalcDistance( gpsRawTable.Rows[i - 1].Field <double>(AndroidGpsRawDao.ColumnLatitude), gpsRawTable.Rows[i - 1].Field <double>(AndroidGpsRawDao.ColumnLongitude), gpsRawTable.Rows[i].Field <double>(AndroidGpsRawDao.ColumnLatitude), gpsRawTable.Rows[i].Field <double>(AndroidGpsRawDao.ColumnLongitude))); meshAndAltitude = AltitudeCalculator.GetInstance().CalcAltitude( gpsRawTable.Rows[i].Field <double>(CorrectedGpsDao.ColumnLatitude), gpsRawTable.Rows[i].Field <double>(CorrectedGpsDao.ColumnLongitude)); row.SetField(CorrectedGpsDao.ColumnTerrainAltitude, meshAndAltitude.Item2); // 速度の算出 //row.SetField(CorrectedGpsDao.ColumnSpeed, SpeedCalculator.CalcSpeed( // gpsRawTable.Rows[i - 1].Field<double>(AndroidGpsRawDao.ColumnLatitude), // gpsRawTable.Rows[i - 1].Field<double>(AndroidGpsRawDao.ColumnLongitude), // gpsRawTable.Rows[i - 1].Field<DateTime>(AndroidGpsRawDao.ColumnJst), // gpsRawTable.Rows[i + 1].Field<double>(AndroidGpsRawDao.ColumnLatitude), // gpsRawTable.Rows[i + 1].Field<double>(AndroidGpsRawDao.ColumnLongitude), // gpsRawTable.Rows[i + 1].Field<DateTime>(AndroidGpsRawDao.ColumnJst), // gpsRawTable.Rows[i].Field<double>(AndroidGpsRawDao.ColumnLatitude), // gpsRawTable.Rows[i].Field<double>(AndroidGpsRawDao.ColumnLongitude))); //速度が1km以上になったらHEADINGを更新する(停止時に1つ1つ計算するとHEADINDが暴れるため) if (row.Field <Single?>(CorrectedGpsDao.ColumnSpeed) > 1.0) { row.SetField(CorrectedGpsDao.ColumnHeading, HeadingCalculator.CalcHeading( gpsRawTable.Rows[i - 1].Field <double>(AndroidGpsRawDao.ColumnLatitude), gpsRawTable.Rows[i - 1].Field <double>(AndroidGpsRawDao.ColumnLongitude), gpsRawTable.Rows[i].Field <double>(AndroidGpsRawDao.ColumnLatitude), gpsRawTable.Rows[i].Field <double>(AndroidGpsRawDao.ColumnLongitude))); } else { row.SetField(CorrectedGpsDao.ColumnHeading, correctedGpsTable.Rows[i - 1].Field <double>(CorrectedGpsDao.ColumnHeading)); } linkAndTheta = LinkMatcher.GetInstance().MatchLink( row.Field <double>(CorrectedGpsDao.ColumnLatitude), row.Field <double>(CorrectedGpsDao.ColumnLongitude), Convert.ToSingle(row.Field <double>(CorrectedGpsDao.ColumnHeading)) ); row.SetField(CorrectedGpsDao.ColumnLinkId, linkAndTheta.Item1); row.SetField(CorrectedGpsDao.ColumnRoadTheta, linkAndTheta.Item2); correctedGpsTable.Rows.Add(row); } #endregion #region インデックスが最後の場合 DataRow lastRow = correctedGpsTable.NewRow(); CopyRawDataDopplerToCorrectedRow(lastRow, gpsRawTable.Rows[gpsRawTable.Rows.Count - 1]); lastRow.SetField(CorrectedGpsDao.ColumnDistanceDifference, 0); lastRow.SetField(CorrectedGpsDao.ColumnSpeed, 0); lastRow.SetField(CorrectedGpsDao.ColumnHeading, 0); meshAndAltitude = AltitudeCalculator.GetInstance().CalcAltitude( gpsRawTable.Rows[gpsRawTable.Rows.Count - 1].Field <double>(CorrectedGpsDao.ColumnLatitude), gpsRawTable.Rows[gpsRawTable.Rows.Count - 1].Field <double>(CorrectedGpsDao.ColumnLongitude)); lastRow.SetField(CorrectedGpsDao.ColumnTerrainAltitude, meshAndAltitude.Item2); linkAndTheta = LinkMatcher.GetInstance().MatchLink( firstRow.Field <double>(CorrectedGpsDao.ColumnLatitude), firstRow.Field <double>(CorrectedGpsDao.ColumnLongitude), 0f); lastRow.SetField(CorrectedGpsDao.ColumnLinkId, linkAndTheta.Item1); lastRow.SetField(CorrectedGpsDao.ColumnRoadTheta, linkAndTheta.Item2); correctedGpsTable.Rows.Add(lastRow); #endregion // ファイルごとの挿入なので主キー違反があっても挿入されないだけ if (correction == InsertConfig.GpsCorrection.DopplerSpeed) { CorrectedGPSDopplerDao.Insert(correctedGpsTable); } }
public bool distanceCheck(Vector3 target, Vector3 currentPoint, float minChange) { return(DistanceCalculator.squareEuclidianDistance(target, currentPoint) >= minChange); }
public RoundingDistCalc(DistanceCalculator _delegate) { this._delegate = _delegate; }
public PlayersService(BoardZContext context, DistanceCalculator distanceCalculator) { Context = context; DistanceCalculator = distanceCalculator; }
public AbsoluteEuclideanDistBelowThresholdIsAMatch(double distanceThreshold) { calculator = new EuclideanDistanceCalculator(); this.distanceThreshold = distanceThreshold; featureExtractor = new PreprocessorAndFeatureExtractor(frameRate); }
public void TracePathTestWithPalindromicContig() { const int KmerLengthConst = 6; const int DangleThreshold = 3; const int RedundantThreshold = 7; List <ISequence> sequences = new List <ISequence>(); Sequence seq = new Sequence(Alphabets.DNA, "ATGCCTC".Select(a => (byte)a).ToArray()); seq.ID = ">10.x1:abc"; sequences.Add(seq); seq = new Sequence(Alphabets.DNA, "CCTCCTAT".Select(a => (byte)a).ToArray()); seq.ID = "1"; sequences.Add(seq); seq = new Sequence(Alphabets.DNA, "TCCTATC".Select(a => (byte)a).ToArray()); seq.ID = "2"; sequences.Add(seq); seq = new Sequence(Alphabets.DNA, "TGCCTCCT".Select(a => (byte)a).ToArray()); seq.ID = "3"; sequences.Add(seq); seq = new Sequence(Alphabets.DNA, "ATCTTAGC".Select(a => (byte)a).ToArray()); seq.ID = "4"; sequences.Add(seq); seq = new Sequence(Alphabets.DNA, "CTATCTTAG".Select(a => (byte)a).ToArray()); seq.ID = "5"; sequences.Add(seq); seq = new Sequence(Alphabets.DNA, "CTTAGCG".Select(a => (byte)a).ToArray()); seq.ID = "6"; sequences.Add(seq); seq = new Sequence(Alphabets.DNA, "GCCTCCTAT".Select(a => (byte)a).ToArray()); seq.ID = ">8.x1:abc"; sequences.Add(seq); seq = new Sequence(Alphabets.DNA, "TAGCGCGCTA".Select(a => (byte)a).ToArray()); seq.ID = ">8.y1:abc"; sequences.Add(seq); seq = new Sequence(Alphabets.DNA, "AGCGCGC".Select(a => (byte)a).ToArray()); seq.ID = ">9.x1:abc"; sequences.Add(seq); seq = new Sequence(Alphabets.DNA, "TTTTTT".Select(a => (byte)a).ToArray()); seq.ID = "7"; sequences.Add(seq); seq = new Sequence(Alphabets.DNA, "TTTTTAAA".Select(a => (byte)a).ToArray()); seq.ID = "8"; sequences.Add(seq); seq = new Sequence(Alphabets.DNA, "TAAAAA".Select(a => (byte)a).ToArray()); seq.ID = "9"; sequences.Add(seq); seq = new Sequence(Alphabets.DNA, "TTTTAG".Select(a => (byte)a).ToArray()); seq.ID = "10"; sequences.Add(seq); seq = new Sequence(Alphabets.DNA, "TTTAGC".Select(a => (byte)a).ToArray()); seq.ID = "11"; sequences.Add(seq); seq = new Sequence(Alphabets.DNA, "GCGCGCCGCGCG".Select(a => (byte)a).ToArray()); seq.ID = "12"; sequences.Add(seq); KmerLength = KmerLengthConst; SequenceReads.Clear(); SetSequenceReads(sequences); CreateGraph(); DanglingLinksThreshold = DangleThreshold; DanglingLinksPurger = new DanglingLinksPurger(DangleThreshold); RedundantPathLengthThreshold = RedundantThreshold; RedundantPathsPurger = new RedundantPathsPurger(RedundantThreshold); UnDangleGraph(); RemoveRedundancy(); IList <ISequence> contigs = BuildContigs().ToList(); ReadContigMapper mapper = new ReadContigMapper(); ReadContigMap maps = mapper.Map(contigs, sequences, KmerLengthConst); MatePairMapper builder = new MatePairMapper(); CloneLibrary.Instance.AddLibrary("abc", (float)5, (float)15); ContigMatePairs pairedReads = builder.MapContigToMatePairs(sequences, maps); ContigMatePairs overlap; OrientationBasedMatePairFilter filter = new OrientationBasedMatePairFilter(); overlap = filter.FilterPairedReads(pairedReads, 0); DistanceCalculator dist = new DistanceCalculator(overlap); overlap = dist.CalculateDistance(); ContigGraph graph = new ContigGraph(); graph.BuildContigGraph(contigs, this.KmerLength); TracePath path = new TracePath(); IList <ScaffoldPath> paths = path.FindPaths(graph, overlap, KmerLengthConst, 3); Assert.AreEqual(paths.Count, 3); Assert.AreEqual(paths.First().Count, 3); ScaffoldPath scaffold = paths.First(); Assert.IsTrue(new string(graph.GetNodeSequence(scaffold[0].Key).Select(a => (char)a).ToArray()).Equals("ATGCCTCCTATCTTAGC")); Assert.IsTrue(new string(graph.GetNodeSequence(scaffold[1].Key).Select(a => (char)a).ToArray()).Equals("TTAGCGCG")); Assert.IsTrue(new string(graph.GetNodeSequence(scaffold[2].Key).Select(a => (char)a).ToArray()).Equals("GCGCGC")); }
protected void InitCalculator() { String calcStr; if (!Args.TryGetValue("distCalculator", out calcStr) || calcStr == null) return; if (calcStr.Equals("haversine", StringComparison.InvariantCultureIgnoreCase)) { Calculator = new GeodesicSphereDistCalc.Haversine(Units.EarthRadius()); } else if (calcStr.Equals("lawOfCosines", StringComparison.InvariantCultureIgnoreCase)) { Calculator = new GeodesicSphereDistCalc.LawOfCosines(Units.EarthRadius()); } else if (calcStr.Equals("vincentySphere", StringComparison.InvariantCultureIgnoreCase)) { Calculator = new GeodesicSphereDistCalc.Vincenty(Units.EarthRadius()); } else if (calcStr.Equals("cartesian", StringComparison.InvariantCultureIgnoreCase)) { Calculator = new CartesianDistCalc(); } else if (calcStr.Equals("cartesian^2", StringComparison.InvariantCultureIgnoreCase)) { Calculator = new CartesianDistCalc(true); } else { throw new Exception("Unknown calculator: " + calcStr); } }
private static void MakeCorrectedGps(DataTable gpsRawTable, InsertConfig.GpsCorrection correction) { DataTable correctedGpsTable = DataTableUtil.GetCorrectedGpsTable(); #region インデックスが 0 の場合 DataRow firstRow = correctedGpsTable.NewRow(); CopyRawDataToCorrectedRow(firstRow, gpsRawTable.Rows[0]); firstRow.SetField(CorrectedGpsDao.ColumnDistanceDifference, 0); firstRow.SetField(CorrectedGpsDao.ColumnSpeed, 0); firstRow.SetField(CorrectedGpsDao.ColumnHeading, 0); correctedGpsTable.Rows.Add(firstRow); #endregion #region インデックスがiの場合 for (int i = 1; i < gpsRawTable.Rows.Count - 1; i++) { DataRow row = correctedGpsTable.NewRow(); CopyRawDataToCorrectedRow(row, gpsRawTable.Rows[i]); // 距離の算出 row.SetField(CorrectedGpsDao.ColumnDistanceDifference, DistanceCalculator.CalcDistance( gpsRawTable.Rows[i - 1].Field <double>(AndroidGpsRawDao.ColumnLatitude), gpsRawTable.Rows[i - 1].Field <double>(AndroidGpsRawDao.ColumnLongitude), gpsRawTable.Rows[i].Field <double>(AndroidGpsRawDao.ColumnLatitude), gpsRawTable.Rows[i].Field <double>(AndroidGpsRawDao.ColumnLongitude))); // 速度の算出 row.SetField(CorrectedGpsDao.ColumnSpeed, SpeedCalculator.CalcSpeed( gpsRawTable.Rows[i - 1].Field <double>(AndroidGpsRawDao.ColumnLatitude), gpsRawTable.Rows[i - 1].Field <double>(AndroidGpsRawDao.ColumnLongitude), gpsRawTable.Rows[i - 1].Field <DateTime>(AndroidGpsRawDao.ColumnJst), gpsRawTable.Rows[i + 1].Field <double>(AndroidGpsRawDao.ColumnLatitude), gpsRawTable.Rows[i + 1].Field <double>(AndroidGpsRawDao.ColumnLongitude), gpsRawTable.Rows[i + 1].Field <DateTime>(AndroidGpsRawDao.ColumnJst), gpsRawTable.Rows[i].Field <double>(AndroidGpsRawDao.ColumnLatitude), gpsRawTable.Rows[i].Field <double>(AndroidGpsRawDao.ColumnLongitude))); //速度が1km以上になったらHEADINGを更新する(停止時に1つ1つ計算するとHEADINDが暴れるため) if (row.Field <Single?>(CorrectedGpsDao.ColumnSpeed) > 1.0) { row.SetField(CorrectedGpsDao.ColumnHeading, HeadingCalculator.CalcHeading( gpsRawTable.Rows[i - 1].Field <double>(AndroidGpsRawDao.ColumnLatitude), gpsRawTable.Rows[i - 1].Field <double>(AndroidGpsRawDao.ColumnLongitude), gpsRawTable.Rows[i].Field <double>(AndroidGpsRawDao.ColumnLatitude), gpsRawTable.Rows[i].Field <double>(AndroidGpsRawDao.ColumnLongitude))); } else { row.SetField(CorrectedGpsDao.ColumnHeading, correctedGpsTable.Rows[i - 1].Field <double>(CorrectedGpsDao.ColumnHeading)); } correctedGpsTable.Rows.Add(row); } #endregion #region インデックスが最後の場合 DataRow lastRow = correctedGpsTable.NewRow(); CopyRawDataToCorrectedRow(lastRow, gpsRawTable.Rows[gpsRawTable.Rows.Count - 1]); lastRow.SetField(CorrectedGpsDao.ColumnDistanceDifference, 0); lastRow.SetField(CorrectedGpsDao.ColumnSpeed, 0); lastRow.SetField(CorrectedGpsDao.ColumnHeading, 0); correctedGpsTable.Rows.Add(lastRow); #endregion #region データ挿入 // ファイルごとの挿入なので主キー違反があっても挿入されないだけ if (correction == InsertConfig.GpsCorrection.SpeedLPFMapMatching)//速度にローパスフィルタを適用 { DataTable correctedGpsSpeedLPFTable = LowPassFilter.speedLowPassFilter(correctedGpsTable, 0.05); CorrectedGpsSpeedLPF005MMDao.Insert(correctedGpsSpeedLPFTable); } else if (correction == InsertConfig.GpsCorrection.MapMatching) { CorrectedGPSMMDao.Insert(correctedGpsTable); } else if (correction == InsertConfig.GpsCorrection.Normal) { CorrectedGpsDao.Insert(correctedGpsTable); } #endregion }