Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

348

349

350

351

352

353

354

355

356

357

358

359

360

361

362

363

364

365

366

367

368

369

370

371

372

373

374

# Copyright (C) 2011, 2012, 2014 Ben Elliston 

# Copyright (C) 2014 The University of New South Wales 

# 

# This file is free software; you can redistribute it and/or modify it 

# under the terms of the GNU General Public License as published by 

# the Free Software Foundation; either version 3 of the License, or 

# (at your option) any later version. 

 

"""A National Electricity Market (NEM) simulation.""" 

import re 

 

import datetime as dt 

import matplotlib.dates as mdates 

import matplotlib.pyplot as plt 

import numpy as np 

from matplotlib.patches import Patch 

from itertools import groupby 

 

import configfile 

import consts 

import generators 

import regions 

 

# Demand is in 30 minute intervals. NOTE: the number of rows in the 

# demand file now dictates the number of timesteps in the simulation. 

 

# Generate a list of column numbers from [2, 4, .., 2*n] 

# (ignore RRP columns) 

columns = [(elt * 2) + 2 for elt in range(regions.numregions)] 

cols = (0, 1) + tuple(columns) 

demand = np.genfromtxt(configfile.get('demand', 'demand-trace'), comments='#', usecols=cols) 

demand = demand.transpose() 

 

# Check for date, time and n demand columns (for n regions). 

assert demand.shape[0] == 2 + regions.numregions, demand.shape[0] 

# The number of rows must be even. 

assert demand.shape[1] % 2 == 0, "odd number of rows in half-hourly demand data" 

 

# Find the start date of the demand data. 

f = open(configfile.get('demand', 'demand-trace')) 

for line in f: 

    if re.search(r'^\s*#', line): 

        continue 

    cols = line.split() 

    year, month, day = cols[0].split('/') 

    startdate = dt.datetime(int(year), int(month), int(day)) 

    assert cols[1] == '00:30:00', 'demand data must start at midnight' 

    break 

f.close() 

 

# For hourly demand, average half-hours n and n+1. 

# Demand is in every second column from columns 2 onwards. 

hourly_demand = (demand[2::, ::2] + demand[2::, 1::2]) / 2 

assert hourly_demand.shape[0] == regions.numregions 

 

 

def default_generation_mix(): 

    """Return a default generator list. 

 

    >>> g = default_generation_mix() 

    >>> len(g) 

    2 

    """ 

    return [generators.CCGT(regions.nsw, 20000), 

            generators.OCGT(regions.nsw, 20000)] 

 

 

# Context objects are used throughout this module. 

class Context: 

 

    """All state is kept in a Context object.""" 

 

    def __init__(self): 

        """Initialise a default context.""" 

        self.verbose = False 

        self.track_exchanges = False 

        self.regions = regions.All 

        self.startdate = startdate 

        # Number of timesteps is determined by the number of demand rows. 

        self.hours = demand.shape[1] / 2 

        # Estimate the number of years from the number of simulation hours. 

        if self.hours == 8760 or self.hours == 8784: 

            self.years = 1 

        else: 

            self.years = self.hours / (365.25 * 24) 

        # NEM standard: 0.002% unserved energy 

        self.relstd = 0.002 

        self.generators = default_generation_mix() 

        self.demand = hourly_demand.copy() 

        self.timesteps = self.demand.shape[1] 

        self.unserved = [] 

        self.unserved_energy = 0 

        self.unserved_hours = 0 

        self.unserved_percent = 0 

        # System non-synchronous penetration limit 

        self.nsp_limit = consts.nsp_limit 

        self.exchanges = np.zeros((self.hours, regions.numregions, regions.numregions)) 

 

    def __str__(self): 

        """A human-readable representation of the context.""" 

        s = "" 

        if self.regions != regions.All: 

            s += 'Regions: ' + str(self.regions) + '\n' 

        if self.verbose: 

            s += 'Generators:' + '\n' 

            for g in self.generators: 

                s += '\t' + str(g) 

                if g.summary(self.costs) is not None: 

                    s += '\n\t   ' + g.summary(self.costs) + '\n' 

                else: 

                    s += '\n' 

        s += 'Timesteps: %d h\n' % self.hours 

        s += 'Demand energy: %.1f TWh\n' % (self.demand.sum() / consts.twh) 

        try: 

            s += 'Spilled energy: %.1f TWh\n' % (self.spill.sum() / consts.twh) 

            if self.spill.sum() > 0: 

                s += 'Spilled hours: %d\n' % (self.spill.sum(axis=0) > 0).sum() 

        except AttributeError: 

            # there may be no 'spill' attribute yet 

            pass 

 

        if self.unserved_energy == 0: 

            s += 'No unserved energy' 

        elif self.unserved_energy > 0: 

            s += 'Unserved energy: %.3f%%' % self.unserved_percent + '\n' 

            if self.unserved_percent > self.relstd: 

                s += 'WARNING: NEM reliability standard exceeded\n' 

            s += 'Unserved total hours: ' + str(self.unserved_hours) + '\n' 

            unserved_events = [g for g, v in groupby(self.unserved, lambda x: bool(x) is True) if g] 

            s += 'Number of unserved energy events: ' + str(len(unserved_events)) + '\n' 

            s += 'min, max shortfalls: ' + str(self.shortfalls) 

        return s 

 

 

