Git Product home page Git Product logo

maddevsio / mad-location-manager Goto Github PK

View Code? Open in Web Editor NEW
521.0 40.0 156.0 16.5 MB

Mad Location Manager is a library for GPS and Accelerometer data "fusion" with Kalman filter

License: MIT License

C 2.77% C++ 24.30% QMake 0.33% Java 44.95% Shell 0.04% Swift 7.85% Objective-C 19.75%
noise-filtering kalman-filter android-library java gps-tracking geohash-algorithm geohash kalman android tracking-application

mad-location-manager's Introduction

This is library for GPS and Accelerometer data "fusion" with Kalman filter. All code is written in Java. It helps to increase position accuracy and GPS distance calculation on Android devices for the driver's and couriers' apps. And also, it may be used for precise tracking in on-demand services.

Project consists of 2 parts:

Blog (english version)

Blog (russian version)

Our site

License: MIT Developed by Mad Devs

What can "Mad Location Manager" do?

This module helps to increase GPS coordinates accuracy and also:

  • reduces the errors in route tracking;
  • decreases the noise from Low-class smartphones;
  • excludes sharp «jumps» to the points remote from a real route;
  • eliminates additional distance when the object is motionless;
  • filters errors duу to the short-term loss of GPS-signal.

How to install

Use last version from link below (jitpack):

How to use

There is example application in current repository called "Sensor Data Collector".

WARNING!!

Right now these sensors should be available:
TYPE_ROTATION_VECTOR, TYPE_LINEAR_ACCELERATION.

It's possible to use just TYPE_ACCELEROMETER with high-pass filter.
Also it's possible to use Madgwick filter instead of rotation vector, but gyroscope and magnetometer sensors should be available in that case.

KalmanLocationService

This is main class. It implements data collecting and processing. You need to make several preparation steps for using it:

  1. Add to application manifest this:
<service
            android:name="mad.location.manager.lib.Services.KalmanLocationService"
            android:enabled="true"
            android:exported="false"
            android:stopWithTask="false" />
  1. Create some class and implement LocationServiceInterface and optionally LocationServiceStatusInterface .
  2. Register this class with ServicesHelper.addLocationServiceInterface(this) (do it in constructor for example)
  3. Handle locationChanged callback. There is Kalman filtered location WITHOUT geohash filtering. Example of geohash filtering is in MapPresenter class.
  4. Init location service settings object (or use standard one) and pass it to reset() function.

Important things!

It's recommended to use start(), stop() and reset() methods, because this service has internal state. Use start() method at the beginning of new route. Stop service when your application doesn't use locations data. That need to be done for decrease battery consumption.

Kalman filter settings

There are several settings for KalmanFilter. All of them stored in KalmanLocationService.Settings class.

  • Acceleration deviation - this value controls process noise covariance matrix. In other words it's "trust level" of accelerometer data. Low value means that accelerometer data is more preferable.
  • Gps min time - minimum time interval between location updates, in milliseconds
  • Gps min distance - minimum distance between location updates, in meters
  • Sensor frequency in Herz - the rate sensor events are delivered at
  • GeoHash precision - length of geohash string (and precision)
  • GeoHash min point - count of points with same geohash. GPS point becomes valid only when count greater then this value.
  • Logger - if you need to log something to file just implement ILogger interface and initialize settings with that object. If you don't need that - just pass null .

There is an example in MainActivity class how to use logger and settings.

GeoHashRTFilter

There are 2 ways of using GeoHash real-time filter :

  • It could be used as part of KalmanLocationService. It will work inside that thread and will be used by service. But then you need to use start(), stop() and reset() methods.
  • It could be used as external component and filter Location objects from any source (not only from KalmanLocationService). You need to reset it before using and then use method filter() .

It will calculate distance in 2 ways : Vincenty and haversine formula . Both of them show good results so maybe we will add some flag for choose.

The roadmap

Visualizer

  • Implement some route visualizer for desktop application
  • Implement Kalman filter and test all settings
  • Implement noise generator for logged data
  • Improve UI. Need to use some controls for coefficient/noise changes

