Пример #1
0
        /// <summary>
        /// Gets number of steps for current day
        /// </summary>
        /// <returns><c>true</c> if steps were successfully fetched, <c>false</c> otherwise</returns>
        private async Task <bool> GetStepsAsync()
        {
            StepCounter stepCounter = null;

            try
            {
                stepCounter = await StepCounter.GetDefaultAsync();

                _steps = await stepCounter.GetStepCountForRangeAsync(
                    DateTime.Now.Date,
                    DateTime.Now - DateTime.Now.Date);
            }
            catch (Exception e)
            {
                _lastError = SenseHelper.GetSenseError(e.HResult);
                return(false);
            }
            finally
            {
                if (stepCounter != null)
                {
                    stepCounter.Dispose();
                }
            }
            return(true);
        }
Пример #2
0
        /// <summary>
        /// Gets number of steps for current day
        /// </summary>
        /// <returns><c>true</c> if steps were successfully fetched, <c>false</c> otherwise</returns>
        private async Task <bool> GetStepsAsync()
        {
            // First try the pedometer
            try
            {
                var readings = await Pedometer.GetSystemHistoryAsync(DateTime.Now.Date, DateTime.Now - DateTime.Now.Date);

                _steps = StepCountData.FromPedometerReadings(readings);
                return(true);
            }
            catch (Exception)
            {
                // Continue to the fallback
            }

            // Fall back to using Lumia Sensor Core.
            IStepCounter stepCounter = null;

            try
            {
                //var qualifiers = Windows.ApplicationModel.Resources.Core.ResourceContext.GetForCurrentView().QualifierValues;

                if (DeviceTypeHelper.GetDeviceFormFactorType() == DeviceFormFactorType.Phone)
                {
                    stepCounter = await StepCounter.GetDefaultAsync();

                    StepCount count = await stepCounter.GetStepCountForRangeAsync(DateTime.Now.Date, DateTime.Now - DateTime.Now.Date);

                    _steps = StepCountData.FromLumiaStepCount(count);
                }
                else
                {
                    var obj = await SenseRecording.LoadFromFileAsync("Simulations\\short recording.txt");

                    if (!await CallSensorCoreApiAsync(async() => {
                        stepCounter = await StepCounterSimulator.GetDefaultAsync(obj, DateTime.Now - TimeSpan.FromHours(12));
                        StepCount count = await stepCounter.GetStepCountForRangeAsync(DateTime.Now.Date, DateTime.Now - DateTime.Now.Date);
                        _steps = StepCountData.FromLumiaStepCount(count);
                    }))
                    {
                        return(false);
                    }
                }
            }
            catch (Exception e)
            {
                _lastError = SenseHelper.GetSenseError(e.HResult);
                return(false);
            }
            finally
            {
                if (stepCounter != null && typeof(StepCounter) == stepCounter.GetType())
                {
                    ((StepCounter)stepCounter).Dispose();
                }
            }
            return(true);
        }
Пример #3
0
        public async Task <StepCount> UpdateStepCountAsync(StepCount stepCount)
        {
            Request request = new Request(Method.PUT, $"patients/{stepCount.PatientId}/stepcounts/{stepCount.Id}");

            request.Body["patient_id"] = stepCount.PatientId;
            request.Body["count"]      = stepCount.Count;
            request.Body["date"]       = stepCount.Date.ToString("yyyy-MM-dd");
            return(await ExecuteAsync <StepCount>(request));
        }
Пример #4
0
        /// <summary>
        /// Returns step count for given day
        /// </summary>
        /// <returns>Step count for given day</returns>
        public async Task <StepCountData> GetTotalStepCountAsync(DateTime day)
        {
            if (_stepCounter != null && _sensorActive)
            {
                StepCount steps = await _stepCounter.GetStepCountForRangeAsync(day.Date, TimeSpan.FromDays(1));

                return(StepCountData.FromLumiaStepCount(steps));
            }
            return(null);
        }
Пример #5
0
        /// <summary>
        /// Factory that creates a StepCountData object from a Lumia StepCount
        /// </summary>
        /// <param name="stepCount"></param>
        /// <returns></returns>
        public static StepCountData FromLumiaStepCount(StepCount stepCount)
        {
            StepCountData steps = new StepCountData();

            steps.RunningCount = stepCount.RunningStepCount;
            steps.WalkingCount = stepCount.WalkingStepCount;
            steps.UnknownCount = 0;

            return(steps);
        }
