\section{Circuits}
  \subsection{Capacitants}
  Previously we found that $E=\frac{\sigma}{2\epsilon_0}+\frac{\sigma}{2\epsilon_0}=\frac{\sigma}{\epsilon_0}$ where $\sigma = \frac{Q}{A}$. Let's find potential $V$ between the plates. Recall that $v=-\int\vec{E}\cdot d\vec{s}$.
  \begin{align*}
    V&=-\int_0^d\vec{E}\cdot d\vec{s}\\
    \text{for } \vec{E}&=\frac{\sigma}{\epsilon_0}\\
    V&=-\int_0^d Eds=-\int_0^d Edx\\
    &=-E\int_0^d dx\\
    V&=-Ed \text{ This is from the pos to negative plate}\\
    \shortintertext{Equivilently from - to + plate:}\\
    V&=-int_0^d \vec{E}\cdot d\vec{s}\\
    &=-int_0^d(-Eds)=\int_0^d Edx\\
    V&=Ed \text{ This is from neg to pos plate}
    \shortintertext{Now we want to relate our two equations to a charge to find the charge within the plate.}
  \end{align*}
  Consider that if there are more charges on the plates, then the potential (difference) between them will be larger. Difference is in paranthesis because we could have had a $\Delta V$ instead of just a V if we wanted. The potential goes with the field, and the field is larger if we have more charges in it.
  \begin{align*}
    Q~V\\
    \shortintertext{Let us introduce capacitance $C$ such that $Q=CV$. In magnitude, we found $V=Ed$, which gives the potential difference accross the plates. And $E=\frac{\sigma}{\epsilon_0}$}\\
    V&=\frac{\sigma}{\epsilon_0}d=\frac{1}{\epsilon}\frac{Q}{A}d\\
    \shortintertext{Using our new definition of $V=\frac{Q}{C}$, we find:}\\
    \frac{1}{\epsilon_0}\frac{Q}{A}d&=\frac{Q}{C}\\
    C&=\epsilon_0 \frac{A}{d}\\
    \shortintertext{This is for parallel plate capacitance. This only depends on geometry. Due to the equation $Q=CV$, as soon as we know the charge on the plates we can easily determine the potential energy of the plates. $Q=CV$ is true for all capacitors.}
  \end{align*}
  Let's discuss combining capacitors. For a parallel plate capacitor, we found that it's capacitance is $C=\epsilon_0 \frac{A}{d}$. What if we stacked plates together? What would the capacitancebe for this combined system?
  \begin{align*}
    A_{new}&=A_1+A_2+A_3\\
    &=\frac{d}{\epsilon_0}C_1+\frac{d}{\epsilon_0}C_2+\frac{d}{\epsilon_0}C_3\\
    \frac{d}{\epsilon_0}C_{new}&=\frac{d}{\epsilon_0}C_1+\frac{d}{\epsilon_0}C_2+\frac{d}{\epsilon_0}C_3\\
    \shortintertext{d is the same everywhere, and $\epsilon_0$ is a constant so they both cancel}\\
    C_{new}&=C_1+C_2+C-3\\
    C_{new}&= C_{parallel}\\
    \shortintertext{Capacitants increase when area is increased.}
  \end{align*}
  What if instead we put capacitors one after another (in sequential order)? The area is the same, and the two middle sets of plates are going to have zero charge.
  \begin{align*}
    d_{new}&=d_1+d_2+d_3\\
    \epsilon_0\frac{A}{C_{new}}&=\epsilon_0\frac{A}{C_1}+\epsilon_0\frac{A}{C_2}+\epsilon_0\frac{A}{C_3}\\
    \frac{1}{C_{series}}&=\frac{1}{C_1}+\frac{1}{C_2}+\frac{1}{C_3}+...\\
    C_{series}&=\left[\frac{1}{C_1}+\frac{1}{C_2}+\frac{1}{C_3}+...\right]\\
  \end{align*}
  Capacitance let's us calculate the energy stored inside of the field between its plates. This is similar to throwing a ball from a lower surface to a hgiher one. The kinetic energy is changed into potential energy.
  \begin{align*}
    \shortintertext{Recall that $U=VQ$.}\\
    \shortintertext{Consider:}\\
    dU&=VdQ\\
    \shortintertext{and $Q=CV$}\\
    \to dU&=\frac{Q}{C}dQ\\
    U&=\frac{1}{C}\int QdQ\\
    &=\frac{1}{C}\frac{1}{2}Q^2\\
    &=\frac{1}{2}\frac{1}{C}C^2V^2\\
    \alignedbox{U}{=\frac{1}{2}CV^2}
    \shortintertext{Or}\\
    \alignedbox{U}{=\frac{1}{2}\frac{Q^2}{C}}\\
    U&=\frac{1}{2}Q^2\frac{V}{Q}\\
    \alignedbox{U}{\frac{1}{2}QV}\\
  \end{align*}
  Let's discuss energy density.
  \begin{align*}
    u&=\frac{U}{volume}\\
    \shortintertext{This is always true, but for a parallel-plate capacitor, the volume is:}
    volume&=Ad\\
    \shortintertext{Then,}\\
    U&=\frac{1}{2}CV^2\\
    \to u&=\frac{1}{2}CV^2\frac{1}{Ad}\\
    &=\frac{1}{2}\left(\epsilon_0\frac{A}{d}\right)V^2\frac{1}{Ad}\\
    u&=\frac{\epsilon_0}{2}\frac{V^2}{d^2}\\
    u&=\frac{\epsilon_0}{2}\left(\frac{V}{d}\right)^2\\
    \shortintertext{Recall,}\\
    V&=Ed\\
    \to E&=\frac{V}{d}\\
    \shortintertext{We find}\\
    \alignedbox{u}{=\frac{\epsilon_0}{2}E^2}\\
    \shortintertext{Energy density relies solely on the energy field between the plates.}\\
  \end{align*}

  \subsubsection{Example 1}
  Let's find the capacitance C of the demo capacitor. The area of the capacitor is A ($A=\pi r^2$) for $r=6cm$. $A=\pi 35cm^2$, also d is 2cm. We also need $\epsilon_0$. This number is a constant. i$\epsilon_0 = 8.85\times10^{-12} \frac{F}{m}$, where F stands for ferads. For parallel plates, $C=\epsilon_0\frac{A}{d}$. The units are ferads $(F)$.
  \begin{align*}
    C&=\left(8.85\times10^{-12}\frac{F}{m}\right)\left(\frac{\pi 36cm^2}{2cm}\right)\left(\frac{1m}{100cm}\right)\\
    \alignedbox{C}{=5.00\times10^{-12}F=5pF}\\
    \shortintertext{C of the other two objects:}\\
    C_{blue}&=10\mu F=10\times10^{-6}F=10^{-5}F\\
    C_{brown}&=0.33\mu F=0.33\times10^{-6}F=3.3\times10^{-7}\\
  \end{align*}
  The capacitance of a capacitor is typically given within tolerances, not as raw numbers.
  Let's find the electric field around the first capacitor. If there is no charge on the plates, then there is no electric field between the plates, thus the capacitor is not storing any energy. An analogy to gravity: if there is no mass for two plates you're trying to calculate gravity for, then there is no gravity between the two plates. By adding electric charge to the plates, a field is created between them in which energy is stored.
  \begin{align*}
    U&=\frac{1}{2}CV^2\\
    Q&=CV\\
    U&=\frac{1}{2}QV\\
    &=\frac{1}{2}\frac{Q^2}{C}\\
    \shortintertext{Let's put a 9V battery across our capacitor.}\\
    U&=\frac{1}{2}CV^2\\
    &=\frac{1}{2}(5\times10^{-12}F)(9V)^2\\
    U&=2.03\times10^{-10}J\\
    \alignedbox{U}{=.203nJ}\\
  \end{align*}
  Consider a microwave oven. Many are powered at around 1200 Watts. We run it for 2 minutes. How much energy does this use? How much time is how much energy used?
  \begin{align*}
    P&=\frac{\Delta E}{\Delta T}\\
    \Delta E &= P\Delta T\\
    &=\left(1200\frac{J}{s}\right)(120s)\\
    \alignedbox{\Delta E}{=144000J}\\
    &=144kJ
  \end{align*}
  There are some benefits for something using a low amount of power.  Let's recall that $C=5\times10^{-5}$. Q of d would like instead $10\times10^{-17}F$. d can combine capacitors. Consider $C=\epsilon\frac{A}{d}$. If you want more capacitance, you can increase the area. If you double the area you double the capacitance.
  \begin{align*}
    C&=C_1+C_2\\
    &=2C\\
    &=10\times10^{-12}\\
  \end{align*}
  \subsubsection{Example 2}
  There is a potential across the plates such that if a charge is placed you can easily calculate the potential energy and then the kinetic energy. Let's find the capacitants of something that is not necessarily parallel plates. We still need 2 plates, but they are not going to be flat plates. We are going to calculate the capacitance of a spherical capacitor.
  \begin{align*}
    Q&=CV\\
    C_{parallelplates}=\epsilon_0\frac{A}{d}\\
    \shortintertext{The capacitance of a capacitor is always fully defined.}\\
    \shortintertext{For the spherical case, let's find C. Q is the charge on either plate, NOT BOTH. This is to prevent having zero as your Q value. The easiest way to find the voltage is by using Gauss' law to find $\vec{E}$ to find the electric field then using that to solve for the volutage.}\\
    \vec{E}&=0 \text{ }r<a\\
    \vec{E}&=0 \text{ }r>b\\
    \shortintertext{For $a<r<b$:}\\
    \oint E\cdot d\vec{a}&=\frac{q_{enc}}{\epsilon_0}\\
    E(4\pi r^2)&=\frac{Q}{\epsilon_0}\\
    \alignedbox{\vec{E}}{=\frac{1}{4\pi\epsilon_0}\frac{Q}{r^2}\hat{r}}\\
    V&=-\int\vec{E}\cdot d\vec{l}
    \shortintertext{From $r=a$ to $r=b$}\\
    V&=-\int_a^b\frac{1}{4\pi\epsilon_0}\frac{Q}{r^2}\hat{r}\cdot d\vec{r}\\
    \shortintertext{Potential is always path independent. The dot product enforces it in this situation. It always ends up being $E\cdot dl$ which is in the $r$ direction. Therefore the direction does not matter but the start and endpoints do matter. Analagous to gravity where the potential energy remains the same regardless of the horizontal position of an object.}\\
    &=-\frac{1}{r\pi\epsilon_0}Q\int_a^b\frac{1}{r^2}\hat{r}\cdot dr\hat{r}\\
    \shortintertext{This can be done because it is being written in it's direction vector times the magnitude. This will make the computations easier. Now we are able to find the dot product because the unit vectors are being dotted now as well.}\\
    &=-\frac{1}{4\pi\epsilon_0}Q\int_a^b r^{-2}dr\\
    V&=-\frac{1}{4\pi\epsilon_0}Q(-r^{-1})\Big|_{r=a}^{r=b}\\
    V&=\frac{1}{4\pi\epsilon_0}Q\left(\frac{1}{b}-\frac{1}{a}\right)\\
    \shortintertext{We need to ask ourselves if the sign or the units make sense for the sign. From $a\to b$, the voltage should decrease because it's being taken away from the electric charge. V is always a scalar so our "direction" is correct. We can now use $Q=CV$. $Q$ is not the total charge, it is the charge on either plate.}\\
    C&=\frac{Q}{V}=\frac{|Q|}{|V|}\\
    &=\frac{Q}{\frac{1}{4\pi\epsilon_0}Q\left(\frac{1}{a}-\frac{1}{b}\right)}\\
    &=4\pi\epsilon_0\left(\frac{1}{a}-\frac{1}{b}\right)^{-1}\\
    \alignedbox{C}{=4\pi\epsilon_0\frac{ab}{b-a}}
  \end{align*}
  \subsection{Dialectics}
  We can nicely build capacitors by placing insulators between the plates. If you can decrease the space between the capacitors, then there is a higher capacitance level. For parallel plates,
  \begin{align*}
    \vec{E_{new}}&=\vec{E}+\vec{E_i}\\
    \vec{E_{new}}&<\vec{E}\\
    \vec{E_{new}}&=\frac{1}{\kappa}\vec{E}\\
    C&=\kappa C_0\\
  \end{align*}
  \subsection{Current and Resistance}
  Electric current is the movement of charges in time. $I=\frac{dq}{dt}$ This means that in order to have a current, the mobile charges must be in the presence of an electric field. If you apply a force, then the charges start to move and the movement of charges is an electric current. Imagine a region with some charges and due to external charges, an external electric field affects the charges in the original region. All of the charges are going to move in the direction of the field. Because of this, the motion of the charges is messy. Also, electrons on a conductor. The electrons are all initially going to be spread out along the conductor, but if an electric field is implemented along the surface of the field, all of the charges are going to move the opposite direction of the electric field. The charges end up zigzagging along the path of the conductor.
  \newline\newline
  Charge is given in Coulombs (C). The elementary charge is $e=1.602\times 10^{-19}C$. The unit for current is $\frac{C}{s}$. This is also called an ampere or amp (A). \newline\newline Consider a copper wire being influenced by an external electric field (figure 4.9.1). $v_d$ is the drift velocity. This is the average speed of charged particles moving in a current. What about for electrons in a copper wire?
  \begin{align*}
    \shortintertext{We've said:}
    I&=\frac{dq}{dt}\\
    \shortintertext{Let's break it down into individual charges:}\\
    I&=\frac{d(eN)}{dt}\\
    &=e\frac{dN}{dT}\\
    &=e\frac{ndV}{dt}\\
    \shortintertext{Where $n$ is the number of electrons in a volume}\\
    &=e\frac{nAdl}{dt}\\
    &=enAv_d\\
    \alignedbox{v_d}{=\frac{I}{enA}}\\
  \end{align*}
  For a current of 10A, consider a copper wire of radius 1mm.We know that $e=1.602\times 10^{-19}$, and $A=\pi r^2$ for $r=1mm$. The number density is around $10^{23}\frac{1}{cm}\left(\frac{100cm}{m}\right)^3=10^{29}\frac{1}{m^3}$. Plugging these numbers in we will find a typical drift velocity of about $v_d \approx 10^{-4}\frac{m}{s}$ or $0.1\frac{mm}{s}$. This is very slow.\newline\newline
  Current dencity is:
  \begin{align*}
    dI&=\vec{J}\cdot d\vec{A}\\
    I&=\int\vec{J}\cdot d\vec{A}\\
  \end{align*}
  Why do I care about $\vec{J}$ in the first place? When the electrons move in the wire, the external electric field forces them down the wire making those electrons move through a volume of the form $V=Al$. A is the crosssectional area of the wire, so current density let's us relate the movement of the electrons to the shape/geometry of the wire. $\vec{J}$ flows through $d\vec{A}$. The stronger the external field, the larger the current density.
  \begin{align*}
    \vec{J}&\approx\vec{E}\\
    \vec{J}&=\sigma\vec{E}\\
    \vec{J}&=\frac{1}{\rho}\vec{E}\\
  \end{align*}
  $\sigma$ is electric conductance, and $\rho$ is electric resistivity. Further, $\rho=\frac{1}{\sigma}$. Both $\rho$ and $\sigma$ depend of the properties of the materials of the wire. You can think of $\sigma$ as telling us how good of a conductor a given material is. Whereas, $\rho$ tells us how poor of a conductor the material is.
  \begin{align*}
    \shortintertext{Figure 4.9.3}
    \vec{E}=\rho\vec{J}\\
    \shortintertext{Let's consider uniform $\vec{E}$ considering magnitudes:}\\
    E&=\rho J\\
    &=\rho\frac{I}{A}
    \shortintertext{You can do this substitution because of the following:}\\
    \int dI&=\int\vec{J}\cdot d\vec{A}\\
    &=\int JdA\\
    &=J\int dA\\
    I&=JA\\
    \shortintertext{When electric charges are uniform we can calculate the voltage:}\\
    V&=-\int\vec{E}\cdot d\vec{l}\\
    &=-\int Edl\\
    &=-E\int dl\\
    V&=-El\\
    \shortintertext{Now substituting for E:}
    \frac{V}{l}&=\rho\frac{I}{A}\\
    V&=I\rho\frac{l}{A}\\
    \text{Where }R&=\rho\frac{l}{A}\text{ called resistance.}\\
    \shortintertext{Notice that R depends on material $\rho$ and on geometry $\frac{l}{A}$}\\
    I=\frac{V}{R}=\frac{V}{\rho}\frac{A}{l}\\
  \end{align*}
  Resistance depends on geometry and resistivity. Resistivity is a property of a material (intrinsic property). $R=\rho\frac{l}{A}$.
  \subsubsection{Example 1}
  Let's find the resistivity $\rho$ for the power resistor. We know that $R=10\Omega$. The length of the resistor is $L=18cm$, and the area is $A=2cm\times1cm$. Using the equation above, we can solve for $\rho$ and find the resistance of the object.
  \begin{align*}
    R&=\rho\frac{l}{A}\\
    \rho&=R\frac{A}{L}\\
    \rho&=10\Omega\left(\frac{2cm^2}{18cm}\right)\left(\frac{1m}{100cm}\right)\\
    \alignedbox{\rho}{=0.0111\Omega m}\\
  \end{align*}
  For comparison's sake, the resistivity of silver is $\rho_{silver}=1.59\times10^{-8}\Omega m$.
  \subsubsection{Example 2}
  Resistors in series. There is a long resistor with another resistor right behind it ($r_1,r_2, r_3$). What is the net (equivalent) resistance? An electron goes from one resistor to the next and so on.
  \begin{align*}
    R&=\rho\frac{L}{A}\to L=R\frac{A}{\rho}\\
    L_{eq}&=L_1+L_2+L_3\\
    R_{eq}\frac{A}{\rho}&=R_{1}\frac{A}{\rho}+R_{2}\frac{A}{\rho}+R_{3}\frac{A}{\rho}\\
    \alignedbox{R_{eq}}{=R_1+R_2+R_3}\\
  \end{align*}
  \subsubsection{Example 2}
  Resistors in parallel. If resistors are in parallel, then the charges see the resistors as one large resistor. Analogous to a river. If a river widens, then the water slows down. Adding up the areas:
  \begin{align*}
    A_{eq}&=A_1+A_2+A_3\\
    A&=\rho\frac{l}{R}\\
    \rho\frac{L}{R_{eq}}&=\rho\frac{L}{R_{1}}+\rho\frac{L}{R_{2}}+\rho\frac{L}{R_{3}}\\
    \alignedbox{\frac{1}{R_{eq}}}{=\frac{1}{R_{1}}+\frac{1}{R_{2}}+\frac{1}{R_{3}}}\\
  \end{align*}
  In series:\newline
  $R_{eq}=R_1+R_2+R_3$\newline
  $C_{eq}=\left(\frac{1}{C_1}+\frac{1}{C_2}+\frac{1}{C_3}+\right)$\newline
  In parallel:\newline
  $R_{eq}=\left(\frac{1}{R_1}+\frac{1}{R_2}+\frac{1}{R_3}+\right)$\newline
  $C_{eq}=C_1+C_2+C_3$\newline
  For some capacitors, if there are only two of them
  \begin{align*}
    C_{eq}&=\left(\frac{1}{C_1}+\frac{1}{C_2}\right)^{-1}\\
    &=\frac{1}{\frac{1}{C_1}+\frac{1}{c_2}}\\
    C_{eq}&=\frac{1}{\frac{1}{C_1}+\frac{1}{c_2}}\frac{C_1C_2}{C_1C_2}\\
    &=\frac{1}{C_2+C_1}\frac{C_1C_2}{1}\\
    \alignedbox{C_{eq}}{=\frac{C_1C_2}{C_1+C_2}}\\
    \alignedbox{R_{eq}}{=\frac{R_1R_2}{R_1+R_2}}\\
  \end{align*}
  Electrical Power
  \begin{align*}
    P&=\frac{dW}{dt}=\frac{dU}{dt}\\
    P&=\frac{d(qV)}{dt}\\
    \shortintertext{For a given voltage, the power output is:}
    P&=V\frac{dq}{dt}\\
    P&=VI\\
    \alignedbox{P}{=IV}\\
    \shortintertext{For a circuit with a resistance R,}\\
    V&=IR\\
    \to P=I^2R \text{ and } P=\frac{V^2}{R}\\
  \end{align*}
  Household outlets in America supply 120 Volts. In order to change the power output of an appliance, we must adjust its resistance to change the current. We want $P_{max}=I_{max}V$. We know that $V=IR$.
  \begin{align*}
    I_{max}&=\frac{V}{R_{max}}
  \end{align*}
  For some resistor of resistance R, the power it outputs is $P=I^2R$. The resistor will disipate energy as heat.
  \subsubsection{Example 3}
  Say a wire of diameter $d=4mm$ has a current through it, $I=6mA$. Assume a uniform current density.
  \begin{align*}
    dI&=\vec{J}\cdot d\vec{a}\\
    \int dI &=\int Jda\\
    I&=J\int da\\
    I&=JA\\
    \alignedbox{J}{=\frac{I}{A}}\\
    \shortintertext{Recall,}\\
    \vec{E}&=\sigma\vec{J}\\
    \to V&= IR\\
  \end{align*}
  \subsection{Circuits and Circuit Analysis}
  Let's start with an example and then lets discuss the physical implications of the example after
  \subsubsection{Example 1}
  \begin{figure}[!h]
    \centering
    \begin{circuitikz} \draw
    (0,0) to[battery=$V_0$] (0,4)
          to[resistor=$R_0$, i>_=$I_0$] (4,4)
          to[resistor=$R_1$, i>_=$I_0$] (4,0)
          to[resistor=$R_2$, i>_=$I_0$] (0,0)
    ;
    \end{circuitikz}
  \end{figure}
  There is one current that describes this entire circuit. Let's let $V_0 = 11V$, $R_0=10k\Omega$, $R_1=12k\Omega$, and $R_2=35k\Omega$. To get $I_0$ we need to know $R_eq$. These resistors are all in series with each other. Because they are all in series,we know that:
  \begin{align*}
    R_{eq}&=R_0+R_1+R_2\\
    &=57k\Omega\\
    \shortintertext{Then with $V=IR$ we set:}\\
    V_0&=I_0R_{eq}\\
    \alignedbox{I_0}{=\frac{V_0}{R_{eq}}}\\
    I_0&=\frac{11V}{57k\Omega}=0.193mA
  \end{align*}
  If you start somewhere in a gravatational field, and you move something down, it has changed in its potential energy. Because electric force is conservative, a charge that travels any path and then comes back to its original location has no net change in potential energy
  \begin{align*}
    \shortintertext{For a given loop,}\\
    \sum qV_{loop}&=0\\
    \sum V_{loop}&=0\\
  \end{align*}
  To use this, pick any starting location. Take a complete path that's called a loop and consider the change in voltage across various circuit elements. For a battery or a power supply, if you travel from the negative to the positive, you have an increase in voltage across the battery. Converse also works. For a resistor, if you are traveling \underline{with} the current, voltage will \underline{drop} across the resistor.
  \newline\newline
  Let's try a clockwise loop from the top left corner.
  \begin{align*}
    \sum V_{loop} &=\\
    -I_0R_0-I_0R_1-I_0R_2+V_0&=0\\
    V_0&=I_0(R_0+R_1+R_2)\\
    V_{R_0}&=-I_0R_0=(-0.193mA)(10k\Omega)\\
    V_{R_0}&=-1.93V\\
    V_{R_1}&=-2.32V\\
    V_{R_2}&=-6.76V\\
    \alignedbox{\sum V_{loop}}{=-11.0V}\\
    P_{R_0}&=IV\\
    IV&=0.37mW\\
  \end{align*}
  \subsubsection{Example 2}
  \begin{figure}[!h]
    \centering
    \begin{circuitikz}
      \draw
      (4,4) to[battery=$I_0$] (0,4)
            to[short, -*, i=$I_0$] (0,2)
            node[label={[font=\footnotesize]left:X}] {}
            to[R=$R_1$, i>_=$I_1$] (4,2)
            node[label={[font=\footnotesize]right:Y}] {} -- (4,4)
      (0,2) -- (0,0)
            to[R=$R_2$, i>_=$I_2$] (4,0)
            to[short, -*] (4,2)
      ;
    \end{circuitikz}
  \end{figure}
  \begin{align*}
    \sum V_{loop}&=0\\
    a&:-V_0+I_1R_1=0\\
    b&:-I_1R_1+I_2R_2=0\\
    \alignedbox{\sum I_{in}}{=\sum I_{out}}\\
    x&:I_0=I_1+I_2\\
    y&:I_1+I_2=I_0\\
  \end{align*}
  \newline
  There are basically two rules when it comes to circuit analysis. $\sum V_{loop} = 0$ and $\sum I_{in}=I_{out}$. This is essentially conservation of energy and conservation of charge. Let's consider the following circuit.
  \begin{figure}[!h]
    \centering
    \begin{circuitikz}
      \draw
      (4,4) to[isource=$I_0$] (0,4)
            to[short, -*, i=$I_0$] (0,2)
            node[label={[font=\footnotesize]left:X}] {}
            to[R=$R_1$, i>_=$I_1$] (4,2)
            node[label={[font=\footnotesize]right:Y}] {} -- (4,4)
      (0,2) -- (0,0)
            to[R=$R_2$, i>_=$I_2$] (4,0)
            to[short, -*] (4,2)
      ;
    \end{circuitikz}
  \end{figure}
  Let's let $V_0=11V$, $R_1=12k\Omega$, and $R_2=35k\Omega$. First let's find the current directly out of the battery.
  \begin{align*}
    R_{eq}&=\frac{R_1R_2}{R_1+R_2}=8.94k\Omega\\
    V_0&=I_0R_{eq}\\
    \alignedbox{I_0}{=\frac{V_0}{R_{eq}}}\\
    I_0&=\frac{11V}{8.94k\Omega}=1.23mA\\
    P_0=I_0V_0&=(1.23mA)(11V)=13.5mW\\
    \shortintertext{Now let's find the current through each resistor. Let's start with going from the batter to $R_1$ and back (a). and then going from $R_2$ through $R_1$. The third loop could go from the battery to $R_2$ and back but it is not important to do so because all of the variables show up in these two equations already.}\\
    \sum V_{loop}&=0\\
    a&) V_0-I_1R_1 = 0\\
    b&) I_1R_1-I_1R_2 = 0\\
    \sum I_{in}&=\sum I_{out}\\
    x&)I_0=I_1+I_2\\
    y&)I_1+I_2=I_0\\
    \shortintertext{We have already done the physics, and now we must solve for the things that we do not know. This is just basic algebra.}\\
    \to V_0&=I_1R_1\\
    I_1&=\frac{V_0}{R_0}\\
    &=\frac{11V}{12k\Omega}\\
    \alignedbox{I_1}{=0.917mA}\\
    \to I_2&=I_0-I_1\\
    &=1.23mA-0.917mA\\
    \alignedbox{I_2}{=0.313mA}
    \shortintertext{Now let's find the power of these two resistors. Remember $V=IV=I^2R=\frac{V^2}{R}$}\\
    P_1&=I_1^2R_1=(0.917mA)^2(12k\Omega)\\
    P_1&=10.1mW\\
    P_2&=I_2^2R_2=(0.313mA)^2(35k\Omega)\\
    P_2&=3.43mW\\
    \shortintertext{Notice that $P_1+P_2=13.5mW$, which is the same amount of power that the batter puts out! Now let's find the voltage drops across $R_1+R_2$ from $IV$}\\
    V_1&=\frac{P_1}{I_1}=\frac{10.1mW}{0.916mA}\\
    V_1&=11.0V\\
    V_2&=\frac{P_2}{I_2}=\frac{3.43mW}{0.313mA}\\
    V_2&=11.0V\\
    \shortintertext{Notice that $V_1=V_2=V_0$. We get the same voltage across all three.}
  \end{align*}
  The voltage drops across parallel segments of circuit are \underline{equal}. $V_0$, $R_1$, and $R_2$ are all in parallel, which means they all have the same voltage. We essentially did it with the first loop but we did not. Energy is conserved, but voltage is \underline{NOT} conservative. To determine how to combine the resistors, you \underline{must} first determine where the charge will flow.
  \subsubsection{Example (Draw Later)}
  \begin{figure}[h!]
    \centering
    \begin{circuitikz}
      \draw (10,0) to[isource=$V_0$] (10,8)
                   to[R=$R_0$](5,8) -- (0,8)
                   to[R=$R_4$](0,4)
                   to[R=$R_5$](0,0) -- (10,0)
            (5,8)  to[R=$R_1$] (5,4) -- (7.5, 4)
                   to[R=$R_3$](7.5,0)
            (5,4) -- (2.5, 4)
                   to[R=$R_2$](2.5, 0);
    \end{circuitikz}
  \end{figure}
  There is a short within this circuit, which means it flows without resistance. Even with a short, you still calculate everything the same way. Let's find the current out of the battery and the power output of $R_0$
  \begin{align*}
    \sum V_{bat} &=0\\
    \sum I_{in} &= \sum I_{out}\\
    \shortintertext{A quick way to get $I_0$ is using $V_0=I_0R_{eq}$. Let's find $R_{eq}$}\\
    R_{eq}&=R_0\frac{R_{45}R_{123}}{R_{45}+R{123}}\\
    \text{Also, } R_{45}&=R_4+R_5\\
    R_{123}&=R_1+\frac{R_2R_3}{R_2+R_3}\\
    \alignedbox{R_{eq}}{=R_0+\frac{\left(R_4+R_5\right)\left(R_1+\frac{R_2R_3}{R_2+R_3}\right)}{R_4+R_5+R_1+\frac{R_2R_3}{R_2+R_3}}}\\
  \end{align*}
  \subsubsection{Using measuring tools}
  How to measure current using a digital multimeter.\newline\newline
  To measure current, we must carefullt add the ammeter to the circuit. To use an ammeter you must break the circuit. So in order to add an ammeter, first be sure the circuit is \underline{not} currently powered! Plug the hole with the ammeter and \underline{then} turn on the power supply.\newline\newline
  How to measure voltage using a DMM.\newline\newline
  Set the DMM to the voltmeter. Set the DMM to be a voltage. We then add the loads across the element whose voltage drop we want to measure. We must not break the circuit or turn off the power supply to measure the voltage.\newline\newline
  Ammeters go into circuits and have low internal resistance, while voltmeters go across circuit elements and have high internal resistance.
  \subsection{Resistors and Capacitors in Circuits}
  \begin{align*}
    V_R&=IR\\
    V_C=\frac{Q}{C}\\
    \shortintertext{When the swtich is closed:}\\
    V_R&=V_C=0\\
    \shortintertext{Let's throw the switch to the position (a):}.\\
    \shortintertext{There are no junctions and there is only one loop:}\\
    \sum V_{loop} = 0\\
    V_0-IR-\frac{Q}{C}&=0\\
  \end{align*}
  How much charge acumulates on the plates? What is Q in terms of capacitance, resistance, and the battery. The amount of charge that accumulates within the circuit is a property of the circuit only, wheras battery voltage, resistance, and capacitance are functions of themselves. Using $I=\frac{dQ}{dt}$, we get an equation that's a differential. We must get $dQ$ with $Q$ and we must get $dt$ with $t$.
  \begin{align*}
    V_0-R\frac{dQ}{dt}-\frac{Q}{C}&=0\\
    V_0-\frac{Q}{C}&=R\frac{dQ}{dt}\\
    CV_0-Q&=RC\frac{dQ}{dt}\\
    \frac{1}{RC}&=\frac{1}{CV_0-Q}\frac{dQ}{dt}\\
    \frac{dt}{RC}&=\frac{dQ}{CV_0-Q}\\
    \int_0^t\frac{dt}{RC}&=\int_0^Q\frac{dQ}{CV_0-Q}\\
    \shortintertext{Let $U=CV_0-Q$, and $du=-dQ$:}\\
    \frac{1}{RC}(t-0)&=\int_{CV_0}^{CV_0-Q}\frac{-du}{u}\\
    \frac{t}{RC}&=-ln\left(\frac{CV_0-Q}{CV_0}\right)\\
    e^{-\frac{t}{RC}}&=\frac{CV_0-Q}{CV_0}\\
    CV_0e^{-\frac{t}{RC}}&=CV_0-Q\\
    Q&=CV_0-CV_0e^{-\frac{t}{RC}}\\
    \alignedbox{Q(t)}{=CV_0\left(1-e^{-\frac{t}{RC}}\right)}\\
    \text{Charging} &\text{ a capacitor}\\
    \shortintertext{At $t=0$}
    Q(0)&=CV_0\left(1-e^{-\frac{0}{RC}}\right)=0\\
    \shortintertext{After a long time, $Q=CV_0$}\\
    V_0&=IR-\frac{CV_0}{C}=0\\
    V_0-IR&=V_0\\
    \shortintertext{This is only true if $I=0$. If we take the dervivative of our $Q(t)$ then we can see how current depends on time:}\\
    I(t)&=\frac{d}{dt}Q(t)\\
    &=CV_0\left(0-\frac{-1}{RC}e^{-\frac{t}{RC}}\right)\\
    \alignedbox{I(t)}{=\frac{V_0}{R}e^{-\frac{t}{RC}}}\\
    \shortintertext{Charging a capacitor. Notice that RC has dimension of time.}
  \end{align*}
  \newpage


% section3
\chapter {Matrices and Matrix Algebra}

\section{Operations on Matrices}

No MATLAB problems in this section.

\section{Inverses; Algebraic Properties of Matrices}

\begin{exer}
In this problem, we compute $A^{5} - 3A^{3} + 7A - 4I$ for the matrix $A$, where
$$
A = \left[\begin{array}{rrrr} 1&\hspace{3mm} 2&\hspace{1mm} -3&\hspace{2mm} 0\\ 1 & 1 & -2 & 1 \\ 2 & 1 & 3 & 4 \\ -3 & 2 & 2 & -8 \end{array} \right].
$$
\begin{enumerate}

\vspace{2mm}
\item[(a)]  Using the syntax $A$\hspace{1mm}$\hat{}$\hspace{1mm}$k$ which produces the $k$-th power of a square matrix and the command \textit{eye} for the identity matrix, compute the above matrix polynomial.

\vspace{1mm}
\item[(b)]  Using the command \textit{polyvalm}, compute the above matrix polynomial.

\vspace{1mm}
\item[(c)]  Tell what happens if you type the syntax $A.$\hspace{1mm}$\hat{}$\hspace{1mm}$k$.

\end{enumerate}
\end{exer}

\begin{sol}

\begin{verbatim}

% Construct the matrix A.
A = [1 2 -3 0; 1 1 -2 1; 2 1 3 4; -3 2 2 -8];

% (a)
result_a = A^5 + (-3)*A^3 + 7*A + (-4)*eye(4);

% Display the matrix polynomial.
disp('The result of the matrix polynomial is');
disp(result_a)

% (b)
% Coefficient of the matrix polynomial.
coeff_poly = [1 0 -3 0 7 -4];

% Evaluate the matrix polynomial of coefficient
% with coeff_poly vector with the input matrix A.
result_b = polyvalm(coeff_poly, A);

% Display the matrix polynomial.
disp('The result of the matrix polynomial is');
disp(result_b);

% (c)
disp('The result of A.^2 is'); disp(A.^2);
disp('The result of A.^3 is'); disp(A.^3);
disp('The result of A.^4 is'); disp(A.^4);
\end{verbatim}

\begin{outputs}

\begin{verbatim}

The result of the matrix polynomial is
         874       -1272         -39        3021
        2580       -2306        -723        7536
        5191       -4121       -2444       14563
      -16852       12539        5649      -46917

The result of the matrix polynomial is
         874       -1272         -39        3021
        2580       -2306        -723        7536
        5191       -4121       -2444       14563
      -16852       12539        5649      -46917

The result of A.^2 is
     1     4     9     0
     1     1     4     1
     4     1     9    16
     9     4     4    64

The result of A.^3 is
     1     8   -27     0
     1     1    -8     1
     8     1    27    64
   -27     8     8  -512

The result of A.^4 is
           1          16          81           0
           1           1          16           1
          16           1          81         256
          81          16          16        4096
\end{verbatim}
\end{outputs}

\noindent From the results, we can see that the syntax $A.$\hspace{1mm}$\hat{}$\hspace{1mm}$k$ produces the entrywise $k$-th powers of the matrix $A$.

\end{sol}

\section{Elementary Matrices; A Method for Finding $A^{-1}$}

\begin{exer}

In this problem, we solve the linear system $A \mathbf{x} = \mathbf{b}$ by using matrix inversion, where
$$
A = \left[\begin{array}{rrrr} 3 &\hspace{2.5mm} 3 & -4 & -3 \\ 0 & 6 & 1 & 1\\ 5 & 4 & 2 & 1 \\ 2 & 3 & 3 & 2 \end{array} \right] \hspace{2mm} \mathrm{and} \hspace{3mm} \textbf{b} = \left[\begin{array}{r} -2 \\ 3 \\ 5 \\ 1 \end{array} \right].
$$

\begin{enumerate}
%8a
\item[(a)] Use the MATLAB command \textit{inv} or the syntax $A$\hspace{1mm}$\hat{}$\hspace{1mm}$(-1)$ to find the inverse of $A$.
\vspace{1mm}
%8b
\item[(b)] Display the output matrix as a rational form, NOT decimally. You may use the command \textit{format}.
\vspace{1mm}
%8c
\item[(c)] Using the result of (a), compute the solution of the linear system $A \mathbf{x} = \mathbf{b}$ by taking $\mathbf{x} = A^{-1} \mathbf{b}$.

\end{enumerate}

\end{exer}

\begin{sol}

\begin{verbatim}

% Construct the matrix A and the right-hand-side vector b.
A = [3 3 -4 -3; 0 6 1 1; 5 4 2 1; 2 3 3 2];
b = [-2 3 5 1]';

% (a)
% Use the command inv.
Inv_A1 = inv(A);

% Use the syntax A^(-1).
Inv_A2 = A^(-1);

% (b)
format rat;
disp('The result of the command inv is'); disp(Inv_A1);
disp('The result of the syntax A^(-1) is'); disp(Inv_A2);

% (c)
% Since A is invertible, the solution to Ax=b is x=A^(-1)*b.
x = Inv_A1 * b;
disp('The solution to Ax=b is x = A^(-1)*b'); disp(x');
\end{verbatim}

\begin{outputs}

\begin{verbatim}

The result of the command inv is
 -7    5   12  -19
  3   -2   -5    8
 41  -30  -69  111
-59   43   99 -159

The result of the syntax A^(-1) is
 -7    5   12  -19
  3   -2   -5    8
 41  -30  -69  111
-59   43   99 -159

The solution to Ax=b is x = A^(-1)*b
    70      -29     -406      583
\end{verbatim}
\end{outputs}
\end{sol}

\section{Subspaces and Linear Independence}

\begin{exer} (\textit{Sigma notation})\\
Compute the linear combination
$$\mathbf{v}=\Sigma_{j=1}^{25} c_{j}\mathbf{v}_{j}$$
for $c_{j}=1/j$ and $\mathbf{v}_{j}=(\sin j, \cos j).$

\end{exer}

\begin{sol}
\begin{verbatim}

v=zeros(1,2);
for i=1:25
    v=v+(1/i)*[sin(i), cos(i)];
end
disp(v);
\end{verbatim}

\begin{outputs}
\begin{verbatim}

1.0322    0.0553
\end{verbatim}
\end{outputs}
\end{sol}

\vspace{3mm}

\begin{exer} Let $\mathbf{v_{1}}=(4, 3, 2, 1)$, $\mathbf{v_{2}}=(5, 1, 2, 4)$, $\mathbf{v_{3}}=(7, 1, 5, 3)$, $\mathbf{x}=(16, 5, 9, 8)$, and $\mathbf{y}=(3, 1, 2, 7)$. Determine whether $\mathbf{x}$ and $\mathbf{y}$ lie in $\textrm{span}\{\mathbf{v_{1}}, \mathbf{v_{2}}, \mathbf{v_{3}}\}$.

\end{exer}

\begin{sol}

\begin{verbatim}

% Construct v1, v2, v3, x, y
v1=[4 3 2 1]'; v2=[5 1 2 4]'; v3=[7 1 5 3]';
x=[16 5 9 8]'; y=[3 1 2 7]';

% Augmented matrices [v1|v2|v3|x] and [v1|v2|v3|y]
X=[v1 v2 v3 x];
Y=[v1 v2 v3 y];

disp('Reduced row echelon form of [v1 v2 v3 x] is');
disp(rref(X));
disp('Reduced row echelon form of [v1 v2 v3 y] is');
disp(rref(Y));
\end{verbatim}

\begin{outputs}

\begin{verbatim}

Reduced row echelon form of [v1 v2 v3 x] is
       1              0              0              1
       0              1              0              1
       0              0              1              1
       0              0              0              0

Reduced row echelon form of [v1 v2 v3 y] is
       1              0              0              0
       0              1              0              0
       0              0              1              0
       0              0              0              1
\end{verbatim}
\end{outputs}

\noindent Therefore, $\mathbf{x}$ lies in $\textrm{span}\{\mathbf{v_{1}}, \mathbf{v_{2}}, \mathbf{v_{3}}\}$ and $\mathbf{y}$ does not lie in $\textrm{span}\{\mathbf{v_{1}}, \mathbf{v_{2}}, \mathbf{v_{3}}\}$.
\end{sol}

%\begin{exer} (\textit{Linear Combinations})\\
%Use the MATLAB command \textit{rref} to express the vector $\mathbf{b}=(-21, \hspace{1mm}-60, \hspace{1mm}-3, \hspace{1mm}108, \hspace{1mm}84)$ as a linear combination of $\mathbf{v_{1}}$, $\mathbf{v_{2}}$, and $\mathbf{v_{3}}$ where $\mathbf{v_{1}}=(1, \hspace{1mm} -1, \hspace{1mm}3, \hspace{1mm}11, \hspace{1mm}20)$, $\mathbf{v_{2}}=(10, \hspace{1mm}5, \hspace{1mm}15, \hspace{1mm}20, \hspace{1mm}11)$, and $\mathbf{v_{3}}=(3, \hspace{1mm}3, \hspace{1mm}4, \hspace{1mm}4, \hspace{1mm}9)$.
%
%\end{exer}
%
%
%\begin{sol}
%
%\begin{verbatim}
%
%% Construct b as a column vector.
%b = [-21 -60 -3 108 84]';
%
%% Set v1, v2, v3 as column vectors.
%v1 = [1 -1 3 11 20]';
%v2 = [10 5 15 20 11]';
%v3 = [3 3 4 4 9]';
%
%% Set a matrix A with column vectors v1, v2 and v3.
%A = [v1 v2 v3];
%
%% Construct the augmented matrix [A | b].
%augA = [A b];
%
%% Find the reduced row echelon form of augA.
%rref_augA = rref(augA);
%
%% Extract the solution vector from rref_augA.
%x = rref_augA(1:3, 4);
%
%% From the result of rref_augA, we get rank(A) = rank([A | b]),
%% hence, we can find each coefficient of this linear combination.
%% Otherwise, we cannot find a linear combination of b as v1, v2, and v3.
%
%% Moreover, since rank(A) = rank([A | b]) = the number of columns of A,
%% b is uniquely expressed as a linear combination of v1, v2, and v3.
%
%format rat % Display the result as an integer form.
%disp('b is a linear combination of x(1)*v1+x(2)*v2+x(3)*v3, where');
%disp('x(1) ='); disp(x(1));
%disp('x(2) ='); disp(x(2));
%disp('x(3) ='); disp(x(3));
%\end{verbatim}
%
%
%\begin{outputs}
%
%\begin{verbatim}
%
%b is a linear combination of x(1)*v1+x(2)*v2+x(3)*v3, where
%x(1) =
%      12
%
%x(2) =
%       3
%
%x(3) =
%     -21
%\end{verbatim}
%\end{outputs}
%\end{sol}

\section{The Geometry of Linear Systems}

No MATLAB problems in this section.

%%% Week2
\newpage
\section{Matrices with Special Forms}

\begin{exer} (\textit{Inverting $(I-A)$})
\begin{enumerate}
%7a
\item[(a)]  (\textit{Inverting $(I-A)$ when $A$ is nilpotent}) Using MATLAB, show that the matrix
$$
A = \left[\begin{array}{rrr} 2&\quad 11&\quad 3\\ -2 & -11 & -3\\ 8 & 35 & 9 \end{array} \right]
$$
is nilpotent, and then use Theorem~3.6.6 in the text book to compute $(I-A)^{-1}$. Check your answer by computing the inverse directly in MATLAB.
\vspace{1mm}

\item[(b)] (\textit{Approximating $(I-A)^{-1}$ by a power series}) Using MATLAB, confirm that the matrix
$$
A = \left[\displaystyle\begin{array}{rrr} 0&\quad \displaystyle\frac{1}{4}&\quad \displaystyle\frac{1}{8}\\ \displaystyle\frac{1}{4} & \displaystyle\frac{1}{8} & \displaystyle\frac{1}{10}\\ \displaystyle\frac{1}{8} & \displaystyle\frac{1}{10} & \displaystyle\frac{1}{10} \end{array} \right]
$$
satisfies the condition in Theorem~3.6.7 of the text book. You may use the command \textit{sum}. Since $A$ satisfies that condition, $(I-A)$ is invertible and can be expressed by the series in Formula~(18) in Section~3.6 of the text book. Compute the approximation $$(I-A)^{-1}\approx I+A+A^2+A^3+\cdots+A^{10},$$ and compare it with the inverse of $I-A$ produced directly by MATLAB. To how many decimal places do the results agree? You may use the command \textit{format} to display the output with long digits.

\end{enumerate}
\end{exer}

\begin{sol}
\verb""
\begin{enumerate}
\item[(a)]
\begin{verbatim}
% (a)-i
A = [ 2 11 3 ; -2 -11 -3; 8 35 9];  % Construct the matrix A.
% Compute the A^2, A^3, ... , and display.
disp('A^2 is'); disp(A^2);
disp('A^3 is'); disp(A^3);

% (a)-ii Comparing two result

% By Theorem 3.6.6, (I-A)^(-1)=I+A+A^2.
result1=eye(3)+A+A^2;

% Compute the inverse of (I-A) directly.
result2=inv(eye(3)-A);
disp('I+A+A^2 is'); disp(result1);
disp('(I-A)^(-1) is'); disp(result2);

% Display as a rational form.
format rat;
disp('Rational form of (I-A)^(-1) is');disp(result2);
\end{verbatim}

\begin{outputs}

\begin{verbatim}

A^2 is
     6     6     0
    -6    -6     0
    18    18     0

A^3 is
     0     0     0
     0     0     0
     0     0     0

I+A+A^2 is
     9    17     3
    -8   -16    -3
    26    53    10

(I-A)^(-1) is
    9.0000   17.0000    3.0000
   -8.0000  -16.0000   -3.0000
   26.0000   53.0000   10.0000

Rational form of (I-A)^(-1) is
       9             17              3
      -8            -16             -3
      26             53             10
\end{verbatim}

\end{outputs}

\noindent Since $A^{3} = \mathbf{0}$, $A$ is nilpotent.
By the Theorem $3.6.6$, since $A^{3} = \mathbf{0}$, $I-A$ is invertible and $(I-A)^{-1} = I + A + A^{2}.$ To check answer by computing the inverse directly in MATLAB, we implement as in the next page.

\item[(b)]
\begin{verbatim}
% Construct the matrix A.
A=[0 1/4 1/8; 1/4 1/8 1/10; 1/8 1/10 1/10];

% Check that the condition in Theorem 3.6.7
% of the text book is satisfied for matrix A.
column_sum=sum(abs(A),1);   % column-wise sum
row_sum=sum(abs(A),2);  % row-wise sum
disp('The sum of the absolute values of the entries in each column is');
disp(column_sum);
disp('The sum of the absolute values of the entries in each row is');
disp(row_sum);

result3=eye(size(A))+A+A^2+A^3+A^4+A^5+A^6+A^7+A^8+A^9+A^10;
result4=inv(eye(3)-A);

format long;	% Display the result with long digits
disp('With format long');
disp('Approximated inv(I-A) is'); disp(result3);
disp('Exact inv(I-A) is'); disp(result4);
\end{verbatim}

\begin{outputs}

\begin{verbatim}

The sum of the absolute values of the entries in each column is
       3/8           19/40          13/40

The sum of the absolute values of the entries in each row is
       3/8
      19/40
      13/40

With format long
Approximated inv(I-A) is
   1.108587459181130   0.338615080927493   0.191581699462210
   0.338615080927493   1.260966638806045   0.187122081247432
   0.191581699462210   0.187122081247432   1.158500720998029

Exact inv(I-A) is
   1.108610894508188   0.338643199287067   0.191600757491367
   0.338643199287067   1.261000334187368   0.187144925921800
   0.191600757491367   0.187144925921800   1.158516208087334
\end{verbatim}

\end{outputs}

\noindent The approximation result agrees with the exact result to 2 decimal places.
\end{enumerate}
\end{sol}

\section{Matrix Factorizations; $LU$-Decomposition}

\begin{exer}(\textit{LU-decompositions})
In this problem, we find an $LU$-decomposition of $A$, where $A$ is given in the \mbox{Example $2$} of the Section $3.7$.

\vspace{2mm}
\begin{enumerate}
\item[(a)] Find an $LU$-decomposition of $A$ by following the procedure given in the Example $2$.
\vspace{1mm}
\item[(b)] Solve the linear system $A \mathbf{x} = \mathbf{b}$ by using the $LU$-decomposition of $A$ obtained in (a), where $\textbf{b} = \left[\begin{array}{r} 0 \\ -2 \\ 1 \end{array} \right].$
\vspace{1mm}
\item[(c)] Tell what happens if you use the MATLAB command \textit{lu} of $A$. Explain why this result differs from the result in (a).

\end{enumerate}

\end{exer}

\begin{sol}

\begin{verbatim}

%(a)
A = [6 -2 0; 9 -1 1; 3 7 5]; % Set the matrix A.

format rat; % Display results as a rational form.

% Initialization of U and L.
U = A; L = eye(3);

% Multiply the first row by 1/6.
U(1,:)=(1/6)*U(1,:);
% L(1,1) is the inverse of 1/6.
L(1,1)=(1/6)^(-1);

% Add (-9) times the first to the second.
U(2,:)=((-9)*U(1,:))+U(2,:);
% L(2,1) is the negative of (-9).
L(2,1)=-(-9);

% Add (-3) times the first to the third.
U(3,:)=((-3)*U(1,:))+U(3,:);
% L(3,1) is the negative of (-3).
L(3,1)=-(-3);

% Multiply the second row by 1/2.
U(2,:)=(1/2)*U(2,:);
% L(2,2) is the inverse of 1/2.
L(2,2)=(1/2)^(-1);

% Add (-8) times the second to the third.
U(3,:)=((-8)*U(2,:))+U(3,:);
% L(3,2) is the negative of (-8).
L(3,2)=-(-8);

disp('A is'); disp(A);
disp('The Lower Triangular part L is'); disp(L);
disp('The Upper Triangular part U is'); disp(U);
disp('The product L*U is'); disp(L*U);

%(b)
% Solve the linear system Ax=b
% by using the LU-decomposition obtained in (a).

% First, let us solve L*y = b by forward substitution.
 % Set the right-hand-side vector b.
b = [0 -2 1]';

 % Initialization of the solution vector y.
y = zeros(3, 1);
y(1) = b(1) / L(1, 1);
y(2) = (b(2) - (L(2, 1)*y(1))) / L(2, 2);
y(3) = (b(3) - (L(3, 1)*y(1)) - (L(3, 2)*y(2))) / L(3, 3);

% Next, let us solve U*x = y by backward substitution.
x = zeros(3, 1); % Initialization of the solution vector x.
x(3) = y(3) / U(3, 3);
x(2) = (y(2) - (U(2, 3)*x(3))) / U(2, 2);
x(1) = (y(1) - (U(1, 3)*x(3)) - (U(1, 2)*x(2))) / U(1, 1);

disp('The solution to Ax=b by the LU-decomposition is'); disp(x');

% (c)
fprintf('Using MATLAB command lu\n');
% LU decomposition of A with a permutation matrix.
[L U P] = lu(A);

disp('Lower triangular part L is'); disp(L);
disp('Upper triangular part U is'); disp(U);
disp('The permutation matrix P is'); disp(P);
disp('PA='); disp(P*A); disp('LU='); disp(L*U);

\end{verbatim}

\begin{outputs}

\begin{verbatim}

A is
       6             -2              0
       9             -1              1
       3              7              5

The Lower Triangular part L is
       6              0              0
       9              2              0
       3              8              1

The Upper Triangular part U is
       1             -1/3            0
       0              1              1/2
       0              0              1

The product L*U is
       6             -2              0
       9             -1              1
       3              7              5

The solution to Ax=b by the LU-decomposition is
     -11/6          -11/2            9

Using MATLAB command lu

Lower triangular part L is
       1              0              0
       1/3            1              0
       2/3           -2/11           1
Upper triangular part U is
       9             -1              1
       0             22/3           14/3
       0              0              2/11
The permutation matrix P is
       0              1              0
       0              0              1
       1              0              0
PA=
       9             -1              1
       3              7              5
       6             -2              0
LU=
       9             -1              1
       3              7              5
       6             -2              0

\end{verbatim}

\end{outputs}

\noindent Since the permutation matrix $P$ is not the identity matrix, the MATLAB command \textit{lu} gave us an $LU$-decomposition after multiplying $A$ by the permutation matrix $P$, hence, this decomposition is a $PLU$-decomposition of $A$ because $PA=LU$. Since at least one row interchange of $A$ occurred in the process of $LU$-decomposition, this result is different from the previous decomposition obtained in $(a)$.

\end{sol}

\vspace{3mm}
\begin{exer} (\textit{LU-decomposition})
\begin{enumerate}
\item[(a)] The MATLAB command \textit{lu} is used to find the $LU$-decomposition of a matrix $A$. Tell what happens if you use the command $lu$ for $A$, where $A$ is given in the Example 2 of the Section 3.7. Explain why this result differs from the result in the textbook.
\vspace{1mm}
\item[(b)] Using MATLAB, observe what happens when you try to find an $LU$-decomposition of a singular matrix.

\end{enumerate}
\end{exer}

\begin{sol}

\begin{verbatim}

% (a)
% Construct the matrix A.
A=[6 -2 0; 9 -1 1; 3 7 5];

% LU decomposition of A.
[L U P]=lu(A);
disp('[L U P]=lu(A)');
disp('L'); disp(L); disp('U'); disp(U); disp('P'); disp(P);

% (b)
% Construct the some singular matrices.
A1=[1 0 0; -2 0 0; 4 6 1];
A2=[1 -2 7; -4 8 5; 2 -4 3];
A3=[1 0 0; -2 0 0; 4 6 1];

% LU decompositions of them.
[L1 U1 P1]=lu(A1); [L2 U2 P2]=lu(A2); [L3 U3 P3]=lu(A3);
disp('[L1 U1 P1]=lu(A1)'); disp('L1');disp(L1);disp('U1');disp(U1);
disp('[L2 U2 P2]=lu(A2)'); disp('L2');disp(L2); disp('U2');disp(U2);
disp('[L3 U3 P3]=lu(A3)'); disp('L3');disp(L3); disp('U3');disp(U3);
\end{verbatim}

\begin{outputs}

\begin{verbatim}

[L U P]=lu(A)
L
    1.0000         0         0
    0.3333    1.0000         0
    0.6667   -0.1818    1.0000

U
    9.0000   -1.0000    1.0000
         0    7.3333    4.6667
         0         0    0.1818

P
     0     1     0
     0     0     1
     1     0     0

[L1 U1 P1]=lu(A1)
L1
    1.0000         0         0
   -0.5000    1.0000         0
    0.2500   -0.5000    1.0000
U1
    4.0000    6.0000    1.0000
         0    3.0000    0.5000
         0         0         0

[L2 U2 P2]=lu(A2)
L2
    1.0000         0         0
   -0.2500    1.0000         0
   -0.5000         0    1.0000
U2
   -4.0000    8.0000    5.0000
         0         0    8.2500
         0         0    5.5000

[L3 U3 P3]=lu(A3)
L3
    1.0000         0         0
   -0.5000    1.0000         0
    0.2500   -0.5000    1.0000
U3
    4.0000    6.0000    1.0000
         0    3.0000    0.5000
         0         0         0

\end{verbatim}
\end{outputs}

\noindent \textit{Remark on (a).} Since the permutation matrix $P$ is not the identity matrix, the MATLAB command \textit{lu} gave us an $LU$-decomposition after multiplying $A$ by the permutation matrix $P$, hence, this decomposition is a $PLU$-decomposition of $A$ because $PA=LU$. Since at least one row interchange of $A$ occurred in the process of $LU$-decomposition, this result is different from the decomposition result in the textbook.

\vspace{2mm}
\noindent \textit{Remark on (b).} When we try $LU$-decomposition of the sigular matrices using the MATLAB command \textit{lu}, the resulting upper triangular matrices are singular.

\end{sol}

_codes/intro/Learning MATLAB with Linear Algebra (Jeon, Lee)/section3.tex

files/intro/Learning MATLAB with Linear Algebra (Jeon, Lee)/section3.tex


\documentclass[11pt]{article}

\usepackage{amsmath}
\usepackage{textcomp}
\usepackage{graphicx}
\usepackage{multicol}
\usepackage[top=0.8in, bottom=0.8in, left=0.8in, right=0.8in]{geometry}
% add other packages here
\usepackage[font=small,labelfont=bf]{caption} % Required for specifying captions to tables and figures

% put your group number and names in the author field
\title{\bf Exercise 2: A Reactive Agent for the Pickup and Delivery Problem}
\author{Group \textnumero 70: Jelena Banjac, Stratos Triantafyllou}

% the report should not be longer than 3 pages

\begin{document}
\maketitle

\section{Problem Representation}

\subsection{Representation Description}
% describe how you design the state representation, the possible actions, the reward table and the probability transition table

Our implementation assumes as state a route from an origin city to a destination city. The next city the vehicle will visit next is modeled as an action. If a vehicle on a route is carrying out a delivery task, no destination city is defined - implemented with the method \texttt{hasTask()}.

This flag is used in the creation of the reward table. If the vehicle is carrying out a delivery task next, then the added reward R(s, a) is computed based on the income for the delivery from the destination city in s to the next city as defined in the action a, subtracting the distance between these two cities. If the vehicle is just moving to the next city without delivering a task, we just subtract the distance between the cities.

To compute transition probabilities, if the vehicle is carrying out a delivery task, we use the probability that the agent moves between the origin and the destination city. If the vehicle is just moving to a neighbor city, each neighbor has the same probability and the transition is random.

\subsection{Implementation Details}
% describe the implementation details of the representations above and the implementation details of the reinforcement learning algorithm you implemented
Implementation of the state is in the \texttt{state.RouteState} with parameters \texttt{fromCity} and \texttt{toCity}. The initialization of all the states is done in the method \texttt{initializeStates}. In total we have ${N}^2$ states.
The action is implemented in the class \texttt{action.RouteAction} with parameter \texttt{neighborCity}. The method \texttt{initializeActions} is initializing all the actions. In total we have N actions.
Before Reinforcement Learning Algorithm (RLA), we fill in the Reward table - \texttt{R(s,a)}. Reward is calculated differently depending whther the agent has a tas or not. We also initialize Q-table - \texttt{Q(s,a)} together with the vector with state values and corresponding action to take in that state - \texttt{V}. When Q table is initialized, it does not use all the combinations of state and action. The constraints are: the agent cannot stay in the same city and if there is no delivery, the action needs to be a neighbor city.
These tables are all located in the \texttt{tables.Tables}.
We compute this vector in method \texttt{rla()} by value iteration. This value improves with each iteration, and our stopping criteria is until the difference between two successive iteration is smaller than $\epsilon$=0.001.

\section{Results}
% in this section, you describe several results from the experiments with your reactive agent
In this section, we will describe several results from the experiments with our reactive agent.

\subsection{Experiment 1: Discount factor}
% the purpose of this experiment is to understand how the discount factor influences the result
In the first experiment, we want to understand how discount factor $\gamma$ influences the results. The discount factor represents how much we discount the future, i.e. how much an agent is taking care of rewards from the future states. If the $\gamma$=0, it means that we discard the future totally. Whereas, the higher the value of $\gamma$, the higher the effect of the future on the value of state value V(S).

\subsubsection{Setting}
% you describe how you perform the experiment (you also need to specify the configuration used for the experiment)
This experiment was performed with the following settings:
(1) discount factor for our reactive agent: $\gamma$ $\epsilon$ [0.15, 0.50, 0.85, 0.95, 0.99]; (2) cost per km for all vehicles is 5 CHF; (3) capacity of all the vehicles is 30 KG; (4) speed of all the vehicles vehicle is 220 KM/H; (5) topology is Switzerland.

\subsubsection{Observations}
% you describe the experimental results and the conclusions you inferred from these results
Number of iterations of RLA algorithm until good enough is: [6, 9, 11, 9, 7] for the discount factors $\gamma$ $\epsilon$ [0.99, 0.95, 0.95, 0.85, 0.50, 0.15], respectively. We run several times (3 times) in order to get a confidence intervals of total profits and reward per kilometer results. Using this information we can find the best value of $\gamma$.

\begin{multicols}{2}
\includegraphics[scale=0.2]{ex1-rpk-full.png}
\captionof{figure}{Reward per kilometer - full image}

\includegraphics[scale=0.2]{ex1-rpk-zoomed.png}
\captionof{figure}{Reward per kilometer - zoomed}
\end{multicols}

\begin{multicols}{2}
\includegraphics[scale=0.2]{ex1-tp-full.png}
\captionof{figure}{Total profit - full image}

\includegraphics[scale=0.2]{ex1-tp-zoomed.png}
\captionof{figure}{Total profit - zoomed}
\end{multicols}

From the images above, we can see that with our settings the agent that performs the best is the one with the discount factor $\gamma$ = 0.85. It means that it takes into an account the future pretty highly.

\subsection{Experiment 2: Comparisons with dummy agents}
% you compare the results of your agent with two dummy agents: the random agent that was already given in the starter files and another dummy agent that you define and create. You should report the results from the simulations using the topologies given in the starter files and optionally, additional topologies that you create.
In this experiment, we compare the results of our agent with two dummy agents: the random agent in the starter files and another dummy agent that has $\gamma$=0. We perform this experiment on different typologies.

\subsubsection{Setting}
% you describe how you perform the experiment and you describe the dummy agent you created (you also need to specify the configuration used for the experiment)
The first dummy agent is a random agent does not implement the Reinforcement Learning Algorithm (RLA) and chooses the next path to move randomly. The second dummy agent is the agent that discards the effect of the future states, therefore, it acts only to maximize an immediate reward. The third agent is our final agent that performs the best.
Additional settings we have are: (1) cost per km for all vehicles is 5 CHF; (2) capacity of all the vehicles is 30 KG; (3) speed of all the vehicles vehicle is 220 KM/H

\subsubsection{Observations}
% elaborate on the observed results

\begin{multicols}{2}
\includegraphics[scale=0.18]{ex2-rpk-full.png}
\captionof{figure}{Switzerland topology - Reward per kilometer (full image)}

\includegraphics[scale=0.18]{ex2-rpk-zoomed.png}
\captionof{figure}{Switzerland - Reward per kilometer (zoomed)}
\end{multicols}

\begin{multicols}{2}
\includegraphics[scale=0.19]{ex2-tp-full.png}
\captionof{figure}{Switzerland - Total profit (full image)}

\includegraphics[scale=0.19]{ex2-tp-zoomed.png}
\captionof{figure}{Switzerland - Total profit (zoomed)}
\end{multicols}
From the images of the performance of agents in Swiss topology, we can see that random agent (green) performs worse than the ones that implement the RLA, see Fig.5, Fig.6, Fig.7, and Fig.8. Even the agent that is using the discount factor $\gamma$=0 is performing better than the random one (which is expected since it is maximizing an immediate reward and does not go randomly). The agent which we think was the best was the one with $\gamma$=0.85 (blue).

\begin{multicols}{2}
\includegraphics[scale=0.19]{fr1.png}
\captionof{figure}{France - Total profit (zoomed)}

\includegraphics[scale=0.19]{fr2.png}
\captionof{figure}{France - Reward per kilometer (full)}
\end{multicols}
However, when we ran the agents in a different topology (France), we got that the random one still performs the worse, however, the agent with $\gamma$=0.95 performs better than the one with $\gamma$=0.85. And the agent that gets the immediate reward has performance with the result in between these agents, see Fig.9 and Fig.10. We did the same for the topology of England. The discount factor that performs the best there was $\gamma$=0.5. More information can be found in the notebooks.

\end{document}


\section*{Materials and Methods}

\subsection*{Formulas.}
For mathematical formulas you should use the math environment. See this example:

\begin{center}
$f(A_{ik},A_{jk}) = min(A_{ik},A_{jk}) - C_{1} max(A_{ik},A_{jk}) e^{-C_{2}min(A_{ik},A_{jk})}$
\end{center}


\RequirePackage[l2tabu, orthodox]{nag}
\documentclass[landscape, letterpaper, 8pt]{extarticle}

\usepackage[margin=.25in]{geometry}
\usepackage{fontspec}
\usepackage{amssymb}
\usepackage{mathtools}
\usepackage{multicol}
\usepackage{enumitem}
\usepackage{scrextend}

%\setmainfont{Lato}
%\linespread{0.2}

\renewcommand{\complement}[1]{{#1}^\mathsf{c}}
\DeclarePairedDelimiter{\floor}{\lfloor}{\rfloor}

\begin{document}
\begin{multicols}{3}
    \section*{Logic Properties}
    \begin{itemize}[noitemsep,nolistsep]
        \item \textbf{Generalization: } $p~\therefore p \lor q$ and $q~\therefore p \lor q$
        \item \textbf{Specialization: } $p \land q~\therefore p$ or $q$
        \item \textbf{Conjunction: } $p,~q~\therefore p \land q$
        \item \textbf{Eliminiation: } $p \lor q,~\neg q~\therefore p$
        \item \textbf{Division into Cases: } $p \lor q,~p\implies r,~q\implies r~\therefore r$
        \item \textbf{Contradiction Rule: } $\neg p \implies c~\therefore p$
    \end{itemize}
    \subsection*{Implies}
    \begin{itemize}[noitemsep,nolistsep]
        \item \textbf{Statement: } $p \implies q$
        \item \textbf{Converse: } $q \implies p$
        \item \textbf{Inverse: } $\neg p \implies \neg q$
        \item \textbf{Contrapositive: } $\neg q \implies \neg p$
    \end{itemize}
    \subsection*{Quantified}
    \begin{itemize}[noitemsep,nolistsep]
        \item \textbf{Universal Instantiation: } $\forall x,~P(x)~\therefore P(a)$ also applies to $\exists$.
        \item \textbf{Universal Generalization: }$P(a)~\therefore \forall x,~P(x)$ also applies to $\exists$.
        \item \textbf{Negation: }$\neg(\forall x, Q(X)) \equiv \exists x, \neg Q(x)$ and $\neg(\exists x, Q(X)) \equiv \forall x, \neg Q(x)$.
        \item \textbf{Universal Modus Ponens: } $\forall x, P(x)\implies Q(x),~P(a)~\therefore Q(a)$ does not apply to $\exists$.
        \item \textbf{Universal Modus Tolens: } $\forall x, P(x)\implies Q(x),~\neg Q(a) \therefore \neg P(a)$ does not apply to $\exists$.
        \item \textbf{Converse Error: }$ \begin{aligned}
                                 & \forall x, P(x) \implies Q(x) \\
                                 & Q(a)                          \\
                      \therefore & P(a)
                  \end{aligned}$
        \item \textbf{Inverse Error: } $\begin{aligned}
                                 & \forall x, P(x) \implies Q(x) \\
                                 & \neg P(a)                     \\
                      \therefore & Q(a)
                  \end{aligned}$

    \end{itemize}
    \section*{Induction}
    \subsection*{Strong Induction}
    \textbf{Let} $P(n)$ be the property to be proven, let $a$ and $b$ be fixed integers where $a\leq b$.

    Suppose the following:
    \begin{enumerate}[noitemsep,nolistsep]
        \item \textbf{Basis:} $P(a), P(a+1), \ldots P(b)$ are true.
        \item \textbf{Induction:} For all integers $k\geq b$, if $P(i)$ is true for all integers from $a$ to $k$ then $P(k+1)$ is true.
        \item Hence for all integers $n\geq a, P(n)$ is true.
    \end{enumerate}
    \section*{Number Theory}
    \begin{itemize}[noitemsep,nolistsep]
        \item \textbf{Even} $n$ is even $\iff \exists k, n = 2k$.
        \item \textbf{Odd} $n$ is odd $\iff \exists k, n = 2k+1$.
        \item \textbf{Prime} $n$ is prime $\iff \forall r, s$, if $n = rs$ then $r=1$ and $s = n$ or vice versa.
        \item \textbf{Composite} $n$ is composite $\iff \exists r, s$, if $n = rs$ and $1 < r < s$ and $1 < s < n$.
        \item \textbf{Rational} $r$ is rational $\iff \exists a, b$ such that $r = \frac{a}{b}$ and $b \neq 0$.
        \item \textbf{Divisible} $d|n \iff \exists k$ such that $n=dk$.
    \end{itemize}
    \section*{Sets}
    Can be proven by using Induction, Algebra or Element method.

    Element Method: Usually with equality or subset relations: prove that an element in LHS is an element in RHS.
    \begin{itemize}[noitemsep,nolistsep]
        \item Proper Subset: $A \subseteq B$ \textbf{AND} there is one element in B that is \textbf{not} in A
        \item Power Set: $\wp(\{x, y, z\}) = \{\emptyset, \{x\}, \{y\}, \{z\},\\
                  \{x, y\},\{x, z\}, \{y, z\}, \{x, y, z\}$
        \item Disjoint set:$A\cap B = \varnothing$
    \end{itemize}
    \subsection*{Identities}
    \begin{itemize}[noitemsep,nolistsep]
        \item Commutative Law
              \begin{itemize}[noitemsep,nolistsep]
                  \item $A \cup B = B \cup A $ and $A \cap B = B \cap A$
              \end{itemize}
        \item Associative Law
              \begin{itemize}[noitemsep,nolistsep]
                  \item $(A \cup B) \cup C = A \cup (B \cup C)$ and $(A \cap B) \cap C = A \cap (B \cap C)$
              \end{itemize}
        \item Distributive Law
              \begin{itemize}[noitemsep,nolistsep]
                  \item $A \cup (B \cap C) = (A \cup B) \cap (A \cup C)$
                  \item $A \cap (B \cup C) = (A \cap B) \cup (A \cap C)$
              \end{itemize}
        \item Identity Law
              \begin{itemize}[noitemsep,nolistsep]
                  \item $A \cup \varnothing = A$ and $A \cap U$
              \end{itemize}
        \item Idempotent Law
              \begin{itemize}[noitemsep,nolistsep]
                  \item $A \cup A = A$ and $A\cap A = A$
              \end{itemize}
        \item Universal Bound Law
              \begin{itemize}[noitemsep,nolistsep]
                  \item $A \cup U = U$ and $A  \cap \varnothing = \varnothing$
              \end{itemize}
        \item DeMorgan's Law
              \begin{itemize}[noitemsep,nolistsep]
                  \item $\complement{(A \cup B)} = \complement{A} \cap \complement{B}$ and $\complement{(A \cap B)} = \complement{A} \cup \complement{B}$
              \end{itemize}
        \item Absorption Law
              \begin{itemize}[noitemsep,nolistsep]
                  \item $A \cup (A \cap B) = A$ and $A \cap (A \cup B) = A$
              \end{itemize}
        \item Set Difference Law
              \begin{itemize}[noitemsep,nolistsep]
                  \item $A-B = A \cap \complement{B}$
              \end{itemize}
        \item Complement Law
              \begin{itemize}[noitemsep,nolistsep]
                  \item $A\cup \complement{A} = U$ and $A \cap \complement{A} = \varnothing$
              \end{itemize}
    \end{itemize}
    \section*{Functions}
    A function $f$ from a set $X$ to a set $Y$ denoted by $f: X \to Y$ where $X$ is the domain and $Y$ is the co-domain.
    Every element in $X$ relates to some element in $Y$ and each element in $X$ must map to at most one element in $Y$.
    \subsection*{One-to-One functions}
    $\forall x_1, x_2 \in X[(F(x_1) = F(x_2)) \implies (x_1 = x_2)]$
    \subsection*{Onto functions}
    $\forall y \in Y[ \exists x \in X \text{ where } F(x)=y]$
    \subsection*{Inverse functions}
    $F^{-1}(y) = x\text{ where }F(x) = y$.
    $F(x)$ has to be bijective (both one-to-one and onto).
    \section*{Relations}
    A partition of set $A$ is a collection of nonempty, mutually disjoint subsets whose union is $A$, i.e. $A_1 \cup A_2 \cup A_3 \cup \ldots \cup A_i = A$
    \begin{itemize}[noitemsep,nolistsep]
        \item Reflexive $\forall x \in A[(x, x) \in \mathbb{R}]$
        \item Symmetric $\forall x, y \in A[(x, y) \in \mathbb{R} \implies (y, x) \in \mathbb{R}]$
        \item Transitive $\forall x, y, z \in A[(x R y \land y R z)\implies x R z]$
        \item Partition-induced relation: $\forall x, y \in A[x R y \iff (x, y) \in \text{single partition }A_i]$
        \item Equivalence Relation: When a relation is relation is reflexive, symmetric and transitive.
        \item Identity Relation: $I_A = \{(x, y) \in A \times A~|~x=y\}$
    \end{itemize}
    \subsection*{Equivalence Classes}
    The subset of all elements that are related to $a$.

    Suppose $A$ is a set and $R$ is an equivalence relation on $A$. For each element $a$ in $A$, the \textbf{equivalence class of $a$}, $[a]$ or \textbf{class of $a$} is the set of all elements $x$ in $A$ such that $x$ is related to $a$ by $R$. \[[a] = \{x \in A~|~x~R~a\}\]
    \section*{Partial Order Relations}
    A relation that is reflexive, antisymmetric and transitive.
    \subsection*{Antisymmetry}
    A relation is antisymmetric if $x R y \land y R x,~x = y$
    A relation is \textbf{not} antisymmetric if $x R y \land y R x\text{ but }x \neq y$
    \section*{Counting}
    $P(E)$ is \[P(E) = |E|/|S|\] where S is the set of possible outcomes and E is the set of events.

    Number of elements: $|{n, n+1, n+2, \ldots, m}| = m - n + 1$
    \subsection*{Permutations and Combinations}
    Number of possible arrangements of n units: $n!$
    \begin{itemize}[noitemsep,nolistsep]
        \item With $n_1$ duplicates: $\frac{n!}{n_1!}$
        \item With $m$ units in certain order: $(n-(m-1))!$
        \item In a circle/rotation: $\frac{n!}{n}$ (Let 1 be fixed, arrange the rest.)
    \end{itemize}

    $P(n, r) = \frac{n!}{(n-r)!}$

    $C(n, r) = \binom{n}{r} = \frac{P(n, r)}{r!}$

    Number of Combinations with repetitions allowed: $\binom{r+n-1}{r}$

    $\binom{n}{r} = \binom{n}{n-r}$

    Pascal's Formula: $\binom{n+1}{r} = \binom{n}{r-1}+ \binom{n}{r}$

    Binomial Theorem:\begin{align*}
        (a+b)^n & = \sum_{k=0}^n\binom{n}{k} a^{n-k}b^k                                  \\
                & = a^n + \binom{n}{1} a^{n-1} b^1                                       \\
                & + \binom{n}{2} a^{n-2} b^2 + \ldots + \binom{n}{n-1} a^1 b^{n-1} + b^n \\
    \end{align*}
    \subsection*{Pigeonhole Principle}
    If $n$ pigeons fly into $m$ pigeonholes, and $n > km$ for some $k \in \mathbb{Z}^+$ then at least one pigeonhole contains k+1 or more pigeons.

    Generalized: \[k = \floor*{\frac{n}{m}}\]

    "The maximum value has at least the average value, for any non-empty finite bag of real numbers" -Prof. Djikstra
    \section*{Examples}
    \newtheorem{example}{Example}
    \subsection*{Strong Induction}
    \begin{example}
        \begin{equation*}
            \begin{aligned}
                f(n) = \begin{cases}
                    1                   & \text{if }n=1      \\
                    3                   & \text{if }n=2      \\
                    f(n-1) + 2f(n-2) +3 & \text{if } n\geq 3
                \end{cases}
            \end{aligned}
        \end{equation*}
        Using mathematical induction, prove that for all $n \geq 3: f(n) \geq 2^n$

        Answer:
        \begin{equation*}
            \begin{aligned}
                f(k+1) =f(k)+ 2f(k-1)+3              \\
                \text{Use fact that $f(n) \geq 2^n$} \\
                f(k+1) \geq 2^k+2\cdot 2^{k-1} +3    \\
                \text{and } f(k+1) \geq 2^k + 2^k +3 = 2^{k+1} + 3 \geq 2^{k+1}
            \end{aligned}
        \end{equation*}
    \end{example}
    \subsection*{Weak Induction}
    \begin{example}
        What is the smallest value of k such that any integer postage of k, or
        more, cents can be formed by using only 3-cent and 8-cent stamps?

        Use mathematical induction to prove that all integer postages of k, or more, cents can be
        obtained.
        \begin{equation*}
            \begin{aligned}
                \textbf{Basis: } P(n):                             & n = 3a + 8b       \\
                \textbf{Induction: } P(n+1):                       & n+1 = 3a' + 8b'   \\
                \textbf{Case 1: } \text{if } b \geq 1, n = 3a + 8b & \text{, so}       \\
                n+1 = 3a+1+8b                                      & = 8(b-1) + 9 + 3a \\
                n+1                                                & = 8(b-1) +3(a+3)  \\
                \textbf{Hence }a' = a+3      \text{ and }          & b' = b - 1        \\
                \textbf{Case 2: } \text{if } b = 0, n = 3a         &                   \\
                \text{Since }n \geq 14,~a \geq 5                                       \\
                n+1 = 1 + 15 + 3(l-5)                              & = 16+ 3(l-5)      \\
                \textbf{Hence }a' = l-5      \text{ and }          & b' = 2            \\
            \end{aligned}
        \end{equation*}
    \end{example}
    \begin{example}
        Recall that the $n$'th Harmonic number, $H_n$, is defined as:
        \[
            H_n = 1+ \frac{1}{2} + \frac{1}{3} + \ldots + \frac{1}{n}
        \]
        Use mathematical induction to prove that for all positive integers $n$:
        \[
            H_1 + H_2 + \ldots + H_n = (n+1)H_n -n
        \]
        Answer:
        \begin{equation*}
            \begin{aligned}
                \textbf{Basis: } P(n): & H_1 + H_2 + \ldots + H_n = (n+1) H_n-n \\
                P(1):                  & H_1 = 1 = 2H_1 -1                      \\
            \end{aligned}
        \end{equation*}
        \begin{equation*}
            \begin{aligned}
                \textbf{Induction: } & H_1 + \ldots + H_k + H_{k+1} = (k+1)H_k - k + H_{k+1}                  \\
                \text{Using IH for k}                                                                         \\
                =                    & (k+1)(1+\frac{1}{2}+\ldots+\frac{1}{k})-k  +(1+\ldots + \frac{1}{k+1}) \\
                =                    & \ldots                                                                 \\
                % Rest of the fucking owl
                =                    & (k+2) (1+\frac{1}{2} + \ldots + \frac{1}{k+1}) - (k+1)
            \end{aligned}
        \end{equation*}
    \end{example}
    \subsection*{Functions}
    Let $f: X \mapsto Y$ and $g: Y \mapsto Z$ be functions. Indicate whether each statement below is true or false. Give a proof for each true statement and a counterexample for each false statement.

    \textbf{a) If $g \circ f$ is onto then $f$ is onto.}

    \textbf{Answer: } False.

    $X = {1, 2}, Y = {1, 2, 3}, Z = {1, 2}, f(1) = 1, f(2) = 2, g(1) = 1, g(2) = 2, g(3) = 2$

    \textbf{b) If $g \circ f$ is onto then $g$ is onto.}

    \textbf{Answer: } True.

    Let $z \in Z$. There exists $x \in X$ such that $g(f(x)) = z$ since $g \circ f$ is onto. So $g(y) = z$ for $y = f(x)$. Therefore $g$ is onto.

    \textbf{c) If $g \circ f$ is one-to-one then $f$ is one-to-one.}

    \textbf{Answer: } True.

    Let $x_1, x_2 \in X$ such that $f(x_1) = f(x_2)$.

    Then $g(f(x_1)) = g(f(x_2))$. Now $g(f(x_1)) = g(f(x_2))$ by definition of composition. Therefore $x_1 = x_2$ since $g \circ f$ is one-to-one. This implies $f$ is one-to-one.

    \textbf{d) If $g \circ f$ is one-to-one then $g$ is one-to-one.}

    \textbf{Answer: } False.

    Use part (a).

    \subsection*{Counting}
    \begin{example}
        How many three-digit integers are divisible by 5?
        \begin{equation*}
            \begin{aligned}
                \text{Three-digit integers} = {100, 101, \ldots, 999}                                         \\
                \left\lfloor \frac{100}{5} \right\rfloor = 20, \left\lfloor \frac{999}{5} \right\rfloor = 199 \\
                \text{by number of elements theorem: } 199-20 + 1 = 180
            \end{aligned}
        \end{equation*}
    \end{example}
    \begin{example}
        Consider a robot moving in an $m \times n$ grid, where $m\leq n$. It starts at the coordinate $(1,1)$. At each step, when it is at position $(i,j)$, it either moves one square up to $(i+1, j)$ or one square right to $(i, j+1)$. How many ways can the robot travel from $(1,1)$ to $(m,n)$? Justify your answer.

        Answer:
        \begin{align*}
            m - 1 \text{ possible steps up.}               \\
            n - 1 \text{ possible steps right.}            \\
            (m - 1) + (n - 1) \text{ total steps.}         \\
            \text{Each step up and right are the same, so} \\
            \frac{(m+n - 2)!}{(m-1)!(n-1)!}                \\
        \end{align*}
    \end{example}
    \subsection*{Direct proofs}
    \begin{example}
        $6-7\sqrt{2}$ is irrational.
        \begin{align*}
            \text{Assume } 6-7\sqrt{2} = \frac{p}{q} \text{ where } p, q \in \mathbb{Z} \land q \not = 0. \\
            \sqrt{2} = \frac{\left(\frac{p}{q}-6\right)}{-7} = \frac{p-6q}{-7q}                           \\
        \end{align*}
        This is rational as both the numerator and denominator are products and differences of integers and thus are integers, and the denominator is not equal to zero.
    \end{example}
    \subsection*{Pigeonhole Princple}
    \begin{example}
        For every 27 word sequence in a paragraph, at least two words will start with the same letter.

        \textbf{Reason: } There are 27 words that can start with the 26 different English letters. By the pigeonhole principle, two of the words must start with the same letter.
    \end{example}
    \begin{example}
        If a theatre holds 1300 people, how many seats need to be filled to ensure that two people have the same first and last initials?

        \textbf{Answer: } 26 letters in English language, Fname.Lname = 1 letter on each initial. $26 * 26$ means at least 1 person as each combination of initials. $26 * 26 +1$ ensures at least 1 duplicate.
    \end{example}
    \begin{example}
        Let ABC be an equilateral triangle with AB = 1. Show that by selecting 10 points, there are at least two with distance $\leq \frac{1}{3}$ apart.

        \textbf{Answer: } If you split up the triangle by $\frac{1}{3}$ lengths, you will create 9 slots. The 10th will be in the same triangle as another, which is less than $\frac{1}{3}$.
    \end{example}
    \begin{example}
        Prove with the pigeonhole principle that having 100 whole numbers, one can choose 15 of them so that the difference of any 2 is divisible by 7?

        \textbf{Answer: } Use the generalized pigeonhole principle.

        Let $S: \{1\ldots100\}.~S' = S \mod 7 = \{1 \mod 7 \ldots 100 \mod 7\}$

        Partition $S'$ into $7$ subsets of equal size where each subset has same value for $S \mod 7$.

        By generalized PHP, where $\lfloor \frac{units}{holes}\rfloor$ units in each hole, there are at least $\lfloor \frac{100}{7} \rfloor = 14$ remainders in each subset of $S'$.

        $14 * 7 = 98$ which is $2$ less than $100$. We can place those $2$ with the other subsets that contain the same number, increasing the number to at least 15 for one or more of the subsets.

    \end{example}
\end{multicols}
\end{document}


\section{$I$-invariance of $\Bun_G$, and $G$-CW-complexes}
Let $G$ be a topological group. We need to show that the functor
$\Bun_G:\Top^{op}\to\Set$ is $I$-invariant, i.e., the projection
$X\times I\xrightarrow{\pr}X$ induces an isomorphism
$\Bun_G(X)\xrightarrow{\simeq}\Bun_G(X\times I)$.
Injectivity is easy: the composite $X\xrightarrow{\inc_0} X\times
I\xrightarrow{\pr}X$ gives you a splitting
$\Bun_G(X)\xrightarrow{\pr_\ast}\Bun_G(X\times I)\xrightarrow{\inc_0}\Bun_G(X)$
whose composite is the identity.

The rest of this lecture is devoted to proving surjectivity. We will prove this
when $X$ is a CW-complex (Husemoller does the general case; see \cite[\S
4.9]{husemoller}). We begin with a small digression.
%Consider two principal $G$-bundles $P\to X$ and $Q\to Y$, with a map $f:X\to
%Y$. We would like to understand maps $P\to f^\ast Q$ over $X$, i.e.,
%$G$-equivariant dotted maps that make the following diagram commute.
%\begin{equation*}
%    \xymatrix{
%	P\ar@{-->}[r]^g\ar[d] & Q\ar[d]\\
%	X\ar[r]_f & Y
%    }
%\end{equation*}
%Suppose I have $P\to X\times I$; then we get $in_0^\ast P\to X$. This has to
%be what you get when you ---. All we have to do is construct a map $P\to
%in_0^\ast P$ like in the diagram above.
\subsection{$G$-CW-complexes}
We would like to define CW-complexes with an action of the group $G$. The
na\"ive definition (of a space with an action of the group $G$) will not be
sufficient; rather, we will require that each cell have an action of $G$.

In other words, we will build $G$-CW-complexes out of ``$G$-cells''. This is
supposed to be something of the form $D^n\times H\backslash G$, where $H$ is a
closed subgroup of $G$. Here, the space $H\backslash G$ is the orbit space,
viewed as a right $G$-space. The boundary of the $G$-cell $D^n\times
H\backslash G$ is just $\partial D^n\times H\backslash G$. More precisely:
\begin{definition}
    A $G$-CW-complex is a (right) $G$-space $X$ with a filtration
    $0=X_{-1}\subseteq X_0\subseteq \cdots\subseteq X$ such that for all $n$,
    there exists a pushout square:
    \begin{equation*}
	\xymatrix{
	    \coprod\partial D^n_\alpha\times H_\alpha\backslash G\ar[r]\ar[d] &
	    \coprod D^n_\alpha\times H_\alpha\backslash G\ar[d]\\
	    X_{n-1}\ar[r] & X_n,
	    }
    \end{equation*}
    and $X$ has the direct limit topology.
\end{definition}
Notice that a CW-complex is a $G$-CW-complex for the trivial group $G$.
\begin{theorem}
    If $G$ is a compact Lie group and $M$ a compact smooth $G$-manifold, then
    $M$ admits a $G$-CW-structure.
\end{theorem}
This is the analogue of the classical result that a compact smooth manifold is
homotopy equivalent to a CW-complex, but it is much harder to prove the
equivariant statement.

Note that if $G$ acts principally (Definition \ref{principaldefn}) on $P$, then
every $G$-CW-structure on $P$ is ``free'', i.e., $H_\alpha = 0$.
\begin{enumerate}
    \item If $X$ is a $G$-CW-complex, then $X/G$ inherits a CW-structure whose
	$n$-skeleton is given by $(X/G)_n = X_n/G$.
    \item If $P\to X$ is a principal $G$-bundle, then a CW-structure on $X$
	lifts to a $G$-CW-structure on $P$.
\end{enumerate}
\subsection{Proof of $I$-invariance}
Recall that our goal is to prove that every $G$-bundle over $X\times I$ is
pulled back from some vector bundle over $X$.

As a baby case of Theorem \ref{Iinvariance} we will prove that if
$X$ is contractible, then any principal $G$-bundle over $X$ is trivial, i.e.,
$P\simeq X\times G$ as $G$-bundles.

Let us first prove the following: if $P\downarrow X$ has a section, then it's
trivial. Indeed, suppose we have a section $s:X\to P$. Since $P$ has an action
of the group on it, we may extend this to a map $X\times G\to P$ by sending
$(x,g)\mapsto gs(x)$. As this is a map of $G$-bundles over $X$, it is an
isomorphism by Theorem \ref{morphismiso}, as desired.

To prove the statement about triviality of any principal $G$-bundle over a
contractible space, it therefore suffices to construct a section for any
principal $G$-bundle. Consider the constant map $X\to P$. Then the following
diagram commutes up to homotopy, and hence (by Exercise
\ref{sectionuptohomotopy}(1)) there is an \emph{actual} section of $P\to X$, as
desired.
\begin{equation*}
    \xymatrix{
	& P\ar[d]\\
	X\ar[ur]^{\mathrm{const}}\ar[r] & X
    }
\end{equation*}
For the general case, we will assume $X$ is a CW-complex. For notational
convenience, let us write $Y=X\times I$. We will use descending induction to
construct the desired principal $G$-bundle over $X$.

To do this, we will filter $Y$ by subcomplexes. Let $Y_0 = X\times 0$; in
general, we define
$$Y_n = X\times 0\cup X_{n-1}\times I.$$
It follows that we may construct $Y_n$ out of $Y_{n-1}$ via a pushout:
\begin{equation*}
    \xymatrix{
	\coprod_{\alpha\in\Sigma_{n-1}}(\partial D^{n-1}\times I \cup
	D^{n-1}_\alpha\times 0) \ar[r]\ar[d]_{\coprod_{\alpha\in\Sigma_{n-1}}
	f_\alpha\times 1_I\cup\phi_\alpha\times 0} &
	\coprod_\alpha(D^{n-1}_\alpha\times I) \ar[d]\\
	Y_{n-1}\ar[r] & Y_n,
    }
\end{equation*}
where the maps $f_\alpha$ and $\phi_\alpha$ are defined as:
\begin{equation*}
    \xymatrix{
	\partial D^{n-1}_\alpha\ar[r]^{f_\alpha}\ar[d] & X_{n-2}\ar[d]\\
	D^{n-1}_\alpha\ar[r]_{\phi_\alpha} & X_{n-1}
    }
\end{equation*}
In other words, the $f_\alpha$ are the attaching maps and the $\phi_\alpha$ are
the characteristic maps.

Consider a principal $G$-bundle $P\xrightarrow{p}Y = X\times I$. Define $P_n =
p^{-1}(Y_n)$; then we can build $P_n$ from $P_{n-1}$ in a similar way:
\begin{equation*}
    \xymatrix{
	\coprod_\alpha(\partial D^{n-1}_\alpha\times I\cup D^{n-1}_\alpha\times
	0)\times G\ar[r]\ar[d] & \coprod_\alpha (D^{n-1}_\alpha\times I)\times
	G\ar[d]\\
	P_{n-1}\ar[r] & P_n
    }
\end{equation*}
%This makes sense since $D^n_\alpha\times I$ is a contractible space, and same
%thing for the other factor.
Note that this isn't \emph{quite} a $G$-CW-structure. Recall that we are
attempting to fill in a dotted map:
\begin{equation*}
    \xymatrix{
	P\ar@{-->}[r]\ar[d] & P_0\ar[d]\\
	Y\ar[r]_{\pr} & Y_0 = X
    }
\end{equation*}
\todo{finish this...}
I'm constructing this inductively-- we have $P_{n-1}\to P_0$. So I want to define $\coprod_\alpha(D^{n-1}_\alpha\times I)\times G\to P_0$ that's equivariant. That's the same thing as a map $\coprod_\alpha (D^{n-1}_\alpha\times I)\to P_0$ that's compatible with the map from $\coprod(\partial D^{n-1}_\alpha\times I\cup D^{n-1}_\alpha\times 0)$. Namely, I want to fill in:
\begin{equation}\label{finally}
    \xymatrix{
	\coprod_\alpha (\partial D^{n-1}_\alpha\times I\cup D^{n-1}_\alpha\times 0)\ar[r]\ar[d] & \coprod_\alpha(D^{n-1}_\alpha\times I)\ar@{-->}[dddr]\ar[d] & \\
	\coprod_\alpha(\partial D^{n-1}_\alpha\times I\cup D^{n-1}_\alpha\times 0)\times G\ar[r]\ar[d] & \coprod_\alpha (D^{n-1}_\alpha\times I)\times G\ar@{-->}[ddr]\ar[d] & \\
	P_{n-1}\ar[drr]_{\mathrm{induction}}\ar[r] & P_n\ar[dr] & \\
	& & P_0\ar[d]\\
	& & X
    }
\end{equation}
Now, I know that $(D^{n-1}\times I,\partial D^{n-1}\times I\cup D^{n-1}\times 0)\simeq (D^{n-1}\times I,D^{n-1}\times 0)$. So what I have is:
\begin{equation*}
    \xymatrix{
	D^{n-1}\times 0\ar[d]\ar[r]^{\mathrm{induction}} & P_0\ar[d]\\
	D^{n-1}\times I\ar[r]_{\phi\circ pr}\ar@{-->}[ur] & X
    }
\end{equation*}
So the dotted map exists, since $P_0\to X$ is a fibration!

OK, so note that I haven't checked that the outer diagram in Equation \ref{finally} commutes, because otherwise we wouldn't get $P_n\to P_0$.
\begin{exercise}
    Check my question above.

    Turns out this is easy, because you have a factorization:
\begin{equation*}
    \xymatrix{
	D^{n-1}\times 0\ar[d]\ar[r] & P_{n-1}\ar[r]^{\mathrm{induction}} & P_0\ar[d]\\
	D^{n-1}\times I\ar[rr]_{\phi\circ pr}\ar@{-->}[urr] & & X
    }
\end{equation*}
\end{exercise}
Oh my god, look what time it is! Oh well, at least we got the proof done.


\section{Chain Adjacency and Incidence}
\label{chain-adjacencies-and-incidensies}
%=========================================

Boundary decompositions (B-reps) are the typical representations used in solid modeling and computer graphcs. The model boundary is partitioned into vertices (\texttt{V}: 0-cells), edges (\texttt{E}: 1-cells), and faces (\texttt{F}: 2-cells), where faces are often triangles or more general convex cells.

\subsection{Boundary representation of solid models}
\label{boundary-representation-of-solid-models}
%--------------------------------------------------

In particular, a typical solid modeling representation employs some specialized data structure to efficiently traverse the boundary, moving from some element to the adjacent ones (with same dimension) or to incident ones (with different dimension). Several data structures have been used for this purpose~\cite{HofShapiro:2017}, taking into account both the efficiency of topological queries and the storage compactness. Three binary adjacency relations and six binary incidence relations can be needed by algorithms, as shown in Table~\ref{tab:relations}a.

Using chain operators, or better their matrices, when an ordering of elements has been fixed inside the sets \texttt{V}, \texttt{E}, and \texttt{F} using one-dimensional arrays, such binary relations can be represented and/or computed as shown in Table~\ref{tab:relations}b. It is easy to show (see Table~\ref{tab:relations}b), that all linear operators between chain spaces corresponding to binary relations between boundary elements can  be derived from $\partial_1$ and $\partial_2$ via matrix transposition or product over semirings~\cite{DBLP:journals/corr/KepnerABBFGHKLM16,GraphBLAS:API:2017}.

\begin{table}[htp]
\caption{(a) The 9 binary relations between boundary elements, and the 16 binary relations between decompositive elements; (b) corresponding linear operators between chain spaces. Remember that $\partial_p: C_p\to C_{p-1}$ and that $\delta_p = \partial_{p+1}^\top$. }
\begin{center}
\begin{tabular}{|c|ccc|c|}
\hline
 &\texttt{V} & \texttt{E} & \texttt{F} & \texttt{C} \\
\hline
\texttt{V} &\texttt{VV} & \texttt{VE} & \texttt{VF} & \texttt{VC} \\
\texttt{E} &\texttt{EV} & \texttt{EE} & \texttt{EF} & \texttt{EC} \\
\texttt{F} &\texttt{FV} & \texttt{FE} & \texttt{FF} & \texttt{FC} \\
\hline
\texttt{C} &\texttt{CV} & \texttt{CE} & \texttt{CF} & \texttt{CC} \\
\hline
\end{tabular}
$\qquad$
\begin{tabular}{|c|ccc|c|}
\hline
 &\texttt{$C_0$} & \texttt{$C_1$} & \texttt{$C_2$} & \texttt{$C_3$} \\
\hline
\texttt{$C_0$} & $[\partial_1][\delta_0]$ & $[\partial_1]$ & $[\partial_1][\partial_2]$ & $[\partial_1][\partial_2][\partial_3]$\\
\texttt{$C_1$} & $[\delta_0]$  & $[\delta_0][\partial_1]$ & $[\partial_2]$ & $[\partial_2][\partial_3]$ \\
\texttt{$C_2$} & $[\delta_1][\delta_0]$ & $[\delta_1]$ & $[\delta_1][\partial_2]$ & $[\partial_3]$ \\
\hline
\texttt{$C_3$} & $[\delta_2][\delta_1][\delta_0]$ & $[\delta_2][\delta_1]$ & $[\delta_2]$ & $[\delta_2][\partial_3]$ \\
\hline
\end{tabular}
\end{center}
\label{tab:relations}
\end{table}%

Note that we have assumed vectors as column matrices, so that an operator maps the column space to the row space of its matrix. Hence, in order to maintain the consistency between the two representations  we should read the relation $\texttt{AB} \subset \texttt{A}\times \texttt{B}$ as a map $\texttt{AB}: \texttt{B} \to \texttt{A}$.

\subsection{Space Decompositions}\label{space-decompositions}
%-------------------------------------------------------------
A similar representation scheme---called \emph{decompositive} in~\cite{Requicha:1980:RRS:356827.356833}---is also  used, both in solid modeling and in order to represent the domain decomposition in FEM and other discretizations of physical models. In this case a partition of the whole domain is provided, using cellular 3-complexes, given by \texttt{V}, \texttt{E}, \texttt{F}, and \texttt{C} sets of $0$-, 1-, 2- and 3-cells, where often the \texttt{C} elements  are either tetrahedra or hexahedra.

For the topology of a graph (cellular 1-complex) just $C_0$ (vertices) and $C_1$ (edges) are needed, so that a complete representation is given by the signed or unsigned matrix $[\partial_1]$, corresponding to the relation $\texttt{EV} \equiv C_1\to C_0$.

It is worth noting that operators $\partial_1$, $\partial_2$, and $\partial_3$ are sufficient to represent the complete collection of $4\times 4$ operators (see Table~\ref{tab:relations}b), via matrix transposition or product over semirings. In other words, the \emph{chain complex} $C_\bullet = (C_p, \partial_p)$ of boundary matrices, $1\leq p\leq 1,2,3$ is a \emph{complete representation} of the topology of (a) graphs, (b) B-reps, and (c) decompositive representations, respectively.

Cellular complexes may be either \emph{oriented} (signed) or \emph{non-oriented} (unsigned). In the first case the elements of operator matrices are taken over the domain $D=\{0,1\}$; in the second case they belong to the domain $D=\{-1,0,1\}$, so that passing from a coefficient $+1$ to a coefficient $-1$ (or viceversa) the element orientation is reversed.

\subsection{Minimal representations}\label{minimal-reps}

Most of earlier algorithms and procedures~\cite{
4055948,
Ala:1992:PAB:616022.617736,
Baumgart:1972:WEP:891970,
bowyer1995introducing,
bowyer1995svlis,
Braid:1975:SSB:360715.360727,
Brisson:1989:RGS:73833.73858,
cadanda,
Dobkin:1987:PMT:41958.41967,
Gomes:1999:MMB:304012.304039,
Guibas:1985:PMG:282918.282923,
HoffmannK01,
Kalay:1989:HET:63718.63719,
Lee:2001:PES:376957.376976,
Lienhardt:1991:TMB:115604.115610,
Mantyla:1988:ISM:60949,
Paoluzzi:1989:BAO:70248.70249,
Paoluzzi:1993:DMS:169728.169719,
Paoluzzi:1995:GPP:212332.212349,
Pascucci:1995:DCB:218013.218055,
Pratt94ashape,
Raghothama:1999:CUD:304012.304019,
Rap97,
RequichaVoelcker:77,
Rossignac:1991:CNG:115604.115606,
Rossignac:SGC:90,
Shapiro:1991:RSS:124951,
Shapiro:1995:PFS:218013.218029,
Silva:81,
Weiler:86,
Weiler:88,
Woo:85,
wozny1990geometric,
Yamaguchi:85,
yamaguchi1995ntb,
Zhou:2016:MAS:2897824.2925901,
bieri:95,
Rossignac:89,
Hoffmann:91,
Hoffmann:1989:GSM:74803,
Hoffmann:1987:RSO:866286}
work with data
structures optimized for selected classes of geometric
objects. By contrast, our formulation, representation, and algorithms, cast in
terms of (co)chain complexes of (co)boundary maps, may be
applied to very different geometric objects, ranging from solid models
to engineering meshes, geographical systems, biomedical images.

Given a set $S=\{s_j\}$, the \emph{characteristic function} $\chi_A: S\to\{0,1\}$ takes value 1 for all elements of $A\subseteq S$ and 0 at all elements of $S$ not in $A$.
We call \emph{characteristic matrix} $M$ of a collection of subsets $A_i\subseteq S$ ($i=1,\ldots,n$) the binary  matrix $M=(m_{ij})$, with $m_{ij} = \chi_{A_i}(s_j)$. {A  matrix $M_p$, whose rows are indexed by unit $p$-chains and columns are indexed by unit $0$-chains, provides a useful representation of a basis for the linear space $C_p$. Permuting (reindexing) either rows or columns provides a different basis.}   While chains are mostly presented as formal sums of cells, in the actual implementation their signed coordinate vectors are used as \emph{sparse} arrays, and in particular as CSC (Compressed Sparse Column) maps : $\N\to\{-1,0,1\}$.

It is possible to show~\cite{} that, when the $d$-cells are convex, the topology of a cellular $d$-complex is fully described by $M_{d-1}$ and by an embedding function $\mu: \texttt{V}\to \E^d$. When $d$-cells are more complex---say, non-convex or with holes---the triple $(M_{d-1}, M_{d-2}, \mu)$ is needed to get a full knowledge of the topology of the complex.

We call \texttt{LAR} (Linear Algebraic Representation) of subsets of a set \texttt{V} (vertices), the array, indexed by ordinals (one-to-one with subsets), of arrays of indices to \texttt{V} elements. This one is a compact representation of the \emph{characteristic matrix} of the collection of subsets.


\chapter{Graphing Polynomials}

In using polynomials to solve real-world problems, it is often handy
to know what the graph of the polynomial looks like. You have many of
the tools you need to start to sketch out the the graphs:
\begin{itemize}
\item To find where the graph crosses the y-axis, you can evaluate the polynomial at $x = 0$.
\item To find where the graph crosses the x-axis, you can find the roots of the polynomial.
\item To find the level spots on the graph (often the top of a hump or the bottom of a dip), you can take the derivative of the polynomial (which is a polynomial), and find the roots of that.
\end{itemize}\index{polynomial!graphing}

\textit{FIXME: Diagram of those things}

For example, if you wanted to graph the polynomial $f(x) = -x^3 -x^2 +
6x$, you might plug in a few values that are easy to compute:
\begin{itemize}
\item $f(-2) = -8$
\item $f(-1) = -6$
\item $f(0) = 0$
\item $f(1) = 4$
\item $f(2) = 0$
\end{itemize}

So, right away we know two roots: $x = 0$ and $x = 2$. Are there
others? We won't know until we factor the polynomial:
\begin{multline*}
  -x^3 -x^2 + 6x \\
  = (-1x)(x^2 + x - 6) \\
  = (-1x)(x + 3)(x - 2)
\end{multline*}
So, yes, there is a third root: $x = -3$

What about the level spots? $f'(x) = -3x^2 - 2x + 6$. Where is that zero?
\begin{multline*}
  -3x^2 -2x + 6 = 0 \\
  x^2 + \frac{2}{3}x - 2 = 0
\end{multline*}
We have a formula for quadratics like this:
\begin{multline*}
  x = -\frac{b}{2} \pm \frac{\sqrt{b^2 - 4c}}{2} \\
  = -\frac{\frac{2}{3}}{2} \pm \frac{\sqrt{\left(\frac{2}{3}\right)^2 - 4(-2)}}{2} \\
  = -\frac{1}{3} \pm \frac{\sqrt{\frac{4}{9} + 8}}{2} \\
  = -\frac{1}{3} \pm \frac{\sqrt{\frac{85}{9}}}{2} \\
  = -\frac{1}{3} \pm \frac{\sqrt{85}}{6} \\
  \approx 1.20 \text{ and } -1.87
\end{multline*}

Now you might plug those numbers in:
\begin{itemize}
\item $f(1.2) \approx 4.0 $
\item $f(-1.87) \approx -8.2$
\end{itemize}

\section{Leading term in graphing}

There is one more trick you need before you can draw a good graph of a
polynomial. As you go father and farther to the left and right, where
does the function go?  That is, does the graph go up on both ends
(like a smile)? Or does it go down on both ends (like a frown)? Or
does the negative end go down (frowny) while the positive end go up
(smiley)? Or does the negative go up (smiley) and the positive end go
down (frowny)?

Assuming the polynomial is not constant, there are only those four
possibilties. It is determined entirely by the leading term of the
polynomial.  If the degree of the leading term is even, both ends go
in the same direction (both are smiley or both are frowny).  If the
coefficient of the leading term is positive, the positive end is
smiley.

The graph we are working on has a leading term of $-1x^3$. The degree is odd, thus the ends go in different directions. The coefficient is negative, so the positive end points down.  Now you can draw the graph, which should look something like this:

\includegraphics[width=\textwidth]{annotated_graph.png}


\input{../header_function}

%---------- start document ---------- %
 \section{gcd -- gcd algorithm}\linkedzero{gcd}
%
  \subsection{gcd -- the greatest common divisor}\linkedone{gcd}{gcd}
   \func{gcd}{\hiki{a}{integer},\ \hiki{b}{integer}}{\out{integer}}\\
   \spacing
   % document of basic document
   \quad Return the greatest common divisor of two integers \param{a} and \param{b}.\\
   \spacing
   % added document
   %\spacing
   % input, output document
   \quad \param{a},\ \param{b} must be int, long or \linkingone{rational}{Integer}.
   Even if one of the arguments is negative, the result is non-negative.\\
%
  \subsection{binarygcd -- binary gcd algorithm}\linkedone{gcd}{binarygcd}
   \func{binarygcd}{\hiki{a}{integer},\ \hiki{b}{integer}}{\out{integer}}\\
   \spacing
   % document of basic document
   \quad Return the greatest common divisor of two integers \param{a} and \param{b} by binary gcd algorithm.\\
   \spacing
   % added document
   \quad \negok This function is an alias of \linkingone{arygcd}{binarygcd}\\
   \spacing
   % input, output document
   \quad \param{a},\ \param{b} must be int, long, or \linkingone{rational}{Integer}.\\
%
  \subsection{extgcd -- extended gcd algorithm}\linkedone{gcd}{extgcd}
   \func{extgcd}{\hiki{a}{integer},\ \hiki{b}{integer}}{(\out{integer},\ \out{integer},\ \out{integer})}\\
   \spacing
   % document of basic document
   \quad Return the greatest common divisor $d$ of two integers \param{a} and \param{b} and $u,\ v$ such that $d = \param{a}u + \param{b}v$.\\
   \spacing
   % added document
   %\spacing
   % input, output document
   \quad \param{a},\ \param{b} must be int, long, or \linkingone{rational}{Integer}.\\
   The returned value is a tuple (\param{u},\ \param{v},\ \param{d}).\\
%
  \subsection{lcm -- the least common multiple}\linkedone{gcd}{lcm}
   \func{lcm}{\hiki{a}{integer},\ \hiki{b}{integer}}{\out{integer}}\\
   \spacing
   % document of basic document
   \quad Return the least common multiple of two integers \param{a} and \param{b}.\\
   \spacing
   % added document
   \negok If both \param{a} and \param{b} are zero, then it raises an exception.
   \spacing
   % input, output document
   \quad \param{a},\ \param{b} must be int, long, or \linkingone{rational}{Integer}.\\
%
  \subsection{gcd\_of\_list -- gcd of many integers}\linkedone{gcd}{gcd\_of\_list}
   \func{gcd\_of\_list}{\hiki{integers}{list}}{\out{list}}\\
   \spacing
   % document of basic document
   \quad Return gcd of multiple integers.\\
   \spacing
   % added document
   \quad For given \param{integers} $[x_1,\ldots,x_n]$, return a list $[d,\ [c_1,\ldots,c_n]]$ such that $d=c_1 x_1+\cdots+c_n x_n$, where $d$ is the greatest common divisor of $x_1,\ldots, x_n$.\\
   \spacing
   % input, output document
   \quad \param{integers} is a list which elements are int or long\\
   This function returns $[d,\ [c_1,\ldots,c_n]]$, where $d,\ c_i$ are an integer.\\
%
  \subsection{coprime -- coprime check}\linkedone{gcd}{coprime}
   \func{coprime}{\hiki{a}{integer},\ \hiki{b}{integer}}{\out{bool}}\\
   \spacing
   % document of basic document
   \quad Return True if \param{a} and \param{b} are coprime, False otherwise.\\
   \spacing
   % added document
   %\spacing
   % input, output document
   \quad \param{a},\ \param{b} are int, long, or \linkingone{rational}{Integer}.\\
%
  \subsection{pairwise\_coprime -- coprime check of many integers}\linkedone{gcd}{pairwise\_coprime}
   \func{pairwise\_coprime}{\hiki{integers}{list}}{\out{bool}}\\
   \spacing
   % document of basic document
   \quad Return True if all integers in \param{integers} are pairwise coprime, False otherwise.\\
   \spacing
   % added document
   %\spacing
   % input, output document
   \quad \param{integers} is a list which elements are int, long, or \linkingone{rational}{Integer}.\\
%
\begin{ex}
>>> gcd.gcd(12, 18)
6
>>> gcd.gcd(12, -18)
6
>>> gcd.gcd(-12, -18)
6
>>> gcd.extgcd(12, -18)
(-1, -1, 6)
>>> gcd.extgcd(-12, -18)
(1, -1, 6)
>>> gcd.extgcd(0, -18)
(0, -1, 18)
>>> gcd.lcm(12, 18)
36
>>> gcd.lcm(12, -18)
-36
>>> gcd.gcd_of_list([60, 90, 210])
[30, [-1, 1, 0]]
\end{ex}%Don't indent!(indent causes an error.)
\C

%---------- end document ---------- %

\input{../footer}