Welcome to Phys 77


Who am I?

Dar, PhD student in Physics, working in experimental quantum computing, Quantum Nanoelectronic Lab.

DarDahlen@berkeley.edu
150 LeConte - W 4-6pm

My programming rules of thumb:

0) If you don't understand why it's working, you aren't done yet
1) Google is your friend
2) Someone, somewhere, has already tried to do what I'm trying to do
3) Guess and check works suprisingly well
4) RTFM (Read the Manual)


What are we doing?

  • The Course - 10k Foot View:
    What is not clear here will be explained in more detail on Monday. If you can't wait till then, the syllabus is on bcourses.berkeley.edu
    • Lectures - Mondays
    • Workshops - Fridays (40% of your grade, required attendence)
    • Homework (mostly python based, 40% of grade)
    • Final Project (20% of grade)
  • Workshops Specifically - Friday afternoons:
    I am in charge of workshops, these will mostly be pair programming, working on homework or workshop specific assignments. When a programming homework assignment is given out, I will randomly assign you into pairs (using python), each homework will be treated as a pair assignment, where you will each recieve the same grade. During workshops when there are homework assignments, we will be practicing pair programming, where one person "drives" and the other person gives advice.

Goals for Today:

0) You can download this notebook from   github.com/dahlend/Physics77Fall17
1) Install Python 3.6 (via Anaconda)
2) Get Jupyter Running
3) Write a simple program
4) Bonus Problems at the bottom if you get bored

Step 0 - Open this notebook

github.com/dahlend/Physics77Fall17

Click on "Workshop 1 - Introduction"

Step 1 - What is Anaconda?

Anaconda is a pre-packaged python that includes effectively all the tools we will use in this course. In addition, it allows us to install librarys we are missing in a very simple manner.

Step 1 of today will be downloading and installing Anaconda.

https://www.continuum.io/downloads

Download and install Python 3.6 appropriate for your OS.

Step 2 - Run Jupyter

Jupyter is a an interface for making it easy to run Python and see your result. This 'website' is actually a jupyter notebook.

I'll show you what you can do:


In [1]:
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline

# Defines an x vector, going from 0 to 2 pi in 20 steps
x = np.linspace(start=0, stop=2*np.pi, num=20)

plt.plot(x, np.sin(x), label='Sin') # Plot sin
plt.plot(x, np.cos(x), 'o-', label='Cos') # Plot cos

plt.legend() # add a legend to the plot

print("We made this vector x:")
print(x) # print the vector we made


We made this vector x:
[ 0.          0.33069396  0.66138793  0.99208189  1.32277585  1.65346982
  1.98416378  2.31485774  2.64555171  2.97624567  3.30693964  3.6376336
  3.96832756  4.29902153  4.62971549  4.96040945  5.29110342  5.62179738
  5.95249134  6.28318531]

Now that you have anaconda installed, we will open a jupyter notebook.

  • if you are on mac/unix open "terminal"
  • If you are on windows open "command prompt"

Then type in:
jupyter notebook

Step 3 - Run a simple program

Take copy the code from above and run it, (shift + enter or ctrl + enter).

Play around with it, delete a line, see what happens, programming is often a trial and error excercise.

Bonus Problems -

Days where we don't have assigned homework will often include a bonus problem. These problems will often be at or beyond the limits of what have currently been covered in class. Don't feel bad if you currently have NO idea how to do it, by the end of the semester you should have the tools needed to attempt them!

Bonus 0 -

Plot an exponential decay of the form:

$y = e^{-t}$

With t going from 0 to 5.

Label the x-axis and y-axis appropriately, and put a title on the plot.

You might have to do some googling for this, the plotting tool we are using is called matplotlib.

Bonus 1

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.

Step 2 in Detail


In [2]:
# Code comments start with a # symbol, which means python ignores the line after it

# Many tools you need are in things called Libraries/Packages/Modules, 
# these libraries are often built for free by hobbyists

# Python's primary plotting library is called matplotlib