Пример #6
0
        private static StepCount GetStepCount(IActualTraceStep step)
        {
            // build step string ID
            string stepId = step.GetStringId();

            if (!TraceValidator.s_stepCounts.ContainsKey(stepId))
            {
                TraceValidator.s_stepCounts.Add(stepId, new StepCount(step));
            }

            StepCount stepCount = TraceValidator.s_stepCounts[stepId];

            return(stepCount);
        }
Пример #7
0
        public void UpdateStepCount_Patient_Successful()
        {
            // Arrange
            Helpers.PatientLogin();
            StepCount stepCount = StepCountResource.CreateStepCount(1, 3652, new DateTime(2018, 12, 05));

            stepCount.Count = 4215;

            // Act
            stepCount = StepCountResource.UpdateStepCount(stepCount);

            // Assert
            Assert.AreEqual(4215, stepCount.Count);
            Assert.AreEqual(47, stepCount.Id);
        }
Пример #8
0
 private void displayUI()
 {
     if (scoreText)
     {
         scoreText.text = "Score: " + GetCumulativeReward().ToString("0.00");
     }
     if (stepText)
     {
         stepText.text = "Steps: " + StepCount.ToString() + " / " + maxEpisodeSteps;
     }
     if (lifeText)
     {
         lifeText.text = "Lives: " + controller.getLife() + " / 5";
     }
 }
Пример #9
0
        public void CreateStepCount_Patient_Successful()
        {
            // Arrange
            Helpers.PatientLogin();
            long     patientId = 1;
            int      count     = 4215;
            DateTime dateTime  = new DateTime(2018, 12, 05);

            // Act
            StepCount stepCount = StepCountResource.CreateStepCount(patientId, count, dateTime);

            // Assert
            Assert.AreEqual(patientId, stepCount.PatientId);
            Assert.AreEqual(count, stepCount.Count);
            Assert.AreEqual(47, stepCount.Id);
        }
Пример #10
0
 protected override int GetCompareTo(Report other)
 {
     if (other.FoodCount.CompareTo(FoodCount) == 0)
     {
         if (StepCount == other.StepCount)
         {
             return(KnownAs.CompareTo(other.KnownAs));
         }
         else
         {
             return(StepCount.CompareTo(other.StepCount));
         }
     }
     else
     {
         return(other.FoodCount.CompareTo(FoodCount));
     }
 }
Пример #11
0
        /// <summary>
        /// Gets number of steps for current day
        /// </summary>
        /// <returns><c>true</c> if steps were successfully fetched, <c>false</c> otherwise</returns>
        private async Task <bool> GetStepsAsync()
        {
            // First try the pedometer
            try
            {
                var readings = await Pedometer.GetSystemHistoryAsync(DateTime.Now.Date, DateTime.Now - DateTime.Now.Date);

                _steps = StepCountData.FromPedometerReadings(readings);
                return(true);
            }
            catch (Exception)
            {
                // Continue to the fallback
            }

            // Fall back to using Lumia Sensor Core.
            StepCounter stepCounter = null;

            try
            {
                stepCounter = await StepCounter.GetDefaultAsync();

                StepCount count = await stepCounter.GetStepCountForRangeAsync(
                    DateTime.Now.Date,
                    DateTime.Now - DateTime.Now.Date);

                _steps = StepCountData.FromLumiaStepCount(count);
            }
            catch (Exception e)
            {
                _lastError = SenseHelper.GetSenseError(e.HResult);
                return(false);
            }
            finally
            {
                if (stepCounter != null)
                {
                    stepCounter.Dispose();
                }
            }
            return(true);
        }
Пример #12
0
        /// <summary>
        /// Factory that creates a StepCountData object from a Lumia StepCount
        /// </summary>
        /// <param name="stepCount"></param>
        /// <returns></returns>
        public static StepCountData FromLumiaStepCount(StepCount stepCount)
        {
            StepCountData steps = new StepCountData();

            try
            {
                if (stepCount == null)
                {
                    return(steps);
                }
                steps.RunningCount = stepCount.RunningStepCount;
                steps.WalkingCount = stepCount.WalkingStepCount;
                steps.UnknownCount = 0;
            }
            catch (Exception)
            {
            }

            return(steps);
        }
