JetCracker

Life-time learner's blog

Effects of Alcohol Consumption on HRV and Sleep

HRVtraining

Excessive alcohol consumption is not uncommon among high school, collegiate and professional athletes. This typically occurs after competitions during the season and likely with greater frequency throughout the offseason. Today I’d like to share what I’ve learned after reading through the available research pertaining to alcohol and HRV in healthy individuals. In addition I will post up some ithlete data I’ve collected showing the effects that excessive drinking has on HRV.

Bau and colleagues (2011) investigated the effects of 60g of ethanol ingestion on HRV in young men. HRV was measured before and during the following 17 hours after ingestion. Compared to the control group, the ethanol group saw a decrease in all time domain indices of HRV that persisted for 10 hours.

Koskinen et al (1994) tested the effects of ethanol consumption (1g/kg) on HRV in healthy young males (n=12). HRV was measured prior to ethanol ingestion and…

View original post 448 more words

Constrained Cubic Spline Interpolation in Java

Representation of numeric data is a very common problem. On PC we usually use different data visualisation software from Microsoft Excel or OpenOffice Calc to more advanced utilities for charting, such as QtPlot or Origin. These apps are designed for processing of data and you can easily draw a printable scatter plot or a pie chart. But what if you need to draw a plot in your own application?

Example of charts in CardioMood

There are plenty of libraries that can draw different kinds of charts. To draw charts in the web, you might use Google Charts API, or jQuery Flot for example. In my Android app, I use GraphView and ShinobiCharts.

Spline overshoot example

Line charts look nice when they are smooth. The most popular way to make your chart look smooth is to apply a cubic spline interpolation. This type of interpolation is very common and you have it already implemented in many open source mathematic libraries. However a simple cubic spline has a few flaws.

The result function is smooth (it is actually very smooth – twice continuously differentiable), but it tends to overshoot, especially in places where you don’t expect. This is illustrated in the picture above. When we draw a line chart, we usually have some knowledge about the process we are trying to visualise. For instance, the resulting function must be monotonic, or the function value should never be negative. If this information is critical, we must use more advanced interpolation algorithms.

If the function is monotonic, in Android you can just use MonotoneCubicSpline:

import android.util.Spline;

