Example #1
0
    public static void Main()
    {
        IInputContainer           inputContainer           = new InputContainer(new ConsoleInputGetter());
        IInitialCheckpointGuesser initialCheckpointGuesser = new InitialCheckpointGuesser(inputContainer);
        ICheckpointMemory         checkpointMemory         = new CheckpointMemory();
        IBoostUseCalculator       boostUseCalculator       = new BoostUseCalculator(checkpointMemory);
        ISpeedCalculator          speedCalculator          = new SpeedCalculator();
        IAngleCalculator          angleCalculator          = new AngleCalculator();

        IGamestateCalculator gamestateCalculator = new GamestateCalculator(inputContainer);

        ITargetFinding targetFinding = new SmartTargetFinder(checkpointMemory, inputContainer, speedCalculator,
                                                             angleCalculator);
        //ITargetFinding targetFinding = new SimpleTargetFinder();

        ISlowDownCalculator linearMovementAngleSlowDownCalculator = new LinearMovementAngleSlowDownCalculator(null,
                                                                                                              gamestateCalculator, inputContainer, angleCalculator, checkpointMemory);
        ISlowDownCalculator distanceSlowDownCalculator =
            new SimpleDistanceSlowDownCalculator(linearMovementAngleSlowDownCalculator, checkpointMemory,
                                                 inputContainer);
        ISlowDownCalculator hitPredictionSlowDownCalculator =
            new HitPredictionSlowDownCalculator(distanceSlowDownCalculator, gamestateCalculator, checkpointMemory,
                                                inputContainer);
        ISlowDownCalculator slowDownCalculator = new LinearAngleSlowDownCalculator(hitPredictionSlowDownCalculator,
                                                                                   inputContainer);
        //ISlowDownCalculator slowDownCalculator = new SimpleAngleSlowDownCalculator(null,inputContainer);

        IThrustCalculator thrustCalculator = new AngleAndDistThrustCalculator(checkpointMemory, boostUseCalculator,
                                                                              angleCalculator,
                                                                              slowDownCalculator, gamestateCalculator);

        new Player().Start(inputContainer, initialCheckpointGuesser, checkpointMemory, boostUseCalculator, targetFinding,
                           thrustCalculator, speedCalculator, gamestateCalculator);
    }
Example #2
0
        /// <summary>
        /// 检查是否下载完成
        /// </summary>
        /// <param name="speedCalculator"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        private async Task <int> CheckDownloadInfoAsync(SpeedCalculator speedCalculator, CancellationToken cancellationToken)
        {
            var retryTasks = new List <DownloadTask>();
            var retryCount = 0;
            int errorCount = 0;
            Func <DownloadSegmentInfo, bool> predicate = GetCheckDownloadSegmentInfoFunc();

            while ((errorCount = DownloadInfo.Count(predicate)) > 0)
            {
                if (retryCount >= 3)
                {
                    break;
                }
                Console.WriteLine($"错误数据个数:{errorCount},开始第{retryCount}次重试");
                foreach (var item in DownloadInfo)
                {
                    if (predicate(item))
                    {
                        item.SrcStream = null;
                        var task = DownloadSegmentFileAsync(item, (r, percentage) =>
                        {
                            speedCalculator.CurrentValue += r;
                        }, cancellationToken);
                        retryTasks.Add(task);
                    }
                }
                await retryTasks.StartAndWaitAllThrottled(MaxThreadCount);

                retryCount++;
            }
            return(errorCount);
        }
Example #3
0
        public override void Start()
        {
            if (State != DownloadState.Prepared &&
                State != DownloadState.Pause)
            {
                return;
            }
            State = DownloadState.Downloading;
            //每次重新开始

            Message.TempFilePath  = ApplicationData.Current.LocalCacheFolder.Path + @"\" + StorageTools.StorageManager.GetTemporaryName() + ".tmp";
            speedHelper           = new SpeedCalculator();
            speedHelper.IsEnabled = true;

            client                          = new WebClient();
            client.Credentials              = CredentialCache.DefaultCredentials;
            client.DownloadFileCompleted   += Client_DownloadFileCompleted;
            client.DownloadProgressChanged += (o, e) =>
            {
                if (o != client)
                {
                    return;
                }
                speedHelper.CurrentValue = e.BytesReceived;
                _prog_.Speed             = speedHelper.Speed;
                _prog_.AverageSpeed      = speedHelper.AverageSpeed;
                _prog_.TargetValue       = null;
                _prog_.CurrentValue      = speedHelper.CurrentValue;
                DownloadProgressChanged?.Invoke(_prog_);
            };
            client.DownloadFileAsync(new Uri(Message.URL), Message.TempFilePath);
        }
        static void Main(string[] args)
        {
            var positionCalculator = new PositionCalculator();

            // Using the real transponder data receiver
            var receiver = TransponderReceiverFactory.CreateTransponderDataReceiver();

            // Dependency injection with the real TDR
            var formatter = new Formatter(receiver);

            var speed      = new SpeedCalculator();
            var position   = new PositionCalculator();
            var clear      = new ClearConsole();
            var render     = new RenderData(clear);
            var writer     = new LogWriter();
            var log        = new Log(writer);
            var seperation = new SeperationCalculator(log);
            var system     = new AirTrafficController(formatter, seperation, render, position, speed, clear);

            // Let the real TDR execute in the background
            while (true)
            {
                Thread.Sleep(1000);
            }
        }