Пример #13
0
 //GUI Stuff for connecting
 private void OnGUI()
 {
     GUILayout.BeginArea(new Rect(Screen.width / 2 - 100, 0, 200, 150));
     //If the player hasn't connected yet, allow the player to connect
     if (!DarkRiftAPI.isConnected)
     {
         _IP = GUILayout.TextField(_IP);
         if (GUILayout.Button("Connect"))
         {
             DarkRiftAPI.Connect(_IP);
             //Connect to the DarkRift server hosted on the machine with _IP IP Address
         }
     }
     if (!DoVisualize)
     {
         Texture2D tex = new Texture2D(1, 1);
         tex.SetPixel(1, 1, new Color32(255, 255, 255, 255));
         GUI.DrawTexture(new Rect(0, 0, Screen.width, Screen.height), tex);
         GUILayout.Label("Catching up", Style);
     }
     GUILayout.Label("Step Count: " + StepCount.ToString(), Style);
     GUILayout.EndArea();
 }
Пример #14
0
        /// <summary>
        /// Loads steps for the given day
        /// </summary>
        /// <param name="fetchDate">Date to fetch steps for</param>
        /// <returns>List of step counts per data point interval for the given day</returns>
        private async Task <Dictionary <DateTime, StepCount> > LoadDaySteps(DateTime fetchDate)
        {
            Dictionary <DateTime, StepCount> daySteps = new Dictionary <DateTime, StepCount>();

            try
            {
                int totalMinutesPerDay = 24 * 60;
                int dataPoints         = totalMinutesPerDay / DataPointInterval;
                for (int i = 0; i <= dataPoints; i++)
                {
                    DateTime fetchFrom = fetchDate.Date + TimeSpan.FromMinutes(i * DataPointInterval);
                    if (fetchFrom > DateTime.Now)
                    {
                        break;
                    }
                    TimeSpan fetchRange = TimeSpan.FromMinutes(DataPointInterval);
                    if ((fetchFrom + fetchRange) > DateTime.Now)
                    {
                        fetchRange = DateTime.Now - fetchFrom;
                    }
                    StepCount stepCount = await _stepCounter.GetStepCountForRangeAsync(
                        fetchFrom,
                        fetchRange
                        );

                    if (stepCount != null)
                    {
                        daySteps.Add(fetchFrom, stepCount);
                    }
                }
            }
            catch (Exception)
            {
            }
            return(daySteps);
        }
