AER 1610
Computer Applications in Aerospace
Engineering
Assistant Professor:
Ahmed Mohamed Rashed Desoki
Aerospace Engineering Department,
Faculty of Engineering, Cairo University
Wednesday 21st February, 2024
Proudly created by
Except for the figures created by Matlab, this document has been created by Free and
open source software (FOSS). Special thanks go to the numerous generous developers
behind the following projects:
GNU project free software, mass collaboration project aiming to give users freedom
LATEX document markup language
TEX Live cross-platform LATEX distribution
MiKTEX LATEX distribution for Windows
LYX cross-platform LATEX-based document preparation system
Beamer LATEX class for creating presentation slides and handouts
Inkscape cross-platform vector graphics editor
TEX Text Inkscape plugin for creating and editing LATEX formulae
Other great projects I failed to mention . . .
Table of Contents
Table of Contents
i
List of Laboratories
xi
List of Codes
xiii
List of Suggested Projects
xv
Course Description
xvii
Course Assessment
xix
Course Guidelines
xix
Feedback
xix
Assignment List
xx
Abbreviations
xxi
1
1
Hardware
1.1 History of Computer
1.1.1
Dawn of Mechanical Computers . . . . . . . . . . . . . . . . . . . . . .
1.1.2
First Generation (1937–1946); Dawn of Electronic Computers . . . . . .
1.1.3
Second Generation (1947–1962); Dawn of the Operating System (OS) . .
1.1.4
Third Generation; Dawn of Transistors . . . . . . . . . . . . . . . . . . .
1.1.5
Parallel Computing Generation . . . . . . . . . . . . . . . . . . . . . . .
1.1.6
Future of Computers . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2
2
2
3
4
5
7
1.2 The Personal Computer (PC)
7
1.3 The Central Processing Unit (CPU)
1.3.1
CPU Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.3.2
Parallel Computing . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.3.2.1 Symmetric Multiprocessing (SMP) . . . . . . . . . . . . . . . . . . . .
1.3.2.2 Distributed Processing . . . . . . . . . . . . . . . . . . . . . . . . . .
1.3.3
Heterogeneous Computing . . . . . . . . . . . . . . . . . . . . . . . . .
1.3.3.1 The Graphical Processing Unit (GPU) . . . . . . . . . . . . . . . . . .
13
13
14
14
15
17
19
1.4 The Embedded Computer
1.4.1
The Microcontroller . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
22
23
1.5 Additional Information
1.5.1
The MSX Home Computer . . . . . . . . . . . . . . . . . . . . . . . . .
1.5.2
PC Evolution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.5.3
RAID Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.5.4
Computer Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
24
24
26
28
29
i
1.5.5
Top 500 Supercomputer Statistics . . . . . . . . . . . . . . . . . . . . . .
33
1.6 Questions
36
2
39
Software
2.1 Open–Source Software (OSS)
2.1.1
The License . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.1.2
FOSS vs Commercial–SW . . . . . . . . . . . . . . . . . . . . . . . . .
39
40
41
2.2 The Operating System (OS)
2.2.1
OS Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.2.2
History of Operating Systems . . . . . . . . . . . . . . . . . . . . . . . .
2.2.2.1 Unix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.2.2.2 BSD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.2.2.3 Apple Macintosh OS . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.2.2.4 GNU Linux OS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.2.2.5 DOS and Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.2.2.6 OS/2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.2.2.7 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.2.3
Comparisons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
47
48
50
52
52
53
54
57
59
59
59
2.3 SW Applications
2.3.1
Cross–Platform Application SW . . . . . . . . . . . . . . . . . . . . . .
2.3.2
Bloat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
62
62
62
2.4 Malware
2.4.1
Tuning MS Windows against Viruses . . . . . . . . . . . . . . . . . . . .
64
69
2.5 Additional Information
2.5.1
Fork vs Branch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.5.2
Character Encoding . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.5.3
Data Backup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
71
71
71
72
2.6 Laboratory Work
2.6.1
Windows Viruses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.6.2
Install Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.6.3
Install Linux . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
73
73
73
76
2.7 Questions
79
3
81
Networks and the Internet
3.1 Network Topology
86
3.2 Network Hardware
3.2.1
More Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
87
91
3.3 Logical Networks
93
ii
3.3.1
Sample Logical Networks . . . . . . . . . . . . . . . . . . . . . . . . . .
93
3.4 The Internet
95
3.4.1
The Internet Protocol Suite (TCP/IP) . . . . . . . . . . . . . . . . . . . . 97
3.4.2
The IP Address . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
3.4.3
The Router . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
3.4.4
All-in-one SOHO Network Hardware . . . . . . . . . . . . . . . . . . . . 107
3.4.5
Host Name Resolution . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
3.4.6
The Whole Picture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
3.5 Network Security
117
3.5.1
The Firewall . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
3.6 Cloud Computing
120
3.7 Privacy
121
3.8 Laboratory Work
127
3.8.1
Point-to-Point Connection . . . . . . . . . . . . . . . . . . . . . . . . . . 127
3.8.2
Sharing a Directory over Network . . . . . . . . . . . . . . . . . . . . . . 129
3.9 Project Ideas
137
3.10 Questions
138
4
143
Scientific Computing and Visualization using Matlab
4.1 Introduction
4.2 Basics
4.2.1
4.2.2
4.2.3
4.2.4
143
145
Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
Saving, Clearing and Re–loading Variables . . . . . . . . . . . . . . . . . 153
4.3 Array Arithmetic
155
4.3.1
Matrix Arithmetic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
4.4 Accessing Arrays
159
4.4.1
The Comma–Separated List . . . . . . . . . . . . . . . . . . . . . . . . . 163
4.5 Programming
164
4.5.1
Flow Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
4.5.2
Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
4.5.3
Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
4.5.3.1 Advanced Topics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
4.5.3.2 Types of Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
4.5.4
Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
4.5.4.1 Calculating Sine by Taylor Series . . . . . . . . . . . . . . . . . . . . . 172
4.5.4.2 Root–Finding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176
iii
4.5.5
Improving Code Performance . . . . . . . . . . . . . . . . . . . . . . . . 177
4.6 Visualization
178
4.6.1
2D Visualization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
4.6.2
3D Visualization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
4.6.2.1 Tweaking Rectangular Grids . . . . . . . . . . . . . . . . . . . . . . . 196
4.6.3
Overriding Default Graphics Properties . . . . . . . . . . . . . . . . . . . 197
4.6.4
Exporting Figures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198
4.7 Debugging
199
4.8 OOP in Matlab
201
4.8.1
Class Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
4.8.2
Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204
4.8.3
Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
4.8.4
Dynamic Referencing . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208
4.8.5
Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208
4.8.5.1 Inheriting Multiple Classes . . . . . . . . . . . . . . . . . . . . . . . . 212
4.8.6
Documenting Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
4.8.7
Object Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
4.8.7.1 Designing Methods to Handle Object Arrays . . . . . . . . . . . . . . . 217
4.8.7.2 Arrays of Objects of Different Classes . . . . . . . . . . . . . . . . . . 223
4.8.8
Handle Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
4.8.9
More Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
4.9 Further Topics
227
4.10 FOSS Alternatives
228
4.11 Laboratory Work
229
4.12 Problems
230
5
257
Serious Programming
5.1 Programming Languages
257
5.1.1
Compiled vs. Interpreted Languages . . . . . . . . . . . . . . . . . . . . 258
5.1.2
Programming Language Standardization . . . . . . . . . . . . . . . . . . 258
5.1.3
The Fortran Programming Language . . . . . . . . . . . . . . . . . . . . 259
5.1.4
C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261
5.2 The Compiler
261
5.2.1
Compiler Optimization . . . . . . . . . . . . . . . . . . . . . . . . . . . 262
5.2.2
The Preprocessor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263
5.2.3
The Linker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264
5.2.4
Notable Compilers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266
5.2.4.1 MS Visual C++ (MSVC) Compiler . . . . . . . . . . . . . . . . . . . . 266
5.2.4.2 Intel Compilers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266
5.2.4.3 The GNU Toolchain . . . . . . . . . . . . . . . . . . . . . . . . . . . 266
iv
5.2.4.4 Other Compilers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266
5.3 Build Systems
267
5.3.1
make . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267
5.3.2
The Integrated Development Environment (IDE) . . . . . . . . . . . . . . 267
5.3.3
CMake . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
5.3.4
Ninja . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
5.4 Software Libraries
270
5.4.1
Notable Scientific Software Libraries . . . . . . . . . . . . . . . . . . . . 270
5.5 Useful Tools
276
5.5.1
Documentation Generator . . . . . . . . . . . . . . . . . . . . . . . . . . 276
5.5.2
Revision Control System (RCS) . . . . . . . . . . . . . . . . . . . . . . . 276
5.5.3
Regular Expressions (RegEx) . . . . . . . . . . . . . . . . . . . . . . . . 278
5.6 Laboratory Work
280
5.6.1
Matlab MEX-Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280
5.6.2
Building and Debugging MEX-Files . . . . . . . . . . . . . . . . . . . . 283
5.6.2.1 Building using Matlab’s “mex” Script . . . . . . . . . . . . . . . . . . 283
5.6.2.2 Building and Debugging using Visual Studio . . . . . . . . . . . . . . 284
5.6.2.3 Building and Debugging using Visual Studio Code . . . . . . . . . . . 287
5.6.2.4 Building using GNU-make . . . . . . . . . . . . . . . . . . . . . . . . 289
5.6.2.5 Building using CMake . . . . . . . . . . . . . . . . . . . . . . . . . . 294
5.6.2.6 Building and Debugging using Eclipse . . . . . . . . . . . . . . . . . . 295
5.7 Questions
297
6
299
Matlab Alternatives
6.1 Sample Matlab Codes
301
6.1.1
Simple Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301
6.1.2
Comprehensive Example . . . . . . . . . . . . . . . . . . . . . . . . . . 303
6.2 Porting Matlab to C
317
6.2.1
The Simple Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317
6.3 Porting Matlab to Fortran
318
6.3.1
The Simple Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319
6.3.2
The Comprehensive Example . . . . . . . . . . . . . . . . . . . . . . . . 319
6.4 Porting Matlab to C++
323
6.4.1
The valarray Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323
6.4.2
The Simple Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324
6.4.3
The Matrix Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325
6.4.4
The Comprehensive Example . . . . . . . . . . . . . . . . . . . . . . . . 325
6.4.5
Armadillo Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329
6.4.6
The Comprehensive Example Again . . . . . . . . . . . . . . . . . . . . 330
v
6.5 Porting Matlab to Python
333
6.5.1
Simple Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333
6.5.2
Comprehensive Example . . . . . . . . . . . . . . . . . . . . . . . . . . 335
6.6 Porting Matlab to Julia
345
6.6.1
Simple Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345
7
Technical Writing and Presentation
347
7.1 LATEX
348
7.2 LYX
352
7.3 Beamer
355
7.4 Microsoft Word
359
7.5 Laboratory Work
369
7.5.1
Technical Writing using LYX . . . . . . . . . . . . . . . . . . . . . . . . 369
7.5.2
Presenting using Beamer . . . . . . . . . . . . . . . . . . . . . . . . . . 369
7.5.3
Technical Writing using MS Word . . . . . . . . . . . . . . . . . . . . . 369
7.6 Questions
370
8
371
Vector Graphics
8.1 Inkscape
374
8.1.1
Interesting Plug-ins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377
8.1.1.1 Function Plotter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377
8.1.1.2 TexText . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377
8.1.2
Learning Inkscape . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 378
8.2 Laboratory Work
379
8.2.1
Vector Graphing using Inkscape . . . . . . . . . . . . . . . . . . . . . . 379
9
Computer-Aided Design
381
9.1 Assignments
383
10
385
Project
10.1 Suggested Project Ideas
386
10.2 Work Groups
387
10.3 Work Plan
388
10.4 Preliminary Report
389
vi
10.5 Presentation
389
10.6 Report
390
10.7 Grading
391
Appendices
393
A
Tuning Windows
393
B
Brief Introduction to Linux
399
B.1
Notable Linux Distributions . . . . . . . . . . . . . . . . . . . . . . . . . 400
B.2
CLI Shell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403
B.3
GUI Shells . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407
B.4
Linux File System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 409
B.5
Installing SW . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 410
B.6
More Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413
C
Useful SW Applications
415
C.1
Useful Cross–Platform Applications . . . . . . . . . . . . . . . . . . . . 415
C.2
Useful Applications for Windows . . . . . . . . . . . . . . . . . . . . . . 415
C.3
Useful Applications for Linux . . . . . . . . . . . . . . . . . . . . . . . . 416
D
Data Backup
417
E
Data Rates
421
F
Introduction to Object Oriented Programming
425
G
GNU Toolchain
429
G.1
GNU Compiler Collection (GCC) . . . . . . . . . . . . . . . . . . . . . . 429
G.1.1 GCC Compiler/Linker Options . . . . . . . . . . . . . . . . . . . . . . 429
G.2
GNU Debugger (GDB) . . . . . . . . . . . . . . . . . . . . . . . . . . . 431
G.3
GNU Toolchain . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 431
G.4
GNU Toolchain for Windows . . . . . . . . . . . . . . . . . . . . . . . . 433
H
Doxygen
I
Make
I.1
I.2
J
Ninja (Draft)
449
K
CMake (Draft)
451
L
Visual Studio
453
M
Eclipse
457
M.1
Installing Eclipse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 458
435
437
Text Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443
Additional Topics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443
vii
M.2
M.3
Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 460
Project Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463
M.3.1 Managed Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 465
M.3.2 Makefile-based Projects . . . . . . . . . . . . . . . . . . . . . . . . . . 467
M.4
Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 470
M.5
Indexing and Refactoring . . . . . . . . . . . . . . . . . . . . . . . . . . 472
N
Visual Studio Code (Draft)
475
O
Scientific Computing and Visualization using Python
479
O.1
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 479
O.1.1 Installing Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 482
O.1.2 Python 2 or 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 483
O.1.3 Interactive Shells . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 483
O.1.4 Notable Python IDE’s . . . . . . . . . . . . . . . . . . . . . . . . . . . 488
O.1.5 Importing Packages, Modules, Functions, . . . . . . . . . . . . . . . . . 489
O.2
Standard Python Tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . 492
O.3
Scientific Computing with Python . . . . . . . . . . . . . . . . . . . . . 494
O.3.1 NumPy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 495
O.3.2 SciPy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 499
O.3.3 matplotlib . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 500
O.3.4 Pandas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 501
O.3.5 Bokeh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 502
O.3.6 SymPy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 504
O.4
Call FORTRAN, C and Matlab from Python . . . . . . . . . . . . . . . . 504
O.4.1 Call FORTRAN from Python . . . . . . . . . . . . . . . . . . . . . . . 504
O.4.2 Call C from Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . 504
O.4.3 Call MATLAB from Python . . . . . . . . . . . . . . . . . . . . . . . 504
O.4.4 Call Python from MATLAB . . . . . . . . . . . . . . . . . . . . . . . 505
O.5
Python Alternatives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 505
P
Scientific Computing and Visualization using Julia
507
P.1
Learning Julia . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 510
P.2
Julia vs Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 513
P.3
Julia REPL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 514
P.4
Tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 514
P.5
Methods of a Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . 515
P.6
OOP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 516
P.7
Visualization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 517
P.8
Tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 518
P.9
Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 518
P.10
Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 519
P.11
Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 521
P.11.1 Defining functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 521
P.11.2 More on anonymous functions . . . . . . . . . . . . . . . . . . . . . . 522
P.11.3 Void functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 522
P.11.4 Optional positional arguments . . . . . . . . . . . . . . . . . . . . . . 523
P.11.5 Keyword arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . 523
P.11.6 Performance tip . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 524
viii
P.11.7 Function documentation . . . . . . . . . . . . . . . . . . . . . . . . . 524
P.12
Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 524
P.12.1 Vectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 524
P.12.2 Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 525
P.12.3 N–dimensional Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . 526
P.12.4 Slices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 526
P.12.5 Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 527
P.12.6 Tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 527
P.12.7 Splatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 528
P.12.8 Named tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 528
P.12.9 Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 529
P.13
Control Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 529
P.13.1 If . . . else . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 529
P.14
Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 530
P.14.1 For loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 530
P.14.2 Break . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 531
P.14.3 Continue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 531
P.14.4 While loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 531
P.14.5 Enumerate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 532
P.15
Working with arrays: broadcasting . . . . . . . . . . . . . . . . . . . . . 533
P.16
Operations with arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . 533
P.17
Broadcasting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 533
P.18
Variable Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 534
P.18.1 Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 534
P.18.2 Local Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 535
P.18.3 let construct . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 536
P.18.4 Global scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 537
P.18.5 Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 537
P.18.6 Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 537
P.19
Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 538
P.19.1 Working with modules . . . . . . . . . . . . . . . . . . . . . . . . . . 538
P.19.2 Code inclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 540
P.19.3 Code documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . 541
P.20
Types and Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 543
P.20.1 Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 544
P.20.2 Functions and types: multiple dispatch . . . . . . . . . . . . . . . . . . 545
P.21
Type constructor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 546
P.21.1 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 547
P.22
Working with Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . 548
P.22.1 Creation of a package . . . . . . . . . . . . . . . . . . . . . . . . . . . 548
P.22.2 Using a user defined package . . . . . . . . . . . . . . . . . . . . . . . 549
P.22.3 Adding dependencies . . . . . . . . . . . . . . . . . . . . . . . . . . . 550
P.22.4 Package initialisation . . . . . . . . . . . . . . . . . . . . . . . . . . . 551
P.23
Coding workflow with VSCode . . . . . . . . . . . . . . . . . . . . . . . 551
P.23.1 Revise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 551
P.23.2 Code formatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 551
P.24
Multi panel coding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 552
P.24.1 Split up/down/right/left . . . . . . . . . . . . . . . . . . . . . . . . . . 552
ix
P.24.2 Split in group . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 553
P.24.3 Code navigation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 554
P.24.4 Find and replace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 554
P.24.5 Multi line cursor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 554
P.24.6 Documentation panel . . . . . . . . . . . . . . . . . . . . . . . . . . . 555
P.24.7 Variable explorer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 555
P.24.8 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 556
P.24.9 Breakpoints and code navigation . . . . . . . . . . . . . . . . . . . . . 557
P.24.10 Debugger panels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 559
P.24.11 Editing the function namespace . . . . . . . . . . . . . . . . . . . . . . 560
P.24.12 Function profiling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 562
P.24.13 Profile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 562
P.24.14 Problem tab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 565
P.24.15 TODO explorer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 566
Q
Examples on Properties of Symmetric/Anti-Symmetric Cross-sections
569
References
575
Index
577
x
List of Laboratories
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Windows Viruses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
Install MS Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
Tuning Windows PC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
Install Linux . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
Point-to-Point Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
Sharing Files over a LAN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
Creating Matlab Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
Create Matlab Script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
Code Improvement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
Create Matlab Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
Root–Finding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
2D Graphing–I . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
2D Graphing–II . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
2D & 3D Graphing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
3D Graphing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
OOP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
Building and Debugging MEX-File using Visual Studio . . . . . . . . . . . . . 284
Debugging MEX-Files using Visual Studio Code . . . . . . . . . . . . . . . . 287
Building MEX-File using GNU-make . . . . . . . . . . . . . . . . . . . . . . 289
Building and Debugging MEX-Files using Eclipse . . . . . . . . . . . . . . . . 295
Technical Writing using LYX . . . . . . . . . . . . . . . . . . . . . . . . . . . 369
Presenting using Beamer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369
Technical Writing using MS Word . . . . . . . . . . . . . . . . . . . . . . . . 369
Vector Graphing using Inkscape . . . . . . . . . . . . . . . . . . . . . . . . . 379
xi
This page is intentionally left blank!
xii
List of Codes
4.1 function myFunc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
4.2 function ourSine1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
4.3 function ourSine2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
4.4 function ourSine3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
4.5 function ourSine4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174
4.6 Sine MainScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
4.7 cArea simple.m . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
4.8 cDistantArea simple.m . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208
4.9 cArea.m . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
4.10 cDistantArea.m . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218
4.11 File cCmAr.m . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
4.12 File test cCmAr.m . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223
4.13 “cValueClass” Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
4.14 “cHandleClass” Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
4.15 ISA main script.m . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234
4.16 MainScript.m . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
4.18 FreeResponse main script.m . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
4.22 SDOF FRF MainScript.m . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246
5.3 Compile and Link the MEX-files using Visual Studio . . . . . . . . . . . . . . 284
5.4 Makefile for building MEX-files . . . . . . . . . . . . . . . . . . . . . . . . . 289
6.1 Free Response Matlab function . . . . . . . . . . . . . . . . . . . . . . . . . 301
6.2 FreeResponse main Matlab script . . . . . . . . . . . . . . . . . . . . . . . . 301
6.3 MDOF FRF Visc slow Matlab function . . . . . . . . . . . . . . . . . . . . . . 303
6.4 quad eig Matlab function . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303
6.5 MDOF Eig Visc Matlab function . . . . . . . . . . . . . . . . . . . . . . . . . 303
6.6 MDOF FRF Visc Matlab function . . . . . . . . . . . . . . . . . . . . . . . . . 304
6.7 plot FRF 3d Matlab function . . . . . . . . . . . . . . . . . . . . . . . . . . 305
6.8 plot FRF Nyq Matlab function . . . . . . . . . . . . . . . . . . . . . . . . . . 307
6.9 plot FRF r i Matlab function . . . . . . . . . . . . . . . . . . . . . . . . . . 308
6.10 plot FRF mag phase Matlab function . . . . . . . . . . . . . . . . . . . . . . 309
6.11 N DOF sys Matlab function . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312
6.12 correctedPhase Matlab function . . . . . . . . . . . . . . . . . . . . . . . . 313
6.13 MDOF FRF Visc main Matlab script . . . . . . . . . . . . . . . . . . . . . . . 314
6.14 C implementation of code 6.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . 317
6.15 Fortran implementation of code 6.1 . . . . . . . . . . . . . . . . . . . . . . . . 319
6.16 Fortran implementation of code 6.3 . . . . . . . . . . . . . . . . . . . . . . . . 319
6.17 Fortran implementation of code 6.4 . . . . . . . . . . . . . . . . . . . . . . . . 320
6.18 Fortran implementation of code 6.5 . . . . . . . . . . . . . . . . . . . . . . . . 320
6.19 Fortran implementation of code 6.6 . . . . . . . . . . . . . . . . . . . . . . . . 322
6.20 C++ implementation of code 6.1 . . . . . . . . . . . . . . . . . . . . . . . . . 324
6.21 C++ implementation of code 6.3 . . . . . . . . . . . . . . . . . . . . . . . . . 325
6.22 C++ implementation of code 6.4 . . . . . . . . . . . . . . . . . . . . . . . . . 326
6.23 C++ implementation of code 6.5 . . . . . . . . . . . . . . . . . . . . . . . . . 327
6.24 C++ implementation of code 6.6 . . . . . . . . . . . . . . . . . . . . . . . . . 328
6.25 C++ implementation of code 6.4 . . . . . . . . . . . . . . . . . . . . . . . . . 330
6.26 C++ implementation of code 6.5 . . . . . . . . . . . . . . . . . . . . . . . . . 330
xiii
6.27 C++ implementation of code 6.6 . . . . . . . . . . . . . . . . . . . . . . . . . 331
6.28 Python implementation of code 6.1 . . . . . . . . . . . . . . . . . . . . . . . . 333
6.29 Python implementation of code 6.2 . . . . . . . . . . . . . . . . . . . . . . . . 334
6.30 Python implementation of code 6.3 . . . . . . . . . . . . . . . . . . . . . . . . 335
6.31 Python implementation of code 6.4 . . . . . . . . . . . . . . . . . . . . . . . . 335
6.32 Python implementation of code 6.5 . . . . . . . . . . . . . . . . . . . . . . . . 335
6.33 Python implementation of code 6.6 . . . . . . . . . . . . . . . . . . . . . . . . 336
6.34 Python implementation of code 6.7 . . . . . . . . . . . . . . . . . . . . . . . . 337
6.35 Python implementation of code 6.8 . . . . . . . . . . . . . . . . . . . . . . . . 338
6.36 Python implementation of code 6.9 . . . . . . . . . . . . . . . . . . . . . . . . 338
6.37 Python implementation of code 6.10 . . . . . . . . . . . . . . . . . . . . . . . 339
6.38 Python implementation of code 6.11 . . . . . . . . . . . . . . . . . . . . . . . 341
6.39 Python implementation of code 6.12 . . . . . . . . . . . . . . . . . . . . . . . 341
6.40 Python implementation of code 6.13 . . . . . . . . . . . . . . . . . . . . . . . 342
6.41 Julia implementation of code 6.1 . . . . . . . . . . . . . . . . . . . . . . . . . 345
6.42 Julia implementation of code 6.2 . . . . . . . . . . . . . . . . . . . . . . . . . 346
H.1 Shell script to install doxygen and doxywizard. . . . . . . . . . . . . . . . . . 435
I.1 file1.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 438
I.2 file2.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 438
I.3 file3.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 438
I.4 header1.h . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 438
I.5 header2.h . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 438
I.6 header3.h . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 438
I.7 A modest Makefile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 438
I.8 Sample Pattern Rule . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441
I.9 Sample Suffix Rule . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 442
I.10 Debug and Release Makefile . . . . . . . . . . . . . . . . . . . . . . . . . . . 445
I.11 Pictorial part of a makefile . . . . . . . . . . . . . . . . . . . . . . . . . . . . 447
xiv
List of Suggested Projects
xv
This page is intentionally left blank!
xvi
Course Description
Title Computer Applications in Aerospace Engineering∗
Code AER 1610
Instructor
Assistant prof. Ahmed Mohamed Rashed Desoki
Office Hours
• Monday; after 11:00 a.m.
• Thursday; after 12:00 p.m.
Credit Hours 4 (1 lecture + 1 tutorial + 2 laboratory)
( 12 lecture + 12 tutorial + 1 laboratory)/week
Grade 75 (15 term work + 15 project + 45 final exam)
Tutorials/Laboratories will be
• Once week, section 1 then section 2
• Next week, section 2 then section 1
1
Course Objectives
To know most important/necessary computer facts/skills/concepts
2
Learning Outcomes (LO’s)
1. Describe computer hardware (HW)
2. Describe operating systems (OS’s) and software (SW)
3. Design and effectively use simple SOHO LANs
4. Solve problems and visualize results using Matlab
5. Describe general concepts of serious programming
6. Create professional documents, presentations, handouts and vector graphics
3
∗
Applications means application software, i.e. programs.
xvii
xviii
Lab.
Chapter
1
Hardware
2
Software
3
Networks and the Internet
4
Scientific Computing and Visualization using Matlab
5
Serious Programming
6
Matlab Alternatives
7
Technical Writing and Presentation
8
Vector Graphics
9
Computer-Aided Design
10
Project
Total
Lect./Tutor.
Course Topics
1.5
1.5
2
5
1
2
1
8
1
1
0.5
0.5
1
14
1
1
14
Course Assessment
Assessment Type
Reports
Laboratories
Midterm
Final Exam
Total
Weight (%)
10
10
10
45
75
5
Course Guidelines
General Guidelines
• Late assignments are not accepted
Cheating is prohibited
• If you submitted a copy of your friend’s work, both of you will be graded as zero
Plastic covers of submitted reports are prohibited
• Just use stables
6
Feedback
At the end of every lecture, you are highly encouraged to send me an A5 note with your:
• opinions/suggestions
• what you want to learn in the next lecture/section
7
xix
Assignment List
#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Assignment Name
Due date
xx
Abbreviations
ABC Atanasoff-Berry Computer
DNS Domain Name System
ACL Access Control List
DOS Disk Operating System
AI
Artificial Intelligence
DP
DisplayPort
API
Application Programming Interface
EB
Exa byte
ECC Error–Correcting Code
APSL Apple Public Source License
EiB
ASIC application-specific integrated circuit
Exbibyte
EU’s Execution Units
AWS Amazon Web Services
FMA Fused Multiply–Add
bash
FOSS Free and Open-Source Software
Bourne Again SHell
BLAS Basic Linear Algebra Subprograms
FP16 16–bit floating–point
BSD Berkeley Software Distribution
FP32 32 bit floating-point
FP32 32–bit floating–point
CAD Computer Aided Design/Drafting
FP64 64–bit floating–point
CAE Computer Aided Engineering
FPGA Field-Programmable Gate Array
CAM Computer Aided Manufacturing
FRF
Frequency Response Function
CAPE Computer Aided Production Engineering
GB
Giga byte
CAS Computer Algebra System
GCC GNU Compiler Collection
CC
Creative Commons
CD
Compact Disc
GDB GNU Symbolic Debugger
GiB
Gibibyte
GPL General Public License
CDT C/C++ Development Tools
GPU Graphics Processing Unit
CIFS Common Internet File System
GUI
CLI
Command Line Interface
CPL
Common Public License
Graphical User Interface
HBM High-Bandwidth Memory
HDD Hard Disk
CPU Central Processing Unit
HPC High Performance Computing
CWD Current Working Directory
HPC High Performance Computing
DHCP Dynamic Host Configuration Protocol
HW
Hardware
IaaS
Infrastructure as a Service
DL
Deep Learning
dll
dynamic link library
IANA Internet Assigned Numbers Authority
xxi
IDE
Integrated Development Environment
MPL Mozilla Public License
MS
IEEE Institute of Electrical and Electronics Engineers
Microsoft
MSBuild Microsoft Build Engine
MSYS Minimal System
IP
Internet Protocol
ISP
Internet Service Provider
ISV
Independent Software Vendor
JDK
Java Development Kit
JIS
Japanese Industrial Standards
JIT
Just-In-Time
kB
Kilo byte
NetBIOS Network
System
KiB
Kibibyte
NIC
L2
Layer 2
NVM Non-Volatile Memory
L3
Layer 3
NVMe NVM Express
LA
Link Aggregation
OMPC Open-Source
Compiler
MULTICS Multiplexed Operating
Computing System
and
NAS Network Attached Storage
NAT Network Address Translation
NBNS NetBIOS Name Service
LACP Link Aggregation Control Protocol
OO
LAG Link Aggregation Group
Basic
Input/Output
Network Interface Controller
Matlab-to-Python
Object Oriented
OOP Object Oriented Programming
LAN Local Area Network
OS
Operating System
LAPACK Linear Algebra Package
OSS
Open Source Software
LGPL Lesser General Public License
P2P
Peer-to-peer
LLVM Low-Level Virtual Machine
PaaS Platform as a Service
MAC Matrix–Multiply–Accumulate
PB
Peta byte
Malware Malicious Software
PC
Personal Computer
MB
Mega byte
pdf
Portable Document Format
Mbps Mega bit/second
PiB
Pebibyte
MEX Matlab EXecutable
PIC
Position Independent Code
MiB
PM
Package Manager
MinGW Minimalist GNU for Windows
PPA
Personal Package Archive
MKL Math Kernel Library
QDOS Quick and Dirty Operating System
modem modulator/demodulator
QoS
Mebibyte
xxii
Quality of Service
RaaS Ransomware as a Service
SW
Software
RAM Random Access Memory
TB
Tera byte
RCS
TCP
Transmission Control Protocol
Revision Control System
RegEx Regular Expression
TDP Thermal Design Power
REPL Read–Eval–Print Loop
TiB
RHEL Red Hat Enterprise Linux
UDP User Datagram Protocol
rpm
Red Hat Package Manager
UEFI Unified Extensible Firmware Interface
RT
Ray Tracing
UI
RTOS Real Time Operating System
Tebibyte
User Interface
SaaS Software as a Service
UNICS Uniplexed Operating and Computing System
SAS
VLAN Virtual Local Area Network
Serial Attached SCSI
SDN Software-Defined Networking
VPN Virtual Private Networks
SLE
VRAM Video RAM
SUSE Linux Enterprise
SMB Server Message Block
VS
SMP Symmetric Multiprocessing
WAN Wide Area Network
Wi-Fi Wireless Fidelity
SNMP Simple Network Management Protocol
so
Visual Studio
WINS Windows Internet Name Service
shared object
WSL Windows Subsystem for Linux
SOHO Small Office/Home Office
YB
Yotta byte
SSD
Solid State Drive
YiB
Yobibyte
STL
Standard Template Library
ZB
Zetta byte
SUS
Single Unix Specification
ZiB
Zebibyte
xxiii
This page is intentionally left blank!
xxiv
Part 1
Hardware
References
1. Wikipedia: the free encyclopedia (http://en.wikipedia.org)
2. The Internet
3. Gadgets, Games, Robots and the Digital World, Dorling Kindersley Publishing, 2011 [1]
• Arabic translation is available at Misr Public Library (www.mpl.org.eg)
9
PROCESSOR
STORAGE
OUTPUT
INFORMATION
INPUT
What is a Computer?
It is an electronic device that executes a set of instructions∗ to perform calculations and to retrieve/manipulate/store information.
INFORMATION
Examples
• Personal Computer (PC)
• Smart phone
• Calculator
• Digital watch
• Digital camera
• Digital satellite receiver
• ...
10
Hardware vs Software
Simply;
• hardware (HW) are the computer physical parts that you can touch
• software (SW) are the programs executed on the HW
11
∗
Instructions set is called “program”
1
1.1
History of Computer
1.1.1
Dawn of Mechanical Computers
Babbage’s Analytical Engine, 1837
Computers had their beginning with a 19th century English mathematics professor named
Charles Babbage.
• He designed the Analytical Engine
• The basic framework of computers are based on this engine
1.1.2
First Generation (1937–1946); Dawn of Electronic Computers
• In 1937 the first electronic digital computer was built by Dr. John V. Atanasoff and
Clifford Berry
– It was called the “Atanasoff–Berry Computer” (ABC)
2
• In 1943, an electronic computer named “Colossus” was built by the English for breaking
German ciphers during World War II
• Developments continued until the first general–purpose digital computer, the “Electronic
Numerical Integrator and Computer” (ENIAC), was built in 1946
– This computer weighed 30 tons, and had 18,000 vacuum tubes
– When it was turned on for the first time, lights dimmed in sections of Philadelphia
Vacuum Tube module
• Computers of this generation could only perform single task, and they had no Operating
System (OS)
13
1.1.3
Second Generation (1947–1962); Dawn of the Operating System
(OS)
• In 1951, the first computer for commercial use was introduced to the public; the “Universal
Automatic Computer” (UNIVAC)
• In 1953 the International Business Machine (IBM) 650 and 700 series computers made
their mark in the computer world
3
An IBM 650 at Texas A&M University. The IBM 533 card
reader and punch is on the right.
• These computers had memory and OS
– Storage media such as tape and disk were in use
– Also printers were used for output
– Over 100 computer programming languages were developed
1.1.4
Third Generation; Dawn of Transistors
Third Generation (1963–present)
Intel 8742 8–bit microcontroller IC
This generation used transistors instead of vacuum tubes.
• Computers became smaller, powerful, reliable and able to run several programs at the
same time∗
• In 1981, IBM introduced the personal computer (PC) for home and office use
• In 1983, Microsoft and ASCII† introduced the MSX‡ home computer
• In 1984, Apple introduced the Macintosh computer
∗
This is called multi–tasking.
a Japanese company
‡
[sec. 1.5.1]
†
4
1.1.5
Parallel Computing Generation
Moore’s Law
16
Processor Clock–Speed Limits
10000
1000
1000
Surface of the sun
Ro c ke t No zzle
Nu c le a r Re a c to r
100
Pentium III
Pentium 4
Pentium II
Ho t P la te
10
Pentium Pro
Pentium
i486
i386
1
10
5
1
0.1
0.01
Serial Computing Era
Parallel Computing Era
Moore's law
Saturated
Saturated
• The higher the processor speed, the more power/heat is consumed/generated
• This is why there is hardly PC processors over 3.7 GHz
• Highest clock speeds are stuck between 8.5 and 9 GHz and require liquid Nitrogen cooling
Serial Computing
Until recently most computers were serial computers.
• Such computers have a single processor
– For PC’s, the Pentium 4 is a notable example of this era
∗ It was very fast but also very hot
∗ Hence it demanded strong coolers leading to heavy weights and high power
consumption
∗ Laptops became heavy and hot
– For supercomputers of the 1990s, such as the Cray, they were extremely expensive
(usually over $1,000,000) and often required cooling by liquid Helium
∗ therefore just running them was also very expensive
Parallel Computing
Parallel computing is based on the idea that if multiple tasks could be processed simultaneously
on multiple processors, then a program would be able to run more rapidly than it could on a
single processor.
• For PC’s, the Core 2 Duo is a notable example of this new era
6
– It consumed less power and dissipated less heat
∗ Laptops became lighter
∗ By 2008, most new PCs contained more than one processor
• For supercomputers, clusters have been, since 1994, a much cheaper solution to the problem of fast processing
• Having multiple processors does not necessarily mean that parallel computing will occur
automatically
– The programming language, used to write a program, and the OS both must be able
to distribute tasks between processors
19
1.1.6
Future of Computers
Quantum Computing
• https://en.wikipedia.org/wiki/Quantum_computing
20
1.2
The Personal Computer (PC)
HW of the Personal Computer (PC)
1. Monitor
2. Motherboard
3. CPU
4. RAM
5. Graphics and expansion
cards
6. Power supply
7. Optical disc drive
7
8. Hard disk drive
9. Keyboard
10. Mouse
The Central Processing Unit (CPU)
The most important specification of the CPU is its clock speed, rather than the number of cores.
• That is, a 2.6 GHz core i5 processor can perform better than a 1.6 GHz core i7 processor
Memory
Memory refers to the kind of storage HW that is fast enough to be directly accessible by the
processor.
• Since it is too fast, it is expensive
• Typical memory example is the Random Access Memory (RAM )
– RAM is volatile (looses its content when powered off)
• Error–Correction Code (ECC) memory is a type of memory that includes special circuitry
to detect and correct errors
– ECC memory can identify and rectify single–bit errors, which can occur due to various factors such as cosmic rays, electrical interference, or other environmental factors
[chatGPT]
∗ The probability of encountering memory errors in typical PC’s is relatively low
however
∗ The vast majority of users, including those running simulations, do not face
significant issues related to memory errors
– ECC memories are restricted to professional solutions, such as professional workstations [sec. 1.5.4] and professional–grade GPU’s [sec. 1.3.3.1]
8
Graphics Card
The graphics card off–loads graphics rendering from the CPU.
• The most important component of a graphics card is its CPU; known as the Graphical
Processing Unit (GPU)
24
Integrated vs Dedicated Graphics Cards
• For everyday tasks, like web browsing, office applications, and light gaming, the integrated
graphics card∗ is usually very satisfactory
• For graphic–intensive applications, like gaming, video encoding, content creation, 3D
modeling, and deep learning, a dedicated graphics card is recommended
– Dedicated graphics cards offer better performance and are designed specifically for
these demanding applications
– There are two grades of dedicated graphics cards; consumer–grade, and
professional–grade
Examples
Purpose
Firmware
Optimized for
FP64 arithmetic
VRAM
Drivers
Target Computer
Cooling
Price
Dedicated Graphics Cards†
Consumer–Grade
Professional–Grade
nVidia–GeForce &
nVidia–Quadro &
AMD–Radeon
AMD–Radeon–Pro/FirePro
gaming, entertainment
intensive applications such
multimedia, everyday tasks
as video creation and
encoding , large CAD/CAE
problems, . . .
prioritize high–frame–rate
prioritize rendering accuracy
over rendering accuracy
gaming performance
precision, accuracy, stability
limited or none
few‡ models
no ECC
ECC§
Gaming–oriented with
Certified by ISV’s¶
frequent updates
standard PC’s
workstations and servers
standard cooling
specialized cooling
more affordable
more expensive
– CAD and CAE pre–processing applications can have very satisfactory performance
using any professional–grade, and many gaming, GPU’s [2]
– Some CAE solvers‖ can run several times faster using specific professional–grade
GPU’s with powerful double–precision (FP64) arithmetic capabilities [sec. 1.3.3.1]
∗
e.g. Intel–graphics
[ChatGPT]
‡
FP64 capability is typically restricted to one or two flagship products per generation [2]
§
Error–Correcting Code
¶
Independent Software Vendors
‖
such as sparse solvers, eigensolvers based on the sparse direct solver [3], implicit solvers [2], . . . )
†
9
– Deep Learning (DL) workloads can be substantially accelerated using Tensor Cores∗∗
[sec. 1.3.3.1]
nVidia–GeForce RTX 3060
for desktops
nVidia–Quadro RTX 6000
for workstations
nVidia–Tesla V100 for
Data centers
Advice
Do not waste your money buying the most expensive graphics–cards, unless you have strong
reasons.
Storage
Storage refers to the slower storage HW.
• They are too slow to serve the processor
• Hence storage HW are cheaper than memory HW
• Storage HW are not volatile (retains their content when powered off)
• Typical examples include the HDD, CD, DVD, Flash disk, SAS, SSD, NVMe, magnetic
tape, ...
• Usually, storage speed is a bottleneck of the overall PC response speed∗
– That is, upgrading to a faster storage device greatly increases the PC response
– However, make sure the motherboard supports higher speed storage devices
∗∗
∗
found in nVidia GPUs
This differs from computation speed, which depends on both the CPU and RAM.
10
Actual Storage Speeds
8000
Sequential Read
Sequential Write
7000
7000
6000
5000
MByte/s
5000
4000
3500
3000
2000
2000
1000
550
150
550
130
0
SATA HDD
SATA SSD
NVMe PCIe 3.0 x4
NVMe PCIe 4.0 x4
Useful information
• File Recovery Specifics for SSD www.r-studio.com/SSD_Recovery.html
26
11
(17,066.)
800.
6,000.
51,200.
409,600.
204,800.
136,528.
10,000.
32,000.
12,000.
1,000.
(MByte/s)
(750.)
3,000.
(750.)
(375.)
3,000.
6,000.
(6,400.)
(3,938.)
(66.7)
(133.)
Mbit/s
(187.5)
8,000.
(375.)
(1,500.)
80,000.
(25,600.)
Speed of Storage vs Memory
8 bit = 1 Byte
(51,200.)
Memory vs Storage Comparison
1,500.
1,064.
100.
533.6
80.
10.
Storage Bus
Memory
Assignment
• Answer questions (1.1) and (1.2)
Monitor
• Monitor resolution is more important than the area size
Assignment
• Answer question (1.4)
12
1.3
The Central Processing Unit (CPU)
The CPU is the HW that executes instructions by performing arithmetic, logic and input/output
operations.
• The CPU is well known as the “Processor”
31
1.3.1
CPU Architecture
The CPU only understands 0 and 1.
• These letters can form variety of machine languages
– The machine language of one CPU may differ from that of another CPU depending
on the CPU architecture
32–bit CPU can address a maximum of 232 = 4 GiB memory
64–bit CPU can address a maximum of 264 = 16 EiB∗ memory
32
Notable CPU Architectures
• x86 is the old days 32–bit CPU architecture for PC’s
• Itanium (IA–64) is a 64–bit CPU architecture
– developed by Intel
– not compatible with the older x86 architecture
∗ That is, old application SW written for x86 CPU’s cannot run
– Therefore, IA–64 failed in the PC market
– IA–64 still exists, but not for PC’s
• x86–64 (also called AMD64) is the current major 64–bit CPU architecture for PC’s
∗
[appendix E]
13
– developed by AMD
– fully backward compatible with the older x86 architecture
∗ That is, old application SW written for x86 CPU’s can still run
– Therefore, x86–64 surpassed IA–64
∗ Intel had to adopt† x86–64 architecture for its PC CPU’s
• ARM is another very popular architecture characterized by low power consumption
– In 2011, 95% of smartphones/tablets, 90% of hard disk drives, 40% of digital televisions and 15% of microcontrollers and 20% of mobile computers are based on ARM
processors
– Examples include most Android phones/tablets, Microsoft’s first generation Surface
and Surface 2, Apple’s iPhone, iPad and iPod, Nvidia’s Tegra, Raspberry–Pi, BeagleBoard, BeagleBone, Texas Instruments’ OMAP, Canon PowerShot digital cameras,
Nintendo DS, . . .
Assignment
• Answer questions (1.5) and (1.6)
1.3.2
Parallel Computing
1.3.2.1
Symmetric Multiprocessing (SMP)
Processor
Processor
Processor
Bus
Memory
A symmetric multiprocessor (SMP) computer is a system with multiple identical processors
that share memory and connect via a bus.
• The system is controlled by a single OS instance
• However, the so called “Bus contention” prevents scaling
Multicore Processors
A multicore processor is a sample of SMP. Examples include:
†
• Recent PCs
• iphone
• ...
• Sony PlayStation
• Smart phones
However, Intel called its x86–64 implementation as “EM64T”, and then changed the name to “Intel 64”.
14
36
1.3.2.2
Distributed Processing
Distributed system
Processor
Memory
Processor
Memory
Processor
Processor
Memory
Memory
A distributed computer is a distributed memory computer system in which the processing elements are connected by a network
• The Network is slower than the bus [appendix E]
• Distributed computers are highly scalable
Cluster
Grid
Machines connected by fast local area net- Machines connected by slower wide area networks (LAN)
works (WAN); such as the Internet
37
15
Top500 Supercomputer Statistics
The vast majority of the TOP500 supercomputers are clusters.
Architecture - Systems Share
100
90
80
70
Share
60
50
40
30
20
10
0
1995
2000
Single Processor
Constellations
MPP
SIMD
2005
2010
SMP
16
2015
Cluster
1.3.3
Heterogeneous Computing
Hardware Accelerator∗
Hardware acceleration is the use of a special hardware to perform some function, more efficiently than is possible using software running on a general–purpose CPU.
• Example accelerators include:
– Coprocessor
– Sound card
– Graphics card
– Network Interface Controller (NIC)
39
Heterogeneous Computing†
Heterogeneous computing refers to systems that use more than one kind of processor.
• Heterogeneous computing has become popular way to reach better energy efficiency and
higher performance
– As of November 2014, 9 of the 10 top computers are hetrogeneous
• The processor that is used to accelerate the primary CPU is called coprocessor‡
• Example coprocessors include:
– Graphical Processing Units (GPUs)
– Field–Programmable Gate Arrays (FPGAs)
– Application–Specific Integrated Circuit (ASICs)
§
40
The Field–Programmable Gate Array (FPGA)¶
FPGA is a reprogrammable chip.
• In contrast to CPU, programming an FPGA rewires the chip itself rather than run a SW
application
∗
[https://en.wikipedia.org/wiki/Hardware_acceleration]
[https://en.wikipedia.org/wiki/Heterogeneous_computing]
‡
[https://en.wikipedia.org/wiki/Coprocessor]
§
[https://medium.com/grovf/heterogeneous-computing-as-a-next-generationarchitecture-for-scaling-data-centers-trends-ae5c5f5725f9]
¶
[www.ni.com/fpga]
†
17
• FPGA chip adoption across all industries is driven by the fact that FPGA’s combine the best
parts of application–specific integrated circuits (ASIC’s) and processor–based systems.
These benefits include the following:
– Faster I/O response
– Exceeding the computing power of digital signal processors
– Rapid prototyping and verification without the fabrication process of custom ASIC
design
– Field–upgradable eliminating the expense of custom ASIC re–design and maintenance
For more information, check:
• https://embeddedmicro.com/blogs/tutorials/what-is-an-fpga
• https://en.wikipedia.org/wiki/Field-programmable_gate_array
18
1.3.3.1
The Graphical Processing Unit (GPU)
GPU’s were originally designed to render triangles in 3D graphics.
• Recently, GPU’s are increasingly used for scientific computations∗†‡
GPU (Thousands of cores)
CPU (Multiple cores)
ALU
ALU
ALU
ALU
Control
Fast connection
( low latency bus)
System Memory (RAM)
CPU
Slower connection
( PCIe bus)
GPU Memory (VRAM)
Cache Memory
GPU
• few strong cores optimized for serial
processing
• thousands of weaker cores effective for
massive parallel computing
• designed to handle complex control
logic
• only do one thing well; handle repetitive low–level tasks§
• fast access to RAM
• slower access to RAM¶
– includes a High–Bandwidth
Memory (HBM) Video RAM
(VRAM)
–
• RAM can swap to/from disk
• VRAM cannot swap to/from disk
• A GPU can accelerate an application if both the following are satisfied:
1. massively parallel; the computations can be broken down into hundreds/thousands
of independent tasks
2. computationally intensive; computation time significantly exceeds the time spent
on transferring data to/from VRAM
∗
[https://en.wikipedia.org/wiki/High_Bandwidth_Memory]
[www.mathworks.com/company/newsletters/articles/gpu-programming-in-matlab.html]
‡
[https://nyu-cds.github.io/python-gpu/01-introduction/]
§
more transistors are devoted to processing, rather than caching and flow control
¶
due to the slower PCIe bus
†
19
• Most coprocessors are nVidia GPU’s
Accelerator/CP Family System Share; as of November 2019
Typical nVidia GPU’s
GeForce RTX 3060
Quadro RTX 6000
Quadro GV100
20
Tesla V100
VRAM
(TFLOPS)
Cores
Intel UHD
GeForce
GeForce
Quadro
Quadro
Tesla V100
Graphics
GTX
1660
Ti
RTX
3060
RTX
6000
GV100
630∗
Year
2020
2019
2021
2019
2018
2017
CUDA
24†
1,536
3,584
4,608
5,120
5,120
RT
N/A
N/A
28
72
N/A
N/A
Tensor
N/A
N/A
112
576
640
640
FP32‡
N/A
5.5
12.74
16.3
14.8
15.7
FP64§¶
N/A
0.17
0.398
0.510
7.4
7.8
Size (GB) Shared with CPU
6 GDDR5 12 GDDR6 24 GDDR6 32 HBM2 32 HBM2
‖
Bandwidth (GB/s)
N/A
288
360
624
870
900
ECC
N/A
No
No
Yes
Yes
Yes
Gaming,
Usage
HPC, AI
3D graphics, RT,
Basic graphics
Gaming, multimedia
HPC, DL,
multimedia, AI,
inference, virtual
AI, simulations
simulations
295
250
RT
TDP (W)
125
1xDP 1.4,
1xHDMI 2.0,
1xDVI-D
Connectors
Price
120
N/A
170
workstations
3xDP 1.4,
4xDP 1.4,
4xDP 1.4,
1xHDMI 2.1 1xVirtualLink 1xVirtualLink
∼$279
∼$329
∼$4,500
∼$9,000
250
N/A
∼$10,000
• Refer to https://www.nvidia.com/content/dam/en-zz/Solutions/gtcs22/
design-visualization/quadro-product-literature/quadro-amperelinecard-us-nvidia-web.pdf for specifications of more recent GPU’s
∗∗
∗
integrated in 10th generation Intel CPU’s
Execution Units (EU’s)
‡
FP32 is commonly used in graphics rendering and general–purpose computing
§
FP64 is essential for scientific simulations and certain HPC
¶
FP64 capability is typically restricted to one or two flagship products per generation [2]
‖
Memory bandwidth is a measure of the amount of data that can be transferred between the GPU and its memory.
It is calculated by multiplying the memory bus width (in bits) by the memory speed (in Hz) and dividing by 8 to
convert bits to bytes. [chatGPT]
∗∗
[www.nvidia.com/en-us/data-center/gpu-accelerated-applications/ansys]
†
21
GPU Core Types [chatGPT]
CUDA Cores
• handle tasks such as graphics rendering
• general parallel processing tasks
• One CUDA core performs one operation per clock cycle
Ray Tracing (RT) Cores
• dedicated for real–time RT
• significantly improved real–time graphics rendering
Tensor Cores:
• dedicated for Deep Learning (DL)
• accelerate mixed–precision Matrix–Multiply–Accumulate (MAC) (also known as
Fused Multiply–Add or (FMA)) operations, which are fundamental to the training of
deep neural networks.
• One tensor core can perform multiple operations per clock cycle
1.4
The Embedded Computer
It is a computer with limited resources.
• Therefore is it usually dedicated for a
fixed function
internals of an ADSL modem/router. A modern example of an embedded
system. Labelled parts include a processor (4), RAM (6), and flash memory
(7).∗
Example Embedded Computers
∗
• Networking equipment (routers, access
points, . . . )
• Cheap mobiles phones
• Digital satellite receiver
• Digital watches
• Digital video cameras
• Cheap dynamic data acquisition systems
• Calculators
[http://commons.wikimedia.org/wiki/File:ADSL_modem_router_internals_labeled.jpg]
22
(DAQ)
• ...
45
1.4.1
The Microcontroller
The microcontroller is basically an embedded computer on a chip.
• It contains CPU, input/output interface, memory∗ , clock, timer, . . .
46
Example Microcontrollers
• ATmega’s
• PIC’s
• Arduino
• Mbed
47
Assignment
• Answer question (1.7)
48
∗
usually EEPROM. This memoryretain its content when powered off.
23
1.5
Additional Information
1.5.1
The MSX Home Computer
MSX∗ is a standardized home computer architecture, announced by Microsoft and ASCII† in
1983.
• Many companies manufactured MSX computers, including: Sony, Panasonic, Sanyo,
JVC, Toshiba, Canon, Casio, Fujitsu, Hitachi, Sharp/Epcom, Pioneer, Al–Alamiah, Mitsubishi, NEC, Philips, Yamaha, Yashica, General, Samsung, . . . .
• MSX was popular in Japan, South Korea, Brazil, Netherlands, France, Spain, Finland,
Egypt, Arabian Gulf countries and former Soviet Union during the 1980s
– Most Japanese companies decided to avoid the intensely competitive U.S. market
• Before the great success of Nintendo’s Family Computer, MSX was the platform for which
major Japanese game studios produced video games
• A Sony MSX2 machine was launched into space on board of a Russian MIR spacecraft
• One professional broadcast video workstation was based on Sony HitBit HB–F900 MSX2
computer
• Although MSX was developed by Microsoft’s Japanese partner (ASCII), Microsoft
showed little support for the project beyond making the system software
∗
†
[https://en.wikipedia.org/wiki/MSX] and [www.giantbomb.com/msx/3045-15/]
a Japanese company
24
Sakhr Computers∗
MSX Sakhr AX150, made in Japan by Yamaha for Al–Alamiah,
used in Egypt and Arabian Gulf countries
Dr. Nabil Ali; 1938–2016
In the 1980s, Sakhr Computers (developed by Al–Alamiah, a Kuwaiti company), started the
production of the first Arabic version of MSX computers.
• The project was conceived by Dr. Nabil Ali†‡ and financed by Mohamed Al–Sharekh
• Al–Alamiah was the first to Arabise BASIC and the MSX LOGO
• Al–Alamiah started producing Yamaha AX100 and a few other models, including MSX2
and MSX2+
– It also produced other common models, including AX100, AX123, AX150, AX170,
AH200, AX200, AX230, AX235, AX250, AX330, AX350–I, AX350–II, AX355,
AX370, AX500, AX550, AX660, and AX990
– The most popular and affordable model was the Sakhr MSX AX170
50
∗
[https://en.wikipedia.org/wiki/MSX]
B.Sc., M.Sc. & Ph.D. in Aeronautical Engineering in 1960, 1967 & 1971 respectively, from the Aeronautical
Engineering Department (currently known as Aerospace Engineering Department), Cairo University.
‡
[https://web.archive.org/web/20160424144710/http://www.ahram.org.eg/NewsQ/475020.
aspx]
†
25
1.5.2 PC Evolution
PC Evolution
26
27
51
More Information
• Reference [1]
– Evolution of the computer
– How Apple Grew
• https://en.wikipedia.org/wiki/History_of_personal_computers
• www.businessinsider.com/30-years-mac-evolution-2014-1?op=1
1.5.3
RAID Controller
RAID Controller∗
∗
[www.prepressure.com/library/technology/raid]
28
1.5.4
Computer Classes
Workstation vs Home/Office Desktop PC’s
Built for
Applications
Motherboard
CPU
ECC RAM
Graphics card
Coprocessor†
RAID
Shape
Warranty
Support
Price
Examples
Dell††
Workstation
reliability & durability
professional∗
more sockets for CPU,
RAM, disks, LAN,
coprocessors†
Intel core i7, i9 or Xeon‡
supported
professional–grade§
supported
SW and/or HW
desktop or rack
longer
better∗∗
expensive
Desktop PC
home & office
home/office, gaming
less sockets
Intel core–i3, i5 or i7
not supported
integrated¶ or
consumer–grade‖
not supported
none
desktop or all–in–one
shorter
cheap
Precision
Inspiron, XPS, G–series,
Alienware
HP
Lenovo
ThinkStation P–series
Apple
Mac–Pro, iMac–Pro
Lenovo, ThinkCentre,
IdeaCentre
iMac
∗
e.g.: CAD/CAE, media/entertainment, . . .
e.g.: GPU, FPGA, ASIC, . . .
‡
Intel Xeon has more cores and cache memory than core–ix processors. Additionally, it supports multiple
sockets, ECC RAM and many RAM modules.
§
e.g.: nVidia–Quadro or AMD–Radeon–Pro
¶
Intel–graphics
‖
e.g.: nVidia–GeForce or AMD–Radeon
∗∗
e.g.: Windows support, Linux support, extended firmware updates, . . .
††
I began to feel that Dell uses the most advanced/powerful HW than other PC vendors.
†
29
Dell Precision 7920 Tower Workstation
Dell Precision 7920 Rack Workstation
30
Laptop Lines
Built for
Workstation
reliability &
durability
Gaming
high specifications
Applications
professional
gaming
Motherboard
more sockets for
RAM & disks
Intel core i7, i9 (>
2 GHz) or Xeon
supported
professional–grade
CPU
ECC RAM
Graphics
card
RAID
Keyboard
Power
consumption
Thickness
Weight
Price
Examples
Dell∗
HP
Lenovo
Apple
Business
reliability,
durability &
portability
home/office
Home/Office
portability
Intel core–i7 or i9
(> 2 GHz)
not supported
consumer–grade
Intel core–i3, i5 or
i7
not supported
integrated or
consumer–grade
Intel core–i3, i5 or
i7 (< 2 GHz)
not supported
integrated or
consumer–grade
sometimes (SW)
well–designed
high
RGB lights
high
well–designed
low–moderate
low–moderate
thick
heavy
most expensive
thick
heavy
expensive
thin–thick
light–heavy
moderate–
expensive
thin–thick
light–heavy
cheap–moderate
Precision
G–series,
Alienware
Omen
Legion
Lattitude, XPS
Inspiron, XPS
Elite, ProBook
ThinkPad
MacBook Pro,
MacBook Air
Pavilion
Lenovo, ideapad
MacBook Air
ZBook
ThinkPad P–series
MacBook Pro
home/office,
gaming
55
Desktop or Laptop?
∗
I began to feel that Dell uses the most advanced/powerful HW than other PC vendors.
31
[www.facebook.com/100002098327218/posts/
pfbid0GWsmLZac5Jfup2ugS7yWtkULkXtex1wAzNVwEn6145K3D5RhdoZWZkuP38sicGnDl/
?mibextid=Nif5oz]
32
1.5.5
Top 500 Supercomputer Statistics
As of November 2015, TOP500 supercomputers are mostly based on x86–64 CPUs (Intel
EMT64 and AMD x86–64 instruction set architecture).
[www.top500.org/statistics/]
Processor Generation System Share; as of June 2020
Vendors - Systems Share
100
90
80
70
Share
60
50
40
30
20
10
0
1995
2000
2005
2010
2015
Atos
Lenovo
IBM
Hitachi
TMC
Cray/HPE
NEC
Inspur
Oracle
Huawei
Fujitsu
Others
Dell EMC
Sugon
HPE
Intel
33
Segments - Systems Share
100
90
80
70
Share
60
50
40
30
20
10
0
1995
2000
2005
Vendor
Government
Industry
Research
Academic
Others
2010
2015
Classified
Application Area - Systems Share
100
90
80
70
Share
60
50
40
30
20
10
0
1995
Nov 01, 19982000
Research
Electronics
Not Specified
Weather and Climate Research
2005
99
Semiconductor
21
2010
2015
0
Telecommunication
47
134
Automotive
13
18
Geophysics
21
27
Web Services
2
Others
Services
1
Software
3
29
Database
17
Aerospace
Information Service
3
IT Services
Chemistry
7
Finance
0
33
Energy
10
Information Processing Service
4
Defense
11
Logistic Services
0
34
Countries - Systems Share
100
90
80
70
Share
60
50
40
30
20
10
0
1995
2000
2005
2010
2015
United Kingdom
Italy
France
United States
China
Ireland
Others
Japan
Germany
Russia
Cores per Socket - Systems Share
100
90
80
70
Share
60
50
40
30
20
10
0
1995
2000
2005
2010
2015
60
64
68
32
24
20
22
28
1
2
4
6
9
8
260
10
12
14
16
18
48
57
35
1.6
Questions
1.1. When a student formatted his new 500 GB HDD, he discovered that it is only 465 GiB.
Explain the this difference?
Hint check appendix E
1.2. If your PC has a:
(a) SATA HDD, what is the generation of the SATA bus?
(b) NVMe HDD, what is the PCI Express version and its link width and link speed?
Hint refer to www.nextofwindows.com/how-to-tell-the-storage-controlleris-sata-2-or-sata-3-on-windows
1.3. Based on your answer to question 1.2;
(a) decide the fastest HDD technology suitable for your PC (SATA HDD, SATA SSD,
NVMe PCIe 3.0, NVMe PCIe 4.0, . . . )
(b) decide the fastest USB flash drive speed to use with your PC
i. Standard speeds (Read speed ≤110 MB/s and Write speed ≤15 MB/s)
Read speed Write Speed
Brand
Model no.
(MB/s)
(MB/s)
1 Kingstone DT50/128GB
110
15
2 Kingstone DTSE9G2/128GB
100
15
3 Kingstone DTDUO3C/128GB
100
15
4 Kingstone DTMC3/128GB
100
15
ii. High speeds (Read speed 150∼300 MB/s and Write speed 30∼60 MB/s)
Read speed Write Speed
Brand
Model no.
(MB/s)
(MB/s)
1 SanDisk
SDCZ73-128G-G46
150
30
2 Kingstone DTKN/128GB
200
60
3 Samsung MUF-128BE4/AM
300
60
4 Samsung MUF-128AB/AM
300
60
iii. Super high speeds (≥300 MB read and ≥150 MB Write)
Read speed Write Speed
Brand
Model no.
(MB/s)
(MB/s)
1 Kingstone HXS3/128GB
350
250
2 SanDisk
SDCZ880-128G-G46
420
380
1.4. Obtain the screen resolution of the following:
(a) HD TV
(d) Projector
(b) Full HD TV
(e) Cheap Samsung smartphone
(c) 4K TV
(f) Expensive Samsung smartphone
36
1.5. Survey the memory limits of:
(a) Windows XP
(d) Windows 10 32 bit
(b) Windows 7 32 bit
(e) Ubuntu 32 bit
(c) Windows 8 32 bit
(f) Android
1.6. While in a big electronics mall, you found two brand new tablets, one with a powerful
Intel processor, and the other with a powerful nVidia processor.
(a) Do you think there are any hidden restrictions/problems?
(b) Discuss them if any
Hint read these web pages
• www.networkworld.com/article/2360304/opensource-subnet/intelconfronts-a-big-mobile-challenge-native-compatibility.html
• www.theregister.co.uk/Print/2014/05/02/arm_test_results_
attack_intel/
1.7. Survey the processors of a sample of the following (processor model, architecture name,
number of addressing bits, memory limit, number of cores)
(h) Rasperry–Pi
(a) Arduino
(b) ATmega ???
(c) ATMEL ???
(d) AVR ???
(e) Beagle–bone
(f) Mbed
(g) PIC ???
(i) Samsung S5 smart phone
(j) iPhone 5s
(k) Samsung Tab 3
(l) iPad latest generation
(m) any other computer system you like
1.8. Classify the following as either non–embedded computer, embedded computer or
microcontroller
(a) Arduino Uno
(b) ATmega ???
(c) ATMEL ???
(d) AVR ???
(e) Beagle–bone ???
(f) Mbed ???
(g) PIC ???
(h) Rasperry–Pi ???
(i) Samsung S5 smart phone
(j) iPhone 5s
(k) Samsung Tab 3
(l) iPad latest generation
(m) any other computer system you like
58
37
This page is intentionally left blank!
38
Part 2
Software
References
1. Wikipedia: the free encyclopedia (http://en.wikipedia.org)
2. The Internet
3. Greg Lehey, The complete FreeBSD, O’REILLY & ASSOC INC., 2003. [4]
4. Michael W. Lucas, Absolute FreeBSD, No Starch Press, 2008. [5]
59
Lab Preparation
Well prepare yourself for:
• lab 1
• lab 2
• lab 3
• lab 4
60
2.1
Open–Source Software (OSS)
Free Software
Free software means that the user has the freedom to run, copy, distribute, study, change and
improve the SW.
Compiler
MyProg.o
MyProg.cpp
MyProg.obj
• Free is a matter of liberty, not price
MyProg
C++ code
MyProg
61
01010101
Open Source Software (OSS)
MyProg.o
MyProg.cpp
MyProg.obj
MyProg
MyProg
MyProg
functionA
C++ code
01010101
functionA.o
functionA.obj
functionA
01010101
Linker
functionA.cpp
Compiler
developer A
MyProg.exe
C++ code
functionA
01010101
MyProg
OS dependent
subroutines
functionB
01010101
01010101
01010101
functionB.o
functionB.obj
functionB.cpp
functionB
functionB
01010101
C++ code
OSS are computer SW whose source code is published and made available with a license.
MyProg.o
MyProg.cpp
Compiler
developer A
• OSS are often developed through community collaboration
MyProg.obj
– The community may consist of individual–programmers and/or large–companies
MyProg
MyProg
MyProg
– Constructive collaboration requires good management by wise and clever board
MyProg.exe
01010101
Linker
C++ code
functionA
• Many individuals who start an open source project, usually end up as large companies
functionB.cpp
functionB
C++ code
MyLibrary.a
functionA.obj
MyLibrary.lib
functionA
01010101
functionB.o
functionB.obj
functionB
01010101
Linker
functionA
C++ code
Compiler
developer B
functionA.cpp
functionA.o
39
functionA
01010101
functionB
01010101
01010101
MyProg
OS dependent
subroutines
functionB
01010101
01010101
01010101
62
FOSS
A FOSS can be classified as both free and OSS∗ .
2.1.1
The License
The license may grant/deny licensees the right to copy, modify and redistribute the SW (or
content).
• The license may also impose obligations.
– For example, the OSS license may require dependent SW to:
∗ use the same OSS license
∗ include attribution to the original author
∗ ...
• For brief description of notable licenses, refer to [Software licensing, Linux User & Developer magazine, Issue 180, pages 28–31]
Notable OSS Licenses†
License
GPL
Proprietary SW
linking
Not allowed
Distribution
LGPL
Allowed
Only with GPL
compatible SW
Allowed‡
APSL
Apache
BSD
CPL
Allowed
Allowed
Allowed
Not clear¶
Allowed
Allowed
Allowed
Not clear¶
Jabber
MIT (X11)
MPL
Python
Allowed
Allowed
Allowed
Allowed (?)
Allowed‖
Allowed
Allowed
Allowed
∗
Redistributing of modified
code
Only if derivative is GPL
compatible
Only if the derivative is LGPL
or GPL
Only under APSL
Allowed§
Allowed
Only under CPL compatible
license
Allowed∗∗
Allowed
Only under MPL
Allowed, assuming the
package includes a list of
changes to the original Python
and copyright notices on all
files.
[https://en.wikipedia.org/wiki/Free_and_open-source_software]
[http://web.archive.org/web/20090317083515/http://developer.kde.org/documentation/
licensing/licenses_summary.html]
‡
You have to provide source code of the distributed LGPL library with (if any) modifications, changes to the
LGPL library should be allowed to third parties and if BC your app/lib should still work with the modified LGPL
lib/app.
§
As long as the name “Apache” isn’t used in the name of the derivative work
¶
But do not mix code covered by this license with incompatible licenses.
‖
Only the portions of “the Work” licensed under the Jabber license needs to stay licensed as such.
∗∗
Can be under a different license as long as the source code is provided and a few License specific requirements
are fulfilled.
†
40
License
Sun Public
Proprietary SW
linking
Allowed
Distribution
Allowed
Redistributing of modified
code
Only under Sun Public
• For help choosing a license, refer to http://choosealicense.com/
65
2.1.2
FOSS vs Commercial–SW
The Brute Force of OSS
The main power of an OSS project comes from the collaboration of minds and efforts of many
contributors.
• This enabled many OSS projects to surpass commercial competitors. Typical examples
are:
– Firefox (vs Internet Explorer)
– Linux (vs Unix)
66
41
Case Study: The Rise of Mozilla Firefox
How Mozilla Firefox surpassed MS Internet Explorer after it has surpassed Netscape Navigator?
∗
∗
[https://maps-and-tables.blogspot.com/2016/01/historical-market-shares-ofbrowsers.html]
42
Case Study: The Rise of Linux
Since 2005, almost all the top 500 supercomputer use GNU Linux OS.
Operating system Family - Systems Share
100
90
80
70
Share
60
50
40
30
20
10
0
1995
2000
2005
2010
Windows
Mac OS
N/A
BSD Based
Linux
Mixed
2015
Unix
Cores per Socket - Systems Share
100
90
80
70
Share
60
50
40
30
20
10
0
1995
2000
2005
2010
2015
60
64
68
32
24
20
22
28
1
2
4
6
9
8
260
10
12
14
16
18
48
• Refer to sec. 2.2.2.4 for more information
68
43
Notable FOSS Projects
Application SW
• 7–Zip
• Inkscape
• NASA World Wind
• Blender
• Firefox
• OpenOffice.org
• Eclipse
• Chromium
• LibreOffice
• GIMP
• Thunderbird
• PrestaShop
• Perl
• Python
• Julia
• PHP
• Ruby
Programming Languages
Operating Systems
• Android
• Linux
• ReactOS
• FreeBSD
• OpenIndiana
• Haiku
• Apache
• MongoDB
• TYPO3
• Drupal
• Moodle
• MediaWiki
• WordPress
Server SW
Widespread of FOSS Nowadays
FOSS are very widely utilized nowadays, powering millions of servers, desktops, smart–phones,
....
OSS Drawbacks
• OSS usually have serious drawbacks, such as:
– no warranty
– support is through the community∗
– lack of high–quality documentation
– difficult installation
– less stable
∗
– less polished
– less–friendly UI
– slow download servers
– ...
Community support may not be accepted by serious customers who are unwilling to publishing their work to
the public.
44
• Serious customers usually fear that the saved license–costs are payed by harder–work and
more–time†
– Therefore, many of them choose commercial SW
71
Comprehending Minds of FOSS and Commercial–SW
• A commercial–SW company usually has:
– full–time programmers
– clear plans/decisions based on accumulated experiences with customers
– financial resources that enable outsourcing difficult problems to experts to obtain
high–quality solutions
• On the other hand, developers of a FOSS project work for free
– Hence, they work non–regularly; in their spare time
• As a result, what a commercial company can achieve in months, can last years of the FOSS
developers∗ !
• However, both parties describe their features/improvements using the same words
– Both parties are saying the truth, but from their respective points of view
• As a user, you should comprehend both descriptions differently to take the right decision
72
Clone SW
SW
MS–Word
Matlab
Clone Alternative
Libre–office–Writer
GNU–Octave
Non–clone Alternative
LYX
Python, Julia, Scilab
A clone SW follows another SW. Therefor clones are:
• always lagging
• usually inferior
That is, most probably you won’t be satisfied with a clone SW.
OSS Alternatives to Proprietary–SW
The following links may help you finding OSS alternatives to many proprietary–SW:
• www.findbestopensource.com/
• www.dedoimedo.com/computers/new-cool-list-linux.html
• www.openhub.net†
45
73
Be advised to avoid clone alternatives.
74
More information
• www.findbestopensource.com/article-detail/open-source-startups
• www.findbestopensource.com/article-detail/contribute-to-opensource
• www.findbestopensource.com/article-detail/learn_from_open-source
• www.findbestopensource.com/article-detail/make_money_opensource
• en.opensuse.org/portal:How_to_participate
• https://opensource.guide
• Imagine Publishing
– Linux User&Developer magazine (www.linuxuser.co.uk)
– Linux Tips, Tricks, Apps & Hacks (www.imagineshop.co.uk/bookazines.html)
– Linux & Open Source Genius Guide (www.imagineshop.co.uk/bookazines.
html)
• Arabic web pages
– Introduction to Open Source Software (http://ojuba.org/wiki/%D9%85%D9%
82%D8%AF%D9%85%D8%A9_%D9%81%D9%8A_%D8%A7%D9%84%D8%A8%D8%B1%D9%
85%D8%AC%D9%8A%D8%A7%D8%AA_%D8%A7%D9%84%D8%AD%D8%B1%D8%A9)
– www.linuxac.org
– http://itwadi.com
– www.ojuba.org
Assignment
• Answer questions (2.1) & (2.2)
†
[www.code-aster.de/code-aster.html]
Of course, if the number of FOSS developers increased and, more importantly, harmony could be achieved
during their collaboration, the FOSS can advance faster than commercial counterparts. This may be achievable for
small projects such as Firefox or VLC–player. But this is hardly possible for very big projects spanning a multitude
of different disciplines such as multiphysics–CAE–SW, or CAD SW spanning parts, assembly, drafting, CAM,
Testing, PLM, . . . .
†
very useful for checking the current state of an OSS
∗
46
2.2
The Operating System (OS)
User
SW Applications
el
Sh
GU
LI
C
Kernel
IS
he
ll
Hardware
l
Usable OS
Better OS
The OS is a set of SW that manage HW resources and provide services for application SW.
• OS’s are found on almost any device that contains a computer; from cellular phones and
video game consoles to supercomputers and web servers
• Example OS’s include:
– MS Windows
– Unix–like OS’s (Android, iOS, GNU–
Linux, Mac OS, . . . )
77
The Kernel
User
SW Applications
l
el
Sh
GU
LI
C
Kernel
IS
he
ll
Hardware
Usable OS
Better OS
The Kernel is the subset of the OS having control over the HW.
• The kernel can be accessed through its Application Programming Interface (API)
– In other words, it is inaccessible to the user
78
47
The Shell
The Shell is a User Interface (UI) that enables users to access the OS services. A shell can have:
• Command Line Interface (CLI)
• Graphical User Interface (GUI)
Typical CLI Shells
• MS Windows has:
– Windows Subsystem for Linux (WSL)
– Command Prompt
– Windows PowerShell
• Linux has has several shells, as detailed in sec. B.2
Typical GUI Shells
• MS Windows has one GUI–shell
• Linux has several GUI shells, as detailed in sec. B.3
2.2.1
OS Types
• Single/Multi–tasking
• Real–time
• Distributed
• Single/Multi–user
• Embedded
• ...
Real–Time OS (RTOS)
ROTS is an OS intended to operate on real–time devices, e.g.:
• Expensive Video cameras
• Expensive mobiles phones
• Expensive dynamic data acquisition systems (DAQ)
• Expensive satellite receiver
• ...
Embedded OS
Embedded OS is designed to operate on embedded systems.
• Hence, it is designed to be very compact and extremely efficient
48
Distributed OS
Distributed system
Processor
Memory
Processor
Memory
Processor
Processor
Memory
Memory
Distributed OS can manage a group of independent computing nodes. Examples include:
• MS Windows Server
• Linux
85
49
2.2.2 History of Operating Systems
50
∗
∗
https://www.reddit.com/r/linux/comments/kporah/i_made_a_simple_diagram_on_history_of_os_feel
Evolution of Unix–Like OS’s
1969
1969
Unnamed PDP-7 operating system
1971 to 1973
Unix
Version 1 to 4
1974 to 1975
Unix
Version 5 to 6
Open source
Mixed/shared source
Closed source
PWB/Unix
1978
1971 to 1973
1974 to 1975
1978
BSD
1.0 to 2.0
1979
Unix
Version 7
1979
Unix/32V
1980
1980
BSD
3.0 to 4.1
1981
Xenix
1.0 to 2.3
1982
BSD 4.2
1983
1985
SCO Xenix
Unix
Version 8
BSD 4.3
1986
Unix
9 and 10
(last versions
from
Bell Labs)
1987
1988
51
1989
Minix
1.x
NexTSTEP
OpenSTEP
1.0 to 4.2
SCO Xenix
V/386
BSD
4.4-Lite
&
Lite Release 2
NetBSD
0.8 to 1.0
NetBSD
1.1 to 1.2
SCO UNIX
3.2.4
OpenBSD
1.0 to 2.2
NetBSD 1.3
1987
HP-UX
2.0 to 3.0
System V
R4
Linux
2.0 to 6.x
Mac OS X
Server
Minix
3.1.0 to 3.4.0
1993
1994
1995
OpenServer
5.0 to 5.04
1996
Solaris
2.1 to 9
1997
1998
NetBSD
1.4 to 9.x
FreeBSD
5.0 to 13.x
2000
OpenServer
5.0.5 to 5.0.7
2003
Mac OS X,
OS X,
macOS
10.x to 13.x
(Darwin
1.2.1 to 22)
HP-UX
6 to 11.10
UnixWare
1.x to 2.x
(System V R4.2)
1999
FreeBSD
3.3 to 4.x
2004
2005 to 2007
1988
1989
AIX
3.0 to 7.3
FreeBSD
3.0 to 3.2
Minix
2.x
1986
1991
1997
1998
2010
HP-UX
1.0 to 1.2
1992
FreeBSD
1.0 to 2.2x
1995
2008 to 2009
1985
System V
R3
SunOS
4
1996
2001 to 2002
1984
1990
386BSD
1993
2000
System V
R1 to R2
SCO Xenix
V/386
BSD Net/1
Linux 0.0.1
To 0.9
1994
1999
SCO Xenix
V/286
1983
BSD Net/2
1991
1992
AIX
1.0
BSD 4.3
Tahoe
BSD 4.3
Reno
1990
SunOS
1.2 to 3.0
1982
Xenix
3.0
SunOS
1 to 1.1
1984
Unix-like systems
1981
System III
2011 to 2018
2019 to 2023
2003
UnixWare
7.x
(System V R5)
OpenBSD
2.3 to 7.2
DragonFly BSD
1.0 to 6.4
2001 to 2002
OpenServer
6.x
2004
HP-UX
11i v1 to 11i v3
Solaris
10
Solaris
11.0 to 11.4
OpenSolaris
& derivatives
(Illumos, etc.)
2005 to 2007
2008 to 2009
2010
2011 to 2018
2019 to 2023
∗
87
∗
https://commons.wikimedia.org/wiki/File:Unix_history-simple.svg
2.2.2.1
Unix
In the 1960s, the Massachusetts Institute of Technology (MIT), AT&T’s Bell–Labs, and General Electric (GE) developed an experimental operating system called MULTICS (Multiplexed
Operating and Computing System) for the GE–645 mainframe.
• In 1969, after withdrawing from collaboration with GE and MIT, Bell–Labs developed
the Uniplexed Operating and Computing System (UNICS)
• UNICS evolved into the common UNIX of today
• In the early 1990s, AT&T sold its Unix rights to Novell, which then sold it to the Santa
Cruz Operation (SCO)
• Currently, UNIX is a trademark of “The Open Group”, a neutral industry consortium
Notable Unix OS’s
• AIX by IBM
• IRIX∗ by Silicon Graphics
• BSD∗ by University of California,
Berkeley
• Mac OS X† by Apple
• Solaris by Sun‡ Microsystems
• HP–UX by HP
• Xenix∗§ by Microsoft
Unix–like OS
For an OS to call itself Unix, the OS vendor must prove that the OS complies with the so called
Single–Unix–Specification (SUS).
• Otherwise, the vendor can call it “Unix–like OS”
Notable Unix–like OS’s
• FreeBSD
2.2.2.2
• Darwin
• Linux
BSD
A research group of the University of California at Berkeley modified AT&T’s UNIX to run on
their new DEC VAX 11/780 computer.
• They called this OS “BSD” (Berkeley Software Distribution)
• The University of California had made their BSD available as OSS
∗
Discontinued
As of 2014, the Unix version with the largest installed base is Mac OS X.
‡
acquired by Oracle in 2010
§
In the mid–to–late 1980s, Xenix was the most common Unix variant, measured according to the number of
machines on which it was installed.
†
52
– This caused many problems and legal–courts with AT&T for a long time
• Since then, BSD inspired many OS developments
• Currently BSD is obsolete
92
FreeBSD
FreeBSD is the current direct descendant of BSD.
• Due to its permissive license, much of FreeBSD’s code base has become an integral part
of other OS’s such as∗ :
– Apple’s Mac OS X, watchOS, and tvOS
– FreeNAS
– Nintendo Switch system software
– Sony’s PlayStation
• FreeBSD had become popular among commercial and ISP† users, powering extremely
successful sites like Yahoo and Hotmail
• FreeBSD is not certified as compatible with the SUS
– That is, FreeBSD is a Unix–like OS
93
2.2.2.3
Apple Macintosh OS
[https://en.wikipedia.org/wiki/MacOS]
• In 1984, the classical Macintosh OS was first introduced
• In 1985, Steve Jobs, the co–founder of Apple Inc., left Apple Inc.
– Steve then created NeXT Inc. where he started developing the NeXTSTEP OS based
on BSD
• In 1997, Apple purchased NeXT Inc. in order to use NeXTSTEP as the basis for its next
generation OS
– Steve returned to Apple
• In 1999, the last release of the classical Macintosh OS, Mac OS 9, was released
∗
†
[https://en.wikipedia.org/wiki/FreeBSD]
Internet Service Provider
53
• In 2000, Apple released the core of their proposed OS as OSS and called it “Darwin”
– Higher–level components remained however closed–source
• In March 2001, Mac OS X 10.0, was released
• Since Mac OS X 10.5, Mac OS∗ is certified as compatible with the SUS†
– That is, Mac OS X is an official UNIX
Darwin OS
Darwin‡ is the open source testing ground of Mac OS, iOS, watchOS, and tvOS.
• It is still active till now
• It has only a CLI
2.2.2.4
GNU Linux OS
The GNU Project
The GNU project is a free SW project announced on 1983 by Richard Stallman at MIT.
• The founding goal of the project was to develop “a sufficient body of free software [...] to
get along without any software that is not free.”
• In January, 1984, the project began
working on an OS called “GNU OS”
MySQL
drivers and modules
Hardware
except Mac OS X 10.7
[www.opengroup.org/openbrand/register/apple.htm]
‡
[https://en.wikipedia.org/wiki/Darwin_(operating_system)]
†
54
Apache
gcc
GNU coreutils
bash
GNU C Library
other libraries
sockets
device files
Linux kernel
processes
file systems
protocols
∗
memory management
GUI
KDE
Kernel
PHP
Gnome
HW
OS
sshd
XFCE
Services,
CLI,
Libraries & Servers &
Core utilities Interpreters
X.org
Application SW
Other application SW
– This OS was completed in 1992
when the Linux kernel was released as FOSS
The MINIX OS§
MINIX is a minimal Unix–like OS, created by prof. Andrew S. Tanenbaum, for study and research.
• MINIX was first released in 1987 as an OSS
– However, MINIX license limited it to educational use only
– This prevented MINIX from being a free SW∗
97
The Linux Kernel†
In 1991, Linus Torvalds (a student in University of Helsinki at Finland at that time) was frustrated
by the non–free license of MINIX.
• Therefore, Linus developed his own kernel on MINIX, which eventually became the Linux
kernel
– Later, further development took place and Linux matured
• Adoption of Linux started in the mid–1990s, when organizations such as NASA started
replacing their increasingly expensive supercomputers with clusters of inexpensive commodity computers
– Commercial use began when Dell and IBM, followed by HP, started supporting
Linux on their clusters
§
[https://en.wikipedia.org/wiki/Linux]
until the licensing changed in April 2000
†
[https://en.wikipedia.org/wiki/Linux]
∗
55
Operating system Family - Systems Share
100
90
80
70
Share
60
50
40
30
20
10
0
1995
2000
2005
2010
Windows
Mac OS
N/A
Unix
BSD Based
Linux
Mixed
2015
• Linux is a superb example of how few, dedicated and clever people can produce an OS that is better than well–known commercial
systems developed by a large number of trained SW engineers
• As of Linux kernel version 4.13∗
, developers are 1,681 individual and 225 companies
• Refer to appendix B for further details
∗
[www.linuxfoundation.org/2017-linux-kernel-report-landing-page/]
56
Top companies contributing
to the Linux kernel, 4.8–
4.13
Company
%
Intel
13.1 %
none
8.2 %
Red Hat
7.2 %
Linaro
5.6 %
unknown
4.1 %
IBM
4.1 %
consultants
3.3 %
Samsung
3.2 %
SUSE
3.0 %
Google
3.0 %
AMD
2.7 %
Renesas Electronics
2.0 %
Mellanox
2.0 %
Oracle
1.7 %
Huawei Technologies
1.5 %
Broadcom
1.5 %
ARM
1.5 %
Texas Instruments
1.4 %
Free Electrons
1.2 %
NXP Semiconductors
1.0 %
Canonical
1.0 %
Facebook
0.9 %
Imagination Technologies 0.8 %
Cavium
0.8 %
Code Aurora Forum
0.8 %
Outreachy
0.8 %
BayLibre
0.7 %
NVidia
0.7 %
linutronix
0.7 %
Rockchip
0.6 %
Linux Distribution
Linux is a kernel rather than a complete OS.
• In 1994† , the GNU community agreed to call the GNU OS as “GNU/Linux OS”
PHP
MySQL
Apache
gcc
GNU coreutils
bash
GNU C Library
other libraries
sockets
device files
Linux kernel
processes
file systems
protocols
drivers and modules
GUI
KDE
Gnome
memory management
HW
Hardware
Kernel
OS
sshd
XFCE
Services,
CLI,
Libraries & Servers &
Core utilities Interpreters
X.org
Application SW
Other application SW
– However, many users prefer to call the OS as “Linux”
• A Linux distribution assembles all the packages/tools/utilities necessary for an easy to
install/use OS
A Linux distribution
(e.g. for configuration,
installation like Yast, mcc)
distribution specific
applications
e.g. Red Hat, Fedora, Ubuntu, Mint,Manjaro
proprietary applications
Manuals
(e.g. Adobe Reader, graphics driver)
Linux kernel
free applications
Support
(phone
mail, etc)
(e.g. KDE, OpenOffice, Apache)
• Refer to sec. B.1 for notable Linux distributions
99
2.2.2.5
DOS and Windows
MS DOS
In 1981, when IBM introduced their Personal Computer (PC), it had a minimum of 16 kB RAM
and no HDD.
• This prevented using UNIX on PC
• IBM entrusted Microsoft (MS) to supply the OS
• MS chose “86/DOS”, a clone of Digital Research’s successful CP/M OS originally called
QDOS∗ (Quick and Dirty Operating System)
– 86/DOS ran fine without a HDD, and it didn’t use too much RAM
– MS changed the acronym DOS to “Disk Operating System”
– IBM marketed its version as PC–DOS, while MS marketed its version as MS–DOS
100
†
∗
[https://en.wikipedia.org/wiki/GNU/Linux_naming_controversy]
[https://en.wikipedia.org/wiki/86-DOS]
57
MS Windows
• www.theguardian.com/technology/2014/oct/02/from-windows-1-towindows-10-29-years-of-windows-evolution
• https://en.wikipedia.org/wiki/History_of_Microsoft_Windows
• https://en.wikipedia.org/wiki/Microsoft_Windows
• www.operating-system.org/betriebssystem/_english/bs-windows.htm
Windows UI Evolution
Somewhere, something went terribly wrong!
Assignment
• Answer questions (2.3), (2.4) & (2.5)
58
2.2.2.6
OS/2
OS/2 was a series of OS’s, initially created by Microsoft and IBM.
• Due to a conflict how to position OS/2 relative to MS Windows 3.1, OS/2 development
fell to IBM exclusively
• The first version was released in December 1987, and the last release was released in
December 2001
• It was possible to create applications that work on both Windows 3.x and OS/2
• OS/2 shares similarities with Unix, Xenix, and Windows NT
104
2.2.2.7
Summary
Refer to the hierarchy figures on pages 50∼51
2.2.3
105
Comparisons
59
Market Share of Supercomputer OS’s∗
Operating system Family - Systems Share
100
90
80
70
Share
60
50
40
30
20
10
0
1995
2000
2005
Windows
Mac OS
N/A
BSD Based
Linux
Mixed
2010
2015
Unix
Market Share of PC OS’s∗
Market share
100%
75%
50%
25%
Ja
n
'1
Ap 3
r'
1
Ju 3
l '1
O 3
ct
'1
Ja 3
n
'1
Ap 4
r'
1
Ju 4
l '1
O 4
ct
'1
Ja 4
n
'1
Ap 5
r'
1
Ju 5
l '1
O 5
ct
'1
Ja 5
n
'1
Ap 6
r'
1
Ju 6
l '1
O 6
ct
'1
Ja 6
n
Ap '17
ril
'
Ju 17
ly
'1
O 7
ct
'1
Ja 7
n
Ap '18
ril
'
Ju 18
ly
'1
O 8
ct
'1
Ja 8
n
Ap '19
ril
'
Ju 19
ly
'1
O 9
ct
'1
Ja 9
n
'2
0
0%
Windows
∗
∗
MacOS X
Linux
[www.top500.org]
[www.statista.com]
60
Chrome OS
Others/unknown*
Windows, Mac–OS and Linux for PC’s
• Main Linux problems on the desktop, 2013 edition (http://linuxfonts.narod.ru/
why.linux.is.not.ready.for.the.desktop.current.html)
108
Market Share of Smart Phone OS’s∗
Market share
100%
75%
50%
25%
Ja
n
'1
Ap 2
r'
12
Ju
l '1
O 2
ct
'1
Ja 2
n
'1
Ap 3
r'
13
Ju
l '1
O 3
ct
'1
Ja 3
n
'1
Ap 4
r'
14
Ju
l '1
O 4
ct
'1
Ja 4
n
'1
Ap 5
r'
15
Ju
l '1
O 5
ct
'1
Ja 5
n
'1
Ap 6
r'
16
Ju
l '1
O 6
ct
'1
Ja 6
n
'1
Ap 7
r'
17
Ju
l '1
O 7
ct
'1
7
0%
Android
iOS
Windows Phone
Series 40 (Nokia)*
Symbian OS*
Samsung
BlackBerry OS
Unknown /Other
109
Assignment
• Answer question (2.6)
110
∗
www.statista.com
61
2.3
SW Applications
2.3.1
Cross–Platform Application SW
Cross–platform refers to SW or computing methods and concepts that operate on multiple computer platforms.
• For example, Mozilla Firefox has versions for Windows, Linux, BSD and Mac OS
– In other words, Firefox source code can be compiled for several OS’s
Using a Windows compiler, the Windows version of Firefox was produced
Using a Linux compiler, the Linux version of Firefox was produced
Using a Mac compiler, the Mac OS version of Firefox was produced
...
– Windows version of Firefox runs only on Windows and cannot run on any other OS
∗ The same applies for other versions
Useful SW Applications
• Check appendix C
Assignment
• Answer questions (2.7), (2.8) & (2.9)
2.3.2
Bloat
Successive versions of many long–lived SW applications become increasingly slower and need
increasingly higher HW resources without offering justifiable improvements. Examples include:
MS Windows
Windows 95
Windows 98
Windows 2000
Windows XP
Windows Vista
Windows 7
Windows 8
Windows 10
Windows 11
Minimum HW requirements
Processor
RAM
25 MHz
4 MB
66 MHz
16 MB
133 MHz
32 MB
233 MHz
64 MB
1 GHz
1 GB
1 GHz
1 GB
1 GHz
1 GB
1 GHz
1 GB
2×1 GHz
4 GB
62
Installed Size
50 MB
175 MB
650 MB
1 GB
4 GB
6.3 GB
10 GB
12 GB
12 GB
MS Office
Office 6
Office xp
Office 2003
Office 2007
Office 2010
Office 2016
Office 2019
Minimum HW requirements
Processor
RAM
40 MHz
8 MB
133 MHz
64 MB
233 MHz
128 MB
500 MHz
256 MB
500 MHz
256 MB
1 GHz
2 GB
1.6 GHz
Installed Size
88 MB
122 MB
1.33 GB
0.97 GB
MS Visual Studio
Visual Studio 6
Visual Studio 2005
Visual Studio 2008
Visual Studio 2010
Visual Studio 2012
Visual Studio 2015
Visual Studio 2017
Minimum HW requirements
Processor
RAM
90 MHz
24 MB
600 MHz
192 MB
1.6 GHz
334 MB
1.6 GHz
1 GB
1.6 GHz
1 GB
1.6 GHz
1 GB
1.8 GHz
2 GB
Installed Size
154
280 MB
410 MB
3 GB
10 GB
14.6 GB
20 GB
SolidWorks 2000
SolidWorks 2011
SolidWorks 2017
SolidWorks 2018
Minimum HW requirements
Processor
RAM
256 MB
2 GB
4 GB
8 GB
Installed Size
220 MB
8 GB
13 GB
20 GB
SolidWorks
114
Matlab
Minimum HW requirements
Processor
RAM
Matlab 4
Matlab 5
Matlab 2006a
Matlab 2011b
Matlab 2016b
Matlab 2017b
Matlab 2019b
Matlab 2021b
Installed Size
2.3 GB
6 GB
16 GB
27 GB
63
2.4
Malware
Malicious software∗ (Malware) are specifically designed to inflict some harmful/bad/illegitimate
action.
• Common malware types include:
– viruses
– trojans
– ransomware
– spyware
– worms
– bots
– backdoors
– adware
• If a malware is executed, it usually:
– copies itself to several places in your HDD
– sets itself as autostart process
– creates several traps to re–execute itself
– and finally starts its harmful job
Typical Malware [6, table 2-2]
Action
Virus
Worm
Trojan
What does it do?
Inserts malicious code into
a program or data file
Exploits a vulnerability
in an application or
operating system
Masquerades as
performing a benign
action but also does
something malicious
How does it spread to
other computers?
User transfersinfected files
to other devices
Uses a network to travel
from one computer to
another
User transfers Trojan
file to other computers
Does it infect a file?
Yes
No
It can
Does there need to be user
action for it to spread?
Yes
No
Yes
Ransomware encrypts a victim’s files and demands a ransom to restore such files
Malware Spread
• Malware usually spread through:
– malicious email attachments
– infected software apps
– infected external storage devices†
– compromised websites
– ...
• More aggressive attacks exploit security holes to infect computers through the network;
without any user interaction
∗
†
[https://tools.cisco.com/security/center/resources/virus_differences]
e.g.: USB flash drives
64
• Malware kits on the deep web enables cybercriminals to purchase and use software tools
to create malware with specific capabilities
– Individuals with little or no technical background can easily and cheaply order Ransomware as a Service (RaaS) [sec. 3.6]
117
What to Do to Protect Against Malware?∗
• Backup and recovery plan for all critical data
– Note that network–connected backups can also vulnerable to malware
– Therefore, critical backups should be isolated from the network for optimum protection
• Continuously update the OS and SW with the latest security patches
• Maintain up–to–date anti–virus SW
• Restrict users’ permissions to install and run unwanted SW
• Apply the principle of “Least Privilege” to all systems and services
• Do not download attachments or follow links from suspicious emails
– Do not enabling macros from email attachments
• Avoid running unknown SW
• Disable auto play of new partitions
• Avoid visiting bad websites
• Do watch the extension of the file you are double–clicking
• Check that what you are executing is not a shortcut/link
118
∗
[https://security.berkeley.edu/faq/ransomware]
65
Cyber Attacks in the News
[www.bbc.com/arabic/middleeast58573362]
[www.bbc.com/arabic/world-64697744]
66
ر
ر
التأمي نف ر
ن
الت استهدفت مؤسسات حيوية عالية
شت دول العالم
ي
بعض الهجمات اإللكتونية ي
https://www.bbc.com/arabic/business-57325184
أكب رشكة لحوم يف العالم
هجوم يستهدف ر02-06-2021 1
ر
https://www.bbc.com/arabic/business-57052971
أكب خط أنابيب يف الواليات المتحدة
ون عىل ر
حالة طوارئ إثر هجوم إلكب ي10-05-2021
www.bbc.com/arabic/world-56899399
قراصنة يهددون رشطة واشنطن بإفشاء أشارها27-04-2021 2
إلكبون يعطل بث إحدى أكب القنوات التليفزيونية ف ر
هجوم ر28-03-2021 3
www.bbc.com/arabic/science-and-tech-56558903
أسباليا
ر
ي
ي
ر
كامبا" مراقبة داخل مؤسسات من بينها عيادات خاصة ر
www.bbc.com/arabic/science-and-tech-56323626
وشكة تسال
ألف ر150 " رشكة أمريكية تحقق يف اخباق10-03-2021 4
ر
البيت األبيض يحذر من "تهديد فعىل" ر: مايكروسوفت06-03-2021 5
www.bbc.com/arabic/science-and-tech-56297463
اإللكبونيات العمالقة
الخباق برنامج بريد رشكة
ي
ابباز جامعة أمريكية والحصول عىل ر
كيف تمكن قراصنة من ر30-06-2020 6
www.bbc.com/arabic/science-and-tech-53225880
أكب من مليون دوالر؟
www.bbc.com/arabic/world-52656314
الصي بـ"محاولة شقة أبحاث" حول الوباء
الواليات المتحدة تتهم: رفبوس كورونا13-05-2020 7
ر
www.bbc.com/arabic/science-and-tech-52349177
الفبوس يوميا
مليون رسالة احتيال عن ر18 غوغل تحظر19-04-2020 8
ر
www.bbc.com/arabic/business-51046886
يجب رشكة الرصافة عىل العودة إىل السجالت الورقية
ون ر
هجوم إلكب ي: ترافلكس10-01-2020 9
ر
www.bbc.com/arabic/science-and-tech-50857171
خطب يستهدف وزارة الخارجية النمساوية
ون
ر
هجوم إلكب ي05-01-2020 10
ر
www.bbc.com/arabic/middleeast-50799204
ون" يف أسبوع واحد
ثان هجوم إلكب ي
إيران تعلن إحباط " ي15-12-2019 11
ّ فيسبوك يؤكد05-09-2019 12
www.bbc.com/arabic/science-and-tech-49596081
المستخدمي
ماليي
ترسب أرقام هواتف
ر
ر
www.bbc.com/arabic/world-49166226
ماليي من عمالء مؤسسة مالية أمريكية
106 شقة بيانات30-07-2019 13
ر
اسبلين ر
مليون ر183 الخطوط الجوية البيطانية تواجه غرامة بـ08-07-2019 14
www.bbc.com/arabic/world-48906726
الخباق قراصنة بيانات عمالء
ر
ي
واشنطن "تنفذ هجوما ر23-06-2019 15
www.bbc.com/arabic/middleeast-48737811
إلكبونيا" عىل نظم تسليح إيرانية
شقة صور آالف المسافرين ف عملية قرصنة ر12-06-2019 16
www.bbc.com/arabic/science-and-tech-48585344
إلكبونية بالواليات المتحدة
ي
ر
www.bbc.com/arabic/vert-fut-46974782
ون أصاب منطقة يف أالسكا بالشلل
قصة هجوم إلكب ي25-01-2019 17
ر
www.bbc.com/arabic/science-and-tech-46714963
ون يستهدف صحفا أمريكية بارزة ويعرقل أنشطة الطباعة والتوزي ــع
هجوم إلكب ي30-12-2018 18
www.bbc.com/arabic/business-43528443
مليار دوالر58 أشار أسوأ أسبوع يف تاري ــخ فيسبوك وخسارة25-03-2018 19
www.bbc.com/arabic/science-and-tech-41744319
السء يرصب أوكرانيا وروسيا ويطلب فدية
األرنب ي25-10-2017 20
ر
ون
www.bbc.com/arabic/science-and-tech-40472627
أوكرانيا تتهم روسيا بالوقوف وراء أحدث هجوم إلكب ي02-07-2017 21
ر
www.bbc.com/arabic/media-40428729
ون الذي ضب العالم؟
ما هو رفبوس "بيتيا" االلكب ي28-06-2017 22
www.bbc.com/arabic/science-and-tech-40347359
" رشكة كورية جنوبية تدفع مليون دوالر لقراصنة لـ"استعادة السيطرة عىل أجهزتها21-06-2017 23
اليوروبول يدعو إىل تحقيق دوىل ف هجمات ر13-05-2017 24
www.bbc.com/arabic/science-and-tech-39907190
بلد100 الكبونية "ليس لها مثيل" طالت نحو
ي ي
ر
ون
https://ar.wikipedia.org/wiki/%D9%87%D8%AC%D9%88%D9%85_%D9%88%D8%A7%D9%86%D8%A7%D9%83%D8%B1%D8%A7%D9%8A_%D8%A7%D9%84%D8%A5%D9%84%D9%83%D
هجوم الفدية اإللكب ي12-05-2017 25
ر
سون
االمريك يتهم كوريا الشمالية بشن هجمات الكبونية عىل
مكتب التحقيقات االتحادي19-12-2014 26
www.bbc.com/arabic/scienceandtech/2014/12/141219_fbi_sony_attacks
ي
ي
www.bbc.com/arabic/scienceandtech/2014/07/140715_cnet_hacked
"س نت
قراصنة روس يرسقون بيانات مليون مستخدم من موقع " ي15-07-2014 27
ر
www.bbc.com/arabic/scienceandtech/2014/02/140223_internet_security_routers
" هجمات القراصنة عىل أجهزة توجيه االنبنت " يف تصاعد23-02-2014 28
كوريا الجنوبية تطور سالحا ر21-02-2014 29
www.bbc.com/arabic/scienceandtech/2014/02/140221_skorea_nkorea_cyberweapons.shtml
إلكبونيا يف مواجهة الشمال
ر
ر
www.center-lcrc.com/index.php?s=4&id=7643
ان
قصة الدودة اإللكبونية المخربة للمرسوع النووي اإلير ي.. ستكسنيت04-04-2013 30
ر
www.bbc.com/arabic/scienceandtech/2012/08/120831_computer-virus.shtml
ون يرصب "راس غاز" القطرية
هجوم الكب ي31-08-2012 31
إيران تتعرض لهجوم ر29-05-2012 32
www.bbc.com/arabic/scienceandtech/2012/05/120529_cyber_attack_iran_israel
ون جديد
إلكب
ي
www.bbc.com/arabic/middleeast/2010/09/100926_bushehr_virus_tc2
بفبوس
طهران تقر بإصابة بعض أجهزة الكمبيوتر الشخصية يف بوشهر ر26-09-2010 33
119
Case Study; The Stuxent Worm
Stuxnet∗ is a worm that caused substantial damage to the nuclear program of Iran.
• Stuxnet was first uncovered in 2010. It is thought to have been in development since 2005†
• It is widely understood that stuxent is a cyberweapon built jointly by the United States and
Israel
• Stuxnet specifically scans for Siemens Step7 software on computers controlling a PLC
(computers that control gas centrifuges that separates nuclear materials)
– Stuxnet reportedly ruined almost one–fifth of Iran’s nuclear centrifuges
– Stuxent infected over 200,000 computers and caused 1,000 machines to physically
degrade
• Stuxnet has three modules:
1. worm that executes all routines related to the main payload of the attack
2. link file that automatically executes the propagated copies of the worm
3. rootkit that is responsible for hiding all malicious files and processes
∗
†
[https://en.wikipedia.org/wiki/Stuxnet]
At that time, Iran was still setting up its uranium enrichment facility.
67
[https://m.facebook.com/story.php?story_fbid=2096765737070017&id=
100002098327218]
68
120
Assignment
• Answer questions (2.10), (2.11) and (2.12)
121
2.4.1
Tuning MS Windows against Viruses
Usual Forms of Windows Viruses
Any executable file including:
• *.exe
• *.bat
• *.com
• *.lnk
• *.dll
• *.cmd
• *.reg
• ...
122
69
Basic Traps Infecting Windows with a Virus
• Autorun.inf
• desktop.ini
• Hide your files/folders and create a virus copy with the same name.exe (or name.lnk) and
set the .exe file icon to:
– yellow folder icon
– ...
– MS Word/Excel document icon
Tuning MS Windows against Viruses
• Disable autorun feature of Windows
• Do not hide any file or folder
• Do not hide file extensions
• Sort the files by type (extension)
• Install a program that monitors autostart programs (e.g.: WinPatrol∗ )
• Regularly install windows security updates
• Install a good/lightweight anti–virus and regularly update it
Be Careful
• Do watch the extension of the file you are double–clicking/executing
• Check that what you are executing is not a shortcut/link
If Infected with a Virus
• Boot from a live Linux distribution (Ubuntu for example) from a bootable USB flash disk
• Backup all your data/settings/preferences/. . .
• Scan your files on a clean PC using a strong and up–to–date antivirus
• Format and reinstall Windows
Assignment
• Answer questions (2.13) & (2.14)
∗
WinPatrol worked very well with Windows XP and 7. However, it is no longer effective for Windows 10 and
beyond!
70
2.5
Additional Information
Sakhr Software Company∗
Sakhr Software is an Arabic–language technology company based in Kuwait.
• Sakhr Software was founded in 1982 by Mohammed Al–Sharekh after branching out of
his computer HW company Al–Alamiah [sec. 1.5.1]
• In 1990, following the Gulf War, Sakhr relocated to Heliopolis, Cairo
– After that, the company terminated all HW manufacturing projects, and focused exclusively on developing SW
• After nearly three decades in the industry and more than US$100 million investments,
Sakhr now leads the field of Arabic machine–translation, OCR, speech–recognition,
speech–synthesis, search, and localization
– Sakhr provided Arabic localization services to Saudi’s Ministry of Education,
Egypt’s Ministry of Commerce, Oman’s Ministry of Education, and Dubai Chamber
of Commerce and Industry
• Sakhr research and engineering activities are in Silicon Valley and Egypt, with sales offices in the U.S. (Washington, DC and California), Kuwait, UAE (Dubai and Abu Dhabi),
Oman, Egypt and Saudi Arabia
128
2.5.1
Fork vs Branch
Copying the source code of a SW project, and further developing it, results in a dependent SW
that is called either a:
fork
branch
if the dependent SW does not adopt subse- if the dependent SW continuously adopts subquent developments of the parent SW
sequent developments of the parent SW
• E.g., Mac OS X is a fork of BSD [sec.
2.2.2.3]
• E.g., Linux Mint is a branch of Ubuntu
which is a branch of Debian [sec.B.1]
129
2.5.2
Character Encoding
• ASCII code is a 7–bit code that represents 27 =128 different characters.
– That is enough for all upper–case and lower–case letters, digit and punctuation marks
on most English keyboards
• Extended ASCII code is an 8–bit code that represents 28 =256 different characters
– This enabled using characters such as é or © for other European languages
∗
[https://en.wikipedia.org/wiki/Sakhr_Software_Company]
71
• Japanese used the JIS† (Japanese Industrial Standards) encoding
• Arabic however used several encodings such as: Windows–1256, ISO–8859–6, . . .
– This yielded unreadable text when using the wrong encoding
• Unicode uses between 8 and 32 bits per character
– It can represent 232 =4 GibiCharacter, covering all the languages of the world
∗
‡
†
2.5.3
Data Backup
• Check appendix D
†
Since Japanese uses a unique encoding, it does not suffer the problems we encounter when displaying Arabic
text
∗
[www.bbc.co.uk/education/guides/zp73wmn/revision/5]
[https://msdn.microsoft.com/en-us/library/bb688113(d=printer).aspx]
‡
[https://techblog.workiva.com/tech-blog/unobfuscating-unicode-ubiquity-practicalguide-unicode-and-utf-8]
†
72
2.6
Laboratory Work
2.6.1
Windows Viruses
Laboratory 1 (Windows Viruses)
Bring an infected flash disk and explain:
• what did the virus do?
• what is the virus going to do?
• what is you plan against the virus?
132
2.6.2
Install Windows
Partitioning Recommendations
It is recommended to separate the OS partition from your personal data. That is, create:
• partition “C:” for Windows and user account folders
• separate partition(s) for your personal data
• Never save/copy your files to your user folders; e.g.: Desktop, Documents, Pictures, . . .
Note that Windows∗ can resize existing partitions.
∗
Windows 7 and later
73
133
Laboratory 2 (Install MS Windows)
If your OS is setup by your PC manufacturer,
• create the backup DVD’s
Otherwise,
1. download all your HW drivers from your support page
2. ensure BIOS or UEFI is well configured for best performance and security. E.g.:
• HDD controller is set to the fastest mode∗
• Use UEFI instead of BIOS (if your PC supports UEFI)
– Enable secure boot
• ...
3. install Windows
• Recommended: separate your HDD into separate partitions (one for each OS
and another for your data)
• Activate your Windows
4. If Windows didn’t install HW drivers correctly, install them yourself
• Depending on your PC manufacturer, these SW can greatly simplify installing
HW drivers:
– Dell SupportAssist
– HP Support Assistant
– Lenovo Vantage
5. Update your Windows
• Updating may solve several strange problems, eg.: unrecognized HW, malfunctioning HW, . . .
∗
E.g. AHCI for SATA)
74
Laboratory 3 (Tuning Windows PC)
1. Tune your PC; as explained in appendix A. That is:
• disable automatic downloading/installation of Windows updates
• disable Windows Telemetry
• Disable Unnecessary Auto–Start Processes
2. Tune Windows against viruses, as explained in sec. 2.4.1
3. Add Arabic input language
4. Choose your power plan
• when to turn off the display
75
• when the computer sleeps
• ...
5. Clone backup the OS partition
6. Install security SW (WinPatrol† (or similar SW), anti–virus\spyware\. . . )
7. Install productivity SW
• Take care that MS Office restores automatic downloading and installation of Windows updates
8. Incrementally backup the OS partition again
9. Copy your data to the HDD
10. Create a separate incremental backup strategy for your data
Project idea 1 (Deploy Windows & SW to Multiple PC’s)
• Deploy Windows and HW drivers to multiple PC’s
• Manage deployed Windows OS’s
• Install/Uninstall application SW
• ...
Suggested solutions are:
• FOG Project∗
• Clonezilla
• CloneDeploy†
• Microsoft Deployment Toolkit (MDT)
or System Center Configuration Managerद
• Acronis Snap Deploy
• SmartDeploy
2.6.3
Install Linux
The swap Partition‖
Swap space forms a part of the virtual memory, which is a combination of the physical memory
(RAM) and the swap space.
WinPatrol worked very well with Windows XP and 7. However, it is no longer effective for Windows 10 and
beyond!
∗
https://fogproject.org/
†
http://clonedeploy.org/
‡
Free with Windows Server
§
https://technet.microsoft.com/en-us/windows/mt240567
¶
https://technet.microsoft.com/en-us/library/mt158221%28v=vs.85%29.aspx
‖
[https://help.ubuntu.com/community/SwapFaq]
76
• It is recommended to put the swap partition on fast accessible place of the HDD such as
the start or the end of the HDD.
RAM (GB)
1
2
3
4
5
6
8
12
16
24
32
64
128
No hibernation
1
1
2
2
2
2
3
3
4
5
6
8
11
swap (GB)
With hibernation
2
3
5
6
7
8
11
15
20
29
38
72
139
Maximum
2
4
6
8
10
12
16
24
32
48
64
128
256
137
Partitioning Recommendations
It is recommended to separate the OS partition from your personal data. That is, create:
• partition “/” for Linux OS
• separate partition for the user account(s) “/home” and users’ personal data∗
138
Dual–booting Linux with Windows
If you are installing Linux beside an existing Windows (dual boot scenario), it is better to resize
windows partitions from Windows† rather than from Linux installation media.
• This is much more stable and safe
139
Laboratory 4 (Install Linux)
• Download and install latest VMWare player
• Download your favorite Linux distribution
– Popular distributions include: Ubuntu, Linux Mint, Manjaro, elementary, OpenSuse, Fedora, Mageia
– Popular desktop environments include: KDE, Xcfe, Gnome, Cinnamon
– Make sure your chosen distribution is compatible with your version of VMWare
player
∗
†
or you may create another partition for users’ personal data
Windows 7 and later
77
• Copy the following to your PC:
– VMWare player
– Your favorite Linux dist
• Create a virtual machine and install your favorite Linux distribution
– Respect the minimum requirements
– Partitioning
∗ swap
∗ /
∗ /home
∗ ...
– Never forget your root password
• Practice installing new SW as explained in sec. B.5
• Practice using the OS
Basic tasks for new Linux users
• www.ibm.com/developerworks/linux/tutorials/l-basics/
Uninstalling Linux from a Windows Dual–boot PC∗
• Restart the PC to Windows Command Prompt
• Execute the command > bootrec /fixmbr
• Reboot to Windows and delete all Linux partitions
• Use the space resulting from Linux deleted partitions as you wish. E.g.:
– Extend Windows partitions
– create new partitions
– ...
∗
[https://askubuntu.com/questions/133533/how-to-remove-ubuntu-and-put-windows-back-
on]
78
2.7
Questions
2.1. Make a survey about “Google Summer of Code”
2.2. If you could join Google Summer of Code, before receiving your stipend, who will judges
your work?
(a) Google
(c) GNU community
(b) A mentoring organization
(d) A public vote
2.3. In less than 70% of an A4 paper, survey the history of MS Windows
2.4. What are the new features of the latest update of Windows 11?
Hint Check the release notes
2.5. As a student, how can you obtain a licensed version of the following?
(a) MS Windows
(c) MS Visual Studio
(b) MS Office
(d) Matlab
2.6. Survey the maximum file size and partition size of the following file systems
(a) FAT 16
(f) Btrfs
(b) FAT 32
(g) Joliet
(c) exFAT
(h) UDF
(d) NTFS
(e) ext4
(i) ZFS
2.7. Survey the capabilities of Acronis True Image Home and answer the following
(a) what is a backup?
(b) What is the difference between full, incremental and differential backup?
(c) What else should be performed in a good backup?
(d) What is the difference between partition backup and data backup?
(e) What is the difference between backup and synchronization?
(f) Give some free/open–source/cross–platform alternatives to Acronis True Image
Home
2.8. If your OS was damaged and you decided to format your HDD, how can you backup your
data before formatting?
2.9. What is your best dictionary collection for use with GoldenDict?
2.10. Explore the “Technology” section of websites like BBC (www.bbc.co.uk/arabic/
scienceandtech/) or Aljazeera (www.aljazeera.net/scienceandtechnology/
pages), channels of “BBC4Tech”, and and get two cyber–security related stories
2.11. Mention two sample traps fooling you to steal your passwords
2.12. Survey what is:
79
(a) spyware
(b) Trojan
(c) rootkits
(d) spam
(e) phishing
You may use [1, The bad side of the Web]
2.13. Answer the following questions;
(a) What is a malware?
(b) What file extensions do you expect for a virus file?
(c) How can you identify a virus?
(d) How do viruses spread?
(e) How can you tune your PC against viruses (other than using anti–virus)?
(f) Is an anti–virus sufficient to guard a PC against viruses?
(g) When should you doubt that your PC is infected?
(h) What to do if your PC got infected?
(i) Is Linux/Unix immune against viruses?
(j) Can a PC–Windows virus run on Linux, iPhone, Android, Windows–phone?
2.14. Tell exactly how your PC got infected with a virus
• What is your plan prevent this to occur again?
80
Part 3
Networks and the Internet
References
1. J. Ross, Network Know-How an Essential Guide for The Accidental Admin, No Starch
Press, 2009. [7]
2. Basic Networking Tutorial (www.techiwarehouse.com/engine/d9e99072/BasicNetworking-Tutorial). [8]
3. Reference Manual for the RangeMax Wireless Router WPN824, 2005. [9]
4. Gadgets, Games, Robots and the Digital World, Dorling Kindersley Publishing, 2011. [1]
• Arabic translation is available at Misr Public Library (www.mpl.org.eg)
5. Wikipedia: the free encyclopedia (http://en.wikipedia.org)
6. The Internet
144
What to do with a Network?
Ethernet LAN
Access
Point
Gateway
router
Switch
Print
server
Laptop
Desktop
NAS
server
Printer
File
server
HDD
HDD
Storage
Storage
Media
player
TV
Using a network, you can share:
• files
• HW (eg: printer, scanner, storage, camera, . . . )
• Internet
• multimedia (streaming)
• ...
• A device connected to the network is called a node
145
81
LAN vs WAN
Another
LAN
Another
LAN
WAN
LAN
Gateway
router
Access
Point
Switch
• Local Area Network (LAN) is the local network you connect to
• Wide Area Network (WAN) is the network outside your LAN
Ethernet
Another
LAN
Another
LAN
WAN
LAN
Gateway
router
Access
Point
Switch
Ethernet is one of the methods for establishing LANs.
• Ethernet is fast, extremely easy-to-use, flexible, and inexpensive
82
• Today, more than 85% of all LAN’s use some form of Ethernet. Examples include:
Wired Ethernet∗
Wireless Ethernet (Wi-Fi)‖
– 10Base-T (10 Mbps† )
– IEEE 802.11g (˜ 54 Mbps)
– 100Base-T‡ (100 Mbps)
– IEEE 802.11n (˜ 600 Mbps)
– 1000Base-T§ (1 Gbps)
– IEEE 802.11ac (˜ 6.93 Gbps)
– 10GBase¶ (10 Gbps)
– IEEE 802.11ax (˜ 9.61 Gbps)
• Wireless Ethernet is also called Wi-Fi (short for Wireless Fidelity)
8 bit = 1 Byte
(866.25)
(1,250.)
Speed of wired vs wireless Ethernet
10,000.
11,000.
6,930.
1,000.
(75.)
(125.)
8,000.
1,000.
600.
100.
(6.75)
(12.5)
800.
10.
54.
8.
1.
0.8
0.1
0.08
0.01
0.008
(MByte/s)
100.
80.
Mbit/s
(1,375.)
• For the speeds above, wired speeds are actual, while Wi-Fi speeds are theoretical limits
0.001
Fast Ethernet
Gigabit Ethernet
10 Gigabit Ethernet
IEEE 802.11g
Wired Ethernet
IEEE 802.11n
IEEE 802.11ac
IEEE 802.11ax
Wireless Ethernet
147
∗
[https://en.wikipedia.org/wiki/Ethernet_physical_layer]
Mega bit/second
‡
Fast Ethernet
§
Gigabit Ethernet
¶
10 Gigabit Ethernet
‖
[https://en.wikipedia.org/wiki/IEEE_802.11]
†
83
Advertised Wi-Fi Speeds
Although the advertised speeds of wired ethernet are actual, advertised Wi-Fi speeds are theoretical limits!!
• Main factors that adversely affect Wi-Fi speed include:
– Distance: The farther out, the slower the connection gets.
– Obstacles: Walls and large objects will block the signals and shorten the Wi-Fi
range.
– Interference: The more devices of the same radio frequencies being used in the
same area, the slower they get.
– Compatibility: When devices of different Wi-Fi speed tiers, standards and manufacturers are used together, oftentimes they must adhere to a lower speed standard in
order for all to function together properly.
– Shared bandwidth: available bandwidth is shared between all users on the same
wireless network.
• Therefore, actual Wi-Fi speeds are always significantly lower than their theoretical limit
802.11a
802.11b
802.11g
Carrier Frequency∗
(GHz)
5
2.4
2.4
802.11n
2.4 & 5
802.11ac
5
Channel Bandwidth
(MHz)
20
22
20
20
40
20
40
80
160
‡
Theoretical speed
(Mbps)
54
11
54
288.8
600
346.8
800
1733.2
3466.8
Actual Speed†
(Mbps)
20
2˜6
20
40˜50
70˜100
70˜100
380˜500
[https://en.wikipedia.org/wiki/Template:802.11_network_standards]
Actual real-life average speeds you can expect from wireless routers within a reasonable distance, with low interference and small number of simultaneous clients [www.speedguide.net/faq/what-is-the-actual-reallife-speed-of-wireless-374] and [www.lifewire.com/how-fast-is-a-wifi-network-816543] and
[www.cnet.com/how-to/your-router-isnt-as-fast-as-you-think-it-is-heres-why/]
§
84
Top 500 Supercomputer Network Technologies¶
Interconnect Family - Systems Share
100
90
80
70
Share
60
50
40
30
20
10
0
1995
2000
2005
2010
Proprietary Network
Infiniband
Quadrics
Others
N/A
Fat Tree
Custom Interconnect
Cray Interconnect
NUMAlink
Gigabit Ethernet
Crossbar
SP Switch
Omnipath
Myrinet
2015
149
¶
[www.top500.org/statistics/]
85
3.1
Network Topology
Point-to-point
Star
Mesh
Hub or
Switch
Ad hoc
or
Wifi direct
Access
point
Wireless Infrastructure mode
• Point-to-point
– No need for switch nor access point
– Fastest data transfer rate
• Star
– Often used in Small Office/Home Office (SOHO) LANs
– Data transfer rate is the speed of the hub/switch/access-point
• Mesh
– Often used in the WAN connecting your LAN to the Internet
86
3.2
Network Hardware
LAN Cables
Many devices today support Auto MDI-X capability, wherein straight through cable can be used
in place of a crossover cable, or vice versa.
87
151
Hub
Ethernet
Hub
• When a data packet enters a hub, the hub sends that packet to all of the nodes connected
to the hub
– Thus, only one packet can travel through the network at a time
• Each node compares the address on the packet with its own address and either accepts or
ignores it
• Therefore, a network is no faster than the slowest node
– If all computers in a network have 100 Mbps NIC, but the network printer has 10
Mbps NIC, the whole network will run at 10 Mbps or less
• As more nodes use the hub at the same time, data transfer speed through the entire network
drops
• Hubs are currently obsolete
Switch
Ethernet
Ethernet
Switch
5
4
3
Port led
On
= Ethernet link
Blinking = Activity
Off
= No link
A switch reads the address of each packet and delivers it to its destination solely.
• Thus, there is no need to send the target-node-address with the packets
88
2
1
• Additionally, the switch can handle more than one connection simultaneously
• Moreover, a node can simultaneously send and receive at the same time∗
• As a result, the speed and throughput are much higher than the hub
– 10/100 Mbps and 100/1000 Mbps switches are common nowadays in the market
153
Switch Types∗
Unmanaged switches are basic plug-and-play switches with no configuration, management, or
monitoring options.
Smart managed switches additionally offer Quality of Service (QoS), Virtual Local Area Networks (VLAN), and network traffic monitoring (SNMP).
• They can be managed from a web browser without requiring any additional SW.
Managed switches offer wider management features with Layer 2 (L2) (switching) and Layer 3
(L3) (routing) functionalities.
• Advanced L2 features include granular
traffic control using Access Control Lists
(ACL) and scalable deployment options
(using L2/L3 DHCP relay agents).
154
• Advanced L3 features include resilient
and load-balanced static/dynamic routing.
• They can be managed through a CLI to
enable easy configuration and deployment in wide-scale enterprise environments.
Access Point
An access point may work in several modes, including:
Ethernet
∗
∗
This is called full duplex mode.
[https://kb.netgear.com/25445/Which-NETGEAR-switch-is-right-for-me]
89
Switch
Switch
Bridge
Access
point
Gateway
router
• Access-point (or infrastructure) mode
– The access point sends a data packet to all nodes
∗ Each node checks the packet address to accept/ignore it
∗ This is basically the same concept of the hub
• Bridge mode
Switch
Repeater/Extender
Access
point
Gateway
router
• Repeater (or extender) mode
– This mode however halves∗ the wireless bandwidth, since the repeater communicates
both with the main access-point and the client nodes
– Repeaters also bounce back all the router’s traffic, creating congestion and slowing
the network
Wi-Fi Security [7, ch. 13]
Wi-Fi uses radio signals with a well defined set of characteristics!
• So anybody who wants to dedicate enough time and effort to monitor these signals can
probably find a way to intercept and read the data contained in them
• Refer to [7, ch. 13] for more information
∗
[www.speedguide.net/faq/wireless-repeater-extender-vs-access-point-385]
90
Powerline Networks
pair
pair
Router
Desktop
pair
Set-Top Box&TV
• Refer to [7, page 16]
157
Assignment
• Answer questions (3.1), (3.2) and (3.3)
158
3.2.1
More Information
• Reference [1];
• Reference [7];
– What do search engines do?
– ch. 12: Sharing files through your
network
– Who invented Google?
– ch. 14: Printers and other devices
on your network
– Server farm
– ch. 15: Other things you can connect to your network
– ch. 13: Virtual Private Networks
(VPN)
159
91
Link Aggregation Group (LAG)∗
Link Aggregation (LA) allows combining multiple Ethernet links into a single logical link.
• LAG types are:
1. Static
– requires manually configuring the switch
– doesn’t help isolate errors, such as incorrectly connected cables
2. Dynamic
– uses Link Aggregation Control Protocol (LACP)
– tracks that each cable is actually connected to the intended LAG∗
– helps preventing errors
• Unmanaged switches do not support LA
• Not all managed switches support LACP
Microsoft NIC Teaming
Windows-based systems, NIC teaming† improves network performance and fault tolerance.
• Teaming allows combining multiple physical NIC’s into one virtual NIC
– Traffic sent through the virtual NIC is load-balanced across the assigned physical
NIC’s
• Teaming on Windows Server can support up to 32 physical connections per virtual NIC
• Teaming offers a simple solution for link aggregation and load balancing, failover and
Software-Defined Networking (SDN)
• One of the benefits of Microsoft’s NIC teaming is that it is hardware and vendor independent
• Teaming modes:
– Switch Independent
∗ the only mode that doesn’t require configuration changes on the switches
∗ allows connecting to multiple, non-stack switches
∗ uses MAC address to control to which interface incoming data should be sent
– Static LAG
∗ requires connect to a single switch or a single switch stack
– LACP (Dynamic LAG)
∗ requires connect to a single switch or a single switch stack
∗
[https://kb.netgear.com/000051185/What-are-link-aggregation-and-LACP-and-how-canI-use-them-in-my-network]
∗
LACP will not send data through links that are not connected to the expected LAG
†
[www.serverwatch.com/guides/nic-teaming]
92
3.3
Logical Networks
Logical Network Modes
Irrespective of the physical network topology, nodes in a network may communicate in any of
the following modes:
Peer-to-peer (P2P)
Client-server
All nodes are peers
• No node has control over another
One or more nodes are servers
• Servers can control the security and
permissions of other nodes
• No security
Peers share their resources
Clients share server’s resources
162
3.3.1
Sample Logical Networks
Peer-to-peer vs Direct Download
Peer-to-peer download
Direct download
Peers share their bandwidths
Clients share server’s bandwidth
163
93
Microsoft Windows Workgroup vs Domain Networks∗
MS Workgroup
MS Domain
All computers are peers
One or more computers are servers
• no computer has control over another
• The server can manage, update and
control the security/permissions of
clients
• This eases making changes to clients
• Usually Windows Server is the server
OS
To use any computer, you must have an
account on this computer
If you have an account on the domain, you
can log on to any computer using your
domain account
Additional Examples
Several SW applications offer server/client editions to manage the clients from a central server.
Examples include:
• Anti virus corporate edition
• Deep Freeze enterprise edition
• ...
Project idea 2 (Windows Administration)
Administer a Windows PC to:
• allow only running a set of predetermined programs
• prevent SW install/uninstall
• restrict internet activity only to windows update, anti-virus update, email . . .
• prevent usage of removable usb flash disks and/or CD/DVD
• disable autorun
• ...
Is this possible without establishing Windows Domain network?
∗
[windows.microsoft.com/en-us/windows-vista/what-is-the-difference-between-adomain-and-a-workgroup]
94
3.4
The Internet
The Internet Service Provider (ISP)
Another
customer's LAN
Another
customer's LAN
ISP’s
WAN
LAN
Access
Point
Gateway
router
Switch
In Egypt, sample ISP’s are We, Vodafone, Orange, Etisalat, . . .
167
Assignment
• Answer question (3.4)
168
The Modem
Your home LAN probably connects to the Internet through a telephone-cable or cellular-phonewireless-network.
• The modem (modulator/demodulator) is the device that converts the data packets within
the LAN to signals that can travel through the telephone-cable or the cellular-phonewireless-network
• Sample modems are:
– 3G/3.5G/4G USB modem
– V.92 56k fax modem
– ADSL modem
Ethernet
Line in
– Satellite modem
95
169
11,000.
6,930.
1,000.
1,000.
(21.625)
(75.)
(125.)
8,000.
8.192
8.
(12.5)
(1.7475)
(6.5)
52.
24.576
1.
0.056
(0.0072)
(0.0018)
(0.007)
0.8
0.08
10.
13.98
12.288
(0.048)
(1.024)
54.
100.
173.
100.
(0.0296)
80.
(1.536)
(6.75)
(12.5)
100.
(3.072)
600.
800.
Mbit/s
8 bit = 1 Byte
0.384
(MByte/s)
10,000.
Speed of Ethernet vs Internet
(1,375.)
(866.25)
(1,250.)
Ethernet vs Internet Speeds
0.1
0.2368
0.0576
0.01
0.0144
0.008
0.001
Wired Ethernet
Wireless Ethernet
Wired Internet
Wireless Internet
• Remember that wired speeds are actual, while wireless speeds are theoretical limits
• In some countries, further speeds may be established. For example;
– In Japan
∗ 50 Mbit/s ADSL was common in 2004
∗ 100 Mbit/s FTTH was common in 2007
∗ 1000 Mbit/s FTTH is common since 201x
Assignment
• Answer question (3.5)
96
3.4.1
The Internet Protocol Suite (TCP/IP)
Hidden layers of Internet
97
TCP/IP model
Application process 1
Application process 2
Data
Data
4: Application layer
Data
4: Application layer
data
3: Transport layer
Segment
3: Transport layer
header
Packet
IP
header
2: Internet layer
2: Internet layer
IP data
Frame
1: Link layer
Frame
header
Frame data
Frame
footer
Physical link data transmission
The Internet Protocol (IP) Suite
The rules (protocols) that control the Internet
are called TCP/IP protocols.
• The most important TCP/IP protocols are:
TCP (Transmission Control Protocol)
IP (Internet Protocol)
UDP (User Datagram Protocol)
– alternative to the TCP
98
1: Link layer
173
3.4.2
The IP Address
MAC and IP addresses
MAC address serves as the device name
• It is assigned by the manufacturer of the Network Interface Controller (NIC) HW
(e.g.: your network card), according to the rules managed by the Institute of Electrical and Electronics Engineers (IEEE)
• It is stored in the HW and cannot be changed
IP address serves as the device address
• It is assigned according to LAN rules
• It often changes every time you connect to a LAN
• To identify your MAC address and your current IP address, run the CLI command
– ipconfig /all for Windows
– ifconfig for Linux/Mac
C:\>IPConfig /all
Windows IP Configuration
Host Name . . . . . . . . . . . . : desktop
Primary Dns Suffix . . . . . . . :
Node Type . . . . . . . . . . . . : Unknown
IP Routing Enabled. . . . . . . . : No
WINS Proxy Enabled. . . . . . . . : No
DNS Suffix Search List. . . . . . : domain.actdsltmp
Ethernet adapter Local Area Connection:
Connection-specific DNS Suffix . : domain.actdsltmp
Description . . . . . . . . . . . : Intel(R) PRO/100 VE Network
Connection
Physical Address. . . . . . . . . : 00-0C-F1-AA-BF-BF
Dhcp Enabled. . . . . . . . . . . : Yes
Autoconfiguration Enabled . . . . : Yes
IP Address. . . . . . . . . . . . : 192.168.1.100
Subnet Mask . . . . . . . . . . . : 255.255.255.0
Default Gateway . . . . . . . . . : 192.168.1.1
DHCP Server . . . . . . . . . . . : 192.168.1.1
DNS Servers . . . . . . . . . . . : 198.137.231.1
206.63.63.1
Lease Obtained. . . . . . . . . . : Wednesday, April 08, 2009 3:11:22 PM
Lease Expires . . . . . . . . . . : Friday, April 10, 2009 3:11:22 PM
.The IPConfig /all command displays additional information about your connection
174
99
IPv4 and IPv6
The technical committees, international standards organizations and government agencies that
manage the Internet have all agreed on a numeric address.
• The agency responsible for assigning numeric IP addresses on the Internet is the Internet
Assigned Numbers Authority (IANA)
• IANA is a department of ICANN, a nonprofit private American corporation
IPv4 is a 32-bit (4 bytes) IP address
• It supports just over 4 million addresses
• It is shown as four numbers between 0 and 255 like 192.168.3.200
IPv6 was recently introduced featuring 128 bits (16 bytes)
• It supports just over 4 billion addresses
• It is typically represented in HEX
Assignment
• Answer question (3.6)
100
Reserved IP Addresses
Another customer's LAN
IP: 103.75.201.47
ISP’s WAN host
IP: 103.75.201.0
Another customer's LAN
IP: 103.75.201.50
WAN IP: 103.75.201.48
Ethernet LAN
Gateway Router
Access
Point
LAN IP: 192.168.0.1
Switch
IP:192.168.0.100
IP:192.168.0.101
IP:192.168.0.102
IP:192.168.0.105
• IANA has reserved several blocks of IP addresses for LANs. Among them are:
– 10.0.0.0 to 10.255.255.255∗
– 172.16.0.0 to 172.31.255.255†
– 192.168.0.0 to 192.168.255.255‡
• When a router receives a packet from the LAN with an address in one of these ranges, it
does not send it to the WAN (the Internet, for ex.)
On the Internet, the servers use IP’s from a range provided by IANA
Within a LAN, the DHCP server uses IP’s from the reserved range
177
∗
This falls within the Class A address range of 1.0.0.0 to 127.0.0.0, in which the first bit is 0
This falls within the Class B address range of 128.0.0.0 to 191.255.0.0, in which the first two bits are 10
‡
This falls within the Class C range of 192.0.0.0 through 223.255.255.0, in which the first three bits are 110
†
101
Fixed and Dynamic IP Address
The IP address of a network node can be either:
Fixed (or Static) IP
Dynamic IP
• You manually assign the IP
• The node receives the IP from the
Dynamic Host Configuration Protocol
(DHCP) server
• Both types can work equally well
– However, IP adresses should respect IANA rules, and someone should take care
about IP conflicts
Assignment
• Answer questions (3.7), (3.8), (3.9) & (3.10)
102
Subnet Mask
Subnet mask specifies which part of the IP
address changes for each node within the
LAN
• For example, the most common subnet mask is 255.255.255.0, which means that the last
of the four numbers vary for each node within the LAN
– E.g., if your LAN controls all the addresses in the 123.223.123.XXX group, your
address might be 123.223.123.103, while another node on the same LAN might have
123.223.123.117
• In large complex networks, subnet masking can be used to divide a network into smaller
subsidiary networks, or subnets
– Nodes within the same subnet can exchange data more quickly
• Using subnets is an advanced networking practice;
– you’re not likely to see this setup in a simple home network or very small business
network
– More information are in [9, Appendix B]
180
More Information
• www.ralphb.net/ipsubnet/index.html
181
Assignment
• Answer question (3.11)
182
103
3.4.3
The Router
Another customer's LAN
IP: 103.75.201.47
Another customer's LAN
IP: 103.75.201.50
ISP’s WAN host
IP: 103.75.201.0
WAN IP: 103.75.201.48
Ethernet LAN
Gateway Router
LAN IP: 192.168.0.1
Access
Point
Switch
LAN
WAN
IP:192.168.0.100
IP:192.168.0.101
IP:192.168.0.102
IP:192.168.0.105
High speeds can be easily established within a LAN. On the other hand, establishing high bandwidth between a LAN and the Internet is not that easy!
• Therefore, for best usage of the slower WAN link, LAN traffic must be examined so that
only data meant for the Internet can go outside the LAN
Ethernet
Line in
OR
Reset
Ethernet LAN
IP:192.168.0.100
Access Point
Ethernet
IP:192.168.0.102
Gateway Router
Switch
Ethernet
Reset
Reset
1
2
3
4
5
LAN
LAN IP:
192.168.0.1
104
WAN
WAN IP:
103.75.201.48
OR
3G/4G Modem
ADSL modem
3G/4G modem
• This is the main function of the router
3G/4G Gateway Router
Reset
LAN
LAN IP:
192.168.0.1
3G/4G modem
WAN IP:
103.75.201.48
Functions of the Router
Another customer's LAN
IP: 103.75.201.47
ISP’s WAN host
IP: 103.75.201.0
Another customer's LAN
IP: 103.75.201.50
WAN IP: 103.75.201.48
Ethernet LAN
Gateway Router
Access
Point
LAN IP: 192.168.0.1
Switch
IP:192.168.0.100
IP:192.168.0.101
IP:192.168.0.102
IP:192.168.0.105
Function 1: Connecting a LAN to WAN
• The router examines each data packet within the LAN
• If a packet is meant for the WAN, the router routs (sends) it outside the LAN
• Hence the router acts as a gateway
• Additional information are in [9, app. B]
Function 2: Network Address Translation (NAT)
The router has two different IP addresses; the WAN-side and LAN-side IP addresses
• NAT converts the WAN-side IP address to the LAN-side IP addresses
• Hence, the WAN only sees the router WAN side IP address rather than the individual IP’s
within the LAN
– That is, you are somehow protected behind the router
– Therefore, WAN-side IP address is called “public IP”
• Hence, within your LAN, you can have IP addresses identical to those within your neighbor’s LAN, without interference
184
More information
[www.diffen.com/difference/Router_vs_Switch]
105
Router
LAN
Switch
Ethernet
WAN
5
Function
Data transmitted
Address used for
transmission
NAT
Detailed function
4
3
2
1
Creates a new LAN and
connects it to a WAN
Packets
IP address
Expands an existing LAN
by adding more nodes
Frames
MAC address
Can Perform NAT
Routes (chooses the best
route) to send the data
outside the LAN to its
destination (according to
IP rules)
Cannot perform NAT
• Do You Need a Router for Simple Single-Computer Setups?
– www.howtogeek.com/183439/ask-htg-do-you-need-a-router-forsimple-single-computer-setups/
106
3.4.4
All-in-one SOHO Network Hardware
Summary of Networking HW
• Modem
• Access-Point/Wireless-bridge/Repeater
Ethernet
Line in
Ethernet
• Router
LAN
WAN
• Print/Scan Server
Ethernet
• Switch
Printer/Scanner
• NAS/File/Media Server
Ethernet
Ethernet
5
4
3
2
1
Storage
186
107
All-in-one SOHO Network Hardware
For Small Office/Home Office (SOHO) networks, two or more network devices are often combined into a single box, for example:
• Advanced access point = switch + access point
Advanced Access Point
Access
Point
Switch
LAN
4
3
2
1
• Basic wireless router = Gateway router + switch + access point + DHCP server + basic
management + basic firewall
Wireless router
Access
Point
3
Firewall
DHCP
Server
Gateway
Router
WAN
LAN
4
Switch
2
1
• Basic wireless ADSL modem = ADSL modem + Wireless router
Basic Wireless ADSL modem
Access
Point
Line In
LAN
4
3
2
1
108
Switch
Firewall
DHCP
Server
Gateway
Router
ADSL
Modem
• Advanced wireless ADSL modem = Wireless ADSL modem router + advanced management + advanced firewall + printer/scanner/NAS/file/download server/multimedia sever
Advanced wireless ADSL modem
4
3
Printer/scanner
/NAS/file
/multimedia Server
Line In
LAN
Access
Point
Switch
Firewall
DHCP
Server
Gateway ADSL
Router Modem
2 1/WAN
HDD
HDD
• 3G/4G wireless router = 3G/4G router + switch + access point
3G/4G wireless router
Access
point
Wifi
3G/4G
Router
3G/4G modem
3G/4G modem
Ethernet
Switch
• 3G/4G wireless modem = 3G/4G modem + access point
3G/4G wireless modem
Access
point
Router
3G/4G
Modem
Wifi
SIM card
Only one Internet source (ADSL modem, 3G/4G modem, 3G/4G router or none) can be used
109
• All in one internet box = advanced wireless ADSL modem + 3G/4G modem + 3G/4G
router∗
All in one Internet box
SIM card
USB share
Line In
LAN
4
3
2
Print/NAS/
file/multimedia
Server
1/WAN
Access
Point
Switch Firewall DHCP
Server
Gateway
Router
ADSL Modem
3G Modem
LAN cable
3G/4G modem
3G Router
HDD
HDD
• Wireless network printer = printer + switch +print server + wireless bridge
Wireless network printer
Printer
Print
Server
Wireless
Bridge
Switch
Wifi
• NAS storage = storage + NAS server + switch + wireless bridge
NAS storage
Storage
Wifi
NAS
Server
Wireless
Bridge
Switch
HDD
HDD
• File server = storage + File server + switch + wireless bridge
File server
Storage
Wifi
HDD
HDD
110
File
Server
Wireless
Bridge
Switch
• Media server = storage + media server + switch + wireless bridge
Media server
Storage
Wifi
Media
Server
Wireless
Bridge
Switch
HDD
HDD
• Smart TV = TV + media player + switch + wireless bridge + OS∗
Smart TV
TV
Media
Player
Wireless
Bridge
NAS 2
Switch
NAS 1
• TV box = media player + switch + wireless bridge + OS
TV
TV Box
Media
Player
Wireless
Bridge
NAS 2
Switch
NAS 1
187
Assignment
• Answer questions (3.12), (3.13) and (3.14)
188
3.4.5
Host Name Resolution
Computer-Name and Internet-Domain-Name
A PC/server within a LAN/Internet respectively can be called using its IP-address.
• Humans however prefer addresses in the form of words rather than numbers
• This is why PC’s-on-a-LAN and servers-on-the-Internet have names
• Host name resolution is the process of translating a computer-Name/Internet-DomainName to its corresponding IP address
– NetBIOS Name Service (NBNS) does this job within LAN’s†
– Domain Name System (DNS) resolution does this job on the Internet
189
∗
Such as Android or Windows 10
[https://superuser.com/questions/119318/host-name-resolution-on-a-home-network],
[https://wiki.wireshark.org/NetBIOS/NBNS]
†
111
Domain Name System Resolution∗
DNS resolution is the process of translating an Internet-domain-name to its corresponding IP
address.
• When you type the domain name of a website into a browser,
– the browser sends the domain name to a server called DNS
– the DNS server searches its database for the corresponding IP address, and returns
it to your browser
– the browser then connects to website using this IP
• You can find the IP corresponding to any domain name using the CLI shell command
ping www.google.com
• It is generally best to use the DNS server supplied by your ISP†
• Some commercial DNS services can also provide some added features
– For example, OpenDNS (www.opendns.com) can provide another layer of filtering
against spyware, identity theft, adult sites, and other possible problems
∗ To use OpenDNS family shield, use these DNS servers 208.67.220.123 and
208.67.222.123
NetBIOS Name Service (NBNS)
NBNS translates a NetBIOS computer-Name to its corresponding IP address within a LAN† .
• Windows Internet Name Service (WINS) is Microsoft’s implementation of NBNS‡
∗
Also known as DNS lookup
because this server is probably closer to you
‡
[https://en.wikipedia.org/wiki/Windows_Internet_Name_Service]
†
112
Assignment
• Answer question (3.15)
192
Root Name Servers∗†
• A combination of limits in the DNS and certain protocols resulted in a decision to limit
the number of root name servers to 13 logical servers, denoted with letters from A to M
– Ten servers were originally in the United States. Three servers were originally located in Stockholm (I), Amsterdam (K), and Tokyo (M)
– This does not mean there are only 13 physical root name servers; each operator uses
redundant computer equipment to provide reliable service even if failure of HW or
SW occurs
– As of 25 May 2023, the number of root server instances is 1,702
• The DNS Root Server System Advisory Committee is an ICANN committee
– However, the root zone is controlled by the United States Department of Commerce
who must approve all changes to the root zone file requested by ICANN
193
∗
†
[https://en.wikipedia.org/wiki/Root_name_server]
[www.root-servers.org/]
113
Excerpts from Public News
[www.bbc.com/arabic/world-57575736]
Assignment
• Answer questions (3.17) and (3.18)
114
3.4.6 The Whole Picture
115
196
Assignment
• Answer questions (3.19) to (3.22)
Section Preparation
• Well prepare yourself for laboratory 5.
116
3.5
Network Security
Cyber Attacks
Intruders break into your LAN for several reasons:
• Just to overcome the challenge of “cracking” protected files
• Steal confidential information
• They want to use your LAN to:
– obtain a high-speed Internet connection
– send unsavory or illegal data (spam, viruses, rootkits, offensive materials, . . . )
– download illegal data
– ...
• They want to interfere with normal network operation by overloading the network’s ability
to handle data, altering or deleting essential SW, or causing HW to break down
• An unprotected system with a lot of unused storage space can be an attractive target for
hackers who want to distribute pirated SW, music, or video files
– you didn’t think they store that stuff on their own computers, did you?
199
Network Security
The main objective of network security is to limit access only to authorized users, and reject
anyone else.
• Sample tools for maintaining a secure network include:
– different access levels for different users
– passwords
– firewalls
– more complex methods, such as:
∗ kernel-level mandatory access control systems
∗ authentication and authorization mechanisms
∗ data encryption
∗ ...
200
117
Most Common Passwords∗
Top 25 most common passwords by year according to SplashData
Rank
2011[6]
2012[7]
1
password
password
2
123456
3
12345678
4
2013[8]
2014[9]
2015[10]
2016[5]
2017[11]
2018[12]
2019[13]
123456
123456
123456
123456
123456
123456
123456
123456
password
password
password
password
password
password
123456789
12345678
12345678
12345
12345678
12345
12345678
123456789
qwerty
qwerty
abc123
qwerty
12345678
qwerty
12345678
qwerty
12345678
password
5
abc123
qwerty
abc123
qwerty
12345
football
12345
12345
1234567
6
monkey
monkey
123456789
123456789
123456789
qwerty
123456789
111111
12345678
7
1234567
letmein
111111
1234
football
1234567890
letmein
1234567
12345
8
letmein
dragon
1234567
baseball
1234
1234567
1234567
sunshine
iloveyou
9
trustno1
111111
iloveyou
dragon
1234567
princess
football
qwerty
111111
10
dragon
baseball
adobe123[a]
football
baseball
1234
iloveyou
iloveyou
123123
abc123
11
baseball
iloveyou
123123
1234567
welcome
login
admin
princess
12
111111
trustno1
admin
monkey
1234567890
welcome
welcome
admin
qwerty123
13
iloveyou
1234567
1234567890
letmein
abc123
solo
monkey
welcome
1q2w3e4r
14
master
sunshine
letmein
abc123
111111
abc123
login
666666
admin
15
sunshine
master
photoshop[a]
111111
1qaz2wsx
admin
abc123
abc123
qwertyuiop
16
ashley
123123
1234
mustang
dragon
121212
starwars
football
654321
17
bailey
welcome
monkey
access
master
flower
123123
123123
555555
18
passw0rd
shadow
shadow
shadow
monkey
passw0rd
dragon
monkey
lovely
19
shadow
ashley
sunshine
master
letmein
dragon
passw0rd
654321
7777777
20
123123
football
12345
michael
login
sunshine
master
!@#$%^&*
welcome
21
654321
jesus
password1
superman
princess
master
hello
charlie
888888
22
superman
michael
princess
696969
qwertyuiop
hottie
freedom
aa123456
princess
23
qazwsx
ninja
azerty
123123
solo
loveme
whatever
donald
dragon
24
michael
mustang
trustno1
batman
passw0rd
zaq1zaq1
qazwsx
password1
password1
25
Football
password1
000000
trustno1
starwars
password1
trustno1
qwerty123
123qwe
Additional Details
• Refer to [6, ch. 2]
3.5.1
The Firewall
The firewall is a software that uses a set of rules to inspect incoming data and block:
• data from a source that isn’t on the list
• files that match a particular description (such as viruses)
∗
[https://en.wikipedia.org/wiki/List_of_the_most_common_passwords]
118
LAN Firewall
Internet
Firewall
Ethernet
A network firewall isolates a LAN from the Internet
For SOHO LANs, a firewall is probably built-in inside the all in one gateway router.
204
Individual Computer Firewall
A firewall SW may also be installed on individual computer.
• Several good firewall products are available as shareware, and others are free to noncommercial users
– ZoneAlarm (www.zonealarm.com) and LANguard (www.languard.com) are both
well-regarded Windows firewall SW products
– There’s also a firewall built into Windows that is adequate for most home and small
business networks
• The number of idiots and creeps on the Internet is surprisingly large
– If your firewall notifies you when an outside computer tries to connect to your network, your firewall log will probably list several break-in attempts every day
205
More Information [1]
• Social Networking
• Keeping us safe
• The bad side of the Web
• Making money online
206
119
3.6
Cloud Computing
Servers
Software
Laptops
50
60
6 7 8
Desktops
70
40
5
4
3
2
1
0
80
90
30
100
20
F
E
110
10
0
120
12345
NE WS
Monitoring
Collaboration
Communication
Content
Finance
Platform
Identity
Runtime
Object Storage
Queue
Database
Infrastructure
Compute
Virtual Machine
Block Storage
Phones
Network
Tablets
Many HW, SW, services, resources, . . . nowadays are made available to you over the cloud
(typically the Internet).
• Typical examples are:
– Software as a Service (SaaS)
– Infrastructure as a Service (IaaS)
– Platform as a Service (PaaS)
– ...
• Two big cloud service providers are:
2. Microsoft Azure†
1. Amazon Web Services (AWS)∗
• Usually end users access cloud services through a web browser or a light weight app.
Local Services
MS Office, Libre Office, . . .
HDD
Outlook, Thunderbird, . . .
Windows, Mac OS, Ubuntu, . . .
git
Equivalent Cloud Services
MS Office 365, Google Docs, Zoho Office
Suite, . . .
OneDrive, Google Drive, DropBox, . . .
Gmail, Yahoo Mail, . . .
Chrome OS
github.com, bitbucket.com, . . .
∗
For a brief introduction, refer to www.youtube.com/watch?app=desktop&v=3XFODda6YXo and www.
youtube.com/watch?app=desktop&v=JIbIYCM48to.
†
For a brief introduction, refer to www.youtube.com/watch?app=desktop&v=3Arj5zlUPG4.
120
Privacy
3.7
Public News about Privacy
بعض األخبار المتعلقة بانتهاك الخصوصية
24-02-2020 1
10-08-2020 2
10-09-2014 3
12-09-2014 4
24-06-2019 5
06-07-2018 6
07-04-2018 7
31-03-2018 8
05-04-2018 9
06-04-2018 10
22-03-2018 11
25-03-2018 12
21-03-2018 13
30-01-2018 14
07-12-2017 15
18-01-2018 16
27-07-2020 17
ر
https://www.arageek.com/2012/08/29/7-surprising-terms-in-online-agrrements.html
االلكتونية ٧
رشوط ستتفاجأ بوجودها يف اتفاقية استخدام المواقع
ٌ
ٌ
https://www.arageek.com/2013/09/04/israili-companies-operating-in-the-arab-web-market.html
رشكات إشائيلية تنتحــل الهوية ( العالميــة ) لالنتشــار يف األسواق العــربية
ر
ر
اإللكتونية للتجارب https://www.bbc.com/arabic/scienceandtech/2014/09/140910_vert_fut_websites_hidden_tricks.shtml
اإلنتنت :كيف تخضعنا المواقع
ياهو تكشف تهديدات من الحكومة األمريكية لتسليم معلومات المستخدمي https://www.bbc.com/arabic/scienceandtech/2014/09/140912_yahoo_cia_fine.shtml
https://www.bbc.com/arabic/science-and-tech-48743845
هل تحمل "جاسوسا" يف جيبك يسجل كل تفاصيل حياتك؟
https://www.bbc.com/arabic/science-and-tech-44738817?SThisFB
ماذا يفعل موقع فيسبوك وغته من عمالقة التكنولوجيا ببياناتك؟
https://www.bbc.com/arabic/media-43683069
كيف يتم استخدام بيانات فيسبوك للتالعب بالناخبي؟
https://www.bbc.com/arabic/science-and-tech-43595632
تحديث جديد ألجهزة أيفون يكشف طريقة التعامل مع بياناتك الشخصية
فضيحة ر
https://www.bbc.com/arabic/science-and-tech-43650266
اختاق بيانات فيسبوك طالت 87مليون مستخدم وزوكربتج أمام الكونغرس األربعاء
موظفو غوغل "يرفضون" العمل ف ر
https://www.bbc.com/arabic/business-43658322
مشوع للبنتاغون
ي
https://www.bbc.com/arabic/interactivity-43505654
االجتماع بياناتنا الشخصية للتأثت يف آرائنا الفكرية وتوجهاتنا السياسية؟
هل تستخدم مواقع التواصل
ي
https://www.bbc.com/arabic/business-43528443
أشار أسوأ أسبوع يف تاري ــخ فيسبوك وخسارة 58مليار دوالر
https://www.bbc.com/arabic/media-43484857
االجتماع "تحرك دفة السياسة"
وسائل التواصل
ي
https://www.bbc.com/arabic/science-and-tech-42858480
ياض يكشف تحركات جنود داخل قواعد عسكرية
تطبيق ر ي
دليلك إىل "حياة رقمية" ال تكشف أشارك عىل ر
https://www.bbc.com/arabic/vert-fut-42259871
اإلنتنت
https://www.bbc.com/arabic/vert-cap-42741366
سيارات غوغل لتصوير الشوارع تكشف كثتا من أشار المجتمعات
https://www.bbc.com/arabic/world-53545088
صين موقع "لينكد إن" للتجسس؟
كيف استخدم عميل
ي
208
Excerpts from Public News
[www.bbc.com/arabic/vert-cap]42741366
121
[www.bbc.com/arabic/vert-fut42259871]
[www.bbc.com/arabic/media-43484857]
[www.bbc.com/arabic/science-andtech-42858480]
[www.bbc.com/arabic/business43528443]
122
[www.bbc.com/arabic/science-andtech-43650266]
[www.bbc.com/arabic/interactivity43505654]
[www.bbc.com/arabic/business43658322]
[www.bbc.com/arabic/science-andtech-43595632]
123
[www.bbc.com/arabic/science-andtech-48743845]
[www.bbc.com/arabic/media-43683069]
[www.bbc.com/arabic/science-andtech-63641900]
[www.bbc.com/arabic/science-andtech-44738817?SThisFB]
124
[www.bbc.com/arabic/tv-and-radio64667776]
[www.bbc.com/arabic/science-andtech-64799783]
• Seriously read and understand the following pages:
– www.bbc.co.uk/arabic/scienceandtech/2014/09/140912_yahoo_cia_
fine.shtml
– www.bbc.co.uk/arabic/scienceandtech/2014/09/140910_vert_fut_
websites_hidden_tricks.shtml
– www.google.com/trends/ and www.google.com/trends/topcharts
– www.arageek.com/2013/09/04/israili-companies-operating-in-thearab-web-market.html
– www.arageek.com/2012/08/29/7-surprising-terms-in-onlineagrrements.html
209
125
What do the Companies behind your Smart Phone Know about you?
Assignment
• Answer questions (3.23), (3.24) & (3.25)
Project idea 3 (Information Security and Privacy)
Make a serious study about information security and privacy and answer question 3.26.
126
3.8
Laboratory Work
3.8.1
Point-to-Point Connection
Static IP Configuration
The factory default IP address of network printers, access points, . . . is static∗ .
• To configure any of these peripherals, you have to connect them directly to your PC (pointto-point connection)
– In this case, there is no DHCP server that gives your PC its IP address
– Therefore, you have to manually configure the IP address of your PC
213
Establishing Point-to-Point Connection on a Windows PC†
To establish a point-to-point connection on a Windows PC, do the following:
1. Open Network and Sharing Center
4. Select Internet Protocol Version 4
(TCP/IPv4) and then, click on Properties.
2. Click Change adapter settings
3. Right-click on the Local Are Connection
icon and click on Properties
∗
†
Usually it is written on a sticker label on the bottom of the device.
[www.linksys.com/us/support-article?articleNum=132336]
127
• If the access point or network printer or the other PC IP is 192.168.1.1, configure the IP
address of the Windows PC as follows:
IP address
Gateway
Node 1
192.168.1.1
192.168.1.2
Node 2
192.168.1.2
192.168.1.1
Laboratory 5 (Point-to-Point Connection)
1. Connect two nodes using:
Point-to-point
• Wired LAN cables
– There is no DHCP server, hence you have to assign
both IP’s manually.
Hu
Sw
• Wifi
– Virtual access point (hotspot)∗
– Ad-hoc
Ad hoc
or
Wifi direct
†
– Wifi direct‡
• Measure File transfer rate
2. Configure an access point
PC
Access point
• As an example, you may try the emulator of the TL-WA801ND access point at
www.tp-link.com/resources/simulator/TL-WA801ND/index.htm
Wire
∗
Supported beginning from in Windows 8.
Not available anymore after Windows 7.
‡
Seems not implemented yet in Windows.
†
128
3.8.2
Sharing a Directory over Network
Server Message Block (SMB) and Samba
SMB is a protocol used by Windows networks mainly for sharing files, printers, serial ports, . . .
• SMB was also known as Common Internet File System (CIFS)
Samba is a free re-implementation (using reverse engineering) of the SMB protocol∗ .
• Samba runs on most Unix-like systems, such as Linux, Solaris, AIX, Mac OS X, . . .
216
Sharing a Directory on Windows 10
1. Ensure the network is private†
• For Wi-Fi connection
• For wired connection
2. Ensure the file discovery is enabled for private (current) connection
∗
†
[http://en.wikipedia.org/wiki/Samba_%28software%29]
https://tinkertry.com/how-to-change-windows-10-network-type-from-public-to-private
129
3. Create a new user account∗ for use in directory sharing.
• This account need not be administrator
• Ensure this account has a password†
• Submit the username and password of this account to other persons who will access
the shared directory
4. Open the “File Explorer” and right click the directory to be shared and select “Share
with>Specific people...”, and select the username you have just created for directory sharing, and specify the sharing permissions
∗
Otherwise, you can use your current account, but in this case you have to give the your username and password
to the persons who will access your shared directory.
†
Otherwise, Windows will refuse sharing.
130
5. Restart may be required
6. If you want to know which files/directories you have shared, type “\\localhost” into the
address bar of “File Explorer”
217
Troubleshooting
If sharing didn’t work, check the following:
1. Ensure the following services start automatically: ∗
• Function Discovery Provider Host
• Function Discovery Resource Publication
• SSDP Discovery
• UPnP Device Host
2. Ensure “File and Printer Sharing” is allowed through Windows firewall†
• Windows Security . Firewall & network protection . Allow app through firewall
. File and Printer Sharing . Private
∗
https://support.microsoft.com/en-us/help/4092694/windows-10-file-sharing-over-anetwork
†
[www.windowscentral.com/how-share-files-and-printers-without-homegroup-windows-10]
131
Sharing a Directory on Linux∗†
1. Create a new user account‡ for use in directory sharing.
• This account need not be administrator
2. Ensure correct permissions for the directory you want to share by the above user (visible,
writable, . . . )
3. Ensure the “samba” package is installed§
4. Install the “system-config-samba” package¶
• This creates shortcut called “Samba” in the program launcher
• Execute “Samba” launcher
∗
[www.howtogeek.com/176471/how-to-share-files-between-windows-and-linux/]
[https://help.ubuntu.com/community/How%20to%20Create%20a%20Network%20Share%
20Via%20Samba%20Via%20CLI%20%28Command-line%20interface/Linux%20Terminal%29%20%20Uncomplicated,%20Simple%20and%20Brief%20Way!]
‡
Otherwise, you can use your current username, but in this case you have to give the your username to the
persons who will access the shared directory.
§
This applies for debian based Linux distributions.
¶
This applies for debian based Linux distributions.
†
132
5. Execute “Preferences>Samba Users” and select the username you have just created for
directory sharing, and specify the Samba Password
6. Execute “File>Add Share” and select the directory to be shared and the permissions you
like and the users allowed to access the shared directory.
7. Restart the SMB service by executing the following shell commands
sudo service smbd restart
sudo service nmbd restart
8. Submit the username and samba password to other persons who will access the shared
directory.
9. Open the “File Explorer” and type the IP address of the host PC preceded by “//”
219
Accessing a Shared directory from a Windows Client
1. Connect to the same LAN of the PC with the shared directory∗
2. Ensure the network is private†
• For Wi-Fi connection
• For wired connection
∗
†
Either point-to-point and star connections are equally well.
https://tinkertry.com/how-to-change-windows-10-network-type-from-public-to-private
133
3. Ensure the file discovery is enabled for private (current) connection
4. Open the “File Explorer” and type the computer-name or IP-address of the host PC preceded by “\\”. For example:
• \\PCNAME\
• \\192.168.1.6\
5. Type the user name and password supplied by the host PC administrator
134
Accessing a Shared Directory from a Linux Client
1. Connect to the same LAN of the PC with the shared directory∗ .
2. Ensure the “cifs-utils” and “smbclient” packages are installed∗
3. Open the file explorer and type the computer-name or IP-address of the host PC preceded
by “smb://”. For example:
• smb://PCNAME/
• smb://192.168.1.6/
4. Type the user name and password supplied by the host PC administrator
221
∗
∗
Either point-to-point and star connections are equally well.
This applies for debian based Linux distributions.
135
Laboratory 6 (Sharing Files over a LAN)
1. Using either point-to-point or star, wired or Wifi networks, share files, Internet, . . .
and stream videos
• Test several OS’s, for example:
– Windows
– Linux
– Windows
Windows
Linux
Linux
• Monitor the data transfer rate
2. Configure a SOHO modem/router
All in one Internet box
Print/NAS/
file/multimedia
Server
Access
Point
Switch Firewall DHCP
Server
Gateway
Router
ADSL Modem
3G Modem
LAN cable
3G Router
HDD
• As an example, you may try the emulator of the TD-W8970 all-in-one
modem/router available at www.tp-link.com/eg/emulators.html?model=
TD-W8970
Online Networking HW Emulators
You can try the emulators of many Networking HW online. For example:
• TP-LINK emulators are available at www.tp-link.com/eg/emulators.html
• CISCO emulators are available at https://supportforums.cisco.com/community/
136
911/cisco-small-business-online-device-emulators
223
3.9
Project Ideas
Project idea 4 (Windows Cluster)
Create a Windows cluster.
• Test the cluster power using a parallel job
• You may use real PC’s or virtual machines
224
Project idea 5 (Linux Cluster)
Create a Linux cluster.
• Test the cluster power using a parallel job
• You may use real PC’s or rasberry-pi or beagle-bone, virtual machines, . . .
225
Project idea 6 (Rasperry-pi as a Networking Device)
Use Rasperry-pi to create any of:
1. smart TV box (HTPC, IPTV) (internet,
media player)
4. 3G router (wired and wireless)
2. wireless router
6. p2p client
3. wireless bridge
7. NAS
5. download cleint
• See “Rasperry Pi for Beginners” book by Imagine Publishing
226
Project idea 7 (VPN)
VPN over public WLAN’s.
227
137
3.10
Questions
3.1. Explain how to identify the speed of your wired or wireless network adapters
(a) Mention these speeds as well
3.2. How can you connect your desktop and wired-Ethernet-printer to a wireless network?
3.3. How can you connect a USB printer to a network?
3.4. What can your ISP know about you?
3.5. How can you monitor your current download/upload bit-rate on MS Windows?
3.6. Obtain the MAC address of your
(a) laptop Ethernet adapter
(b) laptop Wifi adapter
(c) smart phone
(d) ADSL router
(e) access point
3.7. Where/How can you obtain the following “Internet Protocol (TCP/IP) Properties” dialog
box?
Clearly mention your Windows version as well
3.8. Obtain the following information when your laptop is connected to your home network
and university network
(a) IP address
(b) DNS servers
3.9. For the following devices in your office LAN, which of them should have a fixed IP? which
should have a dynamic IP?
Organize your answer in a two columns table.
138
(a) business laptop
(b) business desktops
(c) guests’ tablets/smartphones/laptops
(d) printer
(e) access point
(f) file server
(g) media server
(h) media player
(i) data server
(j) router LAN side IP address
(k) router WAN side IP address
3.10. You have two access points and a network printer. The factory setting for all of them is
that they have fixed (static) IP of 192.168.1.1. Also your gateway router has the same LAN
side IP address. Explain how should you setup them in a LAN?
3.11. You have a LAN connected to a router. You want to create another LAN behind your
gateway router. Therefore, you connect another router behind the first router.
(a) Adjust the subnet mask and the LAN-side-DHCP-IP-range of the two routers
3.12. Look for combined networking HW similar to those of section 3.4.4. Mention the complete product descriptive name, model number and its price.
• Organize your answer as
Brand name
Tp-Link
Product descriptive name
5-Port 10/100Mbp switch
Model no.
TL-SF1005D
Price
49 EGP
• You may use www.amazon.eg and www.tp-link.com, or similar websites
3.13. How can you turn a wireless router into an access point?
Hint watch www.youtube.com/watch?v=Cg_gGECGLiY&t=614s
3.14. How can you turn a wireless ADSL modem into an access point?
3.15. Obtain the IP address of www.bbc.co.uk
(a) How can you use this IP address?
3.16. Try to visit Faculty of Engineering University website from your home Internet.
(a) Discuss any difficulty you may face
3.17. Explain what happens when you write a wrong address in your Internet browser, for example www.zmxmzm.com
3.18. Who owns and who controls the Internet?
You may find (http://walhaseb.com/archives/9949) helpful
3.19. How can you create a website on your local PC?
3.20. How can you transfer a file from one PC to another using a LAN cable?
(a) Measure the file transfer data rate
3.21. If you want to connect your PC directly to a network printer using a LAN cable (point to
point connection),
139
explain the necessary IP configurations
3.22. How can you transfer a file from one PC to another using Wifi?
(a) Measure the file transfer data rate
You may make use of this article www.arageek.com/2014/04/07/how-to-use-wifidirect.html
3.23. Print and study and the “terms of use” and “privacy statement” of one cloud service you
use (in Arabic)
3.24. How frequently do governments request information about individual Facebook accounts?
Check
https://transparency.fb.com/data/government-data-requests/
(translated to your language)
(a) Which requests were accepted?
Check
https://about.meta.com/actions/safety/audiences/law/
guidelines/ (translated to your language)
3.25. Compare accessing your email through
(a) browser
(b) email client using POP3 protocol
(c) email client using IMAP protocol
3.26. Make a survey on privacy, and try to answer the following questions:
(a) Cloud service providers spends billions of dollars serving you for free, why?
(b) How cloud service providers earn money?
You may find this (http://walhaseb.com/archives/5367) helpful
(c) Why Facebook bought WhatsApp with billions of dollars?
(d) Why Google bought YouTube with billions of dollars?
(e) Why Microsoft bought Skype with billions of dollars?
(f) What is the difference between Chrome and chromium?
Check
www.aljazeera.net/news/pages/d2ab5fc5-53b8-4a63-87325fafcbe6366d
(g) What do the companies behind your smart phone know about you?
e.g.: Apple for iPhone holders, Google for Android-phone holders and Microsoft for
Windows phone holders, . . .
(h) What happens if you log in to a service using your Facebook (or Google, . . . ) account?
(i) When you create your Facebook account, it rudely requests your email password,
why?
(j) Why Facebook always encourage you to upload/submit more and more information
(your photos, your mobile number, where do you live, where do you work, which
schools you attended, . . . )?
140
(k) Why Gmail wants to know your mobile phone number, why?
(l) Why YouTube demands your mobile phone number when you try to upload a long
video?
(m) Why Facebook excite you to tag faces in any photo they have?
228
141
This page is intentionally left blank!
142
Part 4
Scientific Computing and Visualization
using Matlab
4.1
Introduction
Matlab
Matlab stands for “Matrix laboratory”.
• Matlab can be thought of as a super–powerful graphical calculator
• In addition, Matlab is a programming language
• Matlab is an interpreted language; that is: [sec. 5.1.1]
– Commands are compiled line by line
– If there is a syntax error in the 10th line, Matlab will discover this error after executing the former 9 lines
229
Matlab Window
• The “command window” is a traditional CLI shell, very similar to Windows and Linux
CLI shells. That is:
– files are looked for in the “current folder” then in a pre–defined list of paths∗
∗
To edit this list, execute “Home>Set Path”.
143
– up/down arrows retrieves previously executed commands
– ...
• The “current folder” is the default folder for reading/writing/executing files.
Customization
• File>Preferences
– You may need to adjust the font size
– If you want to change the font, be advised to choose fixed–width–font
My Recommended Layout
It is a matter of taste, but I prefer to layout Matlab window as shown.
144
Getting Help
To read the documentation of a built–in function (“fzero” for example);
• execute either of the following commands:
>> help fzero
>> doc fzero
• or use the Help window
233
4.2
Basics
4.2.1
Data Types
Matlab is a weakly typed language.
• That is, no need to declare variables!
• Most often used data types are:
– 64–bit double (FP64) 3.141592653589793 (default data type)
sign
fraction
(52 bit)
exponent
(11 bit)
63
0
52
– char ’a’
– Boolean
∗ zero means false
∗ nonzero means true
• Other types are also supported. For example∗ :
– 32–bit single (FP32) 3.1415927
sign exponent (8 bits)
fraction (23 bits)
0 0 1 1 1 1 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
31 30
23 22
(bit index)
= 0.15625
0
– complex (single and double)
– integer (8–bit and 16–bit)
– string “Ahmed”
– ...
234
∗
Check: “Matlab . Language Fundamentals . Data Types” for the complete list.
145
Variables
To create a variable;
>> var=3.14
• Variable name
The first character must be a LETTER.
– after that, any combination of letters, numbers and “ ”, except for the space character
– Variable names are CASE SENSITIVE. That is, “var1” is different from “Var1”
• Built–in variables (Don’t use these names)
√
– i, 1i, j and 1j indicate −1
– pi has the value 3.1415926 . . .
– ans stores the last unassigned value (same as your calculator)
– Inf and indicate ∞
– NaN indicates “Not a Number”. E.g.: 00 , ∞
, 0.∞, . . .
∞
4.2.2
Operators
b
a |{z}
− |{z}
|{z}
operand operator operand
−
a
|{z}
|{z}
operand
unary
operator
Matlab operators fall into three categories:
1. Arithmetic operators perform numeric computations
• a+2
• -2*b
• c^5
Arithmetic Operator
:
+
+
.*
./
.\
.^
.’
*
/
\
^
’
Description
Colon operator
Unary plus
Unary minus
Addition
Subtraction
Element–wise Multiplication
Element–wise Right division
Element–wise Left division
Element–wise Power
Transpose
Matrix multiplication
Matrix right division
Matrix left division
Matrix power
Complex conjugate transpose
146
2. Relational operators compare operands quantitatively
Operator
<
<=
>
>=
==
~=
Description
Less than
Less than or equal to
Greater than
Greater than or equal to
Equal to
Not equal to
• Examples are:
– a==5 checks whether a = 5
– a<=3 checks whether a ≤ 3
– a~=5 checks whether a 6= 5
• These operators return true (1) or false (0)
3. Logical operators: “&”, “|” and “~”
Logical operators
And
Or
Not
Element wise
&
|
~
Short circuit (scalars)
&&
||
• Examples are:
– a>5 & a<=7 checks whether 5 < a ≤ 7
– ~(a>5 & a<=7) is equivalent to a<=5 | a>7
• These operators return true (1) or false (0)
• Short–Circuit logical operators: “&&” and “||”
– operate on scalar operands
– they evaluate their second operand only when the result is not fully determined
by the first operand
236
Arithmetic Operator Precedence∗
Precedence levels determine the order in which expressions are evaluated.
• Within the same precedence level, operators are evaluated from left to right
• The precedence order is shown below, ordered from highest to lowest
1. ()
4. Unary +, unary - & ~
2. .’, .^, ’ & ^
5. .*, ./, .\, *, / & \
3. .^-, .^+, .^~, ^-, ^+, ^~
6. + & -
∗
[www.mathworks.com/help/matlab/matlab_prog/operator-precedence.html]
147
7. :
10. |
8. <, <=, >, >=, == & ~=
11. &&
9. &
12. ||
Overriding Default Precedence
The default precedence can be overridden using parentheses.
>> a=3;
>> b=2;
>> c=a./b.^2
c =
0.7500
>> c=(a./b).^2
c =
2.2500
>>
Assignment
• Implement problem (4.1)
4.2.3
Arrays
Scalars
• A scalar variable can be given a value explicitly
>> a=10
a =
10
>>
• or calculated from existing variables
>> c=1.3*45-2*a
c =
38.5
>>
• To suppress the output, append the line with “;”
>> a=20;
>>
148
Displaying/Storing Data
Both HDD data transfer speed and monitor display frequency are much slower than the CPU and
RAM. Hence:
• storing data to the HDD can considerably slow your program speed
• displaying data to the screen can also considerably slow your program speed
Arrays
Matlab arrays can be either:
same–type arrays
• numbers
cell arrays
array of elements of different data types
• characters
• strings
• classes
• ...
242
Vectors (1D Array)
Row vector: comma or space separated values between brackets []
>> row1=[1 2 5.4 -6.6]
>> row2=[1,2,5.4,-6.6]
Column vector: semicolon separated values between brackets
>> column=[4;2;7;4]
243
149
Character Vectors
To construct character row vectors, use single quotes ’’
>> char vec=’Hello, I am Ahmed’
char vec =
Hello, I am Ahmed
Matrices (2D Arrays)
Matrices are created similar to vectors.
>> mat1=[1 2;3 4]
mat1 =
1
2
3
4
>> a row=[1 2];
>> b row=[3 4];
>> c col=[5;6];
>> d mat=[a row;b row];
>> e mat=[d mat c col];
>> f mat=[[e mat e mat];[a row b row a row]];
Array Size
>> size(a row)
ans =
1
2
>> size(c col)
ans =
2
1
>> size(e mat)
ans =
2
3
>> size(a row,1)
ans =
1
>> size(a row,2)
ans =
2
>> size(c col,1)
ans =
2
>> size(c col,2)
ans =
1
>> size(e mat,1)
ans =
2
>> size(e mat,2)
ans =
3
150
>> length(a row)
ans =
2
>> length(c col)
ans =
2
>> length(e mat)
ans =
3
>> numel(e mat)
ans =
6
246
Character Arrays
>> char vec1=’Hello, I am ’
char vec1 =
’Hello, I am ’
>> size(char vec1)
ans =
1
12
>> length(char vec1)
ans =
12
>> char vec2=’Ahmed’
char vec2 =
’Ahmed’
>> length(char vec2)
ans =
5
>> [char vec1,char vec2]
ans =
’Hello, I am Ahmed’
>> [char vec2;’Mohamed’]
Error using vertcat
Dimensions of arrays being concatenated
are not consistent.
247
The String Data Type
The string data type was introduced in Matlab R2016b.
• To construct a string, use double quotes ""
>> str1="Hello, I am "
str1 =
"Hello, I am "
>> size(str1)
ans =
1
1
>> length(str1)
ans =
1
>> strlength(str1)
ans =
12
>> str2="Ahmed"
str2 =
"Ahmed"
>> strlength(str2)
ans =
5
>> str row=[str1,str2]
str row =
1x2 string array
"Hello, I am "
"Ahmed"
>> size(str row)
ans =
1
2
>> strlength(str row)
ans =
12
5
>> str3=str1+str2
str3 =
"Hello, I am Ahmed"
>> size(str3)
ans =
1
1
>> strlength(str3)
ans =
17
>> str col=[str2;"Mohamed"]
str col =
2x1 string array
"Ahmed"
"Mohamed"
>> size(str col)
ans =
2
1
>> strlength(str col)
ans =
5
7
• As of Matlab R2018b, functions that accepts character arrays (and cell arrays of character
vectors) also accepts string arrays
151
• For more information, refer to:
– www.mathworks.com/help/matlab/matlab_prog/represent-text-withcharacter-and-string-arrays.html
– www.mathworks.com/help/matlab/matlab_prog/create-stringarrays.html
Cell Arrays
A cell array can contain different data types.
• To construct cell array, use curly braces {}
>> a cmat={’hello world’,[1 5 6 2];rand(3,2),’Ahmed’}
a cmat =
2x2 cell array
{’hello world’}
{[1 5 6 2]}
{3x2 double
}
{’Ahmed’ }
Array Initialization
• To initialize a numeric array;
>> o row=ones(1,5)
o row =
1
1
1
1
1
>> val row=3*ones(1,5)
val row =
3
3
3
3
3
>> val row=repelem(3,1,5)
val row =
3
3
3
3
3
>> z row=zeros(1,5)
z row =
0
0
0
0
>> n row=nan(1,5)
n row =
NaN
NaN
NaN
NaN
NaN
>> r row=rand(1,5)
r row =
0.81472
0.90579
0.12699
0
0.91338
• To initialize a linear vector of numbers;
>> a row=linspace(0,7,5)
a row =
0
1.75
3.5
>> b row=0:2:10
b row =
0
2
4
6
>> c row=1:5
c row =
1
2
3
4
5.25
8
7
10
5
152
0.63236
• To initialize a string array;
>> str row=strings(1,3)
str row =
1x3 string array
""
""
""
>> str1 row=repelem("Ahmed",1,3)
str1 row =
1x3 string array
"Ahmed"
"Ahmed"
"Ahmed"
• To initialize a cell array;
>> a crow=cell(1,3)
a crow =
1x3 cell array
{0x0 double}
{0x0 double}
{0x0 double}
>> b crow=repelem({1:3},1,3)
b crow =
1x3 cell array
{[1 2 3]}
{[1 2 3]}
{[1 2 3]}
• To initialize an array of graphics objects [sec. 4.6]
>> gObjects arr=gobjects(1,3)
ans =
1x3 GraphicsPlaceholder array:
GraphicsPlaceholder
GraphicsPlaceholder
GraphicsPlaceholder
250
4.2.4
Saving, Clearing and Re–loading Variables
• save command saves variables to a file, e.g.:
– To save all variables to myFile.mat
>> save myFile
∗ By default, the file is saved in the current folder
– To save the a and b variables only
>> save myFile a b
– To save to another folder, explicitly specify the path
>> save C:\MyFolder\myFile a b
• clearvars command removes variables from Matlab’s memory, e.g.:
>> clearvars a b
This clears variables a and b from the memory. They disappear from the workspace.
>> clearvars
This clears all variables from the memory. All the variables disappear from the workspace.
153
• load command loads variables from a file into Matlab’s memory
– To load a file in the current folder
>> load myFile
– To load a file in another folder, explicitly specify the path
>> load C:\MyFolder\myFile
The a and b variables appear again in the workspace.
mat Files
mat files are binary files.
• Binary files store numbers as binary bits
sign exponent (8 bits)
fraction (23 bits)
0 0 1 1 1 1 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
31 30
23 22
(bit index)
= 0.15625
0
– Numbers are stored with full accuracy
– Files cannot be opened using a text editor∗
• ASCII text files† stores numbers as ASCII characters
– Files have larger size as compared to binary files
– Files can be opened using a text editor
Old Codes Compatibility
In old versions of Matlab, the “clear all” command was used to clear all the variables.
• In recent versions however, “clear all” job has changed
• Therefore in old Matlab codes, consider replacing the “clear all” command with
“clearvars”
Clearing the Command Window
>> clc
Laboratory
• Implement laboratory 7 on page 229
∗
†
Notepad for example
[sec. 2.5.2]
154
4.3
Array Arithmetic
Matlab arithmetic operators are element–wise operators. That is:
• operands sizes must be identical or compatible
• operator applies to the individual elements of the operands
256
Addition and Subtraction
>> rng(0)
>> mat1=rand(2,3);
>> mat2=rand(3,2);
>> mat3=ones(2,3);
>> mat1+mat3
ans =
1.8147
1.127
1.9058
1.9134
>> mat1+mat2
Error using +
Matrix dimensions must agree.
>> mat1+transpose(mat2)
ans =
1.0932
0.67387
1.8707
1.071
1.6324
1.0975
1.5899
1.0681
257
Array Multiplication, Division & Exponentiation
Array arithmetic operations are the same as matrix arithmetic [sec. 4.3.1] operations except for
multiplication, division and exponentiation.
• Therefore, array operators for multiplication, division and exponentiation are preceded
with “.” as “.*”, “./”, “.\” and “.^” to distinguish them from matrix operations
Examples
h
1 2 3
i
.∗
h
4 2
i
= Error
4\4
4
4
2 .\ 7 = 2\7
3
1\3
1
4
4
4∗4
2 . ∗ 7 = 2 ∗ 7
1∗3
1
3
4
4
4/4
2 ./ 7 = 2/7
1
3
1/3
4
4
4ˆ4
2 .ˆ 7 = 2ˆ7
1
3
1ˆ3
258
Compatible Array Sizes∗
Two arrays have compatible sizes if, for every dimension, their dimension sizes are either the
same or one of them is 1.
• Starting from R2016b, if the two operands have compatible sizes, Matlab expands both
operands to the same compatible size before applying the operand
∗
[www.mathworks.com/help/matlab/matlab_prog/compatible-array-sizes-for-basicoperations.html]
155
>> mat1+2
%mat1=rand(2,3)
ans =
2.8147
2.127
2.9058
2.9134
>> 5+mat2
%mat2=rand(3,2)
ans =
5.2785
5.9649
5.5469
5.1576
5.9575
5.9706
2.6324
2.0975
>> col1=(1:3).’
col1 =
1
2
3
>> mat2+col1
%mat2=rand(3,2)
ans =
1.2785
1.9649
2.5469
2.1576
3.9575
3.9706
>> col1+mat2
ans =
1.2785
1.9649
2.5469
2.1576
3.9575
3.9706
>> col1+mat1
%mat1=rand(2,3)
Matrix dimensions must agree.
>> row1=4:6
row1 =
4
5
>> col1+row1
ans =
5
6
6
7
7
8
>> row1+col1
ans =
5
6
6
7
7
8
6
%col1=(1:3).’
7
8
9
156
7
8
9
>> pages1=ones(1,3,3)
pages1(:,:,1) =
1
1
1
pages1(:,:,2) =
1
1
1
pages1(:,:,3) =
1
1
1
>> pages1+mat1
ans(:,:,1) =
1.8147
1.9058
ans(:,:,2) =
1.8147
1.9058
ans(:,:,3) =
1.8147
1.9058
%mat1=rand(2,3)
1.127
1.9134
1.6324
1.0975
1.127
1.9134
1.6324
1.0975
1.127
1.9134
1.6324
1.0975
259
Transpose
The transpose operator turns columns into rows and vice versa.
• The “’” operator gives the Hermitian–transpose, i.e. it transposes and conjugates the array
• For arrays of real numbers “.’” and “’” yield the same result
>> a mat=[1 2; 3 4+i]
a mat =
1.0000
2.0000
3.0000
4.0000 + 1.0000i
>> transpose(a mat)
ans =
1.0000
3.0000
2.0000
4.0000 + 1.0000i
>> a mat’
ans =
1.0000
2.0000
>> a mat.’
ans =
1.0000
2.0000
3.0000
4.0000 - 1.0000i
3.0000
4.0000 + 1.0000i
260
Functions and Arrays
Almost all Matlab functions work on scalars as well as arrays.
>> t vec=[1 2 3]
t vec =
1
2
3
>> f vec=exp(t vec)
f vec =
2.7183
7.3891
20.086
261
157
4.3.1
Matrix Arithmetic
Matrix arithmetic operations are the same as array arithmetic operations except for multiplication, division and exponentiation.
• Matrix operators for multiplication, division and exponentiation are “*”, “/”, “\” and “^”
Matrix Multiplication, Division & Exponentiation
• For matrix multiplication, inner dimensions must match; unless one operand is a scalar
• For matrix exponentiation;
– the exponent must be a scalar
– the matrix must be square
• For matrix left or right division;
– division is the same as multiplying by the inverse of the divisor matrix
– the divisor matrix must be square
– inner dimensions must match; unless one operand is a scalar
"
"
#
4
11
1 2 3
=
∗ 2
32
4 5 6
1
2×1
2×3
"
# 3×1 "
#
1 2 3
2 4 6
∗2=
4 5 6
8 10 12
2×3
"
#
"
# " 2×3 #
1 2
1 2
1 2
ˆ2 =
∗
3 4
3 4
3 4
#
1 1
2 2
3 3
"
/
1 2
2 1
3×2
#
"
#−1
1 1
1 2
= 2 2
∗
2 1
3 3
2×2
2×2
3×2
0.33333 0.33333
= 0.66667 0.66667
1
1
3×2
"
1 2
2 1
#
"
2×2
\
1 1 1
2 2 2
#
"
=
2×3
"
=
158
1 2
2 1
#−1
2×2
1 1 1
0 0 0
"
∗
#
2×3
1 1 1
2 2 2
#
2×3
Assignment
• Implement problems (4.5) to (4.6)
4.4
Accessing Arrays
Matlab arrays can be accessed using either index or subscripts.
• For example, if a mat is a 3×3 array, you can access its elements using either:
Index
as if the array is a column vector
a mat(1)
a mat(2)
a mat(3)
a mat(4)
a mat(5)
a mat(6)
Subscripts
(row,column)
a mat(1,1)
a mat(2,1)
a mat(3,1)
a mat(7)
a mat(8)
a mat(9)
a mat(1,2)
a mat(2,2)
a mat(3,2)
a mat(1,3)
a mat(2,3)
a mat(3,3)
• Matlab indexing starts at 1∗
• Check the ind2sub and sub2ind built–in Matlab functions
265
Vector Index
The index can be a vector.
∗
>> a row=1:4
a row =
1
2
3
4
>> b col=(10:10:40).’
b col =
10
20
30
40
>> a row(2:4)
ans =
2
3
4
>> b col(1:end-1)
ans =
10
20
30
>> a row([3,4,1])
ans =
3
4
1
>> b col([3,4,1])
ans =
30
40
10
>> A mat=round(10*rand(4))
A mat =
3
1
6
5
7
5
2
7
7
10
8
9
2
3
3
10
>> A mat(1:7)
ans =
Columns 1 through 4
3
7
7
Columns 5 through 7
1
5
10
>> A mat((1:7).’)
ans =
same as Fortran. On thew other hand, C/C++ indexing starts at 0.
159
2
>> A mat(:)
ans =
3
7
7
2
1
5
10
3
6
2
8
3
5
7
9
10
3
7
7
2
1
5
10
Vector Subscripts
Also subscripts can be vectors.
>> A mat
A mat =
3
1
6
5
7
5
2
7
7
10
8
9
2
3
3
10
>> A mat(1:3,1:2)
ans =
3
1
7
5
7
10
>> A mat([1 4 3],[1 4])
ans =
3
5
2
10
7
9
>> A mat(1,:)
ans =
3
1
6
>> A mat(1:3,:)
ans =
3
1
6
7
5
2
7
10
8
>> A mat([1,3,2],:)
ans =
3
1
6
7
10
8
7
5
2
>> A mat(:,2)
ans =
1
5
10
3
>> A mat(:,2:end)
ans =
1
6
5
5
2
7
10
8
9
3
3
10
>> A mat(:,[4,1,3])
ans =
5
3
6
7
7
2
9
10
7
2
5
5
7
9
5
9
7
8
3
>> A mat(2,:)=[3,6,3,7]
A mat =
3
1
6
5
3
6
3
7
7
10
8
9
2
3
3
10
>> A mat(:,3)=[4;5;7;4]
A mat =
3
1
4
5
3
6
5
7
7
10
7
9
2
3
4
10
160
267
For vectors, index is more handy than subscript;
>> a row(1,2)*b col(2,1)
ans =
40
>> a row(2)*b col(2)
ans =
40
268
Logical Indexing
>> A mat=round(10*rand(3))
A mat =
5
3
8
1
8
2
1
3
9
Example 1. Create an array C mat so that
(
0
Ci,j =
Ai,j
, : Ai,j < 5
otherwise
• Solution 1 Vector index
>> C mat=A mat;
>> mask=A mat<5
mask =
3x3 logical array
0
1
0
1
0
1
1
1
0
>> ind=find(mask)
ind =
2
3
4
6
8
>> C mat(ind)=0
C mat =
5
0
8
0
8
0
0
0
9
• Solution 2 Logical indexing; just for demonstration
>> C mat=A mat;
>> mask=A mat<5
mask =
3x3 logical array
0
1
0
1
0
1
1
1
0
>> C mat(mask)=0
C mat =
5
0
8
0
8
0
0
0
9
• Solution 3 Logical indexing
>> C mat=A mat;
>> C mat(A mat<5)=0
C mat =
5
0
8
0
8
0
0
0
9
269
161
Accessing Cell Arrays
• Use parentheses () to retrieve the cells of a cell array
>> a cmat={’hello world’,’hello Cairo’,[1 5 6 2];rand(3,2),’Ahmed’,1:3}
a cmat =
2x3 cell array
{’hello world’}
{’hello Cairo’}
{1x4 double}
{3x2 double
}
{’Ahmed’
}
{1x3 double}
>> a cmat(1,1)
ans =
1x1 cell array
{’hello world’}
>> a cmat(1:2,1:2)
ans =
2x2 cell array
{’hello world’}
{’hello Cairo’}
{3x2 double
}
{’Ahmed’
}
>> a cmat(1:2,1:2)={’hello Giza’,1:3;’Noor’,[4;5;6]}
a cmat =
2x3 cell array
{’hello Giza’}
{1x3 double}
{1x4 double}
{’Noor’
}
{3x1 double}
{1x3 double}
• Use curly braces {} to access the contents within cells
>> a cmat{1,1}
ans =
’hello Giza’
>> a cmat{1,1}=5:10
a cmat =
2x3 cell array
{1x6 double}
{1x3 double}
{1x4 double}
{’Noor’
}
{3x1 double}
{1x3 double}
>> a cmat{1,2}
ans =
1
2
3
>> a cmat{1,2}=’hello Qena’
a cmat =
2x3 cell array
{1x6 double}
{’hello Qena’}
{1x4 double}
{’Noor’
}
{3x1 double }
{1x3 double}
>> a cmat{1:2,1:2}
%This creates comma-separated list.
%This is the same as typing a cmat{1,1},a cmat{2,1},a cmat{1,2},a cmat{2,2}
ans =
5
6
7
8
9
10
ans =
’Noor’
ans =
’hello Qena’
ans =
4
5
6
%Assigning Output from a Comma-Separated List
>> [var1,var2,var3,var4]=a cmat{1:2,1:2}
var1 =
162
5
6
7
var2 =
’Noor’
var3 =
’hello Qena’
var4 =
4
5
6
8
9
10
270
4.4.1
The Comma–Separated List
The comma–separated list can be used in five situations:
1. to combine multiple statements in one line; a=5,b=7,c=2,d=9
2. inside [ ] to create an array; [a,b,c,d]
3. inside { } to create a cell array; {a,b,c,d}
4. inside ( ) for indexing and function input arguments; a mat(1,2)=func(a,b)
5. inside [ ] for assigning function output arguments; [v,d]=eig(a)
271
163
4.5
Programming
4.5.1
Flow Control
case Statement (Draft)
switch variable
case value1
...
statements1
...
case value2
...
statements2
...
end
switch variable
case value1
...
statements1
...
case value2
...
statements2
...
otherwise
...
statements3
...
end
• variable1 must be a scalar or character vector (string)
• value1, value2, . . . must be a scalar, string, or a cell array of scalars or strings
• case statement tests for equality solely
– For other tests∗ , use if statement
if Statement
if cond1
...
statements
...
end
∗
if cond1
...
statements1
...
else
...
statements2
...
end
>, <, >=, <=
164
if cond1
...
statements1
...
elseif cond2
...
statements2
...
else
...
statements3
...
end
for Loop
for n=1:100
...
statements
...
end
for n=[1,9,4,3]
...
statements
...
end
• for loop is used for known number of iterations
• The loop variable “n”
– is defined as a row vector∗
– is a scalar† within the loop
– need not have consecutive values
274
while Loop
while cond1
...
statements
...
end
• while loop is used for unknown number of iterations, as long as “cond1” is true
• Take care of infinite loops!
275
Controlling Loops
• break terminates execution of for or while loop
• continue skips the current iteration and passes control to next iteration of for or
while loop
276
Useful Logical Functions
>> a row=[0.53 0.67 0.01 0.38 0.07 0.42 0.69];
>> a row<0.5
ans =
0
0
1
1
1
1
0
∗
†
In fact, it can be defined as a multi–row array. Refer to the documentation for details.
If it is defined a multi–row array, loop variable “n” is a column of the array
165
>> all(a row<0.5)
ans =
0
>> all(a row<1)
ans =
1
4.5.2
>> any(a row<0.5)
ans =
1
>> any(a row>1)
ans =
0
Scripts
You can execute Matlab commands using either the:
• command window
– Interactive
– Code is lost after closing Matlab
• .m text file (script file)
– By saving the file, the code is not lost after closing Matlab
– Matlab editor∗ is designed for editing Matlab codes
.m file naming rules
Same as variable names;
• first character must be a LETTER
• after that, any combination of letters, numbers and “ ”, except for the space character
Warning
All the variables created by a script remain alive after the script finishes running.
• You can check them in the workspace window
• Old variables usually cause confusion after modifying and re–running the script
• This is why it is preferable to start your script with the command clearvars
∗
Any other text editor (such as notepad) can edit .m files as well.
166
The Matlab Editor
.m file path
* means that it's not saved
Debugging tools
Line
numbers
}
function declaration
Help of the m file
Real-time
variable watch
Click to set
a breakpoint
Real-time
error check
Comment
279
Comments
Anything following a “%” is considered a comment.
• Thoroughly comment your code to avoid wasting time later
• For a code file, it is a customary habit to write the file documentation at the beginning as
contiguous lines of comments
280
Running a script file
There are two ways to run an .m file;
1. type the .m file name in the command window and press “Enter”
• If Matlab does not know where is the .m file, an error message appears
• Remember that Matlab is CASE SENSITIVE; i.e. file1 is different from File1
2. open the .m file in Matlab editor and click “Run” toolbar button, or equivalently press “F5”
• The following message may appear
281
167
Path to .m Files
You can save your .m files anywhere in your disk, but you must inform Matlab where are your
.m files.
• To do so, execute “Home>Set Path” to add the .m file path to the list of Matlab paths
• Alternatively, this can be automatically done by opening the .m file in Matlab’s editor and
executing “Debug>Run” or press “F5”
– If the .m file was not already in the list of Matlab paths, the following dialog box is
displayed. You can either choose the:
– “Change Folder” to set the .m file path as the “current directory”, but this is not
recommended
– “Add to Path” to add the .m file to Matlab path
Laboratories
• Implement Laboratories 8 and 9 on page 229
4.5.3
Functions
A functions look exactly like script, except for:
• the function must have a declaration
• the function .m file should be named same as the function name
Inputs must be specified
function [x, y, z] = funName(in1, in2)
Function name should
match MATLAB file
name
Must have the reserved
word: function
If more than one output,
must be in brackets
Function vs Script
168
Function
Script
• Can have several inputs and outputs
• No explicit input nor output
• Variables (other than outputs) are
cleared after the function runs
• Variables remain alive after the script
runs
285
Advantages of Matlab Functions
Matlab has enormous built–in functions. Most of them are:
• open source. For example, execute the following command
>> open fzero
• element–wise
• receive/return variable number of inputs/outputs
>> A 3D=zeros(2,4,8); %3D array
>> D=size(A 3D)
D =
2
4
8
>> [m,n]=size(A 3D)
m =
2
n =
32
>> [m,n,p]=size(A 3D)
m =
2
n =
4
p =
8
>> n=size(A 3D,2)
n =
4
286
Error Checking/Reporting
Use these built–in functions:
• error
• warning
287
Laboratory
• Implement Laboratory 10 on page 229
288
4.5.3.1
Advanced Topics
Functions with Variable Number of Inputs/Outputs
Refer to:
• www.mathworks.com/help/matlab/matlab_prog/support-variable-numberof-inputs.html
• www.mathworks.com/help/matlab/matlab_prog/support-variable-numberof-outputs.html
289
169
Output from Matlab Functions
Matlab passes function input arguments by value∗ . That is, Matlab functions:
• cannot modify the values of input arguments
• can only modify the values of output arguments
Code 4.1: function myFunc
function out=myFunc(x)
out=x^2;
x=x+1;
end
>> a=5;
>> b=myFunc(a)
b =
25
>> a
a =
5
Function Argument Validation
• Refer to www.mathworks.com/help/matlab/matlab_prog/function-argumentvalidation-1.html
4.5.3.2
Types of Functions
• Local functions in a File
• Private functions in a subfolder
• Nested functions in a File
• Anonymous functions without a file
Anonymous Functions†
An anonymous function is a function that is not stored in a program file, but is associated with
a variable whose data type is “function handle”.
>> myfunction = @(x,y) (x^2 + y^2 + x*y);
>> x = 1;
>> y = 10;
>> z = myfunction(x,y)
z =
111
• Anonymous functions can:
– accept multiple inputs and return one output
– contain only a single executable statement
Function Handle‡
Function handles can store not only an anonymous function, but also variables that the expression
requires for evaluation.
∗
[www.mathworks.com/matlabcentral/answers/96960-does-matlab-pass-parameters-usingcall-by-value-or-call-by-reference]
†
[www.mathworks.com/help/matlab/matlab_prog/anonymous-functions.html]
‡
[www.mathworks.com/help/matlab/matlab_prog/anonymous-functions.html]
170
>> a = 1.3;
>> b = .2;
>> c = 30;
>> parabola = @(x) (a*x.^2 + b*x + c);
>> clear a b c
>> y = parabola(1)
y =
31.5000
• Multiple function handles can be stored is a cell array as:
>> f = {@(x) (x.^2);
@(y) (y + 10);
@(x,y) (x.^2 + y + 10)};
>> x = 1;
>> y = 10;
>> f{1}(x)
ans =
1
>> f{2}(y)
ans =
20
>> f{3}(x,y)
ans =
21
294
171
4.5.4
Applications
4.5.4.1
Calculating Sine by Taylor Series
Example 2. Create Matlab function to calculate the sine function using its Taylor series expansion near x = 0 (i.e.: Maclaurin series).
sin(x) =
∞
X
(−1)n 2n+1
x
(2n
+
1)!
n=0
≈
N
X
(−1)n 2n+1
x
(2n
+
1)!
n=0
172
Code 4.2: function ourSine1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
function result=ourSine1(x)
%This function computes sin(x) using Taylor series expansion around x=0, i.e.
Maclaurin series.
%
%This function uses poor algorithm for calculating sin(x). It is for demonstration
purposes only
N=84; %This is the maximum value for which factorial(2*N+1) can be calculated using
the double precision data type
%This value gives error of order:
% 2.242e-16 for x within [-pi,pi]
% 4.151e-5 for x within 9*[-pi,pi]
if abs(x) > 9*pi
error(’This function is accurate only for x values around zero.’)
elseif abs(x) > pi
warning(’This function is accurate only for x values around zero.’)
end
result=0;
for n=0:N
result=result+(-1)^n/factorial(2*n+1)*x^(2*n+1);
end
Code 4.3: function ourSine2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
function result=ourSine2(x)
%This function computes sin(x) using Taylor series expansion around x=0, i.e.
Maclaurin series.
%
%This function uses poor algorithm for calculating sin(x). It is for demonstration
purposes only
if abs(x) > 9*pi
error(’This function is accurate only for x values around zero.’)
elseif abs(x) > pi
warning(’This function is accurate only for x values around zero.’)
end
Conv_prec=10*eps;
result=0;
newTerm=inf;
n=0;
while abs(newTerm) > Conv_prec
newTerm=(-1)^n/factorial(2*n+1)*x^(2*n+1);
result=result+newTerm;
n=n+1;
end
Code 4.4: function ourSine3
1
2
function result=ourSine3(x)
%This function computes sin(x) using Taylor series expansion around x=0, i.e.
Maclaurin series.
173
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
%
%This function uses poor algorithm for calculating sin(x). It is for demonstration
purposes only
N=84; %This is the maximum value for which factorial(2*N+1) can be calculated using
the double precision data type
%This value gives error of order:
% 2.242e-16 for x within [-pi,pi]
% 4.151e-5 for x within 9*[-pi,pi]
if abs(x) > 9*pi
error(’This function is accurate only for x values around zero.’)
elseif abs(x) > pi
warning(’This function is accurate only for x values around zero.’)
end
Conv_prec=10*eps;
result=0;
newTerm=inf;
n=0;
while (abs(newTerm) > Conv_prec) && (n<=N)
newTerm=(-1)^n/factorial(2*n+1)*x^(2*n+1);
result=result+newTerm;
n=n+1;
end
if n>N
warning(’result may be inaccurate!’)
end
Code 4.5: function ourSine4
1
2
3
4
5
6
7
8
9
10
11
12
13
function result=ourSine4(x_vec)
%This function computes sin(x) using Taylor series expansion around x=0, i.e.
Maclaurin series.
%
%This function uses poor algorithm for calculating sin(x). It is for demonstration
purposes only
x_vec=mod(x_vec+pi,2*pi)-pi; %Since sine is periodic, this calculates the value within
[-pi,pi] that has the same sine as x
N=14; %gives error of order 4.694e-16 for any x within [-pi,pi]
result=0;
for n=0:N
result=result+(-1)^n/factorial(2*n+1)*x_vec.^(2*n+1);
end
174
Running the Main Script
>>Sine MainScript
Warning: This function is accurate
only for x values around zero.
> In ourSine at 12
In Sine MainScript at 4
error1 =
-4.1507e-05
Warning: This function is accurate
only for x values around zero.
> In ourSine1 at 12
In Sine MainScript at 5
error2 =
-4.1507e-05
Warning: This function is accurate
only for x values around zero.
> In ourSine2 at 12
In Sine MainScript at 6
error3 =
-4.1507e-05
error4 =
1.4491e-15
Elapsed time is 0.000165 seconds.
Elapsed time is 0.906409 seconds.
Elapsed time is 0.450197 seconds.
Elapsed time is 0.450985 seconds.
Elapsed time is 0.096219 seconds.
Code 4.6: Sine MainScript
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
clc
x=9*pi;
error1=sin(x)-ourSine1(x)
error2=sin(x)-ourSine2(x)
error3=sin(x)-ourSine3(x)
error4=sin(x)-ourSine4(x)
w=warning(’off’,’all’);
ii_max=1000;
tic
for ii=1:ii_max
sin(x);
end
toc
tic
for ii=1:ii_max
ourSine1(x);
end
toc
tic
for ii=1:ii_max
ourSine2(x);
end
toc
tic
for ii=1:ii_max
ourSine3(x);
end
toc
tic
for ii=1:ii_max
ourSine4(x);
end
toc
warning(w);
296
175
4.5.4.2
Root–Finding
Many real–world problems require finding the roots of an arbitrary function; f (x) = 0.
• “fzero” Matlab function calculates roots for any arbitrary function near a given point x0
>> fzero(@(x) (cos(x)),pi/4)
ans =
1.5708
>> fzero(@(eta) (cos(exp(eta))+eta^2-1),1)
ans =
1.3367
Example 3.
1
0.8
0.6
0.4
0.2
0
-0.2
-0.4
-0.6
-0.8
-1
0
0.2
0.4
0.6
0.8
1
1.2
1.4
1.6
1.8
>> w n=1;
>> zeta=0.1;
>> x0=-1;
>> v0=0;
>> f n=w n/2/pi;
>> T n=1/f n;
>> t=fzero(@(t) SDOF Free Response Visc(w n,zeta,x0,v0,t),.7*T n)
t =
4.8368
>> t/T n
ans =
0.7698
>> t=fzero(@(t) SDOF Free Response Visc(w n,zeta,x0,v0,t),.8*T n)
176
2
t =
4.8368
>> t/T n
ans =
0.7698
>> t=fzero(@(t) SDOF Free Response Visc(w n,zeta,x0,v0,t),1.2*T n)
t =
7.9942
>> t/T n
ans =
1.2723
>> t=fzero(@(t) SDOF Free Response Visc(w n,zeta,x0,v0,t),1.7*T n)
t =
11.152
>> t/T n
ans =
1.7748
298
Laboratory
• Implement laboratory 11 on page 229
299
Assignment
• Implement problems (4.15) and (4.16)
300
4.5.5
Improving Code Performance
• Refer to www.mathworks.com/help/matlab/performance-and-memory.html
– Improve Performance
– Measure and Profile Code
∗ Preallocation
∗ Vectorization
– Identify and Reduce Memory Requirements
301
177
4.6
Visualization
Supported Plots∗
Types of MATLAB Plots
There are various functions that you can use to plot data in MATLAB®. This table classifies and illustrates the common graphics functions.
Line Plots
Scatter and
Bubble Charts
Data Distribution
Plots
Discrete
Geographic
Data
Plots
Plots
Polar Plots
Contour Plots
Vector
Fields
Surface and
Mesh Plots
Volume
Visualization
Animation
plot
scatter
histogram
bar
geoplot
polarplot
contour
quiver
surf
streamline
animatedline image
plot3
scatter3
histogram2
barh
geoscatter polarhistogram
contourf
quiver3
surfc
streamslice
comet
stairs
bubblechart
scatterhistogram bar3
geobubble
contour3
feather
surfl
streamparticles comet3
errorbar
bubblechart3 boxchart
bar3h
polarbubblechart contourslice
ribbon
streamribbon
area
swarmchart
swarmchart
pareto
compass
pcolor
streamtube
stackedplot swarmchart3
swarmchart3
stem
ezpolar
fsurf
coneplot
loglog
pie
stem3
fimplicit3 slice
semilogx
pie3
stairs
mesh
semilogy
wordcloud
meshc
fplot
bubblecloud
meshz
fplot3
heatmap
waterfall
fimplicit
parallelplot
fmesh
spy
polarscatter
fcontour
plotmatrix
∗
[www.mathworks.com/help/matlab/creating_plots/types-of-matlab-plots.html]
178
Images
imagesc
4.6.1
2D Visualization
Creating Plots
>> x vec=0:pi/10:2*pi;
>> y vec=sin(x vec);
>> plot(x vec,y vec)
303
1
0.8
0.6
0.4
0.2
0
-0.2
-0.4
-0.6
-0.8
-1
0
1
2
3
4
Controlling Plot Properties
There are several ways to control plot properties, as follows:
• At creation (highly Recommended)
>> plot(x vec,y vec,’--rs’, ...
’LineWidth’,2,’MarkerEdgeColor’,’k’, ...
’MarkerFaceColor’,’g’,’MarkerSize’,10)
1
0.8
0.6
0.4
0.2
0
-0.2
-0.4
-0.6
-0.8
-1
0
1
2
3
4
5
6
• After creation
1. Using Commands (recommended)
>> oCurve=plot(x vec,y vec);
>> set(oCurve,’LineWidth’,2,’LineStyle’,’--’, ...
’Color’,’r’, ... %or RGB components
’Marker’,’s’,’MarkerEdgeColor’,’k’, ...
’MarkerFaceColor’,’g’,’MarkerSize’,10)
179
7
5
6
7
1
0.8
0.6
0.4
0.2
0
-0.2
-0.4
-0.6
-0.8
-1
0
1
2
3
4
5
6
7
– Objects properties can be controlled/checked using the “set”/“get” commands
>> get(oCurve,’LineWidth’)
ans =
2
get(oCurve,’LineWidth’) gets the line width of the curve object oCurve
get(oCurve) returns all properties and their current values of the curve object
oCurve
set(oCurve) returns the user–settable properties and possible values of the
curve object oCurve
– Alternatively, you can use the dot notation
>> oCurve.LineWidth=4;
>> oCurve.LineStyle=’:’;
>> oCurve.Color=’b’;
%or RGB components
>> oCurve.Marker=’o’;
>> oCurve.MarkerEdgeColor=’r’;
>> oCurve.MarkerFaceColor=’y’;
>> oCurve.MarkerSize=15;
1
0.8
0.6
0.4
0.2
0
-0.2
-0.4
-0.6
-0.8
-1
0
1
2
3
4
5
6
7
>> oCurve.LineWidth
ans =
4
– Refer to www.mathworks.com/help/matlab/graphics-objects.html for
complete description of all graphics objects and their properties
180
2. Interactively (Not recommended)
– Press the arrow button in the toolbar
– select any object and right–click, or double–click
– you may select “More Properties ...”
– enjoy interactive editing
304
Line Styles and Colors∗
Colors†
Value Meaning
’c’
cyan
’m’
magenta
’y’
yellow
’r’
red
’g’
green
’b’
blue
’w’
’k’
Line Styles
Value Meaning
’-’
solid
’--’
dashed
’:’
dotted
’.-’ dash–dot
none
no line
white
black
Marker Types
Value Meaning
’+’
plus sign
’o’
circle
’*’
asterisk
’x’
cross
’s’
square
’d’
diamond
..
..
.
.
none
no marker
305
∗
†
[www.mathworks.com/help/matlab/ref/plot.html]
Any other color can also be specified using RGB components
181
Adding Plots to an Existing Graph
>> plot(x_vec,sin(x_vec)-.25) %older curve
is lost
>> hold on
>> plot(x_vec,sin(x_vec)-1)
>> plot(x_vec,sin(x_vec)-1.25)
0.5
1
0
0.5
-0.5
0
-1
-0.5
-1.5
-1
-2
-2.5
-1.5
0
1
2
3
4
5
6
0
7
1
2
3
4
5
6
7
>> set(gca,’ColorOrderIndex’,1); %Restart
Color Order
>> plot(x_vec,sin(x_vec)-1.5)
>> plot(x_vec,sin(x_vec)-1.75)
>> plot(x_vec,sin(x_vec)-.5,x_vec,sin(
x_vec)-.75) %older curve is lost
0.5
0.5
0
0
-0.5
-0.5
-1
-1.5
-1
-2
-1.5
-2.5
-2
-3
0
1
2
3
4
5
6
0
7
182
1
2
3
4
5
6
7
Annotating Figures
>> xlabel(’x = 0:2\pi’)
>> ylabel(’sin(x)’)
>> title(’Plot of the Sine Function’)
>> legendString_vec=["sin(x)","sin(x-\pi/2)","sin(x-\pi)","sin(x-1.5\pi)"];
>> legend(legendString_vec)
Plot of the Sine Function
0.5
sin(x)
sin(x- /2)
sin(x- )
sin(x-1.5 )
0
sin(x)
-0.5
-1
-1.5
-2
-2.5
-3
0
1
2
3
4
5
6
7
x = 0:2
• Check www.mathworks.com/help/matlab/creating_plots/greek-letters-andspecial-characters-in-graph-text.html
307
LATEX Equations
>> xlabel(’$x = 0:2\pi$’,’interpreter’,’latex’)
>> ylabel(’$\sin(x)$’,’interpreter’,’latex’)
>> title(’Plot of $\sin(x)$ Function’,’interpreter’,’latex’)
>> legendString_vec=["$\sin(x)$","$\sin(x-\frac{\pi}{2})$","$\sin(x-\pi)$","$\sin(x
-1.5\pi)$"];
>> legend(legendString_vec,’interpreter’,’latex’)
0.5
0
-0.5
-1
-1.5
-2
-2.5
-3
0
1
2
3
4
5
6
7
308
183
Customizing Axis
>> grid on
>> oAx1=gca;
>> oAx1.XTick=0:pi/2:2*pi;
>> oAx1.XTickLabel=["$0$","$\frac{\pi}{2}$","$\pi$","$1.5\pi$","$2\pi$"];
>> oAx1.XAxis.TickLabelInterpreter=’latex’;
>> oAx1.XLim=[0,2*pi];
>> oAx1.YTick=-1:.5:1;
0.5
0
-0.5
-1
• gca is a built–in command that returns the current axis object
• similarly gcf is a built–in command that returns the current figure object
Axis Limits, Styles and Modes
• axis([xmin xmax ymin ymax])
– sets the limits of the axes to the values stored in the xmin, xmax, ymin and ymax
variables
– specifying xmax and/or ymax as inf lets Matlab automatically choose these limits
– Similarly, specifying xmin and/or ymin as -inf lets Matlab automatically choose
these limits
• axis auto
– automatically choose all axis limits
– there are also axis auto x , . . . , axis auto xy , . . .
• lims=axis
– returns the x and y-axes limits for the current axes
• axis equal
– makes x and y axes scale the same
184
– equivalent to set(gca,’DataAspectRatio’,[1,1,1])
• axis square
– makes the current axis look like a box
– equivalent to set(gca,’PlotBoxAspectRatio’,[1,1,1])
• axis tight
– fits axis to data
• Refer to www.mathworks.com/help/matlab/ref/axis.html for more information and
details
• There are similar xlim , ylim and zlim commands
Example 4 (Axis Modes).
>> figure
>> theta_vec=0:pi/30:2*pi;
>> z1_vec=8+exp(1i*theta_vec);
>> z2_vec=2*exp(1i*theta_vec);
>> plot(real(z1_vec),imag(z1_vec),real(z2_vec),imag(z2_vec))
>> axis square
>> axis equal
2
4
1.5
3
2
1
1
0.5
0
0
-1
-0.5
-2
-1
-3
-1.5
-4
-2
-1
0
1
2
3
4
5
6
7
8
-2
-2
9
0
2
4
6
8
10
310
Subplots; the Legacy Way for Multiple Plots
185
Tiled Layouts; the Modern Way for Multiple Plots
>> figure;
>> tile1=tiledlayout(2,3); % 2 by 3 tiles
>> xlabel(’x-axis’)
>> ylabel(’y-axis’)
>> oAx1=nexttile;
>> x_col=linspace(0,360).’;
>> plot(x_col,sind(x_col))
>> ylabel(’y-axis’)
>> title(’Curve 1’)
>> oAx5=nexttile(5); %jump to tile no. 5
>> plot(4*x_col,1.75*sind(4*x_col))
>> xlabel(’x-axis’)
>> oAx2=nexttile; %row major tile indexing
>> plot(2*x_col,1.25*sind(2*x_col))
>> title(’Curve 2’)
>> oAx4=nexttile(4); %jump to tile no. 4
>> plot(3*x_col,1.5*sind(3*x_col))
Curve 1
1
>> oAx36=nexttile(3,[2,1]); %Tile spanning
several rows/columns
>> plot(x_col,[1,-1.25,1.5,-1.75].*sind(
x_col))
>> xlabel(’x-axis’)
>> ylabel(’y-axis’)
>> title(’Combined curves’)
Curve 2
Combined curves
2
1
y-axis
0.5
0.5
0
1.5
0
1
-0.5
-0.5
-1
0
200
400
2
0.5
0
500
y-axis
-1
0
2
y-axis
-0.5
1
1
0
0
-1
-1
-1
-2
0
500
x-axis
1000
-2
-1.5
0
500
1000
x-axis
186
-2
0
200
x-axis
400
Shared Title and Axis–labels
>> xlabel(tile1,’Shared xlabel’)
>> ylabel(tile1,’Shared ylabel’)
>> title(tile1,’Shared Title’)
Shared Title
Curve 1
1
Curve 2
Combined curves
2
1
y-axis
0.5
0.5
0
1
-0.5
-0.5
Shared ylabel
1.5
0
-1
0
200
400
0.5
0
2
2
1
1
0
0
-1
-1
500
y-axis
-1
0
-0.5
y-axis
-1
-2
0
500
1000
-2
x-axis
-1.5
0
500
-2
1000
x-axis
0
200
400
x-axis
Shared xlabel
313
Link the Limits of Multiple Axis
>> linkaxes([oAx1,oAx2,oAx4,oAx5],’xy’);
>> oAx2.YTickLabel={};
>> oAx5.YTickLabel={};
% More formatting for better display
>> oAx1.XTickLabel={};
>> oAx2.XTickLabel={};
>> tile1.TileSpacing=’tight’;
Shared Title
Curve 1
Shared ylabel
y-axis
2
Curve 2
1
1.5
0
1
-1
y-axis
0.5
-2
2
y-axis
Combined curves
2
0
1
-0.5
0
-1
-1
-1.5
-2
0
500
1000
x-axis
0
500
1000
x-axis
-2
0
200
400
x-axis
Shared xlabel
314
187
TiledChartLayout Properties
• Refer
to
www.mathworks.com/help/matlab/ref/matlab.graphics.layout.
tiledchartlayout-properties.html
Laboratories
• Implement laboratories 12 and 13 on page 229
Extra Information
Refer to:
• www.mathworks.com/help/matlab/examples.html . Graphics
• www.mathworks.com/help/matlab/creating_plots/graph-with-multiple-xaxes-and-y-axes.html
188
4.6.2
3D Visualization
3D Plots
Line Graphs
Mesh Graphs
and Bar
Graphs
Area Graphs
and
Constructive
Objects
Surface
Graphs
Direction
Graphs
Volumetric
Graphs
plot3
mesh
pie3
surf
quiver3
scatter3
contour3
meshc
fill3
surfl
comet3
coneplot
contourslice
meshz
patch
surfc
streamslice
streamline
ezplot3
ezmesh
cylinder
ezsurf
streamribbon
waterfall
stem3
ellipsoid
ezsurfc
streamtube
bar3
sphere
bar3h
318
189
3D Line
“plot3” is identical to “plot” command, but takes 3 vectors instead of 2.
>> figure;
>> theta_vec=linspace(0,3*2*pi);
>> x1_vec=sin(theta_vec);
>> y1_vec=cos(theta_vec);
>> z1_vec=linspace(0,10,length(theta_vec));
10
8
Z-AXIS
6
4
>> x2_vec=x1_vec;
>> y2_vec=y1_vec-4;
2
0
2
0
>> plot3(x1_vec,y1_vec,z1_vec,x2_vec,y2_vec,
z1_vec);
>> xlabel(’X-AXIS’);ylabel(’Y-AXIS’);zlabel(’ZAXIS’)
1
0.5
-2
0
-4
-0.5
Y-AXIS
-6
-1
X-AXIS
Data Aspect Ratio
10
Z-AXIS
>> oAx=gca;
>> ar=oAx.DataAspectRatio
ar =
1
4
5
>> oAx.DataAspectRatio=[ar(1),ar(1),
ar(3)];
5
0
1
0
-1
-2
-3
1
Y-AXIS
-4
0
-5
Laboratory
• Implement laboratory 14 on page 229
190
-1
X-AXIS
Surface Plots
• To plot a line in the 3D, 3 vectors are needed
• To plot a rectangular surface in the 3D, 3 matrices are needed
>> figure;
>> x_vec=-2:2
x_vec =
-2 -1 0 1 2
>> y_vec=-1:1
y_vec =
-1 0 1
>> [x_mat,y_mat]=meshgrid(x_vec,y_vec)
x_mat =
-2 -1 0 1 2
-2 -1 0 1 2
-2 -1 0 1 2
y_mat =
-1 -1 -1 -1 -1
0 0 0 0 0
1 1 1 1 1
>> z_mat=x_mat.*exp(-x_mat.^2-y_mat.^2);
>> surf(x_mat,y_mat,z_mat)
>> colorbar
>> xlabel(’X-AXIS’);
>> ylabel(’Y-AXIS’);
>> zlabel(’Z-AXIS’)
0.3
0.4
0.2
0.2
Z-AXIS
0.1
0
0
-0.2
-0.1
-0.4
1
-0.2
0.5
2
1
0
Y-AXIS
-0.3
0
-0.5
-1
-1
-2
X-AXIS
322
View Direction
>> view(0,90)
>> view(-37.5,30)
1
0.3
0.3
0.8
0.4
0.6
0.2
0.2
0.4
0.2
0.1
0.1
0
Z-AXIS
Y-AXIS
0.2
0
0
0
-0.2
-0.2
-0.1
-0.1
-0.4
-0.2
-0.6
-0.4
1
-0.2
0.5
-0.8
-0.3
2
1
0
0
-0.5
-1
-2
Y-AXIS
-1.5
-1
-0.5
0
0.5
1
1.5
2
-0.3
-1
-1
-2
X-AXIS
X-AXIS
323
191
More Dense Surface Mesh
0.4
>> figure;
>> x_vec=linspace(-2,2,40);
>> y_vec=linspace(-1,1,20);
>> [x_mat,y_mat]=meshgrid(x_vec,y_vec);
>> z_mat=x_mat.*exp(-x_mat.^2-y_mat.^2);
>> surf(x_mat,y_mat,z_mat)
>> colorbar
0.3
0.5
0.2
0.1
0
0
-0.1
-0.5
1
-0.2
0.5
2
0
-0.5
-0.4
-1
-1
>> view(2)
-0.3
1
0
-2
>> view(3)
1
0.4
0.4
0.8
0.3
0.3
0.5
0.6
0.2
0.2
0.4
0.1
0.1
0.2
0
0
0
0
-0.2
-0.1
-0.1
-0.4
-0.2
-0.5
1
-0.6
-0.3
-0.8
-1
-2
-0.4
-1
0
1
-0.2
0.5
2
0
-0.5
-1
-1
2
192
-0.3
1
0
-2
-0.4
Surface Shading
>> shading interp
>> shading flat
0.4
0.4
0.3
0.5
0.3
0.5
0.2
0.2
0.1
0
0.1
0
0
0
-0.1
-0.1
-0.5
1
-0.5
1
-0.2
0.5
2
-0.2
0.5
2
0
-0.5
-1
-1
0
-0.5
1
0
-0.3
1
0
-0.3
-0.4
-0.4
-1
-1
-2
-2
>> shading faceted
0.4
0.3
0.5
0.2
0.1
0
0
-0.1
-0.5
1
-0.2
0.5
2
-0.3
1
0
0
-0.5
-0.4
-1
-1
-2
325
Surface Colors
Surface colors are by default proportional to
the Z matrix.
>> surf(x mat,y mat,z mat,-z mat)
>> colorbar
• Surface colors can be changed
0.4
• This can add a 4th dimension to the plot
0.3
0.5
0.2
0.1
0
0
-0.1
-0.5
1
-0.2
0.5
2
0
-0.5
-1
-1
193
-0.3
1
0
-2
-0.4
Surface Colormaps
>> colormap(jet)
>> colormap(hot)
0.4
0.4
0.3
0.5
0.3
0.5
0.2
0.2
0.1
0.1
0
0
-0.5
1
0
0
-0.1
-0.1
-0.2
0.5
2
-0.5
1
-0.3
-0.2
0.5
1
0
0
-0.5
-1
-1
2
0
-0.5
-0.4
-0.3
1
0
-0.4
-1
-1
-2
-2
>> colormap(parula)
0.4
0.3
0.5
0.2
0.1
0
0
-0.1
-0.5
1
-0.2
0.5
2
0
-0.5
-1
-1
194
-0.3
1
0
-2
-0.4
Similar 3D Visualizations
The following commands are similar, or closely related to “surf”:
• surfc
• meshz
• contourf
• mesh
• contour
• pcolor
• meshc
• contour3
• ...
Examples:
1
>> figure;
>> pcolor(x_mat,y_mat,z_mat)
0.8
0.6
0.4
0.2
0
-0.2
-0.4
-0.6
-0.8
-1
-2
>> figure;
>> mesh(x_mat,y_mat,z_mat)
-1.5
-1
-0.5
0
0.5
1
1.5
2
0.5
0
-0.5
1
0.5
2
1
0
0
-0.5
-1
-1
>> mesh(x_mat,y_mat,z_mat,’FaceColor’,’
none’,’EdgeColor’,[0,0,0])
328
-2
0.5
0
-0.5
1
0.5
2
1
0
0
-0.5
-1
-1
195
-2
4.6.2.1
Tweaking Rectangular Grids
Plain Rectangular Grid
>> x_vec=-10:0.25:10;
>> y_vec=-10:0.25:10;
>> [x_mat,y_mat]=meshgrid(x_vec,y_vec);
>> r_mat=sqrt(x_mat.^2+y_mat.^2);
>> z_mat=sinc(r_mat/pi);
>> mesh(x_mat,y_mat,z_mat);
>> view(0,90)
10
8
6
4
2
1
0
-2
0.5
-4
0
-6
-8
-0.5
10
-10
-10
5
-5
0
5
10
0
5
10
10
5
0
0
-5
-5
-10
-10
Tweaked Rectangular Grid
>> theta_vec=linspace(0,.75*2*pi,30);
>> r_vec=0:0.25:10;
>> [theta_mat,r_mat]=meshgrid(theta_vec,
r_vec);
>> z_mat=sinc(r_mat/pi);
>> [x_mat,y_mat]=pol2cart(theta_mat,r_mat)
;
>> mesh(x_mat,y_mat,z_mat);
>> view(0,90)
10
8
6
4
2
0
1
-2
-4
0.5
-6
-8
0
-10
-10
-0.5
10
5
10
5
0
0
-5
-5
-10
-10
196
-5
Extra information
Refer to:
• www.mathworks.com/help/matlab/examples.html . Graphics
Laboratory
• Implement laboratory 15 on page 229
332
4.6.3
Overriding Default Graphics Properties
You can change the default graphics properties, for example:
• The following may be suitable for figures to be printed on:
– black laser printer
set(groot,’DefaultAxesColorOrder’,[0,0,0])
set(groot,’DefaultAxesLineStyleOrder’,["-o",":s","--+"])
set(groot,’DefaultLineLineWidth’,1.5);
– color printer
set(groot,’DefaultAxesColorOrder’,[0,0,1;
0,0,0;
1,0,0;
0,0.5,0;
1,0,1])
set(groot,’DefaultAxesLineStyleOrder’,’-|--|-.’)
set(groot,’DefaultLineLineWidth’,1.5);
• To revert back to the line color order and title and label styles of Matlab prior to R2014b,
set(groot,’DefaultAxesColorOrder’,[0,0,1;
0,0.5,0;
1,0,0;
0,0.75,0.75;
0.75,0,0.75;
0.75,0.75,0;
0.25,0.25,0.25])
set(groot,’DefaultAxesTitleFontWeight’,’normal’)
set(groot,’DefaultAxesTitleFontSizeMultiplier’,1)
set(groot,’DefaultAxesLabelFontSizeMultiplier’,1)
• To revert back to the colormap of Matlab prior to R2014b,
set(groot,’DefaultFigureColormap’,jet)
• At the end of your script/function, don’t forget to reset all the properties you have changed
by using commands like the following
set(groot,’DefaultAxesColorOrder’,’remove’)
set(groot,’DefaultAxesLineStyleOrder’,’remove’)
set(groot,’DefaultLineLineWidth’,’remove’)
set(groot,’DefaultAxesTitleFontWeight’,’remove’)
set(groot,’DefaultAxesTitleFontSizeMultiplier’,’remove’)
set(groot,’DefaultAxesLabelFontSizeMultiplier’,’remove’)
set(groot,’DefaultFigureColormap’,’remove’)
333
197
4.6.4
Exporting Figures
Saving/Exporting Figures
Matlab can save figures in many formats including:
.png
.jpg
Raster
Loose–less compression
Lossy compression
Vector
Compressed
Compatible with MS office
Compatible with MS office & web
browsers
.pdf
.emf
.svg
..
.
..
.
Raster
Vector
0.5
0
-0.5
-1
• Method 1 using commands (highly recommended)
– For example, to export figure number 1 as “filename.pdf” with resolution of 600 dpi,
write the command
>> print(’-r600’,’-dpdf’,’-f1’,’filename’);
– There is a Perl program called “pdfcrop” for cropping the generated pdf
∗ This program, ships with both MiKTEX and TEX Live LATEX distributions
∗ Perl should be installed∗
• Method 2 File . Export Setup
– Make sure to choose resolution not less than 600 dpi
• Alternatively, you may use Edit . copy figure, and then past the figure in your favorite
word processor
198
Assignment
• Implement problems (4.25), (4.26) and (4.27)
Printing Figures
• File . Print Preview
• Or you can use the following command to send figure number 1 with resolution of 600 dpi
to a
– color printer
– monochrome printer
>> print(’-r600’,’-dwinc’,’-f1’);
>> print(’-r600’,’-dwin’,’-f1’);
• Make sure to choose resolution of 600 dpi or higher
336
After Done with Figures
• clc , cla & clf
clears the command window, current axis & current figure
• close([1 3])
closes figures 1 and 3
• close all
closes all figures (useful in scripts/functions)
337
4.7
Debugging
• Explore the debug toolbar
∗
“Strawberry Perl” is a sample open–source Perl implementation for Microsoft Windows.
199
click to set breakpoints
code execution is paused
at this line
– Breakpoints . Pause on Errors/Warnings is very helpful for debugging
200
4.8
OOP in Matlab
Introduction to Object Oriented Programming (OOP)
• Refer to appendix F
339
Codes of this Section
All codes of this section are available open source @ https://github.com/ahmed-rashed/OOP_
Tutorial
340
Application 4.1 (Properties of Cross–Sections).
Iŷ = Iy + A z 2
Iẑ = Iz + A y 2
Iŷẑ = Iyz + A y z
(4.1)
341
Sample Class Definition
Code 4.7: cArea simple.m
end
classdef cArea_simple %The file-name must
be the same as the class-name
if nargin==4
oThisObject.Iyz=Iyz;
end
properties
A double {mustBeNonnegative}
Iy(1,1) double {mustBeNonnegative
}=0
Iz(1,1) double {mustBeNonnegative
}=0
Iyz(1,1) double =0
end
end
function Iy_hat=Iy_hat(oThisObject,
z_bar)
Iy_hat=oThisObject.Iy+
oThisObject.A*z_bar.^2;
end
function Iz_hat=Iz_hat(oThisObject,
y_bar)
Iz_hat=oThisObject.Iz+
oThisObject.A*y_bar.^2;
end
methods
function oThisObject=cArea_simple(A
,Iy,Iz,Iyz) % Constructor
if nargin>=1
oThisObject.A=A;
end
function Iyz_hat=Iyz_hat(
oThisObject,y_bar,z_bar)
Iyz_hat=oThisObject.Iyz+
oThisObject.A*y_bar*z_bar;
end
if nargin>=2
oThisObject.Iy=Iy;
end
end
if nargin>=3
oThisObject.Iz=Iz;
end
342
201
Instantiating (Creating) Object of a Class
>> oArea=cArea_simple
oArea =
cArea_simple with properties:
A: []
Iy: 0
Iz: 0
Iyz: 0
>> oArea=cArea_simple(1)
oArea =
cArea_simple with properties:
A: 1
Iy: 0
Iz: 0
Iyz: 0
>> oArea=cArea_simple(1,2)
oArea =
cArea_simple with properties:
A: 1
Iy: 2
Iz: 0
Iyz: 0
>> oArea=cArea_simple(1,2,3)
oArea =
cArea_simple with properties:
A: 1
Iy: 2
Iz: 3
Iyz: 0
>> oArea=cArea_simple(1,2,3,4)
oArea =
cArea_simple with properties:
A: 1
Iy: 2
Iz: 3
Iyz: 4
Using Properties and Methods
>> oArea.A
ans =
1
>> oArea.A=8
oArea =
cArea_simple with properties:
A: 8
Iy: 2
Iz: 3
Iyz: 4
>> oArea.Iz_hat(5)
ans =
203
>> Iz_hat(oArea,5)
ans =
203
>> oArea.Iy_hat(6)
ans =
290
>> oArea.Iyz_hat(5,6)
ans =
244
202
4.8.1
Class Definition
classdef (Attribute1 = value1, Attribute2 = value2, ...) ClassName
...
end
• The class definition .m file should be named same as the class name
• Refer to code 4.7 on page 201 for sample class definition
345
Class Attributes
Some important attributes are:
• Abstract
– An abstract class cannot be instantiated, but serves as a way to define a unified interface for use by its subclasses
– When a property or method is attributed as abstract, Matlab automatically attributes
its class as abstract
– Details are available in www.mathworks.com/help/matlab/matlab_oop/
abstract-classes-and-interfaces.html
• More attributes are listed @ www.mathworks.com/help/matlab/matlab_oop/classattributes.html
346
203
4.8.2
Properties
Properties Definition
The general syntax for properties definition is:
properties (Attribute1 = value1, Attribute2 = value2, ...)
prop1 (dimensions) class {validators} = defaultValue
...
end
• Refer to code 4.7 on page 201 for sample property definitions
– More information are available @ www.mathworks.com/help/matlab/matlab_
oop/defining-properties.html
Property Attributes
Some important attributes are:
• Access restricts reading and setting the property value
– Sets SetAccess and GetAccess to the same value
– Access values are explained on page 206
• GetAccess restricts reading the property value
– Values are same as Access
• SetAccess restricts setting the property value
– Values are same as Access, in addition to:
∗ immutable restricts setting the property to the constructor only. You cannot
change the value of an immutable property after the object is created.
• Abstract Logical value. Default: false
– If true, the property has no implementation, but a concrete subclass must redefine
this property without Abstract being set to true
∗ A Superclass may define an abstract property to enforce consistent interface
among subclasses
– When a property∗ is attributed as Abstract, Matlab automatically attributes its class
as Abstract
• Hidden Determines whether the property should be shown in a property list
• Dependent A dependent property is calculated by a class method whenever the dependent
property is requested
∗
or method
204
• Unlike other OOP programming languages, Matlab does not provide the static property
attribute†‡ . A static property:
– is shared by all objects of the class
– can be modified after creation
– can be accessed without creating objects; using the class name
• Constant properties can only be initialized in its defining block, and its value cannot be
changed later on.
– By definition, a constant property is static
• More attributes are listed @ www.mathworks.com/help/matlab/matlab_oop/
property-attributes.html
348
Property Validation
• Refer to www.mathworks.com/help/matlab/matlab_oop/property-validatorfunctions.html
349
4.8.3
Methods
The Constructor Method
The constructor method creates objects of the class.
• Refer to code 4.7 on page 201 for a typical constructor method
• The constructor has the same name as the class
• The constructor:
– creates an object
– assigns its properties
– returns the created object as output
• To create object array, the constructor must support being called without input arguments
[sec. 4.8.7]
350
†
[www.mathworks.com/help/matlab/matlab_oop/matlab-vs-other-oo-languages.html#
buwskub]
‡
However, there are two workarounds in www.mathworks.com/help/matlab/matlab_oop/static-data.
html.
205
Ordinary Methods∗
An ordinary method is a function that operates on the object properties.
• Refer to code 4.7 on page 201 for typical methods
• The first input argument must be the parent object
• An ordinary method can be called using either of the following notations:
– dot notation; object.method(argument)
– function notation; method(object,argument)
• Same as ordinary functions, Matlab passes input arguments to ordinary methods by value
[sec. 4.5.3.1]
– Hence, ordinary methods cannot modify properties
– Refer to sec. 4.8.8 for more information
Specialized Methods
• Refer to www.mathworks.com/help/matlab/matlab_oop/how-to-use-methods.
html
Method Attributes∗
Some important attributes are:
• Access:
– public (default) unrestricts access
– private restricts access to the parent class only
– protected restricts access to the parent class and its subclasses
∗ Note that a superclass cannot access subclass’s protected methods
– {?ClassName1,?ClassName2,...} restricts access to classes in the list; and their
subclasses; in addition to the parent class
∗ That is, access is protected to the listed classes, and is private† to the parent
class
∗ The parent class can be included in this list
∗ If the parent class is not included in this list, its subclasses cannot access‡ the
method
• Static Static methods are associated with the class, rather than its objects. Hence, a static
method:
∗
[www.mathworks.com/help/matlab/matlab_oop/ordinary-methods.html]
[www.mathworks.com/help/matlab/matlab_oop/method-attributes.html]
†
In fact, there is a slight difference explained in ‡.
‡
Accordingly, the subclasses cannot also override the method. This makes this access behavior different from
private.
∗
206
– can be called without creating objects
– definition does not require the object as input argument
– can use constant properties
– cannot modify/use object properties/methods
• Abstract
– An abstract method has no implementation,
[a,b]=Method1(x,y) )
only a syntax line (e.g.,
∗ Subclasses are not required to define the same number of input and output arguments
– When a method∗ is attributed as abstract, Matlab automatically attributes its class as
abstract
• Sealed If true, the method cannot be redefined in a subclass
• Hidden When false, the method name shows in the list of methods displayed using the
methods or methodsview commands. If set to true, the method name is not included
in these listings and ismethod does not return true for this method name.
353
∗
or property
207
4.8.4
Dynamic Referencing
The following statements are equivalent:
>> obj.Property1
>> obj.(’Property1’)
>> propName = ’Property1’;
>> obj.(propName)
• You can call a method and pass its input arguments using another set of parentheses:
>> obj.(expression)(arg1,arg2,...)
• Using this notation, you can make dynamic references to properties and methods
4.8.5
Inheritance
Inheritance
A subclass inherits all properties and methods of its superclass.
Sample Subclass
Code 4.8: cDistantArea simple.m
%Construct the subclass
oThisObject.y_bar=y_bar;
oThisObject.z_bar=z_bar;
classdef cDistantArea_simple <
cArea_simple %The file-name must be
the same as the class-name
end
properties
y_bar(1,1) double
z_bar(1,1) double
end
function Iy_hat=Iy_hat(oThisObject)
Iy_hat=Iy_hat@cArea_simple(
oThisObject,oThisObject.
z_bar); %#ok<NODEF>
end
methods
function oThisObject=
cDistantArea_simple(A,Iy,Iz,Iyz
,y_bar,z_bar) % Constructor
if nargin==0
superClassArgs={};
elseif nargin==6
superClassArgs={A,Iy,Iz,Iyz
};
else
error(’This class can be
constructed using zero
or 6 inputs.’);
end
function Iz_hat=Iz_hat(oThisObject)
Iz_hat=Iz_hat@cArea_simple(
oThisObject,oThisObject.
y_bar); %#ok<NODEF>
end
function Iyz_hat=Iyz_hat(
oThisObject)
Iyz_hat=Iyz_hat@cArea_simple(
oThisObject,oThisObject.
y_bar,oThisObject.z_bar); %
#ok<NODEF>
end
end
%Construct the superclass
oThisObject@cArea_simple(
superClassArgs{:});
end
208
Using a Subclass
>> oArea=cArea_simple(1,2,3,4)
oArea =
cArea_simple with properties:
A: 1
Iy: 2
Iz: 3
Iyz: 4
>> oArea.Iz_hat(5)
ans =
28
>> oArea.Iy_hat(6)
ans =
38
>> oArea.Iyz_hat(5,6)
ans =
34
>> oDistantArea=cDistantArea_simple(1,2
,3,4,5,6)
oDistantArea =
cDistantArea_simple with properties:
y_bar: 5
z_bar: 6
A: 1
Iy: 2
Iz: 3
Iyz: 4
>> oDistantArea.Iz_hat
ans =
28
>> oDistantArea.Iy_hat
ans =
38
>> oDistantArea.Iyz_hat
ans =
34
357
The Subclass Constructor∗
Before a subclass is constructed, its superclass must be constructed beforehand, using the superclass constructor.
• Refer to code 4.8 on the facing page for a sample subclass
• The superclass constructor can be explicitly called from the subclass constructor, using
the following syntax
– This call must come before any reference to the subclass object
– This call cannot be conditional (i.e., within loops, conditions, switches, try/catch, or
nested functions)
∗ Conditionals can however be used to create a comma–separated list [sec. 4.4.1]
of the superclass constructor arguments
∗
[www.mathworks.com/help/matlab/matlab_oop/subclass-constructors.html]
209
∗ This list can then be unconditionally passed to the explicit call to the superclass
constructor
• If the superclass constructor was not explicitly called from the subclass constructor, MATLAB implicitly call it with no arguments.
– Therefore, the superclass constructors must support being called with no input argument [code 4.7 on page 201]
– If the subclass inherits from multiple superclasses, their constructors are called in
the order written in the classdef block of the subclass
• When the subclass does not define a constructor, the default constructor passes its inputs
to the direct superclass constructor
Overloading Inherited Methods
A subclass can overload methods of its superclass.
• Refer to code 4.8 on page 208 for a typical subclass
• An overloaded superclass method can be called only from its overloading subclass method,
using the following syntax
• Subclass methods that override superclass methods must define the same value for the
Access attribute as is defined by the superclass method
210
Overloading Inherited Properties∗
A superclass property cannot be overloaded unless it is either private or abstract.
• Referencing the overloaded property from either the super/sub–class accesses its respective property
classdef cSuper
properties(Access=private)
Prop=2
end
classdef cSub < cSuper
properties
Prop=1
end
methods
function p=superMethod(
oThisObject)
p=oThisObject.Prop;
end
end
end
methods
function p=subMethod(
oThisObject)
p=oThisObject.Prop;
end
end
end
>> obj=cSub;
>> obj.superMethod
ans =
2
>> obj.subMethod
ans =
1
360
Identifying Class Type
• isa determines if a class is of (or derived from) a specified class
• class determine the class of an object
>> isa(oDistantArea,’cArea_simple’)
ans =
logical
1
>> class(oDistantArea)
ans =
’cDistantArea_simple’
>> isa(oDistantArea,
’cDistantArea_simple’)
ans =
logical
1
361
More Information
• Designing Heterogeneous Class Hierarchies
– Refer to www.mathworks.com/help/matlab/matlab_oop/heterogeneousarrays.html
362
∗
[www.mathworks.com/help/matlab/matlab_oop/modify-superclass-properties.html]
211
4.8.5.1
Inheriting Multiple Classes
Inheriting Multiple Classes∗
classdef SubClass < SuperClass1 & SuperClass2
...
end
When inheriting multiple classes, if more than one superclass defines a property/method/event
having the same name, there must be an unambiguous resolution to the multiple definitions.
Property Conflicts
If two or more superclasses define a property with the same name, then at least one of the following must be true:
• All, or all but one of the properties must be private
• The properties have the same definition in all superclasses
– For example, all the superclasses inherited the conflicting property from a common
superclass
Method Conflicts
If two or more superclasses define each a method with the same name, then at least one of the
following must be true:
• The subclass overloads this method to disambiguate access resolution of this method
• Each of these superclasses attribute its method as private
• The method has the same definition in all subclasses
– For example, all the superclasses inherited the method from a common superclass
• Only one superclass defines the method as Sealed, in which case, the subclass adopts the
sealed method definition
• The superclasses define the methods as Abstract
Event Conflicts
If two or more superclasses define events with the same name, then at least one of the following
must be true:
• The event ListenAccess and NotifyAccess attributes must be private
• The event has the same definition in all superclasses
– For example, all the superclasses inherited the event from a common superclass
∗
[www.mathworks.com/help/matlab/matlab_oop/subclassing-multiple-classes.html]
212
4.8.6
Documenting Classes
The doc command∗
The doc command can be used to display the information, that Matlab derives from the class
definition, in HTML format.
• For example, doc cDistantArea_simple yields
367
∗
[www.mathworks.com/help/matlab/matlab_prog/create-help-for-classes.html]
213
Class Diagram Viewer
• matlab.diagram.ClassViewer opens the Class Diagram Viewer
matlab.diagram.ClassViewer(’Classes’,["cArea_simple","cDistantArea_simple
"])•
adds cArea simple and cDistantArea simple to the Class Browser and viewer
cArea_simple
Properties
A: double
Iy: double
Iyz: double
Iz: double
Methods
cArea_simple
Iyz_hat
Iy_hat
Iz_hat
cDistantArea_simple
Properties
y_hat: double
z_hat: double
Methods
cDistantArea_simple
Iyz_hat
Iy_hat
Iz_hat
214
4.8.7
Object Arrays
Main Reference
• [10, ch. 10]
369
Object Array Initialization
• An object array can be initialized by using the repelem function
>> oArea_arr=repelem(cArea_simple(3.2),2,2)
oArea_arr =
2x2 cArea_simple array with properties:
A
Iy
Iz
Iyz
• An inferior way to initialize object array is by assigning the last element of the array [10,
ch. 10]
– By doing so, Matlab initializes the previous array elements by calling the class constructor with no arguments
– Therefore, the constructor must support being called with no input argument [code
4.7 on page 201]
– The remaining array elements can be assigned one by one
>> oArea1_arr(2,1)=cArea_simple(1.4)
oArea1_arr =
2x2 cArea_simple array with
properties:
A
Iy
Iz
Iyz
>> oArea1_arr(2,2)=cArea_simple(3.2)
oArea1_arr =
2x2 cArea_simple array with
properties:
A
Iy
Iz
Iyz
370
215
Properties of an Object Array
Referencing a property of an object array returns a comma–separated list [sec. 4.4.1] of the
property values.
>> oArea1_arr.A
ans =
[]
ans =
1.4000
ans =
[]
ans =
3.2000
>> oArea1_arr.Iy
ans =
0
ans =
0
ans =
0
ans =
0
>> oArea1_arr(1,1).A,oArea1_arr(2,1)
.A,oArea1_arr(1,2).A,oArea1_arr
(2,2).A
ans =
[]
ans =
1.4000
ans =
[]
ans =
3.2000
>> oArea1_arr(1,1).Iy,oArea1_arr(2,1)
.Iy,oArea1_arr(1,2).Iy,oArea1_arr
(2,2).Iy
ans =
0
ans =
0
ans =
0
ans =
0
• To convert the elements of a comma–separated list to a row vector, enclose it in []
>> reshape([oArea1_arr.Iy],
size(oArea1_arr))
ans =
0 0
0 0
>> [oArea1_arr.A]
ans =
1.4000 3.2000
>> [oArea1_arr.Iy]
ans =
0 0 0 0
• To create a cell array from the comma–separated list, enclose it in {}
>> {oArea1_arr.A}
ans =
1x4 cell array
{0x0 double} {[1.4000]} {0x0 double} {[3.2000]}
>> {oArea1_arr.Iy}
ans =
1x4 cell array
{[0]} {[0]} {[0]} {[0]}
216
4.8.7.1
Designing Methods to Handle Object Arrays
Methods (including the constructor) can be designed to handle object arrays.
372
Typical Class Designed to Handle Object Arrays
Code 4.9: cArea.m
if any(size(Iz_arr)~=A_arr_size),
error(’Iz_arr and A_arr must have
identical size.’),end
for n=1:N
oThisObject_arr(n).Iz=Iz_arr(n); %
#ok<AGROW>
end
classdef cArea %The file-name must be the same as
the class-name
%Methods of this class can handle object arrays
properties
A(1,1) double {mustBeNonnegative}
Iy(1,1) double {mustBeNonnegative}=0
Iz(1,1) double {mustBeNonnegative}=0
Iyz(1,1) double =0
end
end
if nargin==4
if any(size(Iyz_arr)~=A_arr_size),
error(’Iyz_arr and A_arr must
have identical size.’),end
for n=1:N
oThisObject_arr(n).Iyz=Iyz_arr(n);
%#ok<AGROW>
end
end
methods
% Constructor that can initialize object
array
function oThisObject_arr=cArea(A_arr,Iy_arr,
Iz_arr,Iyz_arr)
if nargin>=1
A_arr_size=size(A_arr);
dims_c=num2cell(A_arr_size);
oThisObject_arr=repelem(
oThisObject_arr,dims_c{:}); %
Initialize the object array
end
function Iy_hat_arr=Iy_hat(oThisObject_arr,
z_hat_arr)
Iy_hat_arr=reshape([oThisObject_arr.Iy]+[
oThisObject_arr.A].*z_hat_arr(:)
.’.^2,size(oThisObject_arr));
end
N=numel(A_arr);
for n=1:N
oThisObject_arr(n).A=A_arr(n);
end
% % Or alternatively
% A_carr=num2cell(A_arr);
% [oThisObject_arr.A]=deal(A_carr{:});
end
function Iz_hat_arr=Iz_hat(oThisObject_arr,
y_bar)
Iz_hat_arr=reshape([oThisObject_arr.Iz]+[
oThisObject_arr.A].*y_bar(:).’.^2,
size(oThisObject_arr));
end
if nargin>=2
if any(size(Iy_arr)~=A_arr_size),
error(’Iy_arr and A_arr must have
identical size.’),end
for n=1:N
oThisObject_arr(n).Iy=Iy_arr(n); %
#ok<AGROW>
end
end
function Iyz_hat_arr=Iyz_hat(oThisObject_arr,
y_bar,z_bar)
Iyz_hat_arr=reshape([oThisObject_arr.Iyz
]+[oThisObject_arr.A].*y_bar(:).’.*
z_bar(:).’,size(oThisObject_arr));
end
end
end
if nargin>=3
373
217
Typical Subclass Designed to Handle Object Arrays
Code 4.10: cDistantArea.m
error(’y_hat_arr and A_arr must
have identical size.’),end
y_hat_carr=num2cell(y_hat_arr);
[oThisObject_arr.y_bar]=deal(
y_hat_carr{:});
classdef cDistantArea < cArea %The file-name must be
the same as the class-name
%Methods of this class can handle object arrays
properties
y_bar(1,1) double
z_bar(1,1) double
end
if any(size(z_hat_arr)~=A_arr_size),
error(’z_hat_arr and A_arr must
have identical size.’),end
z_hat_carr=num2cell(z_hat_arr);
[oThisObject_arr.z_bar]=deal(
z_hat_carr{:});
methods
% Constructor that can initialize object
array
function oThisObject_arr=cDistantArea(A_arr,
Iy_arr,Iz_arr,Iyz_arr,y_hat_arr,
z_hat_arr)
if nargin==0 %This is needed to create
array of this class
superClassArgs={};
elseif nargin==6
superClassArgs={A_arr,Iy_arr,Iz_arr,
Iyz_arr};
else
error(’This class can be constructed
using zero or 6 inputs.’);
end
end
end
function Iy_hat=Iy_hat(oThisObject_arr)
Iy_hat=Iy_hat@cArea(oThisObject_arr,[
oThisObject_arr.z_bar]); %#ok<NODEF>
end
function Iz_hat=Iz_hat(oThisObject_arr)
Iz_hat=Iz_hat@cArea(oThisObject_arr,[
oThisObject_arr.y_bar]); %#ok<NODEF>
end
function Iyz_hat=Iyz_hat(oThisObject_arr)
Iyz_hat=Iyz_hat@cArea(oThisObject_arr,[
oThisObject_arr.y_bar],[
oThisObject_arr.z_bar]); %#ok<NODEF>
end
%Construct the superclass
oThisObject_arr@cArea(superClassArgs{:});
%Construct the subclass
if nargin~=0
A_arr_size=size(A_arr);
if any(size(y_hat_arr)~=A_arr_size),
end
end
Using a Constructor Designed to Initialize an Object Array
>> A_arr=[1,2,3;4,5,6]
A_arr =
1 2 3
4 5 6
>> Iyz_arr=zeros(2,3)
Iyz_arr =
0 0 0
0 0 0
>> Iy_arr=[7,8,9;10,11,12]
Iy_arr =
7 8 9
10 11 12
>> y_bar_arr=[1,2,3;4,5,6]
y_bar_arr =
1 2 3
4 5 6
>> Iz_arr=[13,14,15;16,17,18]
Iz_arr =
13 14 15
16 17 18
>> z_bar_arr=[7,8,9;10,11,12]
z_bar_arr =
7 8 9
10 11 12
>> oArea2_arr=cArea(A_arr,Iy_arr,
Iz_arr)
oArea2_arr =
2x3 cArea array with properties:
A
Iy
Iz
Iyz
>> oDistantArea_arr=cDistantArea(A_arr,
Iy_arr,Iz_arr,Iyz_arr,y_bar_arr,z_bar_arr)
oDistantArea_arr =
2x3 cDistantArea array with properties:
y_bar
z_bar
A
Iy
Iz
Iyz
218
Using Methods Designed to Handle Object Arrays
>> oArea2_arr.Iz_hat(5)
ans =
38 64 90
116 142 168
>> oArea2_arr.Iyz_hat(5,6)
ans =
30 60 90
120 150 180
>> oArea2_arr.Iz_hat(y_bar_arr)
ans =
14 22 42
80 142 234
>> oArea2_arr.Iyz_hat(y_bar_arr,z_bar_arr)
ans =
7 32 81
160 275 432
>> oDistantArea_arr.Iz_hat
ans =
14 22 42
80 142 234
>> oDistantArea_arr.Iyz_hat
ans =
7 32 81
160 275 432
376
Application 4.2 (Properties of a Composite Cross–sections).
=
O
O
A=
X
Ai
(4.2)
i
Qŷ =
Iŷ =
X
X
i
Qẑ =
i
i
Qŷ
z=
A
&
Qẑ
y=
A
Iy = Iŷ − A z
& Iẑ =
X
I¯z,i + Ai ŷi2
i
2
X
&
I¯y,i + Ai ẑi2
Ai ẑi
Iz = Iẑ − A y
& Iŷẑ =
X
Ai ŷi
I¯yz,i + Ai ŷi ẑi
(4.3)
(4.4)
(4.5)
i
2
Iyz = Iŷẑ − A y z
(4.6)
where:
• (ŷi , ẑi ) are the coordinates of the centroid of Ai
• I¯y,i , I¯z,i and I¯yz,i are the 2nd moments of area Ai around its centroidal axes
219
377
The cCmAr Class
The following class implements this problem.
Code 4.11: File cCmAr.m
classdef cCmAr %The file-name must be the same as the class-name
properties
oDistantArea_vec(1,:) cDistantArea %row vector
end
methods
% Constructor
function oThisCompositeArea=cCmAr(A_vec,Iy_vec,Iz_vec,Iyz_vec,y_hat_vec,
z_hat_vec)
if nargin==6
if ~isvector(A_vec),error(’A_vec must be a vector’);end
A_vec_size=size(A_vec);
if any(size(Iy_vec)~=A_vec_size),error(’A_vec and Iy_vec must have the
same size’),end
if any(size(Iz_vec)~=A_vec_size),error(’A_vec and Iz_vec must have the
same size’),end
if any(size(Iyz_vec)~=A_vec_size),error(’A_vec and Iyz_vec must have the
same size’),end
if any(size(y_hat_vec)~=A_vec_size),error(’A_vec and y_hat_vec must have
the same size’),end
if any(size(z_hat_vec)~=A_vec_size),error(’A_vec and z_hat_vec must have
the same size’),end
%Assign class properties
oThisCompositeArea.oDistantArea_vec=cDistantArea(A_vec,Iy_vec,Iz_vec,
Iyz_vec,y_hat_vec,z_hat_vec);
elseif nargin ~= 0
error(’This class can be constructed using zero or 6 inputs.’);
end
end
function A=A(oThisCompositeArea)
A=sum([oThisCompositeArea.oDistantArea_vec.A]);
end
function Qy=Qy(oThisCompositeArea)
Qy=sum([oThisCompositeArea.oDistantArea_vec.A].*[oThisCompositeArea.
oDistantArea_vec.z_bar]);
end
function Qz=Qz(oThisCompositeArea)
Qz=sum([oThisCompositeArea.oDistantArea_vec.A].*[oThisCompositeArea.
oDistantArea_vec.y_bar]);
end
function y_bar=y_bar(oThisCompositeArea)
y_bar=oThisCompositeArea.Qz/oThisCompositeArea.A;
end
function z_bar=z_bar(oThisCompositeArea)
z_bar=oThisCompositeArea.Qy/oThisCompositeArea.A;
end
220
function Iy_hat=Iy_hat(oThisCompositeArea)
Iy_hat=sum([oThisCompositeArea.oDistantArea_vec.Iy])+sum([
oThisCompositeArea.oDistantArea_vec.A].*[oThisCompositeArea.
oDistantArea_vec.z_bar].^2);
end
function Iz_hat=Iz_hat(oThisCompositeArea)
Iz_hat=sum([oThisCompositeArea.oDistantArea_vec.Iz])+sum([
oThisCompositeArea.oDistantArea_vec.A].*[oThisCompositeArea.
oDistantArea_vec.y_bar].^2);
end
function Iyz_hat=Iyz_hat(oThisCompositeArea)
Iyz_hat=sum([oThisCompositeArea.oDistantArea_vec.Iyz])+sum([
oThisCompositeArea.oDistantArea_vec.A].*[oThisCompositeArea.
oDistantArea_vec.y_bar].*[oThisCompositeArea.oDistantArea_vec.z_bar]);
end
function Iy=Iy(oThisCompositeArea)
Iy=oThisCompositeArea.Iy_hat-oThisCompositeArea.A*oThisCompositeArea.z_bar
.^2;
end
function Iz=Iz(oThisCompositeArea)
Iz=oThisCompositeArea.Iz_hat-oThisCompositeArea.A*oThisCompositeArea.y_bar
.^2;
end
function Iyz=Iyz(oThisCompositeArea)
Iyz=oThisCompositeArea.Iyz_hat-oThisCompositeArea.A*oThisCompositeArea.
y_bar*oThisCompositeArea.z_bar;
end
end
end
378
Example 5 (Composite Cross–Section).
For the shown cross–section, calculate A, y, z, Iy , Iz L76×51×12.7 C200×20.5
and Iyz .
S250×37.8
221
Solution
From tables of sec. ??, properties of cross–section component are identified as:
L76×51×12.7
C200×20.5
S250×37.8
(3)
C200×20.5
(2)
(1)
L76×51×12.7
(4)
S250×37.8
(7)
(6)
(5)
222
Code 4.12: File test cCmAr.m
y_bar=oSec1.y_bar
z_bar=oSec1.z_bar
Iy=oSec1.Iy
Iz=oSec1.Iz
Iyz=oSec1.Iyz
clc
clearvars
% All properties are in mm
% Problem 1.2-e
A1=1450;Iy1=0.278;Iz1=0.799;Iyz1=-tan(2*(
atan(.413)+pi/2))*(Iy1-Iz1)/2;y1
=(203/2+27.4);z1=(254/2+7.7-14.7);
A2=2610;Iy2=0.633;Iz2=15;Iyz2=0;y2=0;z2
=254/2+7.7-14.1;
A4=4810;Iy4=51.2;Iz4=2.8;Iyz4=0;y4=0;z4=0;
A_vec=[A1,A2,A1,A4,A1,A2,A1];
Iy_vec=[Iy1,Iy2,Iy1,Iy4,Iy1,Iy2,Iy1];
Iz_vec=[Iz1,Iz2,Iz1,Iz4,Iz1,Iz2,Iz1];
Iyz_vec=[Iyz1,Iyz2,-Iyz1,Iyz4,-Iyz1,-Iyz2,
Iyz1];
y_hat_vec=[y1,y2,-y1,y4,y1,-y2,-y1];
z_hat_vec=[z1,z2,z1,z4,-z1,-z2,-z1];
oSec1=cCmAr(A_vec,Iy_vec,Iz_vec,Iyz_vec,
y_hat_vec,z_hat_vec);
% Problem 1.2-f
% Dimensions are in mm
ind_vec=[1,2,4,6,7];
A_vec1=A_vec(ind_vec);
Iy_vec1=Iy_vec(ind_vec);
Iz_vec1=Iz_vec(ind_vec);
Iyz_vec1=Iyz_vec(ind_vec);
y_hat_vec1=y_hat_vec(ind_vec);
z_hat_vec1=z_hat_vec(ind_vec);
oSec2=cCmAr(A_vec1,Iy_vec1,Iz_vec1,
Iyz_vec1,y_hat_vec1,z_hat_vec1);
A=oSec2.A %#ok<*NOPTS>
y_bar=oSec2.y_bar
z_bar=oSec2.z_bar
Iy=oSec2.Iy
Iz=oSec2.Iz
Iyz=oSec2.Iyz
A=oSec1.A %#ok<*NASGU,*NOPTS>
>> test_cCmAr
oSec1 =
cCompositeArea with properties:
oDistantArea_vec: [1x7 cDistantArea]
A =
15830
y_bar =
0
z_bar =
1.8385e-15
Iy =
1.5944e+08
Iz =
9.6368e+07
Iyz =
0
379
Laboratory
• Implement laboratory 16 on page 229
380
4.8.7.2
Arrays of Objects of Different Classes
Heterogeneous Class Arrays
Refer to:
• www.mathworks.com/help/matlab/matlab_oop/heterogeneous-arrays.html
• www.mathworks.com/help/matlab/matlab_oop/heterogeneous-superclassconstructors.html
381
223
Invoking a Method of a Heterogeneous Array∗
To invoke a method on a heterogeneous array, the common superclass of the array must define
or inherit this method as Sealed.
• This ensures that the same method definition exists for all elements of the array irrespective
of their subclass
∗
[www.mathworks.com/help/matlab/matlab_oop/heterogeneous-arrays.html#bun20km]
224
4.8.8
Handle Classes
A is a value class
A is a handle class
A
A
Class
Instanse 1
Class
Instanse 1
>> B = A;
>> B = A;
A
B
A
Class
Instanse 1
B
Class
Instanse 1
Class
Instanse 1
Same as ordinary functions, Matlab passes input arguments to ordinary methods by value [sec.
4.5.3.1].
• For a method to modify a property of an object,
– and since the object itself is one of the input arguments to the method,
– then any modifications to the property will be lost
– This is the disadvantage of the so called “value classes”
• This disadvantage is solved in the so called “handle class”
– You can think of a handle class as a pointer to the class
– Objects of a handle class is passed by handle∗
– Thus, when a method modifies a property, the modification will be preserved
383
∗
In Fortran and C++ terminology, this is called “pass by reference”. In C terminology, this is achievable through
“pass by pointer”.
225
Sample Value Class
Sample Handle Class
Code 4.13: “cValueClass” Class
Code 4.14: “cHandleClass” Class
classdef cValueClass
properties
prop1
end
classdef cHandleClass < handle
properties
prop1
end
methods
%Constructor
function oThisClass=cValueClass(
value)
oThisClass.prop1=value;
end
methods
%Constructor
function oThisClass=cHandleClass(
value)
oThisClass.prop1=value;
end
%This method will not work as
expected
function setProp1(oThisClass,
value)
oThisClass.prop1=value;
end
%This method works as expected
function setProp1(oThisClass,
value)
oThisClass.prop1=value;
end
end
end
end
end
>> oValueClass=cValueClass(5);
>> oValueClass.prop1
ans =
5
>> oValueClass.prop1=10
oValueClass =
cValueClass with properties:
prop1: 10
>> oValueClass.setProp1(7);
>> oValueClass.prop1
ans =
10
4.8.9
>> oHandleClass=cHandleClass(5);
>> oHandleClass.prop1
ans =
5
>> oHandleClass.prop1=10
oHandleClass =
cHandleClass with properties:
prop1: 10
>> oHandleClass.setProp1(7);
>> oHandleClass.prop1
ans =
7
More Information
OOP in Matlab versus other Languages
• www.mathworks.com/help/matlab/matlab_oop/matlab-vs-other-oolanguages.html
226
4.9
Further Topics
• Animation
• Toolboxes
• Parallel computing
– Usually Matlab is very up to date
• Simulink
– Usually you will find recent/robust/mature/. . .
methods/algorithms
• GUI
– Most of the toolbox functions are
open source
– Building sophisticated GUI’s using
Matlab is not recommended
• Matlab APPS tab
• Sparse matrices
– Check the “APPS” tab for several
toolbox–based applications
– Refer to www.mathworks.com/help/
matlab/sparse-matrices.html
• M2HTML: Documentation System for
Matlab in HTML
– Refer to www.artefact.tk/
software/matlab/m2html
387
Project idea 8 (Matlab Instrument Control Toolbox)
• Interface with an instrument using Matlab
• Well document your experience
• Prepare a tutorial
388
227
Further Learning
The following Stanford University course by “Matthew J. Zahr” is very comprehensive.
• CME 292: Advanced Matlab for Scientific Computing, accessible at http://web.
stanford.edu/~mzahr/cme292.html
389
4.10
FOSS Alternatives
Clone alternatives
Non–clone alternatives
• GNU–Octave
• Python language
– Strong and mature alternative
• Julia language
– Better suited to scientific computing
• Scilab
• SageMath
228
4.11
Laboratory Work
Laboratory 7 (Creating Matlab Variables)
Laboratory 12 (2D Graphing–I)
• Implement problems (4.2) to (4.4)
• Implement problem (4.17)
Laboratory 13 (2D Graphing–II)
Laboratory 8 (Create Matlab Script)
• Implement problems (4.18), (4.19) &
(4.20)
• Implement problem (4.7)
Laboratory 9 (Code Improvement)
Laboratory 14 (2D & 3D Graphing)
• Implement problems (4.8) & (4.9)
• Implement problem (4.22)
Laboratory 10 (Create Matlab Function)
Laboratory 15 (3D Graphing)
• Implement problems (4.10) & (4.11)
Laboratory 11 (Root–Finding)
• Implement problems (4.23) & (4.24)
Laboratory 16 (OOP)
• Implement problems (4.12), (4.13)
and (4.14)
229
• Implement problems (4.29), (4.30),
(4.31), (4.32) and (4.33)
4.12
Problems
4.1. Write Matlab expressions to evaluate the following formulae using the minimum number
of parentheses “()”.
Assume all variables are scalars
Do not use the “\” operator
r hG
(a)
r + hG
(b) T0 + a (hG − hG0 )
g0
− aR
T
(c) p0
T0
p
1 − ζ2
2
2
x0 + ωv0n
(j) ωn
r
(k)
p
x20 ωn2 + 2ζωn x0 v0 + v02
p
(l)
ωn 1 − ζ 2
g0 (hG −hG0 )
−
RT0
p
(d) p0 e
2
√
ζ − 1 − ζ ωn x0 − v0
(e) γRT
p
(m)
2ω
ζ2 − 1
n
(f) A sin (ωn t + θ)
x
ω
−ζωn t
0
n
−1
(g) B e
sin (ωd t + φ)
(n) tan
v0
−ωn t
(h) e
x0 + (ωn x0 + v0 ) t
!
p
2
√
√
x
ω
1
−
ζ
0 n
−1
2
2
(i) e−ζωn t Ce−ωn ζ −1 t + Deωn ζ −1 t (o) tan
ζωn x0 + v0
4.2. Create the following scalar variables (i and j are the imaginary number)
(a) a = 10
(b) b = 2.5 × 106
4.3. Create the following vectors
h
i
(a) 3.14 15 9 26
8
2.71
(b)
28
182
(c) c = 2 + 3i,
(c)
h
(d) d = ej2π/3
5 4.8 . . . −4.8 −5
i
(numbers from 5 to -5 in increments of
-0.2)
(d) Hello (string)
4.4. Create the following matrices
2 ··· 2
(a) ... . . . ...
0 0
.
0 .. 0
(b) 0 0 5
.. . . . . . .
.
0 0 ...
2 ··· 2
1
...
..
.
..
.
..
.
0
0
0
..
.
0
1
(diagonal matrix with the diagonal
1 2 3 4 5 4 3 2 1 )
(9 × 9 matrix of 2’s)
Hint use the diag built–in function
230
1
2
(c) 3
..
.
10
11 . . . 91
12 . . . 92
13 . . . 93
..
..
..
.
.
.
20 . . . 100
N aN N aN N aN N aN
(d) N aN N aN N aN N aN
N aN N aN N aN N aN
Hint use the reshape built–in function
(e) 5 × 3 matrix of random integers with
values on the range −3 to 3
Hint use the rand and round built–in
function
4.5. For the following expressions;
a is a scalar
b is a scalar
a row is 1 × 3 array
b row is 1 × 3 array
b col is 3 × 1 array
d mat is 2 × 5 array
c mat is 3 × 2 array
Determine the dimensions of the result of the following expressions. (Note that some
expressions may fail to be evaluated)
(a) a row*a row
(h) b col*d mat
(o) d mat*c mat
(b) a row*b col
(i) c mat*a row
(p) d mat*d mat
(c) a row*c mat
(j) c mat*b col
(d) a row*d mat
(k) c mat*c mat
(e) b col*a row
(l) c mat*d mat
(f) b col*b col
(m) d mat*a row
(s) a*b*a row.*b row
(g) b col*c mat
(n) d mat*b col
(t) a.*b.*a row*b row
(q) a*b*a row*b row
(r) a.*b.*a row.*b row
(u) [a row a row a row]*[b row b row b row]
(v) [a row a row a row].*[b row b row b row]
(w) [a row,a row,a row]*[b row,b row,b row]
(x) [a row,a row,a row].*[b row,b row,b row]
(y) [a row;a row;a row]*[b row;b row;b row]
(z) [a row;a row;a row].*[b row;b row;b row]
4.6. Regarding problem (4.1)
(i) t, hG , T and p are M × 1 column vectors
(ii) ζ is 1 × N row vector
(iii) all other variables are scalars
(a) rewrite the expressions to evaluate all the formulae
(b) determine the dimensions of the result of each expression
231
4.7. Create a script to calculate and plot the altitude (h), temperature (T ), pressure (p), density
(ρ) and speed of sound (a) of the International Standard Atmosphere (ISA) versus the
geopotential altitude (hG ), given that
h (hG ) =
r hG
r + hG
(4.7)
(
T0 + a0 (hG − hG0 ) , : gradient
T (hG ) =
T0
, : isothermal
− g0
a0 R
T
p
, : gradient
0
T0
p (hG ) =
g0 (hG −hG0 )
p0 e− RT0
, : isothermal
p
ρ=
RT
p
a = γRT
T0 (˚K)
288.16
216.66
216.66
282.66
282.66
165.66
165.66
(4.11)
p0 (N/m2 )
101330
22632
2488.6
120.44
58.321
1.0094
0.10444
a0 (˚K/m)
−0.0065
0.003
−0.0045
0.004
Hints:
• Use matrix concatenations
• Display hG & h in km
• Display T in ℃
• Display p in bar
• Display a in km/h
• Begin your script with
clc
clearvars
close all
120
100
80
60
40
20
0
0
20
40
232
60
(4.9)
(4.10)
g0 = 9.80665 m/s2 , R = 287.04, r = 6.356766 × 106 m, γ = 1.4 and
hG0 (m)
0
11, 000
25, 000
47, 000
53, 000
79, 000
90, 000
105, 000
(4.8)
80
100
120
120
120
100
100
80
80
60
60
40
40
20
20
0
-100
-50
0
900
0
120
120
100
100
80
80
60
60
40
40
20
20
0
1000
1100
1200
0.5
1
1.5
0
0
0.5
1
4.8. Improve problem (4.7) for maintenance
4.9. Modify your script to use only the following inputs
233
0
hG0 (m)
0
11, 000
25, 000
47, 000
53, 000
79, 000
90, 000
105, 000
T0 (˚K)
288.16
p0 (N/m2 )
101330
a0 (˚K/m)
−0.0065
0.003
−0.0045
0.004
4.10. Improve problem (4.7) for readability by using the following function.
function [h_vec,T_vec,p_vec,rho_vec,a_vec]=isa_prop(h_G_vec)
Hints You may use the following script to call your function and plot the ISA properties
Code 4.15: ISA main script.m
clc
clearvars
close all
h_G_vec= %Complete this. Row vector or column vector of 10000 point
tic; %To measure the execution time
[h_vec,T_vec,p_vec,rho_vec,a_vec]=isa_prop(h_G_vec);
toc %To measure the execution time
figure;
%plot h_vec & h_G_vec
xlabel(’$h$ (km)’,’interpreter’,’latex’)
ylabel(’$h_{G}$ (km)’,’interpreter’,’latex’)
figure;
tiledlayout(1,2)
nexttile
%plot T_vec & h_G_vec
xlabel(’$T$ (\r{ }C)’,’interpreter’,’latex’)
ylabel(’$h_{G}$ (km)’,’interpreter’,’latex’)
nexttile
%plot a_vec & h_G_vec
xlabel(’$a$ (km/h)’,’interpreter’,’latex’)
ylabel(’$h_{G}$ (km)’,’interpreter’,’latex’)
figure;
tiledlayout(1,2)
nexttile
%plot p_vec & h_G_vec
xlabel(’$p$ (bar)’,’interpreter’,’latex’)
ylabel(’$h_{G}$ (km)’,’interpreter’,’latex’)
nexttile
%plot rho_vec & h_G_vec
xlabel(’$\rho$ (kg/m\textsuperscript{3})’,’interpreter’,’latex’)
ylabel(’$h_{G}$ (km)’,’interpreter’,’latex’)
234
4.11. Improve problem (4.10) for maintenance
4.12. Write a function to find the root of an arbitrary function using the Secant method∗
f (x)
xn = xn−1 − f xn−1
xn−1 − xn−2
f xn−1 − f xn−2
f (xn-2)
f (xn-1)
xn
xn-1
x
xn-2
Test your function by finding the roots of x2 − x − 8 using x0 = 2 & x1 = 3
You may use the MainScript.m [code 4.16] script to call your function
Convergence of the Secant method
The secant method will converge to the root if the initial values x0 and x1 are sufficiently
close to the root.
d
f (x) is small within the interval
• If dx
[x0 , x1 ], this method may not converge
f (x)
x0
x3
x2
x1
x
4.13. Write a function to find the root of an arbitrary function using the Bisection method†
• Beginning with two points before and after the
root,
xb + xa
xn =
2
f (x)
xb1
∗
†
[https://en.wikipedia.org/wiki/Secant_method]
[https://en.wikipedia.org/wiki/Bisection_method]
235
xb2 xb3
xa2
xa1
x
• Update xb & xa based on the condition
sign f (xn ) = sign f (xb ) =
true
=⇒ xb = xn
false
=⇒ xa = xn
• Repeat till convergence
Test your function by finding the roots of x2 − x − 8 using xb = 3 & xa = 4
You may use the MainScript.m [code 4.16] script to call your function
Convergence of the BiSection method
The method is guaranteed to converge if f (x) is continuous on the interval [xb , xa ].
• However, its convergence is slower than the secant method
4.14. Write a function to find the root of an arbitrary function using the False position method∗ .
• The false position method takes the best of both the secant and bisection methods
• Beginning with two points before and after the
root, same as the secant method,
xn = xb − f (xb )
f (x)
xb − xa
f (xb ) − f (xa )
xa1
xa2
xb2
• Same as the bisection method, update xb & xa based on the condition
sign f (xn ) = sign f (xb ) =
true
=⇒ xb = xn
false
=⇒ xa = xn
• Repeat till convergence
Test your function by finding the roots of x2 − x − 8 using xb,0 = 3 & xa,0 = 4
You may use the MainScript.m [code 4.16] script to call your function
∗
[https://en.wikipedia.org/wiki/False_position_method]
236
xb1 x
Convergence of the False Position method
f (x)
• Same as the secant method, this method converges very
d
fast unless dx
f (x) is small
10
• Same as the bisection method, this method is guaranteed
to converge if f (x) is continuous
5
0
Code 4.16: MainScript.m
fn_handle(x)
clc
clearvars
N_max=1000;
tic
for n=1:N_max
x=secant(fn_handle,x_0,x_1);
end
toc
fn_handle=@(x) (x^2-x-8); %Handle of
the function to be solved
% Secant Method
x_0=2; %1st intial guess
x_1=3; %2nd intial guess
x=secant(fn_handle,x_0,x_1)
fn_handle(x)
1.0
x
tic
for n=1:N_max
x=bisection(fn_handle,x_b,x_a);
end
toc
% Bisection method
x_b=3; %point before the root
x_a=4; %point after the root
x=bisection(fn_handle,x_b,x_a)
fn_handle(x)
tic
for n=1:N_max
x=falsePosition(fn_handle,x_b,x_a);
end
toc
% False position method
x=falsePosition(fn_handle,x_b,x_a)
4.15. Survey Brent’s root–finding method (https://en.wikipedia.org/wiki/Brent’s_
method)
4.16. Explore the source code of Matlab’s “fzero” function and determine:
(a) the root–finding method used
(c) any other useful information
(b) where this method is explained
237
4.17. Consider the Single Degree Of Freedom (SDOF) damped mass spring system shown below
x(t)
• Dividing by m yields
k
f (t)
m
ẍ(t) + 2ζωn ẋ(t) + ωn2 x(t) =
f (t)
m
c
where
or
d
r
ωn ≡
The equation of motion can be written as
mẍ(t) + cẋ(t) + kx(t) = f (t)
k
m
c
cc
√
cc ≡ 2 km
ζ≡
• For free vibration, f (t) = 0, the solution of the above differential equation is given
to you as
A sin (ωn t + θ)
,: ζ = 0
−ζωn t
sin (ωd t + φ)
,: 0 < ζ < 1
B e
x(t) = e−ωn t x0 + (ωn x0 + v0 ) t
,: ζ = 1
√
√
2
2
−ζωn t
,: ζ > 1
Ce−ωn ζ −1 t + Deωn ζ −1 t
e
where x0 is the initial displacement, v0 is the initial velocity and
p
2−1−ζ ω x −v
ζ
p
n 0
0
p
C≡
ωd ≡ ωn 1 − ζ 2
s
2ωn ζ 2 − 1
2
v0
A ≡ x20 +
ωn
p
p
2−1+ζ ω x +v
ζ
2 2
2
n 0
0
x0 ωn + 2ζωn x0 v0 + v0
p
p
B≡
D≡
ωn 1 − ζ 2
2ωn ζ 2 − 1
× × MISLEADING × ×
−1
θ ≡ tan
x0 ω n
v0
× × MISLEADING × ×
and
p
× × MISLEADING × ×
φ ≡ tan−1
1 − ζ2
x0 ω n
ζωn x0 + v0
!
× × MISLEADING × ×
(a) Create a Matlab function called “SDOF Free Response Visc” to calculate x(t) as
follows
function x_vec=SDOF_Free_Response_Visc(w_n,zeta,x0,v0,t_vec)
• w n, zeta, x0 and v0 are scalars
• t vec is a vector
238
Common mistake
• Use the “atan2” function for calculating θ and φ
• “atan2(y,x)” function uses y and x values to determine the correct angle
quadrant. Hence it returns angles in the closed interval [−π, π]
• “atan” function on the other hand returns angles in the range [− π2 , π2 ]
(b) Test your function by using it to plot the following figure
1
0.8
0.6
0.4
0.2
0
-0.2
-0.4
-0.6
-0.8
-1
0
0.2
0.4
0.6
0.8
1
1.2
1.4
1.6
1.8
2
You may use the FreeResponse main script.m [code 4.18] script as a guide
Code 4.18: FreeResponse main script.m
figure
hold on
for zeta=zeta_vec
x_vec=SDOF_Free_Response_Visc(w_n,
zeta,x0,v0,t_vec);
% plot x_vec versus t_vec/T_n
end
clc
clearvars
close all
x0=-1;
v0=0;
w_n=1;
f_n=w_n/2/pi;
T_n=1/f_n;
zeta_vec=[0,.1,.2,.4,1/sqrt(2),1,2];
legend_str_vec="$\zeta = "+zeta_vec+’$’
;
legend_str_vec(5)="$\zeta=1/\sqrt{2}$";
title(’$x(t)$ for $\omega_{n}=1$,$x_
{0}=-1$ and $v_{0}=0$’,’interpreter
’,’latex’);
xlabel(’$t/T_{n}\qquad,:T_{n}=1/f_{n
}=2\pi/\omega_{n}$’,’interpreter’,’
latex’);
% plot the legend
t_vec= ;%Create 1000 point
239
4.18. For the system of problem (4.17), for the harmonic input
f (t) = F0 sin(Ωt)
the response for x0 = v0 = 0, is given to you as
F0
t cos (ωn t)
,: ζ = 0 & r = 1
− 2mω
n
F0
− 2ζr cos (Ωt) + 1 − r2 sin (Ωt)
otherwise
2
2
x(t) = mωn2 (1−r2 ) +(2ζr)
!
−ζωn t
2
2 sin(ωd t)
+r
e
2ζ
cos
(ω
t)
+
ω
2ζ
−
1
+
r
d
n
ωd
where
r≡
Ω
ωn
ωd ≡ ωn
p
1 − ζ2
(a) Create a Matlab function to calculate x(t) as follows
function x_vec=SDOF_Harmonic_Response_Visc(w_n,zeta,F0_by_m,r,
t_vec)
(b) Plot x(t) versus t on the left axis, and f (t) versus t on the right axis, for ωn = 3,
F0 = 1, m = 0.5, ζ = 0 and r = 0.2, 0.9, 1, 1.1 & 2
(c) Format your plot to look exactly like the following figure
• x(t) axis limits are tightly fitted
• f (t) axis limits are set to F 0*[-1,1]
• The
shared
title
is
written
in
LATEX
as
"Harmonic response for $\zeta = "+zeta+’$’
• Remove the horizontal axis tick labels of all tiles other than the bottom one using
the command set(gca,’XTickLabel’,[])
• Create x(t) axis label using LATEX as ’$x(t)$ due to $f(t)$’
• Create f (t) axis label using LATEX as "$f(t),:r="+r_vec(n)+’$’
240
1
0.2
0.1
0.5
0
0
-0.1
-0.5
-0.2
2
-1
1
1
0.5
0
0
-1
-0.5
-2
-1
1
10
0.5
5
0
0
-5
-0.5
-10
-1
1
2
1
0.5
0
0
-1
-0.5
-2
-1
1
0.1
0.5
0
0
-0.1
-0.5
0
5
10
15
20
241
25
30
35
-1
40
4.19. Parameterize the main script of problem (4.18) by converting it to a function with the
following header
function plotHarmonicResponse(w_n,F_0,m,zeta,r_row,t_col)
• Use this function to create the following figure using ζ = 0.05
1
0.2
0.1
0.5
0
0
-0.1
-0.5
-0.2
-1
1
1
0.5
0.5
0
0
-0.5
-0.5
-1
-1
1
2
1
0.5
0
0
-1
-0.5
-2
-1
1
1
0.5
0.5
0
0
-0.5
-0.5
-1
-1
1
0.1
0.5
0
0
-0.5
-0.1
0
5
10
15
20
242
25
30
35
-1
40
4.20. Modify the codes of problem (4.19) to link x(t) limits of all tiles.
• Use the modified codes to create the following figures
1
10
0.5
5
0
0
-5
-0.5
-10
-1
1
10
0.5
5
0
0
-5
-0.5
-10
-1
1
10
0.5
5
0
0
-5
-0.5
-10
-1
1
10
0.5
5
0
0
-5
-0.5
-10
-1
1
10
0.5
5
0
0
-5
-0.5
-10
0
5
10
15
20
25
30
35
-1
40
2
1
1
0.5
0
0
-1
-0.5
-2
2
-1
1
1
0.5
0
0
-1
-0.5
-2
-1
1
2
1
0.5
0
0
-1
-0.5
-2
2
-1
1
1
0.5
0
0
-1
-0.5
-2
-1
1
2
1
0.5
0
0
-1
-0.5
-2
0
5
10
15
20
243
25
30
35
-1
40
4.21. Use the following hack to improve the ylabels as shown in the following figure?
ax_hidden=axes(tile1,’Visible’,’off’);
ax_hidden.Layout.TileSpan=[N,1];
yyaxis(ax_hidden, ’left’);
ylabel("$x(t)$ due to $f(t)$",’interpreter’,’latex’,’FontSize’,12,’Visible’,’on’)
;
yyaxis(ax_hidden, ’right’);
ylabel(["";"";"$f(t)=F_{0}\sin(\Omega t)=F_{0}\sin(r\omega_{\mathrm{n}}t)\quad,:r
\equiv\frac{\Omega}{\omega_{\mathrm{n}}}$"],’interpreter’,’latex’,’FontSize’
,12,’Visible’,’on’);
1
10
0.5
5
0
0
-5
-0.5
-10
-1
1
10
0.5
5
0
0
-5
-0.5
-10
-1
1
10
0.5
5
0
0
-5
-0.5
-10
-1
1
10
0.5
5
0
0
-5
-0.5
-10
-1
1
10
0.5
5
0
0
-5
-0.5
-10
0
5
10
15
20
244
25
30
35
-1
40
2
1
1
0.5
0
0
-1
-0.5
-2
2
-1
1
1
0.5
0
0
-1
-0.5
-2
-1
1
2
1
0.5
0
0
-1
-0.5
-2
2
-1
1
1
0.5
0
0
-1
-0.5
-2
-1
1
2
1
0.5
0
0
-1
-0.5
-2
0
5
10
15
20
25
30
35
-1
40
4.22. Consider the damped mass spring system of problem (4.17). The Frequency Response
Function (FRF) of the system is given to you as
H(ω) =
k 1−
ω
ωn
1
2
+ 2iζ ωωn
Note that H(ω) is complex.
(a) Create a Matlab function to calculate H(ω) as follows
function H_cols=SDOF_FRF(k,w_n,w_col,zeta_row)
where k, w n are scalars, w col is a column vector and zeta row is a row vector
(b) Create a script that calls the above function and plots figures exactly like the following
√
• Use ωn = 2, k = 3, ζ = 0.1, 0.15, 0.2, 0.3, 0.5, 1/ 2, 1, 2
• Use Matlab functions “real” and “imag” to calculate the real and imaginary
parts of a complex number
• Use Matlab functions “abs” and “angle” to calculate the magnitude and phase
(in radians) of a complex number
• Figure titles is written in LATEX as "$H(\omega)$ for $\omega_{\mathrm{n}}="+w_n+’$
• ω/ωn is written in LATEX as ’$\omega/\omega_{\mathrm{n}}$’
• <(H(ω)) is written in LATEX as ’$\Re(H(\omega))$’
• =(H(ω)) is written in LATEX as ’$\Im(H(\omega))$’
245
• ζ = 0.1 is written in LATEX as ’$\zeta=0.1$’
√
• ζ = 1/ 2 is written in LATEX as ’$\zeta=1/\sqrt{2}$’
• For the 3D curve
– plot ω/ωn versus < H(ω) and =(H(ω)) (along x, y & z axes respectively)
– adjust the data aspect ratio of < H(ω) same as =(H(ω))
– orient the plot using the command “view(30,20)”
• For |H| and ∠H curves (bode plot)
– the |H(ω)| curve is three times longer than that of ∠H(ω)
– plot ∠H(ω) in degrees
– |H(ω)| is written in LATEX as ’$|H(\omega)|$’
– ∠H(ω) (deg.) is written in LATEX as ’$\angle H(\omega)$ (deg.)’
– Make sure you format ∠H(ω) axis as in the shown figure
– Remove the x tick labels of the |H(ω)| curve
• For <(H(ω)) and =(H(ω)) curves
– Remove the x tick labels of the <(H(ω)) curve
• For < H(ω) versus =(H(ω)) curve (Nyquist plot)
– adjust the data aspect ratio of < H(ω) same as =(H(ω))
You may use the SDOF FRF MainScript.m [code 4.22] script as a guide
Code 4.22: SDOF FRF MainScript.m
%%Complete here
H_cols=SDOF_FRF(k,w_n,w_col,zeta_row);
figure; %For the 3d curve
plot3(w_col/w_n,real(H_cols),imag(H_cols))
view(30,20)
%%Complete here
figure; %For the real and imaginary curves vs w/w_n
tile2=tiledlayout(2,1,’TileSpacing’,’tight’);
nexttile %For real(H) vs w/w_n
%%Complete here
nexttile %For imag(H) vs w/w_n
%%Complete here
figure; %For the absolute and angle curves vs w/w_n
tiledlayout(4,1,’TileSpacing’,’tight’);
nexttile(1,[3,1]) %For abs(H) vs w/w_n
%%Complete here
246
nexttile(4) %For angle(H) vs w/w_n
%%Complete here
figure; %For the real vs imaginary
%%Complete here
0
-0.5
-1
-1.5
1
-2
0
0.5
0
1
1.5
2
2.5
247
-1
1
0.5
0
-0.5
-1
0
-0.5
-1
-1.5
-2
0
0.5
1
1.5
2
2.5
-180
0
0.5
1
1.5
2
2.5
1.8
1.6
1.4
1.2
1
0.8
0.6
0.4
0.2
0
0
-90
248
0
-0.2
-0.4
-0.6
-0.8
-1
-1.2
-1.4
-1.6
-0.5
0
0.5
1
4.23. Create a figure identical to the following, representing a nozzle velocity magnitude, where
• Nozzle total angle α = 10◦
• Velocity magnitude
• Nozzle start radius r1 = 5
1
θ
v = 2 sinc 4
r
α
• Nozzle end radius r2 = 10
Note that
• α and θ in the above equation are in radians
• aspect ratio of the x and y axes should be the same for proper display
Hint: Use “pcolor” Matlab function
Nozzle flow; velocity distribution
0.03
0.5
0.02
0
0.01
-0.5
0
5
6
7
8
9
4.24. Improve the figure of problem (4.23) for file size (and consequently RAM requirements,
. . . ) to obtain the following figure
249
Nozzle flow; velocity distribution
0.03
0.5
0.02
0
0.01
-0.5
0
5
6
7
8
9
Hint use the contourf command
4.25. Write a command to export figure window number 5 to an emf file with a resolution of
600 dpi
4.26. Create a function that export a given figure window to pdf with a given name using 600
dpi
• Your function should include options for
– fitting the figure window to portrait A4 paper
– fitting the figure window to landscape A4 paper
– no fitting
– ...
4.27. Create a function that export a given figure window to emf picture with a given name using
600 dpi
• Your function should include options for
– fitting the figure window to portrait A4 paper
– fitting the figure window to landscape A4 paper
– no fitting
– ...
4.28. For the NACA 23021 airfoil defined by the following parameters, generate the following
external C–algebraic–grid needed to calculate the external flow over the airfoil
rLE = 4.85e − 2 m & αLE = 17◦
xc × 100 (m)
yu × 100 (m)
−yl × 100 (m)
0
0
0
xc × 100 (m)
yu × 100 (m)
−yl × 100 (m)
40
12.05
8.83
1.25
0.22
2.08
2.5
1.53
3.14
50
11.8
8.14
5
2.76
4.52
7.5
5.05
5.55
10
7.09
6.32
15
8.9
7.51
20
10.4
8.3
25
11.49
8.76
60
11.19
7.07
70
10.03
5.72
80
9.13
4.13
90
7.93
2.3
95
6.14
1.3
100
4.87
0.22
250
30
12.06
8.95
1
0.8
0.6
0.4
0.2
0
−0.2
−0.4
−0.6
−0.8
−0.5
0
0.5
251
1
1.5
2
4.29. Re–implement example 5 on page 221 by considering the y–symmetry of the cross–
section.
Hints
• Don’t convert the units to m.
• If ŷ is an axis of symmetry;
– many properties vanish
Qŷ = 0
z=0
z = ẑ
Iy = Iŷ
Iyz = Iŷẑ = 0
• Do not repeat any piece of code already written in code 4.11 on page 220
– only half the cross–section can be
used to calculate
A=2
X
Ai
half
half
Qẑ = 2
X
Iŷ =
X
X
I¯y,i + Ai zi2
Iẑ =
X
X
2Ai ŷi
half
I¯z,i + Ai ŷi 2
2I¯y,i + 2Ai zi2
half
half
Iẑ = 2
Qẑ =
X
Ai ŷi
half
Iŷ = 2
– To do so, you may alternatively
use
X
A=
2Ai
half
– areas having zi = 0 need to be
halved [example 6 on page 569]
2I¯z,i + 2Ai ŷi 2
half
– That is, use double the properties
of the non–halved areas
– Thus, you can use the existing
code without modification
4.30. Re–implement example 5 on page 221 by considering the z–symmetry of the cross–
section.
Hints
• Use the inheritance hierarchy diagram
on page 255 as a guide
• Don’t convert the units to m.
• Use abstract class
252
4.31. Re–implement example 5 on page 221 by considering the double symmetry of the cross–
section.
Hints
• Don’t convert the units to m.
• For double symmetry;
– many properties vanish
Qẑ = 0
y=0
y = ŷ
Iz = Iẑ
Iyz = Iŷẑ = 0
Qŷ = 0
z=0
z = ẑ
Iy = Iŷ
– only quarter the cross–section can
be used to calculate
A=4
X
Ai
quarter
Iŷ = 4
X I¯y,i + Ai zi2
Iẑ = 4
– To do so, you may alternatively
use
X
4Ai
A=
quarter
Iŷ =
quarter
X • Do not repeat any piece of code already written in code 4.11 on page 220
I¯z,i + Ai ŷi 2
4I¯y,i + 4Ai zi2
quarter
Iẑ =
quarter
X X 4I¯z,i + 4Ai ŷi 2
quarter
– areas having either yi = 0 or zi =
0 need to be halved [example 7 on
page 571]
– areas having both yi = 0 and zi =
0 need to be quartered
– That is, use 4–times the properties of the non–quartered areas
(take care of the halved areas)
– Thus, you can use the existing
code without modification
4.32. Re–implement problem 4.31 without repeating any piece of code already written in the
codes of problems 4.29 and 4.30
• Use the inheritance hierarchy diagram on page 255 as a guide
253
4.33. For the shown anti–symmetric cross–section,
calculate A, y, z, Iy , Iz and Iyz .
L76×51×12.7
C200×20.5
S250×37.8
Hints
• Don’t convert the units to m.
• For anti–symmetry;
– center of symmetry coincides
with the centroid
– many properties vanish
Qẑ = 0
y=0
y = ŷ
Iz = Iẑ
Iyz = Iŷẑ
Qŷ = 0
z=0
z = ẑ
Iy = Iŷ
– Any of the y–anti–symmetric or
z–anti–symmetric halves can be
used to calculate
A=2
X
– To do so, you may alternatively
use
X
2Ai
A=
half
Iŷ =
X
Iẑ =
X
Iŷẑ =
X
Ai
X
I¯y,i + Ai zi2
X
Iŷẑ = 2
X
I¯z,i + Ai yi2
2I¯z,i + 2Ai yi2
half
half
Iẑ = 2
2I¯y,i + 2Ai zi2
half
half
Iŷ = 2
• Use code 4.11 on page 220 and do not
repeat any piece of code
2I¯yz,i + 2Ai yi zi
half
half
I¯yz,i + Ai yi zi
half
– If you choose y–anti–symmetry,
areas having zi = 0 need to be
halved [example 8 on page 573]
– Similarly, if you choose z–anti–
symmetry, areas having yi = 0
need to be halved
254
– That is, use double the properties
of the non–halved areas
– Thus, you can use the existing
code without modification
• Do not repeating any piece of code already written in the codes earlier problems
• Use the following inheritance hierarchy diagram as a guide
cCmAr
cCmAr_Sym_z_Abst
cCmAr_Sym_y
cCmAr_Sym_z
cCmAr_ASym_z
cCmAr_Sym_yz
401
255
This page is intentionally left blank!
256
Part 5
Serious Programming
5.1
Programming Languages
Top Programming Languages 2022∗
402
∗
[https://spectrum.ieee.org/top-programming-languages/]
257
5.1.1
Compiled vs. Interpreted Languages
• Compiled language compiles the whole program, at compile time, into machine code that
targets a specific HW† .
– Examples are: Fortran, C and C++
– Advantages include very efficient codes
– Disadvantages include lengthy compile time
• Interpreted language translates a program statement, one after another, at run time, into
another language; often machine code∗ .
– Examples are: Python, Ruby, Matlab, Mathematica, . . .
– Advantages include portability
– Disadvantages include slower programs; since the translation overhead is added to
the execution overhead
• In principle, any programming language can be implemented with a compiler or an interpreter†
– Example languages having both compilers and interpreters are‡ : BASIC, C, Lisp,
Pascal, Python, Matlab, . . .
Compiled or Interpreted; Which One is Better?
Modifying a program’s source code is a common task during the development of an application.
• Using a compiled language, each modification needs long compiling time
• Using an interpreted language, the time necessary to test modifications is significantly
shorter
• Therefore, interpreters tend to favor the development of software prototypes§
• On the other hand, it makes sense to use a compiled language for intensive applications¶
5.1.2
Programming Language Standardization
Most programming languages are standardized. That is, they have ISO/ANSI/IEC/. . . specifications.
• The standard of a programming language is usually regularly updated. E.g.:
– C++ has: C98, C++03, C++11, C++14, C++17, C++20, . . .
†
[www.ibm.com/support/knowledgecenter/zosbasics/com.ibm.zos.zappldev/zappldev_85.htm]
[https://en.wikipedia.org/wiki/Interpreted_language]
†
[https://en.wikipedia.org/wiki/Compiled_language]
‡
[https://en.wikipedia.org/wiki/Interpreted_language]
§
[https://en.wikibooks.org/wiki/Introduction_to_Programming_Languages/Interpreted_
Programs]
¶
[www.ibm.com/support/knowledgecenter/zosbasics/com.ibm.zos.zappldev/zappldev_85.htm]
∗
258
– Fortran has: . . . FORTRAN 66, FORTRAN 77, Fortran 90, Fortran 95, Fortran
2003, Fortran 2008, Fortran 2018, . . .
• Individuals/Companies may implement a compiler that complies with the programming
language standard. For example‖ :
– C\C++ has the following compiler implementations:
∗ Visual C++ (by Microsoft)
∗ Borland C++ (by Borland)
∗ Solaris Studio (by Sun∗ )
∗ Open64 (by AMD, SGI, Google, HP,
Intel Nvidia, PathScale, Tsinghua
University and others)
∗ gcc (by the GNU project)
∗ g++ (C++ compiler; by the GNU
project)
∗ Intel C++ compiler (by Intel)
∗ Open Watcom (by Sybase)
∗ XL C\C++ (by IBM)
∗ ...
– Fortran has the following compiler implementations:
∗ Visual Fortran (by Microsoft† )
∗ Compaq Visual Fortran (by Compaq‡ )
∗ Solaris Studio (by Sun)
∗ PGFortran (by The Portland Group)
∗ GFortran (by the GNU project)
∗ Intel Fortran compiler (by Intel)
∗ Open64 (by Google, HP, Intel,
Nvidia, PathScale, Tsinghua University and others)
∗ Open Watcom (by Sybase)
∗ NAG Fortran Compiler (by NAG)
∗ XL Fortran (by IBM)
∗ ...
405
5.1.3
The Fortran Programming Language
In 1953, John W. Backus submitted a proposal to his superiors at IBM to develop a more practical
alternative to the assembly language.
• Fortran is considered:
– the first optimizing compiler [sec. 5.2.1]
– the most popular for computationally intensive applications and highperformance computing (HPC)
– the first language supported across a variety of computer architectures
∗ Fortran is used for ranking supercomputers
• Up to 2019, there are: . . . FORTRAN 66, FORTRAN 77, Fortran 90, Fortran 95, Fortran
2003, Fortran 2008, Fortran 2018, . . .
406
‖
[http://en.wikipedia.org/wiki/List_of_compilers]
Currently acquired by Oracle
†
Discontinued
‡
Discontinued
∗
259
Fortran Reference Card
Modern Fortran Reference Card
(c) 2014 Michael Goerz <goerz@physik.uni-kassel.de>
http://www.michaelgoerz.net
This work is licensed under the Creative Commons
Attribution-Noncommercial-Share Alike 3.0 License. To view a copy
of this license, visit http://creativecommons.org/licenses/by-nc-sa/
1
Data Types
1.1 Simple Data Types
integer(specs)[,attrs] :: i
integer
real(specs)[,attrs] :: r
real number
complex(specs)[,attrs] :: z
complex number
logical(specs)[,attrs] :: b
boolean variable
character(specs)[,attrs] :: s string
real, parameter :: c = 2.9e1
constant declaration
real(idp) :: d; d = 1.0d0
double precision real
s2=s(2:5); s2=s(:5); s2=s(5:) substring extraction
attributes: parameter, pointer, target, allocatable,
dimension, public, private, intent, optional, save,
external, intrinsic
specs: kind=..., for character: len=...
double precision: integer, parameter :: idp = kind(1.0d0)
260
1.2 Derived Data Types
type person t
character(len=10) :: name
integer :: age
end type person t
type group t
type(person t),allocatable &
& :: members(:)
end type group t
name = group%members(1)%name
1.3 Arrays and Matrices
real :: v(5)
real :: a(-1:1,3)
real, allocatable :: a(:)
a=(/1.2,b(2:6,:),3.5/)
v = 1/v + a(1:5,5)
allocate(a(5),b(2:4),stat=e)
dealloate(a,b)
2
3
define derived data type
F2008 : allocatable . . .
. . . components
access structure component
explicit array, index 1..5
2D array, index -1..1, 1..3
“deferred shape” array
array constructor
array expression
array allocation
array de-allocation
1.4 Pointers (avoid!)
real, pointer :: p
real, pointer :: a(:)
real, target :: r
p => r
associated(p, [target])
nullify(p)
declare pointer
“deferred shape” array
define target
set pointer p to r
pointer assoc. with target?
associate pointer with NUL
1.5 Operators
.lt. .le. .eq. .ne. .gt. .ge.
<
<=
==
/=
>
>=
.not. .and. .or. .eqv. .neqv.
x**(-y)
’AB’//’CD’
relational operators
relational op aliases
logical operators
exponentiation
string concatenation
Control Constructs
if (...) action
if (...) then
block
else if (...) then; block
else; block
end if
select case (number)
case (:0)
block
case (1:2); block
case (3); block
case (4:); block
case default; block
end select
outer: do
inner: do i=from,to,step
if (...) cycle inner
if (...) exit outer
end do inner
end do outer
do while (...);block;end do
if statement
if-construct
select-construct
everything up to 0 (incl.)
number is 1 or 2
number is 3
everything up from 4 (incl.)
fall-through case
controlled do-loop
counter do-loop
next iteration
exit from named loop
do-while loop
Program Structure
program myprog
use foo, lname => usename
use foo2, only: [only-list]
implicit none
interface;...;end interface
specification-statements
exec-statements
stop ’message’
contains
internal-subprograms
end program myprog
module foo
use bar
public :: f1, f2, ...
private
interface;...;end interface
specification statements
contains
internal-subprograms
end module foo
function f(a,g) result r
real, intent(in) :: a
real :: r
interface
real function g(x)
real, intent(in) :: x
end function g
end interface
r = g(a)
end function f
recursive function f(x) ...
elemental function f(x) ...
main program
used module, with rename
selective use
require variable declaration
explicit interfaces
var/type declarations etc.
statements
terminate program
subroutines, functions
module
used module
list public subroutines
make private by default
explicit interfaces
var/type declarations, etc.
“module subprograms”
function definition
input parameter
return type
explicit interface block
dummy var g is function
function call
allow recursion
work on args of any rank
subroutine s(n,i,j,a,b,c,d,r,e) subroutine definition
integer, intent(in) :: n
read-only dummy variable
integer, intent(inout) :: i read-write dummy variable
integer, intent(out) :: j
write-only dummy variable
real(idp) :: a(n)
explicit shape dummy array
real(idp) :: b(2:,:)
assumed shape dummy array
real(idp) :: c(10,*)
assumed size dummy array
real, allocatable :: d(:)
deferred shape (F2008 )
character(len=*) :: r
assumed length string
integer, optional :: e
optional dummy variable
integer :: m = 1
same as integer,save::m=1
if (present(e)) ...
presence check
return
forced exit
end subroutine s
call s(1,i,j,a,b,c,d,e=1,r="s") subroutine call
Notes:
• explicit shape allows for reshaping trick (no copies!):
you can pass array of any dim/shape, but matching size.
• assumed shape ignores lbounds/ubounds of actual argument
• deferred shape keeps lbounds/ubounds of actual argument
• subroutines/functions may be declared as pure (no side effects)
Use of interfaces:
• explicit interface for external or dummy procedures
interface
interface body
sub/function specs
end interface
• generic/operator/conversion interface
interface generic-spec
module procedure list
internal subs/functions
end interface
generic-spec can be any of the following:
1. “generic name”, for overloading routines
2. operator name (+ -, etc) for defining ops on derived types
You can also define new operators names, e.g. .cross.
Procedures must be one- or two-argument functions.
3. assignment (=) for defining assignments for derived types.
Procedures must be two-argument subroutines.
The generic-spec interfaces should be used inside of a module;
otherwise, use full sub/function specs instead of module
procedure list.
4
Intrinsic Procedures
4.1 Transfer and Conversion Functions
abs(a)
absolute value
aimag(z)
imag. part of complex z
aint(x, kind), anint(x, kind) to whole number real
dble(a)
to double precision
cmplx(x, y, kind)
create x + i y
cmplx(x, kind=idp)
real to dp complex
int(a, kind), nint(a, kind)
to int (truncated/rounded)
real(x, kind)
to real (i.e. real part)
char(i, kind), achar(i)
char of ASCII code
ichar(c), iachar(c)
ASCII code of character
logical(l, kind)
change kind of logical l
ibits(i, pos, len)
extract sequence of bits
transfer(source, mold, size)
reinterpret data
Assignment
• Answer question (5.1)
408
5.1.4
C++
C++ is a high-level, general-purpose programming language, created in 1979∗ by Bjarne Stroustrup, as an extension of the C programming language† .
• C++ was designed with a bias towards:
– performance
– flexibility of use
– efficiency
• Up to 2019, there are C98, C++03, C++11, C++14, C++17 and C++20
409
5.2
The Compiler
The compiler is a CLI program that transforms source code into machine code.
• This machine code is called “object code”
MyProg
C++ code
Compiler
MyProg.o
MyProg.cpp
• Object code differs according MyProg.cpp
to the target:
– OS (Windows, Linux, . . . )
MyProg.obj
MyProg
01010101
MyProg.o
MyProg.obj
– CPU (x86, x86-64, IA64, ARM, . . . )
MyProg
MyProg
MyProg
MyProg.exe
functionA
C++ code
functionA.o
functionA.obj
functionA
01010101
Linker
functionA.cpp
Compiler
developer A
Therefore, if any of the above
has changed, the01010101
compiler has to be changed accordingly
C++ code
functionA
and the source code has to be recompiled again.
01010101
MyProg
functionB
01010101
01010101
functionB.o
functionB.cpp
functionB.obj
functionB
functionB
01010101
C++ code
C++ was initially known as “C with Classes”. Since 1982, Stroustrup named it C++.
MyProg.o
[https://en.wikipedia.org/wiki/C%2B%2B]
MyProg
C++ code
261
MyProg.obj
MyProg
01010101
r
MyProg.cpp
Compiler
†
developer A
∗
OS dependent
subroutines
01010101
410
5.2.1
Compiler Optimization
The compiler converts a code written in a high-level programming language to an equivalent
low-level instructions suitable to a specific HW.
• Depending on the specific HW architecture, the compiler may be able to optimize the code
to improve its performance, reduce the needed HW resources, . . . .
• Compiler optimization often may:
– omit some declared variables
– alter/re-organize the algorithm
– not execute some statements (because for example they compute constant results)
– move a statement out of a loop (because for example it is constant within the loop)
– use specific CPU features instead of some of code algorithms
– assign extra memory for dynamic arrays
– ...
• Drawbacks of compiler optimization may include:
– increased compilation time and HW resources
– inability to debug the program
Debugging and Optimization
During code developing, a developer usually needs to debug his code. Typical debugging scenarios may include:
• stop code execution at some point∗ and check variables’ values
• change variables’ values
• skip the execution of some statements
• ...
To enable debugging, the compiler should:
• not optimize the code
• generate:
– symbol names for functions and variables
– type information
– line number locations
– ...
∗
usually called a “break point”
262
5.2.2
The Preprocessor
The preprocesor is a CLI program that processes the source code before it is compiled.
Code 5.1: Sample C++ header file
#ifndef MyHeaderFile //MyHeaderFile
#define MyHeaderFile
#include <stdio.h>
#include <cmath>
//C++ Code goes here
//
//
• C preprocessor directives are preceded #endif //MyHeaderFile
with “#”, for example:
413
Portable Code
For Fortran, C and C++ for example, the code
can become portable∗ by:
• parameterizing the code using preprocessor definitions and macros
Code 5.2: Sample portable Fortran code
#if defined(__x86_64__)
# define mwPointer integer*8
#else
# define mwPointer integer*4
#endif
• adhering to the language standard
• ...
!Your code goes here
414
∗
can be complied on several OS’s and/or HW
263
5.2.3
The Linker
MyProg.o
MyProg.obj
MyProg
• static library
C++ code
Compiler
The linker is a CLI program that combines object file(s) into either:
MyProg.cpp
•MyProg
shared library
• executable program
01010101
Static Linking
MyProg.o
MyProg.obj
MyProg.cpp
MyProg
MyProg
MyProg
MyProg.exe
C++ code
functionA.cpp
functionA
C++ code
MyProg.obj
MyProg
01010101
01010101
functionA.o
functionA.obj
functionA
01010101
Linker
MyProg
C++ code
Compiler
developer A
MyProg.cpp
Compiler
MyProg.o
functionA
01010101
MyProg
OS dependent
subroutines
functionB
01010101
01010101
01010101
functionB.o
functionB.obj
functionB.cpp
functionB
MyProg.cpp
C++ code
MyProg.o
MyProg.obj
functionB
01010101
MyProg
MyProg
MyProg
functionA
01010101
functionB
functionB
functionB
01010101
functionA.cpp 01010101
functionA.obj
MyLibrary.lib
functionA
functionA
Compiler
MyLibrary.a
C++ code
MyProg.o
functionB.cpp
functionB
MyProg.obj
01010101
functionB.o
functionB.obj
functionB
functionB.o
functionB.obj
functionB
MyLibrary.a
MyLibrary.lib
MyProg
01010101
Linker
Compiler
01010101
MyProg.obj
Linker
functionA.o
Compiler
developer A
developer B
functionB
01010101
functionB
01010101
MyProg.exe
functionA.obj
functionA
01010101
functionB
01010101
MyProg.dll
MyProg.obj
functionB.o
functionB.obj
functionA
inker
functionB.cpp
01010101
r
ompiler
functionA
er
veloper B
A
MyProg.cpp
functionA.obj
functionA
MyProg.o
01010101
01010101
functionA.o
C++ code
OS dependent
subroutines
MyProg.so
functionA.cpp
264
01010101
MyProg
OS dependent
MyProg.exe
subroutines
01010101
MyProg
OS dependent
subroutines
functionB
01010101
MyProg
01010101
C++ code
01010101
functionA
functionA
MyProg
01010101
MyProg.exe
OS dependent
subroutines
functionB
01010101
01010101
functionA
C++ code
MyProg
MyProg
functionA
functionB.cpp
functionA
01010101
MyProg
functionA.cpp
MyProg
MyProg.exe
01010101
C++ code
MyProg.cpp
MyProg
01010101
01010101
MyProg.o
C++ code
01010101
Linker
C++ code
OS dependent
subroutines
MyProg
functionA.o
Compiler
developer B
MyProg
MyProg
functionA
01010101
functionB.o
functionB.obj
MyProg.cpp
MyProg.obj
Linker
functionA.obj
functionB.cpp
C++ code
developer A
C++ code
functionA.o
Linker
C++ code
MyProg
01010101
Linker
functionA
MyProg.cpp
Compiler
functionA.cpp
Compiler
C++ code
developer A
developer A
MyProg.exe
MyProg.o
01010101
01010101
01010101
functionB
Li
functionB.cpp
Co
develo
functionB.o
functionB.obj
functionB
functionB
01010101
01010101
C++ code
Dynamic Linking
MyProg
MyProg
MyProg.exe
MyProg.obj
Linker
MyProg.cpp
Compiler
developer A
MyProg.o
MyProg
OS dependent
subroutines
MyProg
01010101
01010101
01010101
C++ code
MyProg.so
MyProg.dll
functionA.obj
functionA
functionA
C++ code
functionB.cpp
functionB
functionA
Linker
functionA.cpp
Compiler
developer B
functionA.o
01010101
functionB.o
functionB.obj
functionB
OS dependent
subroutines
01010101
functionB
01010101
C++ code
01010101
01010101
417
File Extensions
Object file
Static library
Shared library
Executable program
Windows
.obj
.lib
.dll†
.exe
Unix-like
.o
.a∗
.so‡
(none)
418
∗
.a stands for “archive”
.dll stands for “dynamic link library”
‡
.so stands for “shared object”
†
265
Static vs Shared Library
Static Library
Shared Library
• Archive of object files
• Library of executable programs
– Not executable
– Loaded into the memory and executed by the CPU
• Several programs may simultaneously
call the same shared library (multithreading)
Unix-like Library Naming Conventions
On Unix-like OS’s, a static/shared library filename should start with “lib”. Additional details
are available @:
• www.ibm.com/developerworks/library/l-shobj/
• http://tldp.org/HOWTO/Program-Library-HOWTO/shared-libraries.html
5.2.4
Notable Compilers
5.2.4.1
MS Visual C++ (MSVC) Compiler
MSVC Compiler is available for free download under the brand “Microsoft C++ Build Tools”∗† .
• Microsoft C++ Build Tools is a key component of MS Visual Studio
5.2.4.2
Intel Compilers
Intel provides commercial and free‡ C\C++ and Fortran compilers under several brands such
as:
• Intel Parallel Studio XE
5.2.4.3
• Intel System Studio
The GNU Toolchain
• Refer to appendix G
5.2.4.4
Other Compilers
Project idea 9 (Matlab Compiler Toolbox)
MATLAB compiler can compile MATLAB programs to standalone SW applications.
• SW applications created with MATLAB Compiler use the MATLAB Runtime
∗
[https://visualstudio.microsoft.com/visual-cpp-build-tools/]
The brand name usually changes from version to another.
‡
https://software.intel.com/en-us/qualify-for-free-software/
†
266
– This Runtime can be packaged with the SW application, or users can download
it during installation
• Try to compile codes of sec. 6.1 to standalone SW applications
– Try to convert them to MEX functions
– Compare with our C and C++ codes of sections 6.2 and 6.4
• Well document your experience
• Prepare a tutorial
424
5.3
Build Systems
Building denotes compiling source code files and linking the compiled files to obtain executable
or library file(s).
• Building a large SW project with multiple source files can be complicated and timeconsuming. Reasons include:
– Compilation is a time and resource consuming task
– All source files need to be compiled
– Modifying some files usually necessitate re-compiling and re-linking several other
files
– Certain source files need to be compiled before others
– Compiled files need to be linked in special plan
– ...
Therefore, it makes sense to automate the build process.
5.3.1
make
Refer to appendix I.
5.3.2
426
The Integrated Development Environment (IDE)
Usually the IDE:
• keep track of all the project files and configurations , . . .
• includes an advanced text editor
• can refactor∗ code
• calls the compiler
• helps solving compile errors
– Code highlighting
– Code completion
– ...
∗
425
• calls the linker
• helps solving link errors
[sec. M.5]
267
• provides GUI for the debugger
• ...
Notable IDE’s are:
• Eclipse (Cross-platform)
• Xcode (Mac OS)
• Visual Studio (Windows & MacOS)
• NetBeans (Cross-platform)
• Visual Studio Code (Cross-platform)
• ...
Visual Studio
• Refer to appendix L
Eclipse
• Refer to appendix M
Visual Studio Code
• Refer to appendix N
268
Stack Overflow 2019 Survey∗
5.3.3
Stack Overflow 2022 Survey†
CMake
• Refer to appendix K
433
5.3.4
Ninja
Refer to appendix J.
434
∗
[https://insights.stackoverflow.com/survey/2019#technology-_-most-populardevelopment-environments]
†
[https://survey.stackoverflow.co/2022/#section-most-popular-technologiesintegrated-development-environment]
269
5.4
Software Libraries
There are numerous SW libraries covering vast concepts. Notable examples are:
• Scientific libraries:
– SPOOLES
– NumPy
– SciPy
– Boost
– STL
– SGI
– IMSL
– MKL
– gnuplot
– Plotly
– Grace
– matplotlib
– PLplot
– ...
– OpenGL
– Mesa
– Vulkan
– DirectDraw
– Verge3D
– VTK
– BLAS
– LAPACK
– MUMPS
– PARDISO
– FFTW
– ...
• Visualization libraries:
• Graphics libraries:
5.4.1
– ...
Notable Scientific Software Libraries
Basic Linear Algebra Subprograms (BLAS)
BLAS are a set of low-level open source subroutines that perform common linear algebra operations such as:
• vector/matrix copying,
• linear combinations
• vector scaling,
• matrix multiplication
• vector dot products,
• ...
• BLAS are written in Fortran 77
– can be called from Fortran, C\C++, . . .
• BLAS are still used as a building block in higher-level math programming languages and
libraries, including:
– LAPACK
– Mathematica
– R programming language
– MATLAB
– NumPy
– ...
• BLAS is a de facto standard for linear algebra libraries and routines
– Several BLAS implementations have been tuned for several computer architectures.
Examples include:
270
∗ Automatically Tuned Linear Algebra Software (ATLAS); tuned open source implementation
∗ Intel Math Kernel Library (MKL); tuned for Intel processors
∗ AMD Core Math Library (ACML); tuned for AMD processors
∗ ...
436
271
BLAS Cheat Sheet
Meaning of prefixes
S - REAL
D - DOUBLE PRECISION
C - COMPLEX
Z - COMPLEX*16
(this may not be supported
by all machines)
For the Level 2 BLAS a set of extended-precision routines with
the prefixes ES, ED, EC, EZ may also be available.
Level 1 BLAS
In addition to the listed routines there are two further
extended-precision dot product routines DQDOTI and DQDOTA.
272
Level 2 and Level 3 BLAS
Matrix types:
GE - GEneral
GB - General Band
SY - SYmmetric
SB - Sym. Band
HE - HErmitian
HB - Herm. Band
TR - TRiangular
TB - Triang. Band
SP - Sum. Packed
HP - Herm. Packed
TP - Triang. Packed
Level 2 and Level 3 BLAS Options
Dummy options arguments are declared as CHARACTER*1
and may be passed as character strings.
TRANx = ‘No transpose’, ‘Transpose’,
‘Conjugate transpose’ (X, X T , X H )
UPLO
= ‘Upper triangular’, ‘Lower triangular’
DIAG
= ‘Non-unit triangular’, ‘Unit triangular’
SIDE
= ‘Left’, ‘Right’ (A or op(A) on the left,
or A or op(A) on the right)
For real matrices, TRANSx = ‘T’ and TRANSx = ‘C’ have
the same meaning.
For Hermitian matrices, TRANSx = ‘T’ is not allowed.
For complex symmetric matrices, TRANSx = ‘H’ is not
allowed.
References
C. Lawson, R. Hanson, D. Kincaid, and F. Krogh, “Basic
Linear Algebra Subprograms for Fortran Usage,” ACM Trans.
on Math. Soft. 5 (1979) 308-325
J.J. Dongarra, J. DuCroz, S. Hammarling, and R. Hanson,
“An Extended Set of Fortran Basic Linear Algebra Subprograms,”
ACM Trans. on Math. Soft. 14,1 (1988) 1-32
J.J. Dongarra, I. Duff, J. DuCroz, and S. Hammarling, “A Set
of Level 3 Basic Linear Algebra Subprograms,” ACM Trans.
on Math. Soft. (1989)
Basic
Linear
Obtaining the Software via netlib@ornl.gov
To receive a copy of the single-precision software,
type in a mail message:
send sblas from blas
send sblas2 from blas
send sblas3 from blas
To receive a copy of the double-precision software,
type in a mail message:
send dblas from blas
send dblas2 from blas
send dblas3 from blas
To receive a copy of the complex single-precision software,
type in a mail message:
send cblas from blas
send cblas2 from blas
send cblas3 from blas
Algebra
Subprograms
A Quick Reference Guide
To receive a copy of the complex double-precision software,
type in a mail message:
send zblas from blas
send zblas2 from blas
send zblas3 from blas
University of Tennessee
Oak Ridge National Laboratory
Numerical Algorithms Group Ltd.
Send comments and questions to lapack@cs.utk.edu .
May 11, 1997
Level 1 BLAS
dim scalar vector
vector
scalars
5-element array
SUBROUTINE xROTG (
A, B, C, S )
SUBROUTINE xROTMG(
D1, D2, A, B,
PARAM )
SUBROUTINE xROT ( N,
X, INCX, Y, INCY,
C, S )
SUBROUTINE xROTM ( N,
X, INCX, Y, INCY,
PARAM )
SUBROUTINE xSWAP ( N,
X, INCX, Y, INCY )
SUBROUTINE xSCAL ( N, ALPHA, X, INCX )
SUBROUTINE xCOPY ( N,
X, INCX, Y, INCY )
SUBROUTINE xAXPY ( N, ALPHA, X, INCX, Y, INCY )
FUNCTION
xDOT ( N,
X, INCX, Y, INCY )
FUNCTION
xDOTU ( N,
X, INCX, Y, INCY )
FUNCTION
xDOTC ( N,
X, INCX, Y, INCY )
FUNCTION
xxDOT ( N,
X, INCX, Y, INCY )
FUNCTION
xNRM2 ( N,
X, INCX )
FUNCTION
xASUM ( N,
X, INCX )
FUNCTION
IxAMAX( N,
X, INCX )
Generate plane rotation
Generate modified plane rotation
Apply plane rotation
Apply modified plane rotation
x↔y
x ← αx
y←x
y ← αx + y
dot ← xT y
dot ← xT y
dot ← xH y
dot ← α + xT y
nrm2 ← ||x||2
asum ← ||re(x)||1 + ||im(x)||1
amax ← 1st k ∋ |re(xk )| + |im(xk )|
= max(|re(xi )| + |im(xi )|)
prefixes
S, D
S, D
S, D
S, D
S, D, C, Z
S, D, C, Z, CS, ZD
S, D, C, Z
S, D, C, Z
S, D, DS
C, Z
C, Z
SDS
S, D, SC, DZ
S, D, SC, DZ
S, D, C, Z
Level 2 BLAS
273
options
dim
b-width scalar matrix vector
scalar vector
xGEMV (
TRANS,
M, N,
ALPHA, A, LDA, X, INCX, BETA, Y, INCY )
xGBMV (
TRANS,
M, N, KL, KU, ALPHA, A, LDA, X, INCX, BETA, Y, INCY )
xHEMV ( UPLO,
N,
ALPHA, A, LDA, X, INCX, BETA, Y, INCY )
xHBMV ( UPLO,
N, K,
ALPHA, A, LDA, X, INCX, BETA, Y, INCY )
xHPMV ( UPLO,
N,
ALPHA, AP,
X, INCX, BETA, Y, INCY )
xSYMV ( UPLO,
N,
ALPHA, A, LDA, X, INCX, BETA, Y, INCY )
xSBMV ( UPLO,
N, K,
ALPHA, A, LDA, X, INCX, BETA, Y, INCY )
xSPMV ( UPLO,
N,
ALPHA, AP,
X, INCX, BETA, Y, INCY )
xTRMV ( UPLO, TRANS, DIAG,
N,
A, LDA, X, INCX )
xTBMV ( UPLO, TRANS, DIAG,
N, K,
A, LDA, X, INCX )
xTPMV ( UPLO, TRANS, DIAG,
N,
AP,
X, INCX )
xTRSV ( UPLO, TRANS, DIAG,
N,
A, LDA, X, INCX )
xTBSV ( UPLO, TRANS, DIAG,
N, K,
A, LDA, X, INCX )
xTPSV ( UPLO, TRANS, DIAG,
N,
AP,
X, INCX )
options
dim
scalar vector
vector
matrix
xGER (
M, N, ALPHA, X, INCX, Y, INCY, A, LDA )
xGERU (
M, N, ALPHA, X, INCX, Y, INCY, A, LDA )
xGERC (
M, N, ALPHA, X, INCX, Y, INCY, A, LDA )
xHER ( UPLO,
N, ALPHA, X, INCX,
A, LDA )
xHPR ( UPLO,
N, ALPHA, X, INCX,
AP )
xHER2 ( UPLO,
N, ALPHA, X, INCX, Y, INCY, A, LDA )
xHPR2 ( UPLO,
N, ALPHA, X, INCX, Y, INCY, AP )
xSYR ( UPLO,
N, ALPHA, X, INCX,
A, LDA )
xSPR ( UPLO,
N, ALPHA, X, INCX,
AP )
xSYR2 ( UPLO,
N, ALPHA, X, INCX, Y, INCY, A, LDA )
xSPR2 ( UPLO,
N, ALPHA, X, INCX, Y, INCY, AP )
y ← αAx + βy, y ← αAT x + βy, y ← αAH x + βy, A − m × n
y ← αAx + βy, y ← αAT x + βy, y ← αAH x + βy, A − m × n
y ← αAx + βy
y ← αAx + βy
y ← αAx + βy
y ← αAx + βy
y ← αAx + βy
y ← αAx + βy
x ← Ax, x ← AT x, x ← AH x
x ← Ax, x ← AT x, x ← AH x
x ← Ax, x ← AT x, x ← AH x
x ← AΓ1 x, x ← AΓT x, x ← AΓH x
x ← AΓ1 x, x ← AΓT x, x ← AΓH x
x ← AΓ1 x, x ← AΓT x, x ← AΓH x
S, D, C, Z
S, D, C, Z
C, Z
C, Z
C, Z
S, D
S, D
S, D
S, D, C, Z
S, D, C, Z
S, D, C, Z
S, D, C, Z
S, D, C, Z
S, D, C, Z
A ← αxy T + A, A − m × n
A ← αxy T + A, A − m × n
A ← αxy H + A, A − m × n
A ← αxxH + A
A ← αxxH + A
A ← αxy H + y(αx)H + A
A ← αxy H + y(αx)H + A
A ← αxxT + A
A ← αxxT + A
A ← αxy T + αyxT + A
A ← αxy T + αyxT + A
S, D
C, Z
C, Z
C, Z
C, Z
C, Z
C, Z
S, D
S, D
S, D
S, D
C ← αop(A)op(B) + βC, op(X) = X, X T , X H , C − m × n
C ← αAB + βC, C ← αBA + βC, C − m × n, A = AT
C ← αAB + βC, C ← αBA + βC, C − m × n, A = AH
C ← αAAT + βC, C ← αAT A + βC, C − n × n
C ← αAAH + βC, C ← αAH A + βC, C − n × n
C ← αAB T + ᾱBAT + βC, C ← αAT B + ᾱB T A + βC, C − n × n
C ← αAB H + ᾱBAH + βC, C ← αAH B + ᾱB H A + βC, C − n × n
B ← αop(A)B, B ← αBop(A), op(A) = A, AT , AH , B − m × n
B ← αop(AΓ1 )B, B ← αBop(AΓ1 ), op(A) = A, AT , AH , B − m × n
S, D, C, Z
S, D, C, Z
C, Z
S, D, C, Z
C, Z
S, D, C, Z
C, Z
S, D, C, Z
S, D, C, Z
Level 3 BLAS
options
dim
scalar matrix matrix scalar matrix
xGEMM (
TRANSA, TRANSB,
M, N, K, ALPHA, A, LDA, B, LDB, BETA, C, LDC )
xSYMM ( SIDE, UPLO,
M, N,
ALPHA, A, LDA, B, LDB, BETA, C, LDC )
xHEMM ( SIDE, UPLO,
M, N,
ALPHA, A, LDA, B, LDB, BETA, C, LDC )
xSYRK (
UPLO, TRANS,
N, K, ALPHA, A, LDA,
BETA, C, LDC )
xHERK (
UPLO, TRANS,
N, K, ALPHA, A, LDA,
BETA, C, LDC )
xSYR2K(
UPLO, TRANS,
N, K, ALPHA, A, LDA, B, LDB, BETA, C, LDC )
xHER2K(
UPLO, TRANS,
N, K, ALPHA, A, LDA, B, LDB, BETA, C, LDC )
xTRMM ( SIDE, UPLO, TRANSA,
DIAG, M, N,
ALPHA, A, LDA, B, LDB )
xTRSM ( SIDE, UPLO, TRANSA,
DIAG, M, N,
ALPHA, A, LDA, B, LDB )
2
437
Linear Algebra Package (LAPACK)
LAPACK is a high quality SW library for numerical linear algebra. It can solve:
• systems of linear equations
• eigenvalue problems
• linear least squares
• singular value decomposition
• LAPACK is:
– open source
– built upon Basic Linear Algebra Subroutines (BLAS)
∗ optimized BLAS is vital
– written in Fortran∗
∗ can be called from Fortran, C\C++, . . .
– the backbone of many SW applications including Matlab
– also included in ATLAS, Intel MKL, . . .
The Standard Template Library (STL)
STL is a C++ library.
• STL is a part of the C++ standard
• STL provides provides four components called algorithms, containers, functional, and
iterators
• STL provides the complex and valarray classes
Good references explaining using STL are:
1. N. Josuttis, The C++ Standard Library: A Tutorial and Reference, Addison Wesley, 2nd
edition, 2012. [11]
2. B. Stroustrup, The C++ Programming Language, 3rd ed., Addison-Wesley Publishing
Company, 1997. (Strong and very concise) [12]
3. I. Horton, Using the C++ Standard Template Libraries, Apress, 2015. (Seems good. I
didn’t read it.) [13]
NumPy, SciPy and matplotlib
These are high-quality open-source Python libraries that provide a very strong alternative to
Matlab.
• NumPy† (Numerical Python) adds support for matrices and multi-dimensional arrays,
along with a large library of high-level mathematical functions
• matplotlib is a plotting library very similar to Matlab
• SciPy‡ includes specialized scientific tools for:
∗
LAPACK was originally written in Fortran 77, but moved to Fortran 90 in version 3.2 (2008) [www.netlib.
org/lapack/lapack-3.2.html].
†
You can think of NumPy similar to Matlab.
‡
You can think of SciPy similar to Matlab toolboxes.
274
– linear algebra
– optimization
– integration
– special functions
– signal and image processing
– statistics
– genetic algorithms
– ODE solvers
– ...
• Currently, optimized implementations of NumPy and SciPy, tuned for Intel processors,
are available within the Intel-Distribution-for-Python, which is a part of Intel-MKL.
440
Intel Math Kernel Library (MKL)
Intel MKL is a library of math routines for science, engineering, and financial applications.
• Core math functions include:
– BLAS
– sparse solvers
– NumPy
– LAPACK
– fast Fourier transforms
– SciPy
– ScaLAPACK
– vector math
– ...
• Intel MKL is hand-optimized specifically for Intel processors
• MKL is cross-platform∗
• MKL is available free for non-commercial use
441
More Information
• Check [14] for library comparisons
442
Assignment
• Answer questions (5.2) to (5.3)
443
∗
Windows, Linux and macOS
275
5.5
Useful Tools
5.5.1
Documentation Generator
• www.math.colostate.edu/~bangerth/videos/676/slides.23.pdf
Doxygen
• Check appendix H
Project idea 10 (Using Doxygen to Document a SW Project)
• Use Doxygen to Document a SW Project
5.5.2
Revision Control System (RCS)
RCS’s are examples of tools that help managing source code evolution
for a SW project.
1
Trunks
2
• It may be integrated with the IDE∗
Branches
3
• Examples are:
4
†
– Concurrent Versions System (CVS)
Merges
T1
– Subversion (SVN)
5
Tags
– Git
6
Useful link
7
• Git vs svn (www.findbestopensource.com/articledetail/git-vs-subversion)
9
T2
Centralized vs Decentralized RCS
Typical RCS’s
Centralized
Decentralized
CVS
Git
SVN
HG
...
...
∗
†
http://en.wikipedia.org/wiki/Comparison_of_revision_control_software
Very old, widespread, but not so good
276
Discontinued
development
branch
8
10
Centralized RCS
Ser
Decentralized RCS
ver
ver
Ser
SVN
repo
r
ope
vel
1
De
Git
repo
op
vel
De
2
er
r
ope
vel
1
De
Git
repo
er
lop
2
ve
De
Git
repo
448
Project idea 11 (Open Source Development)
Engage in an OSS project and transfer us your experience.
• Github is an example hosting site
449
Project idea 12 (Create Open Source Project)
Create an OSS project and practice using all collaborative development skills, especially:
• clear/attractive description/presentation of the project to attract targeted developers
• updating source code using a RCS
• Collaborative editing/writing documentation
• ...
450
Project idea 13 (Mobile App Programming)
Create a useful app for any of iPhone or Android smart phones.
• Explain your experience
• Is there easy solutions for cross-platform app development?
451
277
5.5.3
Regular Expressions (RegEx)
Anchors
Sample Patterns
^
Start of line +
([A-Za-z0-9-]+)
Letters, numbers and hyphens
\A
Start of string +
(\d{1,2}\/\d{1,2}\/\d{4})
Date (e.g. 21/3/2006)
$
End of line +
([^\s]+(?=\.(jpg|gif|png))\.\2)
jpg, gif or png image
\Z
End of string +
(^[1-9]{1}$|^[1-4]{1}[0-9]{1}$|^50$)
Any number from 1 to 50 inclusive
\b
Word boundary +
(#?([A-Fa-f0-9]){3}(([A-Fa-f0-9]){3})?)
Valid hexadecimal colour code
\B
Not word boundary +
((?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,15})
8 to 15 character string with at least one
\<
Start of word
\>
End of word
Character Classes
upper case letter, one lower case letter,
and one digit (useful for passwords).
(\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,6})
Email addresses
(\<(/?[^\>]+)\>)
HTML Tags
\c
Control character
\s
White space
\S
Not white space
\d
Digit
\D
Not digit
\w
Word
*
0 or more +
\W
Not word
*?
0 or more, ungreedy +
\xhh
Hexadecimal character hh
+
1 or more +
(a|b)
a or b +
\Oxxx
Octal character xxx
+?
1 or more, ungreedy +
(...)
Group +
?
0 or 1 +
(?:...)
Passive Group +
??
0 or 1, ungreedy +
[abc]
Range (a or b or c) +
{3}
Exactly 3 +
[^abc]
Not a or b or c +
POSIX Character Classes
Note
These patterns are intended for reference purposes and have not been extensively tested.
Please use with caution and test thoroughly before use.
Quantifiers
Ranges
.
Any character except
new line (\n) +
[:upper:]
Upper case letters
{3,}
3 or more +
[a-q]
Letter between a and q +
[:lower:]
Lower case letters
{3,5}
3, 4 or 5 +
[A-Q]
Upper case letter +
[:alpha:]
All letters
{3,5}?
3, 4 or 5, ungreedy +
[:alnum:]
Digits and letters
[:digit:]
Digits
[:xdigit:]
Hexadecimal digits
[:punct:]
Punctuation
\
Escape Character +
[:blank:]
Space and tab
\n
New line +
[:space:]
Blank characters
\r
Carriage return +
[:cntrl:]
Control characters
\t
Tab +
[:graph:]
Printed characters
\v
Vertical tab +
[:print:]
Printed characters and
\f
Form feed +
g
Global match
spaces
\a
Alarm
i
Case-insensitive
Digits, letters and
[\b]
Backspace
m
Multiple lines
underscore
\e
Escape
s
Treat string as single line
\N{name}
Named Character
x
Allow comments and
[:word:]
Special Characters
between A and Q +
[0-7]
Digit between 0 and 7 +
\n
nth group/subpattern +
Note
Ranges are inclusive.
Pattern Modifiers
white space in pattern
Assertions
String Replacement (Backreferences)
e
Evaluate replacement
U
Ungreedy pattern
?=
Lookahead assertion +
?!
Negative lookahead +
$n
nth non-passive group
?<=
Lookbehind assertion +
$2
"xyz" in /^(abc(xyz))$/
?!= or ?<!
Negative lookbehind +
$1
"xyz" in /^(?:abc)(xyz)$/
?>
Once-only Subexpression
$`
Before matched string
^
[
.
?()
Condition [if then]
$'
After matched string
$
{
*
?()|
Condition [if then else]
$+
Last matched string
(
\
+
?#
Comment
$&
Entire matched string
)
|
?
$_
Entire input string
<
>
$$
Literal "$"
Note
Items marked + should work in most
regular expression implementations.
Metacharacters (must be escaped)
Available free from
AddedBytes.com
278
RegEx Example Application
453
279
5.6
Laboratory Work
5.6.1
Matlab MEX-Files
What is Matlab MEX-File?
MEX (Matlab EXecutable) file is a shared library that can be called from Matlab, exactly same
as any Matlab function.
• Matlab supports MEX-files generated by C, C++ or Fortran
Matlab.exe
FreeResponse_main_script.m
Cpp_MEX.dll
%Free_Response( ... );
Cpp_MEX( ... );
SDOF_response
mex functions mx functions
Blas routines Lapack routines
OS dependent
subroutines
mexFunction
Linker
mexFunction.obj
mexFunction
01010101
SDOF_response.obj
SDOF_response
01010101
Compiler
mexFunction
C++ code
mexFunction.cpp
libmex.lib
libmx.lib
Blas routines Lapack routines
mkl_rt.lib
SDOF_response
C++ code
SDOF_response.cpp
• Libmx.lib is a static library provided by Matlab for data exchange between Matlab and ,
C, C++ or Fortran
• Libmex.lib is a static library provided by Matlab for sending commands from C, C++ or
Fortran to Matlab
• mkl rt.lib is a static∗ library provided by Intel MKL that includes BLAS, LAPACK and
other things†
• Cpp MEX.dll is the created shared library (MEX-file)
∗
Alternatively, Intel MKL also provides shared libraries for dynamic linking.
In fact, instructions for linking with MKL do change from version to another. As of March 2018, instructions
are available at https://software.intel.com/en-us/articles/intel-math-kernel-library-intelmkl-compiling-and-linking-with-microsoft-visual-cc and https://software.intel.com/enus/mkl-windows-developer-guide-automatically-linking-your-intel-visual-fortranproject-with-intel-mkl
†
280
– Cpp MEX.dll is to be called from Matlab instead of the SDOF response.m function
– On Windows, Matlab demands renaming the shared library extension from “.dll” to
“.mexw32” for 32-bit systems and “.mexw64” for 64-bit systems
– On Linux, Matlab demands renaming the shared library extension from “.so” to
“.mexa32” for 32-bit systems and “.mexa64” for 64-bit systems
454
Supported Compilers∗
As of Matlab R2018a, the following compilers are supported for creating MEX-files:
• Windows
– MS Visual C++ Compiler (MSVC)
– Intel C\C++ Compilers
– Intel Fortran Compiler
– MinGW-w64 C\C++
∗ MinGW-w64 Fortran is not supported yet
∗ Check
www.mathworks.com/help/matlab/matlab_external/
compiling-c-mex-files-with-mingw.html
• Linux
– GCC†
• Check you are installing a the specific compiler version supported by your version of
Matlab∗
455
Building MEX-Files
The “mex” Matlab script is sufficient for building (compiling and linking) MEX-files [sec.
5.6.2.1].
• This can be fine for small projects
• For larger projects however, it is better to use a dedicated build-system/IDE
• To recognize the compiler/linker options necessary for building MEX-files,
– change Matlab’s current directory to PathTo/Mex source code files
– execute >> mex -v -n filename.c
∗ alternatively, execute >> mex -g -v -n filename.c for a suitable-fordebugging MEX-file‡
456
∗
[www.mathworks.com/support/compilers.html]
GNU compiler collection. It includes C, C++, Fortran compilers
‡
[www.mathworks.com/help/matlab/matlab_external/using-mex-script-options-to-custombuild.html]
†
281
Documentation
• Matlab documentation . MATLAB . Advanced Software Development . MATLAB
API for Other Languages . MEX-File Applications .
– C MEX-Files . Executable C MEX-Files . Compiling MEX-Files with the Microsoft Visual C++ IDE
– Troubleshoot MEX-Files . Debug on Microsoft Windows Platforms
– C MEX-Files . Executable C MEX-Files
– Fortran MEX-Files . Executable Fortran MEX-Files
282
5.6.2
Building and Debugging MEX-Files
Consider the codes of sec. 6.1.1.
• The FreeResponse main.m Matlab script [Code 6.2] calls the Free Response.m Matlab
function [Code 6.1] and plot its results
• It is required to create C, C++ and Fortran MEX-files (shared libraries) alternative to the
Free Response.m Matlab function [Code 6.1]
• MEX-files implementation is available as open source @ https://github.com/ahmedrashed/PortMatlab_remote
• After building the MEX-files,
– note the object files generated by the compiler
– rename the extension of the generated shared libraries to mexw64 (for 64-bit Windows), or mexa64 (for 64-bit Linux)
458
5.6.2.1
Building using Matlab’s “mex” Script
• Install your favorite compiler [sec. 5.6.1]
• Tell Matlab your favorite compiler by executing:
>> mex -setup
• Download the codes @ https://github.com/ahmed-rashed/PortMatlab_remote to
your PC
• Use the “mex” script to compile the source codes and build the MEX-files, as follows:
– To build C MEX-files;
∗ change
Matlab’s
current
directory
to
PathTo/Mex/SDOF FreeResponse/C MEX
∗ execute >> mex -R2018a Free_Response.c mexFunction.c
– To build C++ MEX-files;
∗ change Matlab’s current directory to /Mex/SDOF FreeResponse/Cpp MEX
∗ execute >> mex -R2018a Free_Response.cpp mexFunction.cpp
– Regarding the Fortran MEX-file, unfortunately, the “mex” script only builds
Fortran-77 fixed-form-format files!
∗ Therefore, if you write Fortran 90, or higher, in the free-form-format, you have
to manually build the MEX-files as explained in the following sections
459
283
5.6.2.2
Building and Debugging using Visual Studio
Getting Started with Visual Studio
• Refer to appendix L for getting started with Visual Studio
Laboratory 17 (Building and Debugging MEX-File using Visual Studio)
• Instructions used to compile and link the MEX-files using Visual Studio are as
follows:
[https://github.com/ahmed-rashed/PortMatlab_remote/blob/
master/Mex/README.md#instructions-to-compile-and-link-mex-filesusing-microsoft-visual-studio]
Code 5.3: Compile and Link the MEX-files using Visual Studio
Instructions to compile and link MEX-Files using Microsoft Visual Studio
========================================================================
Reference [www.mathworks.com/help/releases/R2017b/matlab/matlab_external/
compiling-mex-files-with-the-microsoft-visual-c-ide.html]
This assumes you have initially defined the following environment variables:
MATLABROOT
1) Create a module definition file as follows
Project > Add New Item > Module-Definition File (.def)
Specify the name of the file as "ModuleDefinitionFile.def" (or any
other name you like)
Write the following in the file:
EXPORTS mexFunction
# This is for a C MEX-file
or
EXPORTS _MEXFUNCTION # This is for a Fortran MEX-file
2) Add your (.c or .cpp or .f90) source files as follows:
Project > Add Existing Item
3) Modify the project properties as follows:
Project > Properties > All Configurations >
General >
Target Extension > .mexw32 (for win32) or .mexw64 (for win64)
Configuration Type > Dynamic Library (.dll)
C/C++ > or Fortran >
General > Additional Include Directories >
$(MKLIncludeDir)
$(MATLABROOT)/extern/include
Preprocessor > Preprocessor Definitions > add:
MX_COMPAT_64;MATLAB_MEXCMD_RELEASE=R2018a;USE_MEX_CMD;
MATLAB_MEX_FILE
Linker >
General >
Additional Library Directories: $(MATLABROOT)/extern/lib/
win32/microsoft (for win32) or $(MATLABROOT)/extern/lib
/win64/microsoft (for win64)
Input >
284
Additional Dependencies > libmx.lib;libmex.lib;libmat.lib;
libMatlabDataArray.lib;libMatlabEngine.lib
Module Definition File > ModuleDefinitionFile.def (the
filename module definition (.def) file you created)
Debug using $(MATLABROOT)/bin/matlab.exe
4) If you are using Intel MKL, follow the instructions for linking with MKL
These instructions do change from version to another.
As of March 2018, instructions are available at:
https://software.intel.com/en-us/articles/intel-math-kernel-libraryintel-mkl-compiling-and-linking-with-microsoft-visual-cc
and
https://software.intel.com/en-us/mkl-windows-developer-guideautomatically-linking-your-intel-visual-fortran-project-with-intel
-mkl
• You can easily debug shared libraries while in operation. To do so:
Option (1) (Recommended): Attach the Debugger to an already running Matlab
From the Visual Studio [www.mathworks.com/help/matlab/matlab_external/
debugging-on-microsoft-windows-platforms.html]:
– Build the shared library from its source code using the “Debug” configuration
– In the code of the shared library, set breakpoint(s) where you like
– Debug . Attach to Process . select the MATLAB process and click Attach
– From Matlab, call the shared library you have built under the “Debug” configuration
∗ Visual Studio will stop the mex-File execution at the breakpoint you have
specified in its source code and enables you to step in, examine variables,
...
Option (2): Start Matlab from the Debugger
– Build the shared library from its source code using the “Debug” configuration
– In the code of the shared library, set breakpoint(s) where you like
285
– In the project options, specify the path to matlab.exe (or the program that calls
the shared library)
– Press F5, or the “Start Debugging” toolbar button. This will launch Matlab
– From Matlab, call the shared library you have built under the “Debug” configuration
∗ Visual Studio will stop the mex-File execution at the breakpoint you have
specified in its source code and enables you to step in, examine variables,
...
286
5.6.2.3
Building and Debugging using Visual Studio Code
Getting Started with Visual Studio Code
• Refer to appendix N for getting started with Visual Studio Code
• On Windows, make sure that the supported compilers are correctly installed [sec. G.4]
462
Laboratory 18 (Debugging MEX-Files using Visual Studio Code)
• Useful Information are available @ https://blogs.mathworks.com/developer/
2018/06/19/mex-debugging-vscode/
• As explained in appendix N, VSCode is not good enough for building
– Therefore, the Makefile of sec. 5.6.2.4 is used for building the MEX-files
– This is implemented in the following files:
∗ PathTo/Mex/SDOF FreeResponse/C MEX/.vscode/tasks.json
∗ PathTo/Mex/SDOF FreeResponse/Cpp MEX/.vscode/tasks.json
∗ PathTo/Mex/SDOF FreeResponse/Fortran MEX/.vscode/tasks.json
• As an example, on a Linux PC, to build the debug version of the C MEX-file, From
VSCode, do the following
– File
.
Open
Workspace
DOF FreeResponse/SDOF MEX.code-workspace
.
PathTo/Mex/S-
– Terminal . Run Task . make GCC Debug C MEX
• When building using MSVC compiler, remember to start VSCode from within 64-bit
Visual Studio environment. To do so:
– Start Menu . Visual Studio 2019 . x64 Native Tools Command Prompt for VS
2019
– From the opened command prompt, open the existing workspace using VSCode
by executing:
$ cd PathTo/Mex/SDOF_FreeResponse
$ code SDOF_MEX.code-workspace
287
• When building using Intel Fortran Compiler, remember to start VSCode from within
64-bit Intel Visual Studio environment. To do so:
– Start Menu . Intel Parallel Studio XE 2019 . Compiler 19.0 for Intel 64 Visual
Studio 2019 Environment
– From the opened command prompt, open the existing workspace using VSCode
by executing
$ cd PathTo/Mex/SDOF_FreeResponse
$ code SDOF_MEX.code-workspace
• To debug the shared library while in operation, follow the instructions @ https://
blogs.mathworks.com/developer/2018/06/19/mex-debugging-vscode/
• More information in debugging are available @ https://code.visualstudio.
com/docs/editor/debugging
288
5.6.2.4
Building using GNU-make
Getting Started with GNU-make
• Refer to appendix I for getting started with GNU-make
464
Laboratory 19 (Building MEX-File using GNU-make)
The following Makefile resides in PathTo/Mex/SDOF FreeResponse
Code 5.4: Makefile for building MEX-files
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
# This make file assumes the following environment variables are defined
# MATLABROOT
ifeq ($(OS),Windows_NT)
Ext=mexw64
ObjExt=obj
PWD :=$(notdir $(shell cd))
mkdir_CMD=mkdir
rm_CMD=rmdir /S /Q
else
Ext=mexa64
ObjExt=o
PWD :=$(notdir $(shell pwd))
mkdir_CMD=mkdir -p
rm_CMD=rm -rf
endif
MEX-File =$(PWD).$(Ext)
SRC_C=$(wildcard *.c)
SRC_CPP=$(wildcard *.cpp)
SRC_F=$(wildcard *.f90)
MACROS=-DMX_COMPAT_64 -DMATLAB_MEXCMD_RELEASE=R2018a -DUSE_MEX_CMD -DMATLAB_MEX_FILE
OutRootDir=.
DebugDir =Debug
ReleaseDir=Release
OBJ_C_Debug =$(patsubst %.c, $(OutRootDir)/$(DebugDir)/%.$(ObjExt),$(SRC_C))
OBJ_CPP_Debug =$(patsubst %.cpp,$(OutRootDir)/$(DebugDir)/%.$(ObjExt),$(SRC_CPP))
OBJ_F_Debug =$(patsubst %.f90,$(OutRootDir)/$(DebugDir)/%.$(ObjExt),$(SRC_F))
Mod_F_Debug =$(OutRootDir)/$(DebugDir)/mx_interfaces.mod $(OutRootDir)/$(DebugDir)/mex_interfaces.mod
OBJ_C_Release =$(patsubst %.c, $(OutRootDir)/$(ReleaseDir)/%.$(ObjExt),$(SRC_C))
OBJ_CPP_Release =$(patsubst %.cpp,$(OutRootDir)/$(ReleaseDir)/%.$(ObjExt),$(SRC_CPP))
OBJ_F_Release =$(patsubst %.f90,$(OutRootDir)/$(ReleaseDir)/%.$(ObjExt),$(SRC_F))
Mod_F_Release =$(OutRootDir)/$(ReleaseDir)/mx_interfaces.mod $(OutRootDir)/$(ReleaseDir)/
mex_interfaces.mod
# Do not delete the $(Mod_F_Release) $(Mod_F_Debug) files
.SECONDARY: $(Mod_F_Release) $(Mod_F_Debug)
.PHONY: MSVC_IVF_Release MSVC_IVF_Debug GCC_Release GCC_Debug MINGW_Release MINGW_Debug cleanDebug
cleanRelease clean
CC=gcc
CXX=g++
Compile_Flag=-c
CompileOutFlag=-o
FC=gfortran
LD=gcc
CFLAGS =-I"$(MATLABROOT)/extern/include"
CPPFLAGS =$(CFLAGS)
FFLAGS =$(CFLAGS)
LDFLAGS =-Wl,--no-undefined -shared
LinkOutFlag =-o
ModOutFlag =-J
289
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
################################################
MSVC_IVF_CC:=cl
MSVC_IVF_CXX:=cl
MSVC_IVF_FC:=ifort
MSVC_IVF_LD:=link
MSVC_IVF_MACROS:=$(patsubst -D%,/D%,$(MACROS)) /D_CRT_SECURE_NO_DEPRECATE /D_SCL_SECURE_NO_DEPRECATE /
D_SECURE_SCL=0
MSVC_IVF_CFLAGS :=$(CFLAGS) /Zp8 /GR /W3 /EHs /nologo /MD
MSVC_IVF_CPPFLAGS :=$(CPPFLAGS) /Zp8 /GR /W3 /EHs /nologo /MD
MSVC_IVF_FFLAGS :=$(FFLAGS) /nologo /fpp /Qprec /MD /fp:source /assume:bscc /integer-size:64
MSVC_IVF_C_LIBS :=libmx.lib libmex.lib libmat.lib kernel32.lib user32.lib gdi32.lib winspool.lib
comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib
MSVC_IVF_CPP_LIBS :=libMatlabDataArray.lib libMatlabEngine.lib
MSVC_IVF_F_LIBS :=
MSVC_IVF_LibPath :=/LIBPATH:"$(MATLABROOT)/extern/lib/win64/microsoft"
MSVC_IVF_LDFLAGS :=/nologo /manifest /DLL /DEF:ModuleDefinitionFile.def
MSVC_IVF_LinkOutFlag :=/out:
MSVC_IVF_ModOutFlag :=/module:
MSVC_IVF_Compile_Flag:=/c
MSVC_IVF_CompileOutFlag:=/Fo
MSVC_IVF_Release: CC:=$(MSVC_IVF_CC)
MSVC_IVF_Release: CXX:=$(MSVC_IVF_CXX)
MSVC_IVF_Release: FC:=$(MSVC_IVF_FC)
MSVC_IVF_Release: LD:=$(MSVC_IVF_LD)
MSVC_IVF_Release: C_LIBS:=$(MSVC_IVF_C_LIBS)
MSVC_IVF_Release: CPP_LIBS:=$(MSVC_IVF_CPP_LIBS)
MSVC_IVF_Release: F_LIBS:=$(MSVC_IVF_F_LIBS)
MSVC_IVF_Release: LibPath:=$(MSVC_IVF_LibPath)
MSVC_IVF_Release: LDFLAGS:=$(MSVC_IVF_LDFLAGS)
MSVC_IVF_Release: LinkOutFlag:=$(MSVC_IVF_LinkOutFlag)
MSVC_IVF_Release: ModOutFlag:=$(MSVC_IVF_ModOutFlag)
MSVC_IVF_Release: MACROS :=$(MSVC_IVF_MACROS) /DNDEBUG
MSVC_IVF_Release: CFLAGS :=$(MSVC_IVF_CFLAGS) /O2 /OyMSVC_IVF_Release: CPPFLAGS :=$(MSVC_IVF_CPPFLAGS) /O2 /OyMSVC_IVF_Release: FFLAGS :=$(MSVC_IVF_FFLAGS) /O2
MSVC_IVF_Release: Compile_Flag:=$(MSVC_IVF_Compile_Flag)
MSVC_IVF_Release: CompileOutFlag:=$(MSVC_IVF_CompileOutFlag)
MSVC_IVF_Debug: CC:=$(MSVC_IVF_CC)
MSVC_IVF_Debug: CXX:=$(MSVC_IVF_CXX)
MSVC_IVF_Debug: FC:=$(MSVC_IVF_FC)
MSVC_IVF_Debug: LD:=$(MSVC_IVF_LD)
MSVC_IVF_Debug: C_LIBS:=$(MSVC_IVF_C_LIBS)
MSVC_IVF_Debug: CPP_LIBS:=$(MSVC_IVF_CPP_LIBS)
MSVC_IVF_Debug: F_LIBS:=$(MSVC_IVF_F_LIBS)
MSVC_IVF_Debug: LibPath:=$(MSVC_IVF_LibPath)
MSVC_IVF_Debug: LDFLAGS :=$(MSVC_IVF_LDFLAGS) /debug /PDB:"$(OutRootDir)/$(DebugDir)/$(MEX-File).
mexw64.pdb"
MSVC_IVF_Debug: LinkOutFlag:=$(MSVC_IVF_LinkOutFlag)
MSVC_IVF_Debug: ModOutFlag:=$(MSVC_IVF_ModOutFlag)
MSVC_IVF_Debug: MACROS :=$(MSVC_IVF_MACROS)
MSVC_IVF_Debug: CFLAGS :=$(MSVC_IVF_CFLAGS) /Z7
MSVC_IVF_Debug: CPPFLAGS :=$(MSVC_IVF_CPPFLAGS) /Z7
MSVC_IVF_Debug: FFLAGS :=$(MSVC_IVF_FFLAGS) /Z7
MSVC_IVF_Debug: Compile_Flag:=$(MSVC_IVF_Compile_Flag)
MSVC_IVF_Debug: CompileOutFlag:=$(MSVC_IVF_CompileOutFlag)
################################################
################################################
GCC_MACROS :=$(MACROS) -D_GNU_SOURCE
GCC_CFLAGS :=$(CFLAGS) -fexceptions -fno-omit-frame-pointer -fPIC -pthread
GCC_CPPFLAGS :=$(GCC_CFLAGS)
GCC_FFLAGS :=$(FFLAGS) -cpp -fPIC -fbackslash -fdefault-integer-8
GCC_base_LIBS :=-lmx -lmex -lmat -lm
GCC_C_LIBS :=$(GCC_base_LIBS) -lstdc++
GCC_CPP_LIBS :=-lMatlabDataArray
GCC_F_LIBS :=-lgfortran
GCC_LibPath :=-L"${MATLABROOT}/bin/glnxa64"
GCC_LDFLAGS :=$(LDFLAGS) -pthread -Wl,--version-script,"mexFunction.map" -Wl,-rpath-link,"${MATLABROOT
}/bin/glnxa64"
125
290
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
GCC_Release: C_LIBS:=$(GCC_C_LIBS)
GCC_Release: CPP_LIBS:=$(GCC_CPP_LIBS)
GCC_Release: F_LIBS:=$(GCC_F_LIBS)
GCC_Release: LibPath:=$(GCC_LibPath)
GCC_Release: MACROS :=$(GCC_MACROS) -DNDEBUG
GCC_Release: CFLAGS :=$(GCC_CFLAGS) -O2 -fwrapv
GCC_Release: CPPFLAGS :=$(GCC_CPPFLAGS) -O2 -fwrapv
GCC_Release: FFLAGS :=$(GCC_FFLAGS) -O2
GCC_Release: LDFLAGS :=$(GCC_LDFLAGS) -O
GCC_Debug: MACROS:=$(GCC_MACROS)
GCC_Debug: C_LIBS:=$(GCC_C_LIBS)
GCC_Debug: CPP_LIBS:=$(GCC_CPP_LIBS)
GCC_Debug: F_LIBS:=$(GCC_F_LIBS)
GCC_Debug: LibPath:=$(GCC_LibPath)
GCC_Debug: CFLAGS :=$(GCC_CFLAGS) -g
GCC_Debug: CPPFLAGS :=$(GCC_CPPFLAGS) -g
GCC_Debug: FFLAGS :=$(GCC_FFLAGS) -g
GCC_Debug: LDFLAGS :=$(GCC_LDFLAGS) -g
################################################
################################################
MINGW_CFLAGS :=$(CFLAGS) -fexceptions -fno-omit-frame-pointer -m64
MINGW_CPPFLAGS :=$(MINGW_CFLAGS)
MINGW_C_LIBS :=-llibmx -llibmex -llibmat
MINGW_CPP_LIBS :=-lm -llibMatlabDataArray -llibMatlabEngine
MINGW_LibPath :=-L"${MATLABROOT}/extern/lib/win64/mingw64"
MINGW_LDFLAGS :=$(LDFLAGS) -m64 -Wl,"ModuleDefinitionFile.def"
MINGW_Release: C_LIBS:=$(MINGW_C_LIBS)
MINGW_Release: CPP_LIBS:=$(MINGW_CPP_LIBS)
MINGW_Release: LibPath:=$(MINGW_LibPath)
MINGW_Release: MACROS :=$(MINGW_MACROS) -DNDEBUG
MINGW_Release: CFLAGS :=$(MINGW_CFLAGS) -O2 -fwrapv
MINGW_Release: CPPFLAGS :=$(MINGW_CPPFLAGS) -O2 -fwrapv
MINGW_Release: LDFLAGS :=$(MINGW_LDFLAGS) -s
MINGW_Debug: C_LIBS:=$(MINGW_C_LIBS)
MINGW_Debug: CPP_LIBS:=$(MINGW_CPP_LIBS)
MINGW_Debug: LibPath:=$(MINGW_LibPath)
MINGW_Debug: CFLAGS :=$(MINGW_CFLAGS) -g
MINGW_Debug: CPPFLAGS :=$(MINGW_CPPFLAGS) -g
MINGW_Debug: LDFLAGS :=$(MINGW_LDFLAGS) -g
################################################
################################################
#Callable Targets
MSVC_IVF_Release GCC_Release MINGW_Release: $(OutRootDir)/$(ReleaseDir)/$(MEX-File)
MSVC_IVF_Debug GCC_Debug MINGW_Debug: $(OutRootDir)/$(DebugDir)/$(MEX-File)
cleanDebug:
-$(rm_CMD) "$(OutRootDir)/$(DebugDir)"
@echo cleanDebug done
cleanRelease:
-$(rm_CMD) "$(OutRootDir)/$(ReleaseDir)"
@echo cleanRelease done
clean: cleanDebug cleanRelease
############################################################
# Pattern Rules
# Multiple targets cannot be used with pattern rules [https://www.gnu.org/software/make/manual/
html_node/Multiple-Targets.html]
$(OutRootDir)/$(ReleaseDir)/%.$(ObjExt): %.c | $(OutRootDir)/$(ReleaseDir)
$(CC) $(Compile_Flag) $(MACROS) $(CFLAGS) $< $(CompileOutFlag)"$@"
$(OutRootDir)/$(DebugDir)/%.$(ObjExt): %.c | $(OutRootDir)/$(DebugDir)
$(CC) $(Compile_Flag) $(MACROS) $(CFLAGS) $< $(CompileOutFlag)"$@"
$(OutRootDir)/$(ReleaseDir)/%.$(ObjExt): %.cpp | $(OutRootDir)/$(ReleaseDir)
$(CXX) $(Compile_Flag) $(MACROS) $(CPPFLAGS) $< $(CompileOutFlag)"$@"
291
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
$(OutRootDir)/$(DebugDir)/%.$(ObjExt): %.cpp | $(OutRootDir)/$(DebugDir)
$(CXX) $(Compile_Flag) $(MACROS) $(CPPFLAGS) $< $(CompileOutFlag)"$@"
$(OutRootDir)/$(ReleaseDir)/%.$(ObjExt): %.f90 | $(Mod_F_Release) $(OutRootDir)/$(ReleaseDir)
$(FC) $(Compile_Flag) $(MACROS) $(FFLAGS) $< $(ModOutFlag)"$(OutRootDir)/$(ReleaseDir)" $(
CompileOutFlag)"$@"
$(OutRootDir)/$(DebugDir)/%.$(ObjExt): %.f90 | $(Mod_F_Debug) $(OutRootDir)/$(DebugDir)
$(FC) $(Compile_Flag) $(MACROS) $(FFLAGS) $< $(ModOutFlag)"$(OutRootDir)/$(DebugDir)" $(
CompileOutFlag)"$@"
$(OutRootDir)/$(ReleaseDir)/%.mod: ../../%.f90 | $(OutRootDir)/$(ReleaseDir)
$(FC) $(Compile_Flag) $(MACROS) $(FFLAGS) $< $(ModOutFlag)"$(OutRootDir)/$(ReleaseDir)" $(
CompileOutFlag)"$(OutRootDir)/$(ReleaseDir)/$*.$(ObjExt)"
$(OutRootDir)/$(DebugDir)/%.mod: ../../%.f90 | $(OutRootDir)/$(DebugDir)
$(FC) $(Compile_Flag) $(MACROS) $(FFLAGS) $< $(ModOutFlag)"$(OutRootDir)/$(DebugDir)" $(
CompileOutFlag)"$(OutRootDir)/$(DebugDir)/$*.$(ObjExt)"
############################################################
# Create output directory
$(OutRootDir)/$(ReleaseDir) $(OutRootDir)/$(DebugDir):
-$(mkdir_CMD) $@
# Create the MEX-file
# Multiple targets cannot be used with pattern rules [https://www.gnu.org/software/make/manual/
html_node/Multiple-Targets.html]
$(OutRootDir)/$(ReleaseDir)/$(MEX-File): $(OBJ_C_Release) $(OBJ_CPP_Release) $(OBJ_F_Release)
$(OutRootDir)/$(DebugDir)/$(MEX-File): $(OBJ_C_Debug) $(OBJ_CPP_Debug) $(OBJ_F_Debug)
$(OutRootDir)/$(ReleaseDir)/$(MEX-File) $(OutRootDir)/$(DebugDir)/$(MEX-File):
$(LD) $(LDFLAGS) $^ $(LibPath) $(C_LIBS) $(CPP_LIBS) $(F_LIBS) $(LinkOutFlag)$@
• On Linux;
– Only GCC is supported for creating C, C++ and Fortran MEX-files [sec. 5.6.1]
– To build the C MEX-file, open a shell and execute:
$ cd PathTo/Mex/SDOF_FreeResponse/C_MEX
∗ To build an optimized MEX-file, execute
$ make -f ../Makefile GCC_Release
∗ To build an MEX-file suitable for debugging, execute
$ make -f ../Makefile GCC_Debug
– To build the C++ MEX-file, open a shell and execute:
$ cd PathTo/Mex/SDOF_FreeResponse/Cpp_MEX
∗ To build an optimized MEX-file, execute
$ make -f ../Makefile GCC_Release LD=g++
∗ To build an MEX-file suitable for debugging, execute
$ make -f ../Makefile GCC_Debug LD=g++
– To build the Fortran MEX-file, open a shell and execute:
$ cd PathTo/Mex/SDOF_FreeResponse/Fortran_MEX
∗ To build an optimized MEX-file, execute
$ make -f ../Makefile GCC_Release LD=gfortran
∗ To build an MEX-file suitable for debugging, execute
$ make -f ../Makefile GCC_Debug LD=gfortran
292
• On Windows,
– MS Visual C++ (MSVC) Compiler is supported for creating C and C++ MEXfiles [sec. 5.6.1]
– Intel Fortran Compiler is supported for creating C and C++ MEX-files [sec.
5.6.1]
– GCC (available on Windows through MinGW-w64) is supported for creating C
and C++ MEX-files [sec. 5.6.1]
– To build the C MEX-file, open a shell and execute:
$ cd PathTo/Mex/SDOF_FreeResponse/C_MEX
∗ To build an optimized MEX-file using the MSVC Compiler, execute:
Start Menu . Visual Studio 2019 . x64 Native
Tools Command Prompt for VS 2019
From the opened command prompt, execute
$ make -f ../Makefile
MSVC_IVF_Release
∗ To build an MEX-file suitable for debugging using the MSVC Compiler,
execute:
Start Menu . Visual Studio 2019 . x64 Native Tools Command Prompt for
VS 2019
$ make -f ../Makefile MSVC_IVF_Release
∗ To build an optimized MEX-file using the MinGW-w64 Compiler, execute:
$ make -f ../Makefile MINGW_Release
∗ To build an MEX-file suitable for debugging using the MinGW-w64 Compiler, execute:
$ make -f ../Makefile MINGW_Release
– To build the C++ MEX-file, open a shell and execute:
$ cd PathTo/Mex/SDOF_FreeResponse/Cpp_MEX
∗ To build an optimized MEX-file using the MSVC Compiler, execute:
Start Menu . Visual Studio 2019 . x64 Native Tools Command Prompt for
VS 2019
$ make -f ../Makefile MSVC_IVF_Release
∗ To build an MEX-file suitable for debugging using the MSVC Compiler,
execute:
Start Menu . Visual Studio 2019 . x64 Native Tools Command Prompt for
VS 2019
$ make -f ../Makefile MSVC_IVF_Debug
∗ To build an optimized MEX-file using the MinGW-w64 Compiler, execute:
$ make -f ../Makefile MINGW_Release LD=g++
293
∗ To build an MEX-file suitable for debugging using the MinGW-w64 Compiler, execute:
$ make -f ../Makefile MINGW_Debug LD=g++
– To build the Fortran MEX-file, open a shell and execute:
$ cd PathTo/Mex/SDOF_FreeResponse/Fortran_MEX
∗ To build an optimized MEX-file using Intel Fortran Compiler, execute:
Start Menu . Intel Parallel Studio XE 2019 .
Compiler 19.0 for Intel 64 Visual Studio 2019 Environment
From the opened command prompt, execute
$ make -f ../Makefile
MSVC_IVF_Release
∗ To build an MEX-file suitable for debugging using Intel Fortran Compiler,
execute:
$ make -f ../Makefile MSVC_IVF_Debug
5.6.2.5
Building using CMake
Getting Started with CMake
• Refer to appendix K for getting started with CMake
Project idea 14 (Building MEX-File using CMake)
Build and debug the MEX-files of sec. 5.6.2 using CMake.
• You can start by using the “CMake Tools” VSCode extention [https://
marketplace.visualstudio.com/items?itemName=ms-vscode.cmake-tools]
– There are helpful tutorial links in this page
• Check also the following:
– www.40tude.fr/compile-cpp-code-with-vscode-cmake-nmake/
• Document your experience
294
5.6.2.6
Building and Debugging using Eclipse
Getting Started with Eclipse
• Refer to appendix M for getting started with Eclipse
• On Windows, make sure that MinGW-w64 is correctly installed [sec. G.4]
468
Laboratory 20 (Building and Debugging MEX-Files using Eclipse)
• Useful Information are available @:
– www.mathworks.com/matlabcentral/answers/423263-how-to-debugmex-files-in-eclipse-mars-compiled-with-mingw64-and-the-gflag-in-matlab-r2017b-and
– http://fliu37.com/index.php/2016/06/25/create-mex-projectusing-linux-eclipse/
– http://stackoverflow.com/questions/14471276/is-it-possibleto-debug-mex-code-with-eclipse
– www.ibm.com/developerworks/library/os-eclipse-cdt-debug1/
index.html
– www.ibm.com/developerworks/library/os-eclipse-cdt-debug2/
index.html
Debugging Option (1) (Recommended): Attach the Debugger to already running Matlab
Windows
• www.mathworks.com/matlabcentral/answers/241291-how-to-debugmex-file-compiled-with-mingw64-and-g-flags
Linux
• GDB needs elevated permissions to attach to a process. When using attach to
process, you need to provide your password before the debugging session can
begin [https://code.visualstudio.com/docs/languages/cpp].
• Check https://github.com/Microsoft/MIEngine/wiki/Troubleshootattaching-to-processes-using-GDB
Debugging Option (2): Start Matlab from the Debugger
Windows
Linux
• www.mathworks.com/help/matlab/matlab_external/debugging-onlinux-platforms.html
• www.mathworks.com/matlabcentral/answers/91741-how-do-i-debugc-mex-files-under-unix
295
• https://stackoverflow.com/questions/14471276/is-it-possibleto-debug-mex-code-with-eclipse
• Build the MEX-file (shared library) using the “Debug” configuration
• In the code of the shared library, set breakpoint(s) where you like
• In the project options, specify the path to matlab.exe (or the program that calls the
shared library)
• Press F5, or the “Start Debugging” toolbar button. This will launch Matlab
• From Matlab, call the shared library you have built under the “Debug” configuration
– Visual Studio will stop the mex-File execution at the breakpoint you have specified in its source code and enables you to step in, examine variables, . . .
296
5.7
Questions
5.1. What is new in
(a) Fortran 90
(c) Fortran 2018
(b) Fortran 2003
5.2. Specify the LAPACK subroutines that
(a) solve a system of linear equations
(b) invert a matrix
(c) calculate the eigenvalues and eigenvectors of a matrix
5.3. Make a short survey about the following libraries
(a) IMSL
(b) Boost
470
297
This page is intentionally left blank!
298
Part 6
Matlab Alternatives
Why not Just use Matlab?∗
Matlab is excellent for algorithm prototyping, but you will need to use a real programming
language (e.g., C, C++, Fortran, . . . ) when the:
• problem is very large
• speed is critical
• algorithm is embedded in a larger system
• you want to avoid proprietary SW
471
Matlab Wonderful Features
• Array expressions
A=B+C./D.*E ,: A, B, C, D & E are arrays
• Advanced array indexing
A col=B(:,1)+C col.*transpose(D(2,:));
• Large and powerful mathematical library
– inv, eig, fzero, fmin, . . .
• Wonderful visualizations
– 2D & 3D
472
∗
Prof. S. Boyd, EE364b, Stanford University
299
Matlab vs other Alternatives
300
Default data type
Complex data type
Exponentiation
operator
Case sensitive
Arrays storage∗
Array indexing
Start index
Array arithmetic
Advanced indexing†
Subroutine name
∗
Matlab
double
built in
^
Yes
column-wise
A mat(1,2,3)
1
Yes
Yes
function
Passing subroutine
input arguments
by value
Strict compiler
checking§
Functions can return
several outputs
No
Yes
Important for mixed language programming
Advanced indexing can refer to entire array sections
‡
C++ only
§
Demands proper declarations. Crucial for proper function calling.
†
Fortran
integer/single
built in
**
C/C++
none
No
pow( , )
No
Yes
column-wise
row-wise
A mat(1,2,3) A mat[1][2][3]
1
0
Yes
No
Yes
No
SUBROUTINE
none
&
FUNCTION
by reference
by value
(default)
by reference‡
No
Yes
No
No
Python
Julia
**
built in
^
row-wise
A mat[1,2,3]
0
Yes
Yes
column-wise
A mat[1,2,3]
1
Yes
Yes
by reference
Yes
Yes
Row-wise vs Column-wise Arrays
474
6.1
Sample Matlab Codes
6.1.1
Simple Example
• Implementation is available as open source @ https://github.com/ahmed-rashed/
PortMatlab_remote
Code 6.1: Free Response Matlab function
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function x_vec=Free_Response(w_n,zeta,x0,v0,t_vec)
if zeta==0
A=sqrt(x0^2+v0^2/w_n^2);
theta=atan2(x0*w_n,v0);
x_vec=A*sin(w_n*t_vec+theta);
elseif zeta<1
w_d=w_n*sqrt(1-zeta^2);
B=sqrt(x0^2*w_n^2+2*zeta*w_n*x0*v0+v0^2)/w_d;
phi=atan2(x0*w_d,(zeta*w_n*x0+v0));
x_vec=B*exp(-zeta*w_n*t_vec).*sin(w_d*t_vec+phi);
elseif zeta==1
x_vec=exp(-w_n*t_vec).*(x0+(w_n*x0+v0)*t_vec);
elseif zeta>1
temp=w_n*sqrt(zeta^2-1);
C=((temp-zeta*w_n)*x0-v0)/2/temp;
D=((temp+zeta*w_n)*x0+v0)/2/temp;
x_vec=exp(-zeta*w_n*t_vec).*(C*exp(-temp*t_vec)+D*exp(temp*t_vec));
end
• Code 6.1 above is called from code 6.2 below to plot the following curves
Code 6.2: FreeResponse main Matlab script
1
2
3
clc
clearvars
close all
301
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
x0=-1;
v0=0;
w_n=1;
f_n=w_n/2/pi;
T_n=1/f_n;
zeta_vec=[0,.1,.2,.4,1/sqrt(2),1,2];
legend_str_vec="$\zeta = "+zeta_vec+’$’;
legend_str_vec(5)="$\zeta=1/\sqrt{2}$";
t_vec=linspace(0,2*T_n,500);
figure
hold all
for n=1:length(zeta_vec)
x_vec=Free_Response(w_n,zeta_vec(n),x0,v0,t_vec);
% x_vec1=C_MEX(w_n,zeta_vec(n),x0,v0,t_vec);clear C_MEX;max(abs(x_vec1-x_vec)),x_vec=
x_vec1;
% x_vec2=Cpp_MEX(w_n,zeta_vec(n),x0,v0,t_vec);clear Cpp_MEX;max(abs(x_vec2-x_vec)),
x_vec=x_vec2;
% x_vec3=Fortran_MEX(w_n,zeta_vec(n),x0,v0,t_vec);clear Fortran_MEX;max(abs(x_vec3x_vec)),x_vec=x_vec3;
plot(t_vec/T_n,x_vec)
end
title(’$x(t)$ for $\omega_{n}=1$, $x_{0}=-1$ and $v_{0}=0$’,’interpreter’,’latex’);
xlabel(’$t/T_{n}\qquad,:T_{n}=1/f_{n}=2\pi/\omega_{n}$’,’interpreter’,’latex’);
legend(legend_str_vec,’interpreter’,’latex’,’Location’,’SouthEast’);
grid on
export_figure(gcf,’’,"SDOF_1")
1
0.8
0.6
0.4
0.2
0
-0.2
-0.4
-0.6
-0.8
-1
0
0.5
1
302
1.5
2
6.1.2
Comprehensive Example
Computational Functions
• Implementation is available as open source @ https://github.com/ahmed-rashed/
PortMatlab_remote
Code 6.3: MDOF FRF Visc slow Matlab function
1
2
3
4
5
6
7
8
9
10
function H_cols=MDOF_FRF_Visc_slow(M_mat,C_mat,K_mat,w_col,ii_row,jj_row)
n_f_points=size(w_col,1);
H_cols=zeros(n_f_points,length(jj_row));
for ii=1:n_f_points
H_w=inv(-w_col(ii)^2*M_mat+1i*w_col(ii)*C_mat+K_mat);
ind_row=sub2ind(size(M_mat),ii_row,jj_row);
H_cols(ii,:)=H_w(ind_row);
end
Code 6.4: quad eig Matlab function
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function [Epsi_normalized,Val_vec]=quad_eig(K_mat,C_mat,M_mat)
N=size(M_mat,1);
N_mat=M_mat;
A=[-K_mat,0*M_mat;0*M_mat,N_mat];
B=[C_mat,M_mat;N_mat,0*M_mat];
[Phi,Val_mat] = eig(A,B);
Val_vec=diag(Val_mat);
B_r_vec=diag(Phi.’*B*Phi);
Phi_normalized=Phi;
for ii=1:2*N
Phi_normalized(:,ii)=Phi_normalized(:,ii)/sqrt(B_r_vec(ii));
end
Epsi_normalized=Phi_normalized(1:N,:);
Code 6.5: MDOF Eig Visc Matlab function
1
2
3
4
5
6
7
8
9
10
11
function [EigVectors_Normalized, EigValues_vec]=MDOF_Eig_Visc(M_mat, C_mat, K_mat,
isPropotional)
if nargin<4
isPropotional=false;
end
N=size(M_mat,1);
if isPropotional || all(all(C_mat==0)) %Undamped or proportional
[EigVectors_U,EigValues_U_mat]=eig(-K_mat,M_mat);
EigValues_U_vec=diag(EigValues_U_mat);
303
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
M_r_vec=diag(EigVectors_U.’*M_mat*EigVectors_U);
w_U_r_vec=sqrt(-EigValues_U_vec);
C_r_vec=diag(EigVectors_U.’*C_mat*EigVectors_U);
zeta_r_vec=C_r_vec./(2*M_r_vec.*w_U_r_vec);
w_d_r_vec=w_U_r_vec.*sqrt(1-zeta_r_vec.^2);
EigValues_vec_temp=-zeta_r_vec.*w_U_r_vec+1i*w_d_r_vec;
EigValues_vec=nan(2*N,1);
EigValues_vec(1:2:2*N-1)=EigValues_vec_temp;
EigValues_vec(2:2:2*N)=conj(EigValues_vec_temp);
EigVectors_Normalized=nan(N,2*N);
EigVectors_Normalized(:,1:2:2*N-1)=EigVectors_U*diag(1./sqrt(1i*2*w_d_r_vec.*
M_r_vec));
EigVectors_Normalized(:,2:2:2*N)=conj(EigVectors_Normalized(:,1:2:2*N-1));
else %Non-proportional
[EigVectors_Normalized,EigValues_vec]=quad_eig(K_mat,C_mat,M_mat);
end
[~,Index]=sort(abs(imag(EigValues_vec(1:2:2*N-1))));
IIndex=nan(2*N,1);
IIndex(1:2:2*N-1)=2*Index-1;
IIndex(2:2:2*N)=2*Index;
EigValues_vec=EigValues_vec(IIndex);
EigVectors_Normalized=EigVectors_Normalized(:,IIndex);
Code 6.6: MDOF FRF Visc Matlab function
1
2
3
4
5
6
7
8
9
10
11
12
13
14
function H_w_n_m_cols=MDOF_FRF_Visc(EigValues_vec, EigVectors_Normalized, w_column,
n_row, m_row)
N=size(EigVectors_Normalized,1);
N_w=size(w_column,1);
if (any(size(n_row)~=size(m_row)));error(’Dimensions of n_row and m_row must be
identical’);end
N_cols=size(n_row,2);
H_w_n_m_cols_SDOF=zeros(N_w,N_cols);
H_w_n_m_cols=zeros(N_w,N_cols);
A_ind_row=sub2ind([N,N],n_row,m_row);
for r=1:2*N
A_r=EigVectors_Normalized(:,r)*EigVectors_Normalized(:,r).’;
A_r_temp_row=A_r(A_ind_row);
H_w_n_m_cols_SDOF=H_w_n_m_cols_SDOF+(1./(1i*w_column-EigValues_vec(r)))*
A_r_temp_row;
15
16
if imag(EigValues_vec(r))~=0 && mod(r,2)~=0 %complex eigenvalue and odd r
17
continue
18
end
19
20
H_w_n_m_cols=H_w_n_m_cols+H_w_n_m_cols_SDOF;
21
H_w_n_m_cols_SDOF=zeros(N_w,N_cols);
22 end
304
Graphics Functions
• Implementation is available as open source @ https://github.com/ahmed-rashed/
PortMatlab_remote
Code 6.7: plot FRF 3d Matlab function
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
function plot_FRF_3d(f_vec,H_vec, ...
f_label,H_label,DispRealImag,DispMagLines) %Optional arguments
curve_h=plot3(f_vec,real(H_vec),imag(H_vec));
view(30,20);
grid on
DataAspectRatio=get(gca,’DataAspectRatio’);
set(gca,’DataAspectRatio’,[DataAspectRatio(1),DataAspectRatio(2),DataAspectRatio(2)]);
if nargin<3
f_label=’$f$ (Hz)’;
else
if isempty(f_label)
f_label=’$f$ (Hz)’;
end
end
indices=strfind(f_label,’$’);
if length(indices)<2,error(’f_label does not include LaTeX inline equation !!’),end
H_real_multiplier=’’;
if nargin<4
H_Latex_subtitle=’H’;
else
if isempty(H_label)
H_Latex_subtitle=’H’;
elseif iscellstr(H_label)
if length(H_label)~=2
error(’If H_label is cell string, it must have two elements; one for
H_Latex_subtitle and the other for H_real_multiplier’)
end
H_Latex_subtitle=H_label{1};
H_real_multiplier=H_label{2};
else
H_Latex_subtitle=H_label;
end
end
H_Latex_subtitle=[H_Latex_subtitle,’\left(’,f_label(indices(1)+1:indices(2)-1),’\right
)’];
38
39 xlabel(f_label,’interpreter’, ’latex’);
40 ylabel([’$\Re\left(’,H_Latex_subtitle,’\right)’,H_real_multiplier,’$’], ’interpreter’,
’latex’)
41 zlabel([’$\Im\left(’,H_Latex_subtitle,’\right)’,H_real_multiplier,’$’], ’interpreter’,
’latex’)
42
43 if nargin>4
44
nexta = get(gca,’NextPlot’);
45
nextf = get(gcf,’NextPlot’);
46
305
47
48
49
50
51
52
53
54
55
56
57
if DispRealImag
set(gca,’YLimMode’,’manual’);
set(gca,’ZLimMode’,’manual’);
ylims=ylim;
zlims=zlim;
set(gcf,’NextPlot’,’add’);
set(gca,’NextPlot’,’add’);
%Nyquist
hLine=line(f_vec*0,real(H_vec),imag(H_vec),’Color’,get(curve_h,’Color’),’
LineStyle’,get(curve_h,’LineStyle’),’LineWidth’,get(curve_h,’LineWidth’)/3)
;
set(get(get(hLine,’Annotation’),’LegendInformation’),’IconDisplayStyle’,’off’);
% Exclude line from legend
58
59
60
61
%Imag
hLine=line(f_vec,max(ylims)*ones(size(f_vec)),imag(H_vec),’Color’,get(curve_h,’
Color’),’LineStyle’,get(curve_h,’LineStyle’),’LineWidth’,get(curve_h,’
LineWidth’)/3);
set(get(get(hLine,’Annotation’),’LegendInformation’),’IconDisplayStyle’,’off’);
% Exclude line from legend
62
63
64
65
%Real
hLine=line(f_vec,real(H_vec),min(zlims)*ones(size(f_vec)),’Color’,get(curve_h,’
Color’),’LineStyle’,get(curve_h,’LineStyle’),’LineWidth’,get(curve_h,’
LineWidth’)/3);
set(get(get(hLine,’Annotation’),’LegendInformation’),’IconDisplayStyle’,’off’);
% Exclude line from legend
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
end
if nargin>5
if DispMagLines
n_f=length(f_vec);
n_MagLines=DispMagLines;
delta_temp=floor(n_f/n_MagLines);
iidx=1:delta_temp:n_f;
set(gcf,’NextPlot’,’add’);
set(gca,’NextPlot’,’add’);
setappdata(gca,’PlotHoldStyle’,false);
if n_f==size(H_vec,1)
H_temp=H_vec(iidx,:);
else %Assuming that n_f==size(H_vec,2)
H_temp=H_vec(:,iidx);
end
handle=quiver3(f_vec(iidx),0*f_vec(iidx),0*f_vec(iidx),0*f_vec(iidx),real(
H_temp),imag(H_temp),0,’ShowArrowHead’,’off’,’LineWidth’,get(curve_h,’
LineWidth’)/3);
set(get(get(handle,’Annotation’),’LegendInformation’),’IconDisplayStyle’,’
off’); % Exclude line from legend
handle2=plot3(f_vec(iidx),real(H_temp),imag(H_temp),’.’,’MarkerSize’,15,’
MarkerEdgeColor’,get(handle,’Color’));
set(get(get(handle2,’Annotation’),’LegendInformation’),’IconDisplayStyle’,’
off’); % Exclude line from legend
306
91
92
end
93
end
94
95
set(gcf,’NextPlot’,nexta);
96
set(gca,’NextPlot’,nextf);
97 end
Code 6.8: plot FRF Nyq Matlab function
1
2
3
4
5
6
7
8
9
10
11
12
function curve_handle=plot_FRF_Nyq(H_vec, ...
H_label,DispMagLines,varargin) %Optional arguments
H_real_multiplier=’’;
if nargin<2
H_Latex_subtitle=’H’;
else
if isempty(H_label)
H_Latex_subtitle=’H’;
elseif iscellstr(H_label)
if length(H_label)~=2
error(’If H_label is cell string, it must have two elements; one for
H_Latex_subtitle and the other for H_real_multiplier’)
end
H_Latex_subtitle=H_label{1};
H_real_multiplier=H_label{2};
else
H_Latex_subtitle=H_label;
end
end
H_Latex_subtitle=[H_Latex_subtitle,’\left(f \right)’];
13
14
15
16
17
18
19
20
21
22 curve_handle=plot(real(H_vec),imag(H_vec),varargin{:});
23 if nargin>2
24
if DispMagLines
25
n_f=length(H_vec);
26
n_MagLines=DispMagLines;
27
delta_temp=floor(n_f/n_MagLines);
28
iidx=1:delta_temp:n_f;
29
30
set(gcf,’NextPlot’,’add’);
31
set(gca,’NextPlot’,’add’);
32
setappdata(gca,’PlotHoldStyle’,false);
33
34
if n_f==size(H_vec,1)
35
H_temp_vec=H_vec(iidx,:);
36
else %Assuming that n_f==size(H_vec,2)
37
H_temp_vec=H_vec(:,iidx);
38
end
39
40
handle=quiver(0*H_temp_vec,0*H_temp_vec,real(H_temp_vec),imag(H_temp_vec),0,’
ShowArrowHead’,’off’,’LineWidth’,get(curve_handle,’LineWidth’)/3);
41
set(get(get(handle,’Annotation’),’LegendInformation’),’IconDisplayStyle’,’off’)
; % Exclude line from legend
42
43
handle2=plot(real(H_temp_vec),imag(H_temp_vec),’.’,’MarkerSize’,15,’
MarkerEdgeColor’,get(handle,’Color’));
307
44
45
46
47
48
49
50
51
52
53
set(get(get(handle2,’Annotation’),’LegendInformation’),’IconDisplayStyle’,’off’
); % Exclude line from legend
end
end
vax=axis;
DataAspectRatio=get(gca,’DataAspectRatio’);
set(gca,’DataAspectRatio’,[DataAspectRatio(1),DataAspectRatio(1),DataAspectRatio(3)]);
axis(vax);
xlabel([’$\Re\left(’,H_Latex_subtitle,’\right)’,H_real_multiplier,’$’], ’interpreter’,
’latex’)
54 ylabel([’$\Im\left(’,H_Latex_subtitle,’\right)’,H_real_multiplier,’$’], ’interpreter’,
’latex’)
55 grid on
Code 6.9: plot FRF r i Matlab function
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
function [ax_r,ax_i,h1,h2]=plot_FRF_r_i(f_vec,H_vec, ...
ax_r,ax_i,f_label,H_label) %Optional arguments
if nargin<3
ax_r=subplot(2,1,1);
ax_i=subplot(2,1,2);
end
if nargin<5
f_label=’$f$ (Hz)’;
else
if isempty(f_label)
f_label=’$f$ (Hz)’;
end
end
indices=strfind(f_label,’$’);
if length(indices)<2,error(’f_label does not include LaTeX inline equation !!’),end
H_real_multiplier=’’;
if nargin<6
H_Latex_subtitle=’H’;
else
if isempty(H_label)
H_Latex_subtitle=’H’;
elseif iscellstr(H_label)
if length(H_label)~=2
error(’If H_label is cell string, it must have two elements; one for
H_Latex_subtitle and the other for H_real_multiplier’)
end
H_Latex_subtitle=H_label{1};
H_real_multiplier=H_label{2};
else
H_Latex_subtitle=H_label;
end
end
H_Latex_subtitle=[H_Latex_subtitle,’\left(’,f_label(indices(1)+1:indices(2)-1),’\right
)’];
36
37 h1=plot(ax_r,f_vec,real(H_vec));
38 %xlabel(ax_r,f_label, ’interpreter’, ’latex’);
308
39 %set(ax_r,’XTick’,[]);
40 set(ax_r,’XTickLabel’,[]);
41 ylabel(ax_r,[’$\Re\left(’,H_Latex_subtitle,’\right)’,H_real_multiplier,’$’], ’
interpreter’, ’latex’)
42 set(ax_r,’xGrid’,’on’,’YGrid’,’on’);
43
44 h2=plot(ax_i,f_vec,imag(H_vec));
45 xlabel(ax_i,f_label, ’interpreter’, ’latex’);
46 ylabel(ax_i,[’$\Im\left(’,H_Latex_subtitle,’\right)’,H_real_multiplier,’$’], ’
interpreter’, ’latex’)
47 set(ax_i,’xGrid’,’on’,’YGrid’,’on’);
Code 6.10: plot FRF mag phase Matlab function
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
function [ax_mag_h,ax_phase_h,curve_mag_h,curve_phase_h]= ...
plot_FRF_mag_phase(f_vec,H_vec, ...
islin,ax_mag_h,ax_phase_h,f_label,H_label,DispMagLines,
maxPhaseLag, ... %Optional arguments
varargin)
%To create a nonvalid graphics object (axis handle), use eigther:
%1) h=gobjects
%2) h=matlab.graphics.GraphicsPlaceholder
if nargin<3
islin=true;
else
if isempty(islin)
islin=true;
end
end
if nargin<4
ax_mag_h=subplot(4,1,[1:3]);
else
if isempty(ax_mag_h)
ax_mag_h=subplot(4,1,[1:3]);
end
end
if nargin<5
ax_phase_h=subplot(4,1,4);
else
if isempty(ax_phase_h)
ax_phase_h=subplot(4,1,4);
end
end
if nargin<6
f_label=’$f$ (Hz)’;
else
if isempty(f_label)
f_label=’$f$ (Hz)’;
end
end
indices=strfind(f_label,’$’);
if length(indices)<2,error(’f_label does not include LaTeX inline equation !!’),end
H_real_multiplier=’’;
309
44 if nargin<7
45
H_Latex_subtitle=’H’;
46 else
47
if isempty(H_label)
48
H_Latex_subtitle=’H’;
49
elseif iscellstr(H_label)
50
if length(H_label)~=2
51
error(’If H_label is cell string, it must have two elements; one for
H_Latex_subtitle and the other for H_real_multiplier’)
52
end
53
H_Latex_subtitle=H_label{1};
54
H_real_multiplier=H_label{2};
55
else
56
H_Latex_subtitle=H_label;
57
end
58 end
59 H_Latex_subtitle=[H_Latex_subtitle,’\left(’,f_label(indices(1)+1:indices(2)-1),’\right
)’];
60
61 curve_mag_h=plot(ax_mag_h,f_vec,abs(H_vec),varargin{:});
62 n_f=length(f_vec);
63
64 if nargin>7
65
if DispMagLines
66
n_MagLines=DispMagLines;
67
delta_temp=floor(n_f/n_MagLines);
68
iidx=1:delta_temp:n_f;
69
70
set(gcf,’NextPlot’,’add’);
71
set(gca,’NextPlot’,’add’);
72
setappdata(gca,’PlotHoldStyle’,false);
73
74
if n_f==size(H_vec,1)
75
H_temp=H_vec(iidx,:);
76
else %Assuming that n_f==size(H_vec,2)
77
H_temp=H_vec(:,iidx);
78
end
79
80
handle=stem(ax_mag_h,f_vec(iidx),abs(H_temp),’LineWidth’,get(curve_mag_h,’
LineWidth’)/3,’Marker’,’none’);
81
set(get(get(handle,’Annotation’),’LegendInformation’),’IconDisplayStyle’,’off’)
; % Exclude line from legend
82
83
handle2=plot(ax_mag_h,f_vec(iidx),abs(H_temp),’.’,’MarkerSize’,15,’
MarkerEdgeColor’,get(handle,’Color’));
84
set(get(get(handle2,’Annotation’),’LegendInformation’),’IconDisplayStyle’,’off’
); % Exclude line from legend
85
end
86 end
87
88 if nargin<9
89
maxPhaseLag=[];
90 end
91
92 if islin(1)
93
set(ax_mag_h,’YScale’,’lin’)
94 else
95
set(ax_mag_h,’YScale’,’log’)
310
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
end
if length(islin)>1
if islin(2)
set(ax_mag_h,’XScale’,’lin’)
if isgraphics(ax_phase_h),set(ax_phase_h,’XScale’,’lin’),end
else
set(ax_mag_h,’XScale’,’log’)
if isgraphics(ax_phase_h),set(ax_phase_h,’XScale’,’log’),end
end
end
if isgraphics(ax_phase_h)
set(ax_mag_h,’XTickLabel’,[]);
else
xlabel(ax_mag_h,f_label, ’interpreter’, ’latex’)
end
% if iscell(H_Latex_subtitle)
% legStr=cell(size(H_Latex_subtitle));
% for ii=1:length(H_Latex_subtitle)
% legStr{ii}=[’$\left|’,H_Latex_subtitle{ii},’\right|$’];
% end
% legend(ax_mag_h,legStr, ’interpreter’, ’latex’)
% else
ylabel(ax_mag_h,[’$\left|’,H_Latex_subtitle,’\right|’,H_real_multiplier,’$’], ’
interpreter’, ’latex’)
% end
set(ax_mag_h,’xGrid’,’on’,’YGrid’,’on’);
%Plot the phase
if isgraphics(ax_phase_h)
H_angle_vec=correctedPhase(H_vec,maxPhaseLag);
curve_phase_h=plot(ax_phase_h,f_vec,H_angle_vec,varargin{:});
if nargin>7
if DispMagLines
set(gcf,’NextPlot’,’add’);
set(gca,’NextPlot’,’add’);
setappdata(gca,’PlotHoldStyle’,false);
if n_f==size(H_vec,1)
H_angle_vec_temp=H_angle_vec(iidx,:);
else %Assuming that n_f==size(H_vec,2)
H_angle_vec_temp=H_angle_vec(:,iidx);
end
handle2=plot(ax_phase_h,f_vec(iidx),H_angle_vec_temp,’.’,’MarkerSize’,15,’
MarkerEdgeColor’,get(handle,’Color’));
set(get(get(handle2,’Annotation’),’LegendInformation’),’IconDisplayStyle’,’
off’); % Exclude line from legend
141
142
143
144
145
146
147
148
149
150
end
end
xlabel(ax_phase_h,f_label, ’interpreter’, ’latex’)
% if iscell(H_Latex_subtitle)
% for ii=1:length(H_Latex_subtitle)
% legStr{ii}=[’$\angle ’,H_Latex_subtitle{ii},’$’];
% end
% legend(ax_phase_h,legStr, ’interpreter’, ’latex’)
311
151
152
% else
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
% end
ylabel(ax_phase_h,[’$\angle \left(’,H_Latex_subtitle,’\right)$’], ’interpreter’
, ’latex’)
yStep=pi;
%yTicks=get(ax_phase_h,’YTick’);
%set(ax_phase_h,’YTick’,yStep*[floor(yTicks(1)/yStep):ceil(yTicks(end)/yStep)]);
if strcmp(get(ax_phase_h,’YLimMode’),’manual’)
ylimits=get(ax_phase_h,’ylim’);
yLim_min=min(yStep*floor(min(min(H_angle_vec))/yStep),ylimits(1));
yLim_max=max(yStep*ceil(max(max(H_angle_vec))/yStep),ylimits(2));
else
yLim_min=yStep*floor(min(min(H_angle_vec))/yStep);
yLim_max=yStep*ceil(max(max(H_angle_vec))/yStep);
end
N_ticks=round((yLim_max-yLim_min)/yStep)+1;
if N_ticks>6
yStep=yStep*round(N_ticks/6);
end
yTicks=[yLim_min:yStep:yLim_max];
N_ticks=length(yTicks);
set(ax_phase_h,’YTick’,yTicks);
yTickLabels=strings(1,N_ticks);
for ii=1:N_ticks
if yTicks(ii)==0
yTickLabels(ii)=’$0$’;
elseif yTicks(ii)==pi
yTickLabels(ii)=’$\pi$’;
elseif yTicks(ii)==-pi
yTickLabels(ii)=’$-\pi$’;
else
yTickLabels(ii)="$"+(yTicks(ii)/pi)+’\pi$’;
end
end
ax_phase_h.YAxis.TickLabelInterpreter=’latex’;
set(ax_phase_h,’YTickLabel’,yTickLabels);
if yLim_min~=yLim_max
ylim(ax_phase_h,[yLim_min,yLim_max])
end
set(ax_phase_h,’xGrid’,’on’,’YGrid’,’on’);
set(ax_phase_h,’YMinorTick’,’on’);
end
Auxiliary Functions
• Implementation is available as open source @ https://github.com/ahmed-rashed/
PortMatlab_remote
Code 6.11: N DOF sys Matlab function
1
2
3
4
5
function [M_mat,C_mat,K_mat]=N_DOF_sys(m_vec,c_vec,k_vec)
N=length(m_vec);
M_mat=diag(m_vec);
C_mat=diag(c_vec(1:N)+c_vec(2:N+1))+diag(-c_vec(2:N),1)+diag(-c_vec(2:N),-1);
312
6
K_mat=diag(k_vec(1:N)+k_vec(2:N+1))+diag(-k_vec(2:N),1)+diag(-k_vec(2:N),-1);
Code 6.12: correctedPhase Matlab function
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
function H_angle_vec=correctedPhase(H_vec, ...
maxPhaseLag) %Optional arguments
if nargin<2
maxPhaseLag=-pi;
else
if isempty(maxPhaseLag)
maxPhaseLag=-pi;
end
end
n_f=length(H_vec);
H_angle_vec=angle(H_vec);
H_angle_vec(abs(H_angle_vec)<1e3*eps)=0;
H_angle_vec(abs(H_angle_vec-pi)<1e3*eps)=pi;
H_angle_vec(abs(H_angle_vec+pi)<1e3*eps)=-pi;
H_angle_vec(abs(H_vec)==0)=nan;
%Force phase to be less than maxPhaseLag
indd=H_angle_vec-maxPhaseLag>0;
H_angle_vec(indd)=H_angle_vec(indd)-2*pi*ceil((H_angle_vec(indd)-maxPhaseLag)/2/pi);
%Force phase to be decreasing for jumps >= 45 deg
for ii=1:n_f-1
dd=H_angle_vec(ii+1)-H_angle_vec(ii);
if dd>=pi/4
H_angle_vec(ii+1)=H_angle_vec(ii+1)-2*pi*ceil(dd/2/pi);
end
end
H_angle_vec=unwrap(H_angle_vec);
313
478
Main Script
All the former codes are called from code 6.13 below to plot the following curves:
10 -3
1
10 -4
0.5
5
0
0
-0.5
-1
-5
10 -4
5
-10
0
1
-5
-15
0
10
0
20
30
40
10 -3
-10
-1
-15
0
4
5
10
15
20
25
30
35
40
5
10
15
20
25
30
35
40
10 -4
10 -2
2
10 -4
0
-2
10 -6
-4
10 -8
-6
-2
-3
-8
-4
-5
0
-10
-12
-5
0
5
10 -4
Code 6.13: MDOF FRF Visc main Matlab script
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
clearvars
clc
close all
f_final=40;
n_f_points=10000;
islin=0;
N=3;
m=10*ones(1,N);
c=8*ones(1,N+1);
k=[161000/2*ones(1,N),0];
ii_row=[1,1,1];
jj_row=[3,2,1];
314
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
[M,C,K]=N_DOF_sys(m,c,k);isProportional=false;
% C=zeros(size(M));isProportional=true;
% C=.0001*M+.0001*K;isProportional=true;
f_col=linspace(0,f_final,n_f_points).’;
w_col=2*pi*f_col;
%% Slow FRF
tic
H_cols0=MDOF_FRF_Visc_slow(M,C,K,w_col,ii_row,jj_row);
toc
tic
H_cols1=MDOF_FRF_Visc_Slow_Fortran(M,C,K,w_col,ii_row,jj_row);clear
MDOF_FRF_Visc_Slow_Fortran;
31 toc
32 max(max(abs(H_cols1-H_cols0)))
33
34 tic
35 H_cols2=MDOF_FRF_Visc_Slow_cpp(M,C,K,w_col,ii_row,jj_row);clear MDOF_FRF_Visc_Slow_cpp
;
36 toc
37 max(max(abs(H_cols2-H_cols0)))
38
39 %% Fast FRF
40 tic
41 [EigVectors_Normalized0, EigValues_vec0]=MDOF_Eig_Visc(M, C, K,isProportional);
42 H_cols3=MDOF_FRF_Visc(EigValues_vec0, EigVectors_Normalized0, w_col, ii_row, jj_row);
43 toc
44 max(max(abs(H_cols3-H_cols0)))
45 H_cols=H_cols3;
46
47 tic
48 [EigVectors_Normalized1, EigValues_vec1]=MDOF_Eig_Visc_Fortran(M, C, K,isProportional)
;clear MDOF_Eig_Visc_Fortran;
49 H_cols4=MDOF_FRF_Visc_Fortran(EigValues_vec1, EigVectors_Normalized1, w_col, ii_row,
jj_row);clear MDOF_FRF_Visc_Fortran;
50 toc
51 max(max(abs(EigVectors_Normalized1-EigVectors_Normalized0)))
52 max(abs(EigValues_vec1-EigValues_vec0))
53 max(max(abs(H_cols4-H_cols3)))
54 H_cols=H_cols4;
55
56 tic
57 [EigVectors_Normalized2, EigValues_vec2]=MDOF_Eig_Visc_cpp(M, C, K,isProportional);
clear MDOF_Eig_Visc_cpp;
58 H_cols5=MDOF_FRF_Visc_cpp(EigValues_vec2, EigVectors_Normalized2, w_col, ii_row,
jj_row);clear MDOF_FRF_Visc_cpp;
59 toc
60 max(max(abs(EigVectors_Normalized2-EigVectors_Normalized0)))
61 max(abs(EigValues_vec2-EigValues_vec0))
62 max(max(abs(H_cols5-H_cols3)))
63 H_cols=H_cols5;
64
65 tic
66 [EigVectors_Normalized3, EigValues_vec3]=MDOF_Eig_Visc_cpp_Armadillo(M, C, K,
isProportional);clear MDOF_Eig_Visc_cpp_Armadillo;
315
67 H_cols6=MDOF_FRF_Visc_cpp_Armadillo(EigValues_vec3, EigVectors_Normalized3, w_col,
ii_row, jj_row);clear MDOF_FRF_Visc_cpp_Armadillo;
68 toc
69 max(max(abs(EigVectors_Normalized3-EigVectors_Normalized0)))
70 max(abs(EigValues_vec3-EigValues_vec0))
71 max(max(abs(H_cols6-H_cols3)))
72 H_cols=H_cols6;
73
74 f_3d=figure;hold all
75
76 f_r_i=figure;
77 ax_r=subplot(2,1,1);hold all
78 ax_i=subplot(2,1,2);hold all
79
80 f_Nyq=figure;hold all
81
82 f_mag_phase=figure;
83 ax_mag=subplot(4,1,[1,2,3]);hold all
84 ax_phase=subplot(4,1,4);hold all
85
86 legend_str_vec=strings(length(jj_row),1);
87 for ii=1:length(jj_row)
88
legend_str_vec(ii)="$H_{1,"+jj_row(ii)+’}$’;
89
90
figure(f_3d)
91
plot_FRF_3d(f_col,H_cols(:,ii),’’,’’,1);
92
93
plot_FRF_r_i(f_col,H_cols(:,ii),ax_r,ax_i);
94
95
figure(f_Nyq)
96
plot_FRF_Nyq(H_cols(:,ii));
97
98
plot_FRF_mag_phase(f_col,H_cols(:,ii),islin,ax_mag,ax_phase);
99 end
100
101 figure(f_3d)
102 legend(legend_str_vec,’interpreter’,’latex’,’Location’,’bestOutside’)
103
104 figure(f_Nyq)
105 legend(legend_str_vec,’interpreter’,’latex’,’Location’,’bestOutside’)
106
107 legend(ax_r,legend_str_vec,’interpreter’,’latex’,’Location’,’NorthEast’)
108
109 legend(ax_mag,legend_str_vec,’interpreter’,’latex’,’Location’,’NorthEast’)
110
111 export_figure((1:4),’’,["H_MDOF_3D","H_MDOF_r_i","H_MDOF_Nyq","H_MDOF_mag_phase"])
316
6.2
Porting Matlab to C
Array expressions
• Not supported
Advanced array indexing
• Not supported
Mathematical library
• Built-in library is limited
• But there are many external libraries callable from C
– Example include BLAS, LAPACK, . . .
480
6.2.1
The Simple Example
Due to the lack of a graphics library accessible from C, only the computational function of sec.
6.1.1 are ported herein to C.
• Implementation is available as open source @ https://github.com/ahmed-rashed/
PortMatlab_remote
Code 6.14: C implementation of code 6.1
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
#include <stddef.h>
#include <math.h>
void Free_Response(const double* const p_w_n, const double* const p_zeta, const double
* const p_x0, const double* const p_v0, const double t_vec[], double x_vec[],
const size_t* const p_N)
{
if (*p_zeta==0)
{
double A=sqrt(*p_x0 * *p_x0 + *p_v0 * *p_v0 / *p_w_n / *p_w_n);
double theta=atan2(*p_x0 * *p_w_n, *p_v0);
int n;
for (n=0; n < (*p_N);n++)
{
x_vec[n]=A*sin(*p_w_n*t_vec[n]+theta);
}
}
else if (*p_zeta<1)
{
double w_d=*p_w_n*sqrt(1- *p_zeta * *p_zeta);
double B=sqrt(*p_x0 * *p_x0 * *p_w_n * *p_w_n+2 * *p_zeta * *p_w_n * *p_x0 * *
p_v0 + *p_v0 * *p_v0) / w_d;
double phi=atan2(*p_x0 * w_d,(*p_zeta * *p_w_n * *p_x0 + *p_v0));
int n;
for (n=0; n < *p_N;n++)
{
x_vec[n]=B * exp(-*p_zeta * *p_w_n * t_vec[n]) * sin(w_d * t_vec[n] + phi);
}
317
26
27
28
29
30
31
32
}
else if (*p_zeta==1)
{
int n;
for (n=0; n < *p_N;n++)
{
x_vec[n]=exp(- *p_w_n * t_vec[n]) * (*p_x0 + (*p_w_n * *p_x0 + *p_v0) *
t_vec[n]);
}
}
else if (*p_zeta > 1)
{
double temp=*p_w_n * sqrt(*p_zeta * *p_zeta - 1);
double C=((temp - *p_zeta * *p_w_n) * *p_x0 - *p_v0) / 2 / temp;
double D=((temp + *p_zeta * *p_w_n) * *p_x0 + *p_v0) / 2 / temp;
int n;
for (n=0; n < *p_N;n++)
{
x_vec[n]=exp(- *p_zeta * *p_w_n * t_vec[n]) * (C * exp(-temp * t_vec[n])+D
* exp(temp * t_vec[n]));
}
}
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48 }
return;
6.3
Porting Matlab to Fortran
Porting Matlab to Fortran
Array expressions
• already supported
• array arithmetic is optimized
Advanced array indexing
• already supported
Mathematical library
• Built-in library is better than C
– MATMUL is a built in function∗
• There are many external libraries callable from Fortran
– Example include BLAS, LAPACK, IMSL, . . .
∗
Hence, and since array arithmetic is supported, BLAS is almost useless within Fortran.
318
6.3.1
The Simple Example
Due to the lack of a graphics library accessible from Fortran, only the computational function
of sec. 6.1.1 are ported herein to Fortran.
• Implementation is available as open source @ https://github.com/ahmed-rashed/
PortMatlab_remote
Code 6.15: Fortran implementation of code 6.1
1 FUNCTION FREE_RESPONSE(w_n,zeta,x0,v0,t_vec,N)
2
USE, INTRINSIC :: ISO_C_BINDING, ONLY: C_SIZE_T
3
4
IMPLICIT NONE
5
INTEGER(C_SIZE_T), INTENT(IN) :: N
6
REAL(8) w_n,zeta,x0,v0,t_vec(N),FREE_RESPONSE(N)
7
REAL(8) A,theta,w_d,B,phi,temp,C,D
8
9
10
IF (zeta==0) THEN
11
A=DSQRT(x0**2+v0**2/w_n**2)
12
theta=DATAN2(x0*w_n,v0)
13
FREE_RESPONSE=A*DSIN(w_n*t_vec+theta)
14
ELSE IF (zeta<1) THEN
15
w_d=w_n*DSQRT(1-zeta**2)
16
B=DSQRT(x0**2*w_n**2+2*zeta*w_n*x0*v0+v0**2)/w_d
17
phi=DATAN2(x0*w_d,(zeta*w_n*x0+v0))
18
FREE_RESPONSE=B*DEXP(-zeta*w_n*t_vec)*DSIN(w_d*t_vec+phi)
19
ELSE IF (zeta==1) THEN
20
FREE_RESPONSE=DEXP(-w_n*t_vec)*(x0+(w_n*x0+v0)*t_vec)
21
ELSE IF (zeta>1) THEN
22
temp=w_n*DSQRT(zeta**2-1)
23
C=((temp-zeta*w_n)*x0-v0)/2/temp
24
D=((temp+zeta*w_n)*x0+v0)/2/temp
25
FREE_RESPONSE=DEXP(-zeta*w_n*t_vec)*(C*DEXP(-temp*t_vec)+D*DEXP(temp*t_vec))
26
END IF
27
28 END FUNCTION FREE_RESPONSE
6.3.2
The Comprehensive Example
Due to the lack of a graphics library accessible from Fortran, only the computational functions
of sec. 6.1.2 are ported herein to Fortran.
• Implementation is available as open source @ https://github.com/ahmed-rashed/
PortMatlab_remote
Code 6.16: Fortran implementation of code 6.3
1
2
3
4
5
6
FUNCTION MDOF_FRF_VISC_SLOW(M_mat,C_mat,K_mat,N,w_col,n_w_points,n_vec,m_vec,n_n_row)
USE, INTRINSIC :: ISO_C_BINDING, ONLY: C_SIZE_T
USE Matrix_LAPACK_interfaces
IMPLICIT NONE
INTEGER(C_SIZE_T), INTENT(IN) :: N,n_w_points,n_n_row
319
483
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
REAL(8), INTENT(IN) :: M_mat(N,N),C_mat(N,N),K_mat(N,N),w_col(n_w_points,1),n_vec(
n_n_row),m_vec(n_n_row)
COMPLEX(8) MDOF_FRF_VISC_SLOW(n_w_points,n_n_row)
INTEGER(C_SIZE_T) nn,mm
COMPLEX(8) i,H_w_mat(N,N)
REAL(8) pi
PARAMETER (pi=DATAN(1D0)*4D0, i=(0D0,1D0))
DO nn=1,n_w_points
H_w_mat=zInv(-w_col(nn,1)*w_col(nn,1)*M_mat+i*w_col(nn,1)*C_mat+K_mat,N)
DO mm=1,n_n_row
MDOF_FRF_VISC_SLOW(nn,mm)=H_w_mat(n_vec(mm),m_vec(mm))
END DO
END DO
END FUNCTION MDOF_FRF_VISC_SLOW
Code 6.17: Fortran implementation of code 6.4
1 SUBROUTINE quad_eig(K_mat,C_mat,M_mat,N,Epsi_normalized_mat,EigVal_vec)
2
USE, INTRINSIC :: ISO_C_BINDING, ONLY: C_SIZE_T
3
USE Matrix_LAPACK_interfaces
4
USE Matrix_Operations_interfaces
5
6
IMPLICIT NONE
7
INTEGER(C_SIZE_T), INTENT(IN) :: N
8
REAL(8), INTENT(IN) :: M_mat(N,N),C_mat(N,N),K_mat(N,N)
9
COMPLEX(8), INTENT(OUT) :: Epsi_normalized_mat(N,2*N), EigVal_vec(2*N)
10
11
INTEGER(C_SIZE_T) NN
12
REAL(8) N_mat(N,N),A_mat(2*N,2*N),B_mat(2*N,2*N)
13
COMPLEX(8) Phi_mat(2*N,2*N), Phi_normalized_mat(2*N,2*N), B_r_vec(2*N)
14
15
N_mat=M_mat
16
A_mat=0
17
A_mat(1:N,1:N)=-K_mat
18
A_mat(N+1:2*N,N+1:2*N)=N_mat
19
B_mat=0
20
B_mat(1:N,1:N)=C_mat
21
B_mat(1:N,N+1:2*N)=M_mat
22
B_mat(N+1:2*N,1:N)=N_mat
23
CALL dGenEig(A_mat, B_mat, EigVal_vec, Phi_mat, 2*N)
24
B_r_vec=zMatDiag(MATMUL(MATMUL(TRANSPOSE(Phi_mat),B_mat),Phi_mat),2*N)
25
26
Phi_normalized_mat=Phi_mat
27
DO NN=1,2*N
28
Phi_normalized_mat(:,NN)=Phi_normalized_mat(:,NN)/zsqrt(B_r_vec(NN))
29
END DO
30
31
Epsi_normalized_mat=Phi_normalized_mat(1:N,:)
32
33 END SUBROUTINE quad_eig
Code 6.18: Fortran implementation of code 6.5
320
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
SUBROUTINE MDOF_Eig_Visc(M_mat,C_mat,K_mat,N,isProportional,EigValues_vec,
EigVectors_Normalized)
USE, INTRINSIC :: ISO_C_BINDING, ONLY: C_SIZE_T
USE IFPORT
USE Matrix_LAPACK_interfaces
USE Matrix_Operations_interfaces
IMPLICIT NONE
INTEGER(C_SIZE_T), INTENT(IN) :: N
LOGICAL, INTENT(IN) :: isProportional
REAL(8), INTENT(IN) :: M_mat(N,N),C_mat(N,N),K_mat(N,N)
COMPLEX(8), INTENT(OUT) :: EigVectors_Normalized(N,2*N), EigValues_vec(2*N)
COMPLEX(8) i
REAL(8), ALLOCATABLE :: EigVectors_U_mat(:,:), EigValues_U_vec(:), M_r_vec(:),
w_U_r_vec(:), C_r_vec(:), zeta_r_vec(:), w_d_r_vec(:), Temp_Vec(:)
COMPLEX(8), ALLOCATABLE :: EigValues_vec_temp(:)
INTEGER(C_SIZE_T) iindex(N), iiindex(2*N), NN
PARAMETER (i=(0D0,1D0))
IF (isProportional .OR. all(C_mat==0)) THEN !Undamped or proportional
ALLOCATE(EigVectors_U_mat(N,N), EigValues_U_vec(N), M_r_vec(N), w_U_r_vec(N),
C_r_vec(N), zeta_r_vec(N), w_d_r_vec(N), EigValues_vec_temp(N), Temp_Vec(N)
)
CALL dGenSymDefEig(-K_mat,M_mat,EigValues_U_vec,EigVectors_U_mat,N)
M_r_vec=dMatDiag(MATMUL(MATMUL(TRANSPOSE(EigVectors_U_mat),M_mat),
EigVectors_U_mat),N)
w_U_r_vec=DSQRT(-EigValues_U_vec)
C_r_vec=dMatDiag(MATMUL(MATMUL(TRANSPOSE(EigVectors_U_mat),C_mat),
EigVectors_U_mat),N)
zeta_r_vec=C_r_vec/(2*M_r_vec*w_U_r_vec)
w_d_r_vec=w_U_r_vec*DSQRT(1-zeta_r_vec**2)
EigValues_vec_temp=-zeta_r_vec*w_U_r_vec+i*w_d_r_vec
EigValues_vec(1:2*N-1:2)=EigValues_vec_temp
EigValues_vec(2:2*N:2)=DCONJG(EigValues_vec_temp)
EigVectors_Normalized(:,1:2*N-1:2)=MATMUL(EigVectors_U_mat,zDiagMat(1/zsqrt(i
*2*w_d_r_vec*M_r_vec),N))
EigVectors_Normalized(:,2:2*N:2)=DCONJG(EigVectors_Normalized(:,1:2*N-1:2))
ELSE !Non-proportional
CALL quad_eig(K_mat,C_mat,M_mat,N,EigVectors_Normalized,EigValues_vec)
END IF
Do NN=1,N
iindex(NN)=2*NN-1
END DO
CALL QSORT(iindex,N,SIZEOF(iindex(1)),cmp_function)
iiindex(1:2*N-1:2)=iindex
iiindex(2:2*N:2)=iindex+1
EigValues_vec=EigValues_vec(iiindex)
EigVectors_Normalized=EigVectors_Normalized(:,iiindex)
CONTAINS
321
52
53
54
55
56
57
58
INTEGER(2) FUNCTION cmp_function(ind1, ind2)
USE, INTRINSIC :: ISO_C_BINDING, ONLY: C_SIZE_T
INTEGER(C_SIZE_T), INTENT(IN) :: ind1, ind2
IF (DABS(DIMAG(EigValues_vec(ind1))) > DABS(DIMAG(EigValues_vec(ind2)))) THEN
cmp_function=1
ELSE IF (DABS(DIMAG(EigValues_vec(ind1))) < DABS(DIMAG(EigValues_vec(ind2))))
THEN
cmp_function=-1
ELSE
cmp_function=0
END IF
59
60
61
62
63
64
END FUNCTION cmp_function
65 END SUBROUTINE MDOF_Eig_Visc
Code 6.19: Fortran implementation of code 6.6
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
FUNCTION MDOF_FRF_Visc(EigValues_vec, EigVectors_Normalized_mat, N, w_column, N_w,
n_vec, m_vec, N_cols)
USE, INTRINSIC :: ISO_C_BINDING, ONLY: C_SIZE_T
IMPLICIT NONE
INTEGER(C_SIZE_T), INTENT(IN) :: N, N_w, N_cols
INTEGER(C_SIZE_T), INTENT(IN) :: n_vec(N_cols), m_vec(N_cols)
COMPLEX(8), INTENT(IN) :: EigValues_vec(2*N), EigVectors_Normalized_mat(N,2*N)
REAL(8), INTENT(IN) :: w_column(N_w,1)
COMPLEX(8) MDOF_FRF_Visc(N_w,N_cols)
INTEGER(C_SIZE_T) ii,r
COMPLEX(8) i,H_w_n_m_cols_SDOF(N_w,N_cols), A_r(2*N,2*N), A_r_temp_row(1,N_cols)
PARAMETER (i=(0D0,1D0))
H_w_n_m_cols_SDOF=0
MDOF_FRF_Visc=0
DO r=1,2*N
A_r=MATMUL(RESHAPE(EigVectors_Normalized_mat(:,r),(/N,1/)),RESHAPE(
EigVectors_Normalized_mat(:,r),(/1,N/)))
DO ii=1,N_cols
A_r_temp_row(1,ii)=A_r(n_vec(ii), m_vec(ii))
END DO
H_w_n_m_cols_SDOF=H_w_n_m_cols_SDOF+MATMUL((1/(i*w_column-EigValues_vec(r))),
A_r_temp_row)
IF ((DIMAG(EigValues_vec(r))/=0) .AND. (MOD(r,2)/=0)) THEN !complex eigenvalue
and odd r
CYCLE
END IF
26
27
28
29
MDOF_FRF_Visc=MDOF_FRF_Visc+H_w_n_m_cols_SDOF
30
H_w_n_m_cols_SDOF=0
31
END DO
32
33 END FUNCTION MDOF_FRF_Visc
322
Details
• Double precision numbers are written as 4D1 (which means 4 × 101 )
• To simplify the programs, I crated several functions/subroutines as explained below
[https://github.com/ahmed-rashed/PortMatlab_remote]:
– In “Matrix LAPACK.f90”, I created several functions/subroutines calling the corresponding LAPACK subroutines to simplify linear algebra operations
– In “Matrix Operations.f90”, I created several functions/subroutines to simplify
matrix operations
485
6.4
Porting Matlab to C++
6.4.1
The valarray Class
valarray is a template array class designed for high speed numerics. Thus it:
• allows array expressions
• allows advanced indexing
• is optimized
• is a part of the STL
• However, the valarray class represents 1D array
– Hence, additional effort is needed to extend it for matrices (2D arrays)
486
algorithm
algorithm is a header file that define a template library covering a wide range of algorithms that can be applied to a set of elements stored in a container (array).
• algorithm is a part of the STL
487
Porting Matlab to C++
Regarding the C++ programming language;
Array expressions
• Supported by the “valarray” STL class
– Array arithmetic is optimized
Advanced array indexing
• Supported in “valarray” STL class
– Indexing is optimized
323
Mathematical library
• Built-in library is limited
• The “algorithm” STL header file provides some useful array algorithms
• There are many external libraries callable from C
– Example include BLAS, LAPACK, IMSL, Boost, . . .
6.4.2
The Simple Example
Due to the lack of a graphics library accessible from C++, only the computational function of
sec. 6.1.1 are ported herein to C++.
• Implementation is available as open source @ https://github.com/ahmed-rashed/
PortMatlab_remote
Code 6.20: C++ implementation of code 6.1
1
2
3
4
#include <valarray>
#include <math.h>
std::valarray<double> Free_Response(const double& w_n, const double& zeta, const
double& x0, const double& v0, const std::valarray<double>& t_vec)
{
if (zeta==0)
{
double A=sqrt(x0*x0+v0*v0/w_n/w_n);
double theta=atan2(x0*w_n,v0);
return A*sin(w_n*t_vec+theta);
}
else if (zeta<1)
{
double w_d=w_n*sqrt(1-zeta*zeta);
double B=sqrt(x0*x0*w_n*w_n+2*zeta*w_n*x0*v0+v0*v0)/w_d;
double phi=atan2(x0*w_d,(zeta*w_n*x0+v0));
return B*exp(-zeta*w_n*t_vec)*sin(w_d*t_vec+phi);
}
else if (zeta==1)
{
return exp(-w_n*t_vec)*(x0+(w_n*x0+v0)*t_vec);
}
else if (zeta>1)
{
double temp=w_n*sqrt(zeta*zeta-1);
double C=((temp-zeta*w_n)*x0-v0)/2/temp;
double D=((temp+zeta*w_n)*x0+v0)/2/temp;
return exp(-zeta*w_n*t_vec)*(C*exp(-temp*t_vec)+D*exp(temp*t_vec));
}
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 }
return std::valarray<double>();
324
6.4.3
The Matrix Class
I (Dr. Ahmed M. Rashed Desoki) created a template class called “Matrix” inheriting the
valarray class.
• Hence, my Matrix class inherits:
– array expressions
– arithmetic optimizations
– advanced array indexing
– ...
• Implementation can be found at https://github.com/ahmed-rashed/PortMatlab_
remote
– I used BLAS in “Matrix BLAS.h” to create the overloaded function MatMul for
single, double, single-complex and double-complex precisions
– I used LAPACK in “Matrix LAPACK.h” to create several overloaded functions to
simplify linear algebra operations
– I created several functions in “MatrixOperations.h” to simplify matrix operations
– I created the “valarray ComplexRealOperators.h” header file to tell C++ compiler how to add/subtract/multiply/divide real and complex valarrays
• This class is not complete yet. Future work include:
– supporting sparse matrices
• Also I consider this class not mature yet
– Much more testing is needed
• There are numerous similar classes created by others
– Notable example is Armadillo [sec. 6.4.5]
490
6.4.4
The Comprehensive Example
Due to the lack of a graphics library accessible from C++, only the computational functions of
sec. 6.1.2 are ported herein to C++.
• Implementation is available as open source @ https://github.com/ahmed-rashed/
PortMatlab_remote
Code 6.21: C++ implementation of code 6.3
1
2
3
4
5
6
7
8
9
#include <complex>
#include <valarray>
#include <math.h>
#include "valarray_ComplexRealOperators.hpp"
#include "Matrix_LAPACK.hpp"
#include "a_matrices.hpp"
using namespace std;
using namespace a_matrices;
325
10
11 Matrix<complex<double> > MDOF_FRF_Visc_Slow(const Matrix<double>& M_mat,const Matrix<
double>& C_mat,const Matrix<double>& K_mat,const Matrix<double>& w_col, const
valarray<size_t>& index_vec)
12 {
13
const double pi=atan(1.0)*4;
14
const complex<double> i(0,1);
15
const size_t n_w_points=w_col.size();
16
const size_t n_index_vec=index_vec.size();
17
18
Matrix<complex<double> > H_cols(n_w_points,n_index_vec);
19
20
for (size_t n=0; n<n_w_points; n++)
21
{
22
Matrix<complex<double> > H_w_mat=SymInv(-w_col[n][0]*w_col[n][0]*M_mat+i*w_col[
n][0]*C_mat+K_mat);
23
24
H_cols.row(n)=H_w_mat[index_vec];
25
}
26
27
return H_cols;
28 }
Code 6.22: C++ implementation of code 6.4
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
#include <complex>
#include <valarray>
#include <math.h>
#include <algorithm>
#include <numeric>
#include "valarray_ComplexRealOperators.hpp"
#include "Matrix_BLAS.hpp"
#include "Matrix_LAPACK.hpp"
#include "a_matrices.hpp"
using namespace std;
using namespace a_matrices;
void quad_eig(const Matrix<double>& K_mat,const Matrix<double>& C_mat,const Matrix<
double>& M_mat, Matrix<complex<double> >& Epsi_normalized_mat, valarray<complex<
double> >& EigVal_vec)
{
const complex<double> i(0,1);
size_t N=M_mat.cols;
if (EigVal_vec.size()!=2*N) throw("valarray EigVal_vec must have length same as the
number of rows of matrix M_mat.");
if (Epsi_normalized_mat.rows!=N) throw("Matrix Epsi_normalized_mat must have twice
the number of rows as matrix M_mat.");
if (Epsi_normalized_mat.cols!=2*N) throw("Matrix Epsi_normalized_mat must have
twice the number of columns as matrix M_mat.");
Matrix<double> N_mat(M_mat);
Matrix<double> A_mat(2*N,2*N,0.0);
A_mat.SubMatrix(0,N-1,0,N-1)=valarray<double>(-K_mat.SubMatrix(0,N-1,0,N-1));
A_mat.SubMatrix(N,2*N-1,N,2*N-1)=valarray<double>(N_mat.SubMatrix(0,N-1,0,N-1));
Matrix<double> B_mat(2*N,2*N,0.0);
326
29
30
31
32
33
34
35
B_mat.SubMatrix(0,N-1,0,N-1)=valarray<double>(C_mat.SubMatrix(0,N-1,0,N-1));
B_mat.SubMatrix(0,N-1,N,2*N-1)=valarray<double>(M_mat.SubMatrix(0,N-1,0,N-1));
B_mat.SubMatrix(N,2*N-1,0,N-1)=valarray<double>(N_mat.SubMatrix(0,N-1,0,N-1));
Matrix<complex<double> > Phi_mat(2*N,2*N), Phi_normalized_mat(2*N,2*N);
GenEig(A_mat, B_mat, EigVal_vec, Phi_mat);
valarray<complex<double> > B_r_vec(MatDiag(MatMul(MatMul(transpose(Phi_mat),B_mat),
Phi_mat)));
36
37
38
39
Phi_normalized_mat=scale_cols(Phi_mat,1.0/sqrt(B_r_vec));
Epsi_normalized_mat.SubMatrix(0,N-1,0,2*N-1)=valarray<complex<double> >(
Phi_normalized_mat.SubMatrix(0,N-1,0,2*N-1));
40 }
Code 6.23: C++ implementation of code 6.5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <complex>
#include <valarray>
#include <math.h>
#include <algorithm>
#include <numeric>
#include "valarray_ComplexRealOperators.hpp"
#include "Matrix_BLAS.hpp"
#include "Matrix_LAPACK.hpp"
#include "a_matrices.hpp"
using namespace std;
using namespace a_matrices;
void quad_eig(const Matrix<double>& K_mat,const Matrix<double>& C_mat,const Matrix<
double>& M_mat, Matrix<complex<double> >& Epsi_normalized_mat, valarray<complex<
double> >& EigVal_vec);
15
16 void MDOF_Eig_Visc(const Matrix<double>& M_mat,const Matrix<double>& C_mat,const
Matrix<double>& K_mat, const bool& isPropotional, Matrix<complex<double> >&
EigVectors_Normalized, valarray<complex<double> >& EigValues_vec)
17 {
18
size_t N=M_mat.cols;
19
if (EigValues_vec.size()!=2*N) throw("valarray EigValues_vec must have length same
as the number of rows of matrix M_mat.");
20
if (EigVectors_Normalized.rows!=N) throw("Matrix Epsi_normalized_mat must have the
same number of rows as matrix M_mat.");
21
if (EigVectors_Normalized.cols!=2*N) throw("Matrix Epsi_normalized_mat must have
twice the number of columns as matrix M_mat.");
22
23
const complex<double> i(0,1);
24
if (isPropotional || all(C_mat==0.0)) //Undamped or proportional
25
{
26
Matrix<double> EigVectors_U_mat(N,N);
27
valarray<double> EigValues_U_vec(N);
28
GenSymDefEig(-K_mat,M_mat, EigValues_U_vec, EigVectors_U_mat);
29
30
valarray<double> M_r_vec(MatDiag(MatMul(MatMul(transpose(EigVectors_U_mat),
M_mat),EigVectors_U_mat)));
31
valarray<double> w_U_r_vec(sqrt(-EigValues_U_vec));
32
327
33
valarray<double> C_r_vec=MatDiag(MatMul(MatMul(transpose(EigVectors_U_mat),
C_mat),EigVectors_U_mat));
valarray<double> zeta_r_vec(C_r_vec/(2.0*M_r_vec*w_U_r_vec));
valarray<double> w_d_r_vec(w_U_r_vec*sqrt(1.0-zeta_r_vec*zeta_r_vec));
valarray<complex<double> > EigValues_vec_temp(-zeta_r_vec*w_U_r_vec+i*w_d_r_vec
);
34
35
36
37
38
39
40
41
EigValues_vec[slice(0,N,2)]=EigValues_vec_temp;
EigValues_vec[slice(1,N,2)]=conj(EigValues_vec_temp);
EigVectors_Normalized.SubMatrix(0, N-1, 1, 0, 2*N-2, 2)=valarray<complex<double
> >(scale_cols(EigVectors_U_mat+i*Matrix<double>(N,N,0.0),1.0/sqrt(i*2.0*
w_d_r_vec*M_r_vec)).SubMatrix(0, N-1, 0, N-1));
EigVectors_Normalized.SubMatrix(0, N-1, 1, 1, 2*N-1, 2)=conj(valarray<complex<
double> >(EigVectors_Normalized.SubMatrix(0, N-1, 1, 0, 2*N-2, 2)));
42
43
44
45
46
47
48
49
50
51
52
}
else //Non-proportional
{
quad_eig(K_mat,C_mat,M_mat, EigVectors_Normalized, EigValues_vec);
}
valarray<size_t> Index(N);
iota(begin(Index), end(Index), 0);
Index=size_t(2)*Index;
sort(begin(Index), end(Index), [&](size_t a, size_t b) { return abs(imag(
EigValues_vec[a])) < abs(imag(EigValues_vec[b])); });
valarray<size_t> IIndex(2*N);
IIndex[slice(0,N,2)]=Index;
IIndex[slice(1,N,2)]=Index+size_t(1);
valarray<complex<double> > EigValuesTemp_vec(EigValues_vec);
EigValues_vec=EigValuesTemp_vec[IIndex];
Matrix<complex<double> > EigVectors_NormalizedTemp(EigVectors_Normalized);
for (size_t n=0;n<2*N;n++)
EigVectors_Normalized.col(n)=valarray<complex<double> >(
EigVectors_NormalizedTemp.col(IIndex[n]));
53
54
55
56
57
58
59
60
61
62
63 }
return;
Code 6.24: C++ implementation of code 6.6
1
2
3
4
5
6
7
8
9
10
11
12
#include <complex>
#include <valarray>
#include <math.h>
#include "valarray_ComplexRealOperators.hpp"
#include "Matrix_BLAS.hpp"
#include "MatrixOperations.hpp"
#include "a_matrices.hpp"
using namespace std;
using namespace a_matrices;
Matrix<complex<double> > MDOF_FRF_Visc(const valarray<complex<double> >& EigValues_vec
, const Matrix<complex<double> >& EigVectors_Normalized_mat, const Matrix<double>&
w_column, const valarray<size_t>& m_vec, const valarray<size_t>& n_vec)
13 {
14
size_t N=EigVectors_Normalized_mat.rows;
15
size_t N_w=w_column.size();
328
16
17
18
19
20
21
22
23
24
25
size_t N_cols=m_vec.size();
const complex<double> i(0,1);
Matrix<complex<double> > H_w_mat_SDOF(N_w,N_cols,complex<double>(0,0));
Matrix<complex<double> > H_w_n_m_cols(N_w,N_cols,complex<double>(0,0));
valarray<size_t> A_ind=RowMajorSub2Ind(N, m_vec, n_vec);
for (int r=0;r<2*N;r++)
{
Matrix<complex<double> > EigVector_r(N,1,valarray<complex<double> >(
EigVectors_Normalized_mat.col(r)));
Matrix<complex<double> > A_r_mat=MatMul(EigVector_r,transpose(EigVector_r));
Matrix<complex<double> > A_r_temp_row(1,N_cols,valarray<complex<double> >(
A_r_mat[A_ind]));
H_w_mat_SDOF=H_w_mat_SDOF+MatMul(1.0/(i*w_column-EigValues_vec[r]),A_r_temp_row
);
26
27
28
29
30
31
32
33
34
35
36
37
38 }
if ((imag(EigValues_vec[r])!=0) && ((r+1)%2!=0))
continue;
H_w_n_m_cols=H_w_n_m_cols+H_w_mat_SDOF;
H_w_mat_SDOF= complex<double>(0, 0);
}
return H_w_n_m_cols;
6.4.5
Armadillo Classes
Armadillo∗ is a high quality C++ linear algebra library, aiming towards a good balance between
speed and ease of use.
• Armadillo is basically designed for building MEX C++ files callable from Matlab. Therefore:
– Armadillo’s syntax (API) is deliberately similar to Matlab
– Despite C arrays are row-major, Armadillo arrays are column-major†
• Armadillo is FOSS, distributed under a license useful in both open-source and proprietary contexts
• Armadillo provides efficient classes for vectors, matrices and cubes, as well as many
functions which operate on the classes (eg. contiguous and non-contiguous submatrix
views)
• Various matrix decompositions are provided through integration with LAPACK, or one
of its high performance drop-in replacements (such as the multi-threaded Intel MKL, or
AMD ACML, or OpenBLAS libraries)
• An automatic expression evaluator combines several operations to increase efficiency and
reduce temporaries
∗
†
[http://arma.sourceforge.net/]
That is, arrays are stored column by column.
329
491
• I consider Armadillo very mature
Project idea 15 (Port Matlab to C++ using “Armadillo” Library)
Port Matlab codes of section 6.1.1 to C++ using the “Armadillo” Library
6.4.6
The Comprehensive Example Again
Due to the lack of a graphics library accessible from C++, only the computational functions of
sec. 6.1.2 are ported herein to C++ using the “Armadillo” Library.
• Implementation is available as open source @ https://github.com/ahmed-rashed/
PortMatlab_remote
Code 6.25: C++ implementation of code 6.4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <complex>
#include <math.h>
#include "ArmadilloMatrixOperations.hpp"
using namespace std;
using namespace arma;
void quad_eig(const Mat<double>& K_mat,const Mat<double>& C_mat,const Mat<double>&
M_mat, Mat<complex<double> >& Epsi_normalized_mat, Col<complex<double> >&
EigValues_col)
{
size_t N=M_mat.n_rows;
Mat<double> N_mat=M_mat;
Mat<double> A_mat=join_vert(join_horiz(-K_mat,zeros<Mat<double > >(N,N)),join_horiz
(zeros<Mat<double > >(N,N),N_mat));
Mat<double> B_mat=join_vert(join_horiz(C_mat,M_mat),join_horiz(N_mat, zeros<Mat<
double > >(N,N)));
15
16
17
18
19
20
21
22
23
24
25 }
Mat<complex<double> > Phi_mat;
eig_pair(EigValues_col, Phi_mat, A_mat, B_mat);
Col<complex<double> > B_r_vec=diagvec((strans(Phi_mat)*B_mat*Phi_mat));
Mat<complex<double> > Phi_normalized_mat(2*N,2*N);
for (size_t n=0;n<2*N;n++)
Phi_normalized_mat.col(n)=Phi_mat.col(n)/sqrt(B_r_vec(n));
Epsi_normalized_mat=Phi_normalized_mat.rows(0,N-1);
Code 6.26: C++ implementation of code 6.5
1
2
3
4
5
6
7
#include <complex>
#include <math.h>
#include "ArmadilloMatrixOperations.hpp"
using namespace std;
using namespace arma;
330
8
9
void quad_eig(const Mat<double>& K_mat,const Mat<double>& C_mat,const Mat<double>&
M_mat, Mat<complex<double> >& Epsi_normalized_mat, Col<complex<double> >&
EigValues_col);
10
11 void MDOF_Eig_Visc(const Mat<double>& M_mat,const Mat<double>& C_mat,const Mat<double
>& K_mat, const bool& isPropotional, Mat<complex<double> >&
EigVectors_Normalized_mat, Col<complex<double> >& EigValues_col)
12 {
13
const complex<double> i(0,1);
14
size_t N=M_mat.n_rows;
15
uvec nn=conv_to<uvec>::from(stepvec(1,2,2*N-1)-1);
16
if(isPropotional || all(all(C_mat==0))) //Undamped or proportional
17
{
18
Col<complex<double> > EigValues_U_vec;
19
Mat<complex<double> > EigVectors_U_mat;
20
eig_pair(EigValues_U_vec, EigVectors_U_mat, -K_mat, M_mat);
21
22
Col<double> M_r_col=diagvec(strans(real(EigVectors_U_mat))*M_mat*real(
EigVectors_U_mat));
23
Col<double> w_U_r_col=sqrt(-real(EigValues_U_vec));
24
25
Col<double> C_r_col=diagvec(strans(real(EigVectors_U_mat))*C_mat*real(
EigVectors_U_mat));
26
Col<double> zeta_col=C_r_col/(2*M_r_col%w_U_r_col);
27
Col<double> w_d_r_col=w_U_r_col%sqrt(1-square(zeta_col));
28
Col<complex<double> > EigValues_col_temp=-zeta_col%w_U_r_col+i*w_d_r_col;
29
30
EigValues_col=Col<complex<double> >(2*N);
31
EigValues_col(nn)=EigValues_col_temp;
32
EigValues_col(nn+1)=conj(EigValues_col_temp);
33
34
EigVectors_Normalized_mat=Mat<complex<double> >(N,2*N);
35
EigVectors_Normalized_mat.cols(nn)=real(EigVectors_U_mat)*diagmat(1/(sqrt(i
*2.0*w_d_r_col%M_r_col)));
36
EigVectors_Normalized_mat.cols(nn+1)=conj(EigVectors_Normalized_mat.cols(nn));
37
}
38
else
39
{
40
quad_eig(K_mat, C_mat, M_mat, EigVectors_Normalized_mat, EigValues_col);
41
}
42
43
uvec Index=sort_index(abs(imag(EigValues_col(nn))));
44
uvec IIndex(2*N);
45
IIndex(nn)=2*Index;
46
IIndex(nn+1)=2*Index+1;
47
EigValues_col=EigValues_col(IIndex);
48
EigVectors_Normalized_mat=EigVectors_Normalized_mat.cols(IIndex);
49
50
return;
51 }
Code 6.27: C++ implementation of code 6.6
1
2
3
4
#include <complex>
#include <math.h>
331
5
6
7
8
9
10
11
#include "ArmadilloMatrixOperations.hpp"
//#include "armaMex.hpp"
using namespace std;
using namespace arma;
Mat<complex<double> > MDOF_FRF_Visc(const Col<complex<double> >& EigValues_col, const
Mat<complex<double> >& EigVectors_Normalized_mat, const Mat<double>& w_column,
const Row<double>& n_C, const Row<double>& m_C)
12 {
13
const size_t N=EigVectors_Normalized_mat.n_rows;
14
const size_t n_w=w_column.size();
15
16
//The following check was already performed in the mexFunction. Hence it is
unnecessary here
17
//if (n_C.size() != m_C.size()) throw("Dimensions of n_C and m_C must be identical
");
18
19
const size_t n_col=n_C.size();
20
const complex<double> i(0,1);
21
22
Mat<complex<double> > H_w_mat_SDOF(n_w,n_col);
23
H_w_mat_SDOF.zeros();
24
Mat<complex<double> > H_w_n_m_cols(n_w,n_col);
25
H_w_n_m_cols.zeros();
26
Row<uword> A_ind_row=ColMajorSub2Ind(N, n_C, m_C); //Armadillo is column major
27
for (int r=0;r<2*N;r++)
28
{
29
Mat<complex<double> > A_r_mat=EigVectors_Normalized_mat.col(r)*strans(
EigVectors_Normalized_mat.col(r));
30
Row<complex<double> > A_r_temp_row=strans(A_r_mat(A_ind_row));
31
H_w_mat_SDOF=H_w_mat_SDOF+(1/(i*w_column-EigValues_col(r)))*A_r_temp_row;
32
33
if ((imag(EigValues_col(r))!=0) && ((r+1)%2!=0))
34
continue;
35
36
H_w_n_m_cols=H_w_n_m_cols+H_w_mat_SDOF;
37
H_w_mat_SDOF.zeros();
38
}
39
40
return H_w_n_m_cols;
41 }
Project idea 16 (Matlab Coder)
MATLAB Coder™ generates readable and portable C and C++ code from MATLAB® code.
• The Generated code can be converted to Matlab MEX function
• Try to export codes of sec. 6.1 to C and\or C++ using Matlab coder
– Try to convert them to MEX functions
– Compare with our C and C++ codes of sections 6.2 and 6.4
• Well document your experience
• Prepare a tutorial
332
6.5
Porting Matlab to Python
This web-page https://docs.scipy.org/doc/numpy-dev/user/numpy-for-matlabusers.html? and the links therein can help porting Matlab codes to Python.
6.5.1
496
Simple Example
Contrary to C, Fortran and C++, the matplotlib and MayaVi enable Python to produce beautiful
graphics similar to Matlab.
• Therefore, the complete Matlab project of sec. 6.1.1 is ported herein to Python
• Implementation is available as open source @ https://github.com/ahmed-rashed/
PortMatlab_remote
Code 6.28: Python implementation of code 6.1
1 def Free_Response(w_n,zeta,x0,v0,t_vec):
2
from numpy import sin,sqrt,pi,exp,arctan2
3
4
if zeta==0:
5
A=sqrt(x0**2+v0**2/w_n**2)
6
theta=arctan2(x0*w_n,v0)
7
x_vec=A*sin(w_n*t_vec+theta)
8
elif zeta<1:
9
w_d=w_n*sqrt(1-zeta**2)
10
B=sqrt(x0**2*w_n**2+2*zeta*w_n*x0*v0+v0**2)/w_d
11
phi=arctan2(x0*w_d,(zeta*w_n*x0+v0))
12
x_vec=B*exp(-zeta*w_n*t_vec)*sin(w_d*t_vec+phi)
13
elif zeta==1:
14
x_vec=exp(-w_n*t_vec)*(x0+(w_n*x0+v0)*t_vec)
15
elif zeta>1:
16
temp=w_n*sqrt(zeta**2-1)
17
C=((temp-zeta*w_n)*x0-v0)/2/temp
18
D=((temp+zeta*w_n)*x0+v0)/2/temp
19
x_vec=exp(-zeta*w_n*t_vec)*(C*exp(-temp*t_vec)+D*exp(temp*t_vec))
20
21
return x_vec
Code 6.28 above is called from code 6.2 below to plot the following curves
333
x(t) for ωn = 1, x0 = −1 and v0 = 0
1.0
0.5
0.0
ζ=0
ζ = 0.1
ζ = 0.2
ζ = 0.4
ζ = 0.707
ζ=1
ζ=2
−0.5
−1.0
0.0
0.5
t/Tn
1.0
, : Tn = 1/fn = 2π/ωn
1.5
2.0
Code 6.29: Python implementation of code 6.2
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
from numpy import linspace,sqrt,pi,array
import matplotlib.pyplot as plt
import matplotlib
from Free_Response import Free_Response
if __name__ == ’__main__’:
plt.close(’all’)
matplotlib.rcParams[’text.usetex’] = True
x0=-1
v0=0
w_n=1
f_n=w_n/2.0/pi
T_n=1/f_n
zeta_vec=array([0,.1,.2,.4,1/sqrt(2),1,2])
t_vec=linspace(0,2*T_n,500)
for zeta in zeta_vec:
x_vec=Free_Response(w_n,zeta,x0,v0,t_vec)
plt.plot(t_vec/T_n,x_vec, label=r’$\zeta = %.3g$’ %zeta)
plt.title(r’$x(t)$ for $\omega_{n}=%g$, $x_{0}=%g$ and $v_{0}=%g$’ %(w_n,x0,v0))
plt.xlabel(r’$t/T_{n}\qquad,:T_{n}=1/f_{n}=2\pi/\omega_{n}$’)
plt.legend(loc=’lower right’)
plt.grid()
plt.savefig(’SDOF_1_Python.pdf’, bbox_inches=’tight’)
plt.show()
334
6.5.2
Comprehensive Example
Contrary to C, Fortran and C++, the matplotlib and MayaVi enable Python to produce beautiful
graphics similar to Matlab.
• Therefore, the complete Matlab project of sec. 6.1.2 is ported herein to Python
• Implementation is available as open source @ https://github.com/ahmed-rashed/
PortMatlab_remote
498
Computational Functions
Code 6.30: Python implementation of code 6.3
1 def MDOF_FRF_Visc_slow(M_mat,C_mat,K_mat,w_vec,n_row,m_row):
2
import numpy as np
3
4
n_w_points=w_vec.size
5
H_cols=np.zeros((n_w_points,m_row.size),dtype=complex)
6
for ii in np.arange(0,n_w_points):
7
H_w=np.linalg.inv(-w_vec[ii]**2*M_mat+1j*w_vec[ii]*C_mat+K_mat)
8
9
H_cols[ii,:]=H_w[n_row,m_row]
10
11
return H_cols
Code 6.31: Python implementation of code 6.4
1
2
3
4
5
6
7
8
9
def quad_eig(K_mat,C_mat,M_mat):
import numpy as np
import scipy as sp
import scipy.linalg as la
#from scipy import linalg as la
n=M_mat.shape[0]
N_mat=M_mat
A=np.concatenate((np.concatenate((-K_mat,0*M_mat),axis=1),np.concatenate((0*M_mat,
N_mat),axis=1)),axis=0)
B=np.concatenate((np.concatenate((C_mat,M_mat),axis=1),np.concatenate((N_mat,0*
M_mat),axis=1)),axis=0)
Val_vec,Phi=la.eig(A,B) #Ordinary or generalized eigenvalue problem of a complex
Hermitian or real symmetric matrix
B_r=np.dot(np.dot(Phi.T,B),Phi)
Phi_normalized=la.lstsq(np.sqrt(B_r.T),Phi.T)[0].T
Epsi_normalized=Phi_normalized[0:n,:]
10
11
12
13
14
15
16
return Epsi_normalized,Val_vec
Code 6.32: Python implementation of code 6.5
1
2
3
4
5
def MDOF_Eig_Visc(M_mat,C_mat,K_mat,isPropotional=False):
import numpy as np
import scipy as sp
from quad_eig import quad_eig
335
6
7
8
N=M_mat.shape[0]
if isPropotional or np.all(C_mat==0): #undamped or proportional
EigValues_U_vec,EigVectors_U=sp.linalg.eigh(-K_mat,M_mat) #Ordinary or
generalized eigenvalue problem of a complex Hermitian or real symmetric
matrix
M_r_vec=np.diag(np.dot(np.dot(EigVectors_U.T,M_mat),EigVectors_U))
w_U_r_vec=np.sqrt(-EigValues_U_vec)
C_r_vec=np.diag(np.dot(np.dot(EigVectors_U.T,C_mat),EigVectors_U))
zeta_r_vec=C_r_vec/(2*M_r_vec*w_U_r_vec)
w_d_r_vec=w_U_r_vec*np.sqrt(1-zeta_r_vec**2)
EigValues_vec_temp=-zeta_r_vec*w_U_r_vec+1j*w_d_r_vec
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
EigValues_vec=np.zeros((2*N),dtype=complex)
EigValues_vec[0:2*N-1:2]=EigValues_vec_temp
EigValues_vec[1:2*N:2]=EigValues_vec_temp.conj()
EigVector_Normalized=np.zeros((N,2*N),dtype=complex)
EigVector_Normalized[:,0:2*N-1:2]=sp.linalg.solve(np.diag(np.sqrt(1j*2*
w_d_r_vec*M_r_vec)),EigVectors_U.T).T
EigVector_Normalized[:,1:2*N:2]=EigVector_Normalized[:,0:2*N-1:2].conj()
else: #non proportional
EigVector_Normalized,EigValues_vec=quad_eig(K_mat,C_mat,M_mat)
Index=np.argsort(np.absolute(EigValues_vec[0:2*N-1:2].imag))
IIndex=np.empty(2*N,dtype=int)
IIndex[0:2*N-1:2]=2*Index;
IIndex[1:2*N:2]=2*Index+1;
EigValues_vec1=EigValues_vec[IIndex]
EigVector_Normalized1=EigVector_Normalized[:,IIndex]
return EigVector_Normalized1,EigValues_vec1
Code 6.33: Python implementation of code 6.6
1 "Initialized by Alyaa Mansour, 1st year Aerospace; Spring 2016"
2
3 def MDOF_FRF_Visc(EigValues_vec,EigVectors_Normalized,w_col,ii_vec,jj_vec):
4
import numpy as np
5
6
N=EigVectors_Normalized.shape[0]
7
n_w=w_col.size
8
if ii_vec.size!=jj_vec.size:
9
raise NameError(’Dimensions of ii_vec and jj_vec must be identical’)
10
11
n_col=ii_vec.size
12
H_w_mat_SDOF=np.zeros((n_w,n_col),dtype=complex)
13
H_w_mat=np.zeros((n_w,n_col),dtype=complex)
14
for r in np.arange(2*N):
15
A_r=np.dot(EigVectors_Normalized[:,[r]],EigVectors_Normalized[:,[r]].T)
16
A_r_temp_row=np.reshape(A_r[ii_vec,jj_vec],(1,n_col))
17
H_w_mat_SDOF=H_w_mat_SDOF+np.dot((1/(1j*w_col-EigValues_vec[r])),A_r_temp_row)
18
if EigValues_vec[r].imag!=0 and np.mod(r+1,2)!=0: #complex eigenvalue and odd r
19
continue
20
21
H_w_mat=H_w_mat+H_w_mat_SDOF
22
H_w_mat_SDOF=np.zeros((n_w,n_col),dtype=complex)
23
24
return H_w_mat
336
499
Graphics Functions
Code 6.34: Python implementation of code 6.7
1
2
3
4
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
def plot_FRF_3d(f_vec,H_vec,f_label=’$f$ (Hz)’,H_subtitle=’H’,lineLabel=’’,
DispRealImag=False,DispMagLines=False):
import numpy as np
5
6
7
n_f=f_vec.size
8
np.reshape(f_vec,n_f)
9
np.reshape(H_vec,n_f)
10
11
ind1=f_label.find(’$’)
12
if ind1==-1:
13
raise NameError(’f_label does not include LaTeX inline equation !!’)
14
ind2=f_label.find(’$’,ind1+1)
15
if ind2==-1:
16
raise NameError(’f_label does not include LaTeX inline equation !!’)
17
H_subtitle1=r’%s\left(%s\right)’ %(H_subtitle ,f_label[ind1+1:ind2])
18
19
line_3d=plt.plot(f_vec,H_vec.real,H_vec.imag,label=r’%s’ %lineLabel)
20
21 # plt.axis(’equal’)
22
plt.grid()
23
24
plt.xlabel(r’%s’ %f_label)
25
plt.ylabel(r’$\Re\left(%s\right)$’ %H_subtitle1)
26
plt.gca().set_zlabel(r’$\Im\left(%s\right)$’ %H_subtitle1)
27
28
xlimm=plt.xlim()
29
ylimm=plt.ylim()
30
zlimm=plt.gca().get_zlim()
31
#Bug workaround
32
a1=xlimm[0]
33
b1=xlimm[1]
34
a3=zlimm[0]
35
b3=zlimm[1]
36
37
if DispRealImag:
38
plt.plot(H_vec.real,H_vec.imag,zs=xlimm[0],zdir=’x’, color=line_3d[0].get_color
(),linestyle=line_3d[0].get_linestyle(),linewidth=line_3d[0].get_linewidth
()/3)
39
plt.plot(f_vec,H_vec.real,zs=a3,zdir=’z’, color=line_3d[0].get_color(),
linestyle=line_3d[0].get_linestyle(),linewidth=line_3d[0].get_linewidth()
/3)
40
plt.plot(f_vec,H_vec.imag,zs=ylimm[1],zdir=’y’, color=line_3d[0].get_color(),
linestyle=line_3d[0].get_linestyle(),linewidth=line_3d[0].get_linewidth()
/3)
41
#Bug Workaround
42
plt.xlim(a1,b1)
43
plt.ylim(ylimm)
44
plt.gca().set_zlim(a3,b3)
45
337
46
47
48
49
50
51
52
if DispMagLines:
n_MagLines=20
delta_temp=np.floor(n_f/n_MagLines)
iidx=np.arange(1,n_f,delta_temp,dtype=np.intp)
plt.quiver3D(f_vec[iidx],0*f_vec[iidx],0*f_vec[iidx],0*f_vec[iidx],H_vec[iidx].
real,H_vec[iidx].imag, length=.001)
53
54
55
56
#plt.plot(f_vec[iidx],H_vec[iidx].real,H_vec[iidx].imag,’.’,’MarkerSize’,15,
color=line_3d[0].get_color());
return line_3d
Code 6.35: Python implementation of code 6.8
1 import matplotlib.pyplot as plt
2
3 def plot_FRF_Nyq(H_vec,H_subtitle=’H’,lineLabel=’’,DispMagLines=False):
4
import numpy as np
5
6
n_f=H_vec.size
7
np.reshape(H_vec,n_f)
8
9
H_subtitle1=r’%s\left(f \right)’ %H_subtitle
10
11
h3=plt.plot(H_vec.real,H_vec.imag,label=r’%s’ %lineLabel)
12
13
if DispMagLines:
14
n_MagLines=20
15
delta_temp=np.floor(n_f/n_MagLines)
16
iidx=np.arange(1,n_f,delta_temp,dtype=np.intp)
17
18
plt.quiver(0*H_vec,0*H_vec,H_vec.real,H_vec.imag)
19
20
plt.axis(’equal’)
21
22
plt.xlabel(r’$\Re\left(%s\right)$’ %H_subtitle1)
23
plt.ylabel(r’$\Im\left(%s\right)$’ %H_subtitle1)
24
25
plt.grid()
26
27
return h3
Code 6.36: Python implementation of code 6.9
1
2
3
4
5
6
7
8
9
10
import matplotlib.pyplot as plt
def plot_FRF_r_i(f_vec,H_vec,ax_r=None,ax_i=None,f_label=’$f$ (Hz)’,H_subtitle=’H’,
lineLabel=’’,DispMagLines=False):
import numpy as np
if ax_r is None:
ax_r=plt.subplot(2,1,1)
if ax_i is None:
plt.setp(ax_r.get_xticklabels(), visible=False)
338
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
if ax_i is None:
ax_i=plt.subplot(2,1,2, sharex=ax_r)
n_f=f_vec.size
np.reshape(f_vec,n_f)
np.reshape(H_vec,n_f)
ind1=f_label.find(’$’)
if ind1==-1:
raise NameError(’f_label does not include LaTeX inline equation !!’)
ind2=f_label.find(’$’,ind1+1)
if ind2==-1:
raise NameError(’f_label does not include LaTeX inline equation !!’)
H_subtitle1=r’%s\left(%s\right)’ %(H_subtitle ,f_label[ind1+1:ind2])
h1=ax_r.plot(f_vec,H_vec.real,label=r’%s’ %lineLabel)
ax_r.set_ylabel(r’$\Re\left(%s\right)$’ %H_subtitle1)
ax_r.grid()
h2=ax_i.plot(f_vec,H_vec.imag)
ax_i.set_xlabel(r’%s’ %f_label)
ax_i.set_ylabel(r’$\Im\left(%s\right)$’ %H_subtitle1)
ax_i.grid()
return ax_r,ax_i,h1,h2
Code 6.37: Python implementation of code 6.10
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
from correctedPhase import correctedPhase
def plot_FRF_mag_phase(f_vec,H_vec,ax_mag=None,ax_phase=None,maxPhaseLag=None,islin_y=
True,islin_x=True,f_label=’$f$ (Hz)’,H_subtitle=’H’,lineLabel=’’,DispMagLines=
False):
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
from matplotlib import rc
rc(’font’, **{’family’: ’serif’, ’serif’: [’Computer Modern’]})
rc(’text’, usetex=True)
if ax_mag is None:
ax_mag=plt.subplot2grid((4,1), (0,0), rowspan=3)
if ax_phase is None:
plt.setp(ax_mag.get_xticklabels(), visible=False)
if ax_phase is None:
ax_phase=plt.subplot2grid((4,1), (3,0), sharex=ax_mag)
n_f=f_vec.size
np.reshape(f_vec,n_f)
np.reshape(H_vec,n_f)
ind1=f_label.find(’$’)
if ind1==-1:
raise NameError(’f_label does not include LaTeX inline equation !!’)
ind2=f_label.find(’$’,ind1+1)
339
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
if ind2==-1:
raise NameError(’f_label does not include LaTeX inline equation !!’)
H_subtitle1=r’%s\left(%s\right)’ %(H_subtitle ,f_label[ind1+1:ind2])
h1=ax_mag.plot(f_vec,np.absolute(H_vec),label=r’%s’ %lineLabel)
if DispMagLines:
n_MagLines=20
delta_temp=np.floor(n_f/n_MagLines)
iidx=np.arange(1,n_f,delta_temp,dtype=np.intp)
markerline, stemlines, baseline=ax_mag.stem(f_vec[iidx],np.absolute(H_vec[iidx
]),linestyle=line_3d[0].get_linestyle())
plt.setp(baseline,’linewidth’, h1[0].get_linewidth()/3)
ax_mag.plot(f_vec[iidx],np.absolute(H_vec[iidx]),’.’,markersize=15)
if islin_y:
ax_mag.set_yscale(’linear’)
else:
ax_mag.set_yscale(’log’)
if islin_x:
ax_mag.set_xscale(’linear’)
#ax_phase.set_xscale(’linear’)
else:
ax_mag.set_xscale(’log’)
#ax_phase.set_xscale(’log’)
ax_mag.set_ylabel(r’$\left|%s\right|$’ %H_subtitle1)
ax_mag.grid()
H_angle_vec=correctedPhase(H_vec,maxPhaseLag)
h2=ax_phase.plot(f_vec,H_angle_vec)
if DispMagLines:
ax_phase.plot(f_vec[iidx],H_angle_vec[iidx],’.’,markersize=15)
ax_phase.set_xlabel(r’%s’ %f_label)
ax_phase.set_ylabel(r’$\angle %s$’ %H_subtitle1)
yStep=np.pi
if ax_phase.get_autoscaley_on():
yLim_min=yStep*np.floor(np.amin(H_angle_vec)/yStep)
yLim_max=yStep*np.ceil(np.amax(H_angle_vec)/yStep)
else:
ylimits=ax_phase.get_ylim()
yLim_min=np.minimum(yStep*np.floor(np.amin(H_angle_vec)/yStep),ylimits[0])
yLim_max=np.maximum(yStep*np.ceil(np.amax(H_angle_vec)/yStep),ylimits[1])
N_ticks=np.round((yLim_max-yLim_min)/yStep)+1
if N_ticks>6:
yStep=yStep*np.round(N_ticks/6)
yTicks=np.arange(yLim_min,yLim_max+yStep,yStep)
N_ticks=yTicks.size
ax_phase.set_yticks(yTicks)
yTickLabels=[r’%d\pi’ %(yTicks[ii]/np.pi) for ii in np.arange(0,N_ticks)]
340
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
for ii in np.arange(0,N_ticks):
if yTicks[ii]==0:
yTickLabels[ii]=’0’
elif yTicks[ii]==np.pi:
yTickLabels[ii]=r’\pi’
elif yTicks[ii]==-np.pi:
yTickLabels[ii]=r’-\pi’
ax_phase.set_yticklabels(yTickLabels)
if yLim_min!=yLim_max:
ax_phase.set_ylim(yLim_min,yLim_max)
ax_phase.grid()
if yStep!=np.pi:
ax_phase.yaxis.set_minor_locator(MultipleLocator(np.pi))
ax_phase.tick_params(axis=’y’,which=’minor’)
return ax_mag,ax_phase,h1,h2
Auxiliary Functions
Code 6.38: Python implementation of code 6.11
1 def N_DOF_sys(m_vec,c_vec,k_vec):
2
import numpy as np
3
4
N=m_vec.size
5
6
M=np.diag(m_vec)
7
C=np.diag(c_vec[0:N]+c_vec[1:N+1])+np.diag(-c_vec[1:N],1)+np.diag(-c_vec[1:N],-1)
8
K=np.diag(k_vec[0:N]+k_vec[1:N+1])+np.diag(-k_vec[1:N],1)+np.diag(-k_vec[1:N],-1)
9
10
return M,C,K
Code 6.39: Python implementation of code 6.12
1 import numpy
2
3 def correctedPhase(H_vec,maxPhaseLag=-numpy.pi):
4
from numpy import pi
5
import numpy as np
6
7
if maxPhaseLag is None:
8
maxPhaseLag=-numpy.pi
9
10
n_f=H_vec.size
11
np.reshape(H_vec,n_f)
12
13
H_angle_vec=np.angle(H_vec)
14
15
H_angle_vec[np.absolute(H_angle_vec)<1e3*np.finfo(type(H_vec[0])).eps]=0
16
H_angle_vec[np.absolute(H_angle_vec-pi)<1e3*np.finfo(type(H_vec[0])).eps]=pi
17
H_angle_vec[np.absolute(H_angle_vec+pi)<1e3*np.finfo(type(H_vec[0])).eps]=-pi
18
H_angle_vec[np.absolute(H_vec)==0]=np.nan
19
20
#Force phase to be less than maxPhaseLag
341
500
21
22
23
24
25
26
27
28
29
30
31
32
indd=H_angle_vec-maxPhaseLag>0
H_angle_vec[indd]=H_angle_vec[indd]-2*pi*np.ceil((H_angle_vec[indd]-maxPhaseLag)/2/
pi)
#Force phase to be decreasing for jumps >= 45 deg
for ii in range(0,n_f-1):
dd=H_angle_vec[ii+1]-H_angle_vec[ii]
if dd>=pi/4:
H_angle_vec[ii+1]=H_angle_vec[ii+1]-2*pi*np.ceil(dd/2/pi)
H_angle_vec=np.unwrap(H_angle_vec)
return H_angle_vec
Main Script
All the former codes are called from code 6.40 below to plot the following curves
0.0006
H1,3
H1,2
H1,1
0.0004
< (H (f ))
H1,3
H1,2
H1,1
−0.0004
= (H (f ))
0.0002
0.0000
−0.0002
−0.0006
−0.0006
0.0004
−0.0008
0.0002
−0.0010
0.0000
−0.0012
= (H (f ))
−0.0002
0.0005
5
10
15
20
f (Hz)
25
30
35
−0.0004
0.0000
)
f)
−0.0005 H (
(
<
40
0.0000
−0.0002
−0.0004
0
0.0002
−0.0006
−0.0008
−0.0010
−0.0010
−0.0012
0
5
10
15
20
f (Hz)
25
30
35
40
10−2
0.0004
H1,3
H1,2
H1,1
0.0002
H1,3
H1,2
H1,1
10−3
10−4
|H (f )|
0.0000
10−5
= (H (f ))
−0.0002
10−6
−0.0004
10−7
−0.0006
10−8
-π
H (f )
−0.0008
6
−0.0010
−0.0012
−0.0010
−0.0005
0.0000
< (H (f ))
0.0005
0.0010
-2π
-3π
-4π
-5π
0
Code 6.40: Python implementation of code 6.13
1
2
3
4
5
6
7
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from MDOF_FRF_Visc_slow import MDOF_FRF_Visc_slow
from MDOF_FRF_Visc import MDOF_FRF_Visc
from MDOF_Eig_Visc import MDOF_Eig_Visc
from N_DOF_sys import N_DOF_sys
342
5
10
15
20
f (Hz)
25
30
35
40
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
from mpl_toolkits.mplot3d import Axes3D
from plot_FRF_3d import plot_FRF_3d
from plot_FRF_Nyq import plot_FRF_Nyq
from plot_FRF_r_i import plot_FRF_r_i
from plot_FRF_mag_phase import plot_FRF_mag_phase
if __name__ == ’__main__’:
plt.close(’all’)
matplotlib.rcParams[’text.usetex’] = True
f_final=40
n_f_points=8000
N=3
m_vec=10*np.ones(N)
c_vec=8*np.ones(N+1)
k_vec=np.concatenate((161000/2*np.ones(N),[0]), axis=0)
n_row=np.array([0,0,0])
m_row=np.array([2,1,0])
isproportional=False
M_mat,C_mat,K_mat=N_DOF_sys(m_vec,c_vec,k_vec)
#C_mat=0;isproportional=True
#C_mat=.0001*M_mat+.0001*K_mat;isproportional=True
f_col=np.linspace(0,f_final,n_f_points).reshape(n_f_points,1)
w_col=2*np.pi*f_col
#Slow FRF calculation
H_cols0=MDOF_FRF_Visc_slow(M_mat,C_mat,K_mat,w_col,n_row,m_row)
#Fast FRF calculation
EigVectors_Normalized, EigValues_vec=MDOF_Eig_Visc(M_mat, C_mat, K_mat,
isproportional)
H_cols=MDOF_FRF_Visc(EigValues_vec, EigVectors_Normalized, w_col, n_row, m_row)
print np.amax(np.absolute(H_cols-H_cols0))
f_3d=plt.figure()
f_3d.gca(projection=’3d’)
f_Nyq=plt.figure()
f_r_i=plt.figure()
f_mag_phase=plt.figure()
ax_mag=None
ax_phase=None
for ii in range(m_row.size):
plt.figure(f_3d.number)
plot_FRF_3d(f_col,H_cols[:,ii],lineLabel=r’$H_{%u,%u}$’ %(n_row[ii]+1,m_row[ii
]+1),DispRealImag=True)[0]
plt.figure(f_Nyq.number)
plot_FRF_Nyq(H_cols[:,ii],lineLabel=r’$H_{%u,%u}$’ %(n_row[ii]+1,m_row[ii]+1))
[0]
plt.figure(f_r_i.number)
ax_r,ax_i=plot_FRF_r_i(f_col,H_cols[:,ii],lineLabel=r’$H_{%u,%u}$’ %(n_row[ii
343
]+1,m_row[ii]+1))[0:2]
63
64
65
66
67
68
69
70
71
72
73
74
75
76
plt.figure(f_mag_phase.number)
ax_mag,ax_phase=plot_FRF_mag_phase(f_col,H_cols[:,ii],ax_mag,ax_phase,islin_y=
False,lineLabel=r’$H_{%u,%u}$’ %(n_row[ii]+1,m_row[ii]+1))[0:2]
f_3d.gca().legend(loc=’upper left’)
f_3d.savefig(’H_3D.pdf’)
f_Nyq.gca().legend()
f_Nyq.savefig(’H_Nyq.pdf’, bbox_inches=’tight’)
ax_r.legend()
f_r_i.savefig(’H_r_i.pdf’, bbox_inches=’tight’)
ax_mag.legend()
f_mag_phase.savefig(’H_mag_phase.pdf’, bbox_inches=’tight’)
plt.show()
344
6.6
Porting Matlab to Julia
6.6.1
Simple Example
Contrary to C, Fortran and C++, Julia can produce beautiful graphics similar to Matlab.
• Therefore, the complete Matlab project of sec. 6.1.1 is ported herein to Julia
• Implementation is available as open source @ https://github.com/ahmed-rashed/
PortMatlab_remote
Code 6.41: Julia implementation of code 6.1
1 function FreeResponse(w_n, zeta, x_0, v_0, t_vec)
2
if zeta == 0
3
A = sqrt(x_0^2 + v_0^2/w_n^2)
4
theta = atan(x_0*w_n,v_0)
5
x_vec=A*sin.(w_n*t_vec.+theta)
6
elseif zeta<1
7
w_d=w_n*sqrt(1-zeta^2)
8
B=sqrt(x_0^2*w_n^2+2*zeta*w_n*x_0*v_0+v_0^2)/w_d
9
phi=atan(x_0*w_d,(zeta*w_n*x_0+v_0))
10
x_vec=B*exp.(-zeta*w_n*t_vec).*sin.(w_d*t_vec.+phi)
11
elseif zeta==1
12
x_vec=exp.(-w_n*t_vec).*(x_0.+(w_n*x_0+v_0)*t_vec)
13
elseif zeta>1
14
temp=w_n*sqrt(zeta^2-1)
15
C=((temp-zeta*w_n)*x_0-v_0)/2/temp
16
D=((temp+zeta*w_n)*x_0+v_0)/2/temp
17
x_vec=exp.(-zeta*w_n*t_vec).*(C*exp.(-temp*t_vec)+D*exp.(temp*t_vec))
18
end
19
20
return x_vec
21 end
Code 6.41 above is called from code 6.42 below to plot the following curves
345
Code 6.42: Julia implementation of code 6.2
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
using Plots
include("FreeResponse.jl")
x_0=-1
v_0=0
w_n=1
f_n=w_n/2pi
T_n=1/f_n
zeta_vec=[0,.1,.2,.4,1/sqrt(2),1,2]
legend_str = ["\$\\zeta = $i \$" for i in union(0:0.1:0.2,[0.4,1/sqrt(2),1,2])]
legend_str[5] = "\$\\zeta = 1/\\sqrt{2}\$"
t_vec= 0:2*T_n/(500-1):2*T_n
plot()
for (n, zeta) in enumerate(zeta_vec)
x_vec=FreeResponse(w_n,zeta,x_0,v_0,t_vec)
plot!(t_vec/T_n,x_vec,label = legend_str[n])
end
p = plot!(legend=:bottomright,grid = true)
title!("\$x(t)\$ for \$\\omega_{n}=1\$, \$x_{0}=-1\$ and \$v_{0}=0\$")
xlabel!("\$t/T_{n}\\qquad,:T_{n}=1/f_{n}=2\\pi/\\omega_{n}\$")
display(p)
png(p,"SDOF_Julia")
Plots.pdf(p, "SDOF_Julia")
Plots.svg(p, "SDOF_Julia")
Project idea 17 (Port Matlab to Julia)
Port Matlab codes of section 6.1.1 to Julia.
The following links may be helpful:
• From zero to Julia! [https://techytok.com/from-zero-to-julia/]
• Julia Basics Cheat Sheet [www.datacamp.com/cheat-sheet/julia-basicscheat-sheet]
• Jose Storopoli, Rik Huijzer and Lazaro Alonso, Julia Data Science, October 2021
[https://juliadatascience.io]
346
Part 7
Technical Writing and Presentation
Word Processors
There are two categories of word processing SW:
• What You See Is What You Get (WYSIWYG)
Examples
• What You See Is What You Mean (WYSIWYM)
WYSIWYG
WYSIWYM
Microsoft Word
LATEX
LYX
LibreOffice Writer
Roughly, you can compare LATEX-to-Word as you compare Matlab-to-Excel
505
LATEX vs MS Word
506
347
7.1
LATEX
LATEX is a FOSS document markup language.
• Simply you can think of LATEX as similar to HTML∗
• In order to create a document in LATEX, a .tex file must be created using any text editor
• The .tex file is then compiled to produce the document
• LATEX can generate several document formats including “pdf”
BibTEX
BibTEX is reference management software for formatting reference lists and text citations in
combination with LATEX.
• More details are available @ www.bibtex.com/
JabRef is a cross–platform FOSS for managing BibTEX databases
LATEX is FOSS
Although being FOSS is an advantage, but it is a drawback at the same time;
• Download servers are slow
• No clean official documentation
• Several alternatives to do the same thing
However; LATEX is very mature and widely used by professional/enterprise publishers.
• Also it has a big user community
– when you encounter a problem, google it. Most likely you will find others had
encountered it and found a solution
∗
(HyperText Markup Language)
348
LATEX 2ε Cheat Sheet
Document classes
book
Default is two-sided.
report
No \part divisions.
article No \part or \chapter divisions.
letter
Letter (?).
slides
Large sans-serif font.
Used at the very beginning of a document:
\documentclass{class}. Use \begin{document} to start
contents and \end{document} to end the document.
Common documentclass options
Font size.
Paper size.
Use two columns.
Set margins for two-sided.
Landscape orientation. Must use dvips
-t landscape.
draft
Double-space lines.
Usage: \documentclass[opt,opt]{class}.
10pt/11pt/12pt
letterpaper/a4paper
twocolumn
twoside
landscape
Packages
349
fullpage Use 1 inch margins.
anysize Set margins: \marginsize{l}{r }{t}{b}.
multicol Use n columns: \begin{multicols}{n}.
latexsym Use LATEX symbol font.
graphicx Show image: \includegraphics[width=x ]{file}.
url
Insert URL: \url{http://. . . }.
Use before \begin{document}. Usage: \usepackage{package}
Lists
Justification
\begin{enumerate} Numbered list.
\begin{itemize}
Bulleted list.
\begin{description}Description list.
\item text
Add an item.
\item[x ] text
Use x instead of normal bullet or number.
Required for descriptions.
Environment
\begin{center}
\begin{flushleft}
\begin{flushright}
References
\linespread{x} changes the line spacing by the multiplier x.
Set a marker for cross-reference, often of the
form \label{sec:item}.
\ref{marker }
Give section/body number of marker.
\pageref{marker } Give page number of marker.
\footnote{text} Print footnote at bottom of page.
Text-mode symbols
\label{marker }
Floating bodies
\begin{table}[place]
Add numbered table.
\begin{figure}[place] Add numbered figure.
\begin{equation}[place] Add numbered equation.
\caption{text}
Caption for the body.
The place is a list valid placements for the body. t=top,
h=here, b=bottom, p=separate page, !=place even if ugly.
Captions and label markers should be within the environment.
Text properties
\pagestyle{empty} Empty header, footer and no page numbers.
\tableofcontents Add a table of contents here.
Document structure
Font size
\author{text} Author of document.
\title{text} Title of document.
\date{text}
Date.
These commands go before \begin{document}. The
declaration \maketitle goes at the top of the document.
Miscellaneous
\part{title}
\subsubsection{title}
\chapter{title}
\paragraph{title}
\section{title}
\subparagraph{title}
\subsection{title}
Use \setcounter{secnumdepth}{x} suppresses heading
numbers of depth > x, where chapter has depth 0. Use a *, as
in \section*{title}, to not number a particular item—these
items will also not appear in the table of contents.
Text environments
Comment (not printed). Requires verbatim
package.
\begin{quote}
Indented quotation block.
\begin{quotation}Like quote with indented paragraphs.
\begin{verse}
Quotation block for verse.
\begin{comment}
Miscellaneous
Symbols
&
$
%
\&
\$
\%
...
|
#
\_
\^{}
\~{}
ˆ
˜
\ldots
\textbar
\#
•
\
§
\textbullet
\textbackslash
\S
Accents
ò \‘o
ȯ \.o
ç \c c
Œ \OE
ø \o
\j
ó \’o
ö \"o
o. \d o
æ \ae
Ø \O
¡ ~‘
ô \^o
o̧ \c o
o \b o
¯
Æ \AE
l \l
¿ ?‘
õ \~o
ǒ \v o
o
o \t oo
å \aa
L \L
ō \=o
ő \H o
œ \oe
Å \AA
ı \i
[[
]]
< \textless
> \textgreater
Delimiters
Font face
Command
Declaration
Effect
\textrm{text}
{\rmfamily text} Roman family
\textsf{text}
{\sffamily text} Sans serif family
\texttt{text}
{\ttfamily text} Typewriter family
\textmd{text}
{\mdseries text} Medium series
\textbf{text}
{\bfseries text} Bold series
\textup{text}
{\upshape text}
Upright shape
\textit{text}
{\itshape text}
Italic shape
\textsl{text}
{\slshape text}
Slanted shape
\textsc{text}
{\scshape text}
Small Caps shape
\emph{text}
{\em text}
Emphasized
\textnormal{text}{\normalfont text}Document font
\underline{text}
Underline
The command (tttt) form handles spacing better than the
declaration (tttt) form.
Title
Declaration
\centering
\raggedright
\raggedleft
Large
\tiny
tiny
\Large
\scriptsize scriptsize
\LARGE
\footnotesize footnotesize
\small
small
\huge
\normalsize normalsize
\large
large
\Huge
These are declarations and should be used in the form {\small
. . . }, or without braces to affect the entire document.
LARGE
huge
Huge
Verbatim text
\begin{verbatim} Verbatim environment.
\begin{verbatim*} Spaces are shown as .
\verb!text!
Text between the delimiting characters (in
this case ‘!’) is verbatim.
‘‘
’’
“ ‘‘
” ’’
{ \{
} \}
((
))
Dashes
Name
hyphen
en-dash
em-dash
Source
----
Example
X-ray
1–5
Yes—or no?
Usage
In words.
Between numbers.
Punctuation.
Line and page breaks
\\
Begin new line without new paragraph.
\\*
Prohibit pagebreak after linebreak.
\kill
Don’t print current line.
\pagebreak Start new page.
\noindent Do not indent current line.
Miscellaneous
February 25, 2014.
Prints ∼ instead of \~{}, which makes ˜.
Space, disallow linebreak (W.J.~Clinton).
Indicate that the . ends a sentence when following
an uppercase letter.
\hspace{l} Horizontal space of length l (Ex: l = 20pt).
\vspace{l} Vertical space of length l.
\rule{w}{h} Line of width w and height h.
\today
$\sim$
~
\@.
Tabular environments
tabbing environment
\= Set tab stop.
\> Go to tab stop.
Tab stops can be set on “invisible” lines with \kill at the end
of the line. Normally \\ is used to separate lines.
tabular environment
Citation types
\begin{array}[pos]{cols}
\begin{tabular}[pos]{cols}
\begin{tabular*}{width}[pos]{cols}
tabular column specification
l
c
r
p{width}
@{decl}
|
Left-justified column.
Centered column.
Right-justified column.
Same as \parbox[t]{width}.
Insert decl instead of inter-column space.
Inserts a vertical line between columns.
tabular elements
\hline
Horizontal line between rows.
\cline{x-y} Horizontal line across columns x through y.
\multicolumn{n}{cols}{text}
A cell that spans n columns, with cols column
specification.
Math mode
For inline math, use \(...\) or $...$. For displayed math,
use \[...\] or \begin{equation}.
Superscriptx
350
x
y
√
n
x
^{x}
\frac{x}{y}
\sqrt[n]{x}
Subscriptx _{x}
P
n
\sum_{k=1}^n
Qnk=1
\prod_{k=1}^n
k=1
Math-mode symbols
≤ \leq
× \times
◦ ^{\circ}
∞ \infty
⊃ \supset
⊂ \subset
∪ \cup
ȧ \dot a
α \alpha
\epsilon
θ \theta
λ \lambda
π \pi
υ \upsilon
ω \omega
Λ \Lambda
Υ \Upsilon
≥ \geq
÷ \div
◦ \circ
¬ \neg
∀ \forall
∃ \exists
∩ \cap
â \hat a
β \beta
ζ \zeta
ι \iota
µ \mu
ρ \rho
φ \phi
Γ \Gamma
Ξ \Xi
Φ \Phi
6= \neq
± \pm
0 \prime
∧ \wedge
∈ \in
∈
/ \notin
| \mid
ā \bar a
γ \gamma
η \eta
κ \kappa
ν \nu
σ \sigma
χ \chi
∆ \Delta
Π \Pi
Ψ \Psi
Full author list and year. (Watson and Crick
1953)
\citeA{key}
Full author list. (Watson and Crick)
\citeN{key}
Full author list and year. Watson and Crick
(1953)
\shortcite{key} Abbreviated author list and year. ?
\shortciteA{key} Abbreviated author list. ?
\shortciteN{key} Abbreviated author list and year. ?
\citeyear{key}
Cite year only. (1953)
All the above have an NP variant without parentheses; Ex.
\citeNP.
\cite{key}
≈ \approx
· \cdot
· · · \cdots
∨ \vee
→ \rightarrow
⇒ \Rightarrow
⇔ \Leftrightarrow
ã \tilde a
δ \delta
ε \varepsilon
ϑ \vartheta
ξ \xi
τ \tau
ψ \psi
Θ \Theta
Σ \Sigma
Ω \Omega
BibTEX entry types
@article
@book
@booklet
@conference
@inbook
@incollection
@misc
@phdthesis
@proceedings
@techreport
@unpublished
Journal or magazine article.
Book with publisher.
Book without publisher.
Article in conference proceedings.
A part of a book and/or range of pages.
A part of book with its own title.
If nothing else fits.
PhD. thesis.
Proceedings of a conference.
Tech report, usually numbered in series.
Unpublished.
BibTEX fields
Address of publisher. Not necessary for major
publishers.
author
Names of authors, of format ....
booktitle
Title of book when part of it is cited.
chapter
Chapter or section number.
edition
Edition of a book.
editor
Names of editors.
institution Sponsoring institution of tech. report.
journal
Journal name.
key
Used for cross ref. when no author.
month
Month published. Use 3-letter abbreviation.
note
Any additional information.
number
Number of journal or magazine.
organization Organization that sponsors a conference.
pages
Page range (2,6,9--12).
publisher
Publisher’s name.
school
Name of school (for thesis).
series
Name of series of books.
title
Title of work.
type
Type of tech. report, ex. “Research Note”.
volume
Volume of a journal or book.
year
Year of publication.
Not all fields need to be filled. See example below.
address
Bibliography and citations
Common BibTEX style files
When using BibTEX, you need to run latex, bibtex, and
latex twice more to resolve dependencies.
abbrv
alpha
plain
Standard
Standard
Standard
abstract
apa
unsrt
alpha with abstract
APA
Unsorted
The LATEX document should have the following two lines just
before \end{document}, where bibfile.bib is the name of the
BibTEX file.
\bibliographystyle{plain}
\bibliography{bibfile}
BibTEX example
The BibTEX database goes in a file called file.bib, which is
processed with bibtex file.
@String{N = {Na\-ture}}
@Article{WC:1953,
author = {James Watson and Francis Crick},
title
= {A structure for Deoxyribose Nucleic Acid},
journal = N,
volume = {171},
pages
= {737},
year
= 1953
}
Sample LATEX document
\documentclass[11pt]{article}
\usepackage{fullpage}
\title{Template}
\author{Name}
\begin{document}
\maketitle
\section{section}
\subsection*{subsection without number}
text \textbf{bold text} text. Some math: $2+2=5$
\subsection{subsection}
text \emph{emphasized text} text. \cite{WC:1953}
discovered the structure of DNA.
A table:
\begin{table}[!th]
\begin{tabular}{|l|c|r|}
\hline
first & row & data \\
second & row & data \\
\hline
\end{tabular}
\caption{This is the caption}
\label{ex:table}
\end{table}
The table is numbered \ref{ex:table}.
\end{document}
Copyright c 2014 Winston Chang
http://www.stdout.org/∼winston/latex/
LATEX IDE
To write a document using LATEX, any text editor can be used.
• But using a dedicated LATEX editor/IDE can greatly ease your job
• A dedicated LATEX IDE:
– can highlight and auto complete LATEX keywords
– has several LATEX templates for several types of documents
– facilitates compiling, solving compile errors and debugging
– ...
• Sample LATEX IDE’s are Texstudio, Kile, Overleaf∗ , . . .
511
Arabic Support
Thanks to the “Arabi”† package, Arabic and Farsi languages are supported with the “Babel”
package.
• However, since arabic users are few, “Arabi” package is not mature enough and some
minor bugs do exist
– Googling about these bugs, usually you find the same or similar bugs do exist in other
languages, and hence you can infer solutions/workarounds
512
Keep your Concentration/Productivity
Due to its WYSIWYM nature, I feel more concentrating/productive while using LATEX as compared to Ms-Word.
513
Installing LATEX Distribution
Notable distributions are:
• TEX Live
– To download the full TEX Live, download the “one huge ISO file”
• MiKTEX
– To install the full MiKTEX on Windows;
1. download the “Net Installer”
2. download the full MiKTEX
3. run the downloaded installer and install the full MiKTEX
– But, in 2018, there were two major MiKTeX bugs that caused many users not to
be able to compile LATEX documents at all, which caused LYX essentially to stop
working‡
514
∗
Overleaf is a SaaS that is available on the cloud.
Thanks to GOD at first of course
‡
[https://wiki.lyx.org/Windows/TeXLive]
†
351
Installing LATEX Editor/IDE
• Notable examples include Texstudio, Kile, . . .
Porting LATEX Documents
.tex files often reference several files (images, bibliography databases, . . . ).
• Therefore, if you want to port a LATEX document to another computer, you have to copy all
these files
7.2
LYX
LYX is a FOSS graphical front-end to LATEX.
• Roughly, you can compare LYX-to-LATEX as you compare Visual Studio-to-MSVC
compiler
• Unlike LATEX, LYX comes with well organized documentation
• Also LYX is mature and has a big user community
– Therefore, when you encounter a problem, google it. Most likely you will find others
had encountered it and found a solution
Keep your Concentration
Due to its WYSIWYM nature, I feel very concentrating/productive while using LYX as compared
to Ms-Word.
Arabic Support
Arabic is supported in LYX.
Installing LYX
The following installation sequence is recommended:
1. Install a full LATEX distribution (TEX Live is preferred over MiKTEX∗ )
2. Uninstall Inkscape > v1.0† if it is installed
3. Install LYX
• Windows
– Installers are available at www.lyx.org
• Linux
– LYX is usually available in most Linux distributions’ repositories
∗
†
[https://wiki.lyx.org/Windows/TeXLive]
This is to avoid a bug in LYX reconfiguration python script.
352
– To receive the latest stable updates in Ubuntu, add the following ppa by executing the following shell command
> sudo add-apt-repository ppa:lyx-devel/release
4. Install Inkscape (optional)
• Confirm path to inkscape.exe is added to the “PATH” environment variable
520
Useful Configurations (optional)
• Tools > Preferences > Language Settings > Spellchecker > Spellcheck continuously
521
Configuring Converters (Optional)
SVG is the file format used by the Inkscape∗ graphing SW. Therefore, confirm that LYX uses
Inkscape† to convert SVG files as follows:
• Tools . Preferences . File Handling . Converters‡ .
– SVG
(compressed)
->
EPS
>
Converter
--export-area-drawing --export-filename=$$o
∗
>
inkscape $$i
[sec. 8.1]
Make sure that the Inkscape is installed, and the path of “inkscape.exe” is added to “path” environment variable.
You can test this by executing “inkscape” from the command prompt.
‡
Note that Inkscape CLI has changed since version 1.0 [https://wiki.inkscape.org/wiki/index.php/
Using_the_Command_Line#Changes_from_0.92]
†
353
– SVG -> EPS > Converter > inkscape $$i --export-area-drawing
--export-filename=$$o
– SVG (compressed) -> PDF (graphics) > Converter > inkscape $$i
--export-area-drawing --export-filename=$$o
– SVG -> PDF (graphics) > Converter > inkscape $$i --export-area-drawing
--export-filename=$$o
– SVG
(compressed)
->
--export-filename=$$o
PNG
>
Converter
>
inkscape $$i
– SVG -> PNG > Converter > inkscape $$i --export-filename=$$o∗
– GIF -> PNG > Converter > magick convert ’$$i[0]’ $$o
∗
For ImageMagick older than release 7.x, use “convert ’$$i[0]’ $$o”
354
Learning LYX
• Explore style-list, menus and toolbars
• Help menu includes very good manuals
– Manuals themselves are LYX documents
∗ So they are essentially very good LYX examples
– You may begin with:
∗ Tutorial
∗ Introduction
• “PathToLyXInstallationDirectory/Resources/templates” folder contains wide variety of
multilingual valuable templates including:
– scientific journals’ templates
– ...
– posters
• “PathToLyXInstallationDirectory/Resources/examples” folder contains wide variety of
multilingual valuable examples including:
...
– Springer book
– thesis
– pdf forms
– beamer presentation, article, poster,
– ...
• https://wiki.lyx.org/Examples/Examples also includes useful examples
523
Porting LYX Documents
Similar to LATEX documents, .lyx files often reference several files (images, bibliography
databases, . . . ).
• Therefore, if you want to port a LYX document to another computer, you have to copy all
these files
– This can be automatically performed by File > Export > LyX Archive
524
Laboratory Work
• Practice the task explained in section 7.5.1
525
7.3
Beamer
Beamer is a LATEX class for creating professional presentation slides.
• Beamer can be easily used within LYX
526
355
Including Videos
Use the multimedia package. For example, the following animation is produced using:
\movie[externalviewer]{\includegraphics[width=0.7\textheight]{
movieThumbnail.png}}{movie1.mp4}
Notes
The movie1.mp4 file is not needed during LATEX compilation
• It is however needed while displaying the generated pdf file
• It must reside in the same folder as the generated pdf file
Including Gif Animations
• Refer to https://tex.stackexchange.com/questions/240243/getting-gifand-or-moving-images-into-a-latex-presentation for details
356
Presentation Handouts
Beamer-Article is a LATEX class that renders Beamer slides on a standard sized paper∗ to create
professional presentation handouts.
• Frame titles are used as paragraph titles
• Slide layout/colors are not rendered
• Sectioning is kept
• Beamer-Article can be easily used within LYX
529
Creating both the Slides and Handouts
You can have a single source file† for the both the slides and their handouts.
• You can still control this single source file so that the slides and the article are different
530
Keep your Concentration
Due to its WYSIWYM nature, I feel very very very concentrating/productive while using LYXBeamer as compared to Ms-Power Point.
531
Installing Beamer
• Beamer class is usually installed by default with LATEX distributions‡
• LYX templates for both Beamer-presentation and Beamer-article are also installed by default with LYX
532
Learning Beamer
• LYX
– Help > Specific Manuals > Beamer Presentations
– Explore the styles list and Insert menu§
• For various themes of Beamer presentation, check www.hartwork.org/beamer-themematrix
• For customization of Beamer presentations, check the “BEAMER appearance cheat
sheet” at http://science.thilucmic.fr
• Beamer User Guide¶ explain creating Beamer presentations in plain LATEX and LYX as
well
• https://latex-beamer.com/ seems a goof tutorial
533
∗
like A4 or letter
LTEX file or LYX file
‡
such as TEXLive and MiKTEX
§
Styles will be available after you set the current document type to Beamer. This is done from the menu command
“Document > Settings > Document Class” and then select either “Beamer” or “Beamer-Article”.
¶
tug.ctan.org/macros/latex/contrib/beamer/doc/beameruserguide.pdf
† A
357
Laboratory Work
• Practice the task explained in section 7.5.2
358
7.4
Microsoft Word
Important Practices using Microsoft Word
Microsoft Word is too simple to give a traditional tutorial.
• Numerous tutorials are however available on the Internet
• Instead, I will stress on important practices using Word
– Unfortunately, many users are not aware about these practices
– Therefore, they use Word inefficiently and waste considerable time, concentration
and effort
535
The Font
• The most important fonts are “+Body” and “+Headings”
536
359
The Paragraph
Paragraph is a sequence of words ended by the line-end character “¶”.
• Note the “Right-to-left” and “Left-to-right” radio buttons
– They are equivalent to the
buttons
360
The Style
• Style is a collection of formats for:
– Font
– Paragraph
– ...
• Word already ships with a variety of
built-in styles
– However, most of them are hidden
by default!
• Notable styles include:
– Normal
∗ It is the parent of most styles
∗ Changing its formattings affects many styles
– Heading 1, 2, . . . , 9
– Body Text First Indent
– Title
– ...
• More information about styles can be found at
– Style basics in Word (http://office.microsoft.com/en-us/word-help/
style-basics-in-word-HA102647012.aspx)
538
361
Minimize Formatting
• Set the paragraph direction using either of the
buttons
• Use styles whenever possible
• View hidden details of your document by using the
button
• Understand how you can use the ruler tools
• Understand Tabs and how to set Tab types
Default Template
The default template is
data%\Microsoft\Templates”
called
“Normal.dotm”
and
is
located
at
“%app-
• It is recommended to modify the default template instead of modifying every new document
– Make sure you are modifying the “Normal.dotm” file, not the “Document.docx” file
• Be very careful not to corrupt the default template
– If you did, you can reset the default template as follows:
1. close Word
2. delete the corrupted “%appdata%\Microsoft\Templates\Normal.dotm” file
3. launch Word again. Word will create a new virgin template when it is missing
Recommended Default Template Modifications
• Page Setup
– All margins = “2.5 cm”
– Gutter position = “left” or “right”
– Paper size = “A4”
– Section start = “Continuous”
– Section direction = “Left-to-right” or
“Right-to-left”
– Apply to “Whole document”
362
• Modify the “Style Pane Options” as shown
• Modify the “Style Set” as shown
363
• Modify the “+Body” and “+Headings” fonts as shown
• Modify the “Normal” style as follows
– Most important is the “Right-to-left” or “Left-to-right” radio button
364
• Modify the 9 “HeadingX” styles as follows
541
Drawing
If your drawing contains more than one drawing object, always collect your drawing objects in the so called “Drawing
Canvas”.
542
Cross-References
Always use cross-references to refer to any part of your document.
543
365
Section Breaks
Section breaks can be used to divide the document into
different sections.
• Every section can have a different layout, i.e.:
– page orientation
– margins
– number of columns
– header/footer
– ...
• However, printing a part of the document becomes
a bit more complicated!
Collaboration
Use the “Review” menu when collaborating with others.
Use Formulae in Tables
• Check
https://support.office.com/en-us/article/use-a-formula-in-aword-or-outlook-table-cbd0596e-ea8a-485e-a35d-b2cb2c4f3e27
366
Numerals
To be able to write “Arabic” numbers within English text, and “Hindi” numbers within Arabic
text, configure Word as follows:
• File > Options > Advanced > Numeral > Context
547
367
Portability
• doc\docx files are not portable
1
0.5
0
-0.5
-1
0
pi
2pi
3pi
• pdf ∗ files are however portable
Laboratory Work
• Practice the task explained in section 7.5.3
∗
pdf is an acronym for “Portable Document Format”
368
4pi
7.5
Laboratory Work
7.5.1
Technical Writing using LYX
Laboratory 21 (Technical Writing using LYX)
• Re-create the attached document using LYX
• This document is available at https://github.com/ahmed-rashed/Sample-LyXReport
550
7.5.2
Presenting using Beamer
Laboratory 22 (Presenting using Beamer)
• Recreate the attached presentation using LYX
– Create the presentation handouts
• This presentation is available at https://github.com/ahmed-rashed/SampleBeamer-Presentation-By-Lyx
551
7.5.3
Technical Writing using MS Word
Laboratory 23 (Technical Writing using MS Word)
• Re-create the attached document using MS Word
• This document is available at https://github.com/ahmed-rashed/SampleWord-Report
552
369
7.6
Questions
7.1. When a student printed his report at a print shop, he obtained the following corrupted
graph. Explain the cause of the corruption.
1
0.5
0
-0.5
-1
0
pi
2pi
3pi
370
4pi
Part 8
Vector Graphics
Raster vs Vector Graphics
.bmp .jpeg .png
.emf .svg .pdf .eps
0.5
0
-0.5
-1
371
Graphics Formats
.bmp
.png
.jpg
Raster
Uncompressed
Loose-less compression
Lossy compression
Vector
.eps
.pdf
.emf
.svg
..
.
..
.
372
Compressed
Compatible with MS office
Compatible with MS office & web
browsers
Vector Graphics Editors
• Adobe Illustrator (de facto standard; bloated)
• LibreOffice Draw
• Corel Draw (bloated)
• Inkscape (light, FOSS, cross-platform and popular; my
favorite)
• ...
556
Project idea 18 (Vector graphics editors)
Create some selected vector graphics using the following SW.
1. Inkscape
4. Adobe illustrator
2. LibreOffice Draw
3. Calligra Flow
5. Corel draw
• Document your experience
557
373
8.1
Inkscape
• Has a big community, i.e.,
• FOSS
• Cross platform
– it is mature enough
• Much much powerful than MS-Word or
MS-Power point sketching capabilities
– when you encounter a problem,
google it. Most likely you will find
others had encountered it and found
a solution
• Has several plugins that greatly expand
its capabilities
Inkscape Capabilities
• Inkscape is based on cubic Bézier∗ curves
Control points
End points
Smooth point
Corner point
Straight line
– Bézier curve is defined using two end points (nodes) and two control points (handles)
• Additionally, Inkscape can draw and edit:
∗
– straight lines
– LATEX formulae
– circles/arcs/ellipses
– function curves
– text
– ...
[https://en.wikipedia.org/wiki/B%C3%A9zier_curve]
374
• You can also import many graphics formats including pdf’s
ASUS Wireless ADSL Router
(A)
(C)
Phone
Line
Wall telephone
outlet
Phone
Line
Wall power outlet
(B)
Network
cable
Phone
Line
– Then you can edit imported graphics as you like
Interesting Preferences
375
559
376
8.1.1
Interesting Plug-ins
8.1.1.1
Function Plotter
Function Plotter is a built in plugin.
561
• It uses Bézier curves, same as Inkscape
• It calculates the function derivative and
use it to adjust the curve slope
– It produces very smooth curves using much less points than Matlab
– You can still modify the end/control points
8.1.1.2
TexText
TexText allows you to write/edit LATEX formulae inside Inkscape.
Ripples
Distorted version of
the original signal
Sudden
discontinuity
Leakage
• Installation instructions are available at https://inkscape.org/~jcwinkler/%E2%
98%85textext
562
377
8.1.2
Learning Inkscape
• Explore menus and toolbars
• Official manual [15] is very good and detailed
– Chapters 1 includes 10 examples
∗ The first 3 examples are enough for a good start
– Chapters 5 explains editing
∗ Surf it fast
• Help menu includes tutorials, FAQ, . . .
• https://academy.hsoub.com/design/illustration/inkscape/
• http://inkscapetutorials.org
378
8.2
Laboratory Work
8.2.1
Vector Graphing using Inkscape
Laboratory 24 (Vector Graphing using Inkscape)
1. Implement examples 1 and 2 of chapter 1 of [15]
2. Write the mathematical formula
∞
X
(−1)n 2n+1
x
sin(x) =
(2n + 1)!
n=0
• Edit it
3. Plot 20 log sin(πx)
πx
• modify the control points to obtain
the shown curve
4. Import a pdf document and edit it
ASUS Wireless ADSL Router
(A)
(C)
Phone
Line
Wall telephone
outlet
Phone
Line
Wall power outlet
(B)
Network
cable
Phone
Line
564
379
This page is intentionally left blank!
380
Part 9
Computer-Aided Design
• Computer Aided Design (CAD) includes:
– Drafting (CAD)
– Engineering (CAE)
– Manufacturing (CAM)
– Production Engineering (CAPE)
– ...
• Since both have the same abbreviation, CA-Design is often confused with CA-Drafting
• CAD SW packages are usually huge and expensive
– This is why competitive FOSS alternatives hardly exist
565
Classification of CAD SW Packages
Drafting
AutoCad
Mainly CAD
CAD/CAE/CAM/. . .
(additional capabilities are available as
plug-ins)
(Additional capabilities are available as
plug-ins)
SolidWorks
Solid Edge
Inventor
Mechanical Desktop
...
NX∗
CATIA
NX-Ideas†
Creo‡
...
• AutoCad is not a competitive CAD package
∗
Formerly called “Unigraphics”
Formerly called “Ideas”
‡
Formerly called “Pro/Engineer”
†
381
• Currently§ there are two very big competitors
1. Seimens which acquired NX, NX-Ideas, NX-Nastran, Solid Edge, Femap, . . .
2. Dassault Systemes which acquired CATIA, SolidWorks, Abacus, . . .
Project idea 19 (Open Source CAD alternatives)
• Find an FOSS alternative to SolidWorks
– E.g.: FreeCad, . . .
• Create parts, assembly and detail drawings
• Document your experience
§
This may have changed
382
9.1
Assignments
9.1. Reproduce a worksheet like the following
(a) Add an isometric view of both parts in the same worksheet
7.50
5
Cover Plate
32
Piston
C
3
SECTION C-C
3.50
10.25
30
27.50
24
8.50
27.50
383
25
R1.50
15
Gesket
R3
16.50
C
24
24
R3
28
24
32
30
UNSPECIFIED RADII 0.5
R1.50
CAIRO UNIVERSITY
FACULTY OF ENGINEERING
Ahmed M Rashed Desoki
15/3/2003
3.50
Drawn
Revised
Scale
0.20 Thick
2:1
Title
Sh. No.
Two Stroke Engine
Details
1
No. of Shs.
3
568
This page is intentionally left blank!
384
Part 10
Project
Project Goal
1. Lear useful SW
2. Apply a SW on a useful serious application
569
Learn a New SW Packages
Typical learning procedure:
Try/Explore/Read about capabilities of the new SW package
Find good examples
Find short course/training/tutorial
Test your knowledge through a real project
Use a book/manual/user-guide
If you find expert who is willing to answer your questions
• you are lucky
• don’t waste the chance
570
SW features
How to Well Choose a SW among many Alternatives?
This depends on a variety of factors including:
• Stability
• Maturity
• Speed of development
• Bloating
time
less mature
less stable
Mature
Stable
Rule of Thumb
For serious applications:
• avoid SW releases with brand new features
• wait for additional one or two releases until it matures/stabilizes
571
385
10.1
Suggested Project Ideas
In addition to previously mentioned project ideas, the following ones are suggested. The complete list of project ideas is available on page xv.
Project idea 20 (Gnuplot)
Re-implement all Matlab graphics we implemented in our course using Gnuplot, or any
other available free graphics library
Project idea 21 (Symbolic Manipulators)
• Choose at least one open-source and one commercial symbolic manipulator
• Choose a set of symbolic problems (Derive the stiffness and mass matrices for a planar
beam Finite Element)
• Compare the performance of the chosen manipulators
• Document all your gained knowledge.experience
• Prepare a tutorial if possible
1. SageMath
2. Mathematica
3. Maple
4. Mupad; Matlab’s Symbolic Toolbox
Project idea 22 (Spread sheets)
Redraw the bar plot of appendix E using:
1. LibreOffice Calc
3. Gnumeric
2. Calligra Sheets
4. . . .
Compare them and conclude
Document your experience
Project idea 23 (Charts)
Create a model chart using the following
1. yED
4. Calligra Flow
2. Dia
5. Visio
3. LibreOffice Draw (my be general vector graphing SW)
386
6. . . .
Compare them and conclude
Document your experience
Project idea 24 (Word Macro)
Create a Word macro to ???
Project idea 25 (Excel Macro)
• Create Excel macro to calculate cross-section properties
• Fill in columns of Ai , ŷi , ẑi , (Iŷ,i or I¯y,i ) and (Iẑ,i or I¯z,i )
• There should be a window asking for y-symmetry/Anti-symmetry
• Same for z-symmetry/anti-symmetry
• Well format column and results titles
• Options for calculating/displaying yi and zi
Project idea 26 (Project management)
1. MS Project
4. Project forge (???)
2. LibrePlan
5. Calligra Plan
3. ProjectLibre (may be clone)
6. . . .
Project idea 27 (Create a wiki about any topic)
Create a wiki about any topic
Project idea 28 (Embedded Programming)
• Arduino
• Beagle-board/Bone
• Rasperry-pi
• ...
Project idea 29 (Deepfreeze alternatives)
• Windows Steadystate
• ...
572
10.2
Work Groups
• Form a group of a suitable size, depending on the project (maximum 5)
• Several competitive groups are allowed and recommended
387
• Background/experience is important
Team Leader
• Team leader (optional)
– Directs the group work
– Help members to do their tasks professionally
• A leader should
– have a wide experience
– do least physical work
– suggest members grades
∗ Leader and all members grade depends on leader’s serious evaluation
∗ Members opinions/suggestions on the leader also affect his grade
10.3
Work Plan
1. A group of students choose/suggest a project
2. Submit a preliminary report of the project
3. Implement your project
4. Submit a printed useful report and make a presentation
• One week after the final exam
• Report must be submitted before the presentation
5. Copy the following to my PC. The following folder structure is mandatory
(case-sensitive)
• Must be submitted before the presentation
388
Project 03 (in case your project is number 3)
Report
– Soft copy of your report (the source and as a pdf)
Presentation
– Soft copy of your presentation (the source and as a pdf)
Recommended Documentation
– Best tutorials/learning materials you recommend
∗ Just mention the link (url) if a documentation is too big
∗ Remember: Too much information is like no information
Extra
– Other materials you recommend
Binaries (optional)
– Installation binaries for your package
575
10.4
Preliminary Report
Prepare and submit a report containing:
1. Project Description: What will you do exactly?
2. Good examples
3. Short course/training/tutorial
4. Outcome of the project
5. Book/manual/user-guide
6. Roles of the project members (optional)
Remember
• Too much information is like no information
– So be concise
576
10.5
Presentation
• Your presentation time is 15 minutes
– 10 minutes presentation
389
– 5 minutes for questions
This cannot be exceeded under any circumstances
• Your presentation must cover the following
1. Capabilities of your package
2. Project Statement
3. Best tutorials/learning materials your recommend
4. Project Implementation
– Summarize all your efforts/knowledge/experience
5. Conclusion/Suggestions/Opinion/. . .
– Better alternatives, especially open source ones
Remember
• One week after the final exam
Presentation Guidelines
• All of the group members must attend the presentation
• It is not necessary that all of the group members speak in the presentation
• Questions are directed to the group
– In response to a question, one or several members may answer the question concisely
• The following project group members should begin their preparation immediately after
the current group finishes their presentation (i.e., during the 5 minutes question time)
10.6
Report
• Must include the same 5 topics requested in the presentation
• Well document all the details behind your presentation
Remember
• Too much information is like no information
– So be concise
• Submitted before the project presentation
390
10.7
Grading
(20%)
• Preliminary report
– Pay enough effort
– Submit in-time
(20%)
• Presentation
– Covers all the five topics requested
– Well prepared
– Respects the allotted time
– Revised
– Concise:
information using the least time/words/material/. . .
ability to present useful
– Response to questions
• Project implementing
(30%)
• Project report
(20%)
• Soft material copied to my PC
(10%)
– Accurately follow the folder structure (case-sensitive)
– Clean material
580
391
This page is intentionally left blank!
392
Appendices
Appendix A
Tuning Windows
Windows Home edition & Group Policy Editor
The Group Policy Editor is not included in Windows Home edition.
• Therefore, the following does not apply for Windows Home edition
581
Disable AutoRun
1. Run “gpedit.msc” (Local Group Policy Editor∗ )
2. Computer Configuration . Administrative Templates . Windows Components . AutoPlay Policies .
(a) Set the default behavior for AutoRun . Enabled . Do not execute any autorun commands
(b) Turn off Autoplay . Enabled . All drives
393
3. Restart your PC
582
Disable Windows Telemetry and Data Collection
1. Start . Settings
.
• For Windows 10;
Privacy .
– General
∗ Disable all the settings
– Diagnostics and Feedback
∗ Disable all the settings
∗ Feedback
Never
frequency
.
• For Windows 11;
Privacy & Security .
– Diagnostics & feedback
∗ Send optional
data: off
diagnostic
– Tailored experiences: off
∗
Professional Editions Only
394
2. Run “gpedit.msc” (Local Group Policy Editor)
3. Computer Configuration . Administrative Templates .
• System . Internet Communication Management . Internet Communication Settings . Turn off Windows Customer Experience Improvement Program . Enable
• Windows Components .
– Application Compatibility
∗ Enable all the “Turn off” fields
– Cloud Content
∗ Enable all the “Turn off” fields
– Data Collection and Preview Builds .
∗ Allow Telemetry/Diagnostic Data . Enaled . 0 - Security/Diagnostic data
off (not recommended)∗
∗
Only works on Windows Enterprise (including LTSC), Educationand Server editions
395
∗ Configure collection of browsing data for Desktop Analytics . Enabled .
Do not allow sending intranet or internet history
∗ Limit Enhanced diagnostic data to the minimum required by Windows Analytics/optional diagnostic data for Desktop Analytics . Enabled . Disable
Windows Analytics Collection
– Internet Explorer . Prevent participation in the Customer Experience Improvement Program . Enable
4. Disable the following services:
• Connected User Experiences and Telemetry∗
• dmwappushsvc
∗
For Windows 10 prior to version 1511, this service was called “Diagnostics Tracking Service”
396
• Program Compatibility Assistance Service
5. Restart your PC
583
Windows 11; Disable Automatic Download/Install of Updates
Run “gpedit.msc” (Edit Group Policy)
• Computer Configuration . Administrative Templates . Windows Components . Windows Update . Manage end user experience . Configure Automatic Updates . Disabled
584
Windows 10; Disable Automatic Download/Install of Updates∗
1. Run “gpedit.msc” (Local Group Policy Editor)
• Computer Configuration . Administrative Templates . Windows Components .
Windows Update .
(a) Configure Automatic Updates . Enabled . 2 - Notify for download and notify
for install
(b) Allow Automatic Updates immediate installation . Disabled
2. Run “services.msc”
• Windows Update . Manual
• Windows Modules Installer . Manual
3. Restart your PC
585
∗
[www.howtogeek.com/224471/how-to-prevent-windows-10-from-automaticallydownloading-updates/]
397
Disable Superfetch
• Run “services.msc”
– Superfetch . Disabled
Disable Unnecessary Auto-Start Processes
• Use the “Autoruns” utility and disable all unnecessary auto-start processes
Avoid Adobe Reader DC
“DC” means "Document Cloud".
• Adobe Reader DC is set to be automatically updated
• Therefore, it doesn’t give the user the ability to disable the updates!
• Hence, rather install Adobe Reader XI (V 11.0.06) which is the last version before the DC
versions
• Or better replace it with PDF-XChange Editor
398
Appendix B
Brief Introduction to Linux
Memorable Linux Milestones
∗
589
∗
www.instagram.com/p/Czd2bE-AEJr/
399
B.1
Notable Linux Distributions
clone
Slackware
Fedora
fork
CentOS
Redhat Enterprise
SUSE Linux Enterprise
Mandriva
openSUSE
Kubuntu
PCLinuxOS
Mageia
debian
Linux
kernel
Ubuntu
LinuxMint
LinuxMint Debian Edition
Gentoo
Android
Arch
Manjaro
Distribution
Description
Red Hat
Enterprise
Linux (RHEL)
Super-corporatized Linux, currently a branch of Fedora
Fedora
Testing ground for developing Red Hat Enterprise Linux
CentOS
Free clone of Red Hat Enterprise Linux, built upon the source code that
Red Hat have to announce (i.e., branch of Red Hat Enterprise).
SUSE Linux
Enterprise
(SLE)
Corporatized Linux, currently a branch of openSUSE
It is famous for its impressive documentation
openSUSE
Testing ground for developing SUSE Linux Enterprise
Mandriva
Linux
One of the most user-friendly distributions. Currently it also became
corporatized
PCLinuxOS
Forked from Mandriva. It is designed to be as close as possible to
MS-Windows.
Mageia
Forked from Mandriva. It is a competitor to Ubuntu
400
Distribution
Description
Debian
A popular non-commercial distribution
Ubuntu
Cleaned-up branch of Debian
Kubuntu
Official flavour of Ubuntu that uses the KDE Plasma desktop
environment
LinuxMint
Improved branch of Ubuntu that offers Cinnamon, MATE and Xfce
desktop environments
elementary OS
Improved branch of Ubuntu which resembles Mac OS using its Pantheon
desktop environment
Gentoo
Compile every thing from scratch via Internet
Arch Linux
Lightweight distribution that focuses on elegance, code correctness,
minimalism and simplicity. Installation requires a lot of work. Its wiki
has become an invaluable repository of Linux-related knowledge.
Manjaro
Arch Linux branch but with a friendly wrapper which makes installing
and working with software packages a quick, click-and-done process.
• For more information
– Ultimate Distros 2013, Linux User & Developer magazine, Issue 130, pages 20–30
– Ultimate Distro & FOSS Guide 2015, Linux User & Developer magazine, Issue 148,
pages 16–25∗
590
∗
I began to feel it is biased!!
401
Testing-Ground Linux Distributions
Designed to be stable
Red Hat Enterprise
CentOS
SUSE Linux Enterprise
Mandriva Linux
PCLinuxOS
Mageia
Debian
Ubuntu
Kubuntu
Mint
elementary OS
Gentoo
Arch Linux
Manjaro
Testing ground
Fedora
openSUSE
Linux Distributions of 2015∗
∗
[www.cio.com/article/2881172/survey-says-kde-plasma-is-the-most-popular-desktoplinux-environment.html]
402
B.2
CLI Shell
Linux Shells
Linux has several CLI shells.
Shell Name
sh
bash
ksh
csh, tcsh
zsh
Description∗
The Bourne shell; the original shell from early versions of UNIX
(Bourne Again SHell) It is a free version of the Bourne shell from the GNU
project. bash adds many features such as editable command lines, a
scrollable command history, and tab completion to help avoid typing long
file names.
The Korn shell. It uses the same syntax as the Bourne shell and has
included the user-friendly features of the C shell. ksh is used in many
installation scripts and should probably be installed on the system even if
it’s not your primary shell.
The C shell, and its derivatives. It is probably the third most popular shell
after bash and Korn shells.
The Z shell. It is an extended Bourne shell with a large number of
improvements, including some features of Bash, ksh, and tcsh.
• Shell programming is detailed in [16, Ch 2]
593
Executing CLI Programs Files on the Shell
To execute a program file† in the shell, simply type the full path to the file in the shell and press
Enter.
• For example to execute the /bin/ls file, execute > /bin/ls in the shell and press
Enter
• If you would like to omit the file path and just write > ls in the shell, you have two
options:
1. Change the Current Working Directory (CWD) to the file path “ /bin ”
2. Add the file path to the “PATH” environment variable‡§
• In Linux/Unix shells, the default path does not include the CWD¶
– Therefore, to specify a file existing in the CWD, you need to write ./filename
594
∗
†
[16] and [www.ibm.com/developerworks/linux/library/l-roadmap2]
This file must be attributed as executable.
‡
To check the paths already defined in “PATH”, execute > echo $PATH .
§
To add “/usr/local/bin” for example to “PATH”, execute > PATH=$PATH:/usr/local/bin
¶
Windows, on the other hand, automatically includes the current directory in the PATH
403
Shell Scripting
• A very good crash course is available @ www.ibm.com/developerworks/linux/
library/l-roadmap2
Script Files
Shell commands can be executed either:
1. interactively; by writing commands one after another in the CLI.
2. by writing commands in a text file (referred to as “script file”), and then executing the
script file itself.
Executing Script Files
A script file can be executed by either:
1. passing the script file name as an argument to the shell executable. E.g.:
> sh scriptfilename
> ksh scriptfilename
> bash scriptfilename
...
2. specifying the specific shell after “ #! ” at 1st line of the script file∗ and setting the script
file permissions to “executable”, and then executing script file itself in the shell
• Example shell specifications are:
“ #!/bin/sh ”
∗
“ #!/bin/bash ”
[www.ibm.com/developerworks/linux/library/l-roadmap2]
404
“ #!/bin/csh ”
Shell Commands Cheat Sheet∗
COMMAND LINECHEAT SHEET
›
presented by TOWER Version control with Git - made easy
DIRECTORIES
$ pwd
FILES
$ rm <file>
Display path of current working directory
$ cd <directory>
Change directory to <directory>
$ cd ..
$ find <dir> -name "<file>"
Delete <file>
$ rm -r <directory>
Delete <directory>
$ rm -f <file>
Navigate to parent directory
Force-delete <file> (add -r to forcedelete a directory)
$ ls
List directory contents
$ mv <file-old> <file-new>
Rename <file-old> to <file-new>
$ ls -la
List detailed directory contents, including$ mv <file> <directory>
hidden files
Move <file> to <directory> (possibly
overwriting an existing file)
$ mkdir <directory>
Create new directory named <directory>
OUTPUT
$ cat <file>
Output the contents of <file>
$ less <file>
Output the contents of <file> using
the less command (which supports
pagination etc.)
$ cp <file> <directory>
Copy <file> to <directory> (possibly
overwriting an existing file)
$ cp -r <directory1>
< directory2>
Copy <directory1> and its contents to
<directory2> (possibly overwriting files
in an existing directory)
$ touch <file>
Update file access & modification time
(and create <file> if it doesn’t exist)
$ head <file>
Output the first 10 lines of <file>
$ <cmd> > <file>
Direct the output of <cmd> into <file>
$ <cmd> >> <file>
Append the output of <cmd> to <file>
$ <cmd1> | <cmd2>
Direct the output of <cmd1> to <cmd2>
$ clear
Clear the command line window
∗
SEARCH
PERMISSIONS
Find all files named <file> inside <dir>
(use wildcards [*] to search for parts of
filenames, e.g. "file.*")
$ grep "<text>" <file>
Output all occurrences of <text> inside
<file> (add -i for case-insensitivity)
$ grep -rl "<text>" <dir>
Search for all files containing <text>
inside <dir>
NETWORK
$ ping <host>
Ping <host> and display status
$ whois <domain>
Output whois information for <domain>
$ curl -O <url/to/file>
Download <file> (via HTTP[S] or FTP)
$ ssh <username>@<host>
Establish an SSH connection to <host>
with user <username>
$ scp <file>
< user>@<host>:/remote/path
Copy <file> to a remote <host>
PROCESSES
$ chmod u=rwx,g+rx,o-x <file>
Sets <file> owner permissions to rwx,
adds rx to group permissions and
removes x permission from others
$ chmod -R 600 <directory>
Change permissions of <directory>
(and its contents) to 600
$ chown <user>:<group> <file>
Change ownership of <file> to <user>
and <group> (add -R to include a
directory’s contents)
[www.git-tower.com/learn/cheat-sheets/cli]
405
$ ps ax
Output currently running processes
$ top
Display live information about currently
running processes
$ kill <pid>
Quit process with ID <pid>
COMMAND LINE TIPS & TRICKS
›
presented by TOWER Version control with Git - made easy
GETTING HELP
THE “CTRL” KEY
HOME FOLDER
On the command line, help is always at
hand:you can either type man <command>|
or <command> --help to receive detailed
documentation about the command in
question.
Various keyboard shortcuts can assist
you when entering text: Hitting CTRL+A|
moves the caret to the beginning
and CTRL+E to the end of the line.
File and directory paths can get long
and awkward. If you’re addressing a
path inside of your home folder though,
you can make things easier by using
the ~ character. So instead of writing
cd /Users/your-username/projects/ , a
simple cd ~/projects/ will do.
FILE PERMISSIONS
On Unix systems, file permissions are
set using three digits: the first one
representing the permissions for the
owning user, the second one for its group,
and the third one for anyone else.
Add up the desired access rights for each
digit as following:
4 —access/read (r)
2 —modify/write (w)
1 —execute (x)
For example, 755 means “rwx” for owner
and “rx” for both group and anyone. 740|
represents “rwx” for owner, “r” for group
and no rights for other users.
In a similar fashion, CTRL+K deletes
all characters after and CTRL+U all
characters in front of the caret.
Pressing CTRL+L clears the screen
(similarly to the clear command). If
you should ever want to abort a running
command, CTRL+C will cancel it.
And in case you should forget your user
name, whoami will remind you.
THE “TAB” KEY
The less command can display and
paginate output. This means that it only
displays one page full of content and then
waits for your explicit instructions. You’ll
know you have less in front of you if the
last line of your screen either shows the
file’s name or just a colon ( : ).
Whenever entering paths and file names,
the TAB key comes in very handy. It
autocompletes what you’ve written,
reducing typos quite efficiently. E.g. when
you want to switch to a different directory,
you can either type every component of
the path by hand:
$ cd ~/projects/acmedesign/docs/
…or use the TAB key (try this yourself):
COMBINING COMMANDS
$ cd ~/pr[TAB]ojects/
ac[TAB]medesign/d[TAB]ocs/
If you plan to run a series of commands
after another, it might be useful to
combine them instead of waiting for each
command to finish before typing the
next one. To do so, simply separate the
commands with a semicolon ( ; ) on the
same line.
In case your typed characters are
ambiguous (because “ac” could point to
the “acmedesign” or the “actionscript”
folder), the command line won’t be able
to autocomplete. In that case, you can
hit TAB twice to view all possible matches
and then type a few more characters.
Additionally, it is possble to execute a
command only if its predecessor produces
a certain result. Code placed after the &&|
operator will only be run if the previous
command completes successfully, while
the opposite || operator only continues
if the previous command fails. The
following command will create the folder
“videos” only if the cd command fails
(and the folder therefore doesn’t exist):
$ cd ~/videos || mkdir ~/videos
THE ARROW KEYS
OUTPUT WITH “LESS”
Apart from the arrow keys, hitting SPACE|
will scroll one page forward, b will scroll
one page backward, and q will quit
the less program.
DIRECTING OUTPUT
The output of a command does not
necessarily have to be printed to the
command line. Instead, you can decide to
direct it to somewhere else.
Using the > operator, for example, output
can be directed to a file. The following
command will save the running processes
to a text file in your home folder:
$ ps ax > ~/processes.txt
The command line keeps a history of the
most recent commands you executed. By
pressing the ARROW UP key, you can step
through the last called commands (starting
with the most recent). ARROW DOWN will
move forward in history towards the most
recent call.
Bonus tip:Calling the history command
prints a list of all recent commands.
• All Linux commands and options are case sensitive
• Commands are almost always lowercase
406
It is also possible to pass output to another
command using the | (pipe) operator,
which makes it very easy to create complex
operations. E.g., this chain of commands
will list the current directory’s contents,
search the list for PDF files and display the
results with the less command:
$ ls | grep ".pdf" | less
B.3
GUI Shells
• More information are in:
– https://wiki.archlinux.org/index.php/Comparison_of_desktop_
environments
– https://itsfoss.com/best-linux-desktop-environments/
– https://fossbytes.com/best-linux-desktop-environments/
– https://en.wikipedia.org/wiki/Comparison_of_X_Window_System_
desktop_environments
599
407
GUI Shells of 2015∗
∗
[www.cio.com/article/2881172/survey-says-kde-plasma-is-the-most-popular-desktoplinux-environment.html]
408
B.4
Linux File System
• Details are available in [17, sec. C.2]
601
Path Representation∗
OS
Separator
Current
Directory
Parent
Directory
Home
Directory
Unix-like
MS Windows
/
/ or \
.
.
..
..
~
602
Filename Suffix†
Linux does not use filename suffix‡ to identity a file’s type.
• Rather, Linux looks at the header contents of a file to identity the type.
• You can still use filename suffixes for human-readability, but Linux doesn’t care.
603
∗
[https://en.wikipedia.org/wiki/Path_(computing)]
[www.ibm.com/developerworks/linux/library/l-roadmap1]
‡
In the language of windows users, file suffix is the file extensions.
†
409
Hidden Files/Directories§
In Unix-like OS’s, any file or folder that starts with a “.” charecter¶‖ is to be treated as hidden .
• That is, the ls command does not display them unless the -a or -A flags are used
B.5
Installing SW
SW Packages
A SW Package is a distribution of a SW and data in the form of archive file. A package file
usually contains:
• description
• directory layout
• version number
• list of dependencies
• executable files
• ...
Among notable package formats are∗ :
Format
apk
APPX and
APPXBundle
deb†
ebuild
PKG
rpm‡
Consumed by
Android
Windows 8 and later, Windows Phone
Debian and its derivatives, such as Ubuntu
Gentoo Linux
OS X, iOS, PlayStation 3, Solaris
RHEL, Fedora and its derivatives such as CentOS and SLE
§
[https://en.wikipedia.org/wiki/Hidden_file_and_hidden_directory]
Such files are commonly called a dot file or dotfile.
‖
for example, /home/user/.config
∗
[https://en.wikipedia.org/wiki/Package_format]
§
[https://en.wikipedia.org/wiki/Deb_(file_format)]
¶
[www.ibm.com/developerworks/linux/library/l-roadmap9/]
¶
410
Package Manager (PM)
A Package Manager‖ is a collection of SW tools that automates the process of downloading,
installing, upgrading, configuring, and removing SW packages in a consistent manner.
User requests
installation of
package
PM finds
needed packages
PM downloads all
needed packages
from repository
PM installs and
configures,
recommends any
manual actions
User uses software
606
Notable PM Front Ends
CLI Front Ends
APT
Pacman
yum
Zypper
urpmi
Used in
Debian and its derivatives
Arch Linux and its derivatives
RHEL, Fedora, CentOS
openSUSE and SLE
Mandriva Linux and Mageia
GUI Front Ends
Synaptic
Ubuntu Software Center
Octopi
Mac App Store
Google Play
App Store
Windows Store
Used in
Debian and its derivatives
Ubuntu
Manjaro
Mac OS
Android
iOS
Windows, Windows Phone
607
SW Repository
A SW repository is a storage server from which SW packages may be downloaded and installed
on a computer. Notable examples are:
• App Store∗
• Ubuntu repositories
• Mac App Store
• Google Play
• Windows Store
608
‖
∗
https://en.wikipedia.org/wiki/Package_manager
for iOS apps
411
Official Repositories of a Linux Distribution
Official Repositories
Most Linux distributions† offer a set of official SW repositories.
• The distribution vendor usually review SW packages by before including them in the official repositories
– Therefore, included packages are usually safe and stable
– However, they may be outdated versions
Third Party Repositories
Anyone can make his own SW repository for hosting whatever packages he likes.
Ubuntu Personal Package Archive (PPA)
PPA is a SW repository hosted on launchpad.net∗ for use with Ubuntu.
• Anyone can apply for an account to set up a PPA repository on launchpad.net
• PPA’s are not checked in any way by the Ubuntu team
– Therefore, PPA packages may be unsafe or unstable
Re-using Downloaded SW Packages
SW package files are usually† downloaded to “/var/cache/apt/archives”.
• If someone else has already downloaded your desired SW packages;
1. copy theses packages to the above directory (instead of re-downloading them)
2. for the APT package manager, run the CLI command sudo apt-get update to
inform it about the copied packages
Installing SW on Linux
SW can be installed from either:
• SW packages (.deb, .rpm, . . . )
– Use PM
• Installers (.run, .bin, .bundle, . . . )
– Simply execute these installers.
• Source code that you “build” on your own computer (.tgz, .tar.gz, .zip, . . . )
– Extract the archive and look for a readme file or alike for instructions how to build
the package
†
Based on my own experience, I found Ubuntu repositories very fast and very big, as compared to openSuse,
Mageia and Fedore repositories.
∗
LaunchPad is developed and maintained by Canonical Ltd.; the company behind Ubuntu.
†
This may vary from a distribution to another.
412
B.6
More Information
• Course 102 Understanding Linux, by Eng. Ahmed El-Arabawy; Director of SW Engineering at Cygnus Broadband
– This is an excellent and very comprehensive course explaining all aspects of Linux
– Slides are available at http://linux4embeddedsystems.com/courses/course/
index.php, while lecture videos are available at www.youtube.com/user/
Linux4Embedded/playlists
• Windows-to-Linux roadmap (www.ibm.com/developerworks/linux/library/lroadmap/)
• The ultimate guide to Linux for Windows users (www.dedoimedo.com/computers/
ultimate-linux-guide-for-windows-users.html)
• 10 Best Linux Desktop Environments And Their Comparison | 2017 Edition (https:
//fossbytes.com/best-linux-desktop-environments/)
• Imagine Publishing
– Linux User&Developer magazine (www.linuxuser.co.uk/)
∗ Dual-boot Linux on any device, issue 135, pages 24–33
∗ KDE Plasma 5 VS Gnome | LXDE | Unity | Cinnamon & more, Issue 144, pages
16–25
∗ Switch to Linux, Issue 141, 2014; pp. 24˜30
– Linux Tips, Tricks, Apps & Hacks (www.imagineshop.co.uk/bookazines.html)
– Linux & Open Source Genius Guides (www.imagineshop.co.uk/bookazines.
html)
• Your Guide To Ubuntu Repositories and Package Management (www.makeuseof.com/
tag/repositories-package-management-ubuntu)
• Arabic websites
– www.linuxac.org
– http://itwadi.com
– www.ojuba.org/
612
Project idea 30 (Remaster Linux)
Remaster Linux-Mint or Ubuntu to create a custom live DVD with your selected modifications and SW collection
613
413
This page is intentionally left blank!
414
Appendix C
C.1
Useful SW Applications
Useful Cross–Platform Applications
GoldenDict; dictionary UI
Babylon Dictionaries or any other dictionaries is needed
Duplicati; FOSS backup SW
Beyond Compare; compare files and directories. Synchronizes folders as well
yEd; create high quality diagrams
Inkscape FOSS vector graphics editor (Adobe–Illustrator alternative)
Krita FOSS photo editor (Adobe–PhotoShop alternative)
OpenShot FOSS simple non–linear video editor (Adobe–Premier alternative)
Shotcut FOSS powerful non–linear video editor (Adobe–Premier alternative)
SystemRescueCD; Bootable CD in case you cannot boot your PC
VLC; powerful and universal media player
614
C.2
Useful Applications for Windows
Acronis True Image Home for all kinds of backup [appendix D]
Autoruns enables detection and disabling unwanted autostart processes
WinPatrol; control windows start–up programs
• WinPatrol worked very well with Windows XP and 7
• However, it is no longer effective for Windows 10 and beyond!
Bulk Rename Utility; a powerful batch file rename utility
HWiNFO detects and displays the specifications of the HW
CrystalDiskMark benchmarks your storage speed
EmfPrinter; emf virtual printer
• Unfortunately does not install on windows 7, 8 & 10
Office Arabic Language Pack
WinDirStat; statistics about what is consuming your storage space
Notepad++; powerful text editor
SVG See; a Windows Explorer extension that renders SVG thumbnails, so that you can have an
overview of your SVG files
415
Windows File Recovery; free sw to recover deleted files
Recuva; to recover deleted files
PDF–XChange Editor; a better alternative to Adobe Acrobat
C.3
Useful Applications for Linux
∗
∗
www.instagram.com/p/C0trG3-gSKu/
416
Appendix D
Data Backup
Backup is to keep a copy of data.
617
Sophisticated Backup SW∗ (draft)
Sophisticated backup SW may enable:
• compress the backup
• encrypt the backup
• increment new backups
• deduplicate Duplicati analyzes the content of backedup files and stores data blocks. Due
to that, Duplicati will find duplicate files and similar content and store them only once in
the backup. As Duplicati analyzes the content of files it can handle situations very well if
files and folders are moved or renamed. As the content does not change, the next backup
will be tiny.
– † In the deduplication process, unique chunks of data, or byte patterns, are identified
and stored during a process of analysis. As the analysis continues, other chunks are
compared to the stored copy and whenever a match occurs, the redundant chunk is
replaced with a small reference that points to the stored chunk. Given that the same
byte pattern may occur dozens, hundreds, or even thousands of times (the match
frequency is dependent on the chunk size), the amount of data that must be stored or
transferred can be greatly reduced.
• Fail-safe design Duplicati is designed to handle various kinds of issues: Network hiccups,
interrupted backups, unavailable or corrupt storage systems. Even if a backup run was
interrupted, it can be continued at a later time. Duplicati will then backup everything that
was missed in the last backup. And even if remote files get corrupted, Duplicati can try to
repair them if local data is still present or restore as much as possible.
• Meta data Duplicati also stores the meta data of files in the backup. When backup files
are restored, the timestamps (last modified, created) will also be restored as well as the
system’s access permissions. To avoid inaccessible files e.g. when the system user’s have
changed, restoring of access permissions is optional.
• Scheduler The built-in scheduler runs your backups automatically at the times and intervals you define. One backup everyday, at the weekend, every hour or even 3pm every 3rd
Monday is possible. And even if a date is missed, Duplicati will run the job as soon as
possible.
• Backup open files When a file is in use by a process or application, it usually cannot be
read by another process, making it impossible to backup that file. On Windows systems,
Duplicati can use Volume Shadow Copy Services (VSS). For Linux based devices Duplicati can use Logical Volume Management (LVM). VSS and LVM offer the possibility to
create an application consistent snapshot of a volume, which is used by Duplicati to make
a reliable backup of these open files.
618
∗
†
https://duplicati.readthedocs.io/en/latest/01-introduction/
[https://en.wikipedia.org/wiki/Data_deduplication]
417
Backup is not:
• synchronization
• disk imaging
Full Backup
www.binbert.com/blog/2010/09/difference-between-differential-incremental-and-full-backups/
It is a complete backup of everything
• To restore, only the last full backup is needed
Differential Backup
www.binbert.com/blog/2010/09/difference-between-differential-incremental-and-full-backups/
is a backup of everything since the last Full Backup
• To restore, only the last differential-backup and its full-backup are needed
418
Incremental Backup
www.binbert.com/blog/2010/09/difference-between-differential-incremental-and-full-backups/
It is a backup from last incremental backup
• To restore, all the incremental-backups and their full-backup are needed
• The drawback is that if data need to be restored from the most recent incremental backup,
the full backup has to be restored first, followed by all incremental backups. This is a
cumbersome and error-sensitive procedure ∗ .
622
∗
https://duplicati.readthedocs.io/en/latest/01-introduction/
419
This page is intentionally left blank!
420
Appendix E
Data Rates
Data transfer rates are also called
• data rates
• useful bit rates
• bit rates
• peak bit rates
• physical layer information rates
• digital bandwidth capacity
• net bit rates
• ...
623
Data Rate Units∗
Unit (SI)
Kilobyte (kB)
Megabyte (MB)
Gigabyte (GB)
Terabyte (TB)
Petabyte (PB)
Exabyte (EB)
Zettabyte (ZB)
Yottabyte (YB)
Bytes
1,000
1,0002
1,0003
1,0004
1,0005
1,0006
1,0007
1,0008
Unit (IEC 60027-2)
Kibibyte (kiB)
Mebibyte (MiB)
Gibibyte (GiB)
Tebibyte (TiB)
Pebibyte (PiB)
Exbibyte (EiB)
Zebibyte (ZiB)
Yobibyte (YiB)
Bytes
1,024
1,0242
1,0243
1,0244
1,0245
1,0246
1,0247
1,0248
624
∗
[http://en.wikipedia.org/w/index.php?title=Data_rate_units&oldid=597391939]
421
Typical Data Rates∗
Most of the following rates are theoretical maximum throughput measures; in practice, the actual effective throughput is almost inevitably lower in proportion to the load from other devices
(network/bus contention), interframe gap, and other overhead in data link layer protocols etc.
Technology
Rate
(Mbit/s)
Wired Ethernet
Fast Ethernet (100BASE–TX)
100
Gigabit Ethernet (1000BASE-T)
1,000
10 Gigabit Ethernet (10GBASE–X)
10,000
InfiniBand
†
Infiniband FDR 4x
54,540
†
Infiniband EDR 4x
100,000
Infiniband HDR 4x†
200,000
Wireless Ethernet
IEEE 802.11b
11
IEEE 802.11g
54
IEEE 802.11n (aka Wi–Fi 4)
600
IEEE 802.11ac (aka Wi–Fi 5)
6,930
IEEE 802.11ax (aka Wi–Fi 6)
11,000
Wired Internet
56k (V.92) (download)
0.056
56k (V.92) (upload)
0.048
ADSL (G.DMT) (download)
8.192
ADSL (G.DMT) (upload)
1.024
ADSL2 (download)
12.288
ADSL2 (upload)
1.44
ADSL2+ (download)
24.576
ADSL2+ (upload)
3.584
VDSL
52
VDSL2
100
GPON (download)
2,488
GPON fiber optic service (upload)
1,244
10G–PON (download)
10,000
10G–PON (upload)
2,500
Wireless Internet
GSM CSD (2G) (download)
0.0144
GSM CSD (2G) (upload)
0.0144
GPRS (2.5G) (download)
0.0576
GPRS (2.5G) (upload)
0.0288
EDGE (2.75G) (download)
0.2368
EDGE (2.75G) (upload)
0.2368
UMTS (3G)(download)
0.384
∗
†
Rate
(MByte/s)
12.5
125
1,250
6,820
12,500
25,000
1.375
6.75
75
866.25
1375
0.007
0.006
1.024
0.18
1.536
0.18
3.072
0.448
7
12.5
311
155.5
1,250
312.5
0.0018
0.0018
0.0072
0.0036
0.0296
0.0296
0.048
[https://en.wikipedia.org/wiki/List_of_device_bit_rates]
Most systems use a 4x InfiniBand. 12x links are typically used for cluster and data centers.
422
Technology
Rate
(Mbit/s)
0.384
13.98
5.76
173
58
UMTS (3G)(upload)
HSDPA/HSUPA (3.5G) (download)
HSDPA/HSUPA (3.5G) (upload)
LTE (4G) (download)
LTE (4G) (upload)
Computer Bus
PCI Express 1.0 x1
2,500.
PCI Express 2.0 x1
5,000.
PCI Express 3.0 x1
8,000.
PCI Express 4.0 x1
16,000.
PCI Express 5.0 x1
32,000.
PCI Express 6.0 x1
60,500.
Storage Buses
UDMA ATA 66
533.6
UDMA ATA 133
1,064
SATA–1
1,500
SAS–1
3,000
SATA–2
3,000
SAS–2
6,000
SATA–3
6,000
SAS–3
12,000
NVMe (PCI Express 3.0 x4)
32,000
NVMe (PCI Express 4.0 x4)
64,000
Peripherals
Parallel IEEE 1284
1
Serial UART
2.7648
I2c
3.4
GPIB/HPIB
8
Serial RS–422
10
USB
12
USB 2.0
480
USB 3.0 (aka USB 3.1 Gen 1)
5,000
USB 3.1 (aka USB 3.1 Gen 2)
10,000
USB 3.2
20,000
Memory
DDR2–800
51,200
DDR3–2133
136,528
DDR4–3200
204,800
DDR5–6400
409,600
Rate
(MByte/s)
0.048
1.7475
0.72
21.625
7.25
250.
500.
984.6
1,969.4
3,937.5
7,562.5
66.7
133
150
300
300
600
600
1,200
3,938
7,876
0.125
345.6
0.425
1
1.25
1.5
60
500
1,212
2,424
6,400
17,066
25,600
51,200
625
423
(500.)
(51,200.)
(17,066.)
(6,400.)
(2,424.)
(1,212.)
(3,938.)
(1,500.)
(375.)
(187.5)
(133.)
10,000.
20,000.
1,000.
5,000.
3,000.3,000.
(60.)
1,500.
1,064.
100.
480.
(0.125)
(0.048)
(0.0296)
8.
10.
12.
1.
3.4
1.
0.1
(0.0072)
0.384
0.2368
(0.0018)
MByte/s
10.
(1.5)
(1.25)
(1.)
(0.425)
13.98
(0.3456)
(1.7475)
52.
24.576
0.8
0.056
51,200.
10,000.
2.7648
0.08
409,600.
204,800.
136,528.
173.
100.
12.288
8.192
8.
12,000.
(375.)
(984.6)
(250.)
(21.625)
(12.5)
(6.5)
(3.072)
(1.536)
54.
(0.007)
424
80.
Mbit/s
(1.024)
100.
(6.75)
600.
(12.5)
800.
8,000.
2,500.
(75.)
(125.)
1,000.
32,000.
16,000.
11,000.
6,930.
10,000.
8,000.
60,500.
(1,375.)
(866.25)
(1,250.)
54,540.
(7,562.5)
100,000.
80,000.
(1,969.4)
200,000.
8 bit = 1 Byte
(25,600.)
Data Transfer Rates
(25,000.)
(12,500.)
(6,817.5)
Summary of Data Transfer Rates
0.01
0.0576
0.0144
0.008
0.001
Wired Ethernet
InfiniBand
Wireless Ethernet
Wired Internet
Wireless Internet
Computer Bus
Storage Bus
Peripheral
Memory
Appendix F
Introduction to Object Oriented Programming
Complex Code
Complex (or ugly) Code usually have the following characteristics:
• Similar code is repeated in many places
• Functions have many inputs/outputs
• Function inputs are submitted to too deeply nested functions
• Too much dependency between functions (spaghetti code)
• Changing one function breaks several other functions
• ...
627
Procedural Programming Control Flow
Procedural programming solves a problem using flow charts.
• The algorithm is the central point
628
Object Oriented (OO) Programming (OOP)
OOP thinks first about the data and second about their manipulation.
• OOP abstracts a problem into objects that interact in a network
• An object has:
– properties that store the data
– methods that manipulate the data
• OOP improves the ability to manage complex code
629
The Class
An object is an instance of a certain class.
• Classes can be referred to as “data types”
Class
Properties
Methods
630
425
Pillars of OOP
1. Encapsulation
2. Abstration
3. Inheritance
4. Polymorphism
Encapsulation
Class
Properties
Methods
Encapsulation is the wrapping of properties and methods into a class.
• Benefits:
– Reduce complexity
– Increase reusability
Abstraction
Object
Private Properties
Public Properties
Private Methods
Public Methods
User
Show only the essentials, and hide complexity and details.
• Benefits:
– Reduce complexity
– Upgrade code without breaking existing code
426
Inheritance
∗
A subclass object inherits properties and methods of the superclass.
• The subclass might:
– overload methods of the superclass
– add new properties, methods, . . .
• Benefits:
– Eliminate redundant code
634
Polymorphism
OOP
Procedural Programming
Polymorphism literally means “many forms”.
• Polymorphism refers to the ability to write code that can operate on different data types.
• Benefits:
– Refactor ugly if/elseif and/or switch/case statements
635
Notable OOP Programming Languages
• C++
• Java
• Matlab
• Python
• ...
636
∗
[https://dzone.com/articles/5-free-courses-to-learn-object-oriented-programmin]
427
This page is intentionally left blank!
428
Appendix G
G.1
GNU Toolchain
GNU Compiler Collection (GCC)
The GNU Compiler Collection (GCC) is a compiler system that supports various programming
languages.
• GCC played an important role in the growth of FOSS, as both a tool and an example
• GCC became the standard compiler for most Unix-like OS’s including Android and iOS
• GCC has been ported to a wide variety of HW platforms
• Standard GCC include front ends for:
5. Objective-C++
1. C/C++ (gcc)
2. C++ (g++)
3. Fortran (gfortran)
4. Objective-C
6. Ada (GNAT)
7. Go
GCC Tutorial
• Check www.ntu.edu.sg/home/ehchua/programming/cpp/gcc_make.html
637
G.1.1
GCC Compiler/Linker Options
GCC Compiler Options
A few commonly used GCC compiler options are∗ :
• -v (verbose mode) prints (on standard error output) the commands executed to run the
stages of compilation. Also print the version number of the compiler driver program and
of the pre-processor and the compiler proper.
∗
[https://gcc.gnu.org/onlinedocs/gcc/Option-Summary.html]
onlinedocs/gfortran/Option-Summary.html]
429
and
[https://gcc.gnu.org/
• -c compiles source files, but do not link
• -Idir adds the directory dir to the list of directories to be searched for header files during
pre-processing. Alternative to -Idir , header files paths can be specified in the environment variable “CPATH”.
• -Wall prints "all" Warning messages
• -Dmacro pre-defines macro = 1
• -Dmacro=defn pre-defines macro = defn
• -g generates symbolic debugging information for use with GDB debugger
• -g3 generates extra debugging information
• -O optimizes to reduce executable size and execution time, without performing any optimizations that take a great deal of compilation time
• -O1 same as -O
• -O3 optimize to the utmost, regardless of the compilation time
• -ansi In C mode, this is equivalent to -std=c90 . In C++ mode, it is equivalent to
-std=c++98
• -fpic generates position independent code (PIC) suitable for use in a shared library.
This sets the macros “ pic ” and “ PIC ” to 1
• -fPIC emits position-independent code, suitable for dynamic linking and avoiding any
limit on the size of the global offset table. This sets the macros “ pic ” and “ PIC ” to
2
• -fopenmp enables handling of OpenMP directives #pragma omp in C/C++ and !$omp
in Fortran. The compiler generates parallel code according to the OpenMP Application
Program Interface v4.5 www.openmp.org. This option implies -pthread , and thus is
only supported on targets that have support for -pthread .
• -pthread defines additional macros required for using the POSIX threads library. This
option should be used consistently for both compilation and linking
GCC Linker Options
A few commonly used GCC linker options are∗ :
• -llibrary searches the standard directories and directories that you specify with -L
for the static library file named “liblibrary.a”.
– Alternatively, you can specify the complete path of a static or dynamic library without the option -l
• -Ldir adds directory “dir” to the list of directories to be searched for -l . Alternative to -Ldir , library files paths can be specified in the environment variable “LIBRARY PATH”.
430
• -pie Produce a dynamically linked position independent executable on targets that support it. For predictable results, you must also specify the same set of options used for
compilation ( -fpie , -fPIE , or model suboptions) when you specify this linker option.
• -static On systems that support dynamic linking, this overrides -pie and prevents
linking with the shared libraries. On other systems, this option has no effect.
• -shared produces a shared object. For predictable results, you must also specify the
same set of options used for compilation ( -fpic , -fPIC , or model suboptions)
• -pthread links with the POSIX threads library. This option should be used consistently
for both compilation and linking.
639
GCC Compiler/Linker Options
A few commonly used GCC compiler/linker options are∗ :
• -o filename places the output in “filename” file. This applies to whatever sort of output
is being produced, whether it is executable file, object file, assembler file or preprocessed
C code
640
G.2
GNU Debugger (GDB)
The GNU Debugger∗ (GDB) is the most popular FOSS debugger in use.
• Originally designed for C, it’s been ported to debug many programming languages
• It’s generally used as a command-line executable, but it can be accessed through software
using the little-known MI protocol† .
641
G.3
GNU Toolchain
The GNU toolchain is a broad collection of programming tools. These tools form a toolchain (a
suite of tools used in a serial manner) used for developing software applications and operating
systems.
• The GNU toolchain includes‡ :
∗
www.ibm.com/developerworks/library/os-eclipse-cdt-debug2/index.html
[www.ibm.com/developerworks/library/os-eclipse-cdt-debug2/index.html]
‡
[https://en.wikipedia.org/wiki/GNU_toolchain]
†
431
– GNU Compiler Collection§ (GCC): a suite of compilers for several programming
languages [c.f. sec. G.1]
– GNU Binutils: a suite of tools including linker and other tools
– GNU Debugger (GDB): a code debugging tool [c.f. sec. G.2]
– GNU make: an automation tool for building (compiling and linking) applications
[c.f. appendix I]
– GNU build system (autotools): A build system including Autoconf, Autoheader, Automake and Libtool.
– ...
Touring GNU Binutils∗
file determines file type. For example:
> file hello.c
hello.c: C source, ASCII text, with CRLF line terminators
> file hello.o
hello.o: data
> file hello.exe
hello.exe: PE32 executable (console) x86-64, for MS Windows
nm lists symbol table of object files or libraries. For example:
$ nm hello.o
0000000000000000 b .bss
0000000000000000 d .data
0000000000000000 p .pdata
0000000000000000 r .rdata
0000000000000000 r .rdata$zzz
0000000000000000 t .text
0000000000000000 r .xdata
U __main
0000000000000000 T main
U puts
$ nm hello.exe | grep main
00000001004080cc I __imp___main
0000000100401120 T __main
00000001004010e0 T main
......
• A “T” in the second column indicates a function that is defined, while a “U” indicates
a function which is undefined and should be resolved by the linker
ldd lists shared library dependencies of an executable file. For example:
> ldd hello.exe
ntdll.dll => /cygdrive/c/WINDOWS/SYSTEM32/ntdll.dll (0x7ff9ba3c0000)
KERNEL32.DLL => /cygdrive/c/WINDOWS/System32/KERNEL32.DLL (0x7ff9b9880000)
KERNELBASE.dll => /cygdrive/c/WINDOWS/System32/KERNELBASE.dll (0x7ff9b6a60000)
SYSFER.DLL => /cygdrive/c/WINDOWS/System32/SYSFER.DLL (0x6ec90000)
ADVAPI32.dll => /cygdrive/c/WINDOWS/System32/ADVAPI32.dll (0x7ff9b79a0000)
msvcrt.dll => /cygdrive/c/WINDOWS/System32/msvcrt.dll (0x7ff9b9100000)
sechost.dll => /cygdrive/c/WINDOWS/System32/sechost.dll (0x7ff9b9000000)
RPCRT4.dll => /cygdrive/c/WINDOWS/System32/RPCRT4.dll (0x7ff9b9700000)
cygwin1.dll => /usr/bin/cygwin1.dll (0x180040000)
§
∗
It includes linkers and other utilities as well.
[www.ntu.edu.sg/home/ehchua/programming/cpp/gcc_make.html]
432
• Additional information are available @ https://sourceware.org/binutils/docs/
binutils/index.html
643
G.4
GNU Toolchain for Windows
MinGW and MinGW-w64
MinGW (Minimalist GNU for Windows) is the GNU toolchain ported for MS Windows.
• MinGW is a FOSS
• MinGW development has halted in 2013
MinGW-w64 is a better alternative that added several new APIs and both 32-bit and 64-bit
support.
• MinGW-w64 was ported to Unix/Linux to enable Unix/Linux to build SW that will
run on Windows
644
MinGW-w64 Installation
• Run the installation executable with the following choices:
– the version you desire∗
– posix
– x86 64†
– seh
• Install into a path with no spaces‡ , e.g.: “C:\mingw-w64\x86 64-6.3.0-posix-seh-rt v5rev1”
• Add the path of the “bin” directory, e.g. “C:\mingw-w64\x86 64-5.3.0-posix-seh-rt v4rev1\mingw64\bin”, to the “Path” environment variable
• Copy “mingw32-make.exe” and rename it to “make.exe”§
• To let Matlab detect MinGW-w64, define an environment variable called
“MW MINGW64 LOC”¶ that contains the path of the installed MinGW-w64, e.g.
“C:\mingw-w64\x86 64-6.3.0-posix-seh-rt v5-rev1\mingw64”
645
∗
If you intend to create Matlab MEX-files, select the version supported by your existing Matlab version. Refer
to www.mathworks.com/support/compilers.html and http://khailaie.com/notes/MEX/MEX-MinGWsetup-Windows.html.
†
assuming you are installing on a standard PC
‡
[www.mathworks.com/help/matlab/matlab_external/install-mingw-support-package.html]
§
This is only needed for the less maintained Photran extension for Eclipse
¶
[www.mathworks.com/matlabcentral/answers/313298-i-already-have-mingw-on-mycomputer-how-do-i-configure-it-to-work-with-matlab]
433
This page is intentionally left blank!
434
Appendix H
Doxygen
Doxygen∗ is a cross-platform tool for generating documentation from annotated source code.
• Doxygen supports:
– C++
– C#
– Python
– VHDL
– C
– PHP
– IDL†
– Tcl
– Objective-C
– Java
– Fortran
– D‡
• Doxygen can help in three ways:
1. It can extract documentation directly from source codes.
– This documentation can be published in HTML, LATEX§ , RTF, compressed
HTML and Unix man pages.
2. It can extract the code structure from undocumented source code.
– It can also visualize the relations between the various elements by generating
include dependency graphs, inheritance diagrams, and collaboration diagrams
3. It can create normal documentation¶
646
Compiling on Linux
• Make sure the following SW are installed‖
– coreutils
– bison
– cmake∗∗
– texlive
–
ghostscript
– flex
– make
– Qt††
– graphviz
– xdot
• Download doxygen source code, unpack it and execute the following shell script
Code H.1: Shell script to install doxygen and doxywizard.
cd doxygen-$VERSION
mkdir build
cd build
cmake -G "Unix Makefiles" ..
cmake -Dbuild_wizard=YES ..
make
cmake -Dbuild_doc=YES ..
make docs
sudo make install
∗
[www.stack.nl/~dimitri/doxygen/]
Corba, Microsoft, and UNO/OpenOffice flavors
‡
to some extent
§
To convert LATEX to hyperlinked PDF, execute make pdf from within the generated “latex” directory [www.
stack.nl/~dimitri/doxygen/manual/output.html].
¶
as was done for the doxygen user manual and website
‖
[www.stack.nl/~dimitri/doxygen/manual/install.html]
∗∗
>2.8.12
††
>v4.3
†
435
– “doxygen” and “doxywizard” should compile without problems and the binaries
should be available in the bin directory, and the HTML documentation should be
available in the html directory.
• You may then create a shortcut to “doxywizard” in the start menu or programs helper of
your Linux distribution.
Getting Started Doxygen
• www.stack.nl/~Edimitri/doxygen/manual/starting.html
• www.stack.nl/~Edimitri/doxygen/manual/starting.html#step2
Documenting a Source Code for use with Doxygen
• www.stack.nl/~Edimitri/doxygen/manual/docblocks.html
• https://github.com/theolind/mahm3lib/wiki/Coding-Convention
436
Appendix I
Make
Make is a CLI build automation tool that can be used to compile any language that has a
command-line compiler
• Make was originally developed for Unix at 1976
• Make becomes widely used in Unix-like OS’s. Current Make implementations include:
– MS nmake
– BSD Make
– GNU Make
• Building a project using Make is much more maintainable, configurable and compact than
building using an IDE, or shell script
• Make not only can build a project, but also it can prepare its manual pages and install its
binaries into their target directories
650
GNU Make∗
GNU Make (known as gmake) is the standard implementation of Make for Linux and Mac OS
X.
• GNU Make provides several extensions over the original Make
• Among notable projects that rely on GNU Make are:
– Linux kernel
– LibreOffice
– GCC
– Mozilla Firefox
– Apache OpenOffice
– ...
651
Makefile
Makefile is a text file that includes rules/instructions to build a project from source code.
• By executing $ make in the CLI shell, Make looks for the makefile in the CWD
– GNU Make looks for “GNUmakefile” at first, then “makefile” and “Makefile”
• makefiles are usually placed in the same directory as the source files of the project
• $ make -f <filename> tells Make to use “filename” as its makefile
• A comment in a makefile starts with “ # ”
• Long line can be broken and continued in several lines via “ \ ”
652
∗
[https://en.wikipedia.org/wiki/Make_(software)]
437
Variables (or Macros)
Within a makefile, a variable can be defined as variable1=value .
• The value of variable1 can be then accessed by writing either $(variable1) or
${variable1} † , unless the variable name consists of a single character‡
• Check Code I.7 for variable examples
• Additional information are available @ www.gnu.org/software/make/manual/html_
node/Using-Variables.html
Sample Project
• Refer to section G.1.1 for brief explanations about GCC compile and link options
Code I.1: file1.c
Code I.3: file3.c
#include <stdlib.h>
#include <stdio.h>
#include "header1.h"
#include "header2.h"
#include "header3.h"
extern void function_two();
extern void function_three();
void function_three()
{}
int main()
{
function_two();
function_three();
printf("Hello, world!\n");
exit (EXIT_SUCCESS);
}
Code I.5: header2.h
Code I.2: file2.c
/* empty feader file */
#include "header1.h"
#include "header2.h"
Code I.6: header3.h
void function_two()
{}
/* empty feader file */
Code I.4: header1.h
/* empty feader file */
Code I.7: A modest Makefile
1
2
3
4
5
6
7
8
9
# This Makefile is poor!
# It is for demonstration purposes only!
# Define some macros
CC =gcc
INSTDIR =./bin
INCLUDE =.
CFLAGS =-O -Wall -ansi
†
‡
Some versions of Make may also accept $variable1 .
Check built in variables for examples.
438
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
.PHONY: all
all: myapp
# Typical target, dependencies and rules
file1.o: file1.c header1.h
$(CC) -I$(INCLUDE) $(CFLAGS) -c file1.c
file2.o: file2.c header1.h header2.h
$(CC) -I$(INCLUDE) $(CFLAGS) -c file2.c
file3.o: file3.c header2.h header3.h
$(CC) -I$(INCLUDE) $(CFLAGS) -c file3.c
myapp: file1.o file2.o file3.o
$(CC) -o myapp file1.o file2.o file3.o
# "-" tells make to ignore any errors
# "@" tells make not to print the command to standard output before executing it
.PHONY: clean
clean:
-rm *.o myapp
@echo Clean done
# "\" is used to connect several lines into one logical line
# "|" denotes order only prerequisites
.PHONY: install
install: myapp | $(INSTDIR)
cp myapp $(INSTDIR) \
&& chmod a+x $(INSTDIR)/myapp \
&& chmod og-w $(INSTDIR)/myapp \
&& echo "Installed in $(INSTDIR)";
$(INSTDIR):
-mkdir -p $@
654
Targets
A target is a file to be created.
• Several targets may exist is a makefile
– Code I.7 for example has the targets: myapp, file1.o, file2.o and file3.o
• To build the first target in the makefile, execute $ make
• To build the “myapp” target for example, execute $ make myapp
• Make builds/rebuils a target only if any of its prerequisites has changed
655
Built-in Target Names∗
Certain names have special meanings if they appear as targets. Among them are:
• .PHONY
∗
[www.gnu.org/software/make/manual/make.html#Special-Targets]
439
– A prerequisites to the .PHONY target is denoted phony target
– The recipe of a phony target is always run; regardless of the target existence or prerequisites modification time
– Therefore, a target, that is not intended to create a file, should be specified as a prerequisite to the .Phony target
– Common phony targets are [c.f. Code I.7]:
all can be used to build several targets
∗ Write all the desired targets as prerequisites
clean
install its rules should be shell commands that move the generated binaries to
their intended paths and modify the environment variables, . . .
• .SECONDEXPANSION
– Prerequisites of the “.SECONDEXPANSION” target will be expanded a second time
after all makefiles have been read in. Refer to Secondary Expansion [sec. I.2]
• .DEFAULT
– The recipe specified for .DEFAULT is used for any target for which no rules are found
(either explicit rules or implicit rules).
• .SECONDARY
– Prerequisites of the “.SECONDARY” target are treated as intermediate files, except
that they are never automatically deleted
– .SECONDARY with no prerequisites causes all targets to be treated as secondary
(i.e., no target is removed because it is considered intermediate)
Prerequisites (or Dependencies)
Prerequisites (or dependencies) are a space or tab separated list of files upon which the target
depends.
• Prerequisites are written after the target, preceded with a colon. For example, in Code I.7;
– myapp depends on file1.o, file2.o and file3.o
– file1.o depends on file1.c and header1.h
– file2.o depends on file2.c, header1.h and header2.h
– file3.o depends on file3.c, header2.h and header3.h
440
Rules (or Recipes)
A rule (or recipe) specifies the shell commands∗ needed to build the target.
• Rules come after prerequisites, preceded with a tab† [c.f. Code I.7]
– a space at the end of a line in the makefile may cause failure
• Make invokes a new shell for each rule
– Therefore, you must connect rules using “ \ ” so that all the rules are on one logical
line and are all passed together to a single shell invocation
• There are some useful special characters preceding a shell command:
– “ - ” tells Make to ignore any errors
∗ In Code I.7 for example, preceding “rm” with “ - ” ignores errors, perhaps because the are no files to delete
– “ @ ” tells Make not to print the command to standard output before executing it
∗ In Code I.7 for example, preceding “echo” with “ @ ” does not print this command to the standard output
• Check COMMAND LINE TIPS & TRICKS in sec. B.2 for the meaning of “ && ”, “ || ”
• As you’ll see later, Make has many built-in rules
658
Pattern Rules∗
Pattern rules specify targets using % as the filename.
• For example, Code I.8 defines a rule to create a .o file from a .cpp file with the same
name
Code I.8: Sample Pattern Rule
%.o: %.cpp
$(CC) -I$(INCLUDE) $(CFLAGS) -c $<
659
Suffix Rules†
Suffix rules are the old-fashioned way of defining implicit rules.
• Suffix rules are obsolete because pattern rules are more general and clearer
• Suffix rules are still just for compatibility with old makefiles
• For example, Code I.9 defines a rule to create a .o file from a .cpp file with the same
name
∗
C.f. B.2
Otherwise, you get the error “makefile:4: *** missing separator. Stop.”. Space(s) won’t do.
∗
[www.gnu.org/software/make/manual/html_node/Pattern-Rules.html]
†
[www.gnu.org/software/make/manual/html_node/Suffix-Rules.html]
†
441
Code I.9: Sample Suffix Rule
.cpp.o:
$(CC) -xc++ $(CFLAGS) -I$(INCLUDE) -c $<
• The “.cpp.o” suffix should be added as a prerequisite to the “.SUFFIXES” special target
Automatic Variables∗
Automatic variables are set by Make after a rule is matched. They include:
• $@ : the target filename
• $* : the target filename without any suffix†
• $< : the first prerequisite filename
• $^ : filenames of all the prerequisites, separated by spaces, without duplicates
• $+ : similar to $^ , but includes duplicates
• $? : the names of all prerequisites that are newer than the target, separated by spaces
Built-in Rules and Variables
Make comes with a huge set of built-in rules and variables. To display the complete set, execute:
$ make -p | less
Make Command Line Options‡
The Make command has several command line options. Most commonly used are:
• -f <filename> tells Make to use “filename” as its makefile
• -k tells Make to keep going although errors are found
– This can be used to find out, in one go, all source files with problems
• -n tells Make to print out what it will do, without actually doing it
– For example, $ make -n &> filename.txt redirects the “stdout” and “stderr”
outputs to “filename.txt”
• -p tells Make to display the complete set of built in rules and variables
– You
may
use
this
$ make -p &> filename.txt
option
as
$ make -p | less
• -d prints debugging information in addition to normal processing
– You may use this option as $ make -d &> filename.txt
∗
[www.gnu.org/software/make/manual/html_node/Automatic-Variables.html]
file extension
‡
[www.gnu.org/software/make/manual/html_node/Options-Summary.html]
†
442
or
Good Learning Materials
• Learn makefile-unix makefile, www.tutorialspoint.com
• GNU Make Manual, www.gnu.org/software/make/manual
• Robert Mecklenburg, Managing Projects with Make, O’Reilly, 3rd ed., 2004 [18]
664
I.1
Text Functions
Pattern Substitutions∗
$(patsubst pattern,replacement,text) finds space-separated-words in “text” that
match “pattern” and replaces them with “replacement”.
• “pattern” and “replacement” may contain the “ % ” wildcard [c.f. Pattern Rules]
• For example, $(patsubst %.c,%.o,file1.c file2.c file3.c) replaces the suffix
“ .c ” with “ .o ” in the given space-separated filenames
665
Substitution References†
Substitution references are a simpler way to get the effect of “ patsubst ”.
• For example, if we defined the variable SourceFiles = file1.c file2.c file3.c
then ObjectFiles = $(SourceFiles:.c=.o) is equivalent to
ObjectFiles = $(patsubst %.c,%.o,$(SourceFiles))
666
More Information
• Refer to www.gnu.org/software/make/manual/html_node/Functions.html
667
I.2
Additional Topics
The Two Flavors of Variables‡
• Recursively expanded variables are defined using “=”
– If the variable contains references to other variables, these references are expanded
at the substitution time
– A major disadvantage is that you cannot append something to a variable, as in
CFLAGS = $(CFLAGS)-O because this will cause an infinite loop
• Simply expanded variables are defined using “:=” or “::=”§
– If the variable contains references to other variables, these references are expanded
once, when the variable is defined
– Example
∗
[www.gnu.org/software/make/manual/html_node/Text-Functions.html]
[www.gnu.org/software/make/manual/html_node/Text-Functions.html]
‡
[www.gnu.org/software/make/manual/make.html#Flavors]
§
Both forms are equivalent in GNU Make; however only the “::=” form was described by POSIX in 2012. So
old versions of Make won’t accept “::=”.
†
443
is equivalent to
x := foo
y := $(x) bar
x := later
y := foo bar
x := later
• Refer to Code 5.4 on page 289 for an example
Order-only Prerequisites∗
There are two different types of prerequisites; normal and order-only prerequisites.
• A normal prerequisite assures:
1. building order. That is, all prerequisites of a target must have been built before building this target
2. rebuilding the target if any of its prerequisites became newer than the current build
of the target
• An order-only prerequisite assures only the first point above.
– That is, it just assures that all the prerequisites of the target were already built and
doesn’t rebuild the target if any of its prerequisites has been updated
• Order-only prerequisites can be specified after a pipe symbol “ | ” in the prerequisites list
• As an example, if the files to be built are to be placed in a separate directory. The problem
is that the timestamp on a directory does change whenever a file is added, removed, or
renamed. In this case, we want to assure that:
– the directory was already created before building any file
– the directory (and accordingly its files) does not become out-of-date after building
placing a new file in the directory
• One way to manage this is by making this directory an order-only prerequisite to all the
files to be built
• Refer to Code I.7 for a sample order-only prerequisite
Secondary Expansion†
GNU Make also has the ability to enable a second expansion of the prerequisites.
• In order for this second expansion to occur, the special target .SECONDEXPANSION
must be defined before the first prerequisite list that makes use of this feature
∗
†
[www.gnu.org/software/make/manual/html_node/Prerequisite-Types.html]
[www.gnu.org/software/make/manual/make.html#Secondary-Expansion]
444
(Draft) Automatic Generation of Prerequisites
Adding “-MM” option to gcc simply scans the source files looking for includes and outputs the
required prerequisite lines in a format ready for insertion into a makefile. For example:
$ gcc -MM file1.c file2.c file3.c
file1.o: file1.c header1.h
file2.o: file2.c header1.h header2.h
file3.o: file3.c header2.h header3.h
$
671
Target-specific Variable Values∗
Variable values are usually global. Exceptions are:
1. automatic variables
2. target-specific variables
• Target-specific variable allows you to alter the value of a variable, based on the current
target
• A target-specific variable affects the prerequisites of the target and all their prerequisites,
recursively† . For example in Code I.10,
– debug: CFLAGS += -g3 modifies the “CFLAGS” variable within the scope of the
“debug” target, and its prerequisite “$(OutRootDir)/$(DebugDir)/$(EXEC main)”;
and
“$(OutRootDir)/$(DebugDir)/$(EXEC main)”
prerequisites
“$(OBJ C Debug)”, and so on recursively
– Note that a given prerequisite will only be built once per invocation of Make, at most
∗ If the a file is a prerequisite of multiple targets, and each of those targets has
a different value for the same target-specific variable, then the first target to be
built will cause this prerequisite file to be built using the first target’s specific
variable value
• Target-specific variables are only available within the context of the recipes of the target‡
and its recursive prerequisites
– That is, Target-specific variables cannot be used as targets nor prerequisites
Code I.10: Debug and Release Makefile
1
2
3
4
5
6
7
8
# This is a better Makefile!
# It is for demonstration purposes only!
ifeq ($(OS),Windows_NT)
ObjExt=obj
mkdir_CMD=mkdir
rm_CMD=rmdir /S /Q
else
∗
[www.gnu.org/software/make/manual/html_node/Target_002dspecific.html]
unless those prerequisites override that variable with their own target-specific variable value
‡
Same as automatic variables
†
445
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
ObjExt=o
mkdir_CMD=mkdir -p
rm_CMD=rm -rf
endif
CC =gcc
CFLAGS =-Wall -ansi
LD =gcc
OutRootDir=.
DebugDir =Debug
ReleaseDir=Release
INSTDIR =./bin
INCLUDE =.
SrcFiles=$(wildcard *.c)
EXEC_main=myapp
OBJ_C_Debug =$(patsubst %.c, $(OutRootDir)/$(DebugDir)/%.$(ObjExt),$(SrcFiles))
OBJ_C_Release =$(patsubst %.c, $(OutRootDir)/$(ReleaseDir)/%.$(ObjExt),$(SrcFiles))
.PHONY: Release Debug cleanDebug cleanRelease clean
# Target specific variables
release: CFLAGS += -O -DNDEBUG
debug: CFLAGS += -g
################################################
#Callable Targets
release: $(OutRootDir)/$(ReleaseDir)/$(EXEC_main)
debug: $(OutRootDir)/$(DebugDir)/$(EXEC_main)
cleanDebug:
-$(rm_CMD) "$(OutRootDir)/$(DebugDir)"
@echo cleanDebug done
cleanRelease:
-$(rm_CMD) "$(OutRootDir)/$(ReleaseDir)"
@echo cleanRelease done
clean: cleanDebug cleanRelease
################################################
# Pattern Rules
# Multiple targets cannot be used with pattern rules [https://www.gnu.org/software/
make/manual/html_node/Multiple-Targets.html]
56 $(OutRootDir)/$(ReleaseDir)/%.$(ObjExt): %.c | $(OutRootDir)/$(ReleaseDir)
57
$(CC) -I$(INCLUDE) $(CFLAGS) -c $< -o"$@"
58
59 $(OutRootDir)/$(DebugDir)/%.$(ObjExt): %.c | $(OutRootDir)/$(DebugDir)
60
$(CC) -I$(INCLUDE) $(CFLAGS) -c $< -o"$@"
61
62 # Create output directory
63 $(OutRootDir)/$(ReleaseDir) $(OutRootDir)/$(DebugDir) $(INSTDIR):
64
-$(mkdir_CMD) $@
65
446
66 # Create the executable
67 # Multiple targets [https://www.gnu.org/software/make/manual/html_node/MultipleTargets.html]
68 $(OutRootDir)/$(ReleaseDir)/$(EXEC_main): $(OBJ_C_Release)
69 $(OutRootDir)/$(DebugDir)/$(EXEC_main): $(OBJ_C_Debug)
70 $(OutRootDir)/$(ReleaseDir)/$(EXEC_main) $(OutRootDir)/$(DebugDir)/$(EXEC_main):
71
$(LD) $^ -o$@
72
73 # "\" is used to connect several lines into one logical line
74 # "|" denotes order only prerequisites
75 .PHONY: install
76 install: release | $(INSTDIR)
77
cp $(OutRootDir)/$(ReleaseDir)/$(EXEC_main) $(INSTDIR) \
78
&& chmod a+x $(INSTDIR)/$(EXEC_main) \
79
&& chmod og-w $(INSTDIR)/$(EXEC_main) \
80
&& echo "Installed in $(INSTDIR)";
672
(Draft) Static Libraries
In the Makefile of Code I.11, the syntax mylib.a(file2.o) means to store the object file
file2.o inside the static library mylib.a.
Code I.11: Pictorial part of a makefile
CC = gcc
myapp: file1.o mylib.a
$(CC) -o myapp file1.o mylib.a
mylib.a: mylib.a(file2.o) mylib.a(file3.o)
file1.o: file1.c header1.h
file2.o: file2.c header1.h header2.h
file3.o: file3.c header2.h header3.h
clean:
-rm *.o *.a
(Draft) Nested Makefiles
???
674
Virtual Path - VPATH & vpath∗
• VPATH (uppercase) can be used to specify the directory to search for prerequisites and
target files. For example:
# Search for prerequisites and targets from "src" and "include"
directories
# The directories are separated by space
VPATH = src include
• vpath (lowercase) is more precise about the file type and its search directory. For example:
∗
673
[www.ntu.edu.sg/home/ehchua/programming/cpp/gcc_make.html]
447
# Search for .c files in "src" directory; .h files in "include"
directory
# The pattern matching character ’%’ matches filename without the
extension
vpath %.c src
vpath %.h include
Functions for File Names
• Refer
to
www.gnu.org/software/make/manual/html_node/File-NameFunctions.html
448
Appendix J
Ninja (Draft)
Ninja is a small build system with a focus on speed. [https://ninja-build.org/]
• Ninja is designed to have its input files generated by a higher-level build system∗ , such as
CMake
• Ninja is designed to run builds as fast as possible
• Ninja performs building faster than GNU make
• Ninja is the default CMake code generators
• Ninja is used to build Google Chrome, parts of Android, LLVM, . . .
677
Why yet another build system?†
Where other build systems are high-level languages Ninja aims to be an assembler.
Ninja build files are human-readable but not especially convenient to write by hand. (See
the generated build file used to build Ninja itself.) These constrained build files allow Ninja to
evaluate incremental builds quickly.
678
Should you use Ninja?‡
Ninja’s low-level approach makes it perfect for embedding into more featureful build systems; see a list of existing tools. Ninja is used to build Google Chrome, parts of Android,
LLVM, and can be used in many other projects due to CMake’s Ninja backend.
See the manual for more: philosophical background, whether and how you can use Ninja for
your project, platform support, and details about the language semantics.
679
∗
[https://github.com/ninja-build/ninja/wiki/List-of-generators-producing-ninjabuild-files]
†
[https://ninja-build.org/]
‡
[https://ninja-build.org/]
449
This page is intentionally left blank!
450
Appendix K
CMake (Draft)
CMake
CMake is a cross-platform FOSS generator of multi-platform build systems.
• CMake can generate∗ :
– IDE projects for Eclipse-CDT† , Visual-Studio‡ , Xcode§ , KDEvelop and CodeBlocks
– build files for MSBuild‡ , NMake‡ , make¶ and Ninja†
• That is, CMake can make a project build-system-independent
• CMake has seen a tremendous uptick in the C++ community in recent years across all
platforms‖∗∗
• CMake provides dependency detection, library interface management, or integration with
CTest, CDash and CPack
680
CMakeLists.txt
Build behavior is defined in CMakeLists.txt files - one in every directory of the source code.
• Each directory’s CMakeLists file defines what the build system should do in that specific
directory
681
Tutorial
• https://cmake.org/cmake/help/latest/manual/cmake-buildsystem.7.htm
• https://cmake.org/cmake/help/latest/guide/tutorial/index.html
• http://derekmolloy.ie/hello-world-introductions-to-cmake/
• https://mirkokiefer.com/cmake-by-example-f95eb47d45b1
682
Build Types
By default, CMake is able to handle the following build types:
• Debug: Usually a classic debug build including debugging information, no optimization
etc.
• Release: Your typical release build with no debugging information and full optimization.
• RelWithDebInfo: Same as Release, but with debugging information.
• MinSizeRel: A special Release build optimized for size.
683
∗
[https://cmake.org/cmake/help/v3.0/manual/cmake-generators.7.html]
†
cross-platform
‡
on Windows OS
§
on Mac OS
¶
on Unix-like platforms such as Linux, macOS
‖
[https://blogs.msdn.microsoft.com/vcblog/2016/10/05/cmake-support-in-visualstudio/]
∗∗
In MS developer surveys, it have been seen that CMake constantly grow in usage year over year since 2012,
surpassing in 2015 the make family (make/gmake/nmake) in terms of adoption
451
This page is intentionally left blank!
452
Appendix L
Visual Studio
Visual Studio (VS)is proprietary IDE developed by Microsoft for the Windows OS.
• VS supports many programming languages including:
– C/C++
– C#
– Visual Basic
– JavaScript/TypeScript
– Python
– R
– Node.js
• At a time, VS can open only one solution. The solution can include several projects
• As of VS 2017, VS supports many FOSS technologies such as:
– R language
– Git
– CMake∗
– Python language
– building projects for Linux†‡
684
∗
[https://blogs.msdn.microsoft.com/vcblog/2016/10/05/cmake-support-in-visualstudio/]
†
[https://blogs.msdn.microsoft.com/vcblog/2017/04/11/linux-development-with-c-invisual-studio/]
‡
[https://blogs.msdn.microsoft.com/vcblog/2017/08/25/visual-c-for-linux-developmentwith-cmake/]
453
Microsoft Build Engine (MSBuild)§
The Microsoft Build Engine (MSBuild) is a FOSS building system. It is a core component of
Visual Studio.
• MSBuild can build SW projects without needing Visual Studio
MS Visual C++
MS Visual C++ is a core component of Visual Studio. It provides:
• MSVC compiler
• debugger
• linker
• ...
For advanced High Performance Computing (HPC), you may replace the Visual C++ compiler
with Intel compilers∗ such as:
• Intel Fortran compiler
• Intel C++ compiler
Changing Project Type
• Project > Properties > General >
Most important configurations are:
– Target Extension
– Configuration Type
§
∗
[https://github.com/Microsoft/msbuild]
purchased separately
454
Configuring Compiler Options
Project > Properties > C/C++ (or Fortran) >
Most important configurations are:
• Configuration: “Debug” or “Release” or “All Configurations”
• Platform: “Win32” or “x64” or “All Platforms”
• General > Additional Include Directories: Specify paths of non-standard header files you
use
• Preprocessor > Preprocessor Definitions: Specify any preprocessor definitions, e.g.:
“ x86 64 ”
• Code Generation > Runtime Library: Choose static or dynamic linking
• Command Line: Review compiler options and add any options you wish
688
Configuring Linker Options
Project > Properties > Linker >
Most important configurations are:
• Configuration: “Debug” or “Release” or “All Configurations”
• Platform: “Win32” or “x64” or “All Platforms”
• General > Additional Library Directories
455
• Input >
– Additional Dependencies
– Module Definition File
• Command Line
Configuring Debugging Options
Project > Properties >
• Configuration: “Debug”
• Debugging
Getting Started with Visual Studio for C and C++ Development
• https://blogs.msdn.microsoft.com/vcblog/2017/04/21/getting-startedwith-visual-studio-for-c-and-cpp-development/
456
Appendix M
Eclipse
Eclipse is a FOSS∗ IDE.
• Eclipse is developed by a consortium of large SW companies†
• Eclipse is cross-platform
• Eclipse supports almost all programming languages
• Eclipse supports a variety of toolchains‡
• Eclipse provides visual debugger interface
• Eclipse has numerous plugins that do almost anything you need
• Eclipse has a big user community
– when you encounter a problem, google it. Most likely you will find others had encountered it and found a solution
692
Advantages and Disadvantages
• Advantages
∗
This means you should expect the usual drawbacks of FOSS. That is, less polished operation and documentation, . . .
†
IBM, Novel, Oracle, . . .
‡
A toolchain is the set of tools that facilitates building a project. On MS Windows, example toolchains are (1)
MS Visual C++ Compiler and (2) MinGW-w64.
457
– FOSS
– Support almost all languages
– No installation
– Not bloated
– Numerous plug-ins for making anything
– Cross-platform
– Big user community
• Disadvantages
– Not well documented/maintained/polished/debugged
M.1
– Separate installation of toolchains
Installing Eclipse
1. Install Java Development Kit (JDK)
2. Download the Eclipse package of your choice∗
• “Eclipse for Parallel Application Developers” includes Tools for C, C++, Fortran,
and UPC, including MPI, OpenMP, OpenACC, a parallel debugger, and remotely
building, running and monitoring applications . . .
3. Unzip the downloaded package to folder with write permission (Not C:\Program files)
4. Create shortcut to Eclipse executable
Integrating a Toolchain with Eclipse†
• Linux
– Just install the GNU toolchain‡ , and Eclipse will detect it
• MS Windows
– MinGW Toolchain [sec. G.4]
∗ Install MSYS2§
– MS Visual C++ Compiler
∗ Install Microsoft C++ Build Tools¶
∗
[www.eclipse.org/downloads/compare.php]
http://help.eclipse.org/oxygen/topic/org.eclipse.cdt.doc.user/concepts/cdt_c_
before_you_begin.htm
‡
Usually it is installed by default.
§
MSYS (Minimal System) is a Windows port of a lightweight Unix-like shell. MSYS2 is a modern rewrite of
MSYS. MSYS2 is needed only to provide the “rm” Linux shell command which Eclipse executes for cleaning a
project. In fact I consider this a bug in Eclipse because there is the “del” command on Windows. After installing
MSYS2, add the path of the “bin” directory, e.g. “C:\msys64\usr\bin”, to the “Path” environment variable
¶
Freely available @ https://visualstudio.microsoft.com/visual-cpp-build-tools/
†
458
∗ The CDT Visual C++ build integration will find these files
∗ No other setup is required.
∗ Note: For this release, the integration should be considered beta quality. It is
not recommended for production use.
• Mac OS X
– Refer to http://help.eclipse.org/oxygen/topic/org.eclipse.cdt.doc.
user/concepts/cdt_c_before_you_begin.htm
695
Eclipse Marketplace
• Help > Eclipse Marketplace
– Eclox: simple doxygen frontend plug-in for Eclipse
696
459
M.2
Getting Started
Customization
• Window > Preferences > General >
– Keys
– Appearance > Colors and Fonts > Basic >
∗ Text Font∗
∗ Text Editor Block Selection Font
– Some useful tips and tricks are available @ www.ntu.edu.sg/home/ehchua/
programming/howto/EclipseJava_HowTo.html
– C/C++ > Editor
∗ Documentation tool comments > Workspace Default > Doxygen†
∗
†
If you want to change the font, be advised to choose fixed-width-font
Of course you must have already installed Doxygen and Eclox.
460
697
Perspective
Perspective is a layout of views (development tools) in the Workbench window. Each type of
perspective is a combination of views, menus, and toolbars that enable you to perform a particular
task. For example:
• C/C++ perspective has views that are organized to help you develop C/C++ programs
• Fortran perspective has views that are organized to help you develop C/C++ programs
• Debug perspective has views that enable you to debug those programs.
• ...
• To open a perspective, select Window > Open Perspective
698
Workspace
• Eclipse IDE uses the workspace directory to store its preferences and development artifacts
• At a time, Eclipse can open only one workspace. The workspace can include several
projects.
699
461
The C/C++ Development Tools (CDT)
CDT is a set of plug-ins that provide C and C++ extensions to the Eclipse workbench.
• A concise tutorial is available @ www.ntu.edu.sg/home/ehchua/programming/
howto/EclipseCpp_HowTo.html
700
The Fortran Development Tools (Photran)
Photran is a set of plug-ins that provide Fortran extensions to the Eclipse workbench.
• Photran is less maintained/polished than CDT. That is:
– Project types are buggy as compared to CDT
– Project toolchains are not well detected as compared to CDT
– Project properties are buggy as compared to CDT
– Documentation is not up-to-date/precise as that of CDT
• As of Photran 9.1∗† , it supports Fortran 77-2008. It includes 39 refactorings (including
Rename, Extract Procedure, and loop transformations).:
Learning Eclipse
• At a minimum, you should browse the official documentation from “Help” menu. This
will save you many agonizing hours trying to figure out how to do some things later.
– Help > Help Contents >
∗ Workbench User Guide
∗ C/C++ Development User Guide
∗ Fortran Development User Guide‡
Using Doxygen within Eclipse
• https://github.com/theolind/mahm3lib/wiki/Integrating-Doxygen-withEclipse
∗
www.eclipse.org/photran/
released with Eclipse 4.5 (Mars) on June 24, 2015
‡
Unfortunately, Photran is less maintained/polished than CDT. Therefore Fortran documentation may be not as
up-to-date/precise as that of CDT.
†
462
M.3
Project Types
Eclipse supports two types of projects:
1. Managed Projects
• Set compile/link settings in a GUI similar to MS Visual Studio∗
• Eclipse creates a Makefile automatically
2. Makefile-based Projects
• Using an existing Makefile
704
New vs Existing Projects
• To create a new project,
– File > New > Project > Select the desired programming language
∗ Select desired project type
∗
Of course the paid Visual Studio is more feature rich and polished than the free Eclipse.
463
• To import existing project or code,
– File > Import > General > Projects from Folder or Archive
464
M.3.1
Managed Projects
Creating a Managed Project
• File > New > Project > Select the desired programming language
– Select desired project type
706
Changing Toolchain
• Project > Properties > C/C++ (or Fortran) Build > Tool Chain Editor >
– Current toolchain
– Current builder
707
465
Configuring Compiler and Linker Options
Most important configurations are:
• Configuration: “Debug” or “Release” or “All Configurations”
• Project > Properties > C/C++ (or Fortran) Build >
– Tool Settings >
– Build Artifact >
466
M.3.2
Makefile-based Projects
Creating a Project from Existing Makefile Code
• File > Import > C/C++ > Existing Code as Makefile Project
– Project name > write your favorite project name
– Existing Code Location > Browse to the directory of the source code project
– Languages > Choose the project languages
– For Fortran projects, make sure to choose “GCC Fortran”
• If the source code is in Fortran, right click the project in the Project Explorer and execute
“Convert to Fortran Project”
467
• Project > Properties > C/C++ Build (or Fortran) >
– Builder Settings >
∗ Build Location > Build Directory > Input path to the main Makefile
– Behavior
468
∗ Build on resource save (Auto Build): input the build target to invoke when
resources (source code files) changes
∗ Build (Incremental Build): input the build target for default make build target
– Logging
∗ Modify the path of the logfile as desired. It is customary to set it in the same
place as compiled files
• Double click the existing Makefile to open it
– In the “Outline” view, right-click desired build targets > Add build Target
– If the “Build Targets” view is not visible, execute Windows > Show Views > Build
Targets
709
Additional Configurations∗
Up to now, Eclipse can only execute the existing makefile to build the project.
• That is, Eclipse do not read anything from the makefile, and hence does not know any
thing about the source code.
∗
[http://help.eclipse.org/photon/nav/13_4_7_1_2_0]
469
• Therefore, in order to use the capabilities of Eclipse, you have to tell Eclipse about everything already defined in the makefile as follows:
• Project > Properties > C/C++ (or Fortran) General > Paths and Symbols >
– Includes: add paths for include directories you have already defined in the Makefile
– Symbols: define the macros you have already defined in the Makefile
– Libraries: define the libraries you have already defined in the Makefile
– Source Location: define locations of the source code
– Output Location: define locations of the generated binaries
– Project > C/C++ Index > Rebuild
M.4
Debugging
Running the Built Executable∗
• Run>Run Configurations... > C/C++ Application > New launch configuration
∗
http://fastlabtutorials.blogspot.com.eg/2015/01/using-eclipse-to-debug-cc-andfortran.html
470
– Select “Enable auto build”
– If the executable needs input arguments, you can specify them in the “(x) Arguments”
tab
– To run the code, click the Run button
711
Configuring Debugging Options
Project > Properties >
• Configuration: “Debug”
• Debugging
712
Graphical Debugging with CDT∗
The CDT’s extensibility allows you to connect its graphical debugging capabilities to your custom debugger.
• Debugging Fortran applications is similar
713
Debugging the Built Executable†
To debug the executable, click the debug button.
• Eclipse then switch to the Debug perspective
714
∗
[www.ibm.com/developerworks/library/os-eclipse-cdt-debug1/index.html]
http://fastlabtutorials.blogspot.com.eg/2015/01/using-eclipse-to-debug-cc-andfortran.html
†
471
M.5
Indexing and Refactoring
Indexing
The C/C++ indexer∗ uses the parser to create a database of your source and header files that
provides the basis for C/C++ search, navigation features and parts of content assist.
• C/C++ indexer is enabled by default
• Fortran indexer is however disabled by default! to enable it:
– Project > Properties > Fortran General > Analysis/Refactoring
• More details are available in
documentation/photran5advanced
https://wiki.eclipse.org/PTP/photran/
Refactoring
Refactorings† are changes to a program that improve its internal design but do not change its
behavior.
• Photran can only refactor free-format Fortran source code
• Refactoring in Photran includes‡ :
– Subprogram Refactorings
– Rename
– Extract Procedure
∗ Add Subroutine Parameter
∗ Permute Subprogram Arguments
– Extract Local Variable
∗
[http://help.eclipse.org/photon/topic/org.eclipse.cdt.doc.user/concepts/cdt_c_
indexer.htm?cp=13_2_9_0]
†
[https://wiki.eclipse.org/PTP/photran/documentation/photran5advanced#Refactoring]
‡
[http://help.eclipse.org/photon/topic/org.eclipse.photran.doc.user/html/advanced/
Refactoring.html?cp=39_2_3]
472
∗ Safe Delete
– Module Refactorings
∗ Make Private Entity Public
∗ Encapsulate Variable
– Use Statement Refactorings
∗ Add ONLY Clause to USE Statement
∗ Minimize ONLY List
– Common Block Refactorings
∗ Make Common Block Variable
Names Consistent
∗ Move Saved Variables to Common Block
– Loop Refactorings
∗ Interchange Loops
∗ Fuse Loops
∗ Reverse Loop
∗ Tile Loop
∗ Unroll Loop
– Refactorings to Remove Obsolete
Language Features
∗ Remove Arithmetic If
∗ Remove Assigned Goto
∗ Remove Branch to End If
∗ Replace Character* with Character(len=)
∗ Remove Computed Goto
∗ Replace Obsolete Operators
∗ Replace Old-Style Do Loops
∗ Remove Pause Statement
∗ Remove Real/Double Precision
Loop Counter
– Refactorings to Improve Coding Style
∗ Add Identifier to End Statement
∗ Change Keyword Case
∗ Convert Between If Statement
and If Construct
∗ Convert Data Statement to Parameter Statements
∗ Introduce Implicit None
∗ Make Save Attributes Explicit
∗ Remove Unreferenced Labels
∗ Remove Unused Local Variables
∗ Standardize Statements
716
473
This page is intentionally left blank!
474
Appendix N
Visual Studio Code (Draft)
VSCode is a powerful:
2. debugger
1. code editor
• As a code editor, VSCode provides the following features:
– syntax highlighting
pletion
– code refactoring
– intelligent code com-
– snippets
– embedded Git
• As a debugger, VSCode supports the Node.js runtime and can debug JavaScript, TypeScript, or any other language that gets transpiled to JavaScript∗
– For debugging other languages and runtimes, install the relevant extensions
• VSCode is, however, not good enough for building binaries
– Even when building using external tools like GNU-make, when there are compile or
link errors, double-clicking the error does not take you to the line causing the error
– This is why VSCode is not denoted as an IDE
717
∗
[https://code.visualstudio.com/docs/editor/debugging]
475
Stack Overflow 2022 Survey†
VSCodium∗
Visual Studio Code collects usage data and sends it to Microsoft† .
• Since VSCode is open-source, it is known exactly what is collected
• VSCodium is an alternative to VSCode that uses only the open-source parts and omits
Microsoft’s trademarks and the telemetry component
†
[https://survey.stackoverflow.co/2022/#section-most-popular-technologiesintegrated-development-environment]
∗
[https://en.wikipedia.org/wiki/Visual_Studio_Code]
†
This telemetry reporting can be disabled
476
Workspace and Folders‡
Users of the full-fledged Visual Studio are used to create a Solution and add Projects to it.
• In VSCode, to create something similar to a Project, open a Folder
• You can add several Folders to the so called Workspace, then save this Workspace
720
.json Files∗
VSCode stores its various configurations in .json files within the .vscode folder.
settings.json file stores settings that are specific to the opened folder
tasks.json file includes build instructions
launch.json file includes debugger settings
• Additionally,
c cpp properties.json includes compiler path and IntelliSense settings, for use within
the C/C++ extension
721
tasks.json†
There are a lots of tools‡ to automate tasks like linting, building, packaging, testing, or deploying
software systems.
• In VSCode, the tasks.json file can be configured to run scripts and start processes so that
many of these tools can be used
722
Tutorial on C/C++ Development with VSCode
• Refer to https://code.visualstudio.com/docs/languages/cpp
723
Debugging
• [https://code.visualstudio.com/docs/editor/debugging]
724
‡
[https://blogs.mathworks.com/developer/2018/06/19/mex-debugging-vscode/]
[https://code.visualstudio.com/docs/cpp/config-mingw]
†
[https://code.visualstudio.com/Docs/editor/tasks]
‡
Examples include the TypeScript Compiler, linters like ESLint and TSLint as well as build systems like Make,
Ant, Gulp, Jake, Rake, and MSBuild.
∗
477
This page is intentionally left blank!
478
Appendix O
Scientific Computing and Visualization using
Python
References
1. Boey Pak Cheong, Python; a programming language changes the world, pcboey@
pytech.com.my, http://pytechresources.com [19]
2. “Python for MATLAB Users”, available at https://code.google.com/archive/p/
python-for-matlab-users/downloads. [20]
3. Robert Johansson, “Lectures on scientific computing with Python”. [21]
725
O.1
Introduction
What is Python? [19]
Python is a high–level programming language developed by Guido van Rossum from 1989.
• It is a popular programming language that is used by many universities, scientists, app
scripters, casual developers, and professional developers, working on applications, web
sites, and cloud services.
Python is:
• Interpreted
• Object–
oriented
• Cross–platform
• FOSS
General characteristics of Python
• Clean and simple language: Easy–to–read and intuitive code, easy–to–learn minimalistic
syntax, maintainability scales well with size of projects.
• Expressive language: Fewer lines of code, fewer bugs, easier to maintain.
Technical details
• Dynamically typed: No need to define the type of variables, function arguments or return
types.
• Automatic memory management: No need to explicitly allocate and deallocate memory
for variables and data arrays. No memory leak bugs.
• Interpreted: No need to compile the code. The Python interpreter reads and executes the
python code directly.
Python Advantages
• Ease of programming, minimizing the time required to develop, debug and maintain the
code.
479
• Well designed language that encourage many good programming practices:
– Modular and object–oriented programming, good system for packaging and re–use
of code. This often results in more transparent, maintainable and bug–free code.
– Documentation tightly integrated with the code.
• A large standard library, and a large collection of add–on packages.
• Lots of documentation, samples, and a strong developer community.
Python Disadvantages
• Since Python is an interpreted and dynamically typed programming language, the execution of python code can be slow compared to compiled statically typed programming
languages, such as C and Fortran.
• Somewhat decentralized, with different environment, packages and documentation spread
out at different places. Can make it harder to get started.
Why Python?
• Easy to learn
• Great performance due to close integration with time–tested and highly optimized codes written in C and Fortran:
• Readable syntax
– blas, atlas blas, lapack, arpack, Intel MKL, ...
• Higher productivity
• Impressive Standard Libraries
• Good support for
• Extensive Third Party Libraries
– Parallel computing with processes
and threads
• Excellent Documentation
– Interprocess communication (MPI)
• Integration with other languages/tools
– GPU computing (OpenCL and
CUDA)
• Powerful & Versatile
– Build
sites
web-
– Networking
and numeric
computing
– GUI
– Data visualization
– Scientific
– ...
• Readily available and suitable for use
on High Performance Computing (HPC)
clusters.
• No license costs, no unnecessary use of
research budget.
• External modules, some defined in
computationally efficient compiled languages such as C and Fortran, can be accessed from Python [22]
• FOSS
• Great community
480
What can you do with Python? [19]
Python by itself not suitable for typical engineering calculations.
• You also need the numeric, scientific and plotting libraries
– NumPy
– SciPy
– Matplotlib
– ...
• Some engineering calculations you can do
– Linear algebra
– Root finding
– Linear or nonlinear regression
– Integration and ordinary differential
equations
– statistics
– plotting
728
FORTRAN Vs Python [19]
Computation Time
Development Time
Past
Expensive
Relatively Cheap
FORTRAN
Nowadays
Cheap
Expensive
Python
• Heavily optimized static typed compiler
• Dynamic typed interpreted language
• World’s oldest yet still used language
• Created 1990
• Existing software needs maintenance
• Python is a good alternative for new software
– Easy to learn
– Free, open–source
– Numerous packages
– Strong community
• Much easier to learn
• Faster to develop code
• Compared with FORTRAN, the core
Python arrays (lists) are not fast
• But Python with SciPy and NumPy is a
game changer
• >90,000 Python packages in pypi
• Scientific/Engineering Category
– > 5500 packages
– In 16 sub–categories
481
O.1.1
Installing Python
There are huge number of Python products∗ .
• In order to install any of these wonderful products, you have to install compatible versions
of all their dependency packages as well.
• This process can be automated by using a package manager
– In Linux, this is straight forward.
∗ For example, to install Python packages for scientific computing and visualization on Linux, simply select major Python packages∗ and the package manager
will do the hard job of identifying, downloading and installing all the necessary
dependencies
– In Windows, however, this is a extremely cumbersome process
• Therefore, there are a number of Python distributions aiming to simplify installing these
wonderful products
Python Distributions
Among available Python distributions, there are:
• Anaconda Cross–platform. Free. Allows commercial use and redistribution
• Intel Python Distribution Cross–platform. Free with forum support. Enterprise support
is available by buying any of Intel Parallel Studio XE or Intel System Studio products.
• Enthought Cross–platform. Commercial. Free for academic use.
• Python(x,y) For Windows only. FOSS.
∗
such as python, spyder, ipython, ipython–notebook, numpy, scipy, sympy, matplotlib, maiavi, . . .
482
731
O.1.2
Python 2 or 3
There are currently two versions of python; Python 2 and Python 3.
• Unfortunately, Python 3 is not backward–compatible with Python 2 [19]
• Python 2 is still the most wide–spread version
• Several versions of Python versions can be installed together
732
O.1.3
Interactive Shells
Interactive Shells
A Python interactive shell is a CLI shell∗ that enables executing commands and displaying their
output.
• Among notable Python interactive shells are:
1. Python interpreter
3. Jupyter Notebook
2. IPython Qt Console
733
∗
Like Matlab’s “command prompt” and Windows and Linux CLI shells
483
Python Interpreter
“Python interpreter” is a python CLI shell.
• To use the interpreter interactively, run $ python at the command line
– The prompt is >>>
– To exit the interpreter, type >>> quit() or press Ctrl+D or close the command line
terminal
• To execute a script file, run $ python my-program.py
• Alternatively, the script file can be executed by running the file itself as
$ my-program.py . This becomes possible by:
1. setting the file permission to be executable
2. define the path to the interpreter∗ in the first line of the script file as
#!/usr/bin/python
– note that this is a comment line as far as the Python interpreter is concerned
• Unfortunately, the standard python interpreter has a number of limitations
IPython Qt Console
• Provides greatly improved user–friendliness
• Allows inline plotting
∗
Works for UNIX–like systems
484
• Command history
– __ and ___ recalls the second and third to last results
∗ use the command history to list the history of commands
∗ use In[n] to access the n–th command string
∗ use Out[n] to access the n–th result
• Tab auto–completion
– type the initial letters and hit the Tab key to get a list of possible completions
– Works for variables, functions, paths, etc.
• In–line editing of code
• The prompt looks like In [1]:
• Documentation
– Type objectName? to get info about objectName
– The standard Python help(objectName) still works
• Auto Call
– For example, abs x calls abs(x) ∗
• and many other features . . .
735
∗
Matlab also allows this.
485
Jupyter Notebook
“Jupyter Notebook “(formerly IPython Notebook) is an HTML–based notebook environment†
editable from the web browser.
• Notebooks can be converted to a number of open standard output formats‡
• To start a new session, run > jupyter notebook from the directory where you want
the notebooks to be stored
• Jupyter also supports Julia, R, Ruby, gnuplot, Octave, Scilab, Matlab, . . .
†
‡
Similar to Mathematica or Maple
like HTML, presentation slides, LATEX, PDF, ReStructuredText, Markdown, Python, . . .
486
Python For Data Science Cheat Sheet
Jupyter Notebook
Working with Different Programming Languages
Widgets
Kernels provide computation and communication with front-end interfaces
like the notebooks. There are three main kernels:
Notebook widgets provide the ability to visualize and control changes
in your data, often as a control like a slider, textbox, etc.
Learn More Python for Data Science Interactively at www.DataCamp.com
IRkernel
Installing Jupyter Notebook will automatically install the IPython kernel.
Saving/Loading Notebooks
Save current notebook
and record checkpoint
Preview of the printed
notebook
Close notebook & stop
running any scripts
Open an existing
notebook
Rename notebook
Revert notebook to a
previous checkpoint
You can use them to build interactive GUIs for your notebooks or to
synchronize stateful and stateless information between Python and
JavaScript.
Interrupt kernel
Restart kernel
Create new notebook
Make a copy of the
current notebook
IJulia
Interrupt kernel &
clear all output
Restart kernel & run
all cells
Connect back to a
remote notebook
Restart kernel & run
all cells
Download serialized
state of all widget
models in use
Save notebook
with interactive
widgets
Embed current
widgets
Run other installed
kernels
Command Mode:
Download notebook as
- IPython notebook
- Python
- HTML
- Markdown
- reST
- LaTeX
- PDF
15
13
1
2
3
4
5
6
7
8
9
10
11
14
12
Writing Code And Text
Code and text are encapsulated by 3 basic cell types: markdown cells, code
cells, and raw NBConvert cells.
487
Edit Cells
Cut currently selected cells
to clipboard
Paste cells from
clipboard above
current cell
Paste cells from
clipboard on top
of current cel
Revert “Delete Cells”
invocation
Copy cells from
clipboard to current
cursor position
Paste cells from
clipboard below
current cell
Delete current cells
Split up a cell from
current cursor
position
Merge current cell
with the one above
Merge current cell
with the one below
Move current cell up
Move current cell
down
Adjust metadata
underlying the
current notebook
Remove cell
attachments
Paste attachments of
current cell
Find and replace
in selected cells
Copy attachments of
current cell
Insert image in
selected cells
Edit Mode:
Executing Cells
Run selected cell(s)
Run current cells down
and create a new one
above
Add new cell below the
current one
Run all cells
Run all cells above the
current cell
Run all cells below
the current cell
Change the cell type of
current cell
toggle, toggle
scrolling and clear
current outputs
toggle, toggle
scrolling and clear
all output
Toggle display of Jupyter
logo and filename
Toggle line numbers
in cells
Walk through a UI tour
List of built-in keyboard
shortcuts
Edit the built-in
keyboard shortcuts
Notebook help topics
Description of
markdown available
in notebook
Information on
unofficial Jupyter
Notebook extensions
IPython help topics
NumPy help topics
Toggle display of toolbar
Toggle display of cell
action icons:
- None
- Edit metadata
- Raw cell format
- Slideshow
- Attachments
- Tags
9. Interrupt kernel
10. Restart kernel
11. Display characteristics
12. Open command palette
13. Current kernel
14. Kernel status
15. Log out from notebook server
Asking For Help
Python help topics
View Cells
Insert Cells
Add new cell above the
current one
Run current cells down
and create a new one
below
1. Save and checkpoint
2. Insert cell below
3. Cut cell
4. Copy cell(s)
5. Paste cell(s) below
6. Move cell up
7. Move cell down
8. Run current cell
SciPy help topics
Matplotlib help topics
SymPy help topics
Pandas help topics
About Jupyter Notebook
DataCamp
Learn Python for Data Science Interactively
O.1.4
Notable Python IDE’s
Among notable Python interactive shells are∗ :
• IDLE the original IDE bundled with most Python distributions
• Eclipse cross–platform
• PyCharm cross–platform; the Intel supported Python IDE on Linux
• Visual Studio Windows
• Visual Studio Code cross–platform
• Spyder the most similar to Matlab
The Spyder IDE
Spyder is IDE is very similar to Matlab.
• It has an editor, interpreter, variable explorer, object inspector, . . .
• It can run scripts in any of following interactive shells:
– IPython Qt Console
– Python interpreter
∗
The complete list is available @ https://en.wikipedia.org/wiki/Comparison_of_integrated_
development_environments#Python
488
O.1.5
Importing Packages, Modules, Functions, . . .
Managing Libraries of Functions [20]
MATLAB and Python have different strategies for organizing and calling libraries of functions.
• In MATLAB, importing functions is implicit.
– Each function must reside in a file of the same name.
– When a function is called, the MATLAB path is searched to find the first matching
function.
– Dealing with functions in different packages with the same name is
– problematic.
• In Python, importing functions is explicit.
– Any number of functions can reside in a file.
– Modules, packages, and function must be explicitly imported when
– needed.
– Name spaces and renaming allows for easy resolution of name conflicts.
739
Importing Packages, Modules, Functions, . . . [20]
• The Python import statement is used to explicitly import packages, modules, classes,
functions, and variables.
module is a python le (.py) that may contain multiple functions, variables, and classes.
package is a collection of modules in a directory. The directory must contain a le named
__init__.py . Packages can be nested.
• The import statement initializes a module or package by executing the code in the module
or __init__.py .
• Python searches current directory and Python path to find matching modules and packages.
• Each module or package is imported only once in a Python session, call reload() to
force reloading.
740
An Example Python Package [20]
Directory structure of a Python package.
• vision/ Top–level package
•
init .py Initialize vision package
• learning/ Subpackage for learning
•
489
init .py
• adaboost.py
• features/ Subpackage for features
• svm.py
•
• tracking/ Subpackage for tracking
• sift.py
•
init .py
• harris.py
• kalman.py
• canny.py
init .py
Importing Modules and Packages [20]
• If the “vision” directory is in the Python path then the following works.
import vision.tracking.kalman # executes vision / tracking / kalman.
py
vision.tracking.kalman.predict () # call a function in kalman.py
• Generally __init__.py includes statements to import all the sub–packages or modules
recursively. So the following usually works, but it imports the whole vision package.
import vision # executes vision / __init__.py
vision.features.harris.detect() # call a function in harris.py
vision.tracking.kalman.predict() # call a function in kalman.py
• The “ as ” keyword allows renaming during import.
import vision.tracking.kalman as kf
kf.predict()
Importing Specific Functions or Variables [20]
• The “ from ” keyword allows importing into the current name space.
from vision.tracking.kalman import predict, correct
predict()
correct()
• Rename specic functions with “ as ”.
from vision.tracking.kalman import predict as my_pred, correct as
my_corr
my_pred()
my_corr()
• Using “ * ” imports of everything into the current name space.
from vision.tracking.kalman import *
predict()
correct()
490
Python Path
• To modify your Python search path to include the locations of your own modules, define
the PYTHONPATH environment variable. [21]
• To have a particular script file executed when the interactive Python interpreter is started,
define the PYTHONSTARTUP environment variable to contain the name of your startup
script. [21]
• Modify sys.path to make temporary changes during execution. [20]
In [9]: import sysIn [10]: sys. path.append ("/ home / tutorial ")In
1]: sys. pathOut[11]:[’’,’/ usr/ bin ’,’/ usr/ lib / python2.7 ’,...’/ usr/ lib / python2
/ dist - packages / IPython / extensions ’,’/ home / tutorial ’]
744
NumPy, SciPy, and Matplotlib
NumPy adds basic MATLAB–like capability to Python:
• multidimensional arrays with homogeneous data types
• specic numeric data types (e.g. int8, uint32, float64)
• array manipulation functions (e.g. reshape, transpose, concatenate)
• array generation (e.g. ones, zeros, eye, random)
• element–wise math operations (e.g. add, multiply, max, sin)
• matrix math operations (e.g. inner/outer product, rank, trace)
• linear algebra (e.g. inv, pinv, svd, eig, det, qr)
SciPy builds on NumPy (much like MATLAB toolboxes) adding:
• multidimensional image processing
• non–linear solvers, optimization, root nding
• signal processing, fast Fourier transforms
• numerical integration, interpolation, statistical functions
• sparse matrices, sparse solvers
• clustering algorithms, distance metrics, spatial data structures
• file IO (including to MATLAB .mat files)
• There are also many add–on toolkits for SciPy, collectively called SciKits. Most
interestinf SciKits are:
scikit-aero Aeronautical engineering calculations in Python.
scikit-image Image processing routines for SciPy
491
scikit-kinematics Python utilites for movements in 3d space
scikit-learn A set of python modules for machine learning and data mining
scikit-optimize Sequential model–based optimization toolbox.
scikit-neuralnetwork Deep neural networks without the learning cliff! A wrapper
library compatible with scikit-learn.
scikit-sound Python utilites for generating and playing sound
scikit-sparse Scikits sparse matrix package
scikit-vi Scikit providing Virtual Instruments
Matplotlib adds MATLAB–like plotting capability on top of NumPy.
O.2
Standard Python Tutorial
Study [22, Chapter 2]
Standard Python is a clean but powerful language and is relatively easy to learn.
492
Python For Data Science Cheat Sheet
Python Basics
Learn More Python for Data Science Interactively at www.datacamp.com
Lists
Selecting List Elements
Variables and Data Types
>>> my_list[1]
>>> my_list[-3]
Select item at index 1
Select 3rd last item
>>> my_list[1:3]
>>> my_list[1:]
>>> my_list[:3]
>>> my_list[:]
Select items at index 1 and 2
Select items after index 0
Select items before index 3
Copy my_list
>>> my_list2[1][0]
>>> my_list2[1][:2]
my_list[list][itemOfList]
Slice
Calculations With Variables
>>> x+2
Sum of two variables
>>> x-2
Subtraction of two variables
>>> x*2
Multiplication of two variables
>>> x**2
Exponentiation of a variable
>>> x%2
Remainder of a variable
>>> x/float(2)
Division of a variable
3
10
25
1
Index starts at 0
Subset
Variable Assignment
>>> x=5
>>> x
5
7
Also see NumPy Arrays
>>> a = 'is'
>>> b = 'nice'
>>> my_list = ['my', 'list', a, b]
>>> my_list2 = [[4,5,6,7], [3,4,5,6]]
493
2.5
Subset Lists of Lists
str()
'5', '3.45', 'True'
Variables to strings
List Operations
>>> my_list + my_list
['my', 'list', 'is', 'nice', 'my', 'list', 'is', 'nice']
>>> my_list * 2
['my', 'list', 'is', 'nice', 'my', 'list', 'is', 'nice']
int()
5, 3, 1
Variables to integers
float()
5.0, 1.0
Variables to floats
bool()
True, True, True
Variables to booleans
Asking For Help
>>> help(str)
'thisStringIsAwesome'
String Operations
>>> my_string * 2
'thisStringIsAwesomethisStringIsAwesome'
>>> my_string + 'Innit'
'thisStringIsAwesomeInnit'
>>> 'm' in my_string
True
Scientific computing
2D plotting
Free IDE that is included
with Anaconda
Leading open data science platform
powered by Python
Create and share
documents with live code,
visualizations, text, ...
Numpy Arrays
Also see Lists
Selecting Numpy Array Elements
Subset
>>> my_array[1]
List Methods
>>> my_array[0:2]
Slice
Get the index of an item
Count an item
Append an item at a time
Remove an item
Remove an item
Reverse the list
Append an item
Remove an item
Insert an item
Sort the list
Index starts at 0
Select item at index 1
2
Select items at index 0 and 1
array([1, 2])
Subset 2D Numpy arrays
>>> my_2darray[:,0]
my_2darray[rows, columns]
array([1, 4])
Numpy Array Operations
>>> my_array > 3
array([False, False, False,
>>> my_array * 2
True], dtype=bool)
array([2, 4, 6, 8])
>>> my_array + np.array([5, 6, 7, 8])
array([6, 8, 10, 12])
Strings
>>> my_string = 'thisStringIsAwesome'
>>> my_string
Machine learning
Install Python
>>> my_list2 > 4
>>> my_list.index(a)
>>> my_list.count(a)
>>> my_list.append('!')
>>> my_list.remove('!')
>>> del(my_list[0:1])
>>> my_list.reverse()
>>> my_list.extend('!')
>>> my_list.pop(-1)
>>> my_list.insert(0,'!')
>>> my_list.sort()
Data analysis
>>> my_list = [1, 2, 3, 4]
>>> my_array = np.array(my_list)
>>> my_2darray = np.array([[1,2,3],[4,5,6]])
True
Types and Type Conversion
Libraries
Import libraries
>>> import numpy
>>> import numpy as np
Selective import
>>> from math import pi
String Operations
Index starts at 0
>>> my_string[3]
>>> my_string[4:9]
String Methods
>>> my_string.upper()
>>> my_string.lower()
>>> my_string.count('w')
>>> my_string.replace('e', 'i')
>>> my_string.strip()
String to uppercase
String to lowercase
Count String elements
Replace String elements
Strip whitespaces
Numpy Array Functions
Get the dimensions of the array
>>> my_array.shape
>>> np.append(other_array)
Append items to an array
>>> np.insert(my_array, 1, 5) Insert items in an array
>>> np.delete(my_array,[1])
Delete items in an array
Mean of the array
>>> np.mean(my_array)
Median of the array
>>> np.median(my_array)
>>> my_array.corrcoef()
Correlation coefficient
>>> np.std(my_array)
Standard deviation
DataCamp
Learn Python for Data Science Interactively
O.3
Scientific Computing with Python
Learning Scientific Computing with Python
As explained earlier, Python is a fantastic programming language with vast capabilities/applications.
• In this part, however, we are interested in using Python for scientific computing
– That is, we are solely interested in using the numpy, SciPy and matplotlib Python
libraries
– Therefore, avoid references explaining the plain Python programming language or
references targeting another applications of Python
For engineering students familiar with Matlab,
very good starting points are:
1. David J. Raymond, Python for Science, 2017, available at http://kestrel.
nmt.edu/~raymond/software/python_notes/scientific_python.pdf and http:
//kestrel.nmt.edu/~raymond/software/python_notes/index.html. (Concise
book suitable for experienced programmers.) [22]
2. Robert Johansson, “Lectures on scientific computing with Python”. (A bit lengthy) [21]
Continuously Updated Open Source Documentation
Since Python is a very active FOSS language, it is continuously improved. Similarly, since the
following documentation are FOSS, they are continuously updated. This is especially useful for
learning recent advances in:
• Installing Python
• Using FORTRAN and C code with Python
• Tools for high–performance computing applications
• ...
494
In conclusion, I suggest you use them as reference manual rather than tutorials.
1. Scipy Lecture Notes, an open–source collaborative documentation, available @ www.
scipy-lectures.org. (A bit lengthy book suitable for novices with shallow programming experience. It is however continuously updates) [23]
746
Why Scientific Computing with Python
O.3.1
747
NumPy
Study [22, Chapter 3]
array vs matrix [21]
• NumPy provides, in addition to np.ndarray , an additional matrix type that you may see
used in some existing code. Which one to use?
• Short answer
– Use arrays.
– They are the standard vector/matrix/tensor type of numpy. Many numpy functions
return arrays, not matrices.
– There is a clear distinction between element–wise operations and linear algebra operations.
– You can have standard vectors or row/column vectors if you like.
The only disadvantage of using the array type is that you will have to use dot instead of *
to multiply (reduce) two tensors (scalar product, matrix vector multiplication etc.).
• Long answer
NumPy contains both an array class and a matrix class. The array class is intended to
be a general–purpose n–dimensional array for many kinds of numerical computing, while
matrix is intended to facilitate linear algebra computations specifically. In practice there
are only a handful of key differences between the two.
– Operator * , dot() , and multiply()
∗ For array, * means element–wise multiplication, and the dot() function is
used for matrix multiplication.
∗ For matrix, * means matrix multiplication, and the multiply() function is
used for element–wise multiplication.
– Handling of vectors (one–dimensional arrays)
∗ For array, the vector shapes 1xN, Nx1, and N are all different things. Operations
like A[:,1] return a one–dimensional array of shape N, not a two–dimensional
array of shape Nx1. Transpose on a one–dimensional array does nothing.
∗ For matrix, one–dimensional arrays are always upconverted to 1xN or Nx1 matrices (row or column vectors). A[:,1] returns a two–dimensional matrix of
shape Nx1.
495
– Handling of higher–dimensional arrays (ndim > 2)
∗ array objects can have number of dimensions > 2;
∗ matrix objects always have exactly two dimensions.
– Convenience attributes
∗ array has a .T attribute, which returns the transpose of the data.
∗ matrix also has .H , .I , and .A attributes, which return the conjugate transpose, inverse, and asarray() of the matrix, respectively.
– Convenience constructor
∗ The array constructor takes (nested) Python sequences as initializers. As in
array([[1,2,3],[4,5,6]])
∗ The matrix constructor additionally takes a convenient string initializer. As in
matrix("[1 2 3; 4 5 6]")
There are pros and cons to using both:
• array
– You can treat one–dimensional arrays as either row or column vectors. dot(A,v)
treats v as a column vector, while dot(v,A) treats v as a row vector. This can
save you having to type a lot of transposes.
∗ Having to use the dot() function for matrix–multiply is messy –
dot(dot(A,B),C) vs. A*B*C
– Element–wise multiplication is easy: A*B
– array is the “default” NumPy type, so it gets the most testing, and is the type most
likely to be returned by 3rd party code that uses NumPy.
– Is quite at home handling data of any number of dimensions.
– Closer in semantics to tensor algebra, if you are familiar with that.
– All operations (*, /, +, - etc.) are elementwise
• matrix
– Behavior is more like that of MATLAB matrices.
∗ Maximum of two-dimensional. To hold three-dimensional data you need array
or perhaps a Python list of matrix.
∗ Minimum of two-dimensional. You cannot have vectors. They must be cast as
single-column or single-row matrices.
∗ Since array is the default in NumPy, some functions may return an array even
if you give them a matrix as an argument. This shouldn’t happen with NumPy
functions (if it does it’s a bug), but 3rd party code based on NumPy may not
honor type preservation like NumPy does.
– A*B is matrix multiplication, so more convenient for linear algebra.
∗ Element–wise multiplication requires calling a function, multipy(A,B)
∗ The use of operator overloading is a bit illogical: * does not work elementwise
but / does
496
The array is thus much more advisable to use.
• Facilities for Matrix Users
NumPy has some features that facilitate the use of the matrix type, which hopefully make
things easier for Matlab converts.
– A matlib module has been added that contains matrix versions of common array
constructors like ones() , zeros() , empty() , eye() , rand() , repmat() ,
etc. Normally these functions return arrays, but the matlib versions return matrix
objects.
– mat has been changed to be a synonym for asmatrix, rather than matrix, thus making
it a concise way to convert an array to a matrix without copying the data.
– Some top–level functions have been removed. For example numpy.rand() now
needs to be accessed as numpy.random.rand() . Or use the rand() from the
matlib module. But the “numpythonic” way is to use numpy.random.random() ,
which takes a tuple for the shape, like other numpy functions.
748
Import Tips
• When writing scripts it is recommended that you:
– only import what you need, for efficiency
– import packages into namespaces, to avoid name clashes
• The community has adopted abbreviated naming conventions:
import numpy as np
import scipy as sp
import matplotlib as mpl
import matplotlib.pyplot as plt
• Some different ways of working with NumPy are :
from pylab import * # Import everything. Good for interactive work,
svd(eye(3)) # but not recommended for writing scripts.
from numpy import eye, array # Import only what you need into the
global namespace.
from numpy.linalg import svd # Verbose syntax for import statements,
svd(eye(3)) # but simple syntax for calling functions.
import numpy as np # Import a superset of what you need into a
namespace.
np.linalg.svd(np.eye(3)) # More verbose syntax for calling functions
.
749
497
Python For Data Science Cheat Sheet
NumPy Basics
Learn Python for Data Science Interactively at www.DataCamp.com
NumPy
2
The NumPy library is the core library for scientific computing in
Python. It provides a high-performance multidimensional array
object, and tools for working with these arrays.
>>> import numpy as np
NumPy Arrays
1
2
3
2D array
3D array
axis 1
axis 0
1.5
2
3
4
5
6
axis 2
axis 1
axis 0
Subsetting, Slicing, Indexing
Array dimensions
Length of array
Number of array dimensions
Number of array elements
Data type of array elements
Name of data type
Convert an array to a different type
498
>>> a = np.array([1,2,3])
>>> b = np.array([(1.5,2,3), (4,5,6)], dtype = float)
>>> c = np.array([[(1.5,2,3), (4,5,6)], [(3,2,1), (4,5,6)]],
dtype = float)
Initial Placeholders
>>> np.zeros((3,4))
Create an array of zeros
>>> np.ones((2,3,4),dtype=np.int16) Create an array of ones
>>> d = np.arange(10,25,5)
Create an array of evenly
spaced values (step value)
>>> np.linspace(0,2,9)
Create an array of evenly
spaced values (number of samples)
>>> e = np.full((2,2),7)
Create a constant array
>>> f = np.eye(2)
Create a 2X2 identity matrix
>>> np.random.random((2,2))
Create an array with random values
>>> np.empty((3,2))
Create an empty array
I/O
Saving & Loading On Disk
>>> np.save('my_array', a)
>>> np.savez('array.npz', a, b)
>>> np.load('my_array.npy')
Saving & Loading Text Files
>>> np.loadtxt("myfile.txt")
>>> np.genfromtxt("my_file.csv", delimiter=',')
>>> np.savetxt("myarray.txt", a, delimiter=" ")
Data Types
Signed 64-bit integer types
Standard double-precision floating point
Complex numbers represented by 128 floats
Boolean type storing TRUE and FALSE values
Python object type
Fixed-length string type
Fixed-length unicode type
Subsetting
>>> np.info(np.ndarray.dtype)
1
2
3
Select the element at the 2nd index
>>> b[1,2]
6.0
1.5
2
3
4
5
6
Select the element at row 1 column 2
(equivalent to b[1][2])
>>> a[0:2]
1
2
3
Select items at index 0 and 1
>>> b[0:2,1]
1.5
2
3
Select items at rows 0 and 1 in column 1
4
5
6
1.5
2
3
4
5
6
3
Slicing
array([ 2.,
Array Mathematics
Also see Lists
>>> a[2]
array([1, 2])
Asking For Help
5.])
>>> b[:1]
>>> c[1,...]
Select all items at row 0
(equivalent to b[0:1, :])
Same as [1,:,:]
>>> a[ : :-1]
Reversed array a
array([[1.5, 2., 3.]])
array([[[ 3., 2., 1.],
[ 4., 5., 6.]]])
>>> g = a - b
Subtraction
>>> np.subtract(a,b)
>>> b + a
Subtraction
Addition
>>> a[a<2]
>>> np.add(b,a)
>>> a / b
Addition
Division
>>> b[[1, 0, 1, 0],[0, 1, 2, 0]]
Select elements (1,0),(0,1),(1,2) and (0,0)
>>> b[[1, 0, 1, 0]][:,[0,1,2,0]]
Select a subset of the matrix’s rows
and columns
array([[-0.5, 0. , 0. ],
[-3. , -3. , -3. ]])
array([[ 2.5,
[ 5. ,
4. ,
7. ,
array([[ 0.66666667, 1.
[ 0.25
, 0.4
array([[
[
1.5,
4. ,
4. ,
10. ,
>>> np.multiply(a,b)
>>> np.exp(b)
>>> np.sqrt(b)
>>> np.sin(a)
>>> np.cos(b)
>>> np.log(a)
>>> e.dot(f)
array([[ 7.,
[ 7.,
array([3, 2, 1])
6. ],
9. ]])
>>> np.divide(a,b)
>>> a * b
Creating Arrays
>>> np.int64
>>> np.float32
>>> np.complex
>>> np.bool
>>> np.object
>>> np.string_
>>> np.unicode_
>>> a.shape
>>> len(a)
>>> b.ndim
>>> e.size
>>> b.dtype
>>> b.dtype.name
>>> b.astype(int)
Arithmetic Operations
Use the following import convention:
1D array
Inspecting Your Array
, 1.
, 0.5
],
]])
9. ],
18. ]])
Division
Multiplication
Multiplication
Exponentiation
Square root
Print sines of an array
Element-wise cosine
Element-wise natural logarithm
Dot product
7.],
7.]])
Element-wise comparison
>>> a < 2
Element-wise comparison
>>> np.array_equal(a, b)
Array-wise comparison
array([[False, True, True],
[False, False, False]], dtype=bool)
array([True, False, False], dtype=bool)
Array-wise sum
Array-wise minimum value
Maximum value of an array row
Cumulative sum of the elements
Mean
Median
Correlation coefficient
Standard deviation
Copying Arrays
3
Fancy Indexing
array([ 4. , 2. , 6. , 1.5])
array([[ 4. ,5. , 6. , 4. ],
[ 1.5, 2. , 3. , 1.5],
[ 4. , 5. , 6. , 4. ],
[ 1.5, 2. , 3. , 1.5]])
Create a view of the array with the same data
Create a copy of the array
Create a deep copy of the array
Sort an array
Sort the elements of an array's axis
Select elements from a less than 2
Array Manipulation
Transposing Array
>>> i = np.transpose(b)
>>> i.T
Permute array dimensions
Permute array dimensions
>>> b.ravel()
>>> g.reshape(3,-2)
Flatten the array
Reshape, but don’t change data
>>> h.resize((2,6))
>>> np.append(h,g)
>>> np.insert(a, 1, 5)
>>> np.delete(a,[1])
Return a new array with shape (2,6)
Append items to an array
Insert items in an array
Delete items from an array
Changing Array Shape
Combining Arrays
>>> np.concatenate((a,d),axis=0) Concatenate arrays
array([ 1,
2,
3, 10, 15, 20])
array([[ 1. ,
[ 1.5,
[ 4. ,
2. ,
2. ,
5. ,
array([[ 7.,
[ 7.,
7.,
7.,
3. ],
3. ],
6. ]])
>>> np.r_[e,f]
>>> np.hstack((e,f))
1.,
0.,
Stack arrays vertically (row-wise)
Stack arrays vertically (row-wise)
Stack arrays horizontally (column-wise)
0.],
1.]])
>>> np.column_stack((a,d))
Create stacked column-wise arrays
>>> np.c_[a,d]
Create stacked column-wise arrays
>>> np.hsplit(a,3)
Split the array horizontally at the 3rd
index
Split the array vertically at the 2nd index
array([[ 1, 10],
[ 2, 15],
[ 3, 20]])
Splitting Arrays
Sorting Arrays
>>> a.sort()
>>> c.sort(axis=0)
2
>>> np.vstack((a,b))
Aggregate Functions
>>> h = a.view()
>>> np.copy(a)
>>> h = a.copy()
1
array([1])
Adding/Removing Elements
Comparison
>>> a == b
>>> a.sum()
>>> a.min()
>>> b.max(axis=0)
>>> b.cumsum(axis=1)
>>> a.mean()
>>> b.median()
>>> a.corrcoef()
>>> np.std(b)
Boolean Indexing
[array([1]),array([2]),array([3])]
>>> np.vsplit(c,2)
[array([[[ 1.5,
[ 4. ,
array([[[ 3.,
[ 4.,
2. , 1. ],
5. , 6. ]]]),
2., 3.],
5., 6.]]])]
DataCamp
Learn Python for Data Science Interactively
O.3.2
SciPy
Python For Data Science Cheat Sheet
SciPy - Linear Algebra
Learn More Python for Data Science Interactively at www.datacamp.com
SciPy
The SciPy library is one of the core packages for
scientific computing that provides mathematical
algorithms and convenience functions built on the
NumPy extension of Python.
Interacting With NumPy
Also see NumPy
>>> import numpy as np
>>> a = np.array([1,2,3])
>>> b = np.array([(1+5j,2j,3j), (4j,5j,6j)])
>>> c = np.array([[(1.5,2,3), (4,5,6)], [(3,2,1), (4,5,6)]])
Index Tricks
>>> np.mgrid[0:5,0:5]
>>> np.ogrid[0:2,0:2]
>>> np.r_[[3,[0]*5,-1:1:10j]
>>> np.c_[b,c]
Create a dense meshgrid
Create an open meshgrid
Stack arrays vertically (row-wise)
Create stacked column-wise arrays
Shape Manipulation
499
>>> np.transpose(b)
>>> b.flatten()
>>> np.hstack((b,c))
>>> np.vstack((a,b))
>>> np.hsplit(c,2)
>>> np.vpslit(d,2)
Permute array dimensions
Flatten the array
Stack arrays horizontally (column-wise)
Stack arrays vertically (row-wise)
Split the array horizontally at the 2nd index
Split the array vertically at the 2nd index
Polynomials
>>> from numpy import poly1d
>>> p = poly1d([3,4,5])
Create a polynomial object
Vectorizing Functions
>>> np.vectorize(myfunc)
Vectorize functions
Type Handling
>>> np.real(c)
Return the real part of the array elements
>>> np.imag(c)
Return the imaginary part of the array elements
>>> np.real_if_close(c,tol=1000) Return a real array if complex parts close to 0
>>> np.cast['f'](np.pi)
Cast object to a data type
Other Useful Functions
>>> from scipy import linalg, sparse
Matrix Functions
Creating Matrices
Addition
>>> A = np.matrix(np.random.random((2,2)))
>>> B = np.asmatrix(b)
>>> C = np.mat(np.random.random((10,5)))
>>> D = np.mat([[3,4], [5,6]])
Basic Matrix Routines
Inverse
(number of samples)
>>> g [3:] += np.pi
>>> np.unwrap(g)
Unwrap
>>> np.logspace(0,10,3)
Create an array of evenly spaced values (log scale)
>>> np.select([c<4],[c*2]) Return values from a list of arrays depending on
conditions
>>> misc.factorial(a)
Factorial
>>> misc.comb(10,3,exact=True) Combine N things taken at k time
>>> misc.central_diff_weights(3) Weights for Np-point central derivative
>>> misc.derivative(myfunc,1.0) Find the n-th derivative of a function at a point
>>> np.add(A,D)
Addition
>>> np.subtract(A,D)
Subtraction
>>> np.divide(A,D)
Division
>>> np.multiply(D,A)
>>> np.dot(A,D)
>>> np.vdot(A,D)
>>> np.inner(A,D)
>>> np.outer(A,D)
>>> np.tensordot(A,D)
>>> np.kron(A,D)
Multiplication
Dot product
Vector dot product
Inner product
Outer product
Tensor dot product
Kronecker product
Matrix exponential
Matrix exponential (Taylor Series)
Matrix exponential (eigenvalue
Subtraction
Division
Multiplication
>>> A.I
>>> linalg.inv(A)
>>> A.T
>>> A.H
>>> np.trace(A)
Inverse
Inverse
Tranpose matrix
Conjugate transposition
Trace
>>> linalg.norm(A)
>>> linalg.norm(A,1)
>>> linalg.norm(A,np.inf)
Frobenius norm
L1 norm (max column sum)
L inf norm (max row sum)
>>> linalg.expm(A)
>>> linalg.expm2(A)
>>> linalg.expm3(D)
>>> np.linalg.matrix_rank(C)
Matrix rank
>>> linalg.logm(A)
Matrix logarithm
>>> linalg.det(A)
Determinant
>>> linalg.solve(A,b)
>>> E = np.mat(a).T
>>> linalg.lstsq(D,E)
Solver for dense matrices
Solver for dense matrices
Least-squares solution to linear matrix
equation
>>> linalg.sinm(D)
>>> linalg.cosm(D)
>>> linalg.tanm(A)
Matrix sine
Matrix cosine
Matrix tangent
>>> linalg.sinhm(D)
>>> linalg.coshm(D)
>>> linalg.tanhm(A)
Hypberbolic matrix sine
Hyperbolic matrix cosine
Hyperbolic matrix tangent
>>> np.sigm(A)
Matrix sign function
>>> linalg.sqrtm(A)
Matrix square root
>>> linalg.funm(A, lambda x: x*x)
Evaluate matrix function
Norm
Rank
Determinant
Solving linear problems
Generalized inverse
>>> linalg.pinv(C)
Compute the pseudo-inverse of a matrix
(least-squares solver)
Compute the pseudo-inverse of a matrix
(SVD)
>>> F = np.eye(3, k=1)
Create a 2X2 identity matrix
>>> G = np.mat(np.identity(2)) Create a 2x2 identity matrix
>>> C[C > 0.5] = 0
>>> H = sparse.csr_matrix(C)
Compressed Sparse Row matrix
>>> I = sparse.csc_matrix(D)
Compressed Sparse Column matrix
>>> J = sparse.dok_matrix(A)
Dictionary Of Keys matrix
>>> E.todense()
Sparse matrix to full matrix
>>> sparse.isspmatrix_csc(A)
Identify sparse matrix
Sparse Matrix Routines
Inverse
Inverse
>>> sparse.linalg.norm(I)
Norm
>>> sparse.linalg.spsolve(H,I)
Solver for sparse matrices
Sparse Matrix Functions
>>> sparse.linalg.expm(I)
Asking For Help
>>> help(scipy.linalg.diagsvd)
>>> np.info(np.matrix)
decomposition)
Logarithm Function
Trigonometric Tunctions
Hyperbolic Trigonometric Functions
Matrix Sign Function
Matrix Square Root
Decompositions
Eigenvalues and Eigenvectors
>>> la, v = linalg.eig(A)
>>> l1, l2 = la
>>> v[:,0]
>>> v[:,1]
>>> linalg.eigvals(A)
Singular Value Decomposition
>>> sparse.linalg.inv(I)
Solving linear problems
Exponential Functions
Arbitrary Functions
Creating Sparse Matrices
Norm
>>> np.angle(b,deg=True)
Return the angle of the complex argument
>>> g = np.linspace(0,np.pi,num=5) Create an array of evenly spaced values
Also see NumPy
You’ll use the linalg and sparse modules. Note that scipy.linalg contains and expands on numpy.linalg.
>>> linalg.pinv2(C)
>>> def myfunc(a):
if a < 0:
return a*2
else:
return a/2
Linear Algebra
Sparse matrix exponential
Solve ordinary or generalized
eigenvalue problem for square matrix
Unpack eigenvalues
First eigenvector
Second eigenvector
Unpack eigenvalues
>>> U,s,Vh = linalg.svd(B)
Singular Value Decomposition (SVD)
>>> M,N = B.shape
>>> Sig = linalg.diagsvd(s,M,N) Construct sigma matrix in SVD
LU Decomposition
>>> P,L,U = linalg.lu(C)
LU Decomposition
Sparse Matrix Decompositions
>>> la, v = sparse.linalg.eigs(F,1)
>>> sparse.linalg.svds(H, 2)
DataCamp
Eigenvalues and eigenvectors
SVD
Learn Python for Data Science Interactively
O.3.3
matplotlib
[22, Chapter 4]
Python For Data Science Cheat Sheet
Matplotlib
Plot Anatomy & Workflow
Plot Anatomy
Learn Python Interactively at www.DataCamp.com
Matplotlib
Y-axis
Matplotlib is a Python 2D plotting library which produces
publication-quality figures in a variety of hardcopy formats
and interactive environments across
platforms.
1 Prepare The Data
Also see Lists & NumPy
1D Data
>>> import numpy as np
>>> x = np.linspace(0, 10, 100)
>>> y = np.cos(x)
>>> z = np.sin(x)
2D Data or Images
500
>>> data = 2 * np.random.random((10, 10))
>>> data2 = 3 * np.random.random((10, 10))
>>> Y, X = np.mgrid[-3:3:100j, -3:3:100j]
>>> U = -1 - X**2 + Y
>>> V = 1 + X - Y**2
>>> from matplotlib.cbook import get_sample_data
>>> img = np.load(get_sample_data('axes_grid/bivariate_normal.npy'))
Workflow
The basic steps to creating plots with matplotlib are:
Axes/Subplot
1 Prepare data 2 Create plot 3 Plot 4 Customize plot 5 Save plot 6 Show plot
>>> import matplotlib.pyplot as plt
>>> x = [1,2,3,4]
Step 1
>>> y = [10,20,25,30]
>>> fig = plt.figure() Step 2
>>> ax = fig.add_subplot(111) Step 3
>>> ax.plot(x, y, color='lightblue', linewidth=3) Step 3, 4
>>> ax.scatter([2,4,6],
[5,15,25],
color='darkgreen',
marker='^')
>>> ax.set_xlim(1, 6.5)
>>> plt.savefig('foo.png')
Step 6
>>> plt.show()
Figure
X-axis
4
Customize Plot
Colors, Color Bars & Color Maps
Mathtext
>>> plt.plot(x, x, x, x**2, x, x**3)
>>> ax.plot(x, y, alpha = 0.4)
>>> ax.plot(x, y, c='k')
>>> fig.colorbar(im, orientation='horizontal')
>>> im = ax.imshow(img,
cmap='seismic')
>>> plt.title(r'$sigma_i=15$', fontsize=20)
Limits, Legends & Layouts
Limits & Autoscaling
Markers
>>> fig, ax = plt.subplots()
>>> ax.scatter(x,y,marker=".")
>>> ax.plot(x,y,marker="o")
>>> import matplotlib.pyplot as plt
Figure
>>> fig = plt.figure()
>>> fig2 = plt.figure(figsize=plt.figaspect(2.0))
Axes
All plotting is done with respect to an Axes. In most cases, a
subplot will fit your needs. A subplot is an axes on a grid system.
>>> fig.add_axes()
>>> ax1 = fig.add_subplot(221) # row-col-num
>>> ax3 = fig.add_subplot(212)
>>> fig3, axes = plt.subplots(nrows=2,ncols=2)
>>> fig4, axes2 = plt.subplots(ncols=3)
Add padding to a plot
Set the aspect ratio of the plot to 1
Set limits for x-and y-axis
Set limits for x-axis
>>> ax.set(title='An Example Axes',
ylabel='Y-Axis',
xlabel='X-Axis')
>>> ax.legend(loc='best')
Set a title and x-and y-axis labels
>>> ax.xaxis.set(ticks=range(1,5),
ticklabels=[3,100,-12,"foo"])
>>> ax.tick_params(axis='y',
direction='inout',
length=10)
Manually set x-ticks
>>> fig3.subplots_adjust(wspace=0.5,
hspace=0.3,
left=0.125,
right=0.9,
top=0.9,
bottom=0.1)
>>> fig.tight_layout()
Adjust the spacing between subplots
Legends
Linestyles
2 Create Plot
>>> ax.margins(x=0.0,y=0.1)
>>> ax.axis('equal')
>>> ax.set(xlim=[0,10.5],ylim=[-1.5,1.5])
>>> ax.set_xlim(0,10.5)
>>> plt.plot(x,y,linewidth=4.0)
>>> plt.plot(x,y,ls='solid')
>>> plt.plot(x,y,ls='--')
>>> plt.plot(x,y,'--',x**2,y**2,'-.')
>>> plt.setp(lines,color='r',linewidth=4.0)
Text & Annotations
>>> ax.text(1,
-2.1,
'Example Graph',
style='italic')
>>> ax.annotate("Sine",
xy=(8, 0),
xycoords='data',
xytext=(10.5, 0),
textcoords='data',
arrowprops=dict(arrowstyle="->",
connectionstyle="arc3"),)
3 Plotting Routines
Subplot Spacing
Vector Fields
>>> fig, ax = plt.subplots()
>>> lines = ax.plot(x,y)
Draw points with lines or markers connecting them
>>> ax.scatter(x,y)
Draw unconnected points, scaled or colored
>>> axes[0,0].bar([1,2,3],[3,4,5])
Plot vertical rectangles (constant width)
>>> axes[1,0].barh([0.5,1,2.5],[0,1,2]) Plot horiontal rectangles (constant height)
>>> axes[1,1].axhline(0.45)
Draw a horizontal line across axes
>>> axes[0,1].axvline(0.65)
Draw a vertical line across axes
>>> ax.fill(x,y,color='blue')
Draw filled polygons
>>> ax.fill_between(x,y,color='yellow') Fill between y-values and 0
>>> axes[0,1].arrow(0,0,0.5,0.5)
>>> axes[1,1].quiver(y,z)
>>> axes[0,1].streamplot(X,Y,U,V)
Colormapped or RGB arrays
Fit subplot(s) in to the figure area
Axis Spines
>>> ax1.spines['top'].set_visible(False)
Make the top axis line for a plot invisible
>>> ax1.spines['bottom'].set_position(('outward',10)) Move the bottom axis line outward
Add an arrow to the axes
Plot a 2D field of arrows
Plot a 2D field of arrows
Data Distributions
Plot a histogram
Make a box and whisker plot
Make a violin plot
2D Data or Images
>>> fig, ax = plt.subplots()
>>> im = ax.imshow(img,
cmap='gist_earth',
interpolation='nearest',
vmin=-2,
vmax=2)
Make y-ticks longer and go in and out
5 Save Plot
Save figures
1D Data
>>> ax1.hist(y)
>>> ax3.boxplot(y)
>>> ax3.violinplot(z)
No overlapping plot elements
Ticks
>>> axes2[0].pcolor(data2)
>>> axes2[0].pcolormesh(data)
>>> CS = plt.contour(Y,X,U)
>>> axes2[2].contourf(data1)
>>> axes2[2]= ax.clabel(CS)
Pseudocolor plot of 2D array
Pseudocolor plot of 2D array
Plot contours
Plot filled contours
Label a contour plot
>>> plt.savefig('foo.png')
Save transparent figures
>>> plt.savefig('foo.png', transparent=True)
6 Show Plot
>>> plt.show()
Close & Clear
>>> plt.cla()
>>> plt.clf()
>>> plt.close()
Clear an axis
Clear the entire figure
Close a window
DataCamp
Learn Python for Data Science Interactively
Matplotlib 2.0.0 - Updated on: 02/2017
O.3.4
Pandas
Python For Data Science Cheat Sheet
Pandas Basics
Learn Python for Data Science Interactively at www.DataCamp.com
Asking For Help
Selection
Also see NumPy Arrays
Getting
>>> s['b']
Get one element
-5
Pandas
The Pandas library is built on NumPy and provides easy-to-use
data structures and data analysis tools for the Python
programming language.
Dropping
>>> help(pd.Series.loc)
>>> df[1:]
Country
1
India
2 Brazil
Capital
New Delhi
Brasília
Population
1303171035
207847528
Get subset of a DataFrame
By Position
>>> import pandas as pd
>>> df.iloc[[0],[0]]
'Belgium'
Pandas Data Structures
'Belgium'
A one-dimensional labeled array
capable of holding any data type
Index
a
3
b
-5
c
7
d
4
>>> s = pd.Series([3, -5, 7, 4], index=['a', 'b', 'c', 'd'])
501
DataFrame
Columns
Country
Population
Belgium
Brussels
1
India
New Delhi 1303171035
2
Brazil
Brasília
0
Index
Capital
11190846
A two-dimensional labeled
data structure with columns
of potentially different types
207847528
>>> data = {'Country': ['Belgium', 'India', 'Brazil'],
'Capital': ['Brussels', 'New Delhi', 'Brasília'],
'Population': [11190846, 1303171035, 207847528]}
>>> df = pd.DataFrame(data,
columns=['Country', 'Capital', 'Population'])
'Belgium'
Select single value by row &
column labels
>>> df.at([0], ['Country'])
'Belgium'
By Label/Position
>>> df.ix[2]
Select single row of
subset of rows
>>> df.ix[:,'Capital']
Select a single column of
subset of columns
>>> df.ix[1,'Capital']
Select rows and columns
Country
Brazil
Capital
Brasília
Population 207847528
0
1
2
Brussels
New Delhi
Brasília
'New Delhi'
Setting
Set index a of Series s to 6
Read and Write to CSV
Read and Write to SQL Query or Database Table
>>> pd.read_csv('file.csv', header=None, nrows=5)
>>> df.to_csv('myDataFrame.csv')
>>> from sqlalchemy import create_engine
>>> engine = create_engine('sqlite:///:memory:')
>>> pd.read_sql("SELECT * FROM my_table;", engine)
>>> pd.read_sql_table('my_table', engine)
>>> pd.read_sql_query("SELECT * FROM my_table;", engine)
Read multiple sheets from the same file
>>> xlsx = pd.ExcelFile('file.xls')
>>> df = pd.read_excel(xlsx, 'Sheet1')
>>> df.sum()
Sum of values
>>> df.cumsum()
Cummulative sum of values
>>> df.min()/df.max()
Minimum/maximum values
>>> df.idxmin()/df.idxmax() Minimum/Maximum index value
>>> df.describe()
Summary statistics
>>> df.mean()
Mean of values
>>> df.median()
Median of values
Applying Functions
>>> f = lambda x: x*2
>>> df.apply(f)
>>> df.applymap(f)
Apply function
Apply function element-wise
Internal Data Alignment
>>> s3 = pd.Series([7, -2, 3], index=['a', 'c', 'd'])
>>> s + s3
a
10.0
c
5.0
b
d
NaN
7.0
Arithmetic Operations with Fill Methods
I/O
>>> pd.read_excel('file.xlsx')
>>> pd.to_excel('dir/myDataFrame.xlsx', sheet_name='Sheet1')
(rows,columns)
Describe index
Describe DataFrame columns
Info on DataFrame
Number of non-NA values
NA values are introduced in the indices that don’t overlap:
>>> s[~(s > 1)]
Series s where value is not >1
>>> s[(s < -1) | (s > 2)]
s where value is <-1 or >2
>>> df[df['Population']>1200000000] Use filter to adjust DataFrame
Read and Write to Excel
>>> df.shape
>>> df.index
>>> df.columns
>>> df.info()
>>> df.count()
Data Alignment
Boolean Indexing
>>> s['a'] = 6
>>> df.sort_index()
Sort by labels along an axis
>>> df.sort_values(by='Country') Sort by the values along an axis
>>> df.rank()
Assign ranks to entries
Summary
By Label
>>> df.loc[[0], ['Country']]
Sort & Rank
Basic Information
Select single value by row &
column
>>> df.iat([0],[0])
Series
Drop values from rows (axis=0)
>>> df.drop('Country', axis=1) Drop values from columns(axis=1)
Retrieving Series/DataFrame Information
Selecting, Boolean Indexing & Setting
Use the following import convention:
>>> s.drop(['a', 'c'])
read_sql()is a convenience wrapper around read_sql_table() and
read_sql_query()
>>> pd.to_sql('myDf', engine)
You can also do the internal data alignment yourself with
the help of the fill methods:
>>> s.add(s3, fill_value=0)
a
b
c
d
10.0
-5.0
5.0
7.0
>>> s.sub(s3, fill_value=2)
>>> s.div(s3, fill_value=4)
>>> s.mul(s3, fill_value=3)
DataCamp
Learn Python for Data Science Interactively
O.3.5
Bokeh
[www.datacamp.com/community/blog/bokeh-cheat-sheet-python]
Bokeh distinguishes itself from other Python visualization libraries such as Matplotlib or
Seaborn in the fact that it is an interactive visualization library that is ideal for anyone who
would like to quickly and easily create interactive plots, dashboards, and data applications.
Bokeh is also known for enabling high–performance visual presentation of large data sets in
modern web browsers.
For data scientists, Bokeh is the ideal tool to build statistical charts quickly and easily; But
there are also other advantages, such as the various output options and the fact that you can embed
your visualizations in applications. And let’s not forget that the wide variety of visualization
customization options makes this Python library an indispensable tool for your data science
toolbox.
502
Python For Data Science Cheat Sheet 3
Renderers & Visual Customizations
Bokeh
Bokeh’s mid-level general purpose bokeh.plotting
interface is centered around two main components: data
and glyphs.
+
=
glyphs
plot
The basic steps to creating plots with the bokeh.plotting
interface are:
1. Prepare some data:
Python lists, NumPy arrays, Pandas DataFrames and other sequences of values
503
2. Create a new plot
3. Add renderers for your data, with visual customizations
4. Specify where to generate the output
5. Show or save the results
>>> from bokeh.plotting import figure
>>> from bokeh.io import output_file, show
>>> x = [1, 2, 3, 4, 5]
Step 1
>>> y = [6, 7, 2, 4, 5]
Step 2
>>> p = figure(title="simple line example",
x_axis_label='x',
y_axis_label='y')
Step 3
>>> p.line(x, y, legend="Temp.", line_width=2)
Step 4
>>> output_file("lines.html")
Step 5
>>> show(p)
>>> p1.line([1,2,3,4], [3,4,5,6], line_width=2)
>>> p2.multi_line(pd.DataFrame([[1,2,3],[5,6,7]]),
pd.DataFrame([[3,4,5],[3,2,1]]),
color="blue")
>>> hover = HoverTool(tooltips=None, mode='vline')
>>> p3.add_tools(hover)
Colormapping
Rows
>>> color_mapper = CategoricalColorMapper(
factors=['US', 'Asia', 'Europe'],
palette=['blue', 'red', 'green'])
>>> p3.circle('mpg', 'cyl', source=cds_df,
color=dict(field='origin',
transform=color_mapper),
legend='Origin'))
US
Asia
Europe
Columns
>>> from bokeh.layouts import row >>> from bokeh.layouts import columns
>>> layout = row(p1,p2,p3)
>>> layout = column(p1,p2,p3)
Nesting Rows & Columns
>>>layout = row(column(p1,p2), p3)
Grid Layout
Linked Plots
>>> from bokeh.layouts import gridplot
>>> row1 = [p1,p2]
>>> row2 = [p3]
>>> layout = gridplot([[p1,p2],[p3]])
Linked Axes
Tabbed Layout
>>> from bokeh.models.widgets import Panel, Tabs
>>> tab1 = Panel(child=p1, title="tab1")
>>> tab2 = Panel(child=p2, title="tab2")
>>> layout = Tabs(tabs=[tab1, tab2])
Also see Data
>>> p2.x_range = p1.x_range
>>> p2.y_range = p1.y_range
Linked Brushing
>>> p4 = figure(plot_width = 100, tools='box_select,lasso_select')
>>> p4.circle('mpg', 'cyl', source=cds_df)
>>> p5 = figure(plot_width = 200, tools='box_select,lasso_select')
>>> p5.circle('mpg', 'hp', source=cds_df)
>>> layout = row(p4,p5)
Legends
Legend Location
Inside Plot Area
Legend Orientation
>>> p.legend.location = 'bottom_left'
>>> p.legend.orientation = "horizontal"
>>> p.legend.orientation = "vertical"
>>> r1 = p2.asterisk(np.array([1,2,3]), np.array([3,2,1])
>>> r2 = p2.line([1,2,3,4], [3,4,5,6])
>>> legend = Legend(items=[("One" , [p1, r1]),("Two" , [r2])], location=(0, -30))
>>> p.add_layout(legend, 'right')
>>> p.legend.border_line_color = "navy"
>>> p.legend.background_fill_color = "white"
Outside Plot Area
4
Bar Chart
>>> from bokeh.charts import Bar
>>> p = Bar(df, stacked=True, palette=['red','blue'])
>>> from bokeh.io import output_notebook, show
>>> output_notebook()
Box Plot
Embedding
Standalone HTML
>>> from bokeh.models import ColumnDataSource
>>> cds_df = ColumnDataSource(df)
Label 1
Label 2
Label 3
Histogram
>>> from bokeh.embed import components
>>> script, div = components(p)
Scatter Plot
>>> show(p1)
>>> show(layout)
>>> from bokeh.charts import Histogram
>>> p = Histogram(df, title='Histogram')
Histogram
Components
5
>>> from bokeh.charts import BoxPlot
>>> p = BoxPlot(df, values='vals', label='cyl',
legend='bottom_right')
>>> from bokeh.embed import file_html
>>> html = file_html(p, CDN, "my_plot")
Show or Save Your Plots
x-axis
>>> save(p1)
>>> save(layout)
Also see Data
Bokeh’s high-level bokeh.charts interface is ideal for quickly
creating statistical charts
Notebook Output
>>> import numpy as np
>>> import pandas as pd
>>> df = pd.DataFrame(np.array([[33.9,4,65, 'US'],
[32.4,4,66, 'Asia'],
[21.4,4,109, 'Europe']]),
columns=['mpg','cyl', 'hp', 'origin'],
index=['Toyota', 'Fiat', 'Volvo'])
Legend Background & Border
Statistical Charts With Bokeh
Output
Output to HTML File
>>> from bokeh.io import output_file, show
>>> output_file('my_bar_chart.html', mode='cdn')
Also see Lists, NumPy & Pandas
>>> from bokeh.plotting import figure
>>> p1 = figure(plot_width=300, tools='pan,box_zoom')
>>> p2 = figure(plot_width=300, plot_height=300,
x_range=(0, 8), y_range=(0, 8))
>>> p3 = figure()
Hover Glyphs
Rows & Columns Layout
Under the hood, your data is converted to Column Data
Sources. You can also do this manually:
2 Plotting
>>> p = figure(tools='box_select')
>>> p.circle('mpg', 'cyl', source=cds_df,
selection_color='red',
nonselection_alpha=0.1)
y-axis
The Python interactive visualization library Bokeh
enables high-performance visual presentation of
large datasets in modern web browsers.
1 Data
>>> p1.circle(np.array([1,2,3]), np.array([3,2,1]),
fill_color='white')
>>> p2.square(np.array([1.5,3.5,5.5]), [1,4,3],
color='blue', size=1)
Line Glyphs
Plotting With Bokeh
Also see Data
Selection and Non-Selection Glyphs
Scatter Markers
Learn Bokeh Interactively at www.DataCamp.com,
taught by Bryan Van de Ven, core contributor
data
Customized Glyphs
Glyphs
>>> from bokeh.charts import Scatter
>>> p = Scatter(df, x='mpg', y ='hp', marker='square',
xlabel='Miles Per Gallon',
ylabel='Horsepower')
DataCamp
Learn Python for Data Science Interactively
O.3.6
SymPy
There are two notable Computer Algebra Systems (CAS) for Python:
SymPy a python module that can be used in any Python program, or in an IPython session, that
provides powerful CAS features.
SageMath a full–featured and very powerful CAS enviroment that aims to provide an open
source system that competes with Mathematica and Maple. SageMath is not a regular
Python module, but rather a CAS environment that uses Python as its programming language.
• SageMath is in some aspects more powerful than SymPy [21, Lecture-5], but both offer
very comprehensive CAS functionality.
• A good tutorial is in [21, Lecture-5]
O.4
Call FORTRAN, C and Matlab from Python
O.4.1
Call FORTRAN from Python
• Check [21, Lecture-6A]
O.4.2
Call C from Python
• [20] and [21, Lecture-6A]
O.4.3
Call MATLAB from Python
References
• [https://stackoverflow.com/questions/2883189/calling-matlabfunctions-from-python/23762412#23762412]
• [20]
Scipy.io can load/save .mat files
• does not require Matlab license
• may need to manipulate format after loading
OMPC ompc.juricap.com
• Converts existing Matlab functions to Python
• Does not require Matlab license
• Works for simple functions
504
pymatlab http://pymatlab.sourceforge.net/
• pure Python, no compilation, using ctypes (good)
• quite raw (ugly)
• memory leaks (bad)
matlab wrapper https://github.com/mrkrd/matlab_wrapper
• forked from pymatlab
• pure Python, no compilation, using ctypes (good)
• pure Python library and you will not need to compile anything.
mlabwrap http://mlabwrap.sourceforge.net/
• cool interface, mlab.sin() (good)
• needs compilation (bad)
• not much development (bad)
mlab https://github.com/ewiger/mlab
• similar interface to mlabwrap (good)
• using raw pipes (hmm)
• there is another very old package with the same name (ugly)
pymatbridge https://github.com/arokem/python-matlab-bridge
• actively developed (good)
• client–server architecture with ZeroMQ and JSON, complex (ugly)
• missing basic functions, there’s no put (bad)
• nice ipython notebook support (good)
754
O.4.4
Call Python from MATLAB
• Check www.mathworks.com/help/matlab/call-python-libraries.html
755
O.5
Python Alternatives
Project idea 31 (Explore the Julia Programming Language)
• Explore scientific equivalents to NymPy, SciPy, matplotlib and Spyder
756
Project idea 32 (Explore the R Programming Language)
R is a highly extensible language and environment for statistical computing and graphics.
[https://docs.microsoft.com/en-us/visualstudio/rtvs/]
505
• Distributed for free under the GNU General Public License,
• Enjoys strong community support,
• Can produce publication–quality plots including mathematical symbols and formulae.
506
Appendix P
Scientific Computing and Visualization using
Julia
Julia in a Nutshell∗
Julia is fast!
• Julia was designed from the beginning for high performance
• Julia programs compile to efficient native code for multiple platforms via LLVM†
758
What is Julia Language?
[www.infoworld.com/article/3241107/python/julia-vs-python-julialanguage-rises-for-data-science.html]
Created in 2009 by a four–person team and unveiled to the public in 2012, Julia is meant
to address the shortcomings in Python and other languages and applications used for scientific
computing and data processing. “We are greedy,” they wrote. They wanted more:
We want a language that’s open source, with a liberal license. We want the speed of
C with the dynamism of Ruby. We want a language that’s homoiconic, with true
macros like Lisp, but with obvious, familiar mathematical notation like Matlab.
We want something as usable for general programming as Python, as easy for
statistics as R, as natural for string processing as Perl, as powerful for linear
algebra as Matlab, as good at gluing programs together as the shell. Something
that is dirt simple to learn, yet keeps the most serious hackers happy. We want
it interactive and we want it compiled.
(Did we mention it should be as fast as C?)
Here are some of the ways Julia implements those aspirations:
Compiled, not interpreted, for speed. Julia is just–in–time‡ (JIT) compiled using the LLVM
compiler framework. At its best, Julia can approach or match the speed of C and Fortran.
Straightforward but useful syntax. Julia’s syntax is similar to Python’s—terse, but also expressive and powerful.
Dynamic typing with static type benefits. You can specify types for variables, like “unsigned
32–bit integer.” But you can also create hierarchies of types to allow general cases for
handling variables of specific types—for instance, to write a function that accepts integers
generally without specifying the length or signing of the integer. And, finally, you can do
without typing entirely if it isn’t needed in a particular context.
∗
[https://julialang.org/]
Low–Level Virtual Machine (LLVM) is a compiler infrastructure to build optimized intermediate and/or binary
machine code.
‡
Just–In–Time compilation occurs at run–time rather than prior to execution, which means it offers both the
speed of compiled code and the flexibility of interpretation. The compiler parses the code and infers types, after
which the LLVM code is generated, which in turn is compiled into native code.
†
507
Python, C, and Fortran libraries are just a call away. Julia can interface directly with external libraries written in C and Fortran. It’s also possible to interface with Python code by
way of the PyCall library, and even share data between Python and Julia.
Metaprogramming. Julia programs can generate other Julia programs, and even modify their
own code, in a way that is reminiscent of languages like Lisp.
[https://julialang.org/]
Julia is a high–level, high–performance dynamic programming language for numerical computing.
• It provides:
– a sophisticated compiler,
– distributed parallel execution,
– numerical accuracy, and
– an extensive mathematical function library.
• Julia’s Base library, largely written in Julia itself, also integrates mature, best–of–breed
open source C and Fortran libraries for:
– linear algebra,
– random number generation,
– signal processing, and
– string processing.
• IJulia, a collaboration between the Jupyter and Julia communities, provides a powerful
browser–based graphical notebook interface to Julia.
Why Julia?
• Modern alternative to Matlab.
• MIT licence and good documentation.
• Cross–platform
• Easy, student–friendly syntax.
• Fast execution thanks to LLVM.
• Extensive bindings to standard numerical libraries.
508
Summary of Features
https://julialang.org/
• Multiple dispatch: providing ability to define function behavior across many combinations
of argument types
• Dynamic type system: types for documentation, optimization, and dispatch
• Good performance, approaching that of statically–compiled languages like C
• Built–in package manager
• Lisp–like macros and other metaprogramming facilities
• Call Python functions: use the PyCall package
• Call C functions directly: no wrappers or special APIs
• Powerful shell–like capabilities for managing other processes
• Designed for parallelism and distributed computation
• Coroutines: lightweight “green” threading
• User–defined types are as fast and compact as built–ins
• Automatic generation of efficient, specialized code for different argument types
• Elegant and extensible conversions and promotions for numeric and other types
• Efficient support for Unicode, including but not limited to UTF–8
• MIT licensed: free and open source
761
Dynamic Type Systems∗
Type systems have traditionally fallen into two quite different camps:
1. static type systems
every program expression must have a type computable at compile time (before the execution of the program)
2. dynamic type systems
nothing is known about types until run time, when the actual values manipulated by the
program are available.
• Julia’s type system is dynamic, but gains some of the advantages of static type systems by
making it possible to indicate that certain values are of specific types.
• This can be of great assistance in generating efficient code, but even more significantly, it
allows method dispatch on the types of function arguments to be deeply integrated with
the language.
762
∗
[https://docs.julialang.org/en/v1/manual/types/#Composite-Types-1]
509
P.1
Learning Julia
Tutorials (Best is first)
1. From zero to Julia! (https://techytok.com/from-zero-to-julia/)
2. Refer to sec. P.7 for visualization tutorials
Cheat Sheets (Best is first)
• Julia Basics Cheat Sheet (www.datacamp.com/cheat-sheet/julia-basics-cheatsheet)
• Julia cheatsheet (https://cheatsheets.quantecon.org/julia-cheatsheet.html)
• The Fast Track to Julia; A quick and dirty overview of Julia (https://juliadocs.
github.io/Julia-Cheat-Sheet/)
• MATLAB–Python–Julia Cheatsheet (https://cheatsheets.quantecon.org/)
• The Julia Express (https://github.com/bkamins/The-Julia-Express)
Recommended Books (Best is first)
1. Jose Storopoli, Rik Huijzer and Lazaro Alonso, Julia Data Science, October 2021 [24]
• Seems brief and concise
• Available freely at https://juliadatascience.io
• Includes excellent visualizations using the sophisticated Makie.jl visualization package
2. Erik Engheim, Julia for Beginners∗ , January 2021 [25]
• Uses the REPL; not the IDE
• Seems detailed and covers advanced topics including OOP
• No information on visualizations nor scientific computing
• You can think about this book as a brief and well organized version of the manual
3. Ben Lauwens and Allen Downey, Think Julia: How to Think Like a Computer Scientist,
O’Reilly Media, April 2019
• Available online @
latest/book.html
https://benlauwens.github.io/ThinkJulia.jl/
510
Courses
The following courses seem useful:
• Scientific Programming in Julia (https://juliateachingctu.github.io/
Scientific-Programming-in-Julia/stable/)
• Julia for Optimization and Learning (https://juliateachingctu.github.io/
Julia-for-Optimization-and-Learning/stable/)
Noteworthy differences from MATLAB [26]
• Julia arrays are indexed with square brackets, A[i,j] .
• Julia arrays are not copied when assigned to another variable. After A = B , changing
elements of B will modify A as well. To avoid this, use A = copy(B) .
• Julia values are not copied when passed to a function. If a function modifies an array, the
changes will be visible in the caller.
• Julia does not automatically grow arrays in an assignment statement. Whereas in MATLAB a(4)= 3.2 can create the array a = [0 0 0 3.2] and a(5)= 7 can grow it into
a = [0 0 0 3.2 7], the corresponding Julia statement a[5] = 7 throws an error if
the length of a is less than 5 or if this statement is the first use of the identifier a. Julia
has push! and append! , which grow Vectors much more efficiently than MATLAB’s
a(end+1) = val.
• The imaginary unit sqrt(-1) is represented in Julia as im , not i or j as in MATLAB.
• In Julia, literal numbers without a decimal point (such as 42) create integers instead of
floating point numbers. As a result, some operations can throw a domain error if they
expect a float; for example, julia> a = -1; 2^a throws a domain error, as the result
is not an integer.
• In Julia, multiple values are returned and assigned as tuples, e.g. (a, b)= (1, 2) or
a, b = 1, 2 . MATLAB’s nargout , which is often used in MATLAB to do optional
work based on the number of returned values, does not exist in Julia. Instead, users can
use optional and keyword arguments to achieve similar capabilities.
• Julia has true one–dimensional arrays. Column vectors are of size N, not Nx1. For example,
rand(N) makes a 1–dimensional array.
• In Julia, [x,y,z] will always construct a 3-element array containing x, y and z.
– To concatenate in the first “vertical” dimension use either vcat(x,y,z) or separate
with semicolons [x; y; z] .
– To concatenate in the second “horizontal” dimension use either hcat(x,y,z) or
separate with spaces [x y z] .
∗
[https://leanpub.com/julia-for-beginners]
511
– To construct block matrices (concatenating in the first two dimensions), use either
hvcat or combine spaces and semicolons [a b; c d] .
• In Julia, a:b and a:b:c construct AbstractRange objects. To construct a full vector
like in MATLAB, use collect(a:b) . Generally, there is no need to call collect
though. An AbstractRange object will act like a normal array in most cases but is more
efficient because it lazily computes its values. This pattern of creating specialized objects
instead of full arrays is used frequently, and is also seen in functions such as range , or
with iterators such as enumerate, and zip. The special objects can mostly be used as if
they were normal arrays.
• Functions in Julia return values from their last expression or the return keyword instead
of listing the names of variables to return in the function definition.
• A Julia script may contain any number of functions, and all definitions will be externally
visible when the file is loaded. Function definitions can be loaded from files outside the
current working directory.
• In Julia, reductions such as sum , prod , and max are performed over every element of
an array when called with a single argument, as in sum(A) , even if A has more than one
dimension.
• In Julia, parentheses must be used to call a function with zero arguments, like in rand() .
• Julia discourages the use of semicolons to end statements. The results of statements are
not automatically printed (except at the interactive prompt), and lines of code do not need
to end with semicolons. println or @printf can be used to print specific output.
• In Julia, if A and B are arrays, logical comparison operations like A == B do not return
an array of booleans. Instead, use A .== B , and similarly for the other boolean operators
like <, >.
• In Julia, the operators &, |, and v (xor) perform the bitwise operations equivalent to
and, or, and xor respectively in MATLAB, and have precedence similar to Python’s
bitwise operators (unlike C). They can operate on scalars or element-wise across arrays
and can be used to combine logical arrays, but note the difference in order of operations: parentheses may be required (e.g., to select elements of A equal to 1 or 2 use
(A .== 1).| (A .== 2) .
• In Julia, the elements of a collection can be passed as arguments to a function using the
splat operator “...”, as in xs=[1,2]; f(xs...) .
• Julia’s svd returns singular values as a vector instead of as a dense diagonal matrix.
• In Julia, “...” is not used to continue lines of code. Instead, incomplete expressions
automatically continue onto the next line.
• In both Julia and MATLAB, the variable ans is set to the value of the last expression
issued in an interactive session. In Julia, unlike MATLAB, ans is not set when Julia code
is run in non-interactive mode.
512
• Julia’s structs do not support dynamically adding fields at runtime, unlike MATLAB’s
classes. Instead, use a Dict. Dict in Julia isn’t ordered.
• In Julia each module has its own global scope/namespace, whereas in MATLAB there is
just one global scope.
• In MATLAB, an idiomatic way to remove unwanted values is to use logical indexing, like
in the expression x(x>3) or in the statement x(x>3)= [] to modify x in-place. In
contrast, Julia provides the higher order functions filter and filter!, allowing users
to write filter(z->z>3, x) and filter!(z->z>3, x) as alternatives to the corresponding transliterations x[x.>3] and x = x[x.>3] . Using filter! reduces the use
of temporary arrays.
• The analogue of extracting (or “dereferencing”) all elements of a cell array, e.g. in
vertcat(A{:}) in MATLAB, is written using the splat operator in Julia, e.g. as
vcat(A...) .
• In Julia, the adjoint function performs conjugate transposition; in MATLAB, adjoint
provides the “adjugate” or classical adjoint, which is the transpose of the matrix of cofactors.
• In Julia, a^b^c is evaluated a^(b^c) while in MATLAB it’s (a^b)^c.
767
P.2
Julia vs Python
[www.infoworld.com/article/3241107/python/julia-vs-python-julia-languagerises-for-data-science.html]
Julia vs. Python
• MATLAB–Python–Julia cheatsheet (https://cheatsheets.quantecon.org/)
Of the many use cases Python covers, data analytics has become perhaps the biggest and most
significant. The Python ecosystem is loaded with libraries, tools, and applications that make the
work of scientific computing and data analysis fast and convenient.
But for the developers behind the Julia language — aimed specifically at “scientific computing, machine learning, data mining, large–scale linear algebra, distributed and parallel
computing”—Python isn’t fast or convenient enough. It’s a trade–off, good for some parts of
this work but terrible for others.
Julia Advantages
Julia was designed from the start for scientific and numerical computation. Thus it’s no surprise
that Julia has many features advantageous for such use cases:
• Faster by default. Julia’s JIT compilation and type declarations mean it can routinely
beat “pure,” unoptimized Python by orders of magnitude.
• A math–friendly syntax. Julia’s syntax for math operations looks more like the way math
formulas are written outside of the computing world.
513
768
• Automatic memory management. Like Python, Julia doesn’t burden the user with the
details of allocating and freeing memory.
• Parallelism. Both Python and Julia can run operations in parallel. But Julia’s syntax is
slightly less top–heavy than Python’s, lowering the threshold to its use.
Python Advantages
Python is a general–purpose computing language that is easy to learn, and that has developed
into a leading language for scientific computing. Some of the reasons Python may still be the
better choice for data science work:
• Julia is still young. It still doesn’t have a 1.0 release, although the developers are getting
close.
• Python has far more third–party packages. Again, Julia’s relative newness means the
culture of software around it is still small.
• Python’s huge community is a huge advantage.
P.3
Julia REPL
Julia REPL stands for Read--Eval--Print Loop
Types
Any
...
P.4
Tuples
They are same as comma–separated–lists of Matlab [sec. 4.4.1]
514
P.5
Methods of a Function
Methods of a Function∗
• It is common for the same conceptual function or operation to be implemented quite differently for different types of arguments: adding two integers is very different from adding
two floating–point numbers, both of which are distinct from adding an integer to a floating–
point number. Despite their implementation differences, these operations all fall under the
general concept of "addition". Accordingly, in Julia, these behaviors all belong to a single
object: the + function.
• To facilitate using many different implementations of the same concept smoothly, functions need not be defined all at once, but can rather be defined piecewise by providing
specific behaviors for certain combinations of argument types and counts. A definition of
one possible behavior for a function is called a method.
772
Multiple Dispatch†
The choice of which method to execute when a function is applied is called dispatch.
• Julia allows the dispatch process to choose which of a function’s methods to call based on
the number of arguments, and their individual types
– This is called multiple dispatch
– This is different than traditional OOP, where dispatch occurs based only on the first
argument, single dispatch, which often has a special argument syntax, and is sometimes implied rather than explicitly written as an argument.
• Multiple dispatch enables achieving high performance, as the compiler can generate specialized code for different combinations of argument types
773
JuliaCon 2019; The Unreasonable Effectiveness of Multiple Dispatch‡
If you’re familiar with Julia and its ecosystem, you may have noticed something lovely but
a bit puzzling: there seems to be an unusually large amount of code reuse between packages
compared to other seemingly similar languages. This sharing of code comes in two forms:
1. Sharing basic types among a wide variety of packages providing disparate functionality;
2. Sharing generic algorithms that work on various implementations of common abstractions.
• Why does generic code in Julia “just work”?
• Why do Julia packages seem to share types with so little friction?
• Both kinds of reuse are supposed to be natural benefits of class–based OOP languages
∗
[https://docs.julialang.org/en/v1/manual/methods/]
[https://docs.julialang.org/en/v1/manual/methods/]
‡
www.youtube.com/watch?v=kc9HwsxE1OY&list=PLP8iPy9hna6StY9tIJIUN3F_co9A0zh0H&index=
6&t=135s
†
515
• After all, inheritance and encapsulation are two of the four pillars of OOP
• Even more puzzling is that Julia has no encapsulation and doesn’t allow inheriting from
concrete types at all.
– Yet both kinds of code reuse are rampant. What is going on?
• In this talk, I make the case that both of kinds sharing stem directly from Julia’s multiple
dispatch programming paradigm.
P.6
OOP
• Julia has no encapsulation
• Julia doesn’t allow inheriting from concrete types
• Julia opts to have structs be immutable by default than to hide the members
– That is, properties cannot have attributes such as private, protected
– But a property can be constant
∗ By definition, a constant property is static
• Ploymorphism is achieved by multiple dispatch
• Or in other words, multiple dispatch is the OO concept of choice for Julia
• [25] (book no 2)
– Julia was not designed to be an OO language
∗ However that does not mean that you cannot apply OO principles and practices
to Julia code
– If this book was only written for people without any prior programming experience,
then this chapter would most likely not exist. There is no particular good reason why
a Julia developers should learn to think OO.
∗ However we must deal with reality. Like perhaps most developers today, I have
spent years steep in OO thinking as it has been the most dominant paradigm for
decades.
∗ If you have struggled for years to grasp OOP and then suddenly get thrown into
a new language where OO thinking isn’t central, it can be disorienting.
– The purpose of this chapter is to help developers with extensive OO experience reuse
and adapt their skills to Julia.
– Continue reading this chapter
516
Composite Type∗
Composite type is a synonym for record, or struct but not class, in other programming
languages.
• Same as mainstream OO languages† , composite types have properties
• Unlike mainstream OO languages, functions are not bundled‡ with composite types
– Alternatively, Julia uses multiple dispatch
775
P.7
Visualization
Visualization∗
As usual with FOSS, there are several alternatives for data visualization with various trade–offs
between features and simplicity, speed and beauty, and a static and dynamic interface. As of
April 2022;
• Plots.jl is a visualization interface and toolset
– It provides a common API across various backends, like GR.jl, PyPlot.jl, and PlotlyJS.jl
– If one backend does not support your desired features, you can switch to another
backend with one command
∗ No need to change your code or
• Makie.jl is a sophisticated package for complex graphics and animations
– [24] (recommended book no. 1) adopts Makie.jl
• Users who are used to "grammar of graphics" plotting APIs should take a look at Gadfly.jl
• VegaLite.jl provides the Vega–Lite grammar of interactive graphics interface as a Julia
package
• For those who do not wish to leave the comfort of the terminal, there is also UnicodePlots.jl
∗
[https://docs.julialang.org/en/v1/manual/types/#Composite-Types-1]
such as C++, Java, Python and Ruby
‡
This is why the composite type is analogous to struct rather than class.
∗
[https://julialang.org/#tab-viz]
†
517
†
Plots Tutorial
https://docs.juliaplots.org/latest/tutorial/ seems excellent (concise and comprehensive).
P.8
Tutorial
P.9
Variables
If we want to really simplify what a program is and what it does, we may say that a program is a
series of instructions to be performed on various kind of data. Such data may be the name of a
place, the height of a person or a series of measurements made by a scientist. In programming,
when we want to “label” a piece of information we give it a name and call it a variable, so we
may say that a variable is a box which contains some kind of data.
In Julia, when we want to assign some data to a variable, we do it by typing:
1 my_name = "Aurelio"
†
[https://discourse.julialang.org/t/what-are-the-biggest-differences-between-makiejl-and-plots-jl/76643/6]
518
2 my_favourite_number = 42
3 my_favourite_pie = 3.1415
Here my name contains a string, which is a piece of text, while my favourite number contains an integer and my favourite pie a floating point number. Contrary to other programming
languages like C++ and similarly to Python, Julia can infer the type of the object on the right
side of the equal sign, so there is no need to specify the type of the variable as you would do in
C++.
If we want to print the value of a variable, we use print:
1 >>>print(my_name)
2 Aurelio
It is possible to perform mathematical operations on numbers and variables and assign the
results to new variables:
1
2
3
4
5
6
7
8
a = 2
b = 3
sum = a + b
difference = a - b
product = a * b
quotient = b / a
power = a^3
modulus = b % a
It is also possible to use rational numbers, if it is needed for exact numerical computations,
and they take the form of numerator//denominator, e.g. 1//3.
For a complete list of the mathematical operations see the official guide.
P.10
Types
In Julia every element has a type. The type system is a hierarchical structure: at the top of the
tree there is the type Any, which means that every element belongs to it, then there are many
other sub-types, for example Number which includes Real and Complex, and Real contains for
example Int (integer) numbers and Float64 numbers.
519
We will deal with types again later, for now what we need to remember is that since every
variable has a type (which can be inferred by the compiler or specified by the programmer),
Julia can build machine code optimised for the specific types which are being used. This is one
of the main reasons why Julia is a really fast language! Furthermore, we can expect that if a
function can work on a Type, for example a Number, it will also work on all of its Subtypes,
like Float64 or Int64.
To determine the type of a variable, we can use the typeof function:
1
2
3
4
5
6
>>>typeof(0.1)
Float64
>>>typeof(42)
Int64
>>>typeof("TechyTok")
String
Although it is possible to change the value of a variable inside a program (it is a variable, after
all) it is good programming practice and is also critical for performance that inside a program
a variable is “type stable”. This means that if we have assigned a = 42 it is better not to
assign a new value to a which cannot be converted into an Int without losing information, like
a Float64 a = 0.42 (if we convert a Float64 to an Int, the decimal part gets truncated).
If we know that a variable (such as a) will have to contain values of type Float64 it is better
to initialise it with a value that is already of that type.
1 a = 2 # if we need to operate with ints
2 b = 2.0 # if we need to operate with floats
It is possible, if needed, to convert a value from a type to another using the function convert,
for example:
1
2
3
4
>>>convert(Float64, 2)
2.00
a = 2
b = convert(Float64, a)
520
5
6
7
8
>>>a
2
>>>b
2.00
P.11
Functions
Functions are the main building blocks in Julia. Every operation on variables and other elements
is performed through functions, even the mathematical operators that we have seen in the chapter
before are functions in an infix form.
If we want to simplify what a function is, we can picture it as a box which can optionally
take an input, performs some operations and returns an output of some sort.
P.11.1
Defining functions
A typical function looks like this:
1 function plus_two(x)
2
#perform some operations
3
return x + 2
4 end
A function starts with the word function and ends with end.
Please notice the indentation of the body of the function (lines 2 and 3): the body of a function (and many other constructs in Julia) must be indented. Although the number of indentation
spaces is not strictly fixed, it is a conventional rule to indent by four spaces.
In Julia the indentation rules are not as strict as in Python, nonetheless it is recommended
that you don’t mix tabs and spaces while indenting you code, and tabs are usually discouraged
as they may lead to problems when switching from one operating system to another.
Please notice that every “block” of code ends with an end, this way you can always know
when something starts and ends.
Although this is the most common way to write functions, it is sometimes convenient to use
the inline version:
1
plus_two(x) = x+2
It is also possible to create anonymous functions (like lambdas in Python) using the following
structure:
1
plus_two = x -> x+2
It is not recommended to use anonymous functions unless they are really simple. It is
generally better to write functions in the first or second way unless you need to write a small
wrapper around another function and pass it to a third function.
The following example is a bit more advanced and it includes topics which we have not yet
studied, like integrals and how to install and use an external package. You can always come back
later to read this example as it is not fundamental at this point of the course but you may find it
useful one day. The take home message is never use anonymous functions unless you know
what you are doing.
521
P.11.2
More on anonymous functions
For example, let’s consider a function f of three variables x, y and z. Let’s suppose we want to
fix two variables (y and z) and integrate f over x, we could do it with:
1
2
3
4
5
using Pkg
Pkg.add("QuadGK")
using QuadGK
f(x,y,z) = (x^2 + 2y)*z
quadgk(x->f(x,42,4), 3, 4)
but we could have also written:
1
2
3
4
5
6
using Pkg
Pkg.add("QuadGK")
using QuadGK
f(x,y,z) = (x^2 + 2y)*z
arg(x) = f(x,42,4)
quadgk(arg, 3, 4)
and the result would have been the same, furthermore, in my opinion, the latter is a cleaner
way to write integrals, especially if we wrap everything inside another function:
1 f(x,y,z) = (x^2 + 2y)*z
2 function integral_of_f(y,z)
3
arg(x) = f(x,y,z)
4
result = quadgk(arg, 3, 4)
5
return result
6 end
Functions can be defined inside other functions, which is really useful to make the code
more readable. Avoid writing long functions inside other functions, but use small lightweight
functions if needed (think of them as if they were aliases to make the code more readable and
simple to maintain). When we define a function inside another function, we can use simpler and
shorter names (like arg or f) without the risk of having overlapping functions and unexpected
behaviour.
P.11.3
Void functions
Functions may also take no arguments and return no value, if needed, for example we can create
a function which prints a string:
1 function say_hi()
2
println("Hello from TechyTok!")
3
return
4 end
If the function returns no value the return can be omitted. In general it is also possible
to omit the return statement even in regular functions and Julia will return the last computed
value. However, in my opinion, in this case it is better to return explicitly a value, for clarity’s
sake.
522
P.11.4
Optional positional arguments
Sometimes a parameter may have a default value which can be specified so that the user doesn’t
need to always type it. For example let’s write a function which converts our “weight” as measured on Earth (in kg) to the one measured on another planet.
1 function myWeight(weightOnEarth, g=9.81)
2
return weightOnEarth*g/9.81
3 end
If the user types myWeight(60) and doesn’t specify g, he or she will get his/her weight as
measured on Earth:
1 >>>myWeight(60)
2 60
If I specify the gravitational acceleration g on another planet (let’s say Mars)
1 >>>myWeight(60, 3.72) # https://en.wikipedia.org/wiki/Gravity_of_Mars
2 22.75
I get my weight on Mars! Pretty light, isn’t it?
As the name suggests positional arguments must be used in the right order, we cannot
specify g before weightOnEarth and, as opposed to other languages like Python, in Julia we
cannot change the order of the arguments even if we specify the name of the parameter. If we
want optional arguments with no fixed position, we need to use keyword arguments.
P.11.5
Keyword arguments
Let’s say we have a function which takes many optional parameters, it might become cumbersome for the user to remember the right order. That’s the case where keyword arguments come
in handy!
Keyword arguments are separated from positional arguments by a semicolon ; and must
always be addressed by their name, although their order is irrelevant. They can be either optional
and not, but usually we use keyword arguments for optional parameters.
1 function my_long_function(a, b=2; c, d=3)
2
return a + b + c + d
3 end
Here a and b are positional arguments, while c and d are keyword arguments.
1
2
3
4
5
6
7
8
>>>my_long_function(1, c=3)
9
>>>my_long_function(1, 2, c=3)
9
>>>my_long_function(1, 2, d=5, c=3)
11
>>>my_long_function(1, 2, d=5)
ERROR: UndefKeywordError: keyword argument c not assigned
As you can see, even if c is a keyword argument, it must always be specified!
523
P.11.6
Performance tip
It is preferable to use positional arguments whenever high performance is required (for example
when writing functions which need to be called many times), it is always possible to write a
wrapper to a function (or a method of the function) which uses keyword arguments, if needed,
as we will see later on when we deal with multiple dispatch.
P.11.7
Function documentation
It is possible to get information on a function by typing in the REPL ? functionName, this will
fetch the documentation for that function, if available, or it will print some information which
the compiler is able to infer.
For example if we query the documentation of the sin function with ? sin we get this
output:
It is also possible to write the documentation of your functions in the following way:
1
2
3
4
5
6
"""
Description of the function
"""
function foo(x)
#... function implementation
end
You can find more information on how to write the code documentation in the lesson on
modules and at the official documentation.
P.12
Arrays
P.12.1
Vectors
A vector is a list of ordered data which share a common type (be it Int, Float or Any). Furthermore a vector is a one–dimensional array, and often “vector” and “array” are used a synonyms.
Contrarily to the mathematical definition of a vector, in programming a vector is simply a
list of values and has no a priori geometrical meaning.
524
In Julia, to create a vector we use the following syntax:
1 a = [1,2,3,4,5]
2 b = [1.2, 3,4,5]
3 c = ["Hello", "it’s me", "TechyTok"]
We can access the members of an array using the indexing syntax: array_name[element_number] , for example, if we want to retrieve the third element of
c we type c[3]. Contrarily to other programming languages, in Julia vectors start at 1, there
is not much to say, it is just like that.
If you want to append an element to an array, we can do it by using the append! function.
Notice the !, this is a Julia convention to say that the function will modify the first argument
given to the function, in fact append!(a, 6)results in a = [1, 2, 3, 4, 5, 6] .
Previously I have said that vector elements must share the same type, if we try to append (or
add) a value to an array with a different type it will result into an error:
1
2
3
4
5
6
7
>>>append!(a, 3.14)
ERROR: InexactError: Int64(2.3)
Stacktrace:
[1] Type at .\float.jl:703 [inlined]
[2] convert at .\number.jl:7 [inlined]
[3] setindex! at .\array.jl:766 [inlined]
[4] _append!(::Array{Int64,1}, ::Base.HasShape{0}, ::Float64) at .\array.
jl:907
8 [5] append!(::Array{Int64,1}, ::Float64) at .\array.jl:899
9 [6] top-level scope at none:0
In this case, we cannot convert a Float64 to an Int64 without losing precision, thus the
error.
To check the type of an array we can type:
1 >>>typeof(a)
2 Array{Int64, 1}
As we can see, a can only store Int64 values or values that can be safely converted to Int64
(such as Int32 for example).
An alternative way to define a Vector, if we want to specify the type of the elements included,
is by using a type name followed by a square bracket and the desired elements:
1 d = Int[1,2,3,4,5]
P.12.2
Matrices
Matrices are two dimensional arrays. We can define a matrix with the following syntax:
1 mat1 = [1 2 3; 4 5 6]
Rows are separated by semi colons ; and columns are separated by spaces.
When we want to access the elements of a matrix, we use the following notation
mat1[row_index, column_index] . If we want to access the 2nd element of the first row
we shall write mat1[1, 2].
525
P.12.3
N–dimensional Arrays
Sometimes we need to create tables with more than 2 dimensions. In this case usually the tables
tend to be big, so there is no explicit way to create an n–dimensional array. The suggested
practice is to create an empty array first, using a new function called zeros, and then fill it
either manually of using a loop.
For example, let’s suppose we want to create a 2x3x4 table, we would do it with
zeros(2,3,4). Let’s suppose we want to fill it with the product of the indexes, we can do
it in the following way:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
table = zeros(2,3,4)
for k in 1:4
for j in 1:3
for i in 1:2
table[i,j,k] = i*j*k
end
end
end
>>>table
234 Array{Float64,3}:
[:, :, 1] =
1.0 2.0 3.0
2.0 4.0 6.0
[:, :, 2] =
2.0 4.0 6.0
4.0 8.0 12.0
[:, :, 3] =
3.0 6.0 9.0
6.0 12.0 18.0
[:, :, 4] =
4.0 8.0 12.0
8.0 16.0 24.0
Please not that Julia stores values in memory differently from Python: in Julia to obtain fast
loops we need to iter first over columns (which means that the first index must vary first and so
on). For this reason if we plan to store, for example, 42 2x2 matrices, we need to create an array
of size 2x2x42 (while in Python we would have created a 42x2x2 table).
P.12.4
Slices
There is a convenient notation (called slicing) to access a subset of elements from an array. Let’s
suppose we want to access the 2nd to 5th elements of an array of length 6, we can do it in the
following way:
1 a = [1,2,3,4,5,6]
2 b = a[2:5]
We can also use this notation to access a subset of a matrix, for example:
1 mat1 = reshape([i for i in 1:16],4,4)
2 mat2 = mat1[2:3, 2:3]
526
3
4
5
6
7
8
9
10
11
12
>>>mat1
44 Array{Int64,2}:
1 5 9 13
2 6 10 14
3 7 11 15
4 8 12 16
>>>mat2
22 Array{Int64,2}:
6 10
7 11
On line 1 we have used a handy notation called list comprehension. [i for i in 1:16]
means “create a vector containing each i comprised from 1 to 16”. We then reshape it to have
a size of 4x4 and store the result in mat1.
It is also possible to have nested list comprehensions like this one:
1 [i+j for i in 1:10 for j in 1:5]
This will create a vector of length 50 containing all the sums of i+j.
P.12.5
Views
If we assign an array a to b with b=a, rewrite:
1
2
3
4
5
a=[1,2,3]
b=a
b[2] = 42
>>>print(a)
[1, 42, 3]
This is particularly useful because it lets us save memory, but may have undesirable effects.
If we want to make a copy of an array we need to use the function copy
1
2
3
4
5
6
7
a=[1,2,3]
b=copy(a)
b[2] = 42
>>>print(a)
[1,2,3]
>>>print(b)
[1, 42, 3]
In some cases, when there are arrays containing other arrays, if we want to make a full copy
of all the contents we need to use deepcopy instead.
P.12.6
Tuples
A tuple is a fixed size group of variables.
Unlike arrays, you cannot increase the size of a tuple once it has been created. Tuples are
created using the following syntax:
1 a = (1,2,3)
2 b = 1, 2, 3
527
So tuples can be created by using regular brackets or no brackets at all! Tuples are really
handy, as it is possible to “unpack” a tuple over many values:
1
2
3
4
tuple1 = (1, 2, 3)
a, b, c = tuple1
>>>print("a=$a b=$b c=$c")
a=1 b=2 c=3
——————————–
I take this occasion to introduce string interpolation. With the indication $x we tell Julia that
it must substitute to $x the value of x, in this case 42. This is particularly useful when we want
to print values, or we want to make custom messages:
name1 = "traveler"
name2 = "techytok"
print("Welcome $name1, this is $name2 :)")
—————————
It is also possible to use tuples to emulate multiple return values from functions:
1
2
3
4
5
6
function return_multiple()
return 42, 43, 44
end
a, b, c = return_multiple()
>>>print("a=$a b=$b c=$c")
a=42 b=43 c=44
P.12.7
Splatting
It is possible to “unpack” a tuple and pass its arguments to a function with the following syntax:
1
2
3
4
5
6
function splat_me(a, b, c)
return a*b*c
end
tuple1 = (1,2,3)
>>>splat_me(tuple1...)
6
So the ... after a tuple will unpack it! This is useful but addictive, use it only if needed as
it is better for clarity (and to avoid multiple dispatch errors) to call a function with its single
parameters.
P.12.8
Named tuples
Named tuples are like tuples but with a name identifier for a single value, for example:
1
2
3
4
>>>namedTuple1 = (a = 1, b = "hello")
(a = 1, b = "hello")
>>>namedTuple1[:a]
1
or in alternative:
528
1
2
3
4
>>>namedTuple2 = NamedTuple{(:a, :b)}((2,"hello2"))
(a = 2, b = "hello2")
>>>namedTuple2[:b]
hello2
P.12.9
Dictionaries
A dictionary is a collection of keys and values. They are unordered (which means that the order
of the keys is random) and are really useful when you need to organise, for example, a dataset.
Let’s suppose we want to create an address book. A single entry should be able to store all
the fundamental characteristics needed to identify a friend: the name of the contact, the phone
number and the shoe size!
1 person1 = Dict("Name" => "Aurelio", "Phone" => 123456789, "Shoe-size" =>
40)
2 person2 = Dict("Name" => "Elena", "Phone" => 123456789, "Shoe-size" =>
36)
I can even make a dictionary containing other dictionaries:
1 addressBook = Dict("Aurelio" => person1, "Elena" => person2)
We can add another friend to the addressBook using the following syntax:
1 person3 = Dict("Name" => "Vittorio", "Phone" => 123456789, "Shoe-size" =>
42)
2 addressBook["Vittorio"] = person3
3 print(addressBook)
P.13
Control Flow
In this lesson we will learn how to work with control statements. We will first learn how to use
conditional blocks like if ... else blocks and then we will learn how to perform loops.
P.13.1
If . . . else
When a program needs to take decisions according to certain conditions, the if ... else
block is the default choice.
Let’s suppose that we want to write a simple implementation of the absolute value of a number. The absolute value of a number is defined as the number itself, if the number is positive, or
the opposite if the value is negative. This is the typical case where the if ... else construct
is useful! We can write a simple absolute function in this way:
1 function absolute(x)
2
if x >= 0
3
return x
4
else
5
return -x
6
end
7 end
529
As you can see, an if ... else block is closed with the word end, like a function.
If we need to check more than one condition, we can bind together conditions using:
“and” is written as & (if both statements are true return true, else return false)
“or” is written as || (if at least one statement is true return true, else return false)
For example, if we want to check whether 3 is both lower than 4 and greater than 1 we type:
1 if 1 < 3 & 3 < 4
2
print("eureka!")
3 end
If we want to check if a value satisfies one of several different conditions, we can use the
elseif statement: Julia will check if the first condition specified in the if is satisfied, if it is
not met it moves on to the first elseif and so on.
1
2
3
4
5
6
7
8
9
10
11
x = 42
if x<1
print("$x < 1")
elseif x < 3
print("$x < 3")
elseif x < 100
print("$x < 100")
else
print("$x is really big!")
end
>>> 42 < 100
P.14
Loops
P.14.1
For loops
Sometimes we want to iterate over a list of values and perform some operation on each element.
For example let’s suppose we want to print all the squares of the numbers between 1 and 10,
we can do it using a for loop:
1 for i in 1:10
2
println(i^2)
3 end
i is the variable which contains the data which gets updated at each new cycle, while 1:10
is a range. A range is an iterable object which does exactly what its name suggests: it specifies
the range on which the loop has to be performed (in this case 1 to 10).
It is also possible to use the alternative notation for i = 1:10 which is completely equivalent.
Please notice that it is possible to loop not only over ranges (which can also be specified
using the range function) but also lists (i.e. arrays, tuples, etc).
For example, let’s suppose we have a list of persons and we want to greet all of them, we can
do it with the for statement:
1 persons = ["Alice", "Bob", "Carla", "Daniel"]
2 for person in persons
3
println("Hello $person, welcome to techytok!")
530
4 end
Here instead of a range, we iterate over the elements of persons and in this case person
will hold the name of a single person, which changes at each iteration step.
For more informations on arrays and collection types, please refer to this lesson.
P.14.2
Break
In the case we want to forcefully interrupt a for loop we can use the break statement, for example:
1 for i in 1:100
2
if i>10
3
break
4
else
5
println(i^2)
6
end
7 end
Here we check if i>10 , in that case we break the loop and finish the iteration, else we
print i^2 .
P.14.3
Continue
This is the opposite of break, continue will forcefully skip the current iteration and move to
the next cycle:
1 for i in 1:30
2
if i % 3 == 0
3
continue
4
else
5
println(i)
6
end
7 end
This loop prints all the numbers from 1 to 30 except the multiples of 3.
P.14.4
While loop
When a loop needs to continue until a certain condition is met, a while loop is the preferable
choice:
1 function while_test()
2
i=0
3
while(i<30)
4
println(i)
5
i += 1
6
end
7 end
531
P.14.5
Enumerate
enumerate is a feature which comes in handy when we need to iterate on an array (or similar)
and we need to keep track of the number of iterations we have already performed.
enumerate will return an iterator (which is something like an array which can be iterated in
for loops). It will produce couples of the form (i, x[i]).
For example:
1
2
3
4
5
6
7
x = ["a","b","c"]
for couple in enumerate(x)
println(couple)
end
(1, "a")
(2, "b")
(3, "c")
The same result could have been obtained “manually”:
1
2
3
4
5
6
7
8
x = ["a","b","c"]
enum_array = [(1,"a"), (2,"b"), (3,"c")]
for i in 1:length(x)
println(enum_array[i])
end
(1, "a")
(2, "b")
(3, "c")
Let’s say we want to read the elements from an array, square them and store them in another
array, we can do it in this way:
1
2
3
4
5
6
7
my_array1 = collect(1:10)
my_array2 = zeros(10)
for (i, element) in enumerate(my_array1)
my_array2[i] = element^2
end
>>>print(my_array2)
[1.0, 4.0, 9.0, 16.0, 25.0, 36.0, 49.0, 64.0, 81.0, 100.0]
For comparison, we could have written the same loop in the following way:
1
2
3
4
5
6
7
my_array1 = collect(1:10)
my_array2 = zeros(10)
for i in 1:length(my_array1)
my_array2[i] = my_array1[i]^2
end
>>>print(my_array2)
[1.0, 4.0, 9.0, 16.0, 25.0, 36.0, 49.0, 64.0, 81.0, 100.0]
For more information on iterators and the enumerate function, please refer to this documentation page.
532
P.15
Working with arrays: broadcasting
Many languages (such as Python with numpy and Matlab) make extensive use of optimised C
or Fortran routines under the hood to perform fast mathematical operations. As such the user is
encouraged to write vectorised code, so that these routines can perform faster.
In Julia, since for loops are already as fast as they can be (close to the speed of C), there is no
need to write vectorised code, as the interpreter will directly compile your code in optimised
machine code which will run as fast as possible on your machine. In Julia nothing happens
under the hood (beside the compilation of the functions).
P.16
Operations with arrays
Julia by default deals with operations on arrays and matrices as one would do in mathematics.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
a = [1,2,3] # is a vector
b = [4,5,6] # is a vector
>>> a*b
ERROR: MethodError: no method matching *(::Array{Int64,1}, ::Array{Int64
,1})
c = [4 5 6] # is a row matrix
>>> a*c
33 Array{Int64,2}:
4 5 6
8 10 12
12 15 18
>>> c*a
1-element Array{Int64,1}:
32
d = reshape([1,2,3,4,5,6,7,8,9],3,3)
>>> d*a
3-element Array{Int64,1}:
30
36
42
This makes perfectly sense from a mathematical point of view and operators behave how we
would mathematically expect. Nonetheless, in programming it is often useful to write operations
which work on an element by element basis, and for this reason broadcasting comes to our help.
P.17
Broadcasting
In Julia, with broadcasting we indicate the action of mapping a function or an operation over
an array element by element.
The broadcasting notation for operators consists of adding a dot . before the operator (for
example .*)
Considering the following example:
1 >>> a .* c
2 33 Array{Int64,2}:
3
4 5 6
533
4
5
6
7
8
9
10
11
12
13
14
15
8 10 12
12 15 18
>>> c .* a
33 Array{Int64,2}:
4 5 6
8 10 12
12 15 18
>>> a .* d
33 Array{Int64,2}:
1 4 7
4 10 16
9 18 27
Notice that when we broadcast the multiplication.
We can use the broadcasting notation also to map a function over an array. There is
no speed gain in doing so, as it will be exactly equivalent to writing a for loop, but its conciseness may be useful sometimes. So the core idea in Julia is to write functions that take scalar
values and use broadcasting when needed, unless the functions must explicitly work on arrays (for example to compute the mean of a series of values, perform matrix operations, vector
multiplications, etc).
To broadcast a function over an array, it is sufficient to put a dot before the brackets .()
1 a = [1,2,3]
2 >>> sin.(a)
3
3-element Array{Float64,1}:
4
0.8414709848078965
5
0.9092974268256817
6
0.1411200080598672
Tip: do not try to write vectorised code in Julia (like you would do in Python and Matlab) if
you don’t need to, even if you are used to coding this way, as the code will become less readable
and more prone to errors. Use instead broadcasting and for loops.
It is also possible to map a function over several values using the map function, but there are
no real advantages in doing so and the broadcasting syntax is often more flexible.
As we will see in the future, in Julia it is really easy to write parallel code using multiprocessing and multi-threading, and it is particularly simple to write such parallel structures
when we encounter a for loop or a map function (which will become a parallel map through
pmap), thus it is convenient to get used to writing your code in such paradigm.
P.18
Variable Scope
In this lesson we will learn what is the scope of a variable and how scopes can be used to rule
when a variable should be accessible in our program.
The scope of a variable is the region of a program where the variable is known and accessible.
A variable may live in two kind of scopes: the global scope or a local scope.
P.18.1
Scope
A variable in the global scope is accessible everywhere in the program and can be modified
by any part of the code. When we define a variable in the REPL or outside of a function, for
534
example, we create a global variable.
A variable in a local scope is only accessible in that scope and in other scopes eventually
defined inside it.
In Julia there are several constructs which introduces a scope:
Construct
Scope type Scope blocks it may be nested in
module, baremodule
global
global
interactive prompt (REPL)
global
global
(mutable) struct, macro
local
global
for, while, try-catch-finally, let
local
global or local
functions (either syntax, anonymous & do-blocks)
local
global or local
comprehensions, broadcast-fusing
local
global or local
As you can see, some constructs introduce a global scope (for example each module has its
separate global scope) and others introduce a local scope (for example functions, for loops
and let blocks).
Let’s now see in more details how to work with scopes and in which scope it is better to
define a variable, depending on its usage.
P.18.2
Local Scope
Let’s start with a construct we are already familiar with: a function. A function declaration
introduce a scope, which means that each variable declared inside a function lives inside the
function, which is good! Thanks to this property we can use the names most suitable for our
variables (x, y, z, etc.) without the risk of clashing with the declaration of other functions.
If a value computed inside a function is needed outside the function it is a good idea to return
that value instead of modifying a global constant external to the function. As a rule of thumb,
a function should rely only on its input parameters and return only the variable which may be
useful for further computations.
Let’s see an example of a variable which exist inside a function (local scope) but doesn’t exist
in the global scope:
1
2
3
4
5
6
function example1()
z = 42
return
end
>>> z
ERROR: UndefVarError: z not defined
Although it is not advisable, it is possible to specify that a variable should be accessed in
the global scope through:
1
2
3
4
5
6
7
function example2()
global z = 42
return
end
>>> example2()
>>> z
42
A better approach is instead to return z and let the user perform the allocation of z:
535
1
2
3
4
5
6
7
function example3()
z = 42
return z
end
>>> z = example3()
>>> z
42
In the case where it is necessary to distinguish between a variable which exists both in the
local and global scope, it is possible to indicate the one that needs to be used through the global
or local annotation before the desired variable (for more details see this page of the Julia documentation).
P.18.3
let construct
The let construct can be used to introduce a new local scope. It is useful, for example, when
you want to perform some computations but you don’t want the intermediate results/variables to
pollute your current scope.
The let block will be able to access all the local (or global) variables available in its parent
scope and will have its own set of local variables. It is also possible to specify some initial values
to mimic the execution of a function once.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
a = let
i=3
i+=5
i # the value returned from the computation
end
>>>a
8
b = let i=5
i+=42
i
end
>>>b
47
c = let i=10
i+=42
i
end
>>>c
52
>>>i
UndefVarError: i not defined
As you can see, let blocks are pretty convenient when it comes to splitting computations
over several lines, but there are other possible uses as shown here.
let blocks are somewhat similar to begin blocks, although begin blocks don’t introduce a
local scope:
1 d = begin
536
2
3
4
5
6
7
8
9
i=41
i+=1
i
end
>>>d
42
>>>i
42
P.18.4
Global scope
Whenever we define a variable in the REPL or in general outside a construct which introduces a
local scope, we place a variable in the global scope. The global scope is accessible everywhere
in the program and a variable in the global scope can be modified by any part of the code. As
such, it is generally advisable to avoid using global variables as much as possible, in fact since
global variables can change their type and value at any time, they cannot be properly optimised
by the compiler.
P.18.5
Constants
One way to mitigate this performance issue is to define global variables as constants through
the const annotation. When we think of a constant we generally imagine a variable which is
immutable, for example the speed of light: the speed of light is a number and so it could be
expressed by a Float64, there is no need to change its type, once it has been defined, to a
String, in this case.
A constant in Julia is a variable which cannot change its type once it is defined (Julia will
throw an error if there is an attempt to modify the type of a constant) and Julia will show a
warning message if we try to modify the value of a constant. Since a constant is “type immutable”
it can be properly optimised by the compiler and there are fewer performance issues.
1
2
3
4
5
6
>>> const C = 299792458 # m / s, this is an Int
299792458
>>> C = 300000000 # change the value of C
WARNING: redefining constant C
>>> C = 2.998 * 1e8 # change the type of C, not permitted
invalid redefinition of constant C
P.18.6
Modules
If you don’t already know what a module is you don’t have to worry, we will talk about modules
in the next lessons and you can come back to this part later!
As we have anticipated, modules introduce separate global scope, which means that a variable which is known inside a module will not be accessible outside of the module unless it is
exported or it is accessed through the ModuleName.varName notation.
1
2
3
4
module ScopeTestModule
export a1
a1 = 25
b1 = 42
537
5
6
7
8
9
10
11
12
13
14
end # end of module
using .ScopeTestModule
>>>a1
25
>>>b1
UndefVarError: b1 not defined
>>>ScopeTestModule.b1
42
>>>ScopeTestModule.b1=26
cannot assign variables in other modules
At line 9-10 we can see that the a1 variable, which is exported by the module, can be accessed directly without specifying the scope of the variable, while on line 12-13 and 15-16
we can see that b1 can only be accessed by specifying where the variable lives (i.e. inside
ScopeTestModule). At line 18-19 we can see that it is not possible to directly modify a variable which is defined inside another module.
P.19
Modules
Modules
It is possible to think of modules as compact blocks of variables and functions which can be
easily imported in another program.
P.19.1
Working with modules
Libraries in Julia come in the form of module which can be loaded via the using notation.
• A module is a separate environment with its sets of variables and functions, some of which
are exported in the calling scope, which means that you can call exported functions by
simply typing their name as if they where defined in the same scope, while others are
accessible only through the ModuleName.functionName notation.
In the following example we will define a simple module which performs some operations and
exports a function .
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
module MyModule
export func2
a=42
function func1(x)
return x^2
end
function func2(x)
return func1(x) + a
end
end #end of module
#%%
using .MyModule
>>>func2(3)
51
>>>func1(3)
538
16 UndefVarError: func1 not defined
17 >>>MyModule.func1(3)
18 9
A module starts with the module keyword and should end with end. Contrarily to functions
and other blocks, one should not add indentation to a module block.
We define a variable, a, and two functions, func1 and func2, but we export only func2 (see
line 2), which means that only func2 will be accessible in the outer scope if we don’t specify
the module to which it belongs.
At line 17 we import MyModule, notice the . before the module name, this is needed as
MyModule is not an “official” package and ultimately because MyModule is defined in the Main
scope (the .Name notation is an abbreviation of Main.Name). At line 19 we call func2 and at
line 22 func1, notice that an error is thrown when we call func1 as it is not exported. If we
want to access it we need to type MyModule.func1(3) as shown at line 25.
Using Official Modules
• In order to use an existing official module, we need first to install it and then import it. You
can do this using the package manager. For this example we will use the SpecialFunctions
package, which contains functions such as the gamma function and the Bessel functions.
1 using Pkg
2 Pkg.add("SpecialFunctions")
At line 1 we import the module called Pkg (with the using keyword) and at line 2 we call
the add function which is defined inside it. add takes as its argument the name of the package
which we want to install and it will download and build it for us. When it is done (it may take a
few minutes) we are ready to use the functions available inside the package!
1
2
3
4
5
using SpecialFunctions
>>>gamma(3)
2.00
>>>sinint(5) #sine integral
1.5499312449446743
If we don’t want to import all of the functions available inside SpecialFunctions but only
some of them, for example the gamma function and sinint, but not cosint, we can do it in the
following way.
Make sure to restart the REPL first, once a package is installed you don’t need to run
Pkg.add... anymore!
1
2
3
4
5
6
7
using SpecialFunctions: gamma, sinint
>>>gamma(3)
2.00
>>>sinint(5)
1.5499312449446743
>>>cosint(5)
UndefVarError: cosint not defined
539
779
Sometimes it is useful to call a function taking in consideration the package where it is
defined. If a function is not exported by the module (more on export later) or if there are
several modules which export a function with the same name and same argument signature, we
can specify which module the function belongs to using the following syntax:
1
2
3
4
5
6
7
8
9
10
11
function gamma(x)
println("I am another ’gamma’ function")
return x^2
end
>>>using SpecialFunctions
WARNING: using SpecialFunctions.gamma in module Main conflicts with an
existing identifier.
>>>gamma(3)
I am another ’gamma’ function
9
>>>SpecialFunctions.gamma(3)
2.0
As you can see at line 7, a warning is shown to let us know that the gamma function exported
by SpecialFunctions is in conflict with the gamma function which we have defined at line 1.
At line 9 we call the gamma function and as we can see the first definition of the function
is what is used (i.e. the user defined function), if we want to call the gamma function inside
SpecialFunctions we need to specify the module which contains it (as done on line 13).
In the case where a conflict like this may arise, it is better to avoid the using notations and
instead use import, which “imports” the desired module, same as the using command, but
without exporting any function in the calling scope.
1
2
3
4
5
6
7
8
9
10
11
12
import SpecialFunctions
>>>gamma(3)
UndefVarError: gamma not defined
>>>SpecialFunctions.gamma(3)
2.0
function gamma(x)
println("I am another ’gamma’ function")
return x^2
end
>>>gamma(3)
I am another ’gamma’ function
9
At line 4 we see that gamma is not defined if we simply type import SpecialFunctions
and at line 6 we see that it becomes mandatory to call it using SpecialFunctions.gamma(3),
after we define the gamma function at line 9-12 it becomes possible to call our “custom” gamma
function.
P.19.2
Code inclusion
As modules become bigger and longer, it is a good practice to split code among different files.
In Julia it is simple to include code from another file in the current program as if the code were
written inside the same file through the include() function.
540
include() takes as its argument the name of the file which should be “pasted” inside the
current program.
The content of big-module-part-1.jl should be:
1 function func1big(x)
2
return x^2
3 end
The content of big-module-part-2.jl should be:
1 a = 42
2 function func2big(x)
3
return func1big(x) + a
4 end
And the content of big-module.jl should be:
1
2
3
4
5
module MyBigModule
include("files/big-module-part-1.jl")
include("files/big-module-part-2.jl")
export func2big
end #end of module
We can now import MyBigModule inside our program (lesson-modules.jl) in the following way:
1
2
3
4
include("big-module.jl")
using .MyBigModule
>>>func2big(3)
51
Depending on your folder structure and if you have downloaded/cloned the techytokexamples repository, you may need to change the current working directory to the one
which contains the files described above (in my case “lesson-modules”) using the command
cd("lesson-modules") for this example to work.
Although one should give meaningful names to the files which make up a module (and not
part1, part2, etc.) this was an example of how one can structure a module:
make a main “module file” which contains the module, imports all of the other files using
include and exports the desired functions.
make several files with meaningful names which perform a group of operations with a common topic.
This structure lets you easily extend the module (simply add new files) and makes the code
more maintainable, if functions which perform similar tasks are grouped in the same file.
Notice that in Julia it is not important the order in which you include the files in the main
module, but in my opinion it is a good practice to include the files in a sort of chronological
order. In our example the function func2big depends on func1big which is defined inside
big-module-part-1.jl, so we should import it before we includebig-module-part-2.jl.
P.19.3
Code documentation
Since you will likely come back to a module you have written; once every few months, you may
not remember what a specific function does. It is thus a good idea to add annotations to your
code through # comment and write a small description of the function.
541
When you type ? functionName in the REPL you get a description of that function and
usually an example of how it can be used. We will now learn how to write such description for
our functions.
One can write the description of a function in the following way:
1
2
3
4
5
6
"""
Description of the function
"""
function foo(x)
#... function implementation
end
There is a set of rules for writing documentation. These rules are listed in the official documentation. Here is a summary:
Start with the function signature (i.e. function name and arguments) indented by 4 spaces
Write a small summary of what the function does
If necessary explain what the arguments mean/do
Optionally give an example of usage of the function
It is advisable to prepend @doc raw"""..., in this way you will be able to write markdown
code inside the description string without the need to escape special characters.
Let’s see how we can document, for example, func2big:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@doc raw"""
func2big(x)
Computes the square of ‘x‘ and add ‘a‘ to it.
# Examples
‘‘‘julia-repl
julia> include("big-module.jl")
julia> using .MyBigModule
julia> func2big(3)
51
‘‘‘
"""
function func2big(x)
return func1big(x) + a
end
After we have imported MyBigModule we can type ?
documentation:
542
func2big in the REPL to read the
Or, if you are using the Juno IDE, we can look up the documentation for func2big in the
documentation explorer (the documentation explorer may take a few minutes to compile the
documentation the first time you use it):
P.20
Types and Structures
In this lesson we will learn what types are and how it is possible to define functions that work
on types. We will learn which are the differences between abstract and concrete types, how
to define immutable and mutable types and how to create a type constructor. We will give a
brief introduction to multiple dispatch and see how types have a role in it.
You can find the code for this lesson here.
We can think of types as containers for data only. Moreover, it is possible to define a type
hierarchy so that functions that work for parent type work also for the children (if they are written
properly). A parent type can only be an AbstractType (like Number), while a child can be both
an abstract or concrete type.
543
In the tree diagram, types in round bubbles are abstract types, while the ones in square
bubbles are concrete types.
P.20.1
Implementation
To declare a Type we use either the type or struct keyword.
To declare an abstract type we use:
1
2
3
4
abstract type Person
end
abstract type Musician <: Person
end
You may find it surprising, but apparently musicians are people, so Musician is a sub-type
of Person. There are many kind of musicians, for example rock-stars and classic musicians, so
we define two new concrete types (in particular this kind of type is called a composite type):
1
2
3
4
5
6
7
8
9
10
11
mutable struct Rockstar <: Musician
name::String
instrument::String
bandName::String
headbandColor::String
instrumentsPlayed::Int
end
struct ClassicMusician <: Musician
name::String
instrument::String
end
Notably rock-stars love to change the colour of their headband, so we have made Rockstar
a mutable struct, which is a concrete type whose elements value can be modified. On the
544
contrary, classic musicians are known for their everlasting love for their instrument, which will
never change, so we have made ClassicMusician an immutable concrete type.
We can define another sub-type of Person, Physicist, as I am a physicist and I was getting
envious of rock-stars:
1
2
3
4
5
6
7
8
9
10
11
12
mutable struct Physicist <: Person
name::String
sleepHours::Float64
favouriteLanguage::String
end
aure = Physicist("Aurelio", 6, "Julia")
>>>aure.name
Aurelio
>>>aure.sleepHours
6
>>>aure.favouriteLanguage
"Julia"
Luckily my exam session is over now and I finally have a little bit more time to sleep, so I’ll
adjust my sleeping schedule to sleep eight hours:
1 aure.sleepHours = 8
Incidentally I am also a ClassicMusician and I play violin, so I can create a new structure:
1 aure_musician = ClassicMusician("Aurelio", "Violin")
2 >>>aure_musician.instrument = "Cello"
3 setfield! immutable struct of type ClassicMusician cannot be changed
As you can see, I love violin and I just can’t change my instrument, as ClassicMusician is
an immutable struct.
I am not a rock-star, but my friend Ricky is one, so we’ll define:
1 ricky = Rockstar("Riccardo", "Voice", "Black Lotus", "red", 2)
2 >>>ricky.headbandColor
3 red
P.20.2
Functions and types: multiple dispatch
It is possible to write functions that operate on both abstract and concrete types. For example,
every person is likely to have a name, so we can define the following function:
1
2
3
4
5
function introduceMe(person::Person)
println("Hello, my name is $(person.name).")
end
>>>introduceMe(aure)
Hello, my name is Aurelio
While only musicians play instruments, so we can define the following function:
1 function introduceMe(person::Musician)
2
println("Hello, my name is $(person.name) and I play $(person.
instrument).")
545
3 end
4 >>>introduceMe(aure_musician)
5 Hello, my name is Aurelio and I play Violin
and for a rock-star we can write:
1 function introduceMe(person::Rockstar)
2
if person.instrument == "Voice"
3
println("Hello, my name is $(person.name) and I sing.")
4
else
5
println("Hello, my name is $(person.name) and I play $(person.
instrument).")
6
end
7
println("My band name is $(person.bandName) and my favourite headband
colour is $(person.headbandColor)!")
8 end
The ::SomeType notation indicates to Julia that person has to be of the aforementioned
type or a sub-type. Only the most strict type requirement is considered (which is the lowest
type in the type tree), for example ricky is a Person, but “more importantly” he is a Rockstar
(Rockstar is placed lower in the type tree), thus introduceMe(person::Rockstar) is called.
In other words, the function with the closest type signature will be called.
This is an example of multiple dispatch, which means that we have written a single function
with different methods depending on the type of the variable. We will come back again to multiple dispatch in this lesson, as it is one of the most important features of Julia and is considered
a more advanced topic, together with type annotations. As an anticipation ::Rockstar is a type
annotation, the compiler will check if person is a Rockstar (or a sub-type of it) and if that is
true it will execute the function.
P.21
Type constructor
When a type is applied like a function it is called a constructor. When we created the previous types, two constructors were generated automatically (these are called default constructors).
One accepts any arguments and calls convert to convert them to the types of the fields, and the
other accepts arguments that match the field types exactly (String and String in the case of
ClassicMusician). The reason both of these are generated is that this makes it easier to add
new definitions without inadvertently replacing a default constructor.
Sometimes it is more convenient to create custom constructor, so that it is possible to assign
default values to certain variables, or perform some initial computations.
1 mutable struct MyData
2
x::Float64
3
x2::Float64
4
y::Float64
5
z::Float64
6 function MyData(x::Float64, y::Float64)
7
x2=x^2
8
z = sin(x2+y)
9
new(x, x2, y, z)
10
end
546
11 end
12 >>>MyData(2.0, 3.0)
13 MyData(2.0, 4.0, 3.0, 0.6569865987187891)
Sometimes it may be useful to use other types for x, x2 and y, so it is possible to use parametric types (i.e. types that accept type information at construction time):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
mutable struct MyData2{T<:Real}
x::T
x2::T
y::T
z::Float64
function MyData2{T}(x::T, y::T) where {T<:Real}
x2=x^2
z = sin(x2+y)
new(x, x2, y, z)
end
end
>>>MyData2{Float64}(2.0,3.0)
MyData2{Float64}(2.0, 4.0, 3.0, 0.6569865987187891)
>>>MyData2{Int}(2,3)
MyData2{Int64}(2, 4, 3, 0.6569865987187891)
It is crucial for performance that you use concrete types inside a composite type (like
Float64 or Int instead of Real, which is an abstract type), thus parametric types are a good
option to maintain type flexibility while also defining all the types of the variables inside a composite type.
For more information on constructors see this article.
P.21.1
Example
Mutable types are particularly useful when it comes to storing data that needs to be shared
between some functions inside a module. It is not uncommon to define custom types in a module
to store all the data which needs to be shared between functions and which is not constant.
1 module TestModuleTypes
2 export Circle, computePerimeter, computeArea, printCircleEquation
3 mutable struct Circle{T<:Real}
4
radius::T
5
perimeter::Float64
6
area::Float64
7
function Circle{T}(radius::T) where T<:Real
8
# we initialize perimeter and area to -1.0, which is not a
possible value
9
new(radius, -1.0, -1.0)
10
end
11 end
12 @doc raw"""
13
computePerimeter(circle::Circle)
14 Compute the perimeter of ‘circle‘ and store the value.
547
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
"""
function computePerimeter(circle::Circle)
circle.perimeter = 2**circle.radius
return circle.perimeter
end
@doc raw"""
computeArea(circle::Circle)
Compute the area of ‘circle‘ and store the value.
"""
function computeArea(circle::Circle)
circle.area = *circle.radius^2
return circle.area
end
@doc raw"""
printCircleEquation(xc::Real, yc::Real, circle::Circle )
Print the equation of a cricle with center at (xc, yc) and radius given
by circle.
"""
function printCircleEquation(xc::Real, yc::Real, circle::Circle )
println("(x - $xc)^2 + (y - $yc)^2 = $(circle.radius^2)")
return
end
end # end module
#%%
using .TestModuleTypes
circle1 = Circle{Float64}(5.0)
computePerimeter(circle1)
circle1.perimeter
computeArea(circle1)
circle1.area
printCircleEquation(2, 3, circle1)
This is a simple module which implements a Circle type which contains the radius, perimeter and area of the circle. There are three functions which respectively compute the perimeter
and area of the circle and store them inside theCircle structure. The third function prints the
equation of a circle with a given centre and the radius stored inside a Circle structure.
Notice that we could have simply computed the perimeter and area inside the type constructor, but I have chosen not to do so for educative purposes.
P.22
Working with Packages
P.22.1
Creation of a package
To create a package, type ] in the REPL to access the package manager and type
generate TestPackage1
548
If the package creation process has been successful, a new package directory should appear
inside your working directory:
Inside the file found at TestPackage1/src/TestPackage1.jl you can see the following lines:
module TestPackage1
greet() = print("Hello World!")
end # module
This is the skeleton of the package, we can modify the module according to our needs and
we can treat this module in the same way as we would do with a normal module. What changes
is the way to import the module/package inside our project.
P.22.2
Using a user defined package
In order to use a user defined package, we need to activate that package. First of all,
make sure that your current working directory is the same as the directory where the package has been created. To check your project working directory, please type pwd(). If the
directory is different (it shouldn’t be), you can change the current working directory with
cd("/path/to/directory").
To summarise, if the package is found at /lesson-packages/TestModule1, the working
directory should be /lesson-packages.
We can now activate the package and test it through the following code in the “lessonpackages.jl”:
using Pkg
Pkg.activate("TestPackage1")
549
#%%
using TestPackage1
TestPackage1.greet()
As you can see at line 5, there is no need to add a . before the name of the package, as it
recognised as an “official” package and not an user defined package.
P.22.3
Adding dependencies
Once a package has been added to the project, it is possible to use it inside the module, so let’s
modify TestModule1.jl in the following way:
module TestPackage1
using SpecialFunctions
export mySpecialFunction
greet() = print("Hello World!")
function mySpecialFunction(x)
return x^2 * gamma(x)
end
end # module
When you change something inside a package, remember to restart the REPL for the changes
to take place.
We can add a dependency to the project in the following way:
type ] to enter the package manager
type in the REPL ] add SpecialFunctions
Some output has been omitted for the sake of brevity.
And now we can call mySpecialFunction
using Pkg
Pkg.activate("TestPackage1")
using TestPackage1
TestPackage1.mySpecialFunction(42)
550
P.22.4
Package initialisation
If we share the package with someone or we want to reinstall a package on another machine, it
is possible to automatically install all the dependencies required for the project.
In order to do so, activate the package normally as we did before and then type the following
code:
using Pkg
Pkg.instantiate()
You can find more information on how to write and use packages at the official documentation.
P.23
Coding workflow with VSCode
P.23.1
Revise
Imagine that you are writing a library. You have a package with a module with several functions inside (see the lesson on packages). As the number of functions inside a module increase,
recompiling the whole module every time you add a new function, or modify one, becomes
increasingly long and tedious.
For this specific reason, Revise comes in our help!
To install Revise, simply type in the REPL:
using Pkg; Pkg.add("Revise")
Now let’s imagine that we are developing TestPackage1. In order to properly activate the
functionalities of Revise, we need to import the library before we load our package. The code
will then look like this:
using Pkg
Pkg.activate("TestPackage1")
using Revise
using TestPackage1
If we call the TestPackage1.greet() function, a greetings message will be printed in the
REPL: Hello World!.
Now, let’s suppose that we want to change the greetings message. Since we are using Revise,
all we need to do is change the function in the TestPackage1\src\TestPackage1.jl file and
save it. In particular, let’s change line 6 and have this new message:
greet() = print("Hello from TechyTok!")
Now, if we call TestPackage1.greet() again (without restarting Julia), it will print Hello
from TechyTok!, and we didn’t need to recompile the module!
With the help of Revise, we can make any modification to our module, i.e. add or remove
functions, change names, or add new variables without the need to restart Julia. This feature will
save you a few minutes every time you need to do an edit, or while you are debugging.
P.23.2
Code formatting
When we code, we don’t always follow the style guidelines. For example, we don’t care about
perfectly aligning every piece of code, maybe we don’t use spaces before and after a = symbol,
or we don’t add the correct spacing everywhere.
551
Fortunately for us, the code formatter comes in our help. Simply press ALT+SHIFT+Enter
with a file open on VSCode and the Julia extension will take care of it! Please note, that the
Language Server must be running before we can format some Julia code, so please run a piece
of your code before you try to format a document.
In case you don’t want to format your whole code, you can also select a piece of code and
press ALT+SHIFT+Enter, and Julia will only format that piece of code.
P.24
Multi panel coding
Sometimes, it becomes useful to code with two files open at the same time. For example. you
might want to take a look at one file where a function is implemented and use it in another one.
Or you need to see at the same time two different lines of the same file. In this regard, panels
come in our help.
In order to split a window in more panels, right click on the tab of a file and a context menu
will show several options:
Let’s consider all the possible options and see what they do:
Split up/down/left/right
Split in group
P.24.1
Split up/down/right/left
If you click one of these options (for example split right) a panel will open on a side of the screen
(the right side in our case). It will look like you have opened the same file twice, while the file
is actually the same one. This way, each modification you make on the file will be “mirrored”
on each panel.
552
This option is especially useful if you need to edit/see two different file at the same time.
You can drag and drop file tabs from each panel to another one, and you are only limited by the
size of your screen. Remember that if you need more space on your screen, you can collapse the
file browser panel on the left by pressing the explorer icon (the one with two sheets, on hte top
left of your screen).
P.24.2
Split in group
Sometimes, you need to edit or read several places in the same file. In this case, the Split in
Group option might be preferable.
When you split a file in group, you will see something like that:
As you can see, the file is not opened inside a new panel, and it is instead split in the same
panel. If you switch to another tab, the new file will not be displayed in a split view, and if you
come back to the previous file the split view will remain in place. This is extremely useful if
you need to explore several parts of the same file and you don’t want to open a different panel. It
is also useful to take a quick peek to another part of the code without losing the line where you
have been working.
This option is compatible with other panels too:
553
P.24.3
Code navigation
A wonderful feature which is made possible by the VSCode extension for Julia is code navigation.
Imagine that you are developing a module, and you want to quickly see the function definition, and in particular the function signature. In order to do it, simply press CTRL and hover
your mouse cursor over the name of the function. You will see a small window with the function
definition:
If you want to quickly go to the function definition, just CTRL+Click on the name of the
function. If you want to go back to where you where before, and you have a mouse with additional
side buttons, you can press the “back” button to go back.
Please notice that code navigation works under certain premises, in particular at the moment
you can only navigate to functions defined inside the same module/namespace. This means that
you won’t be able to navigate to the definition of a function defined inside a module, if you are
working with a script. This is due to the fact that a script runs in the “Base” namespace.
P.24.4
Find and replace
One simple yet useful feature is the ability to find a certain word and eventually replace it. In
order to open the find panel, just press CTRL+F. To open the replace menu, click on the small
arrow on the left of the find field. You will then be able to replace a word with another one.
Sometimes, you decide that you want to refactor your code and change the name of a function.
In order to replace a string everywhere in a folder/whole project there is the Find in Files
feature. In order to access it, press CTRL+SHIFT+F. This menu will help you find a certain string
in your whole project directory, and eventually replace it.
If you want to search a string only in one folder, right click on the folder name in the file
explorer and press Find in Folder.
P.24.5
Multi line cursor
Imagine that you are copying a piece of code and you need to modify the name of a variable.
This could be done with the find and replace function, but sometimes it is just faster to do some
554
edits manually. Nonetheless, usually we don’t want to write the same thing over and over, and
for this reason the multi cursor feature comes in handy.
To place your cursor simultaneously at different places, keep ALT pressed and click on the
new positions: you will see something like this:
If you write something, it will now be written simultaneously by all your cursors.
P.24.6
Documentation panel
In the Julia extension panel (Julia symbol on the left toolbar), there is a
handy documentation tab where you can search for the documentation of a
function:
This panel behaves as the help function would, with the additional bonus that the markdown will be rendered, and thus the documentation will look similar to the official online julia
documentation. You can use this panel to quickly look for the signature of a function, of for
an example on how to use it. If you properly document your functions, you will also be able to
access the documentation for your functions.
At the time of writing, the documentation panel does not seem to work properly. It seems
that not every function for which the documentation is available through the help function is
researchable.
P.24.7
Variable explorer
In many cases, it might not be practical or you might not want to write the code to print a
variable. It is possible to access the value of any defined variable through the variable explorer.
If you open the Julia extension, there will be a panel called WORKSPACE where you can see all
the available namespaces (one for each module, and the global scope).
555
a
If
we
matrix,
define
some
we will be
variables,
able to
like
a
see their
number,
content
a
in
vector
and
the variable
explorer:
It is also possible to expand matrices and view them in a gird view by
clicking on the small button on the right of the variable name (open in
VSCode):
Please notice that since a function is just a particular type of variable, it is possible to also
see a list of the functions defined inside a module/REPL using the variable explorer:
P.24.8
Debugging
Debugging is the process of finding and resolving bugs (errors) within a piece of code. You
might have never used a debugger before, but I’m sure you already experience with some sort of
debugging. A basic way of debugging a piece of code consists in adding print statements here
and there, to see what is happening inside the code.
Although adding print statements is extremely simple and intuitive, it is often not the the best
solution to debug a piece of code. First of all, to print only certain variables is extremely limit556
ing, since your bug might involve some of the variables/functions which you have not printed.
Furthermore, you will have to remove all those print calls at a certain point, wasting a lot of time.
As you might imagine, the proper solution to extensively debug a piece of code is to use a
debugger. Julia comes with a powerful debugger which is further integrated into VSCode. I am
sure you will love it!
First of all, let’s define a simple “working” function and see how we can explore it using a
debugger:
function helper_function(x)
return log10(x) +3
end
function debug_me(x)
a = zeros(10)
for i in 1:length(a)
a[i] = helper_function(x*i)
end
b = a ./ 3
return sum(b)
end
P.24.9
Breakpoints and code navigation
Before we can debug a function, we usually want to add breakpoints. A breakpoint is a line
in the code/function where the debugger will pause the execution and let you examine all the
variables which are stored inside a function. You would usually want to add a breakpoint before
a line where you suspect there might be a problem, or if you want to inspect the state of some
of the variables. As a rule of thumb, you can just add a breakpoint wherever you feel like you
would add a print statement. Don’t worry about adding too many breakpoints, you can always
disable them later.
To add a breakpoint,
click on the left of a line:
a red circle will
appear:
It is possible to debug Julia code in two ways: you can either debug a whole script or debug
a single function.
To debug a whole script, you can either press F5 or click the debug icon on the top right
corner of vscode:
557
Since I mainly develop my code in interactive mode together with Revise, I prefer to debug
my code interactively too.
To debug a single function, you can either use the @enter or @run. Let’s see how this works
before we delve into the differences between the two macros. First of all, let’s start the debugger:
@run debug_me(3)
A new window should open on the left side of VSCode. There are several tabs in that window,
for now let’s focus our attention on the Variables tab. Here we can see the value of all the
variables defined inside the function which we are debugging. At the beginning, the only known
variable is the function argument x.
To navigate our code with the debugger, we will use this command panel (usually on the top
center of the VSCode window):
There are several buttons:
Continue (F5)
Step Over (F10)
Step Into (F11)
Step Out (Shift+F11)
Restart
Disconnect
If we press Continue, the debugger will continue to the next break point. If we press Step
Over the debugger will advance by one line. If we press Step Into when we are currently on
558
a line where a function is called, the debugger will take us inside the function definition. Once
we are inside a function, if we want we can further proceed line by line (with Step Over) and
Step Into other function calls. If we stepped into a function definition, we can come back to
the position where we were before with Step Out, effectively stepping out of the function call.
Since it is not possible to go back one step in the execution of a function, if for some reason
we want to start over, we can press the Restart button.
The debugger will automatically exit once the function has been completely evaluated. If we
want to stop the debug early, we can press the Disconnect button.
The @enter and the @run macro behave similarly. In particular, the @enter macro will
activate the debugger and pause the execution at the first line inside of the function. On the other
hand, @run will start the debugger and run the function up to the first breakpoint. Depending on
what you want to achieve, you can use either one of them to start the debugging process.
P.24.10
Debugger panels
Now that we have understood how to navigate code with the debugger, let’s see how to inspect
the code with the debugger. I encourage you to run the debug me function with the debugger
attached and try the various combinations of buttons to see what happens. As you press the
Continue button, you will see that new variables appear in the variables tab, and their value
will change.
There are several other panels beside the Variables panel, let’s see what they do.
The Watch panel can be useful to keep an eye on an expression or variable, which is not
necessarily part of the function body. Let’s imagine that for some reason we want to monitor the
value of sum(a.^2), we can add that expression in the watch window:
As we press the Continue button, the value of the expression which we are watching is
gonna be updated.
There are three additional panels: Call Stack, Breakpoints and Compiled.
559
The Breakpoints panel shows all the breakpoints in your code, and you can manually activate/disable them without removing them from the code.
The Call Stack panel displays which function is being debugged, which is useful not to
get lost in a rabbit hole while debugging. By clicking on one of the function names you will
reach the corresponding function definition, which might be useful for code navigation.
The Compiled tab allows the user to trigger compilation of some functions inside the call
stack. If the code execution is extremely slow and you are not interested in debugging some
of the functions involved, you can trigger compilation for those functions. This is an advanced
topic which will not always be useful. for further information, see the official documentation.
P.24.11
Editing the function namespace
Using a debugger can be extremely useful when a function throws an error. Let’s consider this
function:
function debug_me2()
x = -1
res = sqrt(x)
return res
end
As we can see, this function computes the square root of a negative number, which does not
exist in the domain of real numbers. If we call this function, Julia will throw a DomainError,
saying that if we want to compute the square root of a negative number, we must specify that we
are working with complex numbers.
The debugger can be useful to troubleshoot what is going on inside a function. In this case it
is obvious why x is a negative number, but with a more complex function we might not know why
we reached that result. Let’s add some breakpoints, start the debugger with @run debug me2()
and head to the variables explorer.
560
Imagine that you have started the debugger, proceeded step by step and reached the domain
error. We now start over and decide that we want to modify the value of x while the function is
still running. For testing purpose, we want to see if a positive value of x will solve the domain
error problem (spoiler: it will). In order to modify the value of a variable mid run, we can use
the variables explorer window. Double click the x variable and change its value to 2:
You can now ask the debugger to Continue and you will not encounter the domain error
anymore. Please notice that changing “manually” the value of x has not changed our code, it
only let us better understand that the x variable is responsible for the domain error.
While the debugger is running, it is also possible to evaluate pieces of code inside the function
namespace. This means that if for some reason we want to do some tests on the variables defined
inside a function, we can do it without writing any additional code inside the function definition.
Let’s start over the debugger, by disconnecting it and running @run debug me(3).
In the same window where the REPL is (middle bottom part of the
VSCode interface) you can see that there is a new DEBUG CONSOLE
now:
This is a REPL which runs “inside” the namespace of the function.
This
means that we can evaluate any expression as if it was written inside the
561
function:
Please note that you can also change the value of any of the variables which exist inside the
function, for example by writing a .+= 2 . This is a double-edged sword and you have to pay
attention to what you are doing if you are evaluating code inside the function context. Anyway,
if you commit some mistakes, you can always restart the function debugging, so nothing you do
in the debug console is permanent.
P.24.12
Function profiling
This section is an excerpt from the code optimisation lesson.
Profiling is the practice of measuing the execution time and memory usage of each part of
a piece of code, in order to better understand how to optimise it. In this section we will learn
how to find the bottlenecks in the execution of a function, so that we know which parts of the
function should be optimised.
As you probably already know, it is possible to measure the execution time of a function using
the @time macro or preferably @btime (which is included in the package BenchmarkTools).
They are useful when we want to measure a single function call, but they give no information on
what is making a function slow. For this reason we need a tool that enables us to identify which
line of code is responsible for the bottleneck.
Luckily there are two exceptional packages which help us in profiling: Profile and the Julia
IDE for VSCode. Both of the tools will run the desired function once and will log the execution
time of each line of code.
Profile works completely in the REPL and will produce a log file. On the other hand, with
the support of VSCode we will be able to display the profiling information in a graph.
P.24.13
Profile
Let’s write two new functions which perform heavy calculations:
function take_a_breath()
sleep(0.2)
return
end
function test8()
r=zeros(100,100)
take_a_breath()
for i in 1:100
562
A=rand(100,100)
r+=A
end
return r
end
We shall now profile test8:
using Profile
test8()
Profile.clear()
@profile test8()
Profile.print()
If you see a log file extraordinarily long, run line 2 to 4 again as it is possible that you have
profiled the compilation of some functions and not test8.
You should see something like:
The number 8 (which may vary) is an indication of how long a function runs. We also have
a 1 and a 4, so probably this block is the one responsible for the bottleneck. Profile thus gives
you a hint that at line 101 (line 8 of the code snippet) there is a bottleneck: who would have
imagined that sleeping for 22ms would have been a slow down?
Unfortunately using Profile.print() is not really user friendly and for this reason VSCode
comes in our help!
After having called test8 again, to make sure that the function has been properly compiled,
we call the profile viewer macro @profview
test8()
@profview test8()
If
on
you have done everything
the right side of VSCode
correctly,
a new
and you should
563
panel should open
see something like
this:
This list will show you at a glance which are the functions which take more time in your code
(in our case, the sleep or wait function) and you can easily evaluate which are the bottlenecks.
It is also possible to display the profiling graphic as a fire graphic.
In order to do it, click on the small fire icon on the top right corner of the profiling window (you might have to install an extension). You will see something like
564
this:
In this case, the flame graph is not that informative, since the function is extremely simple,
but it is a handy tool when profiling complex functions. The graph should be read from the top
to the bottom. The functions on the top usually call the functions under them. If more than one
function is involved you will see several branches and the graph will become more complex.
I encourage you to hover your mouse pointer on the functions in the fire graph: you will see
the run time of each function involved and you are also able to jump to each function definition.
In many cases, the profiler will also add a note on top of the called functions stating how long it
took to run them. In order to scroll the flame graph, press ALT and use the scroll wheel, or click
and drag the plot. To zoom on a region of the flame graph, point to it and use the scroll wheel.
P.24.14
Problem tab
VSCode will also suggest you if there are some possible problems with your code. For example,
you might have called a function with the wrong arguments, or redefined a constant. It is possible
to see all the possible problems with your code in the Problems tab:
565
P.24.15
TODO explorer
This is not properly a feature of the Julia VSCode extension, but it is something that I would
like to show you nonetheless. When you are writing, you might often find yourself in a situation
where you want to add a note that you need to be able to easily find. For example you might want
to add a TODO (like TODO: add documentation), or you have written some piece of unsightly
code that need to be fixed and you want to tag it with FIXME.
All these notes can be written as a code comment in the form:
debug_me2(3) # FIXME: function called with the wrong argument # TODO: add
a TODO
In order to color code them and be able to easily find them, you can install the Todo Tree
extension. To install it, go to the extension tab and type the name of the extension in the search
bar:
After you have installed it, press the small cogwheel to open the extension
configuration menu and search for useColourScheme to enable color coding the
annotations.
After
you
have
done
that,
your
code
will
look
like
this:
There will now be an additional icon in the left toolbar with a tree which will list all your
TODOs, FIXMEs, and so on!
566
567
This page is intentionally left blank!
568
Appendix Q
Examples on Properties of Symmetric/AntiSymmetric Cross-sections
Example 6 (Symmetric Cross-section).
C200 x 20.5
Calculate A, y, z, Iy , Iz , Iyz
C250 x 37
569
Solution
From tables of sec. ??, properties of cross-section component are identified as:
C200×20.5
C250×37
From the symmetry;
• centroidal y axis is identified
C200×20.5
(1)
• Iyz = 0
• only half the cross-section can be considered
(2)
C250×37
Hence, only y, Iy & Iz are calculated as
Qẑ
AX
Ai ŷi
Qẑ = 2
y=
half
Iy,i = 2
X
half
half
X
Iẑ,i = 2
X
Iŷ = Iy = 2
X
Iẑ = 2
I¯y,i + Ai zi2
(3)
I¯z,i + Ai ŷi 2
half
half
To calculate A and y
i
1
Ai
2610
2/2
P
4740
2
half
ŷi
0
−
73.4
− 15.7
2
zi
254
+ 7.7 − 14.1
2
0
X
half
X
Ai
= 9960
y=
half
570
−4.977e4
−4.977e4
4980
Qẑ = 2
A=2
Ai ŷi
0
Qẑ
A
Ai ŷi
= −9954e4
= −9.994
To calculate Iy and Iz
I¯y,i
Iy,i
Ai zi2
I¯z,i
0.633
15
37.9
2
3.7961e7
0
3.7961e7
1.39
2
Iẑ,i
Ai ŷi2
0
1.0452e6
1.0452e6
Iẑ = 2
X
Iẑ,i
half
Iy = 2
X
= 2.0904e6
Iz = Iẑ − A y 2
= 1.0956e6
Iy,i
half
= 7.5922e7
Example 7 (Double Symmetric Cross-section).
Resolve example 5 on page 221 by considering
the double symmetry of the cross-section.
L76×51×12.7
C200×20.5
S250×37.8
Solution
From tables of sec. ??, properties of cross-section component are identified as:
L76×51×12.7
C200×20.5
S250×37.8
571
C200×20.5
(2)
(3)
(1)
L76×51×12.7
(4)
S250×37.8
(7)
(6)
(5)
From the double symmetry;
• centroidal axes are identified
• Iyz = 0
• only quarter the cross-section can be considered
Hence, only Iy & Iz are calculated as
X
Iy = 4
quarter
X
Iz = 4
X Iy,i = 4
I¯y,i + Ai zi2
I¯z,i + Ai yi2
quarter
X Iz,i = 4
quarter
quarter
Ai
1450
yi
203
+ 27.4
2
To calculate Iy and Iz
i
1
2/2
4/4
P
2610
2
4810
4
quarter
0
0
zi
254
+ 7.7 − 14.7
2
254
+ 7.7 − 14.1
2
0
3957.5
Iy,i
I¯y,i
Iz,i
Ai zi2
I¯z,i
0.278
2.088e7
1.898e7
0
3.9860e7
0.799
0.633
2
51.2
4
15
2
2.8
4
Ai yi2
2.4092e7
0
0
2.4092e7
Iy = 4
A=4
X
X
Iy,i
quarter
Ai
= 1.5944e8
quarter
= 15830
572
X
Iẑ = 4
= 9.6368e7
Iẑ,i
quarter
Example 8 (Anti-symmetric Cross-section).
400
Calculate A, y, z, Iy , Iz , Iyz , IP , ρy , ρz , Sy & Sz
100
600
100
100
400
z
Solution
From the anti-symmetry of the cross-section:
400
100
1
• centroidal axes are identified
2
600
• only half the cross-section can be considered
– Any of the y-symmetric or z-symmetric halves is fine
y
100
half
half
Iz = 2
X
half
half
Iyz = 2
X
X
Iz,i = 2
Iyz,i = 2
half
I¯z,i + Ai yi2
3
400
Hence, only Iy , Iz & Iyz are calculated as
X
X
Iy = 2
Iy,i = 2
I¯y,i + Ai zi2
X
100
I¯yz,i + Ai yi zi
half
To calculate A, Iy , Iz and Iyz (y-symmetric half)
Iy,i
Iz,i
i
Ai
yi
zi
I¯y,i
Ai zi2
1
2/2
P
3e4
200
0
250
0
(400−100)×1003
12
1 100×6003
2
12
1.875e9
0
half
6e4
2
6e4
I¯z,i
Ai yi2
100×(400−100)3
12
1 600×1003
2
12
1.2e9
0
2.8e9
Iyz,i
I¯yz,i Ai yi zi
0
0
2
1.45e9
Iyz = 2
X
Iyz,i
1.5e9
0
1.5e9
= 3e9
half
A=2
X
Iy = 2
X
Ai
= 120000
Iy,i
= 5.6e9
Iz,i
= 2.9e9
Ip = Iy + Iz
half
half
Iz = 2
X
half
= 8.5e9
To calculate ρy and ρz
r
Iy
ρy =
= 216.02
A
573
r
Iz
= 155.46
A
To calculate Sy and Sz
Sz =
ρz =
Sy =
Iy
|zmax |
=
5.6e9
= 1.8667e7
300
574
Iz
|ymax |
=
2.9e9
= 8.2857e6
350
References
[1] Gadgets, Games, Robots and the Digital World.
Dorling Kindersley Publishing, 2011.
[2] [Online]. Available: www.goengineer.com/blog/ultimate-guide-to-abaqus-computing
[3] “Installation guide for windows.”
[4] G. Lehey, The complete FreeBSD – Documentation from the Source, 4th ed., ser. O’Reilly
Series. O’REILLY & ASSOC INC, 2003. [Online]. Available: www.lemis.com/grog/
Documentation/CFBSD/book.pdf
[5] M. W. Lucas, Absolute FreeBSD – The Complete Guide to FreeBSD, 2nd ed.
Press, 2008.
[6] M. Ciampa, Security+ Guide to Network Security Fundamentals, 5th ed.
nology, Inc., 2015.
Course Tech-
[7] J. Ross, Network Know–How – An Essential Guide for the Accidental Admin.
Press, 2009.
[8] Basic networking tutorial. [Online]. Available:
d9e99072/Basic-Networking-Tutorial
No Starch
No Starch
www.techiwarehouse.com/engine/
[9] Reference Manual for the RangeMax Wireless Router WPN824, 2005. [Online]. Available:
www.netgear.com
[10] MATLAB Object–Oriented Programming, R2019b ed. MathWorks, Inc. [Online].
Available: https://www.mathworks.com/help/releases/R2019b/pdf doc/matlab/matlab
oop.pdf
[11] N. M. Josuttis, The C++ Standard Library – A Tutorial and Reference, 2nd ed. Addison–
Wesley, 2012.
[12] B. Stroustrup, The C++ Programming Language, 4th ed.
Pearson Education, 2013.
[13] I. Horton, Using the C++ Standard Template Libraries.
Apress, 2015.
[14] C. Mouton, “Linear algebra libraries,” techreport, 3 2009. [Online]. Available:
https://hal.inria.fr/inria-00576469
[15] T. Bah, Inkscape – Guide to a Vector Drawing Program, 4th ed. Prentice Hall, 2011.
[Online]. Available: www.ebook.de/de/product/14765413/tavmjong bah inkscape.html
[16] N. Matthew and R. Stones, Beginning Linux Programming, 4th ed., ser. Programmer to
programmer. John Wiley & Sons, 2007.
[17] Ubuntu Installation Guide, 20th ed., 2020. [Online]. Available: https://help.ubuntu.com/
lts/installation-guide/
[18] R. Mecklenburg, Managing Projects with Make, 3rd ed.
O’Reilly, 2004.
[19] B. P. Cheong. Python; a programming language changes the world. pcboey@pytech.com.
my. [Online]. Available: http://pytechresources.com
575
[20] M. Leotta, A. Perera, P. Reynolds, E. Swears, Y. Zhao, and V. Ganapathi. (2012)
Python for matlab users – promoting open source computer vision research. Kitware,
Inc. / Google Research. [Online]. Available: https://code.google.com/archive/p/pythonfor-matlab-users/downloads
[21] R. Johansson. Lectures on scientific computing with python. (Provides lengthy, but up
to date interesting information. The author has authored [27] as well.). [Online]. Available:
https:
//github.com/jrjohansson/scientific-python-lectures
[22] D. J. Raymond, Python for Science, 2017, (Succinct book suitable for experienced programmers). [Online].
Available: http://kestrel.nmt.edu/ ∼raymond/software/python notes/scientific python.pdf
[23] Scipy lecture notes. (An open–source collaborative documentation. A bit lengthy book suitable for novices with shallow
programming experience.). [Online]. Available: www.scipy-lectures.org/
[24] J. Storopoli, R. Huijzer, and L. Alonso. Julia data science. [Online]. Available:
https://juliadatascience.io
[25] E. Engheim, Julia for Beginners; from Romans to Rockets.
Available: https://leanpub.com/julia-for-beginners
SixtyNorth. [Online].
[26] [Online]. Available: https://docs.julialang.org/en/v1/manual/noteworthy-differences/
[27] R. Johansson, Numerical Python – A Practical Techniques Approach for Industry. Apress,
2015, (Classical length book for novices with no background of programming nor even numerical manipulation theory. Not a good
start for Matlab programmers aware of numerical analysis algorithms.).
576
Index
3.5G, 423
3G, 422
4G, 423
10 Gigabit Ethernet, 83
32–bit, 13
64–bit, 13
A
Access Point, 89
Accessing Arrays, 159
Adobe Illustrator, 373
ADSL, 95, 422
ADSL2, 422
ADSL2+, 422
Adware, 64
AIX, 52
algorithm, 323
AMD64, 13
Apache License, 40
API, 47
Arch Linux, 401
Arithmetic Operators, 146
Armadillo, 329
Arrays, 149
ASICs, 17
AutoCad, 381
B
Beagle–bone, 37
Beamer, 355
Bisection method, 235
BLAS, 270
bmp, 372
Boost, 270, 297
Bot, 64
Branch, 71
breaks, 366
Bridge, 90
BSD, 52
BSD license, 40
Btrfs, 79
C
C++, 261
CAD, 381
CAE, 381
CAM, 381
CAPE, 381
CATIA, 381
Cell Arrays, 152
CentOS, 400
Chrome, 140
chromium, 140
CLI, 48
Client-server, 93
Clone, 45
Cloud, 120
Cloud Computing, 120
Cluster, 15
Column-wise, 301
Compiler, 261
Computer Name, 111
Corel Draw, 373
CPU, 8, 13
CPU architecture, 13
Creo, 381
Cross–Platform, 62
Cross-Reference, 365
CVS, 276
D
Data Rates, 421
Debian, 401
Debugging, 199, 283
DHCP, 102
DHCP server, 101
Dia, 386
DirectDraw, 270
Distributed OS, 49
Distributed Processing, 15
DNS, 111, 112
Domain, 94
DOS, 57
Dynamic IP, 102
Dynamic Linking, 265
E
Eclipse, 268, 295
EDGE, 422
elementary OS, 401
Embedded Computer, 22
Embedded OS, 48
emf, 198, 372
ENIAC, 3
577
eps, 372
Ethernet, 82
exFAT, 79
ext4, 79
extender, 90
F
False position method, 236
FAT 16, 79
FAT 32, 79
Fedora, 400
FFTW, 270
File Sharing, 136
Fixed IP, 102
Fork, 71
Fortran, 259
FOSS, 40
FPGA, 17
FPGAs, 17
Free Software, 39
FreeBSD, 53
Function, 168
Function plotter, 377
G
gateway, 105
GDB, 431
Gentoo, 401
Gigabit Ethernet, 83, 422
Git, 276
GNU OS, 54
GNU project, 54
GNU/Linux OS, 57
GNU–Octave, 228
gnuplot, 270
Google Summer of Code,
79
GPL, 40
GPU, 9, 17, 19
Grace, 270
Grid, 15
GUI, 48
H
hackers, 117
hardware, 1
HBM, 19
Heterogeneous
ing, 17
HP–UX, 52
HSDPA, 423
HSUPA, 423
Hub, 88
Comput-
I
IaaS, 120
IANA, 100
ICANN, 100
IDE, 267
Ideas, 381
IEEE 802.11ac, 422
IEEE 802.11ax, 422
IEEE 802.11b, 422
IEEE 802.11g, 422
IEEE 802.11n, 422
IMAP, 140
IMSL, 270, 297
Index, 159
Infiniband, 422
infrastructure mode, 90
Inkscape, 373, 374
Internet, 95
Internet-Domain-Name,
111
Inventor, 381
IP, 98
IP address, 99
IPv4, 100
IPv6, 100
IPython Notebook, 486
IRIX, 52
ISO–8859–6, 72
ISP, 95
ISV, 9
J
JIS, 72
Joliet, 79
jpg, 198, 372
Julia, 228, 507
Jupyter Notebook, 486
K
Kubuntu, 401
L
L2 switching, 89
L3 routing, 89
LA, 92
LACP, 92
LAG, 92
LAN, 82
LAPACK, 270, 274
LATEX, 348
Layer 2 switching, 89
Layer 3 routing, 89
LGPL, 40
License, 40
Linker, 264
Linux, 55
Linux Distribution, 57
LinuxMint, 401
Logical Indexing, 161
Logical Operators, 147
LTE, 423
LYX, 352
M
.m file, 166
MAC, 99
Mac OS X, 52–54
Macintosh, 4
Mageia, 400
Make, 437
managed switches, 89
Mandriva, 400
Manjaro, 401
Matlab, xviii, 143
matplotlib, 270, 274
Matrices, 150
Mechanical Desktop, 381
Memory, 8
MEX, 280
MEX-File, 280
Microcontroller, 23
MiKTEX, 351
MinGW-w64, 433
MINIX, 55
Mixed Language Programming, 280
MKL, 270, 271, 275
Modem, 95
MS Word, 359
MSX, 4, 24
Multicore Processors, 14
Multimedia server, 109
578
Multiprocessing, 14
multi-threading, 266
MUMPS, 270
N
NAS, 109
NAT, 105
NBNS, 111, 112
NetBeans, 268
NetBIOS, 111
NIC, 17, 99
Normal.dotm, 362
NTFS, 79
NumPy, 270, 274
NX, 381
NX-Ideas, 381
O
object code, 261
OOP, 201, 425
OpenGL, 270
openSUSE, 400
Operator Precedence, 147
OS, 47
OS/2, 59
OSS, 39
P
P2P, 93
PaaS, 120
Paragraph, 360
Parallel Computing, 6, 14
PARDISO, 270
PC, 7
PCLinuxOS, 400
pdf, 198, 368, 372
Peer-to-peer, 93
phishing, 80
Plotly, 270
PLplot, 270
png, 198, 372
POP3, 140
Portability, 368
Powerline Networks, 91
Preprocessor, 263
print server, 109
Privacy, 121
Pro/Engineer, 381
Project management, 387
protocol, 98
public IP, 105
Python, 228, 479
R
Ransomware, 64
Rasperry–Pi, 37
Raster graphics, 371
Red Hat Enterprise, 400
Regular Expressions, 278
Relational Operators, 147
release notes, 79
Repeater, 90
Reserved IP addresses, 101
Revision Control, 276
Revision Control System,
276
RHEL, 400
Root Name Servers, 113
rootkits, 80, 117
Router, 104, 105
Row-wise, 301
RTOS, 48
S
SaaS, 120
SageMath, 228, 386, 504
Samba, 129
SAS, 423
Scilab, 228
SciPy, 270, 274
Script, 166
Secant method, 235
Security, 117
SGI, 270
Shared library, 266
SLE, 400
smart managed switches,
89
SMB, 129
software, 1
SOHO, 86, 108
Solaris, 52
Solid Edge, 381
SolidWorks, 381
spam, 80, 117
Sparse matrices, 227
SPOOLES, 270
Spyware, 64
spyware, 80
static IP, 102
Static library, 266
Static Linking, 264
STL, 270, 274
Storage, 10
Style, 361
Subnet Mask, 103
Subscript, 159
SUS, 52
SUSE Linux Enterprise,
400
svg, 198, 372
SVN, 276
Switch, 88, 105
T
Tabs, 362
TCP, 98
TCP/IP, 97
Teaming, 92
Template, 362
Tex Live, 351
Text editor, 267
TexText, 377
The Current Folder, 144
transistors, 4
Trojan, 64, 80
U
Ubuntu, 401
UDF, 79
UDP, 98
579
UMTS, 422
unicode, 72
UNICS, 52
Unigraphics, 381
UNIVAC, 3
Unix, 52
Unix–like, 52
unmanaged switches, 89
V
V.92, 422
Vector graphics, 371
Vector Indices, 159
Vector Subscripts, 160
Vectors, 149
Virus, 64
Visio, 386
Visual Studio, 268
VPN, 91
VTK, 270
W
WAN, 82
Wi-Fi, 83
Windows–1256, 72
WINS, 112
Wireless Ethernet, 83
Workgroup, 94
Worm, 64
X
x86, 13
x86–64, 13
Xcode, 268
Xenix, 52
Y
yED, 386
Z
ZFS, 79
0
You can add this document to your study collection(s)
Sign in Available only to authorized usersYou can add this document to your saved list
Sign in Available only to authorized users(For complaints, use another form )