Example #5
0
        public override void Pause()
        {
            if (State != DownloadState.Downloading)
            {
                return;
            }
            //临时文件统一删除,由于无法获得文件大小,每次下载都是一次性的
            Message.TempFilePath = "";
            if (client != null)
            {
                client.CancelAsync();
                client.Dispose();
                client = null;
            }

            if (speedHelper != null)
            {
                speedHelper.Dispose();
                speedHelper = null;
            }

            _prog_.AverageSpeed = _prog_.Speed = _prog_.CurrentValue = 0;
            DownloadProgressChanged(_prog_);
            State = DownloadState.Pause;
        }
Example #6
0
 // Use this for initialization
 void Start()
 {
     attackPrepare = false;
     attacking = false;
     if (!sc) {
         sc = GetComponent<SpeedCalculator>();
     }
 }
Example #7
0
        public override void Clear(ExecutionResult executionResult)
        {
            var speed = SpeedCalculator.CalculateBenchmark(executionResult.Output);
            var stat  = new SpeedStat {
                Mode = job.Command.M, Speed = speed.ToString()
            };

            ClientProxyProvider.Client.SendAgentSpeedStats(stat).ConfigureAwait(false);
        }
        public void TestMethod1()
        {
            SpeedCalculator calculateSpeed = new SpeedCalculator();

            var actual   = calculateSpeed.GetCurrentSpeed("15", "3");
            var expected = 5;

            Assert.AreEqual(expected, actual);
        }
        public void TestMethod2()
        {
            SpeedCalculator calculateSpeed = new SpeedCalculator();

            var actual   = calculateSpeed.GetCurrentSpeed("fem", "tvåhundra sextio fem");
            var expected = 15.32473;

            Assert.AreEqual(expected, actual);
        }
        public void TestMethod3()
        {
            SpeedCalculator calculateSpeed = new SpeedCalculator();

            var actual   = calculateSpeed.GetCurrentSpeed("666.262M", "316L");
            var expected = 0.0545454545454545;

            Assert.AreEqual(expected, actual);
        }
Example #11
0
 private void DisposeSpeedHelper()
 {
     if (speedHelper == null)
     {
         return;
     }
     speedHelper.IsEnabled = false;
     speedHelper.Dispose();
     speedHelper = null;
 }
