GPS-Accelerometer Fusion for Crowdsource Measurement Tracking with Kalman Filter Bachelor Thesis Submitted to Escola T` ecnica Superior d’Enginyeria de Telecomunicaci´ o de Barcelona, Universitat Polit`ecnica De Catalunya Carried out in Institute of Telecommunications, Technische Universit¨at Wien In partial fulfilment of the requirements for the degree in Telecommunications Technologies and Services Engineering Written by Gokarna Dumre Tiwari under the supervision of Dipl.-Ing. Eller Lukas Senior Scientistc. Dipl.-Ing. Dr.techn. Philipp Svoboda Dr. Jose Luis Mu˜noz Tapia Vienna, January 19, 2024
Abstract Global Navigation Satellite System (GNSS) technology has become an integral part of modern navigation and location-based services. However, this thesis will focus specifically on the Global Positioning System (GPS), which faces signal inaccuracies due to blockage, interference and multipath effects that limit accuracy. Indoor use is limited by line-of-sight requirements. High power consumption has an impact on mobile device batteries. In urban areas and street canyons or under signal interference, GPS reliability and accuracy decreases and that demands continuous technological advancement. The best known solution to these problems is sensor fusion. GPS sensor fusion with the information from other sensors, such as GPS with an accelerometer, using the Kalman filter, one of the most important and widely used estimation algorithms. This bachelor thesis, conducted at the Vienna University of Technology, explores the potential of GPS-accelerometer fusion by implementing the Kalman filter within a mapping application, SensorDataCollector, for Android devices in Android Studio for crowdsourced measurements. To achieve a successful thesis outcome, it is required to update the app, its components, and its features. However, the hypothesis is that the performance of the Kalman filter is superior to that of the GPS signal, and the main objective is to verify this. This verification has been confirmed through rigorous testing in diverse scenarios, including central urban areas with numerous buildings and interior locations with minimal signal coverage, comparing the performance of GPS with the fused signal of the filter, ensuring the fair comparison by including a reference path and an interpolation procedure using Python. Regarding the indoor testing campaign, the analysis of results has not been possible due to the lack of reference route, but the figures confirm the hypothesis. However, for the urban campaign, the verification was carried out by analysing the test results, comparing the coordinates with the minimum distance and the minimum time difference. The average GPS inaccuracy is greater compared to the filtered signal. The average error for GPS is 6.888 metres and for the filtered signal it is 5.139 metres. i
Resum El sistema de navegaci´o per sat`el·lit Global Navigation Satellite System (GNSS) s’ha convertit en una part integral de la navegaci´o moderna i els serveis basats en la ubicaci´o. No obstant aix`o, aquesta tesi es centrar`a espec´ıficament en el Sistema de Posicionament Global (GPS), que s’enfronta a imprecisi´o de senyal degut a bloqueigs, interfer`encies i efectes multipath que limiten la precisi´o. L’´us en interiors es veu limitat pels requisits de l´ınia de visi´o. El consum alt de pot`encia afecta les bateries dels dispositius m`obils. En `arees urbanes i de carrers, o sota interfer`encies de senyal, la fiabilitat i la precisi´o del GPS disminueixen, la qual cosa exigeix un aven¸c tecnol`ogic continu. La soluci´o m´es coneguda per aquests problemes ´es la fusi´o de sensors. La fusi´o de sensors GPS amb informaci´o d’altres sensors, com per exemple, el GPS amb un acceler`ometre, utilitzant el filtre de Kalman, un dels algoritmes d’estimaci´o m´es importants i `ampliament utilitzats. Aquesta tesi, realitzada a la Universitat de Tecnologia de Viena, explora el potencial de la fusi´o GPS-acceler`ometre mitjan¸cant la implementaci´o del filtre de Kalman dins d’una aplicaci´o de mapes, SensorDataCollector, per a dispositius Android a Android Studio, per a mesures col·laboratives. Per aconseguir els resultats desitjats, ´es necessari l´actualitzaci´o de l’aplicaci´o, dels seus components i de les seves caracter´ıstiques. No obstant aix`o, la hip`otesi ´es que el rendiment del filtre de Kalman ´es superior al de la senyal GPS, i l’objectiu principal ´es verificar aix`o. Aquesta verificaci´o s’ha confirmat mitjan¸cant proves rigoroses en escenaris diversos, incloent `arees urbanes centrals amb nombrosos edificis d’al¸cada i ubicacions interiors amb cobertura de senyal m´ınima, comparant el rendiment del GPS amb la senyal fusionada del filtre, assegurant una comparaci´o justa en incloure una ruta de refer`encia i un procediment d’interpolaci´o utilitzant Python. Pel que fa a la campanya de proves a l’interior, l’an`alisi dels resultats no ha estat possible a causa de la manca de ruta de refer`encia, per`o les figures confirmen la hip`otesi. Per`o, per a la campanya urbana, la verificaci´o es va dur a terme mitjan¸cant l’an`alisi dels resultats de les proves, comparant les coordenades amb la dist`ancia m´ınima i tamb´e amb la difer`encia de temps m´ınima. En ambd`os casos, imprecisi´o mitjana del GPS ´es major en comparaci´o amb la senyal filtrada. L’error mitj`a per al GPS ´es de 6,888 metres i per a la senyal filtrada ´es de 5,139 metres. ii
Resumen El sistema de navegaci´on por sat´elite Global Navigation Satellite System (GNSS) se ha convertido en una parte integral de la navegaci´on moderna y los servicios basados en la ubicaci´on. Sin embargo, esta tesis se centrar´a espec´ıficamente en el Sistema de Posicionamiento Global (GPS), que enfrenta imprecisiones en la se˜nal debido a bloqueos, interferencias y efectos multipath que limitan la precisi´on. El uso en interiores se ve limitado por los requisitos de l´ınea de visi´on. El alto consumo de energ´ıa afecta las bater´ıas de los dispositivos m´oviles. En ´areas urbanas y de calles, o bajo interferencias de se˜nal, la confiabilidad y precisi´on del GPS disminuyen, lo que exige un avance tecnol´ogico continuo. La soluci´on m´as conocida para estos problemas es la fusi´on de sensores. La fusi´on de sensores GPS con informaci´on de otros sensores, como por ejemplo, GPS con un aceler´ometro, utilizando el filtro de Kalman, uno de los algoritmos de estimaci´on m´as importantes y ampliamente utilizados. Esta tesis, realizada en la Universidad de Tecnolog´ıa de Viena, explora el potencial de la fusi´on GPS-aceler´ometro mediante la implementaci´on del filtro de Kalman dentro de una aplicaci´on de mapeo, SensorDataCollector, para dispositivos Android en Android Studio, para mediciones colaborativas. Para lograr los resultado esperados, es necesario actualizar la aplicaci´on, sus componentes y sus caracter´ısticas. Sin embargo, la hip´otesis es que el rendimiento del filtro de Kalman es superior al de la se˜nal GPS, y el objetivo principal es verificar esto. Esta verificaci´on se ha confirmado mediante pruebas rigurosas en diversos escenarios, incluyendo ´areas urbanas centrales con numerosos edificios y ubicaciones interiores con cobertura de se˜nal m´ınima, comparando el rendimiento del GPS con la se˜nal fusionada del filtro, asegurando una comparaci´on justa al incluir una ruta de referencia y un procedimiento de interpolaci´on utilizando Python. Con respecto a la campa˜na de pruebas en interiores, el an´alisis de los resultados no ha sido posible debido a la falta de una ruta de referencia, pero las figuras confirman la hip´otesis. Sin embargo, para la campa˜na urbana, la verificaci´on se llev´o a cabo mediante el an´alisis de los resultados de las pruebas, compar´ando las coordenadas con la distancia m´ınima y tambi´en con la diferencia de tiempo m´ınima. En ambos casos la imprecisi´on promedio del GPS es mayor en comparaci´on con la se˜nal filtrada. El error promedio para el GPS es de 6.888 metros y para la se˜nal filtrada es de 5.139 metros. iii
Acknowledgement First and foremost, I’m incredibly grateful to my amazing supervisors, Eller Lukas, Philipp Svoboda and Jose Luis Mu˜noz Tapia. Their unwavering support, guidance and expertise were invaluable throughout my research. They not only enriched my academic experience but also nurtured my intellectual growth. To my family and friends. Your love, understanding and unwavering support have been my rock throughout this challenging journey. Your unconditional belief in me, even during the most difficult times, has been my driving force in the pursuit of my goals. Thank you all for being an integral part of this academic journey. iv
Revision history and approval record Revision Date Autor (s) Purpose 1.0 20/10/2023 Gokarna Dumre Tiwari Document creation 1.1 27/11/2023 Lukas Eller Initial document revision 2.0 05/12/2023 Gokarna Dumre Tiwari Document structure revision 3.0 03/01/2024 Jose Luis Mu˜noz Tapia Document revision 4.0 07/01/2024 Lukas Eller Document revision 4.1 10/01/2024 Lukas Eller Jose Luis Mu˜noz Tapia Final version revision 4.2 18/01/2024 Gokarna Dumre Tiwari Errors correction 5.0 19/10/2024 Gokarna Dumre Tiwari Final version DOCUMENT DISTRIBUTION LIST Surname/s and Name Email Role Dumre Tiwari, Gokarna
[email protected] Student Eller, Lukas
[email protected] Project Supervisor 1 Svoboda, Philipp
[email protected] Project Supervisor 2 Mu˜noz Tapia, Jose Luis
[email protected] Project Supervisor 3 Written by: Reviewed and approved by: Date 18/01/2024 Date 19/01/2024 Name Gokarna Dumre Tiwari Name Lukas Eller, Jose Luis Mu˜noz Tapia Position Project Author Position Project Supervisors v
Contents Abstract...................................... i Resum....................................... ii Resumen...................................... iii Acknowledgements ................................ iv Tableofcontents ................................. vi ListofFigures................................... vii ListofTable.................................... vii ListofListings .................................. vii Glossary...................................... viii 1 Introduction................................. 1 1.1 Objectives.............................. 1 1.2 WorkPlan.............................. 2 2 Theoretical Background . . . . . . . . . . . . . . . . . . . . . . . . . . 3 2.1 GNSS ................................ 3 2.2 Sensor fusion for location . . . . . . . . . . . . . . . . . . . . . . 4 2.3 Sensors................................ 5 2.4 KalmanFilter............................ 6 3 MadLocationManager........................... 8 3.1 Initial Configuration . . . . . . . . . . . . . . . . . . . . . . . . 8 3.2 Emulators.............................. 9 3.3 Code modifications . . . . . . . . . . . . . . . . . . . . . . . . . 10 3.4 Application ............................. 15 4 Measurements Campaign . . . . . . . . . . . . . . . . . . . . . . . . . . 17 4.1 Methodology ............................ 17 4.2 OutdoorTesting .......................... 18 4.3 IndoorTesting ........................... 21 5 Sustainability Analysis and Ethical Implications . . . . . . . . . . . . . 22 5.1 Sustainability Analysis . . . . . . . . . . . . . . . . . . . . . . . 22 5.2 Ethical implications . . . . . . . . . . . . . . . . . . . . . . . . . 25 5.3 Relationship with the Sustainable Development Goals . . . . . . 25 6 Conclusion.................................. 26 Bibliography ................................... 26 Annex....................................... 29 A1 Virtual Emulator Specification . . . . . . . . . . . . . . . . . . . . . . . 29 A2 CodeModification ............................. 30 A2.1 Conversion of Json File in valid Model . . . . . . . . . . . . . . 30 A2.2 Conversion of coordinates in Cartesian’s axes . . . . . . . . . . . 30 A2.3 Theoretical coordinates interpolation . . . . . . . . . . . . . . . 31 A2.4 Testing route and Real route representation . . . . . . . . . . . 32 A2.5 Matching Coordinates time based . . . . . . . . . . . . . . . . . 33 A2.6 Matching Coordinates Distance based . . . . . . . . . . . . . . . 36 A3 App screenshot test measurement . . . . . . . . . . . . . . . . . . . . . 37
List of Figures 1 Work breakdown structure . . . . . . . . . . . . . . . . . . . . . . . . . 2 2 FinalGantt ................................. 2 3 GPSsatellites[4] .............................. 4 4 Universal GNSS-INS Integration Architecture [6] . . . . . . . . . . . . . 5 5 MLMinAndroidStudio .......................... 8 6 AndroidManifest.............................. 9 7 Virtualemulator .............................. 10 8 Physicalemulator.............................. 10 9 Appicon................................... 15 10 Apphomescreen .............................. 15 11 Appcalibration............................... 15 12 Appaftercalibration............................ 16 13 Appstarttacking.............................. 16 14 Referenceroute ............................... 17 15 OutdoorTests................................ 18 16 All Tests Time-Based Error . . . . . . . . . . . . . . . . . . . . . . . . 19 17 All Tests Distance-Based Error . . . . . . . . . . . . . . . . . . . . . . 19 18 IndoorTests................................. 21 19 Calenderoftasks .............................. 23 List of Tables 1 MeanComparison.............................. 20 2 Salarycosts ................................. 23 3 GeneralCosts................................ 24 List of Listings 1 Activitymain.xml.............................. 10 2 AndrioidManifest.xml............................ 10 3 Gradel.properties .............................. 10 4 MainActivity.java ............................. 11 5 MapPresenter.java ............................. 12 vii
Glossary GNSS : Global navigation satellite system GPS : Global Positioning System MLM : Mad Location Manager GLONASS: Globalnaya Navigazionnaya Sputnikovaya Sistema INS : Inertial Navigation System MSC : Master Control Station UI : User Interface KML : Keyhole Markup Language ECDF : Empirical Cumulative Distribution Function viii
Pk|k= (I−KkH)Pk|k−1(9) The equation (7) computes the Kalman Gain (Kk), which balances the influence of the predicted state and the measurement. It is calculated using the predicted covariance matrix (Pk|k−1), the transpose of the measurement matrix (HT), the measurement noise covariance matrix (R), and the measurement matrix (H). In the context of GPS and accelerometer fusion, Hwould map the state vector to the observable space, capturing the relationship between the system’s estimated state and the actual measurements. The equation (8) updates the state estimate (ˆxk|k) based on the Kalman Gain. It combines the predicted state (ˆxk|k−1) with the product of the Kalman Gain and the difference between the actual measurement (zk) and the predicted measurement (Hˆxk|k−1). This step is crucial for incorporating new measurements and adjusting the state estimate accordingly. The Kalman filter’s update step enables a seamless integration of GPS and accelerometer data, optimizing the trade-off between the global accuracy of GPS and the dynamical information provided by accelerometers. Finally, the equation (9) updates the covariance matrix (Pk|k) to reflect the refined state estimate. It involves subtracting the product of the Kalman Gain, the measurement matrix (H), and the identity matrix (I) from the predicted covariance matrix (Pk|k−1). This process dynamically adapts the covariance matrix to account for the reliability of the measurements. In addition to the fusion of GPS data with sensors using the Kalman filter, the project incorporates other filters, the Madgwick filter and GeoHash. These filters help to present the information collected by the sensors in a user-friendly manner. However, for the measurement campaign and the scope of this thesis, they were irrelevant, so they were barely modified. 7
3 Mad Location Manager After covering some theoretical concepts, the thesis now shifts its focus to the main application, Mad Location Manager (MLM), a publicly available GitHub project that fuses GNSS and accelerometer data using the Kalman filter to improve position accuracy and distance calculations on Android devices. Beyond this primary goal, the application addresses several critical issues, including route tracking errors, noise reduction on low-end devices, and eliminating redundant distance calculations when the object is stationary, among other improvements [9]. 3.1 Initial Configuration Figure 5: MLM in Android Studio In this project there are mainly two folders, as it can be appreciate in Fig. 5. •App - Basically, it contains the general parts of the projects, the global permissions, the Kalman filter services, and also the main classes of the project. For example, MainActivity.java and the MapPresenter.java, as well as interfaces, loggers and settings. 8
•Madlocationmanager - This section contains the appropriate filters, the sensor configurations and their propierties and parameters (several matrices). Looking Fig. 6, it can be seen each folder is structured as follows : Manifest - It contains essential information about the application and its components, such as activities, services, broadcast receivers and content providers. It also declares the permissions required by the application, defines the structure of the application and specifies its entry points. Figure 6: Android Manifest Java - The Java code in Android Studio is responsible for implementing the functionality of the application. This code is written in Java and defines the behaviour of activities, services, broadcast receivers... Res - It contains various resources used by the application, such as layouts, drawables, values, etc. •Drawable: Contains images and other drawable resources. •Layout: Defines the structure and appearance of the application’s user interface. •Values: Stores resources such as strings, colours, dimensions and styles. 3.2 Emulators In Android Studio, it is necessary to have or create an emulator to run the project and execute the application. There are 2 ways to do this, using a virtual emulator in the Android Studio or using a physical mobile phone. At the beginning I used the virtual emulator, but once the application was running I switched to the physical one. 9
Figure 7: Virtual emulator Figure 8: Physical emulator The virtual emulator Fig. 7 was a Nexus SX with API 29 and 15GB of storage, and the physical emulator Fig. 8 was a Samsung smartphone, model SM-G986B, running Android 10th version. 3.3 Code modifications 3.3.1 Application code Once I had the project up and running, my next goal was to customise and personalise the app according to my preferences. These are the changes I had to make to achieve the final result. Activity main.xml - I modified these 2 parameters, latitude & longitude, so that every time the application is launched, the Camp Nou is shown in the initial map. mapbox:mapbox_cameraTargetLat="41.381073043650154" mapbox:mapbox_cameraTargetLng="2.1229592825983605" Listing 1: Activity main.xml AndrioidManifest.xml - I wanted to handle the flow of position and time data, so I added the following permissions to guarantee the correct functioning of the app. <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.NFC" /> Listing 2: AndrioidManifest.xml build.gradle /gradle.properties - Here I added an access token for API authentication and authorisation as I use the Mapbox API, but as this is sensitive data it is only presented in the project. I also included a JitPack to get a Git project (MLM) into the Android Studio build. allprojects { repositories { mavenCentral() 10
maven { url "https://maven.google.com" } google() maven { url ’https://jitpack.io’ } } } Listing 3: Gradel.properties Main Activity.java - This is the core section of the project, where all the behaviour of the application is handled. While using the application, the user can choose the procedure of the location data, either the raw GPS data or the fusion data with Kalman filter. I added the following code to retrieve the provider information to store it in the result files, so in each measurement test I can know which is the provider. To implement this, I created a new function called getProvider() and declared 2 static booleans that will give me the signal sequence information. With the simplest conditional if in the created function I could store the location provider which will be saved together with the coordinates and the time in a json file. protected static Boolean fusedOn= false; protected static Boolean gpsOn= false; private void set_isLogging(boolean isLogging) { if (isLogging) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); m_presenter.stop(); m_presenter.start(); m_geoHashRTFilter.stop(); m_geoHashRTFilter.reset(this); if (fusedProvider.isSelected()) { this.provider = Settings.LocationProvider.FUSED; this.fusedOn=true; this.gpsOn=false; } if (gpsProvider.isSelected()) { this.provider = Settings.LocationProvider.GPS; this.gpsOn=true; this.fusedOn=false; } } } public Settings.LocationProvider getProvider() { if(gpsOn){ return this.provider= Settings.LocationProvider.GPS; } 11
if (fusedOn) { return this.provider= Settings.LocationProvider.FUSED; } return this.provider; } Listing 4: Main Activity.java MapPresenter.java - In this file, I have included code to filter the captured data and store it in a JSON file. gps data.json - During the measurement test, this file captures all the coordinates obtained from the GPS sensors, recording both longitude and latitude along with the corresponding timestamp. It also contains information about the data provider. kalman filter data.json - This file collects all the coordinates collected by the sensors, specifically those filtered by the Kalman filter during the measurement test. This file also contains time and provider information. kalman filter geo data.json - This file does not store raw coordinates, but only the data obtained after applying GeoHash. GeoHash essentially converts coordinates to strings, preceded by an averaging process of the coordinates. Since this functionality already existed in the application interface, we decided to keep it. However, this file did not prove to be of significant use for this thesis. private MainActivity activity = new MainActivity(); // tacknumber to identify tests measurement private int tacknumber = 0; //files names private String gpsFile = "gps_data.json"; private String kalmanFilterFile = "kalman_filter_data.json"; private String kalmanFilterGeoFile = "kalman_filter_geo_data.json"; JSONObject jsonDataKalman = new JSONObject(); JSONObject jsonDataGps = new JSONObject(); JSONObject jsonDataKalmanGeo = new JSONObject(); //json file will be saved only if there is information for (Location loc : new ArrayList<>(m_lstKalmanFilteredCoordinates)) { timestampUnix = loc.getTime(); timestampIso = dateFormat.format(new Date(timestampUnix)); timestamp = timestampIso; routeFilteredKalman.add(new LatLng(loc.getLatitude(), loc.getLongitude())); 12
if (routeFilteredKalman != null) { jsonDataKalman.put("Latitude", loc.getLatitude()); jsonDataKalman.put("Longitude", loc.getLongitude()); jsonDataKalman.put("Timestamp", timestamp); jsonDataKalman.put("Provider", activity.getProvider()); saveLocationDataToJson(tacknumber + "_" + kalmanFilterFile, jsonDataKalman); } } for (Location loc : new ArrayList<>(m_geoHashRTFilter.getGeoFilteredTrack())) { timestampUnix = loc.getTime(); timestampIso = dateFormat.format(new Date(timestampUnix)); timestamp = timestampIso; routeFilteredWithGeoHash.add(new LatLng(loc.getLatitude(), loc.getLongitude())); if (routeFilteredWithGeoHash != null) { jsonDataKalmanGeo.put("Latitude", loc.getLatitude()); jsonDataKalmanGeo.put("Longitude", loc.getLongitude()); jsonDataKalmanGeo.put("Timestamp", timestamp); jsonDataKalmanGeo.put("Provider", activity.getProvider()); saveLocationDataToJson(tacknumber + "_" + kalmanFilterGeoFile, jsonDataKalmanGeo); } } for (Location loc : new ArrayList<>(m_lstGpsCoordinates)) { timestampUnix = loc.getTime(); timestampIso = dateFormat.format(new Date(timestampUnix)); timestamp = timestampIso; routGpsAsIs.add(new LatLng(loc.getLatitude(), loc.getLongitude())); if (routGpsAsIs != null) { jsonDataGps.put("Latitude", loc.getLatitude()); jsonDataGps.put("Longitude", loc.getLongitude()); jsonDataGps.put("Timestamp", timestamp); jsonDataGps.put("Provider", activity.getProvider()); saveLocationDataToJson(tacknumber + "_" + gpsFile, jsonDataGps); } } } public void saveLocationDataToJson(String fileName, JSONObject jsonData) 13
throws IOException { try { //saved filed location String baseDir = String.valueOf(getApplicationContext().getFilesDir()); File filePath = new File(baseDir, fileName); FileWriter fileWriter = new FileWriter(filePath, true); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); //write data in the json file bufferedWriter.write(jsonData.toString()); bufferedWriter.newLine(); bufferedWriter.flush(); bufferedWriter.close(); }catch (IOException e) { e.printStackTrace(); } } Listing 5: MapPresenter.java After the code modifications, In order to obtain a good analysis of the data collected by the application, I had to create the several scripts to process and manage the data, so that I could obtain the final results and conclusions. These scripts are well explained with the measurements evaluation in the section 4. 14
3.4 Application To install the application on the Android device, I first enabled the debugger option on the phone and then installed an external application from Google Play Store, AnyTo, to simulate the location. Secondly, with the USB connection established between the laptop and the smartphone, Android Studio automatically detected the mobile device and installed the application directly on the smartphone. This section shows some screenshots of the mobile applications. Figure 9: App icon Figure 10: App home screen Figure 11: App calibration The Fig. 9 provides a visual representation of the app’s interface on an Android device. The Fig. 10 reflects the home screen of the app, as it can be appreciated, because of the modification of the code, Camp Nou appears. It also shows the user interface (UI), which is basically divided into 3 areas. On the one hand, the top section displays the map, while the middle and bottom sections contain the main buttons. The 3 checkboxes GPS, Filtered and Filtered+Geo allow the user to choose which coordinates to display on the map. In addition, there is a calibration button, the location provider button and the start/stop tracking button. The menu icon, represented by three dots in the top right corner of the app, serves as a gateway to the Kalman filter settings, allowing users to adjust sensor offsets, time 15
intervals between location updates, sensor frequencies and more, either before or during the app runtime. The Fig. 11 then shows the first step of the app, the calibration of the sensors before the tracking starts. Figure 12: App after calibration Figure 13: App start tacking The Fig. 12 illustrates the behaviour of the application after the tracking process has started. It shows your current location and activates the tracking feature, as shown in the Fig. 13, which shows the GPS signal during tracking. Activating all three checkboxes will display the GPS, Filtered and Filtered+Geo signals simultaneously. 16
environmental reports. These reports provide details about sustainable practices, environmental certifications, and the sources of raw materials, including those used in the batteries. Key resources include computing power, data storage and network infrastructure. The idea is to reduce resource consumption by using older equipment. The intention is to improve the environmental footprint, and proper management of electronic waste is crucial to achieving this. The project aims to make efficient use of existing resources, particularly older equipment, while implementing effective e-waste management practices to improve overall environmental sustainability. The main risk is that the application may become dependent on other new devices if the sensors stop working, or that an external party may misuse the product. As the application is already up and running, if work on this project were to be resumed, the time commitment would be significantly reduced and there would be no need for as many devices as previously used for application testing. The main constraint is the time available to carry out this project. Although the results are satisfactory, with more time the focus could be on refining the project to achieve a more sustainable, efficient and durable application. 5.1.2 Economic impact This section outlines the economic impact of the project, including the cost of labour and services used to carry out this thesis. The number of people involved in this thesis was 4, including 1 student and 3 supervisors. The role of the supervisors was to guide and oversee the work carried out by the student, in this case myself. As this was a semester project, it was organised and divided into several parts. Figure 19: Calender of tasks Hour price/hour people Cost (€) Developers 600 20 1 12.000 Supervisors 300 25 3 22.500 Taxes 42% 13.800 Total 48.300 € Table 2: Salary costs This represents the estimated remuneration of the team members involved in the project according to the salaries and taxes of Vienna. In addition, there are associated costs for materials and services. 23
As this work can be carried out remotely without the need for an office, the associated costs for office services have been excluded. Concerning the essential components, the following items are considered: Expense Cost (€) Hardwares Laptop 900 Mobile Devices for Testing 500 Electricity 60 Internet Connection 45 Salaries 48.300 € Water 50 SIM suscrpition 30 Water 50 Miscellaneous Expenses 100 Total 50.075 € Table 3: General Costs The total cost includes both human resources (salaries) and material resources (hardware, internet, etc.) as well as essential services such as water, electricity, etc. The estimated life cycle of the product will probably be similar to its current life cycle, but it will also depend on whether future smartphone versions will require adaptation of the application with updates or modifications. In such cases, the cost could potentially double, as it would be necessary to repeat the same work done during the thesis. The results of this project, particularly the lessons learned from developing apps in Android Studio, could benefit similar projects by providing valuable lessons, code snippets and best practices. Open sourcing of relevant components could further contribute to the wider development community. In addition, rapid changes in technology may require costly updates, and volatile and abrupt changes in the economy may influence discontinuation of product use, are the main risks from an economic perspective. 5.1.3 Social impact It is an open and public project that can be used by anyone, regardless of gender, background or beliefs, with a minimal knowledge of the project. This work includes extensive reflection on personal, professional and ethical standards. Particular attention has been paid to ensuring that inclusive and non-sexist language is used throughout the project. The main goals of updating the dependencies and evaluating the application have been achieved. However, as it’s a very open and comprehensive project, digging deeper reveals areas for improvement, such as sensor calibration, and it’s a project aimed at 24
all kinds of audiences worldwide. There are no barriers or restrictions to using this application. One of the risks is that the user’s location data could be leaked due to a bug in the application. However, as devices become more secure, such incidents are becoming less common. 5.2 Ethical implications This thesis responds to the needs related to the improvement of location accuracy. These needs stem from the huge demand and use of geolocation services. Definelty, this project could have strong implications beyond the proposal. For example, improvements in personal safety and efficiency of location-based services, as well as ethical challenges related to privacy and data security. It is a project that includes some ethical codes such as efficiency, security, equality... and also some integrity codes of the UPC research such as responsibility, transparency and reliability among others. 5.3 Relationship with the Sustainable Development Goals As it is a geolocation application that uses the Kalman filter to correct for inaccuracies in the GPS signal, it contributes to several SDGs [3], in particular these: SDG 3 - Good Health and Well-being: The application will be very useful for ambulances to move more accurately, improving response times and ultimately contributing to better health and well-being. SDG 4 - Quality Education: This project could be used as a research topic to improve accuracy. It could also be used as a tutorial to explain the differences between Kalman filter signals and GPS signals, contributing to quality education. SDG 11 - Sustainable Cities and Communities: The application will help improve the efficiency of urban services and provide information on urban mobility, in line with the goal of creating sustainable cities and communities. SDG 17 - Partnerships for the Goals: As this project has been the subject of research, collaboration with other organisations, universities or government agencies could help to achieve more goals and further improve the application. 25
6 Conclusion This chapter concludes the research work presented in this bachelor thesis, summarising the main factor that determined the evolution and results of the thesis and the potential direction for future work. The thesis involved a series of configurations and modifications to the application to keep it up to date. Then, in order to verify the main hypothesis, filtered signal by kalman filter is more accurate then GPS signal, a series of tests and measurements were carried out. The structure of the project and the development of the application in Android Studio were analysed and thoroughly understood. Working with different devices, both virtual and physical, including emulators, was crucial to confirm the functionality of the application on different devices. Various test campaigns and measurements confirmed the main question of this thesis: overall, the filtered signal is more accurate and useful than the GPS signal in different situations and contexts. As it is detailed in the result section (4), after analysis the mean error of all tests in table 1, it can be concluded that the filtered signal outperformed the GPS signal at least in urban areas. Although the figures and tables contribute to the validation of the hypothesis, the maximum distance error is still unusual - 60 metres. The reason that could lead us to these errors is probably my limited experience of signal processing algorithms or the mobile device itself was not thoroughly analysed in terms of its characteristics or sensors. Also, concerning the reference route, there may be sections where the exact route was not followed during the tests. The test area, an urban area with tall buildings and high population density, could have affected the signals due to multipath interference, amongst other things, and the assumption of a constant speed during the tests. However, in indoor environments with poor coverage, this cannot be confirmed with absolute certainty because the detailed signal analysis could not be taken as the reference coordinates were lacking. Regarding the economic and sustainability study, because it is a big project, there are several people involved, their own investment, people’s salaries, materials and resources, which leads to some economic and environmental impacts. But this app will have a long life span because it can be used in old and low-end smartphones. It is therefore a positive contribution to the reduction of e-waste. This thesis marks the conclusion of a semester’s work. Despite the positive results, there are still certain aspects that need to be addressed. For example, developing the application for other operating systems aside from Android, improving the application’s UI, optimizing the dimensions of the application layout for different devices. These considerations highlight the need for a comprehensive analysis and further study in order to draw definitive conclusions and improve the application. 26
Bibliography [1] Puripak Chunhakam, Phurit Pummarin, Purichaya Jeen-im, Paramote Wardkien, Pichet Wisartpong, and Krittapas Lertteerada. Gps positon predicting system by kalman filter with velocity from obd and direction from magnetometer. In 2021 9th International Electrical Engineering Congress (iEECON), pages 444–447, 2021. [2] Marc Antoni Collell Vendrell. Requeriments de posicionament del cotxe aut`onom. PhD thesis, UPC, Escola d’Enginyeria de Telecomunicaci´o i Aeroespacial de Castelldefels, Departament de Teoria del Senyal i Comunicacions, Sep 2018. [3] Generalitat de Catalunya Departament d’Educaci´o. Els 17 ods. https: //educacio.gencat.cat/ca/departament/linies-estrategiques/ods/els- 17-ods/index.html. 2023. [4] Emil Dziadczyk, Wojciech Zabierowski, and A. Napieralski. Satellite navigation system gps. pages 504 – 506, 03 2007. Sections I, II, III, IV, V, VI, VII. [5] Ziyad Khalaf Farej and Ahmed Nadeem Ismail. On the location accuracy of the multi-antenna gps. In 2023 International Conference on Engineering, Science and Advanced Technology (ICESAT), pages 29–33, 2023. [6] Paul Groves. Principles of GNSS, Inertial, and Multisensor Integrated Navigation Systems, Second Edition. 03 2013. [7] Oleg Katkov. Reduce gps data errors on android app with kalman filter and accelerometer. https://maddevs.io/blog/reduce-gps-data-error-on- android-with-kalman-filter-and-accelerometer/, Mar 2018. Mad Devs Blog, Sections 1, 2, 3, 4, 5, 6, 7, 8. [8] Qiang Li, Ranyang Li, Kaifan Ji, and Wei Dai. Kalman filter and its application. In 2015 8th International Conference on Intelligent Networks and Intelligent Systems (ICINIS), pages 74–77, 2015. [9] Mad Devs. What can ”mad location manager” do? https://github.com/ maddevsio/mad-location-manager, 2020. [10] Samsung Electronics. Samsung electronics releases 2023 sustainability report. https://news.samsung.com/global/samsung-electronics-releases- 2023-sustainability-report,, June 30, 2023. 27
[11] P Srinivas and Anil Kumar. Overview of architecture for gps-ins integration. In 2017 Recent Developments in Control, Automation Power Engineering (RDCAPE), pages 433–438, 2017. [12] TheCircularLab. Los ordenadores tambi´en emiten co2. https://www. thecircularlab.com/los-ordenadores-tambien-emiten-co2/, 2016. [13] Xiaomi Corporation. 2022 environmental, social and governance (esg) report. https://www.mi.com/global/about/sustainability/, 2022. 28
Annex A1 Virtual Emulator Specification Properties avd.ini.displayname Nexus 5X API 29 avd.ini.encoding UTF-8 AvdId Nexus_5X_API_29 disk.dataPartition.size 6442450944 fastboot.forceChosenSnapshotBoot no fastboot.forceColdBoot no fastboot.forceFastBoot yes hw.accelerometer yes hw.arc false hw.audioInput yes hw.battery yes hw.camera.back virtualscene hw.camera.front emulated hw.cpu.ncore 4 hw.device.hash2 MD5:ae200ad6786ec467cb9067f7b46b0fd1 hw.device.manufacturer Google hw.device.name Nexus 5X hw.gps yes hw.gpu.enabled yes hw.gpu.mode auto hw.initialOrientation Portrait hw.keyboard yes hw.lcd.density 420 hw.lcd.height 1920 hw.lcd.width 1080 hw.mainKeys no hw.ramSize 1536 hw.sdCard yes hw.sensors.orientation yes hw.sensors.proximity yes image.androidVersion.api 29 image.sysdir.1 system-images/android-29/google/x86/ PlayStore.enabled true runtime.network.latency none runtime.network.speed full showDeviceFrame yes skin.dynamic yes tag.display Google Play tag.id google_apis_playstore vm.heapSize 228 29
A2 Code Modification A2.1 Conversion of Json File in valid Model import json # Read the content of the JSON file with open(’aaaaaaaa_new_All/6_kalman_filter_data_06.json’,’r’)asfile: data = json.load(file) # Sets to store unique coordinates and timestamps unique_coordinates = set() unique_timestamps = set() # List to store filtered data filtered_data = [] # Iterate through the data and filter unique coordinates and timestamps for entry in data: latitude = entry["Latitude"] longitude = entry["Longitude"] timestamp = entry["Timestamp"] # Check if coordinates and timestamp are unique if (latitude, longitude) not in unique_coordinates and timestamp not in unique_timestamps: # Add to sets and the results list unique_coordinates.add((latitude, longitude)) unique_timestamps.add(timestamp) filtered_data.append({ "Latitude": latitude, "Longitude": longitude, "Timestamp": timestamp, "Provider": entry.get("Provider",""), }) # Write the result to a new file with open(’aaaaaaaa_new_All/6_kalman_filter_data_unique.json’,’w’) as output_file: json.dump(filtered_data, output_file, indent=2) A2.2 Conversion of coordinates in Cartesian’s axes import json from datetime import datetime from pyproj import Proj, transform 30
# Read the content of the JSON file with open(’1_gps_data_01.json’,’r’)asfile: data = json.load(file) # Initialize the projection transformer (WGS 84 to your desired CRS) in_proj = Proj(init=’epsg:4326’)# WGS 84 out_proj = Proj(init=’EPSG:31287’)# Or any other desired CRS # List to store the new coordinates and timestamp transformed_data = [] # Iterate through the data and perform the transformation for entry in data: # Transform the coordinates x, y = transform(in_proj, out_proj, entry[’Longitude’], entry[’Latitude’]) # Convert the timestamp format timestamp = datetime.strptime(entry[’Timestamp’].split(’,’)[1], "%Y-%m-%dT%H:%M:%S.%fZ").strftime("%H:%M:%S") # Save the new coordinates and timestamp transformed_data.append({ "X": x, "Y": y, "Timestamp": timestamp }) # Print the current entry print(f"Original Entry: {entry}") print(f"Transformed Entry: {transformed_data[-1]}\n") # Save the transformed data to a new JSON file with open(’Transformed_1_gps_data_01.json’,’w’) as outfile: json.dump(transformed_data, outfile, indent=2) A2.3 Theoretical coordinates interpolation import json from datetime import datetime, timedelta def calculate_exact_times(coordinates, start_time, end_time): start_time = datetime.strptime(start_time, "%H:%M:%S") end_time = datetime.strptime(end_time, "%H:%M:%S") total_time = end_time - start_time total_time_seconds = total_time.total_seconds() 31
time_interval_seconds = total_time_seconds / (len(coordinates) - 1) exact_times = [] for i, coordinate in enumerate(coordinates): exact_time = start_time + timedelta(seconds=i * time_interval_seconds) exact_times.append({ ’x’: coordinate[’x’], ’y’: coordinate[’y’], ’Exact Time’: exact_time.strftime("%H:%M:%S.%f")[:-3] }) return exact_times # Load coordinates from a JSON file input_file_path = ’aaaaaaaa_new_All/real_coordinates/subsampled_RealCoordinates.json’ with open(input_file_path, ’r’)asfile: coordinates = json.load(file) # Define start and end times with seconds start_time = "13:31:36" end_time = "13:41:24" # Calculate exact times exact_times = calculate_exact_times(coordinates, start_time, end_time) # Save the results to a new JSON file output_file_path = ’aaaaaaaa_new_All/real_coordinates/Theoretical_coordinates_06.json’ with open(output_file_path, ’w’)asfile: json.dump(exact_times, file, indent=2) # Print the results for exact_time in exact_times: print(f"Coordinates: ({exact_time.get(’x’, ’N/A’)}, {exact_time.get(’y’, ’N/A’)}), Exact Time: {exact_time.get(’Exact Time’, ’N/A’)}") A2.4 Testing route and Real route representation import json import matplotlib.pyplot as plt import contextily as ctx 32