microgrid_droopEq_dynamics.py 6.48 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
#from __future__ import division, print_function, absolute_import, unicode_literals

import numpy as np
from numba import njit
import os
from complex_current_and_nodes import DroopEquationNode, SwingEquationNode, define_network_rhs, define_network_rhs_codegen, define_root_rhs

try:
    import baobap as bao
except:
    ImportWarning("Cannot find pyBAOBAP")


default_dir = os.path.join("simulation_data", "microgrid")

def load_PYPSA(filename):
    """
    Loads the specified dataset and returns a (possibly sparse) matrix determining the network connections and their conductances, as well as a node_list of appropriate length. The nodes are of type DroopEquationNodes.
    :param filename: filename of the dataset
    :return: node_list, conductance matrix
    """
    #TODO replace constants with proper values. Attention: k_P,i != k_P,j & k_Q,i != k_Q,j - !!!remember: S^N = 1!!!
    data = np.load(filename)
    input_power = data['input_power']
    for p in input_power:
        print "{}".format(p)
    volt_droop_gain = 0.2 * input_power
    Y = data['Y']
    system_size = len(input_power)
    node_list = [DroopEquationNode(3, infeed=input_power[i], volt_droop_gain=0.1*input_power[i], freq_droop_gain=0.2*input_power[i]) for i in range(system_size)]
    return node_list,Y


def load_PyPSA_df(adm, par):
    #TODO: documentation
    """

    :param adm:
    :param par:
    :return:
    """
    from pandas import read_csv
    Y = np.load(adm)
    Y = Y[()] # this is import to recover a csr_matrix
    df = read_csv(par, index_col=0)
    system_size = df.shape[0]
    node_list = [DroopEquationNode(3, infeed=input_power[i], volt_droop_gain=0.1*input_power[i], freq_droop_gain=0.2*input_power[i]) for i in range(system_size)]
    load_flow_sol = np.zeros(3 * system_size, dtype=np.float64)
    load_flow_sol[:2*system_size] = np.array(df.v_pu.values * np.exp(1.j * df.phi.values), dtype=np.complex128).view(np.float64)
    return node_list, Y, load_flow_sol

def define_gen_rc(brp, rhs, init=None, method="krylov"):
    """

    :param brp: Variable holding the baobap batch run parameters(see: baobap.BatchRunParameters(...)).
    :param rhs: Function handle of function determining the behaviour of the network nodes.
    :param init: A vector of length 3 * brb.system_dimension, containing the initial guesses for the root finding algorithim.
    :param method: String detailing which root finding method to use. Must be one of those implemented in scipy.optimize.root(...).
    :return: returns a function handle to the function generate_run_conditions(batch, run)
    """
    system_size = brp.system_dimension
    if init is None:
        init = np.ones(3 * system_size, dtype=np.float64) * 0.5

    def generate_run_conditions(batch, run):
        """
Takes returns a vector of length
        :param batch:
        :param run: This seems to ne non-essential.
        :return:
        """
        root_rhs = define_root_rhs(2 * system_size, rhs)
        from scipy.optimize import root
        print "start root"
        result = root(root_rhs, init, method="{}".format(method))
        print "end root"
        if result.success:
            ic = result.x
            ic[2 * system_size + batch + 1] += .1 * (1. - 2. * np.random.random())
        else:
            print("failed")
            ic = init
        return ic, ()
    return generate_run_conditions


# This function observes the results of the simulation run and returns its observations in a dict
# noinspection PyUnusedLocal
def lorenz_ob(time_series, rc):
    return{"max_values": np.max(time_series, axis=0)}


def main(sim_dir=default_dir, create_test_data=True, run_test=True, flag_baobab=True):
    import time
    print "start", "{0.tm_year}-{0.tm_mon}.{0.tm_mday}.-{0.tm_hour}h{0.tm_min}m.timestamp".format(time.localtime(time.time()))

    node_list, Y = load_PYPSA('microgrid_testcase.npz')
    load_flow_sol = None
    # node_list, Y, load_flow_sol = load_PyPSA_df("bus_admittance.npy", "bus_parameters")
    # rhs = define_network_rhs(node_list, Y)
    rhs = define_network_rhs_codegen(node_list, Y)

    print "compilation finished", "{0.tm_year}-{0.tm_mon}.{0.tm_mday}.-{0.tm_hour}h{0.tm_min}m.timestamp".format(time.localtime(time.time()))

    if flag_baobab:
        # Run PYPSD code with BAOBAB
        np.random.seed(0)

        result_file, batch_dir = bao.prep_dir(sim_dir)
        times = np.linspace(0, 10, 100)
        brp = bao.BatchRunParameters(number_of_batches=10, simulations_per_batch=10, system_dimension=100)
        ob = bao.combine_obs(bao.run_condition_observer, lorenz_ob)
        bao.run_experiment(result_file, brp, None, define_gen_rc(brp, rhs), ob, times, figures=(True, 1), rhs=rhs)
        res = bao.load_all_fields_from_results(result_file)

        if bao.am_master:
            if create_test_data:
                for key in res.keys():
                    np.save(os.path.join(sim_dir, key), res[key])

            if run_test:
                for key in res.keys():
                    filename = key + ".npy"
                    with open(os.path.join(sim_dir, filename), mode='rb') as f:
                        arr = np.load(f)
                        assert np.allclose(arr, res[key])
    else:
        # Run Test PYPSD without BAOBAB
        times = np.linspace(0., 10., 100)
        from scipy.integrate import odeint

        brp = bao.BatchRunParameters(number_of_batches=1, simulations_per_batch=1, system_dimension=Y.shape[0])

        generate_run_conditions = define_gen_rc(brp, rhs, init=load_flow_sol, method="hybr")
        rc = generate_run_conditions(0, 0)
        print "generate_run_conditions", "{0.tm_year}-{0.tm_mon}.{0.tm_mday}.-{0.tm_hour}h{0.tm_min}m.timestamp".format(time.localtime(time.time()))

        #node_list[0].infeed += 0.1
        rhs = define_network_rhs(node_list, Y)
        print "define_network_rhs", "{0.tm_year}-{0.tm_mon}.{0.tm_mday}.-{0.tm_hour}h{0.tm_min}m.timestamp".format(time.localtime(time.time()))

        states = odeint(rhs, rc[0], times)
        print "integration", "{0.tm_year}-{0.tm_mon}.{0.tm_mday}.-{0.tm_hour}h{0.tm_min}m.timestamp".format(time.localtime(time.time()))

        import matplotlib.pyplot as plt
        from mpl_toolkits.mplot3d import Axes3D

        fig = plt.figure()
        ax = fig.gca(projection='3d')
        for k in range(3):
            ax.plot(states[:, k], states[:, brp.system_dimension+k], states[:, 2*brp.system_dimension+k])
        ax.set_xlabel(r"$\Re$ V")
        ax.set_ylabel(r"$\Im$ V")
        ax.set_zlabel(r"$\omega$")
        plt.show()


if __name__ == "__main__":
    main(flag_baobab=False)