Functional Programming Applied to Electrical Engineering

Master's Dissertation - 03/12/2019

Universidade Federal de Itajubá - ISEE

Hanneli C. A. Tavante

Supervisor: Dr Benedito D. Bonatto

Co-Supervisor: Dr. Maurilio P. Coutinho

Agenda

  • Research goals
  • Relevance
  • Electromagnetic transient analysis software
  • Functional Programming and Haskell
  • Haskell in Electromagnetic Transient Analysis - Implementation 

  • Results

  • Final considerations and future work

  • References

Agenda

  • Research goals
  • Relevance
  • Electromagnetic transient analysis software
  • Functional Programming and Haskell
  • Haskell in Electromagnetic Transient Analysis - Implementation 

  • Results

  • Final considerations and future work

  • References

Electrical Engineering problems might be solved with different approaches/strategies

(example: Electromagnetic Transients can be analysed using Nodal Analysis or State Space Analysis)

Problem

Model 1

Model 2

Model 3

The analysis is often supported by a piece of software written in some programming language (C, C++, Matlab, Python, Java)

These programming languages (C, C++, Matlab, Python, Java) often use the same strategy (paradigm) - imperative programming

Problem

Model 1

Model 2

Model 3

Imperative programming

This work presents an alternative programming paradigm for Electrical Engineering Software

Functional Programming

This work presents an alternative programming paradigm for Electrical Engineering Software

Functional Programming

Problem

Model 1

Model 2

Model 3

Imperative programming

Model 1

Model 2

Model 3

Functional programming

Questions this work answers

  1. What are the benefits of functional programming?
  2. What are the benefits to the code base?
  3. What are the technical challenges to use this paradigm, especially when it comes to Electrical Engineering?
  4. How this paradigm is related to fewer bugs in the codebase?

Agenda

  • Research goals
  • Relevance
  • Electromagnetic transient analysis software
  • Functional Programming and Haskell
  • Haskell in Electromagnetic Transient Analysis - Implementation 

  • Results

  • Final considerations and future work

  • References

Engineering applications are strictly connected to computer programs

Alternative strategies (paradigms) in their programming languages analyse results under another perspective

Instead of treating the programming language paradigm as an invariant, it will be the object of study in this work

Model 1

Model 2

Model 3

Imperative programming

Functional programming

Agenda

  • Research goals
  • Relevance
  • Electromagnetic transient analysis software
  • Functional Programming and Haskell
  • Haskell in Electromagnetic Transient Analysis - Implementation 

  • Results

  • Final considerations and future work

  • References

Electromagnetic transient analysis is the use case adopted in this work

It has an essential role in Electrical Engineering - it can help to determine overcurrent, overvoltage and other unwanted phenomena in power systems 

There are multiple alternatives to simulate basic circuits. This work focuses on implementations of the Nodal Analysis method

The Nodal Admittance Matrix Model

[G][V]=[h]

Given a circuit (example below)

Organize the following matrix representation 

Iteratively simulate it over time

The Algorithm for the simulation

  1. Read the input data

  2. Build the steady-state solution matrix;

  3. Build the transient solution matrix (G);

  4. Find the steady-state solution to initialise histories;

  5. Assume t = ∆t;

  6. Evaluate current and voltage sources;

  7. Solve for node voltages;

  8. Update history functions;

  9. Increment t: t = t + ∆t;

  10. Go back to item 6 if the maximum simulation time hasn’t been reached.

Commercial 

Software

Academic

Software

ATP

EMTP-RV

ETRP-Matlab 

(UNIFEI and UBC)

ETRP-Python

(UNIFEI)

ETRP-Haskell

(UNIFEI)

Agenda

  • Research goals
  • Relevance
  • Electromagnetic transient analysis software
  • Functional Programming and Haskell
  • Haskell in Electromagnetic Transient Analysis - Implementation 

  • Results

  • Final considerations and future work

  • References

Haskell is an example of a functional programming language

The key ideas listed in the following slides are also key ideas for most of the functional languages (not limited to Haskell)

#1 - First class Functions

Functions are interpreted with the same idea of mathematical objects

f(x) = x+ x
double x = x + x

The '=' operator does not bind values to variables in functional languages.

#1 - First class Functions

a = 1
a = a + 10

The code above, which mutates the value of 'a', is inconsistent in a functional setting. It leads to a mathematical inconsistency.

#2 - Strong Type System

It is possible to organise values in collections called types.

In a functional language like Haskell, no runtime errors arise from type mismatches in function calls. This is called 'strong type system'

#3 - Polymorphic types

Functions also have a type.

Their types can be generalised. For example, a function can be applied to both Integer, Float and Double numbers, allowing a generalisation for any Number, requiring a Polymorphic type 'Num'.

#4 - Algebraic types

Types might be composed from other types

For example, the definition of a Component in a circuit certainly requires its value, if it is a R, L, C, or a source and the nodes in where it can be found. It can be represented with a Record:

data ComponentData = 
  ComponentData { 
    componentType :: ComponentType,
    nodeK :: Int,
    nodeM :: Int,
    magnitude :: Double,
  }
data ComponentType = Resistor | Capacitor | Inductor | EAC | EDC

Product Type

Sum Type

Haskell has some extra features on top of the previously listed: It is designed to be a lazy language, it offers support for higher-order functions and if has equational reasoning.

Other functional programming languages: 

SML, OCaml, Lisp, Erlang, Clojure, Scala

Agenda

  • Research goals
  • Relevance
  • Electromagnetic transient analysis software
  • Functional Programming and Haskell
  • Haskell in Electromagnetic Transient Analysis - Implementation

  • Results

  • Final considerations and future work

  • References

Codebase comparison:

Matlab and Haskell version of the ETR-P

ETR-P Program's goal: Run a simulation according to the algorithm proposed by H. Dommel[1].

Limitations: The Haskell version of this work does not include charts, triangular voltage sources, current sources and non-linear components yet. 

[1]H. W. Dommel, “Digital computer solution of electromagnetic transients in single-and multiphase networks,” IEEE transactions on power apparatus and systems, no. 4, pp. 388–399, 1969 

ETR-P Matlab

[2] P. Hudak, The Haskell school of expression: learning functional programming through multimedia. Cambridge University Press, 2000. 

"Programs in Haskell can be viewed as functions whose input is that of the problem being solved, and whose output is the desired result. "[2]

thtaSimulation :: Vector ComponentData -> SimulationData -> SimulationResults

The starting point of the Haskell code must reflect the project's goals

Which translates to the following function signature:

#1 Data Input

Haskell

Matlab

2 CSV Files

1 for the components info

1 for the simulation info

The Headers guide the user

1 single text file

Unstructured

Documentation guides the user

#1 Data Input

Haskell

Matlab

Element Type,Node K,Node M,Value,Source param 1,Source param 2,Plot
EDC,2,0,10,0,0,0 
R,2,1,10,0,0,0
L,1,0,1,0,0,0
Number of Nodes,Number of Voltages Sources,Step Size,Maximum time for simulation
2,1,0.0001,0.05
T   2   1   100E-6  50E-3    0   0   0   0   0
EDC 2   0   10      0       0   0   0   0   5
R   2   1   10      0       0   0   0   0   5
L   1   0   1       0       0   0   0   0   5
NV  1   2   0       0       0   0   0   0   0

#1 Data Input

Haskell

Matlab

Algebraic type for Components

data ComponentData = 
  ComponentData { 
    componentType :: ComponentType,
    nodeK :: Int,
    nodeM :: Int,
    magnitude :: Double,
    param1 :: Double,
    param2 :: Double
   }

data ComponentType = Resistor | Capacitor |
     Inductor | EAC | EDC

Free form;

relies on the 

input file

#2 Initial Setup

Haskell

Matlab

condutance :: ComponentData -> Double -> Double
condutance component dt =
  case componentType component of
    Resistor -> 1.0 / (magnitude component)
    Capacitor -> (magnitude component) * 0.000001 * 2 / dt
    Inductor -> dt / (2 * 0.001 * (magnitude component))
    _ -> 0.0
    
gkm :: Vector ComponentData -> Double -> Vector Double
gkm components dt =
  Vector.map (\c -> condutance c dt) components
for b = 2:bmax
    if strcmp(type(b), 'R') || strcmp(type(b), 'S')
        R = val4(b);
        gkm(b) = 1/R;
    elseif strcmp(type(b), 'L')
        L = val4(b)*1e-3; %mH
        gkm(b) = dt/(2*L);
    elseif strcmp(type(b), 'C')
        C = val4(b)*1e-6; %uF
        gkm(b) = 2*C/dt;
    elseif strcmp(type(b), 'TL')
        Zc = val4(b);
        gkm(b) = 1/Zc;
    end
end

#2 Initial Setup

Haskell

Matlab

condutance :: ComponentData -> Double -> Double
condutance component dt =
  case componentType component of
    Resistor -> 1.0 / (magnitude component)
    Capacitor -> (magnitude component) * 0.000001 * 2 / dt
    Inductor -> dt / (2 * 0.001 * (magnitude component))
    _ -> 0.0
    
gkm :: Vector ComponentData -> Double -> Vector Double
gkm components dt =
  Vector.map (\c -> condutance c dt) components
for b = 2:bmax
    if strcmp(type(b), 'R') || strcmp(type(b), 'S')
        R = val4(b);
        gkm(b) = 1/R;
    elseif strcmp(type(b), 'L')
        L = val4(b)*1e-3; %mH
        gkm(b) = dt/(2*L);
    elseif strcmp(type(b), 'C')
        C = val4(b)*1e-6; %uF
        gkm(b) = 2*C/dt;
    elseif strcmp(type(b), 'TL')
        Zc = val4(b);
        gkm(b) = 1/Zc;
    end
end

Pattern

Matching

#3 Simulation Loop

Haskell

