Friday, December 6, 2013

java observer pattern

A good example to picture observer pattern is a newspaper subscription service with its publisher and subscribers. The observer pattern defines a one-to-many relationship between a set of objects. When the state of one object changes, all of its dependents are notified. A visualized example of observer pattern is below.

I prepared a little example code of java observer pattern(*). The example acts like a tracker agent that it follows price and stock changes of a product. When price/stock information changes, all observers are updated new price/stock information.

The code includes three interfaces. "Subject" interface which is subscription service. The others are "Observer" and "DisplayProduct".

public interface Subject {
	public void registerObserver(Observer observer);
	public void removeObserver(Observer observer);
	/**
	 * Notify all observers when the Subject's state has changed.
	 */
	public void notifyObservers();
}

/**
 * The Observer interface is implemented by all observers,
 * all observers have to implement the update() method.
 */
public interface Observer {
	public void update(float price, boolean stock);
}

/**
 * It will be called when display product needs to be displayed.
 */
public interface DisplayProduct() {
	public void display();
}

The code includes three classes. "Tracker" implements Subject interface that Tracker object is our subject object as above picture.

public class Tracker implements Subject {
	private ArrayList observers;
	private int price;
	private boolean stock;

	public Tracker() {
		observers = new ArrayList();
	}
	
        public void registerObserver(Observer observer) {
		observers.add(observer);
	}

	public void removeObserver(Observer observer) {
		int index = observers.indexOf(o);
		if (index >= 0) {
			observers.remove(index);
		}
	}

	public void notifyObservers() {
		for (int i=0; i < observers.size(); i++) {
			Observer observer = (Observer)observers.get(i);
			observer.update(price,stock);
		}
	}

	public void stockPriceChanged() {
		notifyObservers();
	}

	public void setStockPrice(float mPrice, boolean mStock) {
		this.price = mPrice;
		this.stock = mStock;
		stockPriceChanged();
	}
}

One of the other classes is "FollowedProductDisplay" which is implements both of Observer and DisplayProduct interfaces. FollowedProductDisplay objects are our observers.

public class FollowedProductDisplay implements Observer, DisplayProduct {
	private float price;
	private boolean stock;
	private Subject tracker;

	public FollowedProductDisplay(Subject mTracker) {
		this.tracker = mTracker;
		tracker.registerObserver(this);
	}

	public void update(float mPrice, boolean mStock) {
		this.price = mPrice;
		this.stock = mStock;
		display();
	}

	public void display() {
		System.out.println("Followed product: price -> " 
                    + price + " stock -> " + stock);
	}
}

The last class is "TrackerAgent" that it contains our subject and observer objects.

public class TrackerAgent {
	public static void main(String[] args) {
		Tracker tracker = new Tracker();
		FollowedProductDisplay followedProduct = 
                        new FollowedProductDisplay(tracker);
		tracker.setStockPrice(124.50,true);
		tracker.setStockPrice(114.50,true);
	}
}

The result of the example is below:

Followed product: price -> 124.50  stock -> true
Followed product: price -> 114.50  stock -> true


(*) I get remarkable help from the book. Head First Design Patterns, Eric Freeman, Elisabeth Robson, Bert Bates, Kathy Sierra, O'Reilly Media, 2004.

Tuesday, September 3, 2013

python list comprehension for loop

Let's make a 'python list & dictionary comprehension for loop' example. It selects equal or greater than average value, then returns max 50 elements from dictionary.

def pick_biggest_elements(my_dict):
    values = [x for x in my_dict.values()]
    values.sort()
    average = sum(values) / float(len(values))
    upper_side = [el for el in values if el >= average]
    temp = [key for key, value in my_dict.items() if value in upper_side]
    if len(temp) > 50:
        temp = temp[-50:]
    return [eval(a) for a in temp]

Monday, September 2, 2013

python roulette wheel selection

Selection operator picks out individuals in the population for reproduction in genetic algorithms. Roulette wheel selection that an imaginary proportion of the wheel is assigned to each of the chromosomes based on their fitness value. The fitter chromosome has more chance to select than worse one. Roulette wheel selection is a kind of elitist selection that retaining the best individuals in a generation unchanged in the next generation.

