Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Учебники / 0841558_16EA1_federico_milano_power_system_modelling_and_scripting

.pdf
Скачиваний:
72
Добавлен:
08.06.2015
Размер:
6.72 Mб
Скачать

3.3 Scripting Languages for Computational Science

35

4.C, C++, Java and other languages used for traditional programming are compiled, while Perl, Python and other languages used for scripting are interpreted. An interpreted language facilitates the implementation phase and allows quickly prototyping new functions. On the other hand, compiled languages are able to provide faster applications than interpreted languages. Some nuances to the latter statement is provided in Example 3.1.

5.Traditional programming is general based on low level languages, while scripting prefers high level languages. Of course, the frontier that divides a low level from a high level language is somewhat subjective. However, we can assume that the language is high level for our purposes if we do not need to worry about the language idiosyncrasies and can concentrate on the kernel of our application.

6.Traditional programming generally leads to closed software applications, while scripting promotes open projects. In this context, the terms open and closed have the meanings discussed in the previous Section 3.1. Traditional programming would likely lead to a closed software application even if the source code were available. This is a result of the monolithic approach and low-level languages used in traditional programming.

In conclusion, the scripting language approach intrinsically promotes the reusability of the code and is suitable for quickly developing small applications and/or extensions of existing projects. These features are ideal for didactic purposes and fit well with the scheme shown in Figure 3.2.

3.3Scripting Languages for Computational Science

Based on the discussion of the previous section, scripting appears an interesting option for any computer application. Actually, there are specific advantages that makes this programming approach suitable for computational science. The following is a list of remarks that are relevant to the material presented in this book but that can suite any other branch of engineering applications. For the interested reader, an excellent dissertation about scripting for computational science can be found in [164].

1.While system languages are adequate for big stand-alone applications that require time and a team of software developers, students and researchers are interested in a versatile tool for quickly developing their ideas. The scripting approach is able to provide such versatility and rapidity since most basic operations are already available in existing libraries. Moreover, scripting languages are characterized by a high-rate learning curve compared to system languages. This is due to the fact that scripting languages do not require worrying about type definition, memory allocation, etc. Furthermore the syntax of scripting languages is generally quite simple and clean.

36

3 Power System Scripting

2.As discussed in Chapter 2, scientific computing is not strictly limited to mathematical algorithms or number crunching. Focusing on power system analysis, it is important to have the possibility of a graphical interface for both drawing network one-line diagrams and visualizing results. Furthermore, a graphical user interface can be of great help in educational applications. Scripting languages simplify the process of building such graphical tools. Actually, most scripting languages are general purpose and are not explicitly oriented to scientific applications (such as FORTRAN). Thus, using scripting languages make generally easy or, at least, possible, any kind of task (e.g., web-based applications, multimedia, etc.)

3.Mathematical and scientific applications have been the original purpose of computers and are the noblest way of using such machines. No surprise that in the last decades very e cient libraries for linear algebra, matrix factorization, eigenvalue analysis, etc., have been developed and optimized with the help of thousands of scientists. BLAS, ATLAS, LAPACK, UMFPACK are good examples of such libraries. Most of these libraries are legacy code written in FORTRAN or in C. Using modern scripting languages do not mean to bury old code. On the contrary, the ability of scripting languages of gluing di erent applications allows creating very e cient interfaces and re-utilize legacy libraries. It is important to note that scripting language are generally a high-level layer between the programmer and a variety of low-level libraries.2 Thus using a scripting languages allows taking advantage of all resources in a more e cient and seamless way than system languages.

4.Most scripting languages were born in a Unix or Unix-like environment. For example, Python, Perl, Php, and Ruby. This is not accidental but is largely due to the features of Unix and Unix-like operating systems that highly promote the development of custom applications. Most popular free and open source scripting languages provide a Windows version that thereby makes available the Unix power on this platform. A byproduct is that using popular scripting languages, the code is portable on various platforms with no or very limited modifications. Portability or platform independence can be of great importance in case a scientific project is carried out by di erent research groups or in case of popular projects that receive third-party contributions.