Example #12
0
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="progressAction"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task DownloadFileAsync(Action <ProgressInfo> progressAction, CancellationToken cancellationToken = default)
        {
            if (IsDownloaded)
            {
                return;
            }
            SpeedCalculator speedCalculator = new SpeedCalculator();
            ProgressInfo    progressInfo    = new ProgressInfo();
            bool            isCompleted     = false;

            speedCalculator.Updated += async(h) =>
            {
                progressInfo.AverageSpeed = speedCalculator.AverageSpeed;
                progressInfo.CurrentValue = speedCalculator.CurrentValue;
                progressInfo.Speed        = speedCalculator.Speed;
                progressInfo.Percentage   = DownloadInfo.Percentage;
                progressInfo.TargetValue  = DownloadInfo?.Size;
                progressAction.Invoke(progressInfo);
                var count = DownloadInfo.Count(m => m.Size == 0);
                //Console.WriteLine("count " + count + " size " + DownloadInfo.Size + " read size " + DownloadInfo.TotalReadBytes);
                if (isCompleted)
                {
                    speedCalculator.Stop();
                }
                else
                {
                    await SaveDownloadInfoAsync();
                }
            };

            foreach (var segment in DownloadInfo)
            {
                if (segment.TotalReadBytes != 0 && segment.TotalReadBytes >= segment.Size)
                {
                    continue;
                }
                var task = DownloadSegmentFileAsync(segment, (r, percentage) =>
                {
                    speedCalculator.CurrentValue += r;
                }, cancellationToken);
                FileSegmentaionTasks.Add(task);
            }
            speedCalculator.Start();
            await FileSegmentaionTasks.StartAndWaitAllThrottled(MaxThreadCount);

            var errorCount = await CheckDownloadInfoAsync(speedCalculator, cancellationToken);

            ///错误数量
            if (errorCount == 0)
            {
                await ReconstructSegmentsAsync();
                await CompleteAsync(true);
            }
            isCompleted = true;
        }
        public Speed GetPlaneSpeed()
        {
            return(FsxOperation(() =>
            {
                var trueAirSpeed = GetFsxData(FsxDataOffset.TrueAirSpeed);
                var indicatedAirSpeed = GetFsxData(FsxDataOffset.IndicatedAirSpeed);
                var verticalSpeed = GetFsxData(FsxDataOffset.VerticalSpeed);

                return SpeedCalculator.CalculateSpeed(trueAirSpeed, indicatedAirSpeed, verticalSpeed);
            }));
        }
    /// <summary>
    /// スピードにブレーキをかける処理
    /// ■brake:入力
    /// ■engineSpeed:速度
    /// </summary>
    /// <param name="brake"></param>
    /// <param name="engineSpeed"></param>
    /// <returns></returns>
    public float Brake(float brake, float engineSpeed)
    {
        //reverse時のブレーキを有効にする為、符号を取ってから速度を減らしてる
        float sign = Mathf.Sign(engineSpeed);

        engineSpeed  = Mathf.Abs(engineSpeed);
        engineSpeed += SpeedCalculator.CalcBrakeAmt(brake, mEngineSettings.BrakePower);
        engineSpeed  = Mathf.Clamp(engineSpeed, 0.0f, Mathf.Infinity);
        engineSpeed *= sign;
        return(engineSpeed);
    }
    /*■■■PUBLIC■■■*/
    /// <summary>
    /// 速度を増減させる処理
    /// </summary>
    /// <param name="engineSpeed"></param>
    /// <param name="accel"></param>
    /// <returns></returns>
    public float CalcEngineSpeed(float engineSpeed, float accel)
    {
        accel = Mathf.Clamp01(accel);
        bool isNeutral = (mCurrentGear.Value == GearState.NEUTRAL);
        bool isReverse = (mCurrentGear.Value == GearState.REVERSE);
        bool isStop    = (Mathf.Approximately(engineSpeed, 0.0f));

        if (isNeutral)
        {
            accel = 0.0f;
        }

        /*ギア変更後速度が現在の最高速度より高い場合、accelを0にする*/
        if (!isReverse && engineSpeed > mMaxSpeed)
        {
            accel = 0.0f;
        }

        /*ギアがニュートラル"でない"かつ、エンジン回転数が0以下だった場合、
         * 値を代入する。0だと動かなくなる為*/
        if (!isNeutral && isStop)
        {
            engineSpeed = VehicleSettings.EngineSettings.LOWEST_ENGINE_SPEED;
        }

        //回転数上げる処理。リバースギアのときはアクセル踏むと逆に進む
        if (!isReverse)
        {
            engineSpeed += SpeedCalculator.CalcRotToAdd(engineSpeed, mAccPow, accel, mNeedSpeed);
        }
        else
        {
            engineSpeed -= SpeedCalculator.CalcRotToAdd(engineSpeed, mAccPow, accel, mNeedSpeed);
        }

        //アクセルにあわせて回転数の限界を調節する処理

        /*リバースギアに入れた時に減速が早すぎる為。
         * engine brakeの値を0にするとリバースギアで下がったら止まらなくなる*/
        if (!(isReverse && (engineSpeed > 0.0f)))
        {
            engineSpeed = SpeedLimitController.EngineBrake(engineSpeed, accel, mMaxSpeed, mEngineBrakePow);
        }

        //ギアを下げたとき最大回転数をlerpで逓減する処理
        mCurrentMaxSpeed = SpeedLimitController.DecreaseMaxSpeed(mMaxSpeed, mPreMaxSpeed, mCurrentMaxSpeed, mEngineSettings.DecreaseSpeed);

        //ペナルティ用
        Penalty();

        mCurrentMaxSpeed = Mathf.Abs(mCurrentMaxSpeed);
        //範囲内に収める処理
        return(Mathf.Clamp(engineSpeed, mLowestSpeed, mCurrentMaxSpeed));
    }
