Implementing Roulette Wheel in Python

Fitness Proportionate Selection is a common method in Evolutionary Algorithms, which is also known to us as Roulette Wheel Selection in Evolutionary Algorithms[1] such as Genetic Algorithms.

The basic idea here is to get a random value out of a sample based on a pre-defined bias.

Following is the python implementation (using numpy library) of the Roulette Wheel selection. The wheel_vector should be provided in the following format [….value, bias…..], values can be added as much as required. Bias value is relative, higher the bias value higher the change of getting selected the corresponding value.

For an example, if it is required to declare the wheel vector for a bias dice where no. 6 is more likely to be appeared than other values, it should be defined as follow: note that value 6 is prone to be appeared 5 times more than any other value.

wheel_vector = np.array([1,1,2,1,3,1,4,1,5,1,6,5])

“all Python codes in this article are released under Creative Commons — Public Domain

#!/usr/bin/python

import numpy as np
import random as rand

roulette_wheel = np.array((0))
slot_count = 0

def init_roul_wheel(value_array):

	slot_count = 0
	i=0
	arrsize = value_array.size
	while i < arrsize/2:
		slot_count = slot_count + value_array[2*i+1]
		i = i + 1
	roulette_wheel = np.zeros((slot_count),dtype=np.int)
	#print(roulette_wheel)
	i = 0

	while i < arrsize/2:
		rv = value_array[2*i]
		bv = value_array[2*i+1]
		j = 0
		while j<span 				data-mce-type="bookmark" 				id="mce_SELREST_start" 				data-mce-style="overflow:hidden;line-height:0" 				style="overflow:hidden;line-height:0" 			></span><span 				data-mce-type="bookmark" 				id="mce_SELREST_start" 				data-mce-style="overflow:hidden;line-height:0" 				style="overflow:hidden;line-height:0" 			></span><span 				data-mce-type="bookmark" 				id="mce_SELREST_start" 				data-mce-style="overflow:hidden;line-height:0" 				style="overflow:hidden;line-height:0" 			></span><bv:
			t = rand.randint(0,slot_count-1)
			wheel_alloc = roulette_wheel[t]
			if wheel_alloc == 0:
				roulette_wheel[t] = rv
				j = j + 1
		i = i + 1
	return (roulette_wheel)

def spin(rw):
	slot_count = rw.size
	randno = rand.randint(0,10000)
	rot_degree = randno%360
	rot_unit = 360/slot_count
	rol_no = (rot_degree - (rot_degree%(rot_unit)))/rot_unit
	rol_value = rw[int(rol_no)]
	return rol_value	

wheel_vector = np.array([10,1,20,2,30,2,40,4,50,5,60,4,70,3,80,2,90,2])
x = init_roul_wheel(wheel_vector)
print (spin(x))

Check how the above code works (online python demo)

The above code is quite lengthy as I purposely omitted shortcuts to slice the arrays hoping that it improves the readability of the code.

The next step is to check if the function is really bias. In order to check that the code has been altered as follow. This version iterates the wheel 1,000,000 times and check the results.

#!/usr/bin/python

import numpy as np
import random as rand

roulette_wheel = np.array((0))
slot_count = 0

def init_roul_wheel(value_array):

	slot_count = 0
	i=0
	arrsize = value_array.size
	while i < arrsize/2:
		slot_count = slot_count + value_array[2*i+1]
		i = i + 1
	roulette_wheel = np.zeros((slot_count),dtype=np.int)
	#print(roulette_wheel)
	i = 0

	while i < arrsize/2:
		rv = value_array[2*i]
		bv = value_array[2*i+1]
		j = 0
		while j<bv:
			t = rand.randint(0,slot_count-1)
			wheel_alloc = roulette_wheel[t]
			if wheel_alloc == 0:
				roulette_wheel[t] = rv
				j = j + 1
		i = i + 1
	return (roulette_wheel)

