Python Programming- Analysis and Geophysics Insights

c e r i 8 1 04 d ata a nalysis in g eophysics n.w
1 / 31
Embed
Share

Gain valuable insights into Python programming in geophysics analysis through Dr. Robert Smalley's course. Explore the advantages of high-level languages and learn to run Python interactively using different environments like command line and IDEs.

  • Python programming
  • Geophysics analysis
  • High-level languages
  • Dr. Robert Smalley
  • Data analysis

Uploaded on | 0 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.

E N D

Presentation Transcript


  1. C E R I- -8 1 04 D ata A nalysis in G eophysics D r. R obert (B ob) S malley 3 8 9 2 C entral A ve, R oom 1 03 rsmalley@ memphis.edu F all 2 02 3 T u & T h 1 1 :2 0 am 8 1 04 D ata A nalysis in G eophysics D r. R obert (B ob) S malley 3 8 9 2 C entral A ve, R oom 1 03 rsmalley@ memphis.edu F all 2 02 3 T u & T h 1 1 :2 0 am - -1 2 :45 pm C E R I 6 7 8 6 7 8 - -49 2 9 49 2 9 1 2 :45 pm M eeting 1 8 M eeting 1 8 T hu. O ct 3 1 , 2 02 3 T hu. O ct 3 1 , 2 02 3 C E R I N ew/ L ong B uilding: S tudent C omputer L ab C lass webpage to be announced. M y homepage (has older versions of the course) http:/ / www.ceri.memphis.edu/ people/ smalley/ C E R I N ew/ L ong B uilding: S tudent C omputer L ab C lass webpage to be announced. M y homepage (has older versions of the course) http:/ / www.ceri.memphis.edu/ people/ smalley/

  2. Introduction to P Y T H O N Introduction to P Y T H O N P ython can be run interactively through: P ython can be run interactively through: C ommand line C ommand line S pyder or other "ide" evelopment E E nvironment for P ython) S pyder or other "ide" ( (IIntegrated ntegrated D D evelopment nvironment for P ython) "N otebooks" N otebooks, google colab "N otebooks" ( (J upyter J upyter N otebooks, google colab) )

  3. P ython is a high level language. https:/ / en.wikipedia.org/ wiki/ H igh A high programmers to write programs that are more or less independent of a particular type of computer. S uch languages are considered high human languages and further from machine languages, which are known as low P ython is a high level language. https:/ / en.wikipedia.org/ wiki/ H igh- -level_ programming_ language A high- -level language (H L L ) is a programming language that enables programmers to write programs that are more or less independent of a particular type of computer. S uch languages are considered high- -level because they are closer to human languages and further from machine languages, which are known as low- -level languages (L L L ). level_ programming_ language level language (H L L ) is a programming language that enables level because they are closer to level languages (L L L ).

  4. A dvantages of H igh A dvantages of H igh- -L evel L anguages L evel L anguages T he main advantage of H L L s over L L L s is that H L L s are easier to read, write, and maintain. T he main advantage of H L L s over L L L s is that H L L s are easier to read, write, and maintain. U ltimately, programs written in a H L L must be translated into machine language by a U ltimately, programs written in a H L L must be translated into machine language by a compiler compiler or or interpreter interpreter.. T he first high T he first high- -level programming languages were designed in the 1 9 5 0s ( N ow there are dozens of different languages. level programming languages were designed in the 1 9 5 0s (eg. N ow there are dozens of different languages. eg. F O R T R A N , C O B O L ). F O R T R A N , C O B O L ).

  5. In addition to being a H L L , P ython is also a computer language. A general applicable across application domains and lacks specialized features for any particular domain. it to bake anything acceptably (e.g. C , P ython). A specialized to a particular application domain. Is like bread flour for better bread and cake flour for better cake F ortran, M atlab). In addition to being a H L L , P ython is also a general computer language. general- -purpose language applicable across application domains and lacks specialized features for any particular domain. It is similar to all it to bake anything acceptably.. (e.g. C , P ython). A domain specialized to a particular application domain. Is like bread flour for better bread and cake flour for better cake . (e.g. F ortran, M atlab). general- -purpose purpose A purpose language is a computer language that is broadly is a computer language that is broadly It is similar to all- -purpose flour, you can use purpose flour, you can use domain- -specific language specific language (D S L ) is a computer language (D S L ) is a computer language . (e.g.

  6. A P ython P rimer for M atlab U sers A P ython P rimer for M atlab U sers T his gives an overview of the differences between M A T L A B and P Y T H O N . T his gives an overview of the differences between M A T L A B and P Y T H O N .

  7. W hy would you want to use P ython over M atlab? W hy would you want to use P ython over M atlab? B ecause P ython is free and M atlab is not. B ecause P ython is free and M atlab is not. (but you get what you pay for. U N IX is free also!) (but you get what you pay for. U N IX is free also!) B ecause P ython is a general B ecause P ython is a general- -purpose programming language and M atlab is not. purpose programming language and M atlab is not. F or a very particular set of problems, M atlab is an awesome tool. F or many other problems however, it is just about unusable. F or a very particular set of problems, M atlab is an awesome tool. F or many other problems however, it is just about unusable.

  8. T he biggest strength of M atlab is its matrix engine. T he biggest strength of M atlab is its matrix engine. P ython, by itself, does not have a convenient matrix engine. P ython, by itself, does not have a convenient matrix engine. H owever, there are three packages (think M atlab T oolboxes) that will add this capability to P ython: Numpy (the matrix engine) H owever, there are three packages (think M atlab T oolboxes) that will add this capability to P ython: (the matrix engine) Scipy (matrix manipulation) (matrix manipulation) Matplotlib (plotting) (plotting)

  9. L ike M atlab, P ython is L ike M atlab, P ython is Interpreted Interpreted and code can be copied from one machine to another and will run without change. (except for some hardware dependent programs) and code can be copied from one machine to another and will run without change. (except for some hardware dependent programs)

  10. dynamically typed, that is, every variable can hold data of any type, as in: a = 5 # a number a = [1, 2, 3] # a list a = 'text' # a string L ike M atlab, P ython is L ike M atlab, P ython is dynamically typed hold data of any type, as in: , that is, every variable can but each call "clobbers" the old definition, you don t get 3 versions of a but each call "clobbers" the old definition, you don t get 3 versions of

  11. U nlike M atlab, P ython is U nlike M atlab, P ython is strongly typed strongly typed, that is, you can not add a number to a string, etc. , that is, you can not add a number to a string, etc. In M atlab, adding a single number to a string will convert that string into an array of numbers, then add the single number to each of the numbers in the array. In M atlab, adding a single number to a string will convert that string into an array of numbers, then add the single number to each of the numbers in the array. P ython will simply throw an error. P ython will simply throw an error.

  12. U nlike M atlab, every P ython file can contain as many functions as you like. B asically, you can organize your code in as many files as you want. T o access functions from other files, use ------------------------------- I disagree with this. Y ou can have as any functions as you want in a M atlab file. Y ou just call "external" functions by their name, no need to import stuff first (this is a major pain in P ython). U nlike M atlab, every P ython file can contain as many functions as you like. B asically, you can organize your code in as many files as you want. T o access functions from other files, use import filename ------------------------------- I disagree with this. Y ou can have as any functions as you want in a M atlab file. Y ou just call "external" functions by their name, no need to import stuff first (this is a major pain in P ython). filename..

  13. U nlike M atlab, P ython is very quick to start. ----------------------------------- A gain P ython is quick to start into the command line mode in the terminal (as is M atlab) B ut nobody does this. It is about the same as M atlab when starting an ID E such as S pyder. U nlike M atlab, P ython is very quick to start. ----------------------------------- A gain not quite true. P ython is quick to start into the command line mode in the terminal (as is M atlab) B ut nobody does this. It is about the same as M atlab when starting an ID E such as S pyder. not quite true.

  14. C an run many P ython programs at the same time (imply can't in M atlab). ----------------------------------- A gain T his is only true in the T o run C an run many P ython programs at the same time (imply can't in M atlab). ----------------------------------- A gain not quite true. T his is only true in the command line/ terminal T o run matlab not quite true. command line/ terminal in both languages. matlab from the command line use in both languages. from the command line use /Applications/MATLAB_R2023b.app/bin/matlab -nojvm -nodesktop If you leave off the If you leave off the -nojvm -nodesktop part it will start the G U I each time you run it! (but this gets confusing) It may be possible o the same part it will start the G U I each time you run it! (but this gets confusing) It may be possible o the same wto wto dith dith spyder, I've not tried it. , I've not tried it.

  15. W hen you start up P ython, it's a rather empty environment. In order to do anything useful, you first have to functionality into your workspace. T hus, you will see a every P ython file. [W hen I was working in S ilicon V alley and there was some fundamental flaw in our product, the joke was to "feature it" ] T his is clearly cumbersome [understatement] S tuff in W hen you start up P ython, it's a rather empty environment. In order to do anything useful, you first have to import some functionality into your workspace. T hus, you will see a few every P ython file. [W hen I was working in S ilicon V alley and there was some fundamental flaw in our product, the joke was to "feature it" ] T his is clearly cumbersome [understatement] S tuff in [] from me, not the P ython propaganda. some few lines of lines of import statements at the top of statements at the top of from me, not the P ython propaganda.

  16. P ython also has namespaces, so if you simply import have to prefix every feature of import numpy a = numpy.zeros(10, 1) P ython also has namespaces, so if you simply import numpy, you will have to prefix every feature of numpy with its name, like this: , you will with its name, like this: usse looks something like structures in M atlab] C learly cumbersome [suboptimal in engineering terms]. looks something like structures in M atlab] C learly cumbersome [suboptimal in engineering terms]. [ [usse S o instead, you can import all of like this, and now don't need the leading from numpy import * a = ones(30, 1) S o instead, you can import all of numpy into the global environment like this, and now don't need the leading numpy: : into the global environment

  17. B etter yet [F E A T U R E IT !], there is a pre- -packaged namespace containing the whole Numpy-Scipy-Matplotlib stack in one piece: from pylab import * a = randn(100, 1) plot(a) show() T ry this without the " Y ou will see that unlike M atlab, P ython does not plot immediately when you execute B etter yet [ F E A T U R E IT !], there is a pre containing the whole packaged namespace stack in one piece: T ry this without the "show". ". Y ou will see that unlike M atlab, P ython does not plot immediately when you execute plot(). (). Instead, it will collect all plotting information and only show it on the screen once you type Instead, it will collect all plotting information and only show it on the screen once you type show().

  18. W hen you type W hen you type show it opens up a graphics window (puts up this it opens up a graphics window (puts up this icon in the toolbar on the mac) and icon in the toolbar on the mac) and locks the terminal locks the terminal window window until you close the graphics window [suboptimal]) until you close the graphics window [suboptimal])

  19. S o far, the code you have seen should look pretty familiar. S o far, the code you have seen should look pretty familiar. A few differences: A few differences: N o semicolons at the end of lines; N o semicolons at the end of lines; " to find where stuff being dumped to screen is coming from] [no more searching for missing " [no more searching for missing ";" to find where stuff being dumped to screen is coming from] In order to print stuff to the console, use the In order to print stuff to the console, use the print() function instead. function instead.

  20. N o end anywhere. N o end anywhere. In P ython, blocks of code are identified by indentation, and they always start with a In P ython, blocks of code are identified by indentation, and they always start with a colon colon like so: like so: sum = 0 for n in [1, 2, 3, 4, 5]: sum = sum + n print(sum) Next executable line, no indent, not in loop T hey end by reducing the indent R emember the semi T hey end by reducing the indent R emember the semi- -colon!! colon!!

  21. O n the M ac in terminal/ command mode it looks like P ython automatically indents O n the M ac in terminal/ command mode it looks like P ython automatically indents % python Some junk >>> sum = 0 >>> for n in [1, 2, 3, 4, 5]: ...

  22. B ut it does not!! If you just start typing you get B ut it does not!! If you just start typing you get >>> sum = 0 >>> for n in [1, 2, 3, 4, 5]: ... sum=sum+n File "<stdin>", line 2 sum=sum+n ^ IndentationError: expected an indented block after 'for' statement on line 1

  23. #!/usr/bin/env python # tests if an integer (input through keyboard) is prime number = int(input("Enter an integer:\n")) # check all integers greater than 1 but less than the sqrt of the number # condition must be satisfied for all integers, so use boolean is_prime to designate if we have found # that an integer falsifies this condition # is_prime is assumed to be true, until we find a divisor is_prime = True tstsqt = int(number**0.5)+1 #the range command goes from 2 to one short of tstsqt!!!! print('test limit for max', tstsqt) print(str(range(2,tstsqt))) #divisor=0 for divisor in range(2,tstsqt): rmdr=number%divisor print("test number "+str(number)+" with divisor "+str(divisor)+" rem "+str(rmdr)) if rmdr == 0: # number is not prime, set flag to false is_prime = False print("Divides by "+str(divisor)) break else: print("keep going") # if no divisors have been found, is_prime is still true and number is prime if is_prime: print(str(number)+" is prime"+" last test "+str(divisor)) else: print(str(number)+" is not prime"+" last test "+str(divisor))

  24. T wo ways to run T wo ways to run iit t If has line highlighted in cyan on last page, can run directly from command line If has line highlighted in cyan on last page, can run directly from command line (base) smalley@CERI-Smalley-16 ~ % primes4.py Enter an integer: 9 test limit for max 4 range(2, 4) test number 9 with divisor 2 rem 1 keep going test number 9 with divisor 3 rem 0 Divides by 3 9 is not prime last test 3 (base) smalley@CERI-Smalley-16 ~ % python primes4.py Enter an integer: 9 test limit for max 4 range(2, 4) test number 9 with divisor 2 rem 1 keep going test number 9 with divisor 3 rem 0 Divides by 3 9 is not prime last test 3 W ith or without line highlighted in cyan O r O r W ith or without line highlighted in cyan

  25. F unction definitions are different. P ython uses the Y ou don't have to name the output variable names in the definition and instead use return(). F unction definitions are different. P ython uses the def keyword instead of function. Y ou don't have to name the output variable names in the definition and instead use return(). keyword instead of function. % Matlab function [out]=abs(number) if number > 0 out = number else out = -number end end # Python def abs(number): if number > 0: return number else: return -number

  26. T here is no easy way to write out a list or matrix in P ython. S ince P ython only gains a matrix engine by importing not have a convenient way of writing arrays or matrices. T his sounds more inconvenient than it actually is [F E A T U R E IT !!], since you are probably using mostly functions like randn() anyway and those work just fine. A lso, many places accept P ython lists (like this instead of N ote that you semicolons to separate lines. T here is no easy way to write out a list or matrix in P ython. S ince P ython only gains a matrix engine by importing Numpy, it does not have a convenient way of writing arrays or matrices. T his sounds more inconvenient than it actually is [F E A T U R E IT !!], since you are probably using mostly functions like zeros() or anyway and those work just fine. A lso, many places accept P ython lists (like this [1, 2, 3]) instead of Numpy arrays, so this rarely is a problem. N ote that you must semicolons to separate lines. , it does or arrays, so this rarely is a problem. must use commas to separate items and can not use use commas to separate items and can not use

  27. C reating a M ake a two C reating a numpy matrix M ake a two- -dimensional matrix matrix dimensional matrix a # create a numpy matrix: m = array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) A s you can see this is Y ou build a 2 from 1 # create a Python list: l = [1 2 3] A s you can see this is N O T Y ou build a 2 - -dimensional matrix (outside brackets) by building it up from 1 - -dimensional matrices (multiple inside brackets). N O T equivalent to M atlab. equivalent to M atlab. dimensional matrix (outside brackets) by building it up dimensional matrices (multiple inside brackets).

  28. P ython is an object E verything in P ython is an object W e are more or less going to ignore this feature initially by going straight to simple arithmetic. P ython is an object- -oriented language. E verything in P ython is an object W e are more or less going to ignore this feature initially by going straight to simple arithmetic. oriented language. P ython has all the standard data types and arithmetic operations Integers (no decimal point), floating point (decimal point & sci notation), strings (in quotes) P ython has all the standard data types and arithmetic operations Integers (no decimal point), floating point (decimal point & sci notation), strings (in quotes) + , + , - -, *, / , ** (exponentiation), % (modulo divide) , *, / , ** (exponentiation), % (modulo divide)

  29. T here are 2 modes to run python Interactive & & S cript W e will start with the famous hello world program. see T here are 2 modes to run python Interactive S cript W e will start with the famous hello world program. see https:/ / www.smart https:/ / www.smart- -jokes.org/ programmer jokes.org/ programmer- -evolution.html A nd evolution.html A nd http:/ / http:/ / helloworldcollection.de helloworldcollection.de/ /

  30. Y our 1st st python program, and 1 F rom the terminal $ python <CR> Y our 1 F rom the python program, and 1st st way to run python. terminal run python in interactive mode way to run python. run python in interactive mode It will print out some junk and then the python prompt E nter print R eturn) It will print out some junk and then the python prompt >>> E nter print 'Hello World!' followed by a R eturn) followed by a <CR> (= = E nter or (= = E nter or >>> print 'Hello World!' Hello World! >>> A nd we are back at the prompt, ready for the next command (same as the shell). A nd we are back at the prompt, ready for the next command (same as the shell).

  31. Y our 2 F rom a terminal, open your favorite editor and enter Y our 2nd F rom a terminal, open your favorite editor and enter nd python program, and 2 python program, and 2nd nd way to run python. way to run python. print hello world! S ave the file as Y O U S ave the file as hello_world.py. (the extension Y O U it is a python script . (the extension py indicates to python does not care what the extension is.). N ow enter indicates to it is a python script python does not care what the extension is.). N ow enter python hello_world.py A ll your python scripts can be saved as text files and run from the command line. A ll your python scripts can be saved as text files and run from the command line.

Related


More Related Content