# Librarys are just Folders in your computer stored in a specific location
# you can get to sub-folders with a . like so:

# You will see this line of code very very often:
import matplotlib.pyplot as plt 

# this essentially imports a folder called pyplot from the folder matplotlib
# but since the name is kind of long, we can say import it but call it something
# else, in this case we are calling it plt



# another tool we will use very very often is Numpy
# numpy is short for numerical python
import numpy as np

# as you google more and more you will see it is common practice to call
# these libraries by thier short names, np and plt


# This next line is not actually python, it is Jupyter
%matplotlib inline
# anytime you see a line start with % it is telling 
# jupyter to do something, in this case we are telling 
# jupyter that we are using matplotlib library, and we want plots "inline"
# which means it plots it in the jupyter notebook.



# Defines an x vector of 20 number, going from 0 to 2 pi
x = np.linspace(start=0, stop=2*np.pi, num=20)

What is going on here?

We are calling np.linspace, which is a function from the numpy library.
Python functions are conceptually similar to a math function, where we pass it variables,

start=0, stop=2*np.pi, num=20  

and the function does something and has a result

In math it would be something like f(x, y, z), but in python:

np.linspace(start=0, stop=2*np.pi, num=20)

But now I want to keep track of the result of that function. So I assign it to a Variable, in this case called 'x'

x = np.linspace(start=0, stop=2*np.pi, num=20)

from now on, any time I use x it is the result of that function (unless I redefine x)

How did I know what variables a function accepts and what it does?

Lets take a look at documentation: np.linspace()

or:


In [3]:
help(np.linspace) # Very helpful!


Help on function linspace in module numpy.core.function_base:

linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)
    Return evenly spaced numbers over a specified interval.
    
    Returns `num` evenly spaced samples, calculated over the
    interval [`start`, `stop`].
    
    The endpoint of the interval can optionally be excluded.
    
    Parameters
    ----------
    start : scalar
        The starting value of the sequence.
    stop : scalar
        The end value of the sequence, unless `endpoint` is set to False.
        In that case, the sequence consists of all but the last of ``num + 1``
        evenly spaced samples, so that `stop` is excluded.  Note that the step
        size changes when `endpoint` is False.
    num : int, optional
        Number of samples to generate. Default is 50. Must be non-negative.
    endpoint : bool, optional
        If True, `stop` is the last sample. Otherwise, it is not included.
        Default is True.
    retstep : bool, optional
        If True, return (`samples`, `step`), where `step` is the spacing
        between samples.
    dtype : dtype, optional
        The type of the output array.  If `dtype` is not given, infer the data
        type from the other input arguments.
    
        .. versionadded:: 1.9.0
    
    Returns
    -------
    samples : ndarray
        There are `num` equally spaced samples in the closed interval
        ``[start, stop]`` or the half-open interval ``[start, stop)``
        (depending on whether `endpoint` is True or False).
    step : float, optional
        Only returned if `retstep` is True
    
        Size of spacing between samples.
    
    
    See Also
    --------
    arange : Similar to `linspace`, but uses a step size (instead of the
             number of samples).
    logspace : Samples uniformly distributed in log space.
    
    Examples
    --------
    >>> np.linspace(2.0, 3.0, num=5)
    array([ 2.  ,  2.25,  2.5 ,  2.75,  3.  ])
    >>> np.linspace(2.0, 3.0, num=5, endpoint=False)
    array([ 2. ,  2.2,  2.4,  2.6,  2.8])
    >>> np.linspace(2.0, 3.0, num=5, retstep=True)
    (array([ 2.  ,  2.25,  2.5 ,  2.75,  3.  ]), 0.25)
    
    Graphical illustration:
    
    >>> import matplotlib.pyplot as plt
    >>> N = 8
    >>> y = np.zeros(N)
    >>> x1 = np.linspace(0, 10, N, endpoint=True)
    >>> x2 = np.linspace(0, 10, N, endpoint=False)
    >>> plt.plot(x1, y, 'o')
    [<matplotlib.lines.Line2D object at 0x...>]
    >>> plt.plot(x2, y + 0.5, 'o')
    [<matplotlib.lines.Line2D object at 0x...>]
    >>> plt.ylim([-0.5, 1])
    (-0.5, 1)
    >>> plt.show()