def spin(rw):
	slot_count = rw.size
	randno = rand.randint(0,10000)
	rot_degree = randno%360
	rot_unit = 360/slot_count
	rol_no = (rot_degree - (rot_degree%(rot_unit)))/rot_unit
	rol_value = rw[int(rol_no)]
	return rol_value	

wheel_vector = np.array([10,1,20,2,30,2,40,4,50,5,60,4,70,3,80,2,90,2])
x = init_roul_wheel(wheel_vector)
#print (spin(x))

cal_rounds = 1000000

results = np.zeros((cal_rounds),dtype=np.int);

i =0 

while i<cal_rounds:
	value = spin(x)
	results[i] = value
	i = i +1

unique, counts = np.unique(results, return_counts=True)
print ("RW Vector", wheel_vector, "\n")
print ("Roulette Wheel", x)
print ("Results: ",unique,"\n\t" ,counts)

i = 0
while i<counts.size:
	#print (unique[i], "occured " + str(counts[i]))
	precentage = (counts[i]*100)/np.sum(counts)
	print (unique[i]," precentage - ",str(precentage) + ' %','('+str(round(precentage))+')')
	i = i +1

rws_output

Check the output of the code above, it shows number of times the values has been selected and the values have been selected based on the bias (check the percentages). Therefore it can be concluded that the function is working as expected.

References

[1] Lipowskia, Adam and Lipowskab, Dorota Roulette-wheel selection via stochastic acceptance – http://www.sciencedirect.com/science/article/pii/S0378437111009010


CC0

To the extent possible under law,
this article, the author

has waived all copyright and related or neighboring rights to “Implementing Roulette Wheel in Python”.

Advertisements

Non-Standard rounding function in Python

This post is about a trivial operation which is rounding. Recently I came across a situation where I need to perform a non standard integer rounding. As we know the standard functions available would round the valie to the nearest 10 or its multiplications. My requirement was rounding to the nearest 5.

So I came across the following solution and I immediately fall in love with this little python snippet and thought of sharing.

Here is goes.

#!/usr/bin/python

def floor(value, divisor):
    ans = value%divisor
    return value-ans

def ceiling(value, divisor):
    ans = value%divisor
    return value+divisor-ans

a = 105

x = ceiling(a,5)
y = floor(a,5)

print(x)
print(y)

The ceiling ( ) function round the value to the nearest upper value which is a multiplication of 5. The floor ( ) function would round the value to the nearest lower value which is a multiplication of 5.


Symmetric-Key Encryption using openSSL

I wrote few blog posts on Asymmetric Key encryption using PHPSecLib library recently and this blog post is on Symmetric-Key Encryption and I ll be using PHP openSSL extension for the implementation. OpenSSL is a open source library which implements SSL and other major cryptographic functions. It is extensively used in Linux, Windows and other operating systems. Luckily PHP got an extension, so we can straightaway use it.

Instead of PHPSecLib, openSSL can be used to implement RSA cryptography functions in PHP as well.

The major drawback in Symmetric-Key Encryption is the usage of the same key to encrypt and decrypt data. However unlike in Asymmetric-Key encryption (I would say RSA hereafter) there is no limit on the data size that can be encrypted and it is relatively faster than RSA. As a result RSA is used to exchange Symmetric Keys securely and then the client and the server continues to communicate based on symmetric-key encryption. Not only for communication but also we can use symmetric key encryption in data storage too. For an example before storing data on a database, it is a good practice to encrypt those data, in such a scenario symmetric key encryption is much more suitable than RSA.

There are plenty of other libraries which provide symmetric key encryption, however it is recommended to use libraries like openSSL or PHPSecLib as they are extensively tested and well maintained. My advice is to use openSSL as much as possible, however due to limitations on your server, it may not be possible to use openSSL for RSA but it can always be used for symmetric key encryption.

Will check the PHP code for the task. It is simple !

My PHP version is PHP Version 7.0.10 and using OpenSSL/1.0.2h, if you want to check yours you can use phpinfo(); function which gives all information regarding your PHP installation.

<?PHP 
$text = 'This is a secret message that should be encrypted before saving it to the database so that even the database is compromised the attacker wont be able to steal data'; 