def _sim(context, starthour, endhour): 

    # reset generator internal state 

    for g in context.generators: 

        g.reset() 

 

    context.exchanges.fill(0) 

    context.generation = np.zeros((len(context.generators), context.hours)) 

    context.lowest_merit_generator = np.zeros(context.hours, dtype=object) 

    context.spill = np.zeros((len(context.generators), context.hours)) 

 

    # Extract generators in the regions of interest. 

    gens = [g for g in context.generators if g.region in context.regions] 

    # And storage-capable generators. 

    storages = [g for g in gens if g.storage_p] 

 

    connections = {} 

    c = regions.connections 

    for r in context.regions: 

        connections[r] = [] 

        for (src, dest), path in zip(c.keys(), c.values()): 

            if src is r and dest in context.regions and regions.in_regions_p(path, context.regions): 

                connections[r].append(path) 

        connections[r].sort() 

        connections[r].sort(key=len) 

 

    assert context.demand.shape == (regions.numregions, context.timesteps) 

 

    # Zero out regions we don't care about. 

    for rgn in [r for r in regions.All if r not in context.regions]: 

        context.demand[rgn] = 0 

 

    # We are free to scribble all over demand_copy. 

    demand_copy = context.demand.copy() 

 

    for hr in xrange(starthour, endhour): 

        hour_demand = demand_copy[::, hr] 

        residual_hour_demand = hour_demand.sum() 

        async_demand = residual_hour_demand * context.nsp_limit 

 

        if context.verbose: 

            print 'hour', hr, 'demand:', hour_demand 

 

        # Dispatch power from each generator in merit order 

        for gidx, g in enumerate(gens): 

            if g.non_synchronous_p and async_demand < residual_hour_demand: 

                gen, spl = g.step(hr, async_demand) 

            else: 

                gen, spl = g.step(hr, residual_hour_demand) 

            assert gen <= residual_hour_demand, \ 

                "generation (%.2f) > demand (%.2f) for %s" % (gen, residual_hour_demand, g) 

            context.generation[gidx, hr] = gen 

            if gen == 0: 

                continue 

 

            if g.non_synchronous_p: 

                async_demand -= gen 

                assert async_demand > -0.1 

                async_demand = max(0, async_demand) 

 

            # This assumes a generator's opcosts are the same year 

            # round, but OK for now. 

            context.lowest_merit_generator[hr] = g 

 

            residual_hour_demand -= gen 

            # residual can go below zero due to rounding 

            assert residual_hour_demand > -0.1 

            residual_hour_demand = max(0, residual_hour_demand) 

 

            if context.verbose: 

                print 'GENERATOR:', g, 'generation =', context.generation[gidx, hr], 'spill =', \ 

                    spl, 'residual demand =', residual_hour_demand, 'async demand =', async_demand 

 

            # distribute the generation across the regions (local region first) 

 

            if context.track_exchanges: 

                paths = connections[g.region] 

                if context.verbose: 

                    print 'PATHS:', paths 

                for path in paths: 

                    if not gen: 

                        break 

 

                    rgn = g.region if len(path) is 0 else path[-1][-1] 

                    rgnidx = rgn.num 

                    transfer = gen if gen < hour_demand[rgnidx] else hour_demand[rgnidx] 

 

                    if transfer > 0: 

                        if context.verbose: 

                            print 'dispatch', int(transfer), 'to', rgn 

                        if rgn is g.region: 

                            context.exchanges[hr, rgnidx, rgnidx] += transfer 

                        else: 

                            # dispatch to another region 

                            for src, dest in path: 

                                context.exchanges[hr, src, dest] += transfer 

                                if context.verbose: 

                                    print src, '->', dest, '(%d)' % transfer 

                                    assert regions.direct_p(src, dest) 

                        hour_demand[rgnidx] -= transfer 

                        gen -= transfer 

 

            if spl > 0: 

                for other in storages: 

                    stored = other.store(hr, spl) 

                    spl -= stored 

                    assert spl >= 0 

 

                    # show the energy transferred, not stored (this is where the loss is handled) 

                    if context.verbose: 

                        print 'STORE:', g.region, '->', other.region, '(%.1f)' % stored 

                    for src, dest in regions.path(g.region, other.region): 

                        context.exchanges[hr, src, dest] += stored 

            context.spill[gidx, hr] = spl 

 

        if context.verbose: 

            if (hour_demand > 0).any(): 

                print 'hour', hr, 'residual:', hour_demand 

    return context 

 

 

