niedziela, 12 stycznia 2014

Inertial behaviour estimation system

This is something I was working on lately. The guy on the movie  is wearing a arduino-powered accelometer readers (elbows, legs and torso) that collects data at 100Hz each. Machine learning approach was used to tag each frame using training data and only torso sensor. Method is very simple but it will be boosted in future.


środa, 5 września 2012

Rough Set approch for document retrieval (part 1)


Setting up an search engine it's an extremely easy task. I've seen a lot's of production level implementation built on top of Lucene or Solr with very little effort. But when  time passes and application is getting bigger and bigger search result is starting to be little bit messy. And then people came up with a lot's of ideas how to work your search result out. One of home-made most common (and very simple) solution I've seen so far is to gather keywords from search result and put them back along with original query to search engine. Actually is not that bad idea, one can find a lots of stuff around the subject in literature under the term: [query expansion].

I'm working recently in a group where [Rough Sets] theory is very popular. So let's try to put our simple idea for QE in this formalism. With every term from dataset there is a set of terms that collocate with it. Upper approximation of this set consists of terms that have first-order [collocation] higher than certain threshold. This approach is well described in [paper]. Authors derive Extended Weighting Scheme from standard TF-IDF weighting making use of this higher-order collocation feature, (U_R(d_i) is sum of sets of upper approx for all t in document d_i):


Method was orginally developed for document clustering but the weighting schemata obviously follows our simple intuition for QE and moves it to indexing time.  I've implemented this formula in python using sparse matrices. Implementation is time/space efficient but not incremental (which means you need to "see" all the documents at indexing time)


import numpy as np
from math import log 
from scipy import sparse 
import timeit

def sparse_trsm(A, fi = 10):   
    A = sparse.csc_matrix(A, dtype=float)
    E, M = [], float(A.shape[0])
    Acoo = A.tocoo(copy = False)
    A.data = np.ones(len(A.data))
    C = A.transpose().dot(A) # 0.6s, lot's of allocation
    A = A.tocsr()
    np.putmask(C.data, C.data < fi, 0)
    C.eliminate_zeros()     

    for i in xrange(A.shape[0]):
        words = A.indices[A.indptr[i]: A.indptr[i + 1]]
        if len(words) > 0:
            #you can fix C[words,:] slicing here 
            U = np.setdiff1d( C[words,:].indices, words) #1.19s
        else : 
            U = []
        E.append(U)
    # 0.00802702903748s  2.67190599442s
    f_D = A.sum(axis = 0).tolist()[0] 
    idf = [log(M / ti) for ti in f_D ]
    idfs2 = np.vectorize(lambda i: log(M/i) / (1+log(M/i))) ( f_D )
    data = tuple( (1 + log(v)) * idf[t]  for (t, v) in zip(Acoo.col, Acoo.data))
    A = sparse.coo_matrix((data, (Acoo.row, Acoo.col))).tocsr() 
    A = A.tocsr(copy = False)
    cols = [i for s in E for i in s]
    rows = [j for s in  [[i] * l for (i, l) in enumerate(map(len, E))] for j in s]
    data = []
    append = data.append

    mintfidf = [min( A.data[ A.indptr[i] : A.indptr[i + 1] ])  
                   if A.indptr[i] != A.indptr[i + 1] else 0. for i in xrange(int(M))]
    for i,j in zip(rows, cols):
        wij = mintfidf[i] * idfs2[j]
        append(wij)        
    W = sparse.coo_matrix((data,(rows,cols)), shape = (A.shape) )
    return A + W, W 

Well it seems that  python isn't that slow - indexing of 10 000 of documents from routers data set took 160sec.
But here comes bummer: number of changes depends on the size of document collection:
For first 1000 docs number of nonzero elements in output doc-term matrix if 140 times larger. It's just that: thresholding of such feature as first-order collocation is too simple. Need to came up with something else. I'm thinking about something like a "second-order TF-IDF" for ngrams will be nice over here.

