HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonModerate

ALOHA network simulation in Python

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
alohanetworkpythonsimulation

Problem

I'm currently studying the book
From Algorithms to Z-Scores: Probabilistic and Statistical Modelling in Computer Science

In the first chapter of the book the ALOHA network protocol is introduced as an example of probabilistic modelling. I decided to write a python simulation and run some tests to check the overall performance of a network of this type (latency, successful transmission/accuracy).

```
import random
class aloha():
'''
Aloha network simulation.
Each node tries to send into a single channel. It generates a message (becomes active)
with probability q. Then it tries to send the message into the channel with probability
p. If more than one nodes try to send, a collision occurs resulting to failure, otherwise
transmission is successful.
'''

def __init__(self, nodes,p_send,q_generate,epochs):
# number of nodes
self.nodes = nodes

# probability that an active node will send the generated message
self.p_send = p_send

# probability that a node will generate a message
self.q_generate = q_generate

# number of time steps to simulate
self.epochs = epochs

# list with the state of each node, initially all inactive
self.states = [False for i in range(self.nodes)]

# list of latencies for each node
self.latencies = [0 for i in range(self.nodes)]

# list of transmission outcomes. True for success
self.result = []

def message_generation(self):
'''
Helper function to check message generation
'''
for i in range(len(self.states)):
# need only to check for inactive nodes
if self.states[i] == False:
if random.random() 1:
self.result.append(False)
# so any active node experiences latency
for active in actives:
self.latencies[active] += 1
else:
# If none wants to send then cert

Solution

Lists of the same primitive elements

Instead of this:

# list with the state of each node, initially all inactive
self.states = [False for i in range(self.nodes)]

# list of latencies for each node 
self.latencies = [0 for i in range(self.nodes)]


A more compact and simpler way to create lists of the same primitive elements:

# list with the state of each node, initially all inactive
self.states = [False] * self.nodes

# list of latencies for each node 
self.latencies = [0] * self.nodes


Just be mindful that this technique is useful with primitive elements only.

Use boolean expressions directly

This is not natural writing style:

if self.states[i] == False:
    # ...

if self.states[i] == True:
    # ...


This is the recommended way:

if not self.states[i]:
    # ...

if self.states[i]:
    # ...


Non-empty lists are truthy, empty lists are falsy

Instead of this:

if (len(senders) == 0):
    # ...


You can write:

if not senders:
    # ...


Use list comprehensions

Instead of this:

actives = []

# gather the indices of all active nodes
for i in range(len(self.states)):
    if self.states[i] == True:
        actives.append(i)


You can write more compactly using a list comprehension like this:

# gather the indices of all active nodes
actives = [i for i in range(len(self.states)) if self.states[i]]


You can do similarly for senders.

Iterating over indexes and values of a list

enumerate is very convenient when iterating over list indexes and values.
For example instead of this:

# gather the indices of all active nodes
actives = [i for i in range(len(self.states)) if self.states[i]]


You can write more compactly and naturally like this:

# gather the indices of all active nodes
actives = [i for i, state in enumerate(self.states) if state]


Coding style

Python has an official style guide called PEP8.
I suggest to follow it.

Code Snippets

# list with the state of each node, initially all inactive
self.states = [False for i in range(self.nodes)]

# list of latencies for each node 
self.latencies = [0 for i in range(self.nodes)]
# list with the state of each node, initially all inactive
self.states = [False] * self.nodes

# list of latencies for each node 
self.latencies = [0] * self.nodes
if self.states[i] == False:
    # ...

if self.states[i] == True:
    # ...
if not self.states[i]:
    # ...

if self.states[i]:
    # ...
if (len(senders) == 0):
    # ...

Context

StackExchange Code Review Q#139923, answer score: 11

Revisions (0)

No revisions yet.