In [4]:
plt.plot(x, np.sin(x), label='Sin') # Plot sin
plt.plot(x, np.cos(x), 'o-', label='Cos') # Plot cos

plt.legend() # add a legend to the plot

print("We made this vector x:")
print(x) # print the vector we made


We made this vector x:
[ 0.          0.33069396  0.66138793  0.99208189  1.32277585  1.65346982
  1.98416378  2.31485774  2.64555171  2.97624567  3.30693964  3.6376336
  3.96832756  4.29902153  4.62971549  4.96040945  5.29110342  5.62179738
  5.95249134  6.28318531]

In [5]:
help(plt.plot) # This one is super long


Help on function plot in module matplotlib.pyplot:

plot(*args, **kwargs)
    Plot lines and/or markers to the
    :class:`~matplotlib.axes.Axes`.  *args* is a variable length
    argument, allowing for multiple *x*, *y* pairs with an
    optional format string.  For example, each of the following is
    legal::
    
        plot(x, y)        # plot x and y using default line style and color
        plot(x, y, 'bo')  # plot x and y using blue circle markers
        plot(y)           # plot y using x as index array 0..N-1
        plot(y, 'r+')     # ditto, but with red plusses
    
    If *x* and/or *y* is 2-dimensional, then the corresponding columns
    will be plotted.
    
    If used with labeled data, make sure that the color spec is not
    included as an element in data, as otherwise the last case
    ``plot("v","r", data={"v":..., "r":...)``
    can be interpreted as the first case which would do ``plot(v, r)``
    using the default line style and color.
    
    If not used with labeled data (i.e., without a data argument),
    an arbitrary number of *x*, *y*, *fmt* groups can be specified, as in::
    
        a.plot(x1, y1, 'g^', x2, y2, 'g-')
    
    Return value is a list of lines that were added.
    
    By default, each line is assigned a different style specified by a
    'style cycle'.  To change this behavior, you can edit the
    axes.prop_cycle rcParam.
    
    The following format string characters are accepted to control
    the line style or marker:
    
    ================    ===============================
    character           description
    ================    ===============================
    ``'-'``             solid line style
    ``'--'``            dashed line style
    ``'-.'``            dash-dot line style
    ``':'``             dotted line style
    ``'.'``             point marker
    ``','``             pixel marker
    ``'o'``             circle marker
    ``'v'``             triangle_down marker
    ``'^'``             triangle_up marker
    ``'<'``             triangle_left marker
    ``'>'``             triangle_right marker
    ``'1'``             tri_down marker
    ``'2'``             tri_up marker
    ``'3'``             tri_left marker
    ``'4'``             tri_right marker
    ``'s'``             square marker
    ``'p'``             pentagon marker
    ``'*'``             star marker
    ``'h'``             hexagon1 marker
    ``'H'``             hexagon2 marker
    ``'+'``             plus marker
    ``'x'``             x marker
    ``'D'``             diamond marker
    ``'d'``             thin_diamond marker
    ``'|'``             vline marker
    ``'_'``             hline marker
    ================    ===============================
    
    
    The following color abbreviations are supported:
    
    ==========  ========
    character   color
    ==========  ========
    'b'         blue
    'g'         green
    'r'         red
    'c'         cyan
    'm'         magenta
    'y'         yellow
    'k'         black
    'w'         white
    ==========  ========
    
    In addition, you can specify colors in many weird and
    wonderful ways, including full names (``'green'``), hex
    strings (``'#008000'``), RGB or RGBA tuples (``(0,1,0,1)``) or
    grayscale intensities as a string (``'0.8'``).  Of these, the
    string specifications can be used in place of a ``fmt`` group,
    but the tuple forms can be used only as ``kwargs``.
    
    Line styles and colors are combined in a single format string, as in
    ``'bo'`` for blue circles.
    
    The *kwargs* can be used to set line properties (any property that has
    a ``set_*`` method).  You can use this to set a line label (for auto
    legends), linewidth, anitialising, marker face color, etc.  Here is an
    example::
    
        plot([1,2,3], [1,2,3], 'go-', label='line 1', linewidth=2)
        plot([1,2,3], [1,4,9], 'rs',  label='line 2')
        axis([0, 4, 0, 10])
        legend()
    
    If you make multiple lines with one plot command, the kwargs
    apply to all those lines, e.g.::
    
        plot(x1, y1, x2, y2, antialiased=False)
    
    Neither line will be antialiased.
    
    You do not need to use format strings, which are just
    abbreviations.  All of the line properties can be controlled
    by keyword arguments.  For example, you can set the color,
    marker, linestyle, and markercolor with::
    
        plot(x, y, color='green', linestyle='dashed', marker='o',
             markerfacecolor='blue', markersize=12).
    
    See :class:`~matplotlib.lines.Line2D` for details.
    
    The kwargs are :class:`~matplotlib.lines.Line2D` properties:
    
      agg_filter: unknown
      alpha: float (0.0 transparent through 1.0 opaque) 
      animated: [True | False] 
      antialiased or aa: [True | False] 
      axes: an :class:`~matplotlib.axes.Axes` instance 
      clip_box: a :class:`matplotlib.transforms.Bbox` instance 
      clip_on: [True | False] 
      clip_path: [ (:class:`~matplotlib.path.Path`, :class:`~matplotlib.transforms.Transform`) | :class:`~matplotlib.patches.Patch` | None ] 
      color or c: any matplotlib color 
      contains: a callable function 
      dash_capstyle: ['butt' | 'round' | 'projecting'] 
      dash_joinstyle: ['miter' | 'round' | 'bevel'] 
      dashes: sequence of on/off ink in points 
      drawstyle: ['default' | 'steps' | 'steps-pre' | 'steps-mid' | 'steps-post'] 
      figure: a :class:`matplotlib.figure.Figure` instance 
      fillstyle: ['full' | 'left' | 'right' | 'bottom' | 'top' | 'none'] 
      gid: an id string 
      label: string or anything printable with '%s' conversion. 
      linestyle or ls: ['solid' | 'dashed', 'dashdot', 'dotted' | (offset, on-off-dash-seq) | ``'-'`` | ``'--'`` | ``'-.'`` | ``':'`` | ``'None'`` | ``' '`` | ``''``]
      linewidth or lw: float value in points 
      marker: :mod:`A valid marker style <matplotlib.markers>`
      markeredgecolor or mec: any matplotlib color 
      markeredgewidth or mew: float value in points 
      markerfacecolor or mfc: any matplotlib color 
      markerfacecoloralt or mfcalt: any matplotlib color 
      markersize or ms: float 
      markevery: [None | int | length-2 tuple of int | slice | list/array of int | float | length-2 tuple of float]
      path_effects: unknown
      picker: float distance in points or callable pick function ``fn(artist, event)`` 
      pickradius: float distance in points 
      rasterized: [True | False | None] 
      sketch_params: unknown
      snap: unknown
      solid_capstyle: ['butt' | 'round' |  'projecting'] 
      solid_joinstyle: ['miter' | 'round' | 'bevel'] 
      transform: a :class:`matplotlib.transforms.Transform` instance 
      url: a url string 
      visible: [True | False] 
      xdata: 1D array 
      ydata: 1D array 
      zorder: any number 
    
    kwargs *scalex* and *scaley*, if defined, are passed on to
    :meth:`~matplotlib.axes.Axes.autoscale_view` to determine
    whether the *x* and *y* axes are autoscaled; the default is
    *True*.
    
    .. note::
        In addition to the above described arguments, this function can take a
        **data** keyword argument. If such a **data** argument is given, the
        following arguments are replaced by **data[<arg>]**:
    
        * All arguments with the following names: 'x', 'y'.


In [ ]: