Beispiel #1
0
def get_connectivity(file_name):

    circuit = MultiCircuit()
    circuit.load_file(file_name)
    circuit.compile()

    # form C
    threshold = 1e-5
    m = len(circuit.branches)
    n = len(circuit.buses)
    C = lil_matrix((m, n), dtype=int)
    buses_dict = {bus: i for i, bus in enumerate(circuit.buses)}
    branches_to_keep_idx = list()
    branches_to_remove_idx = list()
    states = np.zeros(m, dtype=int)
    br_idx = [None] * m

    graph = Graph()

    for i in range(len(circuit.branches)):
        # get the from and to bus indices
        f = buses_dict[circuit.branches[i].bus_from]
        t = buses_dict[circuit.branches[i].bus_to]
        graph.add_edge(f, t)
        C[i, f] = 1
        C[i, t] = -1
        br_idx[i] = i
        rx = circuit.branches[i].R + circuit.branches[i].X

        if circuit.branches[i].branch_type == BranchType.Branch:
            branches_to_remove_idx.append(i)
            states[i] = 0
        else:
            branches_to_keep_idx.append(i)
            states[i] = 1

    C = csc_matrix(C)

    return circuit, states, C, C.transpose() * C, graph
Beispiel #2
0
    cols = ['Type', 'P', 'Q', '|V|', 'angle']
    df = pd.DataFrame(data=data, columns=cols)

    return df


if __name__ == '__main__':
    from GridCal.Engine.CalculationEngine import MultiCircuit, PowerFlowOptions, PowerFlow, SolverType
    from matplotlib import pyplot as plt

    grid = MultiCircuit()
    # grid.load_file('lynn5buspq.xlsx')
    # grid.load_file('lynn5buspv.xlsx')
    # grid.load_file('IEEE30.xlsx')
    grid.load_file(
        '/home/santi/Documentos/GitHub/GridCal/Grids_and_profiles/grids/IEEE 14.xlsx'
    )
    # grid.load_file('/home/santi/Documentos/GitHub/GridCal/Grids_and_profiles/grids/IEEE39.xlsx')
    # grid.load_file('/home/santi/Documentos/GitHub/GridCal/Grids_and_profiles/grids/1354 Pegase.xlsx')

    grid.compile()

    circuit = grid.circuits[0]

    print('\nYbus:\n', circuit.power_flow_input.Ybus.todense())
    print('\nSbus:\n', circuit.power_flow_input.Sbus)
    print('\nIbus:\n', circuit.power_flow_input.Ibus)
    print('\nVbus:\n', circuit.power_flow_input.Vbus)
    print('\ntypes:\n', circuit.power_flow_input.types)
    print('\npq:\n', circuit.power_flow_input.pq)
    print('\npv:\n', circuit.power_flow_input.pv)
Beispiel #3
0
def get_branches_of_bus(B, j):
    """
    Get the indices of the branches connected to the bus j
    :param B: Branch-bus CSC matrix
    :param j: bus index
    :return: list of branches in the bus
    """
    return [B.indices[k] for k in range(B.indptr[j], B.indptr[j + 1])]


if __name__ == '__main__':

    fname = 'D:\\GitHub\\GridCal\\Grids_and_profiles\\grids\\Reduction Model 2.xlsx'

    circuit = MultiCircuit()
    circuit.load_file(fname)
    circuit.compile()

    # form C
    threshold = 1e-5
    m = len(circuit.branches)
    n = len(circuit.buses)
    C = lil_matrix((m, n), dtype=int)
    buses_dict = {bus: i for i, bus in enumerate(circuit.buses)}
    branches_to_keep_idx = list()
    branches_to_remove_idx = list()
    states = np.zeros(m, dtype=int)
    br_idx = [None] * m

    graph = Graph()
Beispiel #4
0
                          index=self.numerical_circuit.branch_names,
                          columns=['Branch flow (MW)'])

        return df


if __name__ == '__main__':

    main_circuit = MultiCircuit()
    # fname = 'D:\\GitHub\\GridCal\\Grids_and_profiles\\grids\\lynn5buspv.xlsx'
    fname = 'D:\\GitHub\\GridCal\\Grids_and_profiles\\grids\\IEEE 30 Bus with storage.xlsx'
    # fname = 'C:\\Users\\spenate\\Documents\\PROYECTOS\\Sensible\\Report\\Test3 - Batteries\\Evora test 3 with storage.xlsx'
    # fname = '/home/santi/Documentos/GitHub/GridCal/Grids_and_profiles/grids/IEEE 30 Bus with storage.xlsx'

    print('Reading...')
    main_circuit.load_file(fname)

    problem = DcOpf(main_circuit,
                    allow_load_shedding=True,
                    allow_generation_shedding=True)

    # run default state
    problem.build_solvers()
    problem.set_default_state()
    problem.solve(verbose=True)
    problem.save()

    res_df = problem.get_gen_results_df()
    print(res_df)

    res_df = problem.get_voltage_results_df()
    return df


