introduction to mathematica scientific computing and visualization boston university katia oleinik...

36
Introduction to Mathematica Scientific Computing and Visualization Boston University Katia Oleinik [email protected]

Upload: kristin-daniels

Post on 16-Dec-2015

219 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Introduction to Mathematica Scientific Computing and Visualization Boston University Katia Oleinik koleinik@bu.edu

Introduction to Mathematica

Scientific Computing and Visualization

Boston University

Katia [email protected]

Page 2: Introduction to Mathematica Scientific Computing and Visualization Boston University Katia Oleinik koleinik@bu.edu

Getting Started

Notebook and Text-Based Interfaces

To start Mathematica on SCC cluster, type mathematica (or Mathematica) at the prompt:

% mathematica

To start Mathematica Kernel ( text-base interface), type math at the prompt:

% math

Page 3: Introduction to Mathematica Scientific Computing and Visualization Boston University Katia Oleinik koleinik@bu.edu

Getting Started

Notebook and Text-Based Interfaces

To start Mathematica on Windows:

Start -> Wolfram Mathematica -> Wolfram Mathematica 9

To start Mathematica Kernel ( text-base interface) on Windows: Start -> Wolfram Mathematica -> Wolfram Mathematica 9 Kernel

Page 4: Introduction to Mathematica Scientific Computing and Visualization Boston University Katia Oleinik koleinik@bu.edu

Getting Started

Notebook and Text-Based Interfaces

Notebook Interface Text-Based Interface

Start mathematica math

Execute command Shift-Enter Enter

Exit Choose the Quit menu item Cntr-D or Quit[]

Page 5: Introduction to Mathematica Scientific Computing and Visualization Boston University Katia Oleinik koleinik@bu.edu

Numerical Calculations

21.7 + 19.94

In[1] := 21.7 + 19.94Out[1] := 41.64

Press Shift + Enter

Page 6: Introduction to Mathematica Scientific Computing and Visualization Boston University Katia Oleinik koleinik@bu.edu

Numerical Calculations

x+y+z add

x-y subtract

x/y divide

x y z or x*y*z multiply

x^y power

x*(y+z) control grouping by parentheses

Note: You can use space or a * sign for multiplication

Page 7: Introduction to Mathematica Scientific Computing and Visualization Boston University Katia Oleinik koleinik@bu.edu

Numerical Calculations

You get exact result with Mathematica unless you request otherwise.

In[1] := 2 ^ 100 (* get exact result *)Out[1] := 1267650600228229401496703205376

In[2] := 2 ^ 100 //N (* get approximation *)Out[2] := 1.26765x1030

In[3] := 1/3 + 2/7 (* get exact result *)Out[3] :=

In[4] := 1/3 + 2/7 //N (* get approximation *)Out[4] := 0.619048

Page 8: Introduction to Mathematica Scientific Computing and Visualization Boston University Katia Oleinik koleinik@bu.edu

Numerical Calculations

If an input number contains an explicit decimal point, Mathematica produces an approximate numerical result.

In[5] := 11/3 + 2/7 (* exact result *)Out[5] :=

In[6] := 1.1/3 + 2/7 (* approximation *)Out[6] := 0.652381

Page 9: Introduction to Mathematica Scientific Computing and Visualization Boston University Katia Oleinik koleinik@bu.edu

Numerical Calculations

Sqrt[x]

Exp[x] exLog[x] ln x

Log[b,x] logb xSin[x], Cos[x], Tan[x] trigonometric functions

ArcSin[x], ... inverse trigonometric functions

n! factorial

FactorInteger[n] prime factors of nAbs[x] |x|

Round[x] closest integer to xMax[x,y,...], Min[x,y,...] maximum and minimum of a set

Mod[n,m] remainder of division of n by mRandom[] random number between 0 and 1

Common Mathematical Functions

Page 10: Introduction to Mathematica Scientific Computing and Visualization Boston University Katia Oleinik koleinik@bu.edu

Numerical Calculations

Functions in Mathematica

• The arguments of ALL Mathematica functions are enclosed in square brackets;

• The names of built-in Mathematica functions begin with capital letters;