3.4Computer Languages Suitable for Power System Analysis

Among the tens (or hundreds) of all available languages, only those that fit some basic requirements are eligible for power system analysis. These requirements are the availability of e cient and easy-to-use libraries for:

2The interpreter of the scripting language itself is generally written in some legacy system language such as C.

3.4 Suitable Computer Languages

37

1.Basic mathematical functions (e.g., exponential, logarithm and trigonometric functions).

2.Complex numbers.

3.Multi-dimensional arrays (e.g., element by element operations and slicing).

4.Linear algebra (e.g., LU and Cholesky’s factorization).

5.Sparse matrices.

6.Eigenvalue analysis of non-symmetrical matrices.

The reasons of the need for these libraries in power system analysis is quite evident. However, the discussions on mathematical tools given in Part II dissipate any possible doubt.

Strictly speaking, only basic mathematical functions are really necessary. All other routines can be implemented starting from there. However, this would require a really long time and results could hardly be as e cient as existing libraries. Graphical libraries, although certainly important for plotting results, have not been included in the basic requirements above. Plotting a curve is a post-processing operation, which can be done by means of external applications such as Gnuplot or Excel R once a plain ascii file of data in tabular format is available. Thus, it su ces that the computer language is able to (e ciently) read and write files, which is a feature common to all languages.

One may argue that also the availability of algorithms for numerical integration of di erential equations or optimization problem solvers can be useful. These algorithms perform properly if adjusted to the specific problem to be solved and is thereby a good idea to avoid using predefined functions unless these can be easily customized.

Computer languages that provide the features described above can be divided into four categories:

1.Legacy system languages (e.g., FORTRAN, C and C++).

