Python for Computational Science and Engineering

Total Page:16

File Type:pdf, Size:1020Kb

Python for Computational Science and Engineering Introduction to Python for Computational Science and Engineering (A beginner's guide) Hans Fangohr Faculty of Engineering and the Environment University of Southampton September 7, 2015 2 Contents 1 Introduction 9 1.1 Computational Modelling . .9 1.1.1 Introduction . .9 1.1.2 Computational Modelling . .9 1.1.3 Programming to support computational modelling . 10 1.2 Why Python for scientific computing? . 11 1.2.1 Optimisation strategies . 12 1.2.2 Get it right first, then make it fast . 13 1.2.3 Prototyping in Python . 13 1.3 Literature . 13 1.3.1 Recorded video lectures on Python for beginners . 13 1.3.2 Python tutor mailing list . 14 1.4 Python version . 14 1.5 This document . 14 1.6 Your feedback . 14 2 A powerful calculator 17 2.1 Python prompt and Read-Eval-Print Loop (REPL) . 17 2.2 Calculator . 17 2.3 Integer division . 18 2.3.1 How to avoid integer division . 18 2.3.2 Why should I care about this division problem? . 19 2.4 Mathematical functions . 20 2.5 Variables . 21 2.5.1 Terminology . 22 2.6 Impossible equations . 22 2.6.1 The += notation . 23 3 Data Types and Data Structures 25 3.1 What type is it? . 25 3.2 Numbers . 25 3.2.1 Integers . 25 3.2.2 Long integers . 26 3.2.3 Floating Point numbers . 26 3.2.4 Complex numbers . 27 3.2.5 Functions applicable to all types of numbers . 27 3.3 Sequences . 27 3.3.1 Sequence type 1: String . 28 3.3.2 Sequence type 2: List . 29 3.3.3 Sequence type 3: Tuples . 31 3 4 CONTENTS 3.3.4 Indexing sequences . 32 3.3.5 Slicing sequences . 33 3.3.6 Dictionaries . 35 3.4 Passing arguments to functions . 37 3.4.1 Call by value . 37 3.4.2 Call by reference . 38 3.4.3 Argument passing in Python . 39 3.4.4 Performance considerations . 40 3.4.5 Inadvertent modification of data . 41 3.4.6 Copying objects . 42 3.5 Equality and Identity/Sameness . 42 3.5.1 Equality . 42 3.5.2 Identity / Sameness . 43 3.5.3 Example: Equality and identity . 43 4 Introspection 45 4.1 dir() . 45 4.1.1 Magic names . 46 4.2 type .............................................. 46 4.3 isinstance . 47 4.4 help . 47 4.5 Docstrings . 49 5 Input and Output 51 5.1 Printing to standard output (normally the screen) . 51 5.1.1 Simple print (not compatible with Python 3.x) . 51 5.1.2 Formatted printing . 52 5.1.3 \str" and \ str ".................................. 53 5.1.4 \repr" and \ repr "................................. 53 5.1.5 Changes from Python 2 to Python 3: print .................... 54 5.1.6 Changes from Python 2 to Python 3: formatting of strings . 54 5.2 Reading and writing files . 55 5.2.1 File reading examples . 56 6 Control Flow 59 6.1 Basics . 59 6.1.1 Conditionals . 59 6.2 If-then-else . 61 6.3 For loop . 61 6.4 While loop . 62 6.5 Relational operators (comparisons) in if and while statements . 62 6.6 Exceptions . 63 6.6.1 Raising Exceptions . 64 6.6.2 Creating our own exceptions . 65 6.6.3 LBYL vs EAFP . 65 7 Functions and modules 67 7.1 Introduction . 67 7.2 Using functions . 67 7.3 Defining functions . 68 7.4 Default values and optional parameters . 70 CONTENTS 5 7.5 Modules . 71 7.5.1 Importing modules . 71 7.5.2 Creating modules . 72 7.5.3 Use of name .................................... 73 7.5.4 Example 1 . 73 7.5.5 Example 2 . 74 8 Functional tools 77 8.1 Anonymous functions . 77 8.2 Map.............................................. 78 8.3 Filter . 78 8.4 List comprehension . 79 8.5 Reduce . 80 8.6 Why not just use for-loops? . 82 8.7 Speed . 83 9 Common tasks 85 9.1 Many ways to compute a series . 85 9.2 Sorting . 88 10 From Matlab to Python 91 10.1 Important commands . 91 10.1.1 The for-loop . ..
Recommended publications
  • Foundations of Computational Science August 29-30, 2019
    Foundations of Computational Science August 29-30, 2019 Thursday, August 29 Time Speaker Title/Abstract 8:30 - 9:30am Breakfast 9:30 - 9:40am Opening Explainable AI and Multimedia Research Abstract: AI as a concept has been around since the 1950’s. With the recent ​ advancements in machine learning algorithms, and the availability of big data and large computing resources, the scene is set for AI to be used in many more systems and applications which will profoundly impact society. The current deep learning based AI systems are mostly in black box form and are often non-explainable. Though it has high performance, it is also known to make occasional fatal mistakes. 9:30 - 10:05am Tat Seng Chua This has limited the applications of AI, especially in mission critical applications. In this talk, I will present the current state-of-the arts in explainable AI, which holds promise to helping humans better understand and interpret the decisions made by the black-box AI models. This is followed by our preliminary research on explainable recommendation, relation inference in videos, as well as leveraging prior domain knowledge, information theoretic principles, and adversarial algorithms to achieving explainable framework. I will also discuss future research towards quality, fairness and robustness of explainable AI. Group Photo and 10:05 - 10:35am Coffee Break Deep Learning-based Chinese Language Computation at Tsinghua University: 10:35 - 10:50am Maosong Sun Progress and Challenges 10:50 - 11:05am Minlie Huang Controllable Text Generation 11:05 - 11:20am Peng Cui Stable Learning: The Convergence of Causal Inference and Machine Learning 11:20 - 11:45am Yike Guo Data Efficiency in Machine Learning Deep Approximation via Deep Learning Abstract: The primary task of many applications is approximating/estimating a ​ function through samples drawn from a probability distribution on the input space.
    [Show full text]
  • Computational Science and Engineering
    Computational Science and Engineering, PhD College of Engineering Graduate Coordinator: TBA Email: Phone: Department Chair: Marwan Bikdash Email: [email protected] Phone: 336-334-7437 The PhD in Computational Science and Engineering (CSE) is an interdisciplinary graduate program designed for students who seek to use advanced computational methods to solve large problems in diverse fields ranging from the basic sciences (physics, chemistry, mathematics, etc.) to sociology, biology, engineering, and economics. The mission of Computational Science and Engineering is to graduate professionals who (a) have expertise in developing novel computational methodologies and products, and/or (b) have extended their expertise in specific disciplines (in science, technology, engineering, and socioeconomics) with computational tools. The Ph.D. program is designed for students with graduate and undergraduate degrees in a variety of fields including engineering, chemistry, physics, mathematics, computer science, and economics who will be trained to develop problem-solving methodologies and computational tools for solving challenging problems. Research in Computational Science and Engineering includes: computational system theory, big data and computational statistics, high-performance computing and scientific visualization, multi-scale and multi-physics modeling, computational solid, fluid and nonlinear dynamics, computational geometry, fast and scalable algorithms, computational civil engineering, bioinformatics and computational biology, and computational physics. Additional Admission Requirements Master of Science or Engineering degree in Computational Science and Engineering (CSE) or in science, engineering, business, economics, technology or in a field allied to computational science or computational engineering field. GRE scores Program Outcomes: Students will demonstrate critical thinking and ability in conducting research in engineering, science and mathematics through computational modeling and simulations.
    [Show full text]
  • Artificial Intelligence Research For
    Charles Xie ([email protected]) is a senior scientist who works at the inter- section between computational science and learning science. Artificial Intelligence research for engineering design By Charles Xie Imagine a high school classroom in 2030. AI is one of the three most promising areas for which Bill Gates Students are challenged to design an said earlier this year he would drop out of college again if he were a young student today. The victory of Google’s AlphaGo against engineering system that meets the needs of a top human Go player in 2016 was a landmark in the history of their community. They work with advanced AI. The game of Go is considered a difficult challenge because computer-aided design (CAD) software that the number of legal positions on a 19×19 grid is estimated to be leverages the power of scientific simulation, 2×10170, far more than the total number of atoms in the observ- mixed reality, and cloud computing. Every able universe combined (1082). While AlphaGo may be only a cool tool needed to complete an engineering type of weak AI that plays Go at present, scientists believe that its development will engender technologies that eventually find design project is seamlessly integrated into applications in other fields. the CAD platform to streamline the learning process. But the most striking capability of Performance modeling the software is its ability to act like a mentor (e.g., simulation-based analysis) who has all the knowledge about the design project to answer questions, learns from all the successful or unsuccessful solutions ever Evaluator attempted by human designers or computer agents, adapts to the needs of each student based on experience interacting with all sorts of designers, inspires students to explore creative ideas, and, most importantly, remains User Ideator responsive all the time without ever running out of steam.
    [Show full text]
  • How to Access Python for Doing Scientific Computing
    How to access Python for doing scientific computing1 Hans Petter Langtangen1,2 1Center for Biomedical Computing, Simula Research Laboratory 2Department of Informatics, University of Oslo Mar 23, 2015 A comprehensive eco system for scientific computing with Python used to be quite a challenge to install on a computer, especially for newcomers. This problem is more or less solved today. There are several options for getting easy access to Python and the most important packages for scientific computations, so the biggest issue for a newcomer is to make a proper choice. An overview of the possibilities together with my own recommendations appears next. Contents 1 Required software2 2 Installing software on your laptop: Mac OS X and Windows3 3 Anaconda and Spyder4 3.1 Spyder on Mac............................4 3.2 Installation of additional packages.................5 3.3 Installing SciTools on Mac......................5 3.4 Installing SciTools on Windows...................5 4 VMWare Fusion virtual machine5 4.1 Installing Ubuntu...........................6 4.2 Installing software on Ubuntu....................7 4.3 File sharing..............................7 5 Dual boot on Windows8 6 Vagrant virtual machine9 1The material in this document is taken from a chapter in the book A Primer on Scientific Programming with Python, 4th edition, by the same author, published by Springer, 2014. 7 How to write and run a Python program9 7.1 The need for a text editor......................9 7.2 Spyder................................. 10 7.3 Text editors.............................. 10 7.4 Terminal windows.......................... 11 7.5 Using a plain text editor and a terminal window......... 12 8 The SageMathCloud and Wakari web services 12 8.1 Basic intro to SageMathCloud...................
    [Show full text]
  • An Evaluation of Tensorflow As a Programming Framework for HPC Applications
    DEGREE PROJECT IN COMPUTER SCIENCE AND ENGINEERING, SECOND CYCLE, 30 CREDITS STOCKHOLM, SWEDEN 2018 An Evaluation of TensorFlow as a Programming Framework for HPC Applications WEI DER CHIEN KTH ROYAL INSTITUTE OF TECHNOLOGY SCHOOL OF ELECTRICAL ENGINEERING AND COMPUTER SCIENCE An Evaluation of TensorFlow as a Programming Framework for HPC Applications WEI DER CHIEN Master in Computer Science Date: August 28, 2018 Supervisor: Stefano Markidis Examiner: Erwin Laure Swedish title: En undersökning av TensorFlow som ett utvecklingsramverk för högpresterande datorsystem School of Electrical Engineering and Computer Science iii Abstract In recent years, deep-learning, a branch of machine learning gained increasing popularity due to their extensive applications and perfor- mance. At the core of these application is dense matrix-matrix multipli- cation. Graphics Processing Units (GPUs) are commonly used in the training process due to their massively parallel computation capabili- ties. In addition, specialized low-precision accelerators have emerged to specifically address Tensor operations. Software frameworks, such as TensorFlow have also emerged to increase the expressiveness of neural network model development. In TensorFlow computation problems are expressed as Computation Graphs where nodes of a graph denote operation and edges denote data movement between operations. With increasing number of heterogeneous accelerators which might co-exist on the same cluster system, it became increasingly difficult for users to program efficient and scalable applications. TensorFlow provides a high level of abstraction and it is possible to place operations of a computation graph on a device easily through a high level API. In this work, the usability of TensorFlow as a programming framework for HPC application is reviewed.
    [Show full text]
  • A Brief Introduction to Mathematical Optimization in Julia (Part 1) What Is Julia? and Why Should I Care?
    A Brief Introduction to Mathematical Optimization in Julia (Part 1) What is Julia? And why should I care? Carleton Coffrin Advanced Network Science Initiative https://lanl-ansi.github.io/ Managed by Triad National Security, LLC for the U.S. Department of Energy’s NNSA LA-UR-21-20278 Warning: This is not a technical talk! 9/25/2019 Julia_prog_language.svg What is Julia? • A “new” programming language developed at MIT • nearly 10 years old (appeared around 2012) • Julia is a high-level, high-performance, dynamic programming language • free and open source • The Creator’s Motivation • build the next-generation of programming language for numerical analysis and computational science • Solve the “two-language problem” (you havefile:///Users/carleton/Downloads/Julia_prog_language.svg to choose between 1/1 performance and implementation simplicity) Who is using Julia? Julia is much more than an academic curiosity! See https://juliacomputing.com/ Why Julia? Application9/25/2019 Julia_prog_language.svg Needs Data Scince Numerical Scripting Computing Automation 9/25/2019 Thin-Border-Logo-Text Julia Data Differential Equations file:///Users/carleton/Downloads/Julia_prog_language.svg 1/1 Deep Learning Mathematical Optimization High Performance https://camo.githubusercontent.com/31d60f762b44d0c3ea47cc16b785e042104a6e03/68747470733a2f2f7777772e6a756c69616f70742e6f72672f696d616765732f6a7… 1/1
    [Show full text]
  • C Language Tutorial
    C Language Tutorial Version 0.042 March, 1999 Original MS-DOS tutorial by Gordon Dodrill, Coronado Enterprises. Moved to Applix by Tim Ward Typed by Karen Ward C programs converted by Tim Ward and Mark Harvey with assistance from Kathy Morton for Visual Calculator Pretty printed by Eric Lindsay Applix 1616 microcomputer project Applix Pty Ltd Introduction The C programming language was originally developed by Dennis Ritchie of Bell Laboratories, and was designed to run on a PDP-11 with a UNIX operating system. Although it was originally intended to run under UNIX, there was a great interest in running it on the IBM PC and com- patibles, and other systems. C is excellent for actually writing system level programs, and the entire Applix 1616/OS operating system is written in C (except for a few assembler routines). It is an excellent language for this environment because of the simplicity of expression, the compactness of the code, and the wide range of applicability. It is not a good "beginning" language because it is somewhat cryptic in nature. It allows the programmer a wide range of operations from high level down to a very low level approaching the level of assembly language. There seems to be no limit to the flexibility available. One experienced C programmer made the statement, "You can program anything in C", and the statement is well supported by my own experience with the language. Along with the resulting freedom however, you take on a great deal of responsibility. It is very easy to write a program that destroys itself due to the silly little errors that, say, a Pascal compiler will flag and call a fatal error.
    [Show full text]
  • Goless Documentation Release 0.6.0
    goless Documentation Release 0.6.0 Rob Galanakis July 11, 2014 Contents 1 Intro 3 2 Goroutines 5 3 Channels 7 4 The select function 9 5 Exception Handling 11 6 Examples 13 7 Benchmarks 15 8 Backends 17 9 Compatibility Details 19 9.1 PyPy................................................... 19 9.2 Python 2 (CPython)........................................... 19 9.3 Python 3 (CPython)........................................... 19 9.4 Stackless Python............................................. 20 10 goless and the GIL 21 11 References 23 12 Contributing 25 13 Miscellany 27 14 Indices and tables 29 i ii goless Documentation, Release 0.6.0 • Intro • Goroutines • Channels • The select function • Exception Handling • Examples • Benchmarks • Backends • Compatibility Details • goless and the GIL • References • Contributing • Miscellany • Indices and tables Contents 1 goless Documentation, Release 0.6.0 2 Contents CHAPTER 1 Intro The goless library provides Go programming language semantics built on top of gevent, PyPy, or Stackless Python. For an example of what goless can do, here is the Go program at https://gobyexample.com/select reimplemented with goless: c1= goless.chan() c2= goless.chan() def func1(): time.sleep(1) c1.send(’one’) goless.go(func1) def func2(): time.sleep(2) c2.send(’two’) goless.go(func2) for i in range(2): case, val= goless.select([goless.rcase(c1), goless.rcase(c2)]) print(val) It is surely a testament to Go’s style that it isn’t much less Python code than Go code, but I quite like this. Don’t you? 3 goless Documentation, Release 0.6.0 4 Chapter 1. Intro CHAPTER 2 Goroutines The goless.go() function mimics Go’s goroutines by, unsurprisingly, running the routine in a tasklet/greenlet.
    [Show full text]
  • From Computational Science to Science Discovery
    FromComputationalSciencetoScienceDiscovery:The NextComputingLandscape GiladShainer,BrianSparks,ScotSchultz,EricLantz,WilliamLiu,TongLiu,GoldiMisra HPCAdvisoryCouncil {Gilad,Brian,Scot,Eric,William,Tong,[email protected]} Computationalscienceisthefieldofstudyconcernedwithconstructingmathematicalmodelsand numericaltechniquesthatrepresentscientific,socialscientificorengineeringproblemsandemploying thesemodelsoncomputers,orclustersofcomputerstoanalyze,exploreorsolvethesemodels. Numericalsimulationenablesthestudyofcomplexphenomenathatwouldbetooexpensiveor dangeroustostudybydirectexperimentation.Thequestforeverhigherlevelsofdetailandrealismin suchsimulationsrequiresenormouscomputationalcapacity,andhasprovidedtheimpetusfor breakthroughsincomputeralgorithmsandarchitectures.Duetotheseadvances,computational scientistsandengineerscannowsolvelargeͲscaleproblemsthatwereoncethoughtintractableby creatingtherelatedmodelsandsimulatethemviahighͲperformancecomputeclustersor supercomputers.Simulationisbeingusedasanintegralpartofthemanufacturing,designanddecisionͲ makingprocesses,andasafundamentaltoolforscientificresearch.ProblemswherehighͲperformance simulationplayapivotalroleincludeforexampleweatherandclimateprediction,nuclearandenergy research,simulationanddesignofvehiclesandaircrafts,electronicdesignautomation,astrophysics, quantummechanics,biology,computationalchemistryandmore. Computationalscienceiscommonlyconsideredthethirdmodeofscience,wherethepreviousmodesor paradigmswereexperimentation/observationandtheory.Inthepast,sciencewasperformedby
    [Show full text]
  • IMPLEMENTING OPTION PRICING MODELS USING PYTHON and CYTHON Sanjiv Dasa and Brian Grangerb
    JOURNAL OF INVESTMENT MANAGEMENT, Vol. 8, No. 4, (2010), pp. 1–12 © JOIM 2010 JOIM www.joim.com IMPLEMENTING OPTION PRICING MODELS USING PYTHON AND CYTHON Sanjiv Dasa and Brian Grangerb In this article we propose a new approach for implementing option pricing models in finance. Financial engineers typically prototype such models in an interactive language (such as Matlab) and then use a compiled language such as C/C++ for production systems. Code is therefore written twice. In this article we show that the Python programming language and the Cython compiler allows prototyping in a Matlab-like manner, followed by direct generation of optimized C code with very minor code modifications. The approach is able to call upon powerful scientific libraries, uses only open source tools, and is free of any licensing costs. We provide examples where Cython speeds up a prototype version by over 500 times. These performance gains in conjunction with vast savings in programmer time make the approach very promising. 1 Introduction production version in a compiled language like C, C++, or Fortran. This duplication of effort slows Computing in financial engineering needs to be fast the deployment of new algorithms and creates ongo- in two critical ways. First, the software development ing software maintenance problems, not to mention process must be fast for human developers; pro- added development costs. grams must be easy and time efficient to write and maintain. Second, the programs themselves must In this paper we describe an approach to tech- be fast when they are run. Traditionally, to meet nical software development that enables a single both of these requirements, at least two versions of version of a program to be written that is both easy a program have to be developed and maintained; a to develop and maintain and achieves high levels prototype in a high-level interactive language like of performance.
    [Show full text]
  • High-Performance Computation with Python | Python Academy | Training IT
    Training: Python Academy High-Performance Computation with Python Training: Python Academy High-Performance Computation with Python TRAINING GOALS: The requirement for extensive and challenging computations is far older than the computing industry. Today, software is a mere means to a specific end, it needs to be newly developed or adapted in countless places in order to achieve the special goals of the users and to run their specific calculations efficiently. Nothing is of more avail to this need than a programming language that is easy for users to learn and that enables them to actively follow and form the realisation of their requirements. Python is this programming language. It is easy to learn, to use and to read. The language makes it easy to write maintainable code and to use it as a basis for communication with other people. Moreover, it makes it easy to optimise and specialise this code in order to use it for challenging and time critical computations. This is the main subject of this course. CONSPECT: Optimizing Python programs Guidelines for optimization. Optimization strategies - Pystone benchmarking concept, CPU usage profiling with cProfile, memory measuring with Guppy_PE Framework. Participants are encouraged to bring their own programs for profiling to the course. Algorithms and anti-patterns - examples of algorithms that are especially slow or fast in Python. The right data structure - comparation of built-in data structures: lists, sets, deque and defaulddict - big-O notation will be exemplified. Caching - deterministic and non-deterministic look on caching and developing decorates for these purposes. The example - we will use a computionally demanding example and implement it first in pure Python.
    [Show full text]
  • Julia: a Fresh Approach to Numerical Computing∗
    SIAM REVIEW c 2017 Society for Industrial and Applied Mathematics Vol. 59, No. 1, pp. 65–98 Julia: A Fresh Approach to Numerical Computing∗ Jeff Bezansony Alan Edelmanz Stefan Karpinskix Viral B. Shahy Abstract. Bridging cultures that have often been distant, Julia combines expertise from the diverse fields of computer science and computational science to create a new approach to numerical computing. Julia is designed to be easy and fast and questions notions generally held to be \laws of nature" by practitioners of numerical computing: 1. High-level dynamic programs have to be slow. 2. One must prototype in one language and then rewrite in another language for speed or deployment. 3. There are parts of a system appropriate for the programmer, and other parts that are best left untouched as they have been built by the experts. We introduce the Julia programming language and its design|a dance between special- ization and abstraction. Specialization allows for custom treatment. Multiple dispatch, a technique from computer science, picks the right algorithm for the right circumstance. Abstraction, which is what good computation is really about, recognizes what remains the same after differences are stripped away. Abstractions in mathematics are captured as code through another technique from computer science, generic programming. Julia shows that one can achieve machine performance without sacrificing human con- venience. Key words. Julia, numerical, scientific computing, parallel AMS subject classifications. 68N15, 65Y05, 97P40 DOI. 10.1137/141000671 Contents 1 Scientific Computing Languages: The Julia Innovation 66 1.1 Julia Architecture and Language Design Philosophy . 67 ∗Received by the editors December 18, 2014; accepted for publication (in revised form) December 16, 2015; published electronically February 7, 2017.
    [Show full text]