float x[] = ...
float y[[] = ...
Spline f = Spline.createMonotoneCubicSpline(x, y);

// this will evaluate y0 = f(x0)
float y0 = f.interpolate(x0);

If we want to avoid overshoot for an arbitrary function, we should find some other interpolation algorithm. One of the methods is called Constrained Cubic Spline Interpolation. It was proposed by CJC Kruger in his article: http://www.korf.co.uk/spline.pdf

The algorithms is based on a classic cubic spline algorithm. The key step in it is the calculation of the slope (first derivative) at each point. Intuitively, the slope will be between the slopes of the adjacent straight lines (can be a mean value of the two slopes), but it also should approach zero if the slope of either line approaches zero.

Unfortunately, I couldn’t find an implementation of the algorithm in Java. That’s why I decided to implement Constrained Spline for my project.

I use Apache Commons Math library. To make the interpolation compatible with my project, I’ve overridden UnivariateInterpolator class. Here is a full code of my implementation.

import org.apache.commons.math3.analysis.interpolation.UnivariateInterpolator;
import org.apache.commons.math3.analysis.polynomials.PolynomialFunction;
import org.apache.commons.math3.analysis.polynomials.PolynomialSplineFunction;
import org.apache.commons.math3.exception.DimensionMismatchException;
import org.apache.commons.math3.exception.NonMonotonicSequenceException;
import org.apache.commons.math3.exception.NumberIsTooSmallException;
import org.apache.commons.math3.exception.util.LocalizedFormats;
import org.apache.commons.math3.util.MathArrays;

/**
 * Constrained Spline Interpolation algorithm (CJC Kruger).
 * Source: http://www.korf.co.uk/spline.pdf
 *
 * Created by Anton Danshin on 24/12/14.
 */
public class ConstrainedSplineInterpolator implements UnivariateInterpolator {

    @Override
    public PolynomialSplineFunction interpolate(double x[], double y[])
            throws DimensionMismatchException, NumberIsTooSmallException, NonMonotonicSequenceException
    {
        if (x.length != y.length) {
            throw new DimensionMismatchException(x.length, y.length);
        }

        if (x.length < 3) {
            throw new NumberIsTooSmallException(LocalizedFormats.NUMBER_OF_POINTS,
                    x.length, 3, true);
        }

        // Number of intervals.  The number of data points is n + 1.
        final int n = x.length - 1;

        MathArrays.checkOrder(x);

        // Differences between knot points
        final double dx[] = new double[n];
        final double dy[] = new double[n];
        for (int i = 0; i < n; i++) {
            dx[i] = x[i + 1] - x[i];
            dy[i] = y[i + 1] - y[i];
        }

        final double f1[] = new double[n+1]; // F'(x[i])
        for (int i=1; i<n; i++) {
            double slope = dy[i-1]*dy[i];
            if (slope > 0d) {
                // doesn't change sign
                f1[i] = 2d / (dx[i]/dy[i] + dx[i-1]/dy[i-1]);
            } else if (slope <= 0d) {
                // changes sign
                f1[i] = 0d;
            }
        }
        f1[0] = 3d * dy[0] / (2d * (dx[0])) - f1[1]/2d;
        f1[n] = 3d * dy[n-1] / (2d * (dx[n-1])) - f1[n-1]/2d;

        // cubic spline coefficients -- a contains constants, b is linear, c quadratic, d is cubic
        final double a[] = new double[n+1];
        final double b[] = new double[n+1];
        final double c[] = new double[n+1];
        final double d[] = new double[n+1];

        for (int i = 1; i <= n; i++) {
            final double f2a = - 2d * (f1[i] + 2 * f1[i-1]) / dx[i-1] + 6d * dy[i-1] / (dx[i-1]*dx[i-1]);
            final double f2b = 2d * (2d * f1[i] + f1[i-1]) / dx[i-1] - 6d * dy[i-1] / (dx[i-1]*dx[i-1]);
            d[i] = (f2b - f2a) / (6d * dx[i-1]);
            c[i] = (x[i] * f2a - x[i-1] * f2b) / (2d * dx[i-1]);
            b[i] = (dy[i-1] -
                    c[i] * (x[i]*x[i] - x[i-1]*x[i-1]) -
                    d[i] * (x[i]*x[i]*x[i] - x[i-1]*x[i-1]*x[i-1])
            ) / dx[i-1];
            a[i] = y[i-1] - b[i]*x[i-1] - c[i]*x[i-1]*x[i-1] - d[i]*x[i-1]*x[i-1]*x[i-1];
        }

        final PolynomialFunction polynomials[] = new PolynomialFunction[n];
        final double coefficients[] = new double[4];
        for (int i = 1; i <= n; i++) {
            coefficients[0] = a[i];
            coefficients[1] = b[i];
            coefficients[2] = c[i];
            coefficients[3] = d[i];
            final double x0 = x[i-1];
            polynomials[i-1] = new PolynomialFunction(coefficients) {
                @Override
                public double value(double x) {
                    // bypass the standard Apache Commons behavior
                    return super.value(x + x0);
                }
            };
        }

        return new PolynomialSplineFunction(x, polynomials);
    }

} 

Feel free to use this in your own code!🙂

HAXM not working on Mac OS X 10.10 Yosemite

By default Android emulator is extremely slow. It takes 5 minutes to start the emulator!

To make it faster there are two approaches:

  1. If your machine supports Intel VT-x technology, you can install special HAXM extension, so that the emulator will make use of all the power your computer has.
  2. If your computer doesn’t support virtualisation, you can still significantly improve the boot time of the emulator by configuring it to save its state. This will make the emulator start faster, but the UI will still be slow, and it will take a bit longer for the emulator to close.

There is a pretty detailed Stackoverflow answer regarding HAXM and Android emulator performance.

Unfortunately, my old laptop didn’t support Intel virtualisation technology, so I didn’t even consider working with emulator. Instead, I always used a physical android device to test my apps.

When I started the emulator on Mac, I hoped it would run much faster (with SSD and Intel Core i7 on board). But no – the emulator was still very slow. This brought me to Stackoverflow, where they discussed how to enhance the speed of Android emulator by installing HAXM.

So, I tried to make the emulator on freshly installed Mac OS X 10.0 Yosemite run faster. I followed the instructions provided in the article, but at the end of installation, I got error message, saying that my laptop supports virtualisation, but VT-x is disabled.

According to Apple official specs, all latest macs that are running on Intel CPUs, have VT-x feature enabled by default. It might seen as disabled by the HAXM Installation Manager for two reasons:

As I didn’t have any other emulators or virtual machines running, I decided to find a way to make it work. And after some googling, I finally found a solution. According to the blog post I found, there was an issue with an incorrectly signed kernel extension on Intel’s part. I believe Intel will fix it soon, but for now as a workaround, we can use the following command:

sudo nvram boot-args="kext-dev-mode=1"

This makes kexts to run in dev mode and disables all signing checks. Changes will take affect after system restart.

Speedometer Gauge with Needle for Android

I am working very hard on my CardioMood app for Android.

As described in one of my previous posts, CardioMood is a health monitoring social service with a stress monitor app. It measures your stress level according to heart rate variability. It also shows a bunch of other parameters, which are represented as different kinds of charts.

Stress Index is a quantitative characteristic of your stress. Normally, the value of Stress Index varies from 50 to 150. The SI value outside of the range could be caused by a number of factors, such as physical or emotional stress, diseases (including heart diseases), and low quality of data obtained from heart rate sensor.

In CardioMood Stress Monitor app, we need to visually represent a calculated value of Stress Index – and that is another problem. I decided to use a speedometer-like gauge.

A simple way: WebView

In our measurement report screen used WebView to visually represent the result.

Android WebView supports almost all HTML and javascript features, which enables developers to render anything and use various javascript libraries already available on the net.

So, WebView gives you an easiest way to add Speedometer gauge to your android app. In our case we used a solution from Geek’s Retreat.

Their implementation is purely javascript. It has a certain number of limitations. For example, you have to specify the exact width and height of the canvas before rendering.

We had hard time with sizing and layouting components in WebView. Soon, we realized that WebView is not reliable – it’s better to use native controls than spend days on fixing issues and supporting diverse screen densities and sizes in HTML.

Hard way: Implementing Android custom view

I decided to take a bull by the horns and convinced our team to stop using WebView. After two days of working, I finally created SpeedometerView – a simple speedometer with needle gauge for Android. It looks similar to it’s javascript brother and has the same features.

CardioMood SpeedometerView in action

Supported features:

  • Major and minor tick marks
  • Custom labels
  • Colored value ranges
  • Animation of arrow (requires Android API level 11+)

Download

Check out a GitHub repo to see source code, release binary and usage example.

UPD: The component was moved to AndroidWidgets library.

GitHub: https://github.com/ntoskrnl/AndroidWidgets

Screenshot of CardioMood with SpeedometerView

Feel free to comment, request features or report bugs.

EnglishSmacks – Real life English words and phrases

English Smacks logoThe-English-Patient.Com – a ground-breaking service for learning English – has recently released a preview of its brand new service: EnglishSmacks!

The app tests your English language skills! Just listen to the phrases and fill in the gaps typing the words missing in the transcript.

There are 5 levels of difficulty. Phrases are taken from world news (CNN, BBC), science movies, pop music etc. I am sure that you will enjoy gathering “tambourines”. Good luck!

Download EnglishSmacks from Google Play!

EnglisSmacks-sceenshotEnglishSmacks-screenshot2

Key features

  • Huge base of phrases
  • Daily updates of exercises
  • Reliable sources (CNN, BBC, movies)
  • Awesome phrases from real life situations

Feel free to download, rate and review the app!

CardioMood Stress Monitor for Android

CardioMood.ComI’d like to introduce an Android application for our CardioMood health service, which is going to revolutionize today’s health & fitness approaches.

You can evaluate your stress level and estimate health of your heart.

Download from Google Play!

ImageImage

Feel free to rate this app and leave your feedback.

Key features

  • Displaying current heart rate
  • Analyzing stress level (by heart rate variability)
  • Different visual representation of collected data with description
  • Storing all your measurements locally
  • Saving results to PNG-images or TXT-files
  • Uses Bluetooth Low Energy (Bluetooth SMART) technology

This application doesn’t use or require any network connections and can be used safely.

Limitations

  • This application is standalone and currently supports devices with Bluetooth 4.0 Low Energy (Motorola phones with Android 4.0+ and other phones with Android 4.3+).
  • The application currently supports only Polar H7 heart rate monitor (was tested and proved to be working).
  • Devices with small screens are currently not fully supported (we are working on it).

This is a demo. In the future we are going to support a much wider range of Android devices and heart rate monitors.

Stay with http://www.cardiomood.com !

TagsCool – Tag your photos online

TagsCool – Tag your photos online

http://www.TagsCool.com – Upload your photos, tag them and share!!!

You can also use it to store your school notes!

www.TagsCool.com

Demo: http://www.youtube.com/watch?v=4OC5kun9v9Y

[Java] [Vimeo] Generating a direct download link to Vimeo clip

Recently, I’ve been looking into ways of playing video streams on Android. Fortunately, with it’s VideoView you can play any video clip easily no matter where the actual file is. All you need is to provide a URL to the video file. With VideoView I managed to play the video even on my friend’s old HTC Desire S with its antient Android 2.3.5! At the end of the article you will find a link to a good article on how to play video in Android using VideoView component.

But soon I found out that I couldn’t play a youtube or vimeo video clip simply because I didn’t have a direct link to the video stream. Unfortunately, for some security reasons Vimeo.com doesn’t provide a download links. But if the video can be shown on the website, it can be downloaded. There’s always a way to do it.

On the internet, there were a lot of discussions about this and I found a solution (for PHP language) to my problem on StackOverflow. I implemented it, but a couple of days ago it suddenly stopped working. Turned out that Vimeo changed the markup of the page and old solutions became not applicable anymore.

I did some investigation into the new Vimeo.com markup and came up with the following solution. Read more of this post

[Java] Worker thread – thread-safe processing items one by one

Often we face the problem of online collecting and handling some data, abtained from various external systems and devices. In some cases it is more convenient to execute the processing code in a different thread. Here is how I usually solve this problem.

Assume the data are divided into chunks which are obtained one by one. The following class contains all necessary logic to process these chunks (*** updated according to the improvements suggested by Valeriy Ovchinnikov).

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

public abstract class WorkerThread<T> extends Thread {

    public static final long TIMEOUT = 200;
    private final BlockingQueue<T> queue = new LinkedBlockingQueue();

    @Override
    public void run() {
        while (!isInterrupted()) {
            try {
                T item = queue.poll(TIMEOUT, TimeUnit.MILLISECONDS);
                if (!isInterrupted() && item != null) {
                    processItem(item);
                }
            } catch (InterruptedException ex) {
                Thread.currentThread().interrupt();
            }
        }
    }

    public void put(T e) {
        queue.add(e);
    }

    public abstract void processItem(T item);
}

All you need is to extend this class and implement its abstract method processItem(T item). The example of it follows.

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

public abstract class WorkerThread extends Thread {

    public static final long TIMEOUT = 200;
    private final BlockingQueue queue = new LinkedBlockingQueue();

    @Override
    public void run() {
        while (!isInterrupted()) {
            try {
                T item = queue.poll(TIMEOUT, TimeUnit.MILLISECONDS);
                if (!isInterrupted() && item != null) {
                    processItem(item);
                }
            } catch (InterruptedException ex) {
                Thread.currentThread().interrupt();
            }
        }
    }

    public void put(T e) {
        queue.add(e);
    }

    public abstract void processItem(T item);
}

To use this class you need to create and start the thread and call put() whenever you want to process next data item.

HRDBWorker hrDBWorker = new HRDBWorker();
hrDBWorker.start();
...
htDBWorker.put(nextItem);

Hopefully, this is the useful piece of code. You are welcome to comment.

Java REST client for Android

In one of my previous posts I told you that I started learning how to code for Android, and created my first Android app. But most of mobile apps are useless when they do not exploit the advantages of the Internet. That is why in order to create a good application you should know how to use the power of the Internet in your app.

There are different ways of how your application is interacting with the Internet and its resources, for instance an app can download data, connect to remote databases, but the most popular way of interaction is RESTful services  (in the development of mobile apps). It just works more effectively than SOAP when the bandwidth is limited.

In this article I’ll show briefly how to create a client for a RESTful service in Android (this should also work in any device supporting Java). Read more of this post