• Unless //N option or decimal point is present, Mathematica tries to output exact value

Page 11: Introduction to Mathematica Scientific Computing and Visualization Boston University Katia Oleinik koleinik@bu.edu

Numerical Calculations

Pi E e

Degree I i =

Infinity ∞

Common Mathematical Constants

The names of all built-in constants begin with capital letters.

Page 12: Introduction to Mathematica Scientific Computing and Visualization Boston University Katia Oleinik koleinik@bu.edu

Numerical Calculations

Specify the degree of precision

In[1] := N[Pi, 30] (* approximation *)Out[1] := 3.14159265358979323846264338328

In[2] := N[Sqrt[7], 10] Out[2] := 2.645751311

Page 13: Introduction to Mathematica Scientific Computing and Visualization Boston University Katia Oleinik koleinik@bu.edu

Numerical Calculations

Using Previous Results - use with care!

In[1] := 7 + 3Out[1] := 10

In[2] := % + 1Out[2] := 11

• % the last result generated

• %% the next-to-last result

• %n the result on output line Out[n]

Note: % is always defined to be the last result that Mathematica generated. It can be anywhere in the script!

Page 14: Introduction to Mathematica Scientific Computing and Visualization Boston University Katia Oleinik koleinik@bu.edu

Numerical Calculations

Variables definition

x = value assign a value to the variable x

x = y = value assign a value to both x and y

x = . or Clear[x] remove any value assigned to x

Notes: • Mathematica is case-sensitive;• To avoid confusion with built-in functions, choose names that start with lower-case

letters; • x y means x times y;• xy with no space means variable name xy;• 5x means 5 times x;

Page 15: Introduction to Mathematica Scientific Computing and Visualization Boston University Katia Oleinik koleinik@bu.edu

Numerical Calculations

Lists of Objects

List is a collection of several objects in Mathematica

In[1] := vec = {2, 4, 1.8}Out[1] := {2, 4, 1.8}

In[2] := vec^2Out[2] := {4, 16, 3.24}

In[3] := vec/(vec-1)Out[3] := {1, , 2.25}

In[4] := vec[[2]] (* extract second element *)Out[4] := 4

In[5] := Part[vec,1] (* extract first element *)Out[5] := 2

Page 16: Introduction to Mathematica Scientific Computing and Visualization Boston University Katia Oleinik koleinik@bu.edu

Graphics

Partial list of Mathematica’s graphs

• Graphics, Graphics3D

• Plot, Plot3D

• ListPlot, ListLinePlot, ListContourPlot, ListPlot3D

• ListLogPlot, ListPolarPlot, ListSurfacePlot3D, ListContourPlot3D

• PrarametricPlot, PolarPlot, RevolutionPlot3D, SphericalPlot3D,

• DensityPlot, ReliefPlot

• GraphPlot, ArrayPlot

• RegionPlot, ContourPlot, RegionPlot3D

Page 17: Introduction to Mathematica Scientific Computing and Visualization Boston University Katia Oleinik koleinik@bu.edu

Graphics

Partial List of Graphics Options

option name default value

AspectRatio 1/GoldenRatio the height-to-width ratio for the plot;

Axes True whether to include axes

AxesLabel None labels to be put on the axes

Frame False draw a frame around the plot

GridLines None what grid lines to include

PlotLabel None an expression to be printed as a label for the plot

PlotRange Automatic the range of coordinates to include in the plot

Ticks Automatic what tick marks to draw if there are axes

Page 18: Introduction to Mathematica Scientific Computing and Visualization Boston University Katia Oleinik koleinik@bu.edu

Graphics

Basic Features for Visualization Functions

Feature Classes:• Styles

• Colors, thickness, pointsize, opacity, …• Element appearance and shape

• Labels• Textual labels and tooltips• Legends

• Interactions• Built-in highlighting effects• Use elements for buttons, popup windows and other events

• Metadata• Wrapper used to include additional information• ChartElementFunction[] for custom appearances

Page 19: Introduction to Mathematica Scientific Computing and Visualization Boston University Katia Oleinik koleinik@bu.edu

Graphics

Feature Scope

Options:

• Specified globally and uniformly

