\documentclass[12pt,letterpaper]{article}

% ---- Standard packages only ----
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[english]{babel}
\usepackage{amsmath,amssymb,amsthm}
\usepackage{geometry}
\usepackage{graphicx}
\usepackage{fancyhdr}
\usepackage{enumitem}
\setlist[itemize]{itemsep=1pt,topsep=2pt,parsep=1pt,partopsep=0pt}
\usepackage{xcolor}
\usepackage{listings}
\usepackage[colorlinks=true,linkcolor=blue,citecolor=blue,urlcolor=blue]{hyperref}

% ---- Page layout ----
\geometry{margin=2.5cm,headheight=14pt,headsep=8pt}
\setlength{\parindent}{0pt}
\setlength{\parskip}{3pt plus 1pt}

% ---- Header / footer ----
\pagestyle{fancy}
\fancyhf{}
\rhead{\small\coursecode\ --- \studentname}
\lhead{\small Homework \hwnumber}
\rfoot{Page \thepage}
\renewcommand{\headrulewidth}{0.4pt}
\renewcommand{\footrulewidth}{0.4pt}

% ---- Metadata (edit these) ----
\newcommand{\coursecode}{Phys 256}
\newcommand{\hwnumber}{5}
\newcommand{\studentname}{Student Name}

% ---- Python listings style ----
\definecolor{codebg}{rgb}{0.97,0.97,0.95}
\definecolor{codekey}{rgb}{0.20,0.40,0.70}
\definecolor{codecom}{rgb}{0.40,0.40,0.40}
\definecolor{codestr}{rgb}{0.60,0.10,0.10}

\lstdefinestyle{pythonstyle}{
  language=Python,
  backgroundcolor=\color{codebg},
  basicstyle=\ttfamily\small,
  keywordstyle=\color{codekey}\bfseries,
  commentstyle=\color{codecom}\itshape,
  stringstyle=\color{codestr},
  showstringspaces=false,
  breaklines=true,
  frame=single,
  rulecolor=\color{codecom},
  numbers=left,
  numberstyle=\tiny\color{codecom},
  stepnumber=1,
  numbersep=8pt,
  tabsize=4,
  captionpos=b
}
\lstset{style=pythonstyle}

