Back to Portfolio
Source Code
Python Implementations
Complete source code for the Markov chain simulations, including app navigation modeling and the PageRank algorithm.
App Navigation Simulation
By Basmala Refaat Mohamed Azab
Simulates user navigation through app screens using Markov chain principles. Calculates visit frequencies, drop-off points, and stationary distribution.
python
import random
import matplotlib.pyplot as plt
import numpy as np
states = ["Home", "Feed", "Profile", "Settings"]
# Transition probability matrix
P = [
[0.65, 0.20, 0.10, 0.05], # From Home
[0.30, 0.55, 0.10, 0.05], # From Feed
[0.25, 0.05, 0.50, 0.20], # From Profile
[0.70, 0.00, 0.20, 0.10] # From Settings
]
def simulate_user(start_index=0, max_steps=20):
"""Simulate a single user's journey through the app."""
current = start_index
journey = [states[current]]
for _ in range(max_steps):
r = random.random()
cumulative = 0
for i in range(len(states)):
cumulative += P[current][i]
if r <= cumulative:
current = i
break
journey.append(states[current])
if states[current] == "Settings":
break
return journey
def run_simulation(num_users=1000):
"""Run simulation for multiple users."""
visits = {state: 0 for state in states}
drop_off = {state: 0 for state in states}
steps_list = []
for _ in range(num_users):
journey = simulate_user()
steps_list.append(len(journey))
for page in journey:
visits[page] += 1
drop_off[journey[-1]] += 1
return visits, drop_off, steps_list
def stationary_distribution(P, tol=1e-6, max_iter=1000):
"""Calculate the stationary distribution."""
n = len(P)
dist = np.array([1/n]*n)
P_np = np.array(P)
for _ in range(max_iter):
new_dist = dist @ P_np
if np.linalg.norm(new_dist - dist) < tol:
return new_dist
dist = new_dist
return dist
# Run simulation
visits, drop_off, steps_list = run_simulation(1000)
print("Most Visited Pages:")
for k, v in visits.items():
print(f"{k}: {v}")
print("\nDrop-off Points:")
for k, v in drop_off.items():
print(f"{k}: {v}")
print(f"\nAverage steps per user: {sum(steps_list)/len(steps_list):.2f}")
stationary = stationary_distribution(P)
print("\nStationary Distribution (long-term probabilities):")
for state, prob in zip(states, stationary):
print(f"{state}: {prob:.3f}")PageRank Algorithm
By Shymaa Mohamed Ahmed
Implementation of Google's PageRank algorithm using power iteration method with damping factor.
python
import numpy as np
# Transition matrix representing link structure of 10 web pages
M = np.array([
[0, 1, 1/4, 1/4, 0, 0, 0, 0, 0, 1/10],
[0, 0, 0, 0, 1/2, 0, 0, 0, 0, 1/10],
[0, 0, 0, 0, 1/2, 0, 0, 0, 0, 1/10],
[0, 0, 1/4, 1/4, 0, 0, 0, 0, 0, 1/10],
[0, 0, 1/4, 0, 0, 1/2, 0, 0, 0, 1/10],
[0, 0, 0, 1/4, 0, 1/2, 0, 0, 0, 1/10],
[0, 0, 0, 0, 0, 0, 1/2, 0, 0, 1/10],
[0, 0, 0, 0, 0, 0, 1/2, 0, 1/2, 1/10],
[0, 0, 0, 0, 0, 0, 0, 1/2, 1/2, 1/10],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1/10]
])
damping = 0.85 # Damping factor (probability of following links)
N = 10 # Number of pages
R = np.ones(N) / N # Initial rank vector (uniform distribution)
# Power iteration method
for iteration in range(100):
# PageRank formula: PR(p) = (1-d)/N + d * M @ R
new_R = damping * (M @ R) + (1 - damping) / N
# Check for convergence
if np.linalg.norm(new_R - R) < 1e-9:
print(f"Converged after {iteration+1} iterations.")
break
R = new_R
# Display results
print("\n=== Final PageRank values ===")
for i, score in enumerate(R):
print(f"Page X{i+1}: {score:.6f}")
# Sort pages by rank
ranking = np.argsort(-R)
print("\n=== Ranking Order (Highest → Lowest) ===")
print([f"X{rank+1}" for rank in ranking])Running the Code
To run these simulations, ensure you have Python 3.x installed with NumPy and Matplotlib:
pip install numpy matplotlib