def _generator_list(context): 

    """Return a list of the generators of interest in this run.""" 

    return [g for g in context.generators if g.region in context.regions and g.capacity > 0] 

 

 

def plot(context, spills=False, filename=None): 

    """Produce a pretty plot of supply and demand.""" 

    spill = context.spill 

    # aggregate demand 

    demand = context.demand.sum(axis=0) 

 

    plt.ylabel('Power (MW)') 

    title = 'Supply/demand balance\nRegions: %s' % context.regions 

    plt.suptitle(title) 

 

    # The ::-1 slicing reverses the 'gens' list so that the legend 

    # appears in "merit order". 

    gen_list = _generator_list(context)[::-1] 

 

    if len(gen_list) > 25: 

        unique = [] 

        keep = [] 

        for g in gen_list: 

            if g.__class__ not in unique: 

                unique.append(g.__class__) 

                # Replace the generator label with its class type. 

                g.label = str(g.__class__).strip('<>').split()[0].split('.')[1] 

                keep.append(g) 

        gen_list = keep 

 

    legend = plt.figlegend([Patch('black', 'red')] + 

                           [g.patch for g in gen_list], 

                           ['unserved'] + [g.label + ' (%.1f GW)' % (g.capacity / 1000.) for g in gen_list], 

                           'upper right') 

    plt.setp(legend.get_texts(), fontsize='small') 

    xdata = mdates.drange(context.startdate, 

                          context.startdate + dt.timedelta(hours=context.hours), 

                          dt.timedelta(hours=1)) 

 

    # Plot demand first. 

    plt.plot(xdata, demand, color='black', linewidth=2) 

    if spills: 

        peakdemand = np.empty_like(demand) 

        peakdemand.fill(demand.max()) 

        plt.plot(xdata, peakdemand, color='black', linestyle='dashed') 

 

    accum = np.zeros(context.timesteps) 

    prev = accum.copy() 

    for g in _generator_list(context): 

        idx = context.generators.index(g) 

        accum += context.generation[idx] 

        # Ensure total generation does not exceed demand in any timestep. 

        assert(np.round(accum, 6) > np.round(demand, 6)).sum() == 0 

        plt.plot(xdata, accum, color='black', linewidth=0.5) 

        plt.fill_between(xdata, prev, accum, facecolor=g.patch.get_fc()) 

        prev = accum.copy() 

    # Unmet demand is shaded red. 

    plt.fill_between(xdata, accum, demand, facecolor='red') 

 

    if spills: 

        prev = demand.copy() 

        for g in [g for g in context.generators if g.region in context.regions]: 

            idx = context.generators.index(g) 

            accum += spill[idx] 

            plt.plot(xdata, accum, color='black') 

            plt.fill_between(xdata, prev, accum, facecolor=g.patch.get_fc(), alpha=0.3) 

            prev = accum.copy() 

 

    plt.gca().xaxis_date() 

    plt.gcf().autofmt_xdate() 

 

    for hr in np.argwhere(context.unserved): 

        unserved_dt = context.startdate + dt.timedelta(hours=hr[0]) 

        xvalue = mdates.date2num(unserved_dt) 

        _, ymax = plt.gca().get_ylim() 

        plt.plot([xvalue], [ymax - 200], "yv", markersize=15, color='red') 

 

    if not filename: 

        plt.show()  # pragma: no cover 

    else: 

        plt.savefig(filename) 

 

 

def run(context, starthour=0, endhour=None): 

    """Run the simulation (without a plot). 

 

    >>> c = Context() 

    >>> c.regions = None 

    >>> run(c) 

    Traceback (most recent call last): 

      ... 

    ValueError: regions is not a list 

    """ 

    if not isinstance(context.regions, list): 

        raise ValueError('regions is not a list') 

 

    if endhour is None: 

        endhour = context.timesteps 

 

    _sim(context, starthour, endhour) 

 

    # Calculate some summary statistics. 

    agg_demand = context.demand.sum(axis=0) 

    context.accum = context.generation.sum(axis=0) 

    context.unserved_energy = (agg_demand - context.accum).sum() 

    context.unserved_energy = max(0, round(context.unserved_energy, 0)) 

    context.unserved = (agg_demand - context.accum) > 0.1 

    context.unserved_hours = context.unserved.sum() 

    total_demand = agg_demand.sum() 

    if total_demand > 0: 

        context.unserved_percent = context.unserved_energy / agg_demand.sum() * 100 

    else: 

        context.unserved_percent = 0. 

 

    shortfall = [agg_demand[hr] - context.accum[hr] 

                 for hr in np.argwhere(context.unserved)] 

    if len(shortfall) == 0: 

        context.shortfalls = (None, None) 

    else: 

        context.shortfalls = (round(min(shortfall)), round(max(shortfall)))