2.Modern system languages (e.g., Delphi, Java, C# and Scala).

3.General purpose scripting languages with inclusion of adequate mathematical libraries (e.g., Python and Perl).

4.Scientific-oriented scripting languages (e.g., Matlab and Octave).

No computer language is perfect. Any choice has advantages and drawbacks. An assumption of this book is that the advantages of using general purpose scripting languages prevail on the advantages provided by other computer languages.

Sections 3.2 and 3.3 provide su cient reasons for preferring scripting languages to system ones. Anyone that has programmed in FORTRAN or in C knows the su ering of building up a complex project. More di cult is to convince supporters of Java or other modern system languages. Java has become popular at the end of the last century as a substitute of C++. In my opinion, Java is not adequate for scientific applications that involve massive number crunching. This is a common drawback of most modern system languages that have been designed by and for computer programmers and not

38

3 Power System Scripting

for engineers. I also think that languages that overuse punctuation marks (e.g., braces) are quite messy but, maybe, it is just a matter of tastes. Much more important for preferring scripting languages is the fact that Java and other modern system programming languages promote closed software tools and, thus, should be avoided in education and research.

More di cult is to justify why general purpose programming languages has to be preferred to scientific-oriented scripting languages. Actually, this may seem just a nonconformist attitude. Matlab along with the Simulink environment is a standard de facto in the scientific community for both education and research. Apart from Matlab, there are a variety of other scripting languages, for example Gauss, MathCAD, Mathematica, Maxima, Modelica, Octave, Q, R, SciLab and Yorick. All these languages are specifically oriented to scientific applications and abound with mathematical functions and libraries.

There are, however, a few drawbacks inherent to languages such as Matlab and other scientific scripting languages that should be carefully evaluated, as follows.

1.Scientific oriented languages are designed to make easy a specific mathematical task. For example, Matlab is systematically matrix oriented, thus any variable is by default a multi-dimensional, easy-to-reshape, complex array. This feature can be convenient in most cases, but one may sometimes simply need a scalar float or a short integer.

2.Most scientific languages do not support classes or provide a na¨ıve class implementation. This fact makes di cult or impossible object-oriented programming.

3.While providing a good support for types useful for mathematical operations (e.g., multi-dimensional arrays), scientific scripting languages often lack or make di cult the use of some useful basic types such as tuples, lists or hashes.

4.Matlab is a proprietary software. Thus, the user has to rely on the solutions provided by the developers of Matlab. Of course, one could use some Matlab-like interpreters such as Octave or SciLab, but at the cost of using a slower interpreter, a limited programming language and a reduced set of libraries.

Despite the arguments above, the scientific community is clearly oriented to Matlab or to system languages. Table 3.1 depicts a rough comparison of a variety of open source software packages for power system analysis. Commercial packages are not considered since all of them are closed applications and, thus, are of no interest for the scope of this book. The features illustrated in Table 3.1 are standard power flow (PF), continuation power flow and/or voltage stability analysis (CPF), optimal power flow (OPF), eigenvalue or small signal stability analysis (EA), time domain simulation (TDS) for transient stability analysis, electro-magnetic transients (EMT), and some

3.5 Python Scripting Language

39

æsthetic features such as graphical user interface (GUI) and one-line diagram editor through computer aided design (CAD).

The tools shown in Table 3.1 are heterogeneous and are characterized by very di erent complexity levels. Thus, it is not fully fair to compare these projects. As a matter of fact, some packages are Ph.D. students’ projects (e.g., MatDyn and Pylon) or niche research tools (e.g., AMES), while others are well-assessed projects with several years of experience (e.g., UWPFLOW). In any case, there is a clear preponderance of Matlab and system languagebased tools. Furthermore, it is not by chance that the two industry-oriented packages, OpenDSS and InterPSS, are based on system languages and use Windows as operating system. In fact, these projects have been developed by companies used for producing proprietary software. On the other hand, Matlab is the preferred language in education and research environments.

3.5Python Scripting Language

This section discusses the reasons for using Python as scripting language throughout this book. In the remainder of this chapter, it is assumed that the reader has some basic knowledge of this language. If this is not the case, among the wide variety of books and on-line documentations about Python, relevant references are [18, 32, 62, 164, 186]. The Python website (www.python.org) is also an excellent starting point for obtaining the latest Python version, learning about Python standard libraries and accessing a variety of spare material related to the Python language. Finally, Appendix A provides a quick reference of non-standard libraries used in this book.

Python is a safely, dynamically and strongly typed language. Hence polymorphism, meta-programming and introspection are easy to implement and to use. Concepts such as safe, dynamic and strong typing as well as meta-programming, polymorphism and introspection are relatively advanced (though intriguing) programming topics. While an in-depth discussion on types can be found in [239], intuitive definitions are as follows:

Safe typing: a programming language is considered “type-safe” if it does not allow operations or conversions that lead to erroneous or unpredictable results. The opposite of safe typing is unsafe typing.

Dynamic typing: a programming language is said to be dynamically typed if the majority of type checking is performed at run-time as opposed to at compile-time. Dynamic typing is easier to find in scripting languages (e.g., Python). The opposite of dynamic typing is static typing, which is typical of system programming languages (e.g., C). Dynamic and static typing can cohabit since a programming language can be dynamically typed in some aspects and statically typed in others (e.g., Matlab).

Strong typing: strongly typed programming languages prevent success for an operation on arguments which have the wrong type. The opposite of strong typing is weak typing.

Table 3.1 Open source packages for power system analysis

Package

Ref.

Language

PF

CPF

OPF

EA

TDS

EMT

GUI

CAD

 

 

 

 

 

 

 

 

 

 

 

AMES

[171]

Java

 

 

 

 

 

 

 

 

EST

[338]

Matlab

 

 

 

 

 

 

 

 

InterPSS

[360]

Java

 

 

 

 

 

 

 

 

MatDyn

[64]

Matlab

 

 

 

 

 

 

 

 

MatEMTP

[181]

Matlab

 

 

 

 

 

 

 

 

Matpower

[363]

Matlab

 

 

 

 

 

 

 

 

ObjectStab

[166]

Modelica

 

 

 

 

 

 

 

 

OpenDSS

[86]

Delphi

 

 

 

 

 

 

 

 

PAT

[271]

Matlab

 

 

 

 

 

 

 

 

PSAT

[195]

Matlab, Octave

 

 

 

 

 

 

 

 

PST

[60]

Matlab

 

 

 

 

 

 

 

 

 

 

 

 

Pylon

[172]

Python

 

 

 

 

 

 

 

 

UWPFLOW

[42]

C

 

 

 

 

 

 

 

 

VST

[53]

Matlab

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

40

Scripting System Power 3

3.5 Python Scripting Language

41

Meta-programming: meta-programming consists in writing computer programs that write or manipulate other programs (or themselves) as their data, or that do part of the work at compile-time that would otherwise be done at run-time.

Introspection: type introspection is the ability of some object-oriented programming languages to determine the type of an object at run-time.

Polymorphism: polymorphism is a programming language feature that allows values of di erent data types to be handled using a unique interface.

Other relevant features of Python are as follows.

1.Python is fully based on well-structured classes, which make easy creating, maintaining and reusing modular object-oriented code.

2.Libraries such as NumPy and CVXOPT provide a link to legacy libraries (e.g., BLAS, LAPACK, UMFPACK, etc.) for manipulating multidimensional arrays, linear algebra, eigenvalue analysis and sparse matrices.

3.Thanks to graphical libraries such as Matplotlib, the ability of producing publication quality 2D figures in Python is at least as powerful as in Matlab.

4.The huge variety of free third-party libraries available for Python, allows easily and quickly extending the features of an application well beyond the scope of the original project.

5.Python is free and open source. Hence Python promotes the implementation and distribution of open projects.

6.Python syntax is relatively simple, neat, compact and elegant. Hence Python is particularly adequate for education and illustrative examples.3

Although the features listed above can be likely found in other scripting languages and does not imply that Python is flawless, these are enough for developing the examples provided in this book.

Example 3.1 Python Performance

Before providing an example of Python script, it is worth checking the performance of Python in terms of power system analysis of a real-world power systems. If Python code were not fast enough, all arguments provided above would loose strength. However, computational e ciency is not the main issue in the context of this book. According to Moore’s law, the number of transistors that can be placed inexpensively on an integrated circuit doubles approximately every two years. Thus, a software application that is comparatively slow today will be solved quickly in a few years. Nevertheless, most readers will likely argue that Python cannot be competitive with Matlab or with system programming languages. As a matter of fact, most power

3Some books use pseudo-code for illustrating implementation examples. The rationale behind the use of pseudo-code is the sake of generality. Actually pseudo-code is a sort of Esperanto of computer languages. However, Python syntax is almost as clear as pseudo-code and has the advantage of being a real scripting language.

42

3 Power System Scripting

system practitioners need a several thousand-bus system case study to believe the robustness and e ciency of novel techniques. Table 3.2 aims clearing any possible mistrust.

Table 3.2 Performance of open source packages for power system analysis

Application

Programming

Total time

Jacob. matrix fact.

 

Language

[s]

time [s]

 

 

 

 

 

 

 

 

UWPFLOW

C

1.155

-

InterPSS

Java

15.97

-

Matpower

Matlab

1.464

0.0363

PSAT

Octave

5.221

0.0433

-

Python

1.420

0.0319

 

 

 

 

Table 3.2 shows the CPU times of di erent power system packages (i.e., UWPFLOW, InterPSS, Matpower, PSAT and a custom code written in Python) for solving the power flow analysis using a standard Newton’s method for a 2746-bus 3514-line network. This case represents the Polish 400, 220 and 110 kV networks during winter 2003-04 evening peak conditions and is provided by the current Matpower release [363]. The processor used is a 2.4 GHz Intel Core 2 Duo with 2 GB of RAM. The software packages used in the comparison are: Java 1.6, Matlab 7.8, Python 2.6.3, Octave 3.0.1, UWPFLOW release 2006, InterPSS 1.4, Matpower 3.2 and PSAT 2.1.5. Simulations were solved using Windows XP R as operating system.

The comparison, although drawn using same environment conditions for all software packages, cannot be completely fair. For example, the time required to load the interpreter (e.g., the Java, Matlab, Octave or Python environments), and to convert the input data file, which vary considerably, are not taken into account. In case of InterPSS and PSAT, the time for creating the output file is not included. However, neglecting technicalities, relevant conclusions are:

1.Python can be competitive with Matlab and Octave.

2.System programming languages are not much faster than e cient scientific scripting languages. However, scripting languages do not perform directly heavy mathematical operations, but call e cient FORTRAN or C-based libraries. Thus, the main conclusion is that the interfaces that link scripting languages with external compiled libraries are quite e cient.

3.Array indexing in Octave is slower than in Matlab. However, the matrix factorization performance of these two languages is comparable.

4.The Java-based application is one order of magnitude slower than the other software tools considered in this comparison. This result is not surprising since Java was not born for number crunching.

3.5 Python Scripting Language

43

5.The mean CPU time needed to factorize the power flow Jacobian matrix is slightly smaller for the Python implementation because the symbolic factorization provided by the module CVXOPT is used. Symbolic factorization allows pre-factorizing dense or sparse matrices based only on the non-zeros elements (see also Appendix A). Thus, if the number and the position of non-zero elements of the Jacobian matrix do not vary, the symbolic factorization is needed only once. The first full factorization required 0.0424 s.

Script 3.1 First Python Script

In Example 2.2 a general modular applications for finding the zero of a nonlinear scalar function. This example provides a possible translation of the scheme shown in Figure 2.3 in the Python language. The goals of this example are to show how: (i) to implement each block of the scheme of Figure 2.3; and (ii) to organize the code in a modular and easily extensible way.

For the sake of simplicity, the whole project is contained in a unique file, say zero.py, and the algorithm used for finding the solution of f (x) = 0 is the Newton’s method.

It is a good habit to begin a Python module with the declarations of the packages used by the module. In this case, the modules optparse and sys are needed for parsing the parameters passed to the module zero.py when it is called from the command line. Then, the modules numpy and cvxopt are needed for array operations and the module matplotlib for producing 2D plots. The script header is as follows:

from optparse import OptionParser

from cvxopt.base import matrix, mul, sin, cos from numpy import linspace

import sys

import matplotlib.pyplot as pyplot

The second step consists in defining the common class for the functions fi(x). Defining a common base class is a good practice that is made possible by the ability of classes of inheriting methods and attributes from other classes. The base class is called parent, ancestor, father or mother class while the classes that inherit the method from the original class are called child class or subclass. Inheritance can be multiple, i.e., a subclass may have several parent classes. However, in this example, only simple inheritance is considered. The class base defines the common methods add for adding a function element, setup for initializing class parameters, and list2matrix for converting lists to double-precision arrays. Since the class base does not define a specific function fi(x), the methods fcall and fxcall for computing fi(xk ) and dfi/dx|k are void. The class base is as follows:

class base():

"""base class for functions"""

def init (self):

44

3 Power System Scripting

self.params = {} self.n = 0

def setup(self):

for key in self.params.keys(): self. dict [key] = []

def list2matrix(self):

for key in self.params.keys():

self. dict__[key] = matrix(self. dict [key], (self.n, 1), ’d’)

def add(self, **kwargs):

self.n += 1

keys = self.params.keys()

for key in keys:

self. dict [key].append(self.params[key])

for key, val in kwargs.iteritems(): if not key in keys: continue self. dict [key][-1] = val

def fcall(self, x):

return

0

 

 

 

 

 

 

def dfcall(self, x):

 

 

 

 

return

0

 

 

 

 

 

 

The internal built-in dictionary4

 

dict

 

contains all attributes and method

names of a class. Using

 

dict

 

makes possible to e ciently use meta-

programming. For example, the method setup dynamically initializes at run-time the parameters of each specific function fi(x). These parameters are defined in the child classes poly and sine, i.e., the polynomial and sine functions. These are implemented as follows:

class poly(base):

"""polynomial class"""

def init (self):

base. init (self)

4Dictionaries are sometimes found in other languages as associative memories, associative arrays or hashes. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys. Keys can be any immutable Python type, e.g., strings or numbers.