Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coding sigma formula?

Python beginner, running 2.7

I cannot find a Pythonic way to code the following formula. My goal is to have a single function into which I can input the values (in previous attempts I've only found a highly repetitive brute-force solution).

formula

Necessary information:

if you don't know what the sigma symbol means: look here

# 'v' is the formula
# 'i' 'j' 'k' are actors with numerical attributes 'c' 's' and 'x'
# 'n' = length of the following lists (length is identical for all four lists)

values_1 = [Bob, Sue, Mary, Jo...] # i, j, and k are any 3 values drawn from this list  
                        # under the condition that i != j != k

values_2 = [5,6,7,8...] # c is drawn from this list. 
                        # if i = values_1[0], then c(i) = values_2[0]. 
                        # same for j and k

values_3 = [9,10,11,12...] # s is drawn from this list.  
                        # if i = values_1[0], then s(i) = values_3[0]

values_4 = [13,14,15, 16..] # x is drawn from this list. 
                           # if i = values_1[0], then x(i) = values_4[0].

def V (j,k):
        #this is where I need help!

v_Bob_Sue = # this is where V(Bob, Sue) should go.
            # this is what the math would look like in English:
# SUM of (c_Mary * s_Mary * ((abs(x_Mary - x_Sue) - abs(x_Mary - x_Bob)) / x's range))
# and (c_Jo * s_Jo * ((abs(x_Jo - x_Sue) - abs(x_Jo - x_Bob)) / x's range))

# Bob and Sue are the j and k value
# we do the formula with all the other actors (from values_1) who AREN'T Bob and Sue


v_Bob_Mary = # etc 
v_Bob_Jo = 
v_Sue_Bob =
v_Sue_Mary =
v_Sue_Jo =
v_Mary_Bob =
v_Mary_Sue =
v_Mary_Jo =
v_Jo_Bob =
v_Jo_Sue =
v_Jo_Mary =
like image 224
user1569317 Avatar asked Aug 06 '12 14:08

user1569317


1 Answers

As for the "sigma", computation is pretty easy as it is also called a "sum". There is a built-in function for this in python : http://docs.python.org/library/functions.html#sum

As for the formula you provide, I think that what you really miss here are lists or arrays. i, j and k can be indices of n-dimensional arrays. I would use the numpy package for this :

import numpy as np

c = np.asarray(values_2)
s = np.asarray(values_3)
x = np.asarray(values_4)

def V(j, k):
    return np.sum(c * s * (np.abs(x - x[j]) - np.abs(x - x[k])) / np.abs(x[-1] - x[0]))

Here Bob and Sue are encoded by there indice position in the values_1 list. This makes it way easier than working with strings or class instances. So you would write :

v_Bob_Sue = V(0, 1)

If you want to automagically create the variables v_Bob_Sue and such you need to define variable names dynamically. So you need the exec statment as follows :

for i in xrange(len(values_1)):
    for j in xrange(len(values_1)):
        exec("v_%s_%s = V(%u, %u)" % (values_1[i], values_1[j], i, j)
like image 125
Nicolas Barbey Avatar answered Oct 19 '22 02:10

Nicolas Barbey