Filter

  • Implement GeoHash function
  • Get device orientation
    • Get device orientation using magnetometer and accelerometer + android sensor manager
    • Get device orientation using magnetometer, accelerometer and gyroscope + Madgwick AHRS
    • Get device orientation using rotation vector virtual sensor
  • Compare result device orientation and choose most stable one
  • Get linear acceleration of device (acceleration without gravity force)
  • Convert relative linear acceleration axis to absolute coordinate system (east/north/up)
  • Implement Kalman filter core
  • Implement Kalman filter for accelerometer and gps data "fusion"
  • Logger for pure GPS data, acceleration data and filtered GPS data.
  • Restore route if gps connection is lost

Library

  • Separate test android application and library
  • Add library to some public repository

Theory

Kalman filtering, also known as linear quadratic estimation (LQE), is an algorithm that uses a series of measurements observed over time, containing statistical noise and other inaccuracies, and produces estimates of unknown variables that tend to be more accurate than those based on a single measurement alone, by estimating a joint probability distribution over the variables for each timeframe.

You can get more details about the filter here.

The filter is a de-facto standard solution in navigation systems. The project simply defines the given data and implements some math.

The project uses 2 data sources: GPS and accelerometer. GPS coordinates are not very accurate, but each of them doesn't depend on previous values. So, there is no accumulation error in this case. On the other hand, the accelerometer has very accurate readings, but it accumulates error related to noise and integration error. Therefore, it is necessary to "fuse" these two sources. Kalman is the best solution here.

So first - we need to define matrices and do some math with them. And second - we need to get real acceleration (not in device orientation).

First one is described in current project's wiki. But second one is little bit more complex thing called "sensor fusion". There is a lot information about this in internet.

Algorithms

Sensor fusion is a term that covers a number of methods and algorithms, including:

For real acceleration we need to know 2 things: "linear acceleration" and device orientation. Linear acceleration is acceleration along each device axis excluding force of gravity. It could be calculated by high pass filter or with more complex algorithms. Device orientation could be calculated in many ways:

  • Using accelerometer + magnetometer
  • Using accelerometer + magnetometer + gyroscope
  • Using Madgwick filter
  • Using virtual "rotation vector" sensor.

Best results show Madgwick filter and ROTATION_VECTOR sensor, but Madgwick filter should be used when we know sensor frequency. Android doesn't provide such information. We can set minimum frequency, but it could be much higher then specified. Also we need to provide gain coefficient for each device. So best solution here is to use virtual ROTATION_VECTOR sensor. You can get more details from current project's wiki.

Issues

Feel free to send pull requests. Also feel free to create issues.

License

MIT License

Copyright (c) 2020 Mad Devs

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.

mad-location-manager's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mad-location-manager's Issues

Sample not working

I have the same issue as described here - #2
I cloned the repository, built the apk and started it on the phone, but it doesn’t seem to work ok.
See the screenshots of what happens when I press on buttons in the app:
2
1

I open the log file in SendDataCollector folder and there I can see a whole bunch of data, like that:

1527313200064|I|X-LOG|31007242 GPS : pos lat=55,593639, lon=37,478290, alt=217,394154, hdop=8,000000, speed=16,755537, bearing=21,427261, sa=0,800000
1527313200065|I|X-LOG|01007242 KalmanAlloc : lon=37,478290, lat=55,593639, speed=16,755537, course=21,427261, m_accDev=0,100000, posDev=8,000000
1527313202025|I|X-LOG|31009225 GPS : pos lat=55,593906, lon=37,478476, alt=217,249434, hdop=6,000000, speed=16,708115, bearing=21,522673, sa=0,600000
1527313202135|I|X-LOG|21009225 KalmanUpdate : pos lon=37,478476, lat=55,593906, xVel=-14,907940, yVel=7,544164, posErr=6,000000, velErr=0,600000
1527313204035|I|X-LOG|31011234 GPS : pos lat=55,594177, lon=37,478662, alt=216,945878, hdop=6,000000, speed=16,529324, bearing=21,998478, sa=0,600000
1527313204138|I|X-LOG|21011234 KalmanUpdate : pos lon=37,478662, lat=55,594177, xVel=-16,528880, yVel=-0,121148, posErr=6,000000, velErr=0,600000

So, the app actually gets the location data but does not show anything on UI of the app (I thought there will be the track shown on the map).
Why doesn’t it show anything?

Location bearing

Hi,

