com.hamdikavak.humanmobility.modeling.test.DataHelper.java Source code

Java tutorial

Introduction

Here is the source code for com.hamdikavak.humanmobility.modeling.test.DataHelper.java

Source

/*
MIT License
    
Copyright (c) 2017 Hamdi Kavak
    
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
    
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
    
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. 
 */

package com.hamdikavak.humanmobility.modeling.test;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;

import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import com.hamdikavak.humanmobility.modeling.spatial.ExtendedLocationTrace;
import com.hamdikavak.humanmobility.modeling.spatial.GeoCoordinate;
import com.hamdikavak.humanmobility.modeling.spatial.LocationTrace;

/**
 * Data methods for test cases.
 * 
 * @author Hamdi Kavak
 * @version 0.2.0
 *
 */
public class DataHelper {

    private final static Logger logger = Logger.getLogger(DataHelper.class);

    public static List<ExtendedLocationTrace> getExtendedTracesFromFile(String path) {
        String line;
        List<ExtendedLocationTrace> traces = new ArrayList<ExtendedLocationTrace>();
        ExtendedLocationTrace aTrace;

        try {
            logger.info("Reading file: " + path);
            BufferedReader reader = new BufferedReader(new FileReader(path));

            // header line
            line = reader.readLine();

            while ((line = reader.readLine()) != null) {
                aTrace = convertLineToAExtendedLocationTraceObject(line);
                traces.add(aTrace);
            }
            reader.close();
        } catch (Exception ex) {
            logger.error(ex.getMessage());
        }

        return traces;
    }

    /**
     * Bring a list of location traces from the file located at {@code path}
     * @param path location of the file
     * @return a list of location traces
     */
    public static List<LocationTrace> getTracesFromFile(String path) {
        String line;
        List<LocationTrace> traces = new ArrayList<LocationTrace>();
        LocationTrace aTrace;

        try {
            logger.info("Reading file: " + path);
            BufferedReader reader = new BufferedReader(new FileReader(path));

            // header line
            line = reader.readLine();

            while ((line = reader.readLine()) != null) {
                aTrace = convertLineToAExtendedLocationTraceObject(line);
                traces.add(aTrace);
            }
            reader.close();
        } catch (Exception ex) {
            logger.error(ex.getMessage());
        }

        return traces;
    }

    private static ExtendedLocationTrace convertLineToAExtendedLocationTraceObject(String line) {
        String[] columnValues;
        ExtendedLocationTrace trace = new ExtendedLocationTrace();

        // a line in the csv file {user_id,utc_time,latitude,longitude}

        columnValues = line.split(",");

        String dtString = columnValues[1].replace("\"", "") + "00"; // 00 added to conform time zone format
        DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ssZ");

        String userId = columnValues[0];
        DateTime dt = DateTime.parse(dtString, formatter);
        Double latitude = Double.parseDouble(columnValues[2]);
        Double longitude = Double.parseDouble(columnValues[3]);

        trace.setUserId(userId);
        trace.setUTCTime(dt);
        trace.setLocalTime(dt.toLocalDateTime());
        trace.setCoordinate(new GeoCoordinate(latitude, longitude));

        return trace;
    }

    /**
     * As its name tells, this method returns the given {@code traces} as a
     * hashmap that holds traces per user where the key values hold user ids
     * 
     * @param traces a list that has location traces from multiple users
     * @return location traces organized by user and sorted by date ascending.
     */
    public static HashMap<String, List<LocationTrace>> organizeTracesByUserAndSort(List<LocationTrace> traces) {
        HashMap<String, List<LocationTrace>> traceMap = new HashMap<String, List<LocationTrace>>();

        // trace organization by user
        for (LocationTrace aTrace : traces) {
            List<LocationTrace> list;
            if (traceMap.containsKey(aTrace.getUserId()) == true) {
                list = traceMap.get(aTrace.getUserId());
            } else {
                list = new ArrayList<LocationTrace>();
                traceMap.put(aTrace.getUserId(), list);
            }
            list.add(aTrace);
        }

        // sorting traces by time ascending

        // comparator object
        Comparator<LocationTrace> comparator = new Comparator<LocationTrace>() {
            public int compare(LocationTrace t1, LocationTrace t2) {
                return (t1.getUTCTime().getMillis() > t2.getUTCTime().getMillis() ? 1 : -1);
            }
        };

        for (String userId : traceMap.keySet()) {
            List<LocationTrace> traceListForUser = traceMap.get(userId);

            Collections.sort(traceListForUser, comparator);
            traceMap.put(userId, traceListForUser);
        }

        return traceMap;
    }

    public static HashMap<String, List<ExtendedLocationTrace>> organizeExtendedTracesByUserAndSort(
            List<ExtendedLocationTrace> traces) {
        HashMap<String, List<ExtendedLocationTrace>> traceMap = new HashMap<String, List<ExtendedLocationTrace>>();

        // trace organization by user
        for (ExtendedLocationTrace aTrace : traces) {
            List<ExtendedLocationTrace> list;
            if (traceMap.containsKey(aTrace.getUserId()) == true) {
                list = traceMap.get(aTrace.getUserId());
            } else {
                list = new ArrayList<ExtendedLocationTrace>();
                traceMap.put(aTrace.getUserId(), list);
            }
            list.add(aTrace);
        }

        // sorting traces by time ascending

        // comparator object
        Comparator<LocationTrace> comparator = new Comparator<LocationTrace>() {
            public int compare(LocationTrace t1, LocationTrace t2) {
                return (t1.getUTCTime().getMillis() > t2.getUTCTime().getMillis() ? 1 : -1);
            }
        };

        for (String userId : traceMap.keySet()) {
            List<ExtendedLocationTrace> traceListForUser = traceMap.get(userId);

            Collections.sort(traceListForUser, comparator);
            traceMap.put(userId, traceListForUser);
        }

        return traceMap;
    }

    public static long[] mergeArrays(long[] alldistances, long[] currentUserDistances) {
        long[] finalArray = new long[alldistances.length + currentUserDistances.length];

        for (int i = 0; i < alldistances.length; i++) {
            finalArray[i] = alldistances[i];
        }

        for (int i = alldistances.length; i < finalArray.length; i++) {
            finalArray[i] = currentUserDistances[i - alldistances.length];
        }

        return finalArray;
    }

    public static double[][] log10(double[][] values) {
        for (int i = 0; i < values.length; i++) {
            for (int j = 0; j < values[i].length; j++) {
                values[i][j] = values[i][j] == 0 ? 0 : Math.log10(values[i][j]);
            }
        }

        return values;
    }

    public static HashMap<Double, Double> log10(HashMap<Long, Double> values) {
        HashMap<Double, Double> newValues = new HashMap<Double, Double>();

        for (Entry<Long, Double> item : values.entrySet()) {
            Double newKey = item.getKey() == 0l ? 0d : Math.log10(item.getKey().doubleValue());
            Double newValue = item.getValue() == 0d ? 0d : Math.log10(item.getValue());
            newValues.put(newKey, newValue);
        }

        return newValues;
    }

}