Art & Science Festiwal

Recently I had the opportunity to co-ordinate an event in our dept. This was a part of [art&science festival] on our university. With bunch of students we put together some exhibitions loosely connected with human-computer-interaction. It was lot of fun! We used all of those things... you know: kinnect, wii, cameras, infrared leds, augumented reality, arduino etc. (see selected videos below). It isn't much but we were able to mount all this in just one week starting almost from scratch. 



 



During the event I met some older guy (engineer I suppose) who was amazed how fast we arranged so many stuff. Well... Today we just have better tools. Open-Source and Open-hardware just kicks ass - It's a industrial revolution. Just watch this  TED to learn more.


niedziela, 26 lutego 2012

Interactive Table

Recently, together with [andrut] we made a interactive table. The table was used for closing exhibition of an culture-educational project [dzwiękospacery].



It was made with [Processing] and a little bit of OpenCV

środa, 14 grudnia 2011

Turn off kde screen dimming

Even if you mess around with power manager policies, kde will turn off the screen if mouse was'nt moved nor key wasn't pressed. Apparently this little script prevents kde from turning screen off.



#!/bin/bash

for (( ; ; ))
do
dbus-send --print-reply --type=method_call --dest=org.freedesktop.ScreenSaver /ScreenSaver org.freedesktop.ScreenSaver.SimulateUserActivity
sleep 60
done

niedziela, 20 listopada 2011

Arduino Sonar Grid

Because of the small project that I did recently I had to build sonar grid on Arduino. The circuit was gathering data from five ultrasonic sensors LV MaxSonar EZ0 and was sending readings to computer via Firmata. I turns out that each sonar will interfere with every other so the signal you will get can be very noisy (depending it on sonar mutual locations and room layout). Something you can do (with this particular sonar) is to turn-off all others sonar in the time of reading data. So if you read data for sonar connected to pin 0 others should not send the ultrasonic wave.

Here goes modified minimal Firmata implementation to achieve this.


#include <Firmata.h>

int analogPin = 0; // counter for reading analog pins
int digitalPin = 0; //conuter for turning on/off digital pins (RX for sensors)
unsigned long currentMillis; // store the current value from millis()
unsigned long previousMillis; // for comparison with currentMillis

void setup()
{
Firmata.setFirmwareVersion(0, 2);

for (digitalPin=2;digitalPin<=7;digitalPin++){
pinMode(digitalPin, OUTPUT);
}
Firmata.begin(57600);
}

void loop()
{
while(Firmata.available())
Firmata.processInput();

currentMillis = millis();
if(currentMillis - previousMillis > 20) {
previousMillis += 20; // run this every 20ms

for(analogPin=0;analogPin<TOTAL_ANALOG_PINS;analogPin++) {
for (digitalPin=2;digitalPin<=7;digitalPin++){
if (digitalPin - 2 == analogPin) {
digitalWrite(digitalPin, HIGH);
}
else {
digitalWrite(digitalPin, LOW);
}
}
delay(40); //wait wait man!
Firmata.sendAnalog(analogPin, analogRead(analogPin));
}
}
}


Analog output (AN pin) from all sonar are connected to A0-A5 pins on Arduino (since we are reading from analog). RX pin (which controls measuring state of sonar) are connected to digital pins 2-5. As you probably see this will get way much lower signal resolution that we can get from one sonar. MaxSonar works in 49ms cycles and sends 42Hz waves at the begining of each cyle only if RX pin is HIGH or unconnected. After changing digital pins state you need to wait a while to seetle state on it and also you need to wait for the sonar to its cycle begining (40ms delay gives very smooth signal).

Of course this is easiest possible solution. Depeding on your need you can read from sonars in pairs on weave reading with differents operations.

wtorek, 17 maja 2011

VLC + p2p real time audio/video streaming