Example #16
0
 public override void Dispose()
 {
     if (State == DownloadState.Disposed)
     {
         return;
     }
     DisposeThreads();
     speedHelper.IsEnabled = false;
     speedHelper.Dispose();
     speedHelper = null;
     StartDisposeTemporaryFile();
     State = DownloadState.Disposed;
 }
    public float BrakeAT(float brake, float engineSpeed)
    {
        float val = 1.0f;

        if (engineSpeed <= 0.0f)
        {
            val = 8.0f;
        }                                       //エンジンブレーキが0に近づける力にブレーキが負ける為かける
        engineSpeed += SpeedCalculator.CalcBrakeAmt(brake, mEngineSettings.BrakePower) * val;
        engineSpeed  = Mathf.Clamp(engineSpeed, mLowestSpeed, Mathf.Infinity);

        return(engineSpeed);
    }
Example #18
0
        public KeyboardTrainerPresenter(
            IKeyboardTrainerView view,
            KeyCharsProvider keyCharsProvider,
            SourceString sourceString,
            SpeedCalculator speedCalculator
            )
        {
            this.keyCharsProvider = keyCharsProvider;
            this.sourceString     = sourceString;
            this.speedCalculator  = speedCalculator;
            this.view             = view;

            SetUpTimer();
            SubscribeToEvent();
        }
        public void Post([FromBody] VibrationData data)
        {
            var previousData = _dbContext.VibrationDatas.Where(vb => vb.RouteId == data.RouteId).OrderByDescending(vb => vb.TimeStamp).FirstOrDefault();

            if (previousData == null)
            {
                //First mesurement in route
                var route      = _dbContext.Routes.Where(r => r.RouteId == data.RouteId).FirstOrDefault();
                var routeStart = new RouteStart {
                    BeginTime = route.BeginTime, StartLocationLatitude = route.StartLocationLatitude, StartLocationLongitude = route.StartLocationLongitude
                };
                SpeedCalculator.CalculateSpeed(routeStart, data);
            }

            else
            {
                SpeedCalculator.CalculateSpeed(previousData, data);
            }
            _dbContext.Add(data);
            _dbContext.SaveChanges();
        }
Example #20
0
        public override void Clear(ExecutionResult executionResult)
        {
            paths.HashFile.SoftDelete("hashfile");

            if (!executionResult.IsSuccessful)
            {
                paths.OutputFile.SoftDelete("outfile");
                paths.PotFile.SoftDelete("potfile");
                return;
            }

            var err = executionResult.Errors.FirstOrDefault(e => e.Contains("No hashes loaded") || e.Contains("Unhandled Exception"));

            if (err != null)
            {
                ClientProxyProvider.Client.SendJobEnd(new { error = err }, job.JobId).ConfigureAwait(false);
                paths.OutputFile.SoftDelete("outfile");
                paths.PotFile.SoftDelete("potfile");
                return;
            }

            var speed = SpeedCalculator.CalculateFact(executionResult.Output);

            if (File.Exists(paths.OutputFile))
            {
                var outfile = Convert.ToBase64String(File.ReadAllBytes(paths.OutputFile));
                var potfile = Convert.ToBase64String(File.ReadAllBytes(paths.PotFile));

                ClientProxyProvider.Client.SendJobEnd(new { outfile, potfile, speed }, job.JobId).ConfigureAwait(false);
                paths.OutputFile.SoftDelete("outfile");
                paths.PotFile.SoftDelete("potfile");
            }
            else
            {
                Logging.Log.Message("Output file не существует, сорян.");
                ClientProxyProvider.Client.SendJobEnd(new { potfile = string.Empty, speed }, job.JobId).ConfigureAwait(false);
            }
        }
