Search in sources :

Example 1 with Activity

use of de.opendiabetes.vault.plugin.importer.googlecrawler.models.Activity in project BachelorPraktikum by lucasbuschlinger.

the class GoogleFitness method fetchActivitiesPerDay.

/**
 * Fetches all activities at a specific day.
 * @param day - a date as unix timestamp
 */
private void fetchActivitiesPerDay(final long day) {
    long[] startEnd = getStartEndDay(day);
    AggregateBy aggregate = new AggregateBy();
    aggregate.setDataTypeName("com.google.activity.segment");
    AggregateRequest agg = new AggregateRequest();
    agg.setStartTimeMillis(startEnd[0]);
    agg.setEndTimeMillis(startEnd[1]);
    agg.setAggregateBy(Arrays.asList(aggregate));
    try {
        Fitness.Users.Dataset.Aggregate request = fitnessService.users().dataset().aggregate("me", agg);
        AggregateResponse rep = request.execute();
        List<DataPoint> activitiesByDataSource = rep.getBucket().get(0).getDataset().get(0).getPoint();
        List<Activity> activities = new ArrayList<>();
        for (DataPoint dp : activitiesByDataSource) {
            activities.add(new Activity(dp.getStartTimeNanos() / NANO_TO_MILLISECONDS_DIVISOR, dp.getEndTimeNanos() / NANO_TO_MILLISECONDS_DIVISOR, dp.getValue().get(0).getIntVal()));
        }
        for (int i = 0; i < activities.size() - 1; i++) {
            Activity currentActivity = activities.get(i);
            Activity nextActivity = activities.get(i + 1);
            if (currentActivity.getActivityId() == nextActivity.getActivityId() && currentActivity.getEndTime() - nextActivity.getStartTime() <= UNIX_TIME_FIVE_MINUTES) {
                currentActivity.setEndTime(nextActivity.getEndTime());
                activities.remove(i + 1);
            }
        }
        LocationHistory.getInstance().addActivities(startEnd[0], activities);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Also used : AggregateBy(com.google.api.services.fitness.model.AggregateBy) AggregateRequest(com.google.api.services.fitness.model.AggregateRequest) AggregateResponse(com.google.api.services.fitness.model.AggregateResponse) ArrayList(java.util.ArrayList) Activity(de.opendiabetes.vault.plugin.importer.googlecrawler.models.Activity) IOException(java.io.IOException) DataPoint(com.google.api.services.fitness.model.DataPoint) DataPoint(com.google.api.services.fitness.model.DataPoint) Fitness(com.google.api.services.fitness.Fitness)

Example 2 with Activity

use of de.opendiabetes.vault.plugin.importer.googlecrawler.models.Activity in project BachelorPraktikum by lucasbuschlinger.

the class LocationHistory method determineRestHeartRate.

/**
 * Determines the resting heart rate at a given day.
 * @param day a valid unix timestamp
 * @return an integer array containing the resting, target and maximum heart rate
 */
private int[] determineRestHeartRate(final long day) {
    int[] hr = new int[3];
    long time = -1;
    List<Activity> activities = getActivityHistory(day);
    for (Activity act : activities) {
        Calendar cal = new GregorianCalendar();
        cal.setTimeInMillis(act.getEndTime());
        if (act.getActivityId() == ActivityTypes.SLEEPING || act.getActivityId() == ActivityTypes.LIGHT_SLEEP || act.getActivityId() == ActivityTypes.DEEP_SLEEP || act.getActivityId() == ActivityTypes.REM_SLEEP || act.getActivityId() == ActivityTypes.AWAKE_DURING_SLEEP) {
            time = act.getEndTime();
        }
    }
    final long wakeUpTime = time;
    List<Integer> rates = new ArrayList<>();
    if (time == -1) {
        getHeartRateHistory(day).forEach(r -> rates.add(r.getRate()));
    } else {
        getHeartRateHistory(day).forEach(r -> {
            if (r.getTimestamp() < wakeUpTime + UNIX_TIME_FIVE_MINUTES && r.getTimestamp() > wakeUpTime - UNIX_TIME_FIVE_MINUTES) {
                rates.add(r.getRate());
            }
        });
    }
    Collections.sort(rates);
    double quantilePos = (rates.size() * 0.3);
    if (quantilePos % 1 == 0) {
        int a = rates.get((int) quantilePos - 1);
        int b = rates.get((int) quantilePos);
        // 0,5*(x(np)*x(np+1))
        hr[Constants.REST_HR] = (int) (0.5 * (a + b));
    } else {
        // floor(np) + 1
        int pos = (int) Math.floor(quantilePos);
        hr[Constants.REST_HR] = rates.get(pos);
    }
    hr[Constants.MAX_HR] = MAXIMUM_HUMAN_HEART_RATE - age;
    // getHeartRateHistory(day).stream().max(Comparator.comparing(HeartRate::getRate)).get().getRate();
    hr[Constants.TARGET_HR] = hr[Constants.MAX_HR] - hr[Constants.REST_HR];
    return hr;
}
Also used : Calendar(java.util.Calendar) GregorianCalendar(java.util.GregorianCalendar) GregorianCalendar(java.util.GregorianCalendar) ArrayList(java.util.ArrayList) Activity(de.opendiabetes.vault.plugin.importer.googlecrawler.models.Activity)

Example 3 with Activity

use of de.opendiabetes.vault.plugin.importer.googlecrawler.models.Activity in project BachelorPraktikum by lucasbuschlinger.

the class LocationHistory method determineActivityIntensity.

/**
 * Determines how intense the activity was by comparing the heart rate to previous data.
 */
public void determineActivityIntensity() {
    for (Map.Entry<Long, List<Activity>> entry : activityHistory.entrySet()) {
        long day = entry.getKey();
        for (Activity act : entry.getValue()) {
            if (act.getEndTime() - act.getStartTime() >= UNIX_TIME_TWENTY_MINUTES) {
                act.setHeartRate(getMinMaxAvgHeartRate(act.getStartTime(), act.getEndTime()));
                if (act.getHeartRate()[Constants.MIN_HR] != -1) {
                    int[] trainingHR = trainingHRHistory.get(day);
                    int targetHR = trainingHR[Constants.TARGET_HR];
                    int restHR = trainingHR[Constants.REST_HR];
                    int averageHR = act.getHeartRate()[Constants.AVG_HR];
                    if ((0.6 * targetHR) + restHR <= averageHR && (0.7 * targetHR) + restHR > averageHR) {
                        act.setIntensity(1);
                    } else if ((0.7 * targetHR) + restHR <= averageHR && (0.75 * targetHR) + restHR >= averageHR) {
                        act.setIntensity(2);
                    } else if ((0.75 * targetHR) + restHR < averageHR && (0.84 * targetHR) + restHR >= averageHR) {
                        act.setIntensity(3);
                    } else if ((0.84 * targetHR) + restHR < averageHR && (0.88 * targetHR) + restHR >= averageHR) {
                        act.setIntensity(4);
                    } else if ((0.88 * targetHR) + restHR < averageHR && (0.92 * targetHR) + restHR >= averageHR) {
                        act.setIntensity(5);
                    } else {
                        act.setIntensity(0);
                    }
                }
            }
        }
    }
}
Also used : Activity(de.opendiabetes.vault.plugin.importer.googlecrawler.models.Activity) ArrayList(java.util.ArrayList) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map)

Example 4 with Activity

use of de.opendiabetes.vault.plugin.importer.googlecrawler.models.Activity in project BachelorPraktikum by lucasbuschlinger.

the class LocationHistory method refineLocations.

/**
 * Populates the activity history by fetching the location names of coordinates
 * from the Google Places API.
 */
public void refineLocations() {
    for (Map.Entry<Long, List<Activity>> entry : activityHistory.entrySet()) {
        List<Coordinate> coords = getLocationsPerDay(entry.getKey());
        for (Activity act : entry.getValue()) {
            if (act.getActivityId() == ActivityTypes.STILL || act.getActivityId() == ActivityTypes.UNKNOWN || act.getActivityId() == ActivityTypes.SLEEPING || act.getActivityId() == ActivityTypes.LIGHT_SLEEP || act.getActivityId() == ActivityTypes.DEEP_SLEEP || act.getActivityId() == ActivityTypes.REM_SLEEP || act.getActivityId() == ActivityTypes.MEDITATION) {
                List<Coordinate> activityCoords = new ArrayList<>();
                long startTime = act.getStartTime();
                long endTime = act.getEndTime();
                for (Coordinate c : coords) {
                    if (c.getTimestamp() >= startTime && c.getTimestamp() <= endTime) {
                        activityCoords.add(c);
                    }
                }
                if (activityCoords.size() > 0) {
                    activityCoords.sort(Comparator.comparing(Coordinate::getAccuracy));
                    int threshold = activityCoords.get((int) (activityCoords.size() * 0.75)).getAccuracy();
                    activityCoords = activityCoords.stream().filter(c -> c.getAccuracy() <= threshold).collect(Collectors.toList());
                    double weightedLatitude = 0;
                    double weightedLongitude = 0;
                    double weight = 0;
                    for (Coordinate c : activityCoords) {
                        weightedLatitude += c.getLatitude() * c.getAccuracy();
                        weightedLongitude += c.getLongitude() * c.getAccuracy();
                        weight += c.getAccuracy();
                    }
                    final double lat = weightedLatitude / weight;
                    final double lng = weightedLongitude / weight;
                    int searchRadius = DEFAULT_RADIUS;
                    if (searchRadius < threshold) {
                        searchRadius = threshold;
                    }
                    String place = GooglePlaces.getInstance().atOwnPlaces(lat, lng, searchRadius);
                    if (place.equals("AWAY")) {
                        place = GooglePlaces.getInstance().isAtContact(lat, lng, searchRadius);
                        if (place.equals("AWAY")) {
                            PlacesSearchResult[] results = GooglePlaces.getInstance().getPlaces(lat, lng, searchRadius);
                            if (results != null) {
                                if (results.length == 1) {
                                    place = results[0].name;
                                } else {
                                    List<PlacesSearchResult> places = extractRealLocations(results);
                                    places.sort((PlacesSearchResult o1, PlacesSearchResult o2) -> {
                                        double o1Distance = GooglePlaces.getInstance().calculateDistance(o1.geometry.location.lat, o1.geometry.location.lng, lat, lng);
                                        double o2Distance = GooglePlaces.getInstance().calculateDistance(o2.geometry.location.lat, o2.geometry.location.lng, lat, lng);
                                        return Double.compare(o1Distance, o2Distance);
                                    });
                                    List<PlacesSearchResult> sportRelatedPlaces = getGymOrSportClub(places);
                                    GoogleMapsPlot.getInstance().addLocation(new LatLng(lat, lng));
                                    if (sportRelatedPlaces.size() == 1) {
                                        place = sportRelatedPlaces.get(0).name;
                                    } else {
                                        Location location = checkForResolvedLocations(lat, lng, searchRadius * 2);
                                        if (location != null) {
                                            place = location.getName();
                                        } else if (sportRelatedPlaces.size() > 1) {
                                            conflictLocations.put(new ConflictedLocationIdentifier(act.getStartTime(), new LatLng(lat, lng)), sportRelatedPlaces);
                                            place = "CONFLICT";
                                        } else if (places.size() > 0) {
                                            results = GooglePlaces.getInstance().getPlaces(lat, lng, searchRadius * 2);
                                            places = extractRealLocations(results);
                                            places.sort((PlacesSearchResult o1, PlacesSearchResult o2) -> {
                                                double o1Distance = GooglePlaces.getInstance().calculateDistance(o1.geometry.location.lat, o1.geometry.location.lng, lat, lng);
                                                double o2Distance = GooglePlaces.getInstance().calculateDistance(o2.geometry.location.lat, o2.geometry.location.lng, lat, lng);
                                                return Double.compare(o1Distance, o2Distance);
                                            });
                                            conflictLocations.put(new ConflictedLocationIdentifier(act.getStartTime(), new LatLng(lat, lng)), places);
                                            place = "CONFLICT";
                                        } else {
                                            place = "UNKNOWN";
                                        }
                                    }
                                }
                            } else {
                                place = "UNKNOWN";
                            }
                        }
                    }
                    act.setLocation(place);
                }
                GoogleMapsPlot.getInstance().addLocationNames(act.getLocation());
            }
        }
    }
}
Also used : ConflictedLocationIdentifier(de.opendiabetes.vault.plugin.importer.googlecrawler.models.ConflictedLocationIdentifier) ArrayList(java.util.ArrayList) Activity(de.opendiabetes.vault.plugin.importer.googlecrawler.models.Activity) Coordinate(de.opendiabetes.vault.plugin.importer.googlecrawler.models.Coordinate) ArrayList(java.util.ArrayList) List(java.util.List) PlacesSearchResult(com.google.maps.model.PlacesSearchResult) LatLng(com.google.maps.model.LatLng) HashMap(java.util.HashMap) Map(java.util.Map) Location(de.opendiabetes.vault.plugin.importer.googlecrawler.models.Location)

Aggregations

Activity (de.opendiabetes.vault.plugin.importer.googlecrawler.models.Activity)4 ArrayList (java.util.ArrayList)4 HashMap (java.util.HashMap)2 List (java.util.List)2 Map (java.util.Map)2 Fitness (com.google.api.services.fitness.Fitness)1 AggregateBy (com.google.api.services.fitness.model.AggregateBy)1 AggregateRequest (com.google.api.services.fitness.model.AggregateRequest)1 AggregateResponse (com.google.api.services.fitness.model.AggregateResponse)1 DataPoint (com.google.api.services.fitness.model.DataPoint)1 LatLng (com.google.maps.model.LatLng)1 PlacesSearchResult (com.google.maps.model.PlacesSearchResult)1 ConflictedLocationIdentifier (de.opendiabetes.vault.plugin.importer.googlecrawler.models.ConflictedLocationIdentifier)1 Coordinate (de.opendiabetes.vault.plugin.importer.googlecrawler.models.Coordinate)1 Location (de.opendiabetes.vault.plugin.importer.googlecrawler.models.Location)1 IOException (java.io.IOException)1 Calendar (java.util.Calendar)1 GregorianCalendar (java.util.GregorianCalendar)1