Here an example of roulette wheel selection via pyhton. Imagine that you have population like

population = [[0,0,1,0,0,0,1],[0,1,0,0,0,0,0]]

And you use a proper fitness function regarding to your problem, and get a python dictionary to wrap your individuals and their fitness values like

population_fitness_dictionary = {"0,0,1,0,0,0,1": 1.245, "0,1,0,0,0,0,0":1.658}

Firstly, we can create a probability list (imaginary proportion of the wheel)

def get_probability_list():
    fitness = population_fitness_dictionary.values()
    total_fit = float(sum(fitness))
    relative_fitness = [f/total_fit for f in fitness]
    probabilities = [sum(relative_fitness[:i+1]) 
                     for i in range(len(relative_fitness))]
    return probabilities

After that, we can write the roulette wheel selection function. Parameters of the function are our population, probability list of the population and a number to select desired individuals for reproduction.

def roulette_wheel_pop(population, probabilities, number):
    chosen = []
    for n in xrange(number):
        r = random.random()
        for (i, individual) in enumerate(population):
            if r <= probabilities[i]:
                chosen.append(list(individual))
                break
    return chosen

Saturday, August 31, 2013

python comprehension split list

I have recently finished a master thesis about genetic algorithms for text segmentation via python, so I have a complicated relationship with python. Actually it always helps to me. This post consists of some python especially list and dictionary comprehensions.

First of all, splitting a list regarding with given another list. For example, you have a list which has sentences as elements. Another list is reference splitter and consists of 0s and 1s.
sentences = ["first sentence", "second sentence", "third sentence",
             "fourth sentence", "fifth sentence"] 
reference = [0,0,1,0]
This list indicates that cut the number of index of '1' at the gap in the sentences list and result list will include two sublists
result = [["first sentence", "second sentence", "third sentence"],
          ["fourth sentence", "fifth sentence"]] 
def split_segments_according_to_reference(reference, sentences):
        temp = []
        result = []
        for i, j in zip(reference,range(len(sentences))):
            temp.append(sentences[j])
            if i == 1:
                result.append(temp)
                temp = []
        if len(sentences) == len(reference)+1:
            temp.append(sentences[-1])
            result.append(temp)
            temp = []
        return result

Thursday, April 25, 2013

Pareto frontier graphic via python

Pareto frontiers are not strictly dominated by any others. An element is dominated if there exists an other element in the set of elements having a better score on one criterion and at least the same score on the others. Here a little example Python Pareto frontier code.
import matplotlib.pyplot as plt

def plot_pareto_frontier(Xs, Ys, maxX=True, maxY=True):
    '''Pareto frontier selection process'''
    sorted_list = sorted([[Xs[i], Ys[i]] for i in range(len(Xs))], reverse=maxY)
    pareto_front = [sorted_list[0]]
    for pair in sorted_list[1:]:
        if maxY:
            if pair[1] >= pareto_front[-1][1]:
                pareto_front.append(pair)
        else:
            if pair[1] <= pareto_front[-1][1]:
                pareto_front.append(pair)
    
    '''Plotting process'''
    plt.scatter(Xs,Ys)
    pf_X = [pair[0] for pair in pareto_front]
    pf_Y = [pair[1] for pair in pareto_front]
    plt.plot(pf_X, pf_Y)
    plt.xlabel("Objective 1")
    plt.ylabel("Objective 2")
    plt.show()


An example Pareto frontier graphic is produced by above python function.

Reference 1. http://code.activestate.com/recipes/578230-pareto-front/

Tuesday, March 19, 2013

.htaccess allows a specific IP or username/pass

This example shows that .htaccess file allows a specific IP else username/pass.
Step one: allows specific IP add these lines to .htaccess file

Order Deny,Allow
Deny from all
allow from 123.456.78.90


Step two: create username/password and use them
First of all, you should create username/password file using htpasswd. Type in terminal: "htpasswd -c filename username" press enter and you should input your password (twice). After that you have a .htpasswd file. The file consists of like below line

sirin:$apr1$vp3kZPGK$HdkGNW2KmYO8GJnTe6oRl1

So, you can add these lines to .htaccess file