Пример #15
0
        /// <summary>
        /// This is an ML-agents framework method called when the agent observes its environment.
        /// These observations are passed to the model as inputs.
        /// They make up the agent's STATE (S) at the current step, or time (t).
        /// The model will use them to decide action to perform.
        ///
        /// NOTE: Aside from these manually created observations, we are also using
        ///     some others built-in to ML-agents, such as Ray Perception Sensor,
        ///     and stacking previous observations
        /// </summary>
        /// <param name="sensor">part of ML Agents API</param>
        public override void CollectObservations(VectorSensor sensor)
        {
            if (!target)
            {
                // if no target, we're in a bad state, so just pass data with all 0
                sensor.AddObservation(0f);
                sensor.AddObservation(0f);
                sensor.AddObservation(0f);
                sensor.AddObservation(0f);
                sensor.AddObservation(0f);
                sensor.AddObservation(0f);
                return;
            }

            // Observations used by SimpleTankAgent (you can use whatever you want for your own agents)
            // 1. Relative angle to enemy, where 0 is dead-on, -1 is negative 180, +1 is positive 180
            // 2. Distance to opponent, normalized
            // 3. Relative angle the enemy is pointing, where 0 is dead-on, -1 is negative 180, +1 is positive 180
            // 4. Our current Health, normalized from 0 to 1
            // 5. Enemy current Health, normalized from 0 to 1
            // 6. If gun is cooling down, true/false

            /* 1 */
            // calc relative angle between forward vector and vector from target to self, rotating about Y axis
            float relativeAngle = Vector3.SignedAngle(transform.forward,
                                                      (target.transform.position - transform.position),
                                                      Vector3.up);
            float relativeAngleObs = Mathf.Clamp(relativeAngle / 180f, -1f, 1f);

            sensor.AddObservation(relativeAngleObs);

            // we're adding a reward penalty here for when we're facing away from enemy,
            // hoping agent learns to generally face enemy to move toward them or fire at them
            if (relativeAngleObs < -0.5f || relativeAngleObs > 0.5f)
            {
                AddReward(-0.001f);
            }

            /* 2 */
            // calc distance
            float distance           = Vector3.Distance(target.transform.position, transform.position);
            float normalizedDistance = distance / 70f;  // map hyponteneuse is roughly 70, use for normalizing
            float distanceObs        = Mathf.Clamp(normalizedDistance, 0f, 1.0f);

            sensor.AddObservation(distanceObs);

            /* 3 */
            // calc relative angle of opponent the same way
            float enemyRelativeAngle = Vector3.SignedAngle(target.transform.forward,
                                                           (transform.position - target.transform.position),
                                                           Vector3.up);
            float enemyRelativeAngleObs = Mathf.Clamp(enemyRelativeAngle / 180f, -1f, 1f);

            sensor.AddObservation(enemyRelativeAngleObs);

            /* 4 */
            // our own health, normalized from 0-1
            if (health)
            {
                sensor.AddObservation(health.NormalizedHealth);
            }
            else
            {
                sensor.AddObservation(0f);
            }

            /* 5 */
            // target's health, normalized from 0-1
            if (targetHealth)
            {
                sensor.AddObservation(targetHealth.NormalizedHealth);
            }
            else
            {
                sensor.AddObservation(0f);
            }

            /* 6 */
            // observe whether our gun is cooling down and can't fire
            // this might not be useful, but agent might learn difference between weak/strong shots,
            // and it might want to fire faster/slower depending on situation
            if (shooting)
            {
                sensor.AddObservation(shooting.cooldown);
            }
            else
            {
                sensor.AddObservation(0f);
            }

            AddReward(-0.0001f);  // tiny negative reward over time to incentivize agent to hurry up

            // do some debug outputting here
            if (debug && textOutput)
            {
                textOutput.output  = "<b>Agent" + playerNumber.ToString() + "</b>\n";
                textOutput.output += "<b>Relative Angle: </b>" + relativeAngleObs.ToString() + "\n";
                textOutput.output += "<b>Distance: </b>" + distanceObs.ToString() + "\n";
                textOutput.output += "<b>Enemy Relative Heading: </b>" + enemyRelativeAngleObs.ToString() + "\n";
                textOutput.output += "<b>Health: </b>" + health.NormalizedHealth.ToString() + "\n";
                textOutput.output += "<b>Enemy Health: </b>" + targetHealth.NormalizedHealth.ToString() + "\n";
                textOutput.output += "<b>Cannon Cooldown: </b>" + shooting.cooldown.ToString() + "\n";
                textOutput.output += "<b>Total Reward: </b>" + GetCumulativeReward().ToString() + "\n";
            }

            if (GetCumulativeReward() == 0.0f)
            {
                Debug.unityLogger.Log(LOGTAG, "AGENT at value 0.0 rewards at step " + StepCount.ToString());
            }

            if (float.Parse(GetCumulativeReward().ToString()) == 0.0f)
            {
                Debug.unityLogger.Log(LOGTAG, "AGENT at string value 0.0 rewards at step " + StepCount.ToString());
            }
        }
Пример #16
0
 /// <summary>
 /// Gets number of steps for current day
 /// </summary>
 /// <returns><c>true</c> if steps were successfully fetched, <c>false</c> otherwise</returns>
 private async Task<bool> GetStepsAsync()
 {
     StepCounter stepCounter = null;
     try
     {
         stepCounter = await StepCounter.GetDefaultAsync();
         _steps = await stepCounter.GetStepCountForRangeAsync( 
             DateTime.Now.Date, 
             DateTime.Now - DateTime.Now.Date );
     }
     catch( Exception e )
     {
         _lastError = SenseHelper.GetSenseError( e.HResult );
         return false;
     }
     finally
     {
         if( stepCounter != null )
         {
             stepCounter.Dispose();
         }
     }
     return true;
 }
 public string GetRowKey()
 {
     return(IterationCount.ToString() + "_" + StepCount.ToString());
 }
Пример #18
0
 public StepActor(string name, int step = 1) : base(name)
 {
     _counter = new StepCount(this, step);
 }
Пример #19
0
 private DataPoint DataPointStepCountConverter(StepCount stepCount)
 {
     return(new DataPoint(DateTimeAxis.ToDouble(stepCount.Date), stepCount.Count));
 }
