piątek, 2 listopada 2012

Linear programming optimal & cheap diet

Assuming we are having a list of 5 example products with it's nutrition facts, price and limitations of quantity we can eat:

name quantity protein carb fat price min max
rice \[p_1\] 100g 8.1g 80g 1g 0.5 2 4
buckwheat groats \[p_2\] 100g 12g 75g 2.7g 3.0 0 -
red beans \[p_3\] 30g 6.9g 18g 0.3g 0.36  0 3
mackerel \[p_4\] 100g 19g 0g 14g 6.15  0 1
fillet chicken \[p_5\] 100g 21g 0g 3.7g 1.6 2 -

Due to a specific diet we want to consume at least 190g of proteins and 280g carbs. Fat doesn't matter in this case. We also want to do it as cheap as possible.

Linear programming

First, we have to specify our objective function.

We are looking for the cheapest combination of all products, therefore we have to add their quantity multiplied by price together and minimalize it.

\[f = 0.5p_1+3p_2+0.36p_3+6.15p_4+1.6p_5 \to min\]
We also want to ensure that out target is included (proteins and carbs):
First row represents proteins in each product, second carbs, third fat.
 \begin{cases} 8.1p_{p_1} + 12p_{p_2} + 6.9p_{p_3} + 19p_{p_4}+ 21p_{p_5}\geqslant 190 \\ 80p_{c_1} + 75p_{c_2} + 18p_{c_3} + 0p_{c_4}+ 0p_{c_5} \geqslant 280 \\ 1p_{f_1} + 2.7p_{f_2} + 0.3p_{f_3} + 14p_{f_4}+ 3.7p_{f_5} \geqslant 0 \end{cases}
To make use of this equations we have to replace the greater than-equal siqn with less than-equal (multiply both sides by -1):

\begin{cases}  -8.1p_{p_1} - 12p_{p_2} - 6.9p_{p_3} - 19p_{p_4}- 21p_{p_5}\leqslant -190 \\ -80p_{c_1} - 75p_{c_2} - 18p_{c_3} - 0p_{c_4}- 0p_{c_5} \leqslant -280 \\ -1p_{f_1} - 2.7p_{f_2} - 0.3p_{f_3} - 14p_{f_4}- 3.7p_{f_5} \leqslant 0 \end{cases}

Remeber about min/max limitations per each product:

\begin{cases} 2 \leqslant p_1 \leqslant 4\\0 \leqslant p_2 \leqslant \infty \\0 \leqslant p_3 \leqslant 3 \\0 \leqslant p_4 \leqslant 1 \\2 \leqslant p_5 \leqslant \infty\end{cases}

Solve it

We will use Matlab's built-in function for solving such problems - linprog().
Will will have to provide arguments such as:

  • linear objective function vector (f)
  • matrix for linear inequality constraints (A)
  • vector for linear inequality constraints (b)
  • vector of lower bounds (lb)
  • vector of upper bounds (ub)

Based on the equations above:

 \[A = \begin{bmatrix} -8.1 & -12 & -6.9 & -19 & -21 \\ -80 & -75 & -18 & 0 & 0 \\-1 & -2.7 & -0.3 & -14 & -3.7 \end{bmatrix} b = \begin{bmatrix} -190 \\ -280 \\0 \end{bmatrix}\]

\[f = \begin{bmatrix} 0.5 \\ 3 \\0.36 \\ 6.15 \\1.6 \end{bmatrix} lb = \begin{bmatrix} 2 \\ 0 \\0 \\ 0 \\2 \end{bmatrix} ub = \begin{bmatrix} 4 \\ \infty \\3 \\ 1 \\\infty \end{bmatrix}\]

Finally - Matlab script:

f = [0.5 3 0.36 6.15 1.6]';
A = [-8.1   -12     -6.9    -19     -21;
     -80    -75     -18     0       0;
     -1     -2.7    -0.3    -14     -3.7];
