Power flow calculation program-sparse technology (2)-storage format by row (column)

Row (column) storage format

Insert picture description here
Insert picture description here

import numpy as np
import random
from matplotlib import pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus'] = False
# matplotlib画图中中文显示会有问题,需要这两行设置默认字体


def sanju(A):
    VA = []
    IA = []
    JA = []
    for i in range(A.shape[0]):
        for j in range(A.shape[1]):
            if A[i, j] != 0:
                VA.append(i)
                IA.append(j)
                JA.append(A[i, j])
    print(VA, '\n', IA, '\n', JA, '\n')
    return VA, IA, JA


def anrows(A):
    VA = []
    JA = []
    IA = [0 for i in range(A.shape[0])]
    count = 0
    for i in range(A.shape[0]):
        cs = count
        f2 = 0
        count = 0
        for j in range(A.shape[1]):
            if A[i, j] != 0:
                count = count + 1
                VA.append(A[i, j])
                JA.append(j)
                f2 = 1  # 检测是否有非零元素,如果有,1,没有,0;
        if i > 0 and IA[i - 1] > 0:
            IA[i] = IA[i - 1] + cs
        elif i > 0 and IA[i - 1] == 0 and f2 == 1:
            IA[i] = 1
        elif f2 == 1 and i == 0:
            IA[i] = 1
        elif f2 == 0 and i == 0:
            IA[i] = 0
    c = [i for i in range(A.shape[0])]
    for i in range(A.shape[0]-1):
        for j in range(IA[i], IA[i + 1]):
            if IA[i] > 0:
                print(f'({i}, {JA[j-1]}):{VA[j - 1]} ', end='  ')
        print('')
    i = i + 1
    for j in range(IA[i], len(VA)+1):
        if IA[i] > 0:
            print(f'({i}, {JA[j-1]}):{VA[j - 1]} ', end='  ')
    print('')
    return VA, JA, IA


A = np.mat(np.zeros((10, 10)))
for i in range(100):
    a = random.randint(0, 9)
    b = random.randint(0, 9)
    A[a, b] = a*b
VAa, JAa, IAa = anrows(A)
print(A)

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_40653652/article/details/110087059