if __name__ == '__main__':
    from GridCal.Engine.CalculationEngine import MultiCircuit, PowerFlowOptions, PowerFlow, SolverType
    from matplotlib import pyplot as plt

    grid = MultiCircuit()
    # grid.load_file('lynn5buspq.xlsx')
    # grid.load_file('lynn5buspv.xlsx')
    # grid.load_file('IEEE30.xlsx')
    # grid.load_file('/home/santi/Documentos/GitHub/GridCal/Grids_and_profiles/grids/IEEE 14.xlsx')
    # grid.load_file('/home/santi/Documentos/GitHub/GridCal/Grids_and_profiles/grids/IEEE39.xlsx')
    # grid.load_file('/home/santi/Documentos/GitHub/GridCal/Grids_and_profiles/grids/1354 Pegase.xlsx')
    grid.load_file(
        '/home/santi/Documentos/GitHub/GridCal/UnderDevelopment/GridCal/Monash2.xlsx'
    )

    grid.compile()

    circuit = grid.circuits[0]

    print('\nYbus:\n', circuit.power_flow_input.Ybus.todense())
    print('\nSbus:\n', circuit.power_flow_input.Sbus)
    print('\nIbus:\n', circuit.power_flow_input.Ibus)
    print('\nVbus:\n', circuit.power_flow_input.Vbus)
    print('\ntypes:\n', circuit.power_flow_input.types)
    print('\npq:\n', circuit.power_flow_input.pq)
    print('\npv:\n', circuit.power_flow_input.pv)
    print('\nvd:\n', circuit.power_flow_input.ref)
Beispiel #6
0
class Blockchain:

    def __init__(self, agent_id_to_grid_id, fname='Grid.xlsx', dt=1):
        self.current_transactions = Transactions()
        self.chain = []
        self.nodes = set()

        self.agent_id_to_grid_id = agent_id_to_grid_id

        self.actors_group = ActorsGroup()

        self.market = Market(actors_group=self.actors_group)

        self.dt = dt

        self.grid = MultiCircuit()
        self.grid.load_file(fname)

        # Create the genesis block
        self.new_block(previous_hash='1', proof=100)

    def register_node(self, address):
        """
        Add a new node to the list of nodes

        :param address: Address of node. Eg. 'http://192.168.0.5:5000'
        """

        parsed_url = urlparse(address)
        if parsed_url.netloc:
            self.nodes.add(parsed_url.netloc)
        elif parsed_url.path:
            # Accepts an URL without scheme like '192.168.0.5:5000'.
            self.nodes.add(parsed_url.path)
        else:
            raise ValueError('Invalid URL')


    def valid_chain(self, chain):
        """
        Determine if a given blockchain is valid

        :param chain: A blockchain
        :return: True if valid, False if not
        """

        last_block = chain[0]
        current_index = 1

        while current_index < len(chain):
            block = chain[current_index]
            print(f'{last_block}')
            print(f'{block}')
            print("\n-----------\n")
            # Check that the hash of the block is correct
            last_block_hash = self.hash(last_block)
            if block['previous_hash'] != last_block_hash:
                return False

            # Check that the Proof of Work is correct
            if not self.valid_proof(last_block['proof'], block['proof'], last_block_hash):
                return False

            last_block = block
            current_index += 1

        return True

    def resolve_conflicts(self):
        """
        This is our consensus algorithm, it resolves conflicts
        by replacing our chain with the longest one in the network.

        :return: True if our chain was replaced, False if not
        """

        neighbours = self.nodes
        new_chain = None

        # We're only looking for chains longer than ours
        max_length = len(self.chain)

        # Grab and verify the chains from all the nodes in our network
        for node in neighbours:
            response = requests.get(f'http://{node}/chain')

            if response.status_code == 200:
                length = response.json()['length']
                chain = response.json()['chain']

                # Check if the length is longer and the chain is valid
                if length > max_length and self.valid_chain(chain):
                    max_length = length
                    new_chain = chain

        # Replace our chain if we discovered a new, valid chain longer than ours
        if new_chain:
            self.chain = new_chain
            return True

        return False

    def new_block(self, proof, previous_hash):
        """
        Create a new Block in the Blockchain

        :param proof: The proof given by the Proof of Work algorithm
        :param previous_hash: Hash of previous Block
        :return: New Block
        """

        block = {
            'index': len(self.chain) + 1,
            'timestamp': time(),
            'transactions': self.current_transactions,
            'proof': proof,
            'previous_hash': previous_hash or self.hash(self.chain[-1]),
        }

        # Reset the current list of transactions
        self.current_transactions = []

        self.chain.append(block)
        return block

    def new_transaction(self, sender, recipient, energy_amount, price, bid_type, electric_hash):
        """
        Creates a new transaction to go into the next mined Block

        :param sender: Address of the Sender
        :param recipient: Address of the Recipient
        :param amount: Amount
        :return: The index of the Block that will hold this transaction
        """

        tr = Transaction(bid_id=len(self.current_transactions),   # this may be repeated but it is only used to print
                         seller_id=sender, buyer_id=recipient, energy_amount=energy_amount,
                         price=price, bid_type=bid_type, bid_hash=electric_hash)

        # self.current_transactions.append({
        #     'sender': sender,
        #     'recipient': recipient,
        #     'energy_amount': energy_amount,
        #     'price': price,
        #     'bid_type': bid_type,
        #     'electric_hash': electric_hash
        # })

        self.current_transactions.append(tr)

        return self.last_block['index'] + 1

    @property
    def last_block(self):
        return self.chain[-1]

    @staticmethod
    def hash(block):
        """
        Creates a SHA-256 hash of a Block

        :param block: Block
        """

        # We must make sure that the Dictionary is Ordered, or we'll have inconsistent hashes
        # block_string = json.dumps(block, sort_keys=True).encode()
        block_string = str(block['index']) + \
                       str(block['timestamp']) + \
                       str(block['proof']) + \
                       str(block['previous_hash']) + \
                       str([j.hash for j in block['transactions']])
        # block_string = block.

        # block_string = block.to_json()

        return hashlib.sha256(block_string.encode('UTF-8')).hexdigest()


    @staticmethod
    def valid_proof( proof ):
        """
        Validates the Proof

        :param proof: <int> Current Proof
        :return: <bool> True if correct, False if not.

        """

        return proof != None
