<jupyter_start><jupyter_text>Useful Introduction to Python, GitHub, and LaTexQuestions that you may be asking:- What is Python?- Why should I use it?- Is it venemous?- Why am I talking to myself?In this chapter, you are going to learn the answers to some of these questions and develop some basic skills.  These skills will be useful in later chapters and will form a springboard so that you can dive into the ocean that is Computational Physics.  The first thing that you may need is motivation, which lies in the history of scientific computing. A HistoryA **computer** is a machine that can carryout sequences of arithmetic or logical operations.  It requires instructions in a specific order (i.e., syntax), and space to hold intermediate/final results (i.e., memory).  Prior to the 20th Century, a computer was a mechanical device that allowed users to perform arithmetic calculations quickly.  An abacus is one such device:| ![abacus](https://upload.wikimedia.org/wikipedia/commons/a/af/Abacus_6.png) ||:--:| |The Chinese suanpan. The number represented on this abacus is 6,302,715,408. (wikipedia:abacus)|The principle of the modern computer was proposed by **<NAME>** (1936) in his paper On Computable Numbers. Turing proposed a "Universal Computing machine" that is capable of computing anything that is computable by executing instructions (program) stored on tape, allowing the machine to be programmable. The fundamental concept of Turing's design is the stored program, where all the instructions for computing are stored in memory. **<NAME>** acknowledged that the central concept of the modern computer was due to this paper.**Colossus** was the world's first electronic digital programmable computer, where it used a large number of valves (vacuum tubes). It had paper-tape input and was capable of being configured to perform a variety of boolean logical operations on its data.  The **ENIAC** (Electronic Numerical Integrator and Computer) was the first electronic programmable computer built in the United States. Like the Colossus, a "program" on the ENIAC was defined by the states of its patch cables and switches. Once a program was written, it had to be mechanically set into the machine with the manual resetting of plugs and switches. | ![ENIAC](https://upload.wikimedia.org/wikipedia/commons/thumb/4/4e/Eniac.jpg/1280px-Eniac.jpg)|:--:| |ENIAC was the first electronic device in the U.S. and performed ballistics trajectory calculations for the United States Army. (wikipedia:computer)|Along with military applications, computers became the catalyst for many scientific and engineering breakthroughs.  In the 1950s, IBM developed the programming language **FORTRAN** (Formula Translation) as a general-purpose, compiled imperative programming language that is especially suited to numeric computation and scientific computing.  Many scientific programs were developed in FORTRAN and are still in use today in computationally intensive areas such as numerical weather prediction, finite element analysis, computational fluid dynamics, geophysics, **computational physics**, crystallography and computational chemistry.Before the development of disk files, text editors and terminals, programs were most often entered on a keypunch keyboard onto 80-column punched cards, one line to a card. The resulting deck of cards would be fed into a card reader to be compiled. Punched card codes included no lower-case letters or many special characters, and special versions of the IBM 026 keypunch were offered that would correctly print the re-purposed special characters used in FORTRAN.  Reflecting punched card input practice, FORTRAN programs were originally written in a fixed-column format, with the first 72 columns read into twelve 36-bit words.| ![Punchcard](https://upload.wikimedia.org/wikipedia/commons/5/58/FortranCardPROJ039.agr.jpg)|:--:| |FORTRAN code on a punched card, showing the specialized uses of columns 1–5, 6 and 73–80. (wikipedia:fortran)|  Why Python?Fast-forwarding from punchcards to the modern era, other computer languages (C, C++, Java) were developed to improve upon FORTRAN in terms of their usage (i.e., easier to code) and compilation speed.  FORTRAN has also changed over many versions that migrated it from punchcards to completely digital files.  The programming language C rivals FORTRAN for speed and has become the backbone of modern computing.  Back to Python.  What is it?Python is a scripting language, which means it takes commands in a more human-like language and translates those commands into machine code (zeros and ones).  The Python interpreter does this one line at a time, but its translation into machine code is less efficient than C or FORTRAN.  For applications where speed is key, Python is used as an interface while portions of the code are passed into the speedier languages.  Alternatively, one can develop their Python code using C extensions for Python (or Cython).Scientists are quickly adopting Python within a range of fields because it is open-source (i.e., free) and much easier for students to learn.  Especially if you have any prior experience in programming, where Python strips away many of the quirks from legacy languages.  Due to the simplified structure of Python programs, you can easily begin programming and get to your results.    Python Basics Create a Jupyter Notebook**To create a Jupyter notebook in Microsoft VS Code**: open the command palette (Windows: Ctrl + Shift + P, iOS: Command + Shift + P) and select the command "Jupyter: Create New Blank Notebook".Python programs include 3 elements: 1) import statements/libraries, 2) custom functions, and 3) regular statements.  Although this document has flowing text, most Python programs are written to be as short as possible.  For these examples, we are using an interactive Python mode, where code blocks are designated with > In [ ]:for input. These codeblocks can be run and re-run with tweaks, but you need to watch out for dependencies (i.e., assumptions that some other code exists in memory).  Let's start by importing a commonly used modules **numpy** and **matplotlib**<jupyter_code>import numpy as np
import matplotlib.pyplot as plt<jupyter_output><empty_output><jupyter_text>These import statements will allow us to use functions with the respective modules.  The numpy module was developed to make managing data structures easier, while the matplotlib library introduces functions from the Matlab Plotting Library  so that we can visualize our results.  To produce a graph, let's first generate some data:<jupyter_code>x = np.arange(1,5,0.5)
y = 3*x + 2<jupyter_output><empty_output><jupyter_text>The first line uses the 'arange' function from numpy, where we use 'np' as a shortcut label.  The 'arange' function takes in up to 3 values as input: starting value, stopping value, and step size to generate a numpy array with an interated sequence:>x = np.array([1. , 1.5, 2. , 2.5, 3. , 3.5, 4. , 4.5])Note that the generated values are floats (i.e., real numbers) and the final value of the array is 4.5 and **not** 5.0.  Python generators typically exclude the end point.  If we wanted to use integers (i.e., whole numbers) instead, then we could have used the 'range' function from pure Python without refferring to the numpy module and excluded the step size as input (e.g., range(0,5)).The second line generates another numpy array using the values stored in 'x'.  More precisely, it makes a temporary copy of 'x', where it performs a multiplication by 3 and addition of 2 to each element of the copied array.  Finally, the temporary copied array is stored as a variable called 'y'.>y = np.array([ 5. ,  6.5,  8. ,  9.5, 11. , 12.5, 14. , 15.5]) Now, we are going to make a plot of the data that we generated.  To create a canvas in matplotlib, we start with the figure function and store it in a container called 'fig'.  The suptitle function uses a string (i.e., array of characters) as input and sets the keyword argument fontsize equal to 16 pt font.  We also introduce a container 'ax' that holds the axes for the canvas through the add_subplot function that takes a three digit number (row column index) as input.<jupyter_code>fig = plt.figure()
fig.suptitle('My first graph', fontsize=16)
ax = fig.add_subplot(111)
ax.plot(x,y,'k.',ms=18)<jupyter_output><empty_output><jupyter_text>To plot our generated data, we simply used the plot function on the axes (the Axes class inherits the plot function from the matplotlib module).  The plot function used the x and y arrays to generate the points, but we also had to tell it that we wanted black points ('k.') with a markersize (ms) equal to 18 pts.However, we may want to make a lot of plots and do not want to copy/paste a bunch of times.  To reuse our commands, we define a custom function 'create_plot' that takes the parameters we may want to vary as input.<jupyter_code>def create_plot(x,y,color,marker,ms):
    fig = plt.figure()
    fig.suptitle('My first graph', fontsize=16)
    ax = fig.add_subplot(111)
    ax.plot(x,y,marker=marker,color=color,ms=18,lw=0)<jupyter_output><empty_output><jupyter_text>Notice that Python uses a tab to delineate what should be included in the function.  Now let's change the color to blue ('b'), the marker to squares ('s') and the markersize to 12 points.<jupyter_code>create_plot(x,y,'b','s',12)<jupyter_output><empty_output><jupyter_text>We can even change the x,y values to something more complicated.<jupyter_code>x = np.arange(0,2*np.pi,0.5)
y = 3*np.sin(x+1)-2
create_plot(x,y,'r','^',1)<jupyter_output><empty_output><jupyter_text>There are many options within matplotlib, where you will find some more useful than others over time.  If in doubt, you can always check the **matplotlib gallery** (https://matplotlib.org/stable/gallery/index.html) or stackexchange (https://stackexchange.com/).  It is likely that someone has already run into your problem/customization and other people have provided a 'possible' solution (not all solutions are good!).  The last bit of customization for this section is to:1. add axis labels    - ax.set_xlabel(*string,fontsize=22) or ax.set_ylabel(*string,fontsize=22)2. modify tick marks     - ax.tick_params(axis='both', direction='out',length = 12.0, width = 8.0)3. modify tick labels    - using ```$``` opens the latex interpreter for custom symbols (e.g., ```$\pi$``` = $\pi$)    - ax.set_xticklabels(['0','$\pi$/2','$\pi$','$3\pi/2$','2$\pi$'])4. set sensible axis limits    - ax.set_xlim(0,2*np.pi)5. add a legend    - add the keyword 'label' to the plot command and set equal to a string    - ax.legend(loc='upper right',fonstize=20)<jupyter_code>fig = plt.figure()
fig.suptitle('My first graph', fontsize=16)
ax = fig.add_subplot(111)
ax.plot(x,y,marker='*',color='orange',ms=18,lw=0,label='SHO')

ax.set_xlabel("Angle (rad.)",fontsize=22)
ax.set_ylabel("Amplitude (ft/s)",fontsize=22)
ax.tick_params(axis='both', direction='out',length = 12.0, width = 8.0)
ax.set_xlim(0,2*np.pi)
ax.set_xticks([0,np.pi/2,np.pi,3.*np.pi/2.,2*np.pi])
ax.set_xticklabels(['0','$\pi$/2','$\pi$','$3\pi/2$','2$\pi$'])
ax.legend(loc='upper center',fontsize=20)<jupyter_output><empty_output><jupyter_text>Figures can be saved to file using the `savefig` function, which takes the filename as an argument.  Additional keyword arguments (kwargs) can be applied that alter the display of the figure (e.g., dpi = 300 sets the dots per inch to 300).<jupyter_code>fig.savefig("SHO.png",bbox_inches='tight',dpi=300)<jupyter_output><empty_output><jupyter_text>Modules to solve problemsThere are many modules within modules, where object-oriented notation is used to access them.  For example, you can generate a random number between 0--1 using the rand() function within the random module within the numpy module (i.e., np.random.rand()).<jupyter_code>np.random.rand()<jupyter_output><empty_output><jupyter_text>Another extremely useful library for physicists is the linear algebra package in numpy. This package provides very fast routines for calculating anything having to do with matrices: eigenvalues, eigenvectors, solutions of systems of linear equations, and so on.>Example 1: In electronics, Kirchhoff's laws are used to solve for the currents through components in circuit networks. Applying these laws gives us systems of linear equations, which can then be expressed as matrix equations, such as:![Kirchoff](Kirchoff_matrix.png)<jupyter_code>A = np.matrix([[-13,2,4],[2,-11,6],[4,6,-15]]) #matrix is an array of an array
B = np.array([5,-10,5])
np.linalg.solve(A,B)<jupyter_output><empty_output><jupyter_text>Reading and writing data from a file Python allows for many forms of input.  There are commands to request user input manually via the terminal window, where this can be a direct request or by command line arguments.  For computational physics, it is likely that you want to know how the output of a program changes with slightly different inputs or to visualize a data set.  At this point manual input is impractical and cumbersome.  In this section, you will learn how to read and write to data files so that you can save your work for later or prepare it for others to use.  Files are created using the open() function that takes a filename and a mode as input.  Here's a table detailing the different modes available to the open() function.| Character   | Meaning || ----------- | :-----------: || 'r'      | reading from a file; returns error if not found || 'w'   | writing to a file; creates a new file/overwrites existing file) || 'x'   | open for exclusive creation; failing if the file already exists || 'a'   | open for writing; appending to the end of the file if it exists || 'b'   | binary mode || 't'   | text mode (default) || '+'   | open for updating (reading and writing) |Let's generate some data using the equation for a simple pendulum:$\ddot{\theta} = \sqrt{\frac{g}{l}} \theta$,which has the solution$\theta(t) = \theta_{max} \sin \left(\sqrt{\frac{g}{l}} t \right)$,where $g$ represents the acceleration due to gravity, $l$ is the length, and $t$ is the time.  Now let's define some variables.<jupyter_code>g = 9.81 #m/s^2 Earth gravity near the surface
l = 1 #meter long string
t = np.arange(0,10.5,0.01) #10 seconds with 0.5 sec increments
theta_max = 45 #maximum amplitude in degrees
fname = "Simple_Pendulum.txt"

theta = theta_max*np.sin(np.sqrt(g/l)*t)
out = open(fname,'w') #create a text file and open it for writing
out.write("#time (s), theta (deg)\n") #write a header

for i in range(0,len(t)):
    out.write("%1.2f, %1.3f\n" % (t[i],theta[i]))
out.close()<jupyter_output><empty_output><jupyter_text>The data is written to "Simple_Pendulum.txt", which exists in the same directory as this Jupyter notebook.  In practice, you may want to include an absolute path in the filename.  Using our code from before, we will read the data from the file.  Notice that we formatted the header with a \ symbol and the lines are comma delimited.  We are going to take advantage of this using the 'genfromtxt' function from numpy.<jupyter_code>x,y = np.genfromtxt("Simple_Pendulum.txt",delimiter=',',comments='#',unpack=True)

fig = plt.figure()
fig.suptitle('Simple Pendulum', fontsize=16)
ax = fig.add_subplot(111)
ax.plot(x,y,'r-',lw=3)

ax.set_xlabel("Time (s)",fontsize=22)
ax.set_ylabel("Amplitude (deg)",fontsize=22)
ax.tick_params(axis='both', direction='out',length = 12.0, width = 8.0)
ax.set_xlim(0,10)
ax.set_xticks(np.arange(0,12,2))<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.09032299658307008, 'fraction_numerical': 0.016375475469021985, 'mean_word_length': 4.907083015993907, 'pattern_counts': {'":': 0, '<': 51, '<?xml version=': 0, '>': 55, 'https://': 5, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '12', 'dir': 'jupyter-structured-clean-dedup', 'id': '337615', 'license': 'MIT', 'n_tokens_mistral': 4535, 'n_tokens_neox': 4254, 'n_words': 2054, 'path': 'docs/_sources/docs/Chapter_1/Gentle_Introduction.ipynb', 'repo_name': 'saturnaxis/PHYS3820_Book', 'size': '15521'}