Thanks for this nice library.
However, it seems that bearing isn't provided with Location callback.
Could this issue be addressed ?

Thanks,
Moti.

Speed values and Q matrix

Can someone tell me why rebuildQ is in function of m_predictCount since the accDev does not change over time?

Also, do you have some clue on why the speed readings are so wrong?

Thank you

How i use Kalmanlocation inside my own service

ServicesHelper.addLocationServiceInterface(SendLocation.this);
when I call this function oncreate of Service class then I get

java.lang.ClassCastException: android.os.BinderProxy cannot be cast to mad.location.manager.lib.Services.KalmanLocationService$LocalBinder

Servicehelper lineno:67

Тестирование на различных данных

Здравствуйте !

Я занимаюсь фильтрацией звезд на треках автотранспорта, возможно ли Ваш пакет использовать для тестирования фильтрации на своих данных ?

callback error

err0

MainActivity.java
private void initActivity() { }
ServicesHelper.getLocationService(this, value -> {}

context = MainActivity
callback = {-$lambda@---}

class com.example.lezh1k.sensordatacollector.-$$Lambda$MainActivity$TCctZCsoVok8NZ14_qqYhiCfNqQ

i guess missing MainActivity.

please help me


err1

Results worse after filtering with kalman.

After filtering with kalman filter my position is very noisy.
My sensor sends me a quaternion from IMU which i use instead of madgwick.
Then I make rotation matrix from it, and rotate my acceleration vector to get Absolute acc.

Is that approach correct? Maybe the quaternion is wrongly calculated?
Sensor is bosch bno055

Размерности матриц

Здравствуйте !

У меня тут еще 1 вопрос появился, в случае когда наблюдениями являются широта, долгота, скорость и направление движения, каковы должны быть размерности матрицы эволюции системы, матрицы управления ? Cпасибо.

Adaptability of code

Hi, just a question not an issue but was not sure where the appropriate place to ask was. So i have two question regarding the implementation of your kalman filter.

Firstly, how adaptable is this. Currently i have an android app that posts it location to a web api at regular intervals. I want to filter the data at server level to keep a log of the original data. I use the fused location provider in my app. So in theory could the kalman filter be moved to a stand alone library that i could just post the gps and sensory data too? Completely new to signal noise and filtering so sorry if these questions sound silly.

And secondly how is the battery consumption with combining the sensory data? Using the fused location provider i have had no battery issues. So does your approach reduce the battery life faster?

Again apologies if this is not the correct place to be asking these questions.

How does this library account for sensors with incompatible update intervals?

A couple of my cheap Android dev phones don't give me any sensors back so I can't step through the code to trace and understand. Does this implementation work for sensors with different update intervals? I.e. if the accelerometer is 10 hz but gps is only 1 hz, can the predict be called more than once before the update is called? (GPS update interval is limited by AOSP or no reception like in a tunnel)

Conversely, if the accelerometer is subject to too much noise and values are unstable, can the update be called more than once before a single predict is called? (Running with phone and accelerometer isn't smooth)

working without sensor

I am working on a port to JS.
And i am facing an issue. When not using sensors (comment the registerListener on android) the returned locations in onLocationChangedImp are 0,0.
This is not expected. It means the kalman filter does not work when no sensor are used. I suppose it is because the matrices are not initialized correctly. But i am not sure how to initialize them.
Can anyone help?
Thanks

Map tracking is not working for me !

I have downloaded the Sensor data collector app but it doesn't seem to work with me.
by "Not working" i mean it doesn't track the route !
Screenshot_1556279582

My mobile is infinix Note 4 and i checked that it has an accelerometer & gyroscope . my GPS is working and has the permission , my network is ON , and this is what my log file looks like !

Screenshot from 2019-04-26 13-52-51
i am appreciating any help!

Poor documentation

Hi, I am working with this library, it works fine with default parameters, but I would like to know more about the settings, so I have some questions:

  1. there are 2 not described parameters for KalmanLocationService.Settings (VelFactor, PosFactor). What they are for? How to use them?
  2. what is the radius of “merging area” for GeohashRTFilter? For example, if the hash length is 8 and the point count is 2.
  3. GeohashRTFFilter calculates 4 distances (distanceGeoFiltered, distanceGeoFilteredHP, distanceAsIs, distanceAsIsHp). What is what? Which one should I use?
  4. How is IsRunning() method (KalmanLocationService) supposed to work? It returns false even when my app is getting location updates, is it ok?

Sample not working

Where i can see documentation? Or working sample? For now, sample not detect location or anything, tested on Genymotion, and two real phones.

Incompatible matrix dimensions.

Im trying to port this to Java, and there is some code I dont understand.
For example: matrix R is created with 2x2 dimensions:
f->R = MatrixAlloc(measureDimension, measureDimension); f->kf = KalmanFilterCreate(4, 2, 2);
And then rebuildR function assigns 4x4 matrix to it.
double velSigma = posSigma * 1.0e-01; MatrixSet(f->kf->R, posSigma, 0.0, 0.0, 0.0, 0.0, posSigma, 0.0, 0.0, 0.0, 0.0, velSigma, 0.0, 0.0, 0.0, 0.0, velSigma); }

Same thing with Zk vector.
Im not an expert in C, so maybe someone could explain this?

compiling Visualizer + disabling GeoHash

heya , really nice project !
few questions 👍
1.
how do i compile the visualizer in order to play the log files(ubuntu or windows) ? i haven't found any Makefile in the project itself.
2.
regarding GeoHash , if i want to disable it i just need to give 0,0 to his config under utils?
if so the green line on map will be only the raw GPS and the blue line will be the Correct GPS coordinate after kalman filter with corrected accelerometer values at that time frame right?

my green and blue lines are on the same coordinates although ive tried to walk few mins in an open streen with the application .

thanks alot.

When 'useGpsSpeed' is 'false', m_kf.Zk is size 2 but update expects size 4

Apparently 'assert' is turned off so the app does not crash even though 'm_kf.Zk.setData(x, y, xVel, yVel);' is passing 4 values when the Zk is only a 2 element vector.

public void update(double timeStamp, double x, double y,
                       double xVel,  double yVel,
                       double posDev,  double velErr) {
        m_predictCount = 0;
        m_timeStampMsUpdate = timeStamp;
        rebuildR(posDev, velErr);
        m_kf.Zk.setData(x, y, xVel, yVel);  // <--- Zk has 2 elements, not 4
        m_kf.update();
   }

cannot be cast to mad.location.manager.lib.Services.KalmanLocationService$LocalBinder

default

Спасибо за огромный труд! Ваша библиотека - моя последняя надежда на успех предприятия, которое уже год как не может быть завершено из-за того что телефоны врут. Особенно когда лежат на месте и никуда не едут.

Я подключил библиотеку как указано в описании. Подключил внутри сервиса который implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener

потому что это то единственное решение которое мне позволило обойти DOZE mode. Мне нужны геоданные пока экран отключен и даже если телефон не трогали пол-часа. Оказалось он не засыпает только когда службы гугла хотят координат тоже.

Помогите пожалуйста

Question for getting absolute acceleration.

I have a question for get absolute acceleration in KalmanLocationService class.

In onSensorChanged callback function:
android.opengl.Matrix.multiplyMV(absAcceleration, 0, rotationMatrixInv, 0, linearAcceleration, 0);
The question is that when the user hold the phone moving, I think apart we need to do rotate from the device coordinate to global coordinate and we also need to do projection in each global coordinate axis.

But for our code, I only see the rotation code and I didn't see the projection code.

Could you tell me is there any misunderstanding of the code?

Any ideas - how else to improve the track?

Get rid of the stars finally?
Screenshot_2019-03-19-14-10-07-188_com example lezh1k sensordatacollector
Screenshot_2019-03-19-14-10-24-670_com example lezh1k sensordatacollector
Here such parameters were used:
public static final int GEOHASH_DEFAULT_PREC = 8;
public static final int GEOHASH_DEFAULT_MIN_POINT_COUNT = 3;

now added (while testing):
public static final int GPS_MIN_DISTANCE = 20;

Using a list of gps points.

Hi,

So your combining sensor and location data. Would it still be possible to do this without the sensor data. For example the predict function. Lets say we have a list of Locations. We Initialise the Kalman Filter with the first Location. And then loop through each location, on each iteration we call predict and then update, we then use the predicted values to update and return the location object. I assume this would reduce the accuracy, but this should still reduce noise and jumping correct?

I ask because have been implementing the kalman in c#. And i only have the Location data, so no sensor data to work with. On the predict function could i not just use the xVal and yVal like below.

var xVal = loc.Speed * Math.Sin(loc.Bearing); var yVal = loc.Speed * Math.Cos(loc.Bearing);

loc being the android Location object. I am still learning how the whole kalman fits together so sorry if i am way off with this question.

Question about the Q matrix.

Thanks for sharing your project.

I have one question about the Q matrix.

In #9 you said that

As you said, posSig should be posSigX and posSigY, but we can get speed measurements only from GPS receiver, so for both directions we have one deviation. That's why we use 1 value.

Base on the code, you calculate the posSig from posDev, and the posDev is calculated from velDev, and the velDev is calculated from accDev, but the value of accDev is coming from the accelerometer.

When we calibrate the accelerometer sensor in the device, we get the sigma from each axis of accelerometer.

So, I think the posSig and velSig are both have two values (x-axis and y-axis).

I changed the code like this:

    private void rebuildQ(double dtUpdate,
                          double accXDev,
                          double accYDev) {
        double velXDev = accXDev * dtUpdate;
        double velYDev = accYDev * dtUpdate;
        double posXDev = accXDev * dtUpdate * dtUpdate / 2;
        double posYDev = accYDev * dtUpdate * dtUpdate / 2;
        double Q[] = {
                posXDev * posXDev,  0.0,                posXDev * velXDev,      0.0,
                0.0,                posYDev * posYDev,  0.0,                    posYDev * velYDev,
                posXDev * velXDev,  0.0,                velXDev * velXDev,      0.0,
                0.0,                posYDev * velYDev,  0.0,                    velYDev * velYDev
        };

        m_kf.Q.setData(Q);

    }

In this code, the accXDev and accYDev is calculated from the calibration step.

I'm not sure whether my thinking is right or not.

If there is any problem, please let me know.

Thank you.

Incorrect Speed readings

Hi Again,

I looks like that the speed readings are incorrect.
Today I drove with the new release 0.1.11 - and the speed readings were incorrect.

Even when I stopped, it keep show some incorrect speed readings.
on some point when I drove about 60-70 kmh it showed more than 100 mSec.

Switching to Android GPS provider gives the correct speed.

(in my app I've implemented both mad and android location providers and I can switch between them from settings in run time)

Thanks again,
Moti.

Работа сервиса, когда приложение в фоне

Здравствуйте!
Крутая библиотека и как раз то, что мне надо. Возник вопрос:

Для отслеживания водителя я использую foreground service. Делаю это, так как обычный фоновый service имеет ограничение на количество запросов местоположения в новых версиях Android + вариант с foreground сервисом выглядит более стабильным (не хотелось бы иметь дело с ситуациями, когда приложение не посчитало "пробег" такси из-за убитого в фоне сервиса).
Как лучше использовать ваше решение , что бы избежать подобных ситуаций (когда, к примеру, для использования навигации водитель свернет приложение)?

accelerometer

Hello, it lib look intersting, thank you!
Im confusing with use only TYPE_ACCELEROMETER in high-pass filter. Some device dont have gyroscopes and TYPE_ROTATION_VECTOR, TYPE_LINEAR_ACCELERATION not available... What values of this sensors i must use in onSensorChanged?

locationChanged never runs

Hello.

I have added mad-location-manager to my Gradle build as well as Android manifest and have implemented LocationServiceInterface within my application. Inside my Fragment's onCreate method I run the following code:

ServicesHelper.getLocationService(getActivity(), value -> {

            if (value.IsRunning()){
                return;
            }
            value.stop();
            KalmanLocationService.Settings settings =
                    new KalmanLocationService.Settings(Utils.ACCELEROMETER_DEFAULT_DEVIATION,
                            Utils.GPS_MIN_DISTANCE,
                            Utils.GPS_MIN_TIME,
                            Utils.GEOHASH_DEFAULT_PREC,
                            Utils.GEOHASH_DEFAULT_MIN_POINT_COUNT,
                            Utils.SENSOR_DEFAULT_FREQ_HZ,
                            null, false);

            value.reset(settings);
            value.start();

            Log.d("MAD", Boolean.toString(value.IsRunning()));
        });

This returns "False" in my LogCat, indicating that even though I 'start' the service it never actually stops running. I have overridden locationChanged() in my Fragment as well to simply log the new latitudes and longitudes but no matter how much walking around I do with the phone this function never runs.

What could be preventing my KalmanLocationService from starting?

coordinate transformation issues

this.absNorthAcc = absNorthAcc * Math.cos(declination) + absEastAcc * Math.sin(declination);
this.absEastAcc = absEastAcc * Math.cos(declination) - absNorthAcc * Math.sin(declination);

As google doc says https://developer.android.com/reference/android/hardware/GeomagneticField.html#getDeclination()

The transformation seems should be like this:
this.absEastAcc = absEastAcc * cos(declination) + absNorthAcc * sin(declination) this.absNorthAcc = absNorthAcc * cos(declination) - absEastAcc * sin(declination)

Clarification on orientation:

Understanding is that
X is in Longitude towards East
Y is in Latitude towards North

Reflected by expressions below:
can we confirm the expression here in file "KalmanLocationService.java"

xVel = speed * Math.cos(course);
yVel = speed * Math.sin(course);

Typically course being angle from North to East should we rather read/write ?

xVel = speed * Math.sin(course);
yVel = speed * Math.cos(course);

what would be my misunderstanding?

Thanks.

 x = loc.getLongitude(); 
 y = loc.getLatitude();

m_kalmanFilter.update(
sdi.getTimestamp(),
Coordinates.longitudeToMeters(sdi.getGpsLon()),
Coordinates.latitudeToMeters(sdi.getGpsLat()),
xVel,
yVel,
sdi.getPosErr(),
sdi.getVelErr()
);

m_kalmanFilter.predict
(sdi.getTimestamp(),
sdi.getAbsEastAcc(),
sdi.getAbsNorthAcc()
);

m_kalmanFilter = new GPSAccKalmanFilter(
false, //todo move to settings
Coordinates.longitudeToMeters(x),
Coordinates.latitudeToMeters(y),
xVel,
yVel,
m_settings.accelerationDeviation,
posDev,
timeStamp
);

Could not resolve library path

Built new app with the configure error:
Could not find method compile() for arguments [com.github.maddevsio:mad-location-manager:0.1.9] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.

Проверить есть ли необходимые сенсоры для работы библиотеки

Я хотел у себя в приложении убедиться что у телефона есть все необходимые сенсоры для работы библиотеки, и если нету то выполнить другой код...

Я проверяю на сенсоры TYPE_LINEAR_ACCELERATION , и TYPE_ROTATION_VECTOR, пример кода ниже.

И так все нормально определялось, до того момента как в руки попал смартфон Galaxy A5 2017, он проверку на эти два сенсора проходит, но location не получаю, и я начал подозревать, может еще на какие то сенсоры надо проверку делать, какие еще сенсоры требует библиотека??

SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
            Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION);
            Sensor sensor2 = sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);
            
            Intent intent;
            if (sensor == null || sensor2 == null)
            {
                // если какой то сенсор не обнаружен, то выполняю другой код
            }
            else {
                intent = new Intent(this, MadLocationMonitoringService.class);
            }
            startService(this,intent);

