Sunday, April 26, 2015

OFF: how Google makes Android worse

Some days ago I got OTA update with Android 5.1. This version does probably improve something, but it apparently impairs other things as well. And because it's related to the system carousel - the list of running applications (on the so called "recents" screen) - which has bad design from the very beginning of Android 5, I couldn't help but writing about this miserable part of UI.

First, I must say that the carousel is constantly changing from one Android version to another between horizontal and vertical layout, as though Google's developers are uncertain themselves which variant is appropriate. The carousel is used intensively, so even a little flaw in its design brings big problems. I'm currently speaking about standard Android in general, and standard Android 5 in particular. Other customized firmware may be free of the issues I'm going to describe.

In Android 5, the carousel is always vertical on my pad. Well, it could be appropriate for portrait screen orientation, but the carousel remains vertical even in landscape mode. When you try to flip through the apps from bottom to top, you will constantly activate the central button of the navigation bar, floating in foreground (over the carousel!), especially because the button has an enlarged sweetspot, because it's Google button (it invokes "Google App" including quicksearchbox and other stuff). It took me a long time to get accustomed to the new - not so convenient - practice: in order to swipe apps from bottom to top, one should swipe from center! Otherwise you'll get into the Google app.

That's how it was since Android 5.0. In Android 5.1 they introduce new strange bug in the carousel. It does not work when you tap an app in it first time. After the first tap the carousel is closed and the launcher is shown. Only if you open the carousel second time, it works as expected.

I know, this is far from the main subject of the blog, but at last it's all about Android. And I'd prefer that Android would not prevent me from working with my applications.

Monday, March 16, 2015

WiFiLine's synthetic probability algorithm revealed

As I promised, I'm posting a short explanation of the built-in "synthetic probability" location algorithm. To start with it let us consider how WiFi data looks like. When you scan a building you get a list of geographical points with WiFi measurements, each of them contains signals from several hotspots, and every hotspot signal is normally detected many times demonstrating varying levels - so called RSSI (Received Signal Strength Indication). All this data is stored in the map, and can be viewed - just switch to the "Scan and Edit" mode, open the list of points and expand any of them - you'll see the names of hotspots detected in this point. Tap a hotspot to open a dialog presenting this spot's RSSI distribution.

Usually it's bumpy, but the more scans you perform in a point the more smooth distribution you get. According to the Central Limit Theorem the distribution tends to be Normal (Gaussian), so one can estimate its mean and standard deviation. This is where the word "synthetic" in the algorithm name comes from: it implies that we can build a synthetic (near to real, yet artificial) probability distribution (mass) function from acquired WiFi data.

Of course, this is just a probability of getting specific signal level of a hotspot S in a point X. We need to combine all such probabilities somehow in order to calculate current user location. And here is the Bayes theorem comes in handy.

P(A | B) * P(B) = P(B | A) * P(A), where

  • P(A) and P(B) are the probabilities (priors) of A and B independent of each other;
  • P(A | B) is the conditional probability of A given that B is true;
  • P(B | A) is the conditional probability of B given that A is true;
Now let us add some suffixes to bring it into our context:

P(Asi | Bxj) * P(Bxj) = P(Bxj | Asi) * P(Asi), where

suffixes 'si' and 'xj' stand for i-th hotspot and j-th point respectively, so:

  • P(Asi) is the prior probability of i-th hotspot;
  • P(Asi | Bxj) is the conditional probability of observing i-th hotspot in j-th point;
  • P(Bxj) is the prior probability of j-th point;
  • P(Bxj | Asi) is the conditional probability of being in j-th point provided that i-th hotspot signal is detected;
Apparently, it's the last probability which we are after:

P(Bxj | Asi) = P(Asi | Bxj) * P(Bxj) / P(Asi)

In the right side of the equation, P(Asi) can be estimated as a percentage of points where the hotspot Si was detected. P(Bxj) is initially 1/N for every point, where N is the total number of points, but later it can be refined by applying our knowledge about current user location and reducing N to a reasonable neighbourhood. At last P(Asi | Bxj) is the probability obtained from the synthesized probability distribution of signals described above.

Having P(Bxj | Asi) for different i-s in every point j, we should combine them by hotspots (by i) in order to get the total probability of point Xj. According to the formula of mutually non-exclusive events:

P(Xj) = P(Σi(Bxj | Asi)) = 1 - Πi(1 - P(Bxj | Asi))

The point with largest value (or an average of K points with largerst values) is most likely the current location of the user.

This is a simplified description of the "synthetic probability" algorithm. It does not cover many nuances such as signal level calibration and in-motion scanning but gives you an idea of how WiFiLine works behind the scenes.

Friday, March 6, 2015

New WiFiLine version has been released

New version of WiFiLine - 1.1.3 - has been just released. The main changes are:

  • debug marks with current user position(s) detected by all built-in algorithms are now optional and disabled by default; in order to enable the marks, one should enter "debug:on" in the processing command line (described some time ago in the blog); "debug:off" disables the marks;
  • the naive multiplier algorithm has been changed a bit, but it's still an experimental thing;
According to latest tests in fields, recommended methods are extended fingerprint and synthetic probability again, as they were before. Position accuracy is 10 meters. I plan to shed some light on the probabilistic method in a future. As for neural network, it requires manual finetuning of input data to get best results. For example, it could be worth removing some non-discriminative hotspots from the map.

Готовится новый выпуск WiFiLine

В разработке и тестировании находится следующая версия WiFiLine. Вот основные изменения:

  • Отладочный вывод на карту меток с результатами работы всех алгоритмов позиционирования сделан опциональным; по-умолчанию, он отключен; чтобы его включить, необходимо ввести в командной строке "debug:on";
  • слегка изменен алгоритм naive multiplier, он все еще является экспериментальным;
По итогам полевого тестирования, рекомендуемыми по-прежнему являются методы расширенного отпечатка и синтетической вероятности. Точность позиционирования - 10 метров. В одной из следующих публикаций я расскажу более подробно о вероятностном методе. Что же касается нейронной сети, то для получения с ней хороших результатов, требуется тонкая ручная подготовка исходных данных, в частности, удаление некоторых хотспотов с малоинформативными сигналами из карты.

Sunday, February 22, 2015

ОФФ: коллективное гипертекстовое литературное творчество

Не так давно я опубликовал один свой проект, никак не связанный с темой навигации, и чтобы не заводить отдельный блог по нему, решил дать краткий анонс здесь - все-таки автор один и тот же. Проект был начат много лет назад и, что называется, "лежал под сукном".

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

В отличие от систем класса wiki, единицей редактирования является не статья, а предложение (фрагмент). Выбор последовательности предложений осуществляется подсчетом их голосов (версия сообщества) или пользователем (персональная версия), а не путем долгих обсуждений каждой правки на отдельной странице.

Сам сервис расположен по адресу hyperfiction-orienteer.rhcloud.com, а более подробное описание - на отдельной странице. Но одна картинка, как известно, стоит сотни слов, поэтому вот краткая презентация:

Каковы общие тенденции рынка в этом направлении? И в печатной литературе, и в электронной форме имеется много произведений с коллективным авторством. Также в интернете выложены многочисленные гипертекстовые произведения, в которых можно менять поток чтения с помощью переходов по гиперссылкам. Интерес к подобным экспериментам находится на подъеме. Интернет, проникший во все сферы жизни, подсказывает пути развития литературы в сторону её социализации (использование социальных сетей) и проактивного отношения к сюжету. Имеются многочисленные примеры форумных ролевых игр, принцип которых заключается в пошаговом описании каждым пользователем действий своего героя в ответ на описания действий героев других пользователей. Известны случаи написания произведений в виде постов в социальных сетях, включая Твиттер. В общем, существует тенденция "интернетизации" литературных форм, что включает коллективное творчество, публичную оценку, многовариантность мнений, интерактивность.

В чем слабые места вышеназванных конкурирующих инструментов? Форумным ролевым играм мешает в развитии использование неприспособленных под их специфику форумных движков. Статическим гипертекстовым произведениям не хватает интерактивности и гибкости. Закрытые коллективы авторов не позволяют пользователям самим принимать участие в творчестве и влиять на произведение хотя бы в виде оценки фрагментов. Все элементы предлагаются разрозненно, и полноценной системы для коллективного, интерактивного, многовариантного создания произведений не существует. Ну или не существовало.

Данный проект - одно из возможных решений.

Wednesday, February 4, 2015

New map visualization feature is available in version 1.1.2

New version 1.1.2 of WiFiLine has been just released. It introduces new map visualization. In the Location mode, a map can now automatically rotate according to user's "view" direction. This makes it easier for user to take his or her bearing, but may create some difficulties in reading labels on the map.

New feature can be enabled in the context menu of the main screen. By default it's disabled, and maps are shown in the standard way: floorplan is static, and user's current bearing is indicated by a green sector inside the compass. When the feature is enabled, there is no a green sector in the compass, because user's "viewing direction" is always forward (up on the screen), and the compass shows only blue and red sectors for the North and the South.

The rotation of a map is performed around the point of user's current location. If current location is unknown (which is possible if navigation was not started, or the algorithm failed due to incomplete or irrelevant WiFi data), map remains static in its default orientation.

In other modes - Scan and Edit, Hotspot signals - the new visualization made intentionally unavailable, otherwise it would be hard for user to edit and analyze the map.

Режим отображения карты с изменяющимся азимутом

Для следующей версии WiFiLine готовится новый способ отображения карты в режиме навигации. В нем карта постоянно поворачивается в соответствии с текущим направлением "взгляда" пользователя. Это позволяет проще ориентироваться на местности, однако может затруднить чтение надписей на карте.

Режим переключается из контекстного меню главного экрана. По-умолчанию он выключен, и поведение карты аналогично прежним версиям программы, то есть отображение плана статично, а текущее направление "взгляда" пользователя обозначается подвижным зеленым сегментом в компасе. Если новый режим включен, карта будет целиком поворачиваться синхронно с поворотом пользователя на местности, а компас отображается без зеленого сегмента (только синий и красный сегменты с направлениями на север и юг), поскольку "взгляд" всегда направлен вперед (вверх экрана).

Следует отметить, что автоматический поворот карты производится относительно последнего определенного местоположения пользователя, поэтому если точка еще не найдена (например, если навигация вовсе не запускалась или определить местоположение просто не удалось), карта остается статичной.

В режиме редактирования и анализа WiFi сигналов данный способ ориентации недоступен, чтобы не осложнять пользователю работу с функциями редактирования.