Relies on Recursion

Uses modular, auxiliar functions

thtaSimulationStep :: [ComponentData] -> Matrix Double -> SimulationData -> Int -> Int -> Double 
     -> Vector Double -> Matrix Double -> Vector Double -> Vector Double -> SimulationResults
thtaSimulationStep _ _ _ _ 1 _ _ vMatrix _ iVector = (iVector, vMatrix)
thtaSimulationStep components condutances simulation thtactl n time ih vMatrix vbVector iVector =
  let (gaa, gab, gba, gbb) = Matrix.splitBlocks ((nodes simulation) - (voltageSources simulation)) 
         ((nodes simulation) - (voltageSources simulation)) condutances
      ihBuffer = buildIhVector (nhComponents components) (stepSize simulation) n 
         (Vector.toList ih) [] vMatrix
      (thta, ihThta, timeThta) = thtaControl thtactl time ihBuffer ih simulation
      vbVec = buildVBVector components timeThta []
      iVec = buildIVector (nhComponents components) (Vector.toList ihThta) (Vector.replicate 
         (nodes simulation) 0)
      (iVecCalc, vVec) = solver (toHMatrixVectorTransformer iVec) (toHMatrixTransformer gaa) 
           (toHMatrixTransformer gab) (toHMatrixTransformer gba) (toHMatrixTransformer gbb) 
               (toHMatrixVectorTransformer vbVec) simulation
      vMatr = Matrix.mapCol (\r _ -> vVec Vector.! (r - 1)) (n-1) vMatrix
  in
      thtaSimulationStep components condutances 
         simulation thta (n-1) timeThta ihThta vMatr vbVec iVecCalc   
https://github.com/hannelita/thtahs - Access on December 01st, 2019

Agenda

  • Research goals
  • Relevance
  • Electromagnetic transient analysis software
  • Functional Programming and Haskell
  • Haskell in Electromagnetic Transient Analysis - Implementation

  • Results

  • Final considerations and future work

  • References

DC Source

AC Source

Comparison - Imperative and Functional programming

Agenda

  • Research goals
  • Relevance
  • Electromagnetic transient analysis software
  • Functional Programming and Haskell
  • Haskell in Electromagnetic Transient Analysis - Implementation

  • Results

  • Final considerations and future work

  • References

Questions this work answers

  1. What are the benefits of functional programming?

Focus on the algorithm, not on array manipulation and temporary variables; mathematical reasoning of the code; not a single if/else block

Questions this work answers

  1. What are the benefits of functional programming?
  2. What are the benefits to the code base?

Several libraries available; the codebase is slightly more compact

  1. What are the benefits of functional programming?
  2. What are the benefits to the code base?
  3. What are the technical challenges to use this paradigm, especially when it comes to Electrical Engineering?

There are not many real world application examples using functional programming, especially in the Engineering domain. Selecting the appropriate types was also a challenge. 

Questions this work answers

  1. What are the benefits of functional programming?
  2. What are the benefits to the code base?
  3. What are the technical challenges to use this paradigm, especially when it comes to Electrical Engineering?
  4. How this paradigm is related to fewer bugs in the codebase?

The strong type system reduced the number of runtime errors. Most of the possible problems showed up in compile time.

Questions this work answers

Discussion

What about Object Oriented Programming?

It is also a valid approach to organise the code, but it is still subjected to the imperative programming paradigm

Example: ETR-Py

Work in progress - ETRP-Haskell

https://github.com/hannelita/thtahs/issues - access on December 01st, 2019

Future works

  • Comparison with other functional languages
  • Is there a better type system for electromagnetic transient analysis?
  • Code Correctness and proofs
  • Mathematical equivalence of code and the phenomena it represents

Future works

Model 1

Model 2

Model 3

Imperative programming

Optimisation

Performance

Bugs

Future works

Model 1

Model 2

Model 3

Fucntional programming

Optimisation

Performance

Bugs

Program correctness

Proofs

Type Theory

Agenda

  • Research goals
  • Relevance
  • Electromagnetic transient analysis software
  • Functional Programming and Haskell
  • Haskell in Electromagnetic Transient Analysis - Implementation

  • Results

  • Final considerations and future work

  • References

Academic work

  • Publication - Tavante HC, Bonatto BD, Coutinho MP. Open Source Implementations of Electromagnetic Transient Algorithms. In 2018 13th IEEE International Conference on Industry Applications (INDUSCON) 2018 Nov 12 (pp. 825-828). IEEE.
  • Workshop - Programming Languages Mentoring Workshop (PLMW) at ICFP 2018

  • Student Volunteer at Principles of Programming Languages (POPL) 2019

  • Student Volunteer at European Conference on Object-Oriented Programming (ECOOP) 2019

  • Student Volunteer at International Conference of Functional Programming (ICFP) 2019

  • TA - Functional Programming 101 course

Other works

References

Thank you!

defense

By Hanneli Tavante (hannelita)

Loading comments...

More from Hanneli Tavante (hannelita)