Пример #20
0
        /// <summary>
        /// Updates visualization
        /// </summary>
        private async Task UpdateScreenAsync()
        {
            // clear visual
            ActivityPanel.Children.Clear();
            TimePanel.Children.Clear();

            //update labels
            ZoomLabel.Text = "" + ZOOM_LEVELS[_currentZoomLevel] + " pixel(s)/minute";
            DateLabel.Text = _iCurrentDate.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
            //update date selected
            DateTime endDate = _iCurrentDate.AddDays(1);

            if (_iCurrentDate.Date == DateTime.Now.Date)
            {
                endDate = DateTime.Now;
            }
            // Add time labels and steps(walking+running) count for each hour
            for (int i = 0; i < 24; i++)
            {
                Grid      timeBlock = new Grid();
                StepCount stepCount = null;
                // getting steps count
                try
                {
                    DateTime fromDate    = _iCurrentDate + TimeSpan.FromHours(i);
                    TimeSpan queryLength = TimeSpan.FromHours(1);
                    if ((fromDate + queryLength) > endDate)
                    {
                        queryLength = endDate - fromDate;
                    }
                    stepCount = await _stepCounter.GetStepCountForRangeAsync(fromDate, queryLength);
                }
                catch (Exception)
                {
                }

                //updating steps count for each hour in visualizer
                TextBlock label = new TextBlock();
                label.Height   = ZOOM_LEVELS[_currentZoomLevel] * 60.0 * BASE_DRAW_SCALE;
                label.FontSize = 14.0;
                if (stepCount != null)
                {
                    label.Text = String.Format(
                        "{0:00}:00\n{1}/{2}",
                        i,
                        stepCount.WalkingStepCount,
                        stepCount.RunningStepCount
                        );
                }
                else
                {
                    label.Text = String.Format("{0:00}:00", i);
                }
                label.VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Top;
                timeBlock.Children.Add(label);
                //creating time(hour) intervel blocks
                Rectangle divider = new Rectangle();
                divider.Width             = 200.0;
                divider.Height            = 0.5;
                divider.Fill              = new SolidColorBrush(Colors.Gray);
                divider.VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Top;
                timeBlock.Children.Add(divider);

                TimePanel.Children.Add(timeBlock);
            }

            // Add activities for each hour in a day
            IList <ActivityMonitorReading> activities = null;

            if (await CallSenseApiAsync(async() =>
            {
                activities = await _activityMonitor.GetActivityHistoryAsync(_iCurrentDate, endDate - _iCurrentDate);
            }))
            {
                if (activities.Count >= 2)
                {
                    ActivityMonitorReading previousReading = activities[0];
                    // if first activity started few minutes after the day started then Add filler if needed
                    if (previousReading.Timestamp > _iCurrentDate)
                    {
                        AppendActivityBarBlock(Colors.Transparent, previousReading.Timestamp - _iCurrentDate);
                    }
                    // Add activities
                    for (int i = 1; i < activities.Count; i++)
                    {
                        ActivityMonitorReading reading = activities[i];
                        TimeSpan activityLength        = reading.Timestamp - previousReading.Timestamp;
                        // if first activity started before the day started then cut off any excess
                        if (previousReading.Timestamp < _iCurrentDate)
                        {
                            activityLength -= (_iCurrentDate - previousReading.Timestamp);
                        }

                        AppendActivityBarBlock(ACTIVITY_COLORS[previousReading.Mode], activityLength);
                        previousReading = reading;
                    }
                    // Show also current activity
                    AppendActivityBarBlock(ACTIVITY_COLORS[previousReading.Mode], endDate - previousReading.Timestamp);
                }
                // Scroll to present/current time
                ActivityScroller.UpdateLayout();
                double scrollTo = (ZOOM_LEVELS[_currentZoomLevel] * (endDate - _iCurrentDate).TotalMinutes * BASE_DRAW_SCALE) - 400.0;
                if (scrollTo < 0.0)
                {
                    scrollTo = 0.0;
                }
                ActivityScroller.ChangeView(null, scrollTo, null);
            }
            else
            {
                MessageDialog dlg = new MessageDialog("Failed to fetch activities");
                await dlg.ShowAsync();
            }
        }
Пример #21
0
        /// <summary>
        /// Factory that creates a StepCountData object from a Lumia StepCount
        /// </summary>
        /// <param name="stepCount"></param>
        /// <returns></returns>
        public static StepCountData FromLumiaStepCount(StepCount stepCount)
        {
            StepCountData steps = new StepCountData();

            steps.RunningCount = stepCount.RunningStepCount;
            steps.WalkingCount = stepCount.WalkingStepCount;
            steps.UnknownCount = 0;

            return steps;
        }
Пример #22
0
 public StepCount UpdateStepCount(StepCount stepCount)
 => UpdateStepCountAsync(stepCount).Result;