Example #21
0
        private async void SpeedUpdated(SpeedCalculator sender)
        {
            await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                DownloadTimeTextBlock.Text = sender.RunningTime.ToString(@"hh\:mm\:ss");
                UpdateIntoDynamicLabelCollection(SpeedText,
                                                 $"{((long)sender.Speed).SizedString()} / s");

                if (Downloader != null)
                {
                    UpdateIntoDynamicLabelCollection(
                        $"{ErrorsText} / {RetriesText}",
                        $"{Downloader.Errors.Count} / {Downloader.Retries}");

                    if (Downloader.Progress is IMeasurableProgress mprogress)
                    {
                        double averageSpeed = sender.AverageSpeed;
                        if (averageSpeed > 0.0)
                        {
                            double remainBytes       = (mprogress.TotalSize - mprogress.DownloadedSize);
                            double secondsPrediction = remainBytes / averageSpeed;
                            UpdateIntoDynamicLabelCollection(RemainingTimeText,
                                                             $"{TimeSpan.FromSeconds(secondsPrediction):hh\\:mm\\:ss}");
                        }
 //and in the other file
 public FTPDownloadFile()
 {
     bytesDownloaded = 0;
     Speed = new SpeedCalculator( this ); // CHANGE
 }
Example #23
0
        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 IEnumerable <RouteInfo> GetRoutesInfoForUser(int id)
        {
            var userRoutes = _dbContext.Routes.Where(r => r.UserId == id).ToList();
            var resultList = new List <RouteInfo>();
            var comparer   = new DataEqualityComparer();

            foreach (var userRoute in userRoutes)
            {
                var dataForRoute = _dbContext.VibrationDatas.Where(vd => vd.RouteId == userRoute.RouteId).ToList().Distinct(comparer).ToList();
                var minSpeed     = 0.0;
                var maxSpeed     = 0.0;
                var averageSpeed = 0.0;
                var distance     = 0.0;
                var timeSpan     = userRoute.EndTime - userRoute.BeginTime;
                var duration     = $"{timeSpan.Value.Hours.ToString("00")}:{timeSpan.Value.Minutes.ToString("00")}:{timeSpan.Value.Seconds.ToString("00")}";

                if (dataForRoute.Any())
                {
                    minSpeed = dataForRoute.First().Speed;
                    maxSpeed = dataForRoute.First().Speed;

                    foreach (var data in dataForRoute)
                    {
                        if (data.Speed < minSpeed)
                        {
                            minSpeed = data.Speed;
                        }
                        if (data.Speed > maxSpeed)
                        {
                            maxSpeed = data.Speed;
                        }
                        averageSpeed += data.Speed;
                    }

                    averageSpeed /= dataForRoute.Count();
                    for (var i = 0; i < dataForRoute.Count(); i++)
                    {
                        if (i == 0)
                        {
                            distance += SpeedCalculator.CalculateDistance(userRoute.StartLocationLongitude, userRoute.StartLocationLatitude, dataForRoute[i].LocationLongitude, dataForRoute[i].LocationLatitude);
                        }

                        else if (i == dataForRoute.Count() - 1)
                        {
                            distance += SpeedCalculator.CalculateDistance(dataForRoute[i].LocationLongitude, dataForRoute[i].LocationLatitude, userRoute.EndLocationLongitude.Value, userRoute.EndLocationLatitude.Value);
                        }

                        else
                        {
                            distance += SpeedCalculator.CalculateDistance(dataForRoute[i - 1].LocationLongitude, dataForRoute[i - 1].LocationLatitude, dataForRoute[i].LocationLongitude, dataForRoute[i].LocationLatitude);
                        }
                    }
                }

                else
                {
                    distance = SpeedCalculator.CalculateDistance(userRoute.StartLocationLongitude, userRoute.StartLocationLatitude, userRoute.EndLocationLongitude.Value, userRoute.EndLocationLatitude.Value);
                    var timeDiff = userRoute.EndTime - userRoute.BeginTime;
                    var speed    = distance / Math.Abs(timeDiff.Value.TotalHours);
                    minSpeed     = speed;
                    maxSpeed     = speed;
                    averageSpeed = speed;
                }

                var result = new RouteInfo {
                    Route = userRoute, Data = dataForRoute, MaximumSpeed = maxSpeed, MinimumSpeed = minSpeed, AverageSpeed = averageSpeed, Distance = distance, Duration = duration
                };
                resultList.Add(result);
            }
            return(resultList);
        }
Example #25
0
        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);
        }
Example #26
0
 private async void SpeedUpdated(SpeedCalculator obj) =>
 await SpeedTextBlock.Dispatcher.RunAsync(
     CoreDispatcherPriority.Normal, () => {
     SpeedTextBlock.Text = ((long)obj.Speed).SizedString() + "/s";
 });
Example #27
0
 public Core()
 {
     _designer        = new GraphDesigner();
     _speedCalculator = new SpeedCalculator();
 }
Example #28
0
        private static void InsertCorrectedGps(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

            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 <Single>(CorrectedGpsDao.ColumnHeading));
                }

                correctedGpsTable.Rows.Add(row);
            }

            #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

            // ファイルごとの挿入なので主キー違反があっても挿入されないだけ
            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
            {
                CorrectedGpsDao.Insert(correctedGpsTable);
            }
        }
 // Use this for initialization
 void Start()
 {
     speedCalc = GameObject.Find("SpeedCalculator").GetComponent <SpeedCalculator>();
 }