$encryption_key = 'password'; $iv = 'randomdigit16bit'; 

$encrypted_data = openssl_encrypt($text, 'aes-256-cbc', $encryption_key, OPENSSL_RAW_DATA, $iv); 

$encrypted_data = base64_encode($encrypted_data); 
var_dump($encrypted_data); 
?>

The code is self explaining, openssl_encrypt is the function that should be used and $text is the data that should be encrypted, then the next parameter is the cipher method, $encryption_key is the key to decrypt the encrypted text. This needs to be stored as it is required later to decrypt the data. I ll discuss about storing keys securely in a future blog post, as it is quite out of the scope for this topic.

Decryption is to be carried out as follow:

<?PHP

$text = 'This is a secret message that should be encrypted before saving it to the database so that even the database is compromised the attacker wont be able to steal data';

$encryption_key = 'password';
$iv = 'randomdigit16bit';

$encrypted_data = openssl_encrypt($text, 'aes-256-cbc', $encryption_key, OPENSSL_RAW_DATA, $iv);

//$encrypted_data = base64_encode($encrypted_data);

$decrypted_data = openssl_decrypt($encrypted_data, 'aes-256-cbc', $encryption_key, OPENSSL_RAW_DATA, $iv);

var_dump($decrypted_data);

?>

Same as the openssl_encrypt function openssl_decrypt function could be used. Note that same $encryption_key and the $iv have been used.

Same as the $encryption_key, $iv should be same in encryption and decryption. $iv is known as the Initialization Vector which adds an extra layer of protection. It can be a random 16 bits string and the value should be stored as it requires in the decryption process as same as the encryption key.

The role of the $iv (Initialization Vector) is to differentiate the encrypted text. For an example the encryption key could be common per user or your web site etc. But you can use a random $iv per each encryption. As a result if you encrypt the same value using the same key, the result is going to be different when you use two different $iv.

Following method can be used to generate 16 bits IV. Make sure you store the IV otherwise decrypted data will not be able to decrypt back.

$iv = openssl_random_pseudo_bytes (16);

That is it, simple and handy isnt it?

Handling arrays (lists) in Python

Arrays are one of the fundamentals in any programming language. However if you have used Python; for example, you may not find arrays in it. Instead you get list. It is a more general form of an array.

I prefer using NumPy library for handling arrays in real-time python developments. However it is required to have a basic knowledge of handling arrays in Python first.

List [ ]

List is a data structure that holds values of any type. It can be a collection of strings, integers or any other valid data type in python. They are dynamic (known as mutable too), meaning that you can add or delete values as you wish.

Define a List with [ ]

It is quite same as other languages, you can use [ ] to define a list.

newArray = []

or with values

newArray = ["Population","X","size",200,"size"]

As in arrays, the element counts starts from 0 and you can use “slicing” in Lists too.

print (newArray[2])

you may use the slicing to assign values to a List elements too.

newArray[2] = 100

You may notice that you can assign a new value and it can be in a different type.

Following is a python script showing things we discussed so far

#!/usr/bin/python
newArray = ["Population","X","size",200,"size"]
print (newArray)
print ("Property of X = " + newArray[2])
newArray[3] = 200/3.5
print (newArray)

m-D List

It is possible to define multi dimensional lists and they behave quite similar to multidimensional arrays.

newArray = ["POST",["Status Code",100,200,300],["fail","pass","error"]]

you can use any combination of data types and any number of dimensions. Again slicing can be used to retrieve or assign values as we have observed above. Refer to the example code below:

#!/usr/bin/python
newArray = ["POST",["Status Code",100,200,300],["fail","pass","error"]]
print (newArray[1][2])
newArray[2][1] = "Success"
print (newArray)

Associative Arrays in Python

However our goal in this post is to see how associative arrays can be handled in Python. In Python associated arrays are termed as dictionaries. Simply it is ordered key-value pairs.

How to define a dictionary:

dataArray = {"method":"POST", "action":"file.py", "status": 500}