AuthType Basic
AuthName "Restricted"
AuthUserFile /Users/sirin/foo/bar/.htpasswd
Require valid-user


Step three: combine them
Finally, you combine them below: also adding "satisfy any" selector keyword

AuthType Basic
AuthName "Restricted"
AuthUserFile /Users/sirin/foo/bar/.htpasswd
Require valid-user
Order Deny,Allow
Deny from all
allow from 123.456.78.90
satisfy any



Tuesday, February 26, 2013

PHP add months to date via "strtotime"

If you need a date calculation via PHP date, you would use "strtotime". For example you have a date and you'll need add months to it.

$start = strtotime("20-09-2012");
$months = 5; 
$result = strtotime("+$months months", $start); 
echo $result; // 20-02-2013

Thursday, January 24, 2013

Monte Carlo simulation for deployment of a WSN

Monte carlo simulation based on random sampling to acquire numerical results. Steps of method: define a domain of inputs, generate inputs randomly, perform a deterministic computation and associate the results. Here an example of Monte Carlo simulation for deployment of a WSN. Assume a uniform random process governs the deployment of network. Assume disk sensing model. Assume that the deployment is done on 100m by 100m square 2D region. Example program that Monte Carlo simulation to find out the necessary number for 99% sensing coverage as a function of sensing radius.
import random
import math

def sensor_location(n):
    coordinates = []
    for i in range(n): 
        x = random.uniform(0,100)
        y = random.uniform(0,100)
        coordinates.append((x,y))
    return coordinates

def coverage_ratio(sample_count,sensor,radius):
    count = 0
    location = sensor_location(sensor)
    for i in range(sample_count):
        xi = random.uniform(0,100)
        yi = random.uniform(0,100)
        sensed = False
        for j in location:
            d = math.sqrt( math.pow((xi-j[0]),2)+ math.pow((yi-j[1]),2))
            if d <= radius:
                sensed = True
                break
        if sensed == False:
            count += 1
     '''
        coverage indicates non-sensed area
     '''
     coverage = ((count/float(sample_count))*10000)
     return 100-(coverage/100) 

def simulation(sample, sensor, radius):
    print "running for radius = %d" % radius
    while True:
        ratio = coverage_ratio(sample,sensor,radius)
        if ratio >= 99.0:
            print "number of required sensor: %d" % sensor
            print "coverage: %f" % ratio
            break
        else:
            sensor+=5
    return ratio

'''perform simulation for 
   initial sensor = 10
   and r = 5 m 
'''
def main():
    simulation(10000,10,5)
 
if __name__ == "__main__":
 main()

After 15 times running the program, the simulation result shows the average necessary sensor number for 99% sensing coverage is 586.73.

Saturday, January 12, 2013

An overview of routing protocols classification in WSNs.

In general, routing protocols can be divided into three groups depending on different network protocol specifications. First, depending on the network structure that the class consists of three routing types are flat-based routing, hierarchical-based routing, and location-based routing.

  • All nodes are typically assigned equal roles of functionality points to flat routing, 
  • Nodes will play different roles in the network points to hierarchical routing, 
  • Sensor nodes’ positions are exploited to route data in the network points to location-based routing. 

Second, depending on how the source finds a route to the destination that the class consists of three routing protocol types is proactive, reactive and hybrid protocols.

  • In proactive protocols, all routes are computed before they are needed,
  • In reactive protocols, routes are computed on demand, 
  • Hybrid protocols use a combination of these two ideas. 

Finally, depending on protocol operation that the class consists of five routing techniques.

  • Multi path-based uses multiple routes simultaneously. 
  • Query-based that the destination node sends a query data from a node to through the network and target node sends the data back to the sender node that initiated the query. 
  • Negotiation-based eliminates redundant data transmissions through negotiation in other terms negotiates data transfers before they occurs. 
  • QoS-based that the network should to balance between energy consumption and data quality. In details, the network has to satisfy certain QoS metrics such as delay, energy, and bandwidth.
  • Coherent-based routing performs only minimum amount of in-network processing. 




Reference: K.Akkaya, M.Younis, ”A Survey of Routing Protocols in Wireless Sensor Networks,” Elsevier Ad Hoc Network Journal, Vol. 3/3 pp. 325- 349, 2005.