matrixDestructiveInvert() question

hello,
Thanks for sharing this project and your work on it.

I have got a question about method to invert matrix. (matrixDestructiveInvert in Matrix class).
I don't clearly understand the way how it is working. Could you tell me if there you use any specific algorithm or you can provide pseudo-code or any source where I can read more about the way you invert matrix in this method?

    public static boolean matrixDestructiveInvert(Matrix mtxin,
                                                  Matrix mtxout) {
       ...

            scalar = 1.0 / mtxin.data[r][r];
            mtxin.scaleRow(r, scalar);
            mtxout.scaleRow(r, scalar);

            for (ri = 0; ri < r; ++ri) {
                scalar = -mtxin.data[ri][r];
                mtxin.shearRow(ri, r, scalar);
                mtxout.shearRow(ri, r, scalar);
            }

            for (ri = r + 1; ri < mtxin.rows; ++ri) {
                scalar = -mtxin.data[ri][r];
                mtxin.shearRow(ri, r, scalar);
                mtxout.shearRow(ri, r, scalar);
            }
        } //for r < mtxin.rows
        return true;
    }

thank you in advance

Location not getting correctly.

Hi,

I'm trying to develop a driver tracking application. At first I was using just Android's LocationManager API with GPS as the only provider. The output was not so perfect, it had jumps all over my route.