% ---- \problem and \solution commands ----
\newcounter{problem}
\makeatletter
\newcommand{\problem}[1]{%
  \refstepcounter{problem}%
  \vspace{6pt}\noindent{\fontsize{14pt}{16pt}\bfseries Problem \theproblem: #1}%
  \par\nobreak\vspace{3pt}}
\newcommand{\solution}{%
  \vspace{-2pt}%
  {\fontsize{14pt}{16pt}\bfseries\noindent Solution\par\nobreak\vspace{2pt}}}
\makeatother

% ---- Custom compact title (redefines \maketitle) ----
\makeatletter
\renewcommand{\maketitle}{%
  \thispagestyle{empty}%
  \noindent{\Large\bfseries \coursecode\ --- Homework \hwnumber}%
  \par\vspace{2pt}%
  \noindent{\studentname}%
  \par\vspace{8pt}%
  \hrule\vspace{10pt}}
\makeatother

\begin{document}
\maketitle
%---------------------------------------------------------------
\section*{Instructions}
\begin{itemize}
  \item You may use AI assistants to help write, test, and debug code, but you must understand your implementation and use your own scientific judgment to assess its validity. \textbf{Do not use AI to write the report.}
  \item Submit a PDF report containing in-line code snippets, plots, numerical results, explanations, and descriptions of relevant test cases. Submit your Python code separately.
  \item In your report, we are looking for you to \textbf{exercise and demonstrate your independent scientific judgment.} Thoughtful reports with careful, critical discussion of the results will receive a higher grade than those that simply run the AI-generated code and paste in the results.
  \item Submit each coded problem in a separate file named \lstinline{p1.py}, \lstinline{p2.py}, etc. You may import functions from previous problems. Include all necessary files in one ZIP archive.
  \item Use NumPy and Matplotlib where appropriate. Fix random seeds or specify them so that stochastic results can be reproduced. Label all plot axes.
\end{itemize}

\vspace{0.25in}

\problem{Fitting Exponential Decay (15 points)}

Consider noisy data $(x_i,y_i)$ described by an exponential model
$f(x)=a e^{-\lambda x}$, with adjustable parameters
$\vec{p}=(a,\lambda)$. The data is available in the dataset
\texttt{decay\_data.csv} on the course website. Our goal is to fit this data with the best model parameters by minimizing the sum of squared residuals,

\[
\boxed{\chi^2(a,\lambda)=\sum_{i=1}^N
\left[y_i-ae^{-\lambda x_i}\right]^2.}
\]

\begin{enumerate}
    \item[(a)] \textbf{Implement model and objective:}
Implement the exponential model \\ 
\texttt{exp\_model(x, p)} and the sum of squared residuals \\
\texttt{chi\_squared(f, data, p)}, where \texttt{p = np.array([a, lam])} and \texttt{data} is a $N \times 2$ Numpy array containing the datapoints.

  \item[(b)] \textbf{Visualize:}
  Plot a contour map of $\chi^2(a,\lambda)$ over $0\leq a\leq 5$, $0\leq\lambda\leq 2$. Include a colorbar and estimate the minimum `by eye.'

  \item[(c)] \textbf{Gradient descent:}
Implement \texttt{gradient\_descent(f, p0, eta, nsteps)} using analytical or numerical gradients. Return the full trajectory $\vec{p}_n$. Starting from $\vec{p}_0=(2,0.3)$, use gradient descent to minimize $\chi^2$ and overlay the trajectory on your contour plot. Report the final best-fit parameters $\vec{p}_*$ and $\chi^2$, and plot the resulting best-fit curve on top of the noisy data. Explore several learning rates $\eta$, illustrating slow convergence, rapid convergence, and instability. Plot $\chi^2(\vec{p}_n)$ versus iteration for three choices of $\eta$, and briefly explain the behavior.

  \item[(d)] \textbf{Compare to SciPy:}
Finally, compare your results to the pre-built \\
\texttt{scipy.optimize.curve\_fit} function. Compare its optimal parameters and $\chi^2$ with gradient descent, and plot the data alongside the fitted curve.

\end{enumerate}

\textbf{Submission:} Submit your implementations of \texttt{exp\_model, chi\_squared, gradient\_descent} in a python file \texttt{p1.py} for auto-grading.

\vspace{0.25in}


\problem{AI-Assisted Protein Folding (15 points)}

Consider a chain of $N$ beads connected by rigid links of length $a$,
with bending angles $\vec{\theta}=(\theta_1,\ldots,\theta_{N-2})$.
The total energy is

\[
E(\vec{\theta}) =
\kappa\sum_{i=1}^{N-2}(1-\cos\theta_i)
-\epsilon\sum_{\substack{0\le i<j<N\\j-i\ge 2}}
\exp\left[-\frac{(r_{ij}-r_0)^2}{2\sigma^2}\right],
\]

where $r_{ij}$ is the distance between beads $i$ and $j$.
As in lecture, beads may overlap.

Use an AI coding assistant to help complete the following tasks:

\begin{enumerate}
    \item[(a)] \textbf{Generate code:}
    Write a detailed prompt asking the AI to implement \\
    \texttt{bead\_positions(angles, a)} and \texttt{energy(angles, a, kappa, epsilon, r0, sigma)}
    for arbitrary $N\ge 3$, where \texttt{angles} is a Numpy array containing the angles $\vec{\theta}$. In your prompt, specify the geometry, angle conventions, indexing, and expected input/output formats.
    Submit your prompt and the generated code.

    \item[(b)] \textbf{Validate:}
    Write at least four independent tests, including
    straight-chain geometry,
    reflection symmetry $E(\vec{\theta})=E(-\vec{\theta})$,
    and agreement with a hand-calculated energy.
    Test your code for $N=3,4,5$, and specify which parameters $a,\kappa, r_0, \epsilon, \sigma$ you chose.


    \item[(c)] \textbf{Exploring the 1D energy landscape:}

For $N=3$ beads, the energy depends on one bending angle
$\theta$.
Use golden-section search to minimize $E(\theta)$ for the default parameters $a = \kappa = r_0 = 1, \epsilon = 3, \sigma = 0.2$. Explore the results for at least 5 different initial brackets $[a,b]$.

    \item[(d)] \textbf{Exploring the multi-dimensional energy landscape:}
For $N=5$ beads, the energy depends on three bending angles
$\vec{\theta}=(\theta_1,\theta_2,\theta_3)$.
Use gradient descent to minimize $E(\vec{\theta})$ using the default parameters $a = \kappa = r_0 = 1, \epsilon = 3, \sigma = 0.2$. Start
from at least 20 randomly chosen initial configurations
$\theta_i\in[-\pi,\pi]$ and describe how the choice of initial condition affects your results. Also explore different learning rates $\eta$ and discuss how this choice affects your results.

% Plot a histogram of the final energies and visualize the
% lowest-energy configuration you discover. How many distinct
% local minima do you find? How confident are you that you
% have found the global minimum?

\end{enumerate}

\textbf{Submission:} Include your AI prompts, Python code,
and test results. Describe any corrections made to the AI-generated code. Submit your implementations of \texttt{bead\_positions, energy} in a python file \texttt{p2.py} for auto-grading.

\end{document}