So that later you can use the key value to retrieve the value of the element.

dataArray["action"]

It is possible to use dict(sequence) function to create a dictionary too.

seq = (("method","POST"), ("action","file.py"), (2,500))

dataArray = dict(seq)

Values can be altered referring to the key value

seq = (("method","POST"), ("action","file.py"), (2,500))
dataArray = dict(seq)
dataArray[2] = 100
print (dataArray)

To delete an element, del(element) statement can be used.

seq = (("method","POST"), ("action","file.py"), (2,500))<span 				data-mce-type="bookmark" 				id="mce_SELREST_start" 				data-mce-style="overflow:hidden;line-height:0" 				style="overflow:hidden;line-height:0" 			></span>
dataArray = dict(seq)
del(dataArray["action"])
print (dataArray)

Methods on List

List data type has more methods that are very useful, will cover them briefly.

list.count(x) – Return the number of times value x appears in the list.

list.append(x) – Add element x to the list

list.extend(newList) – Extend the list by appending all the items in the newList

list.insert(n, x) – Insert the element x at n position. The current element at the position n will be moved backward.

list.remove(x) – Remove element which is the first item having the value x

list.pop([i]) – i is optional, remove the element in position i

list.index(x) – Return the index of the first element whose value is x in the list.

list.reverse() – Reverse the elements of a list

In the next part of the post will check how to implement basic data-structures such as stack and queue in python using lists.

Stack

Stack is analogous to a pile of books. The elements which goes last comes first. Therefore stack is a list where the index 0 of the list is the first element of the stack (this element will be the last element to be taken out).

#!/usr/bin/python
stack = [1, 2, 3, 4]
#add elements to the stack
stack.append(5)
stack.append(6)
print(stack)
#taking elements out
x = stack.pop()
print(x)

Queue

Not like stacks, in queues element which goes first come out first. Therefore it is possible to use pop() to retrieve values from a queue but when appending elements it should be placed at the beginning of the list. That is quite inefficient in lists as whole list should be shifted right to accommodate space to the new element.

It is recommended to use collections.deque in python for this purpose which is much more efficient.

However in this post will see how queues can be implemented using the knowledge we have gained so far.

#!/usr/bin/python
queue = [4,3,2,1]
value = [5]
value.extend(queue)
queue = value
print (queue)

Note that in the above example, the new value has been define as an element having one element. Otherwise it is not possible to use this technique.

Following is another way:

#!/usr/bin/python
queue = [4,3,2,1]
queue.reverse()
queue.append(5)
queue.reverse()
print (queue)

Both techniques have 4 lines but I guess that the first method should be more efficient.

Will write on NumPy in the next post.

Overcoming the conventional stumbling block to global success

I do hope you will enjoy the following article as much as I did. May it be a motivation …

Dr. Sanjiva will be delivering “The IESL Ray Wijewardene Memorial Lecture – Nobody to Leader : Achieving Global Leadership with Software”, today (2017 Sep 7) at IESL. More Info…

a 22-year-old, ftesh out of university, can solve problrms but they haven’t seen many problems yet. You learn problems as yoh go along. The key to being a good entrepreneur is not about identifing problems but about caring enough to solve it.

Copyright Notice : This article appeared in DailyFT paper, 2017 Sep 6. http://www.ft.lk and I hold no copyrights. Shared with an intention to educate others. All rights reserved by the above named publication.

How to include PHPSecLib

I got an interesting question on my blog post, RSA cryptography in PHP (How To?). Even the example, I have provided works fine with the source I have provided, you would probably get into some issues when trying it from the scratch. Including PHPSecLib is not straight forward. You cannot just use include() or include_once() functions directly. It follows PEAR standard (PHP Extension and Application Repository), therefore you need to use the following trick if you dont have PEAR installed in your server or in your LAMP/ WAMP deployment.

For an example consider following directory structure:

------- App
+ ----------------- Core
+ ----------------- Vendors

