I think this will be a pretty hard or even impossible question. I have some code here that is build around my scenario describet here.
I took that python code and translated it into lua code but then I spottet an error I made.
If the code is used for a list of ~10 weigths it will work fine but in my case I have lists with up to 60 weights. the code generates an array with all possible bitstrings of length n. and with n = 60 this array would be 2^60 large and that is way to much.
Is there any way to calculate this without generation such a large array? My final code will be in lua but if you know a solution in any other language it will be fine to, I can still translate it later.
python code:
from math import prod
def bitstrings(n) :
"""Return all possible bitstrings of length n"""
if n == 0 :
yield []
return
else :
for b in [0,1] :
for x in bitstrings(n-1) :
yield [b] + x
def prob_selected(weights, num_selected = 5) :
# P(n generated, including e)*P(e of n selected | n generated including e)
# i.e. Sum_n (n generated, including e) * #num_selections / #generated
# num_selected = how many will be drawn out of the hat (at most)
n = len(weights)
final_probability = [0] * n
for bits in bitstrings(n) :
num_generated = sum(bits)
prob_generated = prod([w if b else (1-w) for (w,b) in zip(weights, bits)])
for i in range(n) :
if bits[i] :
final_probability[i] += prob_generated * min(num_selected, num_generated) / num_generated
return final_probability
print(prob_selected([1, 1, 1, 1, 1,
0.5, 0.2, 0.8, 0.9, 0.1]))
lua code:
-- python sum()
table.reduce = function (list, fn)
local acc
for k, v in ipairs(list) do
if 1 == k then
acc = v
else
acc = fn(acc, v)
end
end
return acc
end
local function generateBitstrings (global_arr, n, arr, i)
if i == n then
table.insert(global_arr, {table.unpack(arr)})
return
end
arr[i] = 0
generateBitstrings(global_arr, n, arr, i + 1)
arr[i] = 1
generateBitstrings(global_arr, n, arr, i + 1)
end
local function prob_selected (weights, num_selected)
local n = #weights
local final_probability = {}
for i=1, n do
final_probability[i] = 0
end
local globalArr = {}
generateBitstrings(globalArr, n + 1, {}, 1)
for ibots, bits in ipairs(globalArr) do
local num_generated = table.reduce(
bits,
function(a, b)
return a + b
end
)
local prob_generated = 1
local bitsLength = #bits
for i=1,bitsLength do
if bits[i] == 1 then
prob_generated = prob_generated * weights[i]
else
prob_generated = prob_generated * (1 - weights[i])
end
end
for i=1,n do
if bits[i] == 1 then
final_probability[i] = final_probability[i] + (prob_generated * math.min(num_selected, num_generated) / num_generated)
end
end
end
return final_probability
end
print (table.concat (prob_selected({1, 1, 1, 1, 1,0.5, 0.2, 0.8, 0.9, 0.1}, 5), ', '))