Beispiel #7
0
import pandas as pd
import numpy as np
from scipy.sparse import lil_matrix, csc_matrix

pd.set_option('display.max_rows', 500)
pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 1000)

file_name = 'D:\\GitHub\\GridCal\\Grids_and_profiles\\grids\\Reduction Model 2.xlsx'

from GridCal.Engine.CalculationEngine import MultiCircuit, BranchType

circuit = MultiCircuit()

circuit.load_file(file_name)

circuit.compile()

# form C
threshold = 1e-5
m = len(circuit.branches)
n = len(circuit.buses)
C = lil_matrix((m, n), dtype=int)
buses_dict = {bus: i for i, bus in enumerate(circuit.buses)}
branches_to_keep_idx = list()
branches_to_remove_idx = list()
states = np.zeros(m, dtype=int)
br_idx = [None] * m
for i in range(len(circuit.branches)):
    # get the from and to bus indices
    f = buses_dict[circuit.branches[i].bus_from]
Beispiel #8
0

########################################################################################################################
#  MAIN
########################################################################################################################
if __name__ == "__main__":
    from GridCal.Engine.CalculationEngine import MultiCircuit, PowerFlowOptions, PowerFlow, SolverType
    import pandas as pd

    pd.set_option('display.max_rows', 500)
    pd.set_option('display.max_columns', 500)
    pd.set_option('display.width', 1000)

    grid = MultiCircuit()
    # grid.load_file('lynn5buspq.xlsx')
    grid.load_file('IEEE30.xlsx')
    # grid.load_file('/home/santi/Documentos/GitHub/GridCal/Grids_and_profiles/grids/IEEE 145 Bus.xlsx')
    grid.compile()

    circuit = grid.circuits[0]

    print('\nYbus:\n', circuit.power_flow_input.Ybus.todense())
    print('\nYseries:\n', circuit.power_flow_input.Yseries.todense())
    print('\nYshunt:\n', circuit.power_flow_input.Yshunt)
    print('\nSbus:\n', circuit.power_flow_input.Sbus)
    print('\nIbus:\n', circuit.power_flow_input.Ibus)
    print('\nVbus:\n', circuit.power_flow_input.Vbus)
    print('\ntypes:\n', circuit.power_flow_input.types)
    print('\npq:\n', circuit.power_flow_input.pq)
    print('\npv:\n', circuit.power_flow_input.pv)
    print('\nvd:\n', circuit.power_flow_input.ref)