Assuming that your code lies in the “Core” directory, and you are planning to place PHPSecLib in the “Vendors” directory, you can include the following to your code so that it will find the PHPSecLib without no issue:

 
$path = '../vendors/phpseclib/'; 
set_include_path(get_include_path() . PATH_SEPARATOR . $path);
include_once('Crypt/RSA.php');

Working example:

<?PHP

$path = '../vendors/phpseclib/';
	set_include_path(get_include_path() . PATH_SEPARATOR . $path);
	include_once('Crypt/RSA.php');

$rsa = new Crypt_RSA();
$keys = $rsa->createKey(2048);

var_dump($keys);

$rsa->loadKey($keys['publickey']); // public key
$plaintext = 'I want to get encrypted !';

$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
$ciphertext = $rsa->encrypt($plaintext);

var_dump($ciphertext);

$rsa->loadKey($keys['privatekey']); // private key
$text = $rsa->decrypt($ciphertext);
var_dump($text);
?>

Note that we have explicitly defined the path for the library from the current directory where the executing script is located.

If you insist on using autoload instead, it can be achieved in the following manner. You cannot straight away let the autoload find the class as the file name and the class name are different. Therefore we need to change the path as the code can locate the Crypt_RSA class, which is ../vendors/phpseclib/Crypt/RSA.php

<?PHP

spl_autoload_register(function ($class_name) {
	$path = '../vendors/phpseclib/';
	set_include_path(get_include_path() . PATH_SEPARATOR . $path);
	if($class_name='Crypt_RSA')
	{
		$class_name='Crypt/RSA';
	}
	include_once $class_name.'.php';
});

$rsa = new Crypt_RSA();
$keys = $rsa->createKey(2048);

var_dump($keys);

$rsa->loadKey($keys['publickey']); // public key
$plaintext = 'I want to get encrypted !';

$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
$ciphertext = $rsa->encrypt($plaintext);

var_dump($ciphertext);

$rsa->loadKey($keys['privatekey']); // private key
$text = $rsa->decrypt($ciphertext);
var_dump($text);
?>

Hope you will find this information useful. Cheers !!

How to store keys (RSA) ?

The last post was about handling RSA cryptosystem in PHP. This post is covering a small aspect of the last post.

Once keys (Public and Private) are generated there should be a method of storing the keys, both private and the public keys to use later. Since the keys are having a specific format you are not able to store them in a raw format. It doesn’t work the next time when you try to use them.

There are few formats and methods we can use. In the last post, the generated keys are in PEM (Privacy Enhanced Mail) format. Dont get confused with that. I am suggesting a technique to store the keys. There are many other ways to get this accomplished. Among them base64 encoding/ decoding would be quite handy and easy.

PEM formatted private key is noted below.

-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,CEC7DF536C0F4B98

