### Square Wave Packet Widget


```python
# setup 
import numpy as np
import sympy as sp
sp.init_printing(use_latex='mathjax')

import matplotlib.pyplot as plt
plt.rcParams['figure.figsize'] = (20, 20)  # (width, height)
plt.rcParams['font.size'] = 20
plt.rcParams['legend.fontsize'] = 30
from matplotlib import patches

#get_ipython().magic('matplotlib')  # separate window
get_ipython().magic('matplotlib inline') # inline plotting

from __future__ import print_function
from ipywidgets import interact, interactive, fixed, interact_manual
import ipywidgets as widgets

def f(numks, aa):
    lam = 1e-9 # wavelength
    kval = 2*np.pi/lam # wavenumber can be changed by changing wavelength
    #numks = x
    #numks = 10 # how many wavenumbers do you want in the sum?
    aa = aa*lam/100 # width of square wave as a fraction of wavelength
    xsquare = np.arange(-2*lam, 2*lam, lam/100) # The x values for our sine waves.
    arrlen = np.size(xsquare)
    ksquare = np.arange(1, numks+1, 1) # wavenumbers go from 1 to something
    nvals = np.arange(1, numks+1, 1)
    ksquare = ksquare * kval
    Ans = 2/np.pi/nvals * np.sin(np.pi*aa*nvals/lam)
    fxarg = np.ones((numks,arrlen)) # Create a matrix for kx values to simplify calculations later.
    fxarg = fxarg[:, 0:arrlen]*xsquare # Fill the kx matrix with x values along the rows.
    fxarg = fxarg[0:arrlen, :].T*ksquare # Multiply each column by its appropriate k value.
    fx = np.ones((numks,arrlen))
    fx=Ans*np.cos(fxarg) # Fill the matrix with the appropriate cosine waves.
    
    ones = np.ones(numks)
    sqwv = np.matmul(fx, ones) 
    plt.figure(1)
    plt.rcParams.update({'font.size': 20})
    plt.rcParams.update({'legend.fontsize' : 24})
    plt.subplot(211)
    plt.plot(xsquare,fx[:, :]) # Plot a few of the waves to check that they look right (see Fig. 6.11 in Taylor, Zafiratos, Dubson).
    plt.title('The waves')
    plt.xlabel('x (m)')
    plt.ylabel('Amplitude')
    plt.subplot(212)
    plt.plot(xsquare, sqwv)
    plt.title('The wave packet')
    plt.xlabel('x (m)')
    plt.ylabel('Amplitude')
    plt.subplots_adjust(top=3, bottom=0.1, left=0.1, right=3.0, hspace=0.25,
                    wspace=0.1)
    plt.show()
#    return 0

interact(f, numks=widgets.IntSlider(min=1,max=30,step=1,value=10), aa=widgets.IntSlider(min=5,max=95,step=5,value=5));
```


    A Jupyter Widget



```python

```

d5eba7ff6bad91e174b419e24216499255faf3d0
ipynb
Jupyter Notebook
SquareWavePackets.ipynb
guygastineau/Jupyter
5d97e1a57cc812e1131f1d39edbd6b15341f38ed
MIT
SquareWavePackets.ipynb
guygastineau/Jupyter
5d97e1a57cc812e1131f1d39edbd6b15341f38ed
MIT
2018-08-06T17:55:54.000Z
2018-08-07T18:47:52.000Z
SquareWavePackets.ipynb
guygastineau/Jupyter
5d97e1a57cc812e1131f1d39edbd6b15341f38ed
MIT
2018-08-06T17:39:08.000Z
2018-08-06T17:39:08.000Z
Qwen/Qwen-72B
1. YES
2. YES