It was then I tried using this library. But I lost a lot of locations after that.

route

In this picture Red line shows my route towards destination and Green line shows my route back to where I started. And you can clearly see from the picture that only a few point are plotted. But out of my surprise I got the exact point from where I took the U turn.

NB: The vehicle was continuously moving throughout the route.

My system requires a foreground notification and I'm writing my code on that service. Here is what I included in the code:
`
public class LocationService extends Service implements LocationServiceInterface {
.......

private GeohashRTFilter m_geoHashRTFilter;

@Override
public void onCreate() {
    super.onCreate();

m_geoHashRTFilter = new GeohashRTFilter(Utils.GEOHASH_DEFAULT_PREC, Utils.GEOHASH_DEFAULT_MIN_POINT_COUNT);
startForeground(KEY_NOTIFICATION_ID, getForegroundNotification);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    ServicesHelper.addLocationServiceInterface(this);
    ServicesHelper.getLocationService(this, value -> {
        if (value.IsRunning()) {
            return;
        }
        m_geoHashRTFilter.stop();
        value.stop();
        KalmanLocationService.Settings settings =
                new KalmanLocationService.Settings(Utils.ACCELEROMETER_DEFAULT_DEVIATION,
                        Utils.GPS_MIN_DISTANCE,
                        Utils.GPS_MIN_TIME,
                        Utils.GEOHASH_DEFAULT_PREC,
                        Utils.GEOHASH_DEFAULT_MIN_POINT_COUNT,
                        Utils.SENSOR_DEFAULT_FREQ_HZ,
                        null, false, Utils.DEFAULT_VEL_FACTOR, Utils.DEFAULT_VEL_FACTOR);
        value.reset(settings); 
        value.start();
    });
    return START_STICKY;
}

@OverRide
public void locationChanged(Location location) {
if (location != null ) {
DataManager.getInstance(LocationService.this)
.saveDeviceTracking(location.getLatitude(), location.getLongitude());
}
}
...........
}`