• Examples: ChartStyle, CHartLabels, LabelingFunction, Background

Wrappers:

• Wrapped directly around data

• Can be used at any level, allows for targeted use

• Can be nested

• Examples: Tooltip, Style, Button, Labeled

Page 20: Introduction to Mathematica Scientific Computing and Visualization Boston University Katia Oleinik koleinik@bu.edu

Data Visualization

Basic Statistics Plots

Bar Chart, PieChart, BubbleChart

Histogram, SmoothHistogram, Density Histogram, Histogram3D

QuantilePlot,

ProbabilityPlot, ProbabilityScalePlot

BoxWhiskerChart,

DistributionChart

Page 21: Introduction to Mathematica Scientific Computing and Visualization Boston University Katia Oleinik koleinik@bu.edu

Functions

Function Definition

Use underscore _ after a variable name (function argument)

f([x_] := x^2 + 4 x + 4

To execute a function, simply call it with a given value:

f[1]

Mathematica’s built-in functions start with upper-case letter. Start with lower case letter for the user defined function.

Page 22: Introduction to Mathematica Scientific Computing and Visualization Boston University Katia Oleinik koleinik@bu.edu

Functions

Using Functions

Show function definition: ?f

Expend function: Expand[f[x + y + 1]]

Find derivative of a function: D[f[x], x]

Find integral of a function: Integrate[f[x] ,x]

Find definite integral of a function: Integrate[f[x] ,{x,0,1}]

Clear the definition of a function: Clear[f]

Page 23: Introduction to Mathematica Scientific Computing and Visualization Boston University Katia Oleinik koleinik@bu.edu

Equations

Solving equations

Define equation using double equal sign ==

Solve[4 x^2 + 4 x + 1 == 0]

Mathematica can solve an equation for one variable in terms of another

Solve[5 x^2 -2 Log[y] == 3 x,y]

Solve system of equations:

Solve[{x + 2 y == 5, 7 x – 5 x == -3},{x,y}]

Page 24: Introduction to Mathematica Scientific Computing and Visualization Boston University Katia Oleinik koleinik@bu.edu

Equations

Solving equations

Mathematica can solve algebraic equations in one variable for power less than 5 and

sometimes even higher. But there are some equations for which it is impossible to find the

root(s) algebraically. Mathematica will use Root object to represent the solution. Use N[%]

to evaluate the solution numerically.

In some cases Mathematica can solve equations involving other functions:

In[1] := Solve[Sin[x] == a, x]

Out[1] := {{ x -> ArcSin[a]}}

Page 25: Introduction to Mathematica Scientific Computing and Visualization Boston University Katia Oleinik koleinik@bu.edu

Equations

Solving equations

You can also find an approximate numerical solution using FindRoot[]:

In[1] := FindRoot[Cos[x] == x, {x,0}]

Out[1] := { x -> 0.739085}

Mathematica can solve system of simultaneous equations.

It can eliminate a variable in a system, using Eliminate[] function, or

simplify the system using Reduce[] function.

Page 26: Introduction to Mathematica Scientific Computing and Visualization Boston University Katia Oleinik koleinik@bu.edu

Programs

Programming Constructs

Assignments: = += ++ *= AppendTo

Loops: Do While For Table Nest

Conditionals: If Which Switch And(&&) Equal(==) Less(<) …

Flow Control: Return Throw Catch TimeConstrained

Scope Constructs: Module With Block

I/O: Print Input Pause Import OpenRead …

Page 27: Introduction to Mathematica Scientific Computing and Visualization Boston University Katia Oleinik koleinik@bu.edu

Code Optimization

How to speedup Mathematica code

Use Timing and AbsoluteTiming commands to measure the time of execution:

In[1] := Module[{x = 1/Pi},

Do[x = 3.5 x (1 - x),

{10^6}]; x] //AbsoluteTiming

Page 28: Introduction to Mathematica Scientific Computing and Visualization Boston University Katia Oleinik koleinik@bu.edu

Code Optimization

How to speedup Mathematica code

1. Use floating point approximation if you can and as early in the

code as possible

2. Compile Functions

3. Use parallelization options if possible

4. Use built-in functions

5. Use CudaLink if possible

Page 29: Introduction to Mathematica Scientific Computing and Visualization Boston University Katia Oleinik koleinik@bu.edu

HPC: Vectorization

Making a Compiled Function run in parallel is simple - the user only has to pass the option RuntimeAttributes->"Listable". From there, Compile will run in as many threads as there are on the system.

Automatic parallelization

raySpheresIntersectionColor = Compile[ . . . , CompilationTarget -> "C", RuntimeAttributes -> Listable];

rayTraceCompile[ . . . , raySpheresIntersectionColor[] ];

width = height = 300;

. . .

imgc = rayTraceCompile[centers, radii, colors, x, y];

Image[imgc]

Page 30: Introduction to Mathematica Scientific Computing and Visualization Boston University Katia Oleinik koleinik@bu.edu

HPC: GPU Programming

• Programming languages/environments that allow to write to program GPU to perform general computations.

• CUDA works only on NVIDIA hardware and is proprietary

• OpenCL works on AMD and NVIDIA hardware and is an open standard

CUDA and OpenCL

Page 31: Introduction to Mathematica Scientific Computing and Visualization Boston University Katia Oleinik koleinik@bu.edu

HPC: GPU Programming

Speed!

Modern GPUs are capable to perform 3 TFlops/sec, while high end CPUs – 80GFlops/sec

Fastest supercomputer at the end on 90s, clocked 1TFlop/sec and now you can buy GPU with the same speed for less than $500.

Speed comes from the hardware design.

Why GPU

Page 32: Introduction to Mathematica Scientific Computing and Visualization Boston University Katia Oleinik koleinik@bu.edu

HPC: GPU Programming

A way to use the Graphical Processing Unit (GPU) from within Mathematica integrating with the user’s workflow

A way to load GPU programs into Mathematica and use them as functions

It is NOT an attempt to make all Mathematica functions utilize the GPU

It is NOT meant to automatically speed up Mathematica code

Require :

1. NVIDIA hardware2. Recent video card driver3. Supported C – compiler

CUDALink

Page 33: Introduction to Mathematica Scientific Computing and Visualization Boston University Katia Oleinik koleinik@bu.edu

HPC: GPU Programming

CUDALink contains many built-in function for performing linear algebra, list and image processing, and Fourier analysis.

CUDALink

In[1] := Needs["CUDALink`"] (* Load CUDALink *)

In[2] := CUDAQ[] (* Check if system compatible with CUDA *)Out[2] := TRUE

In[3] := CUDAInformation[] (* Get information about detected GPU *)Out[3] := {1 -> {"Name" -> "Tesla M2070", "Clock Rate" -> 1147000, "Compute Capabilities" -> 2., "GPU Overlap" -> 1, "Maximum Block Dimensions" -> {1024, 1024, 64}, "Maximum Grid Dimensions" -> {65535, 65535, 65535},

Page 34: Introduction to Mathematica Scientific Computing and Visualization Boston University Katia Oleinik koleinik@bu.edu

HPC: GPU Programming

Once CUDALink is loaded built-in functions can be used:

CUDALink

In[1] := m1 = {{1, 1, 1}, {2, 2, 2}, {3, 3, 3}}

In[2] := m2 = {{0, 1, 0}, {1, 1, 1}, {0, 1, 0}}

In[3] := CUDADot[m1,m2] (* Multiply matricies*)

Out[2] := {{1, 3, 1}, {2, 6, 2}, {3, 9, 3}}

Page 35: Introduction to Mathematica Scientific Computing and Visualization Boston University Katia Oleinik koleinik@bu.edu

HPC: GPU Programming

Image Processing

CUDALink

In[1] := swan = Import["swan.JPG"]

Out[1] :=

In[2] := CUDAImageConvolve[swan, GaussianMatrix[16]] (* Convolution *)

Out[2] :=

Page 36: Introduction to Mathematica Scientific Computing and Visualization Boston University Katia Oleinik koleinik@bu.edu

This tutorial has been made possible by Scientific Computing and Visualization

groupat Boston University.

Katia [email protected]

http://www.bu.edu/tech/research/training/tutorials/list/