JetCracker

Life-time learner's blog

Category Archives: Programming

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! 🙂

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.

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 !

[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

JSF Helper Class

When creating web-sites with JSF you often use the same patterns of code. Here are the examples:

// add faces message to Faces Context
FacesContext ctx = FacesContext.getCurrentInstance();
ctx.addMessage(null, new FacesMessage(FacesMessage.FacesMesssage.SEVERITY_INFO,
                                     "Login successful.", "Welcome! You are now signed in."));
// redirect
FacesContext ctx = FacesContext.getCurrentInstance();
NavigationHandler handler = ctx.getApplication().getNavigationHandler();
handler.handleNavigation(ctx, null, "home");
// obtain http session
FacesContext ctx = FacesContext.getCurrentInstance();
HttpServletRequest request = (HttpServletRequest) ctx.getExternalContext().getRequest();
HttpSession session = (HttpSession) request.getSession(true);

This leads to repeating the code and also makes it more difficult to write the tests to the code.
I think it is a good idea to create a helper-class which will do all these operations with faces context under the hood and provide very simple and useful API. Read more of this post

Check out “Polar H7 HRM for Motorola”

https://play.google.com/store/apps/details?id=info.danshin.android.sandbox this link is deprecated (see updated link at the end of the article).

If you are the owner of Polar H7 heart rate monitor and have got Bluetooth LE enabled phone from Motorola, check out my new app.

A new and fully functional version of app for heart rate variability analysis can be found here: https://play.google.com/store/apps/details?id=com.cardiomood.android

See also my article about the app.

[Java Web] [QapTcha] How to add captcha to JSF page

If you want to have prevent spam in your website, you probably need to use captcha.

CAPTCHA (play /ˈkæp.tʃə/) is a type of challenge-response test used in computing as an attempt to ensure that the response is generated by a human being. The process usually involves a computer asking a user to complete a simple test which the computer is able to grade. (Wikipedia)

Early CAPTCHAs such as these, generated by the...

You can see the examples of captchas on the pictures. Captcha is intended to protect the web site from spam, and it helps to avoid “unwanted” registrations, block robots. But it can also deter some “proper” users. As for me, I hate recognizing captchas!

What we need is a simple and user-friendly mechanism to detect robot. Fortunately there are plenty of different solutions for captchas on the internet!

Take a look at QapTcha – a simple, easy-to-use and intuitive captcha system. It needs human action instead of to read a hard text and it is a very lightweight jQuery plugin.

QapTcha Demo Screenshot

All you need is to drag the button from one side to another, and that makes it perfect for mobile devices.

Here I will show you an example of how we can embed this captcha into JSF web-application.

Read more of this post

Reshaka.Ru

Reshaka.Ru logoStudent life is very tough and complicated, especially if you have to combine studying and work.You have to solve a heap of problems, hand in assignments on time, pass a lot of exams. There are a lot of subjects on your curriculum and there is no way you will handle it…

Not since the Reshaka.Ru came out!

Meet our new project: Reshaka.Ru is a new online service for students to solve problems, do your homework, create a project, online help in exams.

We offer reliable guarantees, extremely low prices, friendly and automated interface. Our team is ready to help 24/7. Order a solution to your problem now – and you will never regret!

Official Website:                         http://reshaka.ru
Official Group at vk.com:         http://vk.com/reshaka
Official vk.com app:                  http://vk.com/app2965828

Reshaka.Ru - Order Solution to Your Problem

Order Solution to Your Problem

Reshaka.Ru - Online Help in the Exam

Online Help in the Exam

View russian version.

P.S. The article is aimed at Russian audience. If you are not in Russia, please ignore it.