sOBuGCgafYqmuOwzmG+HKD9Rq1fkL5PCt1ZfDF2lwKLoSjS3Ao68Sb3vrelkF7Df
3RwUOXL+G9HOMgmEmS6e+DacesaPHipvdjTca7k5z6A2ndRaDPB+6GuuswVBzbwm
CbRerep9G1BEyRY0z/3LKCgr1IbcpiPGAtmfEr/aTuqZURkY3eEosGP9Mn66b7Tr
bYaQOYE0tX2hI6GkQHJP9JGBsVLOA9iQ/QYtF3CjxFUTB3fWR3qPV/36SucBxlPx
pNWHPoXQixIAl9wvmJ0lA+y6mkWe0GBPBRWAF1Xum28Ujaw3E+95Vcxp7e2HvehX
xwpG10Xq5OdO0F+Ov4YULGe/VvJuQh6Lwb96qjserkzdfPNRxXm5vudPCRSQylxz
6N4xYUxtZoOOZ0A3znpTS13F+pTHAjAfHEutd17qTAApSlnOUz/CX7NI070pw+Eq
4QjQ9IJju14XBFqjbK8bdsaIAhZvZgTZY995t5F9R30Rf99XpIWTcPIVpX9Zb8nx
Lfxw0ok0Io2mdymy4jttopXgbrt+mky3zf7d2oxengefreuHH0SUYwrCVk5xKZju
NVZPPXP0Sx/f6nyHdv+MFh9mB1YrbuMeP4LSK3tsgVb2P4k3FOaQGwMU32k5KaBP
R97i7RowhiALljGvMouxo87QxdYUZJTVvcDj/42PiGZP6fQO1X35TWkr8INvGAqB
sUKMLZPsZahaSxWZ5uoIiOfjB8RdvmNB6D5DHUviIavkAFLUtZOT18apXhLzrKMO
f9p7WZP5yGVdD0AnWX9NP157VHQYZGNOu6ZHzPMJ38R4+uEtv7mf55A9FQPrYAXK
NOqxpXd5XNmM2Yl+MVlZJ7IXf1TCZicbG+DjQYyQHg9nK43eG61waZCM4EmjF0Vs
hx/FtelrmV5pw1vna0N8rmF4WG6+e6ruZ0ovFOFCsqb5630UJkkRqWKxkN/2t3FW
2LMjNchpswSoe4WQwIAoM+piv31VR+rGYcreDsJprXVPyzTVUZgxUdb7ku2HN1KH
9z336Aot9snJkkdZrsoqoOMCpQuUP987aMS5bQyHmJDWTo7XxPW2BxLYUjTeeqRA
GAk0LVOzTVP57TYi4Ay6cmrdnBsmv6qlCIxOspx83MzYqjOLqQuEpvag1YYTIgzX
6kc5LGpiP4Itd8EEqSdBkRUTetuDsoHdRfHna16i8YS3HwHTei2eF3BbpLXPAt26
aPsSnACs+fTz1GP/Rr7s2kMmnChh/z6afTJVGG1E6fXBOHozY+S2MO3wNr6hupPp
dtP23x88Gjh3TaPdQ7qkg2j0SqDdLLCekvmGhGyT3gKLCAF60NxrJETlHKfyrPHO
BM26pGB22KsYwUlihXTxFlSfP81tY9NQxpu/GjBCutWvQl74BvghHFQUJKIQuqa+
IgtkY+l4zTZ+meSjYvSzA/r3KfLdTIQt5eIVhDs1Jhont2zPBZ1x7n7T+eevj7FP
zVrV5H8ukp38KhtlJ05ufy6628qBOlelsfMExxGxNZICIh40sGaQO3DsBrNlgAln
D+XcWPK81uBIN9jYeRbtTu00n7/bQrJyIHAbKeU+wAb0TF87ets2VPzIwTpdxzc2
-----END RSA PRIVATE KEY-----

Base64 encoded key (note that it appears as a single line, no line breaks).

LS0tLS1CRUdJTiBSU0EgUFJJVkFURSBLRVktLS0tLQ0KUHJvYy1UeXBlOiA0LEVOQ1JZUFRFRA0K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k5eG84MzJ5TG90ZmZGTG40cURFbnY4dUh2aDBDQ2VsY1hKVjENCjBXdmFoOWMwaCtUZGVydWgvZFJoa0NpZjBuMUUyN25hbFBMeS9oQVJJSHpZQUtGbmRUZjZyNGVESmpqalUrcTQNCi0tLS0tRU5EIFJTQSBQUklWQVRFIEtFWS0tLS0t

You can simply use a “TEXT data typed” filed in MySQL table to store base64 encoded key pair and then when it is needed just base64 decode and use it. Even you can apply further encryption against the base64_encoded string to make the key much more secure. You can hash the base64_encoded string and create signatures of the keys as another security measurement.

Simply use the base64_encode( ) and base64_decode( ) functions in PHP.

$encoded_key = base64_encode(myRSA::$privateKey);

$private_key = base64_decode($encoded_key);

NOTE: base64 encoding doesn’t provide any additional security, it is purely assisting towards storing/ passing the keys in a more comfortable way. Therefore you need to use an additional security layer (eg: database data encryption) on top of the stored keys to make it much more secure.