Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

doomsday fuel foobar

import numpy as np

# Returns indexes of active & terminal states
def detect_states(matrix):
    active, terminal = [], []
    for rowN, row in enumerate(matrix):
        (active if sum(row) else terminal).append(rowN)
    return(active,terminal)

# Convert elements of array in simplest form
def simplest_form(B):
    B = B.round().astype(int).A1                   # np.matrix --> np.array
    gcd = np.gcd.reduce(B)
    B = np.append(B, B.sum())                      # append the common denom
    return (B / gcd).astype(int)

# Finds solution by calculating Absorbing probabilities
def solution(m):
    active, terminal = detect_states(m)
    if 0 in terminal:                              # special case when s0 is terminal
        return [1] + [0]*len(terminal[1:]) + [1]
    m = np.matrix(m, dtype=float)[active, :]       # list --> np.matrix (active states only)
    comm_denom = np.prod(m.sum(1))                 # product of sum of all active rows (used later)
    P = m / m.sum(1)                               # divide by sum of row to convert to probability matrix
    Q, R = P[:, active], P[:, terminal]            # separate Q & R
    I = np.identity(len(Q))
    N = (I - Q) ** (-1)                            # calc fundamental matrix
    B = N[0] * R * comm_denom / np.linalg.det(N)   # get absorbing probs & get them close to some integer
    return simplest_form(B)
Comment

PREVIOUS NEXT
Code Example
Python :: Python Selenium import WebElement 
Python :: delete rows in a table that are present in another table pandas 
Python :: python - how many letters are capital in a string 
Python :: Code of recursive binary search 
Python :: python string cut last character 
Python :: sklearn ridge regression 
Python :: python two string equal 
Python :: check auth user django 
Python :: how to write to a specific line in a file python 
Python :: find optimal number of clusters sklearn 
Python :: django templates 
Python :: how to download packages using pip 
Python :: pandas number format 
Python :: logical operators pandas 
Python :: python file write 
Python :: dictionary get all keys 
Python :: Simple Splash screen in pyqt5 
Python :: fibonacci number 
Python :: size pandas dataframe 
Python :: python node class 
Python :: python turn positive into negative 
Python :: python set with counts 
Python :: activate venv 
Python :: flask vs django 
Python :: python dataframe replace in all dataframe 
Python :: dict keys to list in python 
Python :: Python write value in next row of existing .text file 
Python :: sha256 python 
Python :: update xls file using python 
Python :: celery timezone setting django 
ADD CONTENT
Topic
Content
Source link
Name
6+5 =