b = [-190 -280 0]';
lb = [2 0 0 0 2]';
ub = [4 inf 3 1 inf]';

[x, fval] = linprog(f,A,b,[],[],lb,ub);

products_quantities = x
total_price = fval
nutritions = -A*x

And produced outcome:

products_quantities =

    4.0000
    0.0000
    3.0000
    0.0000
    6.5190

total_price =

   13.5105

nutritions =

  190.0000
  374.0000
   29.0205

That means that the most optimal option is to consume 400g of rice, 90g of beans and 650g of fillet chicken. We will pay about 13.5 for this meal and it will provide us 190g of proteins, 374g carbs and 29g of fat.

wtorek, 30 października 2012

Changing class during runtime in Java

Java class is consisting of  three elements:

package + class name + class loader instance

Using the same class loader to load the same class twice won't succeed.

Possible solution:
1. Write the interface for reloadable class (MyReloadableClass.interface)
2. Write the class that implements that interface (Changable.java)
3. Extend the default class loader class (MyClassLoader.java)
4. Write the method to verify the results (Runtime.java)

My implementation of class loader still needs some time to work on (hardcoded path, and class name), but it is proving that the code works fine.

com.interfaces.MyReloadableClass.interface
package com.interfaces;

public interface MyReloadableClass {
    public String getString();
}
com.oop.Changable.java
package com.oop;

import com.interfaces.MyReloadableClass;