Please help me if I'm missing anything in this.

Incorrect speed longitude and latitude in KalmanLocationService.OnLocationChanged

If I am not mistaken, a few small errors are present in the calculation of the velocities and the correction of the absolute accelerations.

Currently they are implement as follows
xVel = speed * Math.cos(course);
yVel = speed * Math.sin(course);

As xVel represents the speed from West to East and the Cos(0) is equal to 1, you would get the the speed is completely projected on xVel when traveling North and yVel would be 0.
xVel = speed * Math.sin(course);
yVel = speed * Math.cos(course);

Furthermore in SensorGpsDataItem the absolute accelerations are corrected as follows
this.absNorthAcc = absNorthAcc * Math.cos(declination) + absEastAcc * Math.sin(declination);
this.absEastAcc = absEastAcc * Math.cos(declination) - absNorthAcc * Math.sin(declination);
The magnetic declination is defined negative if the magnetic north is to the "west" of the true north, which results in the signs being opposite of what the are now.
this.absNorthAcc = absNorthAcc * Math.cos(declination) - absEastAcc * Math.sin(declination);
this.absEastAcc = absEastAcc * Math.cos(declination) + absNorthAcc * Math.sin(declination);

GPS Status Disabled

Hi,

From some reason, even when GPS is enabled, the GPSEnabledChanged callback initially gives a false status value followed by a true value.

Thanks,
Moti.

Gps min time bellow the GPS intervals

Hi,
Thanks for this promising library - It looks great.

We started testing it and we found that we don't get location callbacks in high frequency (higher than the default updates of the GPS). So for example, if we set it to 200 ms we would expect to get 5 updates a sec, but we still got about 1 GPS a sec (our GPS device updates)

From what I understand, even if the GPS data is not changed with such high frequency, the accelerometer has high-frequency updates, so you can fuse the "old" GPS (provided about one sec ago) values with fresh accelerometer values.

Am I right?
Do you think its possible have high frequent callbacks from the Mad-Location Manager?

Covariance matrix Q

Hi. Thanks for sharing the code of your project.
Have been looking through your blog and your code. Note that the matrix Q is a covariance matrix and as such must be symmetric. The specific values you have chosen seem good, meaning that the matrix should be the following:
Q_k = [ \sigma_posX^2 0 \sigma_posX*\sigma_velX 0 \
0 \sigma_posY^2 0 \sigma_posY*\sigma_velY \
\sigma_posX*\sigma_velX 0 \sigma_velX^2 0 \
0 \sigma_posY*\sigma_velY 0 \sigma_velY^2 ]

Matrix B is 1x4 yet RebuildB tries to set it 2x4 data

With asserts enabled, this crashes:

    private void rebuildB(double dtPredict) {
        double dt2 = 0.5*dtPredict*dtPredict;
        double b[] = {
                dt2, 0.0,
                0.0, dt2,
                dtPredict, 0.0,
                0.0, dtPredict
        };
        m_kf.B.setData(b); <-------  b is 1x4
    }