Recently I was coordinating this art event. My responsibility was to setup real-time a/v streams in five cities. Every city was streaming a/v from hd camera and also realy big projector was showing streams from other cities. We decided to go for p2p architecture and use some additional player which can randomly switch streams.

We decided to use VLC ...and first bummer: Vlc dosen't support grabbing video from firewire (or I wasn't able to find this option in UI). We are sure we don't want to put ieee 1394 as v4l device, because only way to do that is by vloopback - and this module... well it isn't quite stable.

This line was used to setup stream with transcoding it by h264.

dvgrab - -noavc -nostop | cvlc - -vvv --no-sub-autodetect-file :demux=rawdv
--sout'#transcode{vcodec=h264,vb=600,acodec=mp3,ab=56,scale=0,width=720,height=576,channels=2}:
duplicate{dst=std{access=http,mux=ts,dst=0.0.0.0:8085}}'

also stream tittle is a neat feature:

#transcode{vcodec=h264,vb=1500,scale=1,width=1024,height=576,
sfilter='marq{marquee=Toruń %Y/%m/%d%H:%M%S,position=10,size=14}',
acodec=mp3,ab=196,channels=2,samplerate=44100}:http{mux=ts,dst=:8081/}

stream merging was achieved by

cvlc url1:port url2:port ... --sout="#gather:http{mux=ts,dst=localhost:8079/}" --sout-keep


this will loopback merged stream to localhost on 8079, just open it in any player and switch streams by vlc ui. Depending on option http-cache (buffer size) switching will be little bit delayed (but this is what we wanted to achieve here). Also notice that --sout-keep will only work if stream config is identicall, so you have two option: transocde it on the client or make same setup on server.

Look also here: auto-reconnect, and someone advised me to take a look on twisted-based streaming software

niedziela, 24 kwietnia 2011

Augumented Reality Model Editor



Augemented Reality Model Editor.

Ogre3d + ARToolkitPlus + little bit of OpenCV

code available on github

sobota, 8 maja 2010

research methodology

Yesterday I was at a little party and I meet there a grad student from Philosophy. After introducing schemata and occasional small-talk we landed with conversation on something like this:

- (me) ... and what is your research methodology?
- Research... what?
- I mean what are you doing all day long at university?
- Oh... I read and write.

piątek, 3 lipca 2009

LPC python binding

Linear Predictive Coding binding to python (using Numpy).

I have used it as a filter:



Underlying code is taken from Princeton (http://soundlab.cs.princeton.edu/software/rt_lpc/)

You can dowload it from: http://www.mat.umk.pl/~mich/lpc_0.1.tar.gz
And be warned - this is only 0.1 version.

niedziela, 23 listopada 2008

SBQL AST Visualizer

Napisałem na szybko wizualizator do drzew składniowych zapytań SBQL: tutaj! (do odpalenia wymagany pydot) W środku jest kilka obrazków z drzewkami.
Ostatecznie gramatyka wyszła mi taka:


Rule 1 query -> LPAREN query RPAREN
Rule 2 query -> LITERAL
Rule 3 query -> NUMBERLITERAL
Rule 4 query -> STRINGLITERAL
Rule 5 query -> UNARYOP query
Rule 6 query -> query SIMPLEBINARYOP query
Rule 7 query -> query DOT query
Rule 8 query -> query COMMA query
Rule 9 query -> query AS query
Rule 10 query -> query JOIN query
Rule 11 query -> query WHERE query
Rule 12 query -> query AND query
Rule 13 query -> query OR query

z kolejnością wiąząń:
precedence = (
('left', 'WHERE', 'JOIN') ,
('left', 'AND', 'OR'),
('left', 'SIMPLEBINARYOP'),
('left', 'AS', 'DOT')
)

na końcu pliku są takie przykłady:
data = {
"01simple": "(2+2 < 4) and 1",
"02projection" : '(Employee where salary < 200).(name, surname)',
"03more" :'(Employee where surname = "Kowalski" and salary < 200).name',
"04MappedJoin" : 'Employee.worksIn.Dept',
"05forjoin" : '(Employee where surname = "Kowalski" and worksIn.Departmet.isLocatedIn.Location.name = "Lodz").(surname, birthdate)',
"06join" : '(Employee as e join e.worksIn.Department as d join d.isLocatedIn.Location as l).(e.surname, l.name)',
"07join2" : '(Employee where surname = "Kowalski" and worksIn.Department.name = "Production").(surname, birthdate)'
}

wtorek, 11 listopada 2008

Citations for today

“Multicore architectures will (finally) bring parallel
computing into the mainstream. To effectively
exploit them, legions of programmers must
emphasize concurrency.”

"Nontrivial software written with threads,
semaphores, and mutexes are
incomprehensible to humans and cannot
and should not be trusted!"

Edward A. Lee

prezentacja - świetny przykład z wzorcem observera



thinking, learning, thinking... argh

wtorek, 4 listopada 2008

Query Language in Java

Dzisiaj nie będzie nic własnoręcznie stworzonego - zamiast tego mała definicja:

Domain Specific Language
The basic idea of a domain specific language (DSL) is a computer language that's targeted to a particular kind of problem, rather than a general purpose language that's aimed at any kind of software problem. blog:DSL

Pewnym uszczegółowieniem tej koncepcji jest pomysł aby w języku konkretnego przeznaczenia (np. języku programowania) stworzyć wrażenie innego języka (wspominałem juz o LINQ?). Bardzo ciekawe jak te mainstreamowe języki ewoluują. Ostatnio natknąłem się na querydsl (warto jest to póki co najlepszy projekt z tym pomysłem). Niewątpliwie i tak tutaj najbardziej narozrabiał Microsoft ze swoim rozszerzeniem LINQ, ale projekty próbujące tego samego w JAVA rosną ostatnio jak grzyby po deszczu; a ja mam wrażenie jakby powstał taki lepszy, mocno typowany JDBC - nice.

niedziela, 26 października 2008

LINQ Decomposed

LINQ (Language Integrated Query), to bardzo przydatne rozszerzenie języków z platformy .NET o "generyczne operacje na kolekcjach". Chodzi mniej więcej o to, że wprowadzono do języka programowania elementy języka zapytań (formuły LINQ). Zamiast jes skrupulatnie opisywać odsyłam w tym momencie do msdn:linq.

Wygląda całkiem fajnie - proste operacja agregowania, selekcji i projekcji w samym języku i to całkiem elegancko, szybko i jeszcze type-safe - no tak przecież powinno być już dawno.
Na tym niespodzianki się jednak nie kończą, okazuje się bowiem, że jest to również pewien rodzaj vendor-dependent middleware! Formuła LINQ może zostać przetłumaczona na zapytanie do bazy danych. Jak to możliwe? Scenariusz mamy podzielony na dwie części:

Cz.1
Sama formuła LINQ w czasie kompilacji jest tłumaczona na natywne zapytanie, czyli zapytanie zadane obiektem (coś na kształt db4o:tutorial). W trakcie kompilacji formuły zostaną przepisane mniej więcej w ten sposób.


Dim formula_query = From emp In db_context.Employees _
Where emp.Country = "USA" _
Select emp.FirstName, emp.LastName

Dim native_query = db_context.Employees. _
Where(Function(empl) empl.Country = "USA"). _
Select(Function(empl) New With {.FirstName = empl.FirstName, .LastName = empl.LastName})


Obiektem zapytania jest w przypadku pracy z samymi kolekcjami jest IEnumerable a w przypadku źródła danych jej specjalizacji IQueryable (a właściwie specjalizacji IQueryable, dostarczonej przez dostawce sterownika)

Cz. 2
Zapytanie jest realizowane leniwie czyli dopiero wtedy gdy poprosimy obiekt zapytania o enumerator dzieje się cała akcja, która opiera się na mechanizmie przepisywania drzew składniowych. W trakcie wykonania silnik dostawcy dostaje AST, który sobie jakoś tam analizuje i to co może zrobić to np. wygenerować zapytanie sql w postaci stringa i posłać go do bazy, odczytać a potem utworzyć kolekcję tych obiektów i zwrócić programiście (no ale oczywiście może o wiele wiele więcej). Napisałem prosty programik na podstawe tego blog:msdn:linq (copy-paste programming), który zamiast robić cokolwiek, to po prostu wypisuje info o każdym węźle. Troche bardziej user-friendly wyjaśnienie jest tutaj codeguru.


var q = from el in context.Data where el +1 > 5 select el;


Call Data.Where(el => ((el + 1) > 5))
Constant Data
Quote el => ((el + 1) > 5)
Lambda el => ((el + 1) > 5)
GreaterThan ((el + 1) > 5)
Add (el + 1)
Parameter el
Constant 1
Constant 5


Pare przykładów.

Dim q = (From order In db_context.Orders Join detail In db_context.Order_Details _
On detail.OrderID Equals order.OrderID _
Select order.ShipName, detail.Quantity).Take(10)

przepisane jest na zapytanie:

SELECT TOP (10) [t0].[ShipName], [t1].[Quantity]
FROM [dbo].[Orders] AS [t0]
INNER JOIN [dbo].[Order Details] AS [t1] ON [t0].[OrderID] = [t1].[OrderID]

późne wiązanie

Dim q = From el In db_context.Employees _
Select el.FirstName, el.LastName, el.Country, el.City
q = From el In q Where el.Country = "USA"
q = From el In q Where el.City = "Seattle"

przepisane jest na zapytanie:

SELECT [t0].[FirstName], [t0].[LastName], [t0].[Country], [t0].[City]
FROM [dbo].[Employees] AS [t0]
WHERE ([t0].[City] = @p0) AND ([t0].[Country] = @p1)

Warto zauważyć, że w przypadku pracy z kolekcjami silnik jest już w samym standardzie LINQ i zachowuje się dosyć inteligentnie wykorzystując yield. Możemy sobie zdefiniować mniej lub bardziej skomplikowaną "transformacje" (tak to nazwijmy) kolekcji w postaci obiektu, a wykonanie jej nie będzie tworzyło stosów pośrednich podczas obróbki, co znaczy tyle, żedla każdego elementu wykona wszystkie kroki transformacji od początku do końca (można powiedzieć, że tworzymy wrażenie składania funkcji i foldowania.

Jeszcze na koniec pare wniosków i faktów:
  • Wygląda to wszystko całkiem fajnie, bo dostajemy bardzo użyteczne rozszerzenie języka programowania. Osobiście bardzo często to wykorzystuje i co ciekawsze nie jako middleware, ale właśnie do pracy z kolekcjami i wcześniej gdy naiwnie pisałem jakieś tam zapętlające się pętle tak teraz dostaje bardzo czytelny i efektywny kod.
  • LINQ nie jest córą Microsoftu, tylko urodziła się jako koncepcja akademicka, która przechodzi tez do innych języków ruby:rinq, php, js:jslinq, i nawet rozaważa się aby do JAVA wstawić jakieś LINQ, zwłaszcza gdy mają zostać dodane domknięcia (closures) w JAVA 1.7
  • Zarzutem dla LINQ jest kiepska wydajność. Jako, że zapytanie jest generowanie w czasie wykonania w istocie robi to pewien narzut, który z powodzeniem można było zrobić w czasie projektowania, no ale ze swego doświadczenia mogę stwierdzić, że dopóki nie będzie się uzywało formuły linq w pętli nie stanowi to aż tak dużego narzutu
  • Koncepcja linq doskonale nadaje się do rozszerzenia jej do PLINQ (Parallel LINQ) o tym będzie później
  • Microsoft zrobił coś co robił już bardzo często, czyli stworzył naprawdę ładny kawałek oprogramowania, a potem zaprezentował jego jeden mały fragment. Warto zauważyć , że przecież w czasie wykonania dostajemy AST pewnych struktur języka, możemy je analizować i jeszcze dodatkowo mieć wypływ na to co wypluwają - no to przecież nie trywialny mechanizm, a jak wiemy może być całkiem użyteczny również.

niedziela, 19 października 2008

Home cooking: metaprogramming a'la Python

Metaprogramowanie to najprościej rzecz ujmując pisanie programów, które piszą programy. Lekki wstęp można znaleźć tutaj wikipedia:Metaprogramming, a całą koncepcję najłatwiej wyjaśnić na przykładzie LISPA, w którym program piszę się bezpośrednio w drzewie składniowym a kod programu jest listą. Zatem przy niewielkiej zmianie w syntaktyce można stworzyć konstrukcje (tutaj: makro), które w momencie uruchomienia generuje inną listę i ją wywołuję jako program.

No dobra, ale po co to wszystko? Okazuje się, że to bardzo potężny mechanizm, a Paul Graham twierdzi, że jego programy w LISP były złożone w około 40% z makr, co pozwalało mu tworzyć web-dwa-zero projekt (który został ostatecznie wykupiony przez Yahoo) znacznie szybciej niż jego ówczesna konkurencja.

No wielkim zaskoczeniem nie będzie, że metaprogramowanie zostało dorzucone również do Pythona, a konstrukcja, która na to pozwala to Metaclasses. Na sam początek:

Metaclasses are deeper magic than 99% of users should ever worry about. If you wonder whether you need them, you don't (the people who actually need them know with certainty that they need them, and don't need an explanation about why). -- Tim Peters

A więc motywacje już mamy (!)

Na początek problem: Stworzyć interpreter zapytań podobnych do tych tutaj sbql:examples. Dodatkowo niech program nie będzie dłuższy niż cztery ekrany. Oczywiście podobieństwo naszych zapytań do zapytań języka SBQL jest mocno naciągane, niemniej jednak przyjrzyjmy się:


class Osoba():
__metaclass__ = pql_memorystore

imie = Attribute(str, "[*..2]")
nazwisko = Attribute(type = str, card = "[1..1]")
wiek = Attribute(int)

def __init__(self, imie, nazwisko):
self.imie = imie
self.nazwisko = nazwisko

w drugiej linijce określamy tylko metaklasę dla naszej, klasy co sprawia, że nasza żmudnie tworzona klasa Osoba po zakończeniu jej definicji staje sie już zupełnie czymś innym. A w naszym przypadku będzie listą. Czyli mamy klasę, która jest jednocześnie listą i dodatkowo każda nowa instancja tej klasy odkłada się do siebie... weird kind of magic
hmmm sprawdźmy:

Możemy zatem tworzyć obiekty:


o1 = Osoba(imie = "Adam", nazwisko = "Janskowski")
o2 = Osoba(imie = "Janek", nazwisko = "Wlodarczyk")
Osoba("Sigmun", "Freud")
Osoba(imie = "Adam", nazwisko = "Malysz")
Osoba("Tolek", "Skoczylas")

i wykonywać na nich coś w rodzaju zapytań, które operują na instancjach własnych klas:


Osoba
Osoba.imie
[o for o in Osoba if o.imie == ['Adam']]
pql_list([o for o in Osoba if o.imie == ['Adam']]).Nazwisko

Pewnie podobieństwo do SBQL można by jeszcze trochę podciągnąć w ramach samego Pythona przeciążając operatory; znacznie więcej dałoby rade pewnie podciągnąć pewnie evalem, ale przecież to nie o to chodziło.

Program jest tutaj. Napisałem go dawno temu (w czasach gdy jeszcze pterodaktyle latały po niebie) i nigdy nie skończyłem ale w sumie mniej więcej działa, a w pliku jest więcej przykładów. Jest tam nawet wstęp do stworzenia kontroli typów i kardynalności atrybutów.