public class Changable implements MyReloadableClass{
    public String getString() {
        return "test1";
    }
}
com.classLoaders.MyClassLoader
package com.classLoaders;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public class MyClassLoader extends ClassLoader {
    public MyClassLoader (ClassLoader parent) {
        super(parent);
    }

    public Class loadClass(String name) throws ClassNotFoundException {
        if (!"com.oop.Changable".equals(name))
            return super.loadClass(name);

        try {
            String url = "file:/home/khozzy/IdeaProjects/ReflectionProject/out/production/ReflectionProject/com/oop/Changable.class";
            URL myURL = new URL(url);
            URLConnection connection = myURL.openConnection();
            InputStream input = connection.getInputStream();
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            int data = input.read();

            while (data != -1) {
                buffer.write(data);
                data = input.read();
            }

            input.close();

            byte[] classData = buffer.toByteArray();

            return defineClass("com.oop.Changable",classData,0, classData.length);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
com.run.Runtime.java
package com.run;

import com.classLoaders.MyClassLoader;
import com.interfaces.MyReloadableClass;
import java.lang.reflect.InvocationTargetException;
import java.util.Scanner;

public class Runtime {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        MyReloadableClass changableObj;

        ClassLoader parentClassLoader = MyClassLoader.class.getClassLoader();

        try {
            changableObj = (MyReloadableClass) getReloadedObject(parentClassLoader,"com.oop.Changable");
            System.out.println(changableObj.getString());

            System.out.println("Change and recompile source file, than press enter...");
            scanner.nextLine();

            changableObj = (MyReloadableClass) getReloadedObject(parentClassLoader,"com.oop.Changable");
            System.out.println(changableObj.getString());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static Object getReloadedObject(ClassLoader parentClassLoader, String name) throws
            ClassNotFoundException,
            NoSuchMethodException,
            InvocationTargetException,
            IllegalAccessException,
            InstantiationException {

        return new MyClassLoader(parentClassLoader).loadClass(name).getConstructor().newInstance();
    }
}
Output:
test1
Change and recompile source file, than press enter...

(do some changes in Changes.java, recompile it than hit enter)
test2

MongoDB development replication-set how-to


I will describe how to configure and run a MongoDB (v2.0.6) replication set consisting of 3 nodes on localhost machine. For more informations (architecture, voting, etc.) please refer to http://www.mongodb.org/display/DOCS/Replica+Sets


1. Create necessary directories for each node

sudo mkdir -p /srv/mongodb/rs0-0
sudo mkdir -p /srv/mongodb/rs0-1
sudo mkdir -p /srv/mongodb/rs0-2


2. Create configuration files for each node

sudo touch /srv/mongodb/rs0-0/node0.conf
sudo touch /srv/mongodb/rs0-1/node1.conf
sudo touch /srv/mongodb/rs0-2/node2.conf


3. Edit each configuration file respectively:


3.1 node0.conf
# mongo.node0.conf
replSet=r0
logpath=node0.log
port = 27017
logappend=true
dbpath=/srv/mongodb/rs0-0
fork = true
rest = true

3.2 node1.conf
# mongo.node1.conf
replSet=r0
logpath=node1.log
port = 27018
logappend=true
dbpath=/srv/mongodb/rs0-1
fork = true
rest = true

3.3 node2.conf
# mongo.node2.conf
replSet=r0
logpath=node2.log
port = 27019
logappend=true
dbpath=/srv/mongodb/rs0-2
fork = true
rest = true

We are creating 3 nodes, each of them works on different port (27017, 27018, 27019), in the same replication set (r0), as a process (fork) with enabled logging and rest interface.


4. Create configuration for replication set

When initalizing a replication set all machines need to know about each others. I would create a text file in json style in main directory and later on copy it's contents to mongo console.

sudo touch /srv/mongodb/config

config = {_id: "r0", 
        members:[
                {_id: 0, host: '127.0.0.1:27017'},
                {_id: 1, host: '127.0.0.1:27018'},
                {_id: 2, host: '127.0.0.1:27019', priority: 0, slaveDelay: 60},
                ]
};

We are creating a new set (named r0) with an array of members. Notice that machine with id 2 works with delay (each operation will be executed with 60 seconds delay) therefore it cannot be elected as primary (priority to zero, necessary condition).


5. Run all nodes

Open 4 terminal windows. First three will represent nodes, the last one will be a mongo client used for establishing connections.

Terminals 1-3 (in directory /srv/mongodb/rs0-x):

sudo mongod -f node[x].conf
tail -f node[x].log

(where [x] stands for node number)


6. Connect to any node and initialize a replication set

In the last terminal type:

mongo localhost:27018 (port could be 27017 or 27019, it doesn't matter right now)

Copy and paste the contents of /srv/mongodb/config file formerly created - it will now become a json-style variable.

Then in console type:

> rs.initiate(config);

As an output you ought see:

{
"info" : "Config now saved locally.  Should come online in about a minute.",
"ok" : 1
}

From now, nodes started communicating to each other. You can see current state of the set by typing:

> rs.status()

{
"set" : "r0",
"date" : ISODate("2012-10-30T15:30:20Z"),
"myState" : 1,
"members" : [
{
"_id" : 0,
"name" : "127.0.0.1:27017",
"health" : 1,
"state" : 2,
"stateStr" : "SECONDARY",
"uptime" : 109,
"optime" : {
"t" : 1351610907000,
"i" : 1
},
"optimeDate" : ISODate("2012-10-30T15:28:27Z"),
"lastHeartbeat" : ISODate("2012-10-30T15:30:19Z"),
"pingMs" : 0
},
{
"_id" : 1,
"name" : "127.0.0.1:27018",
"health" : 1,
"state" : 1,
"stateStr" : "PRIMARY",
"optime" : {
"t" : 1351610907000,
"i" : 1
},
"optimeDate" : ISODate("2012-10-30T15:28:27Z"),
"self" : true
},
{
"_id" : 2,
"name" : "127.0.0.1:27019",
"health" : 1,
"state" : 2,
"stateStr" : "SECONDARY",
"uptime" : 111,
"optime" : {
"t" : 1351610907000,
"i" : 1
},
"optimeDate" : ISODate("2012-10-30T15:28:27Z"),
"lastHeartbeat" : ISODate("2012-10-30T15:30:19Z"),
"pingMs" : 0
}
],
"ok" : 1
}

We can see that all machines are up and in good condition. Node with id was chosen as a PRIMARY node (write/read permissions), while the others are in SECONDARY state.


7. Extras

7.1 Experiments
Experiment how nodes behave in certain situations:
- insert data into primary node, reconnect to other machine and check if it is still available
- insert data on secondary machine (tip. use slaveOk function) and check if it is available to other nodes
- break one node (ie. a safe way to disconnect slave node is to connect to that node and type

use admin
db.shutdownServer()

then reconnect to your primary node, load some data, after a while bring broken node back to live and try to observe the process of automatic recovery (rs.status())
- insert a large set of data, disconnect one node, ensure an index on some field (might take time), reconnect this node as a primary, than perform recovery

7.2 Web status
You can check current status of your set using web browser. Just type http://localhost:28017/_replSet

7.3 Production
Remeber that this configuration is for learning puroposes only. When using it on production always assure that each node is on different machine (or in cloud)

poniedziałek, 8 października 2012

How to change private variable in Java

Picture simple class

src/com/oop/Person.java
package com.oop;

public class Person {
    private String name;
    private String phone;

    public Person(String name, String phone) {
        this.name = name;
        this.phone = phone;
    }

    public String getName() {
        return name;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }
}
There are two private fields - name and phone. Name can be only set using constructor. We cannot modify the private variable in classic way. This can be done using reflection.

src/com/run/Run.java
package com.run;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class Run {
    public static void main(String[] args) {
        try {
            Class c1 = Class.forName("com.oop.Person");
            Object p1 = c1.getConstructor(String.class, String.class).newInstance("John", "3242342");
            Method m1 = c1.getDeclaredMethod("getName");

            Object result = m1.invoke(p1);
            System.out.println(result);

            Field nameField = c1.getDeclaredField("name");
            nameField.setAccessible(true);
            nameField.set(p1,"Derrek");

            result = m1.invoke(p1);
            System.out.println(result);

        } catch (Exception e) {
            System.out.println("Exception: " + e.toString());
        }
    }
}
Using getDeclaredField instead getField let us access private and protected variables. Setting accessible flag allows us to modify it. Finally the output looks like:
John
Derrek

piątek, 20 lipca 2012

MyISAM, InnoDB - general differences


InnoDB is the default storage engine used in MySQL server since 5.5 release.

MyISAM:
+ faster execution of SELECT statements (according to system configuration)
+ easier creation of backup
- locks on table level (write only - except SELECTs)
- buffering only indexes (not stored in memory)

InnoDB:
+ supports transactions
+ supports foreign keys
+ supports ACID (atomicity, consistency, isolation, durability)
+ still being developed
+ locks on rows level
+ good recovery after crash
- slightly worst performance


poniedziałek, 16 lipca 2012

Kinect Head Tracking TV Prototype

Dynamically rendering 3D model using the position of users body using Microsoft Kinect.

Microsoft Kinect is a best selling motion sensor input device produced for Xbox 360 console. 

It was designed to replace traditional pads with players body. To accomplish this, it uses one VGA camera, infrared emitter and receiver, and a set of 4 microphones. The IR receiver collects data in 300 x 200px resolution, and than interpole it to VGA resolution (640 x 480px). We are still able to detect about 48 parts of human body with precision of a couple millimeters.
Using special power supply USB adapter it is possible to connect sensor to PC computer (there is also a version dedicated for this, with different lens). 

Microsoft released a special SDK for developers for non-commercial use. The latest version can be downloaded from here .

Using solutions like:
  • C# and WPF
  • Kinect API 0.9 Beta2
  • Autodesk 3DS Max 2010
  • Viewer3 3D (conversion to XAML)
We are able to create something that works like this:


Model is rendered using special projection matrix:

M = 1 0 x x * znear
0 1 y y * znear
0 0 1 0
0 0 0 1

Where z stands for near pane clipping distance (in this case - screen), and x,y for head position.

This simple example of non standard usage of such a sensor pictures a great variety of other possible deployment of this device which is limited only by imagination.

Source soon available.