Example app is not working

I made a build of the SensorDataCollector example app. Then I tried to run it on a 4 different Android phones. It worked only on one of them. By saying "worked" I mean it started to track route. Do you have any idea what is wrong with other devices? Your help is very appreciated ))

Java Control Matrix Column Number Bug?

I by means am no expert in this field, but am implementing my own version of this library and found that the control matrix here: https://github.com/maddevsio/mad-location-manager/blob/master/madlocationmanager/src/main/java/mad/location/manager/lib/Filters/GPSAccKalmanFilter.java was m_kf = new KalmanFilter(4, mesDim, 1); when I beleive the control matrix should be 2 columns not 1 otherwise the matrix multiplication wouldn't work and also the B control matrix from your blog was two columns. It is also 2 in the cpp version of the GPSKalmanFilter. Kinda confused how this even worked to begin with because you technically should have gotten an indexing error. But anyways those are my findings.
Cheers,
@aflofo

Calibration of sensors for Kalman filter

In the Sample application, there is a calibration button. Is that calibration required for getting the proper results?
Should it be called somehow, when using the mad location manager in the app, before we register with ServicesHelper.addLocationServiceInterface(this) and subscribe to location updates?

Can the GeoHashRealTimeFilter be used with FusedLocationProvider

I will like to know if the geohash realtime filter can be used with the fused location provider from Google services.

I have tried using the kalmanService in this project, but when the car is in motion in high speed I can no longer read coordinates out of the GeoHash. I don't know if the GPS readings are failing completely, or the geohash real-time filter is not producing results.

I am mostly using the defaults as is done in the current project, but still, I am unable to get updates, please let me know if any suggestions.

Manipulating R matrix

Hi,
As we want to manipulate and see if we can gain more accurate results, we would like to manipulate posSigma and velSigma in the R matrix. This can be done by using a factor parameter on the settings (and even expose it on the settings of the app for calibration).

Can you expose the settings such factor parameters?

Kalman throws simmilar results then gps

Hi, i'm not sure if this is an Issue with Library. When i implemented it with default settings and made few measurements i didnt saw any improvements in localization outcome. Maybe i'm doing something wrong but i set up the same Settings for only GPS sensor and the same with KalmanGPSsevice and the predicted results was almost the same then regular filter. Huawei pro 20 lite.

Вопрос по интеграции сервиса

Спасибо за Ваш труд! Очень интересный проект, но, честно говоря, я так и не понял метода интеграции в свое приложение. Можно совсем коротенький пример для пустого проекта - только интеграция сервиса и получение откорректированных координат (без MVP, плиз).
Заранее премного благодарен.

#21 (comment)

Library usage

Hi! I'm trying to make an android application that should rely on high accuracy GPS data, but the default GPS raw data have a lot of noise in them, so after a bit of researching I discovered that I could use the phone's sensors together with the kalman filter in order to filter out the noise! And then I stumbled upon your library! I'm a bit of a novice when it comes to android development and I'm having a hard time trying to understand how to use the tools that you provided! I've looked into your example application but I still couldn't figure out how to use it. For my example I don't really need to display the position on a map, but I need to translate the GPS coordinates into an imaginary grid. Now my question is, how do I transform the sensors data and the GPS data into inputs for a kalman filter? (I believe you're already doing, but I can't understand how). And if I can convert them into proper inputs could I only use your KalmanFilter.java class?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.