-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxml_to_pypsa.py
1093 lines (962 loc) · 43 KB
/
xml_to_pypsa.py
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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2018-2019 Christian Brosig (TH Köln)
# This program 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.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
This package uses the xmlimport package to import electrical networks from
PSS Sincal into PyPSA. It also provides functions to test and repair the
network.
"""
import os
import pandas as pd
import numpy as np
import math
import pypsa
import networkx as nx
import pickle
from xmlimport import XMLimport
class ImporterXMLSincal():
"""
This class enables you to import xmls from PSS-Sincal into PyPSA.
It provides functions to read the data in, convert it, test it and also
to repair it if necessary.
Parameters
----------
list_file: (dict)
list with all xml-files needed with their name and index-column
+++
TODO: - provide more functions to facilitate repairing of data.
- clean up the code!
+++
"""
list_file = {'node': ['Node.xml', 'Node_ID'],
'terminal': ['Terminal.xml', 'Terminal_ID'],
'line': ['Line.xml', 'Element_ID'],
'element': ['Element.xml', 'Element_ID'],
'load': ['Load.xml', 'Element_ID'],
'graphicNode': ['GraphicNode.xml', 'Node_ID'],
'calcParameter': ['CalcParameter.xml', ],
'ecoStation': ['EcoStation.xml','EcoStation_ID'],
'breaker': ['Breaker.xml','Terminal_ID']}
def __init__(self, name, foldername, path=False):
"""
Initialization of the ImporterXMLSincal class.
Parameters
----------
name: string
Name of the network.
foldername: string
Name of the folder to import from.
+++
TODO: - imply a possibility to indicate paths different
from the basepath.
+++
"""
self.name = name
self.foldername = foldername
if path is False:
# Filepath of the programm
dname = os.path.dirname(os.path.realpath(__file__))
else:
dname = path
self.base_path = dname+'/'+foldername
def __repr__(self):
return 'ImporterXMLSincal(name: {}, folder: {})'.format(self.name,
self.foldername)
# %%
def import_xml(self):
xml = XMLimport(self.name,
foldername=self.foldername,
list_file=self.list_file,
path=self.base_path)
xml.xmltodfs()
self.xmls = xml.xmls
# %%
def export_xml_topickles(self, directory):
"""
Exports the dataframes to the indicated directory.
Parameters
----------
:directory (str):
name of directory to export pickle to
:self.list_file (dict):
+++
TODO: - check, if directory and files get overwritten and
imply a warning!
+++
"""
if not os.path.exists(directory):
os.makedirs(directory)
else:
print('path already exists - files might get overwritten!')
input("PRESS ENTER TO CONTINUE. TO ABORT PRESS CTRL+C!")
for name in self.list_file:
filename = directory+'/'+str(name)+'.p'
pickle.dump(self.xmls[name], open(filename, 'wb'))
def import_xml_frompickles(self, directory):
"""
Imports the dataframes from the indicated directory.
Parameters
----------
:directory (str):
name of directory to import pickle from
:self.list_file (dict):
indicates which files need to be imported
:self.xmls (dict):
dict with all imported dataframes
"""
self.xmls = {}
for name in self.list_file:
filename = directory+'/'+str(name)+'.p'
self.xmls[name] = pickle.load(open(filename, 'rb'))
def rawdataintegrity(self):
"""
Performs all the checks and repairs automatically...
+++
TODO: - Write the function!
- Create own functions for each check.
- Extend the ability for checking.
+++
"""
print('performing line-check...')
self.linecheck()
print('further dataintegrity-check still needs to be written...')
def linecheck(self):
"""
Check if the data from imported xml files is valid, or if there are
problems.
Problems being checked for, are:
- Elements (Lines), that connect more than one node.
This would raise an error in the import function.
+++
TODO: -maybe check if nodes are connected otherwise (see comment ins
function)
+++
"""
# Number of Nodes, that are connected by one element.
nofel = self.xmls['terminal'].Element_ID.value_counts()
# Sum of Elements (mostly lines), that connect more than 2 Nodes and
# would thus create an error
nofelsum = nofel[nofel > 2].count()
if nofelsum > 0:
print("WARNING: " + str(nofelsum) +
" Elements connect more than two nodes.")
nofelmore = pd.DataFrame()
nofelmore['#_nodes'] = nofel[nofel > 2]
nofelmore['Element_ID'] = self.xmls['element'].loc[nofelmore.index,
'Element_ID']
nofelmore['Type'] = self.xmls['element'].loc[nofelmore.index,
'Type']
nofelmore['Name'] = self.xmls['element'].loc[nofelmore.index,
'Name']
a = nofelmore.groupby('Type')['Type']
print("These Elements have {} different Type(s): \n{}".format(
str(a.ngroups), str(list(a.groups.keys()))))
# TODO:
# Hier könnte man noch prüfen, ob die Knoten untereinander noch
# eine Verbindung haben, oder ob diese alle nur einmal
# im Element auftauchen.
# nodes = self.xmls['Terminal'].loc[nofelmore.index,'Node_ID']
return nofelmore
elif nofel[nofel < 2].count() > 0:
print('{} '.format(nofel[nofel < 2].count()),
'lines have less than two connected nodes!')
else:
print('lines checked - no line connects more than two components')
def dummyparameters_tozerolines(self,
r=0.0001,
x=0.0001,
b=0.0000002):
"""
This function adds (missing) dummy-parameters to lines for r, x, and b.
PyPSA might get problems in the power flow, if these parameters are
missing. So this function detects missing values and filles them with
values for r, x and b.
Parameters
----------
:r (float): default: 0.0001
:x (float): default: 0.0001
:b (float): default: 0.0000002
+++
TODO
- implement any security checks?
+++
"""
r = 0.0001
x = 0.0001
b = 0.0000002
linesr0 = self.lines[self.lines['r'] == 0]
for line in linesr0.index:
self.lines.at[line, 'r'] = r
linesx0 = self.lines[self.lines['x'] == 0]
for line in linesx0.index:
self.lines.at[line, 'x'] = x
linesb0 = self.lines[self.lines['b'] == 0]
for line in linesb0.index:
self.lines.at[line, 'b'] = b
print('The line parameters on following lines were changed:n/')
print('r: {}'.format(linesr0.index.values))
print('x: {}'.format(linesx0.index.values))
print('b: {}'.format(linesb0.index.values))
def repairlines(self, brokenlines):
"""
This function repairs the lines, that are connected to more than
two nodes, by splitting surplus nodes from the line and creating
dummy lines with neglectable x, r and b to connect the other nodes.
Parameters
----------
:brokenlines (DataFrame):
a list of those lines, that are broken with three columns
#_nodes - the number of nodes connected to the element
type - the Type of this element
name - the Name of this element
index - the Element-ID of this element
+++
TODO: clean up the code!
- use .at instead of .loc for speedup??
+++
"""
line_num = 1
for line in brokenlines['Element_ID']:
# read and separate the data:
filter_nodes = self.xmls['terminal']['Element_ID'] == line
nodes = self.xmls['terminal'].loc[filter_nodes]
line_inputnode = nodes[nodes['TerminalNo'] == '1']['Node_ID'].values[0] # unused? --> delete!
line_outputnodes = nodes[nodes['TerminalNo'] == '2']['Node_ID']
line_outputnode = line_outputnodes.values[0]
surplus_nodes = line_outputnodes.values[1:]
# change data in the xmls-dataframes
i = 1
node_from = line_outputnode
for surplus_node in surplus_nodes:
# create a new line without any resistance on the basis of
# the old line:
line_name = line+'s{}'.format(i) # new nam
# make a copy of existing line
new_line = self.xmls['line'].loc[line].copy()
new_line['Element_ID'] = line_name
new_line['r'] = '0.0001'
new_line['r0'] = '0.0001'
new_line['x'] = '0.0001'
new_line['x0'] = '0.0001'
new_line['l'] = '1'
new_line['c'] = '0.00002'
new_line.name = line_name
self.xmls['line'].loc[line_name] = new_line
# duplicate also the entry in the element-dataframe:
new_element = self.xmls['element'].loc[line].copy()
new_element.name = line_name
new_element['Element_ID'] = line_name
self.xmls['element'].loc[line_name] = new_element
# get the terminal entry
choose_nodes = self.xmls['terminal'][self.xmls['terminal']['Node_ID']==surplus_node]
term_id = choose_nodes['Terminal_ID'].loc[choose_nodes['Element_ID'] ==line].values[0]
# rewrite the terminal entry
self.xmls['terminal'].loc[term_id, 'Element_ID'] = line_name
if self.xmls['terminal'].loc[term_id, 'TerminalNo'] == '1':
print('oh')
self.xmls['terminal'].loc[term_id, 'TerminalNo'] = '2'
# append a new terminal entry
new_term_id = term_id+'s'+str(i)
# duplicate entry
terminal_entry = self.xmls['terminal'].loc[term_id]
# rewrite entry
terminal_entry.name = new_term_id
self.xmls['terminal'].loc[new_term_id] = terminal_entry
self.xmls['terminal'].loc[new_term_id, 'Terminal_ID'] = new_term_id # maybe not necessary??
self.xmls['terminal'].loc[new_term_id, 'TerminalNo'] = '1'
self.xmls['terminal'].loc[new_term_id, 'Node_ID'] = node_from
node_from = surplus_node
i = i+1
print('repaired line {} of {}'.format(line_num,
brokenlines.index.size))
line_num += 1
print('finished repairing lines')
def dfstocomponents(self, set_net_voltage='0', with_breaker=True):
"""
Converts and filters the dataframes from the raw xml-data
into pypsa readable dataframes.
Parameters
----------
:set_net_voltage (String):
with this parameter you can set the net-operating-voltage. If not
set it will be taken from Sincal. In some cases this helps to
include Eco-Stations as generators or loads. In 0.4 kV
networks, declared as general stations will be translated to
generators. In 10 kV networks they will be translated to loads.
:with_breaker (boolean):
if this is set to false, breaker will not effect the network. If
set to True, lines, that are separated by breakers will be deleted.
Set it to false to avoid this.
+++
TODO: rewrite the function in a way, that an API can be used to
automately translocate the values and set up the dataframes?
- clean the code.
- avoid int/float bus-names! write a bus- in front...
+++
"""
if set_net_voltage == '0':
self.net_voltage = self.xmls['calcParameter']['Uref'].values[0]
else:
self.net_voltage = set_net_voltage
try:
import utm
except ImportError:
raise ImportError('<no module named utm found>')
# create buses dataframe:
self.buses = pd.DataFrame()
self.buses['v_nom'] = self.xmls['node']['VoltLevel_ID']
# for name in self.buses.index:
# new_name = 'b'+str(name)
# self.buses['name'].loc[name] = new_name
# self.buses.index = self.buses['name']
self.buses.index.name = 'name'
# transform utm values to latlong
rw_list = self.xmls['graphicNode']['NodeStartX']
hw_list = self.xmls['graphicNode']['NodeStartY']
lat_list = rw_list.copy()
lat_list[:] = 0.0
lat_list[:] = 0.0 # for some reason this needs to be done, to make this a float
long_list = hw_list.copy()
long_list[:] = 0.0
long_list[:] = 0.0
for ind in rw_list.index:
rw = float(rw_list[ind])
hw = float(hw_list[ind])
lat, long = utm.to_latlon(easting=rw,
northing=hw,
zone_number=32,
northern=True)
lat_list[ind] = lat
long_list[ind] = long
self.buses['x'] = lat_list
self.buses['y'] = long_list
self.buses['carrier'] = 'AC'
self.buses['frequency'] = int(self.xmls['calcParameter']['f'].values[0])
# create lines dataframe:
self.lines = pd.DataFrame()
lineterminal = self.xmls['terminal']
lineterminal['breaker_state'] = '1'
# filter lines, that are not connected due to breakers:
if not self.xmls['breaker'].empty:
breaker_state = self.xmls['breaker']['Flag_State']
for term_id in breaker_state.index:
state = breaker_state[term_id]
if len(state) == 1:
lineterminal['breaker_state'].loc[term_id] = state
else:
# TODO: if one of the states is 0, pass that one!
lineterminal['breaker_state'].loc[term_id] = state.ix[0]
lineterminal.index = lineterminal['Element_ID']
lineterminal = lineterminal[self.xmls['element']['Type'] == 'Line']
# gather all lines to be deleted here:
self.line_del = lineterminal['Element_ID'][lineterminal['breaker_state'] == '0']
if not self.line_del.empty:
print('deleting the following lines, due to breakers in the grid:')
print(self.line_del.index)
self.lines['bus0'] = lineterminal[lineterminal['TerminalNo']=='1']['Node_ID']
self.lines['bus1'] = lineterminal[lineterminal['TerminalNo']=='2']['Node_ID']
# TODO: can this be written less time consuming???:
# for line in self.lines.index:
# self.lines['bus0'].loc[line] = 'b'+str(self.lines['bus0'].loc[line])
# self.lines['bus1'].loc[line] = 'b'+str(self.lines['bus1'].loc[line])
self.lines.index.name = 'name'
# Filtern der benötigten Daten:
line_fl = self.xmls['line'][['Ith',
'Un',
'c',
'fn',
'l',
'q',
'r',
'x']].astype(float)
# Multiplication of l and r to get the overall r
self.lines['r'] = line_fl['l'].multiply(line_fl['r'])
# Multiplication of l and x to get the overall x
self.lines['x'] = line_fl['l'].multiply(line_fl['x'])
# Multiplication of l and c, and radial frequency
self.lines['b'] = line_fl['l'].multiply(line_fl['c']*2*math.pi*50*10e-9)
self.lines['s_nom'] = line_fl['Ith'].multiply(line_fl['Un']) # TODO: imply real formula!
# delete lines, that are not connected
if with_breaker == True:
self.lines = self.lines.drop(self.line_del)
# create slack generators dataframe (for given Infeed-nodes):
self.generators = pd.DataFrame()
self.generators['name'] = self.xmls['element'][self.xmls['element']['Type']=='Infeeder']['Element_ID']
self.generators.index = self.generators['name']
self.generators = self.generators.drop(columns='name')
self.generators['control'] = 'slack' # Only for Infeeders!
self.generators['bus'] = 'nan' # create a dummy
# TODO: is this also possible without the for loop?
# connect the generator to a bus
for gname in self.generators.index:
gen_bus = self.xmls['terminal'].loc[self.xmls['terminal']['Element_ID']==gname,'Node_ID']
self.generators.loc[gname, 'bus'] = 'b'+str(gen_bus[0])
# create slack generators dataframe (for given EcoStations):
slacknodes = self.xmls['node']['EcoStation_ID'].astype(float)
# get the type of the ecostations:
# 1 = Netstation
# 2 = Umspannstation
# 3 = Schaltstation
# 4 = Allgemeine Station
# 5 = Verteilnetzstation
if self.net_voltage == '10':
lo = ['4']
gen = ['1', '2']
if self.net_voltage == '0.4':
gen = ['1', '2', '4']
ecost_type = self.xmls['ecoStation']['Flag_Typ']
slacknodes = slacknodes[slacknodes > 0]
slacknodes = slacknodes.astype(int)
for node_id in slacknodes.index:
ecost = slacknodes[node_id]
ecotp = ecost_type[str(ecost)]
if ecotp in gen:
gen_name = self.xmls['node'].loc[node_id, 'Name'].strip()
generator = pd.Series()
generator.name = gen_name
i = 0
new_gen_name = gen_name
while new_gen_name in self.generators.index:
new_gen_name = gen_name+'_'+str(i)
i += 1
gen_name = new_gen_name
generator['control'] = 'slack'
# generator['bus'] = 'b'+str(node_id)
generator['bus'] = node_id
self.generators.loc[gen_name] = generator
elif ecotp in lo:
pass # TODO! needs to be written!
if not self.xmls['load'].empty:
self.loads = pd.DataFrame()
# eap = jahreswirkverbrauch in kwh
self.loads['p_set'] = self.xmls['load']['Eap'].astype(int) / 1000
# self.loads['q_set'] = self.xmls['load']['Eap'].astype(int)
self.loads['bus'] = self.xmls['load']['Element_ID'] # TODO: is this true?? Not Node_ID??? and the b in front!!
names = []
for name in self.xmls['load']['Element_ID']:
names += ['l'+name]
self.loads['name'] = names
self.loads = self.loads.reset_index()
# for some nodes, several loads may exist; count them:
counts = self.loads['name'].value_counts()
for i in counts.index:
val = counts[i]
if val > 1:
add = 0
group = self.loads['name'][self.loads['name'] == i]
for load in group.index:
new_name = i+'_'+str(add)
add += 1
self.loads.loc[load, 'name'] = new_name
self.loads.index = self.loads['name']
self.loads = self.loads.drop(columns='name')
def transform_gen_toTKN(self):
"""
In low-voltage grids, isolation boxes may be mistaken for
generators. In german they are referred to as "Trennkästen",
with the abbreviation TKN. In this function they are filtered and
disconnected. In a second step sub_networks are searched for,
which are not fed by any generator and possess an isolation box.
These are then reconnected to the grid with generator.
Parameters:
----------
None
"""
if hasattr(self, 'network'):
print('transforming gens to TKN')
tkn = pd.DataFrame(columns=self.network.generators.columns)
for name in self.network.generators.index:
if 'TKN' in name:
tkn.loc[name] = self.network.generators.loc[name]
# lines with TKN are split and new buses for each line created
line_list = {}
for line in self.lines.index:
if self.lines.loc[line].bus0 in tkn.bus.values:
bus_name = self.lines.loc[line].bus0
x = self.network.buses.loc[bus_name].x
y = self.network.buses.loc[bus_name].y
f = self.network.buses.loc[bus_name].frequency
v_nom = self.network.buses.loc[bus_name].v_nom
bus_name = bus_name + '_tkn'
while bus_name in line_list:
bus_name = bus_name + 'i'
self.network.lines.bus0[line] = bus_name
self.network.add('Bus',
bus_name,
x=x,
y=y,
v_nom=v_nom)
line_list[bus_name] = line
print('processing line {}'.format(line))
if self.lines.loc[line].bus1 in tkn.bus.values:
bus_name = self.lines.loc[line].bus1
x = self.network.buses.loc[bus_name].x
y = self.network.buses.loc[bus_name].y
f = self.network.buses.loc[bus_name].frequency
v_nom = self.network.buses.loc[bus_name].v_nom
bus_name = bus_name + '_tkn'
while bus_name in line_list:
bus_name = bus_name + 'i'
self.network.lines.bus1[line] = bus_name
self.network.add('Bus',
bus_name,
x=x,
y=y,
v_nom=v_nom)
line_list[bus_name] = line
print('processing line {}'.format(line))
# delete all tkn generators and their (no longer connected) buses from the network:
for gen in tkn.index:
self.network.remove('Bus', tkn.loc[gen].bus)
self.network.remove('Generator', gen)
def refresh_lists(self):
func_list = []
non_func_list = []
print('Determining network topology')
self.network.determine_network_topology()
#self.network.lpf() # TODO: check if also determine-function is sufficient!
print('Reconnecting sub_networks without gen, with TKN')
for sub_network in self.network.sub_networks.obj:
gens = sub_network.generators()
has_gen = True
if len(gens) == 0:
# print('sub {} has no generator'.format(sub_network))
has_gen = False
has_tkn = False
tkn_bus = []
# HIER IST NOCH EIN FEHLER DRIN:
for bus in sub_network.buses().index:
if 'tkn' in bus:
has_tkn = True
tkn_bus += [bus]
if has_tkn and has_gen:
print('functional sub_net with {}'.format(tkn_bus))
func_list += [tkn_bus]
if has_tkn and not has_gen:
non_func_list +=[tkn_bus]
return func_list, non_func_list
func_list, non_func_list = refresh_lists(self)
con_accum = True
while non_func_list and con_accum:
con_accum = False
for tkn in non_func_list:
while con_accum is False and tkn:
tkn_bus = tkn.pop()
tkn_bus_org = tkn_bus
while 'i' in tkn_bus:
tkn_bus = tkn_bus[0:-1]
con_bus = False
for func_buses in func_list:
for func_bus in func_buses:
if tkn_bus in func_bus:
con_bus = func_bus
if con_bus is not False:
con_accum = True
line_name = con_bus+tkn_bus_org
self.network.add('Line',
line_name,
bus0=tkn_bus_org,
bus1=con_bus,
b=0.0000002,
r=0.0001,
x=0.0001)
# get rid of empty lists
non_func_list = [x for x in non_func_list if x != []]
func_list, non_func_list = refresh_lists(self)
# print(non_func_list)
#
def check_busbars(self):
"""
Check, if nodes are connected via busbars, which in PSS-Sincal is
given by the InclName argument.
Returns the InclName row with all relevant entries.
Returns
-------
inc_names: pd.Series()
"""
# store the InclName row
inc_names = self.xmls['node']['InclName']
# drop nans
inc_names = inc_names.dropna()
# drop whitespaces
for node_id in inc_names.index:
inc_names[node_id] = inc_names[node_id].strip()
# drop empty entries
inc_names_notempty = inc_names != ''
inc_names = inc_names[inc_names_notempty]
# print out the list of all entries, to be able to check them
print('The following InclNames were found:')
print(inc_names)
return inc_names
def connect_busbars(self, inc_names, keys=False):
"""
Takes the series of InclName and checks them for the given keys,
then connects all components with the given keys.
Parameters
----------
inc_names : pd.Series()
all relevant InclNames from the PSS-Sincal node dataframe
keys : list
the keys allow to check for tags inside the inc_names list, which
identify the common busbar and thus, which elements should be
connected
+++
TODO: check first, if the pypsa components already exist - if not,
it is not possible to connect the components!!
+++
"""
if hasattr(self, 'network'):
connect_dict = {}
# if no key for the connection is given, all nodes are connected
# with each other
if keys is False:
for node_id in inc_names.index:
connect_dict[node_id] += [node_id]
i = -1
for number in connect_dict:
self.network.add("Line",
"busbar" + str(number),
bus0=buses_list[i],
bus1=buses_list[i+1],
b=0.0000002,
r=0.0001,
x=0.0001)
i += 1
# else only those containing the key are connected to each other
else:
for key in keys:
connect_dict[key] = []
for node_id in inc_names.index:
if key in inc_names[node_id]:
connect_dict[key] += [node_id]
# print(connect_dict)
for key in keys:
buses_list = connect_dict[key]
i = -1
for number in buses_list:
self.network.add("Line",
"busbar" + str(number),
bus0=buses_list[i],
bus1=buses_list[i+1],
b=0.0000002,
r=0.0001,
x=0.0001)
i += 1
def connect_stationstolines(self,
bindings,
b=0.0000002,
r=0.0001,
x=0.0001):
"""
Takes a dataframe of line and node ID's to be connected and connects
them with a dummy line
Parameters
----------
bindings : pd.DataFrame()
line and node ID's to be connected to each other.
+++
TODO: - rewrite the function in a way, that it is universally usables
- rename variable bindings to something understandable
+++
"""
if hasattr(self, 'network'):
# strip whitespaces from element-names
for element in self.xmls['element'].index:
el_name = self.xmls['element'].loc[element, 'Name'].strip()
self.xmls['element'].loc[element, 'Name'] = el_name
# run through all the connections to be made and connect them
for bin_id in bindings:
station_id = bindings.loc['ID_Station',bin_id]
eq_col = self.xmls['node']['Equipment_ID'] == station_id
ecol = self.xmls['node'][eq_col]
if not ecol.empty:
enode_id = ecol.index.values[0]
line_id = bindings.loc['ID_Kabel',bin_id]
line_id = 'ID_'+line_id
lin_col = self.xmls['element']['Name'] == line_id
lcol = self.xmls['element'][lin_col]
lelement_id = lcol.index.values[0]
term_id = self.xmls['terminal']['Node_ID'].loc[lelement_id].values
for node in term_id:
term_col = self.xmls['terminal']['Node_ID'] == node
check = self.xmls['terminal']['Node_ID'][term_col]
if len(check) == 1:
i = 0
newline_name = str(lelement_id)+str(i)
while newline_name in self.network.lines.index:
i += 1
newline_name = str(lelement_id)+str(i)
self.network.add("Line",
newline_name,
bus0=check.values[0],
bus1=enode_id,
b=b,
r=r,
x=x)
def importloadswithprofiles(self,
filename,
ltype='rh0',
feedin=False,
replacetime=False):
"""
This function imports loadprofiles and transforms them into a pypsa
readable dataframe.
Parameters
----------
:filename (str):
name of the load-profile file to be imported
this file should be a .csv with rows:
Time;bus;bus;...
YYYY/MM/DD HH:MM;1,3;2,1;...
meaning the bus, that the load is connected to.
P in kW
:ltype (str):
type of the load, to distinguish several loads at the same bus
:feedin (bool):
if the load is actually a feedin, this can be set here
:replacetime (bool):
if there should be a problem with summer and winter time, this can
be set to replace the datetimeindex
+++
TODO: - implement an option to include unique identifiers in the csv
- change lambda and use a def instead...
+++
"""
# to correctly import date and time, this function is defined:
dateparse = lambda x: pd.datetime.strptime(x, '%Y/%m/%d %H:%M')
loaddat = pd.read_csv(filename,
sep=';',
parse_dates=['Time'],
date_parser=dateparse)
loaddat.index = loaddat['Time']
loaddat = loaddat.drop(columns='Time')
# PyPSA has problems with summer and winter time. If necessary, they
# can be replaced here:
if replacetime is True:
start_time = loaddat.index[0]
end_time = loaddat.index[-1]
f = '15min'
dti = pd.date_range(start=start_time,
end=end_time,
freq=f)
loaddat.index = dti
# convert kW to MW
loaddat = loaddat/1000
# if it is a feedin, this is converted here:
if feedin is True:
loaddat = loaddat*(-1)
if not hasattr(self, 'loads'):
print('no loads until now. Implementing.')
self.loads = pd.DataFrame(columns=['bus', 'p_set'])
self.loads.index.name = 'name'
i = 0
for node in loaddat.columns:
new_node = node
if '.' in node:
# new_node = node[0:len(node)-3] # clean it from any float-numbers
print('WARNING: the load on bus {} may not be recognized!'.format(node),
'Please clean it from any float-numbers.',
'If a . is part of the name, ignore this warning.')
name = 'l'+new_node+ltype
if feedin is True:
p_set = loaddat[node].min()
else:
p_set = loaddat[node].max()
load = {'bus': new_node,
'p_set': p_set}
self.loads.loc[name] = load
i += 1
if not hasattr(self, 'snapshots'):
print('no loadprofile until now. Implementing.')
column = loaddat.columns[0]
self.snapshots = loaddat[column].copy()
self.snapshots.name = 'weighting'
self.snapshots[:] = 1
if not hasattr(self, 'loads_p_set'):
self.loads_p_set = loaddat.copy()
for column in self.loads_p_set.columns:
self.loads_p_set = self.loads_p_set.rename(columns={column: 'l'+column+ltype})
else:
loads_p_set_local = loaddat.copy()
for column in loads_p_set_local.columns:
new_columnname = 'l'+column+ltype
loads_p_set_local = loads_p_set_local.rename(columns={column: new_columnname})
self.loads_p_set[new_columnname] = loads_p_set_local[new_columnname]
def importnetwork(self):
"""
This function imports the converted dataframes into pypsa, checks the
network for consistency and prints out, if not connected subgraphs are
present.
+++
TODO:
- check if the dataframes are available. (partly done)
- rewrite the code with less lines...
- loads-p_set??? --> check for cls names!
- replace try with hasattr
+++
"""
self.network = pypsa.Network()
try:
self.network.import_components_from_dataframe(self.buses, 'Bus')
self.network.import_components_from_dataframe(self.lines, 'Line')
except:
print('ERROR: No buses or lines found! or problems with import')
if hasattr(self, 'loads'):
self.network.import_components_from_dataframe(self.loads, 'Load')
else:
print('no loads implemented')
if hasattr(self, 'generators'):
self.network.import_components_from_dataframe(self.generators,
'Generator')
else:
print('no generators implemented')
if hasattr(self, 'snapshots'):
print('implementing snapshots')
self.network.set_snapshots(self.snapshots.index)
if hasattr(self, 'loads_p_set'):
print('implementing load series')
self.network.import_series_from_dataframe(self.loads_p_set,
'Load',
'p_set')
self.network.consistency_check()
def check_connectivity(self, printdata=False):
"""
checks, if there are not connected graphs inside the network and
prints out additional information to each graph, if printdata is
set to True.
Parameters
----------
printdata: boolean (default: False)
if set to True, the function will print the nodes and edges of
each subgraph/-network
"""
g = self.network.graph()
if nx.number_connected_components(g) > 1:
print('The network consists of {} not connected subgraphs.'.format(nx.number_connected_components(g)))
if g.is_directed():
g = g.to_undirected()
sub_graphs = nx.connected_component_subgraphs(g)
if printdata is True:
for i, sg in enumerate(sub_graphs):
numon = sg.number_of_nodes()
print("subgraph {} has {} nodes".format(i, numon))
print("\tNodes:", sg.nodes(data=True))
print("\tEdges:", sg.edges())
def del_nogen_subs(self):
"""
function deletes subgraphs that have no (slack) generator.
Parameters
----------
None
Returns
-------
None
+++
TODO:
- find a faster way to define the subnetwork - this is too long!
+++
"""
for subnet in self.network.sub_networks.index:
sub = self.network[self.network.buses.sub_network == subnet]
if len(sub.generators) == 0:
sub_buses = sub.buses
sub_lines = sub.lines
sub_generators = sub.generators
sub_loads = sub.loads
for bus in sub_buses.index:
self.network.remove('Bus', name=bus)
for line in sub_lines.index:
self.network.remove('Line', name=line)
for generator in sub_generators.index:
self.network.remove('Generator', name=generator)