{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "%matplotlib inline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Necktie Plot\n\nPlot the lattice stability in dependence of the quadrupole strengths.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Create a new FODO lattice\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import apace as ap\n\nD1 = ap.Drift(\"D1\", length=0.55)\nd1 = ap.Drift(\"D1\", length=0.55)\nb1 = ap.Drift(\"B1\", length=1.5)\nb1 = ap.Dipole(\"B1\", length=1.5, angle=0.392701, e1=0.1963505, e2=0.1963505)\nq1 = ap.Quadrupole(\"Q1\", length=0.2, k1=1.2)\nq2 = ap.Quadrupole(\"Q2\", length=0.4, k1=-1.2)\nfodo_cell = ap.Lattice(\"FODO_CELL\", [q1, d1, b1, d1, q2, d1, b1, d1, q1])\nfodo_ring = ap.Lattice(\"FODO_RING\", [fodo_cell] * 8)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Scan the quadrupole strength and record lattice stability\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import numpy as np\n\nn_steps = 100\nk1_start = 0\nk1_end = 2\n\nq1_values = np.linspace(k1_start, k1_end, n_steps)\nq2_values = np.linspace(k1_start, -k1_end, n_steps)\nstable = np.empty((n_steps, n_steps), dtype=bool)\n\ntwiss = ap.Twiss(fodo_ring)\n\nfor i, q1.k1 in enumerate(q1_values):\n    for j, q2.k1 in enumerate(q2_values):\n        stable[i, j] = twiss.stable"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Plot results using matplotlib\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import matplotlib.pyplot as plt\n\nx, y = np.meshgrid(q1_values, -q2_values)\nCS = plt.contour(x, y, stable)\nplt.xlabel(f\"{q1.name} k1 / m$^{{-1}}$\")\nplt.ylabel(f\"{q2.name} -k1 / m$^{{-1}}$\")\nplt.show()\n\n# TODO change Bend to Drift -> changes necktieplot to center"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.7.9"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}