Handle dead-end situations by teleportation [Copilot Workspace] by sadrasabouri · Pull Request #20 · sadrasabouri/pyrandwalk

· GitHub

1 min read Original article ↗
Expand Up @@ -6,6 +6,7 @@ import numpy as np from numpy import linalg as la import networkx as nx import random

class RandomWalk(): Expand All @@ -27,7 +28,8 @@ def __init__( transitions, payoff=None, cost=None, discount=1): discount=1, jump_on_deadends=False): """ Init method.
Expand All @@ -41,6 +43,8 @@ def __init__( :type cost: list or np.array :param discount: discount which will be applied in each step :type discount: float :param jump_on_deadends: flag to enable teleportation on dead-end nodes :type jump_on_deadends: bool """ if not is_valid_vector_type(states): raise pyrandwalkStateError(INVALID_STATE_TYPE_ERROR) Expand All @@ -59,6 +63,7 @@ def __init__( if cost is None: cost = [0] * len(states) self.f, self.g, self.gamma = np.array(payoff), np.array(cost), discount self.jump_on_deadends = jump_on_deadends
def prob_sec(self, sequence, initial_dist=None): """ Expand Down Expand Up @@ -98,9 +103,13 @@ def run(self, ntimes=10, show=False): probabilities = [1 / len(self.S)] for i in range(ntimes): state_idx = self.S.index(state) next_state = np.random.choice(self.S, p=self.P[state_idx]) next_state_idx = self.S.index(next_state) probability = self.P[state_idx, next_state_idx] if self.jump_on_deadends and np.sum(self.P[state_idx]) == 0: next_state = random.choice(self.S) probability = 1 / len(self.S) else: next_state = np.random.choice(self.S, p=self.P[state_idx]) next_state_idx = self.S.index(next_state) probability = self.P[state_idx, next_state_idx] states.append(next_state) probabilities.append(probability) if show is True: Expand Down